@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,36 @@
1
+ import { clockDoor } from "./internal/door.js";
2
+ import { boxOf, inEntry, install, inWorld, refresh, wall } from "./internal/date.js";
3
+ import { stateOf } from "./internal/state.js";
4
+ const REAL = { kind: "real" };
5
+ /** Each environment's clock, from `ORTHO_CLOCKS`. Anything that does not read as a clock is real: a world never guesses. */
6
+ const clocksOf = (env) => {
7
+ if (!env.ORTHO_CLOCKS)
8
+ return {};
9
+ const parsed = JSON.parse(env.ORTHO_CLOCKS);
10
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
11
+ };
12
+ const declaredIn = (declared) => {
13
+ const clock = declared;
14
+ if (clock?.kind === "stepped" && typeof clock.starts === "string")
15
+ return { kind: "stepped", starts: clock.starts };
16
+ if (clock?.kind === "scaled" && typeof clock.starts === "string" && typeof clock.speed === "number")
17
+ return { kind: "scaled", starts: clock.starts, speed: clock.speed };
18
+ return REAL;
19
+ };
20
+ export const WorldClock = {
21
+ // A world made by `ortho dev` or a prove run has no environment name set beyond `local`; a name nothing declares is real.
22
+ declared: (env) => declaredIn(clocksOf(env)[env.ORTHO_ENVIRONMENT || "local"]),
23
+ state: stateOf,
24
+ door: clockDoor,
25
+ within: (instant, f) => {
26
+ install();
27
+ return inWorld(instant, f);
28
+ },
29
+ entered: (source, box, f, end) => {
30
+ install();
31
+ return inEntry(source, box, f, end);
32
+ },
33
+ box: boxOf,
34
+ refresh,
35
+ wall,
36
+ };
@@ -0,0 +1,152 @@
1
+ import type { Effect } from "effect";
2
+ import type { BusyBox } from "@orthograph/language-effect";
3
+ /** An environment's clock as the model writes it (`environments.<e>.clock`), instants in ISO 8601 with milliseconds. */
4
+ export type ClockDeclaration = {
5
+ readonly kind: "real";
6
+ } | {
7
+ readonly kind: "stepped";
8
+ readonly starts: string;
9
+ } | {
10
+ readonly kind: "scaled";
11
+ readonly starts: string;
12
+ readonly speed: number;
13
+ };
14
+ /**
15
+ * What a request reads the world's time from (kept in the async-local store, so it is per request): a fixed instant for a
16
+ * stepped world, or the anchors of a scaled one, from which every read works out the instant now, with no lookup.
17
+ */
18
+ export type ClockSource = {
19
+ readonly kind: "stepped";
20
+ readonly instant: number;
21
+ } | {
22
+ readonly kind: "scaled";
23
+ readonly realAnchor: number;
24
+ readonly worldAnchor: number;
25
+ readonly speed: number;
26
+ };
27
+ /** The Worker's bindings that say how this world tells time. The generated config sets `ORTHO_CLOCKS`, only when some environment is not real. */
28
+ export interface ClockEnv {
29
+ /** JSON: each environment's declared clock, by the environment's name. Absent: every world is real. */
30
+ readonly ORTHO_CLOCKS?: string;
31
+ readonly ORTHO_ENVIRONMENT?: string;
32
+ }
33
+ /** A row of the world's timer table as the door shows it. */
34
+ export interface ClockTimer {
35
+ readonly due: string;
36
+ readonly owner: string;
37
+ readonly name: string;
38
+ }
39
+ /** What `GET /_world/clock` answers: the clock's kind and instant, and the world's timer table in firing order (M8.07). */
40
+ export interface ClockReading {
41
+ readonly kind: ClockDeclaration["kind"];
42
+ readonly now: string;
43
+ readonly timers: ReadonlyArray<ClockTimer>;
44
+ }
45
+ /** Where a move would land, or why it cannot: nothing is changed. */
46
+ export type Planned = {
47
+ readonly ok: true;
48
+ readonly target: number;
49
+ } | Extract<Moved, {
50
+ readonly ok: false;
51
+ }>;
52
+ /** Why a move did not settle (M8.07): a process stayed busy past the real-time limit, or a durable timer's wake failed. */
53
+ export type Unsettled = {
54
+ readonly _tag: "NeverQuiet";
55
+ readonly busy: ReadonlyArray<string>;
56
+ } | {
57
+ readonly _tag: "WakeFailed";
58
+ readonly owner: string;
59
+ readonly name: string;
60
+ readonly message: string;
61
+ }
62
+ /** The move itself was refused when it came to be planned (a real clock, a bad span, a move back). */
63
+ /** A reset ended the run the move belonged to: nothing was moved after it. */
64
+ | {
65
+ readonly _tag: "WorldReset";
66
+ } | {
67
+ readonly _tag: "Refused";
68
+ readonly status: 400 | 409;
69
+ readonly body: {
70
+ readonly _tag: string;
71
+ readonly message: string;
72
+ };
73
+ };
74
+ /**
75
+ * What settles a stepped world's move (the timers module builds it): walks the clock to the target, firing what is due
76
+ * on the way, and answers once the world is quiet there. `fired` lists the durable timers that ran on the way.
77
+ */
78
+ export interface Controller {
79
+ /**
80
+ * `plan` is made inside the controller's lock, so a move relative to the instant (`"1 month"`) starts from where the move
81
+ * before it ended, not from where the world stood when the request arrived.
82
+ */
83
+ readonly settle: (plan: () => Planned) => Effect.Effect<{
84
+ readonly now: string;
85
+ readonly fired: ReadonlyArray<ClockTimer>;
86
+ }, Unsettled>;
87
+ readonly timers: () => ReadonlyArray<ClockTimer>;
88
+ }
89
+ /** A move of the world's clock: where it landed, or why it could not go. */
90
+ export type Moved = {
91
+ readonly ok: true;
92
+ readonly now: number;
93
+ } | {
94
+ readonly ok: false;
95
+ readonly status: 400 | 409;
96
+ readonly body: {
97
+ readonly _tag: "ClockNotMovable" | "BadMove";
98
+ readonly message: string;
99
+ };
100
+ };
101
+ /** The instant a world keeps, in its own Durable Object's SQLite storage. */
102
+ export interface ClockState {
103
+ readonly kind: ClockDeclaration["kind"];
104
+ /** The world's instant now, in epoch milliseconds. Real: the wall clock. Stepped: where it stands. Scaled: it flows at its speed. */
105
+ readonly now: () => number;
106
+ /** What a request runs inside to read this clock: `undefined` for a real clock, which is never patched. */
107
+ readonly source: () => ClockSource | undefined;
108
+ /**
109
+ * Back to the declared `starts`, a scaled clock re-anchored at the real now: the one sanctioned way back, for the warm
110
+ * reset between runs (ST1.24). The door's `move-to` still refuses an earlier instant. A real clock has nothing to reset.
111
+ */
112
+ readonly reset: () => void;
113
+ /** Where a move would land, without making it: a span (`"1 month"`) or an instant. A real clock refuses; so does a move back. */
114
+ readonly plan: (move: {
115
+ readonly span: string;
116
+ } | {
117
+ readonly to: string;
118
+ }) => Planned;
119
+ /** Move by a span in words (`"1 month"`; months and years on the calendar, in UTC). A real clock refuses. */
120
+ readonly advance: (span: string) => Moved;
121
+ /** Move to an instant (ISO 8601). It never goes back. A real clock refuses. */
122
+ readonly moveTo: (to: string) => Moved;
123
+ }
124
+ export interface WorldClockApi {
125
+ /** The clock this environment declares; real when nothing says otherwise. */
126
+ readonly declared: (env: ClockEnv) => ClockDeclaration;
127
+ /** The world's own state over its SQLite storage; `starts` is read once, when the world is made. */
128
+ readonly state: (sql: SqlStorage, declaration: ClockDeclaration) => ClockState;
129
+ /** `/_world/clock` (GET), `/_world/clock/advance` and `/_world/clock/move-to` (POST); nothing for any other request. */
130
+ readonly door: (state: ClockState, request: Request, controller?: Controller) => Promise<Response> | undefined;
131
+ /**
132
+ * Run `f` with `Date` and Effect's `Clock` reading `source`, through every await, timer and `waitUntil` it starts. The
133
+ * `Date` proxy is installed once, here, the first time it is asked; the source is per async context
134
+ * (`AsyncLocalStorage`), never a global assignment. A scaled source is read live: each read works out the instant now.
135
+ * Callers ask only for a world that is not real.
136
+ */
137
+ readonly within: <A>(source: ClockSource, f: () => A) => A;
138
+ /**
139
+ * `within` for an entry that holds a token of the world's count for its request (`box`): `end` gives it back when the entry
140
+ * ends, whatever way it ends.
141
+ */
142
+ readonly entered: <A>(source: ClockSource, box: BusyBox, f: () => Promise<A>, end: (box: BusyBox) => Promise<unknown>) => Promise<A>;
143
+ /** The running request's token box; nothing outside a request. */
144
+ readonly box: () => BusyBox | undefined;
145
+ /**
146
+ * Point the request that is running at a fresh source: a durable sleep's wake does it, because the request outlived a move
147
+ * of the world's clock (M8.06 call 4). Only this request's own cell changes. False outside a request.
148
+ */
149
+ readonly refresh: (source: ClockSource) => boolean;
150
+ /** The wall clock, for the world's own lifetime and for a scaled clock to anchor against. Never patched. */
151
+ readonly wall: () => number;
152
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { DatabaseApi } from "./types.ts";
2
+ export declare const Database: DatabaseApi;
@@ -0,0 +1,6 @@
1
+ import { Layer } from "effect";
2
+ import { D1Client } from "@effect/sql-d1";
3
+ export const Database = {
4
+ // A binding that is missing or wrong is a broken deploy, not something a caller can handle: it dies.
5
+ d1: (db) => D1Client.layer({ db }).pipe(Layer.orDie),
6
+ };
@@ -0,0 +1,7 @@
1
+ import type { Layer } from "effect";
2
+ import type { SqlClient } from "effect/sql";
3
+ import type { D1Client } from "@effect/sql-d1";
4
+ export interface DatabaseApi {
5
+ /** Effect's `SqlClient` over a D1 binding. Handlers and generated code see only `SqlClient`. */
6
+ readonly d1: (db: D1Database) => Layer.Layer<SqlClient.SqlClient | D1Client.D1Client>;
7
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import type { DecodedEvent, EventChange } from "@orthograph/chain-evm/device";
2
+ import type { FollowerConfig, SinkEntry } from "../types.ts";
3
+ /** An event's arguments as JSON: a uint is its decimal string, an address keeps its case. */
4
+ export declare const fieldsOf: (value: unknown) => unknown;
5
+ /**
6
+ * What the sink is to be told of one change, or nothing. A `Confirmed` event is handed on, and so is a `Corrected` one that
7
+ * had been confirmed; `Observed` is not, and a take-back of an unconfirmed event is dropped: the sink never saw it (M6-chain item 12).
8
+ */
9
+ export declare const entryOf: (config: Pick<FollowerConfig, "chainId" | "contract">, change: EventChange<DecodedEvent>) => SinkEntry | undefined;
@@ -0,0 +1,20 @@
1
+ /** An event's arguments as JSON: a uint is its decimal string, an address keeps its case. */
2
+ export const fieldsOf = (value) => typeof value === "bigint" ? value.toString()
3
+ : Array.isArray(value) ? value.map(fieldsOf)
4
+ : typeof value === "object" && value !== null ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, fieldsOf(v)]))
5
+ : value;
6
+ const idOf = (chainId, event) => `${chainId}:${event.blockHash}:${event.logIndex}`;
7
+ /**
8
+ * What the sink is to be told of one change, or nothing. A `Confirmed` event is handed on, and so is a `Corrected` one that
9
+ * had been confirmed; `Observed` is not, and a take-back of an unconfirmed event is dropped: the sink never saw it (M6-chain item 12).
10
+ */
11
+ export const entryOf = (config, change) => {
12
+ const name = `${config.contract}.${change.event.eventName}`;
13
+ const args = fieldsOf(change.event.args);
14
+ if (change._tag === "Confirmed")
15
+ return { source: "chain", id: idOf(config.chainId, change.event), event: name, fields: args };
16
+ if (change._tag === "Corrected" && change.wasConfirmed) {
17
+ return { source: "chain", id: `${idOf(config.chainId, change.event)}:corrected`, event: `${name}Corrected`, fields: { ...args, wasConfirmed: true } };
18
+ }
19
+ return undefined;
20
+ };
@@ -0,0 +1,18 @@
1
+ import type { FollowerHealth } from "../types.ts";
2
+ /** The fault as an allow-list: a known tag, a known kind, and the sentence that goes with them. Nothing the error said is kept. */
3
+ export declare const classify: (error: unknown) => {
4
+ readonly tag: string;
5
+ readonly kind?: string;
6
+ readonly message: string;
7
+ };
8
+ export declare const failed: (before: FollowerHealth | undefined, error: unknown, at: number) => FollowerHealth;
9
+ interface Source {
10
+ readonly chainId: number;
11
+ readonly contract: string;
12
+ readonly address: string;
13
+ readonly event: unknown;
14
+ readonly fromBlock: string;
15
+ }
16
+ /** The same source means the same stream: a different one starts over (M6-chain item 12, the lead's decision). */
17
+ export declare const sameSource: (a: Source, b: Source) => boolean;
18
+ export {};
@@ -0,0 +1,27 @@
1
+ const SENTENCES = {
2
+ "FollowerFault:unconfigured": "the follower is not configured",
3
+ "FollowerFault:sink-refused": "the sink refused a change",
4
+ "FollowerFault:sink-answer": "the sink answered something other than accepted or seen",
5
+ "FollowerFault:sink-timeout": "the sink did not answer in time",
6
+ "ChainFault:transport": "the RPC could not be reached",
7
+ "ChainFault:timeout": "the RPC did not answer in time",
8
+ "ChainFault:reorg": "the chain changed during the read, or reorganised deeper than the checkpoint's window",
9
+ "ChainFault:configuration": "the chain settings are not valid",
10
+ "ChainFault:event": "an event of the contract could not be decoded",
11
+ "ChainFault": "the chain could not be read",
12
+ "FollowerFault": "the follower could not take a step",
13
+ };
14
+ const KINDS = new Set(["transport", "timeout", "reorg", "configuration", "event", "unsupported", "resource", "rejected", "unsimulated", "unconfigured", "sink-refused", "sink-answer", "sink-timeout"]);
15
+ /** The fault as an allow-list: a known tag, a known kind, and the sentence that goes with them. Nothing the error said is kept. */
16
+ export const classify = (error) => {
17
+ const e = error;
18
+ const tag = e?._tag === "ChainFault" || e?._tag === "FollowerFault" ? e._tag : "Unknown";
19
+ const kind = typeof e?.kind === "string" && KINDS.has(e.kind) ? e.kind : undefined;
20
+ return { tag, ...(kind === undefined ? {} : { kind }), message: SENTENCES[`${tag}:${kind}`] ?? SENTENCES[tag] ?? "the follower met an error it does not name" };
21
+ };
22
+ export const failed = (before, error, at) => ({
23
+ failures: (before?.failures ?? 0) + 1,
24
+ lastError: { ...classify(error), at },
25
+ });
26
+ /** The same source means the same stream: a different one starts over (M6-chain item 12, the lead's decision). */
27
+ export const sameSource = (a, b) => a.chainId === b.chainId && a.contract === b.contract && a.address === b.address && a.fromBlock === b.fromBlock && JSON.stringify(a.event) === JSON.stringify(b.event);
@@ -0,0 +1,26 @@
1
+ import { Effect } from "effect";
2
+ import type { FollowerConfig, FollowerSink, SinkEntry } from "../types.ts";
3
+ import { type Stored } from "./poll.ts";
4
+ export declare const CHECKPOINT = "checkpoint";
5
+ export declare const OUTBOX = "outbox";
6
+ /** What a Durable Object's storage gives, and no more. */
7
+ export interface Store {
8
+ get<T>(key: string): Promise<T | undefined>;
9
+ put<T>(key: string, value: T): Promise<void>;
10
+ delete(key: string): Promise<boolean>;
11
+ }
12
+ /** A step's read of the chain, kept before anything goes to the sink: the checkpoint it leads to, and the entries still to be taken. */
13
+ export interface Outbox {
14
+ readonly checkpoint: Stored;
15
+ readonly entries: ReadonlyArray<SinkEntry>;
16
+ readonly caughtUp: boolean;
17
+ }
18
+ /**
19
+ * One step. A step that left entries in the outbox delivers them first and does not read the chain. Otherwise it reads, stores the new
20
+ * checkpoint together with its entries, and only then hands them on: so a change the sink took is never lost to a failed later one, and a
21
+ * reorg before the retry still finds the checkpoint that says what the sink was told (M6-chain item 12). The sink's "seen" makes a
22
+ * second delivery of an id harmless.
23
+ */
24
+ export declare const runStep: (store: Store, config: FollowerConfig, sink: () => FollowerSink) => Effect.Effect<{
25
+ caughtUp: boolean;
26
+ }, import("@orthograph/chain-evm/device").ChainFault | import("./poll.ts").FollowerFault, never>;
@@ -0,0 +1,35 @@
1
+ import { TimersLive } from "@orthograph/language-effect";
2
+ import { Effect } from "effect";
3
+ import { hand, read } from "./poll.js";
4
+ export const CHECKPOINT = "checkpoint";
5
+ export const OUTBOX = "outbox";
6
+ const wait = (work) => Effect.promise(work);
7
+ /** Hand the entries on in order. Each one taken (accepted or seen) leaves the outbox; when it is empty the checkpoint it led to is the checkpoint. */
8
+ const deliver = (store, sink, box) => Effect.gen(function* () {
9
+ for (let i = 0; i < box.entries.length; i++) {
10
+ yield* hand(sink, box.entries[i]);
11
+ yield* wait(() => store.put(OUTBOX, { ...box, entries: box.entries.slice(i + 1) }));
12
+ }
13
+ // The checkpoint first: a stop before the delete leaves an empty outbox, which the next step only commits.
14
+ yield* wait(() => store.put(CHECKPOINT, box.checkpoint));
15
+ yield* wait(() => store.delete(OUTBOX));
16
+ return { caughtUp: box.caughtUp };
17
+ });
18
+ /**
19
+ * One step. A step that left entries in the outbox delivers them first and does not read the chain. Otherwise it reads, stores the new
20
+ * checkpoint together with its entries, and only then hands them on: so a change the sink took is never lost to a failed later one, and a
21
+ * reorg before the retry still finds the checkpoint that says what the sink was told (M6-chain item 12). The sink's "seen" makes a
22
+ * second delivery of an id harmless.
23
+ */
24
+ export const runStep = (store, config, sink) => Effect.gen(function* () {
25
+ const pending = yield* wait(() => store.get(OUTBOX));
26
+ if (pending !== undefined)
27
+ return yield* deliver(store, sink, pending);
28
+ const next = yield* read(config, yield* wait(() => store.get(CHECKPOINT)));
29
+ if (next.entries.length === 0) {
30
+ yield* wait(() => store.put(CHECKPOINT, next.checkpoint));
31
+ return { caughtUp: next.caughtUp };
32
+ }
33
+ yield* wait(() => store.put(OUTBOX, next));
34
+ return yield* deliver(store, sink, next);
35
+ }).pipe(Effect.provide(TimersLive));
@@ -0,0 +1,21 @@
1
+ import { type EventAbi, type EventCheckpoint, type EventFor } from "@orthograph/chain-evm/device";
2
+ import { Timers } from "@orthograph/language-effect";
3
+ import { Effect } from "effect";
4
+ import { type FollowerConfig, type FollowerSink, type SinkEntry } from "../types.ts";
5
+ declare const FollowerFault_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 & {
6
+ readonly _tag: "FollowerFault";
7
+ } & Readonly<A>;
8
+ export declare class FollowerFault extends FollowerFault_base<{
9
+ readonly kind: "unconfigured" | "sink-refused" | "sink-answer" | "sink-timeout";
10
+ readonly message: string;
11
+ }> {
12
+ }
13
+ export type Stored = EventCheckpoint<EventFor<EventAbi>>;
14
+ export declare const hand: (sink: () => FollowerSink, entry: SinkEntry) => Effect.Effect<undefined, FollowerFault, Timers>;
15
+ /** What one read of the chain finds: the checkpoint it leads to and the entries the sink is to be told, in order. Nothing is handed on here. */
16
+ export declare const read: (config: FollowerConfig, old: Stored | undefined) => Effect.Effect<{
17
+ checkpoint: EventCheckpoint<EventFor<import("viem").AbiEvent>>;
18
+ entries: SinkEntry[];
19
+ caughtUp: boolean;
20
+ }, import("@orthograph/chain-evm/device").ChainFault, never>;
21
+ export {};
@@ -0,0 +1,23 @@
1
+ import { makeChainPort, makeEventSource } from "@orthograph/chain-evm/device";
2
+ import { Timers, TimersLive } from "@orthograph/language-effect";
3
+ import { Data, Effect } from "effect";
4
+ import { SINK_TIMEOUT_MS } from "../types.js";
5
+ import { entryOf } from "./entries.js";
6
+ export class FollowerFault extends Data.TaggedError("FollowerFault") {
7
+ }
8
+ export const hand = (sink, entry) => Effect.gen(function* () {
9
+ const timers = yield* Timers;
10
+ const timedOut = new FollowerFault({ kind: "sink-timeout", message: `the sink did not answer ${entry.id} in time` });
11
+ const ask = Effect.tryPromise({ try: () => sink().accept(entry), catch: () => new FollowerFault({ kind: "sink-refused", message: `the sink refused ${entry.id}` }) });
12
+ const answer = yield* Effect.raceFirst(ask, timers.sleep("follower.sink", SINK_TIMEOUT_MS).pipe(Effect.andThen(Effect.fail(timedOut))));
13
+ if (answer !== "accepted" && answer !== "seen")
14
+ return yield* new FollowerFault({ kind: "sink-answer", message: `the sink answered ${JSON.stringify(answer)} for ${entry.id}` });
15
+ });
16
+ /** What one read of the chain finds: the checkpoint it leads to and the entries the sink is to be told, in order. Nothing is handed on here. */
17
+ export const read = (config, old) => Effect.gen(function* () {
18
+ const port = yield* makeChainPort({ chainId: config.chainId, rpcUrl: config.rpcUrl, ...(config.pollIntervalMs === undefined ? {} : { pollIntervalMs: config.pollIntervalMs }) });
19
+ const source = makeEventSource(config.event, config.address, BigInt(config.fromBlock));
20
+ const result = yield* port.follow(source, typeof config.depth === "number" ? { depth: config.depth } : config.depth).poll(old);
21
+ const entries = result.changes.flatMap((change) => entryOf(config, change) ?? []);
22
+ return { checkpoint: result.checkpoint, entries, caughtUp: result.caughtUp };
23
+ }).pipe(Effect.provide(TimersLive));
@@ -0,0 +1,31 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import type { CheckpointView, FollowerApi, FollowerConfig, FollowerHealth } from "./types.ts";
3
+ /**
4
+ * One follower per program, named `eip155:<chainId>:<address, lower case>`. It reads one contract's events through chain-evm's
5
+ * reliable stream and hands each `Confirmed` change, and each `Corrected` one that had been confirmed, to `env.FOLLOWER_SINK`
6
+ * (`Inbox.accept`'s shape). Its checkpoint lives in the Durable Object's storage and moves in one write, only after the sink
7
+ * has taken every change of the step; a replay after a failure or a restart is `seen` at the sink (M6-chain item 12).
8
+ * Export it from the Worker's entry and bind it as `FOLLOWER`. `configure`, `poll` and the alarm run one at a time.
9
+ */
10
+ export declare class Follower extends DurableObject implements FollowerApi {
11
+ private turn;
12
+ /**
13
+ * The same source again keeps the checkpoint; a different one (chain, contract, event or start block) starts a new stream and clears it.
14
+ * With a `pollIntervalMs` there is an alarm at that interval (reset when the interval changes); with none there is not, so a check
15
+ * that calls `poll` by hand is never raced.
16
+ */
17
+ configure(config: FollowerConfig): Promise<void>;
18
+ poll(): Promise<{
19
+ readonly caughtUp: boolean;
20
+ }>;
21
+ /**
22
+ * The alarm does what `poll` does. An error leaves the checkpoint where it was, is recorded (see `health`), and the next alarm is set
23
+ * all the same, so it tries again.
24
+ */
25
+ alarm(): Promise<void>;
26
+ private serially;
27
+ /** One step. A step that succeeds clears the health record; one the alarm makes that fails writes it. */
28
+ private job;
29
+ checkpoint(): Promise<CheckpointView>;
30
+ health(): Promise<FollowerHealth | null>;
31
+ }
@@ -0,0 +1,87 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import { Cause, Clock, Effect } from "effect";
3
+ import { failed, sameSource } from "./internal/health.js";
4
+ import { CHECKPOINT, OUTBOX, runStep } from "./internal/outbox.js";
5
+ import { FollowerFault } from "./internal/poll.js";
6
+ const CONFIG = "config";
7
+ const HEALTH = "health";
8
+ const view = ({ number, hash }) => ({ number: number.toString(), hash });
9
+ /**
10
+ * One follower per program, named `eip155:<chainId>:<address, lower case>`. It reads one contract's events through chain-evm's
11
+ * reliable stream and hands each `Confirmed` change, and each `Corrected` one that had been confirmed, to `env.FOLLOWER_SINK`
12
+ * (`Inbox.accept`'s shape). Its checkpoint lives in the Durable Object's storage and moves in one write, only after the sink
13
+ * has taken every change of the step; a replay after a failure or a restart is `seen` at the sink (M6-chain item 12).
14
+ * Export it from the Worker's entry and bind it as `FOLLOWER`. `configure`, `poll` and the alarm run one at a time.
15
+ */
16
+ export class Follower extends DurableObject {
17
+ turn = Promise.resolve();
18
+ /**
19
+ * The same source again keeps the checkpoint; a different one (chain, contract, event or start block) starts a new stream and clears it.
20
+ * With a `pollIntervalMs` there is an alarm at that interval (reset when the interval changes); with none there is not, so a check
21
+ * that calls `poll` by hand is never raced.
22
+ */
23
+ configure(config) {
24
+ const { ctx } = this;
25
+ return this.serially(() => Effect.runPromise(Effect.gen(function* () {
26
+ const before = yield* Effect.promise(() => ctx.storage.get(CONFIG));
27
+ if (before !== undefined && !sameSource(before, config))
28
+ yield* Effect.promise(() => ctx.storage.delete([CHECKPOINT, OUTBOX, HEALTH]));
29
+ yield* Effect.promise(() => ctx.storage.put(CONFIG, config));
30
+ const period = config.pollIntervalMs;
31
+ if (period === undefined)
32
+ return yield* Effect.promise(() => ctx.storage.deleteAlarm());
33
+ const set = yield* Effect.promise(() => ctx.storage.getAlarm());
34
+ if (set === null || before?.pollIntervalMs !== period) {
35
+ const now = yield* Clock.currentTimeMillis;
36
+ yield* Effect.promise(() => ctx.storage.setAlarm(now + period));
37
+ }
38
+ })));
39
+ }
40
+ poll() {
41
+ return this.serially(this.job(false));
42
+ }
43
+ /**
44
+ * The alarm does what `poll` does. An error leaves the checkpoint where it was, is recorded (see `health`), and the next alarm is set
45
+ * all the same, so it tries again.
46
+ */
47
+ alarm() {
48
+ const { ctx } = this;
49
+ const rearm = () => Effect.runPromise(Effect.gen(function* () {
50
+ const period = (yield* Effect.promise(() => ctx.storage.get(CONFIG)))?.pollIntervalMs;
51
+ if (period === undefined || (yield* Effect.promise(() => ctx.storage.getAlarm())) !== null)
52
+ return;
53
+ const now = yield* Clock.currentTimeMillis;
54
+ yield* Effect.promise(() => ctx.storage.setAlarm(now + period));
55
+ }));
56
+ const run = this.job(true);
57
+ return this.serially(() => run().then(() => undefined, () => undefined).then(rearm));
58
+ }
59
+ serially(run) {
60
+ const done = this.turn.then(run, run);
61
+ this.turn = done.catch(() => undefined);
62
+ return done;
63
+ }
64
+ /** One step. A step that succeeds clears the health record; one the alarm makes that fails writes it. */
65
+ job(record) {
66
+ const { ctx, env } = this;
67
+ return () => Effect.runPromise(Effect.gen(function* () {
68
+ const config = yield* Effect.promise(() => ctx.storage.get(CONFIG));
69
+ if (config === undefined)
70
+ return yield* new FollowerFault({ kind: "unconfigured", message: "this follower has not been configured" });
71
+ const sink = () => env.FOLLOWER_SINK.getByName(ctx.id.name ?? `eip155:${config.chainId}:${config.address}`);
72
+ const next = yield* runStep(ctx.storage, config, sink);
73
+ yield* Effect.promise(() => ctx.storage.delete(HEALTH));
74
+ return { caughtUp: next.caughtUp };
75
+ }).pipe(Effect.tapCause((cause) => !record ? Effect.void : Effect.gen(function* () {
76
+ const at = yield* Clock.currentTimeMillis;
77
+ const before = yield* Effect.promise(() => ctx.storage.get(HEALTH));
78
+ yield* Effect.promise(() => ctx.storage.put(HEALTH, failed(before, Cause.squash(cause), at)));
79
+ }))));
80
+ }
81
+ checkpoint() {
82
+ return this.ctx.storage.get(CHECKPOINT).then((stored) => stored === undefined ? { window: [] } : { ...(stored.through === undefined ? {} : { through: view(stored.through) }), window: stored.window.map(view) });
83
+ }
84
+ health() {
85
+ return this.ctx.storage.get(HEALTH).then((h) => h ?? null);
86
+ }
87
+ }
@@ -0,0 +1,71 @@
1
+ /** What `configure` takes. `event` is the ABI item of the event, as `makeEventSource` takes it (as JSON). */
2
+ export interface FollowerConfig {
3
+ readonly rpcUrl: string;
4
+ /** The chain's numeric id; the follower is named `eip155:<chainId>:<address>`. */
5
+ readonly chainId: number;
6
+ /** The contract's name, the first half of the event names it hands on ("Echo"). */
7
+ readonly contract: string;
8
+ /** Lower case. */
9
+ readonly address: string;
10
+ readonly event: unknown;
11
+ /** The first block to read, a decimal string. */
12
+ readonly fromBlock: string;
13
+ /** The confirmation level: a number of blocks (the check passes `2`), or chain-evm's own `{ depth }` or `{ tag }`. */
14
+ readonly depth: number | {
15
+ readonly depth: number;
16
+ } | {
17
+ readonly tag: "safe" | "finalized";
18
+ };
19
+ readonly pollIntervalMs?: number;
20
+ }
21
+ export interface BlockView {
22
+ readonly number: string;
23
+ readonly hash: string;
24
+ }
25
+ /** What `checkpoint()` answers: the last block read, and the window of block hashes, oldest first. */
26
+ export interface CheckpointView {
27
+ readonly through?: BlockView;
28
+ readonly window: ReadonlyArray<BlockView>;
29
+ }
30
+ /** How long the follower waits for the sink to answer one `accept`; a hung sink must not hold the follower's turn for ever. */
31
+ export declare const SINK_TIMEOUT_MS = 30000;
32
+ /** Why the alarm's last steps failed: the error's tag and kind and a fixed sentence, when (ms), and how many in a row. Cleared by the next step that succeeds. */
33
+ export interface FollowerHealth {
34
+ readonly failures: number;
35
+ /** Only the error's tag, its kind and a fixed sentence for them: nothing the error said, which might hold a URL or a key. */
36
+ readonly lastError: {
37
+ readonly tag: string;
38
+ readonly kind?: string;
39
+ readonly message: string;
40
+ readonly at: number;
41
+ };
42
+ }
43
+ /** What reaches the sink: `Inbox.accept`'s shape (Ask #481). */
44
+ export interface SinkEntry {
45
+ readonly source: "chain";
46
+ /** `${chainId}:${blockHash}:${logIndex}`, and `:corrected` after it for a correction. */
47
+ readonly id: string;
48
+ /** `<Contract>.<Event>`, and `<Contract>.<Event>Corrected` for a correction. */
49
+ readonly event: string;
50
+ readonly fields: Readonly<Record<string, unknown>>;
51
+ }
52
+ export type SinkAnswer = "accepted" | "seen";
53
+ /** The port the follower hands changes to. Goal 11's `Inbox.accept` fills it; until then a Worker binds a Durable Object with this method as `FOLLOWER_SINK`. */
54
+ export interface FollowerSink {
55
+ accept(entry: SinkEntry): Promise<SinkAnswer>;
56
+ }
57
+ export interface FollowerEnv {
58
+ readonly FOLLOWER_SINK: {
59
+ getByName(name: string): FollowerSink;
60
+ };
61
+ }
62
+ /** What the Worker calls on a follower, over Durable Object RPC. */
63
+ export interface FollowerApi {
64
+ configure(config: FollowerConfig): Promise<void>;
65
+ poll(): Promise<{
66
+ readonly caughtUp: boolean;
67
+ }>;
68
+ checkpoint(): Promise<CheckpointView>;
69
+ /** `null` while the follower is well. */
70
+ health(): Promise<FollowerHealth | null>;
71
+ }
@@ -0,0 +1,4 @@
1
+ // The follower: a Durable Object that follows one contract's events and hands each change to its sink (M6.09, M6-chain item 12).
2
+ // Every value that crosses Durable Object RPC is JSON; a uint is a decimal string.
3
+ /** How long the follower waits for the sink to answer one `accept`; a hung sink must not hold the follower's turn for ever. */
4
+ export const SINK_TIMEOUT_MS = 30_000;
@@ -0,0 +1,26 @@
1
+ import { Effect } from "effect";
2
+ import type { EventActor } from "orthograph";
3
+ export interface Delivery {
4
+ readonly id: string;
5
+ readonly trace: string;
6
+ readonly mount: string;
7
+ readonly event: string;
8
+ readonly fields: unknown;
9
+ readonly actor: EventActor | undefined;
10
+ }
11
+ /** The row the inbox kept for an id: the event's name and its payload as it first came. */
12
+ export interface Kept {
13
+ readonly event: string;
14
+ readonly fields: unknown;
15
+ }
16
+ /**
17
+ * `accepted` when this id was new, `seen` with the kept row when the inbox already had it: the unique id decides, in the database, so five
18
+ * deliveries at once are one. The kept row is only read, never changed.
19
+ */
20
+ export type Settled = {
21
+ readonly settled: "accepted";
22
+ } | {
23
+ readonly settled: "seen";
24
+ readonly kept: Kept | undefined;
25
+ };
26
+ export declare const accept: (db: D1Database, d: Delivery) => Effect.Effect<Settled>;
@@ -0,0 +1,10 @@
1
+ // The inbox is the journal (M5-reach-out Q2.3): one row per accepted delivery, its id `<mount>:<the event's identity>`, which is unique,
2
+ // so a delivery that comes twice, by any road, settles once. The row is in the request's trace.
3
+ import { Effect } from "effect";
4
+ export const accept = (db, d) => Effect.promise(() => db.prepare(`INSERT INTO "_journal" ("id", "trace", "operation", "move", "subject", "event", "fields", "actor") VALUES (?, ?, ?, '', ?, ?, ?, ?) ON CONFLICT ("id") DO NOTHING`)
5
+ .bind(d.id, d.trace, `in:${d.mount}`, d.id, d.event, JSON.stringify(d.fields), d.actor === undefined ? null : JSON.stringify(d.actor))
6
+ .run()).pipe(Effect.flatMap((result) => result.meta.changes > 0
7
+ ? Effect.succeed({ settled: "accepted" })
8
+ : Effect.promise(() => db.prepare(`SELECT "event", "fields" FROM "_journal" WHERE "id" = ?`).bind(d.id).first()).pipe(Effect.flatMap((row) => row === null
9
+ ? Effect.succeed(undefined)
10
+ : Effect.try(() => ({ event: row.event, fields: JSON.parse(row.fields) })).pipe(Effect.orElseSucceed(() => undefined))), Effect.map((kept) => ({ settled: "seen", kept })))));