@rlanz/socket 0.0.1-3 → 0.0.1-5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +467 -41
- package/build/chunk-ANT2E3LT.js +136 -0
- package/build/chunk-ANT2E3LT.js.map +1 -0
- package/build/chunk-B4Y3TNDI.js +159 -0
- package/build/chunk-B4Y3TNDI.js.map +1 -0
- package/build/{chunk-GKAD2UOA.js → chunk-D3HUBCBW.js} +1 -1
- package/build/chunk-D3HUBCBW.js.map +1 -0
- package/build/chunk-SFAY2ZA4.js +28 -0
- package/build/chunk-SFAY2ZA4.js.map +1 -0
- package/build/{chunk-XUDFDJME.js → chunk-SHH6U4CI.js} +12 -9
- package/build/chunk-SHH6U4CI.js.map +1 -0
- package/build/chunk-YAX5EHHB.js +453 -0
- package/build/chunk-YAX5EHHB.js.map +1 -0
- package/build/framework-CvxgHwbv.d.ts +12 -0
- package/build/index.d.ts +11 -3
- package/build/index.js +32 -6
- package/build/index.js.map +1 -1
- package/build/providers/socket_provider.d.ts +4 -3
- package/build/providers/socket_provider.js +1774 -57
- package/build/providers/socket_provider.js.map +1 -1
- package/build/services/socket.d.ts +4 -3
- package/build/socket_service-mybqv1hj.d.ts +105 -0
- package/build/src/assembler_hook.d.ts +13 -0
- package/build/src/assembler_hook.js +249 -0
- package/build/src/assembler_hook.js.map +1 -0
- package/build/src/client/index.d.ts +46 -12
- package/build/src/client/index.js +223 -81
- package/build/src/client/index.js.map +1 -1
- package/build/src/client/react.d.ts +27 -0
- package/build/src/client/react.js +69 -0
- package/build/src/client/react.js.map +1 -0
- package/build/src/client/svelte.d.ts +22 -0
- package/build/src/client/svelte.js +82 -0
- package/build/src/client/svelte.js.map +1 -0
- package/build/src/client/types.d.ts +68 -10
- package/build/src/client/vue.d.ts +25 -0
- package/build/src/client/vue.js +81 -0
- package/build/src/client/vue.js.map +1 -0
- package/build/src/decorators.d.ts +4 -4
- package/build/src/decorators.js +1 -1
- package/build/src/health_check.d.ts +4 -3
- package/build/src/otel.js +4 -5
- package/build/src/otel.js.map +1 -1
- package/build/src/testing.d.ts +54 -0
- package/build/src/testing.js +7 -0
- package/build/src/testing.js.map +1 -0
- package/build/src/types.d.ts +2 -2
- package/build/{types-BnOi46bE.d.ts → types-C7Q36ryo.d.ts} +144 -79
- package/package.json +43 -8
- package/build/chunk-GKAD2UOA.js.map +0 -1
- package/build/chunk-NRWRLZAO.js +0 -1794
- package/build/chunk-NRWRLZAO.js.map +0 -1
- package/build/chunk-XUDFDJME.js.map +0 -1
- package/build/shared_types-Dw9AphfO.d.ts +0 -21
- package/build/socket_service-BN1g3ENk.d.ts +0 -144
package/README.md
CHANGED
|
@@ -14,35 +14,78 @@ Register the provider in your AdonisJS application:
|
|
|
14
14
|
// adonisrc.ts
|
|
15
15
|
export default defineConfig({
|
|
16
16
|
providers: [() => import('@rlanz/socket/provider')],
|
|
17
|
+
hooks: {
|
|
18
|
+
init: [() => import('@rlanz/socket/assembler_hook')],
|
|
19
|
+
},
|
|
17
20
|
})
|
|
18
21
|
```
|
|
19
22
|
|
|
23
|
+
The Assembler hook generates both the application registry used for end-to-end client types and the
|
|
24
|
+
server manifest consumed by the provider. They come from the same channel file list, so runtime
|
|
25
|
+
routing cannot drift from the generated client contract. Keep the standard AdonisJS package import
|
|
26
|
+
mapping `#generated/*` pointed at `./.adonisjs/server/*.js`; the provider loads
|
|
27
|
+
`#generated/socket_channels` through that convention.
|
|
28
|
+
|
|
20
29
|
## Configuration
|
|
21
30
|
|
|
22
31
|
Create a socket config file and tune the WebSocket path or heartbeat.
|
|
23
32
|
|
|
24
33
|
```ts
|
|
25
34
|
// config/socket.ts
|
|
26
|
-
import { defineConfig } from '@
|
|
35
|
+
import { defineConfig } from '@rlanz/socket'
|
|
27
36
|
|
|
28
37
|
export default defineConfig({
|
|
29
38
|
websocket: {
|
|
30
39
|
path: '/socket',
|
|
31
|
-
|
|
32
|
-
|
|
40
|
+
allowedOrigins: ['https://app.example.com'],
|
|
41
|
+
pingInterval: '25s',
|
|
42
|
+
pingTimeout: '5s',
|
|
43
|
+
maxBufferedAmount: 16 * 1024 * 1024,
|
|
44
|
+
maxOutboundPayload: 1024 * 1024,
|
|
45
|
+
maxSubscriptionsPerSocket: 100,
|
|
46
|
+
maxChannelNameLength: 255,
|
|
33
47
|
},
|
|
34
48
|
})
|
|
35
49
|
```
|
|
36
50
|
|
|
37
51
|
- `websocket.path` defaults to `/socket`.
|
|
38
|
-
-
|
|
52
|
+
- Browser upgrades are restricted to the request's own origin by default. Use
|
|
53
|
+
`websocket.allowedOrigins` to add exact `http://` or `https://` origins. Clients that do not send
|
|
54
|
+
an `Origin` header remain supported.
|
|
55
|
+
- `websocket.middleware` runs AdonisJS HTTP middleware for the WebSocket upgrade request.
|
|
56
|
+
- `websocket.pingInterval` sends a WebSocket ping every configured duration.
|
|
39
57
|
- `websocket.pingTimeout` closes connections that do not answer in time.
|
|
40
58
|
- If only one heartbeat value is configured, the other one uses the default shown above.
|
|
59
|
+
- `websocket.maxPayload` limits inbound message payloads; it defaults to 1 MiB.
|
|
60
|
+
- `websocket.maxQueuedMessages` limits unresolved non-ping protocol messages per socket; it defaults
|
|
61
|
+
to `100`.
|
|
62
|
+
- `websocket.maxMessagesPerInterval` limits inbound protocol messages per
|
|
63
|
+
`websocket.messageRateInterval`; they default to `1000` messages per `1s`.
|
|
64
|
+
- `websocket.maxBufferedAmount` closes slow outbound sockets when the buffered bytes plus the next
|
|
65
|
+
protocol message would exceed the configured limit; it defaults to 16 MiB.
|
|
66
|
+
- `websocket.maxOutboundPayload` limits every serialized outbound event, ACK, pong, and protocol
|
|
67
|
+
error; it defaults to 1 MiB.
|
|
68
|
+
- `websocket.maxSubscriptionsPerSocket` limits active channel subscriptions retained by one socket;
|
|
69
|
+
it defaults to `100`.
|
|
70
|
+
- `websocket.maxChannelNameLength` limits channel names before routing; it defaults to `255`
|
|
71
|
+
characters.
|
|
72
|
+
|
|
73
|
+
`websocket.middleware` is different from channel middleware. Use it to prepare request-scoped
|
|
74
|
+
services such as sessions or auth during the initial HTTP upgrade; use `static middlewares` on a
|
|
75
|
+
channel class to authorize or enrich individual channel subscriptions.
|
|
76
|
+
|
|
77
|
+
AdonisJS CORS middleware does not authorize the Node.js `upgrade` event and browsers do not apply
|
|
78
|
+
Fetch CORS response checks to WebSockets. The origin check therefore runs before upgrade middleware
|
|
79
|
+
and authentication, which protects cookie- or session-authenticated sockets from cross-site
|
|
80
|
+
WebSocket hijacking. A reverse proxy must preserve the public `Host` and overwrite
|
|
81
|
+
`X-Forwarded-Proto` with the trusted public protocol. If it rewrites either value, add the public
|
|
82
|
+
origin explicitly to `websocket.allowedOrigins` instead of relying on implicit same-origin
|
|
83
|
+
detection.
|
|
41
84
|
|
|
42
85
|
### Authentication
|
|
43
86
|
|
|
44
|
-
Authenticate sockets during the HTTP upgrade with `websocket.authenticate`. The hook receives
|
|
45
|
-
|
|
87
|
+
Authenticate sockets during the HTTP upgrade with `websocket.authenticate`. The hook receives an
|
|
88
|
+
AdonisJS HTTP context and returns the authenticated user.
|
|
46
89
|
|
|
47
90
|
Define `websocket.middleware` when your WebSocket upgrade authentication depends on AdonisJS
|
|
48
91
|
middleware such as sessions or auth initialization. These middleware run only for the HTTP upgrade
|
|
@@ -54,43 +97,49 @@ channel itself through `static middlewares`.
|
|
|
54
97
|
|
|
55
98
|
```ts
|
|
56
99
|
// config/socket.ts
|
|
57
|
-
import { defineConfig } from '@
|
|
100
|
+
import { authenticateWithAdonisAuth, defineConfig } from '@rlanz/socket'
|
|
58
101
|
|
|
59
|
-
|
|
102
|
+
type User = { id: string | number; name: string }
|
|
103
|
+
|
|
104
|
+
export default defineConfig<User>({
|
|
60
105
|
websocket: {
|
|
61
106
|
middleware: [
|
|
62
107
|
() => import('@adonisjs/session/session_middleware'),
|
|
63
108
|
() => import('@adonisjs/auth/initialize_auth_middleware'),
|
|
64
109
|
],
|
|
65
110
|
|
|
66
|
-
|
|
67
|
-
await httpContext!.auth.authenticateUsing()
|
|
68
|
-
const user = httpContext!.auth.getUserOrFail()
|
|
69
|
-
|
|
70
|
-
return {
|
|
71
|
-
user,
|
|
72
|
-
auth,
|
|
73
|
-
data: {
|
|
74
|
-
connectedAt: new Date(),
|
|
75
|
-
},
|
|
76
|
-
}
|
|
77
|
-
},
|
|
111
|
+
authenticate: authenticateWithAdonisAuth<User>(),
|
|
78
112
|
},
|
|
79
113
|
})
|
|
80
114
|
```
|
|
81
115
|
|
|
82
|
-
Return `false`, `null`, or throw to reject the upgrade with `401 Unauthorized`. The returned
|
|
83
|
-
|
|
84
|
-
|
|
116
|
+
Return `false`, `null`, or throw to reject the upgrade with `401 Unauthorized`. The returned user is
|
|
117
|
+
available as `socket.user`. Every connected socket retains the initial Adonis HTTP context at
|
|
118
|
+
`socket.raw.httpContext`; use `socket.raw.data` for mutable socket-lifetime state.
|
|
119
|
+
|
|
120
|
+
The retained HTTP context describes the initial upgrade handshake. After the `101` response, it is
|
|
121
|
+
not an active HTTP request: do not write through `httpContext.response` or expect it to remain
|
|
122
|
+
available through AdonisJS async-local storage. The upgrade pipeline receives the context explicitly
|
|
123
|
+
and does not install it in async-local storage during the handshake either. Copy durable values into
|
|
124
|
+
`socket.user` or `socket.raw.data` instead of keeping response-bound resources alive.
|
|
125
|
+
|
|
126
|
+
Override `websocket.authenticate` when you need custom behavior:
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
async authenticate({ httpContext }) {
|
|
130
|
+
await httpContext.auth.authenticateUsing()
|
|
131
|
+
return httpContext.auth.getUserOrFail()
|
|
132
|
+
}
|
|
133
|
+
```
|
|
85
134
|
|
|
86
135
|
### Horizontal Sync
|
|
87
136
|
|
|
88
|
-
Configure an [`@boringnode/bus`](https://github.com/boringnode/bus) transport to synchronize broadcasts across multiple
|
|
137
|
+
Configure an [`@boringnode/bus`](https://github.com/boringnode/bus) transport to synchronize broadcasts across multiple application instances.
|
|
89
138
|
|
|
90
139
|
```ts
|
|
91
140
|
// config/socket.ts
|
|
92
|
-
import { defineConfig } from '@adonisjs/core/config'
|
|
93
141
|
import { redis } from '@boringnode/bus/transports/redis'
|
|
142
|
+
import { defineConfig } from '@rlanz/socket'
|
|
94
143
|
|
|
95
144
|
export default defineConfig({
|
|
96
145
|
transport: {
|
|
@@ -99,14 +148,14 @@ export default defineConfig({
|
|
|
99
148
|
port: 6379,
|
|
100
149
|
}),
|
|
101
150
|
channel: 'socket::broadcast',
|
|
102
|
-
presenceTimeout:
|
|
151
|
+
presenceTimeout: '100ms',
|
|
103
152
|
},
|
|
104
153
|
})
|
|
105
154
|
```
|
|
106
155
|
|
|
107
156
|
When configured, `socket.to(channel).emit(...)`, `socket.to(channel).except(socketId).emit(...)`, `socket.toUser(userId).emit(...)`, and `socket.broadcast(...)` are delivered locally and published to the bus so other instances can deliver them to their own connected sockets.
|
|
108
157
|
|
|
109
|
-
The default bus channel is `socket::broadcast`. Presence channels also use the bus to build distributed snapshots during subscribe, duplicate subscribe, join, and leave updates. `presenceTimeout` controls how long an instance waits for other instances to answer a presence snapshot request; it defaults to `
|
|
158
|
+
The default bus channel is `socket::broadcast`. Presence channels also use the bus to build distributed snapshots during subscribe, duplicate subscribe, join, and leave updates. `presenceTimeout` controls how long an instance waits for other instances to answer a presence snapshot request; it defaults to `100ms`.
|
|
110
159
|
|
|
111
160
|
### Health Checks
|
|
112
161
|
|
|
@@ -187,9 +236,241 @@ instrumentation.manuallyRegister()
|
|
|
187
236
|
|
|
188
237
|
The instrumentation creates spans for socket connect/disconnect, subscribe/unsubscribe, incoming channel messages, and broadcast delivery. It also records counters for active connections, active subscriptions, received channel messages, broadcast operations, and broadcast deliveries.
|
|
189
238
|
|
|
239
|
+
## Production and scaling
|
|
240
|
+
|
|
241
|
+
### Process and reverse proxy
|
|
242
|
+
|
|
243
|
+
The provider attaches its WebSocket `upgrade` handler to the AdonisJS Node HTTP server after that
|
|
244
|
+
server is ready. WebSockets therefore use the same process, listener, event loop, memory, and failure
|
|
245
|
+
domain as HTTP; there is no separate socket process or port. Size each application instance for its
|
|
246
|
+
combined HTTP and long-lived WebSocket workload, and remember that a process failure drops every
|
|
247
|
+
socket connected to that instance.
|
|
248
|
+
|
|
249
|
+
At the reverse proxy or load balancer:
|
|
250
|
+
|
|
251
|
+
- route `websocket.path` to the AdonisJS HTTP listener and forward WebSocket upgrade requests using
|
|
252
|
+
HTTP/1.1 with the `Upgrade` and `Connection: upgrade` headers;
|
|
253
|
+
- terminate TLS there if desired, use `wss://` publicly, preserve a validated public `Host`, and
|
|
254
|
+
**overwrite** `X-Forwarded-Proto` with the trusted public protocol (`http` or `https`);
|
|
255
|
+
- allow long-lived upgraded connections and set the proxy idle timeout above the configured
|
|
256
|
+
heartbeat cadence; and
|
|
257
|
+
- restrict direct access to the upstream. Same-origin validation trusts `Host` and the first
|
|
258
|
+
`X-Forwarded-Proto` value, so client-supplied versions of those headers must not reach the app.
|
|
259
|
+
|
|
260
|
+
Browser origins are not authorized by AdonisJS CORS middleware. Configure exact public origins in
|
|
261
|
+
[`websocket.allowedOrigins`](#configuration) when the browser origin differs from the public socket
|
|
262
|
+
origin or when the proxy rewrites `Host`. Clients without an `Origin` header are accepted, so use
|
|
263
|
+
upgrade authentication for non-browser clients rather than treating the origin check as
|
|
264
|
+
authentication.
|
|
265
|
+
|
|
266
|
+
### Multiple instances and reconnects
|
|
267
|
+
|
|
268
|
+
A load balancer may route each new upgrade to any ready instance and must keep that upgraded TCP
|
|
269
|
+
connection attached to that instance. The package neither implements nor guarantees sticky
|
|
270
|
+
sessions. Without a [transport](#horizontal-sync), subscriptions, user rooms, broadcasts, and
|
|
271
|
+
presence are local to one instance; affinity is not a replacement for configuring the transport.
|
|
272
|
+
All instances in one logical deployment must use a compatible shared transport and the same bus
|
|
273
|
+
channel.
|
|
274
|
+
|
|
275
|
+
The bundled client reconnects by default with exponential backoff from `250ms` to `5s` and
|
|
276
|
+
re-subscribes desired channels after establishing a new connection, which may be on another
|
|
277
|
+
instance. A reconnect is a new session: pending acknowledgements are rejected, authentication and
|
|
278
|
+
channel middleware run again, and events sent while disconnected are not replayed. The built-in
|
|
279
|
+
backoff has no jitter; stagger deployments or add reconnect staggering in the application when a
|
|
280
|
+
large fleet could reconnect simultaneously.
|
|
281
|
+
|
|
282
|
+
### Transport, presence, and delivery semantics
|
|
283
|
+
|
|
284
|
+
Local broadcasts are sent to currently connected local recipients and are also published to the
|
|
285
|
+
configured `@boringnode/bus` transport. Publication is fire-and-forget from the socket API. This
|
|
286
|
+
package does not persist bus messages, wait for remote delivery, acknowledge recipients, or replay
|
|
287
|
+
missed events; the guarantees of a particular transport do not turn socket delivery into a durable
|
|
288
|
+
application queue.
|
|
289
|
+
|
|
290
|
+
Distributed presence is also best-effort and non-durable. A snapshot contains the replies received
|
|
291
|
+
before `transport.presenceTimeout`; partitions, slow instances, concurrent changes, and restarts can
|
|
292
|
+
produce incomplete snapshots or duplicate/omitted member transitions. Presence hooks must be
|
|
293
|
+
idempotent and presence must not be used as an authoritative online-user or membership store.
|
|
294
|
+
|
|
295
|
+
`sendWithAck()` only confirms that the receiving server-side handler completed and returned a
|
|
296
|
+
result. It does not confirm that a broadcast reached any client. Applications that need durable
|
|
297
|
+
notifications, recovery after reconnect, or at-least-once processing must persist events or state
|
|
298
|
+
outside this package and define their own event IDs, cursors, deduplication, acknowledgement, and
|
|
299
|
+
replay protocol.
|
|
300
|
+
|
|
301
|
+
### Restarts and resource limits
|
|
302
|
+
|
|
303
|
+
On AdonisJS shutdown, the service becomes unready, stops accepting upgrades, terminates existing
|
|
304
|
+
WebSockets, runs their subscription/disconnect finalizers, and then disconnects the bus. It does
|
|
305
|
+
**not** gracefully drain established sockets or wait for in-flight client acknowledgements. For a
|
|
306
|
+
rolling restart, remove the instance from new HTTP/upgrade traffic first when the platform permits,
|
|
307
|
+
expect connected clients to reconnect, and give the process enough termination grace to finish its
|
|
308
|
+
socket finalizers and bus shutdown before sending a forced kill.
|
|
309
|
+
|
|
310
|
+
Review the limits under [Configuration](#configuration) against real payloads and fan-out:
|
|
311
|
+
|
|
312
|
+
- enable heartbeat explicitly; it is disabled when neither `pingInterval` nor `pingTimeout` is set;
|
|
313
|
+
- tune inbound/outbound payload sizes, the per-socket fixed-window message rate, serialized message
|
|
314
|
+
queue depth, subscriptions per socket, and channel-name length;
|
|
315
|
+
- treat rate and queue limits as per-connection safeguards, not perimeter abuse prevention; enforce
|
|
316
|
+
aggregate connection and request limits at the proxy or application boundary; and
|
|
317
|
+
- tune `maxBufferedAmount` for available memory. Slow consumers and oversized outbound frames are
|
|
318
|
+
disconnected rather than buffered without bound or retried.
|
|
319
|
+
|
|
320
|
+
There is no built-in total connection limit. Each connection consumes a file descriptor plus
|
|
321
|
+
application, subscription, queue, heartbeat, and `ws` memory. Set process/container memory limits,
|
|
322
|
+
raise and monitor file-descriptor limits where appropriate, cap connections at the edge, and load
|
|
323
|
+
test representative connection counts, message rates, payloads, and broadcast fan-out before
|
|
324
|
+
production.
|
|
325
|
+
|
|
326
|
+
### Health and monitoring
|
|
327
|
+
|
|
328
|
+
Expose the application-owned readiness endpoint containing [`SocketHealthCheck`](#health-checks)
|
|
329
|
+
and route new upgrades only to ready instances. The check reports local service startup/shutdown
|
|
330
|
+
state and local connection/channel counts; it does not probe the transport backend, remote
|
|
331
|
+
instances, or end-to-end publish delivery. Monitor those dependencies separately and keep a normal
|
|
332
|
+
process liveness check so readiness failures do not automatically cause restart loops.
|
|
333
|
+
|
|
334
|
+
Enable the optional [OpenTelemetry instrumentation](#opentelemetry) and alert on connection and
|
|
335
|
+
disconnection changes, active connections/subscriptions, message errors, and broadcast volume and
|
|
336
|
+
local delivery counts. Also collect process event-loop delay, memory, CPU, open file descriptors,
|
|
337
|
+
proxy upgrade/rejection metrics, reconnect rates, logs, and transport health. Broadcast delivery
|
|
338
|
+
counters count immediate sends to local `ws` objects, not application-level receipt.
|
|
339
|
+
|
|
340
|
+
### Production checklist
|
|
341
|
+
|
|
342
|
+
- [ ] Proxy upgrades on the configured path with HTTP/1.1 `Upgrade`/`Connection` headers.
|
|
343
|
+
- [ ] Terminate TLS safely; preserve a validated public `Host` and overwrite `X-Forwarded-Proto`.
|
|
344
|
+
- [ ] Configure exact `allowedOrigins` and upgrade authentication; protect the upstream from direct
|
|
345
|
+
access.
|
|
346
|
+
- [ ] Set proxy idle timeouts and explicitly configure/test heartbeat behavior.
|
|
347
|
+
- [ ] Configure a shared transport and bus channel for every instance that must exchange broadcasts
|
|
348
|
+
or presence.
|
|
349
|
+
- [ ] Make clients tolerate reconnect, re-authentication, re-subscription, duplicate handling, and
|
|
350
|
+
gaps during deploys or failures.
|
|
351
|
+
- [ ] Persist and replay application-critical events outside the socket bus.
|
|
352
|
+
- [ ] Tune payload, rate, queue, subscription, backpressure, connection, memory, and file-descriptor
|
|
353
|
+
limits using load tests.
|
|
354
|
+
- [ ] Wire readiness, liveness, OpenTelemetry, logs, proxy metrics, and transport monitoring.
|
|
355
|
+
- [ ] Give rolling shutdown enough grace for finalizers and bus disconnect; do not expect socket
|
|
356
|
+
draining.
|
|
357
|
+
|
|
190
358
|
## Channels
|
|
191
359
|
|
|
192
|
-
Channels are discovered from `app/channels/**/*_channel.{ts,js}`. Export a default class extending
|
|
360
|
+
Channels are discovered from `app/channels/**/*_channel.{ts,js}`. Export a default class extending
|
|
361
|
+
`BaseChannel`. Client-to-server payloads and acknowledgements are inferred from public handler
|
|
362
|
+
methods. The optional second generic declares server-to-client events and defaults to `unknown`.
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
// app/channels/chat_channel.ts
|
|
366
|
+
import { BaseChannel } from '@rlanz/socket'
|
|
367
|
+
import type { AuthenticatedSocket } from '@rlanz/socket/types'
|
|
368
|
+
|
|
369
|
+
type User = { id: string; name: string }
|
|
370
|
+
type Message = { id: string; text: string }
|
|
371
|
+
|
|
372
|
+
type ServerEvents = {
|
|
373
|
+
'chat:message': Message
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export default class ChatChannel extends BaseChannel<User, ServerEvents> {
|
|
377
|
+
static pattern = 'chat/:roomId'
|
|
378
|
+
|
|
379
|
+
protected handlers = {
|
|
380
|
+
'chat:send': this.sendMessage,
|
|
381
|
+
'chat:ping': this.ping,
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
async sendMessage(
|
|
385
|
+
socket: AuthenticatedSocket<User>,
|
|
386
|
+
payload: { text: string }
|
|
387
|
+
): Promise<Message> {
|
|
388
|
+
const message = { id: crypto.randomUUID(), text: payload.text }
|
|
389
|
+
this.broadcastExcept(socket.id, 'chat:message', message)
|
|
390
|
+
return message
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
ping(_socket: AuthenticatedSocket<User>, _payload: undefined): void {}
|
|
394
|
+
}
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
The event name comes from `handlers` or `@onMessage('event')`, the handler's second parameter becomes
|
|
398
|
+
the client payload, and `Awaited<ReturnType<handler>>` becomes its acknowledgement. No duplicate
|
|
399
|
+
client event map is required. `ServerEvents` remains explicit because generation does not scan
|
|
400
|
+
`broadcast()` calls; it checks `broadcast()` and `broadcastExcept()`. Omitting it preserves the broad
|
|
401
|
+
legacy broadcast API:
|
|
402
|
+
|
|
403
|
+
```ts
|
|
404
|
+
export default class ChatChannel extends BaseChannel<User> {
|
|
405
|
+
// Server events remain unknown and may be typed by callers when listening.
|
|
406
|
+
}
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
The Assembler hook generates an explicit `AppSocket` registry. Pass it once to the browser client:
|
|
410
|
+
|
|
411
|
+
```ts
|
|
412
|
+
import { Socket } from '@rlanz/socket/client'
|
|
413
|
+
import type { AppSocket } from '#generated/socket'
|
|
414
|
+
|
|
415
|
+
const socket = new Socket<AppSocket>()
|
|
416
|
+
const channel = socket.channel('chat/general')
|
|
417
|
+
|
|
418
|
+
channel.listen('chat:message', (message) => console.log(message.id))
|
|
419
|
+
channel.send('chat:ping')
|
|
420
|
+
|
|
421
|
+
const message = await channel.sendWithAck('chat:send', { text: 'Hello' })
|
|
422
|
+
console.log(message.id)
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
The scanner recognizes default-exported classes that directly extend `BaseChannel`, direct
|
|
426
|
+
string-literal `static pattern` values, and handlers declared as `'event': this.publicMethod`. It also
|
|
427
|
+
recognizes `@onMessage('event')` imported from `@rlanz/socket/decorators`. Handler methods must be
|
|
428
|
+
named, public instance methods so the generated registry can reference their parameter and return
|
|
429
|
+
types. Abstract channels, inline/computed handlers, private/protected/static methods, rest parameters,
|
|
430
|
+
and required parameters after the payload fail generation with a diagnostic. A handler may accept no
|
|
431
|
+
parameters, only the socket, a required payload, or an optional payload. Intermediate channel
|
|
432
|
+
inheritance is deliberately omitted from generated contracts and makes the client registry
|
|
433
|
+
uncertain; runtime channel inheritance remains valid.
|
|
434
|
+
|
|
435
|
+
The default Assembler hook discovers `app/channels/**/*_channel.{ts,js}` and generates both
|
|
436
|
+
`.adonisjs/client/socket.ts` and `.adonisjs/server/socket_channels.ts`. Configure the frontend
|
|
437
|
+
project to resolve an alias such as `#generated/socket` to the client file; this frontend mapping is
|
|
438
|
+
separate from the AdonisJS server `#generated/*` mapping. Generated channel imports are relative by
|
|
439
|
+
default, so an `importAlias` is optional. To customize discovery, replace the package hook in
|
|
440
|
+
`adonisrc.ts` with a local hook:
|
|
441
|
+
|
|
442
|
+
```ts
|
|
443
|
+
// hooks/socket.ts
|
|
444
|
+
import { generateSocketRegistry } from '@rlanz/socket/assembler_hook'
|
|
445
|
+
|
|
446
|
+
export default generateSocketRegistry({
|
|
447
|
+
source: 'realtime',
|
|
448
|
+
glob: ['**/*.ts'],
|
|
449
|
+
output: '.adonisjs/client/socket.d.ts',
|
|
450
|
+
importAlias: '#realtime',
|
|
451
|
+
})
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
```ts
|
|
455
|
+
// adonisrc.ts
|
|
456
|
+
export default defineConfig({
|
|
457
|
+
providers: [() => import('@rlanz/socket/provider')],
|
|
458
|
+
hooks: {
|
|
459
|
+
init: [() => import('./hooks/socket.js')],
|
|
460
|
+
},
|
|
461
|
+
})
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
Generated matching supports literals, required parameters, a final optional parameter, and a final
|
|
465
|
+
wildcard. Dynamic or unsupported patterns are omitted and mark the registry uncertain, causing
|
|
466
|
+
`Socket<AppSocket>` to fall back conservatively to untyped channels. Plain dynamic channel names and
|
|
467
|
+
ambiguous matches also remain untyped; unmatched concrete literals are rejected when the registry is
|
|
468
|
+
certain. Generation provides compile-time types only and does not validate runtime payloads.
|
|
469
|
+
Whispers intentionally remain caller-generic because they are peer-to-peer. Runtime channel files
|
|
470
|
+
always come from the generated server manifest; the former `channels.patterns` runtime setting is no
|
|
471
|
+
longer supported and is rejected to prevent a second discovery source.
|
|
472
|
+
|
|
473
|
+
Legacy untyped channels remain supported without the generated generic:
|
|
193
474
|
|
|
194
475
|
```ts
|
|
195
476
|
// app/channels/chat_channel.ts
|
|
@@ -220,14 +501,14 @@ export default class ChatChannel extends BaseChannel<User> {
|
|
|
220
501
|
Middlewares run before subscription. They may be functions or objects with a `handle` method.
|
|
221
502
|
|
|
222
503
|
```ts
|
|
223
|
-
import { BaseChannel } from '@rlanz/socket'
|
|
504
|
+
import { BaseChannel, SocketResponseError } from '@rlanz/socket'
|
|
224
505
|
import type { MiddlewareContext } from '@rlanz/socket/types'
|
|
225
506
|
|
|
226
507
|
type User = { id: string; name: string }
|
|
227
508
|
|
|
228
509
|
async function auth(ctx: MiddlewareContext<User>, next: () => Promise<void>) {
|
|
229
510
|
if (!ctx.socket.user) {
|
|
230
|
-
throw new
|
|
511
|
+
throw new SocketResponseError('Unauthorized')
|
|
231
512
|
}
|
|
232
513
|
|
|
233
514
|
await ctx.socket.joinUserRoom(ctx.socket.user.id)
|
|
@@ -240,13 +521,18 @@ export default class ChatChannel extends BaseChannel<User> {
|
|
|
240
521
|
}
|
|
241
522
|
```
|
|
242
523
|
|
|
524
|
+
Only `SocketResponseError` messages are intentionally exposed to clients. Unexpected middleware,
|
|
525
|
+
join, and message-handler errors are logged server-side and replaced with a generic protocol error,
|
|
526
|
+
so internal exception details do not leak. Use `SocketResponseError` only for safe, user-facing
|
|
527
|
+
messages.
|
|
528
|
+
|
|
243
529
|
### Presence
|
|
244
530
|
|
|
245
531
|
Enable presence with `static options = { presence: true }` and implement `getPresenceInfo`.
|
|
246
532
|
|
|
247
533
|
```ts
|
|
248
534
|
import { BaseChannel } from '@rlanz/socket'
|
|
249
|
-
import type { AuthenticatedSocket, PresenceMember } from '@rlanz/socket/types'
|
|
535
|
+
import type { AuthenticatedSocket, PresenceInfo, PresenceMember } from '@rlanz/socket/types'
|
|
250
536
|
|
|
251
537
|
type User = { id: string; name: string }
|
|
252
538
|
|
|
@@ -254,10 +540,12 @@ export default class RoomChannel extends BaseChannel<User> {
|
|
|
254
540
|
static pattern = 'rooms/:roomId'
|
|
255
541
|
static options = { presence: true }
|
|
256
542
|
|
|
257
|
-
getPresenceInfo(socket: AuthenticatedSocket<User>):
|
|
543
|
+
getPresenceInfo(socket: AuthenticatedSocket<User>): PresenceInfo {
|
|
258
544
|
return {
|
|
259
545
|
id: socket.user!.id,
|
|
260
|
-
|
|
546
|
+
data: {
|
|
547
|
+
name: socket.user!.name,
|
|
548
|
+
},
|
|
261
549
|
}
|
|
262
550
|
}
|
|
263
551
|
|
|
@@ -271,6 +559,28 @@ export default class RoomChannel extends BaseChannel<User> {
|
|
|
271
559
|
}
|
|
272
560
|
```
|
|
273
561
|
|
|
562
|
+
The `id` identifies one member across multiple sockets or browser tabs. The optional `data` object
|
|
563
|
+
defines the channel-specific public fields exposed on that member. Snapshots and member hooks flatten
|
|
564
|
+
these values into `{ id, ...data, joinedAt }`.
|
|
565
|
+
|
|
566
|
+
Custom presence fields are not normalized or recursively validated. WebSocket and distributed
|
|
567
|
+
transport serialization may transform them, so use JSON-compatible values when local and distributed
|
|
568
|
+
snapshots must have the same shape.
|
|
569
|
+
|
|
570
|
+
Presence is exposed per user ID: multiple sockets or browser tabs for the same ID remain separate
|
|
571
|
+
broadcast destinations but produce one `users` entry and contribute one to `count`. `onMemberJoin`
|
|
572
|
+
runs for the first locally observed connection and `onMemberLeave` for the last; `onJoin` and
|
|
573
|
+
`onLeave` still run for every socket. Across multiple application instances, member hooks are
|
|
574
|
+
best-effort and must be idempotent because concurrent joins, leaves, timeouts, or partitions can
|
|
575
|
+
duplicate or omit a transition. When two connections provide different metadata, the earliest
|
|
576
|
+
connection is the representative. Distributed snapshots are deduplicated across the responses
|
|
577
|
+
received before `transport.presenceTimeout` and therefore remain a best-effort, non-durable view
|
|
578
|
+
during network partitions.
|
|
579
|
+
|
|
580
|
+
Presence snapshots are validated for JSON serialization before join hooks run. Hooks can still
|
|
581
|
+
perform arbitrary external side effects and are not database transactions; keep them idempotent so
|
|
582
|
+
an exception from a later hook can be retried safely.
|
|
583
|
+
|
|
274
584
|
## Channel Messages
|
|
275
585
|
|
|
276
586
|
Incoming client messages are handled through the `handlers` map, the `@onMessage` decorator, or the `onMessage` fallback.
|
|
@@ -280,18 +590,15 @@ import { BaseChannel } from '@rlanz/socket'
|
|
|
280
590
|
import type { AuthenticatedSocket } from '@rlanz/socket/types'
|
|
281
591
|
|
|
282
592
|
type User = { id: string; name: string }
|
|
283
|
-
type Events = {
|
|
284
|
-
'chat:send': { body: string }
|
|
285
|
-
}
|
|
286
593
|
|
|
287
|
-
export default class ChatChannel extends BaseChannel<User
|
|
594
|
+
export default class ChatChannel extends BaseChannel<User> {
|
|
288
595
|
static pattern = 'chat/:roomId'
|
|
289
596
|
|
|
290
597
|
protected handlers = {
|
|
291
598
|
'chat:send': this.sendMessage,
|
|
292
599
|
}
|
|
293
600
|
|
|
294
|
-
async sendMessage(socket: AuthenticatedSocket<User>, data:
|
|
601
|
+
async sendMessage(socket: AuthenticatedSocket<User>, data: { body: string }) {
|
|
295
602
|
this.broadcast('chat:message', {
|
|
296
603
|
user: socket.user,
|
|
297
604
|
body: data.body,
|
|
@@ -306,7 +613,10 @@ export default class ChatChannel extends BaseChannel<User, Events> {
|
|
|
306
613
|
}
|
|
307
614
|
```
|
|
308
615
|
|
|
309
|
-
Returning a value from a handler resolves `sendWithAck()` on the client.
|
|
616
|
+
Returning a value from a handler resolves `sendWithAck()` on the client. Handler results and
|
|
617
|
+
presence snapshots must be JSON-serializable. A non-serializable handler result receives an
|
|
618
|
+
immediate negative acknowledgement; a non-serializable initial presence snapshot rolls back the
|
|
619
|
+
subscription instead of leaving client and server state out of sync.
|
|
310
620
|
|
|
311
621
|
### Client-to-client events
|
|
312
622
|
|
|
@@ -337,7 +647,6 @@ import { Socket } from '@rlanz/socket/client'
|
|
|
337
647
|
const socket = new Socket({
|
|
338
648
|
url: 'http://localhost:3333',
|
|
339
649
|
path: '/socket',
|
|
340
|
-
auth: { token: 'secret' },
|
|
341
650
|
autoReconnect: true,
|
|
342
651
|
reconnectDelay: 250,
|
|
343
652
|
reconnectMaxDelay: 5000,
|
|
@@ -393,14 +702,122 @@ The client reconnects automatically by default. `reconnectDelay` is the initial
|
|
|
393
702
|
milliseconds, and each failed retry doubles the delay until `reconnectMaxDelay` is reached.
|
|
394
703
|
Set `autoReconnect: false` to disable reconnect attempts.
|
|
395
704
|
|
|
705
|
+
### React, Vue, and Svelte
|
|
706
|
+
|
|
707
|
+
Framework adapters keep the generated `AppSocket` type at one application-level factory. Channel
|
|
708
|
+
names, client methods, server events, and payloads then remain inferred without repeating the
|
|
709
|
+
generic in every component.
|
|
710
|
+
|
|
711
|
+
React:
|
|
712
|
+
|
|
713
|
+
```tsx
|
|
714
|
+
// src/socket.ts
|
|
715
|
+
import { Socket } from '@rlanz/socket/client'
|
|
716
|
+
import { createSocketHooks } from '@rlanz/socket/client/react'
|
|
717
|
+
import type { AppSocket } from '#generated/socket'
|
|
718
|
+
|
|
719
|
+
export const socket = new Socket<AppSocket>()
|
|
720
|
+
export const { SocketProvider, useChannel, useChannelEvent, useSocketState } =
|
|
721
|
+
createSocketHooks<AppSocket>()
|
|
722
|
+
|
|
723
|
+
// app.tsx
|
|
724
|
+
<SocketProvider socket={socket} owned>
|
|
725
|
+
<Chat />
|
|
726
|
+
</SocketProvider>
|
|
727
|
+
|
|
728
|
+
function Chat() {
|
|
729
|
+
const channel = useChannel('chat/general')
|
|
730
|
+
useChannelEvent('chat/general', 'chat:message', (message) => console.log(message.id))
|
|
731
|
+
|
|
732
|
+
return <button onClick={() => channel?.send('chat:send', { text: 'Hello' })}>Send</button>
|
|
733
|
+
}
|
|
734
|
+
```
|
|
735
|
+
|
|
736
|
+
Vue:
|
|
737
|
+
|
|
738
|
+
```ts
|
|
739
|
+
// src/socket.ts
|
|
740
|
+
import { Socket } from '@rlanz/socket/client'
|
|
741
|
+
import { createSocketComposables } from '@rlanz/socket/client/vue'
|
|
742
|
+
import type { AppSocket } from '#generated/socket'
|
|
743
|
+
|
|
744
|
+
export const socket = new Socket<AppSocket>()
|
|
745
|
+
export const { provideSocket, useChannel, useChannelEvent, useSocketState } =
|
|
746
|
+
createSocketComposables<AppSocket>()
|
|
747
|
+
|
|
748
|
+
// In the root component setup
|
|
749
|
+
provideSocket(socket, { owned: true })
|
|
750
|
+
|
|
751
|
+
// In a descendant component setup
|
|
752
|
+
const channel = useChannel('chat/general')
|
|
753
|
+
useChannelEvent('chat/general', 'chat:message', (message) => console.log(message.id))
|
|
754
|
+
|
|
755
|
+
function send() {
|
|
756
|
+
channel.value?.send('chat:send', { text: 'Hello' })
|
|
757
|
+
}
|
|
758
|
+
```
|
|
759
|
+
|
|
760
|
+
Svelte:
|
|
761
|
+
|
|
762
|
+
```ts
|
|
763
|
+
// src/socket.ts
|
|
764
|
+
import { Socket } from '@rlanz/socket/client'
|
|
765
|
+
import { createSocketContext } from '@rlanz/socket/client/svelte'
|
|
766
|
+
import type { AppSocket } from '#generated/socket'
|
|
767
|
+
|
|
768
|
+
export const socket = new Socket<AppSocket>()
|
|
769
|
+
export const { setSocket, useSocketState, channel, onChannelEvent } =
|
|
770
|
+
createSocketContext<AppSocket>()
|
|
771
|
+
```
|
|
772
|
+
|
|
773
|
+
```svelte
|
|
774
|
+
<!-- In the root component -->
|
|
775
|
+
<script lang="ts">
|
|
776
|
+
import { setSocket, socket } from './socket'
|
|
777
|
+
|
|
778
|
+
setSocket(socket, { owned: true })
|
|
779
|
+
</script>
|
|
780
|
+
```
|
|
781
|
+
|
|
782
|
+
```svelte
|
|
783
|
+
<!-- In a descendant component -->
|
|
784
|
+
<script lang="ts">
|
|
785
|
+
import { channel, onChannelEvent } from './socket'
|
|
786
|
+
|
|
787
|
+
const chat = channel('chat/general')
|
|
788
|
+
onChannelEvent('chat/general', 'chat:message', (message) => console.log(message.id))
|
|
789
|
+
</script>
|
|
790
|
+
|
|
791
|
+
<button on:click={() => $chat?.send('chat:send', { text: 'Hello' })}>Send</button>
|
|
792
|
+
```
|
|
793
|
+
|
|
794
|
+
Adapters acquire and share channel subscriptions, attach listeners before subscribing, and release
|
|
795
|
+
them when the component, scope, or store consumer is disposed. React returns `null` until its passive
|
|
796
|
+
effect acquires the channel; Vue exposes a nullable shallow ref and Svelte exposes a nullable readable
|
|
797
|
+
store. Multiple consumers of the same channel share one subscription, including across development
|
|
798
|
+
remounts, without removing listeners registered through the direct client API.
|
|
799
|
+
|
|
800
|
+
Sockets are borrowed by default: the adapter neither connects nor disconnects them. Pass `owned` to
|
|
801
|
+
`SocketProvider`, `{ owned: true }` to `provideSocket`, or `{ owned: true }` to `setSocket` only when
|
|
802
|
+
that framework root exclusively owns the socket lifecycle. Otherwise call `socket.connect()` and
|
|
803
|
+
`socket.disconnect()` in application-owned lifecycle code.
|
|
804
|
+
|
|
396
805
|
## Package Exports
|
|
397
806
|
|
|
398
807
|
```ts
|
|
399
|
-
import { BaseChannel, ChannelRouter, PresenceManager
|
|
808
|
+
import { BaseChannel, ChannelRouter, PresenceManager } from '@rlanz/socket'
|
|
400
809
|
import type { AuthenticatedSocket, SocketConfig } from '@rlanz/socket/types'
|
|
401
810
|
import SocketProvider from '@rlanz/socket/provider'
|
|
811
|
+
import socket from '@rlanz/socket/services/main'
|
|
402
812
|
import { onMessage } from '@rlanz/socket/decorators'
|
|
813
|
+
import { SocketHealthCheck } from '@rlanz/socket/health_check'
|
|
814
|
+
import { SocketInstrumentation } from '@rlanz/socket/otel'
|
|
815
|
+
import { SocketFake } from '@rlanz/socket/testing'
|
|
403
816
|
import { Socket, Channel } from '@rlanz/socket/client'
|
|
817
|
+
import { generateSocketRegistry } from '@rlanz/socket/assembler_hook'
|
|
818
|
+
import { createSocketHooks } from '@rlanz/socket/client/react'
|
|
819
|
+
import { createSocketComposables } from '@rlanz/socket/client/vue'
|
|
820
|
+
import { createSocketContext } from '@rlanz/socket/client/svelte'
|
|
404
821
|
import type { SocketOptions, PresenceData } from '@rlanz/socket/client/types'
|
|
405
822
|
```
|
|
406
823
|
|
|
@@ -408,7 +825,16 @@ Available exports:
|
|
|
408
825
|
|
|
409
826
|
- `@rlanz/socket`
|
|
410
827
|
- `@rlanz/socket/provider`
|
|
828
|
+
- `@rlanz/socket/assembler_hook`
|
|
829
|
+
- `@rlanz/socket/services/main`
|
|
411
830
|
- `@rlanz/socket/decorators`
|
|
831
|
+
- `@rlanz/socket/health_check`
|
|
832
|
+
- `@rlanz/socket/otel`
|
|
833
|
+
- `@rlanz/socket/testing`
|
|
412
834
|
- `@rlanz/socket/types`
|
|
835
|
+
- `@rlanz/socket/types/tracing_channels`
|
|
413
836
|
- `@rlanz/socket/client`
|
|
414
837
|
- `@rlanz/socket/client/types`
|
|
838
|
+
- `@rlanz/socket/client/react`
|
|
839
|
+
- `@rlanz/socket/client/vue`
|
|
840
|
+
- `@rlanz/socket/client/svelte`
|