Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b73e2b613 | ||
|
|
ec51e5a778 | ||
|
|
c0e73bce55 | ||
|
|
b898e4c5be | ||
|
|
61bc066f82 | ||
|
|
7f46c1b8c9 | ||
|
|
156d74bbe3 | ||
|
|
862b860020 | ||
|
|
100fad7d18 | ||
|
|
6d6a199728 | ||
|
|
21b975676d | ||
|
|
2c111770b3 | ||
|
|
52f44335e4
|
||
|
|
a06e1cb5eb | ||
|
|
58913254e0 | ||
|
|
02d7bcd93b | ||
|
|
1e52e82d6d | ||
|
|
3023fe5b2a | ||
|
|
7896ee6638
|
||
|
|
ed94423855
|
||
|
|
c3172a04b1
|
||
|
|
cc803f47a7 | ||
|
|
3bb95988fc | ||
|
|
e87e3bb953 | ||
|
|
41db17f1ec | ||
|
|
61868fe93e
|
||
|
|
9cea5ed493
|
||
|
|
e0296e0ccd
|
||
|
|
9cea74943c
|
||
|
|
35c430114e
|
||
|
|
6c7017bc75
|
||
|
|
041cc31c5f
|
||
|
|
cc811eddfe
|
||
|
|
984031c6e2
|
||
|
|
75ff49a9d1
|
||
|
|
d6ac0da75d
|
||
|
|
455139dfe9
|
||
|
|
f0efa6d041 | ||
|
|
314f90b5f3 | ||
|
|
053450429c | ||
|
|
8dcdb08755 | ||
|
|
ba61d3b5ae | ||
|
|
74e4360d71 |
@@ -0,0 +1,277 @@
|
|||||||
|
---
|
||||||
|
name: shadcn
|
||||||
|
description: Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn/ui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for "shadcn init", "create an app with --preset", or "switch to --preset".
|
||||||
|
user-invocable: false
|
||||||
|
allowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)
|
||||||
|
---
|
||||||
|
|
||||||
|
# shadcn/ui
|
||||||
|
|
||||||
|
A framework for building ui, components and design systems. Components are added as source code to the user's project via the CLI.
|
||||||
|
|
||||||
|
> **IMPORTANT:** Run all CLI commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest` — based on the project's `packageManager`. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
|
||||||
|
|
||||||
|
## Current Project Context
|
||||||
|
|
||||||
|
```json
|
||||||
|
!`npx shadcn@latest info --json`
|
||||||
|
```
|
||||||
|
|
||||||
|
The JSON above contains the project config and installed components. Use `npx shadcn@latest docs <component>` to get documentation and example URLs for any component.
|
||||||
|
|
||||||
|
## Principles
|
||||||
|
|
||||||
|
1. **Use existing components first.** Use `npx shadcn@latest search` to check registries before writing custom UI. Check community registries too.
|
||||||
|
2. **Compose, don't reinvent.** Settings page = Tabs + Card + form controls. Dashboard = Sidebar + Card + Chart + Table.
|
||||||
|
3. **Use built-in variants before custom styles.** `variant="outline"`, `size="sm"`, etc.
|
||||||
|
4. **Use semantic colors.** `bg-primary`, `text-muted-foreground` — never raw values like `bg-blue-500`.
|
||||||
|
|
||||||
|
## Critical Rules
|
||||||
|
|
||||||
|
These rules are **always enforced**. Each links to a file with Incorrect/Correct code pairs.
|
||||||
|
|
||||||
|
### Styling & Tailwind → [styling.md](./rules/styling.md)
|
||||||
|
|
||||||
|
- **`className` for layout, not styling.** Never override component colors or typography.
|
||||||
|
- **No `space-x-*` or `space-y-*`.** Use `flex` with `gap-*`. For vertical stacks, `flex flex-col gap-*`.
|
||||||
|
- **Use `size-*` when width and height are equal.** `size-10` not `w-10 h-10`.
|
||||||
|
- **Use `truncate` shorthand.** Not `overflow-hidden text-ellipsis whitespace-nowrap`.
|
||||||
|
- **No manual `dark:` color overrides.** Use semantic tokens (`bg-background`, `text-muted-foreground`).
|
||||||
|
- **Use `cn()` for conditional classes.** Don't write manual template literal ternaries.
|
||||||
|
- **No manual `z-index` on overlay components.** Dialog, Sheet, Popover, etc. handle their own stacking.
|
||||||
|
|
||||||
|
### Forms & Inputs → [forms.md](./rules/forms.md)
|
||||||
|
|
||||||
|
- **Forms use `FieldGroup` + `Field`.** Never use raw `div` with `space-y-*` or `grid gap-*` for form layout.
|
||||||
|
- **`InputGroup` uses `InputGroupInput`/`InputGroupTextarea`.** Never raw `Input`/`Textarea` inside `InputGroup`.
|
||||||
|
- **Buttons inside inputs use `InputGroup` + `InputGroupAddon`.**
|
||||||
|
- **Option sets (2–7 choices) use `ToggleGroup`.** Don't loop `Button` with manual active state.
|
||||||
|
- **`FieldSet` + `FieldLegend` for grouping related checkboxes/radios.** Don't use a `div` with a heading.
|
||||||
|
- **Field validation uses `data-invalid` + `aria-invalid`.** `data-invalid` on `Field`, `aria-invalid` on the control. For disabled: `data-disabled` on `Field`, `disabled` on the control.
|
||||||
|
|
||||||
|
### Component Structure → [composition.md](./rules/composition.md)
|
||||||
|
|
||||||
|
- **Items always inside their Group.** `SelectItem` → `SelectGroup`. `DropdownMenuItem` → `DropdownMenuGroup`. `CommandItem` → `CommandGroup`.
|
||||||
|
- **Use `asChild` (radix) or `render` (base) for custom triggers.** Check `base` field from `npx shadcn@latest info`. → [base-vs-radix.md](./rules/base-vs-radix.md)
|
||||||
|
- **Dialog, Sheet, and Drawer always need a Title.** `DialogTitle`, `SheetTitle`, `DrawerTitle` required for accessibility. Use `className="sr-only"` if visually hidden.
|
||||||
|
- **Use full Card composition.** `CardHeader`/`CardTitle`/`CardDescription`/`CardContent`/`CardFooter`. Don't dump everything in `CardContent`.
|
||||||
|
- **Button has no `isPending`/`isLoading`.** Compose with `Spinner` + `data-icon` + `disabled`.
|
||||||
|
- **`TabsTrigger` must be inside `TabsList`.** Never render triggers directly in `Tabs`.
|
||||||
|
- **`Avatar` always needs `AvatarFallback`.** For when the image fails to load.
|
||||||
|
|
||||||
|
### Use Components, Not Custom Markup → [composition.md](./rules/composition.md)
|
||||||
|
|
||||||
|
- **Use existing components before custom markup.** Check if a component exists before writing a styled `div`.
|
||||||
|
- **Callouts use `Alert`.** Don't build custom styled divs.
|
||||||
|
- **Empty states use `Empty`.** Don't build custom empty state markup.
|
||||||
|
- **Toast follows the project base.** Use `toast` from the `toast` component for
|
||||||
|
Base UI projects. Use `toast()` from `sonner` for Radix and React Aria
|
||||||
|
projects.
|
||||||
|
- **Use `Separator`** instead of `<hr>` or `<div className="border-t">`.
|
||||||
|
- **Use `Skeleton`** for loading placeholders. No custom `animate-pulse` divs.
|
||||||
|
- **Use `Badge`** instead of custom styled spans.
|
||||||
|
|
||||||
|
### Icons → [icons.md](./rules/icons.md)
|
||||||
|
|
||||||
|
- **Icons in `Button` use `data-icon`.** `data-icon="inline-start"` or `data-icon="inline-end"` on the icon.
|
||||||
|
- **No sizing classes on icons inside components.** Components handle icon sizing via CSS. No `size-4` or `w-4 h-4`.
|
||||||
|
- **Pass icons as objects, not string keys.** `icon={CheckIcon}`, not a string lookup.
|
||||||
|
|
||||||
|
### Chat & Messaging → [chat.md](./rules/chat.md)
|
||||||
|
|
||||||
|
- **Chat UI composes the chat primitives.** Conversations use `MessageScroller`, rows use `Message`, surfaces use `Bubble`. Never hand-rolled bubble `div`s or a raw scroll container.
|
||||||
|
- **`MessageScroller` owns scroll behavior.** Streaming follow, anchoring, and jump-to-latest (`MessageScrollerButton`) are built in. Don't write a `useStickToBottom`/`ResizeObserver` hook.
|
||||||
|
- **Attachments use `Attachment`; system notes and dividers use `Marker`.** Not `Item` cards or `Separator` + a label.
|
||||||
|
|
||||||
|
### CLI
|
||||||
|
|
||||||
|
- **Never decode preset codes or build preset URLs manually.** Use `npx shadcn@latest preset decode <code>`, `preset url <code>`, or `preset open <code>`. For project-aware preset detection, use `npx shadcn@latest preset resolve`.
|
||||||
|
- **Apply preset codes directly with the CLI.** Use `npx shadcn@latest apply <code>` for existing projects, or `npx shadcn@latest init --preset <code>` when initializing.
|
||||||
|
|
||||||
|
## Key Patterns
|
||||||
|
|
||||||
|
These are the most common patterns that differentiate correct shadcn/ui code. For edge cases, see the linked rule files above.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Form layout: FieldGroup + Field, not div + Label.
|
||||||
|
<FieldGroup>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||||
|
<Input id="email" />
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
|
||||||
|
// Validation: data-invalid on Field, aria-invalid on the control.
|
||||||
|
<Field data-invalid>
|
||||||
|
<FieldLabel>Email</FieldLabel>
|
||||||
|
<Input aria-invalid />
|
||||||
|
<FieldDescription>Invalid email.</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
// Icons in buttons: data-icon, no sizing classes.
|
||||||
|
<Button>
|
||||||
|
<SearchIcon data-icon="inline-start" />
|
||||||
|
Search
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
// Spacing: gap-*, not space-y-*.
|
||||||
|
<div className="flex flex-col gap-4"> // correct
|
||||||
|
<div className="space-y-4"> // wrong
|
||||||
|
|
||||||
|
// Equal dimensions: size-*, not w-* h-*.
|
||||||
|
<Avatar className="size-10"> // correct
|
||||||
|
<Avatar className="w-10 h-10"> // wrong
|
||||||
|
|
||||||
|
// Status colors: Badge variants or semantic tokens, not raw colors.
|
||||||
|
<Badge variant="secondary">+20.1%</Badge> // correct
|
||||||
|
<span className="text-emerald-600">+20.1%</span> // wrong
|
||||||
|
```
|
||||||
|
|
||||||
|
## Component Selection
|
||||||
|
|
||||||
|
| Need | Use |
|
||||||
|
| -------------------------- | --------------------------------------------------------------------------------------------------- |
|
||||||
|
| Button/action | `Button` with appropriate variant |
|
||||||
|
| Form inputs | `Input`, `Select`, `Combobox`, `Switch`, `Checkbox`, `RadioGroup`, `Textarea`, `InputOTP`, `Slider` |
|
||||||
|
| Toggle between 2–5 options | `ToggleGroup` + `ToggleGroupItem` |
|
||||||
|
| Data display | `Table`, `Card`, `Badge`, `Avatar` |
|
||||||
|
| Navigation | `Sidebar`, `NavigationMenu`, `Breadcrumb`, `Tabs`, `Pagination` |
|
||||||
|
| Overlays | `Dialog` (modal), `Sheet` (side panel), `Drawer` (bottom sheet), `AlertDialog` (confirmation) |
|
||||||
|
| Feedback | `toast` (Base UI), `sonner` (Radix/Aria), `Alert`, `Progress`, `Skeleton`, `Spinner` |
|
||||||
|
| Command palette | `Command` inside `Dialog` |
|
||||||
|
| Charts | `Chart` (wraps Recharts) |
|
||||||
|
| Layout | `Card`, `Separator`, `Resizable`, `ScrollArea`, `Accordion`, `Collapsible` |
|
||||||
|
| Empty states | `Empty` |
|
||||||
|
| Menus | `DropdownMenu`, `ContextMenu`, `Menubar` |
|
||||||
|
| Tooltips/info | `Tooltip`, `HoverCard`, `Popover` |
|
||||||
|
| Chat / conversation UI | `MessageScroller`, `Message`, `Bubble`, `Attachment`, `Marker` |
|
||||||
|
|
||||||
|
## Key Fields
|
||||||
|
|
||||||
|
The injected project context contains these key fields:
|
||||||
|
|
||||||
|
- **`aliases`** → use the actual alias prefix for imports (e.g. `@/`, `~/`), never hardcode.
|
||||||
|
- **`isRSC`** → when `true`, components using `useState`, `useEffect`, event handlers, or browser APIs need `"use client"` at the top of the file. Always reference this field when advising on the directive.
|
||||||
|
- **`tailwindVersion`** → `"v4"` uses `@theme inline` blocks; `"v3"` uses `tailwind.config.js`.
|
||||||
|
- **`tailwindCssFile`** → the global CSS file where custom CSS variables are defined. Always edit this file, never create a new one.
|
||||||
|
- **`style`** → component visual treatment (e.g. `nova`, `vega`).
|
||||||
|
- **`base`** → primitive library (`radix` or `base`). Affects component APIs and available props.
|
||||||
|
- **`iconLibrary`** → determines icon imports. Use `lucide-react` for `lucide`, `@tabler/icons-react` for `tabler`, etc. Never assume `lucide-react`.
|
||||||
|
- **`resolvedPaths`** → exact file-system destinations for components, utils, hooks, etc.
|
||||||
|
- **`framework`** → routing and file conventions (e.g. Next.js App Router vs Vite SPA).
|
||||||
|
- **`packageManager`** → use this for any non-shadcn dependency installs (e.g. `pnpm add date-fns` vs `npm install date-fns`).
|
||||||
|
- **`preset`** → resolved preset code and values for the current project. Use `npx shadcn@latest preset resolve --json` when you only need preset information.
|
||||||
|
|
||||||
|
See [cli.md — `info` command](./cli.md) for the full field reference.
|
||||||
|
|
||||||
|
## Component Docs, Examples, and Usage
|
||||||
|
|
||||||
|
Run `npx shadcn@latest docs <component>` to get the URLs for a component's documentation, examples, and API reference. Fetch these URLs to get the actual content.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest docs button dialog select
|
||||||
|
```
|
||||||
|
|
||||||
|
**When creating, fixing, debugging, or using a component, always run `npx shadcn@latest docs` and fetch the URLs first.** This ensures you're working with the correct API and usage patterns rather than guessing.
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
1. **Get project context** — already injected above. Run `npx shadcn@latest info` again if you need to refresh.
|
||||||
|
2. **Check installed components first** — before running `add`, always check the `components` list from project context or list the `resolvedPaths.ui` directory. Don't import components that haven't been added, and don't re-add ones already installed.
|
||||||
|
3. **Find components** — `npx shadcn@latest search`.
|
||||||
|
4. **Get docs and examples** — run `npx shadcn@latest docs <component>` to get URLs, then fetch them. Use `npx shadcn@latest view` to browse registry items you haven't installed. To preview changes to installed components, use `npx shadcn@latest add --diff`.
|
||||||
|
5. **Install or update** — `npx shadcn@latest add`. When updating existing components, use `--dry-run` and `--diff` to preview changes first (see [Updating Components](#updating-components) below).
|
||||||
|
6. **Fix imports in third-party components** — After adding components from community registries (e.g. `@bundui`, `@magicui`), check the added non-UI files for hardcoded import paths like `@/components/ui/...`. These won't match the project's actual aliases. Use `npx shadcn@latest info` to get the correct `ui` alias (e.g. `@workspace/ui/components`) and rewrite the imports accordingly. The CLI rewrites imports for its own UI files, but third-party registry components may use default paths that don't match the project.
|
||||||
|
7. **Review added components** — After adding a component or block from any registry, **always read the added files and verify they are correct**. Check for missing sub-components (e.g. `SelectItem` without `SelectGroup`), missing imports, incorrect composition, or violations of the [Critical Rules](#critical-rules). Also replace any icon imports with the project's `iconLibrary` from the project context (e.g. if the registry item uses `lucide-react` but the project uses `hugeicons`, swap the imports and icon names accordingly). Fix all issues before moving on.
|
||||||
|
8. **Registry must be explicit** — When the user asks to add a block or component, **do not guess the registry**. If no registry is specified (e.g. user says "add a login block" without specifying `@shadcn`, `@tailark`, `owner/repo`, etc.), ask which registry to use. Never default to a registry on behalf of the user.
|
||||||
|
9. **Switching presets** — Ask the user first: **overwrite**, **partial**, **merge**, or **skip**?
|
||||||
|
- **Inspect current preset**: `npx shadcn@latest preset resolve`. Use `--json` when you need structured values.
|
||||||
|
- **Inspect incoming preset**: `npx shadcn@latest preset decode <code>`. Use `preset url <code>` or `preset open <code>` to share or open the preset builder.
|
||||||
|
- **Overwrite**: `npx shadcn@latest apply <code>`. Overwrites detected components, fonts, and CSS variables.
|
||||||
|
- **Partial**: `npx shadcn@latest apply <code> --only theme,font`. Updates only the selected preset parts without reinstalling UI components. Supported values are `theme` and `font`; comma-separated combinations are allowed. `icon` is intentionally not supported, because icon changes may require full component reinstall and transforms.
|
||||||
|
- **Merge**: `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to list installed components, then for each installed component use `--dry-run` and `--diff` to [smart merge](#updating-components) it individually.
|
||||||
|
- **Skip**: `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS, leaves components as-is.
|
||||||
|
- **Important**: Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
|
||||||
|
|
||||||
|
## Updating Components
|
||||||
|
|
||||||
|
When the user asks to update a component from upstream while keeping their local changes, use `--dry-run` and `--diff` to intelligently merge. **NEVER fetch raw files from GitHub manually — always use the CLI.**
|
||||||
|
|
||||||
|
1. Run `npx shadcn@latest add <component> --dry-run` to see all files that would be affected.
|
||||||
|
2. For each file, run `npx shadcn@latest add <component> --diff <file>` to see what changed upstream vs local.
|
||||||
|
3. Decide per file based on the diff:
|
||||||
|
- No local changes → safe to overwrite.
|
||||||
|
- Has local changes → read the local file, analyze the diff, and apply upstream updates while preserving local modifications.
|
||||||
|
- User says "just update everything" → use `--overwrite`, but confirm first.
|
||||||
|
4. **Never use `--overwrite` without the user's explicit approval.**
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create a new project.
|
||||||
|
npx shadcn@latest init --name my-app --preset base-nova
|
||||||
|
npx shadcn@latest init --name my-app --preset a2r6bw --template vite
|
||||||
|
|
||||||
|
# Create a monorepo project.
|
||||||
|
npx shadcn@latest init --name my-app --preset base-nova --monorepo
|
||||||
|
npx shadcn@latest init --name my-app --preset base-nova --template next --monorepo
|
||||||
|
|
||||||
|
# Initialize existing project.
|
||||||
|
npx shadcn@latest init --preset base-nova
|
||||||
|
npx shadcn@latest init --defaults # shortcut: --template=next --preset=nova (base style implied)
|
||||||
|
|
||||||
|
# Apply a preset to an existing project.
|
||||||
|
npx shadcn@latest apply a2r6bw
|
||||||
|
npx shadcn@latest apply a2r6bw --only theme
|
||||||
|
npx shadcn@latest apply a2r6bw --only font
|
||||||
|
npx shadcn@latest apply a2r6bw --only theme,font
|
||||||
|
|
||||||
|
# Inspect preset codes and project preset state.
|
||||||
|
npx shadcn@latest preset decode a2r6bw
|
||||||
|
npx shadcn@latest preset url a2r6bw
|
||||||
|
npx shadcn@latest preset open a2r6bw
|
||||||
|
npx shadcn@latest preset resolve
|
||||||
|
npx shadcn@latest preset resolve --json
|
||||||
|
|
||||||
|
# Add components.
|
||||||
|
npx shadcn@latest add button card dialog
|
||||||
|
npx shadcn@latest add @magicui/shimmer-button
|
||||||
|
npx shadcn@latest add owner/repo/item
|
||||||
|
npx shadcn@latest add --all
|
||||||
|
|
||||||
|
# Preview changes before adding/updating.
|
||||||
|
npx shadcn@latest add button --dry-run
|
||||||
|
npx shadcn@latest add button --diff button.tsx
|
||||||
|
npx shadcn@latest add @acme/form --view button.tsx
|
||||||
|
npx shadcn@latest add owner/repo/item --dry-run
|
||||||
|
|
||||||
|
# Search registries.
|
||||||
|
npx shadcn@latest search @shadcn -q "sidebar"
|
||||||
|
npx shadcn@latest search @tailark -q "stats"
|
||||||
|
npx shadcn@latest search owner/repo -q "login"
|
||||||
|
npx shadcn@latest search # all configured registries
|
||||||
|
npx shadcn@latest search @shadcn -q "menu" -t ui # filter by item type
|
||||||
|
|
||||||
|
# Get component docs and example URLs.
|
||||||
|
npx shadcn@latest docs button dialog select
|
||||||
|
|
||||||
|
# View registry item details (for items not yet installed).
|
||||||
|
npx shadcn@latest view @shadcn/button
|
||||||
|
npx shadcn@latest view owner/repo/item
|
||||||
|
```
|
||||||
|
|
||||||
|
**Named presets:** `nova`, `vega`, `maia`, `lyra`, `mira`, `luma`
|
||||||
|
**Templates:** `next`, `vite`, `start`, `react-router`, `astro` (all support `--monorepo`) and `laravel` (not supported for monorepo)
|
||||||
|
**Preset codes:** Version-prefixed base62 strings (e.g. `a2r6bw` or `b0`), from [ui.shadcn.com](https://ui.shadcn.com).
|
||||||
|
|
||||||
|
## Detailed References
|
||||||
|
|
||||||
|
- [rules/forms.md](./rules/forms.md) — FieldGroup, Field, InputGroup, ToggleGroup, FieldSet, validation states
|
||||||
|
- [rules/composition.md](./rules/composition.md) — Groups, overlays, Card, Tabs, Avatar, Alert, Empty, Toast, Separator, Skeleton, Badge, Button loading
|
||||||
|
- [rules/chat.md](./rules/chat.md) — MessageScroller, Message, Bubble, Attachment, Marker; streaming, anchoring, jump-to-latest
|
||||||
|
- [rules/icons.md](./rules/icons.md) — data-icon, icon sizing, passing icons as objects
|
||||||
|
- [rules/styling.md](./rules/styling.md) — Semantic colors, variants, className, spacing, size, truncate, dark mode, cn(), z-index
|
||||||
|
- [rules/base-vs-radix.md](./rules/base-vs-radix.md) — asChild vs render, Select, ToggleGroup, Slider, Accordion
|
||||||
|
- [cli.md](./cli.md) — Commands, flags, presets, templates
|
||||||
|
- [registry.md](./registry.md) — Authoring source registries, `include`, item definitions, dependencies, GitHub registry rules
|
||||||
|
- [customization.md](./customization.md) — Theming, CSS variables, extending components
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
interface:
|
||||||
|
display_name: "shadcn/ui"
|
||||||
|
short_description: "Manages shadcn/ui components — adding, searching, fixing, debugging, styling, and composing UI."
|
||||||
|
icon_small: "./assets/shadcn-small.png"
|
||||||
|
icon_large: "./assets/shadcn.png"
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,290 @@
|
|||||||
|
# shadcn CLI Reference
|
||||||
|
|
||||||
|
Configuration is read from `components.json`.
|
||||||
|
|
||||||
|
> **IMPORTANT:** Always run commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest`. Check `packageManager` from project context to choose the right one. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
|
||||||
|
|
||||||
|
> **IMPORTANT:** Only use the flags documented below. Do not invent or guess flags — if a flag isn't listed here, it doesn't exist. The CLI auto-detects the package manager from the project's lockfile; there is no `--package-manager` flag.
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- Commands: init, apply, add (dry-run, smart merge), search, view, docs, info, build
|
||||||
|
- Templates: next, vite, start, react-router, astro
|
||||||
|
- Presets: named, code, URL formats and fields
|
||||||
|
- Switching presets
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
### `init` — Initialize or create a project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest init [components...] [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Initializes shadcn/ui in an existing project or creates a new project (when `--name` is provided). Optionally installs components in the same step.
|
||||||
|
|
||||||
|
| Flag | Short | Description | Default |
|
||||||
|
| ----------------------- | ----- | --------------------------------------------------------- | ------- |
|
||||||
|
| `--template <template>` | `-t` | Template (next, start, vite, next-monorepo, react-router) | — |
|
||||||
|
| `--preset [name]` | `-p` | Preset configuration (named, code, or URL) | — |
|
||||||
|
| `--yes` | `-y` | Skip confirmation prompt | `true` |
|
||||||
|
| `--defaults` | `-d` | Use defaults (`--template=next --preset=base-nova`) | `false` |
|
||||||
|
| `--force` | `-f` | Force overwrite existing configuration | `false` |
|
||||||
|
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||||
|
| `--name <name>` | `-n` | Name for new project | — |
|
||||||
|
| `--silent` | `-s` | Mute output | `false` |
|
||||||
|
| `--rtl` | | Enable RTL support | — |
|
||||||
|
| `--reinstall` | | Re-install existing UI components | `false` |
|
||||||
|
| `--monorepo` | | Scaffold a monorepo project | — |
|
||||||
|
| `--no-monorepo` | | Skip the monorepo prompt | — |
|
||||||
|
|
||||||
|
`npx shadcn@latest create` is an alias for `npx shadcn@latest init`.
|
||||||
|
|
||||||
|
### `apply` — Apply a preset to an existing project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest apply [preset] [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Applies a preset to an existing project, overwriting preset-driven config, fonts, CSS variables, and detected UI components.
|
||||||
|
|
||||||
|
| Flag | Short | Description | Default |
|
||||||
|
| ------------------- | ----- | ------------------------------------------ | ------- |
|
||||||
|
| `--preset <preset>` | — | Preset configuration (named, code, or URL) | — |
|
||||||
|
| `--yes` | `-y` | Skip confirmation prompt | `false` |
|
||||||
|
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||||
|
| `--silent` | `-s` | Mute output | `false` |
|
||||||
|
|
||||||
|
`[preset]` is a shorthand for `--preset <preset>`. If both are provided, they must match.
|
||||||
|
If no preset is provided, the CLI offers to open the custom preset builder on `ui.shadcn.com/create`.
|
||||||
|
|
||||||
|
### `add` — Add components
|
||||||
|
|
||||||
|
> **IMPORTANT:** To compare local components against upstream or to preview changes, ALWAYS use `npx shadcn@latest add <component> --dry-run`, `--diff`, or `--view`. NEVER fetch raw files from GitHub or other sources manually. The CLI handles registry resolution, file paths, and CSS diffing automatically.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest add [components...] [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Accepts component names, registry-prefixed names (`@magicui/shimmer-button`),
|
||||||
|
GitHub item addresses (`owner/repo/item`), URLs, or local paths.
|
||||||
|
|
||||||
|
| Flag | Short | Description | Default |
|
||||||
|
| --------------- | ----- | -------------------------------------------------------------------------------------------------------------------- | ------- |
|
||||||
|
| `--yes` | `-y` | Skip confirmation prompt | `false` |
|
||||||
|
| `--overwrite` | `-o` | Overwrite existing files | `false` |
|
||||||
|
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||||
|
| `--all` | `-a` | Add all available components | `false` |
|
||||||
|
| `--path <path>` | `-p` | Target path for the component | — |
|
||||||
|
| `--silent` | `-s` | Mute output | `false` |
|
||||||
|
| `--dry-run` | | Preview all changes without writing files | `false` |
|
||||||
|
| `--diff [path]` | | Show diffs. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
|
||||||
|
| `--view [path]` | | Show file contents. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
|
||||||
|
|
||||||
|
#### Dry-Run Mode
|
||||||
|
|
||||||
|
Use `--dry-run` to preview what `add` would do without writing any files. `--diff` and `--view` both imply `--dry-run`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Preview all changes.
|
||||||
|
npx shadcn@latest add button --dry-run
|
||||||
|
|
||||||
|
# Show diffs for all files (top 5).
|
||||||
|
npx shadcn@latest add button --diff
|
||||||
|
|
||||||
|
# Show the diff for a specific file.
|
||||||
|
npx shadcn@latest add button --diff button.tsx
|
||||||
|
|
||||||
|
# Show contents for all files (top 5).
|
||||||
|
npx shadcn@latest add button --view
|
||||||
|
|
||||||
|
# Show the full content of a specific file.
|
||||||
|
npx shadcn@latest add button --view button.tsx
|
||||||
|
|
||||||
|
# Works with URLs too.
|
||||||
|
npx shadcn@latest add https://api.npoint.io/abc123 --dry-run
|
||||||
|
|
||||||
|
# Works with public GitHub registries too.
|
||||||
|
npx shadcn@latest add owner/repo/item --dry-run
|
||||||
|
|
||||||
|
# CSS diffs.
|
||||||
|
npx shadcn@latest add button --diff globals.css
|
||||||
|
```
|
||||||
|
|
||||||
|
**When to use dry-run:**
|
||||||
|
|
||||||
|
- When the user asks "what files will this add?" or "what will this change?" — use `--dry-run`.
|
||||||
|
- Before overwriting existing components — use `--diff` to preview the changes first.
|
||||||
|
- When the user wants to inspect component source code without installing — use `--view`.
|
||||||
|
- When checking what CSS changes would be made to `globals.css` — use `--diff globals.css`.
|
||||||
|
- When the user asks to review or audit third-party registry code before installing — use `--view` to inspect the source.
|
||||||
|
|
||||||
|
> **`npx shadcn@latest add --dry-run` vs `npx shadcn@latest view`:** Prefer `npx shadcn@latest add --dry-run/--diff/--view` over `npx shadcn@latest view` when the user wants to preview changes to their project. `npx shadcn@latest view` only shows raw registry metadata. `npx shadcn@latest add --dry-run` shows exactly what would happen in the user's project: resolved file paths, diffs against existing files, and CSS updates. Use `npx shadcn@latest view` only when the user wants to browse registry info without a project context.
|
||||||
|
|
||||||
|
#### Smart Merge from Upstream
|
||||||
|
|
||||||
|
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full workflow.
|
||||||
|
|
||||||
|
### `search` — Search registries
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest search [registries...] [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Fuzzy search across registries. Also aliased as `npx shadcn@latest list`.
|
||||||
|
Supports namespaces (`@acme`), public GitHub registry sources (`owner/repo`),
|
||||||
|
and registry catalog URLs. Without `-q`, lists all items. When no registries are
|
||||||
|
passed, searches every registry configured in `components.json`.
|
||||||
|
|
||||||
|
| Flag | Short | Description | Default |
|
||||||
|
| ------------------- | ----- | ------------------------------------------------- | ------- |
|
||||||
|
| `--query <query>` | `-q` | Search query | — |
|
||||||
|
| `--type <type>` | `-t` | Filter by item type (e.g. `ui`, `block`, `hook`); comma-separated | — |
|
||||||
|
| `--limit <number>` | `-l` | Max items to display | `100` |
|
||||||
|
| `--offset <number>` | `-o` | Items to skip | `0` |
|
||||||
|
| `--json` | | Output as JSON | `false` |
|
||||||
|
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||||
|
|
||||||
|
### `view` — View item details
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest view <items...> [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Displays item info including file contents. Examples:
|
||||||
|
`npx shadcn@latest view @shadcn/button`,
|
||||||
|
`npx shadcn@latest view owner/repo/item`.
|
||||||
|
|
||||||
|
### `docs` — Get component documentation URLs
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest docs <components...> [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Outputs resolved URLs for component documentation, examples, and API references. Accepts one or more component names. Fetch the URLs to get the actual content.
|
||||||
|
|
||||||
|
Example output for `npx shadcn@latest docs input button`:
|
||||||
|
|
||||||
|
```
|
||||||
|
base radix
|
||||||
|
|
||||||
|
input
|
||||||
|
docs https://ui.shadcn.com/docs/components/radix/input
|
||||||
|
examples https://raw.githubusercontent.com/.../examples/input-example.tsx
|
||||||
|
|
||||||
|
button
|
||||||
|
docs https://ui.shadcn.com/docs/components/radix/button
|
||||||
|
examples https://raw.githubusercontent.com/.../examples/button-example.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
Some components include an `api` link to the underlying library (e.g. `cmdk` for the command component).
|
||||||
|
|
||||||
|
### `diff` — Check for updates
|
||||||
|
|
||||||
|
Do not use this command. Use `npx shadcn@latest add --diff` instead.
|
||||||
|
|
||||||
|
### `info` — Project information
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest info [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Displays project info and `components.json` configuration. Run this first to discover the project's framework, aliases, Tailwind version, and resolved paths.
|
||||||
|
|
||||||
|
| Flag | Short | Description | Default |
|
||||||
|
| ------------- | ----- | ----------------- | ------- |
|
||||||
|
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||||
|
|
||||||
|
**Project Info fields:**
|
||||||
|
|
||||||
|
| Field | Type | Meaning |
|
||||||
|
| -------------------- | --------- | ------------------------------------------------------------------ |
|
||||||
|
| `framework` | `string` | Detected framework (`next`, `vite`, `react-router`, `start`, etc.) |
|
||||||
|
| `frameworkVersion` | `string` | Framework version (e.g. `15.2.4`) |
|
||||||
|
| `isSrcDir` | `boolean` | Whether the project uses a `src/` directory |
|
||||||
|
| `isRSC` | `boolean` | Whether React Server Components are enabled |
|
||||||
|
| `isTsx` | `boolean` | Whether the project uses TypeScript |
|
||||||
|
| `tailwindVersion` | `string` | `"v3"` or `"v4"` |
|
||||||
|
| `tailwindConfigFile` | `string` | Path to the Tailwind config file |
|
||||||
|
| `tailwindCssFile` | `string` | Path to the global CSS file |
|
||||||
|
| `aliasPrefix` | `string` | Import alias prefix (e.g. `@`, `~`, `@/`) |
|
||||||
|
| `packageManager` | `string` | Detected package manager (`npm`, `pnpm`, `yarn`, `bun`) |
|
||||||
|
|
||||||
|
**Components.json fields:**
|
||||||
|
|
||||||
|
| Field | Type | Meaning |
|
||||||
|
| -------------------- | --------- | ------------------------------------------------------------------------------------------ |
|
||||||
|
| `base` | `string` | Primitive library (`radix` or `base`) — determines component APIs and available props |
|
||||||
|
| `style` | `string` | Visual style (e.g. `nova`, `vega`) |
|
||||||
|
| `rsc` | `boolean` | RSC flag from config |
|
||||||
|
| `tsx` | `boolean` | TypeScript flag |
|
||||||
|
| `tailwind.config` | `string` | Tailwind config path |
|
||||||
|
| `tailwind.css` | `string` | Global CSS path — this is where custom CSS variables go |
|
||||||
|
| `iconLibrary` | `string` | Icon library — determines icon import package (e.g. `lucide-react`, `@tabler/icons-react`) |
|
||||||
|
| `aliases.components` | `string` | Component import alias (e.g. `@/components`) |
|
||||||
|
| `aliases.utils` | `string` | Utils import alias (e.g. `@/lib/utils`) |
|
||||||
|
| `aliases.ui` | `string` | UI component alias (e.g. `@/components/ui`) |
|
||||||
|
| `aliases.lib` | `string` | Lib alias (e.g. `@/lib`) |
|
||||||
|
| `aliases.hooks` | `string` | Hooks alias (e.g. `@/hooks`) |
|
||||||
|
| `resolvedPaths` | `object` | Absolute file-system paths for each alias |
|
||||||
|
| `registries` | `object` | Configured custom registries |
|
||||||
|
|
||||||
|
**Links fields:**
|
||||||
|
|
||||||
|
The `info` output includes a **Links** section with templated URLs for component docs, source, and examples. For resolved URLs, use `npx shadcn@latest docs <component>` instead.
|
||||||
|
|
||||||
|
### `build` — Build a custom registry
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest build [registry] [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Builds `registry.json` into individual JSON files for distribution. Default input: `./registry.json`, default output: `./public/r`.
|
||||||
|
|
||||||
|
For authoring rules, `include`, item definitions, `registryDependencies`, and
|
||||||
|
GitHub registry behavior, see [registry.md](./registry.md).
|
||||||
|
|
||||||
|
| Flag | Short | Description | Default |
|
||||||
|
| ----------------- | ----- | ----------------- | ------------ |
|
||||||
|
| `--output <path>` | `-o` | Output directory | `./public/r` |
|
||||||
|
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Templates
|
||||||
|
|
||||||
|
| Value | Framework | Monorepo support |
|
||||||
|
| -------------- | -------------- | ---------------- |
|
||||||
|
| `next` | Next.js | Yes |
|
||||||
|
| `vite` | Vite | Yes |
|
||||||
|
| `start` | TanStack Start | Yes |
|
||||||
|
| `react-router` | React Router | Yes |
|
||||||
|
| `astro` | Astro | Yes |
|
||||||
|
| `laravel` | Laravel | No |
|
||||||
|
|
||||||
|
All templates support monorepo scaffolding via the `--monorepo` flag. When passed, the CLI uses a monorepo-specific template directory (e.g. `next-monorepo`, `vite-monorepo`). When neither `--monorepo` nor `--no-monorepo` is passed, the CLI prompts interactively. Laravel does not support monorepo scaffolding.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Presets
|
||||||
|
|
||||||
|
Three ways to specify a preset via `--preset`:
|
||||||
|
|
||||||
|
1. **Named:** `--preset nova` or `--preset lyra`
|
||||||
|
2. **Code:** `--preset a2r6bw` (version-prefixed base62 string, e.g. `a2r6bw` or `b0`)
|
||||||
|
3. **URL:** `--preset "https://ui.shadcn.com/init?base=radix&style=nova&..."`
|
||||||
|
|
||||||
|
> **IMPORTANT:** Never try to decode, fetch, or resolve preset codes manually. Preset codes are opaque — pass them directly to `npx shadcn@latest init --preset <code>` and let the CLI handle resolution.
|
||||||
|
> Use `npx shadcn@latest apply --preset <code>` when overwriting an existing project's preset.
|
||||||
|
|
||||||
|
## Switching Presets
|
||||||
|
|
||||||
|
Ask the user first: **overwrite**, **merge**, or **skip** existing components?
|
||||||
|
|
||||||
|
- **Overwrite / Re-install** → `npx shadcn@latest apply --preset <code>`. Overwrites all detected component files with the new preset styles. Use when the user hasn't customized components.
|
||||||
|
- **Merge** → `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to get the list of installed components and use the [smart merge workflow](./SKILL.md#updating-components) to update them one by one, preserving local changes. Use when the user has customized components.
|
||||||
|
- **Skip** → `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS variables, leaves existing components as-is.
|
||||||
|
|
||||||
|
Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
# Customization & Theming
|
||||||
|
|
||||||
|
Components reference semantic CSS variable tokens. Change the variables to change every component.
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- How it works (CSS variables → Tailwind utilities → components)
|
||||||
|
- Color variables and OKLCH format
|
||||||
|
- Dark mode setup
|
||||||
|
- Changing the theme (presets, CSS variables)
|
||||||
|
- Adding custom colors (Tailwind v3 and v4)
|
||||||
|
- Border radius
|
||||||
|
- Customizing components (variants, className, wrappers)
|
||||||
|
- Checking for updates
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## How It Works
|
||||||
|
|
||||||
|
1. CSS variables defined in `:root` (light) and `.dark` (dark mode).
|
||||||
|
2. Tailwind maps them to utilities: `bg-primary`, `text-muted-foreground`, etc.
|
||||||
|
3. Components use these utilities — changing a variable changes all components that reference it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Color Variables
|
||||||
|
|
||||||
|
Every color follows the `name` / `name-foreground` convention. The base variable is for backgrounds, `-foreground` is for text/icons on that background.
|
||||||
|
|
||||||
|
| Variable | Purpose |
|
||||||
|
| -------------------------------------------- | -------------------------------- |
|
||||||
|
| `--background` / `--foreground` | Page background and default text |
|
||||||
|
| `--card` / `--card-foreground` | Card surfaces |
|
||||||
|
| `--primary` / `--primary-foreground` | Primary buttons and actions |
|
||||||
|
| `--secondary` / `--secondary-foreground` | Secondary actions |
|
||||||
|
| `--muted` / `--muted-foreground` | Muted/disabled states |
|
||||||
|
| `--accent` / `--accent-foreground` | Hover and accent states |
|
||||||
|
| `--destructive` / `--destructive-foreground` | Error and destructive actions |
|
||||||
|
| `--border` | Default border color |
|
||||||
|
| `--input` | Form input borders |
|
||||||
|
| `--ring` | Focus ring color |
|
||||||
|
| `--chart-1` through `--chart-5` | Chart/data visualization |
|
||||||
|
| `--sidebar-*` | Sidebar-specific colors |
|
||||||
|
| `--surface` / `--surface-foreground` | Secondary surface |
|
||||||
|
|
||||||
|
Colors use OKLCH: `--primary: oklch(0.205 0 0)` where values are lightness (0–1), chroma (0 = gray), and hue (0–360).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dark Mode
|
||||||
|
|
||||||
|
Class-based toggle via `.dark` on the root element. In Next.js, use `next-themes`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { ThemeProvider } from "next-themes"
|
||||||
|
|
||||||
|
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
|
||||||
|
{children}
|
||||||
|
</ThemeProvider>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Changing the Theme
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Apply a preset code from ui.shadcn.com.
|
||||||
|
npx shadcn@latest apply --preset a2r6bw
|
||||||
|
|
||||||
|
# Positional shorthand also works.
|
||||||
|
npx shadcn@latest apply a2r6bw
|
||||||
|
|
||||||
|
# Switch to a named preset and overwrite existing components.
|
||||||
|
npx shadcn@latest apply --preset nova
|
||||||
|
|
||||||
|
# Preserve existing components instead.
|
||||||
|
npx shadcn@latest init --preset nova --force --no-reinstall
|
||||||
|
|
||||||
|
# Use a custom theme URL.
|
||||||
|
npx shadcn@latest apply --preset "https://ui.shadcn.com/init?base=radix&style=nova&theme=blue&..."
|
||||||
|
```
|
||||||
|
|
||||||
|
Or edit CSS variables directly in `globals.css`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Adding Custom Colors
|
||||||
|
|
||||||
|
Add variables to the file at `tailwindCssFile` from `npx shadcn@latest info` (typically `globals.css`). Never create a new CSS file for this.
|
||||||
|
|
||||||
|
```css
|
||||||
|
/* 1. Define in the global CSS file. */
|
||||||
|
:root {
|
||||||
|
--warning: oklch(0.84 0.16 84);
|
||||||
|
--warning-foreground: oklch(0.28 0.07 46);
|
||||||
|
}
|
||||||
|
.dark {
|
||||||
|
--warning: oklch(0.41 0.11 46);
|
||||||
|
--warning-foreground: oklch(0.99 0.02 95);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```css
|
||||||
|
/* 2a. Register with Tailwind v4 (@theme inline). */
|
||||||
|
@theme inline {
|
||||||
|
--color-warning: var(--warning);
|
||||||
|
--color-warning-foreground: var(--warning-foreground);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
When `tailwindVersion` is `"v3"` (check via `npx shadcn@latest info`), register in `tailwind.config.js` instead:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// 2b. Register with Tailwind v3 (tailwind.config.js).
|
||||||
|
module.exports = {
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
warning: "oklch(var(--warning) / <alpha-value>)",
|
||||||
|
"warning-foreground":
|
||||||
|
"oklch(var(--warning-foreground) / <alpha-value>)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// 3. Use in components.
|
||||||
|
<div className="bg-warning text-warning-foreground">Warning</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Border Radius
|
||||||
|
|
||||||
|
`--radius` controls border radius globally. Components derive values from it (`rounded-lg` = `var(--radius)`, `rounded-md` = `calc(var(--radius) - 2px)`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Customizing Components
|
||||||
|
|
||||||
|
See also: [rules/styling.md](./rules/styling.md) for Incorrect/Correct examples.
|
||||||
|
|
||||||
|
Prefer these approaches in order:
|
||||||
|
|
||||||
|
### 1. Built-in variants
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button variant="outline" size="sm">
|
||||||
|
Click
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Tailwind classes via `className`
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Card className="mx-auto max-w-md">...</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Add a new variant
|
||||||
|
|
||||||
|
Edit the component source to add a variant via `cva`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// components/ui/button.tsx
|
||||||
|
warning: "bg-warning text-warning-foreground hover:bg-warning/90",
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Wrapper components
|
||||||
|
|
||||||
|
Compose shadcn/ui primitives into higher-level components:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export function ConfirmDialog({ title, description, onConfirm, children }) {
|
||||||
|
return (
|
||||||
|
<AlertDialog>
|
||||||
|
<AlertDialogTrigger asChild>{children}</AlertDialogTrigger>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>{description}</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||||
|
<AlertDialogAction onClick={onConfirm}>Confirm</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Checking for Updates
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest add button --diff
|
||||||
|
```
|
||||||
|
|
||||||
|
To preview exactly what would change before updating, use `--dry-run` and `--diff`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest add button --dry-run # see all affected files
|
||||||
|
npx shadcn@latest add button --diff button.tsx # see the diff for a specific file
|
||||||
|
```
|
||||||
|
|
||||||
|
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full smart merge workflow.
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
{
|
||||||
|
"skill_name": "shadcn",
|
||||||
|
"evals": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"prompt": "I'm building a Next.js app with shadcn/ui (base-nova preset, lucide icons). Create a settings form component with fields for: full name, email address, and notification preferences (email, SMS, push notifications as toggle options). Add validation states for required fields.",
|
||||||
|
"expected_output": "A React component using FieldGroup, Field, ToggleGroup, data-invalid/aria-invalid validation, gap-* spacing, and semantic colors.",
|
||||||
|
"files": [],
|
||||||
|
"expectations": [
|
||||||
|
"Uses FieldGroup and Field components for form layout instead of raw div with space-y",
|
||||||
|
"Uses Switch for independent on/off notification toggles (not looping Button with manual active state)",
|
||||||
|
"Uses data-invalid on Field and aria-invalid on the input control for validation states",
|
||||||
|
"Uses gap-* (e.g. gap-4, gap-6) instead of space-y-* or space-x-* for spacing",
|
||||||
|
"Uses semantic color tokens (e.g. bg-background, text-muted-foreground, text-destructive) instead of raw colors like bg-red-500",
|
||||||
|
"No manual dark: color overrides"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"prompt": "Create a dialog component for editing a user profile. It should have the user's avatar at the top, input fields for name and bio, and Save/Cancel buttons with appropriate icons. Using shadcn/ui with radix-nova preset and tabler icons.",
|
||||||
|
"expected_output": "A React component with DialogTitle, Avatar+AvatarFallback, data-icon on icon buttons, no icon sizing classes, tabler icon imports.",
|
||||||
|
"files": [],
|
||||||
|
"expectations": [
|
||||||
|
"Includes DialogTitle for accessibility (visible or with sr-only class)",
|
||||||
|
"Avatar component includes AvatarFallback",
|
||||||
|
"Icons on buttons use the data-icon attribute (data-icon=\"inline-start\" or data-icon=\"inline-end\")",
|
||||||
|
"No sizing classes on icons inside components (no size-4, w-4, h-4, etc.)",
|
||||||
|
"Uses tabler icons (@tabler/icons-react) instead of lucide-react",
|
||||||
|
"Uses asChild for custom triggers (radix preset)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"prompt": "Create a dashboard component that shows 4 stat cards in a grid. Each card has a title, large number, percentage change badge, and a loading skeleton state. Using shadcn/ui with base-nova preset and lucide icons.",
|
||||||
|
"expected_output": "A React component with full Card composition, Skeleton for loading, Badge for changes, semantic colors, gap-* spacing.",
|
||||||
|
"files": [],
|
||||||
|
"expectations": [
|
||||||
|
"Uses full Card composition with CardHeader, CardTitle, CardContent (not dumping everything into CardContent)",
|
||||||
|
"Uses Skeleton component for loading placeholders instead of custom animate-pulse divs",
|
||||||
|
"Uses Badge component for percentage change instead of custom styled spans",
|
||||||
|
"Uses semantic color tokens instead of raw color values like bg-green-500 or text-red-600",
|
||||||
|
"Uses gap-* instead of space-y-* or space-x-* for spacing",
|
||||||
|
"Uses size-* when width and height are equal instead of separate w-* h-*"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"prompt": "I'm building a Next.js app with shadcn/ui (base-nova preset, lucide icons). Build a chat conversation view: a scrollable thread of messages from two different people, each with an avatar, sender name, timestamp, and message bubble. A couple of messages include an image attachment and a PDF file attachment, and there's a 'Today' divider separating the days.",
|
||||||
|
"expected_output": "A React component composing MessageScroller, Message, Bubble, Attachment, and Marker from the registry instead of hand-rolled bubble/divider/attachment markup.",
|
||||||
|
"files": [],
|
||||||
|
"expectations": [
|
||||||
|
"Uses MessageScroller (MessageScrollerProvider, MessageScrollerViewport, MessageScrollerContent, MessageScrollerItem) for the scrollable thread instead of a raw overflow-y-auto div or ScrollArea",
|
||||||
|
"Wraps each row in MessageScrollerItem inside MessageScrollerContent",
|
||||||
|
"Uses Message with MessageAvatar/MessageContent/MessageHeader for row layout instead of custom flex divs",
|
||||||
|
"Uses Bubble + BubbleContent for the message surface instead of a styled div with bg-muted/bg-primary",
|
||||||
|
"Uses Attachment (AttachmentMedia, AttachmentContent, AttachmentTitle, AttachmentDescription) for the file and image attachments instead of Item or a custom card",
|
||||||
|
"Uses Marker (variant=\"separator\") for the 'Today' divider instead of Separator plus a centered label",
|
||||||
|
"Uses semantic color tokens and gap-* spacing; no raw colors like bg-emerald-500 and no space-y-*",
|
||||||
|
"Includes \"use client\" when the component uses state or event handlers (isRSC)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"prompt": "Using shadcn/ui (base-nova preset, lucide icons), build a streaming AI chat UI. The assistant's reply streams in while it generates, the view auto-scrolls to follow the latest content but stops following if the user scrolls up to read earlier messages, a 'jump to latest' button appears when the user has scrolled away from the bottom, and a subtle 'thinking…' shimmer shows while the model is generating.",
|
||||||
|
"expected_output": "A React component that delegates scroll/anchor behavior to MessageScroller and uses MessageScrollerButton for jump-to-latest and the shimmer utility for the thinking indicator — no hand-rolled scroll logic or custom shimmer keyframes.",
|
||||||
|
"files": [],
|
||||||
|
"expectations": [
|
||||||
|
"Uses MessageScroller with MessageScrollerProvider (autoScroll) and scrollAnchor on message items for the stick-to-bottom/follow behavior instead of a custom useStickToBottom hook or ResizeObserver/scrollTop wiring",
|
||||||
|
"Uses MessageScrollerButton for the jump-to-latest control instead of a hand-built conditional button driven by manual scroll-position state",
|
||||||
|
"Uses the shimmer utility class for the 'thinking…' indicator instead of a custom @keyframes or bg-clip-text gradient animation",
|
||||||
|
"Wraps each message row in MessageScrollerItem inside MessageScrollerContent",
|
||||||
|
"Uses Message + Bubble + BubbleContent for the conversation rows instead of hand-rolled bubble divs",
|
||||||
|
"Uses semantic color tokens and gap-* spacing; includes \"use client\" (isRSC)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
# shadcn MCP Server
|
||||||
|
|
||||||
|
The CLI includes an MCP server that lets AI assistants search, browse, view, and install items from registries.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
shadcn mcp # start the MCP server (stdio)
|
||||||
|
shadcn mcp init # write config for your editor
|
||||||
|
```
|
||||||
|
|
||||||
|
Editor config files:
|
||||||
|
|
||||||
|
| Editor | Config file |
|
||||||
|
| ----------- | ------------------------------- |
|
||||||
|
| Claude Code | `.mcp.json` |
|
||||||
|
| Cursor | `.cursor/mcp.json` |
|
||||||
|
| VS Code | `.vscode/mcp.json` |
|
||||||
|
| OpenCode | `opencode.json` |
|
||||||
|
| Codex | `~/.codex/config.toml` (manual) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
|
||||||
|
> **Tip:** MCP tools handle registry operations (search, view, install). For project configuration (aliases, framework, Tailwind version), use `npx shadcn@latest info` — there is no MCP equivalent.
|
||||||
|
|
||||||
|
### `shadcn:get_project_registries`
|
||||||
|
|
||||||
|
Returns registry names from `components.json`. Errors if no `components.json` exists.
|
||||||
|
|
||||||
|
**Input:** none
|
||||||
|
|
||||||
|
### `shadcn:list_items_in_registries`
|
||||||
|
|
||||||
|
Lists all items from one or more registries. Registries can be configured
|
||||||
|
namespaces such as `@acme`, public GitHub sources such as `owner/repo`, or
|
||||||
|
registry catalog URLs. Omit `registries` to list from every registry configured
|
||||||
|
in `components.json`.
|
||||||
|
|
||||||
|
**Input:** `registries` (string[], optional — omit for all configured), `types` (string[], optional — e.g. `["ui", "block"]`), `limit` (number, optional, defaults to 100), `offset` (number, optional)
|
||||||
|
|
||||||
|
### `shadcn:search_items_in_registries`
|
||||||
|
|
||||||
|
Fuzzy search across registries. Registries can be configured namespaces, public
|
||||||
|
GitHub sources, or registry catalog URLs. Omit `registries` to search every
|
||||||
|
registry configured in `components.json` — e.g. "find me a hero" across all
|
||||||
|
configured registries.
|
||||||
|
|
||||||
|
**Input:** `registries` (string[], optional — omit for all configured), `query` (string), `types` (string[], optional — e.g. `["ui", "block"]`), `limit` (number, optional, defaults to 100), `offset` (number, optional)
|
||||||
|
|
||||||
|
### `shadcn:view_items_in_registries`
|
||||||
|
|
||||||
|
View item details including full file contents.
|
||||||
|
|
||||||
|
**Input:** `items` (string[]) — e.g.
|
||||||
|
`["@shadcn/button", "@shadcn/card", "owner/repo/item"]`
|
||||||
|
|
||||||
|
### `shadcn:get_item_examples_from_registries`
|
||||||
|
|
||||||
|
Find usage examples and demos with source code. Omit `registries` to search
|
||||||
|
every registry configured in `components.json`.
|
||||||
|
|
||||||
|
**Input:** `registries` (string[], optional — omit for all configured), `query` (string) — e.g. `"accordion-demo"`, `"button example"`
|
||||||
|
|
||||||
|
### `shadcn:get_add_command_for_items`
|
||||||
|
|
||||||
|
Returns the CLI install command.
|
||||||
|
|
||||||
|
**Input:** `items` (string[]) — e.g. `["@shadcn/button"]`
|
||||||
|
|
||||||
|
### `shadcn:get_audit_checklist`
|
||||||
|
|
||||||
|
Returns a checklist for verifying components (imports, deps, lint, TypeScript).
|
||||||
|
|
||||||
|
**Input:** none
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Configuring Registries
|
||||||
|
|
||||||
|
Namespaced and authenticated registries are set in `components.json`. The
|
||||||
|
`@shadcn` registry is always built-in. Public GitHub registries can also be used
|
||||||
|
directly as `owner/repo` registry sources when the repository has a root
|
||||||
|
`registry.json`; they do not need `components.json` configuration.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"registries": {
|
||||||
|
"@acme": "https://acme.com/r/{name}.json",
|
||||||
|
"@private": {
|
||||||
|
"url": "https://private.com/r/{name}.json",
|
||||||
|
"headers": { "Authorization": "Bearer ${MY_TOKEN}" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Names must start with `@`.
|
||||||
|
- URLs must contain `{name}`.
|
||||||
|
- `${VAR}` references are resolved from environment variables.
|
||||||
|
|
||||||
|
Community registry index: `https://ui.shadcn.com/r/registries.json`
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
# Registry Authoring and Addresses
|
||||||
|
|
||||||
|
Use this reference when the user wants to create, fix, publish, or reason about
|
||||||
|
a shadcn registry.
|
||||||
|
|
||||||
|
## Mental Model
|
||||||
|
|
||||||
|
A registry has two forms:
|
||||||
|
|
||||||
|
- **Source registry**: an authored `registry.json` in a project or repository.
|
||||||
|
It may use `include` and file paths that point at source files.
|
||||||
|
- **Built registry**: generated JSON files served to CLI consumers, usually
|
||||||
|
from `public/r`. Use `npx shadcn@latest build` to create this form.
|
||||||
|
|
||||||
|
The CLI installer consumes registry item payloads. A source registry is a way to
|
||||||
|
author those payloads from real files.
|
||||||
|
|
||||||
|
Registry items are not limited to React components. They can distribute
|
||||||
|
components, hooks, utilities, design tokens, pages, config files, docs, rules,
|
||||||
|
workflows, templates, MCP files, and other project files.
|
||||||
|
|
||||||
|
## Root `registry.json`
|
||||||
|
|
||||||
|
The root registry file should define registry metadata and either `items` or
|
||||||
|
`include`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema/registry.json",
|
||||||
|
"name": "acme",
|
||||||
|
"homepage": "https://acme.com",
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"name": "absolute-url",
|
||||||
|
"type": "registry:lib",
|
||||||
|
"title": "Absolute URL",
|
||||||
|
"description": "A utility to turn any path into an absolute URL.",
|
||||||
|
"files": [
|
||||||
|
{
|
||||||
|
"path": "lib/absolute-url.ts",
|
||||||
|
"type": "registry:lib"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Root registry rules:
|
||||||
|
|
||||||
|
- Root `registry.json` must include `name` and `homepage`.
|
||||||
|
- `items` is an array of registry item definitions.
|
||||||
|
- `include` may be used to split the source registry into multiple files.
|
||||||
|
- Included registry files may omit `name` and `homepage`.
|
||||||
|
|
||||||
|
## Include
|
||||||
|
|
||||||
|
Use `include` to keep large registries modular.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema/registry.json",
|
||||||
|
"name": "acme",
|
||||||
|
"homepage": "https://acme.com",
|
||||||
|
"include": ["registry/ui/registry.json", "registry/blocks/registry.json"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Include rules:
|
||||||
|
|
||||||
|
- Include paths are relative to the `registry.json` that declares them.
|
||||||
|
- Include paths must explicitly point to a `registry.json` file.
|
||||||
|
- Do not use remote URLs, absolute paths, or parent traversal (`..`).
|
||||||
|
- Item file paths are relative to the registry file that declares the item.
|
||||||
|
- Duplicate item names fail across the resolved registry.
|
||||||
|
|
||||||
|
Example included file:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"name": "button",
|
||||||
|
"type": "registry:ui",
|
||||||
|
"files": [
|
||||||
|
{
|
||||||
|
"path": "button.tsx",
|
||||||
|
"type": "registry:ui"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If this file is at `registry/ui/registry.json`, then `button.tsx` is read from
|
||||||
|
`registry/ui/button.tsx`, and the built item path is emitted relative to the
|
||||||
|
root registry.
|
||||||
|
|
||||||
|
## Item Definitions
|
||||||
|
|
||||||
|
Common item fields:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "login-form",
|
||||||
|
"type": "registry:block",
|
||||||
|
"title": "Login Form",
|
||||||
|
"description": "A login form with email and password fields.",
|
||||||
|
"dependencies": ["zod"],
|
||||||
|
"registryDependencies": ["button", "input", "label"],
|
||||||
|
"files": [
|
||||||
|
{
|
||||||
|
"path": "blocks/login-form.tsx",
|
||||||
|
"type": "registry:block"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"cssVars": {
|
||||||
|
"light": {
|
||||||
|
"brand": "oklch(0.62 0.18 250)"
|
||||||
|
},
|
||||||
|
"dark": {
|
||||||
|
"brand": "oklch(0.72 0.16 250)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Important fields:
|
||||||
|
|
||||||
|
- `name`: the installable item name. It is not necessarily a file path.
|
||||||
|
- `type`: one of the registry item types, such as `registry:ui`,
|
||||||
|
`registry:block`, `registry:lib`, `registry:hook`, `registry:file`,
|
||||||
|
`registry:page`, `registry:theme`, `registry:style`, `registry:font`, or
|
||||||
|
`registry:item`.
|
||||||
|
- `files`: source files copied or generated by the item.
|
||||||
|
- `dependencies`: npm runtime dependencies.
|
||||||
|
- `devDependencies`: npm development dependencies.
|
||||||
|
- `registryDependencies`: other registry items required by this item.
|
||||||
|
- `cssVars`, `css`, `tailwind`, `envVars`, and `docs`: optional install-time
|
||||||
|
additions.
|
||||||
|
|
||||||
|
File rules:
|
||||||
|
|
||||||
|
- File paths are relative to the declaring `registry.json`.
|
||||||
|
- `registry:file` and `registry:page` files require a `target`.
|
||||||
|
- Do not use remote file URLs in source registry file paths.
|
||||||
|
- Keep source files copy-pasteable: no hidden app-only imports.
|
||||||
|
|
||||||
|
## Registry Dependencies
|
||||||
|
|
||||||
|
`registryDependencies` entries are item addresses, not file paths.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "login-form",
|
||||||
|
"type": "registry:block",
|
||||||
|
"registryDependencies": ["button", "@acme/input", "acme/ui/card#v1.2.0"],
|
||||||
|
"files": [
|
||||||
|
{
|
||||||
|
"path": "blocks/login-form.tsx",
|
||||||
|
"type": "registry:block"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Dependency rules:
|
||||||
|
|
||||||
|
- Bare names such as `"button"` mean official shadcn items.
|
||||||
|
- Bare names never mean same-registry or same-repository items.
|
||||||
|
- Namespaced dependencies use `@namespace/item-name`.
|
||||||
|
- GitHub dependencies use `owner/repo/item-name`.
|
||||||
|
- Pin GitHub dependencies with `owner/repo/item-name#ref` when needed.
|
||||||
|
- Refs are not inherited. If `owner/repo/foo#v2` depends on `bar` from the same
|
||||||
|
repo at `v2`, write `owner/repo/bar#v2`.
|
||||||
|
- Do not use relative dependencies such as `"./bar"`.
|
||||||
|
|
||||||
|
## Address Schemes
|
||||||
|
|
||||||
|
When reasoning about a registry item string, classify it first.
|
||||||
|
|
||||||
|
| Address | Scheme | Meaning |
|
||||||
|
| ----------------------------------- | --------- | ------------------------------------------------------------ |
|
||||||
|
| `button` | shadcn | Official shadcn item named `button`. |
|
||||||
|
| `@acme/button` | namespace | Item `button` from configured registry `@acme`. |
|
||||||
|
| `@acme/ui/button` | namespace | Item `ui/button` from configured registry `@acme`. |
|
||||||
|
| `https://example.com/r/button.json` | url | Built registry item JSON at that URL. |
|
||||||
|
| `./button.json` | file | Built registry item JSON on disk. |
|
||||||
|
| `acme/ui/button` | github | Item `button` from GitHub repo `acme/ui`. |
|
||||||
|
| `acme/ui/forms/login#main` | github | Item `forms/login` from GitHub repo `acme/ui` at ref `main`. |
|
||||||
|
|
||||||
|
For namespace and GitHub addresses, slashful item names are allowed and are item
|
||||||
|
names, not file paths. Addresses ending in `.json` keep file-address
|
||||||
|
precedence, so `acme/ui/data/schema.json` is treated as a file path, not a
|
||||||
|
GitHub item address.
|
||||||
|
|
||||||
|
## GitHub Registries
|
||||||
|
|
||||||
|
A public GitHub repository can act as a source registry when it has a root
|
||||||
|
`registry.json`.
|
||||||
|
|
||||||
|
```txt
|
||||||
|
owner/repo/item-name[#ref]
|
||||||
|
```
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- The first two path segments are GitHub owner and repo.
|
||||||
|
- All remaining path segments are the registry item name.
|
||||||
|
- The source entrypoint is always root `registry.json`.
|
||||||
|
- GitHub registries are source registries consumed directly by the CLI. They do
|
||||||
|
not require `shadcn build` or generated item JSON files.
|
||||||
|
- `include` follows the same source-registry rules as local registries.
|
||||||
|
- Currently, GitHub addresses support public `github.com` repositories only.
|
||||||
|
- Private repos and GitHub Enterprise require explicit product decisions.
|
||||||
|
|
||||||
|
When implementing GitHub registry fetching, resolve refs to a commit SHA before
|
||||||
|
reading source files. Do not read moving refs directly from
|
||||||
|
`raw.githubusercontent.com`, because branch-like refs can be cached for several
|
||||||
|
minutes.
|
||||||
|
|
||||||
|
Preferred flow:
|
||||||
|
|
||||||
|
```txt
|
||||||
|
owner/repo[#ref]
|
||||||
|
-> resolve ref with git ls-remote
|
||||||
|
-> commit SHA
|
||||||
|
-> read https://raw.githubusercontent.com/{owner}/{repo}/{sha}/registry.json
|
||||||
|
-> read includes and item files from the same SHA
|
||||||
|
```
|
||||||
|
|
||||||
|
This keeps a command on one consistent repository snapshot.
|
||||||
|
|
||||||
|
Full 40-character commit SHAs are already stable and can be used directly.
|
||||||
|
Branches, tags, and short refs require Git so the CLI can resolve them to a
|
||||||
|
commit SHA first.
|
||||||
|
|
||||||
|
## Build and Verify
|
||||||
|
|
||||||
|
Use the CLI to build source registries:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest build
|
||||||
|
npx shadcn@latest build registry.json --output public/r
|
||||||
|
```
|
||||||
|
|
||||||
|
Use CLI commands to inspect the result:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest list @acme
|
||||||
|
npx shadcn@latest search @acme -q "login"
|
||||||
|
npx shadcn@latest view @acme/login-form
|
||||||
|
npx shadcn@latest add @acme/login-form --dry-run
|
||||||
|
npx shadcn@latest registry validate ./registry.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Use GitHub addresses directly for public GitHub registries:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest list owner/repo
|
||||||
|
npx shadcn@latest search owner/repo -q "login"
|
||||||
|
npx shadcn@latest view owner/repo/item
|
||||||
|
npx shadcn@latest add owner/repo/item --dry-run
|
||||||
|
npx shadcn@latest registry validate owner/repo
|
||||||
|
```
|
||||||
|
|
||||||
|
When working on registry implementation in the shadcn/ui codebase:
|
||||||
|
|
||||||
|
- Keep address parsing pure and testable.
|
||||||
|
- Do not add side effects to validators.
|
||||||
|
- Preserve existing behavior for official shadcn, namespace, URL, and file
|
||||||
|
schemes.
|
||||||
|
- Add tests for address parsing, source loading, dependency resolution, list,
|
||||||
|
search, view, and add paths.
|
||||||
|
- Prefer small source-reader abstractions over a plugin system until there are
|
||||||
|
multiple real providers.
|
||||||
@@ -0,0 +1,306 @@
|
|||||||
|
# Base vs Radix
|
||||||
|
|
||||||
|
API differences between `base` and `radix`. Check the `base` field from `npx shadcn@latest info`.
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- Composition: asChild vs render
|
||||||
|
- Button / trigger as non-button element
|
||||||
|
- Select (items prop, placeholder, positioning, multiple, object values)
|
||||||
|
- ToggleGroup (type vs multiple)
|
||||||
|
- Slider (scalar vs array)
|
||||||
|
- Accordion (type and defaultValue)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Composition: asChild (radix) vs render (base)
|
||||||
|
|
||||||
|
Radix uses `asChild` to replace the default element. Base uses `render`. Don't wrap triggers in extra elements.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<DialogTrigger>
|
||||||
|
<div>
|
||||||
|
<Button>Open</Button>
|
||||||
|
</div>
|
||||||
|
</DialogTrigger>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<Button>Open</Button>
|
||||||
|
</DialogTrigger>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<DialogTrigger render={<Button />}>Open</DialogTrigger>
|
||||||
|
```
|
||||||
|
|
||||||
|
This applies to all trigger and close components: `DialogTrigger`, `SheetTrigger`, `AlertDialogTrigger`, `DropdownMenuTrigger`, `PopoverTrigger`, `TooltipTrigger`, `CollapsibleTrigger`, `DialogClose`, `SheetClose`, `NavigationMenuLink`, `BreadcrumbLink`, `SidebarMenuButton`, `Badge`, `Item`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Button / trigger as non-button element (base only)
|
||||||
|
|
||||||
|
When `render` changes an element to a non-button (`<a>`, `<span>`), add `nativeButton={false}`.
|
||||||
|
|
||||||
|
**Incorrect (base):** missing `nativeButton={false}`.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button render={<a href="/docs" />}>Read the docs</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button render={<a href="/docs" />} nativeButton={false}>
|
||||||
|
Read the docs
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button asChild>
|
||||||
|
<a href="/docs">Read the docs</a>
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
Same for triggers whose `render` is not a `Button`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// base.
|
||||||
|
<PopoverTrigger render={<InputGroupAddon />} nativeButton={false}>
|
||||||
|
Pick date
|
||||||
|
</PopoverTrigger>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Select
|
||||||
|
|
||||||
|
**items prop (base only).** Base requires an `items` prop on the root. Radix uses inline JSX only.
|
||||||
|
|
||||||
|
**Incorrect (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Select>
|
||||||
|
<SelectTrigger><SelectValue placeholder="Select a fruit" /></SelectTrigger>
|
||||||
|
</Select>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const items = [
|
||||||
|
{ label: "Select a fruit", value: null },
|
||||||
|
{ label: "Apple", value: "apple" },
|
||||||
|
{ label: "Banana", value: "banana" },
|
||||||
|
]
|
||||||
|
|
||||||
|
<Select items={items}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectGroup>
|
||||||
|
{items.map((item) => (
|
||||||
|
<SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectGroup>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Select>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select a fruit" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectGroup>
|
||||||
|
<SelectItem value="apple">Apple</SelectItem>
|
||||||
|
<SelectItem value="banana">Banana</SelectItem>
|
||||||
|
</SelectGroup>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Placeholder.** Base uses a `{ value: null }` item in the items array. Radix uses `<SelectValue placeholder="...">`.
|
||||||
|
|
||||||
|
**Content positioning.** Base uses `alignItemWithTrigger`. Radix uses `position`.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// base.
|
||||||
|
<SelectContent alignItemWithTrigger={false} side="bottom">
|
||||||
|
|
||||||
|
// radix.
|
||||||
|
<SelectContent position="popper">
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Select — multiple selection and object values (base only)
|
||||||
|
|
||||||
|
Base supports `multiple`, render-function children on `SelectValue`, and object values with `itemToStringValue`. Radix is single-select with string values only.
|
||||||
|
|
||||||
|
**Correct (base — multiple selection):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Select items={items} multiple defaultValue={[]}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue>
|
||||||
|
{(value: string[]) => value.length === 0 ? "Select fruits" : `${value.length} selected`}
|
||||||
|
</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
...
|
||||||
|
</Select>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base — object values):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Select defaultValue={plans[0]} itemToStringValue={(plan) => plan.name}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue>{(value) => value.name}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
...
|
||||||
|
</Select>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ToggleGroup
|
||||||
|
|
||||||
|
Base uses a `multiple` boolean prop. Radix uses `type="single"` or `type="multiple"`.
|
||||||
|
|
||||||
|
**Incorrect (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<ToggleGroup type="single" defaultValue="daily">
|
||||||
|
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Single (no prop needed), defaultValue is always an array.
|
||||||
|
<ToggleGroup defaultValue={["daily"]} spacing={2}>
|
||||||
|
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
|
||||||
|
// Multi-selection.
|
||||||
|
<ToggleGroup multiple>
|
||||||
|
<ToggleGroupItem value="bold">Bold</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="italic">Italic</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Single, defaultValue is a string.
|
||||||
|
<ToggleGroup type="single" defaultValue="daily" spacing={2}>
|
||||||
|
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
|
||||||
|
// Multi-selection.
|
||||||
|
<ToggleGroup type="multiple">
|
||||||
|
<ToggleGroupItem value="bold">Bold</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="italic">Italic</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Controlled single value:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// base — wrap/unwrap arrays.
|
||||||
|
const [value, setValue] = React.useState("normal")
|
||||||
|
<ToggleGroup value={[value]} onValueChange={(v) => setValue(v[0])}>
|
||||||
|
|
||||||
|
// radix — plain string.
|
||||||
|
const [value, setValue] = React.useState("normal")
|
||||||
|
<ToggleGroup type="single" value={value} onValueChange={setValue}>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Slider
|
||||||
|
|
||||||
|
Base accepts a plain number for a single thumb. Radix always requires an array.
|
||||||
|
|
||||||
|
**Incorrect (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Slider defaultValue={[50]} max={100} step={1} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Slider defaultValue={50} max={100} step={1} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Slider defaultValue={[50]} max={100} step={1} />
|
||||||
|
```
|
||||||
|
|
||||||
|
Both use arrays for range sliders. Controlled `onValueChange` in base may need a cast:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// base.
|
||||||
|
const [value, setValue] = React.useState([0.3, 0.7])
|
||||||
|
<Slider value={value} onValueChange={(v) => setValue(v as number[])} />
|
||||||
|
|
||||||
|
// radix.
|
||||||
|
const [value, setValue] = React.useState([0.3, 0.7])
|
||||||
|
<Slider value={value} onValueChange={setValue} />
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Accordion
|
||||||
|
|
||||||
|
Radix requires `type="single"` or `type="multiple"` and supports `collapsible`. `defaultValue` is a string. Base uses no `type` prop, uses `multiple` boolean, and `defaultValue` is always an array.
|
||||||
|
|
||||||
|
**Incorrect (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Accordion type="single" collapsible defaultValue="item-1">
|
||||||
|
<AccordionItem value="item-1">...</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Accordion defaultValue={["item-1"]}>
|
||||||
|
<AccordionItem value="item-1">...</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
|
||||||
|
// Multi-select.
|
||||||
|
<Accordion multiple defaultValue={["item-1", "item-2"]}>
|
||||||
|
<AccordionItem value="item-1">...</AccordionItem>
|
||||||
|
<AccordionItem value="item-2">...</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Accordion type="single" collapsible defaultValue="item-1">
|
||||||
|
<AccordionItem value="item-1">...</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
```
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
# Chat & Messaging
|
||||||
|
|
||||||
|
Components for conversation and chat UI. Compose these instead of hand-rolling
|
||||||
|
bubbles, scroll containers, dividers, or attachment cards.
|
||||||
|
|
||||||
|
Install: `npx shadcn@latest add message-scroller message bubble attachment marker`
|
||||||
|
|
||||||
|
The same component names and props ship for both `base` and `radix`; only
|
||||||
|
composition differs (`render` vs `asChild`). See [base-vs-radix.md](./base-vs-radix.md).
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- Scrollable threads use MessageScroller
|
||||||
|
- Message rows use Message
|
||||||
|
- Message surfaces use Bubble
|
||||||
|
- Attachments use Attachment
|
||||||
|
- System notes and dividers use Marker
|
||||||
|
- Streaming, anchoring, and jump-to-latest are built in
|
||||||
|
- Escape hatch: the scroller hooks
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Scrollable threads use MessageScroller
|
||||||
|
|
||||||
|
A conversation that scrolls, follows new messages, restores position, or jumps
|
||||||
|
to a message uses `MessageScroller`. Don't build a raw overflow container with
|
||||||
|
manual scroll wiring, and don't reach for `ScrollArea`.
|
||||||
|
|
||||||
|
The parts nest in a fixed order. Every direct child of the content is wrapped in
|
||||||
|
a `MessageScrollerItem` so the scroller can measure, anchor, preserve position,
|
||||||
|
track visibility, and jump to it. `MessageScrollerButton` sits inside
|
||||||
|
`MessageScroller`, after the viewport.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Hand-rolled scroll container with manual stick-to-bottom logic.
|
||||||
|
<div ref={scrollRef} onScroll={handleScroll} className="flex-1 overflow-y-auto">
|
||||||
|
<div className="flex flex-col gap-6 p-4">
|
||||||
|
{messages.map((m) => (
|
||||||
|
<ChatMessage key={m.id} message={m} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<MessageScrollerProvider autoScroll>
|
||||||
|
<MessageScroller>
|
||||||
|
<MessageScrollerViewport>
|
||||||
|
<MessageScrollerContent>
|
||||||
|
{messages.map((message) => (
|
||||||
|
<MessageScrollerItem
|
||||||
|
key={message.id}
|
||||||
|
messageId={message.id}
|
||||||
|
scrollAnchor={message.role === "user"}
|
||||||
|
>
|
||||||
|
<Message align={message.role === "user" ? "end" : "start"}>
|
||||||
|
{/* ...message content... */}
|
||||||
|
</Message>
|
||||||
|
</MessageScrollerItem>
|
||||||
|
))}
|
||||||
|
</MessageScrollerContent>
|
||||||
|
</MessageScrollerViewport>
|
||||||
|
<MessageScrollerButton />
|
||||||
|
</MessageScroller>
|
||||||
|
</MessageScrollerProvider>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Message rows use Message
|
||||||
|
|
||||||
|
`Message` lays out a single row: avatar, header, content, footer, with
|
||||||
|
alignment. Group consecutive rows from one sender with `MessageGroup`. Don't
|
||||||
|
rebuild the row from flex divs.
|
||||||
|
|
||||||
|
`align="end"` is the current user's side; `align="start"` is everyone else.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Message align="start">
|
||||||
|
<MessageAvatar>
|
||||||
|
<Avatar>
|
||||||
|
<AvatarImage src={sender.avatar} alt={sender.name} />
|
||||||
|
<AvatarFallback>{initials}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
</MessageAvatar>
|
||||||
|
<MessageContent>
|
||||||
|
<MessageHeader>{sender.name}</MessageHeader>
|
||||||
|
<Bubble>
|
||||||
|
<BubbleContent>{text}</BubbleContent>
|
||||||
|
</Bubble>
|
||||||
|
<MessageFooter>{time}</MessageFooter>
|
||||||
|
</MessageContent>
|
||||||
|
</Message>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Message surfaces use Bubble
|
||||||
|
|
||||||
|
The colored message surface is `Bubble` + `BubbleContent`, never a styled `div`
|
||||||
|
with `bg-muted` / `bg-primary` and hand-managed corners.
|
||||||
|
|
||||||
|
- `variant`: `default`, `secondary`, `muted`, `tinted`, `outline`, `ghost`, `destructive`.
|
||||||
|
- `align`: `start` or `end` (matches the `Message` side).
|
||||||
|
|
||||||
|
`BubbleReactions` renders the reaction cluster. `side` (`top` | `bottom`) and
|
||||||
|
`align` (`start` | `end`) position it against the bubble. Don't lay reactions out
|
||||||
|
with absolutely-positioned `Badge`s.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className="w-fit rounded-2xl bg-primary px-3 py-2 text-primary-foreground">
|
||||||
|
{text}
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Bubble variant="default" align="end">
|
||||||
|
<BubbleContent>{text}</BubbleContent>
|
||||||
|
<BubbleReactions side="bottom" align="end">
|
||||||
|
<Badge variant="secondary">👍 2</Badge>
|
||||||
|
</BubbleReactions>
|
||||||
|
</Bubble>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Attachments use Attachment
|
||||||
|
|
||||||
|
File and image attachments use `Attachment`, not `Item` or a custom card. It
|
||||||
|
carries upload state, so wire `state` to the real status rather than rendering a
|
||||||
|
separate spinner.
|
||||||
|
|
||||||
|
- `state`: `idle`, `uploading`, `processing`, `error`, `done`. `uploading` and
|
||||||
|
`processing` apply the `shimmer` animation to the title automatically.
|
||||||
|
- `size`: `default`, `sm`, `xs`. `orientation`: `horizontal`, `vertical`.
|
||||||
|
- Use `AttachmentGroup` to lay out several attachments in a scrolling row.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Attachment state="done">
|
||||||
|
<AttachmentMedia variant="icon">
|
||||||
|
<FileTextIcon />
|
||||||
|
</AttachmentMedia>
|
||||||
|
<AttachmentContent>
|
||||||
|
<AttachmentTitle>homepage-feedback.pdf</AttachmentTitle>
|
||||||
|
<AttachmentDescription>PDF · 2.4 MB</AttachmentDescription>
|
||||||
|
</AttachmentContent>
|
||||||
|
<AttachmentActions>
|
||||||
|
<AttachmentAction>
|
||||||
|
<DownloadIcon />
|
||||||
|
</AttachmentAction>
|
||||||
|
</AttachmentActions>
|
||||||
|
</Attachment>
|
||||||
|
```
|
||||||
|
|
||||||
|
For an image, use `<AttachmentMedia variant="image">` with an `img` child.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## System notes and dividers use Marker
|
||||||
|
|
||||||
|
Status lines ("Sarah joined the conversation"), date dividers ("Today"), and
|
||||||
|
labeled separators are `Marker`, not a `Separator` plus a centered span.
|
||||||
|
|
||||||
|
- `variant`: `default` (plain row), `separator` (centered label with rules on
|
||||||
|
each side), `border` (bottom-bordered row).
|
||||||
|
- `MarkerIcon` holds a leading icon; `MarkerContent` holds the label.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className="flex items-center gap-3 py-2">
|
||||||
|
<Separator className="flex-1" />
|
||||||
|
<span className="text-xs text-muted-foreground">Today</span>
|
||||||
|
<Separator className="flex-1" />
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Marker variant="separator">
|
||||||
|
<MarkerContent>Today</MarkerContent>
|
||||||
|
</Marker>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Streaming, anchoring, and jump-to-latest are built in
|
||||||
|
|
||||||
|
`MessageScroller` handles the behavior that chat UIs usually reinvent. Don't
|
||||||
|
write a `useStickToBottom` hook, a `ResizeObserver`, or manual `scrollTop` math.
|
||||||
|
|
||||||
|
- **Follow the live edge while streaming.** `MessageScrollerProvider` with
|
||||||
|
`autoScroll` keeps the view pinned to new content and yields the moment the
|
||||||
|
user scrolls up. Streaming token updates that grow the last message are
|
||||||
|
followed automatically.
|
||||||
|
- **Anchor a turn.** `scrollAnchor` on a `MessageScrollerItem` marks the row to
|
||||||
|
hold in view (typically the user's message that started the turn).
|
||||||
|
- **Jump to latest.** `MessageScrollerButton` appears when the user scrolls away
|
||||||
|
and scrolls back on click. `direction="end"` (default) or `direction="start"`.
|
||||||
|
It is a self-managing control, so don't gate it behind your own scroll-position
|
||||||
|
state.
|
||||||
|
|
||||||
|
For a "thinking…" indicator while the model generates, apply the `shimmer`
|
||||||
|
utility to text. Don't author a custom keyframe animation. See
|
||||||
|
[styling.md](./styling.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Escape hatch: the scroller hooks
|
||||||
|
|
||||||
|
For behavior the parts don't expose, read state from the hooks rather than
|
||||||
|
re-implementing the scroller: `useMessageScroller`,
|
||||||
|
`useMessageScrollerVisibility`, and `useMessageScrollerScrollable`. They come
|
||||||
|
from the auto-installed `@shadcn/react` dependency, so there's nothing extra to
|
||||||
|
install. Reach for them only when composition can't express what you need.
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
# Component Composition
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- Items always inside their Group component
|
||||||
|
- Callouts use Alert
|
||||||
|
- Empty states use Empty component
|
||||||
|
- Toast notifications follow the project base
|
||||||
|
- Choosing between overlay components
|
||||||
|
- Dialog, Sheet, and Drawer always need a Title
|
||||||
|
- Card structure
|
||||||
|
- Button has no isPending or isLoading prop
|
||||||
|
- TabsTrigger must be inside TabsList
|
||||||
|
- Avatar always needs AvatarFallback
|
||||||
|
- Use Separator instead of raw hr or border divs
|
||||||
|
- Use Skeleton for loading placeholders
|
||||||
|
- Use Badge instead of custom styled spans
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Items always inside their Group component
|
||||||
|
|
||||||
|
Never render items directly inside the content container.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="apple">Apple</SelectItem>
|
||||||
|
<SelectItem value="banana">Banana</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<SelectContent>
|
||||||
|
<SelectGroup>
|
||||||
|
<SelectItem value="apple">Apple</SelectItem>
|
||||||
|
<SelectItem value="banana">Banana</SelectItem>
|
||||||
|
</SelectGroup>
|
||||||
|
</SelectContent>
|
||||||
|
```
|
||||||
|
|
||||||
|
This applies to all group-based components:
|
||||||
|
|
||||||
|
| Item | Group |
|
||||||
|
|------|-------|
|
||||||
|
| `SelectItem`, `SelectLabel` | `SelectGroup` |
|
||||||
|
| `DropdownMenuItem`, `DropdownMenuLabel`, `DropdownMenuSub` | `DropdownMenuGroup` |
|
||||||
|
| `MenubarItem` | `MenubarGroup` |
|
||||||
|
| `ContextMenuItem` | `ContextMenuGroup` |
|
||||||
|
| `CommandItem` | `CommandGroup` |
|
||||||
|
| `MessageScrollerItem` | `MessageScrollerContent` |
|
||||||
|
| `Message` (consecutive, same sender) | `MessageGroup` |
|
||||||
|
| `Bubble` (stacked) | `BubbleGroup` |
|
||||||
|
| `Attachment` (in a row) | `AttachmentGroup` |
|
||||||
|
|
||||||
|
Chat components nest in a fixed order (`MessageScrollerProvider` → `MessageScroller` → `MessageScrollerViewport` → `MessageScrollerContent` → `MessageScrollerItem`). See [chat.md](./chat.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Callouts use Alert
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Alert>
|
||||||
|
<AlertTitle>Warning</AlertTitle>
|
||||||
|
<AlertDescription>Something needs attention.</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Empty states use Empty component
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Empty>
|
||||||
|
<EmptyHeader>
|
||||||
|
<EmptyMedia variant="icon"><FolderIcon /></EmptyMedia>
|
||||||
|
<EmptyTitle>No projects yet</EmptyTitle>
|
||||||
|
<EmptyDescription>Get started by creating a new project.</EmptyDescription>
|
||||||
|
</EmptyHeader>
|
||||||
|
<EmptyContent>
|
||||||
|
<Button>Create Project</Button>
|
||||||
|
</EmptyContent>
|
||||||
|
</Empty>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Toast notifications follow the project base
|
||||||
|
|
||||||
|
For Base UI projects, use the `toast` component:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { toast } from "@/components/ui/toast"
|
||||||
|
|
||||||
|
toast.add({
|
||||||
|
title: "Changes saved.",
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
For Radix and React Aria projects, use Sonner:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { toast } from "sonner"
|
||||||
|
|
||||||
|
toast.success("Changes saved.")
|
||||||
|
toast.error("Something went wrong.")
|
||||||
|
toast("File deleted.", {
|
||||||
|
action: { label: "Undo", onClick: () => undoDelete() },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Choosing between overlay components
|
||||||
|
|
||||||
|
| Use case | Component |
|
||||||
|
|----------|-----------|
|
||||||
|
| Focused task that requires input | `Dialog` |
|
||||||
|
| Destructive action confirmation | `AlertDialog` |
|
||||||
|
| Side panel with details or filters | `Sheet` |
|
||||||
|
| Mobile-first bottom panel | `Drawer` |
|
||||||
|
| Quick info on hover | `HoverCard` |
|
||||||
|
| Small contextual content on click | `Popover` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dialog, Sheet, and Drawer always need a Title
|
||||||
|
|
||||||
|
`DialogTitle`, `SheetTitle`, `DrawerTitle` are required for accessibility. Use `className="sr-only"` if visually hidden.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Edit Profile</DialogTitle>
|
||||||
|
<DialogDescription>Update your profile.</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
...
|
||||||
|
</DialogContent>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Card structure
|
||||||
|
|
||||||
|
Use full composition — don't dump everything into `CardContent`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Team Members</CardTitle>
|
||||||
|
<CardDescription>Manage your team.</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>...</CardContent>
|
||||||
|
<CardFooter>
|
||||||
|
<Button>Invite</Button>
|
||||||
|
</CardFooter>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Button has no isPending or isLoading prop
|
||||||
|
|
||||||
|
Compose with `Spinner` + `data-icon` + `disabled`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button disabled>
|
||||||
|
<Spinner data-icon="inline-start" />
|
||||||
|
Saving...
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## TabsTrigger must be inside TabsList
|
||||||
|
|
||||||
|
Never render `TabsTrigger` directly inside `Tabs` — always wrap in `TabsList`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Tabs defaultValue="account">
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="account">Account</TabsTrigger>
|
||||||
|
<TabsTrigger value="password">Password</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent value="account">...</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Avatar always needs AvatarFallback
|
||||||
|
|
||||||
|
Always include `AvatarFallback` for when the image fails to load:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Avatar>
|
||||||
|
<AvatarImage src="/avatar.png" alt="User" />
|
||||||
|
<AvatarFallback>JD</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use existing components instead of custom markup
|
||||||
|
|
||||||
|
| Instead of | Use |
|
||||||
|
|---|---|
|
||||||
|
| `<hr>` or `<div className="border-t">` | `<Separator />` |
|
||||||
|
| `<div className="animate-pulse">` with styled divs | `<Skeleton className="h-4 w-3/4" />` |
|
||||||
|
| `<span className="rounded-full bg-green-100 ...">` | `<Badge variant="secondary">` |
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
# Forms & Inputs
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- Forms use FieldGroup + Field
|
||||||
|
- InputGroup requires InputGroupInput/InputGroupTextarea
|
||||||
|
- Buttons inside inputs use InputGroup + InputGroupAddon
|
||||||
|
- Option sets (2–7 choices) use ToggleGroup
|
||||||
|
- FieldSet + FieldLegend for grouping related fields
|
||||||
|
- Field validation and disabled states
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Forms use FieldGroup + Field
|
||||||
|
|
||||||
|
Always use `FieldGroup` + `Field` — never raw `div` with `space-y-*`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<FieldGroup>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||||
|
<Input id="email" type="email" />
|
||||||
|
</Field>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="password">Password</FieldLabel>
|
||||||
|
<Input id="password" type="password" />
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `Field orientation="horizontal"` for settings pages. Use `FieldLabel className="sr-only"` for visually hidden labels.
|
||||||
|
|
||||||
|
**Choosing form controls:**
|
||||||
|
|
||||||
|
- Simple text input → `Input`
|
||||||
|
- Dropdown with predefined options → `Select`
|
||||||
|
- Searchable dropdown → `Combobox`
|
||||||
|
- Native HTML select (no JS) → `native-select`
|
||||||
|
- Boolean toggle → `Switch` (for settings) or `Checkbox` (for forms)
|
||||||
|
- Single choice from few options → `RadioGroup`
|
||||||
|
- Toggle between 2–5 options → `ToggleGroup` + `ToggleGroupItem`
|
||||||
|
- OTP/verification code → `InputOTP`
|
||||||
|
- Multi-line text → `Textarea`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## InputGroup requires InputGroupInput/InputGroupTextarea
|
||||||
|
|
||||||
|
Never use raw `Input` or `Textarea` inside an `InputGroup`.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<InputGroup>
|
||||||
|
<Input placeholder="Search..." />
|
||||||
|
</InputGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { InputGroup, InputGroupInput } from "@/components/ui/input-group"
|
||||||
|
|
||||||
|
<InputGroup>
|
||||||
|
<InputGroupInput placeholder="Search..." />
|
||||||
|
</InputGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Buttons inside inputs use InputGroup + InputGroupAddon
|
||||||
|
|
||||||
|
Never place a `Button` directly inside or adjacent to an `Input` with custom positioning.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className="relative">
|
||||||
|
<Input placeholder="Search..." className="pr-10" />
|
||||||
|
<Button className="absolute right-0 top-0" size="icon">
|
||||||
|
<SearchIcon />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { InputGroup, InputGroupInput, InputGroupAddon } from "@/components/ui/input-group"
|
||||||
|
|
||||||
|
<InputGroup>
|
||||||
|
<InputGroupInput placeholder="Search..." />
|
||||||
|
<InputGroupAddon>
|
||||||
|
<Button size="icon">
|
||||||
|
<SearchIcon data-icon="inline-start" />
|
||||||
|
</Button>
|
||||||
|
</InputGroupAddon>
|
||||||
|
</InputGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Option sets (2–7 choices) use ToggleGroup
|
||||||
|
|
||||||
|
Don't manually loop `Button` components with active state.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const [selected, setSelected] = useState("daily")
|
||||||
|
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{["daily", "weekly", "monthly"].map((option) => (
|
||||||
|
<Button
|
||||||
|
key={option}
|
||||||
|
variant={selected === option ? "default" : "outline"}
|
||||||
|
onClick={() => setSelected(option)}
|
||||||
|
>
|
||||||
|
{option}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
|
||||||
|
|
||||||
|
<ToggleGroup spacing={2}>
|
||||||
|
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="monthly">Monthly</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
Combine with `Field` for labelled toggle groups:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Field orientation="horizontal">
|
||||||
|
<FieldTitle id="theme-label">Theme</FieldTitle>
|
||||||
|
<ToggleGroup aria-labelledby="theme-label" spacing={2}>
|
||||||
|
<ToggleGroupItem value="light">Light</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="dark">Dark</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="system">System</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
</Field>
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Note:** `defaultValue` and `type`/`multiple` props differ between base and radix. See [base-vs-radix.md](./base-vs-radix.md#togglegroup).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## FieldSet + FieldLegend for grouping related fields
|
||||||
|
|
||||||
|
Use `FieldSet` + `FieldLegend` for related checkboxes, radios, or switches — not `div` with a heading:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<FieldSet>
|
||||||
|
<FieldLegend variant="label">Preferences</FieldLegend>
|
||||||
|
<FieldDescription>Select all that apply.</FieldDescription>
|
||||||
|
<FieldGroup className="gap-3">
|
||||||
|
<Field orientation="horizontal">
|
||||||
|
<Checkbox id="dark" />
|
||||||
|
<FieldLabel htmlFor="dark" className="font-normal">Dark mode</FieldLabel>
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
</FieldSet>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Field validation and disabled states
|
||||||
|
|
||||||
|
Both attributes are needed — `data-invalid`/`data-disabled` styles the field (label, description), while `aria-invalid`/`disabled` styles the control.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Invalid.
|
||||||
|
<Field data-invalid>
|
||||||
|
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||||
|
<Input id="email" aria-invalid />
|
||||||
|
<FieldDescription>Invalid email address.</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
// Disabled.
|
||||||
|
<Field data-disabled>
|
||||||
|
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||||
|
<Input id="email" disabled />
|
||||||
|
</Field>
|
||||||
|
```
|
||||||
|
|
||||||
|
Works for all controls: `Input`, `Textarea`, `Select`, `Checkbox`, `RadioGroupItem`, `Switch`, `Slider`, `NativeSelect`, `InputOTP`.
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
# Icons
|
||||||
|
|
||||||
|
**Always use the project's configured `iconLibrary` for imports.** Check the `iconLibrary` field from project context: `lucide` → `lucide-react`, `tabler` → `@tabler/icons-react`, etc. Never assume `lucide-react`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Icons in Button use data-icon attribute
|
||||||
|
|
||||||
|
Add `data-icon="inline-start"` (prefix) or `data-icon="inline-end"` (suffix) to the icon. No sizing classes on the icon.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button>
|
||||||
|
<SearchIcon className="mr-2 size-4" />
|
||||||
|
Search
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button>
|
||||||
|
<SearchIcon data-icon="inline-start"/>
|
||||||
|
Search
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button>
|
||||||
|
Next
|
||||||
|
<ArrowRightIcon data-icon="inline-end"/>
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## No sizing classes on icons inside components
|
||||||
|
|
||||||
|
Components handle icon sizing via CSS. Don't add `size-4`, `w-4 h-4`, or other sizing classes to icons inside `Button`, `DropdownMenuItem`, `Alert`, `Sidebar*`, or other shadcn components. Unless the user explicitly asks for custom icon sizes.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button>
|
||||||
|
<SearchIcon className="size-4" data-icon="inline-start" />
|
||||||
|
Search
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<SettingsIcon className="mr-2 size-4" />
|
||||||
|
Settings
|
||||||
|
</DropdownMenuItem>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button>
|
||||||
|
<SearchIcon data-icon="inline-start" />
|
||||||
|
Search
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<SettingsIcon />
|
||||||
|
Settings
|
||||||
|
</DropdownMenuItem>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pass icons as component objects, not string keys
|
||||||
|
|
||||||
|
Use `icon={CheckIcon}`, not a string key to a lookup map.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const iconMap = {
|
||||||
|
check: CheckIcon,
|
||||||
|
alert: AlertIcon,
|
||||||
|
}
|
||||||
|
|
||||||
|
function StatusBadge({ icon }: { icon: string }) {
|
||||||
|
const Icon = iconMap[icon]
|
||||||
|
return <Icon />
|
||||||
|
}
|
||||||
|
|
||||||
|
<StatusBadge icon="check" />
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Import from the project's configured iconLibrary (e.g. lucide-react, @tabler/icons-react).
|
||||||
|
import { CheckIcon } from "lucide-react"
|
||||||
|
|
||||||
|
function StatusBadge({ icon: Icon }: { icon: React.ComponentType }) {
|
||||||
|
return <Icon />
|
||||||
|
}
|
||||||
|
|
||||||
|
<StatusBadge icon={CheckIcon} />
|
||||||
|
```
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
# Styling & Customization
|
||||||
|
|
||||||
|
See [customization.md](../customization.md) for theming, CSS variables, and adding custom colors.
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- Semantic colors
|
||||||
|
- Built-in variants first
|
||||||
|
- className for layout only
|
||||||
|
- No space-x-* / space-y-*
|
||||||
|
- Prefer size-* over w-* h-* when equal
|
||||||
|
- Prefer truncate shorthand
|
||||||
|
- No manual dark: color overrides
|
||||||
|
- Use cn() for conditional classes
|
||||||
|
- No manual z-index on overlay components
|
||||||
|
- Use shimmer / scroll-fade utilities, not custom animations
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Semantic colors
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className="bg-blue-500 text-white">
|
||||||
|
<p className="text-gray-600">Secondary text</p>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className="bg-primary text-primary-foreground">
|
||||||
|
<p className="text-muted-foreground">Secondary text</p>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## No raw color values for status/state indicators
|
||||||
|
|
||||||
|
For positive, negative, or status indicators, use Badge variants, semantic tokens like `text-destructive`, or define custom CSS variables — don't reach for raw Tailwind colors.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<span className="text-emerald-600">+20.1%</span>
|
||||||
|
<span className="text-green-500">Active</span>
|
||||||
|
<span className="text-red-600">-3.2%</span>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Badge variant="secondary">+20.1%</Badge>
|
||||||
|
<Badge>Active</Badge>
|
||||||
|
<span className="text-destructive">-3.2%</span>
|
||||||
|
```
|
||||||
|
|
||||||
|
If you need a success/positive color that doesn't exist as a semantic token, use a Badge variant or ask the user about adding a custom CSS variable to the theme (see [customization.md](../customization.md)).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Built-in variants first
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button className="border border-input bg-transparent hover:bg-accent">
|
||||||
|
Click me
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button variant="outline">Click me</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## className for layout only
|
||||||
|
|
||||||
|
Use `className` for layout (e.g. `max-w-md`, `mx-auto`, `mt-4`), **not** for overriding component colors or typography. To change colors, use semantic tokens, built-in variants, or CSS variables.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Card className="bg-blue-100 text-blue-900 font-bold">
|
||||||
|
<CardContent>Dashboard</CardContent>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Card className="max-w-md mx-auto">
|
||||||
|
<CardContent>Dashboard</CardContent>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
To customize a component's appearance, prefer these approaches in order:
|
||||||
|
1. **Built-in variants** — `variant="outline"`, `variant="destructive"`, etc.
|
||||||
|
2. **Semantic color tokens** — `bg-primary`, `text-muted-foreground`.
|
||||||
|
3. **CSS variables** — define custom colors in the global CSS file (see [customization.md](../customization.md)).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## No space-x-* / space-y-*
|
||||||
|
|
||||||
|
Use `gap-*` instead. `space-y-4` → `flex flex-col gap-4`. `space-x-2` → `flex gap-2`.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className="flex flex-col gap-4">
|
||||||
|
<Input />
|
||||||
|
<Input />
|
||||||
|
<Button>Submit</Button>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prefer size-* over w-* h-* when equal
|
||||||
|
|
||||||
|
`size-10` not `w-10 h-10`. Applies to icons, avatars, skeletons, etc.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prefer truncate shorthand
|
||||||
|
|
||||||
|
`truncate` not `overflow-hidden text-ellipsis whitespace-nowrap`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## No manual dark: color overrides
|
||||||
|
|
||||||
|
Use semantic tokens — they handle light/dark via CSS variables. `bg-background text-foreground` not `bg-white dark:bg-gray-950`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use cn() for conditional classes
|
||||||
|
|
||||||
|
Use the `cn()` utility from the project for conditional or merged class names. Don't write manual ternaries in className strings.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className={`flex items-center ${isActive ? "bg-primary text-primary-foreground" : "bg-muted"}`}>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
<div className={cn("flex items-center", isActive ? "bg-primary text-primary-foreground" : "bg-muted")}>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## No manual z-index on overlay components
|
||||||
|
|
||||||
|
`Dialog`, `Sheet`, `Drawer`, `AlertDialog`, `DropdownMenu`, `Popover`, `Tooltip`, `HoverCard` handle their own stacking. Never add `z-50` or `z-[999]`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use shimmer / scroll-fade utilities, not custom animations
|
||||||
|
|
||||||
|
For a live "thinking…" or loading-text shimmer, apply the `shimmer` utility. Don't author a custom `@keyframes` or a `bg-clip-text` gradient sweep.
|
||||||
|
|
||||||
|
For scroll-aware edge fading on a scroll container, use `scroll-fade` (and the axis variants `scroll-fade-x` / `scroll-fade-b`). Don't hand-roll mask gradients. The chat components already apply these internally: `Attachment` shimmers its title during upload, and `MessageScrollerViewport` fades its edges.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<span className="animate-pulse bg-gradient-to-r from-muted-foreground/40 via-foreground/70 to-muted-foreground/40 bg-clip-text text-transparent [animation:shimmer_1.6s_infinite]">
|
||||||
|
Thinking…
|
||||||
|
</span>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<span className="shimmer">Thinking…</span>
|
||||||
|
```
|
||||||
+6
-19
@@ -2,32 +2,19 @@
|
|||||||
<classpath>
|
<classpath>
|
||||||
<classpathentry kind="src" path="src"/>
|
<classpathentry kind="src" path="src"/>
|
||||||
<classpathentry kind="lib" path="lib/gson-2.1.jar"/>
|
<classpathentry kind="lib" path="lib/gson-2.1.jar"/>
|
||||||
<classpathentry kind="lib" path="lib/javassist.jar" sourcepath="C:/Users/ADMINI~1/AppData/Local/Temp/1/.org.sf.feeling.decompiler1686963856070/source/javassist-3.29.2-GA-sources.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/ini4j.jar"/>
|
<classpathentry kind="lib" path="lib/ini4j.jar"/>
|
||||||
<classpathentry kind="lib" path="lib/JFreeChart1.5.2.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/toml4j-0.7.1.jar"/>
|
<classpathentry kind="lib" path="lib/toml4j-0.7.1.jar"/>
|
||||||
<classpathentry kind="lib" path="lib/pcap4j-core-1.8.2.jar" sourcepath="C:/Users/ADMINI~1/AppData/Local/Temp/1/.org.sf.feeling.decompiler1725520274095/source/pcap4j-core-1.8.2-sources.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/pcap4j-packetfactory-propertiesbased-1.8.2.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/pcap4j-packetfactory-static-1.8.2.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/pcap4j-sample-1.8.2.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/slf4j-api-2.0.9.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/slf4j-api-2.0.9-javadoc.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/slf4j-api-2.0.9-sources.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/slf4j-api-2.0.9-tests.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/disruptor-4.0.0.jar" sourcepath="lib/disruptor-4.0.0-sources.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/disruptor-4.0.0-javadoc.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/disruptor-4.0.0-sources.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/KNElib1.0.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/KNEOptimize.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/JavaTUN0.3.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/uuid-creator-6.1.1.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/jctools-core-4.0.6.jar"/>
|
<classpathentry kind="lib" path="lib/jctools-core-4.0.6.jar"/>
|
||||||
<classpathentry kind="lib" path="lib/jctools-core-4.0.6-javadoc.jar"/>
|
|
||||||
<classpathentry kind="lib" path="lib/jctools-core-4.0.6-sources.jar"/>
|
<classpathentry kind="lib" path="lib/jctools-core-4.0.6-sources.jar"/>
|
||||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jdk-26.0.1">
|
<classpathentry kind="lib" path="lib/KNElib1.0.jar"/>
|
||||||
|
<classpathentry kind="lib" path="lib/JavaTUN0.3.jar"/>
|
||||||
|
<classpathentry kind="lib" path="lib/KNEOptimize.jar"/>
|
||||||
|
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-25">
|
||||||
<attributes>
|
<attributes>
|
||||||
<attribute name="module" value="true"/>
|
<attribute name="module" value="true"/>
|
||||||
</attributes>
|
</attributes>
|
||||||
</classpathentry>
|
</classpathentry>
|
||||||
|
<classpathentry kind="lib" path="lib/jfreechart-1.5.3.jar"/>
|
||||||
|
<classpathentry kind="lib" path="lib/jfreechart-1.5.3-sources.jar"/>
|
||||||
<classpathentry kind="output" path="bin"/>
|
<classpathentry kind="output" path="bin"/>
|
||||||
</classpath>
|
</classpath>
|
||||||
|
|||||||
+13
@@ -3,3 +3,16 @@
|
|||||||
/klalbs4.json
|
/klalbs4.json
|
||||||
/klalbs.json
|
/klalbs.json
|
||||||
/klalbs2.json
|
/klalbs2.json
|
||||||
|
|
||||||
|
# Dashboard / Frontend
|
||||||
|
dashboard/node_modules/
|
||||||
|
dashboard/dist/
|
||||||
|
dashboard/.pnpm-store/
|
||||||
|
.pnpm-debug.log*
|
||||||
|
dashboard/.env.local
|
||||||
|
dashboard/.env.*.local
|
||||||
|
|
||||||
|
/klalb-config.json
|
||||||
|
/klalbconfig-old.json
|
||||||
|
|
||||||
|
/.slim/
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[submodule "dashboard"]
|
||||||
|
path = dashboard
|
||||||
|
url = https://git.code.cq.cn/SerinaNya/KLALB-dashboard.git
|
||||||
Generated
+38
@@ -0,0 +1,38 @@
|
|||||||
|
<component name="libraryTable">
|
||||||
|
<library name="jfreechart-1.5.3">
|
||||||
|
<CLASSES>
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/jfreechart-1.5.3.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/disruptor-4.0.0.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/gson-2.1.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/ini4j.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/javassist.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/JavaTUN0.3.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/jctools-core-4.0.6.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/KNElib1.0.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/KNEOptimize.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/pcap4j-core-1.8.2.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/pcap4j-packetfactory-propertiesbased-1.8.2.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/pcap4j-packetfactory-static-1.8.2.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/pcap4j-packettest-1.8.2-tests.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/pcap4j-sample-1.8.2.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/slf4j-api-2.0.9.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/slf4j-api-2.0.9-tests.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/toml4j-0.7.1.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/uuid-creator-6.1.1.jar!/" />
|
||||||
|
</CLASSES>
|
||||||
|
<JAVADOC>
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/jctools-core-4.0.6-javadoc.jar!/" />
|
||||||
|
</JAVADOC>
|
||||||
|
<SOURCES>
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/jfreechart-1.5.3-sources.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/disruptor-4.0.0-sources.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/ini4j.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/JavaTUN0.3.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/jctools-core-4.0.6-sources.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/KNElib1.0.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/slf4j-api-2.0.9-sources.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/toml4j-0.7.1.jar!/" />
|
||||||
|
<root url="jar://$PROJECT_DIR$/lib/uuid-creator-6.1.1-sources.jar!/" />
|
||||||
|
</SOURCES>
|
||||||
|
</library>
|
||||||
|
</component>
|
||||||
Generated
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project version="4">
|
<project version="4">
|
||||||
<component name="ProjectRootManager" version="2">
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_26" project-jdk-name="jdk-26.0.1" project-jdk-type="JavaSDK">
|
||||||
<output url="file://$PROJECT_DIR$/classes" />
|
<output url="file://$PROJECT_DIR$/classes" />
|
||||||
</component>
|
</component>
|
||||||
</project>
|
</project>
|
||||||
Generated
+1
@@ -2,5 +2,6 @@
|
|||||||
<project version="4">
|
<project version="4">
|
||||||
<component name="VcsDirectoryMappings">
|
<component name="VcsDirectoryMappings">
|
||||||
<mapping directory="" vcs="Git" />
|
<mapping directory="" vcs="Git" />
|
||||||
|
<mapping directory="$PROJECT_DIR$/dashboard" vcs="Git" />
|
||||||
</component>
|
</component>
|
||||||
</project>
|
</project>
|
||||||
@@ -14,4 +14,15 @@
|
|||||||
<natures>
|
<natures>
|
||||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||||
</natures>
|
</natures>
|
||||||
|
<filteredResources>
|
||||||
|
<filter>
|
||||||
|
<id>1787317094049</id>
|
||||||
|
<name></name>
|
||||||
|
<type>30</type>
|
||||||
|
<matcher>
|
||||||
|
<id>org.eclipse.core.resources.regexFilterMatcher</id>
|
||||||
|
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
|
||||||
|
</matcher>
|
||||||
|
</filter>
|
||||||
|
</filteredResources>
|
||||||
</projectDescription>
|
</projectDescription>
|
||||||
|
|||||||
Vendored
+27
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"type": "java",
|
||||||
|
"name": "KLALBMain (VS Code 自动构建)",
|
||||||
|
"request": "launch",
|
||||||
|
"mainClass": "org.kne.cloud.network.klalb.KLALBMain",
|
||||||
|
"projectName": "KLALB",
|
||||||
|
"cwd": "${workspaceFolder}",
|
||||||
|
"vmArgs": "--enable-native-access=ALL-UNNAMED --add-opens=java.base/jdk.internal.misc=ALL-UNNAMED"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "java",
|
||||||
|
"name": "KLALBMain (直接用 bin 目录)",
|
||||||
|
"request": "launch",
|
||||||
|
"mainClass": "org.kne.cloud.network.klalb.KLALBMain",
|
||||||
|
"cwd": "${workspaceFolder}",
|
||||||
|
"classPaths": [
|
||||||
|
"${workspaceFolder}/bin",
|
||||||
|
"${workspaceFolder}/src",
|
||||||
|
"${workspaceFolder}/lib/*"
|
||||||
|
],
|
||||||
|
"vmArgs": "--enable-native-access=ALL-UNNAMED --add-opens=java.base/jdk.internal.misc=ALL-UNNAMED"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Vendored
+9
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"java.configuration.runtimes": [
|
||||||
|
{
|
||||||
|
"name": "JavaSE-25",
|
||||||
|
"path": "C:\\Program Files\\Zulu\\zulu-25",
|
||||||
|
"default": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
# AGENTS.md
|
||||||
|
|
||||||
|
KLALB ("KLALB Decentralized SRv6 Network") — Java load-balancing/tunnel system that merges multiple WAN links into one virtual IPv6/SRv6 network. Version constant lives in `src/org/kne/cloud/network/klalb/CONST.java`. Protocol specs and manuals are the Chinese `.docx` files in the repo root.
|
||||||
|
|
||||||
|
## Build & run
|
||||||
|
|
||||||
|
No Maven/Gradle. Plain Eclipse/IntelliJ project: dependencies are vendored jars in `lib/`, output goes to `bin/` (gitignored). When adding a jar, update **both** `.classpath` and `KLALB.iml`.
|
||||||
|
|
||||||
|
Compile (`javac` is NOT on PATH — use the full JDK path; `-encoding UTF-8` is mandatory because sources contain Chinese text):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
& "C:\Program Files\Zulu\zulu-25\bin\javac.exe" -encoding UTF-8 -cp "lib/*" -d bin (Get-ChildItem -Recurse src -Filter *.java | ForEach-Object FullName)
|
||||||
|
```
|
||||||
|
|
||||||
|
Warnings about `ThreadTool` varargs / deprecated `finalize` are pre-existing and expected — success = exit code 0. After recompiling, restart the running app (IDE-debugged JVMs keep old classes).
|
||||||
|
|
||||||
|
Run from the repo root — CWD matters:
|
||||||
|
- reads `klalb-config.json` from CWD
|
||||||
|
- loads native libs from CWD: `tuntap4j.dll/.so/.dylib`, `wintun.dll`, `fastcopy.dll` (TUN device support)
|
||||||
|
- classpath must include `src` as well as `bin`: i18n bundles (`/klalb_*.properties`) and images (`/assets/*`) are classpath resources that Eclipse copies to `bin` but manual `javac` does not
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
java --enable-native-access=ALL-UNNAMED "--add-opens=java.base/jdk.internal.misc=ALL-UNNAMED" -cp "bin;src;lib/*" org.kne.cloud.network.klalb.KLALBMain
|
||||||
|
```
|
||||||
|
|
||||||
|
IDE metadata targets JDK 26 (`jdk-26.0.1`); the tree also compiles cleanly on JDK 25. `.classpath` now references the standard container `JavaSE-25` — an execution-environment spec that any JDK ≥25 satisfies, so it works unchanged on JDK 26 machines too (the original named `jdk-26.0.1` VM broke VS Code import on machines without it). `.vscode/settings.json` maps `JavaSE-25` to the locally installed Adoptium JDK; register every installed JDK there when adding another one. Keep compiler compliance ≤25 (`.settings` pins 19) so both JDKs stay usable.
|
||||||
|
|
||||||
|
Runtime gotchas (all verified):
|
||||||
|
- On JDK 25, `KNEOptimize.jar`'s `FastLib` reflects into `jdk.internal.misc.Unsafe`; without the two JVM flags above it throws `InaccessibleObjectException` at startup (app still runs).
|
||||||
|
- Creating the SRv6 TUN adapter (`WintunCreateAdapter`) requires an elevated shell; without admin rights it logs "创建虚拟网卡失败" and continues with only the `inLoopBack` interface — links/bridges still work.
|
||||||
|
- To disable TUN creation completely (e.g. for non-admin UI/routing testing), set `"enableTUN": false` in `klalb-config.json` or toggle off "启用 TUN 虚拟网卡" in GUI/Web settings.
|
||||||
|
- Routing broadcast (`RouterInfo`) transmits `deviceName`, which topology and node overview panels display. `deviceDescription` is NOT broadcast — it only leaves the node in full node-info query responses (see srv6 API below); `ExtraRoutes` remain local controller configs.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
No test suite, no CI. Classes named `*Test*` (`nathole/`, `ntp/`) are manual `main()` harnesses requiring real network peers. Practical check = compile succeeds + app launches.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
- Entrypoint `org.kne.cloud.network.klalb.KLALBMain`: load config → build `KLALBProxySystem` → open Swing GUI (`KLALBStateGUI3`) unless `"nogui": true` → start `KLALBWebServer` (if `"webUI": true` or web server enabled, default port `4665`) → interactive console (`help`, `links-state`, `route`, `kperf`, ...).
|
||||||
|
- `org.kne.cloud.network.klalb.web.KLALBWebServer` — built-in HTTP/SSE server (JDK `HttpServer`):
|
||||||
|
- API endpoints: `/api/status`, `/api/events` (SSE stream, 200ms intervals), `/api/links`, `/api/links/action`, `/api/links/reconnect`, `/api/routing-table`, `/api/nodes` (topology graph), `/api/node-info?address=<ipv6>` (on-demand full node info), `/api/config`.
|
||||||
|
- Static file hosting / SPA fallback: serves `dashboard/dist/` assets directly.
|
||||||
|
- `org.kne.cloud.network` — generic socket framework: `VirtualSocket*` hierarchy, `SocketBridge` port-forwarding proxies, `ProtocolDetector` (multi-protocol mux on one port), `MultiProtocolSocketAddress` = URI-style addresses (`tcp://`, `udp://`, `kltp://`, `ntp://`) dispatched through the `SocketType` registry.
|
||||||
|
- `...network.klalb` — app core: `KLALBController` (the virtual SRv6 network), `KLALBRemoteLink` (WAN lines), `*Packet` wire-format classes, virtual socket implementations.
|
||||||
|
- `...network.congestion` — pluggable congestion control (BBR, Vegas2, DCTCP...), chosen via `"congestionAlgorithm"` in config.
|
||||||
|
- `...network.kltp` — custom reliable transport protocol (packets/streams).
|
||||||
|
- `...network.ipv6`, `...network.srv6` — packet codecs, route table, Dijkstra path computation.
|
||||||
|
- **Node-info query API** (`...network.srv6`, JSON datagrams on `KLALBRoutingProtocol.DEFAULT_PORT=1001`): `KLALBRoutingProtocolAPIServer/Client` speak two request types —
|
||||||
|
- `nodeinfotinyreq/resp` → device name ONLY; never gated by any flag (name is public via broadcast anyway).
|
||||||
|
- `nodeinfofullreq/resp` → externalEndpoints + deviceName + deviceDescription. `denyExternalEndpointQuery=true` hides ONLY the endpoint list (`data=null`); name/description still answer.
|
||||||
|
- GUI rule: opening `NodeInformationPanel` = Full query; use `requestNodeInfoTiny` for lightweight/background lookups. Legacy `openlines*` message types were removed — mixed-version meshes get silence, so upgrade the whole network together.
|
||||||
|
- `JsonDataPacket` stores its UTF-8 payload length in a 2-byte header field: keep every JSON message under 64 KiB.
|
||||||
|
- `...network.frpc` — frp client integration.
|
||||||
|
- `...klalb.ui` — all Swing UI code.
|
||||||
|
|
||||||
|
## Frontend (Dashboard)
|
||||||
|
|
||||||
|
Located in `dashboard/`:
|
||||||
|
- **Git layout**: `dashboard/` is a separate git repo wired in as a submodule (own origin on `git.code.cq.cn`). Commit frontend changes inside `dashboard/` first, then bump the submodule pointer in the parent repo — parent-repo commits alone do not capture them.
|
||||||
|
- **Stack**: Vite + React 19 + TypeScript + Tailwind CSS v4 + `@base-ui/react` (style: `base-nova`, icons: `lucide-react`, toasts: `@base-ui/react/toast`).
|
||||||
|
- **Routing**: Hash-based routing (`#/overview`, `#/connections`, `#/routing-table`, `#/topology`, `#/settings`) for seamless SPA hosting under Java `KLALBWebServer`.
|
||||||
|
- **Package Manager**: `pnpm` (run all commands from `dashboard/` directory).
|
||||||
|
- **Component installation**: **Must** use CLI via `pnpm dlx shadcn@latest add <component>` (e.g. `pnpm dlx shadcn@latest add alert card badge toast`). Never create or fake shadcn components manually. Non-shadcn libs (`@xyflow/react`, `d3-force`) are installed via plain `pnpm add`.
|
||||||
|
- **Commands**:
|
||||||
|
- `pnpm dev` — Start Vite dev server (proxies `/api` to backend `http://127.0.0.1:4665`).
|
||||||
|
- `pnpm build` — Typecheck and build SPA to `dashboard/dist` (which Java `KLALBWebServer` serves directly).
|
||||||
|
- `pnpm lint` / `pnpm typecheck` — Verification.
|
||||||
|
- **Pages & data flow**:
|
||||||
|
- Overview / Connections read the SSE stream (`use-klalb-sse.ts`, 200ms pushes of status + links).
|
||||||
|
- Settings loads/saves `/api/config` (`use-klalb-config.ts`); save payload must keep legacy field aliases alongside new names for compatibility.
|
||||||
|
- Routing table polls `/api/routing-table` every 1s (`use-routing-table.ts`); `cost` is delay-derived and displayed in milliseconds.
|
||||||
|
- Topology polls `/api/nodes` every 1s (`use-topology.ts`) — SSE does NOT carry topology.
|
||||||
|
- Selecting a topology node queries `/api/node-info`; remote node descriptions require a full SRv6 node-info request and can time out after 3s.
|
||||||
|
- Topology layout: `d3-force` headless simulation (recomputed only when node/edge structure changes) rendered by `@xyflow/react` with custom `device-node` / `link-edge` components in `src/components/topology/`.
|
||||||
|
- React hooks lint rule forbids `setState` synchronously inside effects — initialize form state via component `key` remount + lazy `useState(() => ...)` initializers (see `SettingsForm` pattern).
|
||||||
|
|
||||||
|
## Config
|
||||||
|
|
||||||
|
`klalb-config.json` is an array of items discriminated by their `"Type"` field. Adding a new item type requires a `KLALBConfigItem` subclass **plus** new cases in both `KLALBConfigItem.getDefaultJsonDeserializer()` and `getDefaultJsonSerializer()`; unknown types are preserved as `UnknownKLALBConfigItem`. Any Gson instance handling config must register these adapters via `registerToGsonBuilder` (see `KLALBProxySystem`).
|
||||||
|
|
||||||
|
Key controller config fields:
|
||||||
|
- `externalEndpoints` / `autoConnections`: published vs auto-connect endpoint lists (renamed from `openConnections`, which itself replaced legacy `LineTable`; the old name was a developer naming mistake — these addresses are this node's externally published endpoints, not "connections").
|
||||||
|
- `ntpServers`: time server list (replaces `ntpServerTable`).
|
||||||
|
- `denyExternalEndpointQuery` / `denyExternalEndpointBroadcast`: safety flags — the query flag hides ONLY the external-endpoint list in full node-info responses (device name/description still answer; Tiny queries are never gated), the broadcast flag disables LAN multicast discovery (renamed from `denyConnectionQuery` / `denyConnectionBroadcast`, which replaced `denyLineTableQuery` / `denyLineTableBroadcast`).
|
||||||
|
- `enableTUN`: boolean flag for TUN interface creation (`"TUNName"` configures device name).
|
||||||
|
- `webListen`: Web API listen address, normally `http://0.0.0.0:4665`; legacy `webPort` is accepted on load/API input.
|
||||||
|
|
||||||
|
Legacy JSON keys are still accepted on load: `KLALBConfigItem.getDefaultJsonDeserializer()` normalizes old key names (`openConnections`/`LineTable`, `denyConnectionQuery`, `denyLineTable*`, ...) before reflective deserialization (manual rewrite because gson-2.1 has no `@SerializedName(alternate=...)`), and `handleConfig` in the web server accepts them too. New saves always write canonical names.
|
||||||
|
|
||||||
|
Gson quirks:
|
||||||
|
- **gson-2.1 (vendored) is ancient**: its `JSON_ELEMENT` adapter factory only matches exact `JsonElement.class`, NOT subclasses. Calling `gson.toJson(Object)` with a runtime `JsonObject`/`JsonArray` reflectively serializes the internal field as `{"members": {...}}`. `KLALBWebServer.sendJsonResponse` guards against this by using `JsonElement.toString()` for JsonElement instances — keep that guard when adding new response paths. SSE avoids the issue entirely via `JsonObject.toString()`.
|
||||||
|
- `/api/config` GET/POST is parsed field-by-field in `KLALBWebServer.handleConfig` (NOT whole-object Gson reflection) because polymorphic fields (`List<InetAddress>`, `List<MultiProtocolSocketAddress>`) break reflective mapping. Keep new config fields in sync there, accepting both legacy and new JSON key names.
|
||||||
|
- `InetAddress`, `MultiProtocolSocketAddress`, and `KLALBConfigItem` custom adapters are registered on the shared Gson in `KLALBProxySystem`; the web server reuses that instance via `proxySystem.getGson()`.
|
||||||
|
- Saving via web API persists through `KLALBProxySystem.saveConfigToFile()` (GUI save consumer takes precedence when present).
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- Sources are UTF-8; comments, log/UI strings, and commit messages are largely Chinese.
|
||||||
|
- UI strings go through `UIEnv.getRsb().getString(...)`; add keys to **both** `src/klalb_zh_CN.properties` and `src/klalb_en_US.properties`.
|
||||||
|
- `client.cfg`, `server.cfg`, `linetable.txt` at the root are example line-table/port-rule files loaded via the GUI file picker — not hardwired paths.
|
||||||
@@ -249,5 +249,6 @@
|
|||||||
</library>
|
</library>
|
||||||
</orderEntry>
|
</orderEntry>
|
||||||
<orderEntry type="jdk" jdkName="jdk-26.0.1" jdkType="JavaSDK" />
|
<orderEntry type="jdk" jdkName="jdk-26.0.1" jdkType="JavaSDK" />
|
||||||
|
<orderEntry type="library" name="jfreechart-1.5.3" level="project" />
|
||||||
</component>
|
</component>
|
||||||
</module>
|
</module>
|
||||||
Binary file not shown.
-20
@@ -1,20 +0,0 @@
|
|||||||
//加速线路
|
|
||||||
{KLALBRemote}->43.248.189.107:35000
|
|
||||||
{KLALBRemote}->cn-bj-bgp-3.openfrp.top:65529
|
|
||||||
{KLALBRemote}->180.76.147.250:65529
|
|
||||||
{KLALBRemote}->cn-ah-dx-1.natfrp.cloud:65529
|
|
||||||
{KLALBRemote}->cn-nn-dx-1.natfrp.cloud:65529
|
|
||||||
{KLALBRemote}->cn-wh-dx-1.natfrp.cloud:65529
|
|
||||||
{KLALBRemote}->cn-zz-bgp-10.natfrp.cloud:23330
|
|
||||||
{KLALBRemote}->cn-zz-bgp-7.natfrp.cloud:33336
|
|
||||||
{KLALBRemote}->43.143.109.64:49965
|
|
||||||
{KLALBRemote}->frp.104300.xyz:49965
|
|
||||||
{KLALBRemote}->us.afrps.cn:49966
|
|
||||||
{KLALBRemote}->hk.afrps.cn:49966
|
|
||||||
{KLALBRemote}->la.afrps.cn:49966
|
|
||||||
{KLALBRemote}->frp.freefrp.net:49965
|
|
||||||
{KLALBRemote}->frp1.freefrp.net:49965
|
|
||||||
{KLALBRemote}->frp2.freefrp.net:49965
|
|
||||||
{KLALBRemote}->frp4.freefrp.net:49965
|
|
||||||
|
|
||||||
0.0.0.0:25565->{KLALBVirtual}[171d:a999:e697:4b23:ae52:9f29:4532:e1ee]:25565
|
|
||||||
Submodule
+1
Submodule dashboard added at 885a0c2d89
Binary file not shown.
@@ -1,123 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"language": "ZH_CN",
|
|
||||||
"nogui": false,
|
|
||||||
"VirtualAddress": "2486:1:0:0:0:0:0:8888",
|
|
||||||
"VirtualASN": 2142606939373348329,
|
|
||||||
"DNS": [
|
|
||||||
"2486:1:0:0:0:0:0:8888"
|
|
||||||
],
|
|
||||||
"TCPListen": "0.0.0.0:4565",
|
|
||||||
"UDPListen": "{UDP}0.0.0.0:4572",
|
|
||||||
"VirtualSocketName": "KLALB_Stream",
|
|
||||||
"LineTable": [
|
|
||||||
"07f4acdef99b.ofalias.net:4565"
|
|
||||||
],
|
|
||||||
"ConnectLineTable": [
|
|
||||||
"home-ipv6.sliveridc1.cn:4565",
|
|
||||||
"home-ltipv6.sliveridc1.cn:4565",
|
|
||||||
"cn-gd-gz.sliveridc1.cn:4565"
|
|
||||||
],
|
|
||||||
"ntpServerTable": [
|
|
||||||
"{UDP}ntp1.aliyun.com:123",
|
|
||||||
"{UDP}ntp2.aliyun.com:123",
|
|
||||||
"{UDP}ntp3.aliyun.com:123",
|
|
||||||
"{UDP}ntp4.aliyun.com:123",
|
|
||||||
"{UDP}ntp5.aliyun.com:123",
|
|
||||||
"{UDP}ntp6.aliyun.com:123",
|
|
||||||
"{UDP}ntp7.aliyun.com:123",
|
|
||||||
"{UDP}ntp1.tencent.com:123",
|
|
||||||
"{UDP}ntp2.tencent.com:123",
|
|
||||||
"{UDP}ntp3.tencent.com:123",
|
|
||||||
"{UDP}ntp4.tencent.com:123",
|
|
||||||
"{UDP}ntp5.tencent.com:123",
|
|
||||||
"{UDP}time.google.com:123",
|
|
||||||
"{UDP}time.apple.com:123",
|
|
||||||
"{UDP}pool.ntp.org:123",
|
|
||||||
"{UDP}ntp.ntsc.ac.cn:123",
|
|
||||||
"{UDP}us.ntp.org.cn:123"
|
|
||||||
],
|
|
||||||
"denyLineTableQuery": true,
|
|
||||||
"denyLineTableBroadcast": true,
|
|
||||||
"congestionAlgorithm": "BBR",
|
|
||||||
"burstLimit": 1.5,
|
|
||||||
"delayUpperBound": 1.3,
|
|
||||||
"delayLowerBound": 1.3,
|
|
||||||
"nagleDelayTime": 1000000,
|
|
||||||
"linkNagleDelayTime": 0,
|
|
||||||
"linkConnectionsCount": 1,
|
|
||||||
"TUNName": "KLALB_SRv6",
|
|
||||||
"NetworkInterfaceExcepts": [],
|
|
||||||
"Type": "KLALBController"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"Listen": "0.0.0.0:4572",
|
|
||||||
"Bridge": {
|
|
||||||
"KLALB": "SocketBridge",
|
|
||||||
"RDP": "SocketBridge",
|
|
||||||
"HTTP": "SocketBridge",
|
|
||||||
"HTTPS": "SocketBridge",
|
|
||||||
"DEFAULT": "MinecraftSocketBridge23332"
|
|
||||||
},
|
|
||||||
"Connect": {
|
|
||||||
"KLALB": "127.0.0.1:4565",
|
|
||||||
"RDP": "127.0.0.1:3389",
|
|
||||||
"HTTP": "127.0.0.1:5212",
|
|
||||||
"HTTPS": "192.168.1.235:443",
|
|
||||||
"DEFAULT": "127.0.0.1:36555"
|
|
||||||
},
|
|
||||||
"Type": "SocketBridge"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"Listen": "{KLALB_Stream}[::0]:23332",
|
|
||||||
"Bridge": {
|
|
||||||
"DEFAULT": "MinecraftSocketBridge23332"
|
|
||||||
},
|
|
||||||
"Connect": {
|
|
||||||
"DEFAULT": "127.0.0.1:36555"
|
|
||||||
},
|
|
||||||
"Type": "SocketBridge"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"Listen": "{KLALB_Stream}[::0]:23333",
|
|
||||||
"Bridge": {
|
|
||||||
"DEFAULT": "SocketBridge"
|
|
||||||
},
|
|
||||||
"Connect": {
|
|
||||||
"DEFAULT": "127.0.0.1:5212"
|
|
||||||
},
|
|
||||||
"Type": "SocketBridge"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"Listen": "{KLALB_Stream}[::0]:25565",
|
|
||||||
"Bridge": {
|
|
||||||
"DEFAULT": "SocketBridge"
|
|
||||||
},
|
|
||||||
"Connect": {
|
|
||||||
"DEFAULT": "127.0.0.1:25566"
|
|
||||||
},
|
|
||||||
"Type": "SocketBridge"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"Listen": "0.0.0.0:25561",
|
|
||||||
"Bridge": {
|
|
||||||
"KLALB": "SocketBridge",
|
|
||||||
"DEFAULT": "MinecraftSocketBridge23330"
|
|
||||||
},
|
|
||||||
"Connect": {
|
|
||||||
"KLALB": "127.0.0.1:4565",
|
|
||||||
"DEFAULT": "127.0.0.1:25562"
|
|
||||||
},
|
|
||||||
"Type": "SocketBridge"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"Listen": "{KLALB_Stream}[::0]:23330",
|
|
||||||
"Bridge": {
|
|
||||||
"DEFAULT": "MinecraftSocketBridge23330"
|
|
||||||
},
|
|
||||||
"Connect": {
|
|
||||||
"DEFAULT": "127.0.0.1:25562"
|
|
||||||
},
|
|
||||||
"Type": "SocketBridge"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
[
|
|
||||||
{"Type":"KLALBController" ,
|
|
||||||
"TCPListen" : "0.0.0.0:4565",
|
|
||||||
"UDPListen" : "{UDP}0.0.0.0:4572",
|
|
||||||
"VirtualSocketName" : "KLALB_Stream",
|
|
||||||
"LineTable":["43.248.189.107:65529",
|
|
||||||
"cn-bj-bgp-3.openfrp.top:65529",
|
|
||||||
"180.76.147.250:65529",
|
|
||||||
"cn-ah-dx-1.natfrp.cloud:65529",
|
|
||||||
"cn-nn-dx-1.natfrp.cloud:65529",
|
|
||||||
"cn-wh-dx-1.natfrp.cloud:65529",
|
|
||||||
"cn-zz-bgp-10.natfrp.cloud:23330",
|
|
||||||
"cn-zz-bgp-7.natfrp.cloud:33336",
|
|
||||||
"43.143.109.64:49965",
|
|
||||||
"frp.104300.xyz:49965",
|
|
||||||
"us.afrps.cn:49966",
|
|
||||||
"hk.afrps.cn:49966",
|
|
||||||
"la.afrps.cn:49966",
|
|
||||||
"frp.freefrp.net:49965",
|
|
||||||
"frp1.freefrp.net:49965",
|
|
||||||
"frp2.freefrp.net:49965",
|
|
||||||
"frp4.freefrp.net:49965",
|
|
||||||
"cn-he-plc-2.openfrp.top:4572",
|
|
||||||
"{UDP}cn-he-plc-2.openfrp.top:4572",
|
|
||||||
"frp-mom.top:22226",
|
|
||||||
"frp-man.top:36555",
|
|
||||||
"us-sjc-bgp-2.openfrp.top:36555",
|
|
||||||
"us-sjc-bgp-1.openfrp.top:36555",
|
|
||||||
"[240e:340:d856:b700:6d02:6a6a:f9fc:865b]:4572"]
|
|
||||||
},
|
|
||||||
{"Type":"SocketBridge" ,
|
|
||||||
"Listen" : "0.0.0.0:4572",
|
|
||||||
"Bridge":{
|
|
||||||
"KLALB" : "SocketBridge",
|
|
||||||
"RDP":"SocketBridge",
|
|
||||||
"HTTP":"SocketBridge",
|
|
||||||
"HTTPS":"SocketBridge",
|
|
||||||
"DEFAULT":"MinecraftSocketBridge23332"
|
|
||||||
} ,
|
|
||||||
"Connect" : {
|
|
||||||
"KLALB" : "127.0.0.1:4565",
|
|
||||||
"RDP":"127.0.0.1:3389",
|
|
||||||
"HTTP":"127.0.0.1:5212",
|
|
||||||
"HTTPS":"192.168.1.235:443",
|
|
||||||
"DEFAULT":"127.0.0.1:36555"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{"Type":"SocketBridge" ,
|
|
||||||
"Listen" : "{KLALB_Stream}[::0]:23332",
|
|
||||||
"Bridge":"MinecraftSocketBridge23332",
|
|
||||||
"Connect" : "127.0.0.1:36555"
|
|
||||||
},
|
|
||||||
{ "Type":"SocketBridge" ,
|
|
||||||
"Listen" : "{KLALB_Stream}[::0]:23333",
|
|
||||||
"Bridge":"SocketBridge",
|
|
||||||
"Connect" : "127.0.0.1:5212"
|
|
||||||
},
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
{"Type":"SocketBridge" ,
|
|
||||||
"Listen" : "0.0.0.0:25561",
|
|
||||||
"Bridge":{
|
|
||||||
"KLALB" : "SocketBridge",
|
|
||||||
"DEFAULT":"MinecraftSocketBridge23330"
|
|
||||||
} ,
|
|
||||||
"Connect" : {
|
|
||||||
"KLALB" : "127.0.0.1:4565",
|
|
||||||
"DEFAULT":"127.0.0.1:25562"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{"Type":"SocketBridge" ,
|
|
||||||
"Listen" : "{KLALB_Stream}[::0]:23330",
|
|
||||||
"Bridge":"MinecraftSocketBridge23330",
|
|
||||||
"Connect" : "127.0.0.1:25562"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
virtualip=cefe:49b8:f837:4b00:b9cd:dbdd:c299:349
|
|
||||||
bind=0.0.0.0:4569
|
|
||||||
local=127.0.0.1:5212
|
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,29 +0,0 @@
|
|||||||
0.0.0.0:35000(RDP)->192.168.1.233:3389
|
|
||||||
0.0.0.0:35000(HTTPS)->192.168.1.233:8444
|
|
||||||
0.0.0.0:35000(HTTP)->192.168.1.233:5212
|
|
||||||
0.0.0.0:35000(SSH)->192.168.1.236:22
|
|
||||||
0.0.0.0:35000(KLALB)->{KLALBRemote}
|
|
||||||
0.0.0.0:35000->127.0.0.1:35001 //Winds服(普通线路)
|
|
||||||
|
|
||||||
{KLALBVirtual}[::0]:25565->127.0.0.1:35001 //Winds服(加速线路)
|
|
||||||
|
|
||||||
//加速线路
|
|
||||||
{KLALBRemote}->43.248.189.107:35000
|
|
||||||
{KLALBRemote}->cn-bj-bgp-3.openfrp.top:65529
|
|
||||||
{KLALBRemote}->180.76.147.250:65529
|
|
||||||
{KLALBRemote}->cn-ah-dx-1.natfrp.cloud:65529
|
|
||||||
{KLALBRemote}->cn-nn-dx-1.natfrp.cloud:65529
|
|
||||||
{KLALBRemote}->cn-wh-dx-1.natfrp.cloud:65529
|
|
||||||
{KLALBRemote}->cn-zz-bgp-10.natfrp.cloud:23330
|
|
||||||
{KLALBRemote}->cn-zz-bgp-7.natfrp.cloud:33336
|
|
||||||
{KLALBRemote}->43.143.109.64:49965
|
|
||||||
{KLALBRemote}->frp.104300.xyz:49965
|
|
||||||
{KLALBRemote}->us.afrps.cn:49966
|
|
||||||
{KLALBRemote}->hk.afrps.cn:49966
|
|
||||||
{KLALBRemote}->la.afrps.cn:49966
|
|
||||||
{KLALBRemote}->frp.freefrp.net:49965
|
|
||||||
{KLALBRemote}->frp1.freefrp.net:49965
|
|
||||||
{KLALBRemote}->frp2.freefrp.net:49965
|
|
||||||
{KLALBRemote}->frp4.freefrp.net:49965
|
|
||||||
|
|
||||||
0.0.0.0:25565->{KLALBVirtual}[171d:a999:e697:4b23:ae52:9f29:4532:e1ee]:25565
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
43.248.189.107:65529
|
|
||||||
cn-bj-bgp-3.openfrp.top:65529
|
|
||||||
180.76.147.250:65529
|
|
||||||
cn-ah-dx-1.natfrp.cloud:65529
|
|
||||||
cn-nn-dx-1.natfrp.cloud:65529
|
|
||||||
cn-wh-dx-1.natfrp.cloud:65529
|
|
||||||
cn-zz-bgp-10.natfrp.cloud:23330
|
|
||||||
cn-zz-bgp-7.natfrp.cloud:33336
|
|
||||||
43.143.109.64:49965
|
|
||||||
frp.104300.xyz:49965
|
|
||||||
us.afrps.cn:49966
|
|
||||||
hk.afrps.cn:49966
|
|
||||||
la.afrps.cn:49966
|
|
||||||
frp.freefrp.net:49965
|
|
||||||
frp1.freefrp.net:49965
|
|
||||||
frp2.freefrp.net:49965
|
|
||||||
frp4.freefrp.net:49965
|
|
||||||
cn-he-plc-2.openfrp.top:4569
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
0.0.0.0:35000(RDP)->192.168.1.233:3389
|
|
||||||
0.0.0.0:35000(HTTPS)->192.168.1.233:8444
|
|
||||||
0.0.0.0:35000(HTTP)->192.168.1.233:5212
|
|
||||||
0.0.0.0:35000(SSH)->192.168.1.236:22
|
|
||||||
0.0.0.0:35000(KLALB)->{KLALBRemote}
|
|
||||||
0.0.0.0:35000->127.0.0.1:35001 //Winds服(普通线路)
|
|
||||||
|
|
||||||
{KLALBVirtual}[::0]:25565->127.0.0.1:35001 //Winds服(加速线路)
|
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"skills": {
|
||||||
|
"shadcn": {
|
||||||
|
"source": "shadcn/ui",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "skills/shadcn/SKILL.md",
|
||||||
|
"computedHash": "c1a68ee06a668aced9ab2b5fbdea5f989864123794eb2e056b339a072dbb7f10"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,10 @@ networkgraph=Network graph
|
|||||||
language=Language
|
language=Language
|
||||||
basicsettings=Basic settings
|
basicsettings=Basic settings
|
||||||
ipv6addr=IPv6 address
|
ipv6addr=IPv6 address
|
||||||
|
devicename=Device name
|
||||||
|
devicedescription=Device description
|
||||||
dnsserver=DNS server
|
dnsserver=DNS server
|
||||||
|
extraroutes=Extra routes
|
||||||
asnumber=AS number
|
asnumber=AS number
|
||||||
tcplistening=TCP listening
|
tcplistening=TCP listening
|
||||||
udplistening=UDP listening
|
udplistening=UDP listening
|
||||||
@@ -34,6 +37,7 @@ saveconfigsuccess=Save config success
|
|||||||
warning=Warning
|
warning=Warning
|
||||||
invaildipv6addr=IPv6 address:Invaild Input
|
invaildipv6addr=IPv6 address:Invaild Input
|
||||||
invailddnsserver=DNS server:Invaild Input
|
invailddnsserver=DNS server:Invaild Input
|
||||||
|
invaildextraroutes=Extra routes:Invaild Input
|
||||||
invaildasnumber=AS number:Invaild Input
|
invaildasnumber=AS number:Invaild Input
|
||||||
invaildtcplisten=TCP listen:Invaild Input
|
invaildtcplisten=TCP listen:Invaild Input
|
||||||
invaildudplisten=UDP listen:Invaild Input
|
invaildudplisten=UDP listen:Invaild Input
|
||||||
@@ -104,4 +108,18 @@ downloadbasedelay=Download Base
|
|||||||
uploadbasedelay=Upload Base
|
uploadbasedelay=Upload Base
|
||||||
burstlimit=Burst limit
|
burstlimit=Burst limit
|
||||||
performancesettings=Performance settings
|
performancesettings=Performance settings
|
||||||
performancestrategy=Performance strategy
|
performancestrategy=Performance strategy
|
||||||
|
singlecore=Single-Core - Cache Affinity First (Best energy/performance ratio, for low-power & cloud)
|
||||||
|
multifill=Multi-Core - Fill Cores Sequentially (Recommended for general-purpose physical servers)
|
||||||
|
multiscatter=Multi-Core - Spread Load Evenly (Optimized for multi-socket NUMA architectures)
|
||||||
|
webapisettings=Web API settings
|
||||||
|
enablewebapi=Enable Web API
|
||||||
|
weblistenaddr=Web API listen address
|
||||||
|
invaildweblistenaddr=Invalid Web API listen address
|
||||||
|
enabletun=Enable TUN adapter
|
||||||
|
congestionmonitor=Congestion control monitor
|
||||||
|
rttbaseline=RTT baseline
|
||||||
|
rtt=RTT
|
||||||
|
rttmax=RTT max
|
||||||
|
rttmin=RTT min
|
||||||
|
rto=RTO
|
||||||
@@ -3,7 +3,10 @@ networkgraph=网络拓扑图
|
|||||||
language=语言
|
language=语言
|
||||||
basicsettings=基本设置
|
basicsettings=基本设置
|
||||||
ipv6addr=IPv6地址
|
ipv6addr=IPv6地址
|
||||||
|
devicename=设备名称
|
||||||
|
devicedescription=设备描述
|
||||||
dnsserver=DNS服务器
|
dnsserver=DNS服务器
|
||||||
|
extraroutes=额外路由
|
||||||
asnumber=AS号码
|
asnumber=AS号码
|
||||||
tcplistening=TCP监听端口
|
tcplistening=TCP监听端口
|
||||||
udplistening=UDP监听端口
|
udplistening=UDP监听端口
|
||||||
@@ -34,6 +37,7 @@ saveconfigsuccess=保存配置成功
|
|||||||
warning=警告
|
warning=警告
|
||||||
invaildipv6addr=IPv6地址:非法输入
|
invaildipv6addr=IPv6地址:非法输入
|
||||||
invailddnsserver=DNS服务器:非法输入
|
invailddnsserver=DNS服务器:非法输入
|
||||||
|
invaildextraroutes=额外路由:非法输入
|
||||||
invaildasnumber=AS号码:非法输入
|
invaildasnumber=AS号码:非法输入
|
||||||
invaildtcplisten=TCP监听端口:非法输入
|
invaildtcplisten=TCP监听端口:非法输入
|
||||||
invaildudplisten=UDP监听端口:非法输入
|
invaildudplisten=UDP监听端口:非法输入
|
||||||
@@ -104,4 +108,18 @@ downloadbasedelay=下载延迟基线
|
|||||||
uploadbasedelay=上传延迟基线
|
uploadbasedelay=上传延迟基线
|
||||||
burstlimit=突发限制
|
burstlimit=突发限制
|
||||||
performancesettings=性能设置
|
performancesettings=性能设置
|
||||||
performancestrategy=性能策略
|
performancestrategy=性能策略
|
||||||
|
singlecore=单核-缓存命中率优先(高能耗比,适合低功耗设备、云机)
|
||||||
|
multifill=多核-负载按顺序填充(适合大多数物理服务器、电脑)
|
||||||
|
multiscatter=多核-负载均匀打散分配(适合特殊的多路NUMA服务器)
|
||||||
|
webapisettings=Web API 设置
|
||||||
|
enablewebapi=启用 Web API
|
||||||
|
weblistenaddr=Web API 监听地址:端口
|
||||||
|
invaildweblistenaddr=无效的 Web API 监听地址:端口
|
||||||
|
enabletun=启用TUN虚拟网卡
|
||||||
|
congestionmonitor=拥塞控制监视器
|
||||||
|
rttbaseline=往返延迟基线
|
||||||
|
rtt=往返延迟
|
||||||
|
rttmax=往返延迟上限
|
||||||
|
rttmin=往返延迟下限
|
||||||
|
rto=重传超时
|
||||||
@@ -5,6 +5,9 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
import org.kne.math.Long128;
|
import org.kne.math.Long128;
|
||||||
|
|
||||||
@@ -256,4 +259,27 @@ public class NTPTimestamps {
|
|||||||
.setBit(63);
|
.setBit(63);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static Long128 median(List<Long128> values) {
|
||||||
|
Objects.requireNonNull(values);
|
||||||
|
if ( values.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("列表不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. 创建副本并排序
|
||||||
|
List<Long128> sorted = new ArrayList<>(values);
|
||||||
|
sorted.sort(Long128::compareTo);
|
||||||
|
|
||||||
|
// 2. 计算中位数
|
||||||
|
int size = sorted.size();
|
||||||
|
if (size % 2 == 1) {
|
||||||
|
// 奇数个:取中间值
|
||||||
|
return sorted.get(size / 2);
|
||||||
|
} else {
|
||||||
|
// 偶数个:取中间两个的平均值
|
||||||
|
Long128 left = sorted.get(size / 2 - 1);
|
||||||
|
Long128 right = sorted.get(size / 2);
|
||||||
|
return left.add(right).divide(Long128.valueOf(2));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
package org.kne.cloud.network;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.DatagramSocket;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.net.NetworkInterface;
|
||||||
|
import java.net.SocketAddress;
|
||||||
|
import java.net.SocketOption;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.ClosedChannelException;
|
||||||
|
import java.nio.channels.DatagramChannel;
|
||||||
|
import java.nio.channels.MembershipKey;
|
||||||
|
import java.nio.channels.SelectableChannel;
|
||||||
|
import java.nio.channels.SelectionKey;
|
||||||
|
import java.nio.channels.Selector;
|
||||||
|
import java.nio.channels.spi.SelectorProvider;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自制的 UDP AIO 通道,内部使用线程池模拟异步收包。
|
||||||
|
* 用户只需设置回调,无需自己管理线程。
|
||||||
|
*
|
||||||
|
* 完整委托了 DatagramChannel 的所有公共方法。
|
||||||
|
*/
|
||||||
|
public class AsynchronousDatagramChannel implements AutoCloseable {
|
||||||
|
|
||||||
|
private final DatagramChannel delegate;
|
||||||
|
private final ExecutorService workerPool;
|
||||||
|
private final AtomicBoolean running = new AtomicBoolean(true);
|
||||||
|
private volatile ReceiveHandler handler;
|
||||||
|
private final int bufferSize;
|
||||||
|
private int threadCount;
|
||||||
|
|
||||||
|
// ==================== 回调接口 ====================
|
||||||
|
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface ReceiveHandler {
|
||||||
|
void onReceive(SocketAddress from, ByteBuffer data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 构造方法 ====================
|
||||||
|
|
||||||
|
public AsynchronousDatagramChannel() throws IOException {
|
||||||
|
this(65535, Runtime.getRuntime().availableProcessors());
|
||||||
|
}
|
||||||
|
|
||||||
|
public AsynchronousDatagramChannel(int bufferSize, int threadCount) throws IOException {
|
||||||
|
this.bufferSize = bufferSize;
|
||||||
|
this.delegate = DatagramChannel.open();
|
||||||
|
delegate.configureBlocking(true);
|
||||||
|
this.threadCount=threadCount;
|
||||||
|
this.workerPool = Executors.newFixedThreadPool(threadCount, r -> {
|
||||||
|
Thread t = new Thread(r, "AsyncDatagramReader");
|
||||||
|
t.setDaemon(true);
|
||||||
|
return t;
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void startWorkers() {
|
||||||
|
|
||||||
|
for (int i = 0; i < threadCount; i++) {
|
||||||
|
workerPool.submit(this::readerLoop);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 核心方法 ====================
|
||||||
|
|
||||||
|
public void setReceiveHandler(ReceiveHandler handler) {
|
||||||
|
this.handler = handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void readerLoop() {
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
|
||||||
|
while (running.get()) {
|
||||||
|
try {
|
||||||
|
buffer.clear();
|
||||||
|
SocketAddress from = delegate.receive(buffer);
|
||||||
|
if (from == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
buffer.flip();
|
||||||
|
ReceiveHandler localHandler = handler;
|
||||||
|
if (localHandler != null) {
|
||||||
|
localHandler.onReceive(from, buffer);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
if (running.get()) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int send(ByteBuffer data, SocketAddress target) throws IOException {
|
||||||
|
return delegate.send(data, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== DatagramChannel 委托方法 ====================
|
||||||
|
|
||||||
|
// --- 连接相关 ---
|
||||||
|
|
||||||
|
public DatagramChannel connect(SocketAddress remote) throws IOException {
|
||||||
|
return delegate.connect(remote);
|
||||||
|
}
|
||||||
|
|
||||||
|
public DatagramChannel disconnect() throws IOException {
|
||||||
|
return delegate.disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isConnected() {
|
||||||
|
return delegate.isConnected();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 绑定相关 ---
|
||||||
|
|
||||||
|
public DatagramChannel bind(SocketAddress local) throws IOException {
|
||||||
|
return delegate.bind(local);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SocketAddress getLocalAddress() throws IOException {
|
||||||
|
return delegate.getLocalAddress();
|
||||||
|
}
|
||||||
|
|
||||||
|
public SocketAddress getRemoteAddress() throws IOException {
|
||||||
|
return delegate.getRemoteAddress();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 读写相关 ---
|
||||||
|
|
||||||
|
public int read(ByteBuffer dst) throws IOException {
|
||||||
|
return delegate.read(dst);
|
||||||
|
}
|
||||||
|
|
||||||
|
public long read(ByteBuffer[] dsts) throws IOException {
|
||||||
|
return delegate.read(dsts);
|
||||||
|
}
|
||||||
|
|
||||||
|
public long read(ByteBuffer[] dsts, int offset, int length) throws IOException {
|
||||||
|
return delegate.read(dsts, offset, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int write(ByteBuffer src) throws IOException {
|
||||||
|
return delegate.write(src);
|
||||||
|
}
|
||||||
|
|
||||||
|
public long write(ByteBuffer[] srcs) throws IOException {
|
||||||
|
return delegate.write(srcs);
|
||||||
|
}
|
||||||
|
|
||||||
|
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
|
||||||
|
return delegate.write(srcs, offset, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 接收相关 ---
|
||||||
|
|
||||||
|
public SocketAddress receive(ByteBuffer dst) throws IOException {
|
||||||
|
return delegate.receive(dst);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 多播 (Multicast) ---
|
||||||
|
|
||||||
|
public MembershipKey join(InetAddress group, NetworkInterface interf) throws IOException {
|
||||||
|
return delegate.join(group, interf);
|
||||||
|
}
|
||||||
|
|
||||||
|
public MembershipKey join(InetAddress group, NetworkInterface interf, InetAddress source) throws IOException {
|
||||||
|
return delegate.join(group, interf, source);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 选项相关 ---
|
||||||
|
|
||||||
|
public <T> DatagramChannel setOption(SocketOption<T> name, T value) throws IOException {
|
||||||
|
return delegate.setOption(name, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> T getOption(SocketOption<T> name) throws IOException {
|
||||||
|
return delegate.getOption(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<SocketOption<?>> supportedOptions() {
|
||||||
|
return delegate.supportedOptions();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 阻塞模式 ---
|
||||||
|
|
||||||
|
|
||||||
|
public boolean isBlocking() {
|
||||||
|
return delegate.isBlocking();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 选择器相关 ---
|
||||||
|
|
||||||
|
public SelectableChannel configureBlocking(boolean block) throws IOException {
|
||||||
|
return delegate.configureBlocking(block);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SelectorProvider provider() {
|
||||||
|
return delegate.provider();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int validOps() {
|
||||||
|
return delegate.validOps();
|
||||||
|
}
|
||||||
|
|
||||||
|
public SelectionKey keyFor(Selector sel) {
|
||||||
|
return delegate.keyFor(sel);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SelectionKey register(Selector sel, int ops) throws ClosedChannelException {
|
||||||
|
return delegate.register(sel, ops);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SelectionKey register(Selector sel, int ops, Object att) throws ClosedChannelException {
|
||||||
|
return delegate.register(sel, ops, att);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 状态查询 ---
|
||||||
|
|
||||||
|
public boolean isOpen() {
|
||||||
|
return delegate.isOpen() && running.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public DatagramSocket socket() {
|
||||||
|
return delegate.socket();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 关闭方法 ====================
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() throws Exception {
|
||||||
|
running.set(false);
|
||||||
|
workerPool.shutdownNow();
|
||||||
|
delegate.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 静态工厂方法 ====================
|
||||||
|
|
||||||
|
public static AsynchronousDatagramChannel open() throws IOException {
|
||||||
|
return new AsynchronousDatagramChannel();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AsynchronousDatagramChannel open(int bufferSize) throws IOException {
|
||||||
|
return new AsynchronousDatagramChannel(bufferSize, Runtime.getRuntime().availableProcessors());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AsynchronousDatagramChannel open(int bufferSize, int threadCount) throws IOException {
|
||||||
|
return new AsynchronousDatagramChannel(bufferSize, threadCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 测试示例 ====================
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
int port = 4567;
|
||||||
|
AsynchronousDatagramChannel channel = AsynchronousDatagramChannel.open();
|
||||||
|
channel.bind(new InetSocketAddress(port));
|
||||||
|
|
||||||
|
channel.setReceiveHandler((from, data) -> {
|
||||||
|
byte[] bytes = new byte[data.remaining()];
|
||||||
|
data.get(bytes);
|
||||||
|
String msg = new String(bytes);
|
||||||
|
System.out.println("Received from " + from + ": " + msg);
|
||||||
|
});
|
||||||
|
|
||||||
|
System.out.println("Echo server running on port " + port);
|
||||||
|
System.out.println("Press Enter to stop...");
|
||||||
|
System.in.read();
|
||||||
|
|
||||||
|
channel.close();
|
||||||
|
System.out.println("Server stopped.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,14 +3,9 @@ package org.kne.cloud.network;
|
|||||||
import java.io.Closeable;
|
import java.io.Closeable;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.DatagramSocket;
|
import java.net.DatagramSocket;
|
||||||
import java.net.InetAddress;
|
|
||||||
import java.net.ServerSocket;
|
|
||||||
import java.net.Socket;
|
|
||||||
import java.net.SocketException;
|
import java.net.SocketException;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
import javax.net.ServerSocketFactory;
|
|
||||||
|
|
||||||
public class DatagramSocketListener implements Closeable,AutoCloseable{
|
public class DatagramSocketListener implements Closeable,AutoCloseable{
|
||||||
private DatagramServerSocket serverSocket;
|
private DatagramServerSocket serverSocket;
|
||||||
public DatagramServerSocket getDatagramServerSocket() {
|
public DatagramServerSocket getDatagramServerSocket() {
|
||||||
@@ -36,10 +31,10 @@ public class DatagramSocketListener implements Closeable,AutoCloseable{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
private MultipurposeSocketAddress multipurposeSocketAddress;
|
private MultiProtocolSocketAddress multiProtocolSocketAddress;
|
||||||
|
|
||||||
public DatagramSocketListener(MultipurposeSocketAddress multipurposeSocketAddress) throws IOException {
|
public DatagramSocketListener(MultiProtocolSocketAddress multiProtocolSocketAddress) throws IOException {
|
||||||
this.multipurposeSocketAddress=multipurposeSocketAddress;
|
this.multiProtocolSocketAddress = multiProtocolSocketAddress;
|
||||||
open();
|
open();
|
||||||
}
|
}
|
||||||
public DatagramSocketListener(DatagramServerSocket tserverSocket) throws IOException {
|
public DatagramSocketListener(DatagramServerSocket tserverSocket) throws IOException {
|
||||||
@@ -49,7 +44,7 @@ public class DatagramSocketListener implements Closeable,AutoCloseable{
|
|||||||
|
|
||||||
private void open() throws IOException {
|
private void open() throws IOException {
|
||||||
if(serverSocket==null)
|
if(serverSocket==null)
|
||||||
serverSocket=multipurposeSocketAddress.listenDatagramServerSocket();
|
serverSocket= multiProtocolSocketAddress.listenDatagramServerSocket();
|
||||||
//new Thread(r).start();
|
//new Thread(r).start();
|
||||||
ThreadTool.makePThreadIfSupport("端口监听线程",r).start();
|
ThreadTool.makePThreadIfSupport("端口监听线程",r).start();
|
||||||
}
|
}
|
||||||
@@ -63,8 +58,8 @@ public class DatagramSocketListener implements Closeable,AutoCloseable{
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
public MultipurposeSocketAddress getMultipurposeSocketAddress() {
|
public MultiProtocolSocketAddress getMultipurposeSocketAddress() {
|
||||||
return multipurposeSocketAddress;
|
return multiProtocolSocketAddress;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Consumer<DatagramSocket> getCon() {
|
public Consumer<DatagramSocket> getCon() {
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
package org.kne.cloud.network;
|
package org.kne.cloud.network;
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
|
|
||||||
public class HostPortMap extends LinkedHashMap<String, MultipurposeSocketAddress> {
|
public class HostPortMap extends LinkedHashMap<String, MultiProtocolSocketAddress> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
@@ -11,9 +10,9 @@ public class HostPortMap extends LinkedHashMap<String, MultipurposeSocketAddress
|
|||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
|
||||||
public MultipurposeSocketAddress putN$H(String str) {
|
public MultiProtocolSocketAddress putN$H(String str) {
|
||||||
String[] strx=str.split("\\$");
|
String[] strx=str.split("\\$");
|
||||||
return super.put(strx[0], new MultipurposeSocketAddress( strx[1]));
|
return super.put(strx[0], new MultiProtocolSocketAddress( strx[1]));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,16 +7,8 @@ import java.io.DataInputStream;
|
|||||||
import java.io.DataOutputStream;
|
import java.io.DataOutputStream;
|
||||||
import java.io.EOFException;
|
import java.io.EOFException;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.DatagramPacket;
|
import java.net.*;
|
||||||
import java.net.InetAddress;
|
|
||||||
import java.net.InetSocketAddress;
|
|
||||||
import java.net.MulticastSocket;
|
|
||||||
import java.net.NetworkInterface;
|
|
||||||
import java.net.NoRouteToHostException;
|
|
||||||
import java.net.SocketException;
|
|
||||||
import java.net.UnknownHostException;
|
|
||||||
import java.util.Enumeration;
|
import java.util.Enumeration;
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
@@ -29,12 +21,11 @@ public class IPMulticastDiscovery implements Closeable, AutoCloseable {
|
|||||||
private NetworkInterface ninterface;
|
private NetworkInterface ninterface;
|
||||||
private volatile boolean closed = false;
|
private volatile boolean closed = false;
|
||||||
private InetSocketAddress group;
|
private InetSocketAddress group;
|
||||||
private InetSocketAddress bind;
|
|
||||||
private int type;
|
private int type;
|
||||||
private List<MultipurposeSocketAddress> msas;
|
private List<MultiProtocolSocketAddress> msas;
|
||||||
private UUID selfUUID;
|
private UUID selfUUID;
|
||||||
|
|
||||||
private volatile Consumer<MultipurposeSocketAddress> con;
|
private volatile Consumer<MultiProtocolSocketAddress> con;
|
||||||
private long timeInterval;
|
private long timeInterval;
|
||||||
|
|
||||||
public long getTimeInterval() {
|
public long getTimeInterval() {
|
||||||
@@ -45,7 +36,7 @@ public class IPMulticastDiscovery implements Closeable, AutoCloseable {
|
|||||||
this.timeInterval = timeInterval;
|
this.timeInterval = timeInterval;
|
||||||
}
|
}
|
||||||
|
|
||||||
public NetworkInterface getNinterface() {
|
public NetworkInterface getInterface() {
|
||||||
return ninterface;
|
return ninterface;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,22 +45,24 @@ public class IPMulticastDiscovery implements Closeable, AutoCloseable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public InetSocketAddress getBind() {
|
public InetSocketAddress getBind() {
|
||||||
return bind;
|
return (InetSocketAddress) soc.getLocalSocketAddress();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Consumer<MultipurposeSocketAddress> getCon() {
|
public Consumer<MultiProtocolSocketAddress> getCon() {
|
||||||
return con;
|
return con;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCon(Consumer<MultipurposeSocketAddress> con) {
|
public void setCon(Consumer<MultiProtocolSocketAddress> con) {
|
||||||
this.con = con;
|
this.con = con;
|
||||||
}
|
}
|
||||||
|
|
||||||
public IPMulticastDiscovery(InetSocketAddress bind, InetSocketAddress group, NetworkInterface ninterface,
|
public IPMulticastDiscovery(InetSocketAddress bind, InetSocketAddress group, NetworkInterface ninterface,
|
||||||
List<MultipurposeSocketAddress> msas,UUID node,long timeInterval) throws IOException {
|
List<MultiProtocolSocketAddress> msas, UUID node, long timeInterval) throws IOException {
|
||||||
soc = new MulticastSocket(bind);
|
soc = new MulticastSocket(null);
|
||||||
|
soc.setReuseAddress(true);
|
||||||
|
soc.bind(bind);
|
||||||
|
soc.setNetworkInterface(ninterface);
|
||||||
soc.joinGroup(group, ninterface);
|
soc.joinGroup(group, ninterface);
|
||||||
this.bind = bind;
|
|
||||||
this.group = group;
|
this.group = group;
|
||||||
this.ninterface = ninterface;
|
this.ninterface = ninterface;
|
||||||
this.msas = msas;
|
this.msas = msas;
|
||||||
@@ -82,46 +75,22 @@ public class IPMulticastDiscovery implements Closeable, AutoCloseable {
|
|||||||
ThreadTool.makeVDaemonThreadIfSupport("线路通知线程", () -> {
|
ThreadTool.makeVDaemonThreadIfSupport("线路通知线程", () -> {
|
||||||
try {
|
try {
|
||||||
while (!closed) {
|
while (!closed) {
|
||||||
HashSet<MultipurposeSocketAddress> s = new HashSet<MultipurposeSocketAddress>();
|
/*MultipurposeSocketAddress mpsa = new MultipurposeSocketAddress(
|
||||||
synchronized (msas) {
|
multipurposeSocketAddress.getType(), "::0", multipurposeSocketAddress.getPort());*/
|
||||||
for (Iterator<MultipurposeSocketAddress> iterator = msas.iterator(); iterator.hasNext();) {
|
if(msas!=null) {
|
||||||
MultipurposeSocketAddress multipurposeSocketAddress = (MultipurposeSocketAddress) iterator
|
synchronized (msas) {
|
||||||
.next();
|
for (Iterator<MultiProtocolSocketAddress> iterator = msas.iterator(); iterator.hasNext(); ) {
|
||||||
|
MultiProtocolSocketAddress multiProtocolSocketAddress = (MultiProtocolSocketAddress) iterator
|
||||||
|
.next();
|
||||||
|
|
||||||
MultipurposeSocketAddress mpsa = new MultipurposeSocketAddress(
|
try {
|
||||||
multipurposeSocketAddress.getType(), "::0", multipurposeSocketAddress.getPort());
|
send(multiProtocolSocketAddress);
|
||||||
try {
|
} catch (NoRouteToHostException | UnknownHostException e) {
|
||||||
if (s.add(mpsa)) {
|
|
||||||
boolean bf = true;
|
|
||||||
Enumeration<InetAddress> ei = ninterface.getInetAddresses();
|
|
||||||
while (ei.hasMoreElements()) {
|
|
||||||
InetAddress inetAddress = (InetAddress) ei.nextElement();
|
|
||||||
if (inetAddress.equals(multipurposeSocketAddress.getInetAddress())) {
|
|
||||||
bf = false;
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if (bf) {
|
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
|
||||||
DataOutputStream dops = new DataOutputStream(baos);
|
|
||||||
dops.writeInt(multipurposeSocketAddress.getPort());
|
|
||||||
dops.writeUTF(multipurposeSocketAddress.getType());
|
|
||||||
dops.writeLong(selfUUID.getMostSignificantBits());
|
|
||||||
dops.writeLong(selfUUID.getLeastSignificantBits());
|
|
||||||
dops.close();
|
|
||||||
byte[] b = baos.toByteArray();
|
|
||||||
DatagramPacket dp = new DatagramPacket(b, b.length, group);
|
|
||||||
soc.send(dp);
|
|
||||||
if(debug)
|
|
||||||
System.out.println("发送广播:"+multipurposeSocketAddress+" "+group+" "+selfUUID);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (NoRouteToHostException|UnknownHostException e) {
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Thread.sleep(timeInterval);
|
Thread.sleep(timeInterval);
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
@@ -143,28 +112,9 @@ public class IPMulticastDiscovery implements Closeable, AutoCloseable {
|
|||||||
try {
|
try {
|
||||||
loop:while (!closed) {
|
loop:while (!closed) {
|
||||||
try {
|
try {
|
||||||
byte[] b = new byte[65535];
|
MultiProtocolSocketAddress mpsa = receive();
|
||||||
DatagramPacket dp = new DatagramPacket(b, b.length);
|
if (mpsa == null) continue;
|
||||||
soc.receive(dp);
|
InetAddress mpsai=mpsa.getInetAddress();
|
||||||
ByteArrayInputStream bis = new ByteArrayInputStream(b, 0, dp.getLength());
|
|
||||||
DataInputStream dis = new DataInputStream(bis);
|
|
||||||
int port = dis.readInt();
|
|
||||||
String type = dis.readUTF();
|
|
||||||
long h=dis.readLong();
|
|
||||||
long l=dis.readLong();
|
|
||||||
UUID uid=new UUID(h, l);
|
|
||||||
dis.close();
|
|
||||||
MultipurposeSocketAddress mpsa = new MultipurposeSocketAddress(type, dp.getAddress().getHostAddress(),
|
|
||||||
port);
|
|
||||||
if(debug) {
|
|
||||||
if(uid.equals(selfUUID)) {
|
|
||||||
System.out.println("丢弃广播:"+mpsa+" "+dp.getSocketAddress()+" "+uid);
|
|
||||||
continue;
|
|
||||||
}else {
|
|
||||||
System.out.println("接收广播:"+mpsa+" "+dp.getSocketAddress()+" "+uid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
InetAddress mpsai=mpsa.getInetAddress();
|
|
||||||
Enumeration<InetAddress> ei = ninterface.getInetAddresses();
|
Enumeration<InetAddress> ei = ninterface.getInetAddresses();
|
||||||
while (ei.hasMoreElements()) {
|
while (ei.hasMoreElements()) {
|
||||||
InetAddress inetAddress = (InetAddress) ei.nextElement();
|
InetAddress inetAddress = (InetAddress) ei.nextElement();
|
||||||
@@ -186,7 +136,7 @@ public class IPMulticastDiscovery implements Closeable, AutoCloseable {
|
|||||||
if(!isClosed())
|
if(!isClosed())
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}catch (IOException e) {
|
}catch (IOException e) {
|
||||||
System.out.println(bind + " " + group + " " + ninterface);
|
System.out.println(getBind() + " " + group + " " + ninterface);
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
@@ -196,7 +146,48 @@ public class IPMulticastDiscovery implements Closeable, AutoCloseable {
|
|||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
}).start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private MultiProtocolSocketAddress receive() throws IOException {
|
||||||
|
byte[] b = new byte[65535];
|
||||||
|
DatagramPacket dp = new DatagramPacket(b, b.length);
|
||||||
|
soc.receive(dp);
|
||||||
|
ByteArrayInputStream bis = new ByteArrayInputStream(b, 0, dp.getLength());
|
||||||
|
DataInputStream dis = new DataInputStream(bis);
|
||||||
|
String val = dis.readUTF();
|
||||||
|
long h=dis.readLong();
|
||||||
|
long l=dis.readLong();
|
||||||
|
UUID uid=new UUID(h, l);
|
||||||
|
dis.close();
|
||||||
|
MultiProtocolSocketAddress mpsa = new MultiProtocolSocketAddress(val);
|
||||||
|
if(mpsa.getInetAddress().isAnyLocalAddress()){
|
||||||
|
mpsa=new MultiProtocolSocketAddress(mpsa.getProtocol(),dp.getAddress().getHostAddress(),mpsa.getPort());
|
||||||
|
}
|
||||||
|
if(debug) {
|
||||||
|
if(uid.equals(selfUUID)) {
|
||||||
|
System.out.println(ninterface.getDisplayName()+" 丢弃广播:"+mpsa+" "+dp.getSocketAddress()+" "+uid);
|
||||||
|
return null;
|
||||||
|
}else {
|
||||||
|
System.out.println(ninterface.getDisplayName()+ " 接收广播:"+mpsa+" "+dp.getSocketAddress()+" "+uid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return mpsa;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void send(MultiProtocolSocketAddress multiProtocolSocketAddress) throws IOException {
|
||||||
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
|
DataOutputStream dops = new DataOutputStream(baos);
|
||||||
|
dops.writeUTF(multiProtocolSocketAddress.toString());
|
||||||
|
dops.writeLong(selfUUID.getMostSignificantBits());
|
||||||
|
dops.writeLong(selfUUID.getLeastSignificantBits());
|
||||||
|
dops.close();
|
||||||
|
byte[] b = baos.toByteArray();
|
||||||
|
DatagramPacket dp = new DatagramPacket(b, b.length, group);
|
||||||
|
soc.send(dp);
|
||||||
|
if(debug)
|
||||||
|
System.out.println(ninterface.getDisplayName()+" 发送广播:"+ multiProtocolSocketAddress +" "+group+" "+selfUUID);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+477
-471
@@ -1,471 +1,477 @@
|
|||||||
package org.kne.cloud.network;
|
package org.kne.cloud.network;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.net.DatagramSocket;
|
import java.net.*;
|
||||||
import java.net.Inet6Address;
|
import java.nio.channels.ServerSocketChannel;
|
||||||
import java.net.InetAddress;
|
import java.nio.channels.SocketChannel;
|
||||||
import java.net.InetSocketAddress;
|
import java.util.*;
|
||||||
import java.net.ServerSocket;
|
|
||||||
import java.net.Socket;
|
import javax.net.ServerSocketFactory;
|
||||||
import java.net.SocketAddress;
|
import javax.net.SocketFactory;
|
||||||
import java.net.UnknownHostException;
|
|
||||||
import java.nio.channels.ServerSocketChannel;
|
import com.google.gson.GsonBuilder;
|
||||||
import java.nio.channels.SocketChannel;
|
import com.google.gson.JsonDeserializationContext;
|
||||||
import java.util.*;
|
import com.google.gson.JsonDeserializer;
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
import javax.net.ServerSocketFactory;
|
import com.google.gson.JsonParseException;
|
||||||
import javax.net.SocketFactory;
|
import com.google.gson.JsonPrimitive;
|
||||||
|
import com.google.gson.JsonSerializationContext;
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.JsonSerializer;
|
||||||
import com.google.gson.GsonBuilder;
|
import org.kne.cloud.network.ntp.NTPSocketType;
|
||||||
import com.google.gson.JsonDeserializationContext;
|
|
||||||
import com.google.gson.JsonDeserializer;
|
public class MultiProtocolSocketAddress implements Serializable{
|
||||||
import com.google.gson.JsonElement;
|
/**
|
||||||
import com.google.gson.JsonParseException;
|
*
|
||||||
import com.google.gson.JsonPrimitive;
|
*/
|
||||||
import com.google.gson.JsonSerializationContext;
|
private static final Map<String,SocketType> socketTypeRegister=new HashMap<>();
|
||||||
import com.google.gson.JsonSerializer;
|
|
||||||
|
static {
|
||||||
public class MultipurposeSocketAddress implements Serializable{
|
socketTypeRegister.put("tcp", TCPSocketType.getInstance());
|
||||||
/**
|
socketTypeRegister.put("udp", UDPSocketType.getInstance());
|
||||||
*
|
socketTypeRegister.put("ntp", NTPSocketType.getInstance());
|
||||||
*/
|
}
|
||||||
private static final Map<String,SocketType> socketTypeRegister=new HashMap<>();
|
|
||||||
|
|
||||||
|
|
||||||
static {
|
public static Map<String, SocketType> getSocketTypeRegister() {
|
||||||
socketTypeRegister.put("TCP", new SocketType(new DefaultSocketFactory(), new DefaultServerSocketFactory(),new DefaultSocketChannelFactory(),new DefaultServerSocketChannelFactory()));
|
return socketTypeRegister;
|
||||||
socketTypeRegister.put("UDP", new SocketType(new DefaultDatagramSocketFactory(),new DefaultDatagramServerSocketFactory()));
|
}
|
||||||
}
|
private static final long serialVersionUID = 1L;
|
||||||
|
private String protocol;
|
||||||
|
private String host;
|
||||||
|
private ProtocolStack ps=new ProtocolStack();
|
||||||
public static Map<String, SocketType> getSocketTypeRegister() {
|
|
||||||
return socketTypeRegister;
|
|
||||||
}
|
private int port;
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
private String type;
|
public MultiProtocolSocketAddress(String hostport) {
|
||||||
private String host;
|
this(hostport,"tcp");
|
||||||
private ProtocolStack ps=new ProtocolStack();
|
}
|
||||||
|
public MultiProtocolSocketAddress(String hostport, String defaultprotocol) {
|
||||||
|
try {
|
||||||
private int port;
|
if (!hostport.contains("://")) {
|
||||||
|
hostport = defaultprotocol.toLowerCase() + "://" + hostport;
|
||||||
public MultipurposeSocketAddress(String hostport) {
|
}
|
||||||
this(hostport,"TCP");
|
URI uri = new URI(hostport);
|
||||||
}
|
|
||||||
public MultipurposeSocketAddress(String hostport,String defaulttype) {
|
this.protocol = uri.getScheme().toLowerCase();
|
||||||
hostport=hostport.trim();
|
this.host = uri.getHost();
|
||||||
if (hostport.startsWith("{")) {
|
if (this.host == null) {
|
||||||
int i=hostport.indexOf("}");
|
throw new IllegalArgumentException("无效的主机地址: " + hostport);
|
||||||
if(i==-1) {
|
}
|
||||||
throw new IllegalArgumentException("missing }");
|
this.port = resolvePort(uri, this.protocol);
|
||||||
}
|
|
||||||
type=hostport.substring(1, i);
|
// 可选:处理查询参数
|
||||||
hostport=hostport.substring(i+1);
|
String query = uri.getQuery();
|
||||||
}else {
|
if (query != null && !query.isEmpty()) {
|
||||||
type=defaulttype;
|
// 解析查询参数作为扩展信息
|
||||||
}
|
}
|
||||||
int index =hostport.lastIndexOf(":");
|
} catch (URISyntaxException e) {
|
||||||
host=hostport.substring(0,index);
|
throw new IllegalArgumentException("无效的地址格式: " + hostport, e);
|
||||||
host=host.replace("[", "");
|
}
|
||||||
host=host.replace("]", "");
|
}
|
||||||
String tps=hostport.substring(index+1);
|
|
||||||
int v=tps.indexOf("(");
|
private int resolvePort(URI uri, String protocol) {
|
||||||
if(v!=-1) {
|
int port = uri.getPort();
|
||||||
ps.add(new Protocol(tps.substring(v+1,tps.lastIndexOf(")") )));
|
if (port != -1) {
|
||||||
tps=tps.substring(0, v);
|
return port;
|
||||||
}
|
}
|
||||||
port=Integer.parseInt(tps);
|
SocketType socketType = socketTypeRegister.get(protocol);
|
||||||
if(port<0) {
|
if (socketType != null) {
|
||||||
throw new IllegalArgumentException("port < 0");
|
int defaultPort = socketType.getDefaultPort();
|
||||||
}
|
if (defaultPort != -1) {
|
||||||
}
|
return defaultPort;
|
||||||
@Override
|
}
|
||||||
public int hashCode() {
|
}
|
||||||
return Objects.hash(host, port, ps, type);
|
throw new IllegalArgumentException(
|
||||||
}
|
"未指定端口号,且协议 " + protocol + " 没有默认端口: " + uri
|
||||||
@Override
|
);
|
||||||
public boolean equals(Object obj) {
|
}
|
||||||
if (this == obj)
|
@Override
|
||||||
return true;
|
public int hashCode() {
|
||||||
if (obj == null)
|
return Objects.hash(host, port, ps, protocol);
|
||||||
return false;
|
}
|
||||||
if (getClass() != obj.getClass())
|
@Override
|
||||||
return false;
|
public boolean equals(Object obj) {
|
||||||
MultipurposeSocketAddress other = (MultipurposeSocketAddress) obj;
|
if (this == obj)
|
||||||
return Objects.equals(host, other.host) && port == other.port && Objects.equals(ps, other.ps)
|
return true;
|
||||||
&& Objects.equals(type, other.type);
|
if (obj == null)
|
||||||
}
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
public boolean equals2(Object obj) {
|
return false;
|
||||||
if (this == obj)
|
MultiProtocolSocketAddress other = (MultiProtocolSocketAddress) obj;
|
||||||
return true;
|
return Objects.equals(host, other.host) && port == other.port && Objects.equals(ps, other.ps)
|
||||||
if (obj == null)
|
&& Objects.equals(protocol, other.protocol);
|
||||||
return false;
|
}
|
||||||
if (getClass() != obj.getClass())
|
|
||||||
return false;
|
public boolean equals2(Object obj) {
|
||||||
MultipurposeSocketAddress other = (MultipurposeSocketAddress) obj;
|
if (this == obj)
|
||||||
InetAddress addra=null;
|
return true;
|
||||||
try {
|
if (obj == null)
|
||||||
addra = InetAddress.getByName(host);
|
return false;
|
||||||
} catch (UnknownHostException e) {
|
if (getClass() != obj.getClass())
|
||||||
}
|
return false;
|
||||||
InetAddress addrb=null;
|
MultiProtocolSocketAddress other = (MultiProtocolSocketAddress) obj;
|
||||||
try {
|
InetAddress addra=null;
|
||||||
addrb = InetAddress.getByName(other.host);
|
try {
|
||||||
} catch (UnknownHostException e) {
|
addra = InetAddress.getByName(host);
|
||||||
}
|
} catch (UnknownHostException e) {
|
||||||
boolean hostequals=Objects.equals(addra, addrb);
|
}
|
||||||
|
InetAddress addrb=null;
|
||||||
return hostequals && port == other.port && Objects.equals(ps, other.ps)
|
try {
|
||||||
&& Objects.equals(type, other.type);
|
addrb = InetAddress.getByName(other.host);
|
||||||
}
|
} catch (UnknownHostException e) {
|
||||||
|
}
|
||||||
public MultipurposeSocketAddress(String host2, int port2) {
|
boolean hostequals=Objects.equals(addra, addrb);
|
||||||
this("TCP", host2, port2);
|
|
||||||
}
|
return hostequals && port == other.port && Objects.equals(ps, other.ps)
|
||||||
|
&& Objects.equals(protocol, other.protocol);
|
||||||
public MultipurposeSocketAddress(String type,String host2, int port2) {
|
}
|
||||||
host=host2;
|
|
||||||
port=port2;
|
public MultiProtocolSocketAddress(String host2, int port2) {
|
||||||
this.type=type;
|
this("tcp", host2, port2);
|
||||||
}
|
}
|
||||||
public MultipurposeSocketAddress(InetSocketAddress remoteSocketAddress) {
|
|
||||||
this("TCP",remoteSocketAddress);
|
public MultiProtocolSocketAddress(String protocol, String host2, int port2) {
|
||||||
}
|
host=host2;
|
||||||
public MultipurposeSocketAddress(String type,InetSocketAddress remoteSocketAddress) {
|
port=port2;
|
||||||
host=remoteSocketAddress.getAddress().getHostAddress();
|
this.protocol = protocol;
|
||||||
port=remoteSocketAddress.getPort();
|
}
|
||||||
this.type=type;
|
public MultiProtocolSocketAddress(InetSocketAddress remoteSocketAddress) {
|
||||||
}
|
this("tcp",remoteSocketAddress);
|
||||||
|
}
|
||||||
|
public MultiProtocolSocketAddress(String protocol, InetSocketAddress remoteSocketAddress) {
|
||||||
public String getHost() {
|
host=remoteSocketAddress.getAddress().getHostAddress();
|
||||||
return host;
|
port=remoteSocketAddress.getPort();
|
||||||
}
|
this.protocol = protocol;
|
||||||
public int getPort() {
|
}
|
||||||
return port;
|
|
||||||
}
|
|
||||||
public String getType() {
|
public String getHost() {
|
||||||
return type;
|
return host;
|
||||||
}
|
}
|
||||||
|
public int getPort() {
|
||||||
public InetSocketAddress getSocketAddress() {
|
return port;
|
||||||
return new InetSocketAddress(host, port);
|
}
|
||||||
}
|
public String getProtocol() {
|
||||||
|
return protocol;
|
||||||
@Override
|
}
|
||||||
public String toString() {
|
|
||||||
StringBuilder sb=new StringBuilder();
|
public InetSocketAddress getSocketAddress() {
|
||||||
if(!"TCP".equals(type)) {
|
return new InetSocketAddress(host, port);
|
||||||
sb.append('{').append(type).append('}');
|
}
|
||||||
}
|
|
||||||
if(host.contains(":")) {
|
@Override
|
||||||
sb.append('[').append( host).append( "]:").append( port);
|
public String toString() {
|
||||||
}else {
|
try {
|
||||||
sb.append( host).append( ':').append( port);
|
// 获取协议的默认端口
|
||||||
}
|
SocketType socketType = socketTypeRegister.get(protocol);
|
||||||
if(!ps.isEmpty()) {
|
int defaultPort = (socketType != null) ? socketType.getDefaultPort() : -1;
|
||||||
sb.append('(').append(ps.pop().getName()).append(')');
|
|
||||||
}
|
// 如果当前端口等于默认端口,则隐去端口号
|
||||||
return sb.toString();
|
int portToUse = (defaultPort != -1 && this.port == defaultPort) ? -1 : this.port;
|
||||||
}
|
|
||||||
|
URI uri = new URI(protocol, null, host, portToUse, null, null, null);
|
||||||
|
return uri.toString();
|
||||||
|
} catch (URISyntaxException e) {
|
||||||
|
return protocol + "://" + host + ":" + port;
|
||||||
|
}
|
||||||
public Socket connectSocket(InetAddress bindip,int bindport,int timeout) throws UnknownHostException, IOException {
|
}
|
||||||
SocketFactory sf=socketTypeRegister.get(type).getSocketFactory();
|
|
||||||
if(sf==null) {
|
|
||||||
throw new UnsupportedOperationException("Socket Unsupported");
|
|
||||||
}
|
public Socket connectSocket(InetAddress bindip,int bindport,int timeout) throws UnknownHostException, IOException {
|
||||||
Socket s=sf.createSocket();
|
SocketFactory sf=socketTypeRegister.get(protocol).getSocketFactory();
|
||||||
try {
|
if(sf==null) {
|
||||||
s.bind(new InetSocketAddress(bindip, bindport));
|
throw new UnsupportedOperationException("Socket Unsupported");
|
||||||
s.connect(new InetSocketAddress(host, port),timeout);
|
}
|
||||||
}catch(Exception e) {
|
Socket s=sf.createSocket();
|
||||||
s.close();
|
try {
|
||||||
throw e;
|
s.bind(new InetSocketAddress(bindip, bindport));
|
||||||
}
|
s.connect(new InetSocketAddress(host, port),timeout);
|
||||||
return s;
|
}catch(Exception e) {
|
||||||
}
|
s.close();
|
||||||
public Socket connectSocket(InetAddress bindip,int bindport) throws UnknownHostException, IOException {
|
throw e;
|
||||||
SocketFactory sf=socketTypeRegister.get(type).getSocketFactory();
|
}
|
||||||
if(sf==null) {
|
return s;
|
||||||
throw new UnsupportedOperationException("Socket Unsupported");
|
}
|
||||||
}
|
public Socket connectSocket(InetAddress bindip,int bindport) throws UnknownHostException, IOException {
|
||||||
Socket s=sf.createSocket();
|
SocketFactory sf=socketTypeRegister.get(protocol).getSocketFactory();
|
||||||
try {
|
if(sf==null) {
|
||||||
s.bind(new InetSocketAddress(bindip, bindport));
|
throw new UnsupportedOperationException("Socket Unsupported");
|
||||||
s.connect(new InetSocketAddress(host, port));
|
}
|
||||||
}catch(Exception e) {
|
Socket s=sf.createSocket();
|
||||||
s.close();
|
try {
|
||||||
throw e;
|
s.bind(new InetSocketAddress(bindip, bindport));
|
||||||
}
|
s.connect(new InetSocketAddress(host, port));
|
||||||
return s;
|
}catch(Exception e) {
|
||||||
}
|
s.close();
|
||||||
public Socket connectSocket() throws UnknownHostException, IOException {
|
throw e;
|
||||||
SocketFactory sf=socketTypeRegister.get(type).getSocketFactory();
|
}
|
||||||
if(sf==null) {
|
return s;
|
||||||
throw new UnsupportedOperationException("Socket Unsupported");
|
}
|
||||||
}
|
public Socket connectSocket() throws UnknownHostException, IOException {
|
||||||
Socket s=sf.createSocket();
|
SocketFactory sf=socketTypeRegister.get(protocol).getSocketFactory();
|
||||||
try {
|
if(sf==null) {
|
||||||
s.connect(new InetSocketAddress(host, port));
|
throw new UnsupportedOperationException("Socket Unsupported");
|
||||||
}catch(Exception e) {
|
}
|
||||||
s.close();
|
Socket s=sf.createSocket();
|
||||||
throw e;
|
try {
|
||||||
}
|
s.connect(new InetSocketAddress(host, port));
|
||||||
return s;
|
}catch(Exception e) {
|
||||||
}
|
s.close();
|
||||||
public Socket connectSocket(int timeout) throws UnknownHostException, IOException {
|
throw e;
|
||||||
SocketFactory sf=socketTypeRegister.get(type).getSocketFactory();
|
}
|
||||||
if(sf==null) {
|
return s;
|
||||||
throw new UnsupportedOperationException("Socket Unsupported");
|
}
|
||||||
}
|
public Socket connectSocket(int timeout) throws UnknownHostException, IOException {
|
||||||
Socket s=sf.createSocket();
|
SocketFactory sf=socketTypeRegister.get(protocol).getSocketFactory();
|
||||||
try {
|
if(sf==null) {
|
||||||
s.connect(new InetSocketAddress(host, port),timeout);
|
throw new UnsupportedOperationException("Socket Unsupported");
|
||||||
}catch(Exception e) {
|
}
|
||||||
s.close();
|
Socket s=sf.createSocket();
|
||||||
throw e;
|
try {
|
||||||
}
|
s.connect(new InetSocketAddress(host, port),timeout);
|
||||||
return s;
|
}catch(Exception e) {
|
||||||
}
|
s.close();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
return s;
|
||||||
private static TimeoutTimer tmoTimer=new TimeoutTimer();
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
public SocketChannel connectSocketChannel(InetAddress bindip,int bindport,int timeout) throws UnknownHostException, IOException {
|
private static TimeoutTimer tmoTimer=new TimeoutTimer();
|
||||||
SocketChannelFactory sf=socketTypeRegister.get(type).getSocketChannelFactory();
|
|
||||||
if(sf==null) {
|
|
||||||
throw new UnsupportedOperationException("Socket Unsupported");
|
|
||||||
}
|
public SocketChannel connectSocketChannel(InetAddress bindip,int bindport,int timeout) throws UnknownHostException, IOException {
|
||||||
SocketChannel s=sf.createSocketChannel();
|
SocketChannelFactory sf=socketTypeRegister.get(protocol).getSocketChannelFactory();
|
||||||
TimerTask tt=null;
|
if(sf==null) {
|
||||||
try {
|
throw new UnsupportedOperationException("Socket Unsupported");
|
||||||
s.bind(new InetSocketAddress(bindip, bindport));
|
}
|
||||||
tt=tmoTimer.createTimeOutTask(s, timeout);
|
SocketChannel s=sf.createSocketChannel();
|
||||||
|
TimerTask tt=null;
|
||||||
s.connect(new InetSocketAddress(host, port));
|
try {
|
||||||
}catch(Exception e) {
|
s.bind(new InetSocketAddress(bindip, bindport));
|
||||||
s.close();
|
tt=tmoTimer.createTimeOutTask(s, timeout);
|
||||||
throw e;
|
|
||||||
}finally {
|
s.connect(new InetSocketAddress(host, port));
|
||||||
if(tt!=null)
|
}catch(Exception e) {
|
||||||
tt.cancel();
|
s.close();
|
||||||
}
|
throw e;
|
||||||
return s;
|
}finally {
|
||||||
}
|
if(tt!=null)
|
||||||
public SocketChannel connectSocketChannel(InetAddress bindip,int bindport) throws UnknownHostException, IOException {
|
tt.cancel();
|
||||||
SocketChannelFactory sf=socketTypeRegister.get(type).getSocketChannelFactory();
|
}
|
||||||
if(sf==null) {
|
return s;
|
||||||
throw new UnsupportedOperationException("Socket Unsupported");
|
}
|
||||||
}
|
public SocketChannel connectSocketChannel(InetAddress bindip,int bindport) throws UnknownHostException, IOException {
|
||||||
SocketChannel s=sf.createSocketChannel();
|
SocketChannelFactory sf=socketTypeRegister.get(protocol).getSocketChannelFactory();
|
||||||
try {
|
if(sf==null) {
|
||||||
s.bind(new InetSocketAddress(bindip, bindport));
|
throw new UnsupportedOperationException("Socket Unsupported");
|
||||||
s.connect(new InetSocketAddress(host, port));
|
}
|
||||||
}catch(Exception e) {
|
SocketChannel s=sf.createSocketChannel();
|
||||||
s.close();
|
try {
|
||||||
throw e;
|
s.bind(new InetSocketAddress(bindip, bindport));
|
||||||
}
|
s.connect(new InetSocketAddress(host, port));
|
||||||
return s;
|
}catch(Exception e) {
|
||||||
}
|
s.close();
|
||||||
public SocketChannel connectSocketChannel() throws UnknownHostException, IOException {
|
throw e;
|
||||||
SocketChannelFactory sf=socketTypeRegister.get(type).getSocketChannelFactory();
|
}
|
||||||
if(sf==null) {
|
return s;
|
||||||
throw new UnsupportedOperationException("Socket Unsupported");
|
}
|
||||||
}
|
public SocketChannel connectSocketChannel() throws UnknownHostException, IOException {
|
||||||
SocketChannel s=sf.createSocketChannel();
|
SocketChannelFactory sf=socketTypeRegister.get(protocol).getSocketChannelFactory();
|
||||||
try {
|
if(sf==null) {
|
||||||
s.connect(new InetSocketAddress(host, port));
|
throw new UnsupportedOperationException("Socket Unsupported");
|
||||||
}catch(Exception e) {
|
}
|
||||||
s.close();
|
SocketChannel s=sf.createSocketChannel();
|
||||||
throw e;
|
try {
|
||||||
}
|
s.connect(new InetSocketAddress(host, port));
|
||||||
return s;
|
}catch(Exception e) {
|
||||||
}
|
s.close();
|
||||||
public SocketChannel connectSocketChannel(int timeout) throws UnknownHostException, IOException {
|
throw e;
|
||||||
SocketChannelFactory sf=socketTypeRegister.get(type).getSocketChannelFactory();
|
}
|
||||||
if(sf==null) {
|
return s;
|
||||||
throw new UnsupportedOperationException("Socket Unsupported");
|
}
|
||||||
}
|
public SocketChannel connectSocketChannel(int timeout) throws UnknownHostException, IOException {
|
||||||
SocketChannel s=sf.createSocketChannel();
|
SocketChannelFactory sf=socketTypeRegister.get(protocol).getSocketChannelFactory();
|
||||||
|
if(sf==null) {
|
||||||
TimerTask tt=tmoTimer.createTimeOutTask(s, timeout);
|
throw new UnsupportedOperationException("Socket Unsupported");
|
||||||
try {
|
}
|
||||||
s.connect(new InetSocketAddress(host, port));
|
SocketChannel s=sf.createSocketChannel();
|
||||||
}catch(Exception e) {
|
|
||||||
s.close();
|
TimerTask tt=tmoTimer.createTimeOutTask(s, timeout);
|
||||||
throw e;
|
try {
|
||||||
}finally {
|
s.connect(new InetSocketAddress(host, port));
|
||||||
if(tt!=null)
|
}catch(Exception e) {
|
||||||
tt.cancel();
|
s.close();
|
||||||
}
|
throw e;
|
||||||
return s;
|
}finally {
|
||||||
}
|
if(tt!=null)
|
||||||
|
tt.cancel();
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public ServerSocket listenServerSocket() throws UnknownHostException, IOException {
|
|
||||||
ServerSocketFactory srf=socketTypeRegister.get(type).getServerSocketFactory();
|
|
||||||
if(srf==null) {
|
|
||||||
throw new UnsupportedOperationException("ServerSocket Unsupported");
|
|
||||||
}
|
public ServerSocket listenServerSocket() throws UnknownHostException, IOException {
|
||||||
ServerSocket sk=srf.createServerSocket(port, 50, InetAddress.getByName(host));
|
ServerSocketFactory srf=socketTypeRegister.get(protocol).getServerSocketFactory();
|
||||||
return sk;
|
if(srf==null) {
|
||||||
}
|
throw new UnsupportedOperationException("ServerSocket Unsupported");
|
||||||
public ServerSocket listenServerSocket(int backlog) throws UnknownHostException, IOException {
|
}
|
||||||
ServerSocketFactory srf=socketTypeRegister.get(type).getServerSocketFactory();
|
ServerSocket sk=srf.createServerSocket(port, 50, InetAddress.getByName(host));
|
||||||
if(srf==null) {
|
return sk;
|
||||||
throw new UnsupportedOperationException("ServerSocket Unsupported");
|
}
|
||||||
}
|
public ServerSocket listenServerSocket(int backlog) throws UnknownHostException, IOException {
|
||||||
ServerSocket sk=srf.createServerSocket(port, backlog, InetAddress.getByName(host));
|
ServerSocketFactory srf=socketTypeRegister.get(protocol).getServerSocketFactory();
|
||||||
return sk;
|
if(srf==null) {
|
||||||
}
|
throw new UnsupportedOperationException("ServerSocket Unsupported");
|
||||||
|
}
|
||||||
|
ServerSocket sk=srf.createServerSocket(port, backlog, InetAddress.getByName(host));
|
||||||
public ServerSocketChannel listenServerSocketChannel() throws UnknownHostException, IOException {
|
return sk;
|
||||||
ServerSocketChannelFactory srf=socketTypeRegister.get(type).getServerSocketChannelFactory();
|
}
|
||||||
if(srf==null) {
|
|
||||||
throw new UnsupportedOperationException("ServerSocket Unsupported");
|
|
||||||
}
|
public ServerSocketChannel listenServerSocketChannel() throws UnknownHostException, IOException {
|
||||||
ServerSocketChannel sk=srf.createServerSocketChannel(port, 50, InetAddress.getByName(host));
|
ServerSocketChannelFactory srf=socketTypeRegister.get(protocol).getServerSocketChannelFactory();
|
||||||
return sk;
|
if(srf==null) {
|
||||||
}
|
throw new UnsupportedOperationException("ServerSocket Unsupported");
|
||||||
public ServerSocketChannel listenServerSocketChannel(int backlog) throws UnknownHostException, IOException {
|
}
|
||||||
ServerSocketChannelFactory srf=socketTypeRegister.get(type).getServerSocketChannelFactory();
|
ServerSocketChannel sk=srf.createServerSocketChannel(port, 50, InetAddress.getByName(host));
|
||||||
if(srf==null) {
|
return sk;
|
||||||
throw new UnsupportedOperationException("ServerSocket Unsupported");
|
}
|
||||||
}
|
public ServerSocketChannel listenServerSocketChannel(int backlog) throws UnknownHostException, IOException {
|
||||||
ServerSocketChannel sk=srf.createServerSocketChannel(port, backlog, InetAddress.getByName(host));
|
ServerSocketChannelFactory srf=socketTypeRegister.get(protocol).getServerSocketChannelFactory();
|
||||||
return sk;
|
if(srf==null) {
|
||||||
}
|
throw new UnsupportedOperationException("ServerSocket Unsupported");
|
||||||
|
}
|
||||||
|
ServerSocketChannel sk=srf.createServerSocketChannel(port, backlog, InetAddress.getByName(host));
|
||||||
public boolean isStream() {
|
return sk;
|
||||||
return checkIsStream(type);
|
}
|
||||||
}
|
|
||||||
public static boolean checkIsStream(String type2) {
|
|
||||||
return socketTypeRegister.get(type2).isStream();
|
public boolean isStream() {
|
||||||
}
|
return checkIsStream(protocol);
|
||||||
public DatagramSocket connectDatagramSocket(InetAddress bindip,int bindport) throws IOException {
|
}
|
||||||
DatagramSocketFactory dgs=socketTypeRegister.get(type).getDatagramSocketFactory();
|
public static boolean checkIsStream(String type2) {
|
||||||
if(dgs==null) {
|
return socketTypeRegister.get(type2).isStream();
|
||||||
throw new UnsupportedOperationException("DatagramSocket Unsupported");
|
}
|
||||||
}
|
public DatagramSocket connectDatagramSocket(InetAddress bindip,int bindport) throws IOException {
|
||||||
DatagramSocket dgd=dgs.createSocket();
|
DatagramSocketFactory dgs=socketTypeRegister.get(protocol).getDatagramSocketFactory();
|
||||||
try {
|
if(dgs==null) {
|
||||||
dgd.bind(new InetSocketAddress(bindip, bindport));
|
throw new UnsupportedOperationException("DatagramSocket Unsupported");
|
||||||
dgd.connect(new InetSocketAddress(host, port));
|
}
|
||||||
}catch(Exception e) {
|
DatagramSocket dgd=dgs.createSocket();
|
||||||
dgd.close();
|
try {
|
||||||
throw e;
|
dgd.bind(new InetSocketAddress(bindip, bindport));
|
||||||
}
|
dgd.connect(new InetSocketAddress(host, port));
|
||||||
return dgd;
|
}catch(Exception e) {
|
||||||
}
|
dgd.close();
|
||||||
public DatagramSocket connectDatagramSocket() throws IOException {
|
throw e;
|
||||||
DatagramSocketFactory dgs=socketTypeRegister.get(type).getDatagramSocketFactory();
|
}
|
||||||
if(dgs==null) {
|
return dgd;
|
||||||
throw new UnsupportedOperationException("DatagramSocket Unsupported");
|
}
|
||||||
}
|
public DatagramSocket connectDatagramSocket() throws IOException {
|
||||||
DatagramSocket dgd=dgs.createSocket();
|
DatagramSocketFactory dgs=socketTypeRegister.get(protocol).getDatagramSocketFactory();
|
||||||
try {
|
if(dgs==null) {
|
||||||
dgd.connect(new InetSocketAddress(host, port));
|
throw new UnsupportedOperationException("DatagramSocket Unsupported");
|
||||||
}catch(Exception e) {
|
}
|
||||||
dgd.close();
|
DatagramSocket dgd=dgs.createSocket();
|
||||||
throw e;
|
try {
|
||||||
}
|
dgd.connect(new InetSocketAddress(host, port));
|
||||||
return dgd;
|
}catch(Exception e) {
|
||||||
}
|
dgd.close();
|
||||||
public DatagramSocket listenDatagramSocket() throws UnknownHostException, IOException {
|
throw e;
|
||||||
DatagramSocketFactory dgs=socketTypeRegister.get(type).getDatagramSocketFactory();
|
}
|
||||||
if(dgs==null) {
|
return dgd;
|
||||||
throw new UnsupportedOperationException("DatagramSocket Unsupported");
|
}
|
||||||
}
|
public DatagramSocket listenDatagramSocket() throws UnknownHostException, IOException {
|
||||||
DatagramSocket dgd=dgs.createSocket();
|
DatagramSocketFactory dgs=socketTypeRegister.get(protocol).getDatagramSocketFactory();
|
||||||
try {
|
if(dgs==null) {
|
||||||
dgd.bind(new InetSocketAddress(host, port));
|
throw new UnsupportedOperationException("DatagramSocket Unsupported");
|
||||||
}catch(Exception e) {
|
}
|
||||||
dgd.close();
|
DatagramSocket dgd=dgs.createSocket();
|
||||||
throw e;
|
try {
|
||||||
}
|
dgd.bind(new InetSocketAddress(host, port));
|
||||||
return dgd;
|
}catch(Exception e) {
|
||||||
}
|
dgd.close();
|
||||||
|
throw e;
|
||||||
public DatagramServerSocket listenDatagramServerSocket() throws UnknownHostException, IOException {
|
}
|
||||||
DatagramServerSocketFactory srf=socketTypeRegister.get(type).getDatagramServerSocketFactory();
|
return dgd;
|
||||||
if(srf==null) {
|
}
|
||||||
throw new UnsupportedOperationException("DatagramServerSocket Unsupported");
|
|
||||||
}
|
public DatagramServerSocket listenDatagramServerSocket() throws UnknownHostException, IOException {
|
||||||
DatagramServerSocket sk=srf.createDatagramServerSocket(port, 50, InetAddress.getByName(host));
|
DatagramServerSocketFactory srf=socketTypeRegister.get(protocol).getDatagramServerSocketFactory();
|
||||||
return sk;
|
if(srf==null) {
|
||||||
}
|
throw new UnsupportedOperationException("DatagramServerSocket Unsupported");
|
||||||
public DatagramServerSocket listenDatagramServerSocket(int backlog) throws UnknownHostException, IOException {
|
}
|
||||||
DatagramServerSocketFactory srf=socketTypeRegister.get(type).getDatagramServerSocketFactory();
|
DatagramServerSocket sk=srf.createDatagramServerSocket(port, 50, InetAddress.getByName(host));
|
||||||
if(srf==null) {
|
return sk;
|
||||||
throw new UnsupportedOperationException("DatagramServerSocket Unsupported");
|
}
|
||||||
}
|
public DatagramServerSocket listenDatagramServerSocket(int backlog) throws UnknownHostException, IOException {
|
||||||
DatagramServerSocket sk=srf.createDatagramServerSocket(port, backlog, InetAddress.getByName(host));
|
DatagramServerSocketFactory srf=socketTypeRegister.get(protocol).getDatagramServerSocketFactory();
|
||||||
return sk;
|
if(srf==null) {
|
||||||
}
|
throw new UnsupportedOperationException("DatagramServerSocket Unsupported");
|
||||||
public InetAddress getInetAddress() throws UnknownHostException {
|
}
|
||||||
return InetAddress.getByName(host);
|
DatagramServerSocket sk=srf.createDatagramServerSocket(port, backlog, InetAddress.getByName(host));
|
||||||
}
|
return sk;
|
||||||
public InetAddress[] getAllInetAddress() throws UnknownHostException {
|
}
|
||||||
return InetAddress.getAllByName(host);
|
public InetAddress getInetAddress() throws UnknownHostException {
|
||||||
}
|
return InetAddress.getByName(host);
|
||||||
public boolean supportNIO() {
|
}
|
||||||
SocketType stp= socketTypeRegister.get(getType());
|
public InetAddress[] getAllInetAddress() throws UnknownHostException {
|
||||||
if(stp==null)
|
return InetAddress.getAllByName(host);
|
||||||
return false;
|
}
|
||||||
if(stp.getSocketChannelFactory()==null) {
|
public boolean supportNIO() {
|
||||||
return false;
|
SocketType stp= socketTypeRegister.get(getProtocol());
|
||||||
}else {
|
if(stp==null)
|
||||||
return true;
|
return false;
|
||||||
}
|
if(stp.getSocketChannelFactory()==null) {
|
||||||
}
|
return false;
|
||||||
|
}else {
|
||||||
public static JsonDeserializer<MultipurposeSocketAddress>getDefaultJsonDeserializer(){
|
return true;
|
||||||
return new JsonDeserializer<MultipurposeSocketAddress>() {
|
}
|
||||||
|
}
|
||||||
@Override
|
|
||||||
public MultipurposeSocketAddress deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
|
public static JsonDeserializer<MultiProtocolSocketAddress>getDefaultJsonDeserializer(){
|
||||||
throws JsonParseException {
|
return new JsonDeserializer<MultiProtocolSocketAddress>() {
|
||||||
if(arg0.isJsonPrimitive()) {
|
|
||||||
JsonPrimitive jp=(JsonPrimitive) arg0;
|
@Override
|
||||||
if(jp.isString()) {
|
public MultiProtocolSocketAddress deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
|
||||||
return new MultipurposeSocketAddress(jp.getAsString());
|
throws JsonParseException {
|
||||||
}
|
if(arg0.isJsonPrimitive()) {
|
||||||
}
|
JsonPrimitive jp=(JsonPrimitive) arg0;
|
||||||
throw new JsonParseException("not a string:"+arg0);
|
if(jp.isString()) {
|
||||||
}
|
MultiProtocolSocketAddress msa=new MultiProtocolSocketAddress(jp.getAsString());
|
||||||
};
|
// System.out.println(msa);
|
||||||
}
|
return msa;
|
||||||
public static JsonSerializer<MultipurposeSocketAddress>getDefaultJsonSerializer(){
|
}
|
||||||
return new JsonSerializer<MultipurposeSocketAddress>() {
|
}
|
||||||
|
throw new JsonParseException("not a string:"+arg0);
|
||||||
@Override
|
}
|
||||||
public JsonElement serialize(MultipurposeSocketAddress arg0, Type arg1, JsonSerializationContext arg2) {
|
};
|
||||||
return new JsonPrimitive(arg0.toString());
|
}
|
||||||
}
|
public static JsonSerializer<MultiProtocolSocketAddress>getDefaultJsonSerializer(){
|
||||||
};
|
return new JsonSerializer<MultiProtocolSocketAddress>() {
|
||||||
}
|
|
||||||
|
@Override
|
||||||
public static void registerToGsonBuilder(GsonBuilder gsonBuilder) {
|
public JsonElement serialize(MultiProtocolSocketAddress arg0, Type arg1, JsonSerializationContext arg2) {
|
||||||
gsonBuilder.registerTypeAdapter(MultipurposeSocketAddress.class, getDefaultJsonDeserializer());
|
return new JsonPrimitive(arg0.toString());
|
||||||
gsonBuilder.registerTypeAdapter(MultipurposeSocketAddress.class, getDefaultJsonSerializer());
|
}
|
||||||
}
|
};
|
||||||
|
}
|
||||||
}
|
|
||||||
|
public static void registerToGsonBuilder(GsonBuilder gsonBuilder) {
|
||||||
|
gsonBuilder.registerTypeAdapter(MultiProtocolSocketAddress.class, getDefaultJsonDeserializer());
|
||||||
|
gsonBuilder.registerTypeAdapter(MultiProtocolSocketAddress.class, getDefaultJsonSerializer());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
package org.kne.cloud.network;
|
package org.kne.cloud.network;
|
||||||
|
|
||||||
public interface NetworkService {
|
public interface NetworkService {
|
||||||
public void listen(MultipurposeSocketAddress msa);
|
public void listen(MultiProtocolSocketAddress msa);
|
||||||
public void unlisten(MultipurposeSocketAddress msc);
|
public void unlisten(MultiProtocolSocketAddress msc);
|
||||||
|
|
||||||
public void connect(MultipurposeSocketAddress msa);
|
public void connect(MultiProtocolSocketAddress msa);
|
||||||
public void unconnect(MultipurposeSocketAddress msc);
|
public void unconnect(MultiProtocolSocketAddress msc);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,7 @@
|
|||||||
package org.kne.cloud.network;
|
package org.kne.cloud.network;
|
||||||
|
|
||||||
import java.io.DataInputStream;
|
|
||||||
import java.io.DataOutputStream;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
import java.nio.channels.*;
|
|
||||||
import java.nio.channels.spi.AbstractInterruptibleChannel;
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
public class PortRelay {
|
public class PortRelay {
|
||||||
private int port;
|
private int port;
|
||||||
@@ -16,8 +10,8 @@ public class PortRelay {
|
|||||||
public PortRelay(int port, HostPortMap services) throws IOException {
|
public PortRelay(int port, HostPortMap services) throws IOException {
|
||||||
this.services = services;
|
this.services = services;
|
||||||
this.port = port;
|
this.port = port;
|
||||||
MultipurposeSocketAddress.getSocketTypeRegister().put("ProtocolDetectorServerSocket",new SocketType(null, new ProtocolDetectorServerSocketFactory()) );
|
MultiProtocolSocketAddress.getSocketTypeRegister().put("ProtocolDetectorServerSocket",new SocketType(null, new ProtocolDetectorServerSocketFactory()) );
|
||||||
ssc=new SocketListener(new MultipurposeSocketAddress("ProtocolDetectorServerSocket", "0.0.0.0", port));
|
ssc=new SocketListener(new MultiProtocolSocketAddress("ProtocolDetectorServerSocket", "0.0.0.0", port));
|
||||||
}
|
}
|
||||||
public void start() throws IOException {
|
public void start() throws IOException {
|
||||||
ssc.setCon((s)->{
|
ssc.setCon((s)->{
|
||||||
@@ -30,7 +24,7 @@ public class PortRelay {
|
|||||||
}else {
|
}else {
|
||||||
nx=pds.getProtocolStack().pop().getName();
|
nx=pds.getProtocolStack().pop().getName();
|
||||||
}
|
}
|
||||||
MultipurposeSocketAddress hp=services.get(nx);
|
MultiProtocolSocketAddress hp=services.get(nx);
|
||||||
InetSocketAddress sa=(InetSocketAddress) s.getRemoteSocketAddress();
|
InetSocketAddress sa=(InetSocketAddress) s.getRemoteSocketAddress();
|
||||||
System.out.println(sa.getAddress().getHostAddress() + ":" + port
|
System.out.println(sa.getAddress().getHostAddress() + ":" + port
|
||||||
+ "-" + "(" + nx + ")->" + hp.getHost() + ":" + hp.getPort());
|
+ "-" + "(" + nx + ")->" + hp.getHost() + ":" + hp.getPort());
|
||||||
|
|||||||
@@ -1,23 +1,19 @@
|
|||||||
package org.kne.cloud.network;
|
package org.kne.cloud.network;
|
||||||
|
|
||||||
import java.net.UnknownHostException;
|
import java.net.UnknownHostException;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
public class ServiceElement {
|
public class ServiceElement {
|
||||||
public String name;
|
public String name;
|
||||||
public String protocol;
|
public String protocol;
|
||||||
public MultipurposeSocketAddress ipport;
|
public MultiProtocolSocketAddress ipport;
|
||||||
public ServiceElement(String ini) throws UnknownHostException {
|
public ServiceElement(String ini) throws UnknownHostException {
|
||||||
String[]t=ini.split("\\$");
|
String[]t=ini.split("\\$");
|
||||||
if(t.length==1) {
|
if(t.length==1) {
|
||||||
protocol="";
|
protocol="";
|
||||||
ipport=new MultipurposeSocketAddress(t[0]);
|
ipport=new MultiProtocolSocketAddress(t[0]);
|
||||||
}else {
|
}else {
|
||||||
protocol=t[0];
|
protocol=t[0];
|
||||||
ipport=new MultipurposeSocketAddress(t[1]);
|
ipport=new MultiProtocolSocketAddress(t[1]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public ServiceElement() {
|
public ServiceElement() {
|
||||||
|
|||||||
@@ -1,21 +1,20 @@
|
|||||||
package org.kne.cloud.network;
|
package org.kne.cloud.network;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
public class ServiceToSocketProxy extends Proxy{
|
public class ServiceToSocketProxy extends Proxy{
|
||||||
public NetworkService getSrc() {
|
public NetworkService getSrc() {
|
||||||
return src;
|
return src;
|
||||||
}
|
}
|
||||||
public MultipurposeSocketAddress getDes() {
|
public MultiProtocolSocketAddress getDes() {
|
||||||
return des;
|
return des;
|
||||||
}
|
}
|
||||||
public ServiceToSocketProxy(String l, String r) {
|
public ServiceToSocketProxy(String l, String r) {
|
||||||
src=getRegister().get(l.substring(1, l.length()-1));
|
src=getRegister().get(l.substring(1, l.length()-1));
|
||||||
des=new MultipurposeSocketAddress(r);
|
des=new MultiProtocolSocketAddress(r);
|
||||||
}
|
}
|
||||||
private NetworkService src;
|
private NetworkService src;
|
||||||
private MultipurposeSocketAddress des;
|
private MultiProtocolSocketAddress des;
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException {
|
public void close() throws IOException {
|
||||||
// TODO 自动生成的方法存根
|
// TODO 自动生成的方法存根
|
||||||
|
|||||||
@@ -50,10 +50,10 @@ public class SocketChannelListener implements Closeable,AutoCloseable{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
private MultipurposeSocketAddress multipurposeSocketAddress;
|
private MultiProtocolSocketAddress multiProtocolSocketAddress;
|
||||||
|
|
||||||
public SocketChannelListener(MultipurposeSocketAddress multipurposeSocketAddress) throws IOException {
|
public SocketChannelListener(MultiProtocolSocketAddress multiProtocolSocketAddress) throws IOException {
|
||||||
this.multipurposeSocketAddress=multipurposeSocketAddress;
|
this.multiProtocolSocketAddress = multiProtocolSocketAddress;
|
||||||
open();
|
open();
|
||||||
}
|
}
|
||||||
public SocketChannelListener(ServerSocketChannel tserverSocket) throws IOException {
|
public SocketChannelListener(ServerSocketChannel tserverSocket) throws IOException {
|
||||||
@@ -62,9 +62,9 @@ public class SocketChannelListener implements Closeable,AutoCloseable{
|
|||||||
}
|
}
|
||||||
protected void open() throws UnknownHostException, IOException {
|
protected void open() throws UnknownHostException, IOException {
|
||||||
if(serverSocketChannel==null)
|
if(serverSocketChannel==null)
|
||||||
serverSocketChannel=multipurposeSocketAddress.listenServerSocketChannel();
|
serverSocketChannel= multiProtocolSocketAddress.listenServerSocketChannel();
|
||||||
if(serverSocketChannel==null) {
|
if(serverSocketChannel==null) {
|
||||||
throw new IOException(multipurposeSocketAddress.getType()+" unsupport SocketChannel");
|
throw new IOException(multiProtocolSocketAddress.getProtocol()+" unsupport SocketChannel");
|
||||||
}
|
}
|
||||||
ThreadTool.makeVThread("端口监听线程", r).start();
|
ThreadTool.makeVThread("端口监听线程", r).start();
|
||||||
}
|
}
|
||||||
@@ -82,8 +82,8 @@ public class SocketChannelListener implements Closeable,AutoCloseable{
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
public MultipurposeSocketAddress getMultipurposeSocketAddress() {
|
public MultiProtocolSocketAddress getMultipurposeSocketAddress() {
|
||||||
return multipurposeSocketAddress;
|
return multiProtocolSocketAddress;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Consumer<SocketChannel> getCon() {
|
public Consumer<SocketChannel> getCon() {
|
||||||
|
|||||||
@@ -2,15 +2,12 @@ package org.kne.cloud.network;
|
|||||||
|
|
||||||
import java.io.Closeable;
|
import java.io.Closeable;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.InetAddress;
|
|
||||||
import java.net.ServerSocket;
|
import java.net.ServerSocket;
|
||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
import java.net.SocketException;
|
import java.net.SocketException;
|
||||||
import java.net.UnknownHostException;
|
import java.net.UnknownHostException;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
import javax.net.ServerSocketFactory;
|
|
||||||
|
|
||||||
public class SocketListener implements Closeable,AutoCloseable{
|
public class SocketListener implements Closeable,AutoCloseable{
|
||||||
protected ServerSocket serverSocket;
|
protected ServerSocket serverSocket;
|
||||||
public ServerSocket getServerSocket() {
|
public ServerSocket getServerSocket() {
|
||||||
@@ -53,10 +50,10 @@ public class SocketListener implements Closeable,AutoCloseable{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
private MultipurposeSocketAddress multipurposeSocketAddress;
|
private MultiProtocolSocketAddress multiProtocolSocketAddress;
|
||||||
|
|
||||||
public SocketListener(MultipurposeSocketAddress multipurposeSocketAddress) throws IOException {
|
public SocketListener(MultiProtocolSocketAddress multiProtocolSocketAddress) throws IOException {
|
||||||
this.multipurposeSocketAddress=multipurposeSocketAddress;
|
this.multiProtocolSocketAddress = multiProtocolSocketAddress;
|
||||||
open();
|
open();
|
||||||
}
|
}
|
||||||
public SocketListener(ServerSocket tserverSocket) throws IOException {
|
public SocketListener(ServerSocket tserverSocket) throws IOException {
|
||||||
@@ -65,7 +62,7 @@ public class SocketListener implements Closeable,AutoCloseable{
|
|||||||
}
|
}
|
||||||
protected void open() throws UnknownHostException, IOException {
|
protected void open() throws UnknownHostException, IOException {
|
||||||
if(serverSocket==null)
|
if(serverSocket==null)
|
||||||
serverSocket=multipurposeSocketAddress.listenServerSocket();
|
serverSocket= multiProtocolSocketAddress.listenServerSocket();
|
||||||
ThreadTool.makeVThread("端口监听线程", r).start();
|
ThreadTool.makeVThread("端口监听线程", r).start();
|
||||||
}
|
}
|
||||||
public void close() {
|
public void close() {
|
||||||
@@ -82,8 +79,8 @@ public class SocketListener implements Closeable,AutoCloseable{
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
public MultipurposeSocketAddress getMultipurposeSocketAddress() {
|
public MultiProtocolSocketAddress getMultipurposeSocketAddress() {
|
||||||
return multipurposeSocketAddress;
|
return multiProtocolSocketAddress;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Consumer<Socket> getCon() {
|
public Consumer<Socket> getCon() {
|
||||||
|
|||||||
@@ -1,21 +1,19 @@
|
|||||||
package org.kne.cloud.network;
|
package org.kne.cloud.network;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.Socket;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
public class SocketToServiceProxy extends Proxy {
|
public class SocketToServiceProxy extends Proxy {
|
||||||
public SocketToServiceProxy(String l, String r) {
|
public SocketToServiceProxy(String l, String r) {
|
||||||
src=new MultipurposeSocketAddress(l);
|
src=new MultiProtocolSocketAddress(l);
|
||||||
des=getRegister().get(r.substring(1, r.length()-1)) ;
|
des=getRegister().get(r.substring(1, r.length()-1)) ;
|
||||||
}
|
}
|
||||||
public MultipurposeSocketAddress getSrc() {
|
public MultiProtocolSocketAddress getSrc() {
|
||||||
return src;
|
return src;
|
||||||
}
|
}
|
||||||
public NetworkService getDes() {
|
public NetworkService getDes() {
|
||||||
return des;
|
return des;
|
||||||
}
|
}
|
||||||
private MultipurposeSocketAddress src;
|
private MultiProtocolSocketAddress src;
|
||||||
private NetworkService des;
|
private NetworkService des;
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException {
|
public void close() throws IOException {
|
||||||
|
|||||||
@@ -4,10 +4,7 @@ import java.io.IOException;
|
|||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
import java.net.SocketOption;
|
|
||||||
import java.net.SocketOptions;
|
|
||||||
import java.net.StandardSocketOptions;
|
import java.net.StandardSocketOptions;
|
||||||
import java.net.UnknownHostException;
|
|
||||||
import java.nio.channels.SocketChannel;
|
import java.nio.channels.SocketChannel;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -15,8 +12,8 @@ public class SocketToSocketProxy extends Proxy {
|
|||||||
private SocketListener sl;
|
private SocketListener sl;
|
||||||
private SocketChannelListener scl;
|
private SocketChannelListener scl;
|
||||||
private DatagramSocketListener dsl;
|
private DatagramSocketListener dsl;
|
||||||
private MultipurposeSocketAddress listen, cbind, defaultConnect;
|
private MultiProtocolSocketAddress listen, cbind, defaultConnect;
|
||||||
private Map<String, MultipurposeSocketAddress> detectedConnect;
|
private Map<String, MultiProtocolSocketAddress> detectedConnect;
|
||||||
private SocketBridgeFactory defaultFactory;
|
private SocketBridgeFactory defaultFactory;
|
||||||
private SocketChannelBridgeFactory defaultChannelFactory;
|
private SocketChannelBridgeFactory defaultChannelFactory;
|
||||||
private Map<String, SocketBridgeFactory> detectedFactory;
|
private Map<String, SocketBridgeFactory> detectedFactory;
|
||||||
@@ -30,28 +27,28 @@ public class SocketToSocketProxy extends Proxy {
|
|||||||
this.defaultSoTimeout = defaultSoTimeout;
|
this.defaultSoTimeout = defaultSoTimeout;
|
||||||
}
|
}
|
||||||
|
|
||||||
public SocketToSocketProxy(MultipurposeSocketAddress listen, MultipurposeSocketAddress connect) throws IOException {
|
public SocketToSocketProxy(MultiProtocolSocketAddress listen, MultiProtocolSocketAddress connect) throws IOException {
|
||||||
this(listen, new MultipurposeSocketAddress(new InetSocketAddress(0)), connect);
|
this(listen, new MultiProtocolSocketAddress(new InetSocketAddress(0)), connect);
|
||||||
}
|
}
|
||||||
|
|
||||||
public SocketToSocketProxy(String l, String r) throws IOException {
|
public SocketToSocketProxy(String l, String r) throws IOException {
|
||||||
this(new MultipurposeSocketAddress(l), new MultipurposeSocketAddress(r));
|
this(new MultiProtocolSocketAddress(l), new MultiProtocolSocketAddress(r));
|
||||||
}
|
}
|
||||||
|
|
||||||
public SocketToSocketProxy(MultipurposeSocketAddress listen, MultipurposeSocketAddress cbind,
|
public SocketToSocketProxy(MultiProtocolSocketAddress listen, MultiProtocolSocketAddress cbind,
|
||||||
MultipurposeSocketAddress defaultConnect, Map<String, MultipurposeSocketAddress> detectedConnect)
|
MultiProtocolSocketAddress defaultConnect, Map<String, MultiProtocolSocketAddress> detectedConnect)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
this(listen,cbind,defaultConnect,detectedConnect,new DefaultSocketBridgeFactory(),null);
|
this(listen,cbind,defaultConnect,detectedConnect,new DefaultSocketBridgeFactory(),null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public SocketToSocketProxy(MultipurposeSocketAddress listen, MultipurposeSocketAddress cbind,
|
public SocketToSocketProxy(MultiProtocolSocketAddress listen, MultiProtocolSocketAddress cbind,
|
||||||
MultipurposeSocketAddress defaultConnect, Map<String, MultipurposeSocketAddress> detectedConnect,SocketBridgeFactory defaultFactory,Map<String, SocketBridgeFactory> detectedFactory)
|
MultiProtocolSocketAddress defaultConnect, Map<String, MultiProtocolSocketAddress> detectedConnect, SocketBridgeFactory defaultFactory, Map<String, SocketBridgeFactory> detectedFactory)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
this(listen, cbind, defaultConnect, detectedConnect, defaultFactory, detectedFactory, new DefaultSocketChannelBridgeFactory());
|
this(listen, cbind, defaultConnect, detectedConnect, defaultFactory, detectedFactory, new DefaultSocketChannelBridgeFactory());
|
||||||
}
|
}
|
||||||
|
|
||||||
public SocketToSocketProxy(MultipurposeSocketAddress listen, MultipurposeSocketAddress cbind,
|
public SocketToSocketProxy(MultiProtocolSocketAddress listen, MultiProtocolSocketAddress cbind,
|
||||||
MultipurposeSocketAddress defaultConnect, Map<String, MultipurposeSocketAddress> detectedConnect,SocketBridgeFactory defaultFactory,Map<String, SocketBridgeFactory> detectedFactory,SocketChannelBridgeFactory defaultChannelFactory)
|
MultiProtocolSocketAddress defaultConnect, Map<String, MultiProtocolSocketAddress> detectedConnect, SocketBridgeFactory defaultFactory, Map<String, SocketBridgeFactory> detectedFactory, SocketChannelBridgeFactory defaultChannelFactory)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
this.listen = listen;
|
this.listen = listen;
|
||||||
this.cbind = cbind;
|
this.cbind = cbind;
|
||||||
@@ -66,8 +63,8 @@ public class SocketToSocketProxy extends Proxy {
|
|||||||
open();
|
open();
|
||||||
}
|
}
|
||||||
|
|
||||||
public SocketToSocketProxy(MultipurposeSocketAddress listen, MultipurposeSocketAddress cbind,
|
public SocketToSocketProxy(MultiProtocolSocketAddress listen, MultiProtocolSocketAddress cbind,
|
||||||
MultipurposeSocketAddress defaultConnect) throws IOException {
|
MultiProtocolSocketAddress defaultConnect) throws IOException {
|
||||||
this(listen, cbind, defaultConnect,null);
|
this(listen, cbind, defaultConnect,null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,7 +109,7 @@ public class SocketToSocketProxy extends Proxy {
|
|||||||
ProtocolStack ps = ((ProtocolDetectorSocket) sox).getProtocolStack();
|
ProtocolStack ps = ((ProtocolDetectorSocket) sox).getProtocolStack();
|
||||||
if (!ps.isEmpty()) {
|
if (!ps.isEmpty()) {
|
||||||
String pname=ps.pop().getName();
|
String pname=ps.pop().getName();
|
||||||
MultipurposeSocketAddress pmsa = detectedConnect.get(pname);
|
MultiProtocolSocketAddress pmsa = detectedConnect.get(pname);
|
||||||
if(pmsa!=null) {
|
if(pmsa!=null) {
|
||||||
sk = pmsa.connectSocket(InetAddress.getByName(cbind.getHost()), cbind.getPort());
|
sk = pmsa.connectSocket(InetAddress.getByName(cbind.getHost()), cbind.getPort());
|
||||||
}else {
|
}else {
|
||||||
@@ -178,19 +175,19 @@ public class SocketToSocketProxy extends Proxy {
|
|||||||
sb.run();
|
sb.run();
|
||||||
}
|
}
|
||||||
|
|
||||||
public MultipurposeSocketAddress getListen() {
|
public MultiProtocolSocketAddress getListen() {
|
||||||
return listen;
|
return listen;
|
||||||
}
|
}
|
||||||
|
|
||||||
public MultipurposeSocketAddress getCbind() {
|
public MultiProtocolSocketAddress getCbind() {
|
||||||
return cbind;
|
return cbind;
|
||||||
}
|
}
|
||||||
|
|
||||||
public MultipurposeSocketAddress getDefaultConnect() {
|
public MultiProtocolSocketAddress getDefaultConnect() {
|
||||||
return defaultConnect;
|
return defaultConnect;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, MultipurposeSocketAddress> getDetectedConnect() {
|
public Map<String, MultiProtocolSocketAddress> getDetectedConnect() {
|
||||||
return detectedConnect;
|
return detectedConnect;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ public class SocketType {
|
|||||||
private DatagramSocketFactory datagramSocketFactory;
|
private DatagramSocketFactory datagramSocketFactory;
|
||||||
private DatagramServerSocketFactory datagramServerSocketFactory;
|
private DatagramServerSocketFactory datagramServerSocketFactory;
|
||||||
private boolean stream;
|
private boolean stream;
|
||||||
|
private int defaultPort=-1;
|
||||||
|
|
||||||
public SocketFactory Channel() {
|
public SocketFactory Channel() {
|
||||||
return socketFactory;
|
return socketFactory;
|
||||||
@@ -74,5 +75,7 @@ public class SocketType {
|
|||||||
return stream;
|
return stream;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public int getDefaultPort(){
|
||||||
|
return defaultPort;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package org.kne.cloud.network;
|
||||||
|
|
||||||
|
public class TCPSocketType extends SocketType {
|
||||||
|
private static final TCPSocketType INSTANCE = new TCPSocketType();
|
||||||
|
|
||||||
|
private TCPSocketType() {
|
||||||
|
super(
|
||||||
|
new DefaultSocketFactory(),
|
||||||
|
new DefaultServerSocketFactory(),
|
||||||
|
new DefaultSocketChannelFactory(),
|
||||||
|
new DefaultServerSocketChannelFactory()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TCPSocketType getInstance() {
|
||||||
|
return INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isStream() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package org.kne.cloud.network;
|
||||||
|
|
||||||
|
public class UDPSocketType extends SocketType {
|
||||||
|
private static final UDPSocketType INSTANCE = new UDPSocketType();
|
||||||
|
|
||||||
|
protected UDPSocketType() {
|
||||||
|
super(
|
||||||
|
new DefaultDatagramSocketFactory(),
|
||||||
|
new DefaultDatagramServerSocketFactory()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static UDPSocketType getInstance() {
|
||||||
|
return INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isStream() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,14 +11,13 @@ public class BBRCongestionAlgorithm implements CongestionAlgorithm ,DetnetConges
|
|||||||
|
|
||||||
private Consumer<Long> windowControlConsumer;
|
private Consumer<Long> windowControlConsumer;
|
||||||
|
|
||||||
private long MIN_RTTVAR = 5000000L;
|
|
||||||
private volatile long RTTMin = 1000000000L;
|
private volatile long RTTMin = 1000000000L;
|
||||||
private volatile long RTTVar = 1000000000L;
|
|
||||||
private volatile long RTTAvg = 1000000000L;
|
|
||||||
private volatile long RTTAvg2 = 1000000000L;
|
private volatile long RTTAvg2 = 1000000000L;
|
||||||
private volatile long RTTTotal = 0;
|
private volatile long RTTTotal = 0;
|
||||||
private volatile long RTTCount = 0;
|
private volatile long RTTCount = 0;
|
||||||
private volatile long RTO = 1000000000L;
|
|
||||||
|
|
||||||
|
private RTTEstimator rttEstimator=new RTTEstimator();
|
||||||
|
|
||||||
|
|
||||||
private volatile long window=MIN_WINDOW;
|
private volatile long window=MIN_WINDOW;
|
||||||
@@ -54,10 +53,7 @@ public class BBRCongestionAlgorithm implements CongestionAlgorithm ,DetnetConges
|
|||||||
} else {
|
} else {
|
||||||
RTTMin = (RTTMin * 99999 + latencyns) / 100000;
|
RTTMin = (RTTMin * 99999 + latencyns) / 100000;
|
||||||
}
|
}
|
||||||
RTTVar = (RTTVar * 3 + Math.abs(RTTAvg - latencyns)) / 4;
|
rttEstimator.putRTT(latencyns);
|
||||||
RTTAvg = (RTTAvg * 7 + latencyns) / 8;
|
|
||||||
|
|
||||||
RTO = RTTAvg + Math.max(MIN_RTTVAR, RTTVar * 4);// RTTVar*4
|
|
||||||
|
|
||||||
RTTTotal += latencyns;
|
RTTTotal += latencyns;
|
||||||
RTTCount++;
|
RTTCount++;
|
||||||
@@ -93,13 +89,13 @@ public class BBRCongestionAlgorithm implements CongestionAlgorithm ,DetnetConges
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void putLoss(long packetSize, long lossns, int losscounter) {
|
public void putLoss(long packetSize, long lossns) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public long getRTO() {
|
public long getRTO() {
|
||||||
return RTO;
|
return rttEstimator.getRTO();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -136,4 +132,29 @@ public class BBRCongestionAlgorithm implements CongestionAlgorithm ,DetnetConges
|
|||||||
return "BBR";
|
return "BBR";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long getBaseRTT() {
|
||||||
|
return rttEstimator.getBaseRTT();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long getCurrentRTT() {
|
||||||
|
return rttEstimator.getCurrentRTT();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getUpperDelayBound() {
|
||||||
|
return MAX_GAIN;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getLowerDelayBound() {
|
||||||
|
return MIN_GAIN;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getBurstLimit() {
|
||||||
|
return burstLimit;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ public interface CongestionAlgorithm {
|
|||||||
public void reset();
|
public void reset();
|
||||||
public void setWindowControlConsumer(Consumer<Long>windowControlConsumer);
|
public void setWindowControlConsumer(Consumer<Long>windowControlConsumer);
|
||||||
public void putAck(long packetSize,long RTTns,boolean ecn);
|
public void putAck(long packetSize,long RTTns,boolean ecn);
|
||||||
default public void putAck(long packetSize,long RTTns,long OWDup,boolean ecn) {
|
public void putLoss(long packetSize,long lossns);
|
||||||
putAck(packetSize,RTTns,ecn);
|
|
||||||
}
|
|
||||||
public void putLoss(long packetSize,long lossns,int losscounter);
|
|
||||||
public void setCurrentWindowUsed(long maxwindow);
|
public void setCurrentWindowUsed(long maxwindow);
|
||||||
public void setCurrentBandwidth(long bandwidth);
|
public void setCurrentBandwidth(long bandwidth);
|
||||||
public long getRTO();
|
public long getRTO();
|
||||||
public String getName();
|
public String getName();
|
||||||
|
|
||||||
|
public long getBaseRTT();
|
||||||
|
|
||||||
|
public long getCurrentRTT();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,126 +0,0 @@
|
|||||||
package org.kne.cloud.network.congestion;
|
|
||||||
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
import org.jctools.counters.FixedSizeStripedLongCounter;
|
|
||||||
import org.kne.cloud.network.klalb.KLALBUtils;
|
|
||||||
|
|
||||||
public class DCTCP2CongestionAlgorithm implements CongestionAlgorithm {
|
|
||||||
|
|
||||||
private static final long BURST_TIME = 1000000L;
|
|
||||||
private static final long BIAS = 2000000L;
|
|
||||||
private static long MIN_WINDOW = 8192;
|
|
||||||
|
|
||||||
private Consumer<Long> windowControlConsumer;
|
|
||||||
|
|
||||||
private long MIN_RTTVAR = 100000000L;
|
|
||||||
private volatile long RTTVar = 1000000000L;
|
|
||||||
private volatile long RTTAvg = 1000000000L;
|
|
||||||
private double ECNAvg2 = 0L;
|
|
||||||
private double alpha=0;
|
|
||||||
private volatile FixedSizeStripedLongCounter ECNSize = KLALBUtils.createCounter();
|
|
||||||
private volatile FixedSizeStripedLongCounter TotalSize = KLALBUtils.createCounter();
|
|
||||||
private volatile long RTO = 500000000L;
|
|
||||||
|
|
||||||
|
|
||||||
private volatile long window=MIN_WINDOW;
|
|
||||||
private volatile long maxwindow = 99999999999L;
|
|
||||||
private volatile long congressWindowSize=MIN_WINDOW;
|
|
||||||
|
|
||||||
private long RTTstartTime = System.nanoTime();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void reset() {
|
|
||||||
window = MIN_WINDOW;
|
|
||||||
if (windowControlConsumer != null) {
|
|
||||||
windowControlConsumer.accept(window);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setWindowControlConsumer(Consumer<Long> windowControlConsumer) {
|
|
||||||
this.windowControlConsumer = windowControlConsumer;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public synchronized void putAck(long packetSize, long latencyns, boolean ecn) {
|
|
||||||
|
|
||||||
|
|
||||||
RTTVar = (RTTVar * 3 + Math.abs(RTTAvg - latencyns)) / 4;
|
|
||||||
RTTAvg = (RTTAvg * 7 + latencyns) / 8;
|
|
||||||
|
|
||||||
RTO = RTTAvg + Math.max(MIN_RTTVAR, RTTVar * 4);// RTTVar*4
|
|
||||||
|
|
||||||
if(ecn) {
|
|
||||||
ECNSize.inc(packetSize);
|
|
||||||
}
|
|
||||||
TotalSize.inc(packetSize);
|
|
||||||
|
|
||||||
|
|
||||||
long curr=System.nanoTime();
|
|
||||||
if(curr-RTTstartTime>(RTTAvg+BIAS)) {
|
|
||||||
RTTstartTime=curr;
|
|
||||||
|
|
||||||
long totalSize=TotalSize.getAndReset();
|
|
||||||
long ecnSize=ECNSize.getAndReset();
|
|
||||||
if(totalSize!=0) {
|
|
||||||
ECNAvg2=ecnSize/(double)totalSize;
|
|
||||||
alpha=(alpha*7+ECNAvg2)/8;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(ECNAvg2>0.5) {
|
|
||||||
congressWindowSize-=200;
|
|
||||||
}else if(ECNAvg2>0.01){
|
|
||||||
congressWindowSize+=200;
|
|
||||||
}else {
|
|
||||||
congressWindowSize+=4000;
|
|
||||||
}
|
|
||||||
//System.out.println(ECNAvg2);
|
|
||||||
//System.out.println(speed+" "+window);
|
|
||||||
|
|
||||||
updateWindowSize();
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updateWindowSize() {
|
|
||||||
if(congressWindowSize<MIN_WINDOW) {
|
|
||||||
congressWindowSize=MIN_WINDOW;
|
|
||||||
}else if(congressWindowSize>maxwindow) {
|
|
||||||
congressWindowSize=maxwindow;
|
|
||||||
}
|
|
||||||
window=Math.max( congressWindowSize,MIN_WINDOW);
|
|
||||||
if (windowControlConsumer != null) {
|
|
||||||
windowControlConsumer.accept(window);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void putLoss(long packetSize, long lossns, int losscounter) {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public long getRTO() {
|
|
||||||
return RTO;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setCurrentWindowUsed(long used) {
|
|
||||||
this.maxwindow=(long) (used*1.5)+MIN_WINDOW;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setCurrentBandwidth(long bandwidth) {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getName() {
|
|
||||||
return "DCTCP2";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -13,16 +13,13 @@ public class DCTCPCongestionAlgorithm implements CongestionAlgorithm {
|
|||||||
|
|
||||||
private Consumer<Long> windowControlConsumer;
|
private Consumer<Long> windowControlConsumer;
|
||||||
|
|
||||||
private AtomicBoolean firstUpdate = new AtomicBoolean(true);
|
|
||||||
private long MIN_RTTVAR = 100000000L;
|
|
||||||
private volatile long RTTMin = 1000000000L;
|
private volatile long RTTMin = 1000000000L;
|
||||||
private volatile long RTTVar = 1000000000L;
|
|
||||||
private volatile long RTTAvg = 1000000000L;
|
|
||||||
private double ECNAvg2 = 0L;
|
private double ECNAvg2 = 0L;
|
||||||
private double alpha=0;
|
private double alpha=0;
|
||||||
private volatile AtomicLong ECNSize = new AtomicLong(0);
|
private volatile AtomicLong ECNSize = new AtomicLong(0);
|
||||||
private volatile AtomicLong TotalSize = new AtomicLong(0);
|
private volatile AtomicLong TotalSize = new AtomicLong(0);
|
||||||
private volatile long RTO = 1000000000L;
|
|
||||||
|
private RTTEstimator rttEstimator=new RTTEstimator(100000000L);
|
||||||
|
|
||||||
|
|
||||||
private volatile long window=MIN_WINDOW;
|
private volatile long window=MIN_WINDOW;
|
||||||
@@ -54,14 +51,7 @@ public class DCTCPCongestionAlgorithm implements CongestionAlgorithm {
|
|||||||
} else {
|
} else {
|
||||||
RTTMin = (RTTMin * 99999 + latencyns) / 100000;
|
RTTMin = (RTTMin * 99999 + latencyns) / 100000;
|
||||||
}
|
}
|
||||||
if (firstUpdate.compareAndSet(true, false)) {
|
rttEstimator.putRTT(latencyns);
|
||||||
RTTAvg = latencyns;
|
|
||||||
RTTVar = latencyns / 2;
|
|
||||||
} else {
|
|
||||||
RTTVar = (RTTVar * 3 + Math.abs(RTTAvg - latencyns)) / 4;
|
|
||||||
RTTAvg = (RTTAvg * 7 + latencyns) / 8;
|
|
||||||
}
|
|
||||||
RTO = RTTAvg + Math.max(MIN_RTTVAR, RTTVar * 4);// RTTVar*4
|
|
||||||
|
|
||||||
if(ecn) {
|
if(ecn) {
|
||||||
ECNSize.addAndGet(packetSize);
|
ECNSize.addAndGet(packetSize);
|
||||||
@@ -88,7 +78,7 @@ public class DCTCPCongestionAlgorithm implements CongestionAlgorithm {
|
|||||||
}
|
}
|
||||||
}else {
|
}else {
|
||||||
if(windowUsed*3L>=congressWindowSize) {
|
if(windowUsed*3L>=congressWindowSize) {
|
||||||
congressWindowSize+=4000;
|
congressWindowSize+=4096;
|
||||||
updateWindowSize();
|
updateWindowSize();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -109,13 +99,13 @@ public class DCTCPCongestionAlgorithm implements CongestionAlgorithm {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void putLoss(long packetSize, long lossns, int losscounter) {
|
public void putLoss(long packetSize, long lossns) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public long getRTO() {
|
public long getRTO() {
|
||||||
return RTO;
|
return rttEstimator.getRTO();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -133,6 +123,15 @@ public class DCTCPCongestionAlgorithm implements CongestionAlgorithm {
|
|||||||
return "DCTCP";
|
return "DCTCP";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long getBaseRTT() {
|
||||||
|
return rttEstimator.getBaseRTT();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long getCurrentRTT() {
|
||||||
|
return rttEstimator.getCurrentRTT();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,4 +4,7 @@ public interface DetnetCongestionAlgorithm extends CongestionAlgorithm {
|
|||||||
public void setUpperDelayBound(double upper);
|
public void setUpperDelayBound(double upper);
|
||||||
public void setLowerDelayBound(double lower);
|
public void setLowerDelayBound(double lower);
|
||||||
public void setBurstLimit(double limit);
|
public void setBurstLimit(double limit);
|
||||||
|
public double getUpperDelayBound( );
|
||||||
|
public double getLowerDelayBound();
|
||||||
|
public double getBurstLimit();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ public class NOCongestionAlgorithm implements CongestionAlgorithm{
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void putLoss(long packetSize, long lossns, int losscounter) {
|
public void putLoss(long packetSize, long lossns) {
|
||||||
// TODO 自动生成的方法存根
|
// TODO 自动生成的方法存根
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -63,4 +63,14 @@ public class NOCongestionAlgorithm implements CongestionAlgorithm{
|
|||||||
return "NO";
|
return "NO";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long getBaseRTT() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long getCurrentRTT() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
package org.kne.cloud.network.congestion;
|
||||||
|
|
||||||
|
import org.kne.cloud.clock.HighAccuracyClock;
|
||||||
|
import org.kne.cloud.network.klalb.KLALBUtils;
|
||||||
|
import org.kne.cloud.network.monitor.ArrayListTimestampMonitor;
|
||||||
|
import org.kne.cloud.network.monitor.DelaySampler;
|
||||||
|
import org.kne.cloud.network.monitor.TimestampMonitor;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 线程安全的 RTT 平滑与 RTO 计算工具。
|
||||||
|
* 基于 RFC 6298 的 Jacobson/Karels 算法。
|
||||||
|
*
|
||||||
|
* 公式:
|
||||||
|
* RTTAvg = (RTTAvg * 7 + RTTns) / 8
|
||||||
|
* RTTVar = (RTTVar * 3 + |RTTAvg - RTTns|) / 4
|
||||||
|
* RTO = RTTAvg + max(MIN_RTTVAR, RTTVar * 4)
|
||||||
|
*/
|
||||||
|
public class RTTEstimator {
|
||||||
|
|
||||||
|
/** RTTVar 下限(纳秒),防止 RTO 过小。默认 20ms。 */
|
||||||
|
private static final long DEFAULT_MIN_RTTVAR_NS = 20_000_000L;
|
||||||
|
|
||||||
|
private final AtomicLong curr;
|
||||||
|
private final AtomicLong rttAvg;
|
||||||
|
private final AtomicLong rttVar;
|
||||||
|
private final AtomicLong rto;
|
||||||
|
private final AtomicLong basertt;
|
||||||
|
private final AtomicBoolean firstUpdate = new AtomicBoolean(true); // 首次标记
|
||||||
|
private final long minRttVarNs;
|
||||||
|
|
||||||
|
|
||||||
|
private long timewindowmax=500000000L;
|
||||||
|
|
||||||
|
long stime=System.nanoTime();
|
||||||
|
|
||||||
|
public RTTEstimator() {
|
||||||
|
this(DEFAULT_MIN_RTTVAR_NS);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RTTEstimator(long minRttVarNs) {
|
||||||
|
this.rttAvg = new AtomicLong(1000000000L);
|
||||||
|
this.rttVar = new AtomicLong(1000000000L);
|
||||||
|
this.curr = new AtomicLong(1000000000L);
|
||||||
|
this.rto = new AtomicLong(1000000000L);
|
||||||
|
this.basertt = new AtomicLong(1000000000L);
|
||||||
|
this.minRttVarNs = minRttVarNs;
|
||||||
|
}
|
||||||
|
private final static long TIME_WINDOW=30000000000L;
|
||||||
|
private final TimestampMonitor<UUID> rttMonitor=new ArrayListTimestampMonitor<UUID>(new HighAccuracyClock(),"RTTMonitor", 100, TIME_WINDOW);
|
||||||
|
private final DelaySampler dsp=new DelaySampler();
|
||||||
|
|
||||||
|
public void update() {
|
||||||
|
dsp.update();
|
||||||
|
|
||||||
|
if(dsp.getSnapshotPacketCount()>0&&dsp.getSnapshotTotalDelay()>0) {
|
||||||
|
rttMonitor. recordPacket(KLALBUtils.createGlobalUUID(),0, 0, dsp.getAvgDelayNanos(),dsp.getMinDelayNanos());
|
||||||
|
}
|
||||||
|
|
||||||
|
long time=System.nanoTime();
|
||||||
|
if(time-stime>timewindowmax) {
|
||||||
|
basertt.lazySet( rttMonitor.calculateMinDelay(TIME_WINDOW));
|
||||||
|
stime=time;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 更新 RTT 估算值(线程安全)。
|
||||||
|
*
|
||||||
|
* @param rttNs 本次 RTT 测量值(纳秒)
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* 更新 RTT 估算值(线程安全,无锁)。
|
||||||
|
*/
|
||||||
|
public void putRTT(long rttNs) {
|
||||||
|
if (rttNs < 0) {
|
||||||
|
throw new IllegalArgumentException("RTT 不能为负数: " + rttNs);
|
||||||
|
}
|
||||||
|
dsp.recordDelay(rttNs);
|
||||||
|
curr.lazySet(rttNs);
|
||||||
|
// 首次更新:CAS 成功则直接初始化,无锁
|
||||||
|
if (firstUpdate.compareAndSet(true, false)) {
|
||||||
|
rttAvg.set(rttNs);
|
||||||
|
rttVar.set(rttNs / 2);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 后续更新:CAS 循环保证原子性
|
||||||
|
|
||||||
|
long oldAvg = rttAvg.get();
|
||||||
|
long newAvg = (oldAvg * 7 + rttNs) / 8;
|
||||||
|
|
||||||
|
long delta = Math.abs(oldAvg - rttNs);
|
||||||
|
rttAvg.lazySet(newAvg);
|
||||||
|
long oldVar = rttVar.get();
|
||||||
|
long newVar = (oldVar * 3 + delta) / 4;
|
||||||
|
rttVar.lazySet(newVar);
|
||||||
|
|
||||||
|
rto .lazySet( newAvg + Math.max(minRttVarNs, newVar * 4));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取平滑 RTT 平均值(纳秒)。
|
||||||
|
*/
|
||||||
|
public long getRTTAvg() {
|
||||||
|
return rttAvg.getPlain();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取 RTT 偏差(纳秒)。
|
||||||
|
*/
|
||||||
|
public long getRTTVar() {
|
||||||
|
return rttVar.getPlain();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取 RTO(重传超时时间,纳秒)。
|
||||||
|
* RTO = RTTAvg + max(MIN_RTTVAR, RTTVar * 4)
|
||||||
|
*/
|
||||||
|
public long getRTO() {
|
||||||
|
return rto.getPlain();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 重置估算器(用于连接重建等场景)。
|
||||||
|
*/
|
||||||
|
public void reset() {
|
||||||
|
rttAvg.set(0);
|
||||||
|
rttVar.set(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return String.format("RttEstimator{avg=%.3fms, var=%.3fms, rto=%.3fms}",
|
||||||
|
rttAvg.get() / 1_000_000.0,
|
||||||
|
rttVar.get() / 1_000_000.0,
|
||||||
|
getRTO() / 1_000_000.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getCurrentRTT() {
|
||||||
|
return curr.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getBaseRTT() {
|
||||||
|
return basertt.get();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,10 @@ import java.net.SocketException;
|
|||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.ScheduledFuture;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
import java.util.concurrent.locks.Condition;
|
import java.util.concurrent.locks.Condition;
|
||||||
import java.util.concurrent.locks.Lock;
|
import java.util.concurrent.locks.Lock;
|
||||||
@@ -13,13 +16,15 @@ import java.util.function.Consumer;
|
|||||||
|
|
||||||
import org.kne.cloud.network.NetworkPacket;
|
import org.kne.cloud.network.NetworkPacket;
|
||||||
import org.kne.cloud.network.ThreadTool;
|
import org.kne.cloud.network.ThreadTool;
|
||||||
|
import org.kne.cloud.network.klalb.KLALBScheduler;
|
||||||
import org.kne.cloud.network.klalb.SendItem;
|
import org.kne.cloud.network.klalb.SendItem;
|
||||||
import org.kne.concurrent.ThreadParker;
|
import org.kne.concurrent.ThreadParker;
|
||||||
|
|
||||||
public class SendPacketSlidingWindow<K, V extends NetworkPacket> implements Closeable, AutoCloseable {
|
public class SendPacketSlidingWindow<K, V extends NetworkPacket> implements Closeable, AutoCloseable {
|
||||||
|
private final ScheduledFuture<?> checkerTask;
|
||||||
private ThreadParker tp=new ThreadParker();
|
private ThreadParker tp=new ThreadParker();
|
||||||
|
|
||||||
private Map<K, SendItem<V>> sendMap = new ConcurrentHashMap<>(2048);
|
private volatile Map<K, SendItem<V>> sendMap = new ConcurrentHashMap<>(2048);
|
||||||
private AtomicLong sendWindowUsed=new AtomicLong(0);
|
private AtomicLong sendWindowUsed=new AtomicLong(0);
|
||||||
//private LongAdder sendWindowUsed = new LongAdder();
|
//private LongAdder sendWindowUsed = new LongAdder();
|
||||||
|
|
||||||
@@ -51,13 +56,12 @@ public class SendPacketSlidingWindow<K, V extends NetworkPacket> implements Clos
|
|||||||
}
|
}
|
||||||
|
|
||||||
public SendPacketSlidingWindow(CongestionAlgorithm algorithm, long windowSize, int headerCalibrate,
|
public SendPacketSlidingWindow(CongestionAlgorithm algorithm, long windowSize, int headerCalibrate,
|
||||||
boolean removeAtResend) {
|
boolean removeAtResend) {
|
||||||
this.headerCalibrate = headerCalibrate;
|
this.headerCalibrate = headerCalibrate;
|
||||||
this.removeAtResend = removeAtResend;
|
this.removeAtResend = removeAtResend;
|
||||||
this.algorithm = algorithm;
|
this.algorithm = algorithm;
|
||||||
this.windowSize=windowSize;
|
this.windowSize=windowSize;
|
||||||
Thread t = ThreadTool.makeVThread("重路由计时器线程", checker);
|
this.checkerTask=KLALBScheduler.getScheduler().scheduleWithFixedDelay(checker,1,1, TimeUnit.MILLISECONDS);
|
||||||
t.start();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public long getWindowSize() {
|
public long getWindowSize() {
|
||||||
@@ -106,7 +110,7 @@ public class SendPacketSlidingWindow<K, V extends NetworkPacket> implements Clos
|
|||||||
boolean congress = sendWindowUsed.get() > windowSize ;
|
boolean congress = sendWindowUsed.get() > windowSize ;
|
||||||
return congress;
|
return congress;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void waitForAvaliable() throws SocketException {
|
public void waitForAvaliable() throws SocketException {
|
||||||
while(isCongestion()) {
|
while(isCongestion()) {
|
||||||
if(closed) {
|
if(closed) {
|
||||||
@@ -119,28 +123,27 @@ public class SendPacketSlidingWindow<K, V extends NetworkPacket> implements Clos
|
|||||||
waitForAvaliable();
|
waitForAvaliable();
|
||||||
put(sequence,packet);
|
put(sequence,packet);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void put(K sequence, V packet) {
|
public void put(K sequence, V packet) {
|
||||||
SendItem<V> newitem = new SendItem<V>(packet,headerCalibrate);
|
SendItem<V> newitem = new SendItem<V>(packet,headerCalibrate);
|
||||||
SendItem<V> old = sendMap.put(sequence, newitem);
|
SendItem<V> old = sendMap.put(sequence, newitem);
|
||||||
long dx=0;
|
long dx=0;
|
||||||
if (old != null) {
|
if (old != null) {
|
||||||
dx=-old.getPacketLength() ;
|
dx=-old.getPacketLength() ;
|
||||||
}
|
}
|
||||||
long newWindow =sendWindowUsed.addAndGet(newitem.getPacketLength() +dx);
|
long newWindow =sendWindowUsed.addAndGet(newitem.getPacketLength() +dx);
|
||||||
algorithm.setCurrentWindowUsed(newWindow);
|
algorithm.setCurrentWindowUsed(newWindow);
|
||||||
}
|
}
|
||||||
public V ack(K sequence) {
|
public V ack(K sequence) {
|
||||||
return ack(sequence,false);
|
return ack(sequence,0,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public V ack(K sequence,boolean ecn) {
|
public V ack(K sequence,long RTTns,boolean ecn) {
|
||||||
SendItem<V> ipv6;
|
SendItem<V> ipv6;
|
||||||
if ((ipv6 = sendMap.remove(sequence)) != null) {
|
if ((ipv6 = sendMap.remove(sequence)) != null) {
|
||||||
long newWindow =sendWindowUsed.addAndGet(-ipv6.getPacketLength() );
|
long newWindow =sendWindowUsed.addAndGet(-ipv6.getPacketLength() );
|
||||||
algorithm.setCurrentWindowUsed(newWindow);
|
algorithm.setCurrentWindowUsed(newWindow);
|
||||||
long RTTC = System.nanoTime() - ipv6.getSendtime();
|
algorithm.putAck(ipv6.getPacketLength(), RTTns, ecn);
|
||||||
algorithm.putAck(ipv6.getPacketLength(), RTTC, ecn);
|
|
||||||
tp.unpark();
|
tp.unpark();
|
||||||
// System.out.println("remove:"+aseq.getSequence()+" "+sendMap.size());
|
// System.out.println("remove:"+aseq.getSequence()+" "+sendMap.size());
|
||||||
Lock lockx = lock;
|
Lock lockx = lock;
|
||||||
@@ -162,73 +165,59 @@ public class SendPacketSlidingWindow<K, V extends NetworkPacket> implements Clos
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public V ack(K sequence,boolean ecn,long OWDdown) {
|
|
||||||
SendItem<V> ipv6;
|
|
||||||
if ((ipv6 = sendMap.remove(sequence)) != null) {
|
|
||||||
long newWindow =sendWindowUsed.addAndGet(-ipv6.getPacketLength() );
|
|
||||||
algorithm.setCurrentWindowUsed(newWindow);
|
|
||||||
long RTTC = System.nanoTime() - ipv6.getSendtime();
|
|
||||||
algorithm.putAck(ipv6.getPacketLength(), RTTC,OWDdown, ecn);
|
|
||||||
tp.unpark();
|
|
||||||
// System.out.println("remove:"+aseq.getSequence()+" "+sendMap.size());
|
|
||||||
Lock lockx = lock;
|
|
||||||
if (lockx != null) {
|
|
||||||
lockx.lock();
|
|
||||||
try {
|
|
||||||
Condition cds = condition;
|
|
||||||
if (cds != null) {
|
|
||||||
cds.signalAll();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
lockx.unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ipv6.getPacket();
|
|
||||||
} else {
|
|
||||||
// System.out.println("miss:"+aseq.getSequence()+" "+sendMap.size());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private class ResendChecker implements Runnable {
|
private class ResendChecker implements Runnable {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while (!closed) {
|
try {
|
||||||
|
if (closed) {
|
||||||
Collection<SendItem<V>> vals = sendMap.values();
|
checkerTask.cancel(false);
|
||||||
for (Iterator<SendItem<V>> iterator = vals.iterator(); iterator.hasNext();) {
|
// 清理资源
|
||||||
SendItem<V> sitm = (SendItem<V>) iterator.next();
|
if (closingConsumer != null) {
|
||||||
long current = System.nanoTime();
|
for (SendItem<V> item : sendMap.values()) {
|
||||||
if (current - sitm.getSendtime() > algorithm.getRTO()) {
|
closingConsumer.accept(item.getPacket());
|
||||||
if (removeAtResend) {
|
|
||||||
iterator.remove();
|
|
||||||
long newWindow = sendWindowUsed.addAndGet((int) -sitm.getPacketLength() );
|
|
||||||
algorithm.setCurrentWindowUsed(newWindow);
|
|
||||||
tp.unpark();
|
|
||||||
} else {
|
|
||||||
sitm.setSendtime(current);
|
|
||||||
}
|
}
|
||||||
V pktr = sitm.getPacket();
|
|
||||||
if (resendConsumer != null)
|
|
||||||
resendConsumer.accept(pktr);
|
|
||||||
}
|
}
|
||||||
}
|
sendMap.clear();
|
||||||
|
sendWindowUsed.set(0);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
|
||||||
|
Set<Map.Entry<K,SendItem<V>>> vals = sendMap.entrySet();
|
||||||
|
for (Iterator<Map.Entry<K,SendItem<V>>> iterator = vals.iterator(); iterator.hasNext(); ) {
|
||||||
|
Map.Entry<K,SendItem<V>> entry = (Map.Entry<K,SendItem<V>>) iterator.next();
|
||||||
|
SendItem<V> sitm=entry.getValue();
|
||||||
|
long current = System.nanoTime();
|
||||||
|
long ftime=current - sitm.getSendtime();
|
||||||
|
if (ftime> algorithm.getRTO()) {
|
||||||
|
|
||||||
|
V pktr = sitm.getPacket();
|
||||||
|
|
||||||
|
if (removeAtResend) {
|
||||||
|
SendItem<V> sitm2=sendMap.remove(entry.getKey());
|
||||||
|
if(sitm2!=null) {
|
||||||
|
if (resendConsumer != null)
|
||||||
|
resendConsumer.accept(pktr);
|
||||||
|
algorithm.putLoss(sitm2.getPacketLength(),ftime);
|
||||||
|
long newWindow = sendWindowUsed.addAndGet((int) -sitm2.getPacketLength());
|
||||||
|
algorithm.setCurrentWindowUsed(newWindow);
|
||||||
|
tp.unpark();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
sitm.setSendtime(current);
|
||||||
|
if (resendConsumer != null)
|
||||||
|
resendConsumer.accept(pktr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
try {
|
|
||||||
Thread.sleep(2);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
// 清理资源
|
|
||||||
if (closingConsumer != null) {
|
|
||||||
for (SendItem<V> item : sendMap.values()) {
|
|
||||||
closingConsumer.accept(item.getPacket());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sendMap.clear();
|
|
||||||
sendWindowUsed.set(0);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,4 +265,4 @@ public class SendPacketSlidingWindow<K, V extends NetworkPacket> implements Clos
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,9 @@ package org.kne.cloud.network.congestion;
|
|||||||
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
import org.kne.cloud.network.monitor.DelaySampler;
|
||||||
|
import org.kne.concurrent.SpinLock;
|
||||||
|
|
||||||
public class Vegas2CongestionAlgorithm implements CongestionAlgorithm,DetnetCongestionAlgorithm {
|
public class Vegas2CongestionAlgorithm implements CongestionAlgorithm,DetnetCongestionAlgorithm {
|
||||||
|
|
||||||
// 可配置的时延膨胀比上下限 - Vegas2.0核心参数
|
// 可配置的时延膨胀比上下限 - Vegas2.0核心参数
|
||||||
@@ -11,29 +14,26 @@ public class Vegas2CongestionAlgorithm implements CongestionAlgorithm,DetnetCong
|
|||||||
|
|
||||||
private static final long BURST_TIME = 2000000L;
|
private static final long BURST_TIME = 2000000L;
|
||||||
private static final long BIAS = 1000000L;
|
private static final long BIAS = 1000000L;
|
||||||
private static long MIN_WINDOW = 16384;
|
private static long MIN_WINDOW = 8192;
|
||||||
|
|
||||||
|
|
||||||
private Consumer<Long> windowControlConsumer;
|
private Consumer<Long> windowControlConsumer;
|
||||||
|
|
||||||
private long MIN_RTTVAR = 30000000L;
|
private volatile long RTTCurr = 1000000000L; // RTT
|
||||||
private volatile long RTTMin = 1000000000L; // BaseRTT
|
private volatile long RTTMin = 1000000000L; // BaseRTT
|
||||||
private volatile long RTTVar = 1000000000L;
|
|
||||||
private volatile long RTTAvg = 1000000000L;
|
|
||||||
private volatile long RTTAvg2 = 1000000000L; // 当前平滑RTT
|
private volatile long RTTAvg2 = 1000000000L; // 当前平滑RTT
|
||||||
private volatile long RTTTotal = 0;
|
private volatile long RTTTotal = 0;
|
||||||
private volatile long RTTCount = 0;
|
private volatile long RTTCount = 0;
|
||||||
private volatile long RTO = 1000000000L;
|
|
||||||
|
|
||||||
|
|
||||||
private volatile long OWDTotal = 0;
|
private RTTEstimator rttEstimator=new RTTEstimator();
|
||||||
private volatile long OWDCount = 0;
|
|
||||||
private volatile long OWDAvg2 = 1000000000L; // 当前平滑OWD
|
|
||||||
private volatile long OWDMin = 1000000000L; // BaseRTT
|
|
||||||
|
|
||||||
private volatile long window = MIN_WINDOW;
|
private volatile long window = MIN_WINDOW;
|
||||||
private volatile long window2 = MIN_WINDOW;
|
private volatile long window2 = MIN_WINDOW;
|
||||||
private volatile long maxwindow = 99999999999L;
|
private volatile long maxwindow = 99999999999L;
|
||||||
|
|
||||||
|
private final SpinLock slock=new SpinLock();
|
||||||
|
|
||||||
public Vegas2CongestionAlgorithm() {
|
public Vegas2CongestionAlgorithm() {
|
||||||
reset();
|
reset();
|
||||||
}
|
}
|
||||||
@@ -58,106 +58,13 @@ public class Vegas2CongestionAlgorithm implements CongestionAlgorithm,DetnetCong
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void putAck(long packetSize, long RTTns, long OWDup, boolean ecn) {
|
|
||||||
if(RTTns<0) {
|
|
||||||
throw new IllegalArgumentException("RTT:"+ RTTns+" is negative!");
|
|
||||||
}
|
|
||||||
// 处理ECN信号 - 将其视为强烈的拥塞信号
|
|
||||||
if (ecn) {
|
|
||||||
// 当收到ECN时,更激进地减少窗口
|
|
||||||
window2 = Math.max(0, window2 * 3 / 4);
|
|
||||||
if (windowControlConsumer != null) {
|
|
||||||
windowControlConsumer.accept(window2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 更新最小RTT(BaseRTT)
|
|
||||||
if (RTTns <= RTTMin) {
|
|
||||||
RTTMin = RTTns;
|
|
||||||
} else {
|
|
||||||
// 缓慢适应:当网络路径真正变化时,BaseRTT应能缓慢更新
|
|
||||||
// 这里使用极慢的衰减因子,只有在持续观测到更低RTT时才快速更新
|
|
||||||
RTTMin = (RTTMin * 999 + RTTns) / 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 更新最小OWD(BaseOWD)
|
|
||||||
if (OWDup <= OWDMin) {
|
|
||||||
OWDMin = OWDup;
|
|
||||||
} else {
|
|
||||||
// 缓慢适应:当网络路径真正变化时,BaseRTT应能缓慢更新
|
|
||||||
// 这里使用极慢的衰减因子,只有在持续观测到更低RTT时才快速更新
|
|
||||||
OWDMin = (OWDMin * 999 + OWDup) / 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 更新平滑RTT估计
|
|
||||||
|
|
||||||
RTTVar = (RTTVar * 3 + Math.abs(RTTAvg - RTTns)) / 4;
|
|
||||||
RTTAvg = (RTTAvg * 7 + RTTns) / 8;
|
|
||||||
|
|
||||||
|
|
||||||
RTO = RTTAvg + Math.max(MIN_RTTVAR, RTTVar * 4);
|
|
||||||
|
|
||||||
RTTTotal += RTTns;
|
|
||||||
RTTCount++;
|
|
||||||
|
|
||||||
OWDTotal += OWDup;
|
|
||||||
OWDCount++;
|
|
||||||
|
|
||||||
long curr = System.nanoTime();
|
|
||||||
// 每个RTT周期调整一次窗口(使用当前估计的RTT)
|
|
||||||
if (curr - RTTstartTime > Math.max(BIAS, 2*RTTMin)) {
|
|
||||||
long RTTCountx=RTTCount;
|
|
||||||
if (RTTCountx > 0) {
|
|
||||||
long currentRTT = RTTTotal / RTTCountx;
|
|
||||||
//RTTAvg2 = (RTTAvg2 * 3 + currentRTT) / 4; // 平滑当前RTT
|
|
||||||
RTTAvg2=currentRTT;
|
|
||||||
RTTTotal = 0;
|
|
||||||
RTTCount = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
long OWDCountx=OWDCount;
|
|
||||||
if (OWDCountx > 0) {
|
|
||||||
long currentOWD = OWDTotal / OWDCountx;
|
|
||||||
OWDAvg2=currentOWD;
|
|
||||||
OWDTotal = 0;
|
|
||||||
OWDCount = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// ================== Vegas2.0核心逻辑 ==================
|
|
||||||
// 1. 计算时延膨胀比
|
|
||||||
double delayRatio = (double) OWDAvg2 / (double) Math.max(BIAS, OWDMin);
|
|
||||||
//System.out.println(delayRatio+" "+RTTAvg2/1000000.0+" "+RTTMin/1000000.0);
|
|
||||||
// 2. 基于比值的窗口调整(取代原来的基于差值的调整)
|
|
||||||
if (delayRatio > delayUpperBound) {
|
|
||||||
// 时延过高:减小窗口,减少幅度与超标程度成正比
|
|
||||||
window2 -= 4096;
|
|
||||||
} else if (delayRatio < delayLowerBound) {
|
|
||||||
// 时延过低:增大窗口,增加幅度与低于目标程度成正比
|
|
||||||
window2 += 4096;
|
|
||||||
} else {
|
|
||||||
|
|
||||||
}
|
|
||||||
// ===================================================
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
updateWindowSize();
|
|
||||||
RTTstartTime = curr;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void putAck(long packetSize, long RTTns, boolean ecn) {
|
public void putAck(long packetSize, long RTTns, boolean ecn) {
|
||||||
if(RTTns<0) {
|
if(RTTns<0) {
|
||||||
throw new IllegalArgumentException("RTT:"+ RTTns+" is negative!");
|
throw new IllegalArgumentException("RTT:"+ RTTns+" is negative!");
|
||||||
}
|
}
|
||||||
|
this.RTTCurr=RTTns;
|
||||||
// 处理ECN信号 - 将其视为强烈的拥塞信号
|
// 处理ECN信号 - 将其视为强烈的拥塞信号
|
||||||
if (ecn) {
|
if (ecn) {
|
||||||
// 当收到ECN时,更激进地减少窗口
|
// 当收到ECN时,更激进地减少窗口
|
||||||
@@ -166,64 +73,54 @@ public class Vegas2CongestionAlgorithm implements CongestionAlgorithm,DetnetCong
|
|||||||
windowControlConsumer.accept(window2);
|
windowControlConsumer.accept(window2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 更新最小RTT(BaseRTT)
|
|
||||||
if (RTTns <= RTTMin) {
|
|
||||||
RTTMin = RTTns;
|
|
||||||
} else {
|
|
||||||
// 缓慢适应:当网络路径真正变化时,BaseRTT应能缓慢更新
|
|
||||||
// 这里使用极慢的衰减因子,只有在持续观测到更低RTT时才快速更新
|
|
||||||
RTTMin = (RTTMin * 999 + RTTns) / 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 更新平滑RTT估计
|
// 更新平滑RTT估计
|
||||||
|
rttEstimator.putRTT(RTTns);
|
||||||
RTTVar = (RTTVar * 3 + Math.abs(RTTAvg - RTTns)) / 4;
|
|
||||||
RTTAvg = (RTTAvg * 7 + RTTns) / 8;
|
|
||||||
|
|
||||||
|
|
||||||
RTO = RTTAvg + Math.max(MIN_RTTVAR, RTTVar * 4);
|
|
||||||
|
|
||||||
RTTTotal += RTTns;
|
RTTTotal += RTTns;
|
||||||
RTTCount++;
|
RTTCount++;
|
||||||
|
if(slock.tryLock())try {
|
||||||
long curr = System.nanoTime();
|
long curr = System.nanoTime();
|
||||||
// 每个RTT周期调整一次窗口(使用当前估计的RTT)
|
// 每个RTT周期调整一次窗口(使用当前估计的RTT)
|
||||||
if (curr - RTTstartTime > Math.max(BIAS, 2*RTTMin)) {
|
if (curr - RTTstartTime > Math.max(BIAS, 2 * RTTMin)) {
|
||||||
long RTTCountx=RTTCount;
|
rttEstimator.update();
|
||||||
if (RTTCountx > 0) {
|
RTTMin = rttEstimator.getBaseRTT();
|
||||||
long currentRTT = RTTTotal / RTTCountx;
|
|
||||||
//RTTAvg2 = (RTTAvg2 * 3 + currentRTT) / 4; // 平滑当前RTT
|
|
||||||
RTTAvg2=currentRTT;
|
long RTTCountx = RTTCount;
|
||||||
RTTTotal = 0;
|
if (RTTCountx > 0) {
|
||||||
RTTCount = 0;
|
long currentRTT = RTTTotal / RTTCountx;
|
||||||
|
//RTTAvg2 = (RTTAvg2 * 3 + currentRTT) / 4; // 平滑当前RTT
|
||||||
|
RTTAvg2 = currentRTT;
|
||||||
|
RTTTotal = 0;
|
||||||
|
RTTCount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================== Vegas2.0核心逻辑 ==================
|
||||||
|
// 1. 计算时延膨胀比
|
||||||
|
double delayRatio = (double) RTTAvg2 / (double) Math.max(BIAS, RTTMin);
|
||||||
|
//System.out.println(delayRatio+" "+RTTAvg2/1000000.0+" "+RTTMin/1000000.0);
|
||||||
|
// 2. 基于比值的窗口调整(取代原来的基于差值的调整)
|
||||||
|
if (delayRatio > delayUpperBound) {
|
||||||
|
// 时延过高:减小窗口,减少幅度与超标程度成正比
|
||||||
|
window2 = window2 - 4096;
|
||||||
|
} else if (delayRatio < delayLowerBound) {
|
||||||
|
// 时延过低:增大窗口,增加幅度与低于目标程度成正比
|
||||||
|
window2 = window2 + 4096;
|
||||||
|
} else {
|
||||||
|
//window2=window2+4096
|
||||||
|
}
|
||||||
|
// ===================================================
|
||||||
|
|
||||||
|
|
||||||
|
updateWindowSize();
|
||||||
|
RTTstartTime = curr;
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
}finally{
|
||||||
// ================== Vegas2.0核心逻辑 ==================
|
slock.unlock();
|
||||||
// 1. 计算时延膨胀比
|
|
||||||
double delayRatio = (double) RTTAvg2 / (double) Math.max(BIAS, RTTMin);
|
|
||||||
//System.out.println(delayRatio+" "+RTTAvg2/1000000.0+" "+RTTMin/1000000.0);
|
|
||||||
// 2. 基于比值的窗口调整(取代原来的基于差值的调整)
|
|
||||||
if (delayRatio > delayUpperBound) {
|
|
||||||
// 时延过高:减小窗口,减少幅度与超标程度成正比
|
|
||||||
window2 -= 4096;
|
|
||||||
} else if (delayRatio < delayLowerBound) {
|
|
||||||
// 时延过低:增大窗口,增加幅度与低于目标程度成正比
|
|
||||||
window2 += 4096;
|
|
||||||
} else {
|
|
||||||
|
|
||||||
}
|
|
||||||
// ===================================================
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
updateWindowSize();
|
|
||||||
RTTstartTime = curr;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,12 +142,12 @@ public class Vegas2CongestionAlgorithm implements CongestionAlgorithm,DetnetCong
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void putLoss(long packetSize, long lossns, int losscounter) {
|
public void putLoss(long packetSize, long lossns) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public long getRTO() {
|
public long getRTO() {
|
||||||
return RTO;
|
return rttEstimator.getRTO();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -269,12 +166,14 @@ public class Vegas2CongestionAlgorithm implements CongestionAlgorithm,DetnetCong
|
|||||||
}
|
}
|
||||||
|
|
||||||
public long getBaseRTT() {
|
public long getBaseRTT() {
|
||||||
return RTTMin;
|
return rttEstimator.getBaseRTT();
|
||||||
}
|
}
|
||||||
|
public long getAvgRTT() {
|
||||||
public long getCurrentRTT() {
|
|
||||||
return RTTAvg2;
|
return RTTAvg2;
|
||||||
}
|
}
|
||||||
|
public long getCurrentRTT() {
|
||||||
|
return RTTCurr;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setUpperDelayBound(double upper) {
|
public void setUpperDelayBound(double upper) {
|
||||||
@@ -295,4 +194,19 @@ public class Vegas2CongestionAlgorithm implements CongestionAlgorithm,DetnetCong
|
|||||||
return "Vegas2";
|
return "Vegas2";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getUpperDelayBound() {
|
||||||
|
return delayUpperBound;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getLowerDelayBound() {
|
||||||
|
return delayLowerBound;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getBurstLimit() {
|
||||||
|
return burstLimit;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -4,16 +4,13 @@ import java.io.IOException;
|
|||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
import java.net.ServerSocket;
|
import java.net.ServerSocket;
|
||||||
import java.net.Socket;
|
|
||||||
import java.net.SocketAddress;
|
import java.net.SocketAddress;
|
||||||
import java.net.SocketImpl;
|
import java.net.SocketImpl;
|
||||||
import java.net.UnknownHostException;
|
import java.net.UnknownHostException;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.Map.Entry;
|
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import org.ini4j.Profile.Section;
|
import org.kne.cloud.network.MultiProtocolSocketAddress;
|
||||||
import org.kne.cloud.network.MultipurposeSocketAddress;
|
|
||||||
|
|
||||||
public class FrpcServerSocket extends ServerSocket {
|
public class FrpcServerSocket extends ServerSocket {
|
||||||
private FrpcProcess frpc;
|
private FrpcProcess frpc;
|
||||||
@@ -76,10 +73,10 @@ public class FrpcServerSocket extends ServerSocket {
|
|||||||
return frpcini.getRemotePort(tunnel);
|
return frpcini.getRemotePort(tunnel);
|
||||||
}
|
}
|
||||||
|
|
||||||
public MultipurposeSocketAddress getTunnelSocketAddress() {
|
public MultiProtocolSocketAddress getTunnelSocketAddress() {
|
||||||
if (!isBound())
|
if (!isBound())
|
||||||
return null;
|
return null;
|
||||||
return new MultipurposeSocketAddress(frpcini.getType(tunnel).toUpperCase(),getTunnelHost(), getTunnelPort());
|
return new MultiProtocolSocketAddress(frpcini.getType(tunnel).toUpperCase(),getTunnelHost(), getTunnelPort());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
package org.kne.cloud.network.ipv6;
|
package org.kne.cloud.network.ipv6;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
import java.util.concurrent.CopyOnWriteArraySet;
|
import java.util.concurrent.CopyOnWriteArraySet;
|
||||||
import java.util.function.BiConsumer;
|
import java.util.function.BiConsumer;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
@@ -8,10 +11,24 @@ import org.kne.cloud.network.srv6.SRv6Router;
|
|||||||
|
|
||||||
public abstract class AbstractIPv6NetworkLink implements IPv6NetworkLink {
|
public abstract class AbstractIPv6NetworkLink implements IPv6NetworkLink {
|
||||||
private CopyOnWriteArraySet<IPv6LinkStateListener> listeners = new CopyOnWriteArraySet<>();
|
private CopyOnWriteArraySet<IPv6LinkStateListener> listeners = new CopyOnWriteArraySet<>();
|
||||||
|
|
||||||
private SRv6Router srv6Router;
|
private SRv6Router srv6Router;
|
||||||
|
private final boolean loopback;
|
||||||
|
|
||||||
|
private final boolean filter;
|
||||||
|
|
||||||
|
|
||||||
|
public AbstractIPv6NetworkLink(boolean loopback) {
|
||||||
|
super();
|
||||||
|
this.loopback = loopback;
|
||||||
|
this.filter = false;
|
||||||
|
}
|
||||||
|
public AbstractIPv6NetworkLink(boolean loopback, boolean filter) {
|
||||||
|
super();
|
||||||
|
this.loopback = loopback;
|
||||||
|
this.filter = filter;
|
||||||
|
}
|
||||||
|
|
||||||
public SRv6Router getSrv6Router() {
|
public SRv6Router getSrv6Router() {
|
||||||
return srv6Router;
|
return srv6Router;
|
||||||
}
|
}
|
||||||
@@ -53,8 +70,54 @@ public abstract class AbstractIPv6NetworkLink implements IPv6NetworkLink {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private BiConsumer<IPv6NetworkLink, Supplier<IPv6Packet>> receiveConsumer;
|
private BiConsumer<IPv6NetworkLink, Supplier<IPv6Packet>> receiveConsumer;
|
||||||
|
|
||||||
|
private Supplier<Long> costSupplier;
|
||||||
@Override
|
@Override
|
||||||
public void setReceiveConsumer(BiConsumer<IPv6NetworkLink,Supplier< IPv6Packet>> receiveConsumer) {
|
public void setReceiveConsumer(BiConsumer<IPv6NetworkLink,Supplier< IPv6Packet>> receiveConsumer) {
|
||||||
this.receiveConsumer = receiveConsumer;
|
this.receiveConsumer = receiveConsumer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isLoopBack() {
|
||||||
|
return loopback;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Supplier<Long> getCostSupplier() {
|
||||||
|
return costSupplier;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCostSupplier(Supplier<Long> costSupplier) {
|
||||||
|
this.costSupplier = costSupplier;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<RouteItem> getRouteItems() {
|
||||||
|
List<RouteItem> rlist = new ArrayList<>();
|
||||||
|
if(isLoopBack()) {
|
||||||
|
for(IPv6AddressGroup group:getAddressGroups()) {
|
||||||
|
rlist.add(new RouteItem(new IPv6AddressGroup(group.getAddress(), 128),
|
||||||
|
group.getAddress(), this, RouteItem.DIRECT, 0, 0, null, "D"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(isUp()) {
|
||||||
|
for (Iterator<Neighbor> iteratorx = getNeighborsInfo().iterator(); iteratorx.hasNext();) {
|
||||||
|
Neighbor addresses = (Neighbor) iteratorx.next();
|
||||||
|
RouteItem ri = new RouteItem(new IPv6AddressGroup(addresses.getAddress().getAddress(), 128),
|
||||||
|
addresses.getAddress().getAddress(), this,RouteItem.SRv6_ENDXSID, 0, 128, costSupplier, "D");
|
||||||
|
rlist.add(ri);
|
||||||
|
|
||||||
|
RouteItem ris = new RouteItem(addresses.getLocator(),
|
||||||
|
addresses.getLocator().getAddress(), this, RouteItem.SRv6_ENDSID, 13, 128,
|
||||||
|
costSupplier, "D");
|
||||||
|
rlist.add(ris);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rlist;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isFilter() {
|
||||||
|
return filter;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,6 +61,10 @@ public final class IPv6Address implements Comparable<IPv6Address> {
|
|||||||
((long)(bytes[15] & 0xFF));
|
((long)(bytes[15] & 0xFF));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public IPv6Address(String string) throws UnknownHostException {
|
||||||
|
this((Inet6Address) Inet6Address.getByName(string));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从两个long创建IPv6地址
|
* 从两个long创建IPv6地址
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -67,7 +67,16 @@ public class IPv6AddressGroup implements Comparable<IPv6AddressGroup>{
|
|||||||
prefixLength=in.read();
|
prefixLength=in.read();
|
||||||
}
|
}
|
||||||
public boolean checkMatch(IPv6Address address2) {
|
public boolean checkMatch(IPv6Address address2) {
|
||||||
return address2.equals(address.maskWith(IPv6Address.createMask(prefixLength)));
|
IPv6Address cmsk= IPv6Address.createMask(prefixLength);
|
||||||
|
return address2.maskWith(cmsk).equals(address.maskWith(cmsk));
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 返回裁剪后的路由表地址(主机位清零)。
|
||||||
|
* 例如 2001:db8:1::100/64 → 2001:db8:1::/64
|
||||||
|
*/
|
||||||
|
public IPv6AddressGroup toNetworkRoute() {
|
||||||
|
IPv6Address mask = IPv6Address.createMask(prefixLength);
|
||||||
|
IPv6Address maskedAddr = address.maskWith(mask);
|
||||||
|
return new IPv6AddressGroup(maskedAddr, prefixLength);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,5 +29,6 @@ public interface IPv6NetworkLink {
|
|||||||
public void setReceiveConsumer(BiConsumer<IPv6NetworkLink, Supplier<IPv6Packet>> srhReceive);
|
public void setReceiveConsumer(BiConsumer<IPv6NetworkLink, Supplier<IPv6Packet>> srhReceive);
|
||||||
public void addIPv6LinkStateListener(IPv6LinkStateListener listener);
|
public void addIPv6LinkStateListener(IPv6LinkStateListener listener);
|
||||||
public void removeIPv6LinkStateListener(IPv6LinkStateListener listener);
|
public void removeIPv6LinkStateListener(IPv6LinkStateListener listener);
|
||||||
|
|
||||||
|
public boolean isFilter();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1378,7 +1378,7 @@ public class IPv6Packet extends NetworkPacket {
|
|||||||
// 重路由计数器
|
// 重路由计数器
|
||||||
private AtomicInteger rerouteCounter = new AtomicInteger(0);
|
private AtomicInteger rerouteCounter = new AtomicInteger(0);
|
||||||
|
|
||||||
public AtomicInteger getRerouteCounter() {
|
public AtomicInteger getRouteCounter() {
|
||||||
return rerouteCounter;
|
return rerouteCounter;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ public class IPv6TUNLoopbackNetworkLink extends AbstractIPv6NetworkLink
|
|||||||
private Lock slok = new SpinLock();
|
private Lock slok = new SpinLock();
|
||||||
|
|
||||||
public IPv6TUNLoopbackNetworkLink(String name,IPv6AddressGroup hostAddress, int mtu, List<InetAddress> dns) throws IOException {
|
public IPv6TUNLoopbackNetworkLink(String name,IPv6AddressGroup hostAddress, int mtu, List<InetAddress> dns) throws IOException {
|
||||||
|
super(true);
|
||||||
if (tun != null)
|
if (tun != null)
|
||||||
throw new IllegalStateException("already open!");
|
throw new IllegalStateException("already open!");
|
||||||
try {
|
try {
|
||||||
@@ -204,13 +205,6 @@ public class IPv6TUNLoopbackNetworkLink extends AbstractIPv6NetworkLink
|
|||||||
LockSupport.unpark(tr);
|
LockSupport.unpark(tr);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isLoopBack() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Neighbor> getNeighborsInfo() {
|
public List<Neighbor> getNeighborsInfo() {
|
||||||
List<Neighbor> hs = new ArrayList<>();
|
List<Neighbor> hs = new ArrayList<>();
|
||||||
@@ -219,10 +213,6 @@ public class IPv6TUNLoopbackNetworkLink extends AbstractIPv6NetworkLink
|
|||||||
return hs;
|
return hs;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* @Override public boolean isCongress(IPv6Packet iPv6Packet,double scale) {
|
|
||||||
* return sendQueue.size() > 1000*scale; }
|
|
||||||
*/
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getName() {
|
public String getName() {
|
||||||
@@ -255,27 +245,4 @@ public class IPv6TUNLoopbackNetworkLink extends AbstractIPv6NetworkLink
|
|||||||
return List.of(hostAddress);
|
return List.of(hostAddress);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<RouteItem> getRouteItems() {
|
|
||||||
List<RouteItem> rlist = new ArrayList<>();
|
|
||||||
|
|
||||||
for (IPv6AddressGroup grp : getAddressGroups()) {
|
|
||||||
rlist.add(new RouteItem(new IPv6AddressGroup(grp.getAddress(), 128), grp.getAddress(), this, "Direct", 0, 1,
|
|
||||||
null, "D", true));
|
|
||||||
}
|
|
||||||
|
|
||||||
for (Iterator<Neighbor> iteratorx = getNeighborsInfo().iterator(); iteratorx.hasNext();) {
|
|
||||||
Neighbor addresses = (Neighbor) iteratorx.next();
|
|
||||||
RouteItem ri = new RouteItem(new IPv6AddressGroup(addresses.getAddress().getAddress(), 128),
|
|
||||||
addresses.getAddress().getAddress(), this, "Direct", 0, 128, null, "D", false);
|
|
||||||
rlist.add(ri);
|
|
||||||
|
|
||||||
RouteItem ris = new RouteItem(addresses.getLocator(), addresses.getLocator().getAddress(), this,
|
|
||||||
"KLALB SRv6", 13, 128, null, "D", false);
|
|
||||||
rlist.add(ris);
|
|
||||||
|
|
||||||
}
|
|
||||||
return rlist;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ public class LoopbackIPv6NetworkLink extends AbstractIPv6NetworkLink implements
|
|||||||
|
|
||||||
//new Inet6AddressGroup(loopbackAddress, 128) new Inet6AddressGroup((Inet6Address) Inet6Address.getByName("::1"), 128)
|
//new Inet6AddressGroup(loopbackAddress, 128) new Inet6AddressGroup((Inet6Address) Inet6Address.getByName("::1"), 128)
|
||||||
public LoopbackIPv6NetworkLink(List<IPv6AddressGroup> addressGroupsx,SRv6Router router) {
|
public LoopbackIPv6NetworkLink(List<IPv6AddressGroup> addressGroupsx,SRv6Router router) {
|
||||||
|
super(true);
|
||||||
this.addressGroups .addAll( addressGroupsx);
|
this.addressGroups .addAll( addressGroupsx);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,10 +55,7 @@ public class LoopbackIPv6NetworkLink extends AbstractIPv6NetworkLink implements
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isLoopBack() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Neighbor> getNeighborsInfo() {
|
public List<Neighbor> getNeighborsInfo() {
|
||||||
@@ -93,29 +91,6 @@ public class LoopbackIPv6NetworkLink extends AbstractIPv6NetworkLink implements
|
|||||||
return rerouteConsumer;
|
return rerouteConsumer;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<RouteItem> getRouteItems() {
|
|
||||||
List<RouteItem> rlist = new ArrayList<>();
|
|
||||||
for(IPv6AddressGroup group:addressGroups) {
|
|
||||||
rlist.add(new RouteItem(new IPv6AddressGroup(group.getAddress(), 128),
|
|
||||||
group.getAddress(), this, "Direct", 0, 0, null, "D", true));
|
|
||||||
}
|
|
||||||
|
|
||||||
for (Iterator<Neighbor> iteratorx = getNeighborsInfo().iterator(); iteratorx.hasNext();) {
|
|
||||||
Neighbor addresses = (Neighbor) iteratorx.next();
|
|
||||||
RouteItem ri = new RouteItem(new IPv6AddressGroup(addresses.getAddress().getAddress(), 128),
|
|
||||||
addresses.getAddress().getAddress(), this, "Direct", 0, 128, null, "D",
|
|
||||||
false);
|
|
||||||
rlist.add(ri);
|
|
||||||
|
|
||||||
RouteItem ris = new RouteItem(addresses.getLocator(),
|
|
||||||
addresses.getLocator().getAddress(), this, "KLALB SRv6", 13, 128,
|
|
||||||
null, "D", false);
|
|
||||||
rlist.add(ris);
|
|
||||||
|
|
||||||
}
|
|
||||||
return rlist;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public SRv6Router getRouter() {
|
public SRv6Router getRouter() {
|
||||||
|
|||||||
@@ -4,6 +4,11 @@ import java.util.Objects;
|
|||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
public class RouteItem implements Comparable<RouteItem>,Cloneable{
|
public class RouteItem implements Comparable<RouteItem>,Cloneable{
|
||||||
|
public static final String DIRECT="Direct";
|
||||||
|
public static final String SRv6_ENDSID="SRv6 ENDSID";
|
||||||
|
public static final String SRv6_ENDXSID="SRv6 ENDXSID";
|
||||||
|
public static final String KLALB_SRv6 = "KLALB_SRv6";
|
||||||
|
|
||||||
private IPv6AddressGroup destination;
|
private IPv6AddressGroup destination;
|
||||||
private IPv6Address nexthop;
|
private IPv6Address nexthop;
|
||||||
private IPv6NetworkLink destlink;
|
private IPv6NetworkLink destlink;
|
||||||
@@ -12,7 +17,6 @@ public class RouteItem implements Comparable<RouteItem>,Cloneable{
|
|||||||
private long cost;
|
private long cost;
|
||||||
private String flag;
|
private String flag;
|
||||||
private Supplier<Long> costSupplier;
|
private Supplier<Long> costSupplier;
|
||||||
private boolean isLoopback;
|
|
||||||
public String getFlag() {
|
public String getFlag() {
|
||||||
return flag;
|
return flag;
|
||||||
}
|
}
|
||||||
@@ -34,21 +38,20 @@ public class RouteItem implements Comparable<RouteItem>,Cloneable{
|
|||||||
&& pre == other.pre && Objects.equals(proto, other.proto);
|
&& pre == other.pre && Objects.equals(proto, other.proto);
|
||||||
}
|
}
|
||||||
public RouteItem(IPv6AddressGroup destination, IPv6Address nexthop, IPv6NetworkLink destlink, String proto, int pre,
|
public RouteItem(IPv6AddressGroup destination, IPv6Address nexthop, IPv6NetworkLink destlink, String proto, int pre,
|
||||||
long cost,String flag,boolean isLoopback) {
|
long cost,String flag) {
|
||||||
super();
|
super();
|
||||||
this.destination = destination;
|
this.destination = destination.toNetworkRoute();
|
||||||
this.nexthop = nexthop;
|
this.nexthop = nexthop;
|
||||||
this.destlink = destlink;
|
this.destlink = destlink;
|
||||||
this.proto = proto;
|
this.proto = proto;
|
||||||
this.pre = pre;
|
this.pre = pre;
|
||||||
this.cost = cost;
|
this.cost = cost;
|
||||||
this.flag=flag;
|
this.flag=flag;
|
||||||
this.isLoopback=isLoopback;
|
|
||||||
}
|
}
|
||||||
public RouteItem(IPv6AddressGroup destination, IPv6Address nexthop, IPv6NetworkLink destlink, String proto, int pre,
|
public RouteItem(IPv6AddressGroup destination, IPv6Address nexthop, IPv6NetworkLink destlink, String proto, int pre,
|
||||||
long cost,Supplier<Long> costSupplier,String flag,boolean isLoopback) {
|
long cost,Supplier<Long> costSupplier,String flag) {
|
||||||
super();
|
super();
|
||||||
this.destination = destination;
|
this.destination = destination.toNetworkRoute();
|
||||||
this.nexthop = nexthop;
|
this.nexthop = nexthop;
|
||||||
this.destlink = destlink;
|
this.destlink = destlink;
|
||||||
this.proto = proto;
|
this.proto = proto;
|
||||||
@@ -56,7 +59,6 @@ public class RouteItem implements Comparable<RouteItem>,Cloneable{
|
|||||||
this.cost = cost;
|
this.cost = cost;
|
||||||
this.costSupplier=costSupplier;
|
this.costSupplier=costSupplier;
|
||||||
this.flag=flag;
|
this.flag=flag;
|
||||||
this.isLoopback=isLoopback;
|
|
||||||
}
|
}
|
||||||
public IPv6AddressGroup getDestination() {
|
public IPv6AddressGroup getDestination() {
|
||||||
return destination;
|
return destination;
|
||||||
@@ -73,9 +75,6 @@ public class RouteItem implements Comparable<RouteItem>,Cloneable{
|
|||||||
public int getPre() {
|
public int getPre() {
|
||||||
return pre;
|
return pre;
|
||||||
}
|
}
|
||||||
public boolean isLoopback() {
|
|
||||||
return isLoopback;
|
|
||||||
}
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return getDestination()+"\t"+getProto()+"\t"+getPre()+"\t"+getCost()+"\t"+getFlag()+"\t"+getNexthop()+"\t"+getDestlink().getName();
|
return getDestination()+"\t"+getProto()+"\t"+getPre()+"\t"+getCost()+"\t"+getFlag()+"\t"+getNexthop()+"\t"+getDestlink().getName();
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user