@midsummer-ai/sdk 0.1.0-staging.3428 → 0.1.0-staging.3434

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 (43) hide show
  1. package/auth-B7rCtXFQ.d.mts +36 -0
  2. package/{build-DQo-JrlN.d.mts → build-BhmOZmGQ.d.mts} +2 -27
  3. package/client.mjs +1 -1
  4. package/contract.mjs +2 -2
  5. package/database/build.d.mts +1 -1
  6. package/database/build.mjs +35 -2
  7. package/database/server.mjs +1 -1
  8. package/database/stand-in.d.mts +2 -1
  9. package/database/stand-in.mjs +2 -2
  10. package/email/client.d.mts +5 -4
  11. package/email/client.mjs +1 -1
  12. package/email/contract.d.mts +3 -1
  13. package/email/contract.mjs +111 -4
  14. package/email/index.d.mts +85 -16
  15. package/email/index.mjs +2 -2
  16. package/email/smtp.mjs +24 -8
  17. package/email/stand-in.d.mts +3 -0
  18. package/email/stand-in.mjs +17 -7
  19. package/email-IH5OllU2.mjs +337 -0
  20. package/errors-B1tO_wdm.mjs +28 -0
  21. package/flows/contract.d.mts +13 -0
  22. package/flows/contract.mjs +483 -0
  23. package/flows/index.d.mts +148 -0
  24. package/flows/index.mjs +347 -0
  25. package/index.mjs +2 -2
  26. package/{names-DfCBKupJ.mjs → names-Do0ot5Ha.mjs} +2 -28
  27. package/package.json +29 -1
  28. package/queues/contract.mjs +144 -1
  29. package/queues/index.d.mts +149 -5
  30. package/queues/index.mjs +56 -12
  31. package/queues/stand-in.mjs +333 -31
  32. package/queues/wire.mjs +302 -16
  33. package/s3.mjs +3 -2
  34. package/{server-EDRbF2u-.mjs → server-Drjni3-F.mjs} +4 -2
  35. package/socket.mjs +1 -1
  36. package/{src-BKrQAqJN.mjs → src-CkP59_Qu.mjs} +2 -1
  37. package/stand-in.mjs +2 -1
  38. package/storage/contract.d.mts +25 -0
  39. package/storage/contract.mjs +153 -0
  40. package/storage/files.d.mts +144 -0
  41. package/storage/files.mjs +513 -0
  42. package/wire.mjs +2 -1
  43. package/email-DXtpr7pT.mjs +0 -214
@@ -1,19 +1,27 @@
1
- import { DEAD, STATS_CAP, backoffMs } from "./index.mjs";
1
+ import { DEAD, QueueError, STATS_CAP, backoffMs } from "./index.mjs";
2
2
  //#region src/queues/stand-in.ts
3
3
  /**
4
4
  * Queues' Stand-in: the Capability's behaviour in memory, for `midsummer dev` and tests. It holds no
5
- * engine code and passes the contract (`@midsummer-ai/sdk/queues/contract`) except durability and scale.
5
+ * engine code and passes the contracts (`@midsummer-ai/sdk/queues/contract` and
6
+ * `@midsummer-ai/sdk/flows/contract`) except durability and scale.
6
7
  *
7
8
  * const jobs = queues(standIn({ clock: Date.now }))
8
9
  *
9
- * A Queue exists from its first send. Everything is lost when the process ends.
10
+ * A Queue exists from its first send. Groups are delivered one at a time, as a Queue with no limits
11
+ * set delivers them; limits are set on the platform (`midsummer queue edit`). Everything is lost when
12
+ * the process ends.
10
13
  */
11
14
  /** Keys a keyed send is remembered for. */
12
15
  const KEY_MS = 864e5;
