@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,62 @@
1
+ import type { Instant, PipelineInstanceId, PipelineRegistration, Pipelines, Toolkit } from '../../contracts/index.js';
2
+ import type { InstanceChange, InstanceRow, Interrupt, ReferenceStore, WakeUp } from '../reference-executor.js';
3
+ import { LocalQueue } from './queue.js';
4
+ /**
5
+ * `pipeline_instances` and `pipeline_steps` (decision 0006) as two Maps. Each method is
6
+ * one statement of the protocol, and none of them awaits between its read
7
+ * and its write, so each is atomic in one isolate as the D1 statement is.
8
+ */
9
+ export declare class MemoryPipelineStore implements ReferenceStore {
10
+ #private;
11
+ insert(row: InstanceRow): Promise<'inserted' | 'exists'>;
12
+ get(id: PipelineInstanceId): Promise<InstanceRow | undefined>;
13
+ update(id: PipelineInstanceId, version: number, change: InstanceChange): Promise<boolean>;
14
+ remove(id: PipelineInstanceId, cutoff: Instant): Promise<void>;
15
+ storeResult(id: PipelineInstanceId, stepIndex: number, result: string, _completedAt: Instant): Promise<void>;
16
+ results(id: PipelineInstanceId): Promise<ReadonlyMap<number, string>>;
17
+ due(now: Instant): Promise<readonly InstanceRow[]>;
18
+ removeEndedBefore(cutoff: Instant): Promise<void>;
19
+ }
20
+ /**
21
+ * THE REFERENCE EXECUTOR ON THE MEMORY ADAPTER. Every local test of a Pipeline
22
+ * runs here.
23
+ *
24
+ * Nothing delivers an in-process queue on its own schedule, so `settle` and
25
+ * `wake` are how a test or `npm run dev` drives it. They are affordances of
26
+ * this adapter, as `LocalQueue.drain` is, and not part of `Pipelines`.
27
+ */
28
+ export type MemoryPipelines = Pipelines & {
29
+ /**
30
+ * Runs the sweeper and delivers every wake-up that is due at the clock's
31
+ * current time, one at a time, until nothing more is due. It never moves
32
+ * the clock. It waits for every consumer in flight, except one that a test
33
+ * parked at an interruption, so a step body that has not returned keeps it
34
+ * from returning.
35
+ */
36
+ settle(): Promise<void>;
37
+ /**
38
+ * Delivers one extra wake-up for the instance now, as a duplicate, early or
39
+ * reordered message would, and returns once it is handled. Without
40
+ * `stepIndex` it names the instance's current step.
41
+ */
42
+ wake(id: PipelineInstanceId, stepIndex?: number): Promise<void>;
43
+ };
44
+ export type MemoryPipelinesOptions = {
45
+ readonly registrations: readonly PipelineRegistration[];
46
+ /**
47
+ * TEST SEAMS. A restarted process is a second executor over the same
48
+ * store and queue, and `interrupt` parks a consumer between two writes.
49
+ * An app passes none of them.
50
+ */
51
+ readonly store?: ReferenceStore;
52
+ readonly queue?: LocalQueue<WakeUp>;
53
+ readonly interrupt?: Interrupt;
54
+ };
55
+ /**
56
+ * Builds the executor. It throws when a registration is refused, as for a
57
+ * Pipeline name outside `[A-Za-z0-9_]{1,64}`.
58
+ *
59
+ * The toolkit supplies the clock (rule 3: backoff and leases are read from
60
+ * it), the logger (rule 4) and the journal its Step rows go to.
61
+ */
62
+ export declare function createMemoryPipelines(toolkit: Pick<Toolkit, 'clock' | 'logger' | 'journal'>, options: MemoryPipelinesOptions): MemoryPipelines;
@@ -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
+ * `pipeline_instances` and `pipeline_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 MemoryPipelineStore {
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
+ * Pipeline 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 createMemoryPipelines(toolkit, options) {
75
+ const { clock, logger, journal } = toolkit;
76
+ const store = options.store ?? new MemoryPipelineStore();
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(`pipelines: 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,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
+ }
@@ -0,0 +1,102 @@
1
+ import { LimitExceeded, checkDuration, fromEpochMs, } from '../../contracts/index.js';
2
+ export class LocalQueue {
3
+ o;
4
+ #pending = [];
5
+ #dead = [];
6
+ #seq = 0;
7
+ constructor(o) {
8
+ this.o = o;
9
+ }
10
+ async send(body, options) {
11
+ const delay = options?.delaySeconds ?? 0;
12
+ // Before the ceiling check, which cannot catch it: NaN > maxDelaySeconds is
13
+ // false, so a NaN delay would pass and the message would never be visible.
14
+ checkDuration('queue', 'delaySeconds', delay);
15
+ // The ADAPTER enforces its own manifest. Never the caller.
16
+ if (delay > this.o.maxDelaySeconds) {
17
+ throw new LimitExceeded('queue', `delaySeconds ${delay} exceeds queueDelayMaxSeconds ${this.o.maxDelaySeconds}`);
18
+ }
19
+ // A Map has no size limit, so this one is enforced because the manifest
20
+ // DECLARES it. An adapter that declares a ceiling and does not apply it
21
+ // lets a body through here that its real counterpart would refuse, which
22
+ // makes the memory adapter useless as the place a payload gets sized.
23
+ const bytes = new TextEncoder().encode(JSON.stringify(body)).byteLength;
24
+ if (bytes > this.o.maxBytes) {
25
+ throw new LimitExceeded('queue', `body of ${bytes} bytes exceeds messageMaxBytes ${this.o.maxBytes}`);
26
+ }
27
+ const id = `local-${++this.#seq}`;
28
+ this.#pending.push({
29
+ id,
30
+ body,
31
+ visibleAt: fromEpochMs(this.o.clock.now() + delay * 1000),
32
+ attempt: 0,
33
+ });
34
+ return id;
35
+ }
36
+ async sendBatch(bodies, options) {
37
+ const ids = [];
38
+ for (const b of bodies) {
39
+ ids.push(await this.send(b, options));
40
+ }
41
+ return ids;
42
+ }
43
+ /** Test and dev only. Deliberately NOT on the Queue contract. */
44
+ async drain(consumer, batchSize = 10) {
45
+ const now = this.o.clock.now();
46
+ const due = this.#pending
47
+ .filter((m) => m.visibleAt <= now)
48
+ .slice(0, batchSize);
49
+ if (due.length === 0) {
50
+ return;
51
+ }
52
+ const acked = new Set();
53
+ const retried = new Map();
54
+ const messages = due.map((m) => ({
55
+ id: m.id,
56
+ body: m.body,
57
+ attempt: m.attempt + 1,
58
+ enqueuedAt: new Date(m.visibleAt).toISOString(),
59
+ identity: this.o.identity,
60
+ }));
61
+ const batch = {
62
+ messages,
63
+ ack: (id) => {
64
+ acked.add(id);
65
+ },
66
+ retry: (id, opts) => {
67
+ retried.set(id, opts?.delaySeconds ?? 0);
68
+ },
69
+ };
70
+ await consumer(batch);
71
+ for (const m of due) {
72
+ if (acked.has(m.id)) {
73
+ this.#remove(m);
74
+ continue;
75
+ }
76
+ // Neither acked nor retried counts as retried: at-least-once means the default
77
+ // on an unhandled message is redelivery, never loss.
78
+ m.attempt += 1;
79
+ if (m.attempt >= this.o.maxAttempts) {
80
+ this.#remove(m);
81
+ this.#dead.push(m);
82
+ continue;
83
+ }
84
+ m.visibleAt = fromEpochMs(this.o.clock.now() + (retried.get(m.id) ?? 0) * 1000);
85
+ }
86
+ }
87
+ #remove(m) {
88
+ const i = this.#pending.indexOf(m);
89
+ if (i >= 0) {
90
+ this.#pending.splice(i, 1);
91
+ }
92
+ }
93
+ pendingCount() {
94
+ return this.#pending.length;
95
+ }
96
+ deadCount() {
97
+ return this.#dead.length;
98
+ }
99
+ dead() {
100
+ return this.#dead.map((m) => m.body);
101
+ }
102
+ }
@@ -0,0 +1,20 @@
1
+ import type { Session } from '@shopify/shopify-api';
2
+ import type { SessionStorage } from '../../contracts/index.js';
3
+ /**
4
+ * No encryption. There is no "raw column" here for an attacker or a test to
5
+ * read, so the encryption-at-rest promise is this library's to keep only
6
+ * where a row actually exists on disk — the Cloudflare adapter. The
7
+ * conformance suite in src/contracts/conformance/session-storage.ts covers
8
+ * everything both adapters owe callers; the encryption assertion is
9
+ * necessarily adapter-specific and lives in
10
+ * src/adapters/cloudflare/session-storage.spec.ts.
11
+ */
12
+ export declare class MemorySessionStorage implements SessionStorage {
13
+ #private;
14
+ storeSession(session: Session): Promise<boolean>;
15
+ loadSession(id: string): Promise<Session | undefined>;
16
+ /** Matches @shopify/shopify-app-session-storage-memory: always true. */
17
+ deleteSession(id: string): Promise<boolean>;
18
+ deleteSessions(ids: string[]): Promise<boolean>;
19
+ findSessionsByShop(shop: string): Promise<Session[]>;
20
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * No encryption. There is no "raw column" here for an attacker or a test to
3
+ * read, so the encryption-at-rest promise is this library's to keep only
4
+ * where a row actually exists on disk — the Cloudflare adapter. The
5
+ * conformance suite in src/contracts/conformance/session-storage.ts covers
6
+ * everything both adapters owe callers; the encryption assertion is
7
+ * necessarily adapter-specific and lives in
8
+ * src/adapters/cloudflare/session-storage.spec.ts.
9
+ */
10
+ export class MemorySessionStorage {
11
+ #sessions = new Map();
12
+ async storeSession(session) {
13
+ this.#sessions.set(session.id, session);
14
+ return true;
15
+ }
16
+ async loadSession(id) {
17
+ return this.#sessions.get(id);
18
+ }
19
+ /** Matches @shopify/shopify-app-session-storage-memory: always true. */
20
+ async deleteSession(id) {
21
+ this.#sessions.delete(id);
22
+ return true;
23
+ }
24
+ async deleteSessions(ids) {
25
+ for (const id of ids) {
26
+ this.#sessions.delete(id);
27
+ }
28
+ return true;
29
+ }
30
+ async findSessionsByShop(shop) {
31
+ return [...this.#sessions.values()].filter((s) => s.shop === shop);
32
+ }
33
+ }
@@ -0,0 +1,8 @@
1
+ import type { Clock, DeploymentIdentity, Toolkit } from '../../contracts/index.js';
2
+ export type MemoryToolkitOptions = {
3
+ readonly identity: DeploymentIdentity;
4
+ readonly correlationId?: string;
5
+ readonly clock?: Clock;
6
+ readonly maxQueueAttempts?: number;
7
+ };
8
+ export declare function createInMemoryToolkit<QueueBody = unknown, WebhookBody = unknown>(o: MemoryToolkitOptions): Toolkit<QueueBody, WebhookBody>;
@@ -0,0 +1,31 @@
1
+ import { systemClock } from '../system-clock.js';
2
+ import { MemoryBlobStore } from './blob-store.js';
3
+ import { MemoryCache } from './cache.js';
4
+ import { MemoryJournal } from './journal.js';
5
+ import { LocalLedger } from './ledger.js';
6
+ import { MemoryLogger } from './logger.js';
7
+ import { LOCAL_MANIFEST } from './manifest.js';
8
+ import { LocalQueue } from './queue.js';
9
+ export function createInMemoryToolkit(o) {
10
+ const clock = o.clock ?? systemClock();
11
+ const queueOptions = {
12
+ clock,
13
+ identity: o.identity,
14
+ maxDelaySeconds: LOCAL_MANIFEST.queueDelayMaxSeconds,
15
+ maxBytes: LOCAL_MANIFEST.messageMaxBytes,
16
+ maxAttempts: o.maxQueueAttempts ?? 5,
17
+ };
18
+ return {
19
+ blobStore: new MemoryBlobStore(),
20
+ cache: new MemoryCache({
21
+ clock,
22
+ minTtlSeconds: LOCAL_MANIFEST.cacheMinTtlSeconds,
23
+ }),
24
+ journal: new MemoryJournal(),
25
+ ledger: new LocalLedger(clock),
26
+ logger: new MemoryLogger(o.identity, o.correlationId ?? crypto.randomUUID()),
27
+ queue: new LocalQueue(queueOptions),
28
+ webhookQueue: new LocalQueue(queueOptions),
29
+ clock,
30
+ };
31
+ }
@@ -0,0 +1,17 @@
1
+ import type pg from 'pg';
2
+ import type { Cache, CacheKey, Clock } from '../../contracts/index.js';
3
+ export type PostgresCacheOptions = {
4
+ /** The app's pool. The cache never opens its own. docs/decisions/0007. */
5
+ readonly pool: pg.Pool;
6
+ readonly clock: Clock;
7
+ /** Postgres has no floor of its own. The manifest's value is passed in. */
8
+ readonly minTtlSeconds: number;
9
+ };
10
+ export declare class PostgresCache implements Cache {
11
+ #private;
12
+ private readonly o;
13
+ constructor(o: PostgresCacheOptions);
14
+ get(key: CacheKey): Promise<string | undefined>;
15
+ put(key: CacheKey, value: string, ttlSeconds: number): Promise<void>;
16
+ delete(key: CacheKey): Promise<void>;
17
+ }
@@ -0,0 +1,69 @@
1
+ import { LimitExceeded, checkDuration, plusSeconds, } from '../../contracts/index.js';
2
+ import { toFault } from './faults.js';
3
+ const TOOL = 'cache';
4
+ /**
5
+ * How many expired rows one write removes. Every row comes from a write, and
6
+ * each write clears up to this many, so expired rows are cleared far faster
7
+ * than they are made while the cache is in use. When writes stop, what is left
8
+ * stays until the next write, unread: `get` never returns an expired row.
9
+ */
10
+ const SWEEP_BATCH = 100;
11
+ /**
12
+ * The expiry is decided against the injected Clock, never `now()`, so the
13
+ * suite can advance a test clock. Inclusive: a row at `expires_at` is a miss.
14
+ */
15
+ const GET = `SELECT value FROM cache_entries WHERE key = $1 AND expires_at > $2`;
16
+ /**
17
+ * The upsert, and in the same statement a sweep of up to SWEEP_BATCH expired
18
+ * rows. SKIP LOCKED leaves rows another write is sweeping to it, so concurrent
19
+ * writes never queue on each other. The key being written is left out of the
20
+ * sweep, because the INSERT may update that very row.
21
+ */
22
+ const PUT = `
23
+ WITH swept AS (
24
+ DELETE FROM cache_entries WHERE key IN (
25
+ SELECT key FROM cache_entries
26
+ WHERE expires_at <= $4 AND key <> $1
27
+ LIMIT ${SWEEP_BATCH}
28
+ FOR UPDATE SKIP LOCKED
29
+ )
30
+ )
31
+ INSERT INTO cache_entries (key, value, expires_at)
32
+ VALUES ($1, $2, $3)
33
+ ON CONFLICT (key) DO UPDATE SET value = $2, expires_at = $3
34
+ `;
35
+ const DELETE = `DELETE FROM cache_entries WHERE key = $1`;
36
+ export class PostgresCache {
37
+ o;
38
+ constructor(o) {
39
+ this.o = o;
40
+ }
41
+ async get(key) {
42
+ const { rows } = await this.#call('get', async () => this.o.pool.query(GET, [key, this.o.clock.now()]));
43
+ return rows[0]?.value;
44
+ }
45
+ async put(key, value, ttlSeconds) {
46
+ // Before the manifest check, which cannot catch it: NaN < minTtlSeconds is
47
+ // false, so a NaN ttl would pass and the value would never expire.
48
+ checkDuration(TOOL, 'ttlSeconds', ttlSeconds);
49
+ // The ADAPTER enforces its own manifest. Never the caller.
50
+ if (ttlSeconds < this.o.minTtlSeconds) {
51
+ throw new LimitExceeded(TOOL, `ttlSeconds ${ttlSeconds} is below cacheMinTtlSeconds ${this.o.minTtlSeconds}`);
52
+ }
53
+ const now = this.o.clock.now();
54
+ // A fractional ttl gives a fractional instant, which BIGINT refuses.
55
+ const expiresAt = Math.ceil(plusSeconds(now, ttlSeconds));
56
+ await this.#call('put', async () => this.o.pool.query(PUT, [key, value, expiresAt, now]));
57
+ }
58
+ async delete(key) {
59
+ await this.#call('delete', async () => this.o.pool.query(DELETE, [key]));
60
+ }
61
+ async #call(operation, f) {
62
+ try {
63
+ return await f();
64
+ }
65
+ catch (e) {
66
+ throw toFault(TOOL, operation, e);
67
+ }
68
+ }
69
+ }
@@ -0,0 +1,27 @@
1
+ export type PostgresToolkitConfig = {
2
+ /** For the app's own `pg.Pool`. The toolkit never opens one. docs/decisions/0007. */
3
+ readonly databaseUrl: string;
4
+ readonly s3: {
5
+ /** Absent for AWS, which the SDK finds from the region. */
6
+ readonly endpoint?: string;
7
+ readonly region: string;
8
+ readonly bucket: string;
9
+ /**
10
+ * From `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`, set as a pair. Set
11
+ * them for MinIO, R2 and GCS (HMAC keys). Leave both unset on AWS, so the
12
+ * SDK's default chain finds the task, pod or instance role.
13
+ */
14
+ readonly credentials?: {
15
+ readonly accessKeyId: string;
16
+ readonly secretAccessKey: string;
17
+ };
18
+ /** MinIO and most self-hosted stores serve a bucket as a path. */
19
+ readonly forcePathStyle: boolean;
20
+ };
21
+ };
22
+ /**
23
+ * Reads and checks every setting once, at start, so a bad deploy fails before
24
+ * it takes traffic instead of on its first request. Every problem is reported
25
+ * together, not the first one found.
26
+ */
27
+ export declare function readPostgresToolkitConfig(env: Readonly<Record<string, string | undefined>>): PostgresToolkitConfig;
@@ -0,0 +1,45 @@
1
+ import { Misconfigured } from '../../contracts/index.js';
2
+ const REQUIRED = ['DATABASE_URL', 'S3_REGION', 'S3_BUCKET'];
3
+ const KEY_PAIR = ['S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY'];
4
+ const isUrl = (value, protocols) => URL.canParse(value) && protocols.includes(new URL(value).protocol);
5
+ /**
6
+ * Reads and checks every setting once, at start, so a bad deploy fails before
7
+ * it takes traffic instead of on its first request. Every problem is reported
8
+ * together, not the first one found.
9
+ */
10
+ export function readPostgresToolkitConfig(env) {
11
+ const value = (name) => env[name]?.trim() ?? '';
12
+ const problems = REQUIRED.filter((name) => value(name) === '').map((name) => `${name} is not set`);
13
+ const databaseUrl = value('DATABASE_URL');
14
+ const endpoint = value('S3_ENDPOINT');
15
+ const pathStyle = value('S3_FORCE_PATH_STYLE');
16
+ const accessKeyId = value('S3_ACCESS_KEY_ID');
17
+ const secretAccessKey = value('S3_SECRET_ACCESS_KEY');
18
+ const keys = accessKeyId !== '' || secretAccessKey !== '';
19
+ if (keys) {
20
+ problems.push(...KEY_PAIR.filter((name) => value(name) === '').map((name) => `${name} is not set, though its pair is`));
21
+ }
22
+ if (databaseUrl !== '' && !isUrl(databaseUrl, ['postgres:', 'postgresql:'])) {
23
+ problems.push('DATABASE_URL is not a postgres:// URL');
24
+ }
25
+ if (endpoint !== '' && !isUrl(endpoint, ['http:', 'https:'])) {
26
+ problems.push('S3_ENDPOINT is not an http(s):// URL');
27
+ }
28
+ if (!['', 'true', 'false'].includes(pathStyle)) {
29
+ problems.push('S3_FORCE_PATH_STYLE must be true or false');
30
+ }
31
+ if (problems.length > 0) {
32
+ // Names only, never values: a secret must not reach a log line.
33
+ throw new Misconfigured('config', problems.join('; '));
34
+ }
35
+ return {
36
+ databaseUrl,
37
+ s3: {
38
+ ...(endpoint === '' ? {} : { endpoint }),
39
+ region: value('S3_REGION'),
40
+ bucket: value('S3_BUCKET'),
41
+ ...(keys ? { credentials: { accessKeyId, secretAccessKey } } : {}),
42
+ forcePathStyle: pathStyle === 'true',
43
+ },
44
+ };
45
+ }
@@ -0,0 +1,14 @@
1
+ import { type ToolFault } from '../../contracts/index.js';
2
+ /**
3
+ * 40001, serialization_failure. Under REPEATABLE READ or SERIALIZABLE, a write
4
+ * that meets a row committed after its snapshot fails with this, where READ
5
+ * COMMITTED would have seen the row.
6
+ */
7
+ export declare const isSerializationFailure: (e: unknown) => boolean;
8
+ /**
9
+ * Unknown failures, including a refused connection, which carries a Node
10
+ * error code rather than a SQLSTATE, are Unavailable and so retryable. A
11
+ * retryable answer to something permanent costs a few attempts; a permanent
12
+ * answer to something transient loses the work.
13
+ */
14
+ export declare function toFault(tool: string, operation: string, e: unknown): ToolFault;