opinionated-machine 5.1.0 → 6.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.
Files changed (55) hide show
  1. package/README.md +966 -2
  2. package/dist/index.d.ts +3 -2
  3. package/dist/index.js +5 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/lib/AbstractController.d.ts +3 -3
  6. package/dist/lib/AbstractController.js.map +1 -1
  7. package/dist/lib/AbstractModule.d.ts +23 -1
  8. package/dist/lib/AbstractModule.js +25 -0
  9. package/dist/lib/AbstractModule.js.map +1 -1
  10. package/dist/lib/DIContext.d.ts +35 -0
  11. package/dist/lib/DIContext.js +108 -1
  12. package/dist/lib/DIContext.js.map +1 -1
  13. package/dist/lib/resolverFunctions.d.ts +34 -0
  14. package/dist/lib/resolverFunctions.js +47 -0
  15. package/dist/lib/resolverFunctions.js.map +1 -1
  16. package/dist/lib/sse/AbstractSSEController.d.ts +163 -0
  17. package/dist/lib/sse/AbstractSSEController.js +228 -0
  18. package/dist/lib/sse/AbstractSSEController.js.map +1 -0
  19. package/dist/lib/sse/SSEConnectionSpy.d.ts +55 -0
  20. package/dist/lib/sse/SSEConnectionSpy.js +136 -0
  21. package/dist/lib/sse/SSEConnectionSpy.js.map +1 -0
  22. package/dist/lib/sse/index.d.ts +5 -0
  23. package/dist/lib/sse/index.js +6 -0
  24. package/dist/lib/sse/index.js.map +1 -0
  25. package/dist/lib/sse/sseContracts.d.ts +132 -0
  26. package/dist/lib/sse/sseContracts.js +102 -0
  27. package/dist/lib/sse/sseContracts.js.map +1 -0
  28. package/dist/lib/sse/sseParser.d.ts +167 -0
  29. package/dist/lib/sse/sseParser.js +225 -0
  30. package/dist/lib/sse/sseParser.js.map +1 -0
  31. package/dist/lib/sse/sseRouteBuilder.d.ts +47 -0
  32. package/dist/lib/sse/sseRouteBuilder.js +114 -0
  33. package/dist/lib/sse/sseRouteBuilder.js.map +1 -0
  34. package/dist/lib/sse/sseTypes.d.ts +164 -0
  35. package/dist/lib/sse/sseTypes.js +2 -0
  36. package/dist/lib/sse/sseTypes.js.map +1 -0
  37. package/dist/lib/testing/index.d.ts +5 -0
  38. package/dist/lib/testing/index.js +5 -0
  39. package/dist/lib/testing/index.js.map +1 -0
  40. package/dist/lib/testing/sseHttpClient.d.ts +203 -0
  41. package/dist/lib/testing/sseHttpClient.js +262 -0
  42. package/dist/lib/testing/sseHttpClient.js.map +1 -0
  43. package/dist/lib/testing/sseInjectClient.d.ts +173 -0
  44. package/dist/lib/testing/sseInjectClient.js +234 -0
  45. package/dist/lib/testing/sseInjectClient.js.map +1 -0
  46. package/dist/lib/testing/sseInjectHelpers.d.ts +59 -0
  47. package/dist/lib/testing/sseInjectHelpers.js +117 -0
  48. package/dist/lib/testing/sseInjectHelpers.js.map +1 -0
  49. package/dist/lib/testing/sseTestServer.d.ts +93 -0
  50. package/dist/lib/testing/sseTestServer.js +108 -0
  51. package/dist/lib/testing/sseTestServer.js.map +1 -0
  52. package/dist/lib/testing/sseTestTypes.d.ts +106 -0
  53. package/dist/lib/testing/sseTestTypes.js +2 -0
  54. package/dist/lib/testing/sseTestTypes.js.map +1 -0
  55. package/package.json +13 -11
package/README.md CHANGED
@@ -1,6 +1,59 @@
1
1
  # opinionated-machine
2
2
  Very opinionated DI framework for fastify, built on top of awilix
3
3
 
