@sincpro/client-framework 1.6.1 → 1.7.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.
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
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.
@@ -823,10 +838,10 @@ src/
823
838
  entrypoint/ BoundedContext, screensTransport
824
839
  infrastructure/ configureProcess, configureLogger, processListeners
825
840
  event_driven/
826
- domain/ Envelope, the messages (an event's, a Command's), the EventQueue,
827
- Subscribes and EventStore ports
841
+ domain/ Envelope, the messages (an event's, a Command's), the MessageQueue,
842
+ Subscribes and MessageStore ports
828
843
  services/ writing and reading messages
829
- adapters/ syncQueue, storedQueue, memoryEventStore
844
+ adapters/ syncQueue, storedQueue, memoryMessageStore
830
845
  entrypoint/ Publisher, Subscriber (the queue's composite entrypoint)
831
846
  codegen/ the generator and its CLI — the only place Node is allowed
832
847
  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;
@@ -1,11 +1,12 @@
1
- import type { EventQueue, Subscribes } from "../domain/queue.js";
1
+ import type { MessageQueue, Subscribes } from "../domain/queue.js";
2
2
  /**
3
3
  * The queue that delivers in the call, in memory — the backend's `SyncQueue`: `publish` returns
4
- * once every bounded context that hears the event executed it. What a web application starts
4
+ * once every bounded context that hears the event executed it, `send` once its bus ran the
5
+ * Command. What a web application starts
5
6
  * with, and what a test proves a flow with.
6
7
  *
7
8
  * Context: nothing is stored, so nothing outlives the process — a phone's queue is durable and
8
9
  * the platform's. Every subscriber runs; then the first failure, if any, reaches the publisher,
9
10
  * as an in-process call would.
10
11
  */
11
- export declare function syncQueue(subscriber: Subscribes): EventQueue;
12
+ export declare function syncQueue(subscriber: Subscribes): MessageQueue;
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * The queue that delivers in the call, in memory — the backend's `SyncQueue`: `publish` returns
3
- * once every bounded context that hears the event executed it. What a web application starts
3
+ * once every bounded context that hears the event executed it, `send` once its bus ran the
4
+ * Command. What a web application starts
4
5
  * with, and what a test proves a flow with.
5
6
  *
6
7
  * Context: nothing is stored, so nothing outlives the process — a phone's queue is durable and
@@ -8,12 +9,17 @@
8
9
  * as an in-process call would.
9
10
  */
10
11
  export function syncQueue(subscriber) {
12
+ const raise = (handled) => {
13
+ const failed = handled.find((one) => "error" in one);
14
+ if (failed && "error" in failed)
15
+ throw failed.error;
16
+ };
11
17
  return {
12
18
  async put(event, envelope) {
13
- const handled = await subscriber.handle(event, envelope);
14
- const failed = handled.find((one) => "error" in one);
15
- if (failed && "error" in failed)
16
- throw failed.error;
19
+ raise(await subscriber.handle(event, envelope));
20
+ },
21
+ async send(command, envelope) {
22
+ raise(await subscriber.execute(command, envelope));
17
23
  },
18
24
  };
19
25
  }
@@ -1,27 +1,29 @@
1
- import type { AnyCommand, CommandClass, CommandDescriptor, DomainEvent, EventClass, EventDescriptor, RemoteEvent } from "../../core/domain/dto.js";
1
+ import type { AnyCommand, CommandClass, CommandDescriptor, DomainEvent, EventClass, EventDescriptor, RemoteCommand, RemoteEvent } from "../../core/domain/dto.js";
2
2
  import type { Envelope } from "./envelope.js";
3
3
  /**
4
- * What carries a published event to whoever hears it — the port each platform implements with
5
- * its own technology, as the backend's `Queue`:
4
+ * What carries a message to whoever consumes it — the port each platform implements with its own
5
+ * technology, as the backend's `Queue`:
6
6
  *
7
7
  * - `syncQueue(subscriber)` — this package's: in the call, in memory (the web's default, tests).
8
- * - a phone: SQLite, so an event outlives a restart, with retries, a dead-letter queue and the
9
- * connectivity it waits for.
10
- * - a browser: IndexedDB to work offline, `BroadcastChannel` to tell the other tabs.
8
+ * - `storedQueue(...)` — stored first, then delivered with the rules of a `Verdict`: a phone's
9
+ * SQLite, a browser's IndexedDB.
11
10
  * - a server's broker, through the backend.
12
11
  *
13
12
  * Context: delivery is the platform's — when, how often, how durably —; what it delivers and to
14
- * whom is the same everywhere: an event, its envelope, and a `Subscribes` that executes it in
15
- * every bounded context that hears it.
13
+ * whom is the same everywhere: an event for every bounded context that hears it, a Command for
14
+ * the one bus that consumes it, each with its envelope.
16
15
  */
17
- export interface EventQueue {
16
+ export interface MessageQueue {
17
+ /** An event, for every bounded context that hears it. */
18
18
  put(event: DomainEvent | RemoteEvent, envelope: Envelope): void | Promise<void>;
19
+ /** A Command, for the one bus that consumes it: an intention, answered when it runs. */
20
+ send(command: AnyCommand | RemoteCommand, envelope: Envelope): void | Promise<void>;
19
21
  }
20
22
  /** What an event of a wire name is rebuilt as: its class, or the generated entry it was registered with. */
21
23
  export type EventType = EventClass<DomainEvent> | EventDescriptor;
22
24
  /** What a Command of an identity is rebuilt as: its class, or the generated entry it was registered with. */
23
25
  export type CommandType = CommandClass<AnyCommand> | CommandDescriptor;
24
- /** What one bounded context answered, or failed with, for a delivered event. */
26
+ /** What one bounded context answered, or failed with, for a delivered message. */
25
27
  export type Handled = {
26
28
  readonly boundedContext: string;
27
29
  readonly answer: unknown;
@@ -41,4 +43,11 @@ export interface Subscribes {
41
43
  * already have it — and what each answered.
42
44
  */
43
45
  handle(event: DomainEvent | RemoteEvent, envelope?: Envelope, skip?: readonly string[]): Promise<Handled[]>;
46
+ /** What a consumed Command of that identity is rebuilt as, or `undefined` when none is. */
47
+ commandTypeOf(identity: string): CommandType | undefined;
48
+ /**
49
+ * The Command executed by the one bus that consumes it — nothing when that bus is in `skip` —,
50
+ * and what it answered or failed with.
51
+ */
52
+ execute(command: AnyCommand | RemoteCommand, envelope?: Envelope, skip?: readonly string[]): Promise<Handled[]>;
44
53
  }
@@ -2,11 +2,11 @@ import type { JsonValue } from "../../common/serialization.js";
2
2
  import type { Envelope } from "./envelope.js";
3
3
  import type { FailureKind } from "@sincpro/criteria";
4
4
  /**
5
- * Where a stored queue keeps what it was handed until every bounded context that hears it has
6
- * executed it — the port each platform implements with its own technology:
5
+ * Where a stored queue keeps what it was handed — events and Commands — until it is done with
6
+ * them: the port each platform implements with its own technology:
7
7
  *
8
- * - `memoryEventStore()` — this package's: the process's memory (a browser tab, a test).
9
- * - a phone: a SQLite table, so an event outlives a restart; the set-aside ones are its
8
+ * - `memoryMessageStore()` — this package's: the process's memory (a browser tab, a test).
9
+ * - a phone: a SQLite table, so a message outlives a restart; the set-aside ones are its
10
10
  * dead-letter queue.
11
11
  * - a browser: IndexedDB, to work offline.
12
12
  *
@@ -14,25 +14,26 @@ import type { FailureKind } from "@sincpro/criteria";
14
14
  * try again, what to set aside, which contexts already have it (`storedQueue`). So the port only
15
15
  * keeps records, in the order they came, and finds the next one waiting.
16
16
  */
17
- export interface EventStore {
18
- /** Keeps a published event, waiting. */
19
- add(stored: StoredEvent): void | Promise<void>;
17
+ export interface MessageStore {
18
+ /** Keeps a message, waiting. */
19
+ add(stored: StoredMessage): void | Promise<void>;
20
20
  /**
21
- * The oldest event still waiting (`pending`), in the order added — but those `skip` names by
22
- * envelope id: not ready yet (no connection, no session), they wait while the rest go on.
21
+ * The oldest message still waiting (`pending`), in the order added — but those `skip` ids:
22
+ * not ready, or waiting their time, they wait while the rest go on.
23
23
  */
24
- next(skip: ReadonlySet<string>): StoredEvent | undefined | Promise<StoredEvent | undefined>;
25
- /** What changed of a stored event — found by its envelope's id. */
26
- save(stored: StoredEvent): void | Promise<void>;
24
+ next(skip: ReadonlySet<string>): StoredMessage | undefined | Promise<StoredMessage | undefined>;
25
+ /** What changed of a stored message — found by its envelope's id. */
26
+ save(stored: StoredMessage): void | Promise<void>;
27
27
  }
28
28
  /**
29
- * - `pending`: waiting to be delivered — again, after `retryAt`, when it failed in a way a retry
30
- * may fix.
31
- * - `delivered`: every bounded context that hears it executed it.
32
- * - `set_aside`: a context failed in a way every attempt would repeat (`PERMANENT_KINDS`) — the
33
- * dead-letter queue; it never holds back what comes after.
29
+ * - `pending`: waiting to be delivered — its first time, or again after `retryAt`.
30
+ * - `delivered`: every bounded context that hears the event executed it; the Command answered.
31
+ * - `set_aside`: it failed and is not tried again on its own — the dead-letter queue, for a
32
+ * person to retry, or to drop.
34
33
  */
35
34
  export type StoredState = "pending" | "delivered" | "set_aside";
35
+ /** What a message is: a fact for whoever hears it, or an intention for the bus that consumes it. */
36
+ export type MessageKind = "event" | "command";
36
37
  /** Why a bounded context did not execute it. */
37
38
  export type DeliveryFailure = {
38
39
  readonly boundedContext: string;
@@ -40,17 +41,21 @@ export type DeliveryFailure = {
40
41
  readonly reason: string;
41
42
  readonly message: string;
42
43
  };
43
- /** A published event as a store keeps it: its envelope, its values and how its delivery goes. */
44
- export type StoredEvent = {
44
+ /** A message as a store keeps it: its envelope, its values and how its delivery goes. */
45
+ export type StoredMessage = {
46
+ readonly kind: MessageKind;
45
47
  readonly envelope: Envelope;
46
- /** The event's values (`valuesOf`): rebuilt as its class on delivery. */
48
+ /** Its values (`valuesOf`): rebuilt as its class on delivery. */
47
49
  readonly payload: JsonValue;
48
50
  readonly state: StoredState;
51
+ /** Every time it was handed to its consumers. */
49
52
  readonly attempts: number;
50
- /** When it may be tried again, ISO; `null` when it need not wait. */
53
+ /** When it may be tried again, ISO; `null` when it need not wait a time. */
51
54
  readonly retryAt: string | null;
52
55
  /** The bounded contexts done with it — executed, or set aside —: a retry never runs them again. */
53
56
  readonly reached: readonly string[];
54
57
  /** Why the last attempt did not reach every context. */
55
58
  readonly failures: readonly DeliveryFailure[];
59
+ /** What a Command answered (`valuesOf`), once delivered; `null` for an event. */
60
+ readonly answer: JsonValue | null;
56
61
  };
@@ -0,0 +1,86 @@
1
+ import type { StoredMessage } from "./store.js";
2
+ import type { FailureKind } from "@sincpro/criteria";
3
+ /**
4
+ * How one message is delivered — what its class declares, what the application sets for it by
5
+ * name, over the queue's:
6
+ *
7
+ * { retries: 0, maxAttempts: Infinity, requiresNetwork: false } // the defaults
8
+ */
9
+ export type DeliveryPolicy = {
10
+ /**
11
+ * How many times it is sent again after a failure (0): sent once, and a failure is set aside —
12
+ * the dead-letter queue — for a person to retry.
13
+ */
14
+ readonly retries?: number;
15
+ /**
16
+ * Every send, waits included, before it is set aside although it could still wait (Infinity):
17
+ * what bounds a message waiting for a server that never comes back.
18
+ */
19
+ readonly maxAttempts?: number;
20
+ /**
21
+ * Its work goes over the network: a failure that says the other side is not there now
22
+ * (`WAITING_KINDS`) waits instead of failing, as long as it takes; a platform's `ready` holds it
23
+ * while there is no connection.
24
+ */
25
+ readonly requiresNetwork?: boolean;
26
+ };
27
+ /** A policy with every rule said. */
28
+ export type FullDeliveryPolicy = Required<DeliveryPolicy>;
29
+ /** The queue's policy when nothing says otherwise. */
30
+ export declare const DEFAULT_DELIVERY_POLICY: FullDeliveryPolicy;
31
+ /**
32
+ * The kinds that mean the other side is not there now — down, an open circuit, out of quota, or
33
+ * the call went out and no answer came back —: a message whose work goes over the network waits
34
+ * them out instead of failing. Sending it again is safe because it carries its key (its id),
35
+ * which the backend runs once (`Idempotency-Key`); a server without keys is verified by the use
36
+ * case before it writes again.
37
+ */
38
+ export declare const WAITING_KINDS: ReadonlySet<FailureKind>;
39
+ /** One delivery, as the verdict reads it. */
40
+ export type Delivery = {
41
+ readonly stored: StoredMessage;
42
+ /** Sends so far, this one included. */
43
+ readonly attempts: number;
44
+ /** What each consumer that failed this time raised. */
45
+ readonly errors: readonly unknown[];
46
+ readonly policy: FullDeliveryPolicy;
47
+ /** The wait before the next send, in ms, as the queue's backoff counts it. */
48
+ readonly backoff: number;
49
+ };
50
+ /**
51
+ * - `delivered`: every consumer has it.
52
+ * - `wait`: not a failure to judge — it waits, `after` ms or, without it, for `ready`.
53
+ * - `retry`: it failed, and is sent again `after` ms.
54
+ * - `set_aside`: it failed, and waits for a person.
55
+ */
56
+ export type Verdict = {
57
+ readonly settlement: "delivered";
58
+ } | {
59
+ readonly settlement: "wait";
60
+ readonly after?: number;
61
+ } | {
62
+ readonly settlement: "retry";
63
+ readonly after: number;
64
+ } | {
65
+ readonly settlement: "set_aside";
66
+ };
67
+ /**
68
+ * The verdict on one delivery — the queue column of sincpro_framework's failure table
69
+ * (`entrypoints/adapters/queue/verdicts.py`), for a client:
70
+ *
71
+ * 1. Nothing failed: delivered.
72
+ * 2. It used its `maxAttempts`: set aside.
73
+ * 3. A failure every attempt would repeat (`PERMANENT_KINDS`): set aside.
74
+ * 4. Its work goes over the network and the other side is not there now (`WAITING_KINDS`): it
75
+ * waits — what the failure asks for (`retryAfter`, an open circuit's time left) or the backoff.
76
+ * 5. Any other failure — a bug, a device that did not answer, a conflict —: sent again while it
77
+ * has `retries`, after the backoff; else set aside.
78
+ * Final: several consumers failed — the one that asks the most: wait, then retry, then set aside.
79
+ *
80
+ * Context: pure, and the queue's default — a platform extends it by wrapping it
81
+ * (`storedQueue({ verdict: (delivery) => mine(delivery) ?? verdictOf(delivery) })`), never by
82
+ * changing the queue.
83
+ */
84
+ export declare function verdictOf(delivery: Delivery): Verdict;
85
+ /** The one verdict of several consumers: the one that asks the most, its longest wait. */
86
+ export declare function combined(verdicts: readonly Verdict[]): Verdict;
@@ -0,0 +1,80 @@
1
+ import { failureOf } from "../../common/failures.js";
2
+ /** The queue's policy when nothing says otherwise. */
3
+ export const DEFAULT_DELIVERY_POLICY = {
4
+ retries: 0,
5
+ maxAttempts: Number.POSITIVE_INFINITY,
6
+ requiresNetwork: false,
7
+ };
8
+ /**
9
+ * The kinds that mean the other side is not there now — down, an open circuit, out of quota, or
10
+ * the call went out and no answer came back —: a message whose work goes over the network waits
11
+ * them out instead of failing. Sending it again is safe because it carries its key (its id),
12
+ * which the backend runs once (`Idempotency-Key`); a server without keys is verified by the use
13
+ * case before it writes again.
14
+ */
15
+ export const WAITING_KINDS = new Set([
16
+ "unavailable",
17
+ "exhausted",
18
+ "in_progress",
19
+ "unknown_outcome",
20
+ ]);
21
+ /**
22
+ * The verdict on one delivery — the queue column of sincpro_framework's failure table
23
+ * (`entrypoints/adapters/queue/verdicts.py`), for a client:
24
+ *
25
+ * 1. Nothing failed: delivered.
26
+ * 2. It used its `maxAttempts`: set aside.
27
+ * 3. A failure every attempt would repeat (`PERMANENT_KINDS`): set aside.
28
+ * 4. Its work goes over the network and the other side is not there now (`WAITING_KINDS`): it
29
+ * waits — what the failure asks for (`retryAfter`, an open circuit's time left) or the backoff.
30
+ * 5. Any other failure — a bug, a device that did not answer, a conflict —: sent again while it
31
+ * has `retries`, after the backoff; else set aside.
32
+ * Final: several consumers failed — the one that asks the most: wait, then retry, then set aside.
33
+ *
34
+ * Context: pure, and the queue's default — a platform extends it by wrapping it
35
+ * (`storedQueue({ verdict: (delivery) => mine(delivery) ?? verdictOf(delivery) })`), never by
36
+ * changing the queue.
37
+ */
38
+ export function verdictOf(delivery) {
39
+ const { errors, attempts, policy, backoff } = delivery;
40
+ if (errors.length === 0)
41
+ return { settlement: "delivered" };
42
+ if (attempts >= policy.maxAttempts)
43
+ return { settlement: "set_aside" };
44
+ const verdicts = errors.map((error) => {
45
+ const failure = failureOf(error);
46
+ if (failure.permanent)
47
+ return { settlement: "set_aside" };
48
+ const asked = (failure.retryAfter ?? 0) * 1000;
49
+ if (policy.requiresNetwork && WAITING_KINDS.has(failure.kind)) {
50
+ return { settlement: "wait", after: Math.max(backoff, asked) };
51
+ }
52
+ if (attempts <= policy.retries) {
53
+ return { settlement: "retry", after: Math.max(backoff, asked) };
54
+ }
55
+ return { settlement: "set_aside" };
56
+ });
57
+ return combined(verdicts);
58
+ }
59
+ const WORST_FIRST = [
60
+ "wait",
61
+ "retry",
62
+ "set_aside",
63
+ "delivered",
64
+ ];
65
+ /** The one verdict of several consumers: the one that asks the most, its longest wait. */
66
+ export function combined(verdicts) {
67
+ for (const settlement of WORST_FIRST) {
68
+ const same = verdicts.filter((one) => one.settlement === settlement);
69
+ if (same.length === 0)
70
+ continue;
71
+ const afters = same.flatMap((one) => "after" in one && one.after !== undefined ? [one.after] : []);
72
+ const after = afters.length > 0 ? Math.max(...afters) : undefined;
73
+ if (settlement === "wait")
74
+ return after === undefined ? { settlement } : { settlement, after };
75
+ if (settlement === "retry")
76
+ return { settlement, after: after ?? 0 };
77
+ return { settlement };
78
+ }
79
+ return { settlement: "delivered" };
80
+ }
@@ -1,15 +1,15 @@
1
1
  import { BIND, type Execution } from "../../context/domain/execution.js";
2
- import type { DomainEvent, RemoteEvent } from "../../core/domain/dto.js";
2
+ import type { AnyCommand, DomainEvent, RemoteCommand, RemoteEvent } from "../../core/domain/dto.js";
3
3
  import type { Cause } from "../../core/domain/pipeline.js";
4
4
  import { type Envelope } from "../domain/envelope.js";
5
- import type { EventQueue } from "../domain/queue.js";
5
+ import type { MessageQueue } from "../domain/queue.js";
6
6
  /**
7
- * Puts events into a queue — what a Feature holds to tell whoever listens, as the backend's
8
- * `Publisher`:
7
+ * Puts messages into a queue — what a Feature or a screen holds to tell whoever listens, or to
8
+ * ask for something that runs when it can, as the backend's `Publisher`:
9
9
  *
10
10
  * shopBoundedContext.addDependency("publisher", new Publisher(queue));
11
- * // in a Feature:
12
- * await this.publisher.publish(new OrderPaid(order.id)); // its Envelope
11
+ * await this.publisher.publish(new OrderPaid(order.id)); // a fact: every hearer
12
+ * await this.publisher.send(new CommandSendMessage(chat, text)); // an intention: its bus
13
13
  *
14
14
  * Context: a dependency of a bounded context is bound to each run (`BIND`), so what a Feature
15
15
  * publishes joins that run's flow — the same `correlationId`, caused by the run — with nothing
@@ -18,9 +18,15 @@ import type { EventQueue } from "../domain/queue.js";
18
18
  export declare class Publisher {
19
19
  private readonly queue;
20
20
  private readonly cause?;
21
- constructor(queue: EventQueue, cause?: Cause | undefined);
21
+ constructor(queue: MessageQueue, cause?: Cause | undefined);
22
22
  /** `event` into the queue, with its envelope; answers the envelope once the queue took it. */
23
23
  publish(event: DomainEvent | RemoteEvent): Promise<Envelope>;
24
- /** The same publisher, publishing as `execution`: its events join that run's flow. */
24
+ /**
25
+ * `command` into the queue, with its envelope: an intention, stored and run by the bus that
26
+ * consumes it when it can — its answer arrives later, kept with it. Answers the envelope once
27
+ * the queue took it: its id is the Command's key.
28
+ */
29
+ send(command: AnyCommand | RemoteCommand): Promise<Envelope>;
30
+ /** The same publisher, publishing as `execution`: what it publishes and sends joins that run's flow. */
25
31
  [BIND](execution: Execution): Publisher;
26
32
  }
@@ -1,13 +1,14 @@
1
1
  import { BIND } from "../../context/domain/execution.js";
2
2
  import { envelopeOf, } from "../domain/envelope.js";
3
+ import { commandEnvelopeOf } from "../services/messages.js";
3
4
  import { traceparentOf } from "../../observability/services/trace-context.js";
4
5
  /**
5
- * Puts events into a queue — what a Feature holds to tell whoever listens, as the backend's
6
- * `Publisher`:
6
+ * Puts messages into a queue — what a Feature or a screen holds to tell whoever listens, or to
7
+ * ask for something that runs when it can, as the backend's `Publisher`:
7
8
  *
8
9
  * shopBoundedContext.addDependency("publisher", new Publisher(queue));
9
- * // in a Feature:
10
- * await this.publisher.publish(new OrderPaid(order.id)); // its Envelope
10
+ * await this.publisher.publish(new OrderPaid(order.id)); // a fact: every hearer
11
+ * await this.publisher.send(new CommandSendMessage(chat, text)); // an intention: its bus
11
12
  *
12
13
  * Context: a dependency of a bounded context is bound to each run (`BIND`), so what a Feature
13
14
  * publishes joins that run's flow — the same `correlationId`, caused by the run — with nothing
@@ -26,7 +27,17 @@ export class Publisher {
26
27
  await this.queue.put(event, envelope);
27
28
  return envelope;
28
29
  }
29
- /** The same publisher, publishing as `execution`: its events join that run's flow. */
30
+ /**
31
+ * `command` into the queue, with its envelope: an intention, stored and run by the bus that
32
+ * consumes it when it can — its answer arrives later, kept with it. Answers the envelope once
33
+ * the queue took it: its id is the Command's key.
34
+ */
35
+ async send(command) {
36
+ const envelope = commandEnvelopeOf(command, this.cause);
37
+ await this.queue.send(command, envelope);
38
+ return envelope;
39
+ }
40
+ /** The same publisher, publishing as `execution`: what it publishes and sends joins that run's flow. */
30
41
  [BIND](execution) {
31
42
  const traceparent = traceparentOf(execution.span);
32
43
  return new Publisher(this.queue, {
@@ -1,5 +1,5 @@
1
1
  import type { EventConsumer, EventKey } from "../../core/domain/consumers.js";
2
- import type { AnyCommand, CommandClass, CommandDescriptor, DomainEvent, DtoKey, EventClass, EventDescriptor, Executable, ExecutableOf, RemoteEvent } from "../../core/domain/dto.js";
2
+ import type { AnyCommand, CommandClass, CommandDescriptor, DomainEvent, DtoKey, EventClass, EventDescriptor, Executable, ExecutableOf, RemoteCommand, RemoteEvent } from "../../core/domain/dto.js";
3
3
  import type { Cause, ExecuteOptions } from "../../core/domain/pipeline.js";
4
4
  import { type HandledEvent } from "../../core/domain/services.js";
5
5
  import { type HandlerRegistrar } from "../../core/services/event-handlers.js";
@@ -128,6 +128,14 @@ export declare class Subscriber<D extends object = Record<never, never>> impleme
128
128
  * Final: what each answered, or failed with; nothing when nobody here knows it.
129
129
  */
130
130
  receive(arrived: Message | BinaryMessage, skip?: readonly string[]): Promise<Handled[]>;
131
+ /**
132
+ * A Command this subscriber consumes, executed by the one bus that registered it — continuing
133
+ * the envelope's flow and trace when there is one —; nothing when that bus is in `skip`.
134
+ * One it does not consume is `CommandNotConsumed`: a bus never runs a Command it did not ask
135
+ * for.
136
+ * Final: what the bus answered, or failed with.
137
+ */
138
+ execute(command: AnyCommand | RemoteCommand, envelope?: Envelope, skip?: readonly string[]): Promise<Handled[]>;
131
139
  /** Every consumer of `event`, each under a key no other one has. */
132
140
  private consumersOf;
133
141
  /** One of its own handlers, as a consumer: its run, with this subscriber's dependencies. */
@@ -4,7 +4,7 @@ import { processHearing } from "../../core/infrastructure/listeners.js";
4
4
  import { identityOf, keyIdentity } from "../../core/services/dto-keys.js";
5
5
  import { eventKeysOf, handlerRegistrar, handles, runHandler, } from "../../core/services/event-handlers.js";
6
6
  import { announceTo } from "../../core/services/listening.js";
7
- import { causeOf, commandFrom, envelopeFrom, eventFrom, readMessage, } from "../services/messages.js";
7
+ import { commandFrom, envelopeFrom, eventFrom, readMessage, } from "../services/messages.js";
8
8
  /** A Command the queue carried that this subscriber was not told to consume. */
9
9
  export class CommandNotConsumed extends Error {
10
10
  type;
@@ -238,13 +238,24 @@ export class Subscriber {
238
238
  throw new CommandNotConsumed(message.type);
239
239
  return [];
240
240
  }
241
- const bus = this.buses.find((one) => one.context.commandTypeOf(message.type) !== undefined);
241
+ return this.execute(commandFrom(commandType, message.data), envelopeFrom(message), skip);
242
+ }
243
+ /**
244
+ * A Command this subscriber consumes, executed by the one bus that registered it — continuing
245
+ * the envelope's flow and trace when there is one —; nothing when that bus is in `skip`.
246
+ * One it does not consume is `CommandNotConsumed`: a bus never runs a Command it did not ask
247
+ * for.
248
+ * Final: what the bus answered, or failed with.
249
+ */
250
+ async execute(command, envelope, skip = []) {
251
+ const identity = identityOf(command)?.wire ?? "";
252
+ if (this.commandTypeOf(identity) === undefined)
253
+ throw new CommandNotConsumed(identity);
254
+ const bus = this.buses.find((one) => one.context.commandTypeOf(identity) !== undefined);
242
255
  if (bus === undefined || skip.includes(bus.key))
243
256
  return [];
244
257
  try {
245
- const answer = await bus.context.execute(commandFrom(commandType, message.data), {
246
- cause: causeOf(message),
247
- });
258
+ const answer = await bus.context.execute(command, envelope ? { cause: envelope } : {});
248
259
  return [{ boundedContext: bus.key, answer }];
249
260
  }
250
261
  catch (error) {
@@ -1,23 +1,24 @@
1
1
  /**
2
- * Event-driven: the ports and the in-memory pieces that let every platform publish domain events
3
- * and hand what a queue carries to the bus the same way — as sincpro_framework's `event_driven`.
4
- * Delivering them durably (SQLite on a phone, IndexedDB in a browser, a broker) is each
5
- * platform's, behind `EventQueue`.
2
+ * Event-driven: the ports and the in-memory pieces that let every platform publish events, send
3
+ * Commands, and hand what a queue carries to the bus the same way — as sincpro_framework's
4
+ * `event_driven`. Delivering them durably (SQLite on a phone, IndexedDB in a browser, a broker)
5
+ * is each platform's, behind `MessageQueue`.
6
6
  *
7
- * domain/ the envelope, the messages (an event, a Command) and the ports: EventQueue,
8
- * Subscribes, EventStore
7
+ * domain/ the envelope, the messages (an event, a Command), the ports (MessageQueue,
8
+ * Subscribes, MessageStore) and the delivery's rules (DeliveryPolicy, verdictOf)
9
9
  * services/ writing and reading messages: a Command by its identity, an event by its name
10
- * adapters/ syncQueue (in the call), storedQueue (store, then deliver, retry, set aside),
11
- * memoryEventStore
10
+ * adapters/ syncQueue (in the call), storedQueue (store, then deliver by the verdict),
11
+ * memoryMessageStore
12
12
  * entrypoint/ Publisher (what a Feature holds), Subscriber (the queue's only entrypoint)
13
13
  */
14
- export { type MemoryEventStore, memoryEventStore, } from "./adapters/memory-event-store.js";
14
+ export { type MemoryMessageStore, memoryMessageStore, } from "./adapters/memory-message-store.js";
15
15
  export { type StoredQueue, storedQueue, type StoredQueueOptions, } from "./adapters/stored-queue.js";
16
16
  export { syncQueue } from "./adapters/sync-queue.js";
17
17
  export { type Envelope, envelopeOf, } from "./domain/envelope.js";
18
18
  export type { BinaryMessage, Message, } from "./domain/messages.js";
19
- export type { CommandType, EventQueue, EventType, Handled, Subscribes, } from "./domain/queue.js";
20
- export type { DeliveryFailure, EventStore, StoredEvent, StoredState, } from "./domain/store.js";
19
+ export type { CommandType, EventType, Handled, MessageQueue, Subscribes, } from "./domain/queue.js";
20
+ export type { DeliveryFailure, MessageKind, MessageStore, StoredMessage, StoredState, } from "./domain/store.js";
21
+ export { combined, DEFAULT_DELIVERY_POLICY, type Delivery, type DeliveryPolicy, type FullDeliveryPolicy, type Verdict, verdictOf, WAITING_KINDS, } from "./domain/verdict.js";
21
22
  export { Publisher } from "./entrypoint/publisher.js";
22
23
  export { CommandNotConsumed, type HearingContext, type NamedSubscriberOptions, Subscriber, type SubscriberOptions, } from "./entrypoint/subscriber.js";
23
- export { causeOf, commandFrom, commandMessageOf, envelopeFrom, eventFrom, eventMessageOf, type MessageOptions, readMessage, } from "./services/messages.js";
24
+ export { causeOf, commandEnvelopeOf, commandFrom, commandMessageOf, envelopeFrom, eventFrom, eventMessageOf, type MessageOptions, readMessage, } from "./services/messages.js";
@@ -1,20 +1,21 @@
1
1
  /**
2
- * Event-driven: the ports and the in-memory pieces that let every platform publish domain events
3
- * and hand what a queue carries to the bus the same way — as sincpro_framework's `event_driven`.
4
- * Delivering them durably (SQLite on a phone, IndexedDB in a browser, a broker) is each
5
- * platform's, behind `EventQueue`.
2
+ * Event-driven: the ports and the in-memory pieces that let every platform publish events, send
3
+ * Commands, and hand what a queue carries to the bus the same way — as sincpro_framework's
4
+ * `event_driven`. Delivering them durably (SQLite on a phone, IndexedDB in a browser, a broker)
5
+ * is each platform's, behind `MessageQueue`.
6
6
  *
7
- * domain/ the envelope, the messages (an event, a Command) and the ports: EventQueue,
8
- * Subscribes, EventStore
7
+ * domain/ the envelope, the messages (an event, a Command), the ports (MessageQueue,
8
+ * Subscribes, MessageStore) and the delivery's rules (DeliveryPolicy, verdictOf)
9
9
  * services/ writing and reading messages: a Command by its identity, an event by its name
10
- * adapters/ syncQueue (in the call), storedQueue (store, then deliver, retry, set aside),
11
- * memoryEventStore
10
+ * adapters/ syncQueue (in the call), storedQueue (store, then deliver by the verdict),
11
+ * memoryMessageStore
12
12
  * entrypoint/ Publisher (what a Feature holds), Subscriber (the queue's only entrypoint)
13
13
  */
14
- export { memoryEventStore, } from "./adapters/memory-event-store.js";
14
+ export { memoryMessageStore, } from "./adapters/memory-message-store.js";
15
15
  export { storedQueue, } from "./adapters/stored-queue.js";
16
16
  export { syncQueue } from "./adapters/sync-queue.js";
17
17
  export { envelopeOf, } from "./domain/envelope.js";
18
+ export { combined, DEFAULT_DELIVERY_POLICY, verdictOf, WAITING_KINDS, } from "./domain/verdict.js";
18
19
  export { Publisher } from "./entrypoint/publisher.js";
19
20
  export { CommandNotConsumed, Subscriber, } from "./entrypoint/subscriber.js";
20
- export { causeOf, commandFrom, commandMessageOf, envelopeFrom, eventFrom, eventMessageOf, readMessage, } from "./services/messages.js";
21
+ export { causeOf, commandEnvelopeOf, commandFrom, commandMessageOf, envelopeFrom, eventFrom, eventMessageOf, readMessage, } from "./services/messages.js";
@@ -14,6 +14,13 @@ export type MessageOptions = {
14
14
  * `as_json`, so a body read alone says which event it is.
15
15
  */
16
16
  export declare function eventMessageOf(event: DomainEvent | RemoteEvent, envelope: Envelope, options?: MessageOptions): Message;
17
+ /**
18
+ * The envelope of a Command sent through a queue — its identity is its name —, sent by the run
19
+ * `cause` names, or the head of its own flow. Its id is the Command's key: what its use case
20
+ * sends as the `Idempotency-Key` (`this.execution.causationId`), so sending it again never runs
21
+ * it twice on a server that keeps keys.
22
+ */
23
+ export declare function commandEnvelopeOf(command: AnyCommand | RemoteCommand, cause?: Cause): Envelope;
17
24
  /**
18
25
  * `command` as it travels — sent by the run `cause` names, or the head of its own flow; its
19
26
  * `type` is its identity, which a bounded context gave it when it registered it.
@@ -32,6 +32,28 @@ export function eventMessageOf(event, envelope, options = {}) {
32
32
  data: { name: envelope.name, ...dataOf(event) },
33
33
  };
34
34
  }
35
+ /**
36
+ * The envelope of a Command sent through a queue — its identity is its name —, sent by the run
37
+ * `cause` names, or the head of its own flow. Its id is the Command's key: what its use case
38
+ * sends as the `Idempotency-Key` (`this.execution.causationId`), so sending it again never runs
39
+ * it twice on a server that keeps keys.
40
+ */
41
+ export function commandEnvelopeOf(command, cause) {
42
+ const known = identityOf(command);
43
+ if (known?.kind !== "command" || known.wire === undefined || known.wire.trim() === "") {
44
+ throw new TypeError(`${known?.type?.name ?? "This Command"} has no identity: a bounded context gives it one when it registers it`);
45
+ }
46
+ const id = newEntityId();
47
+ return {
48
+ name: known.wire,
49
+ id,
50
+ correlationId: cause?.correlationId ?? id,
51
+ causationId: cause?.id ?? null,
52
+ publishedAt: new Date().toISOString(),
53
+ ...(cause?.traceparent ? { traceparent: cause.traceparent } : {}),
54
+ ...(cause?.tracestate ? { tracestate: cause.tracestate } : {}),
55
+ };
56
+ }
35
57
  /**
36
58
  * `command` as it travels — sent by the run `cause` names, or the head of its own flow; its
37
59
  * `type` is its identity, which a bounded context gave it when it registered it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/client-framework",
3
- "version": "1.6.1",
3
+ "version": "1.7.0",
4
4
  "description": "The client side of sincpro_framework, for every platform: Feature and ApplicationService traced and reported by default, applications made of domains, and the typed client generated from a service's contract. No React, no DOM.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,10 +0,0 @@
1
- import type { EventStore, StoredEvent } from "../domain/store.js";
2
- /** A memory store, and what it holds — in the order added — for whoever inspects it. */
3
- export type MemoryEventStore = EventStore & {
4
- readonly events: readonly StoredEvent[];
5
- };
6
- /**
7
- * The events 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 memoryEventStore(): MemoryEventStore;