@spfn/core 0.3.0-beta.23 → 0.3.0-beta.24

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.
@@ -47,6 +47,114 @@ function createBoundedWriter(stream, maxQueue, onClose) {
47
47
  }
48
48
  };
49
49
  }
50
+ var registryLogger = logger.child("@spfn/core:sse");
51
+ var SUBSCRIPTION_GRANTED = "subscription.granted";
52
+ var SUBSCRIPTION_REVOKED = "subscription.revoked";
53
+ function createConnectionRegistry() {
54
+ const bySubject = /* @__PURE__ */ new Map();
55
+ const pendingBySubject = /* @__PURE__ */ new Map();
56
+ const beginAdmission = (subject, signal) => {
57
+ const changes = /* @__PURE__ */ new Map();
58
+ addToSet(pendingBySubject, subject, changes);
59
+ const end = endOnce(signal, () => removeFromSet(pendingBySubject, subject, changes));
60
+ return {
61
+ cancel: end,
62
+ open: (connection) => {
63
+ if (!end()) {
64
+ return false;
65
+ }
66
+ applyRecorded(connection, changes);
67
+ addToSet(bySubject, subject, connection);
68
+ return true;
69
+ }
70
+ };
71
+ };
72
+ const change = (kind, subject, eventName) => {
73
+ const pending = pendingBySubject.get(subject);
74
+ const connections = bySubject.get(subject);
75
+ pending?.forEach((changes) => changes.set(eventName, kind));
76
+ connections?.forEach((connection) => (kind === "grant" ? grantOn : revokeOn)(connection, eventName));
77
+ if (!pending && !connections) {
78
+ registryLogger.debug("SSE subscription change for a subject with no open connection ignored", {
79
+ event: eventName,
80
+ subject
81
+ });
82
+ }
83
+ };
84
+ return {
85
+ beginAdmission,
86
+ remove: (connection) => {
87
+ if (connection.subject) {
88
+ removeFromSet(bySubject, connection.subject, connection);
89
+ }
90
+ },
91
+ /** Open connections only — a pending admission is not counted. */
92
+ count: (subject) => bySubject.get(subject)?.size ?? 0,
93
+ pendingCount: (subject) => pendingBySubject.get(subject)?.size ?? 0,
94
+ grant: (subject, eventName) => change("grant", subject, eventName),
95
+ revoke: (subject, eventName) => change("revoke", subject, eventName)
96
+ };
97
+ }
98
+ function endOnce(signal, remove) {
99
+ let ended = false;
100
+ const end = () => {
101
+ if (ended) {
102
+ return false;
103
+ }
104
+ ended = true;
105
+ signal.removeEventListener("abort", end);
106
+ remove();
107
+ return true;
108
+ };
109
+ signal.addEventListener("abort", end, { once: true });
110
+ if (signal.aborted) {
111
+ end();
112
+ }
113
+ return end;
114
+ }
115
+ function addToSet(map, key, value) {
116
+ const set = map.get(key) ?? /* @__PURE__ */ new Set();
117
+ set.add(value);
118
+ map.set(key, set);
119
+ }
120
+ function removeFromSet(map, key, value) {
121
+ const set = map.get(key);
122
+ set?.delete(value);
123
+ if (set?.size === 0) {
124
+ map.delete(key);
125
+ }
126
+ }
127
+ function applyRecorded(connection, changes) {
128
+ changes.forEach((kind, eventName) => {
129
+ const [from, to] = kind === "grant" ? [connection.denied, connection.allowed] : [connection.allowed, connection.denied];
130
+ if (from.delete(eventName)) {
131
+ to.add(eventName);
132
+ }
133
+ });
134
+ }
135
+ function grantOn(connection, eventName) {
136
+ if (!connection.denied.has(eventName)) {
137
+ return;
138
+ }
139
+ connection.unsubscribes.set(eventName, connection.subscribe(eventName));
140
+ connection.denied.delete(eventName);
141
+ connection.allowed.add(eventName);
142
+ connection.notify(SUBSCRIPTION_GRANTED, eventName);
143
+ }
144
+ function revokeOn(connection, eventName) {
145
+ if (!connection.allowed.has(eventName)) {
146
+ return;
147
+ }
148
+ connection.unsubscribes.get(eventName)?.();
149
+ connection.unsubscribes.delete(eventName);
150
+ connection.allowed.delete(eventName);
151
+ connection.denied.add(eventName);
152
+ connection.notify(SUBSCRIPTION_REVOKED, eventName);
153
+ }
154
+ function unsubscribeAll(connection) {
155
+ connection.unsubscribes.forEach((unsubscribe) => unsubscribe());
156
+ connection.unsubscribes.clear();
157
+ }
50
158
 
