@appweaver/skill 0.0.0-stage → 3.0.0

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.
@@ -0,0 +1,572 @@
1
+ # Realtime
2
+
3
+ The `@appweaver/realtime` module (`weaver module add realtime`, requires `web`) pushes events to the clients over a
4
+ WebSocket or Server-Sent Events (SSE), and lets them call custom actions. A client subscribes to the **channels** of
5
+ `createChannel` and to the **resource events** (`create`, `update`, `delete`) of the models exposing them. Nothing is
6
+ exposed unless declared, and every event is checked against the access of the subscribed user before it is sent.
7
+
8
+ The **streams** carry chunks rather than events: the tokens of an LLM answer, the bytes of a radio station, the frames of
9
+ a video. A subscriber is checked once when it subscribes, never per chunk, so they cost no access check and, on this
10
+ instance, no pub/sub round trip per chunk. See [Streams](#streams).
11
+
12
+ Every message goes through the `PubSub` contract of core: `memory` in the process, or `redis` (`@appweaver/redis`,
13
+ selected by `auto`) to the connections of every instance. The `Events` stay in the process, so the server-side
14
+ listeners still run once. The messages are JSON: the callbacks and the clients receive the dates as ISO strings.
15
+
16
+ ## Channels
17
+
18
+ ```ts
19
+ // src/realtime/index.ts (an application file, loaded at startup; a module creates its channels in its `main` part)
20
+ import { Type } from 'typebox';
21
+ import { createChannel } from '@appweaver/realtime';
22
+
23
+ export const orderShipped = createChannel({
24
+ name: 'order.shipped',
25
+ payload: Type.Object({
26
+ orderId: Type.Integer(),
27
+ customerId: Type.Integer(),
28
+ carrier: Type.String()
29
+ }),
30
+ params: Type.Object({ orderId: Type.Optional(Type.Integer()) }),
31
+ roles: ['customer', 'admin'],
32
+ subscribe: (user, params) => true, // once, when the client subscribes
33
+ deliver: (
34
+ user,
35
+ payload,
36
+ params // for every payload and subscription
37
+ ) =>
38
+ payload.customerId === user?.id &&
39
+ (!params.orderId || params.orderId === payload.orderId)
40
+ });
41
+
42
+ await orderShipped.publish({ orderId: 7, customerId: 1, carrier: 'DHL' }); // validated against `payload`
43
+ ```
44
+
45
+ | Option | Description |
46
+ |----------------------------------|-------------------------------------------------------------------------------------------|
47
+ | `name` | `[a-zA-Z0-9][\w.:-]*`, unique, never starting with `resource:` |
48
+ | `payload`, `params` | TypeBox schemas of the payloads and of the subscription parameters |
49
+ | `public`, `roles`, `permissions` | Who may subscribe, see [Access](#access) |
50
+ | `subscribe`, `deliver` | Return false to deny the subscription, or to keep a payload from it. They run as the user |
51
+ | `description` | Description in the OpenAPI document |
52
+
53
+ The payloads and parameters of the channels and the payloads of the actions are validated with TypeBox, failing with
54
+ `REALTIME_PAYLOAD_INVALID`. The string formats work as on the HTTP routes (`date-time`, `date`, `time`, `email`, `uri`,
55
+ `uuid`, `ipv4`, `ipv6`, `hostname`), registered by `registerSchemaFormats` of `@appweaver/common` unless the
56
+ application registered its own with `Format.Set` of `typebox/format`:
57
+
58
+ ```ts
59
+ payload: Type.Object({
60
+ text: Type.String(),
61
+ sentAt: Type.String({ format: 'date-time' })
62
+ });
63
+ ```
64
+
65
+ ## Resource events
66
+
67
+ ```ts
68
+ createRoutes({
69
+ modelName: 'product',
70
+ events: {
71
+ actions: [
72
+ 'create', // the access of the events: roles ['staff']
73
+ { action: 'update', public: true }, // an access of its own, replacing it
74
+ { action: 'delete', roles: ['admin'] }
75
+ ],
76
+ roles: ['staff']
77
+ }
78
+ });
79
+ ```
80
+
81
+ An action takes the access (`public`, `roles`, `permissions`) of its object, else of the `events`, else of the `find`
82
+ route (its own config or the `defaults` of the routes, its route registered or not): an event delivers a record, so by
83
+ default the users reading it through the API receive it, while the write routes keep their own access.
84
+
85
+ The model exposes `resource:Product` (every action the user has the access of, refused when none) and
86
+ `resource:Product.<action>`. The event data is `{ model, action, current, previous? }`, the records the service
87
+ returned to the request writing them (the same virtual field values, relation counts and hidden soft deleted
88
+ relations), projected onto the `find` response schema of the model, relations included, so without the hidden fields;
89
+ the `omit` of a view of the model does not apply to its events. The relations are restricted for each subscriber, as
90
+ it: a related record the `readRestrictions` of its model's policy hide from the subscriber is left out of a list and
91
+ `null` as a single relation (also when only the database could match them, i.e. a relation filter), and the count of a
92
+ relation whose model restricts the subscriber is left out, since it was counted for the writer. A subscription
93
+ `filter` in the query filter syntax of the routes (`{ status: 'open', total: { _gt: 100 } }`) is matched against the
94
+ scalar fields of `current`; a relation filter matches nothing.
95
+
96
+ ### The `events` policy
97
+
98
+ Before an event reaches a user, `ResourceService.checkEventAccess` runs as that user (`null` when anonymous):
99
+
100
+ 1. the `events` callback of the policy decides alone, when defined;
101
+ 2. otherwise the `checkAccess` of a `find` must pass, and the record must match the `readRestrictions` of the `find`,
102
+ matched in memory (`AND`, `OR`, `NOT`, `equals`, `not`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `contains`,
103
+ `startsWith`, `endsWith`, `mode`), or by a `count` of the database when they filter by a relation. A deleted record
104
+ only the database can match is denied.
105
+
106
+ ```ts
107
+ createPolicy({
108
+ modelName: 'order',
109
+ events: (user, { action, current, previous }) =>
110
+ (!!user && hasRole(user, 'admin')) || current.customerId === user?.id
111
+ });
112
+ ```
113
+
114
+ The access is checked once per event and user, on every instance holding a connection of the user. A service of
115
+ `createService` overrides `eventAccess(event)` for the same. The records of the pub/sub messages hold the hidden
116
+ fields, so the Redis server must be as private as the database.
117
+
118
+ > **Known limitation: relation restrictions cost a query per user and event.** Without an `events` callback, a model
119
+ > whose `readRestrictions` filter by a relation (`{ team: { members: { some: { userId } } } }`) is checked with one
120
+ > `count` of the database for every event and every distinct subscribed user: 1,000 users on `resource:Post` and 50
121
+ > post updates a second make 50,000 queries a second. The number of connections of a user does not matter, the number
122
+ > of users does. A busy model with such restrictions defines the `events` callback, checked in memory:
123
+ >
124
+ > ```ts
125
+ > createPolicy({
126
+ > modelName: 'post',
127
+ > readRestrictions: (user) => ({
128
+ > team: { members: { some: { userId: user?.id } } }
129
+ > }),
130
+ > events: (user, { current }) =>
131
+ > !!user && userTeamIds(user).includes(current.teamId)
132
+ > });
133
+ > ```
134
+
135
+ ## Actions
136
+
137
+ Custom operations only: CRUD keeps its routes, validation and policies.
138
+
139
+ ```ts
140
+ createRealtimeAction({
141
+ name: 'chat.typing',
142
+ payload: Type.Object({ roomId: Type.Integer() }),
143
+ response: Type.Object({ seen: Type.Integer() }),
144
+ roles: ['user'],
145
+ handler: async ({ roomId }, { user, transport, connectionId, ack }) => ({
146
+ seen: 3
147
+ }) // runs as the user
148
+ });
149
+ ```
150
+
151
+ A call with an `id` waits for its `result` or `error`; one without is fire-and-forget, its errors only logged at
152
+ `debug`, for data whose loss is harmless (a cursor, a typing indicator). Over HTTP, `?ack=false` answers 202 at once.
153
+
154
+ ## Streams
155
+
156
+ A stream is an ordered flow of chunks from one producer to one or many connections: `text` (strings), `json` (JSON
157
+ values) or `binary` (bytes, sent as base64 in the JSON frames). Where a channel checks `deliver` and publishes to the
158
+ pub/sub for every payload, a stream:
159
+
160
+ - checks a subscriber once, when it subscribes (`public`, `roles`, `permissions`, `subscribe`), and again only when the
161
+ user changes, like a channel;
162
+ - encodes a chunk once, however many subscribers receive it, and writes it to their connections directly;
163
+ - reaches another instance only while one of them has a subscriber of its key, in batches of
164
+ `realtime.streamRelayFlushInterval` milliseconds (or `streamRelayMaxBatch` bytes) over the `PubSub`, so a stream
165
+ without remote subscribers never touches Redis;
166
+ - keeps its last chunks (`replay`) for the late subscribers and the ones resuming after a reconnection.
167
+
168
+ ### Streaming actions
169
+
170
+ The answer of an LLM to the user asking for it: an action with `stream`, whose handler is an async generator. Its
171
+ chunks reach the caller only, as they come, and the stream ends with the value it returns:
172
+
173
+ ```ts
174
+ import Anthropic from '@anthropic-ai/sdk';
175
+
176
+ const anthropic = new Anthropic();
177
+
178
+ createRealtimeAction({
179
+ name: 'assistant.prompt',
180
+ payload: Type.Object({ prompt: Type.String() }),
181
+ response: Type.Object({ stopReason: Type.String() }),
182
+ stream: { codec: 'text', coalesce: 16 }, // merges the tokens of 16 ms into one chunk
183
+ async *handler({ prompt }, { user, signal }) {
184
+ const stream = anthropic.messages.stream(
185
+ {
186
+ model: process.env.ANTHROPIC_MODEL!,
187
+ max_tokens: 4096,
188
+ messages: [{ role: 'user', content: prompt }]
189
+ },
190
+ { signal }
191
+ );
192
+ for await (const event of stream) {
193
+ if (
194
+ event.type === 'content_block_delta' &&
195
+ event.delta.type === 'text_delta'
196
+ ) {
197
+ yield event.delta.text;
198
+ }
199
+ }
200
+ return {
201
+ stopReason: (await stream.finalMessage()).stop_reason ?? 'end_turn'
202
+ };
203
+ }
204
+ });
205
+ ```
206
+
207
+ - The handler runs as the user, like any action. A handler returning a value instead of an async iterable ends the
208
+ stream with it, and an error ends it with its problem details.
209
+ - The generator is pulled only while the caller reads fast enough (`realtime.streamHighWaterMark`), so a slow client
210
+ pauses the producer instead of buffering the whole answer.
211
+ - `signal` aborts once the client cancels the call, once it disconnects and does not resume within
212
+ `realtime.streamLinger` milliseconds, or once the instance shuts down: pass it to the LLM SDK so the generation stops.
213
+ - Over the WebSocket the call needs an `id` (a fire-and-forget call is refused) and is answered by the stream instead of
214
+ a `result`. Over HTTP, `POST <api>/realtime/actions/:name` with `Accept: text/event-stream` answers with the
215
+ Server-Sent Events of the stream (`406 REALTIME_STREAM_ACCEPT` without it, `400` with `ack=false`), cancelled when
216
+ the client leaves.
217
+ - A client losing its WebSocket resumes the call on its next connection, on the same instance, from the last chunk it
218
+ received (`{ type: 'resume', id, streamId, seq }`), while the stream lingers. Another user is refused with
219
+ `REALTIME_STREAM_NOT_FOUND`.
220
+
221
+ ### Streams of a key
222
+
223
+ A stream of many subscribers, i.e. the answer shown to a whole chat room, or a radio station: `createStream`, opened
224
+ for a key by its producer, anywhere in the application (a route, an action, a queue job of an instance with the module):
225
+
226
+ ```ts
227
+ // src/realtime/index.ts
228
+ export const roomAnswer = createStream({
229
+ name: 'room.answer',
230
+ params: Type.Object({ roomId: Type.Integer() }),
231
+ subscribe: (user, { roomId }, key) =>
232
+ key === String(roomId) && isMember(user, roomId) // once per subscription
233
+ });
234
+
235
+ export const radio = createStream({
236
+ name: 'radio.live',
237
+ codec: 'binary',
238
+ mimeType: 'audio/mpeg',
239
+ public: true,
240
+ replay: { from: 'sync', maxSize: '512KB' }, // a new listener starts at the last frame boundary
241
+ onSlow: 'skip-to-sync' // a slow listener skips to the next frame boundary instead of being closed
242
+ });
243
+
244
+ const writer = roomAnswer.open(String(roomId));
245
+ for await (const token of tokens) {
246
+ writer.write(token);
247
+ await writer.ready; // waits while a subscriber of this instance reads too slowly
248
+ }
249
+ writer.end({ messageId });
250
+
251
+ radio.open('jazz').write(frame, { sync: true }); // a chunk a listener can start from
252
+ ```
253
+
254
+ | Option | Description |
255
+ |----------------------------------|---------------------------------------------------------------------------------------------------------------------|
256
+ | `name` | `[a-zA-Z0-9][\w.:-]*`, unique, subscribed to as the channel `stream:<name>` |
257
+ | `codec` | `text` (default), `json` or `binary` |
258
+ | `mimeType` | The media type of a `binary` stream, told to the clients |
259
+ | `chunk` | The TypeBox schema of the chunks of a `json` stream, checked outside of `prod` |
260
+ | `params` | The TypeBox schema of the subscription parameters |
261
+ | `public`, `roles`, `permissions` | Who may subscribe, see [Access](#access) |
262
+ | `resource` | `{ model, id? }`: the record of a key, a subscriber must be able to `find` it, see [Access](#access-of-the-streams) |
263
+ | `subscribe` | `(user, params, key)`, false denies the subscription; it runs as the user |
264
+ | `replay` | `{ from, maxSize }`: `all` the chunks kept (default), from the last `sync` one, or `none`; the bytes kept |
265
+ | `onSlow` | A subscriber over `realtime.sendBufferLimit`: `close` (default), `drop` its chunks, or `skip-to-sync` |
266
+ | `coalesce` | Milliseconds the `text` or `binary` chunks are merged for, `0` (default) for none |
267
+ | `description` | Description in the OpenAPI document |
268
+
269
+ The streaming actions take the same `codec`, `mimeType`, `chunk`, `replay`, `onSlow` and `coalesce` in their `stream`.
270
+
271
+ The writer of `open(key)` has `write(chunk, { sync? })`, `end(result?)`, `error(error)`, `ready`, `signal` (aborted
272
+ once ended or on shutdown), `ended`, `streamId` and `subscribers` (the subscribers of this instance and the instances
273
+ relaying it). A subscription to a key receives every stream opened for it, several at once each with an ID of its own,
274
+ and stays until it is removed. A missed chunk (a slow subscriber, a reconnection beyond the replay) is announced with a
275
+ `stream.gap` before the next one. A relayed stream whose owner instance goes silent for three
276
+ `realtime.streamRelayHeartbeat` ends with `REALTIME_STREAM_LOST`, and so do the streams of an instance shutting down.
277
+
278
+ ### Inputs
279
+
280
+ The other direction: the chunks a client streams to an action, i.e. the audio of a microphone for a speech to text
281
+ model, read by the handler as `context.input`, an async iterable ending when the client ends it. An action with an
282
+ `input` and a `stream` is duplex (audio in, text out); one with an `input` alone answers with the value it returns:
283
+
284
+ ```ts
285
+ createRealtimeAction({
286
+ name: 'voice.transcribe',
287
+ payload: Type.Object({ language: Type.String() }),
288
+ input: { codec: 'binary', mimeType: 'audio/webm', maxSize: '50MB' },
289
+ stream: { codec: 'text' },
290
+ async *handler({ language }, { input, signal }) {
291
+ yield* stt.transcribe(input!, { language, signal });
292
+ }
293
+ });
294
+
295
+ // The input of one user passed on to the subscribers of a stream (a user broadcasting)
296
+ createRealtimeAction({
297
+ name: 'radio.broadcast',
298
+ payload: Type.Object({ station: Type.String() }),
299
+ roles: ['host'],
300
+ input: { codec: 'binary', mimeType: 'audio/mpeg', maxSize: '1GB' },
301
+ async handler({ station }, { input }) {
302
+ const writer = radio.open(station);
303
+ try {
304
+ for await (const frame of input!) {
305
+ writer.write(frame);
306
+ await writer.ready;
307
+ }
308
+ writer.end();
309
+ } catch (e) {
310
+ writer.error(e); // the call was cancelled, the host disconnected or lost the access
311
+ }
312
+ }
313
+ });
314
+ ```
315
+
316
+ | Option | Description |
317
+ |------------|------------------------------------------------------------------------------------------------------------------------------------|
318
+ | `codec` | `text` (default), `json` or `binary` (`Uint8Array` chunks) |
319
+ | `mimeType` | The media type of a `binary` input, told to the clients |
320
+ | `chunk` | The TypeBox schema of the chunks of a `json` input, checked in every environment |
321
+ | `maxSize` | The size the client may send in all, bytes or a size string, `realtime.streamInputMaxSize` by default (`413 REALTIME_INPUT_LIMIT`) |
322
+
323
+ - An input is sent over the WebSocket only: over HTTP the call fails with `REALTIME_MESSAGE_INVALID`.
324
+ - The access of the action is checked once when the call starts. The chunks pass no rate limit and no access check;
325
+ they are paced by credits instead: the client sends at most `realtime.streamInputWindow` bytes ahead of the handler
326
+ reading them, given back by `input.credit` messages as it reads, so a slow handler slows the client down instead of
327
+ filling the memory of the server. A client sending beyond its window fails the call (`REALTIME_MESSAGE_INVALID`).
328
+ An input of no call receiving one (i.e. a call that just ended) is answered with a `REALTIME_MESSAGE_INVALID` error
329
+ of its ID, and counts against `realtime.messageRateLimit`.
330
+ - A binary chunk is a binary WebSocket message, not base64: the byte `1`, the length of the ID of the call, the ID,
331
+ then the bytes. Any other binary message closes the connection with `1008`.
332
+ - The connection lost while the input is open cancels the call: an input never resumes, the client calls again. Once
333
+ the client ended its input, the stream of a duplex call resumes like any streaming action.
334
+ - `signal` aborts once the call is cancelled, its connection lost, its user losing the access, or the instance shutting
335
+ down, and the iteration of `input` throws (an `AbortError`, or the error of the call).
336
+
337
+ ### Costs
338
+
339
+ | Per chunk | Streams |
340
+ |----------------|----------------------------------------------------------------------------|
341
+ | Access checks | None (once per subscription) |
342
+ | Encoding | One `JSON.stringify`, shared by every subscriber |
343
+ | Pub/sub, Redis | None locally; one publish per batch only while another instance subscribes |
344
+ | Validation | The codec; the `chunk` schema of `json`, of a stream outside of `prod` |
345
+
346
+ The cost that remains is one message per subscriber per chunk on its socket: `coalesce` lowers it for the token
347
+ streams, whose tokens arrive faster than a user reads them.
348
+
349
+ ## Access
350
+
351
+ Every part is private by default: a subscription or a call needs a user. `public`, `roles` and `permissions` on a
352
+ channel, an action, the `events` of a model or one of its actions set who may use it (`roles` and `permissions` ignored
353
+ on a public part). The anonymous clients use the public parts once `realtime.anonymousEnabled` is set:
354
+
355
+ ```jsonc
356
+ // appweaver.json, or REALTIME_ANONYMOUS_ENABLED=true and REALTIME_MAX_ANONYMOUS_CONNECTIONS_PER_IP=5
357
+ {
358
+ "config": {
359
+ "realtime": { "anonymousEnabled": true, "maxAnonymousConnectionsPerIp": 5 }
360
+ }
361
+ }
362
+ ```
363
+
364
+ ```ts
365
+ export const stockPrice = createChannel({
366
+ name: 'stock.price',
367
+ public: true,
368
+ payload: Type.Object({ symbol: Type.String(), price: Type.Number() }),
369
+ params: Type.Object({ symbol: Type.Optional(Type.String()) }),
370
+ deliver: (_, payload, params) =>
371
+ !params.symbol || params.symbol === payload.symbol
372
+ });
373
+ ```
374
+
375
+ A public channel without `deliver` sends every payload to everyone. The HTTP actions route authenticates a request
376
+ carrying credentials (an invalid one fails with `401`), and runs one without as anonymous.
377
+
378
+ ### Access of the streams
379
+
380
+ Every check of a stream runs once, when a client subscribes, and again when its user changes, never per chunk:
381
+
382
+ 1. the module: `realtime.anonymousEnabled` for the clients without a ticket;
383
+ 2. the declaration: `public`, `roles` and `permissions` (the `hasRoles` and `hasPermissions` of the auth model);
384
+ 3. the policy of a resource: with `resource`, the subscriber must be able to `find` the record of the key, as
385
+ themselves, so the `checkAccess` and the `readRestrictions` of the `createPolicy` of its model decide, the same
386
+ rules as the routes of the model. The ID is the key (a number for a key of digits), or `id(key, params)`;
387
+ 4. the `subscribe` callback of the stream, for any other rule.
388
+
389
+ ```ts
390
+ createPolicy({
391
+ modelName: 'chatRoom',
392
+ readRestrictions: (user) => ({ members: { some: { userId: user?.id } } })
393
+ });
394
+
395
+ export const roomAnswer = createStream({
396
+ name: 'room.answer',
397
+ resource: { model: 'ChatRoom' }
398
+ });
399
+ // subscribe to 'stream:room.answer' with key '42': allowed while the user can read the room 42
400
+ ```
401
+
402
+ The access of the producer is the one of the code opening the stream: an action (its `public`, `roles` and
403
+ `permissions`, the policies of the resources it uses as the user), a route, a job. A change the policy depends on but
404
+ the user does not (a member removed from a room) applies at the next subscription, or at once with
405
+ `inject(RealtimeGateway).refresh(userId)`, which checks the subscriptions of the user again.
406
+
407
+ ### Logout, disabling and role changes
408
+
409
+ A change of a user reaches their connections and their calls on every instance, over the WebSocket and HTTP alike:
410
+
411
+ | Change | Subscriptions to streams | Calls (streaming actions, inputs) |
412
+ |----------------------------------------|----------------------------------------------------|--------------------------------------------------------------------------|
413
+ | Logout (`logoutAt`, a password change) | Their connections closed (`4401`), no reconnection | Ended at once with `REALTIME_ACTION_DENIED`, never left to linger |
414
+ | Disabling, deletion | The same | The same |
415
+ | Other roles or permissions | Checked again, the lost ones removed with an error | Ended with `REALTIME_ACTION_DENIED` when the action is no longer allowed |
416
+ | `revoke(userId)`, `refresh(userId)` | The same as a logout, or as other roles | The same |
417
+
418
+ Ending a call aborts its `signal` and fails its `input`, so the generation of an LLM or the reading of an input stops;
419
+ `inject(RealtimeGateway).calls` lists the calls running on the instance.
420
+
421
+ ## Rolling updates
422
+
423
+ A deployment replacing the instances one by one keeps the streams of the clients running. On `SIGTERM` (`app.stop()`)
424
+ the readiness answers `503`, then the realtime part of the instance drains before the server closes:
425
+
426
+ 1. it refuses the new connections (a WebSocket closed with `1012`, an event stream answered `503`) and the new calls
427
+ with a stream or an input (`503 REALTIME_SHUTTING_DOWN`);
428
+ 2. it closes its connections with `1012` (Service Restart), except the ones streaming an input not ended yet, which
429
+ cannot move. The clients reconnect at once to another instance, each after a random part of `reconnectDelay` so
430
+ they do not all arrive together, with their subscriptions;
431
+ 3. a client resuming a streaming action on the new instance (`{ type: 'resume', id, streamId, seq }`) receives it
432
+ relayed from the draining instance, which keeps generating it, checked as the same user. Cancelling it on the new
433
+ instance cancels it on the owner;
434
+ 4. it waits for its calls to end, the ones over HTTP too, at most `realtime.shutdownGracePeriod` milliseconds
435
+ (`30000`), ends the rest with `REALTIME_SHUTTING_DOWN`, and closes what remains with `1001`.
436
+
437
+ | Part | On a rolling update |
438
+ |--------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
439
+ | Channels, resource events | Subscribed again on another instance; the events published during the reconnection are lost |
440
+ | Streams of a key (`createStream`) | Subscribed again, a stream of a surviving instance resumed from its last chunk; the producer of a stream on the stopping instance stops with it (`REALTIME_STREAM_LOST`) |
441
+ | Streaming actions over the WebSocket | Resumed on another instance, relayed from the draining one until they end, within the grace period |
442
+ | Streaming actions over HTTP | Kept on their connection until they end, within the grace period |
443
+ | Inputs | Their connection kept until the client ends the input, within the grace period |
444
+
445
+ Set the termination grace period of the platform (`terminationGracePeriodSeconds` of Kubernetes) above
446
+ `realtime.shutdownGracePeriod`, and the generations to fit in it. A crash or a kill loses the calls of the instance:
447
+ the clients get `REALTIME_STREAM_NOT_FOUND` when resuming, and call again. The tickets and the relay between the
448
+ instances need the `redis` providers of `Memory` and `PubSub`.
449
+
450
+ ## Connections
451
+
452
+ A browser cannot send the `Authorization` header with an `EventSource` or a `WebSocket`, so the client asks for a ticket
453
+ with its credentials, used once and valid `realtime.ticketTtl` milliseconds on every instance (kept in the `Memory`,
454
+ with the user but never their password hash). The user is loaded again when the ticket is redeemed, refused once
455
+ deleted, disabled or logged out since.
456
+
457
+ | Route | Description |
458
+ |----------------------------------------------------|----------------------------------------------------------------------------------------------------------------|
459
+ | `POST <api>/realtime/ticket` | `{ ticket, expiresIn }`, any authentication |
460
+ | `GET <api>/realtime/ws?ticket=` | The WebSocket, described by the `x-appweaver-realtime` extension |
461
+ | `GET <api>/realtime/events?ticket=&subscriptions=` | The SSE stream of the subscriptions of the query, a JSON array; a change reopens it |
462
+ | `POST <api>/realtime/actions/:name?ack=` | Calls an action, answers `{ result }`, or 202 with `ack=false`; a streaming action answers with its SSE stream |
463
+
464
+ A connection without a ticket is anonymous, or refused (`REALTIME_TICKET_INVALID`). It closes with a `reauth` message
465
+ and the code `4401` when the token of its ticket expires or after `realtime.connectionMaxAge`, and the client
466
+ reconnects with a new ticket. A disabled transport (`realtime.sseEnabled`, `realtime.websocketEnabled`) answers its
467
+ route with `404 REALTIME_TRANSPORT_DISABLED`, and is left out of the `transports` of the extension. Delivery is
468
+ at-most-once: an event published while a client reconnects is lost.
469
+
470
+ A change of a user of the auth model reaches their connections on every instance. A logout (a new `logoutAt`, also
471
+ set by a password change), a disabling or a deletion closes them the same way, and the client fails to reconnect. Any
472
+ other change, i.e. other roles, loads the user of the connections again from the database: the checks of the next
473
+ events use it, and the subscriptions the user lost are removed, each answered with a `REALTIME_SUBSCRIPTION_DENIED`
474
+ error. A change the auth model does not see, i.e. the permissions of a role, applies at the next reconnection, or with
475
+ `inject(RealtimeGateway).refresh(userId)`; `revoke(userId)` closes the connections.
476
+
477
+ ### Protocol
478
+
479
+ Every message is a JSON object: a WebSocket text frame, or the `data` of an SSE event whose `id` is the `eventId`.
480
+
481
+ | Client → server (WebSocket) | Answer |
482
+ |-------------------------------------------------------------------------------|--------------------------------------------------------------------|
483
+ | `{ type: 'subscribe', id, channel, params?, filter? }` | `{ type: 'subscribed', id }` |
484
+ | `{ type: 'subscribe', id, channel: 'stream:<name>', key?, params?, resume? }` | `{ type: 'subscribed', id }`, then the streams |
485
+ | `{ type: 'unsubscribe', id }` | `{ type: 'unsubscribed', id }` |
486
+ | `{ type: 'action', id, action, payload }` | `{ type: 'result', id, result }`, the stream of a streaming action |
487
+ | `{ type: 'action', action, payload }` | nothing (fire-and-forget) |
488
+ | `{ type: 'cancel', id }` | `stream.end` with `cancelled` |
489
+ | `{ type: 'input', id, data }`, or a binary message | `{ type: 'input.credit', id, bytes }` as the handler reads |
490
+ | `{ type: 'input.end', id }` | The result, or the end of the stream |
491
+ | `{ type: 'resume', id, streamId, seq }` | The stream of a call, from `seq` |
492
+ | `{ type: 'ping', id? }` | `{ type: 'pong', id? }` |
493
+
494
+ The server sends `{ type: 'welcome', connectionId, expiresAt, heartbeat }` once open, `{ type: 'event', id, channel,
495
+ eventId, data }` for the subscription `id` (chosen by the client, `[\w.:-]{1,64}`), `{ type: 'error', id?, error }` with
496
+ the problem details of a failed message, and `{ type: 'reauth' }` before `4401`. The subscriptions change in the order
497
+ of the messages; the actions run at once.
498
+
499
+ A stream starts with `{ type: 'stream.start', id, sid, streamId, stream, key, codec, mimeType?, seq }` for the
500
+ subscription or the call `id`. Its frames name it by `sid`, the ID of the stream on the connection, so every subscriber
501
+ receives the same encoded frame: `{ type: 'chunk', sid, seq, data, sync? }` (`data` in base64 for `binary`),
502
+ `{ type: 'stream.gap', sid, from, to }`, then `{ type: 'stream.end', sid, seq, result?, cancelled? }` or
503
+ `{ type: 'stream.error', sid, seq, error }`. A subscription resumes a stream of its key with
504
+ `resume: { streamId, seq }`, from the chunks kept.
505
+
506
+ | Close code | Meaning |
507
+ |------------|--------------------------------------------------|
508
+ | `1001` | The server shuts down |
509
+ | `1012` | The server restarts, reconnect at once elsewhere |
510
+ | `1008` | A binary message |
511
+ | `4401` | The authentication expired |
512
+ | `4403` | The ticket is missing or invalid |
513
+ | `4408` | The client reads too slowly |
514
+ | `4429` | Too many connections of the instance, user or IP |
515
+
516
+ ## Client
517
+
518
+ The generated client has `client.realtime`, typed by the channels, resources and actions of the server:
519
+
520
+ ```ts
521
+ const client = createClient({
522
+ baseUrl: 'https://api.example.com',
523
+ auth: { jwt: () => session.accessToken },
524
+ realtime: { anonymous: 'auto' } // anonymous until the login
525
+ });
526
+
527
+ client.realtime.subscribe('stock.price', show, { symbol: 'AAPL' });
528
+ client.realtime.on('Product', ({ action, current }) => refresh(current), {
529
+ action: 'update'
530
+ });
531
+ await client.realtime.send('chat.typing', { roomId: 1 });
532
+ client.realtime.emit('cursor.move', { x: 10, y: 20 });
533
+
534
+ const call = client.realtime.call('assistant.prompt', { prompt }); // a streaming action
535
+ for await (const token of call) output += token;
536
+ const { stopReason } = await call.result;
537
+
538
+ const voice = client.realtime.call(
539
+ 'voice.transcribe',
540
+ { language: 'en' },
541
+ { input: microphoneChunks }
542
+ ); // an input
543
+ for await (const text of voice) showCaption(text);
544
+
545
+ client.realtime.stream(
546
+ 'room.answer',
547
+ {
548
+ onStart: ({ streamId }) => startMessage(streamId),
549
+ onChunk: (token, { streamId }) => append(streamId, token),
550
+ onEnd: (result, { streamId }) => finishMessage(streamId)
551
+ },
552
+ { key: '42', params: { roomId: 42 } }
553
+ );
554
+
555
+ await login();
556
+ await client.realtime.reconnect(); // the connection of the user, with the subscriptions
557
+ ```
558
+
559
+ See [client.md](./client.md#realtime-client) for the methods and the options.
560
+
561
+ ## Config, errors, telemetry, testing
562
+
563
+ - Config: `realtime.*` (`REALTIME_*`) and `pubsub.*` (`PUBSUB_*`), see
564
+ [configuration.md](./configuration.md#realtime-realtime_).
565
+ - Errors: the `REALTIME_*` codes of [errors.md](./errors.md#error-codes).
566
+ - Telemetry (`telemetry.instrumentations.realtime`): the span `realtime action <name>` (until the end of the stream of
567
+ a streaming action), the span `realtime stream <name>` of a stream opened on the instance, the metrics
568
+ `appweaver.realtime.connections`, `appweaver.realtime.events` (`delivered`, `denied`, `dropped`, a dropped chunk
569
+ counted as `stream:<name>`), `appweaver.realtime.messages`, `appweaver.realtime.streams`,
570
+ `appweaver.realtime.stream.chunks`, `appweaver.realtime.stream.bytes` and `appweaver.realtime.input.bytes`.
571
+ - Testing: connect with the global `WebSocket` and `fetch` of Node after a `POST <api>/realtime/ticket`, define
572
+ `MemoryPubSub` of `@appweaver/core/drivers` in a unit test, and test a `PubSub` driver with `testPubSubContract`.