@orthograph/host-cloudflare 0.0.0-stage → 0.1.0-next.1

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 (135) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +2 -2
  3. package/dist/index.d.ts +21 -0
  4. package/dist/index.js +12 -0
  5. package/dist/modules/actors/internal/tables.d.ts +1 -0
  6. package/dist/modules/actors/internal/tables.js +5 -0
  7. package/dist/modules/actors/service.d.ts +18 -0
  8. package/dist/modules/actors/service.js +51 -0
  9. package/dist/modules/actors/types.d.ts +35 -0
  10. package/dist/modules/actors/types.js +1 -0
  11. package/dist/modules/auth/internal/instance.d.ts +4462 -0
  12. package/dist/modules/auth/internal/instance.js +36 -0
  13. package/dist/modules/auth/internal/oauth.d.ts +20 -0
  14. package/dist/modules/auth/internal/oauth.js +70 -0
  15. package/dist/modules/auth/internal/options.d.ts +4886 -0
  16. package/dist/modules/auth/internal/options.js +75 -0
  17. package/dist/modules/auth/internal/schema.d.ts +2 -0
  18. package/dist/modules/auth/internal/schema.js +41 -0
  19. package/dist/modules/auth/internal/world-token.d.ts +15 -0
  20. package/dist/modules/auth/internal/world-token.js +40 -0
  21. package/dist/modules/auth/service.d.ts +9 -0
  22. package/dist/modules/auth/service.js +96 -0
  23. package/dist/modules/auth/types.d.ts +75 -0
  24. package/dist/modules/auth/types.js +1 -0
  25. package/dist/modules/clock/internal/date.d.ts +17 -0
  26. package/dist/modules/clock/internal/date.js +45 -0
  27. package/dist/modules/clock/internal/door.d.ts +2 -0
  28. package/dist/modules/clock/internal/door.js +49 -0
  29. package/dist/modules/clock/internal/state.d.ts +5 -0
  30. package/dist/modules/clock/internal/state.js +78 -0
  31. package/dist/modules/clock/service.d.ts +2 -0
  32. package/dist/modules/clock/service.js +36 -0
  33. package/dist/modules/clock/types.d.ts +152 -0
  34. package/dist/modules/clock/types.js +1 -0
  35. package/dist/modules/database/service.d.ts +2 -0
  36. package/dist/modules/database/service.js +6 -0
  37. package/dist/modules/database/types.d.ts +7 -0
  38. package/dist/modules/database/types.js +1 -0
  39. package/dist/modules/follower/internal/entries.d.ts +9 -0
  40. package/dist/modules/follower/internal/entries.js +20 -0
  41. package/dist/modules/follower/internal/health.d.ts +18 -0
  42. package/dist/modules/follower/internal/health.js +27 -0
  43. package/dist/modules/follower/internal/outbox.d.ts +26 -0
  44. package/dist/modules/follower/internal/outbox.js +35 -0
  45. package/dist/modules/follower/internal/poll.d.ts +21 -0
  46. package/dist/modules/follower/internal/poll.js +23 -0
  47. package/dist/modules/follower/service.d.ts +31 -0
  48. package/dist/modules/follower/service.js +87 -0
  49. package/dist/modules/follower/types.d.ts +71 -0
  50. package/dist/modules/follower/types.js +4 -0
  51. package/dist/modules/inbound/internal/accept.d.ts +26 -0
  52. package/dist/modules/inbound/internal/accept.js +10 -0
  53. package/dist/modules/inbound/internal/read.d.ts +10 -0
  54. package/dist/modules/inbound/internal/read.js +26 -0
  55. package/dist/modules/inbound/internal/same.d.ts +1 -0
  56. package/dist/modules/inbound/internal/same.js +12 -0
  57. package/dist/modules/inbound/internal/verify.d.ts +6 -0
  58. package/dist/modules/inbound/internal/verify.js +57 -0
  59. package/dist/modules/inbound/service.d.ts +2 -0
  60. package/dist/modules/inbound/service.js +110 -0
  61. package/dist/modules/inbound/types.d.ts +28 -0
  62. package/dist/modules/inbound/types.js +1 -0
  63. package/dist/modules/journal/service.d.ts +2 -0
  64. package/dist/modules/journal/service.js +23 -0
  65. package/dist/modules/journal/types.d.ts +8 -0
  66. package/dist/modules/journal/types.js +1 -0
  67. package/dist/modules/relayer/internal/adopt.d.ts +19 -0
  68. package/dist/modules/relayer/internal/adopt.js +34 -0
  69. package/dist/modules/relayer/internal/check.d.ts +16 -0
  70. package/dist/modules/relayer/internal/check.js +141 -0
  71. package/dist/modules/relayer/internal/health.d.ts +5 -0
  72. package/dist/modules/relayer/internal/health.js +7 -0
  73. package/dist/modules/relayer/internal/live.d.ts +26 -0
  74. package/dist/modules/relayer/internal/live.js +25 -0
  75. package/dist/modules/relayer/internal/relay.d.ts +22 -0
  76. package/dist/modules/relayer/internal/relay.js +44 -0
  77. package/dist/modules/relayer/internal/store.d.ts +41 -0
  78. package/dist/modules/relayer/internal/store.js +44 -0
  79. package/dist/modules/relayer/service.d.ts +58 -0
  80. package/dist/modules/relayer/service.js +124 -0
  81. package/dist/modules/relayer/types.d.ts +75 -0
  82. package/dist/modules/relayer/types.js +1 -0
  83. package/dist/modules/store/internal/actors.d.ts +6 -0
  84. package/dist/modules/store/internal/actors.js +24 -0
  85. package/dist/modules/store/internal/commit.d.ts +10 -0
  86. package/dist/modules/store/internal/commit.js +57 -0
  87. package/dist/modules/store/internal/list.d.ts +10 -0
  88. package/dist/modules/store/internal/list.js +28 -0
  89. package/dist/modules/store/internal/rows.d.ts +14 -0
  90. package/dist/modules/store/internal/rows.js +29 -0
  91. package/dist/modules/store/internal/unique.d.ts +3 -0
  92. package/dist/modules/store/internal/unique.js +17 -0
  93. package/dist/modules/store/service.d.ts +2 -0
  94. package/dist/modules/store/service.js +71 -0
  95. package/dist/modules/store/types.d.ts +36 -0
  96. package/dist/modules/store/types.js +1 -0
  97. package/dist/modules/telemetry/internal/exporters.d.ts +21 -0
  98. package/dist/modules/telemetry/internal/exporters.js +66 -0
  99. package/dist/modules/telemetry/service.d.ts +2 -0
  100. package/dist/modules/telemetry/service.js +52 -0
  101. package/dist/modules/telemetry/types.d.ts +36 -0
  102. package/dist/modules/telemetry/types.js +1 -0
  103. package/dist/modules/timers/internal/controller.d.ts +13 -0
  104. package/dist/modules/timers/internal/controller.js +63 -0
  105. package/dist/modules/timers/internal/count.d.ts +39 -0
  106. package/dist/modules/timers/internal/count.js +105 -0
  107. package/dist/modules/timers/internal/limits.d.ts +4 -0
  108. package/dist/modules/timers/internal/limits.js +8 -0
  109. package/dist/modules/timers/internal/table.d.ts +52 -0
  110. package/dist/modules/timers/internal/table.js +181 -0
  111. package/dist/modules/timers/service.d.ts +12 -0
  112. package/dist/modules/timers/service.js +136 -0
  113. package/dist/modules/timers/types.d.ts +82 -0
  114. package/dist/modules/timers/types.js +1 -0
  115. package/dist/modules/world/internal/entry.d.ts +34 -0
  116. package/dist/modules/world/internal/entry.js +69 -0
  117. package/dist/modules/world/internal/facts.d.ts +5 -0
  118. package/dist/modules/world/internal/facts.js +31 -0
  119. package/dist/modules/world/internal/fence.d.ts +9 -0
  120. package/dist/modules/world/internal/fence.js +90 -0
  121. package/dist/modules/world/internal/front-door.d.ts +5 -0
  122. package/dist/modules/world/internal/front-door.js +50 -0
  123. package/dist/modules/world/internal/leases.d.ts +33 -0
  124. package/dist/modules/world/internal/leases.js +79 -0
  125. package/dist/modules/world/internal/reset.d.ts +6 -0
  126. package/dist/modules/world/internal/reset.js +24 -0
  127. package/dist/modules/world/internal/work.d.ts +11 -0
  128. package/dist/modules/world/internal/work.js +73 -0
  129. package/dist/modules/world/internal/worlds.d.ts +7 -0
  130. package/dist/modules/world/internal/worlds.js +48 -0
  131. package/dist/modules/world/service.d.ts +80 -0
  132. package/dist/modules/world/service.js +209 -0
  133. package/dist/modules/world/types.d.ts +47 -0
  134. package/dist/modules/world/types.js +1 -0
  135. package/package.json +41 -3
