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

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