@sincpro/client-framework 1.6.1 → 1.8.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 (30) hide show
  1. package/AGENTS.md +13 -6
  2. package/README.md +53 -25
  3. package/dist/event_driven/adapters/memory-message-store.d.ts +10 -0
  4. package/dist/event_driven/adapters/{memory-event-store.js → memory-message-store.js} +3 -3
  5. package/dist/event_driven/adapters/stored-queue.d.ts +51 -42
  6. package/dist/event_driven/adapters/stored-queue.js +137 -89
  7. package/dist/event_driven/adapters/sync-queue.d.ts +4 -3
  8. package/dist/event_driven/adapters/sync-queue.js +11 -5
  9. package/dist/event_driven/domain/queue.d.ts +19 -10
  10. package/dist/event_driven/domain/store.d.ts +26 -21
  11. package/dist/event_driven/domain/verdict.d.ts +86 -0
  12. package/dist/event_driven/domain/verdict.js +80 -0
  13. package/dist/event_driven/entrypoint/publisher.d.ts +14 -8
  14. package/dist/event_driven/entrypoint/publisher.js +16 -5
  15. package/dist/event_driven/entrypoint/subscriber.d.ts +9 -1
  16. package/dist/event_driven/entrypoint/subscriber.js +16 -5
  17. package/dist/event_driven/index.d.ts +13 -12
  18. package/dist/event_driven/index.js +11 -10
  19. package/dist/event_driven/services/messages.d.ts +7 -0
  20. package/dist/event_driven/services/messages.js +22 -0
  21. package/dist/observability/adapters/console.d.ts +4 -6
  22. package/dist/observability/adapters/console.js +8 -9
  23. package/dist/observability/domain/logging.d.ts +27 -0
  24. package/dist/observability/domain/logging.js +21 -1
  25. package/dist/observability/index.d.ts +2 -2
  26. package/dist/observability/index.js +2 -1
  27. package/dist/observability/services/logging.d.ts +8 -1
  28. package/dist/observability/services/logging.js +16 -0
  29. package/package.json +1 -1
  30. package/dist/event_driven/adapters/memory-event-store.d.ts +0 -10
package/AGENTS.md CHANGED
@@ -33,7 +33,7 @@ module has only the layers it needs, and says what it offers in its own `index.t
33
33
  | `src/client/` | `Transport`, `entity()`, the contract (domain); REST, memory, Parquet; discovery, propagation |
34
34
  | `src/model/` | Model definitions: `defineMeta`, from a JSON Schema, the store of known ones |
35
35
  | `src/core/` | DTOs and events, bus, services, handlers, extension points; pipeline; `BoundedContext`; process |
36
- | `src/event_driven/` | `Envelope`, messages, `EventQueue`/`Subscribes` ports; queues; `Publisher`, `Subscriber` |
36
+ | `src/event_driven/` | `Envelope`, messages, `MessageQueue`/`Subscribes` ports; queues; `Publisher`, `Subscriber` |
37
37
  | `src/codegen/` | The generator and its CLI (`sincpro-client generate`) — the only place Node is allowed |
38
38
  | `src/testing/` | The public entry of the in-memory observability adapters |
39
39
  | `tests/` | vitest in Node, one folder per module; `tests/support/` holds fakes and forge's contracts |
@@ -92,8 +92,8 @@ module has only the layers it needs, and says what it offers in its own `index.t
92
92
  - **How events are carried is here; where they are kept is the platform's.** An event's
93
93
  consumers are acknowledged apart: a bounded context's use case for it (one per bounded context,
94
94
  keyed by its name), its event handlers and a subscriber's (`<owner>/<Handler>`). `storedQueue`
