@anatta.io/tva 0.0.0-stage → 0.2.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 (190) hide show
  1. package/README.md +50 -2
  2. package/dist/adapters/cloudflare/bindings.d.ts +10 -0
  3. package/dist/adapters/cloudflare/bindings.js +1 -0
  4. package/dist/adapters/cloudflare/blob-store.d.ts +39 -0
  5. package/dist/adapters/cloudflare/blob-store.js +95 -0
  6. package/dist/adapters/cloudflare/cache.d.ts +14 -0
  7. package/dist/adapters/cloudflare/cache.js +48 -0
  8. package/dist/adapters/cloudflare/faults.d.ts +7 -0
  9. package/dist/adapters/cloudflare/faults.js +39 -0
  10. package/dist/adapters/cloudflare/index.d.ts +15 -0
  11. package/dist/adapters/cloudflare/index.js +16 -0
  12. package/dist/adapters/cloudflare/journal.d.ts +110 -0
  13. package/dist/adapters/cloudflare/journal.js +325 -0
  14. package/dist/adapters/cloudflare/ledger.d.ts +14 -0
  15. package/dist/adapters/cloudflare/ledger.js +108 -0
  16. package/dist/adapters/cloudflare/logger.d.ts +22 -0
  17. package/dist/adapters/cloudflare/logger.js +49 -0
  18. package/dist/adapters/cloudflare/manifest.d.ts +81 -0
  19. package/dist/adapters/cloudflare/manifest.js +81 -0
  20. package/dist/adapters/cloudflare/pipelines.d.ts +97 -0
  21. package/dist/adapters/cloudflare/pipelines.js +218 -0
  22. package/dist/adapters/cloudflare/queue.d.ts +80 -0
  23. package/dist/adapters/cloudflare/queue.js +177 -0
  24. package/dist/adapters/cloudflare/retention.d.ts +24 -0
  25. package/dist/adapters/cloudflare/retention.js +103 -0
  26. package/dist/adapters/cloudflare/session-storage.d.ts +27 -0
  27. package/dist/adapters/cloudflare/session-storage.js +78 -0
  28. package/dist/adapters/cloudflare/toolkit.d.ts +16 -0
  29. package/dist/adapters/cloudflare/toolkit.js +57 -0
  30. package/dist/adapters/cloudflare/workflow-pipelines.d.ts +66 -0
  31. package/dist/adapters/cloudflare/workflow-pipelines.js +323 -0
  32. package/dist/adapters/journal-records.d.ts +80 -0
  33. package/dist/adapters/journal-records.js +75 -0
  34. package/dist/adapters/memory/blob-store.d.ts +9 -0
  35. package/dist/adapters/memory/blob-store.js +19 -0
  36. package/dist/adapters/memory/cache.d.ts +13 -0
  37. package/dist/adapters/memory/cache.js +36 -0
  38. package/dist/adapters/memory/clock.d.ts +1 -0
  39. package/dist/adapters/memory/clock.js +4 -0
  40. package/dist/adapters/memory/index.d.ts +11 -0
  41. package/dist/adapters/memory/index.js +11 -0
  42. package/dist/adapters/memory/journal.d.ts +35 -0
  43. package/dist/adapters/memory/journal.js +154 -0
  44. package/dist/adapters/memory/ledger.d.ts +9 -0
  45. package/dist/adapters/memory/ledger.js +33 -0
  46. package/dist/adapters/memory/logger.d.ts +16 -0
  47. package/dist/adapters/memory/logger.js +21 -0
  48. package/dist/adapters/memory/manifest.d.ts +59 -0
  49. package/dist/adapters/memory/manifest.js +59 -0
  50. package/dist/adapters/memory/pipelines.d.ts +62 -0
  51. package/dist/adapters/memory/pipelines.js +219 -0
  52. package/dist/adapters/memory/queue.d.ts +20 -0
  53. package/dist/adapters/memory/queue.js +102 -0
  54. package/dist/adapters/memory/session-storage.d.ts +20 -0
  55. package/dist/adapters/memory/session-storage.js +33 -0
  56. package/dist/adapters/memory/toolkit.d.ts +8 -0
  57. package/dist/adapters/memory/toolkit.js +31 -0
  58. package/dist/adapters/postgres/cache.d.ts +17 -0
  59. package/dist/adapters/postgres/cache.js +69 -0
  60. package/dist/adapters/postgres/config.d.ts +27 -0
  61. package/dist/adapters/postgres/config.js +45 -0
  62. package/dist/adapters/postgres/faults.d.ts +14 -0
  63. package/dist/adapters/postgres/faults.js +47 -0
  64. package/dist/adapters/postgres/index.d.ts +12 -0
  65. package/dist/adapters/postgres/index.js +12 -0
  66. package/dist/adapters/postgres/journal.d.ts +86 -0
  67. package/dist/adapters/postgres/journal.js +337 -0
  68. package/dist/adapters/postgres/ledger.d.ts +16 -0
  69. package/dist/adapters/postgres/ledger.js +97 -0
  70. package/dist/adapters/postgres/logger.d.ts +19 -0
  71. package/dist/adapters/postgres/logger.js +37 -0
  72. package/dist/adapters/postgres/manifest.d.ts +52 -0
  73. package/dist/adapters/postgres/manifest.js +53 -0
  74. package/dist/adapters/postgres/migrate.d.ts +20 -0
  75. package/dist/adapters/postgres/migrate.js +96 -0
  76. package/dist/adapters/postgres/queue.d.ts +64 -0
  77. package/dist/adapters/postgres/queue.js +333 -0
  78. package/dist/adapters/postgres/retention.d.ts +18 -0
  79. package/dist/adapters/postgres/retention.js +104 -0
  80. package/dist/adapters/postgres/session-storage.d.ts +20 -0
  81. package/dist/adapters/postgres/session-storage.js +71 -0
  82. package/dist/adapters/postgres/toolkit.d.ts +25 -0
  83. package/dist/adapters/postgres/toolkit.js +58 -0
  84. package/dist/adapters/postgres/with-client.d.ts +11 -0
  85. package/dist/adapters/postgres/with-client.js +29 -0
  86. package/dist/adapters/reference-executor.d.ts +171 -0
  87. package/dist/adapters/reference-executor.js +569 -0
  88. package/dist/adapters/retention.d.ts +18 -0
  89. package/dist/adapters/retention.js +13 -0
  90. package/dist/adapters/s3/blob-store.d.ts +35 -0
  91. package/dist/adapters/s3/blob-store.js +92 -0
  92. package/dist/adapters/s3/faults.d.ts +8 -0
  93. package/dist/adapters/s3/faults.js +34 -0
  94. package/dist/adapters/s3/index.d.ts +2 -0
  95. package/dist/adapters/s3/index.js +2 -0
  96. package/dist/adapters/session-envelope.d.ts +21 -0
  97. package/dist/adapters/session-envelope.js +122 -0
  98. package/dist/adapters/system-clock.d.ts +8 -0
  99. package/dist/adapters/system-clock.js +8 -0
  100. package/dist/contracts/blob-store.d.ts +11 -0
  101. package/dist/contracts/blob-store.js +1 -0
  102. package/dist/contracts/cache.d.ts +27 -0
  103. package/dist/contracts/cache.js +1 -0
  104. package/dist/contracts/duration.d.ts +23 -0
  105. package/dist/contracts/duration.js +27 -0
  106. package/dist/contracts/faults.d.ts +28 -0
  107. package/dist/contracts/faults.js +29 -0
  108. package/dist/contracts/identity.d.ts +12 -0
  109. package/dist/contracts/identity.js +1 -0
  110. package/dist/contracts/index.d.ts +14 -0
  111. package/dist/contracts/index.js +15 -0
  112. package/dist/contracts/instant.d.ts +17 -0
  113. package/dist/contracts/instant.js +12 -0
  114. package/dist/contracts/journal.d.ts +196 -0
  115. package/dist/contracts/journal.js +10 -0
  116. package/dist/contracts/ledger.d.ts +34 -0
  117. package/dist/contracts/ledger.js +1 -0
  118. package/dist/contracts/logger.d.ts +11 -0
  119. package/dist/contracts/logger.js +1 -0
  120. package/dist/contracts/manifest.d.ts +37 -0
  121. package/dist/contracts/manifest.js +30 -0
  122. package/dist/contracts/pipelines.d.ts +348 -0
  123. package/dist/contracts/pipelines.js +1 -0
  124. package/dist/contracts/queue.d.ts +55 -0
  125. package/dist/contracts/queue.js +1 -0
  126. package/dist/contracts/session-storage.d.ts +18 -0
  127. package/dist/contracts/session-storage.js +1 -0
  128. package/dist/contracts/toolkit.d.ts +21 -0
  129. package/dist/contracts/toolkit.js +1 -0
  130. package/dist/pipelines/index.d.ts +1 -0
  131. package/dist/pipelines/index.js +2 -0
  132. package/dist/pipelines/pipeline.d.ts +142 -0
  133. package/dist/pipelines/pipeline.js +140 -0
  134. package/dist/pipelines/use-case-step.d.ts +24 -0
  135. package/dist/pipelines/use-case-step.js +34 -0
  136. package/dist/schedule/schedule.d.ts +40 -0
  137. package/dist/schedule/schedule.js +135 -0
  138. package/dist/use-cases/index.d.ts +3 -0
  139. package/dist/use-cases/index.js +3 -0
  140. package/dist/use-cases/run-use-case.d.ts +33 -0
  141. package/dist/use-cases/run-use-case.js +117 -0
  142. package/dist/use-cases/use-case-consumer.d.ts +44 -0
  143. package/dist/use-cases/use-case-consumer.js +98 -0
  144. package/dist/use-cases/use-case.d.ts +116 -0
  145. package/dist/use-cases/use-case.js +75 -0
  146. package/dist/webhooks/create-webhook-handler.d.ts +63 -0
  147. package/dist/webhooks/create-webhook-handler.js +253 -0
  148. package/dist/webhooks/dead-letter-consumer.d.ts +14 -0
  149. package/dist/webhooks/dead-letter-consumer.js +42 -0
  150. package/dist/webhooks/define-registry.d.ts +42 -0
  151. package/dist/webhooks/define-registry.js +56 -0
  152. package/dist/webhooks/once.d.ts +15 -0
  153. package/dist/webhooks/once.js +29 -0
  154. package/dist/webhooks/redact-customer-bodies.d.ts +29 -0
  155. package/dist/webhooks/redact-customer-bodies.js +45 -0
  156. package/dist/webhooks/replay-webhooks.d.ts +39 -0
  157. package/dist/webhooks/replay-webhooks.js +82 -0
  158. package/dist/webhooks/sign-shopify-webhook.d.ts +14 -0
  159. package/dist/webhooks/sign-shopify-webhook.js +31 -0
  160. package/dist/webhooks/sweep-stuck-tasks.d.ts +32 -0
  161. package/dist/webhooks/sweep-stuck-tasks.js +73 -0
  162. package/dist/webhooks/webhook-consumer.d.ts +52 -0
  163. package/dist/webhooks/webhook-consumer.js +132 -0
  164. package/migrations/0001_create_ledger_claims.sql +23 -0
  165. package/migrations/0002_create_journal.sql +76 -0
  166. package/migrations/0003_create_shopify_sessions.sql +30 -0
  167. package/migrations/0004_create_journal_steps.sql +34 -0
  168. package/migrations/0007_create_job_tables.sql +71 -0
  169. package/migrations/0008_add_ledger_completed_at.sql +7 -0
  170. package/migrations/0009_create_webhook_receipts.sql +34 -0
  171. package/migrations/0010_index_webhook_deliveries_received_at.sql +2 -0
  172. package/migrations/0011_add_webhook_task_reason_code.sql +4 -0
  173. package/migrations/0012_rename_webhook_task_action_to_use_case.sql +11 -0
  174. package/migrations/0013_rename_job_tables_to_pipeline.sql +24 -0
  175. package/migrations/0016_add_webhook_task_requeues.sql +3 -0
  176. package/migrations/postgres/0001_create_ledger_claims.sql +13 -0
  177. package/migrations/postgres/0002_create_journal.sql +48 -0
  178. package/migrations/postgres/0003_create_shopify_sessions.sql +12 -0
  179. package/migrations/postgres/0004_create_journal_steps.sql +19 -0
  180. package/migrations/postgres/0005_create_cache_entries.sql +14 -0
  181. package/migrations/postgres/0006_create_queue.sql +42 -0
  182. package/migrations/postgres/0007_create_job_tables.sql +40 -0
  183. package/migrations/postgres/0008_add_ledger_completed_at.sql +3 -0
  184. package/migrations/postgres/0009_create_webhook_receipts.sql +23 -0
  185. package/migrations/postgres/0010_index_webhook_deliveries_received_at.sql +2 -0
  186. package/migrations/postgres/0011_add_webhook_task_reason_code.sql +3 -0
  187. package/migrations/postgres/0012_rename_webhook_task_action_to_use_case.sql +5 -0
  188. package/migrations/postgres/0013_rename_job_tables_to_pipeline.sql +22 -0
  189. package/migrations/postgres/0016_add_webhook_task_requeues.sql +3 -0
  190. package/package.json +144 -4