16
+ const MAX_STEPS = 1e3;
17
+ const MAX_SIGNALS = 100;
18
+ const ended = (status) => status === "completed" || status === "failed" || status === "cancelled";
13
19
  function standIn(options) {
14
20
  const { clock } = options;
15
21
  const queues = /* @__PURE__ */ new Map();
16
22
  const keys = /* @__PURE__ */ new Map();
23
+ const groups = /* @__PURE__ */ new Map();
24
+ const runs = /* @__PURE__ */ new Map();
17
25
  let sequence = 0;
18
26
  const queueOf = (name) => {
19
27
  let held = queues.get(name);
@@ -22,46 +30,145 @@ function standIn(options) {
22
30
  };
23
31
  const order = (a, b) => a.visibleAt - b.visibleAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
24
32
  const nextId = (at) => `${at.toString(36).padStart(9, "0")}${(sequence++).toString(36).padStart(6, "0")}`;
25
- /** Moves `held` to its dead-letter Queue when its last delivery was its last; returns whether it did. */
26
- const deadLetter = (queue, held) => {
27
- if (queue.endsWith(".dead") || held.maxAttempts === void 0 || held.attempts < held.maxAttempts) return false;
33
+ const groupKey = (queue, group) => `${queue}\n${group}`;
34
+ const runOf = (queue, id) => runs.get(`${queue}\n${id}`);
35
+ /** Gives a Message its place in its group: worked on now when the group has none, or waiting behind it. */
36
+ const join = (queue, held) => {
37
+ if (held.group === void 0 || queue.endsWith(".dead")) return;
38
+ const key = groupKey(queue, held.group);
39
+ const group = groups.get(key) ?? {
40
+ next: 0,
41
+ admitted: 0
42
+ };
43
+ held.seq = group.next;
44
+ group.next += 1;
45
+ if (group.admitted < 1) group.admitted += 1;
46
+ else held.waiting = true;
47
+ groups.set(key, group);
48
+ };
49
+ /** Ends a group's hold of one Message (`freeing` when it was being worked on): the group's next one goes, oldest first. */
50
+ const leave = (queue, group, freeing) => {
51
+ const key = groupKey(queue, group);
52
+ const held = groups.get(key);
53
+ if (!held) return;
54
+ if (freeing) held.admitted = Math.max(0, held.admitted - 1);
55
+ if (held.admitted < 1) {
56
+ const next = (queues.get(queue) ?? []).filter((one) => one.group === group && one.waiting).sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))[0];
57
+ if (next) {
58
+ next.waiting = false;
59
+ next.visibleAt = Math.max(next.visibleAt, clock());
60
+ held.admitted += 1;
61
+ }
62
+ }
63
+ if (held.admitted === 0) groups.delete(key);
64
+ };
65
+ /** Takes a Message out of its Queue; its group's next one goes. */
66
+ const remove = (queue, held) => {
28
67
  const list = queueOf(queue);
29
- list.splice(list.indexOf(held), 1);
30
- const { receipt: _receipt, maxAttempts: _max, ...rest } = held;
68
+ const at = list.indexOf(held);
69
+ if (at >= 0) list.splice(at, 1);
70
+ if (held.group !== void 0 && !queue.endsWith(".dead")) leave(queue, held.group, !held.waiting);
71
+ };
72
+ const endRun = (run, status, end = {}) => {
73
+ run.status = status;
74
+ run.endedAt = clock();
75
+ delete run.waiting;
76
+ delete run.wakeAt;
77
+ if (end.output !== void 0) run.output = end.output;
78
+ if (end.error !== void 0) run.error = end.error;
79
+ };
80
+ /** Moves `held` to its dead-letter Queue when its last delivery was its last; returns whether it did. A run's Message fails its run. */
81
+ const deadLetter = (queue, held, lastError) => {
82
+ if (queue.endsWith(".dead") || held.maxAttempts === void 0 || held.attempts < held.maxAttempts) return false;
83
+ remove(queue, held);
84
+ const { receipt: _receipt, maxAttempts: _max, waiting: _waiting, ...rest } = held;
31
85
  queueOf(`${queue}${DEAD}`).push({
32
86
  ...rest,
33
- visibleAt: clock()
87
+ visibleAt: clock(),
88
+ ...lastError !== void 0 ? { lastError } : {}
34
89
  });
90
+ const run = held.run === void 0 ? void 0 : runOf(queue, held.run);
91
+ if (run && !ended(run.status)) endRun(run, "failed", { error: `Its delivery failed ${held.attempts} ${held.attempts === 1 ? "time" : "times"} without progress${lastError !== void 0 ? `: ${lastError}` : "."}` });
35
92
  return true;
36
93
  };
37
94
  /** The Message a receipt still names: none once its window has ended, though it was not delivered again yet. */
38
95
  const delivered = (queue, receipt) => queues.get(queue)?.find((held) => held.receipt === receipt && held.visibleAt > clock());
96
+ const send = (queue, messages) => {
97
+ const now = clock();
98
+ return messages.map((message) => {
99
+ const remembered = message.key === void 0 ? void 0 : keys.get(`${queue}\n${message.key}`);
100
+ if (remembered && now - remembered.at < KEY_MS) return remembered.id;
101
+ const id = nextId(now);
102
+ const held = {
103
+ id,
104
+ body: message.body,
105
+ sentAt: now,
106
+ visibleAt: now + message.delayMs,
107
+ attempts: 0,
108
+ ...message.group !== void 0 ? { group: message.group } : {},
109
+ ...message.run !== void 0 ? { run: message.run } : {}
110
+ };
111
+ join(queue, held);
112
+ queueOf(queue).push(held);
113
+ if (message.key !== void 0) keys.set(`${queue}\n${message.key}`, {
114
+ id,
115
+ at: now
116
+ });
117
+ return id;
118
+ });
119
+ };
120
+ const stepOut = ({ seq: _seq, ...step }) => step;
121
+ const runOut = (run) => ({
122
+ id: run.id,
123
+ status: run.status,
124
+ input: run.input,
125
+ startedAt: run.startedAt,
126
+ ...run.endedAt !== void 0 ? { endedAt: run.endedAt } : {},
127
+ ...run.wakeAt !== void 0 && !ended(run.status) ? { nextAt: run.wakeAt } : {},
128
+ ...run.output !== void 0 ? { output: run.output } : {},
129
+ ...run.error !== void 0 ? { error: run.error } : {},
130
+ ...run.deadline !== void 0 && !ended(run.status) ? { deadline: run.deadline } : {},
131
+ ...run.group !== void 0 ? { group: run.group } : {},
132
+ steps: [...run.steps.values()].sort((a, b) => a.seq - b.seq).map(stepOut)
133
+ });
134
+ /** The run a current delivery carries; undefined when the receipt has ended. A run past its deadline fails here. */
135
+ const runDelivery = (queue, runId, receipt) => {
136
+ const held = delivered(queue, receipt);
137
+ const run = runOf(queue, runId);
138
+ if (!held || held.run !== runId || !run) return void 0;
139
+ if (!ended(run.status) && run.deadline !== void 0 && clock() >= run.deadline) endRun(run, "failed", { error: `It ran past its timeout of ${Math.round((run.timeoutMs ?? 0) / 1e3)} seconds.` });
140
+ if (ended(run.status)) {
141
+ remove(queue, held);
142
+ return {
143
+ held,
144
+ run,
145
+ over: true
146
+ };
147
+ }
148
+ return {
149
+ held,
150
+ run,
151
+ over: false
152
+ };
153
+ };
154
+ /** Parks a run's Message until `until`, never past its deadline: its delivery ends and its attempts start again. */
155
+ const park = (held, run, until) => {
156
+ delete held.receipt;
157
+ delete held.maxAttempts;
158
+ held.attempts = 0;
159
+ held.visibleAt = Math.min(until, run.deadline ?? Infinity);
160
+ return held.visibleAt;
161
+ };
39
162
  return {
40
163
  async send(queue, messages) {
41
- const now = clock();
42
- return messages.map((message) => {
43
- const remembered = message.key === void 0 ? void 0 : keys.get(`${queue}\n${message.key}`);
44
- if (remembered && now - remembered.at < KEY_MS) return remembered.id;
45
- const id = nextId(now);
46
- queueOf(queue).push({
47
- id,
48
- body: message.body,
49
- sentAt: now,
50
- visibleAt: now + message.delayMs,
51
- attempts: 0
52
- });
53
- if (message.key !== void 0) keys.set(`${queue}\n${message.key}`, {
54
- id,
55
- at: now
56
- });
57
- return id;
58
- });
164
+ return send(queue, messages);
59
165
  },
60
166
  async receive(queue, { limit, visibilityMs, maxAttempts }) {
61
167
  const now = clock();
62
168
  const out = [];
63
169
  for (const held of [...queues.get(queue) ?? []].sort(order)) {
64
170
  if (out.length === limit || held.visibleAt > now) break;
171
+ if (held.waiting) continue;
65
172
  if (held.receipt !== void 0 && deadLetter(queue, held)) continue;
66
173
  held.attempts += 1;
67
174
  held.visibleAt = now + visibilityMs;
@@ -73,14 +180,15 @@ function standIn(options) {
73
180
  sentAt: held.sentAt,
74
181
  attempt: held.attempts,
75
182
  receipt: held.receipt,
76
- visibleUntil: held.visibleAt
183
+ visibleUntil: held.visibleAt,
184
+ ...held.run !== void 0 ? { run: held.run } : {}
77
185
  });
78
186
  }
79
187
  return out;
80
188
  },
81
189
  async ack(queue, receipt) {
82
190
  const held = delivered(queue, receipt);
83
- if (held) queueOf(queue).splice(queueOf(queue).indexOf(held), 1);
191
+ if (held && held.run === void 0) remove(queue, held);
84
192
  },
85
193
  async retry(queue, receipt, delayMs) {
86
194
  const held = delivered(queue, receipt);
@@ -89,6 +197,12 @@ function standIn(options) {
89
197
  delete held.receipt;
90
198
  delete held.maxAttempts;
91
199
  },
200
+ async extend(queue, receipt, visibilityMs) {
201
+ const held = delivered(queue, receipt);
202
+ if (!held) return void 0;
203
+ held.visibleAt = clock() + visibilityMs;
204
+ return held.visibleAt;
205
+ },
92
206
  async stats(queue) {
93
207
  const now = clock();
94
208
  const held = queues.get(queue) ?? [];
@@ -96,13 +210,201 @@ function standIn(options) {
96
210
  const dead = (queues.get(`${queue}.dead`) ?? []).length;
97
211
  return {
98
212
  depth: counted.length,
99
- ready: counted.filter((m) => m.visibleAt <= now).length,
213
+ ready: counted.filter((m) => !m.waiting && m.visibleAt <= now).length,
100
214
  inFlight: counted.filter((m) => m.receipt !== void 0 && m.visibleAt > now).length,
101
- delayed: counted.filter((m) => m.receipt === void 0 && m.visibleAt > now).length,
215
+ delayed: counted.filter((m) => m.waiting || m.receipt === void 0 && m.visibleAt > now).length,
102
216
  ...counted[0] ? { oldestSentAt: counted[0].sentAt } : {},
103
217
  dead: Math.min(dead, STATS_CAP),
104
218
  ...held.length > 1e3 || dead > 1e3 ? { more: true } : {}
105
219
  };
220
+ },
221
+ async start(queue, run) {
222
+ if (runOf(queue, run.id)) return {
223
+ id: run.id,
224
+ started: false
225
+ };
226
+ const [messageId] = send(queue, [{
227
+ body: run.input,
228
+ delayMs: 0,
229
+ run: run.id,
230
+ ...run.group !== void 0 ? { group: run.group } : {}
231
+ }]);
232
+ const now = clock();
233
+ runs.set(`${queue}\n${run.id}`, {
234
+ id: run.id,
235
+ queue,
236
+ status: "running",
237
+ messageId,
238
+ input: run.input,
239
+ startedAt: now,
240
+ steps: /* @__PURE__ */ new Map(),
241
+ signals: [],
242
+ ...run.timeoutMs !== void 0 ? {
243
+ timeoutMs: run.timeoutMs,
244
+ deadline: now + run.timeoutMs
245
+ } : {},
246
+ ...run.group !== void 0 ? { group: run.group } : {}
247
+ });
248
+ return {
249
+ id: run.id,
250
+ started: true
251
+ };
252
+ },
253
+ async load(queue, runId, receipt) {
254
+ const found = runDelivery(queue, runId, receipt);
255
+ if (!found) return void 0;
256
+ if (!found.over) {
257
+ found.run.status = "running";
258
+ delete found.run.waiting;
259
+ delete found.run.wakeAt;
260
+ }
261
+ return {
262
+ now: clock(),
263
+ run: runOut(found.run)
264
+ };
265
+ },
266
+ async record(queue, runId, receipt, write) {
267
+ const found = runDelivery(queue, runId, receipt);
268
+ if (!found || found.over) return void 0;
269
+ const { held, run } = found;
270
+ const now = clock();
271
+ const step = run.steps.get(write.id);
272
+ if (step && (step.state === "done" || step.state === "failed")) return stepOut(step);
273
+ if (!step && run.steps.size >= MAX_STEPS) {
274
+ endRun(run, "failed", { error: `It recorded more than ${MAX_STEPS} steps.` });
275
+ remove(queue, held);
276
+ return;
277
+ }
278
+ const base = {
279
+ id: write.id,
280
+ seq: step?.seq ?? run.steps.size,
281
+ kind: write.kind,
282
+ failures: step?.failures ?? 0,
283
+ at: step?.at ?? now
284
+ };
285
+ const keep = (kept) => {
286
+ run.steps.set(write.id, kept);
287
+ return stepOut(kept);
288
+ };
289
+ const done = (value, extra = {}) => {
290
+ held.attempts = 0;
291
+ run.status = "running";
292
+ delete run.waiting;
293
+ delete run.wakeAt;
294
+ return keep({
295
+ ...base,
296
+ ...extra,
297
+ state: "done",
298
+ ...value !== void 0 ? { value } : {}
299
+ });
300
+ };
301
+ const parked = (kept, until, status) => {
302
+ run.wakeAt = park(held, run, until);
303
+ run.status = status;
304
+ return keep(kept);
305
+ };
306
+ switch (write.kind) {
307
+ case "run": {
308
+ if ("value" in write) return done(write.value);
309
+ const failures = base.failures + 1;
310
+ if (failures > write.retries) {
311
+ held.attempts = 0;
312
+ return keep({
313
+ ...base,
314
+ state: "failed",
315
+ failures,
316
+ error: write.error
317
+ });
318
+ }
319
+ const until = now + backoffMs(failures);
320
+ return parked({
321
+ ...base,
322
+ state: "retrying",
323
+ failures,
324
+ error: write.error,
325
+ until
326
+ }, until, "running");
327
+ }
328
+ case "sleep": {
329
+ const until = step?.until ?? now + write.ms;
330
+ if (until <= now) return done(void 0, { until });
331
+ return parked({
332
+ ...base,
333
+ state: "sleeping",
334
+ until
335
+ }, until, "sleeping");
336
+ }
337
+ case "wait": {
338
+ const kept = run.signals.find((signal) => !signal.consumed && signal.event === write.event);
339
+ if (kept) {
340
+ kept.consumed = true;
341
+ return done(kept.value, { event: write.event });
342
+ }
343
+ const until = step?.until ?? now + write.timeoutMs;
344
+ if (until <= now) return done(void 0, {
345
+ event: write.event,
346
+ until
347
+ });
348
+ run.waiting = {
349
+ step: write.id,
350
+ event: write.event
351
+ };
352
+ return parked({
353
+ ...base,
354
+ state: "waiting",
355
+ event: write.event,
356
+ until
357
+ }, until, "waiting");
358
+ }
359
+ }
360
+ },
361
+ async finish(queue, runId, receipt, end) {
362
+ const found = runDelivery(queue, runId, receipt);
363
+ if (!found || found.over) return;
364
+ endRun(found.run, "output" in end ? "completed" : "failed", end);
365
+ remove(queue, found.held);
366
+ },
367
+ async signal(queue, runId, signal) {
368
+ const run = runOf(queue, runId);
369
+ if (!run) return "missing";
370
+ if (ended(run.status)) return "ended";
371
+ const again = signal.key === void 0 ? void 0 : run.signals.find((one) => one.key === signal.key);
372
+ if (again) return again.consumed ? "delivered" : "kept";
373
+ if (run.signals.length >= MAX_SIGNALS) throw new QueueError("invalid", `a run takes at most ${MAX_SIGNALS} signals`);
374
+ const waiting = run.status === "waiting" && run.waiting?.event === signal.event ? run.waiting : void 0;
375
+ run.signals.push({
376
+ event: signal.event,
377
+ value: signal.value,
378
+ ...signal.key !== void 0 ? { key: signal.key } : {},
379
+ ...waiting ? { consumed: true } : {}
380
+ });
381
+ if (!waiting) return "kept";
382
+ const step = run.steps.get(waiting.step);
383
+ if (step) run.steps.set(waiting.step, {
384
+ ...step,
385
+ state: "done",
386
+ value: signal.value
387
+ });
388
+ run.status = "running";
389
+ delete run.waiting;
390
+ delete run.wakeAt;
391
+ const held = queues.get(queue)?.find((one) => one.id === run.messageId);
392
+ if (held && held.receipt === void 0) held.visibleAt = Math.min(held.visibleAt, clock());
393
+ return "delivered";
394
+ },
395
+ async cancel(queue, runId) {
396
+ const run = runOf(queue, runId);
397
+ if (!run) return void 0;
398
+ if (!ended(run.status)) {
399
+ const held = [...queues.get(queue) ?? [], ...queues.get(`${queue}.dead`) ?? []].find((one) => one.id === run.messageId);
400
+ if (held) remove(queues.get(queue)?.includes(held) ? queue : `${queue}${DEAD}`, held);
401
+ endRun(run, "cancelled");
402
+ }
403
+ return runOut(run);
404
+ },
405
+ async run(queue, runId) {
406
+ const run = runOf(queue, runId);
407
+ return run && runOut(run);
106
408
  }
107
409
  };
108
410
  }