@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.
@@ -468,6 +468,114 @@ function createBoundedWriter(stream, maxQueue, onClose) {
468
468
  }
469
469
  };
470
470
  }
471
+ var registryLogger = logger.child("@spfn/core:sse");
472
+ var SUBSCRIPTION_GRANTED = "subscription.granted";
473
+ var SUBSCRIPTION_REVOKED = "subscription.revoked";
474
+ function createConnectionRegistry() {
475
+ const bySubject = /* @__PURE__ */ new Map();
476
+ const pendingBySubject = /* @__PURE__ */ new Map();
477
+ const beginAdmission = (subject, signal) => {
478
+ const changes = /* @__PURE__ */ new Map();
479
+ addToSet(pendingBySubject, subject, changes);
480
+ const end = endOnce(signal, () => removeFromSet(pendingBySubject, subject, changes));
481
+ return {
482
+ cancel: end,
483
+ open: (connection) => {
484
+ if (!end()) {
485
+ return false;
486
+ }
487
+ applyRecorded(connection, changes);
488
+ addToSet(bySubject, subject, connection);
489
+ return true;
490
+ }
491
+ };
492
+ };
493
+ const change = (kind, subject, eventName) => {
494
+ const pending = pendingBySubject.get(subject);
495
+ const connections = bySubject.get(subject);
496
+ pending?.forEach((changes) => changes.set(eventName, kind));
497
+ connections?.forEach((connection) => (kind === "grant" ? grantOn : revokeOn)(connection, eventName));
498
+ if (!pending && !connections) {
499
+ registryLogger.debug("SSE subscription change for a subject with no open connection ignored", {
500
+ event: eventName,
501
+ subject
502
+ });
503
+ }
504
+ };
505
+ return {
506
+ beginAdmission,
507
+ remove: (connection) => {
508
+ if (connection.subject) {
509
+ removeFromSet(bySubject, connection.subject, connection);
510
+ }
511
+ },
512
+ /** Open connections only — a pending admission is not counted. */
513
+ count: (subject) => bySubject.get(subject)?.size ?? 0,
514
+ pendingCount: (subject) => pendingBySubject.get(subject)?.size ?? 0,
515
+ grant: (subject, eventName) => change("grant", subject, eventName),
516
+ revoke: (subject, eventName) => change("revoke", subject, eventName)
517
+ };
518
+ }
519
+ function endOnce(signal, remove) {
520
+ let ended = false;
521
+ const end = () => {
522
+ if (ended) {
523
+ return false;
524
+ }
525
+ ended = true;
526
+ signal.removeEventListener("abort", end);
527
+ remove();
528
+ return true;
529
+ };
530
+ signal.addEventListener("abort", end, { once: true });
531
+ if (signal.aborted) {
532
+ end();
533
+ }
534
+ return end;
535
+ }
536
+ function addToSet(map, key, value) {
537
+ const set = map.get(key) ?? /* @__PURE__ */ new Set();
538
+ set.add(value);
539
+ map.set(key, set);
540
+ }
541
+ function removeFromSet(map, key, value) {
542
+ const set = map.get(key);
543
+ set?.delete(value);
544
+ if (set?.size === 0) {
545
+ map.delete(key);
546
+ }
547
+ }
548
+ function applyRecorded(connection, changes) {
549
+ changes.forEach((kind, eventName) => {
550
+ const [from, to] = kind === "grant" ? [connection.denied, connection.allowed] : [connection.allowed, connection.denied];
551
+ if (from.delete(eventName)) {
552
+ to.add(eventName);
553
+ }
554
+ });
555
+ }
556
+ function grantOn(connection, eventName) {
557
+ if (!connection.denied.has(eventName)) {
558
+ return;
559
+ }
560
+ connection.unsubscribes.set(eventName, connection.subscribe(eventName));
561
+ connection.denied.delete(eventName);
562
+ connection.allowed.add(eventName);
563
+ connection.notify(SUBSCRIPTION_GRANTED, eventName);
564
+ }
565
+ function revokeOn(connection, eventName) {
566
+ if (!connection.allowed.has(eventName)) {
567
+ return;
568
+ }
569
+ connection.unsubscribes.get(eventName)?.();
570
+ connection.unsubscribes.delete(eventName);
571
+ connection.allowed.delete(eventName);
572
+ connection.denied.add(eventName);
573
+ connection.notify(SUBSCRIPTION_REVOKED, eventName);
574
+ }
575
+ function unsubscribeAll(connection) {
576
+ connection.unsubscribes.forEach((unsubscribe) => unsubscribe());
577
+ connection.unsubscribes.clear();
578
+ }
471
579
 
