apps 1.0.0-beta.3 → 2.0.0-next.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 (90) hide show
  1. package/README.md +10 -48
  2. package/check-publish.mjs +7 -0
  3. package/package.json +27 -56
  4. package/src/Access.ts +37 -0
  5. package/src/Accounts.ts +468 -0
  6. package/src/App.ts +11 -0
  7. package/src/Ask.ts +156 -0
  8. package/src/Changes.ts +13 -0
  9. package/src/Http.ts +30 -0
  10. package/src/Provider.ts +146 -0
  11. package/src/Session.ts +52 -0
  12. package/src/Settings.ts +164 -0
  13. package/src/contract.ts +852 -0
  14. package/src/css-modules.d.ts +2 -0
  15. package/src/desktop/Desktop.ts +192 -0
  16. package/src/desktop/bridge.ts +62 -0
  17. package/src/desktop/errors.ts +88 -0
  18. package/src/desktop/index.ts +15 -0
  19. package/src/entry.ts +48 -0
  20. package/src/index.ts +16 -4
  21. package/src/internal/defects.ts +62 -0
  22. package/src/internal/files.ts +369 -0
  23. package/src/internal/host.ts +17 -0
  24. package/src/internal/query.ts +114 -0
  25. package/src/internal/records.ts +838 -0
  26. package/src/internal/retention.ts +87 -0
  27. package/src/internal/retries.ts +185 -0
  28. package/src/internal/telemetry.ts +167 -0
  29. package/src/migrations.ts +110 -0
  30. package/src/page/Accounts.ts +27 -0
  31. package/src/page/Changes.ts +126 -0
  32. package/src/page/Session.ts +46 -0
  33. package/src/page/client.ts +107 -0
  34. package/src/page/errors.ts +15 -0
  35. package/src/page/http.ts +21 -0
  36. package/src/page/index.ts +18 -0
  37. package/src/page/paths.ts +22 -0
  38. package/src/providers/anthropic.ts +26 -0
  39. package/src/providers/github.ts +49 -0
  40. package/src/providers/google.ts +67 -0
  41. package/src/providers/openai.ts +62 -0
  42. package/src/providers/slack.ts +81 -0
  43. package/src/runtime.ts +1540 -0
  44. package/src/testing.ts +660 -0
  45. package/src/text-modules.d.ts +5 -0
  46. package/src/theme.css +50 -0
  47. package/dist/authoring/index.d.ts +0 -393
  48. package/dist/authoring/index.js +0 -36
  49. package/dist/chunk-4OZFMCTT.js +0 -17
  50. package/dist/chunk-A3H32P2J.js +0 -143
  51. package/dist/chunk-B7NEUIJL.js +0 -14
  52. package/dist/chunk-F7GZYEAC.js +0 -41
  53. package/dist/chunk-MUFMJRXR.js +0 -308
  54. package/dist/chunk-S5KFP4JQ.js +0 -20
  55. package/dist/chunk-Y6LLTN7W.js +0 -99
  56. package/dist/chunk-YUZ4TXOY.js +0 -27
  57. package/dist/http/index.d.ts +0 -9
  58. package/dist/http/index.js +0 -6
  59. package/dist/index.d.ts +0 -4
  60. package/dist/index.js +0 -48
  61. package/dist/manifest/contract.d.ts +0 -63
  62. package/dist/manifest/contract.js +0 -8
  63. package/dist/manifest/index.d.ts +0 -20
  64. package/dist/manifest/index.js +0 -16
  65. package/dist/mcp/client.d.ts +0 -9
  66. package/dist/mcp/index.d.ts +0 -11
  67. package/dist/mcp/index.js +0 -7
  68. package/dist/openapi/index.d.ts +0 -14
  69. package/dist/openapi/index.js +0 -7
  70. package/dist/openapi/mapper.d.ts +0 -7
  71. package/dist/runner/index.d.ts +0 -4
  72. package/dist/runner/index.js +0 -66
  73. package/dist/runner/protocol.d.ts +0 -33
  74. package/dist/runner/protocol.js +0 -8
  75. package/dist/runtime/index.d.ts +0 -83
  76. package/dist/runtime/index.js +0 -12
  77. package/dist/workerd/index.d.ts +0 -7
  78. package/dist/workerd/index.js +0 -10
  79. package/src/authoring/index.ts +0 -658
  80. package/src/http/index.ts +0 -26
  81. package/src/manifest/contract.ts +0 -64
  82. package/src/manifest/index.ts +0 -156
  83. package/src/mcp/client.ts +0 -59
  84. package/src/mcp/index.ts +0 -42
  85. package/src/openapi/index.ts +0 -70
  86. package/src/openapi/mapper.ts +0 -25
  87. package/src/runner/index.ts +0 -80
  88. package/src/runner/protocol.ts +0 -54
  89. package/src/runtime/index.ts +0 -550
  90. package/src/workerd/index.ts +0 -17