51
159
  // src/event/sse/handler.ts
52
160
  var sseLogger = logger.child("@spfn/core:sse");
@@ -77,125 +185,264 @@ function createSSEHandler(router, config = {}, tokenManager) {
77
185
  auth: authConfig,
78
186
  maxQueue = DEFAULT_MAX_QUEUE
79
187
  } = config;
80
- return async (c) => {
81
- const subject = await authenticateToken(c, tokenManager);
82
- if (subject === false) {
83
- return c.json({ error: "Missing token parameter" }, 401);
188
+ const registry = createConnectionRegistry();
189
+ registerSubscriptionControls(router, registry);
190
+ const streamConfig = { router, authConfig, registry, pingInterval, maxQueue };
191
+ const handler = async (c) => {
192
+ const admission = await admitConnection(c, streamConfig, tokenManager);
193
+ if (admission instanceof Response) {
194
+ return admission;
84
195
  }
85
- if (subject === null) {
86
- return c.json({ error: "Invalid or expired token" }, 401);
196
+ if (c.req.raw.signal.aborted) {
197
+ admission.pending?.cancel();
198
+ return new Response(null, { status: 499 });
87
199
  }
88
- if (subject) {
89
- c.set("sseSubject", subject);
90
- }
91
- const requestedEvents = parseRequestedEvents(c);
92
- if (!requestedEvents) {
93
- return c.json({ error: "Missing events parameter" }, 400);
94
- }
95
- const validEventNames = router.eventNames;
96
- const invalidEvents = requestedEvents.filter((e) => !validEventNames.includes(e));
97
- if (invalidEvents.length > 0) {
98
- return c.json({
99
- error: "Invalid event names",
100
- invalidEvents,
101
- validEvents: validEventNames
102
- }, 400);
200
+ c.header("X-Accel-Buffering", "no");
201
+ return streamSSE(c, (stream) => runStream(c, stream, admission, streamConfig), async (err) => {
202
+ sseLogger.error("SSE stream error", {
203
+ error: err.message
204
+ });
205
+ });
206
+ };
207
+ return Object.assign(handler, {
208
+ /** @internal Open registered connections of a subject (tests). */
209
+ _openConnections: (subject) => registry.count(subject),
210
+ /** @internal Connects of a subject still in admission (tests). */
211
+ _pendingAdmissions: (subject) => registry.pendingCount(subject)
212
+ });
213
+ }
214
+ function registerSubscriptionControls(router, registry) {
215
+ for (const eventName of router.eventNames) {
216
+ router.events[eventName]._registerSubscriptionControl({
217
+ grant: (subject) => registry.grant(subject, eventName),
218
+ revoke: (subject) => registry.revoke(subject, eventName)
219
+ });
220
+ }
221
+ }
222
+ async function admitConnection(c, config, tokenManager) {
223
+ const { router, authConfig, registry } = config;
224
+ const subject = await authenticateToken(c, tokenManager);
225
+ if (subject === false) {
226
+ return c.json({ error: "Missing token parameter" }, 401);
227
+ }
228
+ if (subject === null) {
229
+ return c.json({ error: "Invalid or expired token" }, 401);
230
+ }
231
+ if (subject) {
232
+ c.set("sseSubject", subject);
233
+ }
234
+ const requested = parseRequestedEvents(c);
235
+ if (!requested) {
236
+ return c.json({ error: "Missing events parameter" }, 400);
237
+ }
238
+ const validEventNames = router.eventNames;
239
+ const invalidEvents = requested.filter((e) => !validEventNames.includes(e));
240
+ if (invalidEvents.length > 0) {
241
+ return c.json({
242
+ error: "Invalid event names",
243
+ invalidEvents,
244
+ validEvents: validEventNames
245
+ }, 400);
246
+ }
247
+ return whilePending(
248
+ subject ? registry.beginAdmission(subject, c.req.raw.signal) : void 0,
249
+ () => authorizeConnection(c, router, authConfig, subject, requested)
250
+ );
251
+ }
252
+ async function whilePending(pending, check) {
253
+ let outcome;
254
+ try {
255
+ outcome = await check();
256
+ return outcome instanceof Response ? outcome : { ...outcome, pending };
257
+ } finally {
258
+ if (!outcome || outcome instanceof Response) {
259
+ pending?.cancel();
103
260
  }
104
- const allowedEvents = await authorizeEvents(subject, requestedEvents, authConfig);
105
- if (allowedEvents === null) {
106
- return c.json({ error: "Not authorized for any requested events" }, 403);
261
+ }
262
+ }
263
+ async function authorizeConnection(c, router, authConfig, subject, requested) {
264
+ const authorized = await authorizeEvents(subject, requested, authConfig);
265
+ if (authorized === null) {
266
+ return c.json({ error: "Not authorized for any requested events" }, 403);
267
+ }
268
+ const request = { query: c.req.query(), headers: c.req.header() };
269
+ const resolved = await resolveConnectionPrincipal(subject, request, authConfig);
270
+ if (!resolved) {
271
+ return c.json({ error: "Principal could not be resolved" }, 403);
272
+ }
273
+ const allowed = subject ? await checkCanSubscribe(router, authorized, { subject, principal: resolved.principal, request }) : authorized;
274
+ const denied = requested.filter((e) => !allowed.includes(e));
275
+ sseLogger.debug("SSE connection requested", {
276
+ events: allowed,
277
+ deniedEvents: denied,
278
+ subject: subject || void 0,
279
+ clientIp: c.req.header("x-forwarded-for") || c.req.header("x-real-ip")
280
+ });
281
+ return { subject, requested, allowed, denied, request };
282
+ }
283
+ async function resolveConnectionPrincipal(subject, request, authConfig) {
284
+ if (!subject || !authConfig?.resolvePrincipal) {
285
+ return { principal: void 0 };
286
+ }
287
+ try {
288
+ return { principal: await authConfig.resolvePrincipal(subject, request) };
289
+ } catch {
290
+ sseLogger.warn("SSE principal could not be resolved \u2014 connection refused", { subject });
291
+ return null;
292
+ }
293
+ }
294
+ async function checkCanSubscribe(router, events, ctx) {
295
+ const verdicts = await Promise.all(events.map((eventName) => askCanSubscribe(eventName, router.events[eventName], ctx)));
296
+ return events.filter((_, i) => verdicts[i]);
297
+ }
298
+ async function askCanSubscribe(eventName, eventDef, ctx) {
299
+ if (!eventDef) {
300
+ return false;
301
+ }
302
+ if (!eventDef._canSubscribe) {
303
+ return true;
304
+ }
305
+ try {
306
+ return await eventDef._canSubscribe(ctx) === true;
307
+ } catch {
308
+ sseLogger.warn("SSE canSubscribe threw \u2014 event denied on this connection", {
309
+ event: eventName,
310
+ subject: ctx.subject
311
+ });
312
+ return false;
313
+ }
314
+ }
315
+ async function runStream(c, stream, admission, config) {
316
+ const { allowed, denied, subject, request } = admission;
317
+ let connectionDead = false;
318
+ let pingTimer;
319
+ let onClosed;
320
+ const cleanup = (reason) => {
321
+ if (connectionDead) return;
322
+ connectionDead = true;
323
+ clearInterval(pingTimer);
324
+ unsubscribeAll(connection);
325
+ config.registry.remove(connection);
326
+ writer.close();
327
+ onClosed?.();
328
+ sseLogger.info("SSE dead connection cleaned up", {
329
+ events: [...connection.allowed],
330
+ reason
331
+ });
332
+ };
333
+ const writer = createBoundedWriter(stream, config.maxQueue, (reason) => {
334
+ sseLogger.warn("SSE connection closed", { events: [...connection.allowed], reason });
335
+ cleanup(reason);
336
+ });
337
+ const connection = {
338
+ subject,
339
+ requested: admission.requested,
340
+ allowed: new Set(allowed),
341
+ denied: new Set(denied),
342
+ unsubscribes: /* @__PURE__ */ new Map(),
343
+ request,
344
+ subscribe: createEventSubscriber({
345
+ router: config.router,
346
+ authConfig: config.authConfig,
347
+ subject,
348
+ request,
349
+ writer,
350
+ isDead: () => connectionDead
351
+ }),
352
+ notify: (frame, eventName) => {
353
+ if (connectionDead) return;
354
+ writer.enqueue({ event: frame, data: JSON.stringify({ event: eventName }) });
107
355
  }
108
- sseLogger.debug("SSE connection requested", {
109
- events: allowedEvents,
110
- subject: subject || void 0,
111
- clientIp: c.req.header("x-forwarded-for") || c.req.header("x-real-ip")
356
+ };
357
+ if (admission.pending?.open(connection) === false) {
358
+ cleanup("aborted during admission");
359
+ return;
360
+ }
361
+ openSubscriptions(connection, writer);
362
+ pingTimer = setInterval(() => {
363
+ if (connectionDead) return;
364
+ writer.enqueue({
365
+ event: "ping",
366
+ data: JSON.stringify({ timestamp: Date.now() })
112
367
  });
113
- c.header("X-Accel-Buffering", "no");
114
- return streamSSE(c, async (stream) => {
115
- const unsubscribes = [];
116
- let messageId = 0;
117
- let connectionDead = false;
118
- let pingTimer;
119
- let writer;
120
- let onClosed;
121
- const cleanup = (reason) => {
122
- if (connectionDead) return;
123
- connectionDead = true;
124
- clearInterval(pingTimer);
125
- unsubscribes.forEach((fn) => fn());
126
- writer?.close();
127
- onClosed?.();
128
- sseLogger.info("SSE dead connection cleaned up", {
129
- events: allowedEvents,
130
- reason
131
- });
132
- };
133
- writer = createBoundedWriter(stream, maxQueue, (reason) => {
134
- sseLogger.warn("SSE connection closed", { events: allowedEvents, reason });
135
- cleanup(reason);
136
- });
137
- writer.enqueue({
138
- event: "connected",
139
- data: JSON.stringify({
140
- subscribedEvents: allowedEvents,
141
- timestamp: Date.now()
142
- })
143
- });
144
- for (const eventName of allowedEvents) {
145
- const eventDef = router.events[eventName];
146
- if (!eventDef) {
147
- continue;
148
- }
149
- const unsubscribe = eventDef.subscribe((payload) => {
150
- if (connectionDead) return;
151
- if (subject && authConfig?.filter?.[eventName]) {
152
- if (!authConfig.filter[eventName](subject, payload)) {
153
- return;
154
- }
155
- }
156
- messageId++;
157
- sseLogger.debug("SSE sending event", {
158
- event: eventName,
159
- messageId
160
- });
161
- writer.enqueue({
162
- id: String(messageId),
163
- event: eventName,
164
- data: serializeFrame(eventName, payload)
165
- });
166
- });
167
- unsubscribes.push(unsubscribe);
368
+ }, config.pingInterval);
369
+ await waitForDisconnect(c.req.raw.signal, () => connectionDead, (resolve) => {
370
+ onClosed = resolve;
371
+ });
372
+ cleanup();
373
+ }
374
+ function openSubscriptions(connection, writer) {
375
+ writer.enqueue({
376
+ event: "connected",
377
+ data: JSON.stringify({
378
+ subscribedEvents: [...connection.allowed],
379
+ deniedEvents: [...connection.denied],
380
+ timestamp: Date.now()
381
+ })
382
+ });
383
+ for (const eventName of connection.allowed) {
384
+ connection.unsubscribes.set(eventName, connection.subscribe(eventName));
385
+ }
386
+ sseLogger.info("SSE connection established", {
387
+ events: [...connection.allowed],
388
+ deniedEvents: [...connection.denied],
389
+ subscriptionCount: connection.unsubscribes.size
390
+ });
391
+ }
392
+ async function waitForDisconnect(abortSignal, isDead, onServerClose) {
393
+ if (abortSignal.aborted || isDead()) {
394
+ return;
395
+ }
396
+ await new Promise((resolve) => {
397
+ const onAbort = () => resolve();
398
+ abortSignal.addEventListener("abort", onAbort, { once: true });
399
+ onServerClose(() => {
400
+ abortSignal.removeEventListener("abort", onAbort);
401
+ resolve();
402
+ });
403
+ });
404
+ }
405
+ function createEventSubscriber(ctx) {
406
+ let messageId = 0;
407
+ return (eventName) => {
408
+ const eventDef = ctx.router.events[eventName];
409
+ let active = true;
410
+ const unsubscribe = eventDef.subscribe((payload) => {
411
+ if (!active || ctx.isDead() || !passesFrameFilters(eventName, eventDef, payload, ctx)) {
412
+ return;
168
413
  }
169
- sseLogger.info("SSE connection established", {
170
- events: allowedEvents,
171
- subscriptionCount: unsubscribes.length
414
+ messageId++;
415
+ sseLogger.debug("SSE sending event", {
416
+ event: eventName,
417
+ messageId
172
418
  });
173
- pingTimer = setInterval(() => {
174
- if (connectionDead) return;
175
- writer.enqueue({
176
- event: "ping",
177
- data: JSON.stringify({ timestamp: Date.now() })
178
- });
179
- }, pingInterval);
180
- const abortSignal = c.req.raw.signal;
181
- if (!abortSignal.aborted && !connectionDead) {
182
- await new Promise((resolve) => {
183
- const onAbort = () => resolve();
184
- abortSignal.addEventListener("abort", onAbort, { once: true });
185
- onClosed = () => {
186
- abortSignal.removeEventListener("abort", onAbort);
187
- resolve();
188
- };
189
- });
190
- }
191
- cleanup();
192
- }, async (err) => {
193
- sseLogger.error("SSE stream error", {
194
- error: err.message
419
+ ctx.writer.enqueue({
420
+ id: String(messageId),
421
+ event: eventName,
422
+ data: serializeFrame(eventName, payload)
195
423
  });
196
424
  });
425
+ return () => {
426
+ active = false;
427
+ unsubscribe();
428
+ };
197
429
  };
198
430
  }
431
+ function passesFrameFilters(eventName, eventDef, payload, ctx) {
432
+ const globalFilter = ctx.authConfig?.filter?.[eventName];
433
+ if (ctx.subject && globalFilter && !globalFilter(ctx.subject, payload)) {
434
+ return false;
435
+ }
436
+ if (!eventDef._filter) {
437
+ return true;
438
+ }
439
+ try {
440
+ return eventDef._filter(payload, { subject: ctx.subject, request: ctx.request }) === true;
441
+ } catch {
442
+ sseLogger.warn("SSE event filter threw \u2014 frame dropped", { event: eventName, subject: ctx.subject });
443
+ return false;
444
+ }
445
+ }
199
446
  async function authenticateToken(c, tokenManager) {
200
447
  if (!tokenManager) {
201
448
  return void 0;
@@ -211,7 +458,7 @@ function parseRequestedEvents(c) {
211
458
  if (!eventsParam) {
212
459
  return null;
213
460
  }
214
- return eventsParam.split(",").map((e) => e.trim());
461
+ return [...new Set(eventsParam.split(",").map((e) => e.trim()))];
215
462
  }
216
463
  async function authorizeEvents(subject, requestedEvents, authConfig) {
217
464
  if (!subject || !authConfig?.authorize) {