472
580
  // src/event/sse/handler.ts
473
581
  var sseLogger = logger.child("@spfn/core:sse");
@@ -498,125 +606,264 @@ function createSSEHandler(router, config = {}, tokenManager) {
498
606
  auth: authConfig,
499
607
  maxQueue = DEFAULT_MAX_QUEUE
500
608
  } = config;
501
- return async (c) => {
502
- const subject = await authenticateToken(c, tokenManager);
503
- if (subject === false) {
504
- return c.json({ error: "Missing token parameter" }, 401);
609
+ const registry = createConnectionRegistry();
610
+ registerSubscriptionControls(router, registry);
611
+ const streamConfig = { router, authConfig, registry, pingInterval, maxQueue };
612
+ const handler = async (c) => {
613
+ const admission = await admitConnection(c, streamConfig, tokenManager);
614
+ if (admission instanceof Response) {
615
+ return admission;
505
616
  }
506
- if (subject === null) {
507
- return c.json({ error: "Invalid or expired token" }, 401);
617
+ if (c.req.raw.signal.aborted) {
618
+ admission.pending?.cancel();
619
+ return new Response(null, { status: 499 });
508
620
  }
509
- if (subject) {
510
- c.set("sseSubject", subject);
621
+ c.header("X-Accel-Buffering", "no");
622
+ return streamSSE(c, (stream) => runStream(c, stream, admission, streamConfig), async (err) => {
623
+ sseLogger.error("SSE stream error", {
624
+ error: err.message
625
+ });
626
+ });
627
+ };
628
+ return Object.assign(handler, {
629
+ /** @internal Open registered connections of a subject (tests). */
630
+ _openConnections: (subject) => registry.count(subject),
631
+ /** @internal Connects of a subject still in admission (tests). */
632
+ _pendingAdmissions: (subject) => registry.pendingCount(subject)
633
+ });
634
+ }
635
+ function registerSubscriptionControls(router, registry) {
636
+ for (const eventName of router.eventNames) {
637
+ router.events[eventName]._registerSubscriptionControl({
638
+ grant: (subject) => registry.grant(subject, eventName),
639
+ revoke: (subject) => registry.revoke(subject, eventName)
640
+ });
641
+ }
642
+ }
643
+ async function admitConnection(c, config, tokenManager) {
644
+ const { router, authConfig, registry } = config;
645
+ const subject = await authenticateToken(c, tokenManager);
646
+ if (subject === false) {
647
+ return c.json({ error: "Missing token parameter" }, 401);
648
+ }
649
+ if (subject === null) {
650
+ return c.json({ error: "Invalid or expired token" }, 401);
651
+ }
652
+ if (subject) {
653
+ c.set("sseSubject", subject);
654
+ }
655
+ const requested = parseRequestedEvents(c);
656
+ if (!requested) {
657
+ return c.json({ error: "Missing events parameter" }, 400);
658
+ }
659
+ const validEventNames = router.eventNames;
660
+ const invalidEvents = requested.filter((e) => !validEventNames.includes(e));
661
+ if (invalidEvents.length > 0) {
662
+ return c.json({
663
+ error: "Invalid event names",
664
+ invalidEvents,
665
+ validEvents: validEventNames
666
+ }, 400);
667
+ }
668
+ return whilePending(
669
+ subject ? registry.beginAdmission(subject, c.req.raw.signal) : void 0,
670
+ () => authorizeConnection(c, router, authConfig, subject, requested)
671
+ );
672
+ }
673
+ async function whilePending(pending, check) {
674
+ let outcome;
675
+ try {
676
+ outcome = await check();
677
+ return outcome instanceof Response ? outcome : { ...outcome, pending };
678
+ } finally {
679
+ if (!outcome || outcome instanceof Response) {
680
+ pending?.cancel();
511
681
  }
512
- const requestedEvents = parseRequestedEvents(c);
513
- if (!requestedEvents) {
514
- return c.json({ error: "Missing events parameter" }, 400);
682
+ }
683
+ }
684
+ async function authorizeConnection(c, router, authConfig, subject, requested) {
685
+ const authorized = await authorizeEvents(subject, requested, authConfig);
686
+ if (authorized === null) {
687
+ return c.json({ error: "Not authorized for any requested events" }, 403);
688
+ }
689
+ const request = { query: c.req.query(), headers: c.req.header() };
690
+ const resolved = await resolveConnectionPrincipal(subject, request, authConfig);
691
+ if (!resolved) {
692
+ return c.json({ error: "Principal could not be resolved" }, 403);
693
+ }
694
+ const allowed = subject ? await checkCanSubscribe(router, authorized, { subject, principal: resolved.principal, request }) : authorized;
695
+ const denied = requested.filter((e) => !allowed.includes(e));
696
+ sseLogger.debug("SSE connection requested", {
697
+ events: allowed,
698
+ deniedEvents: denied,
699
+ subject: subject || void 0,
700
+ clientIp: c.req.header("x-forwarded-for") || c.req.header("x-real-ip")
701
+ });
702
+ return { subject, requested, allowed, denied, request };
703
+ }
704
+ async function resolveConnectionPrincipal(subject, request, authConfig) {
705
+ if (!subject || !authConfig?.resolvePrincipal) {
706
+ return { principal: void 0 };
707
+ }
708
+ try {
709
+ return { principal: await authConfig.resolvePrincipal(subject, request) };
710
+ } catch {
711
+ sseLogger.warn("SSE principal could not be resolved \u2014 connection refused", { subject });
712
+ return null;
713
+ }
714
+ }
715
+ async function checkCanSubscribe(router, events, ctx) {
716
+ const verdicts = await Promise.all(events.map((eventName) => askCanSubscribe(eventName, router.events[eventName], ctx)));
717
+ return events.filter((_, i) => verdicts[i]);
718
+ }
719
+ async function askCanSubscribe(eventName, eventDef, ctx) {
720
+ if (!eventDef) {
721
+ return false;
722
+ }
723
+ if (!eventDef._canSubscribe) {
724
+ return true;
725
+ }
726
+ try {
727
+ return await eventDef._canSubscribe(ctx) === true;
728
+ } catch {
729
+ sseLogger.warn("SSE canSubscribe threw \u2014 event denied on this connection", {
730
+ event: eventName,
731
+ subject: ctx.subject
732
+ });
733
+ return false;
734
+ }
735
+ }
736
+ async function runStream(c, stream, admission, config) {
737
+ const { allowed, denied, subject, request } = admission;
738
+ let connectionDead = false;
739
+ let pingTimer;
740
+ let onClosed;
741
+ const cleanup = (reason) => {
742
+ if (connectionDead) return;
743
+ connectionDead = true;
744
+ clearInterval(pingTimer);
745
+ unsubscribeAll(connection);
746
+ config.registry.remove(connection);
747
+ writer.close();
748
+ onClosed?.();
749
+ sseLogger.info("SSE dead connection cleaned up", {
750
+ events: [...connection.allowed],
751
+ reason
752
+ });
753
+ };
754
+ const writer = createBoundedWriter(stream, config.maxQueue, (reason) => {
755
+ sseLogger.warn("SSE connection closed", { events: [...connection.allowed], reason });
756
+ cleanup(reason);
757
+ });
758
+ const connection = {
759
+ subject,
760
+ requested: admission.requested,
761
+ allowed: new Set(allowed),
762
+ denied: new Set(denied),
763
+ unsubscribes: /* @__PURE__ */ new Map(),
764
+ request,
765
+ subscribe: createEventSubscriber({
766
+ router: config.router,
767
+ authConfig: config.authConfig,
768
+ subject,
769
+ request,
770
+ writer,
771
+ isDead: () => connectionDead
772
+ }),
773
+ notify: (frame, eventName) => {
774
+ if (connectionDead) return;
775
+ writer.enqueue({ event: frame, data: JSON.stringify({ event: eventName }) });
515
776
  }
516
- const validEventNames = router.eventNames;
517
- const invalidEvents = requestedEvents.filter((e) => !validEventNames.includes(e));
518
- if (invalidEvents.length > 0) {
519
- return c.json({
520
- error: "Invalid event names",
521
- invalidEvents,
522
- validEvents: validEventNames
523
- }, 400);
524
- }
525
- const allowedEvents = await authorizeEvents(subject, requestedEvents, authConfig);
526
- if (allowedEvents === null) {
527
- return c.json({ error: "Not authorized for any requested events" }, 403);
528
- }
529
- sseLogger.debug("SSE connection requested", {
530
- events: allowedEvents,
531
- subject: subject || void 0,
532
- clientIp: c.req.header("x-forwarded-for") || c.req.header("x-real-ip")
777
+ };
778
+ if (admission.pending?.open(connection) === false) {
779
+ cleanup("aborted during admission");
780
+ return;
781
+ }
782
+ openSubscriptions(connection, writer);
783
+ pingTimer = setInterval(() => {
784
+ if (connectionDead) return;
785
+ writer.enqueue({
786
+ event: "ping",
787
+ data: JSON.stringify({ timestamp: Date.now() })
533
788
  });
534
- c.header("X-Accel-Buffering", "no");
535
- return streamSSE(c, async (stream) => {
536
- const unsubscribes = [];
537
- let messageId = 0;
538
- let connectionDead = false;
539
- let pingTimer;
540
- let writer;
541
- let onClosed;
542
- const cleanup = (reason) => {
543
- if (connectionDead) return;
544
- connectionDead = true;
545
- clearInterval(pingTimer);
546
- unsubscribes.forEach((fn) => fn());
547
- writer?.close();
548
- onClosed?.();
549
- sseLogger.info("SSE dead connection cleaned up", {
550
- events: allowedEvents,
551
- reason
552
- });
553
- };
554
- writer = createBoundedWriter(stream, maxQueue, (reason) => {
555
- sseLogger.warn("SSE connection closed", { events: allowedEvents, reason });
556
- cleanup(reason);
557
- });
558
- writer.enqueue({
559
- event: "connected",
560
- data: JSON.stringify({
561
- subscribedEvents: allowedEvents,
562
- timestamp: Date.now()
563
- })
564
- });
565
- for (const eventName of allowedEvents) {
566
- const eventDef = router.events[eventName];
567
- if (!eventDef) {
568
- continue;
569
- }
570
- const unsubscribe = eventDef.subscribe((payload) => {
571
- if (connectionDead) return;
572
- if (subject && authConfig?.filter?.[eventName]) {
573
- if (!authConfig.filter[eventName](subject, payload)) {
574
- return;
575
- }
576
- }
577
- messageId++;
578
- sseLogger.debug("SSE sending event", {
579
- event: eventName,
580
- messageId
581
- });
582
- writer.enqueue({
583
- id: String(messageId),
584
- event: eventName,
585
- data: serializeFrame(eventName, payload)
586
- });
587
- });
588
- unsubscribes.push(unsubscribe);
789
+ }, config.pingInterval);
790
+ await waitForDisconnect(c.req.raw.signal, () => connectionDead, (resolve2) => {
791
+ onClosed = resolve2;
792
+ });
793
+ cleanup();
794
+ }
795
+ function openSubscriptions(connection, writer) {
796
+ writer.enqueue({
797
+ event: "connected",
798
+ data: JSON.stringify({
799
+ subscribedEvents: [...connection.allowed],
800
+ deniedEvents: [...connection.denied],
801
+ timestamp: Date.now()
802
+ })
803
+ });
804
+ for (const eventName of connection.allowed) {
805
+ connection.unsubscribes.set(eventName, connection.subscribe(eventName));
806
+ }
807
+ sseLogger.info("SSE connection established", {
808
+ events: [...connection.allowed],
809
+ deniedEvents: [...connection.denied],
810
+ subscriptionCount: connection.unsubscribes.size
811
+ });
812
+ }
813
+ async function waitForDisconnect(abortSignal, isDead, onServerClose) {
814
+ if (abortSignal.aborted || isDead()) {
815
+ return;
816
+ }
817
+ await new Promise((resolve2) => {
818
+ const onAbort = () => resolve2();
819
+ abortSignal.addEventListener("abort", onAbort, { once: true });
820
+ onServerClose(() => {
821
+ abortSignal.removeEventListener("abort", onAbort);
822
+ resolve2();
823
+ });
824
+ });
825
+ }
826
+ function createEventSubscriber(ctx) {
827
+ let messageId = 0;
828
+ return (eventName) => {
829
+ const eventDef = ctx.router.events[eventName];
830
+ let active = true;
831
+ const unsubscribe = eventDef.subscribe((payload) => {
832
+ if (!active || ctx.isDead() || !passesFrameFilters(eventName, eventDef, payload, ctx)) {
833
+ return;
589
834
  }
590
- sseLogger.info("SSE connection established", {
591
- events: allowedEvents,
592
- subscriptionCount: unsubscribes.length
835
+ messageId++;
836
+ sseLogger.debug("SSE sending event", {
837
+ event: eventName,
838
+ messageId
593
839
  });
594
- pingTimer = setInterval(() => {
595
- if (connectionDead) return;
596
- writer.enqueue({
597
- event: "ping",
598
- data: JSON.stringify({ timestamp: Date.now() })
599
- });
600
- }, pingInterval);
601
- const abortSignal = c.req.raw.signal;
602
- if (!abortSignal.aborted && !connectionDead) {
603
- await new Promise((resolve2) => {
604
- const onAbort = () => resolve2();
605
- abortSignal.addEventListener("abort", onAbort, { once: true });
606
- onClosed = () => {
607
- abortSignal.removeEventListener("abort", onAbort);
608
- resolve2();
609
- };
610
- });
611
- }
612
- cleanup();
613
- }, async (err) => {
614
- sseLogger.error("SSE stream error", {
615
- error: err.message
840
+ ctx.writer.enqueue({
841
+ id: String(messageId),
842
+ event: eventName,
843
+ data: serializeFrame(eventName, payload)
616
844
  });
617
845
  });
846
+ return () => {
847
+ active = false;
848
+ unsubscribe();
849
+ };
618
850
  };
619
851
  }
852
+ function passesFrameFilters(eventName, eventDef, payload, ctx) {
853
+ const globalFilter = ctx.authConfig?.filter?.[eventName];
854
+ if (ctx.subject && globalFilter && !globalFilter(ctx.subject, payload)) {
855
+ return false;
856
+ }
857
+ if (!eventDef._filter) {
858
+ return true;
859
+ }
860
+ try {
861
+ return eventDef._filter(payload, { subject: ctx.subject, request: ctx.request }) === true;
862
+ } catch {
863
+ sseLogger.warn("SSE event filter threw \u2014 frame dropped", { event: eventName, subject: ctx.subject });
864
+ return false;
865
+ }
866
+ }
620
867
  async function authenticateToken(c, tokenManager) {
621
868
  if (!tokenManager) {
622
869
  return void 0;
@@ -632,7 +879,7 @@ function parseRequestedEvents(c) {
632
879
  if (!eventsParam) {
633
880
  return null;
634
881
  }
635
- return eventsParam.split(",").map((e) => e.trim());
882
+ return [...new Set(eventsParam.split(",").map((e) => e.trim()))];
636
883
  }
637
884
  async function authorizeEvents(subject, requestedEvents, authConfig) {
638
885
  if (!subject || !authConfig?.authorize) {