@anatta.io/tva 0.0.0-stage → 0.1.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 (176) hide show
  1. package/README.md +50 -2
  2. package/dist/actions/action-consumer.d.ts +45 -0
  3. package/dist/actions/action-consumer.js +90 -0
  4. package/dist/actions/action.d.ts +67 -0
  5. package/dist/actions/action.js +12 -0
  6. package/dist/actions/index.d.ts +3 -0
  7. package/dist/actions/index.js +4 -0
  8. package/dist/actions/run-action.d.ts +31 -0
  9. package/dist/actions/run-action.js +113 -0
  10. package/dist/adapters/cloudflare/bindings.d.ts +10 -0
  11. package/dist/adapters/cloudflare/bindings.js +1 -0
  12. package/dist/adapters/cloudflare/blob-store.d.ts +39 -0
  13. package/dist/adapters/cloudflare/blob-store.js +95 -0
  14. package/dist/adapters/cloudflare/cache.d.ts +14 -0
  15. package/dist/adapters/cloudflare/cache.js +48 -0
  16. package/dist/adapters/cloudflare/faults.d.ts +7 -0
  17. package/dist/adapters/cloudflare/faults.js +39 -0
  18. package/dist/adapters/cloudflare/index.d.ts +15 -0
  19. package/dist/adapters/cloudflare/index.js +16 -0
  20. package/dist/adapters/cloudflare/jobs.d.ts +97 -0
  21. package/dist/adapters/cloudflare/jobs.js +218 -0
  22. package/dist/adapters/cloudflare/journal.d.ts +107 -0
  23. package/dist/adapters/cloudflare/journal.js +305 -0
  24. package/dist/adapters/cloudflare/ledger.d.ts +14 -0
  25. package/dist/adapters/cloudflare/ledger.js +108 -0
  26. package/dist/adapters/cloudflare/logger.d.ts +22 -0
  27. package/dist/adapters/cloudflare/logger.js +49 -0
  28. package/dist/adapters/cloudflare/manifest.d.ts +81 -0
  29. package/dist/adapters/cloudflare/manifest.js +81 -0
  30. package/dist/adapters/cloudflare/queue.d.ts +80 -0
  31. package/dist/adapters/cloudflare/queue.js +177 -0
  32. package/dist/adapters/cloudflare/retention.d.ts +24 -0
  33. package/dist/adapters/cloudflare/retention.js +103 -0
  34. package/dist/adapters/cloudflare/session-storage.d.ts +27 -0
  35. package/dist/adapters/cloudflare/session-storage.js +78 -0
  36. package/dist/adapters/cloudflare/toolkit.d.ts +16 -0
  37. package/dist/adapters/cloudflare/toolkit.js +57 -0
  38. package/dist/adapters/cloudflare/workflow-jobs.d.ts +57 -0
  39. package/dist/adapters/cloudflare/workflow-jobs.js +319 -0
  40. package/dist/adapters/journal-records.d.ts +79 -0
  41. package/dist/adapters/journal-records.js +74 -0
  42. package/dist/adapters/memory/blob-store.d.ts +9 -0
  43. package/dist/adapters/memory/blob-store.js +19 -0
  44. package/dist/adapters/memory/cache.d.ts +13 -0
  45. package/dist/adapters/memory/cache.js +36 -0
  46. package/dist/adapters/memory/clock.d.ts +1 -0
  47. package/dist/adapters/memory/clock.js +4 -0
  48. package/dist/adapters/memory/index.d.ts +11 -0
  49. package/dist/adapters/memory/index.js +11 -0
  50. package/dist/adapters/memory/jobs.d.ts +62 -0
  51. package/dist/adapters/memory/jobs.js +219 -0
  52. package/dist/adapters/memory/journal.d.ts +34 -0
  53. package/dist/adapters/memory/journal.js +135 -0
  54. package/dist/adapters/memory/ledger.d.ts +9 -0
  55. package/dist/adapters/memory/ledger.js +33 -0
  56. package/dist/adapters/memory/logger.d.ts +16 -0
  57. package/dist/adapters/memory/logger.js +21 -0
  58. package/dist/adapters/memory/manifest.d.ts +59 -0
  59. package/dist/adapters/memory/manifest.js +59 -0
  60. package/dist/adapters/memory/queue.d.ts +20 -0
  61. package/dist/adapters/memory/queue.js +102 -0
  62. package/dist/adapters/memory/session-storage.d.ts +20 -0
  63. package/dist/adapters/memory/session-storage.js +33 -0
  64. package/dist/adapters/memory/toolkit.d.ts +8 -0
  65. package/dist/adapters/memory/toolkit.js +31 -0
  66. package/dist/adapters/postgres/cache.d.ts +17 -0
  67. package/dist/adapters/postgres/cache.js +69 -0
  68. package/dist/adapters/postgres/config.d.ts +27 -0
  69. package/dist/adapters/postgres/config.js +45 -0
  70. package/dist/adapters/postgres/faults.d.ts +14 -0
  71. package/dist/adapters/postgres/faults.js +47 -0
  72. package/dist/adapters/postgres/index.d.ts +12 -0
  73. package/dist/adapters/postgres/index.js +12 -0
  74. package/dist/adapters/postgres/journal.d.ts +83 -0
  75. package/dist/adapters/postgres/journal.js +314 -0
  76. package/dist/adapters/postgres/ledger.d.ts +16 -0
  77. package/dist/adapters/postgres/ledger.js +97 -0
  78. package/dist/adapters/postgres/logger.d.ts +19 -0
  79. package/dist/adapters/postgres/logger.js +37 -0
  80. package/dist/adapters/postgres/manifest.d.ts +52 -0
  81. package/dist/adapters/postgres/manifest.js +53 -0
  82. package/dist/adapters/postgres/migrate.d.ts +20 -0
  83. package/dist/adapters/postgres/migrate.js +96 -0
  84. package/dist/adapters/postgres/queue.d.ts +64 -0
  85. package/dist/adapters/postgres/queue.js +333 -0
  86. package/dist/adapters/postgres/retention.d.ts +18 -0
  87. package/dist/adapters/postgres/retention.js +104 -0
  88. package/dist/adapters/postgres/session-storage.d.ts +20 -0
  89. package/dist/adapters/postgres/session-storage.js +71 -0
  90. package/dist/adapters/postgres/toolkit.d.ts +25 -0
  91. package/dist/adapters/postgres/toolkit.js +58 -0
  92. package/dist/adapters/postgres/with-client.d.ts +11 -0
  93. package/dist/adapters/postgres/with-client.js +29 -0
  94. package/dist/adapters/reference-executor.d.ts +171 -0
  95. package/dist/adapters/reference-executor.js +564 -0
  96. package/dist/adapters/retention.d.ts +18 -0
  97. package/dist/adapters/retention.js +13 -0
  98. package/dist/adapters/s3/blob-store.d.ts +35 -0
  99. package/dist/adapters/s3/blob-store.js +92 -0
  100. package/dist/adapters/s3/faults.d.ts +8 -0
  101. package/dist/adapters/s3/faults.js +34 -0
  102. package/dist/adapters/s3/index.d.ts +2 -0
  103. package/dist/adapters/s3/index.js +2 -0
  104. package/dist/adapters/session-envelope.d.ts +21 -0
  105. package/dist/adapters/session-envelope.js +122 -0
  106. package/dist/adapters/system-clock.d.ts +8 -0
  107. package/dist/adapters/system-clock.js +8 -0
  108. package/dist/contracts/blob-store.d.ts +11 -0
  109. package/dist/contracts/blob-store.js +1 -0
  110. package/dist/contracts/cache.d.ts +27 -0
  111. package/dist/contracts/cache.js +1 -0
  112. package/dist/contracts/duration.d.ts +23 -0
  113. package/dist/contracts/duration.js +27 -0
  114. package/dist/contracts/faults.d.ts +28 -0
  115. package/dist/contracts/faults.js +29 -0
  116. package/dist/contracts/identity.d.ts +12 -0
  117. package/dist/contracts/identity.js +1 -0
  118. package/dist/contracts/index.d.ts +14 -0
  119. package/dist/contracts/index.js +15 -0
  120. package/dist/contracts/instant.d.ts +17 -0
  121. package/dist/contracts/instant.js +12 -0
  122. package/dist/contracts/jobs.d.ts +335 -0
  123. package/dist/contracts/jobs.js +1 -0
  124. package/dist/contracts/journal.d.ts +186 -0
  125. package/dist/contracts/journal.js +10 -0
  126. package/dist/contracts/ledger.d.ts +34 -0
  127. package/dist/contracts/ledger.js +1 -0
  128. package/dist/contracts/logger.d.ts +11 -0
  129. package/dist/contracts/logger.js +1 -0
  130. package/dist/contracts/manifest.d.ts +37 -0
  131. package/dist/contracts/manifest.js +30 -0
  132. package/dist/contracts/queue.d.ts +55 -0
  133. package/dist/contracts/queue.js +1 -0
  134. package/dist/contracts/session-storage.d.ts +18 -0
  135. package/dist/contracts/session-storage.js +1 -0
  136. package/dist/contracts/toolkit.d.ts +21 -0
  137. package/dist/contracts/toolkit.js +1 -0
  138. package/dist/schedule/schedule.d.ts +40 -0
  139. package/dist/schedule/schedule.js +135 -0
  140. package/dist/webhooks/create-webhook-handler.d.ts +63 -0
  141. package/dist/webhooks/create-webhook-handler.js +246 -0
  142. package/dist/webhooks/dead-letter-consumer.d.ts +14 -0
  143. package/dist/webhooks/dead-letter-consumer.js +42 -0
  144. package/dist/webhooks/define-registry.d.ts +42 -0
  145. package/dist/webhooks/define-registry.js +56 -0
  146. package/dist/webhooks/once.d.ts +15 -0
  147. package/dist/webhooks/once.js +29 -0
  148. package/dist/webhooks/redact-customer-bodies.d.ts +29 -0
  149. package/dist/webhooks/redact-customer-bodies.js +45 -0
  150. package/dist/webhooks/replay-webhooks.d.ts +39 -0
  151. package/dist/webhooks/replay-webhooks.js +79 -0
  152. package/dist/webhooks/sign-shopify-webhook.d.ts +14 -0
  153. package/dist/webhooks/sign-shopify-webhook.js +31 -0
  154. package/dist/webhooks/webhook-consumer.d.ts +51 -0
  155. package/dist/webhooks/webhook-consumer.js +127 -0
  156. package/migrations/0001_create_ledger_claims.sql +23 -0
  157. package/migrations/0002_create_journal.sql +76 -0
  158. package/migrations/0003_create_shopify_sessions.sql +30 -0
  159. package/migrations/0004_create_journal_steps.sql +34 -0
  160. package/migrations/0007_create_job_tables.sql +71 -0
  161. package/migrations/0008_add_ledger_completed_at.sql +7 -0
  162. package/migrations/0009_create_webhook_receipts.sql +34 -0
  163. package/migrations/0010_index_webhook_deliveries_received_at.sql +2 -0
  164. package/migrations/0011_add_webhook_task_reason_code.sql +4 -0
  165. package/migrations/postgres/0001_create_ledger_claims.sql +13 -0
  166. package/migrations/postgres/0002_create_journal.sql +48 -0
  167. package/migrations/postgres/0003_create_shopify_sessions.sql +12 -0
  168. package/migrations/postgres/0004_create_journal_steps.sql +19 -0
  169. package/migrations/postgres/0005_create_cache_entries.sql +14 -0
  170. package/migrations/postgres/0006_create_queue.sql +42 -0
  171. package/migrations/postgres/0007_create_job_tables.sql +40 -0
  172. package/migrations/postgres/0008_add_ledger_completed_at.sql +3 -0
  173. package/migrations/postgres/0009_create_webhook_receipts.sql +23 -0
  174. package/migrations/postgres/0010_index_webhook_deliveries_received_at.sql +2 -0
  175. package/migrations/postgres/0011_add_webhook_task_reason_code.sql +3 -0
  176. package/package.json +137 -4
