feat(websocket): Add TypedRouter WebSocket integration, connection registry, peer tagging and broadcast APIs
This commit is contained in:
@@ -93,8 +93,65 @@ await server.start();
|
||||
- LOCK/UNLOCK - Exclusive write locking
|
||||
- GET/HEAD/PUT/DELETE - Standard file operations
|
||||
|
||||
## TypedRouter WebSocket Integration
|
||||
|
||||
SmartServe supports first-class TypedRouter integration for type-safe RPC over WebSockets.
|
||||
|
||||
### Usage
|
||||
|
||||
```typescript
|
||||
import { SmartServe } from '@push.rocks/smartserve';
|
||||
import { TypedRouter, TypedHandler } from '@api.global/typedrequest';
|
||||
|
||||
const router = new TypedRouter();
|
||||
router.addTypedHandler(new TypedHandler('echo', async (data) => {
|
||||
return { echoed: data.message };
|
||||
}));
|
||||
|
||||
const server = new SmartServe({
|
||||
port: 3000,
|
||||
websocket: {
|
||||
typedRouter: router,
|
||||
onConnectionOpen: (peer) => {
|
||||
peer.tags.add('authenticated');
|
||||
console.log(`Client connected: ${peer.id}`);
|
||||
},
|
||||
onConnectionClose: (peer) => {
|
||||
console.log(`Client disconnected: ${peer.id}`);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await server.start();
|
||||
|
||||
// Broadcast to all connections
|
||||
server.broadcastWebSocket({ type: 'notification', message: 'Hello!' });
|
||||
|
||||
// Broadcast to specific tag
|
||||
server.broadcastWebSocketByTag('authenticated', { type: 'secure-message' });
|
||||
|
||||
// Get all connections
|
||||
const connections = server.getWebSocketConnections();
|
||||
```
|
||||
|
||||
### Key Features
|
||||
|
||||
- **TypedRouter mode**: Set `typedRouter` for automatic JSON-RPC routing (mutually exclusive with `onMessage`)
|
||||
- **Connection registry**: Active only when `typedRouter` is set
|
||||
- **Peer tags**: Use `peer.tags.add/has/delete` for connection filtering
|
||||
- **Broadcast methods**: `broadcastWebSocket()` and `broadcastWebSocketByTag()`
|
||||
- **Lifecycle hooks**: `onConnectionOpen` and `onConnectionClose` (alongside existing `onOpen`/`onClose`)
|
||||
|
||||
### Architecture Notes
|
||||
|
||||
- `typedRouter` and `onMessage` are mutually exclusive (throws `WebSocketConfigError` if both set)
|
||||
- Connection registry only active when `typedRouter` is configured
|
||||
- Bun adapter stores peer ID/tags in `ws.data` for persistence across events
|
||||
- Internal `_connectionCallbacks` passed to adapters for registry communication
|
||||
|
||||
## TODO
|
||||
|
||||
- [x] WebDAV protocol support (PROPFIND, MKCOL, COPY, MOVE, LOCK, UNLOCK)
|
||||
- [x] TypedRouter WebSocket integration
|
||||
- [ ] HTTP/2 support investigation
|
||||
- [ ] Performance benchmarks
|
||||
|
||||
Reference in New Issue
Block a user