4
+ ## Table of Contents
5
+
6
+ - [Basic usage](#basic-usage)
7
+ - [Defining controllers](#defining-controllers)
8
+ - [Putting it all together](#putting-it-all-together)
9
+ - [Resolver Functions](#resolver-functions)
10
+ - [Basic Resolvers](#basic-resolvers)
11
+ - [`asSingletonClass`](#assingletonclasstype-opts)
12
+ - [`asSingletonFunction`](#assingletonfunctionfn-opts)
13
+ - [`asClassWithConfig`](#asclasswithconfigtype-config-opts)
14
+ - [Domain Layer Resolvers](#domain-layer-resolvers)
15
+ - [`asServiceClass`](#asserviceclasstype-opts)
16
+ - [`asUseCaseClass`](#asusecaseclasstype-opts)
17
+ - [`asRepositoryClass`](#asrepositoryclasstype-opts)
18
+ - [`asControllerClass`](#ascontrollerclasstype-opts)
19
+ - [`asSSEControllerClass`](#asssecontrollerclasstype-sseoptions-opts)
20
+ - [Message Queue Resolvers](#message-queue-resolvers)
21
+ - [`asMessageQueueHandlerClass`](#asmessagequeuehandlerclasstype-mqoptions-opts)
22
+ - [Background Job Resolvers](#background-job-resolvers)
23
+ - [`asEnqueuedJobWorkerClass`](#asenqueuedjobworkerclasstype-workeroptions-opts)
24
+ - [`asPgBossProcessorClass`](#aspgbossprocessorclasstype-processoroptions-opts)
25
+ - [`asPeriodicJobClass`](#asperiodicjobclasstype-workeroptions-opts)
26
+ - [`asJobQueueClass`](#asjobqueueclasstype-queueoptions-opts)
27
+ - [`asEnqueuedJobQueueManagerFunction`](#asenqueuedjobqueuemanagerfunctionfn-dioptions-opts)
28
+ - [Server-Sent Events (SSE)](#server-sent-events-sse)
29
+ - [Prerequisites](#prerequisites)
30
+ - [Defining SSE Contracts](#defining-sse-contracts)
31
+ - [Creating SSE Controllers](#creating-sse-controllers)
32
+ - [Type-Safe SSE Handlers with buildSSEHandler](#type-safe-sse-handlers-with-buildssehandler)
33
+ - [SSE Controllers Without Dependencies](#sse-controllers-without-dependencies)
34
+ - [Registering SSE Controllers](#registering-sse-controllers)
35
+ - [Registering SSE Routes](#registering-sse-routes)
36
+ - [Broadcasting Events](#broadcasting-events)
37
+ - [Controller-Level Hooks](#controller-level-hooks)
38
+ - [Route-Level Options](#route-level-options)
39
+ - [Graceful Shutdown](#graceful-shutdown)
40
+ - [Error Handling](#error-handling)
41
+ - [Long-lived Connections vs Request-Response Streaming](#long-lived-connections-vs-request-response-streaming)
42
+ - [SSE Parsing Utilities](#sse-parsing-utilities)
43
+ - [parseSSEEvents](#parsesseevents)
44
+ - [parseSSEBuffer](#parsessebuffer)
45
+ - [ParsedSSEEvent Type](#parsedsseevent-type)
46
+ - [Testing SSE Controllers](#testing-sse-controllers)
47
+ - [SSEConnectionSpy API](#sseconnectionspy-api)
48
+ - [Connection Monitoring](#connection-monitoring)
49
+ - [SSE Test Utilities](#sse-test-utilities)
50
+ - [Quick Reference](#quick-reference)
51
+ - [Inject vs HTTP Comparison](#inject-vs-http-comparison)
52
+ - [SSETestServer](#ssetestserver)
53
+ - [SSEHttpClient](#ssehttpclient)
54
+ - [SSEInjectClient](#sseinjectclient)
55
+ - [Contract-Aware Inject Helpers](#contract-aware-inject-helpers)
56
+
4
57
  ## Basic usage
5
58
 
6
59
  Define a module, or several modules, that will be used for resolving dependency graphs, using awilix:
@@ -55,7 +108,8 @@ export class MyModule extends AbstractModule<ModuleDependencies, ExternalDepende
55
108
  }
56
109
 
57
110
  // controllers will be automatically registered on fastify app
58
- resolveControllers() {
111
+ // both REST and SSE controllers go here - SSE controllers are auto-detected
112
+ resolveControllers(diOptions: DependencyInjectionOptions) {
59
113
  return {
60
114
  controller: asControllerClass(MyController),
61
115
  }
@@ -183,6 +237,23 @@ Basic singleton function resolver. Use when you need to resolve a dependency usi
183
237
  config: asSingletonFunction(() => loadConfig())
184
238
  ```
185
239
 
240
+ #### `asClassWithConfig(Type, config, opts?)`
241
+ Register a class with an additional config parameter passed to the constructor. Uses `asFunction` wrapper internally to pass the config as a second parameter. Requires PROXY injection mode.
242
+
243
+ ```ts
244
+ myService: asClassWithConfig(MyService, { enableFeature: true })
245
+ ```
246
+
247
+ The class constructor receives dependencies as the first parameter and config as the second:
248
+
249
+ ```ts
250
+ class MyService {
251
+ constructor(deps: Dependencies, config: { enableFeature: boolean }) {
252
+ // ...
253
+ }
254
+ }
255
+ ```
256
+
186
257
  ### Domain Layer Resolvers
187
258
 
188
259
  #### `asServiceClass(Type, opts?)`
@@ -207,12 +278,25 @@ userRepository: asRepositoryClass(UserRepository)
207
278
  ```
208
279
 
209
280
  #### `asControllerClass(Type, opts?)`
210
- For controller classes. Marks the dependency as **private**. Use in `resolveControllers()`.
281
+ For REST controller classes. Marks the dependency as **private**. Use in `resolveControllers()`.
211
282
 
212
283
  ```ts
213
284
  userController: asControllerClass(UserController)
214
285
  ```
215
286
 
287
+ #### `asSSEControllerClass(Type, sseOptions?, opts?)`
288
+ For SSE controller classes. Marks the dependency as **private** with `isSSEController: true` for auto-detection. Automatically configures `closeAllConnections` as the async dispose method for graceful shutdown. When `sseOptions.diOptions.isTestMode` is true, enables the connection spy for testing. Use in `resolveControllers()` alongside REST controllers.
289
+
290
+ ```ts
291
+ // In resolveControllers()
292
+ resolveControllers(diOptions: DependencyInjectionOptions) {
293
+ return {
294
+ userController: asControllerClass(UserController),
295
+ notificationsSSEController: asSSEControllerClass(NotificationsSSEController, { diOptions }),
296
+ }
297
+ }
298
+ ```
299
+
216
300
  ### Message Queue Resolvers
217
301
 
218
302
  #### `asMessageQueueHandlerClass(Type, mqOptions, opts?)`
@@ -276,3 +360,883 @@ jobQueueManager: asEnqueuedJobQueueManagerFunction(
276
360
  )
277
361
  ```
278
362
 
363
+ ## Server-Sent Events (SSE)
364
+
365
+ The library provides first-class support for Server-Sent Events using [@fastify/sse](https://github.com/fastify/sse). SSE enables real-time, unidirectional streaming from server to client - perfect for notifications, live updates, and streaming responses (like AI chat completions).
366
+
367
+ ### Prerequisites
368
+
369
+ Register the `@fastify/sse` plugin before using SSE controllers:
370
+
371
+ ```ts
372
+ import FastifySSEPlugin from '@fastify/sse'
373
+
374
+ const app = fastify()
375
+ await app.register(FastifySSEPlugin)
376
+ ```
377
+
378
+ ### Defining SSE Contracts
379
+
380
+ Use `buildSSERoute` for GET-based SSE streams or `buildPayloadSSERoute` for POST/PUT/PATCH streams:
381
+
382
+ ```ts
383
+ import { z } from 'zod'
384
+ import { buildSSERoute, buildPayloadSSERoute } from 'opinionated-machine'
385
+
386
+ // GET-based SSE stream (e.g., notifications)
387
+ export const notificationsContract = buildSSERoute({
388
+ path: '/api/notifications/stream',
389
+ params: z.object({}),
390
+ query: z.object({ userId: z.string().optional() }),
391
+ requestHeaders: z.object({}),
392
+ events: {
393
+ notification: z.object({
394
+ id: z.string(),
395
+ message: z.string(),
396
+ }),
397
+ },
398
+ })
399
+
400
+ // POST-based SSE stream (e.g., AI chat completions)
401
+ export const chatCompletionContract = buildPayloadSSERoute({
402
+ method: 'POST',
403
+ path: '/api/chat/completions',
404
+ params: z.object({}),
405
+ query: z.object({}),
406
+ requestHeaders: z.object({}),
407
+ body: z.object({
408
+ message: z.string(),
409
+ stream: z.literal(true),
410
+ }),
411
+ events: {
412
+ chunk: z.object({ content: z.string() }),
413
+ done: z.object({ totalTokens: z.number() }),
414
+ },
415
+ })
416
+ ```
417
+
418
+ ### Creating SSE Controllers
419
+
420
+ SSE controllers extend `AbstractSSEController` and must implement a two-parameter constructor. Use `buildSSEHandler` for automatic type inference of request parameters:
421
+
422
+ ```ts
423
+ import {
424
+ AbstractSSEController,
425
+ buildSSEHandler,
426
+ type SSEControllerConfig,
427
+ type SSEConnection
428
+ } from 'opinionated-machine'
429
+
430
+ type Contracts = {
431
+ notificationsStream: typeof notificationsContract
432
+ }
433
+
434
+ type Dependencies = {
435
+ notificationService: NotificationService
436
+ }
437
+
438
+ export class NotificationsSSEController extends AbstractSSEController<Contracts> {
439
+ public static contracts = {
440
+ notificationsStream: notificationsContract,
441
+ } as const
442
+
443
+ private readonly notificationService: NotificationService
444
+
445
+ // Required: two-parameter constructor (deps object, optional SSE config)
446
+ constructor(deps: Dependencies, sseConfig?: SSEControllerConfig) {
447
+ super(deps, sseConfig)
448
+ this.notificationService = deps.notificationService
449
+ }
450
+
451
+ public buildSSERoutes() {
452
+ return {
453
+ notificationsStream: {
454
+ contract: NotificationsSSEController.contracts.notificationsStream,
455
+ handler: this.handleStream,
456
+ options: {
457
+ onConnect: (conn) => this.onConnect(conn),
458
+ onDisconnect: (conn) => this.onDisconnect(conn),
459
+ },
460
+ },
461
+ }
462
+ }
463
+
464
+ // Handler with automatic type inference from contract
465
+ private handleStream = buildSSEHandler(
466
+ notificationsContract,
467
+ async (request, connection) => {
468
+ // request.query is typed from contract: { userId?: string }
469
+ const userId = request.query.userId ?? 'anonymous'
470
+ connection.context = { userId }
471
+
472
+ // Subscribe to notifications for this user
473
+ this.notificationService.subscribe(userId, async (notification) => {
474
+ await this.sendEvent(connection.id, {
475
+ event: 'notification',
476
+ data: notification,
477
+ })
478
+ })
479
+ },
480
+ )
481
+
482
+ private onConnect = (connection: SSEConnection) => {
483
+ console.log('Client connected:', connection.id)
484
+ }
485
+
486
+ private onDisconnect = (connection: SSEConnection) => {
487
+ const userId = connection.context?.userId as string
488
+ this.notificationService.unsubscribe(userId)
489
+ console.log('Client disconnected:', connection.id)
490
+ }
491
+ }
492
+ ```
493
+
494
+ ### Type-Safe SSE Handlers with `buildSSEHandler`
495
+
496
+ For automatic type inference of request parameters (similar to `buildFastifyPayloadRoute` for regular controllers), use `buildSSEHandler`:
497
+
498
+ ```ts
499
+ import {
500
+ AbstractSSEController,
501
+ buildSSEHandler,
502
+ type SSEControllerConfig,
503
+ type SSEConnection
504
+ } from 'opinionated-machine'
505
+
506
+ class ChatSSEController extends AbstractSSEController<Contracts> {
507
+ public static contracts = {
508
+ chatCompletion: chatCompletionContract,
509
+ } as const
510
+
511
+ constructor(deps: Dependencies, sseConfig?: SSEControllerConfig) {
512
+ super(deps, sseConfig)
513
+ }
514
+
515
+ // Handler with automatic type inference from contract
516
+ private handleChatCompletion = buildSSEHandler(
517
+ chatCompletionContract,
518
+ async (request, connection) => {
519
+ // request.body is typed as { message: string; stream: true }
520
+ // request.query, request.params, request.headers all typed from contract
521
+ const words = request.body.message.split(' ')
522
+
523
+ for (const word of words) {
524
+ await this.sendEvent(connection.id, {
525
+ event: 'chunk',
526
+ data: { content: word },
527
+ })
528
+ }
529
+
530
+ // Gracefully end the stream - all sent data is flushed before connection closes
531
+ this.closeConnection(connection.id)
532
+ },
533
+ )
534
+
535
+ public buildSSERoutes() {
536
+ return {
537
+ chatCompletion: {
538
+ contract: ChatSSEController.contracts.chatCompletion,
539
+ handler: this.handleChatCompletion,
540
+ },
541
+ }
542
+ }
543
+ }
544
+ ```
545
+
546
+ You can also use `InferSSERequest<Contract>` for manual type annotation when needed:
547
+
548
+ ```ts
549
+ import { type InferSSERequest } from 'opinionated-machine'
550
+
551
+ private handleStream = async (
552
+ request: InferSSERequest<typeof chatCompletionContract>,
553
+ connection: SSEConnection,
554
+ ) => {
555
+ // request.body, request.params, etc. all typed from contract
556
+ }
557
+ ```
558
+
559
+ ### SSE Controllers Without Dependencies
560
+
561
+ For controllers without dependencies, still provide the two-parameter constructor:
562
+
563
+ ```ts
564
+ export class SimpleSSEController extends AbstractSSEController<Contracts> {
565
+ constructor(deps: object, sseConfig?: SSEControllerConfig) {
566
+ super(deps, sseConfig)
567
+ }
568
+
569
+ // ... implementation
570
+ }
571
+ ```
572
+
573
+ ### Registering SSE Controllers
574
+
575
+ Use `asSSEControllerClass` in your module's `resolveControllers` method alongside REST controllers. SSE controllers are automatically detected via the `isSSEController` flag and registered in the DI container:
576
+
577
+ ```ts
578
+ import { AbstractModule, asControllerClass, asSSEControllerClass, asServiceClass, type DependencyInjectionOptions } from 'opinionated-machine'
579
+
580
+ export class NotificationsModule extends AbstractModule<Dependencies> {
581
+ resolveDependencies() {
582
+ return {
583
+ notificationService: asServiceClass(NotificationService),
584
+ }
585
+ }
586
+
587
+ resolveControllers(diOptions: DependencyInjectionOptions) {
588
+ return {
589
+ // REST controller
590
+ usersController: asControllerClass(UsersController),
591
+ // SSE controller (automatically detected and registered for SSE routes)
592
+ notificationsSSEController: asSSEControllerClass(NotificationsSSEController, { diOptions }),
593
+ }
594
+ }
595
+ }
596
+ ```
597
+
598
+ ### Registering SSE Routes
599
+
600
+ Call `registerSSERoutes` after registering the `@fastify/sse` plugin:
601
+
602
+ ```ts
603
+ const app = fastify()
604
+ app.setValidatorCompiler(validatorCompiler)
605
+ app.setSerializerCompiler(serializerCompiler)
606
+
607
+ // Register @fastify/sse plugin first
608
+ await app.register(FastifySSEPlugin)
609
+
610
+ // Then register SSE routes
611
+ context.registerSSERoutes(app)
612
+
613
+ // Optionally with global preHandler for authentication
614
+ context.registerSSERoutes(app, {
615
+ preHandler: async (request, reply) => {
616
+ if (!request.headers.authorization) {
617
+ reply.code(401).send({ error: 'Unauthorized' })
618
+ }
619
+ },
620
+ })
621
+
622
+ await app.ready()
623
+ ```
624
+
625
+ ### Broadcasting Events
626
+
627
+ Send events to multiple connections using `broadcast()` or `broadcastIf()`:
628
+
629
+ ```ts
630
+ // Broadcast to ALL connected clients
631
+ await this.broadcast({
632
+ event: 'system',
633
+ data: { message: 'Server maintenance in 5 minutes' },
634
+ })
635
+
636
+ // Broadcast to connections matching a predicate
637
+ await this.broadcastIf(
638
+ { event: 'channel-update', data: { channelId: '123', newMessage: msg } },
639
+ (connection) => connection.context.channelId === '123',
640
+ )
641
+ ```
642
+
643
+ Both methods return the number of clients the message was successfully sent to.
644
+
645
+ ### Controller-Level Hooks
646
+
647
+ Override these optional methods on your controller for global connection handling:
648
+
649
+ ```ts
650
+ class MySSEController extends AbstractSSEController<Contracts> {
651
+ // Called AFTER connection is registered (for all routes)
652
+ protected onConnectionEstablished(connection: SSEConnection): void {
653
+ this.metrics.incrementConnections()
654
+ }
655
+
656
+ // Called BEFORE connection is unregistered (for all routes)
657
+ protected onConnectionClosed(connection: SSEConnection): void {
658
+ this.metrics.decrementConnections()
659
+ }
660
+ }
661
+ ```
662
+
663
+ ### Route-Level Options
664
+
665
+ Each route can have its own `preHandler`, lifecycle hooks, and logger:
666
+
667
+ ```ts
668
+ public buildSSERoutes() {
669
+ return {
670
+ adminStream: {
671
+ contract: AdminSSEController.contracts.adminStream,
672
+ handler: this.handleAdminStream,
673
+ options: {
674
+ // Route-specific authentication
675
+ preHandler: (request, reply) => {
676
+ if (!request.user?.isAdmin) {
677
+ reply.code(403).send({ error: 'Forbidden' })
678
+ }
679
+ },
680
+ onConnect: (conn) => console.log('Admin connected'),
681
+ onDisconnect: (conn) => console.log('Admin disconnected'),
682
+ // Handle client reconnection with Last-Event-ID
683
+ onReconnect: async (conn, lastEventId) => {
684
+ // Return events to replay, or handle manually
685
+ return this.getEventsSince(lastEventId)
686
+ },
687
+ // Optional: logger for error handling (requires @lokalise/node-core)
688
+ logger: this.logger,
689
+ },
690
+ },
691
+ }
692
+ }
693
+ ```
694
+
695
+ **Available route options:**
696
+
697
+ | Option | Description |
698
+ |--------|-------------|
699
+ | `preHandler` | Authentication/authorization hook that runs before SSE connection |
700
+ | `onConnect` | Called after client connects (SSE handshake complete) |
701
+ | `onDisconnect` | Called when client disconnects |
702
+ | `onReconnect` | Handle Last-Event-ID reconnection, return events to replay |
703
+ | `logger` | Optional `SSELogger` for error handling (compatible with pino and `@lokalise/node-core`). If not provided, errors in lifecycle hooks are silently ignored |
704
+
705
+ ### Graceful Shutdown
706
+
707
+ SSE controllers automatically close all connections during application shutdown. This is configured by `asSSEControllerClass` which sets `closeAllConnections` as the async dispose method with priority 5 (early in shutdown sequence).
708
+
709
+ ### Error Handling
710
+
711
+ When `sendEvent()` fails (e.g., client disconnected), it:
712
+ - Returns `false` to indicate failure
713
+ - Automatically removes the dead connection from tracking
714
+ - Prevents further send attempts to that connection
715
+
716
+ ```ts
717
+ const sent = await this.sendEvent(connectionId, { event: 'update', data })
718
+ if (!sent) {
719
+ // Connection was closed or failed - already removed from tracking
720
+ this.cleanup(connectionId)
721
+ }
722
+ ```
723
+
724
+ **Lifecycle hook errors** (`onConnect`, `onReconnect`, `onDisconnect`):
725
+ - All lifecycle hooks are wrapped in try/catch to prevent crashes
726
+ - If a `logger` is provided in route options, errors are logged with context
727
+ - If no logger is provided, errors are silently ignored
728
+ - The connection lifecycle continues even if a hook throws
729
+
730
+ ```ts
731
+ // Provide a logger to capture lifecycle errors
732
+ public buildSSERoutes() {
733
+ return {
734
+ stream: {
735
+ contract: streamContract,
736
+ handler: this.handleStream,
737
+ options: {
738
+ logger: this.logger, // pino-compatible logger
739
+ onConnect: (conn) => { /* may throw */ },
740
+ onDisconnect: (conn) => { /* may throw */ },
741
+ },
742
+ },
743
+ }
744
+ }
745
+ ```
746
+
747
+ ### Long-lived Connections vs Request-Response Streaming
748
+
749
+ **Long-lived connections** (notifications, live updates):
750
+ - Handler sets up subscriptions and returns
751
+ - Connection stays open until client disconnects
752
+ - Events sent via `sendEvent()` from external triggers
753
+
754
+ ```ts
755
+ private handleStream = buildSSEHandler(streamContract, async (request, connection) => {
756
+ // Set up subscription
757
+ this.service.subscribe(connection.id, (data) => {
758
+ this.sendEvent(connection.id, { event: 'update', data })
759
+ })
760
+ // Handler returns, connection stays open
761
+ })
762
+ ```
763
+
764
+ **Request-response streaming** (AI completions):
765
+ - Handler sends all events and closes connection
766
+ - Similar to regular HTTP but with streaming body
767
+
768
+ ```ts
769
+ private handleChatCompletion = buildSSEHandler(chatCompletionContract, async (request, connection) => {
770
+ // request.body is typed from contract
771
+ const words = request.body.message.split(' ')
772
+
773
+ for (const word of words) {
774
+ await this.sendEvent(connection.id, {
775
+ event: 'chunk',
776
+ data: { content: word },
777
+ })
778
+ }
779
+
780
+ await this.sendEvent(connection.id, {
781
+ event: 'done',
782
+ data: { totalTokens: words.length },
783
+ })
784
+
785
+ // Gracefully end the stream - all sent data is flushed before connection closes
786
+ this.closeConnection(connection.id)
787
+ })
788
+ ```
789
+
790
+ ### SSE Parsing Utilities
791
+
792
+ The library provides production-ready utilities for parsing SSE (Server-Sent Events) streams:
793
+
794
+ | Function | Use Case |
795
+ |----------|----------|
796
+ | `parseSSEEvents` | **Testing & complete responses** - when you have the full response body |
797
+ | `parseSSEBuffer` | **Production streaming** - when data arrives incrementally in chunks |
798
+
799
+ #### parseSSEEvents
800
+
801
+ Parse a complete SSE response body into an array of events.
802
+
803
+ **When to use:** Testing with Fastify's `inject()`, or when the full response is available (e.g., request-response style SSE like OpenAI completions):
804
+
805
+ ```ts
806
+ import { parseSSEEvents, type ParsedSSEEvent } from 'opinionated-machine'
807
+
808
+ const responseBody = `event: notification
809
+ data: {"id":"1","message":"Hello"}
810
+
811
+ event: notification
812
+ data: {"id":"2","message":"World"}
813
+
814
+ `
815
+
816
+ const events: ParsedSSEEvent[] = parseSSEEvents(responseBody)
817
+ // Result:
818
+ // [
819
+ // { event: 'notification', data: '{"id":"1","message":"Hello"}' },
820
+ // { event: 'notification', data: '{"id":"2","message":"World"}' }
821
+ // ]
822
+
823
+ // Access parsed data
824
+ const notifications = events.map(e => JSON.parse(e.data))
825
+ ```
826
+
827
+ #### parseSSEBuffer
828
+
829
+ Parse a streaming SSE buffer, handling incomplete events at chunk boundaries.
830
+
831
+ **When to use:** Production clients consuming real-time SSE streams (notifications, live feeds, chat) where events arrive incrementally:
832
+
833
+ ```ts
834
+ import { parseSSEBuffer, type ParseSSEBufferResult } from 'opinionated-machine'
835
+
836
+ let buffer = ''
837
+
838
+ // As chunks arrive from a stream...
839
+ for await (const chunk of stream) {
840
+ buffer += chunk
841
+ const result: ParseSSEBufferResult = parseSSEBuffer(buffer)
842
+
843
+ // Process complete events
844
+ for (const event of result.events) {
845
+ console.log('Received:', event.event, event.data)
846
+ }
847
+
848
+ // Keep incomplete data for next chunk
849
+ buffer = result.remaining
850
+ }
851
+ ```
852
+
853
+ **Production example with fetch:**
854
+
855
+ ```ts
856
+ const response = await fetch(url)
857
+ const reader = response.body!.getReader()
858
+ const decoder = new TextDecoder()
859
+ let buffer = ''
860
+
861
+ while (true) {
862
+ const { done, value } = await reader.read()
863
+ if (done) break
864
+
865
+ buffer += decoder.decode(value, { stream: true })
866
+ const { events, remaining } = parseSSEBuffer(buffer)
867
+ buffer = remaining
868
+
869
+ for (const event of events) {
870
+ console.log('Received:', event.event, JSON.parse(event.data))
871
+ }
872
+ }
873
+ ```
874
+
875
+ #### ParsedSSEEvent Type
876
+
877
+ Both functions return events with this structure:
878
+
879
+ ```ts
880
+ type ParsedSSEEvent = {
881
+ id?: string // Event ID (from "id:" field)
882
+ event?: string // Event type (from "event:" field)
883
+ data: string // Event data (from "data:" field, always present)
884
+ retry?: number // Reconnection interval (from "retry:" field)
885
+ }
886
+ ```
887
+
888
+ ### Testing SSE Controllers
889
+
890
+ Enable the connection spy for testing by passing `isTestMode: true` in diOptions:
891
+
892
+ ```ts
893
+ import { createContainer } from 'awilix'
894
+ import { DIContext, SSETestServer, SSEHttpClient } from 'opinionated-machine'
895
+
896
+ describe('NotificationsSSEController', () => {
897
+ let server: SSETestServer
898
+ let controller: NotificationsSSEController
899
+
900
+ beforeEach(async () => {
901
+ // Create test server with isTestMode enabled
902
+ server = await SSETestServer.create(
903
+ async (app) => {
904
+ // Register your SSE routes here
905
+ },
906
+ {
907
+ setup: async () => {
908
+ // Set up DI container and resources
909
+ return { context }
910
+ },
911
+ }
912
+ )
913
+
914
+ controller = server.resources.context.diContainer.cradle.notificationsSSEController
915
+ })
916
+
917
+ afterEach(async () => {
918
+ await server.resources.context.destroy()
919
+ await server.close()
920
+ })
921
+
922
+ it('receives notifications over SSE', async () => {
923
+ // Connect with awaitServerConnection to eliminate race condition
924
+ const { client, serverConnection } = await SSEHttpClient.connect(
925
+ server.baseUrl,
926
+ '/api/notifications/stream',
927
+ {
928
+ query: { userId: 'test-user' },
929
+ awaitServerConnection: { controller },
930
+ },
931
+ )
932
+
933
+ expect(client.response.ok).toBe(true)
934
+
935
+ // Start collecting events
936
+ const eventsPromise = client.collectEvents(2)
937
+
938
+ // Send events from server (serverConnection is ready immediately)
939
+ await controller.sendEvent(serverConnection.id, {
940
+ event: 'notification',
941
+ data: { id: '1', message: 'Hello!' },
942
+ })
943
+
944
+ await controller.sendEvent(serverConnection.id, {
945
+ event: 'notification',
946
+ data: { id: '2', message: 'World!' },
947
+ })
948
+
949
+ // Wait for events
950
+ const events = await eventsPromise
951
+
952
+ expect(events).toHaveLength(2)
953
+ expect(JSON.parse(events[0].data)).toEqual({ id: '1', message: 'Hello!' })
954
+ expect(JSON.parse(events[1].data)).toEqual({ id: '2', message: 'World!' })
955
+
956
+ // Clean up
957
+ client.close()
958
+ })
959
+ })
960
+ ```
961
+
962
+ ### SSEConnectionSpy API
963
+
964
+ The `connectionSpy` is available when `isTestMode: true` is passed to `asSSEControllerClass`:
965
+
966
+ ```ts
967
+ // Wait for a connection to be established (with timeout)
968
+ const connection = await controller.connectionSpy.waitForConnection({ timeout: 5000 })
969
+
970
+ // Wait for a connection matching a predicate (useful for multiple connections)
971
+ const connection = await controller.connectionSpy.waitForConnection({
972
+ timeout: 5000,
973
+ predicate: (conn) => conn.request.url.includes('/api/notifications'),
974
+ })
975
+
976
+ // Check if a specific connection is active
977
+ const isConnected = controller.connectionSpy.isConnected(connectionId)
978
+
979
+ // Wait for a specific connection to disconnect
980
+ await controller.connectionSpy.waitForDisconnection(connectionId, { timeout: 5000 })
981
+
982
+ // Get all connection events (connect/disconnect history)
983
+ const events = controller.connectionSpy.getEvents()
984
+
985
+ // Clear event history and claimed connections between tests
986
+ controller.connectionSpy.clear()
987
+ ```
988
+
989
+ **Note**: `waitForConnection` tracks "claimed" connections internally. Each call returns a unique unclaimed connection, allowing sequential waits for the same URL path without returning the same connection twice. This is used internally by `SSEHttpClient.connect()` with `awaitServerConnection`.
990
+
991
+ ### Connection Monitoring
992
+
993
+ Controllers have access to utility methods for monitoring connections:
994
+
995
+ ```ts
996
+ // Get count of active connections
997
+ const count = this.getConnectionCount()
998
+
999
+ // Get all active connections (for iteration/inspection)
1000
+ const connections = this.getConnections()
1001
+
1002
+ // Check if connection spy is enabled (useful for conditional logic)
1003
+ if (this.hasConnectionSpy()) {
1004
+ // ...
1005
+ }
1006
+ ```
1007
+
1008
+ ### SSE Test Utilities
1009
+
1010
+ The library provides utilities for testing SSE endpoints.
1011
+
1012
+ **Two connection methods:**
1013
+ - **Inject** - Uses Fastify's built-in `inject()` to simulate HTTP requests directly in-memory, without network overhead. No `listen()` required. Handler must close the connection for the request to complete.
1014
+ - **Real HTTP** - Actual HTTP connection via `fetch()`. Requires the server to be listening. Supports long-lived connections.
1015
+
1016
+ #### Quick Reference
1017
+
1018
+ | Utility | Connection | Requires Contract | Use Case |
1019
+ |---------|------------|-------------------|----------|
1020
+ | `SSEInjectClient` | Inject (in-memory) | No | Request-response SSE without contracts |
1021
+ | `injectSSE` / `injectPayloadSSE` | Inject (in-memory) | **Yes** | Request-response SSE with type-safe contracts |
1022
+ | `SSEHttpClient` | Real HTTP | No | Long-lived SSE connections |
1023
+
1024
+ `SSEInjectClient` and `injectSSE`/`injectPayloadSSE` do the same thing (Fastify inject), but `injectSSE`/`injectPayloadSSE` provide type safety via contracts while `SSEInjectClient` works with raw URLs.
1025
+
1026
+ #### Inject vs HTTP Comparison
1027
+
1028
+ | Feature | Inject (`SSEInjectClient`, `injectSSE`) | HTTP (`SSEHttpClient`) |
1029
+ |---------|----------------------------------------|------------------------|
1030
+ | **Connection** | Fastify's `inject()` - in-memory | Real HTTP via `fetch()` |
1031
+ | **Event delivery** | All events returned at once (after handler closes) | Events arrive incrementally |
1032
+ | **Connection lifecycle** | Handler must close for request to complete | Can stay open indefinitely |
1033
+ | **Server requirement** | No `listen()` needed | Requires running server |
1034
+ | **Best for** | OpenAI-style streaming, batch exports | Notifications, live feeds, chat |
1035
+
1036
+ #### SSETestServer
1037
+
1038
+ Creates a test server with `@fastify/sse` pre-configured:
1039
+
1040
+ ```ts
1041
+ import { SSETestServer, SSEHttpClient } from 'opinionated-machine'
1042
+
1043
+ // Basic usage
1044
+ const server = await SSETestServer.create(async (app) => {
1045
+ app.get('/api/events', async (request, reply) => {
1046
+ reply.sse({ event: 'message', data: { hello: 'world' } })
1047
+ reply.sseClose()
1048
+ })
1049
+ })
1050
+
1051
+ // Connect and test
1052
+ const client = await SSEHttpClient.connect(server.baseUrl, '/api/events')
1053
+ const events = await client.collectEvents(1)
1054
+ expect(events[0].event).toBe('message')
1055
+
1056
+ // Cleanup
1057
+ client.close()
1058
+ await server.close()
1059
+ ```
1060
+
1061
+ With custom resources (DI container, controllers):
1062
+
1063
+ ```ts
1064
+ const server = await SSETestServer.create(
1065
+ async (app) => {
1066
+ // Register routes using resources from setup
1067
+ myController.registerRoutes(app)
1068
+ },
1069
+ {
1070
+ configureApp: async (app) => {
1071
+ app.setValidatorCompiler(validatorCompiler)
1072
+ },
1073
+ setup: async () => {
1074
+ // Resources are available via server.resources
1075
+ const container = createContainer()
1076
+ return { container }
1077
+ },
1078
+ }
1079
+ )
1080
+
1081
+ const { container } = server.resources
1082
+ ```
1083
+
1084
+ #### SSEHttpClient
1085
+
1086
+ For testing long-lived SSE connections using real HTTP:
1087
+
1088
+ ```ts
1089
+ import { SSEHttpClient } from 'opinionated-machine'
1090
+
1091
+ // Connect to SSE endpoint with awaitServerConnection (recommended)
1092
+ // This eliminates the race condition between client connect and server-side registration
1093
+ const { client, serverConnection } = await SSEHttpClient.connect(
1094
+ server.baseUrl,
1095
+ '/api/stream',
1096
+ {
1097
+ query: { userId: 'test' },
1098
+ headers: { authorization: 'Bearer token' },
1099
+ awaitServerConnection: { controller }, // Pass your SSE controller
1100
+ },
1101
+ )
1102
+
1103
+ // serverConnection is ready to use immediately
1104
+ expect(client.response.ok).toBe(true)
1105
+ await controller.sendEvent(serverConnection.id, { event: 'test', data: {} })
1106
+
1107
+ // Collect events by count with timeout
1108
+ const events = await client.collectEvents(3, 5000) // 3 events, 5s timeout
1109
+
1110
+ // Or collect until a predicate is satisfied
1111
+ const events = await client.collectEvents(
1112
+ (event) => event.event === 'done',
1113
+ 5000,
1114
+ )
1115
+
1116
+ // Iterate over events as they arrive
1117
+ for await (const event of client.events()) {
1118
+ console.log(event.event, event.data)
1119
+ if (event.event === 'done') break
1120
+ }
1121
+
1122
+ // Cleanup
1123
+ client.close()
1124
+ ```
1125
+
1126
+ **`collectEvents(countOrPredicate, timeout?)`**
1127
+
1128
+ Collects events until a count is reached or a predicate returns true.
1129
+
1130
+ | Parameter | Type | Description |
1131
+ |-----------|------|-------------|
1132
+ | `countOrPredicate` | `number \| (event) => boolean` | Number of events to collect, or predicate that returns `true` when collection should stop |
1133
+ | `timeout` | `number` | Maximum time to wait in milliseconds (default: 5000) |
1134
+
1135
+ Returns `Promise<ParsedSSEEvent[]>`. Throws an error if the timeout is reached before the condition is met.
1136
+
1137
+ ```ts
1138
+ // Collect exactly 3 events
1139
+ const events = await client.collectEvents(3)
1140
+
1141
+ // Collect with custom timeout
1142
+ const events = await client.collectEvents(5, 10000) // 10s timeout
1143
+
1144
+ // Collect until a specific event type (the matching event IS included)
1145
+ const events = await client.collectEvents((event) => event.event === 'done')
1146
+
1147
+ // Collect until condition with timeout
1148
+ const events = await client.collectEvents(
1149
+ (event) => JSON.parse(event.data).status === 'complete',
1150
+ 30000,
1151
+ )
1152
+ ```
1153
+
1154
+ **`events(signal?)`**
1155
+
1156
+ Async generator that yields events as they arrive. Accepts an optional `AbortSignal` for cancellation.
1157
+
1158
+ ```ts
1159
+ // Basic iteration
1160
+ for await (const event of client.events()) {
1161
+ console.log(event.event, event.data)
1162
+ if (event.event === 'done') break
1163
+ }
1164
+
1165
+ // With abort signal for timeout control
1166
+ const controller = new AbortController()
1167
+ const timeoutId = setTimeout(() => controller.abort(), 5000)
1168
+
1169
+ try {
1170
+ for await (const event of client.events(controller.signal)) {
1171
+ console.log(event)
1172
+ }
1173
+ } finally {
1174
+ clearTimeout(timeoutId)
1175
+ }
1176
+ ```
1177
+
1178
+ **When to omit `awaitServerConnection`**
1179
+
1180
+ Omit `awaitServerConnection` only in these cases:
1181
+ - Testing against external SSE endpoints (not your own controller)
1182
+ - When `isTestMode: false` (connectionSpy not available)
1183
+ - Simple smoke tests that only verify response headers/status without sending server events
1184
+
1185
+ **Consequence**: Without `awaitServerConnection`, `connect()` resolves as soon as HTTP headers are received. Server-side connection registration may not have completed yet, so you cannot reliably send events from the server immediately after `connect()` returns.
1186
+
1187
+ ```ts
1188
+ // Example: smoke test that only checks connection works
1189
+ const client = await SSEHttpClient.connect(server.baseUrl, '/api/stream')
1190
+ expect(client.response.ok).toBe(true)
1191
+ expect(client.response.headers.get('content-type')).toContain('text/event-stream')
1192
+ client.close()
1193
+ ```
1194
+
1195
+ #### SSEInjectClient
1196
+
1197
+ For testing request-response style SSE streams (like OpenAI completions):
1198
+
1199
+ ```ts
1200
+ import { SSEInjectClient } from 'opinionated-machine'
1201
+
1202
+ const client = new SSEInjectClient(app) // No server.listen() needed
1203
+
1204
+ // GET request
1205
+ const conn = await client.connect('/api/export/progress', {
1206
+ headers: { authorization: 'Bearer token' },
1207
+ })
1208
+
1209
+ // POST request with body (OpenAI-style)
1210
+ const conn = await client.connectWithBody(
1211
+ '/api/chat/completions',
1212
+ { model: 'gpt-4', messages: [...], stream: true },
1213
+ )
1214
+
1215
+ // All events are available immediately (inject waits for complete response)
1216
+ expect(conn.getStatusCode()).toBe(200)
1217
+ const events = conn.getReceivedEvents()
1218
+ const chunks = events.filter(e => e.event === 'chunk')
1219
+ ```
1220
+
1221
+ #### Contract-Aware Inject Helpers
1222
+
1223
+ For typed testing with SSE contracts:
1224
+
1225
+ ```ts
1226
+ import { injectSSE, injectPayloadSSE, parseSSEEvents } from 'opinionated-machine'
1227
+
1228
+ // For GET SSE endpoints with contracts
1229
+ const { closed } = injectSSE(app, notificationsContract, {
1230
+ query: { userId: 'test' },
1231
+ })
1232
+ const result = await closed
1233
+ const events = parseSSEEvents(result.body)
1234
+
1235
+ // For POST/PUT/PATCH SSE endpoints with contracts
1236
+ const { closed } = injectPayloadSSE(app, chatCompletionContract, {
1237
+ body: { message: 'Hello', stream: true },
1238
+ })
1239
+ const result = await closed
1240
+ const events = parseSSEEvents(result.body)
1241
+ ```
1242
+