@sincpro/client-framework 1.6.0 → 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.
Files changed (36) hide show
  1. package/AGENTS.md +21 -6
  2. package/README.md +46 -28
  3. package/dist/client/adapters/json-rpc.js +3 -2
  4. package/dist/client/adapters/memory.js +3 -2
  5. package/dist/client/adapters/rest-operations.js +3 -2
  6. package/dist/client/adapters/rest.js +3 -2
  7. package/dist/client/index.d.ts +1 -1
  8. package/dist/client/index.js +1 -1
  9. package/dist/client/services/guarded.js +4 -3
  10. package/dist/client/services/propagation.d.ts +21 -9
  11. package/dist/client/services/propagation.js +60 -3
  12. package/dist/core/entrypoint/screens.js +2 -1
  13. package/dist/core/services/binding.d.ts +5 -2
  14. package/dist/core/services/binding.js +5 -8
  15. package/dist/event_driven/adapters/memory-message-store.d.ts +10 -0
  16. package/dist/event_driven/adapters/{memory-event-store.js → memory-message-store.js} +3 -3
  17. package/dist/event_driven/adapters/stored-queue.d.ts +51 -42
  18. package/dist/event_driven/adapters/stored-queue.js +137 -89
  19. package/dist/event_driven/adapters/sync-queue.d.ts +4 -3
  20. package/dist/event_driven/adapters/sync-queue.js +11 -5
  21. package/dist/event_driven/domain/queue.d.ts +19 -10
  22. package/dist/event_driven/domain/store.d.ts +26 -21
  23. package/dist/event_driven/domain/verdict.d.ts +86 -0
  24. package/dist/event_driven/domain/verdict.js +80 -0
  25. package/dist/event_driven/entrypoint/publisher.d.ts +14 -8
  26. package/dist/event_driven/entrypoint/publisher.js +16 -5
  27. package/dist/event_driven/entrypoint/subscriber.d.ts +9 -1
  28. package/dist/event_driven/entrypoint/subscriber.js +16 -5
  29. package/dist/event_driven/index.d.ts +13 -12
  30. package/dist/event_driven/index.js +11 -10
  31. package/dist/event_driven/services/messages.d.ts +7 -0
  32. package/dist/event_driven/services/messages.js +22 -0
  33. package/dist/observability/adapters/console.d.ts +0 -4
  34. package/dist/observability/adapters/console.js +12 -4
  35. package/package.json +1 -1
  36. package/dist/event_driven/adapters/memory-event-store.d.ts +0 -10
@@ -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
  };