@spfn/core 0.3.0-beta.4 → 0.3.0-beta.6

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.
Files changed (45) hide show
  1. package/README.md +183 -4
  2. package/dist/authz/index.js +1 -381
  3. package/dist/authz/index.js.map +1 -1
  4. package/dist/db/index.d.ts +173 -27
  5. package/dist/db/index.js +192 -57
  6. package/dist/db/index.js.map +1 -1
  7. package/dist/env/loader.js +24 -1
  8. package/dist/env/loader.js.map +1 -1
  9. package/dist/errors/index.js +1 -381
  10. package/dist/errors/index.js.map +1 -1
  11. package/dist/logger/index.js +0 -12
  12. package/dist/logger/index.js.map +1 -1
  13. package/dist/middleware/index.js +6 -387
  14. package/dist/middleware/index.js.map +1 -1
  15. package/dist/nextjs/index.d.ts +18 -1
  16. package/dist/nextjs/index.js +40 -1
  17. package/dist/nextjs/index.js.map +1 -1
  18. package/dist/nextjs/server.d.ts +34 -1
  19. package/dist/nextjs/server.js +14 -0
  20. package/dist/nextjs/server.js.map +1 -1
  21. package/dist/ops/index.d.ts +61 -6
  22. package/dist/ops/index.js +330 -30
  23. package/dist/ops/index.js.map +1 -1
  24. package/dist/server/index.js +24 -1
  25. package/dist/server/index.js.map +1 -1
  26. package/docs/file-upload.md +195 -333
  27. package/package.json +6 -5
  28. package/src/cache/README.md +330 -0
  29. package/src/codegen/README.md +516 -0
  30. package/src/config/README.md +326 -0
  31. package/src/contract/README.md +326 -0
  32. package/src/db/README.md +589 -0
  33. package/src/db/manager/README.md +500 -0
  34. package/src/db/schema/README.md +344 -0
  35. package/src/db/transaction/README.md +822 -0
  36. package/src/env/README.md +651 -0
  37. package/src/errors/README.md +429 -0
  38. package/src/event/README.md +736 -0
  39. package/src/job/README.md +514 -0
  40. package/src/logger/README.md +321 -0
  41. package/src/middleware/README.md +634 -0
  42. package/src/nextjs/README.md +608 -0
  43. package/src/route/README.md +738 -0
  44. package/src/security/README.md +100 -0
  45. package/src/server/README.md +704 -0
