apps 1.0.0-beta.4 → 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 -422
  48. package/dist/authoring/index.js +0 -36
  49. package/dist/chunk-2DVKSPQH.js +0 -312
  50. package/dist/chunk-4OZFMCTT.js +0 -17
  51. package/dist/chunk-535V5K64.js +0 -155
  52. package/dist/chunk-B7NEUIJL.js +0 -14
  53. package/dist/chunk-DP6UJCMX.js +0 -27
  54. package/dist/chunk-QA72XJZU.js +0 -41
  55. package/dist/chunk-S5KFP4JQ.js +0 -20
  56. package/dist/chunk-XYT6GZ7M.js +0 -99
  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 -686
  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 -554
  90. package/src/workerd/index.ts +0 -17
package/src/runtime.ts ADDED
@@ -0,0 +1,1540 @@
1
+ /**
2
+ * The runtime wrapper: turns an app's default-exported Layer into what the
3
+ * host loads (contract `AppObject` and `AppEntrypoint`).
4
+ *
5
+ * Inside the object, which the host runs as a facet with its own SQLite:
6
+ *
7
+ * - The app's Layer is built once into a context, with Effect's own services
8
+ * beneath it: `SqlClient` over the object's SQLite, `HttpRouter`, a single
9
+ * process cluster (`SingleRunner`'s parts, runner state in SQL) with
10
+ * `ClusterWorkflowEngine.layer`, `KeyValueStore` in a table, `FileSystem`,
11
+ * `Config`, `Tracer` and `Logger` over the host's capabilities, and Effect's
12
+ * fetch `HttpClient`.
13
+ * - `fetch` goes into the app's `HttpRouter`, streaming both ways.
14
+ * - Background work: the app tells the host when it next wants `wake()`
15
+ * (facets cannot set alarms). That time is the earliest unprocessed cluster
16
+ * message with a `deliver_at`, and at most 30 s away while a workflow body
17
+ * runs, so an abort mid-run is picked up. Every `DurableClock.sleep` is
18
+ * stored (`InMemoryThreshold` 0) because an in-memory timer dies with the
19
+ * object.
20
+ * - The host, not the app, decides when to let the app go: it asks `status()`
21
+ * after each call and aborts the facet when nothing is in flight. Nothing
22
+ * here survives that abort, and nothing needs to: a new copy re-reads the
23
+ * database, and re-acquires the runner's own shard locks without waiting.
24
+ *
25
+ * The bundle's default entrypoint answers `describe()` without a database: it
26
+ * builds the app's Layer against stand-in services that record what the app
27
+ * registers (scheduled jobs, workflows) and refuse any I/O.
28
+ */
29
+ import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
30
+ import * as SqliteClient from "@effect/sql-sqlite-do/SqliteClient";
31
+ import * as SqliteMigrator from "@effect/sql-sqlite-do/SqliteMigrator";
32
+ import {
33
+ Cause,
34
+ ConfigProvider,
35
+ Context,
36
+ Cron,
37
+ DateTime,
38
+ Duration,
39
+ Effect,
40
+ ErrorReporter,
41
+ Exit,
42
+ Layer,
43
+ Option,
44
+ Scope,
45
+ Tracer,
46
+ } from "effect";
47
+ import * as Digest from "effect/crypto/Digest";
48
+ import * as Defects from "./internal/defects.ts";
49
+ import {
50
+ ClusterCron,
51
+ ClusterWorkflowEngine,
52
+ Entity,
53
+ MessageStorage,
54
+ RunnerHealth,
55
+ Runners,
56
+ RunnerStorage,
57
+ Sharding,
58
+ ShardingConfig,
59
+ SqlMessageStorage,
60
+ SqlRunnerStorage,
61
+ } from "effect/cluster";
62
+ import { FetchHttpClient, HttpEffect, HttpRouter } from "effect/http";
63
+ import { KeyValueStore } from "effect/persistence";
64
+ import { Migrator, SqlClient } from "effect/sql";
65
+ import { DurableClock, WorkflowEngine } from "effect/workflow";
66
+ import * as Access from "./Access.ts";
67
+ import * as Http from "./Http.ts";
68
+ import * as Accounts from "./Accounts.ts";
69
+ import * as Settings from "./Settings.ts";
70
+ import {
71
+ type AccountEvent,
72
+ type AccountEventResult,
73
+ type AccountProfile,
74
+ type AccountRef,
75
+ type AppDescription,
76
+ type AppEntrypoint,
77
+ type AppEnv,
78
+ type AppObject,
79
+ type AppStatus,
80
+ type CheckResult,
81
+ type ParkedRuns,
82
+ CONTRACT_VERSION,
83
+ type McpDescription,
84
+ type MigrateResult,
85
+ type QueryRequest,
86
+ type QueryResult,
87
+ type Result,
88
+ type RunControlResult,
89
+ type RunRef,
90
+ type ScheduledJobDescription,
91
+ type Settled,
92
+ IDENTITY_HEADER,
93
+ START_FAILURE_HEADER,
94
+ type StartFailure,
95
+ type StartFailureBody,
96
+ type TelemetryBatch,
97
+ } from "./contract.ts";
98
+ import * as Files from "./internal/files.ts";
99
+ import { Host } from "./internal/host.ts";
100
+ import { readOnlyQuery } from "./internal/query.ts";
101
+ import { makeRecorder } from "./internal/records.ts";
102
+ import * as Retention from "./internal/retention.ts";
103
+ import * as Retries from "./internal/retries.ts";
104
+ import { makeTelemetry } from "./internal/telemetry.ts";
105
+
106
+ /** A statement that writes: `INSERT`, `UPDATE`, `DELETE`, `REPLACE`, or one of those after `WITH`. */
107
+ const authorWrite =
108
+ /^\s*(insert|update|delete|replace|with\b[\s\S]*\b(insert|update|delete|replace))\b/iu;
109
+
110
+ /**
111
+ * An app's default export: any Layer. A Layer's output is contravariant and its
112
+ * error and requirements covariant, so every app's Layer is one of these; what
113
+ * it requires is what this runtime provides.
114
+ */
115
+ export type AppLayer = Layer.Layer<never, unknown, unknown>;
116
+
117
+ interface JsonRpcReply {
118
+ readonly result?: {
119
+ readonly serverInfo?: { readonly name: unknown; readonly version: unknown };
120
+ readonly _meta?: {
121
+ readonly "io.modelcontextprotocol/serverInfo"?: {
122
+ readonly name: unknown;
123
+ readonly version: unknown;
124
+ };
125
+ };
126
+ readonly instructions?: unknown;
127
+ };
128
+ }
129
+
130
+ /** What the build step passes alongside the app's Layer. */
131
+ export interface AppBuild {
132
+ /** `migrations/`, keyed `<id>_<name>` as Effect's `Migrator.fromRecord` expects. */
133
+ readonly migrations: Readonly<Record<string, Effect.Effect<void, unknown, SqlClient.SqlClient>>>;
134
+ readonly appsVersion: string;
135
+ readonly effectVersion: string;
136
+ /** Where the app's MCP server is mounted, by convention. */
137
+ readonly mcpPath?: string | undefined;
138
+ }
139
+
140
+ /** Tunables; the defaults are the measured ones. */
141
+ export interface RuntimeOptions {
142
+ /** While a workflow body runs, be woken at least this often. */
143
+ readonly resumeBoundMs?: number | undefined;
144
+ /** `SingleRunner`'s runner storage. Default `"sql"`. For experiments. */
145
+ readonly runnerStorage?: "sql" | "memory" | undefined;
146
+ /** How long ended runs are kept; the defaults are in `internal/retention.ts`. For experiments. */
147
+ readonly retention?: Partial<Retention.Periods> | undefined;
148
+ /** Count a job without a stored next run as in flight. Default true. For experiments. */
149
+ readonly jobGuard?: boolean | undefined;
150
+ }
151
+
152
+ const MIGRATIONS_TABLE = "apps_migrations";
153
+ /** Fixed for good: every stored cluster message carries the shard it was hashed to. */
154
+ const SHARDS_PER_GROUP = 1;
155
+ /** How long `cleanup()` keeps pruning before it answers. */
156
+ const CLEANUP_MS = 5_000;
157
+
158
+ /** A write to the job tables this recent may be about to be acted on. */
159
+ const START_FAILURE_KEY = "apps-start-failure";
160
+ const SET_WAKE_RETRY_MS = 1_000;
161
+
162
+ /**
163
+ * `AppStatus.isolate`: made once per isolate, on first use (a Worker may not make random values
164
+ * while its module loads), and kept in this module's own variable for the isolate's life.
165
+ */
166
+ // oxlint-disable-next-line executor/no-module-level-mutable-state -- it names the isolate, so it must outlive every request the isolate handles
167
+ let isolate: string | undefined;
168
+ const isolateId = (): string => (isolate ??= crypto.randomUUID());
169
+
170
+ /**
171
+ * An error's message with every cause's under it: Effect's `Migrator` reports "Failed to execute
172
+ * statement" and keeps SQLite's own reason ("no such table: …") a few causes down.
173
+ */
174
+ const causeChain = (error: unknown): string => {
175
+ const messages: Array<string> = [];
176
+ let current: unknown = error;
177
+ for (let depth = 0; current !== undefined && current !== null && depth < 8; depth += 1) {
178
+ const message =
179
+ typeof current === "object" && "message" in current
180
+ ? String(current.message)
181
+ : String(current);
182
+ if (message !== "" && !messages.some((seen) => seen.includes(message))) messages.push(message);
183
+ current =
184
+ typeof current === "object"
185
+ ? ((current as { readonly cause?: unknown; readonly reason?: unknown }).cause ??
186
+ (current as { readonly reason?: unknown }).reason)
187
+ : undefined;
188
+ }
189
+ return messages.join(": ");
190
+ };
191
+ const QUIET_MS = 100;
192
+ const OPEN_CALL_RECHECK_MS = 1_000;
193
+ const WAKE_SETTLE_MS = 2_000;
194
+ const WAKE_DRAIN_MS = 10_000;
195
+
196
+ interface Resident {
197
+ readonly context: Context.Context<never>;
198
+ readonly scope: Scope.Closeable;
199
+ readonly handler: (request: Request, context?: Context.Context<never>) => Promise<Response>;
200
+ readonly builtAt: number;
201
+ }
202
+
203
+ /** Thrown inside the object when the app's Layer could not be built; carries the failure. */
204
+ class StartFailed extends Error {
205
+ constructor(readonly failure: StartFailure) {
206
+ super(failure.message);
207
+ }
208
+ }
209
+
210
+ /** The setting names a config failure points at (a `Config.String("X")` with no value points at `X`). */
211
+ const configPaths = (issue: unknown, out: Set<string>) => {
212
+ if (typeof issue !== "object" || issue === null) return;
213
+ const node = issue as {
214
+ _tag?: string;
215
+ path?: ReadonlyArray<unknown>;
216
+ issue?: unknown;
217
+ issues?: ReadonlyArray<unknown>;
218
+ };
219
+ if (node._tag === "Pointer" && Array.isArray(node.path) && node.path.length > 0)
220
+ out.add(node.path.map(String).join("_"));
221
+ configPaths(node.issue, out);
222
+ for (const inner of node.issues ?? []) configPaths(inner, out);
223
+ };
224
+
225
+ /**
226
+ * Why a Layer build failed, for the host. A `ConfigError` names settings: missing
227
+ * when the app's settings have no such key, invalid when they do.
228
+ */
229
+ /** The longest a hook runs: the host stops waiting at 30 seconds, so the hook stops there too. */
230
+ const HOOK_LIMIT = Duration.seconds(30);
231
+
232
+ const classify = (
233
+ cause: Cause.Cause<unknown>,
234
+ settings: Readonly<Record<string, string>> | undefined,
235
+ missingDeclared: ReadonlyArray<string> = [],
236
+ ): StartFailure => {
237
+ const names = new Set<string>(missingDeclared);
238
+ let config = false;
239
+ for (const reason of cause.reasons) {
240
+ const value =
241
+ reason._tag === "Fail" ? reason.error : reason._tag === "Die" ? reason.defect : undefined;
242
+ if (
243
+ typeof value === "object" &&
244
+ value !== null &&
245
+ (value as { _tag?: string })._tag === "ConfigError"
246
+ ) {
247
+ config = true;
248
+ configPaths((value as { cause?: { issue?: unknown } }).cause?.issue, names);
249
+ }
250
+ }
251
+ const message = Cause.pretty(cause);
252
+ const at = Date.now();
253
+ if (!config) return { reason: "start-failed", message, settings: [], at };
254
+ const all = [...names];
255
+ const missing = all.filter((name) => settings?.[name] === undefined);
256
+ return missing.length > 0
257
+ ? { reason: "missing-setting", message, settings: missing, at }
258
+ : { reason: "invalid-setting", message, settings: all, at };
259
+ };
260
+
261
+ /** To a caller who is not a member (a public path, a webhook's sender): that the app is not set up, naming nothing. */
262
+ const forCaller = (request: Request, failure: StartFailure): StartFailure =>
263
+ request.headers.has(IDENTITY_HEADER)
264
+ ? failure
265
+ : {
266
+ reason: failure.reason,
267
+ message: "The app is not set up yet.",
268
+ settings: [],
269
+ at: failure.at,
270
+ };
271
+
272
+ const failureResponse = (failure: StartFailure) => {
273
+ const hint =
274
+ failure.reason === "missing-setting"
275
+ ? `Set ${failure.settings.join(", ")} in the app's settings, then call again.`
276
+ : failure.reason === "invalid-setting"
277
+ ? `Fix the value of ${failure.settings.join(", ")} in the app's settings, then call again.`
278
+ : "The app's code failed to start; see the message, fix the code and deploy again.";
279
+ const body: StartFailureBody = { error: "app_not_started", failure, hint };
280
+ return Response.json(body, {
281
+ status: 503,
282
+ headers: { [START_FAILURE_HEADER]: failure.reason, "retry-after": "60" },
283
+ });
284
+ };
285
+
286
+ export { sqlMigration } from "./migrations.ts";
287
+
288
+ const cronString = (cron: Cron.Cron) => {
289
+ const field = (values: ReadonlySet<number>, min: number, max: number) => {
290
+ if (values.size === 0 || values.size === max - min + 1) return "*";
291
+ return [...values].sort((a, b) => a - b).join(",");
292
+ };
293
+ return [
294
+ field(cron.seconds, 0, 59),
295
+ field(cron.minutes, 0, 59),
296
+ field(cron.hours, 0, 23),
297
+ field(cron.days, 1, 31),
298
+ field(cron.months, 1, 12),
299
+ field(cron.weekdays, 0, 6),
300
+ ].join(" ");
301
+ };
302
+
303
+ const mcpRequest = (
304
+ path: string,
305
+ method: string,
306
+ id: number,
307
+ params: Record<string, unknown> = {},
308
+ ) =>
309
+ new Request(new URL(path, "http://app.internal"), {
310
+ method: "POST",
311
+ headers: {
312
+ "content-type": "application/json",
313
+ accept: "application/json, text/event-stream",
314
+ "mcp-protocol-version": "2026-07-28",
315
+ "mcp-method": method,
316
+ },
317
+ body: JSON.stringify({
318
+ jsonrpc: "2.0",
319
+ id,
320
+ method,
321
+ params: {
322
+ ...params,
323
+ _meta: {
324
+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",
325
+ "io.modelcontextprotocol/clientCapabilities": {},
326
+ "io.modelcontextprotocol/clientInfo": { name: "executor-describe", version: "1" },
327
+ },
328
+ },
329
+ }),
330
+ });
331
+
332
+ const readJsonRpc = async (response: Response): Promise<JsonRpcReply | null> => {
333
+ const text = await response.text();
334
+ if (text.trimStart().startsWith("{")) return JSON.parse(text);
335
+ const data = text.split("\n").find((line) => line.startsWith("data:"));
336
+ return data === undefined ? null : JSON.parse(data.slice(5));
337
+ };
338
+
339
+ const refuse = (what: string) => () => Effect.die(new Error(`describe() runs without ${what}`));
340
+
341
+ /** A Durable Object SQL handle that refuses every statement. */
342
+ const noDatabase = {
343
+ exec: () => {
344
+ throw new Error("describe() runs without a database");
345
+ },
346
+ get databaseSize() {
347
+ return 0;
348
+ },
349
+ } as unknown as SqlStorage;
350
+
351
+ /** A registering entity's scheduled job, when it is a `ClusterCron`. */
352
+ const jobOf = (entity: {
353
+ readonly type: string;
354
+ readonly protocol: { readonly annotations: Context.Context<never> };
355
+ }): ScheduledJobDescription | undefined => {
356
+ const schedule = Context.getOption(entity.protocol.annotations, ClusterCron.CronSchedule);
357
+ if (Option.isNone(schedule)) return undefined;
358
+ const { calculateNextRunFromPrevious, cron, skipIfOlderThan } = schedule.value;
359
+ return {
360
+ name: entity.type.replace(/^ClusterCron\//u, ""),
361
+ cron: cronString(cron),
362
+ timeZone: Option.match(cron.tz, {
363
+ onNone: () => null,
364
+ onSome: (zone) => DateTime.zoneToString(zone),
365
+ }),
366
+ next: Cron.next(cron, DateTime.nowUnsafe()).getTime(),
367
+ calculateNextRunFromPrevious,
368
+ skipIfOlderThanMs: Duration.toMillis(skipIfOlderThan),
369
+ };
370
+ };
371
+
372
+ /** The app's MCP server, as its `server/discover` answers, or `null` with none at `mcpPath`. */
373
+ const discoverMcp = async (
374
+ handler: (request: Request) => Promise<Response>,
375
+ mcpPath: string,
376
+ ): Promise<McpDescription | null> => {
377
+ const response = await handler(mcpRequest(mcpPath, "server/discover", 1));
378
+ if (response.status === 404) return null;
379
+ const result = (await readJsonRpc(response))?.result;
380
+ const serverInfo = result?.serverInfo ?? result?._meta?.["io.modelcontextprotocol/serverInfo"];
381
+ if (serverInfo === undefined) return null;
382
+ return {
383
+ path: mcpPath,
384
+ name: String(serverInfo.name),
385
+ version: String(serverInfo.version),
386
+ instructions: typeof result?.instructions === "string" ? result.instructions : null,
387
+ };
388
+ };
389
+
390
+ const describeApp = async (appLayer: AppLayer, build: AppBuild): Promise<AppDescription> => {
391
+ const mcpPath = build.mcpPath ?? "/mcp";
392
+ const jobs: Array<ScheduledJobDescription> = [];
393
+ const workflows: Array<string> = [];
394
+ const sharding = Layer.succeed(
395
+ Sharding.Sharding,
396
+ new Proxy(
397
+ {
398
+ registerEntity: (entity: {
399
+ readonly type: string;
400
+ readonly protocol: { readonly annotations: Context.Context<never> };
401
+ }) =>
402
+ Effect.sync(() => {
403
+ const job = jobOf(entity);
404
+ if (job !== undefined) jobs.push(job);
405
+ }),
406
+ registerSingleton: () => Effect.void,
407
+ } as Record<PropertyKey, unknown>,
408
+ { get: (target, property) => target[property] ?? refuse("the cluster")() },
409
+ ) as unknown as Sharding.Sharding["Service"],
410
+ );
411
+ const engine = Layer.succeed(
412
+ WorkflowEngine.WorkflowEngine,
413
+ new Proxy(
414
+ {
415
+ register: (workflow: { readonly _tag: string }) =>
416
+ Effect.sync(() => workflows.push(workflow._tag)),
417
+ } as Record<PropertyKey, unknown>,
418
+ {
419
+ get: (target, property) => target[property] ?? refuse("the workflow engine"),
420
+ },
421
+ ) as unknown as WorkflowEngine.WorkflowEngine["Service"],
422
+ );
423
+ const platform = Layer.mergeAll(
424
+ sharding,
425
+ engine,
426
+ SqliteClient.layer({ db: noDatabase }),
427
+ HttpRouter.layer,
428
+ FetchHttpClient.layer,
429
+ KeyValueStore.layerMemory,
430
+ Files.layer(undefined),
431
+ ConfigProvider.layer(ConfigProvider.fromEnvRecord({})),
432
+ Layer.succeed(DurableClock.InMemoryThreshold, Duration.zero),
433
+ );
434
+ const scope = Scope.makeUnsafe();
435
+ const base = {
436
+ contractVersion: CONTRACT_VERSION,
437
+ appsVersion: build.appsVersion,
438
+ effectVersion: build.effectVersion,
439
+ accounts: [...Accounts.declarations],
440
+ settings: [...Settings.declarations],
441
+ publicPaths: [...Access.declarations.public],
442
+ http: { firstResponseMs: Http.declarations.firstResponseMs },
443
+ hooks: Accounts.hookCounts(),
444
+ } as const;
445
+ try {
446
+ const exit = await Effect.runPromiseExit(
447
+ Layer.buildWithScope(
448
+ appLayer.pipe(Layer.provideMerge(platform)) as Layer.Layer<unknown, unknown, never>,
449
+ scope,
450
+ ),
451
+ );
452
+ if (Exit.isFailure(exit)) {
453
+ return {
454
+ ...base,
455
+ mcp: "unknown",
456
+ scheduledJobs: "unknown",
457
+ workflows: "unknown",
458
+ unknownReason: Cause.pretty(exit.cause),
459
+ startFailure: classify(exit.cause, {}),
460
+ };
461
+ }
462
+ const context = exit.value as Context.Context<HttpRouter.HttpRouter>;
463
+ const handler = HttpEffect.toWebHandlerWith(context)(
464
+ Context.get(context, HttpRouter.HttpRouter).asHttpEffect() as never,
465
+ ) as (request: Request) => Promise<Response>;
466
+ const mcp = await discoverMcp(handler, mcpPath);
467
+ return {
468
+ ...base,
469
+ mcp,
470
+ scheduledJobs: jobs,
471
+ workflows,
472
+ unknownReason: null,
473
+ startFailure: null,
474
+ };
475
+ } finally {
476
+ await Effect.runPromise(Scope.close(scope, Exit.void));
477
+ }
478
+ };
479
+
480
+ /** The Durable Object class the host runs as a facet (the entry's `App` export). */
481
+ export type AppClass = new (
482
+ ctx: DurableObjectState,
483
+ env: AppEnv,
484
+ ) => DurableObject<AppEnv> & AppObject;
485
+ /** The bundle's default export. */
486
+ export type EntrypointClass = new (
487
+ ctx: ExecutionContext,
488
+ env: AppEnv,
489
+ ) => WorkerEntrypoint<AppEnv> & AppEntrypoint;
490
+
491
+ /**
492
+ * The bundle's default export: `describe()`, with no object and no database.
493
+ * The build step calls this in the bundle's entry (see `entrySource`).
494
+ */
495
+ export const makeEntrypoint = (appLayer: AppLayer, build: AppBuild): EntrypointClass =>
496
+ class Entrypoint extends WorkerEntrypoint<AppEnv> implements AppEntrypoint {
497
+ describe(): Promise<AppDescription> {
498
+ return describeApp(appLayer, build);
499
+ }
500
+ };
501
+
502
+ /**
503
+ * Wrap the app's Layer as the Durable Object class the host loads (the entry's
504
+ * `App` export). The build step calls this in the bundle's entry; authors never do.
505
+ */
506
+ export const makeApp = (
507
+ appLayer: AppLayer,
508
+ build: AppBuild,
509
+ options: RuntimeOptions = {},
510
+ ): AppClass => {
511
+ const resumeBoundMs = options.resumeBoundMs ?? 30_000;
512
+ const runnerStorage = options.runnerStorage ?? "sql";
513
+ const retention: Retention.Periods = { ...Retention.defaultPeriods, ...options.retention };
514
+ const jobGuard = options.jobGuard ?? true;
515
+
516
+ class App extends DurableObject<AppEnv> implements AppObject {
517
+ #resident: Resident | undefined;
518
+ #building: Promise<Resident> | undefined;
519
+ /** Calls open now, a streaming response counting until its body ends. */
520
+ #active = 0;
521
+ #openCalls = 0;
522
+
523
+ /** Workflow bodies executing in memory now. */
524
+ #running = 0;
525
+ #lastWrite = 0;
526
+ /**
527
+ * Why the last start failed, until a start succeeds. Kept in storage: the host lets a copy
528
+ * that could not start go, and the next copy must still say why.
529
+ */
530
+ get #failure(): StartFailure | undefined {
531
+ return this.ctx.storage.kv.get<StartFailure>(START_FAILURE_KEY);
532
+ }
533
+ set #failure(value: StartFailure | undefined) {
534
+ if (value === undefined) this.ctx.storage.kv.delete(START_FAILURE_KEY);
535
+ else this.ctx.storage.kv.put(START_FAILURE_KEY, value);
536
+ }
537
+ /** The settings the last start read, to tell a missing setting from an invalid one. */
538
+ #settingsSeen: Readonly<Record<string, string>> | undefined;
539
+ /** Entity types of the app's ClusterCron jobs, from the resident runner. */
540
+ readonly #crons = new Set<string>();
541
+ /** The scheduled jobs and workflows that registered at this copy's start, with its real settings. */
542
+ #startedJobs: Array<ScheduledJobDescription> = [];
543
+ #startedWorkflows: Array<string> = [];
544
+ /** What started, for the host's next `settle()` or `wake()`; sent once per start. */
545
+ #startedDescription: AppDescription | undefined;
546
+ /** Every entity type the running code registered (workflows, their clocks, jobs). */
547
+ readonly #types = new Set<string>();
548
+ #lastWake: number | null = null;
549
+ #startSteps: {
550
+ settingsMs?: number;
551
+ layerMs?: number;
552
+ tablesMs?: number;
553
+ describeMs?: number;
554
+ } = {};
555
+ #wasBusy = false;
556
+ #kick: ReturnType<typeof setTimeout> | undefined;
557
+ readonly #telemetry = makeTelemetry();
558
+ readonly #recorder = makeRecorder();
559
+
560
+ #pagesKick: ReturnType<typeof setTimeout> | undefined;
561
+ #pagesOwed = false;
562
+ #paging: Promise<void> | undefined;
563
+ #reporting: Promise<void> | undefined;
564
+
565
+ /** Soon (debounced, after the statement's transaction): tell the host the app's data changed. */
566
+ #pagesChanged() {
567
+ if (this.#pagesKick !== undefined) return;
568
+ this.#pagesKick = setTimeout(() => {
569
+ this.#pagesKick = undefined;
570
+ if (this.#active > 0) {
571
+ this.#pagesOwed = true;
572
+ return;
573
+ }
574
+ const pages = this.env.EXECUTOR?.pages;
575
+ if (pages === undefined) return;
576
+ this.#paging = pages
577
+ .changed()
578
+ .catch(() => {})
579
+ .finally(() => {
580
+ this.#paging = undefined;
581
+ });
582
+ this.ctx.waitUntil(this.#paging);
583
+ }, 25);
584
+ }
585
+
586
+ /**
587
+ * Send a change notice still waiting out its debounce now, before the app reports its
588
+ * status: the host may stop the app as soon as it reads that it is idle.
589
+ */
590
+ async #flushPages() {
591
+ if (this.#pagesKick === undefined) return;
592
+ clearTimeout(this.#pagesKick);
593
+ this.#pagesKick = undefined;
594
+ await this.env.EXECUTOR?.pages?.changed().catch(() => {});
595
+ }
596
+
597
+ /** The object's SQL handle, noting every write to the cluster's tables and to the app's own. */
598
+ #sql(): SqlStorage {
599
+ const sql = this.ctx.storage.sql;
600
+ return new Proxy(sql, {
601
+ get: (target, property) => {
602
+ if (property === "exec") {
603
+ return (query: string, ...bindings: Array<unknown>) => {
604
+ const cursor = target.exec(query, ...bindings);
605
+ if (/cluster_/iu.test(query) && /^\s*(insert|update|delete|replace)/iu.test(query)) {
606
+ this.#lastWrite = Date.now();
607
+ this.#schedule();
608
+ } else if (
609
+ authorWrite.test(query) &&
610
+ !/effect_sql_migrations|apps_runs/iu.test(query)
611
+ ) {
612
+ this.#pagesChanged();
613
+ }
614
+ return cursor;
615
+ };
616
+ }
617
+ const value = Reflect.get(target, property, target);
618
+ return typeof value === "function" ? value.bind(target) : value;
619
+ },
620
+ });
621
+ }
622
+
623
+ /** The client takes `storage.sql` when given `storage` (it needs `storage` for transactions). */
624
+ #sqlLayer() {
625
+ const sql = this.#sql();
626
+ const storage = new Proxy(this.ctx.storage, {
627
+ get: (target, property) => {
628
+ if (property === "sql") return sql;
629
+ const value = Reflect.get(target, property, target);
630
+ return typeof value === "function" ? value.bind(target) : value;
631
+ },
632
+ });
633
+ return SqliteClient.layer({ db: sql, storage });
634
+ }
635
+
636
+ /**
637
+ * The one place the wrapper reads Effect's own tables: the next wake comes from
638
+ * `cluster_messages`. Check the columns it reads, so a change in a later Effect
639
+ * fails loudly at start instead of silently losing wakes.
640
+ */
641
+ #checkClusterTables() {
642
+ const columns = new Set(
643
+ [
644
+ ...this.ctx.storage.sql.exec<{ name: string }>(
645
+ "SELECT name FROM pragma_table_info('cluster_messages')",
646
+ ),
647
+ ].map((row) => row.name),
648
+ );
649
+ const missing = ["processed", "deliver_at"].filter((name) => !columns.has(name));
650
+ if (missing.length > 0) {
651
+ throw new Error(
652
+ `apps: cluster_messages has no ${missing.join(", ")} column. This Effect version stores cluster messages differently from the ${build.effectVersion} the runtime was built against; wakes would be lost.`,
653
+ );
654
+ }
655
+ }
656
+
657
+ #one(query: string, ...bindings: Array<unknown>): number | null {
658
+ try {
659
+ const value = this.ctx.storage.sql.exec<{ v: number | null }>(query, ...bindings).one().v;
660
+ return value === null ? null : Number(value);
661
+ } catch {
662
+ return null;
663
+ }
664
+ }
665
+
666
+ /** Registered jobs with no unprocessed message: their next run is not stored yet. */
667
+ #unscheduledJobs(): number {
668
+ let missing = 0;
669
+ for (const type of this.#crons) {
670
+ const stored = this.#one(
671
+ "SELECT count(*) AS v FROM cluster_messages WHERE entity_type = ? AND processed = 0",
672
+ type,
673
+ );
674
+ if (stored === null || stored === 0) missing += 1;
675
+ }
676
+ return missing;
677
+ }
678
+
679
+ /**
680
+ * The entity types this version's code registers, kept in the app's database so that
681
+ * even a copy that has not started its runner can tell parked work from due work. Replaced
682
+ * at every start.
683
+ */
684
+ #storeTypes() {
685
+ const sql = this.ctx.storage.sql;
686
+ sql.exec("CREATE TABLE IF NOT EXISTS apps_entity_types (entity_type TEXT PRIMARY KEY)");
687
+ sql.exec("DELETE FROM apps_entity_types");
688
+ for (const type of this.#types)
689
+ sql.exec("INSERT OR IGNORE INTO apps_entity_types (entity_type) VALUES (?)", type);
690
+ }
691
+
692
+ #storeType(type: string) {
693
+ const sql = this.ctx.storage.sql;
694
+ sql.exec("CREATE TABLE IF NOT EXISTS apps_entity_types (entity_type TEXT PRIMARY KEY)");
695
+ sql.exec("INSERT OR IGNORE INTO apps_entity_types (entity_type) VALUES (?)", type);
696
+ }
697
+
698
+ /**
699
+ * Messages for code this version does not register (after a rollback, or once a workflow or
700
+ * job is deleted) are parked: Effect leaves them unprocessed, and they count neither as due
701
+ * work nor as the next wake. A later version that registers the code again picks them up.
702
+ */
703
+ #parkedWhere(): string | undefined {
704
+ if (
705
+ this.#one(
706
+ "SELECT count(*) AS v FROM sqlite_master WHERE type = 'table' AND name = 'apps_entity_types'",
707
+ ) !== 1
708
+ ) {
709
+ return undefined;
710
+ }
711
+ const unknown = "SELECT entity_type FROM apps_entity_types";
712
+ // external: the workflow engine registers its clock entity whatever the code has, and a clock shares its execution's id.
713
+ return `(cluster_messages.entity_type NOT IN (${unknown}) OR (cluster_messages.entity_type LIKE 'Workflow/-/%' AND cluster_messages.entity_id IN (
714
+ SELECT w.entity_id FROM cluster_messages w
715
+ WHERE w.entity_type LIKE 'Workflow/%' AND w.entity_type NOT LIKE 'Workflow/-/%' AND w.entity_type NOT IN (${unknown}))))`;
716
+ }
717
+
718
+ #known(): string {
719
+ const parked = this.#parkedWhere();
720
+ return parked === undefined ? "" : `AND NOT ${parked}`;
721
+ }
722
+
723
+ /** The earliest unprocessed message with a delivery time, for code this version has. */
724
+ #due(): number | null {
725
+ const now = Date.now();
726
+ Retries.ensureTable(this.ctx.storage.sql);
727
+ const due = this.#one(
728
+ `SELECT min(deliver_at) AS v FROM cluster_messages WHERE processed = 0 AND deliver_at IS NOT NULL ${this.#known()} AND NOT ${Retries.retryingWhere}`,
729
+ now,
730
+ );
731
+ const retry = this.#retrying() > 0 ? Retries.nextRetry(this.ctx.storage.sql, now) : null;
732
+ return due === null ? retry : retry === null ? due : Math.min(due, retry);
733
+ }
734
+
735
+ /**
736
+ * Stored requests with no delivery time and no reply yet: a run in progress, or one a copy that
737
+ * was stopped left to resume. Not counted while they wait out a retry delay.
738
+ */
739
+ #pending(): number {
740
+ Retries.ensureTable(this.ctx.storage.sql);
741
+ return (
742
+ this.#one(
743
+ `SELECT count(*) AS v FROM cluster_messages WHERE processed = 0 AND deliver_at IS NULL ${this.#known()} AND NOT ${Retries.retryingWhere}`,
744
+ Date.now(),
745
+ ) ?? 0
746
+ );
747
+ }
748
+
749
+ /** Unprocessed messages whose run failed and that Effect will retry after a delay. */
750
+ #retrying(): number {
751
+ Retries.ensureTable(this.ctx.storage.sql);
752
+ return (
753
+ this.#one(
754
+ `SELECT count(*) AS v FROM cluster_messages WHERE processed = 0 ${this.#known()} AND ${Retries.retryingWhere}`,
755
+ Date.now(),
756
+ ) ?? 0
757
+ );
758
+ }
759
+
760
+ /** Unprocessed messages already due, for code this version has: being run now, or about to be. */
761
+ #overdue(): number {
762
+ return (
763
+ this.#one(
764
+ `SELECT count(*) AS v FROM cluster_messages WHERE processed = 0 AND deliver_at IS NOT NULL AND deliver_at <= ? ${this.#known()} AND NOT ${Retries.retryingWhere}`,
765
+ Date.now(),
766
+ Date.now(),
767
+ ) ?? 0
768
+ );
769
+ }
770
+
771
+ /** Unprocessed runs for code this version does not register, by workflow or scheduled job. */
772
+ #parked(): Array<ParkedRuns> {
773
+ const parked = this.#parkedWhere();
774
+ if (parked === undefined) return [];
775
+ const rows = this.ctx.storage.sql
776
+ .exec<{ entity_type: string; entity_id: string; tag: string }>(
777
+ `WITH parked AS (SELECT entity_type, entity_id, tag FROM cluster_messages WHERE processed = 0 AND ${parked})
778
+ SELECT entity_type, entity_id, tag FROM parked WHERE entity_type NOT LIKE 'Workflow/-/%'
779
+ UNION ALL
780
+ SELECT DISTINCT w.entity_type, p.entity_id, p.tag FROM parked p JOIN cluster_messages w
781
+ ON w.entity_id = p.entity_id AND w.entity_type LIKE 'Workflow/%' AND w.entity_type NOT LIKE 'Workflow/-/%'
782
+ WHERE p.entity_type LIKE 'Workflow/-/%'`,
783
+ )
784
+ .toArray();
785
+ const runs = new Map<string, Set<string> | number>();
786
+ for (const row of rows) {
787
+ if (row.entity_type.startsWith("ClusterCron/")) {
788
+ const count = runs.get(row.entity_type);
789
+ runs.set(
790
+ row.entity_type,
791
+ (typeof count === "number" ? count : 0) + (row.tag === "run" ? 1 : 0),
792
+ );
793
+ } else {
794
+ const ids = runs.get(row.entity_type);
795
+ const set = ids instanceof Set ? ids : new Set<string>();
796
+ set.add(row.entity_id);
797
+ runs.set(row.entity_type, set);
798
+ }
799
+ }
800
+ return [...runs]
801
+ .sort(([a], [b]) => (a < b ? -1 : 1))
802
+ .map(([type, value]) => ({
803
+ kind: type.startsWith("ClusterCron/")
804
+ ? "scheduled-job"
805
+ : type.startsWith("Workflow/")
806
+ ? "workflow"
807
+ : "entity",
808
+ name: type.replace(/^(ClusterCron|Workflow)\//u, ""),
809
+ runs: typeof value === "number" ? value : value.size,
810
+ }));
811
+ }
812
+
813
+ #layer() {
814
+ const env = this.env;
815
+ const capabilities = env.EXECUTOR;
816
+ const host = Layer.succeed(Host, {
817
+ capabilities,
818
+ appId: env.EXECUTOR_APP_ID,
819
+ appUrl: env.EXECUTOR_APP_URL,
820
+ });
821
+ const sql = this.#sqlLayer();
822
+ const sqlStorage = this.ctx.storage.sql;
823
+ /**
824
+ * Effect's `SqlMessageStorage`, with `unprocessedMessages` filtered (see `Retries.hold`): a
825
+ * fresh runner delivers every unprocessed message at once, so a request waiting out a
826
+ * recorded retry delay, and its entity's other requests, are held back and their claim
827
+ * released with `resetAddress`. Relies on `unprocessedMessages` claiming only what it
828
+ * returns, and on Sharding reading new work only through it. If Effect read messages another
829
+ * way, held requests would run early (more attempts than Effect left running would make);
830
+ * if a claim stopped being released by `resetAddress`, a held request would wait for the
831
+ * ten-minute storage poll. `apps-next-failing` and the kill-during-retries test catch both.
832
+ */
833
+ const heldStorage = Layer.effect(
834
+ MessageStorage.MessageStorage,
835
+ Effect.map(Effect.service(MessageStorage.MessageStorage), (upstream) =>
836
+ MessageStorage.MessageStorage.of({
837
+ ...upstream,
838
+ unprocessedMessages: (shardIds, options) =>
839
+ Effect.flatMap(upstream.unprocessedMessages(shardIds, options), (messages) => {
840
+ const now = Date.now();
841
+ Retries.ensureTable(sqlStorage);
842
+ const hold = (message: (typeof messages)[number]) =>
843
+ message._tag !== "IncomingRequest"
844
+ ? undefined
845
+ : Retries.hold(
846
+ sqlStorage,
847
+ message.envelope.address.entityType,
848
+ message.envelope.address.entityId,
849
+ String(message.envelope.requestId),
850
+ now,
851
+ );
852
+ const held = messages.filter((message) => hold(message) !== undefined);
853
+ if (held.length === 0) return Effect.succeed(messages);
854
+ return Effect.as(
855
+ Effect.forEach(
856
+ held.filter((message) => hold(message) === "later"),
857
+ (message) => upstream.resetAddress(message.envelope.address),
858
+ { discard: true },
859
+ ),
860
+ messages.filter((message) => !held.includes(message)),
861
+ );
862
+ }),
863
+ }),
864
+ ),
865
+ ).pipe(Layer.provide(SqlMessageStorage.layer));
866
+ const cluster = Sharding.layer
867
+ .pipe(
868
+ Layer.provideMerge(Runners.layerNoop),
869
+ Layer.provideMerge(heldStorage),
870
+ Layer.provide([
871
+ runnerStorage === "memory"
872
+ ? RunnerStorage.layerMemory
873
+ : Layer.orDie(SqlRunnerStorage.layer),
874
+ RunnerHealth.layerNoop,
875
+ ]),
876
+ Layer.provide(
877
+ ShardingConfig.layerFromEnv({
878
+ entityMessagePollInterval: Duration.minutes(10),
879
+ // external: each stored cluster message carries its shard id, so shardsPerGroup cannot change once an app has data.
880
+ shardsPerGroup: SHARDS_PER_GROUP,
881
+ }),
882
+ ),
883
+ )
884
+ .pipe(
885
+ Layer.provide([sql, Digest.layerWebCrypto]),
886
+ Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnvRecord({}))),
887
+ );
888
+ const engine = Layer.effect(
889
+ WorkflowEngine.WorkflowEngine,
890
+ Effect.map(Effect.service(WorkflowEngine.WorkflowEngine), (upstream) =>
891
+ WorkflowEngine.WorkflowEngine.of({
892
+ ...upstream,
893
+ register: (workflow, execute) =>
894
+ Effect.andThen(
895
+ Effect.sync(() => {
896
+ if (!this.#startedWorkflows.includes(workflow._tag))
897
+ this.#startedWorkflows.push(workflow._tag);
898
+ }),
899
+ upstream.register(workflow, (payload, executionId) =>
900
+ Effect.suspend(() => {
901
+ this.#running += 1;
902
+ return execute(payload, executionId);
903
+ }).pipe(
904
+ Effect.ensuring(
905
+ Effect.sync(() => {
906
+ this.#running -= 1;
907
+ this.#schedule();
908
+ }),
909
+ ),
910
+ ),
911
+ ),
912
+ ),
913
+ }),
914
+ ),
915
+ ).pipe(Layer.provide(sql));
916
+ const crons = this.#crons;
917
+ const types = this.#types;
918
+ /**
919
+ * Effect's `Sharding`, with `registerEntity` wrapped: it records each registered entity type
920
+ * (parking), counts scheduled jobs, observes each request's outcome for the retry record
921
+ * (`Retries.observe`, keyed by the handler's `requestId`), and passes a `defectRetryPolicy`
922
+ * that continues Effect's restart backoff from that record (`Retries.restartPolicy`, only
923
+ * where the entity sets none). Relies on handlers receiving `(payload, { requestId })` and on
924
+ * the restart step running after the handler's own exit. If either changed, a failing job
925
+ * would restart its backoff at every wake again; `apps-next-failing` measures it.
926
+ */
927
+ const sharding = Layer.effect(
928
+ Sharding.Sharding,
929
+ Effect.map(Effect.service(Sharding.Sharding), (upstream) =>
930
+ Sharding.Sharding.of({
931
+ ...upstream,
932
+ registerEntity: (entity, handlers, options) => {
933
+ if (
934
+ Option.isSome(
935
+ Context.getOption(entity.protocol.annotations, ClusterCron.CronSchedule),
936
+ )
937
+ ) {
938
+ crons.add(entity.type);
939
+ const job = jobOf(entity);
940
+ if (job !== undefined && !this.#startedJobs.some((seen) => seen.name === job.name))
941
+ this.#startedJobs.push(job);
942
+ }
943
+ if (!types.has(entity.type)) {
944
+ types.add(entity.type);
945
+ // external: ClusterWorkflowEngine registers some entities lazily, after the runner starts.
946
+ this.#storeType(entity.type);
947
+ }
948
+ const sql = this.ctx.storage.sql;
949
+ Retries.ensureTable(sql);
950
+ const observed = Effect.flatMap(handlers, (built) =>
951
+ Effect.map(Effect.service(Entity.CurrentAddress), (address) =>
952
+ Retries.observe(
953
+ sql,
954
+ entity.type,
955
+ address.entityId,
956
+ built as Record<string, unknown>,
957
+ ),
958
+ ),
959
+ ) as unknown as typeof handlers;
960
+ return upstream.registerEntity(entity, observed, {
961
+ ...options,
962
+ defectRetryPolicy:
963
+ options?.defectRetryPolicy ?? Retries.restartPolicy(sql, entity.type),
964
+ });
965
+ },
966
+ }),
967
+ ),
968
+ );
969
+ const wrappedSharding = sharding.pipe(Layer.provide(cluster));
970
+ const workflowEngine = engine.pipe(
971
+ Layer.provide(ClusterWorkflowEngine.layer),
972
+ Layer.provide(wrappedSharding),
973
+ Layer.provide(cluster),
974
+ );
975
+ const clusterServices = Layer.mergeAll(
976
+ wrappedSharding,
977
+ workflowEngine,
978
+ Layer.effect(MessageStorage.MessageStorage, Effect.service(MessageStorage.MessageStorage)),
979
+ ).pipe(Layer.provide(cluster));
980
+ const background = Layer.mergeAll(
981
+ this.#recorder.layer.pipe(Layer.provide(Layer.mergeAll(clusterServices, sql))),
982
+ Layer.effect(
983
+ MessageStorage.MessageStorage,
984
+ Effect.service(MessageStorage.MessageStorage),
985
+ ).pipe(Layer.provide(cluster)),
986
+ );
987
+
988
+ const readSettings =
989
+ capabilities === undefined
990
+ ? Effect.succeed({ values: {}, url: null as string | null })
991
+ : Effect.flatMap(
992
+ Effect.promise(() => {
993
+ const asked = Date.now();
994
+ return capabilities.settings.read().finally(() => {
995
+ this.#startSteps.settingsMs = Date.now() - asked;
996
+ });
997
+ }),
998
+ (result) =>
999
+ result.ok
1000
+ ? Effect.succeed({ values: result.value.values, url: result.value.url })
1001
+ : Effect.die(new Error(result.error.message)),
1002
+ );
1003
+ const settingsOnFirstLookup = Layer.unwrap(
1004
+ Effect.map(
1005
+ Effect.cached(
1006
+ Effect.tap(readSettings, ({ values }) =>
1007
+ Effect.sync(() => {
1008
+ this.#settingsSeen = values;
1009
+ }),
1010
+ ),
1011
+ ),
1012
+ (loaded) =>
1013
+ ConfigProvider.layer(
1014
+ ConfigProvider.make((path) =>
1015
+ Effect.flatMap(loaded, ({ values, url }) =>
1016
+ Settings.configProvider(values, url).load(path),
1017
+ ),
1018
+ ),
1019
+ ),
1020
+ ),
1021
+ );
1022
+
1023
+ const platform = Layer.mergeAll(
1024
+ background,
1025
+ sql,
1026
+ HttpRouter.layer,
1027
+ FetchHttpClient.layer,
1028
+ KeyValueStore.layerSql({ table: "apps_key_value" }).pipe(Layer.provide(sql)),
1029
+ Files.layer(capabilities?.files),
1030
+ host,
1031
+ this.#telemetry.layer,
1032
+ settingsOnFirstLookup,
1033
+ ErrorReporter.layer([Defects.reporter], { mergeWithExisting: true }),
1034
+ Layer.succeed(DurableClock.InMemoryThreshold, Duration.zero),
1035
+ );
1036
+ return appLayer.pipe(Layer.provideMerge(platform));
1037
+ }
1038
+
1039
+ #runtime(): Promise<Resident> {
1040
+ if (this.#resident !== undefined) return Promise.resolve(this.#resident);
1041
+ this.#building ??= (async () => {
1042
+ const started = Date.now();
1043
+ this.#startSteps = {};
1044
+ this.#settingsSeen = undefined;
1045
+ this.#crons.clear();
1046
+ this.#types.clear();
1047
+ const scope = Scope.makeUnsafe();
1048
+ this.#startedJobs = [];
1049
+ this.#startedWorkflows = [];
1050
+ const exit = await Effect.runPromiseExit(
1051
+ Layer.buildWithScope(this.#layer() as Layer.Layer<unknown, unknown, never>, scope),
1052
+ );
1053
+ const built = Date.now();
1054
+ this.#startSteps.layerMs = built - started;
1055
+ if (Exit.isFailure(exit)) {
1056
+ await Effect.runPromise(Scope.close(scope, exit));
1057
+ const failure = classify(exit.cause, this.#settingsSeen, Settings.takeMissing());
1058
+ this.#failure = failure;
1059
+ this.#telemetry.note(`apps: the app could not start (${failure.reason})`, {
1060
+ settings: failure.settings.join(","),
1061
+ });
1062
+ throw new StartFailed(failure);
1063
+ }
1064
+ this.#failure = undefined;
1065
+ const context = exit.value as Context.Context<HttpRouter.HttpRouter>;
1066
+ const router = Context.get(context, HttpRouter.HttpRouter);
1067
+ const handler = HttpEffect.toWebHandlerWith(context)(router.asHttpEffect() as never) as (
1068
+ request: Request,
1069
+ context?: Context.Context<never>,
1070
+ ) => Promise<Response>;
1071
+ this.#checkClusterTables();
1072
+ this.#storeTypes();
1073
+ const stored = Date.now();
1074
+ this.#startSteps.tablesMs = stored - built;
1075
+ this.#startedDescription = {
1076
+ contractVersion: CONTRACT_VERSION,
1077
+ appsVersion: build.appsVersion,
1078
+ effectVersion: build.effectVersion,
1079
+ accounts: [...Accounts.declarations],
1080
+ settings: [...Settings.declarations],
1081
+ publicPaths: [...Access.declarations.public],
1082
+ http: { firstResponseMs: Http.declarations.firstResponseMs },
1083
+ hooks: Accounts.hookCounts(),
1084
+ mcp: await discoverMcp(handler, build.mcpPath ?? "/mcp").catch(() => "unknown" as const),
1085
+ scheduledJobs: [...this.#startedJobs],
1086
+ workflows: [...this.#startedWorkflows],
1087
+ unknownReason: null,
1088
+ startFailure: null,
1089
+ };
1090
+ const resident = {
1091
+ context: context as Context.Context<never>,
1092
+ scope,
1093
+ handler,
1094
+ builtAt: Date.now(),
1095
+ };
1096
+ this.#resident = resident;
1097
+ this.#startSteps.describeMs = resident.builtAt - stored;
1098
+ this.#telemetry.note("apps: runner started", {
1099
+ ms: resident.builtAt - started,
1100
+ ...this.#startSteps,
1101
+ });
1102
+ return resident;
1103
+ })().finally(() => {
1104
+ this.#building = undefined;
1105
+ });
1106
+ return this.#building;
1107
+ }
1108
+
1109
+ async #run<A, E, R>(effect: Effect.Effect<A, E, R>): Promise<A> {
1110
+ const resident = await this.#runtime();
1111
+ return Effect.runPromiseWith(resident.context)(effect as Effect.Effect<A, E, never>);
1112
+ }
1113
+
1114
+ async #enter<A>(f: () => Promise<A>): Promise<A> {
1115
+ this.#active += 1;
1116
+ try {
1117
+ return await f();
1118
+ } finally {
1119
+ this.#active -= 1;
1120
+ this.#schedule();
1121
+ }
1122
+ }
1123
+
1124
+ #status(): AppStatus {
1125
+ const failure = this.#failure;
1126
+ if (failure !== undefined && this.#resident === undefined) {
1127
+ return {
1128
+ inFlight: false,
1129
+ openCalls: this.#openCalls,
1130
+ reasons: [failure.reason === "start-failed" ? "failed" : "needs-setup"],
1131
+ next: null,
1132
+ askAgainAt: this.#openCalls > 0 ? Date.now() + OPEN_CALL_RECHECK_MS : null,
1133
+ failure,
1134
+ parked: this.#parked(),
1135
+ databaseBytes: this.#databaseBytes(),
1136
+ isolate: isolateId(),
1137
+ };
1138
+ }
1139
+ const now = Date.now();
1140
+ const reasons: Array<string> = [];
1141
+ // external: across RPC the app cannot always tell when a streamed body it returned has been read to the end, so the host counts open calls.
1142
+ if (this.#building !== undefined) reasons.push("building");
1143
+ const resident = this.#resident;
1144
+ const pending = this.#pending();
1145
+ if (resident !== undefined) {
1146
+ if (this.#running > 0) reasons.push("workflow");
1147
+ if (pending > 0) reasons.push("pending");
1148
+ if (this.#overdue() > 0) reasons.push("due");
1149
+ if (this.#retrying() > 0) reasons.push("retrying");
1150
+ // external: until a ClusterCron's next run is stored, its schedule exists only in memory and an abort loses it.
1151
+ if (jobGuard && this.#unscheduledJobs() > 0) reasons.push("scheduling");
1152
+ if (now - this.#lastWrite < QUIET_MS) reasons.push("writing");
1153
+ }
1154
+ const due = this.#due();
1155
+ const resume = resident === undefined && pending > 0 ? now : null;
1156
+ const bound = this.#running > 0 || pending > 0 ? now + resumeBoundMs : null;
1157
+ const next = [due, resume, bound].reduce<number | null>(
1158
+ (earliest, at) =>
1159
+ at === null ? earliest : earliest === null ? at : Math.min(earliest, at),
1160
+ null,
1161
+ );
1162
+ const busy = reasons.filter((reason) => reason !== "retrying");
1163
+ const long = busy.some(
1164
+ (reason) => reason === "workflow" || reason === "pending" || reason === "due",
1165
+ );
1166
+ return {
1167
+ inFlight: busy.length > 0,
1168
+ openCalls: this.#openCalls,
1169
+ reasons: [...new Set(reasons)],
1170
+ next,
1171
+ askAgainAt:
1172
+ busy.length === 0
1173
+ ? this.#openCalls > 0
1174
+ ? now + OPEN_CALL_RECHECK_MS
1175
+ : null
1176
+ : long
1177
+ ? now + resumeBoundMs
1178
+ : now + QUIET_MS,
1179
+ failure: null,
1180
+ parked: this.#parked(),
1181
+ databaseBytes: this.#databaseBytes(),
1182
+ isolate: isolateId(),
1183
+ };
1184
+ }
1185
+
1186
+ /**
1187
+ * Soon (debounced): tell the host when the next wake is due, and send telemetry. Never while
1188
+ * a call is in the app: the last call's leaving schedules it.
1189
+ */
1190
+ #schedule() {
1191
+ if (this.#active > 0) return;
1192
+ if (this.#pagesOwed) {
1193
+ this.#pagesOwed = false;
1194
+ this.#pagesChanged();
1195
+ }
1196
+ if (this.#kick !== undefined) return;
1197
+ this.#kick = setTimeout(() => {
1198
+ this.#kick = undefined;
1199
+ if (this.#active > 0) return;
1200
+ this.#reporting = this.#report().finally(() => {
1201
+ this.#reporting = undefined;
1202
+ });
1203
+ this.ctx.waitUntil(this.#reporting);
1204
+ }, 25);
1205
+ }
1206
+
1207
+ /** The answer to `settle()` and `wake()`, with what started if the host has not had it. */
1208
+ #settled(): Settled {
1209
+ const description = this.#startedDescription;
1210
+ this.#startedDescription = undefined;
1211
+ return {
1212
+ status: this.#answered(this.#status()),
1213
+ batch: this.#drain(),
1214
+ ...(description === undefined ? {} : { description }),
1215
+ };
1216
+ }
1217
+
1218
+ #databaseBytes(): number | null {
1219
+ try {
1220
+ return this.ctx.storage.sql.databaseSize;
1221
+ } catch {
1222
+ return null;
1223
+ }
1224
+ }
1225
+
1226
+ /**
1227
+ * The status the host is about to read in an answer (`wake()`, `settle()`): it learns from
1228
+ * that whether the app is idle and when it next wants waking, so a report after it has
1229
+ * nothing new to say and no `setWake` (and no extra alarm) follows.
1230
+ */
1231
+ #answered(status: AppStatus): AppStatus {
1232
+ this.#wasBusy = status.inFlight;
1233
+ this.#lastWake = status.next;
1234
+ return status;
1235
+ }
1236
+
1237
+ async #report() {
1238
+ const { inFlight, next } = this.#status();
1239
+ const wasBusy = this.#wasBusy;
1240
+ // external: the host settles a settled app from its alarm, and an alarm that calls into the app while a call computes resets the host's object, so the app says it settled only once no call is in it.
1241
+ const held = wasBusy && !inFlight && this.#active > 0;
1242
+ const settled = wasBusy && !inFlight && !held;
1243
+ this.#wasBusy = held ? true : inFlight;
1244
+ const at = settled ? Date.now() : next;
1245
+ if (settled || at !== this.#lastWake) {
1246
+ try {
1247
+ await this.env.EXECUTOR?.clock.setWake(at);
1248
+ this.#lastWake = at;
1249
+ } catch (cause) {
1250
+ // external: a wake the host never heard of is lost for good, so keep it untold and tell it again shortly.
1251
+ this.#wasBusy = wasBusy;
1252
+ console.error("apps: could not tell the host when to wake the app", cause);
1253
+ this.#telemetry.note("apps: setWake failed", { at: at ?? "never", error: String(cause) });
1254
+ setTimeout(() => this.#schedule(), SET_WAKE_RETRY_MS);
1255
+ }
1256
+ }
1257
+ try {
1258
+ await this.#telemetry.flush(this.env.EXECUTOR?.telemetry);
1259
+ } catch (cause) {
1260
+ console.error("apps: telemetry export failed", cause);
1261
+ }
1262
+ }
1263
+
1264
+ override async fetch(request: Request): Promise<Response> {
1265
+ this.#active += 1;
1266
+ this.#openCalls += 1;
1267
+
1268
+ let response: Response;
1269
+ try {
1270
+ const resident = await this.#runtime();
1271
+ await Promise.all([this.#reporting, this.#paging]);
1272
+ const slot: Defects.DefectSlot = { first: undefined };
1273
+ const answered = await resident.handler(
1274
+ request,
1275
+ Context.make(Defects.CurrentDefectSlot, slot) as Context.Context<never>,
1276
+ );
1277
+ const missing = Settings.takeMissing();
1278
+ response = Defects.withDefect(
1279
+ slot.first?.name === "ConfigError" && missing.length > 0
1280
+ ? failureResponse(
1281
+ forCaller(request, {
1282
+ reason: "missing-setting",
1283
+ message: slot.first.message,
1284
+ settings: missing,
1285
+ at: Date.now(),
1286
+ }),
1287
+ )
1288
+ : answered,
1289
+ slot,
1290
+ );
1291
+ } catch (cause) {
1292
+ this.#leave();
1293
+ if (cause instanceof StartFailed) return failureResponse(forCaller(request, cause.failure));
1294
+ throw cause;
1295
+ }
1296
+ if (response.body === null) {
1297
+ this.#leave();
1298
+ return response;
1299
+ }
1300
+ // external: pipeTo settles once the body has been sent or the client went away, even when the reader stops at a known length.
1301
+ const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
1302
+ response.body.pipeTo(writable).then(
1303
+ () => this.#leave(),
1304
+ () => this.#leave(),
1305
+ );
1306
+ return new Response(readable, response);
1307
+ }
1308
+
1309
+ #leave() {
1310
+ this.#active -= 1;
1311
+ this.#openCalls -= 1;
1312
+ this.#schedule();
1313
+ }
1314
+
1315
+ async status(): Promise<AppStatus> {
1316
+ await this.#flushPages();
1317
+ return this.#status();
1318
+ }
1319
+
1320
+ /** Everything recorded since the host last asked, drained. */
1321
+ #drain(): TelemetryBatch | null {
1322
+ const telemetry = this.#telemetry.take();
1323
+ const records = this.#recorder.take();
1324
+ if (telemetry === undefined && records === undefined) return null;
1325
+ return {
1326
+ spans: telemetry?.spans ?? [],
1327
+ logs: telemetry?.logs ?? [],
1328
+ runs: records?.runs ?? [],
1329
+ steps: records?.steps ?? [],
1330
+ dropped: (telemetry?.dropped ?? 0) + (records?.dropped ?? 0),
1331
+ };
1332
+ }
1333
+
1334
+ async settle(): Promise<Settled> {
1335
+ await this.#reconcile();
1336
+ await this.#flushPages();
1337
+ return this.#settled();
1338
+ }
1339
+
1340
+ async cleanup(): Promise<Settled> {
1341
+ const storage = SqlMessageStorage.layer.pipe(
1342
+ Layer.provide([
1343
+ Digest.layerWebCrypto,
1344
+ ShardingConfig.layer({ shardsPerGroup: SHARDS_PER_GROUP }),
1345
+ ]),
1346
+ Layer.provideMerge(this.#sqlLayer()),
1347
+ );
1348
+ const until = Date.now() + CLEANUP_MS;
1349
+ const pruned = await Effect.runPromise(
1350
+ Effect.gen(function* () {
1351
+ let scheduled = 0;
1352
+ let workflows = 0;
1353
+ while (Date.now() < until) {
1354
+ const step = yield* Retention.prune(retention);
1355
+ scheduled += step.scheduled;
1356
+ workflows += step.workflows;
1357
+ if (step.scheduled + step.workflows === 0) break;
1358
+ }
1359
+ return { scheduled, workflows };
1360
+ }).pipe(
1361
+ Effect.provide(storage),
1362
+ Effect.catchCause((cause) =>
1363
+ Effect.sync(() => {
1364
+ this.#telemetry.note("apps: cleanup failed", { cause: Cause.pretty(cause) });
1365
+ return { scheduled: 0, workflows: 0 };
1366
+ }),
1367
+ ),
1368
+ ),
1369
+ );
1370
+ this.#telemetry.note("apps: cleanup", pruned);
1371
+ return this.#settled();
1372
+ }
1373
+
1374
+ /** Runs whose cancel was sent take their final status from the result Effect stored. Only on a live runner. */
1375
+ async #reconcile() {
1376
+ const resident = this.#resident;
1377
+ if (resident === undefined) return;
1378
+ await Effect.runPromiseWith(resident.context)(this.#recorder.reconcile);
1379
+ }
1380
+
1381
+ /**
1382
+ * Drop the resident runner, so the next call builds one inside itself. The runner's
1383
+ * background fibers (the storage read loop) belong to the call that built them; once that
1384
+ * call has ended, workerd may discard their pending timers and leave them suspended, and a
1385
+ * later `pollStorage` then waits on a loop that never runs. Bounded: a runner stuck that
1386
+ * way may not finish closing, and is dropped regardless.
1387
+ */
1388
+ async #restart() {
1389
+ const resident = this.#resident;
1390
+ if (resident === undefined || this.#building !== undefined) return;
1391
+ this.#resident = undefined;
1392
+ const closed = Effect.runPromise(Scope.close(resident.scope, Exit.void)).then(
1393
+ () => true,
1394
+ () => true,
1395
+ );
1396
+ const timedOut = new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 2_000));
1397
+ if (!(await Promise.race([closed, timedOut])))
1398
+ console.warn("apps: the previous runner did not close in 2 s");
1399
+ }
1400
+
1401
+ async wake(): Promise<Settled> {
1402
+ // external: restarting the runner under in-flight work interrupts it, and starts a second chain of a default-mode ClusterCron.
1403
+ if (this.#active === 0 && this.#running === 0 && this.#overdue() === 0) await this.#restart();
1404
+ try {
1405
+ await this.#enter(async () => {
1406
+ const poll = Effect.flatMap(
1407
+ Effect.service(Sharding.Sharding),
1408
+ (sharding) => sharding.pollStorage,
1409
+ );
1410
+ await this.#run(poll);
1411
+ // external: a storage read loads only messages already due when it runs, so read again until nothing due is left.
1412
+ const until = Date.now() + WAKE_DRAIN_MS;
1413
+ while (this.#overdue() > 0 && Date.now() < until) {
1414
+ await new Promise((resolve) => setTimeout(resolve, 20));
1415
+ await this.#run(poll);
1416
+ }
1417
+ await this.#run(
1418
+ Retention.prune(retention).pipe(
1419
+ Effect.tap(({ scheduled, workflows, removed }) =>
1420
+ scheduled + workflows === 0
1421
+ ? Effect.void
1422
+ : Effect.sync(() => {
1423
+ this.#recorder.stateCleared(removed);
1424
+ this.#telemetry.note("apps: pruned ended runs", { scheduled, workflows });
1425
+ }),
1426
+ ),
1427
+ Effect.catchCause((cause) =>
1428
+ Effect.sync(() =>
1429
+ this.#telemetry.note("apps: pruning failed", { cause: Cause.pretty(cause) }),
1430
+ ),
1431
+ ),
1432
+ ),
1433
+ );
1434
+ });
1435
+ } catch (cause) {
1436
+ if (!(cause instanceof StartFailed)) throw cause;
1437
+ }
1438
+ const settleBy = Date.now() + WAKE_SETTLE_MS;
1439
+ while (Date.now() < settleBy) {
1440
+ const { inFlight, reasons } = this.#status();
1441
+ if (!inFlight || reasons.includes("workflow") || reasons.includes("pending")) break;
1442
+ await new Promise((resolve) => setTimeout(resolve, 10));
1443
+ }
1444
+ this.ctx.waitUntil(this.#report());
1445
+ await this.#reconcile();
1446
+ await this.#flushPages();
1447
+ return this.#settled();
1448
+ }
1449
+
1450
+ async migrate(): Promise<MigrateResult> {
1451
+ return this.#enter(async () => {
1452
+ const run = SqliteMigrator.run({
1453
+ loader: Migrator.fromRecord(build.migrations),
1454
+ table: MIGRATIONS_TABLE,
1455
+ }).pipe(Effect.provide(this.#sqlLayer()));
1456
+ const applied = await Effect.runPromise(
1457
+ run.pipe(Effect.mapError((error) => new Error(causeChain(error)))),
1458
+ );
1459
+ const known = new Set(
1460
+ Object.keys(build.migrations).map((key) => Number.parseInt(key.split("_")[0] ?? "", 10)),
1461
+ );
1462
+ const unknown = [
1463
+ ...this.ctx.storage.sql.exec<{ migration_id: number; name: string }>(
1464
+ `SELECT migration_id, name FROM ${MIGRATIONS_TABLE} ORDER BY migration_id`,
1465
+ ),
1466
+ ]
1467
+ .filter((row) => !known.has(row.migration_id))
1468
+ .map((row) => [row.migration_id, row.name] as const);
1469
+ return { applied: applied.map(([id, name]) => [id, name] as const), unknown };
1470
+ });
1471
+ }
1472
+
1473
+ cancelRun(run: RunRef): Promise<Result<RunControlResult>> {
1474
+ return this.#enter(() => this.#run(this.#recorder.cancel(run)));
1475
+ }
1476
+
1477
+ rerunRun(run: RunRef): Promise<Result<RunControlResult>> {
1478
+ return this.#enter(() => this.#run(this.#recorder.rerun(run)));
1479
+ }
1480
+
1481
+ runJob(job: { readonly name: string }): Promise<Result<RunControlResult>> {
1482
+ return this.#enter(() => this.#run(this.#recorder.runJob(job.name)));
1483
+ }
1484
+
1485
+ query(request: QueryRequest): Promise<Result<QueryResult>> {
1486
+ return this.#enter(async () => readOnlyQuery(this.ctx.storage, request));
1487
+ }
1488
+
1489
+ async accountEvent(event: AccountEvent): Promise<AccountEventResult> {
1490
+ const traced = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1491
+ event.trace === undefined
1492
+ ? effect
1493
+ : effect.pipe(
1494
+ Effect.withSpan(`account ${event.kind} ${event.account.name}`, {
1495
+ parent: Tracer.externalSpan(event.trace),
1496
+ }),
1497
+ );
1498
+ return this.#enter(async () => {
1499
+ const profile =
1500
+ event.kind === "linked"
1501
+ ? await this.#run(traced(Accounts.readProfile(event.account)))
1502
+ : undefined;
1503
+ const externalId =
1504
+ profile?.status === "ok"
1505
+ ? (profile.info["externalId"] ?? null)
1506
+ : event.account.externalId;
1507
+ const exit = await this.#run(
1508
+ Effect.exit(
1509
+ traced(Accounts.runHooks(event, externalId).pipe(Effect.timeout(HOOK_LIMIT))),
1510
+ ),
1511
+ );
1512
+ return Exit.isSuccess(exit)
1513
+ ? { ok: true as const, profile }
1514
+ : {
1515
+ ok: false as const,
1516
+ error: { reason: "HookFailed", message: Cause.pretty(exit.cause) },
1517
+ profile,
1518
+ };
1519
+ });
1520
+ }
1521
+
1522
+ async checkAccount(account: AccountRef): Promise<Result<AccountProfile>> {
1523
+ return this.#enter(async () => ({
1524
+ ok: true as const,
1525
+ value: await this.#run(Accounts.readProfile(account)),
1526
+ }));
1527
+ }
1528
+
1529
+ async check(input: { readonly setting: string }): Promise<Result<CheckResult>> {
1530
+ return this.#enter(async () => ({
1531
+ ok: true as const,
1532
+ value: await this.#run(Settings.runCheck(input.setting)),
1533
+ }));
1534
+ }
1535
+ }
1536
+
1537
+ return App;
1538
+ };
1539
+
1540
+ export { entrySource, type EntryOptions } from "./entry.ts";