95
- holds the rules — store first, deliver in order, retry what may succeed, set aside what never
96
- will, never run one consumer twice — over an `EventStore` the platform plugs (SQLite,
95
+ holds the rules — store first, deliver in order, decide by the verdict (`verdictOf`), never
96
+ run one consumer twice — over a `MessageStore` the platform plugs (SQLite,
97
97
  IndexedDB, memory). A store only keeps records; it never decides.
98
98
  - **The Subscriber is the queue's entrypoint, and it is composite.** One per queue — never one
99
99
  per handler —, created once like a bounded context (`new Subscriber<D>("app")`,
@@ -134,7 +134,12 @@ module has only the layers it needs, and says what it offers in its own `index.t
134
134
  nothing else needs to know a circuit exists.
135
135
  - **Delivery is at least once.** A stored message may run twice after a crash. The use case keys
136
136
  its effect by `this.execution.causationId` (the message's id) or by the entity the event names.
137
- `maxAttempts` sets aside what keeps failing. One process drains a store. `execution` is
137
+ A message is sent once (`retries: 0`) and a failure is set aside; what goes over the network
138
+ (`requiresNetwork`) waits while the other side is not there (`WAITING_KINDS`), until
139
+ `maxAttempts`. A platform extends the rules by wrapping `verdictOf`, never in the queue.
140
+ - **A Command can travel too.** `publisher.send(command)` stores an intention; the bus that
141
+ consumes it (the subscriber's `commands`) runs it when it can, and its answer is kept. Its
142
+ envelope id is its key: the use case sends it as the `Idempotency-Key`. One process drains a store. `execution` is
138
143
  reserved.
139
144
  - **A failure says its kind, whatever the wire.** `failureOf` reads a declared `failureKind`, the
140
145
  `Problem` (the same over REST, JSON-RPC and gRPC), then a REST status. A transport of another
@@ -212,8 +217,10 @@ options)`: no route, no verb, no RPC method. The contract's bindings (`rest`, `r
212
217
  - **The application layer imports no logger.** A bounded context has `projectBoundedContext.logger`; a run
213
218
  hands `this.logger`, bound to its execution. Only `logger` (infrastructure, the global one) and
214
219
  `loggerAdapter` are predefined; injected as a dependency they bind to the run (`BIND`), imported
215
- at module level they do not. No logger is predefined for an application layer. Console is the
216
- default engine; `configureProcess({ logger })` and `configureLogger(...)` take the same
220
+ at module level they do not. No logger is predefined for an application layer. Which INFO and
221
+ DEBUG lines speak is a `LogFilter` (level, layer, bounded context — `speaks`), the same rule
222
+ for the console and any sink (`filteredLogger`); WARN and ERROR always speak, and spans are
223
+ never filtered. Console is the default engine; `configureProcess({ logger })` and `configureLogger(...)` take the same
217
224
  `LoggerConfiguration`. The host chooses production explicitly. Never log DTOs, results or the
218
225
  full session context automatically.
219
226
  - **A failure is described once, as sincpro_framework's failure line** (`PRD_03 §6`,
package/README.md CHANGED
@@ -290,44 +290,59 @@ that hears it continues that flow.
290
290
 
291
291
  What is defined here, and what each platform plugs behind the ports:
292
292
 
293
- | Piece | Here | The platform's |
294
- | ----------------- | -------------------------------------------------------------- | -------------------------------------- |
295
- | `DomainEvent` | the class, its `eventName`, its messages | — |
296
- | `Command` | its identity (given at registration), its messages | — |
297
- | `Envelope` | `name`, `id`, `correlationId`, `causationId`, `publishedAt` | storing it beside the event |
298
- | `EventQueue` port | `syncQueue` (in the call); `storedQueue` (store, then deliver) | a broker's queue, `BroadcastChannel` |
299
- | `EventStore` port | `memoryEventStore()` | mobile: a SQLite table; web: IndexedDB |
300
- | `Subscriber` | pull, rebuild, deliver to every consumer; Commands declared | where messages come from (a socket) |
293
+ | Piece | Here | The platform's |
294
+ | ------------------- | -------------------------------------------------------------- | -------------------------------------- |
295
+ | `DomainEvent` | the class, its `eventName`, its messages | — |
296
+ | `Command` | its identity (given at registration), its messages | — |
297
+ | `Envelope` | `name`, `id`, `correlationId`, `causationId`, `publishedAt` | storing it beside the event |
298
+ | `MessageQueue` port | `syncQueue` (in the call); `storedQueue` (store, then deliver) | a broker's queue, `BroadcastChannel` |
299
+ | `MessageStore` port | `memoryMessageStore()` | mobile: a SQLite table; web: IndexedDB |
300
+ | `Subscriber` | pull, rebuild, deliver to every consumer; Commands declared | where messages come from (a socket) |
301
301
 
302
- ### Stored events: one way to carry them, any store
302
+ ### Stored messages: events and Commands, one way to carry them, any store
303
303
 
304
304
  ```ts
305
305
  const queue = storedQueue({
306
- store: sqliteEventStore(db), // the platform's EventStore; memoryEventStore() in a tab or a test
306
+ store: sqliteMessageStore(db), // the platform's MessageStore; memoryMessageStore() in a tab or a test
307
307
  subscriber: new Subscriber(
308
308
  salesBoundedContext,
309
309
  stockBoundedContext,
310
310
  printingBoundedContext,
311
311
  ),
312
312
  ready: (stored) => connectivity.online || !needsNetwork(stored.envelope.name),
313
+ policyOf: (stored) => policies[stored.envelope.name], // what its class or the app says
313
314
  onSettled: (stored) => activity.show(stored.envelope.name, stored.state),
314
315
  });
315
316
  shopBoundedContext.addDependency("publisher", new Publisher(queue));
316
317
  connectivity.onBack(() => queue.drain()); // and on coming back to the foreground
317
- ```
318
318
 
319
- `publish` returns once the event is stored. Then the queue delivers what waits, one at a time,
320
- in the order stored — the backend's store-and-forward, over whatever store the platform plugs:
319
+ await publisher.publish(new OrderPaid(order.id)); // a fact: every bounded context that hears it
320
+ await publisher.send(new CommandSendMessage(chat, text)); // an intention: the bus that consumes it
321
+ ```
321
322
 
322
- - It is rebuilt as its class — `static fromJSON` when it has one — and executed by everyone who
323
- hears it and does not have it yet: a retry never runs one twice.
324
- - A failure a retry may fix (`failureOf`: unavailable, no answer, a conflict…) is tried again
325
- after the backoff or the wait it asks for, and what follows waits, so the order holds.
326
- - A failure every attempt would repeat (`PERMANENT_KINDS`: a refusal, invalid, not found) sets
327
- it aside — the dead-letter queue — and never holds back what follows.
328
- - One that is not `ready` (no connection, no session) waits while the rest go on.
329
- - After `maxAttempts` (10) a failure a retry might still fix is set aside too: a bug of the
330
- process (`internal`) never holds the line forever.
323
+ `publish` and `send` return once the message is stored. Then the queue delivers what waits, in
324
+ the order stored — the backend's store-and-forward, over whatever store the platform plugs. An
325
+ event goes to everyone who hears it and does not have it yet; a Command, to the bus that
326
+ consumes it (named in the subscriber's `commands`), and its answer is kept. What follows each
327
+ delivery is its verdict (`verdictOf`, the backend's queue verdicts), with its policy:
328
+
329
+ | What happened | Verdict |
330
+ | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
331
+ | every consumer has it | `delivered` |
332
+ | it is not `ready` (no connection, no session) | waits |
333
+ | it goes over the network and the other side is not there now (`WAITING_KINDS`: unavailable, out of quota, an open circuit, sent with no answer) | `wait` — as long as it takes, until `maxAttempts` |
334
+ | a failure every attempt would repeat (`PERMANENT_KINDS`) | `set_aside` |
335
+ | any other failure (a bug, a device that did not answer) | `retry` while it has `retries`, else `set_aside` |
336
+
337
+ - **Sent once by default** (`DEFAULT_DELIVERY_POLICY`: `retries: 0`, `maxAttempts: Infinity`,
338
+ `requiresNetwork: false`): a failure is set aside — the dead-letter queue — for a person.
339
+ - **A message waiting never holds the line**: what is due goes on.
340
+ - **Sent again with the same key.** A Command's envelope id is its key: its use case sends it as
341
+ the `Idempotency-Key` (`this.execution.causationId`), so one that went out with no answer is
342
+ sent again and the backend runs it once. A server without keys is verified by the use case.
343
+ - **Open for extension.** `policy` and `policyOf` set the rules per queue and per message; a
344
+ platform adds its own by wrapping the verdict —
345
+ `verdict: (delivery) => mine(delivery) ?? verdictOf(delivery)` —, never by changing the queue.
331
346
 
332
347
  The port only keeps records — `add`, `next(skip)`, `save` — so a SQLite table, IndexedDB or
333
348
  memory carry events the same way, with the same rules.
@@ -553,6 +568,19 @@ configureLogger({ mode: "development", level: "info", layers: { adapter: false }
553
568
  configureLogger({ mode: "production" }); // the console, silent
554
569
  configureLogger({ engine: combineLoggers(consoleLogger({ mode }), lokiLogger) }); // other sinks
555
570
  configureLogger({ engine: false }); // no logs
571
+
572
+ // Which INFO and DEBUG lines speak — by level, layer and bounded context; WARN and ERROR always.
573
+ // Spans are never filtered: a quiet line still has its span.
574
+ const production = {
575
+ level: "info",
576
+ layers: { adapter: false },
577
+ boundedContexts: { common: false },
578
+ };
579
+ configureLogger({
580
+ engine: filteredLogger(combineLoggers(consoleSink, lokiSink), () =>
581
+ debugging ? {} : production,
582
+ ),
583
+ });
556
584
  ```
557
585
 
558
586
  The console is the default engine. In production it is silent; in development it prints
@@ -823,10 +851,10 @@ src/
823
851
  entrypoint/ BoundedContext, screensTransport
824
852
  infrastructure/ configureProcess, configureLogger, processListeners
825
853
  event_driven/
826
- domain/ Envelope, the messages (an event's, a Command's), the EventQueue,
827
- Subscribes and EventStore ports
854
+ domain/ Envelope, the messages (an event's, a Command's), the MessageQueue,
855
+ Subscribes and MessageStore ports
828
856
  services/ writing and reading messages
829
- adapters/ syncQueue, storedQueue, memoryEventStore
857
+ adapters/ syncQueue, storedQueue, memoryMessageStore
830
858
  entrypoint/ Publisher, Subscriber (the queue's composite entrypoint)
831
859
  codegen/ the generator and its CLI — the only place Node is allowed
832
860
  testing/ memoryTracer, memoryReporter, memoryLogger
@@ -0,0 +1,10 @@
1
+ import type { MessageStore, StoredMessage } from "../domain/store.js";
2
+ /** A memory store, and what it holds — in the order added — for whoever inspects it. */
3
+ export type MemoryMessageStore = MessageStore & {
4
+ readonly messages: readonly StoredMessage[];
5
+ };
6
+ /**
7
+ * The messages of a stored queue in this process's memory: what a browser tab or a test keeps.
8
+ * Gone with the process — a phone's store is a table.
9
+ */
10
+ export declare function memoryMessageStore(): MemoryMessageStore;
@@ -1,11 +1,11 @@
1
1
  /**
2
- * The events of a stored queue in this process's memory: what a browser tab or a test keeps.
2
+ * The messages of a stored queue in this process's memory: what a browser tab or a test keeps.
3
3
  * Gone with the process — a phone's store is a table.
4
4
  */
5
- export function memoryEventStore() {
5
+ export function memoryMessageStore() {
6
6
  const held = [];
7
7
  return {
8
- get events() {
8
+ get messages() {
9
9
  return [...held];
10
10
  },
11
11
  add(stored) {
@@ -1,68 +1,77 @@
1
1
  import { type JsonValue } from "../../common/serialization.js";
2
- import type { DomainEvent, RemoteEvent } from "../../core/domain/dto.js";
3
- import type { EventQueue, EventType, Subscribes } from "../domain/queue.js";
4
- import type { EventStore, StoredEvent } from "../domain/store.js";
2
+ import type { AnyCommand, DomainEvent, RemoteCommand, RemoteEvent } from "../../core/domain/dto.js";
3
+ import type { CommandType, EventType, MessageQueue, Subscribes } from "../domain/queue.js";
4
+ import type { MessageStore, StoredMessage } from "../domain/store.js";
5
+ import { type DeliveryPolicy, type Verdict, verdictOf } from "../domain/verdict.js";
5
6
  export type StoredQueueOptions = {
6
- /** Where the events wait: memory, a phone's SQLite, a browser's IndexedDB. */
7
- readonly store: EventStore;
8
- /** Who executes them: every bounded context that hears each one. */
7
+ /** Where the messages wait: memory, a phone's SQLite, a browser's IndexedDB. */
8
+ readonly store: MessageStore;
9
+ /** Who executes them: every bounded context that hears an event; the bus that consumes a Command. */
9
10
  readonly subscriber: Subscribes;
10
11
  /**
11
- * How a stored payload becomes its class again. By default, `static fromJSON` when the class
12
- * has one, else its values set on an instance of it — as JSON gave them: an event that carries
13
- * a `Money`, a `Decimal` or a date declares `fromJSON` to read them back as such.
12
+ * How a stored event becomes its class again. By default, `static fromJSON` when the class has
13
+ * one, else its values set on an instance of it — as JSON gave them: an event that carries a
14
+ * `Money`, a `Decimal` or a date declares `fromJSON` to read them back as such.
14
15
  */
15
16
  readonly rebuild?: (type: EventType, payload: JsonValue) => DomainEvent | RemoteEvent;
17
+ /** How a stored Command becomes its class again; `commandFrom` by default. */
18
+ readonly rebuildCommand?: (type: CommandType, payload: JsonValue) => AnyCommand | RemoteCommand;
16
19
  /**
17
- * Whether an event may be delivered now — a phone asks for a connection, or a session. One
20
+ * Whether a message may be delivered now — a phone asks for a connection, or a session. One
18
21
  * that is not waits while the rest go on; `drain()` again when what it waits for comes back.
19
22
  */
20
- readonly ready?: (stored: StoredEvent) => boolean | Promise<boolean>;
21
- /** The first wait after a failed attempt, in ms (1 s); doubled each time, never past `longestWait`. */
22
- readonly wait?: number;
23
- /** The longest wait between attempts, in ms (one minute). */
24
- readonly longestWait?: number;
23
+ readonly ready?: (stored: StoredMessage) => boolean | Promise<boolean>;
24
+ /** The queue's policy, over `DEFAULT_DELIVERY_POLICY`: 0 retries, no limit to waiting. */
25
+ readonly policy?: DeliveryPolicy;
26
+ /**
27
+ * One message's policy, over the queue's — what its class declares, what the application set
28
+ * for its name: a platform reads it its own way.
29
+ */
30
+ readonly policyOf?: (stored: StoredMessage) => DeliveryPolicy | undefined;
25
31
  /**
26
- * How many attempts an event gets before it is set aside although a retry might still fix it
27
- * (10): a bug of this process (`internal`) or a dependency gone for good must not hold the line
28
- * forever. `Infinity` keeps trying.
32
+ * The verdict on each delivery — `verdictOf` by default. A platform extends the rules by
33
+ * wrapping it (the phone's "the connection dropped: wait for it"), never by changing the queue.
29
34
  */
30
- readonly maxAttempts?: number;
31
- /** Told each time an event settles — delivered, set aside, or waiting to retry —: a screen's activity. */
32
- readonly onSettled?: (stored: StoredEvent) => void;
35
+ readonly verdict?: (delivery: Parameters<typeof verdictOf>[0]) => Verdict;
36
+ /** The first wait before a message is sent again, in ms (1 s); doubled each time, never past `longestWait`. */
37
+ readonly wait?: number;
38
+ /** The longest wait between sends, in ms (one minute). */
39
+ readonly longestWait?: number;
40
+ /** Told each time a message settles — delivered, set aside, or waiting —: a screen follows it. */
41
+ readonly onSettled?: (stored: StoredMessage) => void;
33
42
  };
34
43
  /** A stored queue, and the door to deliver what waits — on a timer, back online, in the foreground. */
35
- export type StoredQueue = EventQueue & {
44
+ export type StoredQueue = MessageQueue & {
36
45
  drain(): Promise<void>;
37
46
  };
38
47
  /**
39
- * The queue that stores an event before delivering it, and delivers it until every bounded
40
- * context that hears it has it — the backend's store-and-forward (`Forwarding`), over a store
41
- * each platform plugs.
48
+ * The queue that stores a message before delivering it — an event until every bounded context
49
+ * that hears it has it, a Command until the bus that consumes it answered — the backend's
50
+ * store-and-forward (`Forwarding`), over a store each platform plugs.
42
51
  *
43
- * const queue = storedQueue({ store: sqliteEventStore(db), subscriber, ready: online });
52
+ * const queue = storedQueue({ store: sqliteMessageStore(db), subscriber, ready: online });
44
53
  * shopBoundedContext.addDependency("publisher", new Publisher(queue));
45
54
  * connectivity.onBack(() => queue.drain());
46
55
  *
47
- * Context: what a phone did by hand in its event bus, the same on every platform. `publish`
48
- * returns once the event is stored — nobody waits for the delivery. Then, one at a time and in
49
- * the order stored:
56
+ * Context: `publish` and `send` return once the message is stored — nobody waits for the
57
+ * delivery. Then, one at a time and in the order stored:
50
58
  *
51
- * 1. An event not ready (`ready`) waits while the rest go on.
52
- * 2. Nobody hears its name: delivered — a fact recorded, nobody's to act on.
59
+ * 1. A message waiting its time (`retryAt`), or not ready (`ready`), waits while the rest go on.
60
+ * 2. An event nobody hears is delivered — a fact recorded, nobody's to act on —; a Command
61
+ * nobody consumes here is set aside.
53
62
  * 3. Rebuilt as its class; one that cannot be is set aside.
54
- * 4. Executed in every bounded context that hears it and does not have it yet (`reached`).
55
- * 5. A failure every attempt would repeat (`PERMANENT_KINDS`: a refusal, invalid, not found) sets
56
- * that context aside; any other is tried again after the backoff — or what the failure asks
57
- * for (`retryAfter`, an open circuit's time left) —, and what comes after waits, so the
58
- * order holds; after `maxAttempts`, it is set aside too.
59
- * Final: delivered when every context has it, set aside — the dead-letter queue — when one
60
- * refused it for good or ran out of attempts; `onSettled` hears either.
63
+ * 4. An event is executed by every bounded context that hears it and does not have it yet
64
+ * (`reached`); a Command, by the bus that consumes it — its answer kept.
65
+ * 5. The verdict (`verdictOf`, or the platform's) says what follows, with its policy (`policyOf`
66
+ * over `policy`): delivered; wait — the other side is not there now —; sent again while it has
67
+ * retries; or set aside — the dead-letter queue —, for a person. A consumer that failed in a
68
+ * way every attempt would repeat is never run again.
69
+ * Final: `onSettled` hears every settlement.
61
70
  *
62
- * Delivery is at least once: a process that stops after a context executed an event and before
71
+ * Delivery is at least once: a process that stops after a context executed a message and before
63
72
  * the store saved it executes it there again on the next drain. What must not act twice keys what
64
- * it does by the envelope's id — `this.execution.causationId` in the use case of the event — or
65
- * by the entity the event names.
66
- * And one process drains a store: two tabs over one IndexedDB claim it first (the Web Locks API).
73
+ * it does by the envelope's id — `this.execution.causationId` in its use case, the
74
+ * `Idempotency-Key` a write sends — or by the entity it names. And one process drains a store:
75
+ * two tabs over one IndexedDB claim it first (the Web Locks API).
67
76
  */
68
77
  export declare function storedQueue(options: StoredQueueOptions): StoredQueue;
@@ -1,6 +1,7 @@
1
1
  import { failureOf } from "../../common/failures.js";
2
2
  import { valuesOf } from "../../common/serialization.js";
3
- import { eventFrom } from "../services/messages.js";
3
+ import { DEFAULT_DELIVERY_POLICY, verdictOf, } from "../domain/verdict.js";
4
+ import { commandFrom, eventFrom, } from "../services/messages.js";
4
5
  import { loggerAdapter } from "../../observability/services/logging.js";
5
6
  function described(boundedContext, error) {
6
7
  const failure = failureOf(error);
@@ -11,44 +12,56 @@ function described(boundedContext, error) {
11
12
  message: error instanceof Error ? error.message : String(error),
12
13
  };
13
14
  }
15
+ /** `policy` over `base`, rule by rule: what it does not say, `base` says. */
16
+ function over(base, policy) {
17
+ return {
18
+ retries: policy?.retries ?? base.retries,
19
+ maxAttempts: policy?.maxAttempts ?? base.maxAttempts,
20
+ requiresNetwork: policy?.requiresNetwork ?? base.requiresNetwork,
21
+ };
22
+ }
14
23
  /**
15
- * The queue that stores an event before delivering it, and delivers it until every bounded
16
- * context that hears it has it — the backend's store-and-forward (`Forwarding`), over a store
17
- * each platform plugs.
24
+ * The queue that stores a message before delivering it — an event until every bounded context
25
+ * that hears it has it, a Command until the bus that consumes it answered — the backend's
26
+ * store-and-forward (`Forwarding`), over a store each platform plugs.
18
27
  *
19
- * const queue = storedQueue({ store: sqliteEventStore(db), subscriber, ready: online });
28
+ * const queue = storedQueue({ store: sqliteMessageStore(db), subscriber, ready: online });
20
29
  * shopBoundedContext.addDependency("publisher", new Publisher(queue));
21
30
  * connectivity.onBack(() => queue.drain());
22
31
  *
23
- * Context: what a phone did by hand in its event bus, the same on every platform. `publish`
24
- * returns once the event is stored — nobody waits for the delivery. Then, one at a time and in
25
- * the order stored:
32
+ * Context: `publish` and `send` return once the message is stored — nobody waits for the
33
+ * delivery. Then, one at a time and in the order stored:
26
34
  *
27
- * 1. An event not ready (`ready`) waits while the rest go on.
28
- * 2. Nobody hears its name: delivered — a fact recorded, nobody's to act on.
35
+ * 1. A message waiting its time (`retryAt`), or not ready (`ready`), waits while the rest go on.
36
+ * 2. An event nobody hears is delivered — a fact recorded, nobody's to act on —; a Command
37
+ * nobody consumes here is set aside.
29
38
  * 3. Rebuilt as its class; one that cannot be is set aside.
30
- * 4. Executed in every bounded context that hears it and does not have it yet (`reached`).
31
- * 5. A failure every attempt would repeat (`PERMANENT_KINDS`: a refusal, invalid, not found) sets
32
- * that context aside; any other is tried again after the backoff — or what the failure asks
33
- * for (`retryAfter`, an open circuit's time left) —, and what comes after waits, so the
34
- * order holds; after `maxAttempts`, it is set aside too.
35
- * Final: delivered when every context has it, set aside — the dead-letter queue — when one
36
- * refused it for good or ran out of attempts; `onSettled` hears either.
39
+ * 4. An event is executed by every bounded context that hears it and does not have it yet
40
+ * (`reached`); a Command, by the bus that consumes it — its answer kept.
41
+ * 5. The verdict (`verdictOf`, or the platform's) says what follows, with its policy (`policyOf`
42
+ * over `policy`): delivered; wait — the other side is not there now —; sent again while it has
43
+ * retries; or set aside — the dead-letter queue —, for a person. A consumer that failed in a
44
+ * way every attempt would repeat is never run again.
45
+ * Final: `onSettled` hears every settlement.
37
46
  *
38
- * Delivery is at least once: a process that stops after a context executed an event and before
47
+ * Delivery is at least once: a process that stops after a context executed a message and before
39
48
  * the store saved it executes it there again on the next drain. What must not act twice keys what
40
- * it does by the envelope's id — `this.execution.causationId` in the use case of the event — or
41
- * by the entity the event names.
42
- * And one process drains a store: two tabs over one IndexedDB claim it first (the Web Locks API).
49
+ * it does by the envelope's id — `this.execution.causationId` in its use case, the
50
+ * `Idempotency-Key` a write sends — or by the entity it names. And one process drains a store:
51
+ * two tabs over one IndexedDB claim it first (the Web Locks API).
43
52
  */
44
53
  export function storedQueue(options) {
45
54
  const { store, subscriber } = options;
46
55
  const firstWait = options.wait ?? 1000;
47
56
  const longestWait = options.longestWait ?? 60_000;
48
- const maxAttempts = options.maxAttempts ?? 10;
49
- if (!(maxAttempts >= 1))
50
- throw new TypeError("A stored queue needs one attempt at least");
57
+ const base = over(DEFAULT_DELIVERY_POLICY, options.policy);
58
+ if (!(base.retries >= 0))
59
+ throw new TypeError("A stored queue's retries are 0 or more");
60
+ if (!(base.maxAttempts >= 1))
61
+ throw new TypeError("A stored queue sends a message once at least");
51
62
  const rebuild = options.rebuild ?? eventFrom;
63
+ const rebuildCommand = options.rebuildCommand ?? commandFrom;
64
+ const decide = options.verdict ?? verdictOf;
52
65
  let draining;
53
66
  let again = false;
54
67
  let timer;
@@ -71,100 +84,135 @@ export function storedQueue(options) {
71
84
  // A timer of its own must not keep a process alive that has nothing else to do.
72
85
  timer.unref?.();
73
86
  };
74
- /** One pass over what waits; it stops at an event that must wait its turn. */
87
+ /** Runs `head` by its kind; `undefined` when it settled without running. */
88
+ const run = async (head, attempts) => {
89
+ const settledWith = async (state, error) => {
90
+ await settle({
91
+ ...head,
92
+ state,
93
+ attempts,
94
+ retryAt: null,
95
+ failures: error === undefined ? [] : [described("", error)],
96
+ });
97
+ return undefined;
98
+ };
99
+ if (head.kind === "command") {
100
+ const type = subscriber.commandTypeOf(head.envelope.name);
101
+ if (type === undefined)
102
+ return settledWith("set_aside", new Error(`${head.envelope.name} is not consumed from this queue`));
103
+ let command;
104
+ try {
105
+ command = rebuildCommand(type, head.payload);
106
+ }
107
+ catch (error) {
108
+ return settledWith("set_aside", error);
109
+ }
110
+ const handled = await subscriber.execute(command, head.envelope, head.reached);
111
+ const answered = handled.find((one) => !("error" in one));
112
+ return {
113
+ handled,
114
+ answer: answered && "answer" in answered && answered.answer !== undefined
115
+ ? valuesOf(answered.answer)
116
+ : head.answer,
117
+ };
118
+ }
119
+ const type = subscriber.eventTypeOf(head.envelope.name);
120
+ if (type === undefined)
121
+ return settledWith("delivered");
122
+ let event;
123
+ try {
124
+ event = rebuild(type, head.payload);
125
+ }
126
+ catch (error) {
127
+ return settledWith("set_aside", error);
128
+ }
129
+ return {
130
+ handled: await subscriber.handle(event, head.envelope, head.reached),
131
+ answer: null,
132
+ };
133
+ };
134
+ /** One pass over what waits: every message ready and due, in order; then a timer for the next due. */
75
135
  const pass = async () => {
76
136
  const skip = new Set();
137
+ let nextDue;
77
138
  for (;;) {
78
139
  const head = await store.next(skip);
79
140
  if (head === undefined)
80
- return;
141
+ break;
81
142
  const id = head.envelope.id;
82
- if (head.retryAt !== null && Date.parse(head.retryAt) > Date.now()) {
83
- wakeAt(Date.parse(head.retryAt));
84
- return;
143
+ const due = head.retryAt === null ? 0 : Date.parse(head.retryAt);
144
+ if (due > Date.now()) {
145
+ skip.add(id);
146
+ nextDue = nextDue === undefined ? due : Math.min(nextDue, due);
147
+ continue;
85
148
  }
86
149
  if (options.ready && !(await options.ready(head))) {
87
150
  skip.add(id);
88
151
  continue;
89
152
  }
90
153
  const attempts = head.attempts + 1;
91
- const type = subscriber.eventTypeOf(head.envelope.name);
92
- if (type === undefined) {
93
- await settle({ ...head, state: "delivered", attempts, retryAt: null, failures: [] });
154
+ const ran = await run(head, attempts);
155
+ if (ran === undefined)
94
156
  continue;
95
- }
96
- let event;
97
- try {
98
- event = rebuild(type, head.payload);
99
- }
100
- catch (error) {
101
- await settle({
102
- ...head,
103
- state: "set_aside",
104
- attempts,
105
- retryAt: null,
106
- failures: [described("", error)],
107
- });
108
- continue;
109
- }
110
- const handled = await subscriber.handle(event, head.envelope, head.reached);
111
157
  const reached = [...head.reached];
112
158
  const failures = [];
113
- let retryAfter = 0;
114
- let repeat = false;
115
- for (const one of handled) {
159
+ const errors = [];
160
+ for (const one of ran.handled) {
116
161
  if (!("error" in one)) {
117
162
  reached.push(one.boundedContext);
118
163
  continue;
119
164
  }
120
165
  failures.push(described(one.boundedContext, one.error));
121
- const failure = failureOf(one.error);
122
- if (failure.permanent)
166
+ errors.push(one.error);
167
+ // A consumer that refused it for good is never run again, whatever comes next.
168
+ if (failureOf(one.error).permanent)
123
169
  reached.push(one.boundedContext);
124
- else {
125
- repeat = true;
126
- retryAfter = Math.max(retryAfter, (failure.retryAfter ?? 0) * 1000);
127
- }
128
170
  }
129
- if (repeat && attempts < maxAttempts) {
130
- const backoff = Math.min(longestWait, firstWait * 2 ** (attempts - 1));
131
- const at = Date.now() + Math.max(backoff, retryAfter);
171
+ const verdict = decide({
172
+ stored: head,
173
+ attempts,
174
+ errors,
175
+ policy: over(base, options.policyOf?.(head)),
176
+ backoff: Math.min(longestWait, firstWait * 2 ** (attempts - 1)),
177
+ });
178
+ const common = { ...head, attempts, reached, failures, answer: ran.answer };
179
+ if (verdict.settlement === "wait" || verdict.settlement === "retry") {
180
+ const after = verdict.after;
181
+ const at = after === undefined ? null : Date.now() + after;
132
182
  await settle({
133
- ...head,
183
+ ...common,
134
184
  state: "pending",
135
- attempts,
136
- retryAt: new Date(at).toISOString(),
137
- reached,
138
- failures,
185
+ retryAt: at === null ? null : new Date(at).toISOString(),
139
186
  });
140
- wakeAt(at);
141
- return;
187
+ skip.add(id);
188
+ if (at !== null)
189
+ nextDue = nextDue === undefined ? at : Math.min(nextDue, at);
190
+ continue;
142
191
  }
143
- await settle({
144
- ...head,
145
- state: failures.length === 0 ? "delivered" : "set_aside",
146
- attempts,
147
- retryAt: null,
148
- reached,
149
- failures,
150
- });
192
+ await settle({ ...common, state: verdict.settlement, retryAt: null });
151
193
  }
194
+ if (nextDue !== undefined)
195
+ wakeAt(nextDue);
196
+ };
197
+ const store_ = async (kind, message, envelope) => {
198
+ await store.add({
199
+ kind,
200
+ envelope,
201
+ payload: valuesOf(message),
202
+ state: "pending",
203
+ attempts: 0,
204
+ retryAt: null,
205
+ reached: [],
206
+ failures: [],
207
+ answer: null,
208
+ });
209
+ queue.drain().catch((error) => loggerAdapter.error("The stored queue could not deliver", {
210
+ reason: failureOf(error).reason,
211
+ }));
152
212
  };
153
213
  const queue = {
154
- async put(event, envelope) {
155
- await store.add({
156
- envelope,
157
- payload: valuesOf(event),
158
- state: "pending",
159
- attempts: 0,
160
- retryAt: null,
161
- reached: [],
162
- failures: [],
163
- });
164
- queue.drain().catch((error) => loggerAdapter.error("The stored queue could not deliver", {
165
- reason: failureOf(error).reason,
166
- }));
167
- },
214
+ put: (event, envelope) => store_("event", event, envelope),
215
+ send: (command, envelope) => store_("command", command, envelope),
168
216
  drain() {
169
217
  if (draining !== undefined) {
170
218
  again = true;