@@ -0,0 +1,838 @@
1
+ import {
2
+ Cause,
3
+ Context,
4
+ DateTime,
5
+ Duration,
6
+ Effect,
7
+ Exit,
8
+ Layer,
9
+ Option,
10
+ Schema,
11
+ Tracer,
12
+ } from "effect";
13
+ import {
14
+ ClusterCron,
15
+ ClusterSchema,
16
+ Entity,
17
+ EntityAddress,
18
+ EntityId,
19
+ EntityType,
20
+ MessageStorage,
21
+ Sharding,
22
+ } from "effect/cluster";
23
+ import type { Rpc } from "effect/rpc";
24
+ import { SqlClient } from "effect/sql";
25
+ import { Workflow, WorkflowEngine } from "effect/workflow";
26
+ import type {
27
+ RecordedError,
28
+ Result,
29
+ RunControlResult,
30
+ RunRef,
31
+ RunUpdate,
32
+ StepAttempt,
33
+ } from "../contract.ts";
34
+
35
+ export const RUNS_TABLE = "apps_runs";
36
+ /** Stored for a run whose payload the recorder never saw: it cannot be started over. */
37
+ export const UNKNOWN_PAYLOAD = "null";
38
+ export const CRON_PREFIX = "ClusterCron/";
39
+ export const WORKFLOW_PREFIX = "Workflow/";
40
+ export const CLOCK_ENTITY = "Workflow/-/DurableClock";
41
+ export const REPLAYED_ATTRIBUTE = "workflow.replayed";
42
+ export const CRON_EXECUTOR = "executor";
43
+ export const MAX_PENDING = 2_000;
44
+ const TEXT_CHARS = 1_000;
45
+ const PAYLOAD_BYTES = 4_096;
46
+
47
+ export interface RecordsBatch {
48
+ readonly runs: ReadonlyArray<RunUpdate>;
49
+ readonly steps: ReadonlyArray<StepAttempt>;
50
+ readonly dropped: number;
51
+ }
52
+
53
+ export class EffectShapeChanged extends Error {
54
+ override readonly name = "EffectShapeChanged";
55
+ }
56
+
57
+ type AnyWorkflow = Workflow.Workflow<string, Workflow.AnyStructSchema, Schema.Top, Schema.Top>;
58
+ type AnyEntity = Entity.Entity<string, Rpc.Any>;
59
+ interface WorkflowLike {
60
+ readonly _tag: string;
61
+ readonly payloadSchema: Schema.Top;
62
+ }
63
+
64
+ interface CronSchedule {
65
+ readonly calculateNextRunFromPrevious: boolean;
66
+ readonly skipIfOlderThan: Duration.Duration;
67
+ }
68
+
69
+ const plain = (value: unknown): unknown => {
70
+ try {
71
+ return JSON.parse(
72
+ JSON.stringify(value, (_key, inner) =>
73
+ typeof inner === "bigint" ? inner.toString() : inner,
74
+ ),
75
+ );
76
+ } catch {
77
+ return String(value);
78
+ }
79
+ };
80
+
81
+ const clip = (text: string) => (text.length > TEXT_CHARS ? `${text.slice(0, TEXT_CHARS)}…` : text);
82
+
83
+ export const recordedError = (error: unknown): RecordedError => {
84
+ if (typeof error !== "object" || error === null)
85
+ return { tag: null, message: clip(String(error)), detail: null };
86
+ const record = error as Record<string, unknown>;
87
+ const tag =
88
+ typeof record._tag === "string" ? record._tag : error instanceof Error ? error.name : null;
89
+ const message = typeof record.message === "string" ? record.message : String(error);
90
+ const own: Record<string, unknown> = {};
91
+ for (const [key, value] of Object.entries(record)) {
92
+ if (key !== "_tag" && key !== "message" && key !== "stack") own[key] = value;
93
+ }
94
+ const text = JSON.stringify(plain(own));
95
+ return {
96
+ tag,
97
+ message: clip(message),
98
+ detail:
99
+ Object.keys(own).length === 0 || text === undefined || text.length > TEXT_CHARS
100
+ ? null
101
+ : JSON.parse(text),
102
+ };
103
+ };
104
+
105
+ export const causeError = (cause: Cause.Cause<unknown>): RecordedError =>
106
+ recordedError(Cause.squash(cause));
107
+
108
+ const boundedPayload = (encoded: unknown): unknown => {
109
+ const text = JSON.stringify(encoded);
110
+ if (text === undefined) return null;
111
+ const bytes = new TextEncoder().encode(text).byteLength;
112
+ return bytes > PAYLOAD_BYTES ? { truncated: true, bytes } : encoded;
113
+ };
114
+
115
+ const currentTraceId = Effect.map(Effect.option(Effect.currentParentSpan), (span) =>
116
+ Option.match(span, { onNone: () => null, onSome: (value: Tracer.AnySpan) => value.traceId }),
117
+ );
118
+
119
+ const failure = (reason: string, message: string): Result<never> => ({
120
+ ok: false,
121
+ error: { reason, message },
122
+ });
123
+
124
+ export const cronSchedule = (entity: AnyEntity): CronSchedule | undefined =>
125
+ Option.getOrUndefined(Context.getOption(entity.protocol.annotations, ClusterCron.CronSchedule));
126
+
127
+ export const cronRunPayload = (
128
+ entity: AnyEntity,
129
+ dateTime: DateTime.Utc,
130
+ executor: boolean,
131
+ ): unknown => {
132
+ const rpc = entity.protocol.requests.get("run") as
133
+ | { readonly payloadSchema?: unknown }
134
+ | undefined;
135
+ const Payload = rpc?.payloadSchema;
136
+ if (typeof Payload !== "function") {
137
+ throw new EffectShapeChanged(
138
+ `${entity.type} has no "run" request with a class payload: Effect's ClusterCron changed`,
139
+ );
140
+ }
141
+ const payload = new (Payload as new (fields: object) => { readonly dateTime?: unknown })(
142
+ executor ? { dateTime, executor: true } : { dateTime },
143
+ );
144
+ if (!DateTime.isDateTime(payload.dateTime) || !DateTime.Equivalence(payload.dateTime, dateTime)) {
145
+ throw new EffectShapeChanged(
146
+ `${entity.type}'s "run" payload no longer carries dateTime: Effect's ClusterCron changed`,
147
+ );
148
+ }
149
+ return payload;
150
+ };
151
+
152
+ export interface Recorder {
153
+ readonly take: () => RecordsBatch | undefined;
154
+ readonly pending: () => number;
155
+ readonly layer: Layer.Layer<
156
+ WorkflowEngine.WorkflowEngine | Sharding.Sharding,
157
+ never,
158
+ | WorkflowEngine.WorkflowEngine
159
+ | Sharding.Sharding
160
+ | SqlClient.SqlClient
161
+ | MessageStorage.MessageStorage
162
+ >;
163
+ readonly cancel: (run: RunRef) => Effect.Effect<Result<RunControlResult>>;
164
+ readonly rerun: (run: RunRef) => Effect.Effect<Result<RunControlResult>>;
165
+ readonly runJob: (name: string) => Effect.Effect<Result<RunControlResult>>;
166
+ readonly reconcile: Effect.Effect<void>;
167
+ readonly stateCleared: (
168
+ removed: ReadonlyArray<{ readonly workflow: string; readonly executionId: string }>,
169
+ ) => void;
170
+ readonly workflows: () => ReadonlyArray<string>;
171
+ readonly jobs: () => ReadonlyArray<string>;
172
+ }
173
+
174
+ export const makeRecorder = (
175
+ options: { readonly now?: () => number; readonly maxPending?: number } = {},
176
+ ): Recorder => {
177
+ const now = options.now ?? Date.now;
178
+ const maxPending = options.maxPending ?? MAX_PENDING;
179
+ let runs: Array<RunUpdate> = [];
180
+ let steps: Array<StepAttempt> = [];
181
+ let dropped = 0;
182
+ const payloadSent = new Set<string>();
183
+ const sleeping = new Map<string, number>();
184
+ const cancelling = new Set<string>();
185
+ const parkedSeen = new Set<string>();
186
+ let parkedScanned = false;
187
+ const runKey = (ref: RunRef) =>
188
+ ref.kind === "workflow" ? `${ref.workflow}:${ref.executionId}` : `${ref.job}@${ref.slot}`;
189
+ const workflows = new Map<string, AnyWorkflow>();
190
+ const entities = new Map<string, AnyEntity>();
191
+ let engine: WorkflowEngine.WorkflowEngine["Service"] | undefined;
192
+ let sharding: Sharding.Sharding["Service"] | undefined;
193
+ let sql: SqlClient.SqlClient | undefined;
194
+ let storage: MessageStorage.MessageStorage["Service"] | undefined;
195
+ let tableReady = false;
196
+
197
+ const room = () => {
198
+ if (runs.length + steps.length < maxPending) return true;
199
+ dropped += 1;
200
+ return false;
201
+ };
202
+ const record = (update: RunUpdate) => {
203
+ if (room()) runs.push(update);
204
+ };
205
+ const run = (update: RunUpdate) => {
206
+ if (cancelling.has(runKey(update.run))) return;
207
+ record(update);
208
+ };
209
+ const step = (attempt: StepAttempt) => {
210
+ if (cancelling.has(`${attempt.run.workflow}:${attempt.run.executionId}`)) return;
211
+ if (room()) steps.push(attempt);
212
+ };
213
+
214
+ const ensureTable = Effect.suspend(() => {
215
+ if (tableReady || sql === undefined) return Effect.void;
216
+ const client = sql;
217
+ return Effect.gen(function* () {
218
+ yield* client.unsafe(
219
+ `CREATE TABLE IF NOT EXISTS ${RUNS_TABLE} (workflow TEXT NOT NULL, execution_id TEXT NOT NULL, payload TEXT NOT NULL, created_at INTEGER NOT NULL, cancel_requested_at INTEGER, ended_at INTEGER, PRIMARY KEY (workflow, execution_id))`,
220
+ ).raw;
221
+ const columns = yield* client.unsafe<{ readonly name: string }>(
222
+ `SELECT name FROM pragma_table_info('${RUNS_TABLE}')`,
223
+ );
224
+ for (const column of ["cancel_requested_at", "ended_at"]) {
225
+ if (!columns.some((existing) => existing.name === column)) {
226
+ yield* client.unsafe(`ALTER TABLE ${RUNS_TABLE} ADD COLUMN ${column} INTEGER`).raw;
227
+ }
228
+ }
229
+ yield* client.unsafe(
230
+ `CREATE INDEX IF NOT EXISTS ${RUNS_TABLE}_cancels ON ${RUNS_TABLE} (cancel_requested_at) WHERE cancel_requested_at IS NOT NULL`,
231
+ ).raw;
232
+ tableReady = true;
233
+ });
234
+ });
235
+
236
+ const storePayload = (workflow: WorkflowLike, executionId: string, encoded: unknown) =>
237
+ Effect.suspend(() => {
238
+ if (sql === undefined) return Effect.void;
239
+ const client = sql;
240
+ return ensureTable.pipe(
241
+ Effect.andThen(
242
+ client.unsafe(
243
+ `INSERT OR IGNORE INTO ${RUNS_TABLE} (workflow, execution_id, payload, created_at) VALUES (?, ?, ?, ?)`,
244
+ [workflow._tag, executionId, JSON.stringify(encoded), now()],
245
+ ).raw,
246
+ ),
247
+ );
248
+ }).pipe(
249
+ Effect.asVoid,
250
+ Effect.catchCause(() => Effect.void),
251
+ );
252
+
253
+ const readPayload = (workflow: WorkflowLike, executionId: string) =>
254
+ Effect.suspend(() => {
255
+ if (sql === undefined) return Effect.succeed(undefined);
256
+ const client = sql;
257
+ return ensureTable.pipe(
258
+ Effect.andThen(
259
+ client.unsafe<{ readonly payload: string }>(
260
+ `SELECT payload FROM ${RUNS_TABLE} WHERE workflow = ? AND execution_id = ?`,
261
+ [workflow._tag, executionId],
262
+ ),
263
+ ),
264
+ Effect.map((rows) =>
265
+ rows[0] === undefined || rows[0].payload === UNKNOWN_PAYLOAD
266
+ ? undefined
267
+ : (JSON.parse(rows[0].payload) as unknown),
268
+ ),
269
+ );
270
+ }).pipe(Effect.catchCause(() => Effect.succeed(undefined)));
271
+
272
+ const markEnded = (workflow: string, executionId: string, at: number | null) =>
273
+ Effect.suspend(() => {
274
+ if (sql === undefined) return Effect.void;
275
+ const client = sql;
276
+ return ensureTable.pipe(
277
+ Effect.andThen(
278
+ client.unsafe(
279
+ `INSERT INTO ${RUNS_TABLE} (workflow, execution_id, payload, created_at, ended_at) VALUES (?, ?, ?, ?, ?)
280
+ ON CONFLICT (workflow, execution_id) DO UPDATE SET ended_at = excluded.ended_at`,
281
+ [workflow, executionId, UNKNOWN_PAYLOAD, now(), at],
282
+ ).raw,
283
+ ),
284
+ );
285
+ }).pipe(
286
+ Effect.asVoid,
287
+ Effect.catchCause(() => Effect.void),
288
+ );
289
+
290
+ const markCancel = (workflow: string, executionId: string, at: number | null) =>
291
+ Effect.suspend(() => {
292
+ if (sql === undefined) return Effect.void;
293
+ const client = sql;
294
+ return ensureTable.pipe(
295
+ Effect.andThen(
296
+ client.unsafe(
297
+ `UPDATE ${RUNS_TABLE} SET cancel_requested_at = ? WHERE workflow = ? AND execution_id = ?`,
298
+ [at, workflow, executionId],
299
+ ).raw,
300
+ ),
301
+ );
302
+ }).pipe(
303
+ Effect.asVoid,
304
+ Effect.catchCause(() => Effect.void),
305
+ );
306
+
307
+ const markedCancels = Effect.suspend(() => {
308
+ if (sql === undefined)
309
+ return Effect.succeed(
310
+ [] as ReadonlyArray<{ readonly workflow: string; readonly execution_id: string }>,
311
+ );
312
+ const client = sql;
313
+ return ensureTable.pipe(
314
+ Effect.andThen(
315
+ client.unsafe<{ readonly workflow: string; readonly execution_id: string }>(
316
+ `SELECT workflow, execution_id FROM ${RUNS_TABLE} WHERE cancel_requested_at IS NOT NULL`,
317
+ ),
318
+ ),
319
+ );
320
+ }).pipe(
321
+ Effect.catchCause(() =>
322
+ Effect.succeed(
323
+ [] as ReadonlyArray<{ readonly workflow: string; readonly execution_id: string }>,
324
+ ),
325
+ ),
326
+ );
327
+
328
+ const isInterruption = (cause: Cause.Cause<unknown>) => {
329
+ if (Cause.hasInterruptsOnly(cause)) return true;
330
+ const error = Cause.squash(cause);
331
+ return (
332
+ typeof error === "object" &&
333
+ error !== null &&
334
+ /Interrupt/u.test(
335
+ String((error as { readonly _tag?: unknown })._tag ?? (error as Error).name),
336
+ )
337
+ );
338
+ };
339
+
340
+ const reportParked = Effect.suspend(() => {
341
+ if (sql === undefined || parkedScanned) return Effect.void;
342
+ parkedScanned = true;
343
+ const client = sql;
344
+ return Effect.gen(function* () {
345
+ const stored = yield* client.unsafe<{
346
+ readonly entity_type: string;
347
+ readonly entity_id: string;
348
+ }>(
349
+ `SELECT DISTINCT
350
+ CASE WHEN m.entity_type = ? THEN coalesce(
351
+ (SELECT w.entity_type FROM cluster_messages w
352
+ WHERE w.entity_id = m.entity_id AND w.entity_type LIKE '${WORKFLOW_PREFIX}%' AND w.entity_type != ? LIMIT 1),
353
+ m.entity_type) ELSE m.entity_type END AS entity_type,
354
+ m.entity_id AS entity_id
355
+ FROM cluster_messages m
356
+ WHERE m.processed = 0 AND (m.entity_type LIKE '${WORKFLOW_PREFIX}%' OR m.entity_type LIKE '${CRON_PREFIX}%')`,
357
+ [CLOCK_ENTITY, CLOCK_ENTITY],
358
+ );
359
+ for (const { entity_type, entity_id } of stored) {
360
+ if (entity_type === CLOCK_ENTITY) continue;
361
+ const key = `${entity_type}|${entity_id}`;
362
+ if (parkedSeen.has(key)) continue;
363
+ const workflow = entity_type.startsWith(WORKFLOW_PREFIX)
364
+ ? entity_type.slice(WORKFLOW_PREFIX.length)
365
+ : undefined;
366
+ const job = workflow === undefined ? entity_type.slice(CRON_PREFIX.length) : undefined;
367
+ if (workflow !== undefined && workflows.has(workflow)) continue;
368
+ if (job !== undefined && entities.has(entity_type)) continue;
369
+ parkedSeen.add(key);
370
+ record({
371
+ run:
372
+ workflow !== undefined
373
+ ? { kind: "workflow", workflow, executionId: entity_id }
374
+ : { kind: "scheduled", job: job ?? entity_type, slot: entity_id },
375
+ status: "parked",
376
+ time: now(),
377
+ error: {
378
+ tag: "Parked",
379
+ message: `Waits for the ${workflow !== undefined ? `workflow ${workflow}` : `scheduled job ${job}`}, which this version does not register. It resumes when a version registers it again.`,
380
+ detail: { waitingFor: workflow !== undefined ? { workflow } : { job } },
381
+ },
382
+ });
383
+ }
384
+ });
385
+ }).pipe(Effect.catchCause(() => Effect.void));
386
+
387
+ const reconcile: Recorder["reconcile"] = Effect.gen(function* () {
388
+ yield* reportParked;
389
+ if (engine === undefined) return;
390
+ const marked = yield* markedCancels;
391
+ const keys = new Set([
392
+ ...cancelling,
393
+ ...marked.map((row) => `${row.workflow}:${row.execution_id}`),
394
+ ]);
395
+ for (const key of keys) {
396
+ const split = key.indexOf(":");
397
+ const name = key.slice(0, split);
398
+ const executionId = key.slice(split + 1);
399
+ const workflow = workflows.get(name);
400
+ if (workflow === undefined) continue;
401
+ cancelling.add(key);
402
+ const result = yield* engine.poll(workflow, executionId);
403
+ if (Option.isNone(result) || result.value._tag !== "Complete") continue;
404
+ const exit = (result.value as { readonly exit: Exit.Exit<unknown, unknown> }).exit;
405
+ const ref = workflowRef(workflow, executionId);
406
+ const time = now();
407
+ cancelling.delete(key);
408
+ yield* markCancel(name, executionId, null);
409
+ yield* markEnded(name, executionId, time);
410
+ if (Exit.isSuccess(exit))
411
+ record({ run: ref, status: "completed", time, error: null, wakeAt: null });
412
+ else if (isInterruption(exit.cause))
413
+ record({ run: ref, status: "cancelled", time, wakeAt: null });
414
+ else
415
+ record({ run: ref, status: "failed", time, error: causeError(exit.cause), wakeAt: null });
416
+ }
417
+ }).pipe(Effect.catchCause(() => Effect.void)) as Effect.Effect<void>;
418
+
419
+ const encodePayload = (workflow: WorkflowLike, payload: unknown) =>
420
+ Schema.encodeUnknownEffect(Schema.toCodecJson(workflow.payloadSchema))(payload).pipe(
421
+ Effect.catchCause(() => Effect.succeed(plain(payload))),
422
+ ) as Effect.Effect<unknown>;
423
+
424
+ const workflowRef = (workflow: WorkflowLike, executionId: string): RunRef => ({
425
+ kind: "workflow",
426
+ workflow: workflow._tag,
427
+ executionId,
428
+ });
429
+
430
+ const wrapEngine = (
431
+ upstream: WorkflowEngine.WorkflowEngine["Service"],
432
+ ): WorkflowEngine.WorkflowEngine["Service"] => {
433
+ const wrapped: WorkflowEngine.WorkflowEngine["Service"] = {
434
+ ...upstream,
435
+ register: (workflow, execute) => {
436
+ workflows.set(workflow._tag, workflow as unknown as AnyWorkflow);
437
+ return upstream.register(workflow, (payload, executionId) =>
438
+ Effect.gen(function* () {
439
+ const ref = workflowRef(workflow, executionId);
440
+ const key = `${workflow._tag}:${executionId}`;
441
+ const traceId = yield* currentTraceId;
442
+ const first = !payloadSent.has(key);
443
+ const encoded = first ? yield* encodePayload(workflow, payload) : undefined;
444
+ if (first) payloadSent.add(key);
445
+ run({
446
+ run: ref,
447
+ status: "running",
448
+ time: now(),
449
+ traceId,
450
+ ...(first ? { payload: boundedPayload(encoded) } : {}),
451
+ });
452
+ const instance = yield* WorkflowEngine.WorkflowInstance;
453
+ sleeping.delete(key);
454
+ return yield* execute(payload, executionId).pipe(
455
+ Effect.onExit((exit) =>
456
+ Effect.andThen(
457
+ Exit.isSuccess(exit) ||
458
+ (!Cause.hasInterruptsOnly(exit.cause) &&
459
+ !Context.get(workflow.annotations, Workflow.SuspendOnFailure))
460
+ ? markEnded(workflow._tag, executionId, now())
461
+ : Effect.void,
462
+ Effect.sync(() => {
463
+ const wakeAt = sleeping.get(key);
464
+ sleeping.delete(key);
465
+ const time = now();
466
+ if (Exit.isSuccess(exit))
467
+ return run({
468
+ run: ref,
469
+ status: "completed",
470
+ time,
471
+ error: null,
472
+ wakeAt: null,
473
+ });
474
+ if (!Cause.hasInterruptsOnly(exit.cause)) {
475
+ const suspends = Context.get(workflow.annotations, Workflow.SuspendOnFailure);
476
+ return run({
477
+ run: ref,
478
+ status: suspends ? "suspended" : "failed",
479
+ time,
480
+ error: causeError(exit.cause),
481
+ wakeAt: null,
482
+ });
483
+ }
484
+ if (instance.failed && instance.cause !== undefined) {
485
+ return run({
486
+ run: ref,
487
+ status: "suspended",
488
+ time,
489
+ error: causeError(instance.cause),
490
+ wakeAt: null,
491
+ });
492
+ }
493
+ run(
494
+ wakeAt === undefined
495
+ ? { run: ref, status: "waiting", time }
496
+ : { run: ref, status: "sleeping", time, wakeAt },
497
+ );
498
+ }),
499
+ ),
500
+ ),
501
+ );
502
+ }),
503
+ );
504
+ },
505
+ execute: (workflow, executeOptions) =>
506
+ Effect.gen(function* () {
507
+ workflows.set(workflow._tag, workflow as unknown as AnyWorkflow);
508
+ const encoded = yield* encodePayload(workflow, executeOptions.payload);
509
+ yield* storePayload(workflow, executeOptions.executionId, encoded);
510
+ return yield* upstream.execute(workflow, executeOptions);
511
+ }) as never,
512
+ activityExecute: (activity, attempt) =>
513
+ Effect.gen(function* () {
514
+ const instance = yield* WorkflowEngine.WorkflowInstance;
515
+ const traceId = yield* currentTraceId;
516
+ let ranAt: number | undefined;
517
+ let ranFor = 0;
518
+ const observed = Object.create(activity, {
519
+ executeEncoded: {
520
+ value: Effect.suspend(() => {
521
+ ranAt = now();
522
+ return activity.executeEncoded;
523
+ }).pipe(
524
+ Effect.onExit(() =>
525
+ Effect.sync(() => {
526
+ ranFor = now() - (ranAt ?? now());
527
+ }),
528
+ ),
529
+ ),
530
+ },
531
+ }) as typeof activity;
532
+ const calledAt = now();
533
+ const result = yield* upstream.activityExecute(observed, attempt);
534
+ const ran = ranAt !== undefined;
535
+ yield* Effect.annotateCurrentSpan(REPLAYED_ATTRIBUTE, !ran);
536
+ const base = {
537
+ run: { workflow: instance.workflow._tag, executionId: instance.executionId },
538
+ step: activity.name,
539
+ attempt,
540
+ replayed: !ran,
541
+ startTime: ranAt ?? calledAt,
542
+ durationMs: ran ? ranFor : 0,
543
+ traceId,
544
+ };
545
+ if (result._tag === "Complete") {
546
+ const failed = Exit.isFailure(result.exit);
547
+ step({
548
+ ...base,
549
+ status: failed ? "error" : "ok",
550
+ error: failed ? causeError(result.exit.cause) : null,
551
+ });
552
+ } else if (ran) {
553
+ const cause = result.cause;
554
+ step({
555
+ ...base,
556
+ status: "error",
557
+ error: cause === undefined ? null : causeError(cause),
558
+ });
559
+ } else {
560
+ step({ ...base, status: "suspended", error: null });
561
+ }
562
+ return result;
563
+ }) as never,
564
+ interrupt: (workflow, executionId) =>
565
+ Effect.andThen(
566
+ upstream.interrupt(workflow, executionId),
567
+ Effect.suspend(() => {
568
+ const ref = workflowRef(workflow, executionId);
569
+ record({ run: ref, status: "cancelling", time: now(), wakeAt: null });
570
+ cancelling.add(runKey(ref));
571
+ return markCancel(workflow._tag, executionId, now());
572
+ }),
573
+ ),
574
+ scheduleClock: (workflow, clockOptions) =>
575
+ Effect.gen(function* () {
576
+ const key = `${workflow._tag}:${clockOptions.executionId}`;
577
+ const wakeAt = now() + Duration.toMillis(clockOptions.clock.duration);
578
+ // external: a replay schedules every sleep the body reaches again, those already over included, so only a sleep whose clock has not fired yet says when the run wakes.
579
+ const instance = yield* Effect.serviceOption(WorkflowEngine.WorkflowInstance);
580
+ const over =
581
+ Option.isSome(instance) &&
582
+ Option.isSome(
583
+ yield* upstream
584
+ .deferredResult(clockOptions.clock.deferred)
585
+ .pipe(Effect.provideService(WorkflowEngine.WorkflowInstance, instance.value)),
586
+ );
587
+ if (!over) sleeping.set(key, Math.min(sleeping.get(key) ?? wakeAt, wakeAt));
588
+ return yield* upstream.scheduleClock(workflow, clockOptions);
589
+ }),
590
+ };
591
+ return wrapped;
592
+ };
593
+
594
+ const wrapRunHandler =
595
+ (
596
+ entity: AnyEntity,
597
+ schedule: CronSchedule,
598
+ address: EntityAddress.EntityAddress | undefined,
599
+ handler: (request: {
600
+ readonly payload: { readonly dateTime: DateTime.Utc };
601
+ }) => Effect.Effect<unknown, unknown, unknown>,
602
+ ) =>
603
+ (request: { readonly payload: { readonly dateTime: DateTime.Utc } }) => {
604
+ const joinsChain =
605
+ schedule.calculateNextRunFromPrevious &&
606
+ address !== undefined &&
607
+ address.entityId !== CRON_EXECUTOR;
608
+ if (joinsChain) return handler(request);
609
+ const dateTime = request.payload.dateTime;
610
+ const ref: RunRef = {
611
+ kind: "scheduled",
612
+ job: entity.type.slice(CRON_PREFIX.length),
613
+ slot: DateTime.formatIso(dateTime),
614
+ };
615
+ const tooOld =
616
+ DateTime.toEpochMillis(dateTime) < now() - Duration.toMillis(schedule.skipIfOlderThan);
617
+ if (tooOld) {
618
+ return handler(request).pipe(
619
+ Effect.ensuring(Effect.sync(() => run({ run: ref, status: "skipped", time: now() }))),
620
+ );
621
+ }
622
+ return Effect.gen(function* () {
623
+ const traceId = yield* currentTraceId;
624
+ run({ run: ref, status: "running", time: now(), traceId });
625
+ return yield* handler(request).pipe(
626
+ Effect.onExit((exit) =>
627
+ Effect.sync(() => {
628
+ if (Exit.isSuccess(exit))
629
+ return run({ run: ref, status: "completed", time: now(), error: null });
630
+ if (Cause.hasInterruptsOnly(exit.cause)) return;
631
+ run({ run: ref, status: "retrying", time: now(), error: causeError(exit.cause) });
632
+ }),
633
+ ),
634
+ );
635
+ });
636
+ };
637
+
638
+ const wrapSharding = (upstream: Sharding.Sharding["Service"]): Sharding.Sharding["Service"] => ({
639
+ ...upstream,
640
+ registerEntity: (entity, handlers, registerOptions) => {
641
+ const schedule = entity.type.startsWith(CRON_PREFIX)
642
+ ? cronSchedule(entity as unknown as AnyEntity)
643
+ : undefined;
644
+ if (schedule === undefined) return upstream.registerEntity(entity, handlers, registerOptions);
645
+ entities.set(entity.type, entity as unknown as AnyEntity);
646
+ const observed = Effect.flatMap(Effect.serviceOption(Entity.CurrentAddress), (address) =>
647
+ Effect.map(handlers, (built) => {
648
+ const original = (built as Record<string, unknown>).run;
649
+ if (typeof original !== "function") return built;
650
+ return {
651
+ ...built,
652
+ run: wrapRunHandler(
653
+ entity as unknown as AnyEntity,
654
+ schedule,
655
+ Option.getOrUndefined(address),
656
+ original as never,
657
+ ),
658
+ };
659
+ }),
660
+ );
661
+ return upstream.registerEntity(entity, observed as typeof handlers, registerOptions);
662
+ },
663
+ });
664
+
665
+ const workflowAddresses = (
666
+ workflow: AnyWorkflow,
667
+ executionId: string,
668
+ shards: Sharding.Sharding["Service"],
669
+ ) => {
670
+ const id = EntityId.make(executionId);
671
+ const group = Context.get(workflow.annotations, ClusterSchema.ShardGroup)(id);
672
+ return [`${WORKFLOW_PREFIX}${workflow._tag}`, CLOCK_ENTITY].map((type) =>
673
+ EntityAddress.make({
674
+ entityType: EntityType.make(type),
675
+ entityId: id,
676
+ shardId: shards.getShardId(id, group),
677
+ }),
678
+ );
679
+ };
680
+
681
+ const notRunning = (what: string) =>
682
+ failure("NotRunning", `${what} is not running yet: the app has not started its runner.`);
683
+
684
+ const cancel: Recorder["cancel"] = (ref) =>
685
+ Effect.gen(function* () {
686
+ if (engine === undefined || sharding === undefined) return notRunning("The engine");
687
+ if (ref.kind === "workflow") {
688
+ const workflow = workflows.get(ref.workflow);
689
+ if (workflow === undefined)
690
+ return failure("UnknownWorkflow", `The app registers no workflow named ${ref.workflow}.`);
691
+ const result = yield* engine.poll(workflow, ref.executionId);
692
+ if (Option.isNone(result)) return failure("RunNotFound", "The app has no such run.");
693
+ if (result.value._tag === "Complete") {
694
+ return failure("RunEnded", "The run has already ended. Run it again with rerun instead.");
695
+ }
696
+ yield* engine.interrupt(workflow, ref.executionId);
697
+ return { ok: true, value: { run: ref, action: "cancelled" } } as const;
698
+ }
699
+ const entity = entities.get(`${CRON_PREFIX}${ref.job}`);
700
+ const schedule = entity === undefined ? undefined : cronSchedule(entity);
701
+ if (entity === undefined || schedule === undefined)
702
+ return failure("UnknownJob", `The app registers no scheduled job named ${ref.job}.`);
703
+ if (storage === undefined) return notRunning("The message storage");
704
+ const entityId = EntityId.make(
705
+ schedule.calculateNextRunFromPrevious ? CRON_EXECUTOR : ref.slot,
706
+ );
707
+ const group = Context.get(entity.protocol.annotations, ClusterSchema.ShardGroup)(entityId);
708
+ yield* storage.clearAddress(
709
+ EntityAddress.make({
710
+ entityType: EntityType.make(entity.type),
711
+ entityId,
712
+ shardId: sharding.getShardId(entityId, group),
713
+ }),
714
+ );
715
+ run({ run: ref, status: "cancelled", time: now() });
716
+ return { ok: true, value: { run: ref, action: "cancelled" } } as const;
717
+ }).pipe(
718
+ Effect.catchCause((cause) =>
719
+ Effect.succeed(failure("CancelFailed", causeError(cause).message)),
720
+ ),
721
+ ) as Effect.Effect<Result<RunControlResult>>;
722
+
723
+ const runJob: Recorder["runJob"] = (name) =>
724
+ Effect.gen(function* () {
725
+ if (sharding === undefined) return notRunning("The scheduler");
726
+ const entity = entities.get(`${CRON_PREFIX}${name}`);
727
+ const schedule = entity === undefined ? undefined : cronSchedule(entity);
728
+ if (entity === undefined || schedule === undefined)
729
+ return failure("UnknownJob", `The app registers no scheduled job named ${name}.`);
730
+ const at = yield* DateTime.now;
731
+ const payload = cronRunPayload(entity, at, schedule.calculateNextRunFromPrevious);
732
+ const client = (yield* sharding.makeClient(entity)) as unknown as (id: string) => {
733
+ readonly run: (
734
+ payload: unknown,
735
+ options: { readonly discard: true },
736
+ ) => Effect.Effect<void, unknown>;
737
+ };
738
+ const address = schedule.calculateNextRunFromPrevious
739
+ ? CRON_EXECUTOR
740
+ : DateTime.formatIso(at);
741
+ yield* client(address).run(payload, { discard: true });
742
+ return {
743
+ ok: true,
744
+ value: {
745
+ run: { kind: "scheduled", job: name, slot: DateTime.formatIso(at) },
746
+ action: "started",
747
+ },
748
+ } as const;
749
+ }).pipe(
750
+ Effect.catchCause((cause) =>
751
+ Effect.succeed(failure("RunJobFailed", causeError(cause).message)),
752
+ ),
753
+ ) as Effect.Effect<Result<RunControlResult>>;
754
+
755
+ const rerun: Recorder["rerun"] = (ref) =>
756
+ Effect.gen(function* () {
757
+ if (ref.kind === "scheduled") return yield* runJob(ref.job);
758
+ if (engine === undefined || sharding === undefined) return notRunning("The engine");
759
+ const workflow = workflows.get(ref.workflow);
760
+ if (workflow === undefined)
761
+ return failure("UnknownWorkflow", `The app registers no workflow named ${ref.workflow}.`);
762
+ const result = yield* engine.poll(workflow, ref.executionId);
763
+ if (Option.isNone(result)) return failure("RunNotFound", "The app has no such run.");
764
+ const ended =
765
+ result.value._tag === "Complete" ||
766
+ (result.value as { readonly failed?: boolean }).failed === true;
767
+ if (!ended)
768
+ return failure("RunNotEnded", "The run has not ended. Cancel it first, then run it again.");
769
+ const encoded = yield* readPayload(workflow, ref.executionId);
770
+ if (encoded === undefined)
771
+ return failure(
772
+ "PayloadUnknown",
773
+ "The app has no stored payload for this run, so it cannot be started over.",
774
+ );
775
+ const payload = yield* Schema.decodeUnknownEffect(Schema.toCodecJson(workflow.payloadSchema))(
776
+ encoded,
777
+ );
778
+ if (storage === undefined) return notRunning("The message storage");
779
+ for (const address of workflowAddresses(workflow, ref.executionId, sharding))
780
+ yield* storage.clearAddress(address);
781
+ payloadSent.delete(`${workflow._tag}:${ref.executionId}`);
782
+ cancelling.delete(runKey(ref));
783
+ yield* markCancel(workflow._tag, ref.executionId, null);
784
+ yield* markEnded(workflow._tag, ref.executionId, null);
785
+ yield* engine.execute(workflow, {
786
+ executionId: ref.executionId,
787
+ payload: payload as object,
788
+ discard: true,
789
+ });
790
+ return { ok: true, value: { run: ref, action: "restarted" } } as const;
791
+ }).pipe(
792
+ Effect.catchCause((cause) =>
793
+ Effect.succeed(failure("RerunFailed", causeError(cause).message)),
794
+ ),
795
+ ) as Effect.Effect<Result<RunControlResult>>;
796
+
797
+ const layer: Recorder["layer"] = Layer.effectContext(
798
+ Effect.gen(function* () {
799
+ sql = yield* SqlClient.SqlClient;
800
+ storage = yield* MessageStorage.MessageStorage;
801
+ tableReady = false;
802
+ parkedScanned = false;
803
+ sharding = wrapSharding(yield* Sharding.Sharding);
804
+ engine = wrapEngine(yield* WorkflowEngine.WorkflowEngine);
805
+ return Context.make(WorkflowEngine.WorkflowEngine, engine).pipe(
806
+ Context.add(Sharding.Sharding, sharding),
807
+ );
808
+ }),
809
+ );
810
+
811
+ return {
812
+ take: () => {
813
+ if (runs.length === 0 && steps.length === 0 && dropped === 0) return undefined;
814
+ const batch = { runs, steps, dropped };
815
+ runs = [];
816
+ steps = [];
817
+ dropped = 0;
818
+ return batch;
819
+ },
820
+ pending: () => runs.length + steps.length,
821
+ layer,
822
+ cancel,
823
+ rerun,
824
+ runJob,
825
+ reconcile,
826
+ stateCleared: (removed) => {
827
+ for (const { workflow, executionId } of removed)
828
+ record({
829
+ run: { kind: "workflow", workflow, executionId },
830
+ status: "completed",
831
+ time: now(),
832
+ stateCleared: true,
833
+ });
834
+ },
835
+ workflows: () => [...workflows.keys()],
836
+ jobs: () => [...entities.keys()].map((type) => type.slice(CRON_PREFIX.length)),
837
+ };
838
+ };