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

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 +46 -3
@@ -0,0 +1,181 @@
1
+ // The world's timer table (M8.07): one table in the world's Durable Object, so a sleep and a durable timer share one order.
2
+ // A sleeping row lives as long as the process that parked it, which is why it is dropped when the object starts afresh;
3
+ // a durable row outlives it. Firing a row counts its owner first and only then hands it back, so the world is never quiet
4
+ // between the firing and the code that wakes.
5
+ import { Data, Deferred, Duration, Effect, Exit, Fiber, Option } from "effect";
6
+ import { NeverQuiet } from "./count.js";
7
+ /** A durable timer's wake failed: its row is back in the table, and the step that fired it fails, naming it. */
8
+ export class WakeFailed extends Data.TaggedError("WakeFailed") {
9
+ }
10
+ /** `firing` marks a durable row whose wake has started and not yet returned: it is out of the pending set but not gone, so a crash cannot lose it. */
11
+ const SCHEMA = "CREATE TABLE IF NOT EXISTS timers (id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, owner TEXT NOT NULL, name TEXT NOT NULL, holder TEXT, wake TEXT, firing INTEGER NOT NULL DEFAULT 0)";
12
+ /** The furthest instant a `Date` can hold either side of the epoch, in milliseconds: nothing the world's clock cannot hold goes in the table. */
13
+ const MAX_INSTANT = 8.64e15;
14
+ /** An instant the table and the clock can hold; anything else is refused (a defect to the caller) before it reaches SQL. */
15
+ const instantOf = (at, what) => Number.isFinite(at) && Math.abs(at) <= MAX_INSTANT ? at : Effect.runSync(Effect.die(new Error(`${what} needs a finite instant within a Date's range, not ${at}`)));
16
+ const rowOf = (r) => ({ id: r.id, at: r.at, owner: r.owner, name: r.name });
17
+ export const makeTable = (sql, count, wakes,
18
+ /** A real world counts nothing: nobody waits for it to be quiet. */
19
+ counting,
20
+ /** How long a wake may take in real milliseconds before the firing is abandoned (its row recoverable, its token released). */
21
+ wakeLimit = Number.POSITIVE_INFINITY) => {
22
+ sql.exec(SCHEMA);
23
+ if (!sql.exec("PRAGMA table_info(timers)").toArray().some((c) => c.name === "firing"))
24
+ sql.exec("ALTER TABLE timers ADD COLUMN firing INTEGER NOT NULL DEFAULT 0");
25
+ // A sleeping row belongs to a process that is gone with this object's memory.
26
+ sql.exec("DELETE FROM timers WHERE wake IS NULL");
27
+ // A wake the world died in the middle of is not lost (at least once, M8-timers-shape): its row is pending again, due as it was,
28
+ // unless a pending row now has the same (owner, name), which wins. Of several firing rows for one key the newest wins.
29
+ sql.exec("UPDATE timers SET firing = 0 WHERE firing = 1 AND NOT EXISTS (SELECT 1 FROM timers p WHERE p.firing = 0 AND p.wake IS NOT NULL AND p.owner = timers.owner AND p.name = timers.name)");
30
+ sql.exec("DELETE FROM timers WHERE firing = 1");
31
+ sql.exec("DELETE FROM timers WHERE wake IS NOT NULL AND firing = 0 AND id < (SELECT MAX(t.id) FROM timers t WHERE t.wake IS NOT NULL AND t.firing = 0 AND t.owner = timers.owner AND t.name = timers.name)");
32
+ const waiting = new Map();
33
+ /** The wakes running now, so a reset can end them: one from the run being wiped must not carry on into the next. */
34
+ const running = new Set();
35
+ /** The token the world holds for a sleeper from its row firing until the sleeper acknowledges (`cancel`). */
36
+ const woken = new Map();
37
+ /** The pending rows (not firing) that meet `where`, in firing order. */
38
+ const select = (where, ...args) => sql.exec(`SELECT id, at, owner, name, holder, wake FROM timers WHERE firing = 0${where === "" ? "" : ` AND ${where.replace(/^WHERE /, "")}`} ORDER BY at, id, owner`, ...args).toArray();
39
+ const durableOf = (r) => ({ ...rowOf(r), wake: JSON.parse(r.wake) });
40
+ const insert = (r) => sql.exec("INSERT INTO timers (at, owner, name, holder, wake) VALUES (?, ?, ?, ?, ?) RETURNING id", r.at, r.owner, r.name, r.holder, r.wake).one().id;
41
+ /** A sleeping row, taken out for good: false when it was already taken. */
42
+ const forget = (id) => sql.exec("DELETE FROM timers WHERE id = ? AND wake IS NULL", id).rowsWritten > 0;
43
+ /** A durable row, out of the pending set and into `firing`, in one step: false when something else already took it. */
44
+ const take = (id) => sql.exec("UPDATE timers SET firing = 1 WHERE id = ? AND firing = 0", id).rowsWritten > 0;
45
+ /** The wake has returned: the record goes. */
46
+ const done = (id) => void sql.exec("DELETE FROM timers WHERE id = ?", id);
47
+ /** The wake did not finish: pending again, unless the wake already set a replacement under the same (owner, name), which stands alone. */
48
+ const restore = (r) => {
49
+ // Each arrow is one SQL step, and the two run with nothing in between (this object runs one thing at a time): gone because a
50
+ // replacement stands, else pending again. A row a reset already forgot is not brought back (its id is never reused).
51
+ const replaced = sql.exec("DELETE FROM timers WHERE id = ? AND firing = 1 AND EXISTS (SELECT 1 FROM timers p WHERE p.firing = 0 AND p.wake IS NOT NULL AND p.owner = ? AND p.name = ?)", r.id, r.owner, r.name).rowsWritten > 0;
52
+ if (!replaced)
53
+ sql.exec("UPDATE timers SET firing = 0 WHERE id = ? AND firing = 1", r.id);
54
+ };
55
+ /** Give a token back by its id (the world's count ignores one of an older generation, or one already released). */
56
+ const give = (token) => { if (token !== undefined)
57
+ count.leave(token); };
58
+ const bounded = (wait) => Number.isFinite(wakeLimit) ? Effect.timeoutOption(wait, Duration.millis(wakeLimit)) : Effect.map(wait, Option.some);
59
+ /**
60
+ * One firing. Taking the row out, counting what it wakes and starting the wake are one uninterruptible step. The wake runs in a fiber
61
+ * of its own and the firing waits for it for at most `wakeLimit` real milliseconds: a wake that fails, is interrupted or never
62
+ * acknowledges puts its row back to pending (unless a replacement stands) and gives its token back, and the step fails naming it.
63
+ * False when an earlier wake in the walk already took the row.
64
+ */
65
+ const fireOne = (r, source) => Effect.uninterruptibleMask((restoreInterrupt) => Effect.suspend(() => {
66
+ if (r.wake === null) {
67
+ // A sleeper is an in-memory wait: it lives and dies with the process that parked it (and a row is dropped when the object starts),
68
+ // so it needs no record of a firing in progress. The world holds a token for it from here until it acknowledges.
69
+ if (!forget(r.id))
70
+ return Effect.succeed(false);
71
+ const gate = waiting.get(r.id);
72
+ if (gate !== undefined) {
73
+ if (counting)
74
+ woken.set(r.id, count.enter(r.holder ?? r.owner));
75
+ Deferred.doneUnsafe(gate, Effect.succeed({ source, forgotten: false }));
76
+ }
77
+ return Effect.succeed(true);
78
+ }
79
+ const timer = durableOf(r);
80
+ if (wakes === undefined) {
81
+ return Effect.fail(new WakeFailed({ owner: r.owner, name: r.name, message: `no wake handler routes kind ${timer.wake.kind} in this world` }));
82
+ }
83
+ if (!take(r.id))
84
+ return Effect.succeed(false);
85
+ const token = counting ? count.enter(r.owner) : undefined;
86
+ return Effect.gen(function* () {
87
+ const wake = yield* Effect.forkDetach(restoreInterrupt(wakes(timer)));
88
+ running.add(wake);
89
+ // Abandoned: the row goes back to pending now, and the wake, which may never return, is told to stop without waiting for it.
90
+ const abandon = Effect.suspend(() => {
91
+ restore(r);
92
+ return Effect.asVoid(Effect.forkDetach(Fiber.interrupt(wake)));
93
+ });
94
+ const ended = yield* restoreInterrupt(bounded(Fiber.await(wake))).pipe(Effect.onInterrupt(() => abandon), Effect.ensuring(Effect.sync(() => void running.delete(wake))));
95
+ if (Option.isNone(ended)) {
96
+ yield* abandon;
97
+ return yield* Effect.fail(new NeverQuiet({ busy: [r.owner] }));
98
+ }
99
+ if (Exit.isSuccess(ended.value)) {
100
+ done(r.id);
101
+ return true;
102
+ }
103
+ restore(r);
104
+ return yield* Effect.fail(new WakeFailed({ owner: r.owner, name: r.name, message: String(ended.value.cause) }));
105
+ }).pipe(Effect.ensuring(Effect.sync(() => give(token))));
106
+ }));
107
+ return {
108
+ add: (owner, name, at, holder) => {
109
+ const id = insert({ at: instantOf(at, `a sleep for ${owner} ${name}`), owner, name, holder, wake: null });
110
+ waiting.set(id, Deferred.makeUnsafe());
111
+ return id;
112
+ },
113
+ // A row the world no longer knows (a reset forgot it) tells its waiter so: it was part of a run that is over.
114
+ wait: (id) => {
115
+ const gate = waiting.get(id);
116
+ return gate === undefined ? Effect.succeed({ source: undefined, forgotten: true }) : Deferred.await(gate);
117
+ },
118
+ cancel: (id) => {
119
+ const gate = waiting.get(id);
120
+ waiting.delete(id);
121
+ forget(id);
122
+ // The token the world held for the sleeper goes back; one a reset already forgot is ignored by its id.
123
+ give(woken.get(id));
124
+ woken.delete(id);
125
+ // A wait still pending on a row that was taken back is let go, not left as a promise nobody will settle.
126
+ if (gate !== undefined)
127
+ Deferred.doneUnsafe(gate, Effect.succeed({ source: undefined, forgotten: false }));
128
+ },
129
+ set: (at, owner, name, wake) => {
130
+ const pending = select("WHERE wake IS NOT NULL AND owner = ? AND name = ?", owner, name)[0];
131
+ if (pending !== undefined)
132
+ return pending.id;
133
+ // The payload is JSON (rule 4): one that is not (a bigint, a cycle) is refused here, not stored as something else.
134
+ const payload = Effect.runSync(Effect.try(() => JSON.stringify(wake)).pipe(Effect.orDie));
135
+ return insert({ at: instantOf(at, `a durable timer for ${owner} ${name}`), owner, name, holder: null, wake: payload });
136
+ },
137
+ clear: (owner, name) => sql.exec("DELETE FROM timers WHERE wake IS NOT NULL AND firing = 0 AND owner = ? AND name = ?", owner, name).rowsWritten > 0,
138
+ rows: () => select("").map(rowOf),
139
+ durable: () => select("WHERE wake IS NOT NULL").map(durableOf),
140
+ sleeping: () => select("WHERE wake IS NULL").map(rowOf),
141
+ earliest: (target) => {
142
+ const first = select(target === undefined ? "" : "WHERE at <= ?", ...(target === undefined ? [] : [target]))[0];
143
+ return first?.at;
144
+ },
145
+ fire: (at, source) => Effect.gen(function* () {
146
+ const fired = [];
147
+ // Each row leaves the table only as its own firing begins, so a firing that fails leaves the rest pending; and one an
148
+ // earlier wake in this walk cleared or cancelled is gone by then, so it never fires (the rule `TimersMemory.fire` follows).
149
+ let failure;
150
+ for (const r of select("WHERE at <= ?", at)) {
151
+ // A row whose wake fails stays pending, with its retry; the rows due after it still fire, in order. A wake that ran out of time
152
+ // ends the sweep: the bound is per walk, and the next move or alarm retries.
153
+ const result = yield* Effect.result(fireOne(r, source));
154
+ if (result._tag === "Success") {
155
+ if (result.success)
156
+ fired.push({ ...rowOf(r), durable: r.wake !== null });
157
+ }
158
+ else {
159
+ failure ??= result.failure;
160
+ if (result.failure._tag === "NeverQuiet")
161
+ break;
162
+ }
163
+ }
164
+ if (failure !== undefined)
165
+ return yield* Effect.fail(failure);
166
+ return fired;
167
+ }),
168
+ reset: () => {
169
+ sql.exec("DELETE FROM timers");
170
+ // A sleeper still parked on a row is told it was forgotten, so it ends instead of carrying on into the new run; a wake still running
171
+ // is ended too, so it cannot set a row of the old run into the new table.
172
+ for (const gate of waiting.values())
173
+ Deferred.doneUnsafe(gate, Effect.succeed({ source: undefined, forgotten: true }));
174
+ waiting.clear();
175
+ woken.clear();
176
+ for (const wake of running)
177
+ wake.interruptUnsafe();
178
+ running.clear();
179
+ },
180
+ };
181
+ };
@@ -0,0 +1,12 @@
1
+ import { Effect } from "effect";
2
+ import { type DurableTimer } from "@orthograph/language-effect";
3
+ import type { WorldTimersOptions, WorldTimersState, WorldWakes } from "./types.ts";
4
+ export declare const WorldTimers: {
5
+ /** The wake for a durable timer, by its kind: `wakesByKind` over `kinds`. A kind with no handler is a defect, which fails the wake. */
6
+ route: (kinds: WorldWakes) => (timer: DurableTimer) => Effect.Effect<void>;
7
+ /**
8
+ * The timer table and the count of work in flight, over the world's own SQLite storage. A real world counts nothing and
9
+ * fires its rows from an alarm; a stepped or scaled one is walked by the controller (`/_world/clock`).
10
+ */
11
+ state: (options: WorldTimersOptions) => WorldTimersState;
12
+ };
@@ -0,0 +1,136 @@
1
+ import { Effect } from "effect";
2
+ import { TimerWakes, wakesByKind } from "@orthograph/language-effect";
3
+ import { WorldClock } from "#modules/clock/service.js";
4
+ import { makeController } from "./internal/controller.js";
5
+ import { makeCount } from "./internal/count.js";
6
+ import { limitOf } from "./internal/limits.js";
7
+ import { makeTable } from "./internal/table.js";
8
+ const DEFAULT_QUIET_MS = 5_000;
9
+ /** The most timers one move fires at one instant (`ORTHO_FIRE_LIMIT`): a timer that sets itself again at that instant would never end. */
10
+ const DEFAULT_FIRE_LIMIT = 10_000;
11
+ /** A world closed for a reset opens again by itself after this long (real milliseconds). */
12
+ const REOPEN_AFTER_MS = 30_000;
13
+ export const WorldTimers = {
14
+ /** The wake for a durable timer, by its kind: `wakesByKind` over `kinds`. A kind with no handler is a defect, which fails the wake. */
15
+ route: (kinds) => (timer) => Effect.flatMap(Effect.service(TimerWakes), (route) => route.wake(timer)).pipe(Effect.provide(wakesByKind(kinds))),
16
+ /**
17
+ * The timer table and the count of work in flight, over the world's own SQLite storage. A real world counts nothing and
18
+ * fires its rows from an alarm; a stepped or scaled one is walked by the controller (`/_world/clock`).
19
+ */
20
+ state: (options) => {
21
+ const { sql, clock, env, wakes, changed } = options;
22
+ const real = clock.kind === "real";
23
+ const count = makeCount();
24
+ // The quiet bound is for a controller's moves. A real world has none, so nothing times a wake out there: a slow wake that was abandoned
25
+ // could not be aborted and would run twice.
26
+ const table = makeTable(sql, count, wakes, !real, real ? Number.POSITIVE_INFINITY : limitOf(env.ORTHO_QUIET_MS, DEFAULT_QUIET_MS));
27
+ const fireLimit = limitOf(env.ORTHO_FIRE_LIMIT, DEFAULT_FIRE_LIMIT);
28
+ // The world closes to new tokens and to writes while a reset wipes the databases. It opens again when told the wipe is done, or by
29
+ // itself after a while, so a wipe that never finishes cannot keep it shut.
30
+ let closedAt;
31
+ const admit = () => {
32
+ closedAt = undefined;
33
+ count.admit();
34
+ };
35
+ const guard = () => {
36
+ if (closedAt !== undefined && WorldClock.wall() - closedAt > REOPEN_AFTER_MS)
37
+ admit();
38
+ };
39
+ /** A call that carries a token of a run that is over is refused before it touches the table. */
40
+ const live = (token, what) => {
41
+ if (token !== undefined && !real && !count.has(token))
42
+ Effect.runSync(Effect.die(new Error(`${what} came from a run the world has reset`)));
43
+ };
44
+ // A wake that failed put its row back; the alarm tries again a second later rather than at once, in a loop.
45
+ let retryAt;
46
+ const touched = (value) => {
47
+ changed();
48
+ return value;
49
+ };
50
+ return {
51
+ rpc: {
52
+ // A real world counts nothing: its tokens are never taken, so they cannot be missed.
53
+ countEnter: (owner) => {
54
+ if (real)
55
+ return "real";
56
+ guard();
57
+ // Closed for a reset: a request admitted now would lose its writes to the wipe. It is refused.
58
+ if (count.closed())
59
+ return Effect.runSync(Effect.die(new Error(`${owner} was refused: the world is being reset`)));
60
+ return count.enter(owner);
61
+ },
62
+ countSection: (id) => {
63
+ if (real)
64
+ return true;
65
+ guard();
66
+ return count.section(id);
67
+ },
68
+ countSectionEnd: (id) => (real ? undefined : count.sectionEnd(id)),
69
+ countLeave: (id) => (real ? undefined : count.leave(id)),
70
+ countName: (id, owner) => (real ? undefined : count.name(id, owner)),
71
+ countHas: (id) => (real ? true : count.has(id)),
72
+ timerAdd: (owner, name, at, holder, token) => {
73
+ live(token, `a sleep for ${owner}`);
74
+ return touched(table.add(owner, name, at, holder));
75
+ },
76
+ timerWait: (id) => Effect.runPromise(table.wait(id)),
77
+ timerCancel: (id) => void touched(table.cancel(id)),
78
+ timerSet: (at, owner, name, wake, token) => {
79
+ live(token, `a durable timer for ${owner} ${name}`);
80
+ return touched(table.set(at, owner, name, wake));
81
+ },
82
+ timerClear: (owner, name, token) => {
83
+ live(token, `a clear of ${owner} ${name}`);
84
+ return touched(table.clear(owner, name));
85
+ },
86
+ timersSleeping: () => table.sleeping(),
87
+ timersDurable: () => table.durable(),
88
+ },
89
+ controller: makeController({ clock, table, count, limit: limitOf(env.ORTHO_QUIET_MS, DEFAULT_QUIET_MS), fireLimit }),
90
+ nextAlarm: () => {
91
+ const due = real ? table.earliest() : undefined;
92
+ return due === undefined ? undefined : Math.max(due, retryAt ?? 0);
93
+ },
94
+ // Until nothing is due: a wake that set a timer already due, or a row that fell due while the wakes ran, is fired on this
95
+ // alarm and not left for a reschedule that may find the world gone quiet.
96
+ // Only a real world has an alarm for timers: a stepped or scaled one is fired by its controller, at its own instants.
97
+ fireDue: () => {
98
+ if (!real)
99
+ return Effect.void;
100
+ // At most `fireLimit` rows in one sweep: a wake that sets a due row under its own key would never end. Past it the sweep stops and
101
+ // the alarm comes again a second later.
102
+ let fired = 0;
103
+ // Suspended, so each sweep reads the wall clock afresh: a row that fell due while the wakes ran is due at this sweep's cutoff.
104
+ const sweep = Effect.suspend(() => table.fire(WorldClock.wall(), undefined)).pipe(Effect.match({
105
+ onSuccess: (rows) => { fired += rows.length; retryAt = undefined; },
106
+ // A row whose wake failed stays pending, with its retry; `fire` has already gone on to the rows due after it.
107
+ onFailure: () => { retryAt = WorldClock.wall() + 1_000; },
108
+ }), Effect.flatMap(() => {
109
+ if (fired > fireLimit) {
110
+ retryAt = WorldClock.wall() + 1_000;
111
+ return Effect.void;
112
+ }
113
+ return retryAt === undefined && table.earliest(WorldClock.wall()) !== undefined ? sweep : Effect.void;
114
+ }));
115
+ return sweep;
116
+ },
117
+ held: () => count.held(),
118
+ closed: () => {
119
+ guard();
120
+ return count.closed();
121
+ },
122
+ close: () => Effect.suspend(() => {
123
+ if (real)
124
+ return Effect.void;
125
+ closedAt = WorldClock.wall();
126
+ count.close();
127
+ return count.drain(limitOf(env.ORTHO_QUIET_MS, DEFAULT_QUIET_MS));
128
+ }),
129
+ admit,
130
+ reset: () => {
131
+ table.reset();
132
+ count.reset();
133
+ },
134
+ };
135
+ },
136
+ };
@@ -0,0 +1,82 @@
1
+ import type { Effect } from "effect";
2
+ import type { DurableTimer, Wake } from "@orthograph/language-effect";
3
+ import type { NeverQuiet } from "./internal/count.ts";
4
+ import type { ClockSource, ClockState, Controller } from "#modules/clock/types.js";
5
+ /**
6
+ * The wake route (M8.07): each kind of durable timer to the code that wakes what set it. The generated Worker declares the map
7
+ * (empty today; Goals 8 and 10 and the keeper register a kind) and the world's Durable Object runs it, in the world's time,
8
+ * when a durable row falls due. A kind nobody registered fails the wake, and its row stays pending.
9
+ */
10
+ export type WorldWakes = Readonly<Record<string, (timer: DurableTimer) => Effect.Effect<void>>>;
11
+ /** One row, as the Worker sees it. */
12
+ export interface TimerRow {
13
+ readonly id: number;
14
+ readonly at: number;
15
+ readonly owner: string;
16
+ readonly name: string;
17
+ }
18
+ /**
19
+ * What another process calls on the world's Durable Object. `timerWait` stays pending until the world fires the row; the
20
+ * world counts the sleeper (`holder`) before it answers, with the source of the instant it fired at.
21
+ */
22
+ export interface WorldTimersRpc {
23
+ /** Take a token for `owner`: its id, which carries the generation and releases exactly that token. */
24
+ countEnter(owner: string): string;
25
+ /** Release a token by its id; one of an older generation, or one already released, does nothing. */
26
+ countLeave(id: string): void;
27
+ /** Name a token again: the operation names its request's token, which the entry named by its path. */
28
+ countName(id: string, owner: string): void;
29
+ /** Is this token held by the world now? False after a reset, a restart, or its release. */
30
+ countHas(id: string): boolean;
31
+ /** Open a write section for a token (a commit): false when the world no longer holds it, or is closed to writes while it resets. */
32
+ countSection(id: string): boolean | "closed";
33
+ countSectionEnd(id: string): void;
34
+ /** `token` is the caller's own, when it has one: a call that carries a token the world no longer holds is from a run that is over, and is refused. */
35
+ timerAdd(owner: string, name: string, at: number, holder: string, token?: string): number;
36
+ /** Resolves when the world fires the row, or, with `forgotten`, when a reset ended the run the row belonged to. */
37
+ timerWait(id: number): Promise<{
38
+ readonly source: ClockSource | undefined;
39
+ readonly forgotten: boolean;
40
+ }>;
41
+ /** The sleeper is back or gave up: take the row back if it has not fired, release the token the world held for it. Idempotent. */
42
+ timerCancel(id: number): void;
43
+ timerSet(at: number, owner: string, name: string, wake: Wake, token?: string): number;
44
+ timerClear(owner: string, name: string, token?: string): boolean;
45
+ timersSleeping(): ReadonlyArray<TimerRow>;
46
+ timersDurable(): ReadonlyArray<DurableTimer>;
47
+ }
48
+ /** The world's side: the RPC surface, the controller the clock door settles with, and what a real world's alarm needs. */
49
+ export interface WorldTimersState {
50
+ readonly rpc: WorldTimersRpc;
51
+ readonly controller: Controller;
52
+ /** The earliest instant a row is due, which a real world sets its alarm for; nothing for a world that is not real. */
53
+ readonly nextAlarm: () => number | undefined;
54
+ /** A real world's alarm: fire every row that has fallen due, as counted work. */
55
+ readonly fireDue: () => Effect.Effect<void>;
56
+ /** The owner of each token the world holds now, once per token, sorted. */
57
+ readonly held: () => ReadonlyArray<string>;
58
+ /**
59
+ * The first half of the warm reset: the world closes to new tokens and to writes, and waits (bounded) for the write sections already open
60
+ * to end. A request that begins now is refused, rather than admitted into a world that is about to be wiped.
61
+ */
62
+ readonly close: () => Effect.Effect<void, NeverQuiet>;
63
+ /** Is the world closed for a reset now? */
64
+ readonly closed: () => boolean;
65
+ /** The second half: the databases are wiped, and the world admits requests again. Also happens by itself, a while after `close`. */
66
+ readonly admit: () => void;
67
+ /** The warm reset between runs: no row survives, and a sleeper still waiting on a row is woken rather than left hanging. */
68
+ readonly reset: () => void;
69
+ }
70
+ export interface WorldTimersOptions {
71
+ readonly sql: SqlStorage;
72
+ readonly clock: ClockState;
73
+ /** `ORTHO_QUIET_MS`: how long a quiet wait may take in real time before the move fails as `NeverQuiet`. Five seconds when unset. */
74
+ readonly env: {
75
+ readonly ORTHO_QUIET_MS?: string;
76
+ readonly ORTHO_FIRE_LIMIT?: string;
77
+ };
78
+ /** How a durable row reaches the code that set it; with none, firing one fails the step, naming it (M8.10 and Goals 8 and 10 route kinds). */
79
+ readonly wakes?: (timer: DurableTimer) => Effect.Effect<void>;
80
+ /** A row was set or taken: a real world moves its alarm. */
81
+ readonly changed: () => void;
82
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,34 @@
1
+ import type { ClockSource } from "#modules/clock/types.js";
2
+ import type { WorldTimersRpc } from "#modules/timers/types.js";
3
+ import type { EntryEnv } from "../types.ts";
4
+ /** What the Worker calls on its world's Durable Object, over RPC. */
5
+ export interface Keeper extends WorldTimersRpc {
6
+ readonly source: () => Promise<ClockSource | undefined>;
7
+ /** An entry begins: the world takes a token for it under `owner` and answers it with the source its request reads time from. */
8
+ readonly begin: (owner: string) => Promise<{
9
+ readonly source: ClockSource | undefined;
10
+ readonly token: string | undefined;
11
+ }>;
12
+ }
13
+ /** The world's Durable Object stub: the live world's own instance in an environment with leases, the one named `world` otherwise. */
14
+ export declare const keeperOf: (env: EntryEnv) => Promise<Keeper>;
15
+ /**
16
+ * What this request reads the world's time from, asked of the world's Durable Object once per entry; nothing for a real
17
+ * world. A stepped world's source is its instant (it cannot move while a request is in flight: an advance waits for quiet,
18
+ * M8.07); a scaled world's is its anchors, so each read works out the instant now without asking again.
19
+ */
20
+ export declare const sourceOf: (env: EntryEnv) => Promise<ClockSource | undefined>;
21
+ /**
22
+ * Run `f` in this request's world: `Date` and Effect's `Clock` read the world's time, and the world holds one token for the request
23
+ * (`owner`, `entry:<path>`) from the moment it arrives until `f` ends, so nothing that is in flight goes uncounted: a read, the
24
+ * portal, a sign-in, an operation, its retries, its authorization and its commit. A sleep lends the token out and takes it back
25
+ * (`Busy.lend`); the entry's own end gives it back. A real world runs `f` as it is.
26
+ */
27
+ export declare const within: <A>(env: EntryEnv, f: () => Promise<A>, owner?: string) => Promise<A>;
28
+ /** The same for an entry that answers at once (an RPC method): a real world still answers at once, with no promise made. */
29
+ export declare const withinNow: <A>(env: EntryEnv, f: () => A, owner?: string) => A | Promise<A>;
30
+ /**
31
+ * A Worker's entry, wrapped. `/_world/*` is the world's own door: the Durable Object wraps what reads the world's time,
32
+ * and the registry of worlds keeps real time (a world's lifetime is the machine's, K23 section 1), so it is not wrapped here.
33
+ */
34
+ export declare const entry: <Env extends EntryEnv>(handler: ExportedHandler<Env>) => ExportedHandler<Env>;
@@ -0,0 +1,69 @@
1
+ // Every entry that runs app code reads its world's instant and wraps itself (M8.05, M8.06): the Worker's `fetch`,
2
+ // `scheduled` and `queue`, each Durable Object's `fetch`, RPC and `alarm`, a Workflows step. The caller's world does not
3
+ // travel into another object's request, so each entry looks up its own, from the world's Durable Object. A real world
4
+ // skips all of it: no lookup, no patch.
5
+ import { Effect } from "effect";
6
+ import { makeBox } from "@orthograph/language-effect";
7
+ import { WorldClock } from "#modules/clock/service.js";
8
+ import { live } from "./leases.js";
9
+ /** The world's Durable Object stub: the live world's own instance in an environment with leases, the one named `world` otherwise. */
10
+ export const keeperOf = (env) => {
11
+ const name = env.ORTHO_WORLDS === "1" ? Effect.runPromise(live(env.DB)).then((held) => held[0]?.id ?? "world") : Promise.resolve("world");
12
+ return name.then((id) => env.WORLD.get(env.WORLD.idFromName(id)));
13
+ };
14
+ /**
15
+ * What this request reads the world's time from, asked of the world's Durable Object once per entry; nothing for a real
16
+ * world. A stepped world's source is its instant (it cannot move while a request is in flight: an advance waits for quiet,
17
+ * M8.07); a scaled world's is its anchors, so each read works out the instant now without asking again.
18
+ */
19
+ export const sourceOf = (env) => {
20
+ if (WorldClock.declared(env).kind === "real")
21
+ return Promise.resolve(undefined);
22
+ return keeperOf(env).then((keeper) => keeper.source());
23
+ };
24
+ /**
25
+ * Run `f` in this request's world: `Date` and Effect's `Clock` read the world's time, and the world holds one token for the request
26
+ * (`owner`, `entry:<path>`) from the moment it arrives until `f` ends, so nothing that is in flight goes uncounted: a read, the
27
+ * portal, a sign-in, an operation, its retries, its authorization and its commit. A sleep lends the token out and takes it back
28
+ * (`Busy.lend`); the entry's own end gives it back. A real world runs `f` as it is.
29
+ */
30
+ export const within = (env, f, owner = "entry:step") => {
31
+ if (WorldClock.declared(env).kind === "real")
32
+ return f();
33
+ return keeperOf(env).then((keeper) => keeper.begin(owner).then(({ source, token }) => {
34
+ if (source === undefined)
35
+ return (token === undefined ? Promise.resolve() : Promise.resolve(keeper.countLeave(token))).then(f);
36
+ const box = makeBox(owner, { pinned: true, ...(token === undefined ? {} : { id: token }) });
37
+ return WorldClock.entered(source, box, f, (ended) => endRequest(keeper, ended));
38
+ }));
39
+ };
40
+ /**
41
+ * The entry is over: the box is no longer pinned, and if no fiber of it is running (every one lent, or none) its token goes back. A
42
+ * fiber still running (work detached from the response) keeps the token, and gives it back itself when it ends.
43
+ */
44
+ const endRequest = (keeper, box) =>
45
+ // Under the box's own gate, so it cannot end between a fiber's take of the box's token and the record of it: that token would never be released.
46
+ Effect.runPromise(box.gate.withPermits(1)(Effect.sync(() => {
47
+ box.pinned = false;
48
+ if (box.id === undefined || box.holders > box.lent)
49
+ return undefined;
50
+ const id = box.id;
51
+ box.id = undefined;
52
+ return id;
53
+ }))).then((id) => (id === undefined ? undefined : keeper.countLeave(id)));
54
+ /** The same for an entry that answers at once (an RPC method): a real world still answers at once, with no promise made. */
55
+ export const withinNow = (env, f, owner = "entry:rpc") => WorldClock.declared(env).kind === "real" ? f() : within(env, () => Promise.resolve(f()), owner);
56
+ /**
57
+ * A Worker's entry, wrapped. `/_world/*` is the world's own door: the Durable Object wraps what reads the world's time,
58
+ * and the registry of worlds keeps real time (a world's lifetime is the machine's, K23 section 1), so it is not wrapped here.
59
+ */
60
+ export const entry = (handler) => {
61
+ return {
62
+ ...handler,
63
+ ...(handler.fetch === undefined
64
+ ? {}
65
+ : { fetch: (request, env, ctx) => (new URL(request.url).pathname.startsWith("/_world/") ? handler.fetch(request, env, ctx) : within(env, () => Promise.resolve(handler.fetch(request, env, ctx)), `entry:${new URL(request.url).pathname}`)) }),
66
+ ...(handler.scheduled === undefined ? {} : { scheduled: (controller, env, ctx) => within(env, () => Promise.resolve(handler.scheduled(controller, env, ctx)), "entry:scheduled") }),
67
+ ...(handler.queue === undefined ? {} : { queue: (batch, env, ctx) => within(env, () => Promise.resolve(handler.queue(batch, env, ctx)), "entry:queue") }),
68
+ };
69
+ };
@@ -0,0 +1,5 @@
1
+ import { Effect } from "effect";
2
+ import type { WorldHost } from "../types.ts";
3
+ type Where = Pick<WorldHost, "db" | "tables" | "stores" | "actors" | "actorTables">;
4
+ export declare const facts: ({ db, tables, stores, actors, actorTables }: Where, request: Request) => Effect.Effect<Response>;
5
+ export {};
@@ -0,0 +1,31 @@
1
+ // The world's facts: what `prove` reads back after a call, straight from the database, in wire form.
2
+ // `GET /_world/facts/record?table=<thing>&id=<id>` gives a row (or null); `GET /_world/facts/journal?trace=<id>` the
3
+ // trace's journal entries. Only tables the generated server names can be read. A declared store (K3) is its own
4
+ // database with its own tables and `_journal`: a table is read from the database it is in, and a trace's entries
5
+ // are the default's, then each store's.
6
+ import { Effect } from "effect";
7
+ const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
8
+ /** A thing that lives as an actor has no table: its row is what its Durable Object keeps, shown as a table's row is (fields in wire form, `state`, `version`). */
9
+ const actorRecord = (actors, table, id) => Effect.promise(() => {
10
+ const stub = actors.get(actors.idFromName(`${table}:${id}`));
11
+ return stub.find();
12
+ }).pipe(Effect.map((found) => (found === null ? null : { ...found.row, state: found.state, version: found.version })));
13
+ export const facts = ({ db, tables, stores = [], actors, actorTables = [] }, request) => Effect.gen(function* () {
14
+ const url = new URL(request.url);
15
+ const q = (k) => url.searchParams.get(k) ?? "";
16
+ if (url.pathname === "/_world/facts/record") {
17
+ const table = q("table");
18
+ if (actorTables.includes(table))
19
+ return actors ? json(yield* actorRecord(actors, table, q("id"))) : json({ error: `${table} lives as actors, and this Worker has no ACTORS binding` }, 404);
20
+ const holder = tables.includes(table) ? db : stores.find((s) => s.tables.includes(table))?.db;
21
+ if (!holder)
22
+ return json({ error: `no table ${table}` }, 404);
23
+ const row = yield* Effect.promise(() => holder.prepare(`SELECT * FROM "${table}" WHERE "id" = ?`).bind(q("id")).first());
24
+ return json(row ?? null);
25
+ }
26
+ if (url.pathname === "/_world/facts/journal") {
27
+ const each = yield* Effect.forEach([db, ...stores.map((s) => s.db)], (d) => Effect.promise(() => d.prepare(`SELECT * FROM "_journal" WHERE "trace" = ? ORDER BY "seq"`).bind(q("trace")).all()));
28
+ return json(each.flatMap((r) => r.results).map((r) => ({ ...r, fields: JSON.parse(r.fields) })));
29
+ }
30
+ return json({ error: "not a door the world has" }, 404);
31
+ });
@@ -0,0 +1,9 @@
1
+ import type { EntryEnv } from "../types.ts";
2
+ /**
3
+ * Run `f` as a write section of the request in progress. Outside a request (the world's own work) and in a real world it is run as it is. A
4
+ * request whose token is lent out (a fiber of it outside the box, say a statement made while every other fiber sleeps) takes a token of its own
5
+ * for the statement, so the section is still the world's to count and to close; a stale one is refused.
6
+ */
7
+ export declare const section: <A>(env: EntryEnv, f: () => Promise<A>) => Promise<A>;
8
+ /** A database whose every statement is a write section: the handler's `SqlClient`, the store, the journal and the identity run on it. */
9
+ export declare const fenced: (env: EntryEnv, db: D1Database) => D1Database;