@@ -0,0 +1,736 @@
1
+ # @spfn/core/event — Decoupled pub/sub events + SSE streaming
2
+
3
+ In-memory pub/sub event system with TypeBox-typed payloads, optional cache-backed
4
+ multi-instance broadcast, job-queue fan-out, and Server-Sent Events (SSE) streaming to the
5
+ browser. A WebSocket variant shares the same event definitions.
6
+
7
+ ## Import paths
8
+
9
+ There are **four** entry points. Picking the wrong one breaks the build (client code must
10
+ never pull the Hono handler; the handler must never pull the EventSource client).
11
+
12
+ ```typescript
13
+ // Event definitions, router, route-map — isomorphic (define + emit + subscribe)
14
+ import { defineEvent, defineEventRouter, eventRouteMap } from '@spfn/core/event';
15
+
16
+ // Server SSE handler + token manager — SERVER ONLY (Hono, node:crypto)
17
+ import { createSSEHandler, SSETokenManager, CacheTokenStore } from '@spfn/core/event/sse';
18
+
19
+ // Browser SSE client — CLIENT ONLY (EventSource)
20
+ import { createSSEClient, createAuthSSEClient, subscribeToEvents } from '@spfn/core/event/sse/client';
21
+
22
+ // WebSocket router/handler/client — separate surface (see "WebSocket" below)
23
+ import { defineWSRouter } from '@spfn/core/event'; // or '@spfn/core/event/ws'
24
+ import { attachWSHandler } from '@spfn/core/event/ws'; // server
25
+ import { createWSClient } from '@spfn/core/event/ws/client'; // browser
26
+ ```
27
+
28
+ > `createSSEClient` / `createAuthSSEClient` / `subscribeToEvents` live in
29
+ > `@spfn/core/event/sse/**client**` — **not** in `@spfn/core/event/sse`. The bare
30
+ > `@spfn/core/event/sse` is the server handler surface.
31
+
32
+ In practice you rarely call `createSSEHandler` directly — `defineServerConfig().events(router)`
33
+ mounts it for you (see [Server setup](#server-setup-via-defineserverconfig)).
34
+
35
+ ---
36
+
37
+ ## Public API (complete)
38
+
39
+ From `@spfn/core/event`:
40
+
41
+ - `defineEvent(name)` / `defineEvent(name, schema)` — define an event
42
+ - `defineEventRouter(events)` — group events for SSE
43
+ - `defineWSRouter({ events, messages? })` — group events + message handlers for WebSocket
44
+ - `eventRouteMap` — `{ eventsToken: { method: 'POST', path: '/events/token' } }` (merge into RPC proxy)
45
+ - Types: `EventDef`, `EventHandler`, `InferEventPayload`, `PubSubCache`, `JobQueueSender`,
46
+ `EventRouterDef`, `InferEventNames`, `InferEventPayloads`,
47
+ `InferRouterEventPayload` (the two-arg router variant — see note)
48
+
49
+ From `@spfn/core/event/sse`:
50
+
51
+ - `createSSEHandler(router, config?, tokenManager?)` — Hono GET handler
52
+ - `SSETokenManager` (class), `CacheTokenStore` (class)
53
+ - Types: `SSEToken`, `SSETokenStore`, `SSETokenManagerConfig`, `SSEMessage`,
54
+ `SSEHandlerConfig`, `SSEHandlerAuthConfig`, `SSEAuthConfig`, `SSEClientConfig`,
55
+ `SSEEventHandler`, `SSEEventHandlers`, `SSESubscribeOptions`, `SSEConnectionState`,
56
+ `SSEUnsubscribe`
57
+
58
+ From `@spfn/core/event/sse/client`:
59
+
60
+ - `createSSEClient(config?)`, `createAuthSSEClient(config?)`, `subscribeToEvents(events, handlers, config?)`
61
+ - Type: `SSEClient`, `AuthSSEClientConfig`
62
+
63
+ From `@spfn/core/event/ws` / `@spfn/core/event/ws/client`: see [WebSocket](#websocket).
64
+
65
+ > **Two `InferEventPayload`s.** The name `InferEventPayload` exported from
66
+ > `@spfn/core/event` is the **single-arg** one (`InferEventPayload<typeof userCreated>` →
67
+ > payload of one event). The router module's **two-arg** version
68
+ > (`<Router, 'eventName'>`) is re-exported under the alias **`InferRouterEventPayload`** to
69
+ > avoid a clash. Inside the SSE types it is the two-arg form.
70
+ >
71
+ > **No such API.** There is no `event.on(...)`, no `event.publish(...)`, no
72
+ > `createEventBus()`, no `emitSync()`. The model is: `defineEvent` → `.subscribe()` /
73
+ > `.emit()` / `.useCache()`. SSE clients are created with `createSSEClient` /
74
+ > `createAuthSSEClient`, never `new EventSource` directly (that loses typing and token handling).
75
+
76
+ ---
77
+
78
+ ## Quick Start
79
+
80
+ ```typescript
81
+ import { defineEvent } from '@spfn/core/event';
82
+ import { Type } from '@sinclair/typebox';
83
+
84
+ // 1. Define an event with a typed payload
85
+ export const userCreated = defineEvent('user.created', Type.Object({
86
+ userId: Type.String(),
87
+ email: Type.String(),
88
+ }));
89
+
90
+ // 2. Subscribe (in-memory) — returns an unsubscribe function
91
+ const unsubscribe = userCreated.subscribe((payload) =>
92
+ {
93
+ // payload: { userId: string; email: string }
94
+ console.log('User created:', payload.userId);
95
+ });
96
+
97
+ // 3. Emit — awaits all handlers
98
+ await userCreated.emit({ userId: '123', email: 'user@example.com' });
99
+
100
+ // 4. Cleanup
101
+ unsubscribe();
102
+ ```
103
+
104
+ ### Event without payload
105
+
106
+ ```typescript
107
+ export const serverStarted = defineEvent('server.started'); // EventDef<void>
108
+
109
+ serverStarted.subscribe(() => console.log('started'));
110
+ await serverStarted.emit(); // emit() takes no argument when there is no schema
111
+ ```
112
+
113
+ `emit` is typed off the payload: `() => Promise<void>` for void events, `(payload) =>
114
+ Promise<void>` otherwise. Handlers run via `Promise.allSettled` — see
115
+ [error isolation](#error-isolation).
116
+
117
+ ---
118
+
119
+ ## EventDef methods
120
+
121
+ `defineEvent` returns an `EventDef<TPayload>`:
122
+
123
+ | Member | Signature | Notes |
124
+ |--------|-----------|-------|
125
+ | `name` | `readonly string` | event name (e.g. `'user.created'`) |
126
+ | `schema` | `readonly TSchema?` | the TypeBox schema, if provided |
127
+ | `subscribe(handler)` | `(payload) => void \| Promise<void>` ⇒ returns `() => void` | in-memory; returns unsubscribe |
128
+ | `unsubscribeAll()` | `() => void` | drop all in-memory handlers |
129
+ | `emit(payload?)` | `Promise<void>` | fan-out to handlers (or cache) + job queues |
130
+ | `useCache(cache)` | `(PubSubCache) => Promise<EventDef>` | enable cross-instance broadcast (must `await`) |
131
+
132
+ > `_registerJobQueue` and `_payload` exist on the interface but are **internal** —
133
+ > `_registerJobQueue` is called by `@spfn/core/job` when a job does `.on(event)`; `_payload`
134
+ > is a type-inference carrier (always `undefined` at runtime). Don't call them.
135
+
136
+ ---
137
+
138
+ ## Server setup (via `defineServerConfig`)
139
+
140
+ To stream events to the browser, group them with `defineEventRouter` and register the
141
+ router on the server. `.events()` mounts the SSE handler — you don't call `createSSEHandler`
142
+ yourself.
143
+
144
+ ```typescript
145
+ // src/server/events.ts
146
+ import { defineEvent, defineEventRouter } from '@spfn/core/event';
147
+ import { Type } from '@sinclair/typebox';
148
+
149
+ export const userCreated = defineEvent('user.created', Type.Object({
150
+ userId: Type.String(),
151
+ email: Type.String(),
152
+ }));
153
+ export const orderPlaced = defineEvent('order.placed', Type.Object({
154
+ orderId: Type.String(),
155
+ userId: Type.String(),
156
+ amount: Type.Number(),
157
+ }));
158
+
159
+ export const eventRouter = defineEventRouter({ userCreated, orderPlaced });
160
+ export type EventRouter = typeof eventRouter;
161
+ ```
162
+
163
+ ```typescript
164
+ // server.config.ts
165
+ import { defineServerConfig } from '@spfn/core/server';
166
+ import { eventRouter } from './server/events';
167
+
168
+ export default defineServerConfig()
169
+ .routes(appRouter)
170
+ .jobs(jobRouter)
171
+ .events(eventRouter) // → GET /events/stream
172
+ .build();
173
+
174
+ // Custom path + ping interval:
175
+ .events(eventRouter, {
176
+ path: '/sse', // default: '/events/stream'
177
+ pingInterval: 10000, // keep-alive interval, ms (default: 10000 — under proxy idle timeouts)
178
+ })
179
+ ```
180
+
181
+ `.events(router, config)` accepts `Omit<SSEHandlerConfig, 'auth'> & { path?, auth?:
182
+ SSEAuthConfig<TRouter> }`. The `auth` field is the **generic** `SSEAuthConfig<TRouter>` so
183
+ `authorize`/`filter` get full event-name and payload inference from your router.
184
+
185
+ `config` also carries the cross-pod transport knobs (see
186
+ [Multi-instance broadcast](#multi-instance-broadcast-cross-pod-fan-out)):
187
+
188
+ | Option | Type | Default | Description |
189
+ |--------|------|---------|-------------|
190
+ | `multiInstance` | `boolean` | `true` | auto-wire Redis pub/sub when a cache is configured; `false` forces in-process |
191
+ | `channelPrefix` | `string` | env `SPFN_SSE_CHANNEL_PREFIX` or `spfn:sse:` | pub/sub channel prefix; set distinct prefixes to isolate apps sharing one Redis |
192
+
193
+ > `.websockets(router, config)` accepts the same `multiInstance` / `channelPrefix` knobs.
194
+ > Events shared by both routers are wired once.
195
+
196
+ > **Backpressure (`maxQueue`, default 1000).** Each connection's outbound frames go through a
197
+ > single drain loop that `await`s every write, so a slow client applies real backpressure
198
+ > instead of letting frames buffer unboundedly in memory. If the per-connection queue exceeds
199
+ > `maxQueue`, the connection is **closed** (the client reconnects) rather than dropping frames —
200
+ > dropping a chunk would corrupt an ordered token stream. Raise `maxQueue` for very bursty
201
+ > producers; lower it to cap memory more aggressively.
202
+
203
+ > `SSEHandlerConfig` also declares a `headers` field, but the current handler only reads
204
+ > `pingInterval`, `auth`, and `maxQueue`. Setting custom `headers` here is a no-op — set
205
+ > response headers in middleware instead.
206
+
207
+ ---
208
+
209
+ ## SSE authentication (Token Exchange)
210
+
211
+ The browser `EventSource` API cannot send custom headers, so a `Authorization: Bearer` JWT
212
+ can't ride along on the stream request. SPFN uses a **token exchange**: an authenticated
213
+ `POST /events/token` mints a one-time, short-TTL token; the stream request carries it as
214
+ `?token=...`.
215
+
216
+ ```
217
+ Client Server
218
+ │ POST /events/token (Bearer JWT) │ ← protected by config.middlewares (e.g. authenticate)
219
+ │ ───────────────────────────────► │ getSubject(c) → issue one-time token
220
+ │ ◄───────────────────────────── │ { token: "..." } (default TTL 30s)
221
+ │ GET /events/stream?token=…&events=…
222
+ │ ───────────────────────────────► │ verify+consume token (one-time)
223
+ │ │ → authorize(subject, events)
224
+ │ ◄═══════════════════════════════ │ SSE stream opens
225
+ │ event: <name> / data: {…} │ ← filter(subject, payload) per emission
226
+ ```
227
+
228
+ Enable it with `auth: { enabled: true }`:
229
+
230
+ ```typescript
231
+ import { defineServerConfig } from '@spfn/core/server';
232
+ import { authenticate } from '@spfn/auth/server';
233
+
234
+ export default defineServerConfig()
235
+ .middlewares([authenticate]) // protects POST /events/token
236
+ .routes(appRouter)
237
+ .events(eventRouter, {
238
+ auth: { enabled: true },
239
+ })
240
+ .build();
241
+ // → POST /events/token (mints token; subject = c.get('auth').userId by default)
242
+ // → GET /events/stream?token=…&events=…
243
+ ```
244
+
245
+ The token endpoint path is **derived** from the stream path: `/events/stream` →
246
+ `/events/token`, `/sse` → `/token`. It is registered with your app's named middleware
247
+ applied — both the server-level `.middlewares([...])` and the router's `.use([...])` — so
248
+ whatever authenticates your routes also authenticates token issuance.
249
+
250
+ ### Token store (multi-instance)
251
+
252
+ One-time tokens are stored. With `auth.enabled` and no explicit `store`, the server
253
+ auto-detects a cache at startup via `getCache()`:
254
+
255
+ | Environment | Store | How |
256
+ |-------------|-------|-----|
257
+ | No cache (`CACHE_URL` unset) | `InMemoryTokenStore` (Map) | automatic fallback |
258
+ | Cache connected | `CacheTokenStore` (Redis/Valkey, `SET EX` + `GETDEL`, prefix `sse:token:`) | auto-detected |
259
+ | Custom | your `SSETokenStore` impl | pass `auth.store` |
260
+
261
+ Manual / custom store:
262
+
263
+ ```typescript
264
+ import { CacheTokenStore } from '@spfn/core/event/sse';
265
+ import { getCache } from '@spfn/core/cache';
266
+
267
+ .events(eventRouter, {
268
+ auth: { enabled: true, store: new CacheTokenStore(getCache()!) },
269
+ })
270
+ ```
271
+
272
+ ```typescript
273
+ import type { SSETokenStore, SSEToken } from '@spfn/core/event/sse';
274
+
275
+ class DynamoTokenStore implements SSETokenStore
276
+ {
277
+ async set(token: string, data: SSEToken): Promise<void> { /* ... */ }
278
+ async consume(token: string): Promise<SSEToken | null> { /* one-time get+delete */ }
279
+ async cleanup(): Promise<void> { /* remove expired */ }
280
+ }
281
+ ```
282
+
283
+ ### Sharing a token manager with `@spfn/auth`
284
+
285
+ If you already run `@spfn/auth`'s one-time-token system, hand SSE the **same** manager via
286
+ `tokenManager` instead of letting it create its own — both SSE and direct API calls then
287
+ draw from one token pool. Use a **lazy resolver** because `getOneTimeTokenManager()` only
288
+ exists after the auth lifecycle's `afterInfrastructure` runs:
289
+
290
+ ```typescript
291
+ import { createAuthLifecycle, getOneTimeTokenManager } from '@spfn/auth/server';
292
+
293
+ export default defineServerConfig()
294
+ .lifecycle(createAuthLifecycle())
295
+ .events(eventRouter, {
296
+ auth: {
297
+ enabled: true,
298
+ tokenManager: () => getOneTimeTokenManager(), // resolved at server start
299
+ },
300
+ })
301
+ .build();
302
+ ```
303
+
304
+ When `tokenManager` is provided, `store`/`tokenTtl` are ignored (the external manager owns them).
305
+
306
+ ### Authorization hooks
307
+
308
+ Both hooks get full type inference from the router (no casting).
309
+
310
+ `authorize` — runs **once on connect**, decides which events the subject may subscribe to.
311
+ Return the allowed subset; an empty array ⇒ `403`.
312
+
313
+ ```typescript
314
+ .events(eventRouter, {
315
+ auth: {
316
+ enabled: true,
317
+ authorize: async (subject, events) =>
318
+ {
319
+ // events: ('userCreated' | 'orderPlaced')[] — inferred
320
+ const user = await usersRepository.findById(subject);
321
+ return user.role === 'admin' ? events : events.filter(e => !e.startsWith('admin.'));
322
+ },
323
+ },
324
+ })
325
+ ```
326
+
327
+ `filter` — runs **per emission**, decides whether a given payload goes to this subject.
328
+ Return `false` to skip. Payload is typed per event.
329
+
330
+ ```typescript
331
+ .events(eventRouter, {
332
+ auth: {
333
+ enabled: true,
334
+ filter: {
335
+ // payload: { orderId; userId; amount } — inferred
336
+ orderPlaced: (subject, payload) => payload.userId === subject,
337
+ // userCreated: omitted → delivered to all authorized subscribers
338
+ },
339
+ },
340
+ })
341
+ ```
342
+
343
+ ### SSE auth config (`SSEAuthConfig<TRouter>`)
344
+
345
+ | Option | Type | Default | Description |
346
+ |--------|------|---------|-------------|
347
+ | `enabled` | `boolean` | `false` | turn on token auth |
348
+ | `tokenTtl` | `number` | `30000` | token TTL (ms) |
349
+ | `store` | `SSETokenStore` | auto (Cache → InMemory) | token storage backend |
350
+ | `tokenManager` | `SSETokenManager \| () => SSETokenManager` | — | reuse an external manager (lazy resolver recommended); overrides `store`/`tokenTtl` |
351
+ | `getSubject` | `(c: Context) => string \| null` | `c.get('auth')?.userId ?? null` | extract subject on the token endpoint |
352
+ | `authorize` | `(subject, events[]) => events[] \| Promise<…>` | — | subscription authorization (once on connect) |
353
+ | `filter` | `{ [event]?: (subject, payload) => boolean }` | — | per-event payload filter |
354
+
355
+ ---
356
+
357
+ ## Browser client
358
+
359
+ ### `createSSEClient(config?)` — no auth
360
+
361
+ ```typescript
362
+ import { createSSEClient } from '@spfn/core/event/sse/client';
363
+ import type { EventRouter } from '@/server/events';
364
+
365
+ // Defaults: NEXT_PUBLIC_SPFN_API_URL (or http://localhost:8790) + /events/stream
366
+ const client = createSSEClient<EventRouter>();
367
+
368
+ const unsubscribe = client.subscribe({
369
+ events: ['userCreated', 'orderPlaced'], // names inferred from EventRouter
370
+ handlers: {
371
+ userCreated: (payload) => console.log('user', payload.userId),
372
+ orderPlaced: (payload) => console.log('order', payload.orderId),
373
+ },
374
+ onOpen: () => console.log('connected'),
375
+ onError: (err) => console.error(err),
376
+ onReconnect: (attempt) => console.log('reconnect', attempt),
377
+ onClose: () => console.log('closed for good'),
378
+ });
379
+
380
+ client.getState(); // 'connecting' | 'open' | 'closed' | 'error'
381
+ client.close(); // tear down the active connection
382
+ unsubscribe(); // same as close() for that subscription
383
+ ```
384
+
385
+ `SSEClientConfig`:
386
+
387
+ | Option | Type | Default | Description |
388
+ |--------|------|---------|-------------|
389
+ | `host` | `string` | `NEXT_PUBLIC_SPFN_API_URL` or `http://localhost:8790` | backend host |
390
+ | `pathname` | `string` | `/events/stream` | SSE endpoint path |
391
+ | `url` | `string` | — | **deprecated**; full URL overriding host+pathname |
392
+ | `reconnect` | `boolean` | `true` | auto-reconnect on drop |
393
+ | `reconnectDelay` | `number` | `3000` | delay between attempts (ms) |
394
+ | `maxReconnectAttempts` | `number` | `0` | `0` = infinite |
395
+ | `withCredentials` | `boolean` | `false` | send cookies with the EventSource request |
396
+ | `acquireToken` | `() => Promise<string>` | — | mint a token before each (re)connect; appended as `?token=…` |
397
+
398
+ ### `createAuthSSEClient(config?)` — with auth (recommended)
399
+
400
+ Wraps `createSSEClient` and wires `acquireToken` to fetch a one-time token from the RPC
401
+ proxy automatically on every (re)connect.
402
+
403
+ ```typescript
404
+ import { createAuthSSEClient } from '@spfn/core/event/sse/client';
405
+ import type { EventRouter } from '@/server/events';
406
+
407
+ const client = createAuthSSEClient<EventRouter>(); // POSTs /api/rpc/eventsToken under the hood
408
+
409
+ client.subscribe({
410
+ events: ['userCreated'],
411
+ handlers: { userCreated: (p) => console.log(p) },
412
+ });
413
+ ```
414
+
415
+ `AuthSSEClientConfig` = `Omit<SSEClientConfig, 'acquireToken'>` plus `rpcBaseUrl` (default
416
+ `/api/rpc`). It requires `eventRouteMap` merged into your RPC proxy so `eventsToken`
417
+ resolves to `POST /events/token`:
418
+
419
+ ```typescript
420
+ // app/api/rpc/[routeName]/route.ts
421
+ import '@spfn/auth/nextjs/api';
422
+ import { createRpcProxy } from '@spfn/core/nextjs/server';
423
+ import { eventRouteMap } from '@spfn/core/event';
424
+ import { routeMap } from '@/generated/route-map';
425
+
426
+ export const { GET, POST } = createRpcProxy({
427
+ routeMap: { ...routeMap, ...eventRouteMap },
428
+ });
429
+ ```
430
+
431
+ ### `subscribeToEvents(events, handlers, config?)` — one-shot helper
432
+
433
+ ```typescript
434
+ import { subscribeToEvents } from '@spfn/core/event/sse/client';
435
+ import type { EventRouter } from '@/server/events';
436
+
437
+ const unsubscribe = subscribeToEvents<EventRouter>(
438
+ ['userCreated'],
439
+ { userCreated: (payload) => console.log(payload) },
440
+ { host: 'https://api.example.com' }, // optional SSEClientConfig
441
+ );
442
+ ```
443
+
444
+ It creates a throwaway client and subscribes once. For auth, prefer `createAuthSSEClient`
445
+ (this helper takes a plain `SSEClientConfig`, so you'd have to wire `acquireToken` yourself).
446
+
447
+ ---
448
+
449
+ ## Multi-instance broadcast (cross-pod fan-out)
450
+
451
+ By default `emit` only reaches handlers in the **same process**. Across multiple pods, an
452
+ `emit` on the pod that handles the chat POST must still reach the SSE stream pinned to a
453
+ **different** pod — otherwise the stream silently stalls.
454
+
455
+ **This is automatic.** When a cache is configured (`CACHE_URL` / `getCache()` returns a
456
+ client), `.events(router)` and `.websockets(router)` wire every event to a Redis/Valkey
457
+ pub/sub transport at startup. No code change in your app — register the router as usual and
458
+ multi-pod fan-out just works. Without a cache it is a no-op and events stay in-process, so a
459
+ single pod (or local dev) behaves exactly as before.
460
+
461
+ ```typescript
462
+ export default defineServerConfig()
463
+ .events(eventRouter) // CACHE_URL set → cross-pod fan-out; unset → in-process
464
+ .build();
465
+
466
+ // Force in-process even when a cache is present, or set an isolation prefix:
467
+ .events(eventRouter, {
468
+ multiInstance: false, // default true
469
+ channelPrefix: 'my-app:', // default: env SPFN_SSE_CHANNEL_PREFIX, else 'spfn:sse:'
470
+ })
471
+ ```
472
+
473
+ Mechanics (from `event.ts`): once a cache is wired, `emit` calls `cache.publish(name,
474
+ payload)` **instead of** triggering local handlers directly — local handlers (including the
475
+ SSE stream on the same pod) fire when the message comes back through the pub/sub `subscribe`
476
+ callback. Auth `filter` still runs per-subscriber on the **receiving** pod's SSE handler —
477
+ the transport only fans out by event name. Job queues receive the payload on every emit
478
+ regardless of cache.
479
+
480
+ > **Process-global.** `multiInstance` and `channelPrefix` are resolved **once per process**
481
+ > (first `.events()`/`.websockets()` wiring wins); a second router can't change them. That's
482
+ > correct because one process serves one app. An event shared by both routers is wired once.
483
+ >
484
+ > **Payloads must be JSON-serializable** when fan-out is on (they cross Redis as JSON). A
485
+ > `Date` arrives as an ISO string; a void event arrives as `null` on remote pods (vs
486
+ > `undefined` in-process). `bigint`/circular payloads can't serialize — see degrade below.
487
+ >
488
+ > **Ordering needs sequential `await` _and_ healthy publishes.** Per-channel order is preserved
489
+ > end-to-end only if the producer awaits each emit in turn (`for (const c of chunks) await
490
+ > event.emit(c)`). Fire-and-forget (`chunks.forEach(c => event.emit(c))`) races the publishes
491
+ > and can reorder a token stream. Also: a mid-stream publish **failure** delivers its event via
492
+ > the synchronous local fallback, which can land ahead of an earlier successful emit whose echo
493
+ > is still in flight — so a Redis blip mid-stream may reorder relative to in-flight emits. The
494
+ > transport adds no sequence number; if strict order matters across failures, carry one in the
495
+ > payload and reorder on the client.
496
+ >
497
+ > **Channel isolation & receive-side trust.** The default prefix `spfn:sse:` is shared by every
498
+ > SPFN app, so apps sharing **one** Redis with a colliding event name would cross-talk. Set
499
+ > `channelPrefix` / `SPFN_SSE_CHANNEL_PREFIX` per app (the server logs a WARN at startup if
500
+ > you're on the default); separate `CACHE_URL`s per app are isolated already. Note the receiving
501
+ > pod does **not** re-validate a payload against the event schema before delivering it to
502
+ > `filter`/handlers — anything with Redis access can publish to a channel, so treat Redis access
503
+ > as a trust boundary (same level as the one-time-token store).
504
+
505
+ **Degrade**: SSE is lossy (at-most-once). If a publish can't reach Redis (a blip) or the
506
+ payload can't serialize, the event is **still delivered to this pod's own subscribers**
507
+ (local fallback) and logged; only **remote** pods miss it. The same local fallback covers the
508
+ asymmetric case where the publish succeeds but **this pod's subscriber socket is down** (its
509
+ echo — the only path to same-pod streams — wouldn't arrive). A sustained publish outage trips
510
+ a short circuit breaker so emits fast-path to local instead of each paying the publish timeout.
511
+ A publish never crashes `emit` or kills a stream. ioredis auto-reconnects and re-subscribes
512
+ (autoResubscribe, default true). A per-event SUBSCRIBE failure at
513
+ startup degrades that event to in-process (logged) rather than aborting boot. Same-pod
514
+ delivery costs one Redis round-trip — for a single-replica deploy with a cache, prefer
515
+ `multiInstance: false` to skip it.
516
+
517
+ ### Manual `useCache` (advanced)
518
+
519
+ You rarely need this — the server wires it for you. `EventDef.useCache(cache)` is the
520
+ underlying primitive if you drive events outside `defineServerConfig` (e.g. a worker). The
521
+ `PubSubCache` shape it expects:
522
+
523
+ ```typescript
524
+ import { getCache } from '@spfn/core/cache';
525
+
526
+ const cache = getCache();
527
+ if (cache)
528
+ {
529
+ await userCreated.useCache({
530
+ publish: async (channel, message) =>
531
+ {
532
+ await cache.publish(channel, JSON.stringify(message));
533
+ },
534
+ subscribe: async (channel, handler) =>
535
+ {
536
+ const sub = cache.duplicate();
537
+ await sub.subscribe(channel);
538
+ sub.on('message', (ch, msg) =>
539
+ {
540
+ if (ch === channel) handler(JSON.parse(msg));
541
+ });
542
+ },
543
+ });
544
+ }
545
+
546
+ await userCreated.emit({ userId: '123', email: 'a@b.com' }); // broadcasts to all instances
547
+ ```
548
+
549
+ **`await` `useCache` before emitting** — it must finish subscribing first. A direct second
550
+ call on the same `EventDef` logs `Cache already configured` and is ignored. (Separately, the
551
+ server's auto-wiring dedups by **event name** across the SSE and WS routers — tracked in the
552
+ transport, so a shared event's `useCache` is invoked only once and the warn never fires.)
553
+
554
+ ---
555
+
556
+ ## Job integration
557
+
558
+ A job subscribing to an event with `.on(event)` registers itself on the event's job queue;
559
+ the event's `emit` then enqueues the payload to every such queue (in addition to in-memory
560
+ handlers / cache broadcast).
561
+
562
+ ```typescript
563
+ import { defineEvent } from '@spfn/core/event';
564
+ import { job, defineJobRouter } from '@spfn/core/job';
565
+ import { Type } from '@sinclair/typebox';
566
+
567
+ export const orderPlaced = defineEvent('order.placed', Type.Object({
568
+ orderId: Type.String(),
569
+ userId: Type.String(),
570
+ }));
571
+
572
+ export const sendConfirmation = job('send-order-confirmation')
573
+ .on(orderPlaced) // payload type inferred from the event
574
+ .handler(async (payload) => emailService.send(payload.orderId));
575
+
576
+ export const updateInventory = job('update-inventory')
577
+ .on(orderPlaced)
578
+ .handler(async (payload) => inventoryService.reserve(payload.orderId));
579
+
580
+ export const jobRouter = defineJobRouter({ sendConfirmation, updateInventory });
581
+
582
+ await orderPlaced.emit({ orderId: 'ord-1', userId: 'u-1' }); // both jobs enqueue
583
+ ```
584
+
585
+ One emit fans out to in-memory handlers, the SSE stream, and every subscribed job queue —
586
+ fully decoupled.
587
+
588
+ ---
589
+
590
+ ## Pitfalls & anti-patterns
591
+
592
+ - **Wrong import depth for the client.** `createSSEClient` / `createAuthSSEClient` /
593
+ `subscribeToEvents` are in `@spfn/core/event/sse/**client**`, not `@spfn/core/event/sse`.
594
+ The bare `/sse` is the server (Hono) surface; importing it into the browser pulls server code.
595
+ - **`useCache` not awaited before `emit`.** `useCache` is async (it subscribes to the
596
+ channel). Emitting before it resolves can drop the very first cross-instance events. Always
597
+ `await event.useCache(...)` first.
598
+ - **Calling `useCache` twice.** A second call logs `Cache already configured for event: …`
599
+ and is ignored. Configure the cache once per event instance (typically at startup).
600
+ - **Emitting before subscribing (in-memory).** `subscribe` registers a handler set; an
601
+ `emit` that runs before any `subscribe` simply has no handlers. Register handlers / jobs at
602
+ startup, not lazily after the first emit.
603
+ - **`auth.headers`/`SSEHandlerConfig.headers` does nothing.** The handler reads only
604
+ `pingInterval`, `auth`, and `maxQueue`. Don't expect custom response headers from config.
605
+ - **A slow client is dropped, not buffered forever.** Writes are bounded (`maxQueue`, default
606
+ 1000): if a client can't keep up with a fast producer, its connection is closed instead of
607
+ growing memory without limit. Expect occasional reconnects under heavy streaming to slow
608
+ clients; that's the backpressure working, not a bug.
609
+ - **Don't `new EventSource(...)` by hand.** You lose type inference, the `connected`/`ping`
610
+ control-event handling, one-time-token reconnect, and StrictMode-safe teardown that the
611
+ client implements. Use `createSSEClient` / `createAuthSSEClient`.
612
+ - **Token-auth + browser auto-retry.** A one-time token is consumed on first use, so the
613
+ browser's built-in EventSource retry would reconnect with a dead token. The client handles
614
+ this: on error with `acquireToken` set, it closes and reconnects through its own path to
615
+ mint a fresh token. Don't disable `reconnect` expecting native retry to work with auth.
616
+ - **Stream-time errors aren't subscription errors.** `authorize` returning `[]` ⇒ `403` at
617
+ connect; invalid event names ⇒ `400`; missing/expired token ⇒ `401`. `onError` on the
618
+ client fires for transport-level drops, not for these HTTP rejections — check the network
619
+ response when a connection never opens.
620
+ - **Subject default.** Without a custom `getSubject`, the token endpoint reads
621
+ `c.get('auth')?.userId`. If your auth middleware stores the user elsewhere, supply
622
+ `getSubject` or token issuance returns `401`.
623
+ - **One subscription per client.** `createSSEClient(...).subscribe(...)` supersedes any
624
+ previous subscription on that client (the prior connection is closed). For independent
625
+ streams, create separate clients.
626
+ - **`SSETokenManager` keeps a cleanup timer.** It runs an `unref`'d interval; the in-memory
627
+ store needs it to expire tokens. If you construct a manager manually (outside the server),
628
+ call `destroy()` on shutdown. The Redis-backed `CacheTokenStore` relies on TTL and its
629
+ `cleanup()` is a no-op.
630
+
631
+ ---
632
+
633
+ ## WebSocket (bidirectional variant)
634
+
635
+ For client→server messages in addition to server→client push, use a WS router. It reuses
636
+ the same `defineEvent` definitions and shares the SSE token manager / auth model.
637
+
638
+ ```typescript
639
+ // server
640
+ import { defineWSRouter } from '@spfn/core/event'; // also re-exported from /event/ws
641
+ import { attachWSHandler } from '@spfn/core/event/ws';
642
+
643
+ export const wsRouter = defineWSRouter({
644
+ events: { userUpdated, notification }, // server → client push
645
+ messages: { // client → server handlers
646
+ ping: ({ ws }) => ws.send('pong', {}),
647
+ 'chat.send': ({ payload, subject }) => handleChat(payload, subject),
648
+ },
649
+ });
650
+ export type WSRouter = typeof wsRouter;
651
+
652
+ // usually mounted via defineServerConfig().websockets(wsRouter)
653
+ ```
654
+
655
+ ```typescript
656
+ // browser
657
+ import { createWSClient } from '@spfn/core/event/ws/client';
658
+ import type { WSRouter } from '@/server/ws';
659
+
660
+ const client = createWSClient<WSRouter>();
661
+ client.subscribe({ events: ['userUpdated'], handlers: { userUpdated: (p) => {} } });
662
+ client.send('ping', {});
663
+ ```
664
+
665
+ `WSRouterDef` extends `EventRouterDef` with a `messages` map. Message handlers receive
666
+ `{ payload, subject?, ws }` (`WSMessageContext`). See `@spfn/core/event/ws` exports for
667
+ `WSHandlerConfig`, `WSAuthConfig`, `WSClientConfig`, etc.
668
+
669
+ ### Resource limits & backpressure (`WSHandlerConfig`)
670
+
671
+ The WS server is hardened like the SSE path — a slow or dead client cannot exhaust memory
672
+ or connection slots:
673
+
674
+ | Option | Default | Effect |
675
+ |---|---|---|
676
+ | `maxPayload` | `1048576` (1 MiB) | Max inbound frame size; larger frames are rejected by `ws` before they are buffered/parsed. |
677
+ | `maxBufferedBytes` | `1048576` (1 MiB) | Backpressure cap — if a connection's outbound buffer (`bufferedAmount`) exceeds this, the connection is closed with `1013` instead of buffering more (no OOM from a slow consumer). The client reconnects and re-subscribes. |
678
+ | `maxConnections` | `10000` | Global concurrent-connection cap; connections beyond it are rejected with `1013`. |
679
+ | `maxConnectionsPerSubject` | `0` (unlimited) | Per-authenticated-subject connection cap. |
680
+
681
+ Keep-alive also tracks **pongs**: a socket that doesn't answer a ping by the next
682
+ `pingInterval` tick is `terminate()`d, so half-open connections (sleeping device, NAT drop)
683
+ are reaped instead of lingering with their subscriptions and buffers.
684
+
685
+ ---
686
+
687
+ ## Types reference
688
+
689
+ ```typescript
690
+ interface EventDef<TPayload = void> {
691
+ readonly name: string;
692
+ readonly schema?: TSchema;
693
+ subscribe: (handler: EventHandler<TPayload>) => () => void;
694
+ unsubscribeAll: () => void;
695
+ emit: TPayload extends void ? () => Promise<void> : (payload: TPayload) => Promise<void>;
696
+ useCache: (cache: PubSubCache) => Promise<EventDef<TPayload>>;
697
+ }
698
+
699
+ type EventHandler<TPayload> = (payload: TPayload) => void | Promise<void>;
700
+ type InferEventPayload<TEvent> = TEvent extends EventDef<infer P> ? P : never; // single-arg
701
+
702
+ interface PubSubCache {
703
+ publish(channel: string, message: unknown): Promise<void>;
704
+ subscribe(channel: string, handler: (message: unknown) => void | Promise<void>): Promise<void>;
705
+ }
706
+ type JobQueueSender = (queueName: string, payload: unknown) => Promise<void>;
707
+
708
+ interface EventRouterDef<TEvents> {
709
+ readonly events: TEvents;
710
+ readonly eventNames: (keyof TEvents)[];
711
+ readonly _types: { [K in keyof TEvents]: TEvents[K]['_payload'] };
712
+ }
713
+ type InferEventNames<T> = /* keyof router events as string union */;
714
+ type InferEventPayloads<T> = T['_types'];
715
+ // router two-arg payload, exported as `InferRouterEventPayload`:
716
+ type InferRouterEventPayload<T, K> = T['_types'][K];
717
+
718
+ interface SSEMessage<TEvent extends string = string, TPayload = unknown> {
719
+ event: TEvent; data: TPayload; id?: string;
720
+ }
721
+ type SSEConnectionState = 'connecting' | 'open' | 'closed' | 'error';
722
+
723
+ interface SSEToken { token: string; subject: string; expiresAt: number; }
724
+ interface SSETokenStore {
725
+ set(token: string, data: SSEToken): Promise<void>;
726
+ consume(token: string): Promise<SSEToken | null>; // one-time get+delete
727
+ cleanup(): Promise<void>;
728
+ }
729
+ ```
730
+
731
+ ## Related
732
+
733
+ - [@spfn/core/job](../job/README.md) — background jobs that subscribe to events via `.on()`
734
+ - [@spfn/core/cache](../cache/README.md) — Redis/Valkey backing for multi-instance broadcast + token store
735
+ - [@spfn/core/server](../server/README.md) — `defineServerConfig().events()` / `.websockets()`
736
+ - [MDN: Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events)