@@ -0,0 +1,219 @@
1
+ import { toIso } from '../../contracts/index.js';
2
+ import { ReferenceExecutor } from '../reference-executor.js';
3
+ import { LOCAL_MANIFEST } from './manifest.js';
4
+ import { LocalQueue } from './queue.js';
5
+ /**
6
+ * `job_instances` and `job_steps` (decision 0006) as two Maps. Each method is
7
+ * one statement of the protocol, and none of them awaits between its read
8
+ * and its write, so each is atomic in one isolate as the D1 statement is.
9
+ */
10
+ export class MemoryJobStore {
11
+ #instances = new Map();
12
+ #steps = new Map();
13
+ async insert(row) {
14
+ if (this.#instances.has(row.instanceId)) {
15
+ return 'exists';
16
+ }
17
+ this.#instances.set(row.instanceId, row);
18
+ return 'inserted';
19
+ }
20
+ async get(id) {
21
+ return this.#instances.get(id);
22
+ }
23
+ async update(id, version, change) {
24
+ const row = this.#instances.get(id);
25
+ if (row === undefined || row.version !== version) {
26
+ return false;
27
+ }
28
+ this.#instances.set(id, { ...row, ...change, version: version + 1 });
29
+ return true;
30
+ }
31
+ async remove(id, cutoff) {
32
+ const row = this.#instances.get(id);
33
+ if (row?.endedAt == null || row.endedAt > cutoff) {
34
+ return;
35
+ }
36
+ // The order every adapter uses (ReferenceStore): results, then the row.
37
+ this.#steps.delete(id);
38
+ this.#instances.delete(id);
39
+ }
40
+ async storeResult(id, stepIndex, result, _completedAt) {
41
+ const steps = this.#steps.get(id) ?? new Map();
42
+ if (!steps.has(stepIndex)) {
43
+ steps.set(stepIndex, result);
44
+ }
45
+ this.#steps.set(id, steps);
46
+ }
47
+ async results(id) {
48
+ return new Map(this.#steps.get(id));
49
+ }
50
+ async due(now) {
51
+ return [...this.#instances.values()].filter((r) => (r.status === 'running' || r.status === 'failing') &&
52
+ r.nextWakeAt !== null &&
53
+ r.nextWakeAt <= now &&
54
+ (r.leaseExpiresAt === null || r.leaseExpiresAt <= now));
55
+ }
56
+ async removeEndedBefore(cutoff) {
57
+ for (const row of [...this.#instances.values()]) {
58
+ if (row.endedAt !== null && row.endedAt <= cutoff) {
59
+ this.#steps.delete(row.instanceId);
60
+ this.#instances.delete(row.instanceId);
61
+ }
62
+ }
63
+ }
64
+ }
65
+ /** settle() gives up rather than spin, should an instance never progress. */
66
+ const MAX_ROUNDS = 10_000;
67
+ /**
68
+ * Builds the executor. It throws when a registration is refused, as for a
69
+ * Job name outside `[A-Za-z0-9_]{1,64}`.
70
+ *
71
+ * The toolkit supplies the clock (rule 3: backoff and leases are read from
72
+ * it), the logger (rule 4) and the journal its Step rows go to.
73
+ */
74
+ export function createMemoryJobs(toolkit, options) {
75
+ const { clock, logger, journal } = toolkit;
76
+ const store = options.store ?? new MemoryJobStore();
77
+ const queue = options.queue ??
78
+ new LocalQueue({
79
+ clock,
80
+ identity: logger.identity,
81
+ maxDelaySeconds: LOCAL_MANIFEST.queueDelayMaxSeconds,
82
+ maxBytes: LOCAL_MANIFEST.messageMaxBytes,
83
+ maxAttempts: 5,
84
+ });
85
+ // WHAT settle() WAITS FOR. A consumer is in flight from its delivery to
86
+ // its last write; dispatch counts too, because it can be parked. settle()
87
+ // goes on once every consumer in flight is parked, so a consumer a test
88
+ // released is waited for and one it still holds is not.
89
+ let inflight = 0;
90
+ let parkedCount = 0;
91
+ let listeners = [];
92
+ const changed = () => {
93
+ const waiting = listeners;
94
+ listeners = [];
95
+ waiting.forEach((resolve) => {
96
+ resolve();
97
+ });
98
+ };
99
+ const nextChange = async () => new Promise((resolve) => {
100
+ listeners.push(resolve);
101
+ });
102
+ const quiet = async () => {
103
+ while (inflight > parkedCount) {
104
+ await nextChange();
105
+ }
106
+ };
107
+ const tracked = async (work) => {
108
+ inflight++;
109
+ try {
110
+ return await work();
111
+ }
112
+ finally {
113
+ inflight--;
114
+ changed();
115
+ }
116
+ };
117
+ const park = options.interrupt;
118
+ const interrupt = park === undefined
119
+ ? undefined
120
+ : (window, at) => {
121
+ const held = park(window, at);
122
+ if (held === undefined) {
123
+ return undefined;
124
+ }
125
+ parkedCount++;
126
+ changed();
127
+ return held.finally(() => {
128
+ parkedCount--;
129
+ changed();
130
+ });
131
+ };
132
+ const executor = new ReferenceExecutor({
133
+ registrations: options.registrations,
134
+ store,
135
+ queue,
136
+ clock,
137
+ logger,
138
+ journal,
139
+ manifest: LOCAL_MANIFEST,
140
+ ...(interrupt === undefined ? {} : { interrupt }),
141
+ });
142
+ /** One message, to one consumer. False when nothing was due. */
143
+ const deliverOne = async () => {
144
+ let delivered = false;
145
+ let started = () => { };
146
+ const begun = new Promise((resolve) => {
147
+ started = resolve;
148
+ });
149
+ const drained = queue.drain(async (batch) => tracked(async () => {
150
+ delivered = true;
151
+ started();
152
+ await executor.consume(batch);
153
+ }), 1);
154
+ await Promise.race([drained, begun]);
155
+ if (!delivered) {
156
+ return false;
157
+ }
158
+ await quiet();
159
+ return true;
160
+ };
161
+ let wakes = 0;
162
+ return {
163
+ dispatch: async (definition, input, dispatchOptions) => tracked(async () => executor.dispatch(definition, input, dispatchOptions)),
164
+ status: async (id) => executor.status(id),
165
+ async settle() {
166
+ for (let round = 0; round < MAX_ROUNDS; round++) {
167
+ await quiet();
168
+ await executor.sweep();
169
+ let delivered = 0;
170
+ while (await deliverOne()) {
171
+ delivered++;
172
+ }
173
+ if (delivered === 0) {
174
+ return;
175
+ }
176
+ }
177
+ throw new Error(`jobs: settle() did not converge in ${MAX_ROUNDS} rounds`);
178
+ },
179
+ async wake(id, stepIndex) {
180
+ const row = await store.get(id);
181
+ const body = {
182
+ instanceId: id,
183
+ stepIndex: stepIndex ?? row?.currentStep ?? 0,
184
+ };
185
+ const message = {
186
+ id: `wake-${++wakes}`,
187
+ body,
188
+ attempt: 1,
189
+ enqueuedAt: toIso(clock.now()),
190
+ identity: logger.identity,
191
+ };
192
+ let acked = false;
193
+ let retryDelay = 0;
194
+ const batch = {
195
+ messages: [message],
196
+ ack: () => {
197
+ acked = true;
198
+ },
199
+ retry: (_, retryOptions) => {
200
+ retryDelay = retryOptions?.delaySeconds ?? 0;
201
+ },
202
+ };
203
+ let finished = false;
204
+ const consumed = tracked(async () => {
205
+ await executor.consume(batch);
206
+ finished = true;
207
+ });
208
+ // Handled, or parked by a test.
209
+ while (!finished && inflight > parkedCount) {
210
+ await Promise.race([consumed, nextChange()]);
211
+ }
212
+ // What the queue does with a message that is not acknowledged: it
213
+ // comes back, after the delay the consumer asked for.
214
+ if (finished && !acked) {
215
+ await queue.send(body, { delaySeconds: retryDelay });
216
+ }
217
+ },
218
+ };
219
+ }
@@ -0,0 +1,34 @@
1
+ import { type CallRow, type DeliveryRow, type Instant, type Journal, type ReasonCount, type RunId, type RunRow, type StepRow, type TaskCursor, type TaskRow, type TaskState, type UnitKey, type UnitRow } from '../../contracts/index.js';
2
+ export declare class MemoryJournal implements Journal {
3
+ #private;
4
+ startRun(row: RunRow): Promise<void>;
5
+ finishRun(runId: RunId, endedAt: Instant): Promise<void>;
6
+ recordUnit(unit: UnitRow, calls: readonly CallRow[]): Promise<void>;
7
+ /**
8
+ * An array push cannot fail, so there is nothing to log. The never-rejects
9
+ * promise is kept by construction here, and by a catch in the adapters whose
10
+ * storage can fail.
11
+ */
12
+ recordStep(step: StepRow): Promise<void>;
13
+ unitsForRun(runId: RunId, limit?: number): Promise<readonly UnitRow[]>;
14
+ unit(runId: RunId, unitKey: UnitKey): Promise<{
15
+ unit: UnitRow;
16
+ steps: readonly StepRow[];
17
+ calls: readonly CallRow[];
18
+ } | undefined>;
19
+ latestForUnit(unitKey: UnitKey): Promise<UnitRow | undefined>;
20
+ failuresByReason(since: Instant): Promise<readonly ReasonCount[]>;
21
+ recentRuns(limit?: number): Promise<readonly RunRow[]>;
22
+ recordDelivery(delivery: DeliveryRow, actions: readonly string[]): Promise<void>;
23
+ moveTask(deliveryId: string, action: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
24
+ delivery(deliveryId: string): Promise<{
25
+ delivery: DeliveryRow;
26
+ tasks: readonly TaskRow[];
27
+ } | undefined>;
28
+ deadTasks({ action, after, limit, }?: {
29
+ readonly action?: string;
30
+ readonly after?: TaskCursor;
31
+ readonly limit?: number;
32
+ }): Promise<readonly TaskRow[]>;
33
+ stuckTasks(before: Instant, limit?: number): Promise<readonly TaskRow[]>;
34
+ }
@@ -0,0 +1,135 @@
1
+ import { TASK_TRANSITIONS, } from '../../contracts/index.js';
2
+ /** The SQL adapters' order: updated_at, then delivery_id, then action. Strings by code unit, as D1 does; Postgres uses its collation. */
3
+ const byTaskOrder = (a, b) => a.updatedAt - b.updatedAt ||
4
+ (a.deliveryId < b.deliveryId ? -1 : a.deliveryId > b.deliveryId ? 1 : 0) ||
5
+ (a.action < b.action ? -1 : a.action > b.action ? 1 : 0);
6
+ export class MemoryJournal {
7
+ #runs = new Map();
8
+ #units = [];
9
+ #calls = [];
10
+ #steps = [];
11
+ #deliveries = new Map();
12
+ #tasks = new Map();
13
+ async startRun(row) {
14
+ this.#runs.set(row.runId, row);
15
+ }
16
+ async finishRun(runId, endedAt) {
17
+ const r = this.#runs.get(runId);
18
+ if (r !== undefined) {
19
+ this.#runs.set(runId, { ...r, endedAt });
20
+ }
21
+ }
22
+ async recordUnit(unit, calls) {
23
+ this.#units.push(unit);
24
+ this.#calls.push(...calls);
25
+ }
26
+ /**
27
+ * An array push cannot fail, so there is nothing to log. The never-rejects
28
+ * promise is kept by construction here, and by a catch in the adapters whose
29
+ * storage can fail.
30
+ */
31
+ async recordStep(step) {
32
+ this.#steps.push(step);
33
+ }
34
+ async unitsForRun(runId, limit = 100) {
35
+ return this.#units
36
+ .filter((u) => u.runId === runId)
37
+ .sort((a, b) => a.unitKey.localeCompare(b.unitKey)) // stable order; the suite asserts it
38
+ .slice(0, limit);
39
+ }
40
+ async unit(runId, unitKey) {
41
+ const unit = this.#units.find((u) => u.runId === runId && u.unitKey === unitKey);
42
+ if (unit === undefined) {
43
+ return undefined;
44
+ }
45
+ return {
46
+ unit,
47
+ // Array.prototype.sort is stable, so equal instants keep write order.
48
+ steps: this.#steps
49
+ .filter((s) => s.runId === runId && s.unitKey === unitKey)
50
+ .sort((a, b) => a.recordedAt - b.recordedAt),
51
+ calls: this.#calls.filter((c) => c.runId === runId && c.unitKey === unitKey),
52
+ };
53
+ }
54
+ async latestForUnit(unitKey) {
55
+ return [...this.#units].reverse().find((u) => u.unitKey === unitKey);
56
+ }
57
+ async failuresByReason(since) {
58
+ const counts = new Map();
59
+ for (const u of this.#units) {
60
+ if (u.recordedAt < since) {
61
+ continue;
62
+ }
63
+ if (u.outcome === 'written' || u.reasonCode === undefined) {
64
+ continue;
65
+ }
66
+ counts.set(u.reasonCode, (counts.get(u.reasonCode) ?? 0) + 1);
67
+ }
68
+ return [...counts]
69
+ .map(([reasonCode, count]) => ({ reasonCode, count }))
70
+ .sort((a, b) => b.count - a.count || a.reasonCode.localeCompare(b.reasonCode));
71
+ }
72
+ async recentRuns(limit = 20) {
73
+ return [...this.#runs.values()]
74
+ .sort((a, b) => b.startedAt - a.startedAt)
75
+ .slice(0, limit);
76
+ }
77
+ async recordDelivery(delivery, actions) {
78
+ if (!this.#deliveries.has(delivery.deliveryId)) {
79
+ this.#deliveries.set(delivery.deliveryId, delivery);
80
+ }
81
+ for (const action of actions) {
82
+ const key = JSON.stringify([delivery.deliveryId, action]);
83
+ if (!this.#tasks.has(key)) {
84
+ this.#tasks.set(key, {
85
+ deliveryId: delivery.deliveryId,
86
+ action,
87
+ state: 'received',
88
+ updatedAt: delivery.receivedAt,
89
+ });
90
+ }
91
+ }
92
+ }
93
+ async moveTask(deliveryId, action, to, at, reasonCode) {
94
+ const key = JSON.stringify([deliveryId, action]);
95
+ const task = this.#tasks.get(key);
96
+ if (task === undefined || !TASK_TRANSITIONS[to].includes(task.state)) {
97
+ return false;
98
+ }
99
+ const { reasonCode: _cleared, ...rest } = task;
100
+ this.#tasks.set(key, {
101
+ ...rest,
102
+ state: to,
103
+ updatedAt: at,
104
+ ...(reasonCode === undefined ? {} : { reasonCode }),
105
+ });
106
+ return true;
107
+ }
108
+ async delivery(deliveryId) {
109
+ const delivery = this.#deliveries.get(deliveryId);
110
+ if (delivery === undefined) {
111
+ return undefined;
112
+ }
113
+ return {
114
+ delivery,
115
+ tasks: [...this.#tasks.values()]
116
+ .filter((t) => t.deliveryId === deliveryId)
117
+ .sort((a, b) => (a.action < b.action ? -1 : 1)),
118
+ };
119
+ }
120
+ async deadTasks({ action, after, limit = 100, } = {}) {
121
+ return [...this.#tasks.values()]
122
+ .filter((t) => t.state === 'dead' &&
123
+ (action === undefined || t.action === action) &&
124
+ (after === undefined || byTaskOrder(t, after) > 0))
125
+ .sort(byTaskOrder)
126
+ .slice(0, limit);
127
+ }
128
+ async stuckTasks(before, limit = 100) {
129
+ return [...this.#tasks.values()]
130
+ .filter((t) => (t.state === 'received' || t.state === 'processing') &&
131
+ t.updatedAt < before)
132
+ .sort(byTaskOrder)
133
+ .slice(0, limit);
134
+ }
135
+ }
@@ -0,0 +1,9 @@
1
+ import type { ClaimResult, Clock, Ledger } from '../../contracts/index.js';
2
+ export declare class LocalLedger implements Ledger {
3
+ #private;
4
+ private readonly clock;
5
+ constructor(clock: Clock);
6
+ claim(key: string, leaseSeconds: number): Promise<ClaimResult>;
7
+ complete(key: string, ttlSeconds: number): Promise<void>;
8
+ release(key: string): Promise<void>;
9
+ }
@@ -0,0 +1,33 @@
1
+ import { fromEpochMs, toIso } from '../../contracts/index.js';
2
+ export class LocalLedger {
3
+ clock;
4
+ #claims = new Map();
5
+ constructor(clock) {
6
+ this.clock = clock;
7
+ }
8
+ async claim(key, leaseSeconds) {
9
+ const now = this.clock.now();
10
+ const existing = this.#claims.get(key);
11
+ if (existing !== undefined && existing.expiresAt > now) {
12
+ return existing.completedAt === undefined
13
+ ? { status: 'in-progress', claimedAt: toIso(existing.claimedAt) }
14
+ : { status: 'completed', completedAt: toIso(existing.completedAt) };
15
+ }
16
+ this.#claims.set(key, {
17
+ claimedAt: now,
18
+ expiresAt: fromEpochMs(now + leaseSeconds * 1000),
19
+ });
20
+ return { status: 'claimed' };
21
+ }
22
+ async complete(key, ttlSeconds) {
23
+ const now = this.clock.now();
24
+ this.#claims.set(key, {
25
+ claimedAt: this.#claims.get(key)?.claimedAt ?? now,
26
+ completedAt: now,
27
+ expiresAt: fromEpochMs(now + ttlSeconds * 1000),
28
+ });
29
+ }
30
+ async release(key) {
31
+ this.#claims.delete(key);
32
+ }
33
+ }
@@ -0,0 +1,16 @@
1
+ import type { DeploymentIdentity, LogFields, Logger } from '../../contracts/index.js';
2
+ export type Captured = {
3
+ level: 'info' | 'warn' | 'error';
4
+ message: string;
5
+ fields: LogFields;
6
+ };
7
+ export declare class MemoryLogger implements Logger {
8
+ readonly identity: DeploymentIdentity;
9
+ readonly correlationId: string;
10
+ readonly entries: Captured[];
11
+ constructor(identity: DeploymentIdentity, correlationId: string);
12
+ info(message: string, fields?: LogFields): void;
13
+ warn(message: string, fields?: LogFields): void;
14
+ error(message: string, fields?: LogFields): void;
15
+ child(correlationId: string): Logger;
16
+ }
@@ -0,0 +1,21 @@
1
+ export class MemoryLogger {
2
+ identity;
3
+ correlationId;
4
+ entries = [];
5
+ constructor(identity, correlationId) {
6
+ this.identity = identity;
7
+ this.correlationId = correlationId;
8
+ }
9
+ info(message, fields = {}) {
10
+ this.entries.push({ level: 'info', message, fields });
11
+ }
12
+ warn(message, fields = {}) {
13
+ this.entries.push({ level: 'warn', message, fields });
14
+ }
15
+ error(message, fields = {}) {
16
+ this.entries.push({ level: 'error', message, fields });
17
+ }
18
+ child(correlationId) {
19
+ return new MemoryLogger(this.identity, correlationId);
20
+ }
21
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * WHAT THE IN-MEMORY ADAPTER ACTUALLY PROVIDES.
3
+ *
4
+ * A manifest that lies is worse than no manifest: with none, a requirement is
5
+ * checked by a person; with one that overstates the target, `satisfies()`
6
+ * certifies a guarantee nothing implements, and the check that exists to stop
7
+ * an incident becomes the thing that causes one.
8
+ *
9
+ * `lock` and `lockFencing` both used to overstate this adapter. The reasoning
10
+ * that corrected them is in docs/decisions/0002, and the behaviour it rests on
11
+ * is pinned in manifest.spec.ts rather than argued here.
12
+ */
13
+ export declare const LOCAL_MANIFEST: {
14
+ /**
15
+ * `advisory`, not `strict`, and the reason has nothing to do with being
16
+ * in-memory. `Ledger.claim(key, leaseSeconds)` is a LEASE. A holder that is
17
+ * still working when its lease elapses does not stop being a holder, and the
18
+ * next claim succeeds:
19
+ *
20
+ * claim('k', 10) -> claimed holder A starts work
21
+ * ...11 seconds later... one slow call, no bug
22
+ * claim('k', 10) -> claimed holder B, while A is still running
23
+ *
24
+ * Two holders, one process, no concurrency involved — and that is the
25
+ * conformance suite's *required* behaviour, not a defect. `docs/design.md`
26
+ * §6.1 has said all along that a lease with a TTL is not a strict lock; it
27
+ * has no single-process exemption, because it never needed one.
28
+ *
29
+ * §8.2 says the strict lock is `KeyedLock` — a Map here, a Durable Object on
30
+ * Cloudflare. That interface does not exist yet, and when it does this
31
+ * becomes a manifest change with its own issue.
32
+ */
33
+ readonly lock: "advisory";
34
+ /**
35
+ * `false`. `ClaimResult` is `{ status: 'claimed' }` and carries no token, so
36
+ * there is nothing for a holder to present to a downstream write and nothing
37
+ * for that write to reject when it is stale.
38
+ *
39
+ * No adapter can declare otherwise, which is the point: this is not a gap in
40
+ * the in-memory implementation, it is the shape of the interface.
41
+ */
42
+ readonly lockFencing: false;
43
+ readonly queueDelayMaxSeconds: 604800;
44
+ readonly messageMaxBytes: 1000000;
45
+ readonly blobMaxBytes: 100000000;
46
+ readonly cacheMinTtlSeconds: 1;
47
+ /**
48
+ * 1 MiB, the same as Workflows, and deliberately not larger although a Map
49
+ * has no ceiling. A Job definition is written once and run here locally and
50
+ * on Workflows when deployed. A larger local limit would let a step pass
51
+ * every local test and fail in production, which is the failure decision
52
+ * 0003 found when local Queues enforced nothing.
53
+ */
54
+ readonly stepResultMaxBytes: 1048576;
55
+ readonly journalDialect: "sqlite";
56
+ readonly scheduleTimezone: "resolved-in-code";
57
+ /** Tests drive the clock, so the library's floor: one whole second. */
58
+ readonly scheduleMinIntervalSeconds: 1;
59
+ };
@@ -0,0 +1,59 @@
1
+ /**
2
+ * WHAT THE IN-MEMORY ADAPTER ACTUALLY PROVIDES.
3
+ *
4
+ * A manifest that lies is worse than no manifest: with none, a requirement is
5
+ * checked by a person; with one that overstates the target, `satisfies()`
6
+ * certifies a guarantee nothing implements, and the check that exists to stop
7
+ * an incident becomes the thing that causes one.
8
+ *
9
+ * `lock` and `lockFencing` both used to overstate this adapter. The reasoning
10
+ * that corrected them is in docs/decisions/0002, and the behaviour it rests on
11
+ * is pinned in manifest.spec.ts rather than argued here.
12
+ */
13
+ export const LOCAL_MANIFEST = {
14
+ /**
15
+ * `advisory`, not `strict`, and the reason has nothing to do with being
16
+ * in-memory. `Ledger.claim(key, leaseSeconds)` is a LEASE. A holder that is
17
+ * still working when its lease elapses does not stop being a holder, and the
18
+ * next claim succeeds:
19
+ *
20
+ * claim('k', 10) -> claimed holder A starts work
21
+ * ...11 seconds later... one slow call, no bug
22
+ * claim('k', 10) -> claimed holder B, while A is still running
23
+ *
24
+ * Two holders, one process, no concurrency involved — and that is the
25
+ * conformance suite's *required* behaviour, not a defect. `docs/design.md`
26
+ * §6.1 has said all along that a lease with a TTL is not a strict lock; it
27
+ * has no single-process exemption, because it never needed one.
28
+ *
29
+ * §8.2 says the strict lock is `KeyedLock` — a Map here, a Durable Object on
30
+ * Cloudflare. That interface does not exist yet, and when it does this
31
+ * becomes a manifest change with its own issue.
32
+ */
33
+ lock: 'advisory',
34
+ /**
35
+ * `false`. `ClaimResult` is `{ status: 'claimed' }` and carries no token, so
36
+ * there is nothing for a holder to present to a downstream write and nothing
37
+ * for that write to reject when it is stale.
38
+ *
39
+ * No adapter can declare otherwise, which is the point: this is not a gap in
40
+ * the in-memory implementation, it is the shape of the interface.
41
+ */
42
+ lockFencing: false,
43
+ queueDelayMaxSeconds: 604_800,
44
+ messageMaxBytes: 1_000_000,
45
+ blobMaxBytes: 100_000_000,
46
+ cacheMinTtlSeconds: 1,
47
+ /**
48
+ * 1 MiB, the same as Workflows, and deliberately not larger although a Map
49
+ * has no ceiling. A Job definition is written once and run here locally and
50
+ * on Workflows when deployed. A larger local limit would let a step pass
51
+ * every local test and fail in production, which is the failure decision
52
+ * 0003 found when local Queues enforced nothing.
53
+ */
54
+ stepResultMaxBytes: 1_048_576,
55
+ journalDialect: 'sqlite',
56
+ scheduleTimezone: 'resolved-in-code',
57
+ /** Tests drive the clock, so the library's floor: one whole second. */
58
+ scheduleMinIntervalSeconds: 1,
59
+ };
@@ -0,0 +1,20 @@
1
+ import type { Clock, MessageId, Queue, QueueBatch, SendOptions, DeploymentIdentity } from '../../contracts/index.js';
2
+ export type LocalQueueOptions = {
3
+ readonly clock: Clock;
4
+ readonly identity: DeploymentIdentity;
5
+ readonly maxDelaySeconds: number;
6
+ readonly maxBytes: number;
7
+ readonly maxAttempts: number;
8
+ };
9
+ export declare class LocalQueue<T> implements Queue<T> {
10
+ #private;
11
+ private readonly o;
12
+ constructor(o: LocalQueueOptions);
13
+ send(body: T, options?: SendOptions): Promise<MessageId>;
14
+ sendBatch(bodies: readonly T[], options?: SendOptions): Promise<readonly MessageId[]>;
15
+ /** Test and dev only. Deliberately NOT on the Queue contract. */
16
+ drain(consumer: (batch: QueueBatch<T>) => Promise<void>, batchSize?: number): Promise<void>;
17
+ pendingCount(): number;
18
+ deadCount(): number;
19
+ dead(): readonly T[];
20
+ }