@@ -0,0 +1,80 @@
1
+ import type { CallRow, DeliveryRow, RunRow, StepRow, TaskCursor, TaskRow, UnitRow } from '../contracts/index.js';
2
+ /**
3
+ * The journal tables' rows, as both SQL adapters read them. The tables are the
4
+ * same on D1 and Postgres (a parity test holds them so), so the mapping lives
5
+ * above both rather than once in each, where the two copies would drift.
6
+ *
7
+ * A BIGINT column arrives as a string from node-postgres and as a number from
8
+ * D1, so every epoch or duration goes through Number(). Exact up to 2^53 ms.
9
+ * docs/decisions/0007.
10
+ */
11
+ type Big = number | string;
12
+ export type RunRecord = {
13
+ run_id: string;
14
+ job: string;
15
+ trigger: string;
16
+ mode: string;
17
+ started_at: Big;
18
+ identity: string;
19
+ };
20
+ export type UnitRecord = {
21
+ run_id: string;
22
+ unit_key: string;
23
+ unit_type: string;
24
+ recorded_at: Big;
25
+ outcome: string;
26
+ reason_code: string | null;
27
+ plan_hash: string | null;
28
+ plan_ref: string | null;
29
+ duration_ms: Big;
30
+ external_ids: string | null;
31
+ };
32
+ export type StepRecord = {
33
+ run_id: string;
34
+ unit_key: string;
35
+ step: string;
36
+ attempt: number;
37
+ outcome: string;
38
+ reason_code: string | null;
39
+ duration_ms: Big;
40
+ recorded_at: Big;
41
+ };
42
+ export type CallRecord = {
43
+ run_id: string;
44
+ unit_key: string;
45
+ system: string;
46
+ operation: string;
47
+ status: string;
48
+ http_status: number | null;
49
+ idempotency_key: string | null;
50
+ duration_ms: Big | null;
51
+ };
52
+ export type DeliveryRecord = {
53
+ delivery_id: string;
54
+ source: string;
55
+ topic: string;
56
+ shop: string;
57
+ webhook_id: string;
58
+ body_key: string;
59
+ received_at: Big;
60
+ };
61
+ export type TaskRecord = {
62
+ delivery_id: string;
63
+ use_case: string;
64
+ state: string;
65
+ updated_at: Big;
66
+ reason_code: string | null;
67
+ requeues: number;
68
+ };
69
+ /** The same defaults the memory adapter uses, so a limit means one thing. */
70
+ export declare const DEFAULT_UNIT_LIMIT = 100;
71
+ export declare const DEFAULT_RUN_LIMIT = 20;
72
+ export declare const toRunRow: (r: RunRecord) => RunRow;
73
+ export declare const toUnitRow: (r: UnitRecord) => UnitRow;
74
+ export declare const toStepRow: (r: StepRecord) => StepRow;
75
+ export declare const toCallRow: (r: CallRecord) => CallRow;
76
+ export declare const toDeliveryRow: (r: DeliveryRecord) => DeliveryRow;
77
+ export declare const toTaskRow: (r: TaskRecord) => TaskRow;
78
+ /** Before every real row, so a first page needs no second query. */
79
+ export declare const FIRST_TASK: TaskCursor;
80
+ export {};
@@ -0,0 +1,75 @@
1
+ import { fromEpochMs } from '../contracts/index.js';
2
+ /** The same defaults the memory adapter uses, so a limit means one thing. */
3
+ export const DEFAULT_UNIT_LIMIT = 100;
4
+ export const DEFAULT_RUN_LIMIT = 20;
5
+ /**
6
+ * exactOptionalPropertyTypes draws a line between "absent" and "present and
7
+ * undefined", and a NULL column is the first. So an optional field is spread in
8
+ * only when it has a value, rather than assigned undefined.
9
+ */
10
+ const optional = (key, value) => value === null ? {} : { [key]: value };
11
+ export const toRunRow = (r) => ({
12
+ runId: r.run_id,
13
+ job: r.job,
14
+ trigger: r.trigger,
15
+ mode: r.mode,
16
+ startedAt: fromEpochMs(Number(r.started_at)),
17
+ identity: JSON.parse(r.identity),
18
+ });
19
+ export const toUnitRow = (r) => ({
20
+ runId: r.run_id,
21
+ unitKey: r.unit_key,
22
+ unitType: r.unit_type,
23
+ recordedAt: fromEpochMs(Number(r.recorded_at)),
24
+ outcome: r.outcome,
25
+ durationMs: Number(r.duration_ms),
26
+ ...optional('reasonCode', r.reason_code),
27
+ ...optional('planHash', r.plan_hash),
28
+ ...optional('planRef', r.plan_ref),
29
+ ...optional('externalIds', r.external_ids === null
30
+ ? null
31
+ : JSON.parse(r.external_ids)),
32
+ });
33
+ export const toStepRow = (r) => ({
34
+ runId: r.run_id,
35
+ unitKey: r.unit_key,
36
+ step: r.step,
37
+ attempt: r.attempt,
38
+ outcome: r.outcome,
39
+ durationMs: Number(r.duration_ms),
40
+ recordedAt: fromEpochMs(Number(r.recorded_at)),
41
+ ...optional('reasonCode', r.reason_code),
42
+ });
43
+ export const toCallRow = (r) => ({
44
+ runId: r.run_id,
45
+ unitKey: r.unit_key,
46
+ system: r.system,
47
+ operation: r.operation,
48
+ status: r.status,
49
+ ...optional('httpStatus', r.http_status),
50
+ ...optional('idempotencyKey', r.idempotency_key),
51
+ ...optional('durationMs', r.duration_ms === null ? null : Number(r.duration_ms)),
52
+ });
53
+ export const toDeliveryRow = (r) => ({
54
+ deliveryId: r.delivery_id,
55
+ source: r.source,
56
+ topic: r.topic,
57
+ shop: r.shop,
58
+ webhookId: r.webhook_id,
59
+ bodyKey: r.body_key,
60
+ receivedAt: fromEpochMs(Number(r.received_at)),
61
+ });
62
+ export const toTaskRow = (r) => ({
63
+ deliveryId: r.delivery_id,
64
+ useCase: r.use_case,
65
+ state: r.state,
66
+ updatedAt: fromEpochMs(Number(r.updated_at)),
67
+ ...optional('reasonCode', r.reason_code),
68
+ requeues: Number(r.requeues),
69
+ });
70
+ /** Before every real row, so a first page needs no second query. */
71
+ export const FIRST_TASK = {
72
+ updatedAt: fromEpochMs(Number.MIN_SAFE_INTEGER),
73
+ deliveryId: '',
74
+ useCase: '',
75
+ };
@@ -0,0 +1,9 @@
1
+ import type { BlobKey, BlobStore, PutOptions } from '../../contracts/index.js';
2
+ export declare class MemoryBlobStore implements BlobStore {
3
+ #private;
4
+ put(key: BlobKey, body: Uint8Array | string, _options?: PutOptions): Promise<void>;
5
+ get(key: BlobKey): Promise<Uint8Array | undefined>;
6
+ getText(key: BlobKey): Promise<string | undefined>;
7
+ delete(key: BlobKey): Promise<void>;
8
+ list(prefix: string): Promise<readonly BlobKey[]>;
9
+ }
@@ -0,0 +1,19 @@
1
+ export class MemoryBlobStore {
2
+ #blobs = new Map();
3
+ async put(key, body, _options) {
4
+ this.#blobs.set(key, typeof body === 'string' ? new TextEncoder().encode(body) : body);
5
+ }
6
+ async get(key) {
7
+ return this.#blobs.get(key);
8
+ }
9
+ async getText(key) {
10
+ const b = this.#blobs.get(key);
11
+ return b === undefined ? undefined : new TextDecoder().decode(b);
12
+ }
13
+ async delete(key) {
14
+ this.#blobs.delete(key);
15
+ }
16
+ async list(prefix) {
17
+ return [...this.#blobs.keys()].filter((k) => k.startsWith(prefix)).sort();
18
+ }
19
+ }
@@ -0,0 +1,13 @@
1
+ import type { Cache, CacheKey, Clock } from '../../contracts/index.js';
2
+ export type MemoryCacheOptions = {
3
+ readonly clock: Clock;
4
+ readonly minTtlSeconds: number;
5
+ };
6
+ export declare class MemoryCache implements Cache {
7
+ #private;
8
+ private readonly o;
9
+ constructor(o: MemoryCacheOptions);
10
+ get(key: CacheKey): Promise<string | undefined>;
11
+ put(key: CacheKey, value: string, ttlSeconds: number): Promise<void>;
12
+ delete(key: CacheKey): Promise<void>;
13
+ }
@@ -0,0 +1,36 @@
1
+ import { LimitExceeded, checkDuration, plusSeconds, } from '../../contracts/index.js';
2
+ export class MemoryCache {
3
+ o;
4
+ #entries = new Map();
5
+ constructor(o) {
6
+ this.o = o;
7
+ }
8
+ async get(key) {
9
+ const entry = this.#entries.get(key);
10
+ if (entry === undefined) {
11
+ return undefined;
12
+ }
13
+ // Inclusive: at exactly expiresAt the value is gone.
14
+ if (entry.expiresAt <= this.o.clock.now()) {
15
+ this.#entries.delete(key);
16
+ return undefined;
17
+ }
18
+ return entry.value;
19
+ }
20
+ async put(key, value, ttlSeconds) {
21
+ // Before the manifest check, which cannot catch it: NaN < minTtlSeconds is
22
+ // false, so a NaN ttl would pass and the value would never expire.
23
+ checkDuration('cache', 'ttlSeconds', ttlSeconds);
24
+ // The ADAPTER enforces its own manifest. Never the caller.
25
+ if (ttlSeconds < this.o.minTtlSeconds) {
26
+ throw new LimitExceeded('cache', `ttlSeconds ${ttlSeconds} is below cacheMinTtlSeconds ${this.o.minTtlSeconds}`);
27
+ }
28
+ this.#entries.set(key, {
29
+ value,
30
+ expiresAt: plusSeconds(this.o.clock.now(), ttlSeconds),
31
+ });
32
+ }
33
+ async delete(key) {
34
+ this.#entries.delete(key);
35
+ }
36
+ }
@@ -0,0 +1 @@
1
+ export { systemClock } from '../system-clock.js';
@@ -0,0 +1,4 @@
1
+ // Re-exported so a consumer that already imports from `adapters/memory`
2
+ // keeps working. The implementation moved to `adapters/system-clock.ts`: see
3
+ // that file for why.
4
+ export { systemClock } from '../system-clock.js';
@@ -0,0 +1,11 @@
1
+ export * from './clock.js';
2
+ export * from './queue.js';
3
+ export * from './ledger.js';
4
+ export * from './blob-store.js';
5
+ export * from './journal.js';
6
+ export * from './logger.js';
7
+ export * from './manifest.js';
8
+ export * from './session-storage.js';
9
+ export * from './cache.js';
10
+ export * from './toolkit.js';
11
+ export * from './pipelines.js';
@@ -0,0 +1,11 @@
1
+ export * from './clock.js';
2
+ export * from './queue.js';
3
+ export * from './ledger.js';
4
+ export * from './blob-store.js';
5
+ export * from './journal.js';
6
+ export * from './logger.js';
7
+ export * from './manifest.js';
8
+ export * from './session-storage.js';
9
+ export * from './cache.js';
10
+ export * from './toolkit.js';
11
+ export * from './pipelines.js';
@@ -0,0 +1,35 @@
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, useCases: readonly string[]): Promise<void>;
23
+ moveTask(deliveryId: string, useCase: 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({ useCase, after, limit, }?: {
29
+ readonly useCase?: string;
30
+ readonly after?: TaskCursor;
31
+ readonly limit?: number;
32
+ }): Promise<readonly TaskRow[]>;
33
+ stuckTasks(before: Instant, limit?: number): Promise<readonly TaskRow[]>;
34
+ reclaimStuckTask({ deliveryId, useCase, updatedAt, }: Pick<TaskRow, 'deliveryId' | 'useCase' | 'updatedAt'>, at: Instant, to: 'requeued' | 'dead'): Promise<boolean>;
35
+ }
@@ -0,0 +1,154 @@
1
+ import { TASK_TRANSITIONS, } from '../../contracts/index.js';
2
+ const STUCK_STATES = [
3
+ 'received',
4
+ 'processing',
5
+ 'replayed',
6
+ ];
7
+ /** The SQL adapters' order: updated_at, then delivery_id, then use_case. Strings by code unit, as D1 does; Postgres uses its collation. */
8
+ const byTaskOrder = (a, b) => a.updatedAt - b.updatedAt ||
9
+ (a.deliveryId < b.deliveryId ? -1 : a.deliveryId > b.deliveryId ? 1 : 0) ||
10
+ (a.useCase < b.useCase ? -1 : a.useCase > b.useCase ? 1 : 0);
11
+ export class MemoryJournal {
12
+ #runs = new Map();
13
+ #units = [];
14
+ #calls = [];
15
+ #steps = [];
16
+ #deliveries = new Map();
17
+ #tasks = new Map();
18
+ async startRun(row) {
19
+ this.#runs.set(row.runId, row);
20
+ }
21
+ async finishRun(runId, endedAt) {
22
+ const r = this.#runs.get(runId);
23
+ if (r !== undefined) {
24
+ this.#runs.set(runId, { ...r, endedAt });
25
+ }
26
+ }
27
+ async recordUnit(unit, calls) {
28
+ this.#units.push(unit);
29
+ this.#calls.push(...calls);
30
+ }
31
+ /**
32
+ * An array push cannot fail, so there is nothing to log. The never-rejects
33
+ * promise is kept by construction here, and by a catch in the adapters whose
34
+ * storage can fail.
35
+ */
36
+ async recordStep(step) {
37
+ this.#steps.push(step);
38
+ }
39
+ async unitsForRun(runId, limit = 100) {
40
+ return this.#units
41
+ .filter((u) => u.runId === runId)
42
+ .sort((a, b) => a.unitKey.localeCompare(b.unitKey)) // stable order; the suite asserts it
43
+ .slice(0, limit);
44
+ }
45
+ async unit(runId, unitKey) {
46
+ const unit = this.#units.find((u) => u.runId === runId && u.unitKey === unitKey);
47
+ if (unit === undefined) {
48
+ return undefined;
49
+ }
50
+ return {
51
+ unit,
52
+ // Array.prototype.sort is stable, so equal instants keep write order.
53
+ steps: this.#steps
54
+ .filter((s) => s.runId === runId && s.unitKey === unitKey)
55
+ .sort((a, b) => a.recordedAt - b.recordedAt),
56
+ calls: this.#calls.filter((c) => c.runId === runId && c.unitKey === unitKey),
57
+ };
58
+ }
59
+ async latestForUnit(unitKey) {
60
+ return [...this.#units].reverse().find((u) => u.unitKey === unitKey);
61
+ }
62
+ async failuresByReason(since) {
63
+ const counts = new Map();
64
+ for (const u of this.#units) {
65
+ if (u.recordedAt < since) {
66
+ continue;
67
+ }
68
+ if (u.outcome === 'written' || u.reasonCode === undefined) {
69
+ continue;
70
+ }
71
+ counts.set(u.reasonCode, (counts.get(u.reasonCode) ?? 0) + 1);
72
+ }
73
+ return [...counts]
74
+ .map(([reasonCode, count]) => ({ reasonCode, count }))
75
+ .sort((a, b) => b.count - a.count || a.reasonCode.localeCompare(b.reasonCode));
76
+ }
77
+ async recentRuns(limit = 20) {
78
+ return [...this.#runs.values()]
79
+ .sort((a, b) => b.startedAt - a.startedAt)
80
+ .slice(0, limit);
81
+ }
82
+ async recordDelivery(delivery, useCases) {
83
+ if (!this.#deliveries.has(delivery.deliveryId)) {
84
+ this.#deliveries.set(delivery.deliveryId, delivery);
85
+ }
86
+ for (const useCase of useCases) {
87
+ const key = JSON.stringify([delivery.deliveryId, useCase]);
88
+ if (!this.#tasks.has(key)) {
89
+ this.#tasks.set(key, {
90
+ deliveryId: delivery.deliveryId,
91
+ useCase,
92
+ state: 'received',
93
+ updatedAt: delivery.receivedAt,
94
+ requeues: 0,
95
+ });
96
+ }
97
+ }
98
+ }
99
+ async moveTask(deliveryId, useCase, to, at, reasonCode) {
100
+ const key = JSON.stringify([deliveryId, useCase]);
101
+ const task = this.#tasks.get(key);
102
+ if (task === undefined || !TASK_TRANSITIONS[to].includes(task.state)) {
103
+ return false;
104
+ }
105
+ const { reasonCode: _cleared, ...rest } = task;
106
+ this.#tasks.set(key, {
107
+ ...rest,
108
+ state: to,
109
+ updatedAt: at,
110
+ ...(reasonCode === undefined ? {} : { reasonCode }),
111
+ requeues: to === 'replayed' ? 0 : task.requeues,
112
+ });
113
+ return true;
114
+ }
115
+ async delivery(deliveryId) {
116
+ const delivery = this.#deliveries.get(deliveryId);
117
+ if (delivery === undefined) {
118
+ return undefined;
119
+ }
120
+ return {
121
+ delivery,
122
+ tasks: [...this.#tasks.values()]
123
+ .filter((t) => t.deliveryId === deliveryId)
124
+ .sort((a, b) => (a.useCase < b.useCase ? -1 : 1)),
125
+ };
126
+ }
127
+ async deadTasks({ useCase, after, limit = 100, } = {}) {
128
+ return [...this.#tasks.values()]
129
+ .filter((t) => t.state === 'dead' &&
130
+ (useCase === undefined || t.useCase === useCase) &&
131
+ (after === undefined || byTaskOrder(t, after) > 0))
132
+ .sort(byTaskOrder)
133
+ .slice(0, limit);
134
+ }
135
+ async stuckTasks(before, limit = 100) {
136
+ return [...this.#tasks.values()]
137
+ .filter((t) => STUCK_STATES.includes(t.state) && t.updatedAt < before)
138
+ .sort(byTaskOrder)
139
+ .slice(0, limit);
140
+ }
141
+ async reclaimStuckTask({ deliveryId, useCase, updatedAt, }, at, to) {
142
+ const key = JSON.stringify([deliveryId, useCase]);
143
+ const task = this.#tasks.get(key);
144
+ if (task === undefined ||
145
+ !STUCK_STATES.includes(task.state) ||
146
+ task.updatedAt !== updatedAt) {
147
+ return false;
148
+ }
149
+ this.#tasks.set(key, to === 'dead'
150
+ ? { ...task, state: 'dead', updatedAt: at, reasonCode: 'stuck' }
151
+ : { ...task, updatedAt: at, requeues: task.requeues + 1 });
152
+ return true;
153
+ }
154
+ }
@@ -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 Pipeline 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 Pipeline 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
+ };