-
-
Notifications
You must be signed in to change notification settings - Fork 25
Add WebSocket adapter support and enhance setup options #135
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
0-don
wants to merge
4
commits into
k0d13:main
Choose a base branch
from
0-don:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
6295740
Add WebSocket adapter support and enhance setup options
0-don a88235a
Add changeset for adapter support
0-don 1a1a18c
Implement Redis adapter for multi-instance WebSocket communication
0-don 24ad959
Refactor WebSocket server setup and improve Redis adapter test handling
0-don File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "next-ws": minor | ||
| --- | ||
|
|
||
| Add WebSocket adapter support for multi-instance deployments |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| name: Redis Adapter Tests | ||
|
|
||
| on: | ||
| push: | ||
| branches: [main] | ||
| pull_request: | ||
| branches: [main] | ||
|
|
||
| jobs: | ||
| test-redis-adapter: | ||
| runs-on: ubuntu-latest | ||
|
|
||
| services: | ||
| redis: | ||
| image: redis:7-alpine | ||
| ports: | ||
| - 6379:6379 | ||
| options: >- | ||
| --health-cmd "redis-cli ping" | ||
| --health-interval 10s | ||
| --health-timeout 5s | ||
| --health-retries 5 | ||
|
|
||
| steps: | ||
| - uses: actions/checkout@v4 | ||
|
|
||
| - uses: pnpm/action-setup@v4 | ||
| with: | ||
| version: 10.15.0 | ||
|
|
||
| - uses: actions/setup-node@v4 | ||
| with: | ||
| node-version: "22" | ||
| cache: "pnpm" | ||
|
|
||
| - name: Install dependencies | ||
| run: pnpm install --frozen-lockfile | ||
|
|
||
| - name: Build project | ||
| run: pnpm build | ||
|
|
||
| - name: Install Playwright browsers | ||
| run: pnpm exec playwright install --with-deps chromium | ||
|
|
||
| - name: Run Redis adapter tests | ||
| run: pnpm test tests/redis-adapter.test.ts | ||
| env: | ||
| REDIS_URL: redis://localhost:6379 | ||
| CI: true | ||
|
|
||
| - name: Upload test results | ||
| if: failure() | ||
| uses: actions/upload-artifact@v4 | ||
| with: | ||
| name: playwright-report | ||
| path: tests/.report/ | ||
| retention-days: 7 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| import { headers } from 'next/headers'; | ||
|
|
||
| export function GET() { | ||
| const headers = new Headers(); | ||
| headers.set('Connection', 'Upgrade'); | ||
| headers.set('Upgrade', 'websocket'); | ||
| return new Response('Upgrade Required', { status: 426, headers }); | ||
| } | ||
|
|
||
| export async function UPGRADE(client: import('ws').WebSocket) { | ||
| await headers(); | ||
|
|
||
| client.send( | ||
| JSON.stringify({ | ||
| author: 'System', | ||
| content: `Connected to instance ${process.env.INSTANCE_ID || 'unknown'}`, | ||
| }), | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| 'use client'; | ||
|
|
||
| import { MessageList, MessageSubmit, useMessaging } from 'shared/chat-room'; | ||
|
|
||
| export default function Page() { | ||
| const [messages, sendMessage] = useMessaging( | ||
| () => `ws://${window.location.host}/api/ws`, | ||
| ); | ||
|
|
||
| return ( | ||
| <div style={{ maxWidth: '50vh' }}> | ||
| <MessageList messages={messages} /> | ||
| <MessageSubmit onMessage={sendMessage} /> | ||
| </div> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| export default function Layout({ children }: React.PropsWithChildren) { | ||
| return ( | ||
| <html lang="en" style={{ fontFamily: 'sans-serif' }}> | ||
| <body | ||
| style={{ | ||
| backgroundColor: 'black', | ||
| color: 'white', | ||
| display: 'flex', | ||
| flexDirection: 'column', | ||
| alignItems: 'center', | ||
| }} | ||
| > | ||
| {children} | ||
| </body> | ||
| </html> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| globalThis.AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| /// <reference types="next" /> | ||
| /// <reference types="next/image-types/global" /> | ||
| /// <reference path="./.next/types/routes.d.ts" /> | ||
|
|
||
| // NOTE: This file should not be edited | ||
| // see https://nextjs.org/docs/app/api-reference/config/typescript for more information. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| { | ||
| "name": "@examples/redis-adapter", | ||
| "private": true, | ||
| "scripts": { | ||
| "dev": "tsx --require=\"./global.js\" server.ts", | ||
| "prepare": "next-ws patch" | ||
| }, | ||
| "dependencies": { | ||
| "ioredis": "catalog:", | ||
| "next": "catalog:", | ||
| "next-ws": "workspace:^", | ||
| "react": "catalog:", | ||
| "react-dom": "catalog:", | ||
| "shared": "workspace:^" | ||
| }, | ||
| "devDependencies": { | ||
| "@types/react": "catalog:", | ||
| "tsx": "^4.20.4" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| import { Server } from 'node:http'; | ||
| import { parse } from 'node:url'; | ||
| import Redis from 'ioredis'; | ||
| import next from 'next'; | ||
| import { | ||
| type Adapter, | ||
| setAdapter, | ||
| setHttpServer, | ||
| setWebSocketServer, | ||
| } from 'next-ws/server'; | ||
| import { WebSocketServer } from 'ws'; | ||
|
|
||
| class RedisAdapter implements Adapter { | ||
| private pub = new Redis(process.env.REDIS_URL || 'redis://localhost:6379'); | ||
| private sub = new Redis(process.env.REDIS_URL || 'redis://localhost:6379'); | ||
|
|
||
| async broadcast(room: string, message: unknown): Promise<void> { | ||
| const messageStr = | ||
| typeof message === 'string' | ||
| ? message | ||
| : Buffer.isBuffer(message) | ||
| ? message.toString('utf-8') | ||
| : JSON.stringify(message); | ||
| await this.pub.publish(room, messageStr); | ||
| } | ||
|
|
||
| onMessage(room: string, handler: (message: unknown) => void): void { | ||
| this.sub.subscribe(room); | ||
| this.sub.on('message', (channel: string, msg: string) => { | ||
| if (channel === room) handler(msg); | ||
| }); | ||
| } | ||
|
|
||
| async close(): Promise<void> { | ||
| await Promise.all([this.pub.quit(), this.sub.quit()]); | ||
| } | ||
| } | ||
|
|
||
| const httpServer = new Server(); | ||
| setHttpServer(httpServer); | ||
| const webSocketServer = new WebSocketServer({ noServer: true }); | ||
| setWebSocketServer(webSocketServer); | ||
| setAdapter(new RedisAdapter()); | ||
|
|
||
| const dev = process.env.NODE_ENV !== 'production'; | ||
| const hostname = 'localhost'; | ||
| const port = Number.parseInt(process.env.PORT ?? '3000', 10); | ||
| const app = next({ dev, hostname, port, customServer: true }); | ||
| const handle = app.getRequestHandler(); | ||
|
|
||
| app.prepare().then(() => { | ||
| httpServer | ||
| .on('request', async (req, res) => { | ||
| if (!req.url) return; | ||
| const parsedUrl = parse(req.url, true); | ||
| await handle(req, res, parsedUrl); | ||
| }) | ||
| .listen(port, () => { | ||
| console.log( | ||
| ` ▲ Ready on http://${hostname}:${port} (Instance ${process.env.INSTANCE_ID || 'unknown'})`, | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| { | ||
| "$schema": "https://json.schemastore.org/tsconfig.json", | ||
|
|
||
| "include": ["app/**/*", ".next/types/**/*.ts"], | ||
| "exclude": ["node_modules", ".next"], | ||
|
|
||
| "compileOnSave": true, | ||
| "compilerOptions": { | ||
| "allowUnreachableCode": false, | ||
| "allowUnusedLabels": false, | ||
| "exactOptionalPropertyTypes": false, | ||
| "noFallthroughCasesInSwitch": true, | ||
| "noImplicitOverride": true, | ||
| "noImplicitReturns": true, | ||
| "noPropertyAccessFromIndexSignature": false, | ||
| "noUncheckedIndexedAccess": true, | ||
| "noUnusedLocals": true, | ||
| "noUnusedParameters": true, | ||
| "strict": true, | ||
|
|
||
| "allowArbitraryExtensions": false, | ||
| "allowImportingTsExtensions": false, | ||
| "allowJs": true, | ||
| "module": "ESNext", | ||
| "moduleResolution": "Bundler", | ||
| "resolveJsonModule": true, | ||
| "resolvePackageJsonExports": true, | ||
| "resolvePackageJsonImports": true, | ||
|
|
||
| "declaration": true, | ||
| "declarationMap": true, | ||
| "importHelpers": false, | ||
| "newLine": "lf", | ||
| "noEmit": true, | ||
| "noEmitHelpers": true, | ||
| "removeComments": false, | ||
| "sourceMap": true, | ||
| "allowSyntheticDefaultImports": true, | ||
| "esModuleInterop": true, | ||
| "forceConsistentCasingInFileNames": true, | ||
| "isolatedModules": true, | ||
|
|
||
| "experimentalDecorators": true, | ||
| "lib": ["DOM", "DOM.Iterable", "ESNext"], | ||
| "target": "ES2022", | ||
| "useDefineForClassFields": true, | ||
| "skipLibCheck": true, | ||
|
|
||
| "jsx": "preserve", | ||
| "outDir": "./dist", | ||
| "paths": { "~/*": ["./src/*"] }, | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| "plugins": [{ "name": "next" }], | ||
| "incremental": true | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.