@@ -0,0 +1,71 @@
1
+ import { Context, Effect, Layer } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+ import { D1Client } from "@effect/sql-d1";
4
+ import { Store } from "@orthograph/language-effect";
5
+ import { decodeRow } from "./internal/rows.js";
6
+ import { actorCommit, actorFind } from "./internal/actors.js";
7
+ import { commitD1 } from "./internal/commit.js";
8
+ import { listRows } from "./internal/list.js";
9
+ /** Which store a thing lives in, as the commit's one-owner rule sees it: its declared store, else the kind of place. */
10
+ const ownerOf = (thing) => thing.store ?? thing.lives;
11
+ export const StoreD1 = {
12
+ layer: ({ tables, actors, stores = [], people, rules = [] }) => Layer.effect(Store, Effect.gen(function* () {
13
+ const home = { sql: yield* SqlClient.SqlClient, d1: yield* D1Client.D1Client };
14
+ // Each declared database store has a binding of its own, and its own `_journal` and `_requests` beside its tables.
15
+ const apart = new Map();
16
+ for (const [store, db] of stores) {
17
+ const made = yield* Layer.build(D1Client.layer({ db }).pipe(Layer.orDie));
18
+ apart.set(store, { sql: Context.get(made, SqlClient.SqlClient), d1: Context.get(made, D1Client.D1Client) });
19
+ }
20
+ const dbOf = (thing) => (thing.store ? apart.get(thing.store) ?? home : home);
21
+ const tableOf = (thing) => tables.find(([t]) => t === thing)?.[1] ?? "";
22
+ const noActors = Effect.die(new Error("a thing lives as an actor, but the Worker has no ACTORS binding"));
23
+ const everyDb = [home, ...apart.values()];
24
+ return Store.of({
25
+ rules,
26
+ // A request key is kept in the store its call committed to, which the key alone doesn't say: ask each.
27
+ answered: (key) => Effect.forEach(everyDb, ({ sql }) => sql `SELECT "answer" FROM "_requests" WHERE "key" = ${key}`.pipe(Effect.map((rows) => rows[0]?.answer), Effect.orDie)).pipe(Effect.map((answers) => answers.find((a) => a !== undefined))),
28
+ list: (query) => query.thing === people?.thing
29
+ ? Effect.die(new Error("a list read of people: they are the identity's users, read by id only until the identity plugin (M2.05)"))
30
+ : query.thing.lives === "actor"
31
+ ? Effect.die(new Error("a list read needs a thing that lives in the database; actors keep one instance each"))
32
+ : listRows(dbOf(query.thing).sql, tableOf(query.thing), query),
33
+ // #764: a row's place in the order rows were made is its rowid, as `list` gives it.
34
+ place: (thing, id) => thing === people?.thing || thing.lives === "actor"
35
+ ? Effect.succeed(undefined)
36
+ : dbOf(thing).sql `SELECT rowid AS "place" FROM ${dbOf(thing).sql(tableOf(thing))} WHERE "id" = ${id}`.pipe(Effect.map((rows) => (rows[0] === undefined ? undefined : Number(rows[0].place))), Effect.orDie),
37
+ find: (thing, id) => thing === people?.thing
38
+ ? Effect.gen(function* () {
39
+ const rows = yield* home.sql `SELECT * FROM ${home.sql(people.table)} WHERE "id" = ${id}`.pipe(Effect.orDie);
40
+ const row = rows[0];
41
+ return row ? yield* decodeRow(thing, row) : undefined;
42
+ })
43
+ : thing.lives === "actor"
44
+ ? (actors ? actorFind(actors, thing, tableOf(thing), id) : noActors)
45
+ : Effect.gen(function* () {
46
+ const rows = yield* dbOf(thing).sql `SELECT * FROM ${dbOf(thing).sql(tableOf(thing))} WHERE "id" = ${id}`.pipe(Effect.orDie);
47
+ const row = rows[0];
48
+ return row ? yield* decodeRow(thing, row) : undefined;
49
+ }),
50
+ commit: (commit) => {
51
+ const owners = new Set(commit.writes.map((w) => ownerOf(w.thing)));
52
+ if (owners.size > 1)
53
+ return Effect.die(new Error("a call wrote to more than one store: one call commits to one store, and work across stores is a workflow (K3 item 5)"));
54
+ const first = commit.writes[0]?.thing;
55
+ const db = first?.lives === "actor" ? undefined : first ? dbOf(first) : home;
56
+ // A list is guarded in the batch that commits the call (#764): a list it can't join would let its rows go unread.
57
+ const changes = commit.writes.length > 0 || commit.entries.length > 0 || commit.request !== undefined;
58
+ if (changes && (commit.lists ?? []).some((l) => dbOf(l.thing) !== db)) {
59
+ return Effect.die(new Error("a call listed things in one store and committed to another: a list is guarded only in the database the call commits to (#764)"));
60
+ }
61
+ // #1045: the rows it found are guarded in the same batch. One kept elsewhere (a person, an actor, another database) can't join it, and goes unguarded.
62
+ const reads = (commit.reads ?? []).filter((r) => r.thing !== people?.thing && r.thing.lives !== "actor" && dbOf(r.thing) === db);
63
+ if (db !== undefined)
64
+ return commitD1(db, tableOf, { ...commit, reads }, rules);
65
+ if (commit.request)
66
+ return Effect.die(new Error("a request key on an actor's operation: idempotent actors arrive with layer four (design/later.md)"));
67
+ return actors ? actorCommit(actors, commit, tableOf) : noActors;
68
+ },
69
+ });
70
+ })),
71
+ };
@@ -0,0 +1,36 @@
1
+ import type { Layer } from "effect";
2
+ import type { SqlClient } from "effect/sql";
3
+ import type { D1Client } from "@effect/sql-d1";
4
+ import type { Store as Declared, Thing } from "orthograph";
5
+ import type { NamedRule, Store } from "@orthograph/language-effect";
6
+ export interface StoreD1Options {
7
+ /** Each thing and its table name; the generated server writes the list from the things' paths. */
8
+ readonly tables: ReadonlyArray<readonly [Thing, string]>;
9
+ /** The Durable Object namespace that holds one actor per instance, for things that `lives: "actor"`. */
10
+ readonly actors?: DurableObjectNamespace;
11
+ /**
12
+ * Each declared database store and the D1 binding it lives in (K3). A thing that lives in one is read and committed
13
+ * there, with its journal entries and request keys; a thing in no declared store lives in the default database,
14
+ * `SqlClient`'s. One call commits to one store: writes to two are refused.
15
+ */
16
+ readonly stores?: ReadonlyArray<readonly [Declared, D1Database]>;
17
+ /**
18
+ * The thing the identity keeps (its `per_` ids are the identity's users, `Auth`'s contract) and the table the identity
19
+ * keeps them in, both named by the generated server: read from there, never a table of its own, so the runtime finds a
20
+ * person a payload names (K16, M1.46). Only its own fields are decoded. Reads by id only; the identity plugin (M2.05)
21
+ * owns the rest.
22
+ */
23
+ readonly people?: {
24
+ readonly thing: Thing;
25
+ readonly table: string;
26
+ };
27
+ /**
28
+ * The model's rules (G5): each invariant of the project's things, with its full name (`handle.oneHolderPerName`). The database's partial unique index per rule
29
+ * (made by the generated migration, named `<table>_<rule>`) refuses a second holder at commit; the store answers that as a `conflict`, and hands the rules to the
30
+ * runtime, whose `findBy` and before-commit check look through the same ones.
31
+ */
32
+ readonly rules?: ReadonlyArray<NamedRule>;
33
+ }
34
+ export interface StoreD1Api {
35
+ readonly layer: (options: StoreD1Options) => Layer.Layer<Store, never, SqlClient.SqlClient | D1Client.D1Client>;
36
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ import type { Exporter } from "../types.ts";
2
+ /** `OTLP_SINKS`: the sinks as JSON, set by whoever starts the environment. Anything malformed is no sink at all. */
3
+ export declare const sinksOf: (json: string | undefined) => ReadonlyArray<Exporter>;
4
+ /** The Collector at `url`: no credentials, the standard OTLP paths. */
5
+ export declare const collectorOf: (url: string) => Exporter;
6
+ /** What the tracer and logger believe they are sending to. Only its path matters: it picks each exporter's own endpoint. */
7
+ export declare const BASE = "http://otlp.invalid";
8
+ /**
9
+ * Personal details never leave the machine: `user.*`, `organization.id` and anything ending `.email` (the Claude Agent
10
+ * SDK writes `user.email`, `user.account_uuid`, `user.account_id` and `organization.id` on its records). The local
11
+ * Collector keeps what it was sent; every other exporter is sent the records without them.
12
+ */
13
+ export declare const PERSONAL: RegExp;
14
+ /** An OTLP/JSON export without any personal attribute, on resources, spans, events and log records. Not JSON: as it was. */
15
+ export declare const scrub: <B extends BodyInit | null | undefined>(body: B) => B | string;
16
+ /**
17
+ * A `fetch` that sends each export to every exporter's endpoint for that signal. Prefer a successful response so
18
+ * the exporter does not retry a delta another destination accepted. Wait for all sends so a flush under
19
+ * `waitUntil` has finished every send.
20
+ */
21
+ export declare const fanOut: (exporters: ReadonlyArray<Exporter>, base: typeof fetch) => typeof fetch;
@@ -0,0 +1,66 @@
1
+ // Where a request's traces, logs and metrics go, whether to prove's Collector or a sink named in the environment.
2
+ // One fetch fans each export out to all of them, so Effect's exporters
3
+ // stay unaware there is more than one destination.
4
+ import { Option, Schema } from "effect";
5
+ const Endpoint = Schema.Struct({ url: Schema.String, headers: Schema.Record(Schema.String, Schema.String) });
6
+ const Exporters = Schema.Array(Schema.Struct({ id: Schema.String, traces: Endpoint, logs: Endpoint, metrics: Schema.optionalKey(Endpoint) }));
7
+ const decode = Schema.decodeUnknownOption(Schema.fromJsonString(Exporters));
8
+ /** `OTLP_SINKS`: the sinks as JSON, set by whoever starts the environment. Anything malformed is no sink at all. */
9
+ export const sinksOf = (json) => json === undefined || json === "" ? [] : Option.getOrElse(decode(json), () => []);
10
+ /** The Collector at `url`: no credentials, the standard OTLP paths. */
11
+ export const collectorOf = (url) => ({
12
+ id: "local",
13
+ traces: { url: `${url}/v1/traces`, headers: {} },
14
+ logs: { url: `${url}/v1/logs`, headers: {} },
15
+ metrics: { url: `${url}/v1/metrics`, headers: {} },
16
+ });
17
+ /** What the tracer and logger believe they are sending to. Only its path matters: it picks each exporter's own endpoint. */
18
+ export const BASE = "http://otlp.invalid";
19
+ /**
20
+ * Personal details never leave the machine: `user.*`, `organization.id` and anything ending `.email` (the Claude Agent
21
+ * SDK writes `user.email`, `user.account_uuid`, `user.account_id` and `organization.id` on its records). The local
22
+ * Collector keeps what it was sent; every other exporter is sent the records without them.
23
+ */
24
+ export const PERSONAL = /^(user\..*|organization\.id|email|.*\.email)$/;
25
+ const clean = (node) => Array.isArray(node) ? node.map(clean)
26
+ : node !== null && typeof node === "object"
27
+ ? Object.fromEntries(Object.entries(node).map(([k, v]) => [k, k === "attributes" && Array.isArray(v) ? v.filter((a) => !(typeof a?.key === "string" && PERSONAL.test(a.key))).map(clean) : clean(v)]))
28
+ : node;
29
+ /** An OTLP/JSON export without any personal attribute, on resources, spans, events and log records. Not JSON: as it was. */
30
+ export const scrub = (body) => {
31
+ const text = typeof body === "string" ? body : body instanceof Uint8Array ? new TextDecoder().decode(body) : undefined;
32
+ if (text === undefined)
33
+ return body;
34
+ try {
35
+ return JSON.stringify(clean(JSON.parse(text)));
36
+ }
37
+ catch {
38
+ return body;
39
+ }
40
+ };
41
+ const pathOf = (url) => new URL(url).pathname;
42
+ /**
43
+ * A `fetch` that sends each export to every exporter's endpoint for that signal. Prefer a successful response so
44
+ * the exporter does not retry a delta another destination accepted. Wait for all sends so a flush under
45
+ * `waitUntil` has finished every send.
46
+ */
47
+ export const fanOut = (exporters, base) => (input, init) => {
48
+ const path = pathOf(String(input instanceof Request ? input.url : input));
49
+ const signal = path === "/v1/metrics" ? "metrics" : path === "/v1/logs" ? "logs" : "traces";
50
+ const sends = exporters.flatMap((e) => {
51
+ const endpoint = e[signal];
52
+ if (!endpoint)
53
+ return [];
54
+ const headers = new Headers(init?.headers);
55
+ for (const [k, v] of Object.entries(endpoint.headers))
56
+ headers.set(k, v);
57
+ return [base(endpoint.url, { ...init, headers, ...(e.id === "local" || init?.body == null ? {} : { body: scrub(init.body) }) })];
58
+ });
59
+ return Promise.allSettled(sends).then((results) => {
60
+ const answered = results.find((r) => r.status === "fulfilled" && r.value.ok)
61
+ ?? results.find((r) => r.status === "fulfilled");
62
+ if (answered)
63
+ return answered.value;
64
+ throw results[0]?.reason ?? new Error("no exporter");
65
+ });
66
+ };
@@ -0,0 +1,2 @@
1
+ import type { TelemetryApi } from "./types.ts";
2
+ export declare const Telemetry: TelemetryApi;
@@ -0,0 +1,52 @@
1
+ import { Context, Duration, Layer, ManagedRuntime, Metric, Tracer } from "effect";
2
+ import { FetchHttpClient } from "effect/http";
3
+ import { OtlpLogger, OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/observability";
4
+ import { BASE, collectorOf, fanOut, sinksOf } from "./internal/exporters.js";
5
+ const exporters = (targets, serviceName, environment) => {
6
+ // Every signal carries the environment on its resource.
7
+ const attributes = environment === undefined ? {} : { "deployment.environment": environment, "deployment.environment.name": environment };
8
+ const options = { resource: { serviceName, attributes }, exportInterval: "100 millis", maxBatchSize: 64, shutdownTimeout: "3 seconds" };
9
+ return Layer.mergeAll(OtlpTracer.layer({ url: `${BASE}/v1/traces`, ...options }), OtlpLogger.layer({ url: `${BASE}/v1/logs`, ...options }),
10
+ // Flush metrics once at disposal so a periodic export cannot resend the same delta as the final flush.
11
+ ...(targets.some((target) => target.metrics) ? [OtlpMetrics.layer({ url: `${BASE}/v1/metrics`, ...options, exportInterval: Duration.infinity, temporality: "delta" })] : [])).pipe(
12
+ // Export only this request's observations when its runtime closes.
13
+ Layer.provideMerge(Layer.succeed(Metric.MetricRegistry, new Map())), Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer), Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fanOut(targets, globalThis.fetch.bind(globalThis)))));
14
+ };
15
+ const TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
16
+ const hex = (bytes) => Array.from(crypto.getRandomValues(new Uint8Array(bytes)), (b) => b.toString(16).padStart(2, "0")).join("");
17
+ /** Set by `configure`: the environment's sinks and name, for this isolate. */
18
+ let configured = { sinks: undefined, environment: undefined };
19
+ export const Telemetry = {
20
+ configure: (options) => {
21
+ configured = options;
22
+ },
23
+ serve: ({ url, sinks = configured.sinks, environment = configured.environment, service, handler, waitUntil }, request) => {
24
+ const given = request.headers.get("traceparent")?.match(TRACEPARENT);
25
+ const trace = given?.[1] ?? hex(16);
26
+ const spanId = given?.[2] ?? hex(8);
27
+ const flags = given?.[3] ?? "01";
28
+ const headers = new Headers(request.headers);
29
+ if (!given)
30
+ headers.set("traceparent", `00-${trace}-${spanId}-${flags}`);
31
+ const traced = new Request(request, { headers });
32
+ const answered = (response) => {
33
+ const out = new Response(response.body, response);
34
+ out.headers.set("x-trace-id", trace);
35
+ return out;
36
+ };
37
+ // The caller's span is the parent of every span of the call, exported or not: with no target the call's spans still
38
+ // carry the caller's trace, and so does every journal row they write (the staging story reads its facts by it).
39
+ const parent = Tracer.externalSpan({ traceId: trace, spanId, sampled: (parseInt(flags, 16) & 1) === 1 });
40
+ const targets = [...(url ? [collectorOf(url)] : []), ...sinksOf(sinks)];
41
+ if (targets.length === 0)
42
+ return handler(traced, Context.make(Tracer.ParentSpan, parent)).then(answered);
43
+ // One runtime per request: its exporters are flushed when it is disposed, after the response, under waitUntil.
44
+ const runtime = ManagedRuntime.make(exporters(targets, service, environment));
45
+ // Disposed whether the handler answers or throws, so a failed request still exports what it recorded.
46
+ return runtime
47
+ .context()
48
+ .then((context) => handler(traced, Context.add(context, Tracer.ParentSpan, parent)))
49
+ .finally(() => waitUntil(runtime.dispose()))
50
+ .then(answered);
51
+ },
52
+ };
@@ -0,0 +1,36 @@
1
+ import type { Context } from "effect";
2
+ export type WebHandler = (request: Request, context?: Context.Context<never>) => Promise<Response>;
3
+ /** One OTLP/HTTP endpoint: where a signal goes, and the headers it needs (an Axiom token and dataset, say). */
4
+ export interface Endpoint {
5
+ readonly url: string;
6
+ readonly headers: Readonly<Record<string, string>>;
7
+ }
8
+ /** A destination for telemetry: the local Collector, or a sink the environment names. */
9
+ export interface Exporter {
10
+ readonly id: string;
11
+ readonly traces: Endpoint;
12
+ readonly logs: Endpoint;
13
+ readonly metrics?: Endpoint | undefined;
14
+ }
15
+ export interface TelemetryApi {
16
+ /**
17
+ * What the environment adds to the Collector: its sinks (`OTLP_SINKS`) and its name (`ORTHO_ENVIRONMENT`). Bindings
18
+ * never change within an isolate, so the generated Worker says it once per request, on a line of its own, and
19
+ * `serve` keeps its own call as it was.
20
+ */
21
+ readonly configure: (options: {
22
+ readonly sinks: string | undefined;
23
+ readonly environment: string | undefined;
24
+ }) => void;
25
+ readonly serve: (options: {
26
+ /** The local Collector's OTLP/HTTP base URL. Unset and with no sinks: no export, but trace ids still flow. */
27
+ readonly url: string | undefined;
28
+ /** The environment's sinks beside the Collector, as JSON (`OTLP_SINKS`): each one's endpoints and headers. */
29
+ readonly sinks?: string | undefined;
30
+ /** The environment's name, written on every span's resource as `deployment.environment`. */
31
+ readonly environment?: string | undefined;
32
+ readonly service: string;
33
+ readonly handler: WebHandler;
34
+ readonly waitUntil: (promise: Promise<unknown>) => void;
35
+ }, request: Request) => Promise<Response>;
36
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ import type { ClockState, Controller } from "#modules/clock/types.js";
2
+ import { type Count } from "./count.ts";
3
+ import type { Table } from "./table.ts";
4
+ export interface ControllerOptions {
5
+ readonly clock: ClockState;
6
+ readonly table: Table;
7
+ readonly count: Count;
8
+ /** How long a quiet wait may take in real time, in milliseconds. */
9
+ readonly limit: number;
10
+ /** The most timers one move may fire at one instant before it gives up: a timer that sets itself again at the instant it fired at never ends. */
11
+ readonly fireLimit: number;
12
+ }
13
+ export declare const makeController: ({ clock, table, count, limit, fireLimit }: ControllerOptions) => Controller;
@@ -0,0 +1,63 @@
1
+ // The controller (K23 section 5): a move of a stepped world's clock is a walk from timer to timer. Wait until quiet, then
2
+ // find the earliest timer due at or before the target, move the instant to it, fire what is due there (by instant, then
3
+ // the order set, then owner), wait until quiet, and repeat; then move to the target and wait until quiet once more. A quiet
4
+ // wait that runs past its real-time limit fails as `NeverQuiet`, naming who is busy. If that is the first wait, nothing has moved.
5
+ import { Effect, Semaphore } from "effect";
6
+ import { NeverQuiet } from "./count.js";
7
+ const iso = (millis) => new Date(millis).toISOString();
8
+ export const makeController = ({ clock, table, count, limit, fireLimit }) => {
9
+ // One move at a time: a second waits its turn rather than walking the clock under the first.
10
+ const one = Semaphore.makeUnsafe(1);
11
+ return {
12
+ // The generation is read when the move is submitted, before it waits for the lock: a move queued behind another and overtaken by a reset
13
+ // belongs to the world it was asked of, and must not carry on in the next one.
14
+ settle: (plan) => Effect.suspend(() => {
15
+ const born = count.generation();
16
+ return one.withPermits(1)(Effect.gen(function* () {
17
+ if (count.generation() !== born)
18
+ return yield* Effect.fail({ _tag: "WorldReset" });
19
+ const planned = plan();
20
+ if (!planned.ok)
21
+ return yield* Effect.fail({ _tag: "Refused", status: planned.status, body: planned.body });
22
+ const target = planned.target;
23
+ // A reset ends the walk, and it must not move the clock the reset just put back.
24
+ const reset = Effect.suspend(() => (count.generation() === born ? Effect.void : Effect.fail({ _tag: "WorldReset" })));
25
+ const fired = [];
26
+ // How many have fired at the instant the walk is at: past the bound, something keeps registering timers due at it.
27
+ let here = { at: Number.NaN, fired: 0 };
28
+ yield* count.quiet(limit);
29
+ yield* reset;
30
+ // Settled means quiet and nothing due at the target, both at once: a request that registers an already-due timer while a
31
+ // quiet wait is under way (a zero-length sleep at the new instant) is seen on the next turn, so the walk goes on until a
32
+ // quiet wait ends with nothing due and the clock at the target.
33
+ for (;;) {
34
+ const next = table.earliest(target);
35
+ if (next === undefined && clock.now() >= target)
36
+ break;
37
+ // A timer already past due fires where the world stands: the clock never goes back.
38
+ const at = next === undefined ? target : Math.max(next, clock.now());
39
+ yield* reset;
40
+ clock.moveTo(iso(at));
41
+ if (next !== undefined) {
42
+ const batch = yield* table.fire(at, clock.source());
43
+ yield* reset;
44
+ for (const row of batch) {
45
+ if (row.durable)
46
+ fired.push({ due: iso(row.at), owner: row.owner, name: row.name });
47
+ }
48
+ here = { at, fired: here.at === at ? here.fired + batch.length : batch.length };
49
+ if (here.fired > fireLimit) {
50
+ // The clock stays where the walk reached (call 11); the owners still registering timers due now are named.
51
+ const again = new Set([...table.rows().filter((r) => r.at <= Math.max(at, target)).map((r) => r.owner), ...batch.map((r) => r.owner)]);
52
+ return yield* Effect.fail(new NeverQuiet({ busy: [...again].sort() }));
53
+ }
54
+ }
55
+ yield* count.quiet(limit);
56
+ yield* reset;
57
+ }
58
+ return { now: iso(clock.now()), fired };
59
+ }));
60
+ }),
61
+ timers: () => table.rows().map((r) => ({ due: iso(r.at), owner: r.owner, name: r.name })),
62
+ };
63
+ };
@@ -0,0 +1,39 @@
1
+ import { Effect } from "effect";
2
+ declare const NeverQuiet_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
3
+ readonly _tag: "NeverQuiet";
4
+ } & Readonly<A>;
5
+ /** A quiet wait ran past its real-time limit: each token still held is named by its owner, an operation's name for a handler. */
6
+ export declare class NeverQuiet extends NeverQuiet_base<{
7
+ readonly busy: ReadonlyArray<string>;
8
+ }> {
9
+ }
10
+ export interface Count {
11
+ /** Take a token for `owner`: its id, `<epoch>.<generation>.<n>`, the epoch being this incarnation of the count (a restart, or another world). */
12
+ readonly enter: (owner: string) => string;
13
+ /** Release exactly that token; an id of another generation, or one already released, does nothing. */
14
+ readonly leave: (id: string) => void;
15
+ /** Is this token held now? False for an id of another incarnation or generation, or one already released. */
16
+ readonly has: (id: string) => boolean;
17
+ /** How many resets this count has seen: a move that began in one generation must not carry on in the next. */
18
+ readonly generation: () => number;
19
+ /** Name a token again (a request's entry names it by its path, the operation names it when it begins). */
20
+ readonly name: (id: string, owner: string) => void;
21
+ /** The owner of each token held, once per token, sorted. */
22
+ readonly held: () => ReadonlyArray<string>;
23
+ /** Open a write section for a token (a commit): `false` when the world does not hold it (stale), `"closed"` when it does but is closed to writes while it resets. */
24
+ readonly section: (id: string) => boolean | "closed";
25
+ /** The write section ended. */
26
+ readonly sectionEnd: (id: string) => void;
27
+ /** Closed to writes and to new tokens (a reset is wiping the databases), until `admit`. */
28
+ readonly close: () => void;
29
+ readonly admit: () => void;
30
+ readonly closed: () => boolean;
31
+ /** Wait until no write section is open, for at most `limit` milliseconds of real time; a reset has begun, so nothing new opens. */
32
+ readonly drain: (limit: number) => Effect.Effect<void, NeverQuiet>;
33
+ /** Start a new generation: every token of the old one is forgotten, and waiters are released. */
34
+ readonly reset: () => void;
35
+ /** Wait until nothing is held; `NeverQuiet` naming who is, when `limit` milliseconds of real time pass first. */
36
+ readonly quiet: (limit: number) => Effect.Effect<void, NeverQuiet>;
37
+ }
38
+ export declare const makeCount: () => Count;
39
+ export {};
@@ -0,0 +1,105 @@
1
+ // The world's count of work in flight, across every process in it (M8.07): each token has an identity, an id that carries the
2
+ // incarnation and generation it was taken in, and only that id releases it. The owner is kept for naming who is busy. The world is quiet when no
3
+ // token of the current generation is held, on two reads in a row. A reset starts a new generation: an id from an older one, or one
4
+ // already released, can never release a token of the new one.
5
+ import { Data, Deferred, Duration, Effect, Option } from "effect";
6
+ /** A quiet wait ran past its real-time limit: each token still held is named by its owner, an operation's name for a handler. */
7
+ export class NeverQuiet extends Data.TaggedError("NeverQuiet") {
8
+ }
9
+ export const makeCount = () => {
10
+ const tokens = new Map();
11
+ // Ids restart at 0 in a new incarnation (the Durable Object restarted) and in every other world's count, so they carry an epoch of this one's own.
12
+ const epoch = crypto.randomUUID().slice(0, 8);
13
+ let generation = 0;
14
+ let next = 0;
15
+ let waiters = [];
16
+ const sections = new Map();
17
+ let draining = [];
18
+ let closed = false;
19
+ const sectionsEnded = () => {
20
+ if (sections.size > 0)
21
+ return;
22
+ const ready = draining;
23
+ draining = [];
24
+ for (const d of ready)
25
+ Deferred.doneUnsafe(d, Effect.void);
26
+ };
27
+ const held = () => [...tokens.values()].sort();
28
+ const empty = Effect.suspend(() => {
29
+ if (tokens.size === 0)
30
+ return Effect.void;
31
+ const d = Deferred.makeUnsafe();
32
+ waiters.push(d);
33
+ return Deferred.await(d);
34
+ });
35
+ const release = () => {
36
+ const ready = waiters;
37
+ waiters = [];
38
+ for (const d of ready)
39
+ Deferred.doneUnsafe(d, Effect.void);
40
+ };
41
+ // Two reads in a row agree: work a woken process starts on the next turn is seen before the world is called quiet.
42
+ const settled = Effect.gen(function* () {
43
+ yield* empty;
44
+ yield* Effect.yieldNow;
45
+ if (tokens.size !== 0)
46
+ return yield* settled;
47
+ });
48
+ return {
49
+ enter: (owner) => {
50
+ const id = `${epoch}.${generation}.${next++}`;
51
+ tokens.set(id, owner);
52
+ return id;
53
+ },
54
+ leave: (id) => {
55
+ if (!tokens.delete(id))
56
+ return;
57
+ if (tokens.size === 0)
58
+ release();
59
+ },
60
+ name: (id, owner) => {
61
+ if (tokens.has(id))
62
+ tokens.set(id, owner);
63
+ },
64
+ held,
65
+ has: (id) => tokens.has(id),
66
+ section: (id) => {
67
+ if (!tokens.has(id))
68
+ return false;
69
+ if (closed)
70
+ return "closed";
71
+ sections.set(id, (sections.get(id) ?? 0) + 1);
72
+ return true;
73
+ },
74
+ sectionEnd: (id) => {
75
+ const n = sections.get(id);
76
+ if (n === undefined)
77
+ return;
78
+ if (n <= 1)
79
+ sections.delete(id);
80
+ else
81
+ sections.set(id, n - 1);
82
+ sectionsEnded();
83
+ },
84
+ close: () => { closed = true; },
85
+ admit: () => { closed = false; },
86
+ closed: () => closed,
87
+ drain: (limit) => {
88
+ if (sections.size === 0)
89
+ return Effect.void;
90
+ const d = Deferred.makeUnsafe();
91
+ draining.push(d);
92
+ // Sections still open at the bound are named by their owners: the reset fails there, rather than wipe under a write.
93
+ return Deferred.await(d).pipe(Effect.timeoutOption(Duration.millis(limit)), Effect.flatMap((done) => (Option.isSome(done) || sections.size === 0 ? Effect.void : Effect.fail(new NeverQuiet({ busy: [...sections.keys()].map((id) => tokens.get(id) ?? id).sort() })))));
94
+ },
95
+ generation: () => generation,
96
+ reset: () => {
97
+ generation += 1;
98
+ tokens.clear();
99
+ sections.clear();
100
+ sectionsEnded();
101
+ release();
102
+ },
103
+ quiet: (limit) => settled.pipe(Effect.timeoutOption(Duration.millis(limit)), Effect.flatMap((done) => (Option.isSome(done) ? Effect.void : Effect.fail(new NeverQuiet({ busy: held() }))))),
104
+ };
105
+ };
@@ -0,0 +1,4 @@
1
+ /** A timer's delay is a signed 32-bit number of milliseconds: a longer one would fire at once, so no limit is longer than this. */
2
+ export declare const MAX_DELAY_MS: number;
3
+ /** A limit: a whole number greater than nought, no longer than a timer can wait; anything else (a fraction, a huge number, text) is the default. */
4
+ export declare const limitOf: (text: string | undefined, fallback: number) => number;
@@ -0,0 +1,8 @@
1
+ // The world's two real-time bounds (M8.07), read from its environment.
2
+ /** A timer's delay is a signed 32-bit number of milliseconds: a longer one would fire at once, so no limit is longer than this. */
3
+ export const MAX_DELAY_MS = 2 ** 31 - 2;
4
+ /** A limit: a whole number greater than nought, no longer than a timer can wait; anything else (a fraction, a huge number, text) is the default. */
5
+ export const limitOf = (text, fallback) => {
6
+ const n = Number(text);
7
+ return text !== undefined && Number.isInteger(n) && n > 0 ? Math.min(n, MAX_DELAY_MS) : fallback;
8
+ };
@@ -0,0 +1,52 @@
1
+ import { Effect } from "effect";
2
+ import type { DurableTimer, Wake } from "@orthograph/language-effect";
3
+ import type { ClockSource } from "#modules/clock/types.js";
4
+ import { NeverQuiet, type Count } from "./count.ts";
5
+ export interface Row {
6
+ readonly id: number;
7
+ readonly at: number;
8
+ readonly owner: string;
9
+ readonly name: string;
10
+ }
11
+ declare const WakeFailed_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
12
+ readonly _tag: "WakeFailed";
13
+ } & Readonly<A>;
14
+ /** A durable timer's wake failed: its row is back in the table, and the step that fired it fails, naming it. */
15
+ export declare class WakeFailed extends WakeFailed_base<{
16
+ readonly owner: string;
17
+ readonly name: string;
18
+ readonly message: string;
19
+ }> {
20
+ }
21
+ /** What a sleeper learns when its row ends: the instant it fired at, or that the world forgot it (a reset ended the run it belonged to). */
22
+ export interface Woken {
23
+ readonly source: ClockSource | undefined;
24
+ readonly forgotten: boolean;
25
+ }
26
+ export interface Table {
27
+ readonly add: (owner: string, name: string, at: number, holder: string) => number;
28
+ /** Resolves when the row fires, with the source of the instant it fired at; the world holds a token for the sleeper by then. */
29
+ readonly wait: (id: number) => Effect.Effect<Woken>;
30
+ /** The sleeper is back or gave up: the row is taken back if it has not fired, and the token the world held for it is released. Idempotent. */
31
+ readonly cancel: (id: number) => void;
32
+ readonly set: (at: number, owner: string, name: string, wake: Wake) => number;
33
+ readonly clear: (owner: string, name: string) => boolean;
34
+ /** Every row, in firing order: by instant, then the order set. */
35
+ readonly rows: () => ReadonlyArray<Row>;
36
+ readonly durable: () => ReadonlyArray<DurableTimer>;
37
+ readonly sleeping: () => ReadonlyArray<Row>;
38
+ /** The earliest instant a row is due at, at or before `target` when one is given. */
39
+ readonly earliest: (target?: number) => number | undefined;
40
+ /** Fire every row due at or before `at`, in order. A durable row goes to `wakes`; with none, its firing fails. */
41
+ readonly fire: (at: number, source: ClockSource | undefined) => Effect.Effect<ReadonlyArray<Row & {
42
+ readonly durable: boolean;
43
+ }>, WakeFailed | NeverQuiet>;
44
+ /** Forget every row, end the wakes still running, and tell every parked sleeper it was forgotten: the warm reset between runs. */
45
+ readonly reset: () => void;
46
+ }
47
+ export declare const makeTable: (sql: SqlStorage, count: Count, wakes: ((timer: DurableTimer) => Effect.Effect<void>) | undefined,
48
+ /** A real world counts nothing: nobody waits for it to be quiet. */
49
+ counting: boolean,
50
+ /** How long a wake may take in real milliseconds before the firing is abandoned (its row recoverable, its token released). */
51
+ wakeLimit?: number) => Table;
52
+ export {};