@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.
- package/LICENSE +202 -0
- package/README.md +2 -2
- package/dist/index.d.ts +21 -0
- package/dist/index.js +12 -0
- package/dist/modules/actors/internal/tables.d.ts +1 -0
- package/dist/modules/actors/internal/tables.js +5 -0
- package/dist/modules/actors/service.d.ts +18 -0
- package/dist/modules/actors/service.js +51 -0
- package/dist/modules/actors/types.d.ts +35 -0
- package/dist/modules/actors/types.js +1 -0
- package/dist/modules/auth/internal/instance.d.ts +4462 -0
- package/dist/modules/auth/internal/instance.js +36 -0
- package/dist/modules/auth/internal/oauth.d.ts +20 -0
- package/dist/modules/auth/internal/oauth.js +70 -0
- package/dist/modules/auth/internal/options.d.ts +4886 -0
- package/dist/modules/auth/internal/options.js +75 -0
- package/dist/modules/auth/internal/schema.d.ts +2 -0
- package/dist/modules/auth/internal/schema.js +41 -0
- package/dist/modules/auth/internal/world-token.d.ts +15 -0
- package/dist/modules/auth/internal/world-token.js +40 -0
- package/dist/modules/auth/service.d.ts +9 -0
- package/dist/modules/auth/service.js +96 -0
- package/dist/modules/auth/types.d.ts +75 -0
- package/dist/modules/auth/types.js +1 -0
- package/dist/modules/clock/internal/date.d.ts +17 -0
- package/dist/modules/clock/internal/date.js +45 -0
- package/dist/modules/clock/internal/door.d.ts +2 -0
- package/dist/modules/clock/internal/door.js +49 -0
- package/dist/modules/clock/internal/state.d.ts +5 -0
- package/dist/modules/clock/internal/state.js +78 -0
- package/dist/modules/clock/service.d.ts +2 -0
- package/dist/modules/clock/service.js +36 -0
- package/dist/modules/clock/types.d.ts +152 -0
- package/dist/modules/clock/types.js +1 -0
- package/dist/modules/database/service.d.ts +2 -0
- package/dist/modules/database/service.js +6 -0
- package/dist/modules/database/types.d.ts +7 -0
- package/dist/modules/database/types.js +1 -0
- package/dist/modules/follower/internal/entries.d.ts +9 -0
- package/dist/modules/follower/internal/entries.js +20 -0
- package/dist/modules/follower/internal/health.d.ts +18 -0
- package/dist/modules/follower/internal/health.js +27 -0
- package/dist/modules/follower/internal/outbox.d.ts +26 -0
- package/dist/modules/follower/internal/outbox.js +35 -0
- package/dist/modules/follower/internal/poll.d.ts +21 -0
- package/dist/modules/follower/internal/poll.js +23 -0
- package/dist/modules/follower/service.d.ts +31 -0
- package/dist/modules/follower/service.js +87 -0
- package/dist/modules/follower/types.d.ts +71 -0
- package/dist/modules/follower/types.js +4 -0
- package/dist/modules/inbound/internal/accept.d.ts +26 -0
- package/dist/modules/inbound/internal/accept.js +10 -0
- package/dist/modules/inbound/internal/read.d.ts +10 -0
- package/dist/modules/inbound/internal/read.js +26 -0
- package/dist/modules/inbound/internal/same.d.ts +1 -0
- package/dist/modules/inbound/internal/same.js +12 -0
- package/dist/modules/inbound/internal/verify.d.ts +6 -0
- package/dist/modules/inbound/internal/verify.js +57 -0
- package/dist/modules/inbound/service.d.ts +2 -0
- package/dist/modules/inbound/service.js +110 -0
- package/dist/modules/inbound/types.d.ts +28 -0
- package/dist/modules/inbound/types.js +1 -0
- package/dist/modules/journal/service.d.ts +2 -0
- package/dist/modules/journal/service.js +23 -0
- package/dist/modules/journal/types.d.ts +8 -0
- package/dist/modules/journal/types.js +1 -0
- package/dist/modules/relayer/internal/adopt.d.ts +19 -0
- package/dist/modules/relayer/internal/adopt.js +34 -0
- package/dist/modules/relayer/internal/check.d.ts +16 -0
- package/dist/modules/relayer/internal/check.js +141 -0
- package/dist/modules/relayer/internal/health.d.ts +5 -0
- package/dist/modules/relayer/internal/health.js +7 -0
- package/dist/modules/relayer/internal/live.d.ts +26 -0
- package/dist/modules/relayer/internal/live.js +25 -0
- package/dist/modules/relayer/internal/relay.d.ts +22 -0
- package/dist/modules/relayer/internal/relay.js +44 -0
- package/dist/modules/relayer/internal/store.d.ts +41 -0
- package/dist/modules/relayer/internal/store.js +44 -0
- package/dist/modules/relayer/service.d.ts +58 -0
- package/dist/modules/relayer/service.js +124 -0
- package/dist/modules/relayer/types.d.ts +75 -0
- package/dist/modules/relayer/types.js +1 -0
- package/dist/modules/store/internal/actors.d.ts +6 -0
- package/dist/modules/store/internal/actors.js +24 -0
- package/dist/modules/store/internal/commit.d.ts +10 -0
- package/dist/modules/store/internal/commit.js +57 -0
- package/dist/modules/store/internal/list.d.ts +10 -0
- package/dist/modules/store/internal/list.js +28 -0
- package/dist/modules/store/internal/rows.d.ts +14 -0
- package/dist/modules/store/internal/rows.js +29 -0
- package/dist/modules/store/internal/unique.d.ts +3 -0
- package/dist/modules/store/internal/unique.js +17 -0
- package/dist/modules/store/service.d.ts +2 -0
- package/dist/modules/store/service.js +71 -0
- package/dist/modules/store/types.d.ts +36 -0
- package/dist/modules/store/types.js +1 -0
- package/dist/modules/telemetry/internal/exporters.d.ts +21 -0
- package/dist/modules/telemetry/internal/exporters.js +66 -0
- package/dist/modules/telemetry/service.d.ts +2 -0
- package/dist/modules/telemetry/service.js +52 -0
- package/dist/modules/telemetry/types.d.ts +36 -0
- package/dist/modules/telemetry/types.js +1 -0
- package/dist/modules/timers/internal/controller.d.ts +13 -0
- package/dist/modules/timers/internal/controller.js +63 -0
- package/dist/modules/timers/internal/count.d.ts +39 -0
- package/dist/modules/timers/internal/count.js +105 -0
- package/dist/modules/timers/internal/limits.d.ts +4 -0
- package/dist/modules/timers/internal/limits.js +8 -0
- package/dist/modules/timers/internal/table.d.ts +52 -0
- package/dist/modules/timers/internal/table.js +181 -0
- package/dist/modules/timers/service.d.ts +12 -0
- package/dist/modules/timers/service.js +136 -0
- package/dist/modules/timers/types.d.ts +82 -0
- package/dist/modules/timers/types.js +1 -0
- package/dist/modules/world/internal/entry.d.ts +34 -0
- package/dist/modules/world/internal/entry.js +69 -0
- package/dist/modules/world/internal/facts.d.ts +5 -0
- package/dist/modules/world/internal/facts.js +31 -0
- package/dist/modules/world/internal/fence.d.ts +9 -0
- package/dist/modules/world/internal/fence.js +90 -0
- package/dist/modules/world/internal/front-door.d.ts +5 -0
- package/dist/modules/world/internal/front-door.js +50 -0
- package/dist/modules/world/internal/leases.d.ts +33 -0
- package/dist/modules/world/internal/leases.js +79 -0
- package/dist/modules/world/internal/reset.d.ts +6 -0
- package/dist/modules/world/internal/reset.js +24 -0
- package/dist/modules/world/internal/work.d.ts +11 -0
- package/dist/modules/world/internal/work.js +73 -0
- package/dist/modules/world/internal/worlds.d.ts +7 -0
- package/dist/modules/world/internal/worlds.js +48 -0
- package/dist/modules/world/service.d.ts +80 -0
- package/dist/modules/world/service.js +209 -0
- package/dist/modules/world/types.d.ts +47 -0
- package/dist/modules/world/types.js +1 -0
- package/package.json +46 -3
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { Clock, Effect } from "effect";
|
|
2
|
+
import { definite, NO_HASH, reason } from "./adopt.js";
|
|
3
|
+
/**
|
|
4
|
+
* The relayer's store owns its nonces. The moment `prepare` reserves one, a row is written for it (its nonce, no bytes yet), before
|
|
5
|
+
* anything that can fail. A failure after that (a simulation, a signature, a send the node refuses for good) turns the row into a fill
|
|
6
|
+
* row that keeps the same reservation: the alarm sends a zero-value transfer from the relayer to itself at that nonce, so the calls queued
|
|
7
|
+
* behind it are not stuck. The caller still gets the error. The nonce is released only once the node's count is past it.
|
|
8
|
+
*
|
|
9
|
+
* The call is read on the node first, so one that would revert never takes a nonce. Its signed bytes are stored before the send, so a
|
|
10
|
+
* crash cannot orphan a transaction the node may hold, and the alarm sends it if the node does not. While this call works on its row the
|
|
11
|
+
* alarm leaves the row alone. A call is at-least-once: a caller that got no answer should ask `status` before it relays again.
|
|
12
|
+
*/
|
|
13
|
+
export const relay = (parts, call) => Effect.gen(function* () {
|
|
14
|
+
const { live, store } = parts;
|
|
15
|
+
const { port, key } = live;
|
|
16
|
+
yield* port.read({ from: key.address, to: call.to, data: call.data });
|
|
17
|
+
const prepared = yield* port.prepare({ from: key.address, to: call.to, data: call.data });
|
|
18
|
+
const reservation = port.reservationOf(prepared);
|
|
19
|
+
if (reservation === undefined)
|
|
20
|
+
return yield* Effect.die(new Error("a prepared transaction has no reservation"));
|
|
21
|
+
const nonce = prepared.transaction.nonce;
|
|
22
|
+
const id = yield* Effect.sync(() => crypto.randomUUID());
|
|
23
|
+
const createdAt = yield* Clock.currentTimeMillis;
|
|
24
|
+
store.add({ id, nonce, state: "submitting", hash: NO_HASH, serialized: "0x", fromBlock: 0n, fill: false, note: "", createdAt });
|
|
25
|
+
live.held.set(id, { reservation });
|
|
26
|
+
live.inflight.add(id);
|
|
27
|
+
// An alarm is asked for now, with the row, before any more work that can fail or hang: a row that is open always has one coming.
|
|
28
|
+
yield* parts.arm;
|
|
29
|
+
const giveUp = (error) => Effect.gen(function* () {
|
|
30
|
+
store.toFill(id, reason(error));
|
|
31
|
+
live.held.set(id, { reservation });
|
|
32
|
+
return yield* Effect.fail(error);
|
|
33
|
+
});
|
|
34
|
+
const work = Effect.gen(function* () {
|
|
35
|
+
const signed = yield* port.simulate(prepared).pipe(Effect.andThen(port.sign(prepared, key.signer)), Effect.catch(giveUp));
|
|
36
|
+
store.bytes(id, signed.hash, signed.serialized);
|
|
37
|
+
live.held.set(id, { reservation, signed });
|
|
38
|
+
const failed = yield* port.submit(signed).pipe(Effect.map((submission) => { store.sent(id, submission.fromBlock); return undefined; }), Effect.catch((error) => Effect.succeed(error)));
|
|
39
|
+
if (failed !== undefined && definite(failed))
|
|
40
|
+
return yield* giveUp(failed);
|
|
41
|
+
return { id, hash: signed.hash, nonce, from: key.address };
|
|
42
|
+
});
|
|
43
|
+
return yield* work.pipe(Effect.ensuring(Effect.sync(() => { live.inflight.delete(id); }).pipe(Effect.andThen(parts.arm))));
|
|
44
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Hex } from "@orthograph/chain-evm/device";
|
|
2
|
+
import type { RelayerConfig } from "../types.ts";
|
|
3
|
+
/**
|
|
4
|
+
* `submitting` is written before the send, so a crash cannot orphan a transaction: the alarm finds out whether the node has it.
|
|
5
|
+
* `lost` is a submission whose nonce another call took: nothing can send it again, and it answers as `dropped`.
|
|
6
|
+
*/
|
|
7
|
+
export type Kept = "submitting" | "submitted" | "included" | "reverted" | "dropped" | "lost";
|
|
8
|
+
export interface Row {
|
|
9
|
+
readonly id: string;
|
|
10
|
+
readonly nonce: number;
|
|
11
|
+
readonly state: Kept;
|
|
12
|
+
readonly hash: Hex;
|
|
13
|
+
/** The signed bytes, or `0x` for a row that holds its nonce for a fill and has no transaction yet. */
|
|
14
|
+
readonly serialized: Hex;
|
|
15
|
+
readonly fromBlock: bigint;
|
|
16
|
+
/** The call could not be sent: this row holds its nonce, and its transaction is a zero-value transfer from the relayer to itself. */
|
|
17
|
+
readonly fill: boolean;
|
|
18
|
+
/** Why the last attempt to send this again failed, or empty. */
|
|
19
|
+
readonly note: string;
|
|
20
|
+
/** When the row was written, in epoch milliseconds on the Clock: how long it has been pending is read from this. */
|
|
21
|
+
readonly createdAt: number;
|
|
22
|
+
}
|
|
23
|
+
export declare const makeStore: (sql: SqlStorage) => {
|
|
24
|
+
config: () => RelayerConfig | undefined;
|
|
25
|
+
keep: (config: RelayerConfig) => void;
|
|
26
|
+
find: (id: string) => Row | undefined;
|
|
27
|
+
/** The submissions that may still change, lowest nonce first. */
|
|
28
|
+
open: () => Row[];
|
|
29
|
+
add: (row: Row) => void;
|
|
30
|
+
setState: (id: string, state: Kept) => void;
|
|
31
|
+
/** The node accepted it: it is `submitted`, from this block. */
|
|
32
|
+
sent: (id: string, fromBlock: bigint) => void;
|
|
33
|
+
/** The call was signed: its bytes join the row that has held its nonce since `prepare`. */
|
|
34
|
+
bytes: (id: string, hash: Hex, serialized: Hex) => void;
|
|
35
|
+
/** The call can no longer be sent: the row keeps its nonce, without bytes, for the alarm to fill. */
|
|
36
|
+
toFill: (id: string, note: string) => void;
|
|
37
|
+
/** The fill was signed and sent (or may have been): it is the row's transaction now. */
|
|
38
|
+
filled: (id: string, hash: Hex, serialized: Hex, fromBlock: bigint) => void;
|
|
39
|
+
note: (id: string, note: string) => void;
|
|
40
|
+
};
|
|
41
|
+
export type Store = ReturnType<typeof makeStore>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const SCHEMA = [
|
|
2
|
+
"CREATE TABLE IF NOT EXISTS config (one INTEGER PRIMARY KEY CHECK (one = 1), json TEXT NOT NULL)",
|
|
3
|
+
`CREATE TABLE IF NOT EXISTS submissions (
|
|
4
|
+
id TEXT PRIMARY KEY, nonce INTEGER NOT NULL, state TEXT NOT NULL, hash TEXT NOT NULL, serialized TEXT NOT NULL,
|
|
5
|
+
from_block TEXT NOT NULL, fill INTEGER NOT NULL DEFAULT 0, note TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL DEFAULT 0)`,
|
|
6
|
+
"CREATE INDEX IF NOT EXISTS submissions_open ON submissions (state, nonce)",
|
|
7
|
+
];
|
|
8
|
+
const OPEN = "state IN ('submitting', 'submitted', 'dropped')";
|
|
9
|
+
/** A row that is `included`, `reverted` or `lost` cannot change back: every write that could reopen it is guarded by the store, not by the order of the callers. */
|
|
10
|
+
const LIVE = "state NOT IN ('included', 'reverted', 'lost')";
|
|
11
|
+
const rowOf = (raw) => ({
|
|
12
|
+
id: raw.id, nonce: raw.nonce, state: raw.state, hash: raw.hash, serialized: raw.serialized,
|
|
13
|
+
fromBlock: BigInt(raw.from_block), fill: raw.fill === 1, note: raw.note, createdAt: raw.created_at,
|
|
14
|
+
});
|
|
15
|
+
export const makeStore = (sql) => {
|
|
16
|
+
for (const statement of SCHEMA)
|
|
17
|
+
sql.exec(statement);
|
|
18
|
+
const all = (query, ...bindings) => sql.exec(query, ...bindings).toArray().map(rowOf);
|
|
19
|
+
return {
|
|
20
|
+
config: () => {
|
|
21
|
+
const kept = sql.exec("SELECT json FROM config").toArray()[0];
|
|
22
|
+
return kept === undefined ? undefined : JSON.parse(kept.json);
|
|
23
|
+
},
|
|
24
|
+
keep: (config) => { sql.exec("INSERT OR REPLACE INTO config (one, json) VALUES (1, ?)", JSON.stringify(config)); },
|
|
25
|
+
find: (id) => all("SELECT * FROM submissions WHERE id = ?", id)[0],
|
|
26
|
+
/** The submissions that may still change, lowest nonce first. */
|
|
27
|
+
open: () => all(`SELECT * FROM submissions WHERE ${OPEN} ORDER BY nonce`),
|
|
28
|
+
add: (row) => {
|
|
29
|
+
sql.exec("INSERT INTO submissions (id, nonce, state, hash, serialized, from_block, fill, note, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", row.id, row.nonce, row.state, row.hash, row.serialized, row.fromBlock.toString(), row.fill ? 1 : 0, row.note, row.createdAt);
|
|
30
|
+
},
|
|
31
|
+
setState: (id, state) => { sql.exec(`UPDATE submissions SET state = ? WHERE id = ? AND ${LIVE}`, state, id); },
|
|
32
|
+
/** The node accepted it: it is `submitted`, from this block. */
|
|
33
|
+
sent: (id, fromBlock) => { sql.exec(`UPDATE submissions SET state = 'submitted', from_block = ?, note = '' WHERE id = ? AND ${LIVE}`, fromBlock.toString(), id); },
|
|
34
|
+
/** The call was signed: its bytes join the row that has held its nonce since `prepare`. */
|
|
35
|
+
bytes: (id, hash, serialized) => { sql.exec(`UPDATE submissions SET hash = ?, serialized = ? WHERE id = ? AND ${LIVE}`, hash, serialized, id); },
|
|
36
|
+
/** The call can no longer be sent: the row keeps its nonce, without bytes, for the alarm to fill. */
|
|
37
|
+
toFill: (id, note) => { sql.exec(`UPDATE submissions SET fill = 1, state = 'submitting', serialized = '0x', note = ? WHERE id = ? AND ${LIVE}`, note, id); },
|
|
38
|
+
/** The fill was signed and sent (or may have been): it is the row's transaction now. */
|
|
39
|
+
filled: (id, hash, serialized, fromBlock) => {
|
|
40
|
+
sql.exec(`UPDATE submissions SET state = 'submitted', fill = 1, hash = ?, serialized = ?, from_block = ?, note = '' WHERE id = ? AND ${LIVE}`, hash, serialized, fromBlock.toString(), id);
|
|
41
|
+
},
|
|
42
|
+
note: (id, note) => { sql.exec(`UPDATE submissions SET note = ? WHERE id = ? AND ${LIVE}`, note, id); },
|
|
43
|
+
};
|
|
44
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { DurableObject } from "cloudflare:workers";
|
|
2
|
+
import { type Hex } from "@orthograph/chain-evm/device";
|
|
3
|
+
import type { RelayerApi, RelayerConfig, RelayerEnv } from "./types.ts";
|
|
4
|
+
/**
|
|
5
|
+
* The relayer's Durable Object. Export it from the Worker's entry, bind it as `RELAYER`, bind the key as the secret `RELAYER_KEY`, and name
|
|
6
|
+
* each instance by its chain's CAIP-2 id (`env.RELAYER.getByName("eip155:8453")`): one relayer per key, so one per chain. It keeps its
|
|
7
|
+
* submissions in its own SQLite, and its alarm (every `pollIntervalMs` from `configure`, while any submission may still change) sends a
|
|
8
|
+
* dropped transaction again, byte for byte, the same work `reconcile` does on call. `health` names a nonce pending past its deadline.
|
|
9
|
+
*
|
|
10
|
+
* @experimental The bugs in #784 are open: read it before you rely on the relayer.
|
|
11
|
+
*/
|
|
12
|
+
export declare class Relayer extends DurableObject<RelayerEnv> implements RelayerApi {
|
|
13
|
+
private readonly store;
|
|
14
|
+
private readonly lock;
|
|
15
|
+
private readonly starting;
|
|
16
|
+
/** Every `relay` holds one permit while it works; `configure` takes them all, so a Live is only swapped when no call is using it. */
|
|
17
|
+
private readonly swap;
|
|
18
|
+
private live;
|
|
19
|
+
constructor(ctx: DurableObjectState, env: RelayerEnv);
|
|
20
|
+
/** Run an Effect for a caller across Durable Object RPC: a failure arrives as an Error whose message holds no secret. */
|
|
21
|
+
private run;
|
|
22
|
+
/** Ask for the next alarm one period from now, unless one is already set or nothing may still change. */
|
|
23
|
+
private readonly arm;
|
|
24
|
+
private setAlarmAfter;
|
|
25
|
+
/** The live parts, built on first use from the stored configuration and the key binding, and again after a restart. */
|
|
26
|
+
private readonly parts;
|
|
27
|
+
/**
|
|
28
|
+
* Configure under the reconcile lock and with every `relay` drained, so there is only ever one Live: a new one is built (and takes every open
|
|
29
|
+
* row's reservation back) only when nothing is working on the old one, and nothing is working on both. A relay that arrives meanwhile waits.
|
|
30
|
+
*/
|
|
31
|
+
configure(config: RelayerConfig): Promise<{
|
|
32
|
+
readonly address: Hex;
|
|
33
|
+
}>;
|
|
34
|
+
relay(call: {
|
|
35
|
+
readonly to: Hex;
|
|
36
|
+
readonly data: Hex;
|
|
37
|
+
}): Promise<{
|
|
38
|
+
id: string;
|
|
39
|
+
hash: `0x${string}`;
|
|
40
|
+
nonce: number;
|
|
41
|
+
from: `0x${string}`;
|
|
42
|
+
}>;
|
|
43
|
+
health(): Promise<import("./types.ts").RelayerHealth>;
|
|
44
|
+
/**
|
|
45
|
+
* Under the reconcile lock, around the read and any terminal write, so it cannot interleave with a rebroadcast of the same row. The lock order
|
|
46
|
+
* is `configure`: lock, then every swap permit; `relay`: one swap permit; `status`, `reconcile` and the alarm: the lock only. None waits on a
|
|
47
|
+
* lock it already holds, and `relay` never takes the lock.
|
|
48
|
+
*/
|
|
49
|
+
status(id: string): Promise<import("./types.ts").RelayStatus>;
|
|
50
|
+
reconcile(): Promise<{
|
|
51
|
+
replaced: never[];
|
|
52
|
+
rebroadcast: import("./types.ts").Rebroadcast[];
|
|
53
|
+
}>;
|
|
54
|
+
/** The Live is read after the lock is taken, so a `configure` that swapped it meanwhile is not worked around. */
|
|
55
|
+
private readonly reconciling;
|
|
56
|
+
/** The alarm does what `reconcile` does, and asks for the next one while anything may still change. */
|
|
57
|
+
alarm(): Promise<void>;
|
|
58
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { DurableObject } from "cloudflare:workers";
|
|
2
|
+
import { ChainFault } from "@orthograph/chain-evm/device";
|
|
3
|
+
import { TimersLive } from "@orthograph/language-effect/device";
|
|
4
|
+
import { Clock, Effect, Semaphore } from "effect";
|
|
5
|
+
import { reconcile, status } from "./internal/check.js";
|
|
6
|
+
import { describe, startLive } from "./internal/live.js";
|
|
7
|
+
import { health } from "./internal/health.js";
|
|
8
|
+
import { relay } from "./internal/relay.js";
|
|
9
|
+
import { makeStore } from "./internal/store.js";
|
|
10
|
+
const SWAP_PERMITS = 1_000_000;
|
|
11
|
+
const invalid = (message) => new ChainFault({ kind: "configuration", message });
|
|
12
|
+
/**
|
|
13
|
+
* The relayer's Durable Object. Export it from the Worker's entry, bind it as `RELAYER`, bind the key as the secret `RELAYER_KEY`, and name
|
|
14
|
+
* each instance by its chain's CAIP-2 id (`env.RELAYER.getByName("eip155:8453")`): one relayer per key, so one per chain. It keeps its
|
|
15
|
+
* submissions in its own SQLite, and its alarm (every `pollIntervalMs` from `configure`, while any submission may still change) sends a
|
|
16
|
+
* dropped transaction again, byte for byte, the same work `reconcile` does on call. `health` names a nonce pending past its deadline.
|
|
17
|
+
*
|
|
18
|
+
* @experimental The bugs in #784 are open: read it before you rely on the relayer.
|
|
19
|
+
*/
|
|
20
|
+
export class Relayer extends DurableObject {
|
|
21
|
+
store = makeStore(this.ctx.storage.sql);
|
|
22
|
+
lock = Semaphore.makeUnsafe(1);
|
|
23
|
+
starting = Semaphore.makeUnsafe(1);
|
|
24
|
+
/** Every `relay` holds one permit while it works; `configure` takes them all, so a Live is only swapped when no call is using it. */
|
|
25
|
+
swap = Semaphore.makeUnsafe(SWAP_PERMITS);
|
|
26
|
+
live;
|
|
27
|
+
constructor(ctx, env) {
|
|
28
|
+
super(ctx, env);
|
|
29
|
+
// Before any call is served, every open row takes back the reservation of its own nonce. A relayer that is not set up yet (no
|
|
30
|
+
// configuration, no key, a node that does not answer) starts on its first call instead, which waits for the same step; a failure to take
|
|
31
|
+
// a nonce back is a defect and is not caught here, so the Durable Object restarts rather than serve calls that could be handed a nonce
|
|
32
|
+
// a row holds.
|
|
33
|
+
// Then, whether or not that worked, an open row has an alarm coming: it is armed here if the last one is gone.
|
|
34
|
+
void ctx.blockConcurrencyWhile(() => this.store.config() === undefined
|
|
35
|
+
? Promise.resolve()
|
|
36
|
+
: Effect.runPromise((env.RELAYER_KEY ? this.parts.pipe(Effect.asVoid, Effect.catch(() => Effect.void)) : Effect.void).pipe(Effect.andThen(this.arm))));
|
|
37
|
+
}
|
|
38
|
+
/** Run an Effect for a caller across Durable Object RPC: a failure arrives as an Error whose message holds no secret. */
|
|
39
|
+
run(work) {
|
|
40
|
+
return Effect.runPromise(work.pipe(Effect.mapError((error) => new Error(describe(error)))));
|
|
41
|
+
}
|
|
42
|
+
/** Ask for the next alarm one period from now, unless one is already set or nothing may still change. */
|
|
43
|
+
arm = Effect.gen({ self: this }, function* () {
|
|
44
|
+
const period = this.store.config()?.pollIntervalMs;
|
|
45
|
+
if (period === undefined || this.store.open().length === 0)
|
|
46
|
+
return;
|
|
47
|
+
if ((yield* Effect.promise(() => this.ctx.storage.getAlarm())) !== null)
|
|
48
|
+
return;
|
|
49
|
+
yield* this.setAlarmAfter(period);
|
|
50
|
+
});
|
|
51
|
+
setAlarmAfter(period) {
|
|
52
|
+
return Clock.currentTimeMillis.pipe(Effect.flatMap((now) => Effect.promise(() => this.ctx.storage.setAlarm(now + period))));
|
|
53
|
+
}
|
|
54
|
+
/** The live parts, built on first use from the stored configuration and the key binding, and again after a restart. */
|
|
55
|
+
parts = Effect.gen({ self: this }, function* () {
|
|
56
|
+
const live = this.live ?? (yield* this.starting.withPermit(Effect.gen({ self: this }, function* () {
|
|
57
|
+
if (this.live !== undefined)
|
|
58
|
+
return this.live;
|
|
59
|
+
const config = this.store.config();
|
|
60
|
+
if (config === undefined)
|
|
61
|
+
return yield* invalid("this relayer is not configured: call configure first");
|
|
62
|
+
this.live = yield* startLive(config, this.env.RELAYER_KEY, this.store).pipe(Effect.provide(TimersLive));
|
|
63
|
+
return this.live;
|
|
64
|
+
})));
|
|
65
|
+
return { live, store: this.store, arm: this.arm };
|
|
66
|
+
});
|
|
67
|
+
/**
|
|
68
|
+
* Configure under the reconcile lock and with every `relay` drained, so there is only ever one Live: a new one is built (and takes every open
|
|
69
|
+
* row's reservation back) only when nothing is working on the old one, and nothing is working on both. A relay that arrives meanwhile waits.
|
|
70
|
+
*/
|
|
71
|
+
configure(config) {
|
|
72
|
+
return this.run(this.lock.withPermit(this.swap.withPermits(SWAP_PERMITS)(Effect.gen({ self: this }, function* () {
|
|
73
|
+
const kept = this.store.config();
|
|
74
|
+
if (!Number.isSafeInteger(config.chainId) || config.chainId <= 0)
|
|
75
|
+
return yield* invalid("chainId must be a positive integer");
|
|
76
|
+
if (config.pollIntervalMs !== undefined && (!Number.isSafeInteger(config.pollIntervalMs) || config.pollIntervalMs <= 0))
|
|
77
|
+
return yield* invalid("pollIntervalMs must be a positive integer");
|
|
78
|
+
if (config.stuckAfterMs !== undefined && (!Number.isSafeInteger(config.stuckAfterMs) || config.stuckAfterMs <= 0))
|
|
79
|
+
return yield* invalid("stuckAfterMs must be a positive integer");
|
|
80
|
+
if (kept !== undefined && kept.chainId !== config.chainId)
|
|
81
|
+
return yield* invalid(`this relayer is for chain ${kept.chainId}`);
|
|
82
|
+
if (kept?.pollIntervalMs !== config.pollIntervalMs)
|
|
83
|
+
yield* Effect.promise(() => this.ctx.storage.deleteAlarm());
|
|
84
|
+
const changed = kept?.rpcUrl !== config.rpcUrl || kept.pollIntervalMs !== config.pollIntervalMs;
|
|
85
|
+
if (changed || kept?.stuckAfterMs !== config.stuckAfterMs) {
|
|
86
|
+
this.store.keep({
|
|
87
|
+
rpcUrl: config.rpcUrl, chainId: config.chainId,
|
|
88
|
+
...(config.pollIntervalMs === undefined ? {} : { pollIntervalMs: config.pollIntervalMs }),
|
|
89
|
+
...(config.stuckAfterMs === undefined ? {} : { stuckAfterMs: config.stuckAfterMs }),
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
if (changed)
|
|
93
|
+
this.live = undefined;
|
|
94
|
+
// The alarm is asked for whether or not the new Live starts (the node may be down): an open row always has one coming. If it fails, `configure` fails.
|
|
95
|
+
const { live } = yield* this.parts.pipe(Effect.ensuring(this.arm));
|
|
96
|
+
return { address: live.key.address };
|
|
97
|
+
}))));
|
|
98
|
+
}
|
|
99
|
+
relay(call) {
|
|
100
|
+
return this.run(this.swap.withPermits(1)(this.parts.pipe(Effect.flatMap((parts) => relay(parts, call)))));
|
|
101
|
+
}
|
|
102
|
+
health() {
|
|
103
|
+
return this.run(Clock.currentTimeMillis.pipe(Effect.map((now) => health(this.store, now))));
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Under the reconcile lock, around the read and any terminal write, so it cannot interleave with a rebroadcast of the same row. The lock order
|
|
107
|
+
* is `configure`: lock, then every swap permit; `relay`: one swap permit; `status`, `reconcile` and the alarm: the lock only. None waits on a
|
|
108
|
+
* lock it already holds, and `relay` never takes the lock.
|
|
109
|
+
*/
|
|
110
|
+
status(id) {
|
|
111
|
+
return this.run(Effect.suspend(() => this.lock.withPermit(this.parts.pipe(Effect.flatMap((parts) => status(parts, id))))));
|
|
112
|
+
}
|
|
113
|
+
reconcile() {
|
|
114
|
+
return this.run(this.reconciling);
|
|
115
|
+
}
|
|
116
|
+
/** The Live is read after the lock is taken, so a `configure` that swapped it meanwhile is not worked around. */
|
|
117
|
+
reconciling = Effect.suspend(() => this.lock.withPermit(this.parts.pipe(Effect.flatMap(reconcile))));
|
|
118
|
+
/** The alarm does what `reconcile` does, and asks for the next one while anything may still change. */
|
|
119
|
+
alarm() {
|
|
120
|
+
return this.run(this.reconciling.pipe(Effect.ignore, Effect.andThen(Effect.suspend(() => this.store.config()?.pollIntervalMs === undefined || this.store.open().length === 0
|
|
121
|
+
? Effect.void
|
|
122
|
+
: this.setAlarmAfter(this.store.config()?.pollIntervalMs ?? 0)))));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { Hex } from "@orthograph/chain-evm/device";
|
|
2
|
+
/** What the Worker binds for it. The key is a secret binding: `0x` and 64 hex digits. It is never an argument, an answer, a log line or a stored byte. */
|
|
3
|
+
export interface RelayerEnv {
|
|
4
|
+
readonly RELAYER_KEY?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface RelayerConfig {
|
|
7
|
+
readonly rpcUrl: string;
|
|
8
|
+
readonly chainId: number;
|
|
9
|
+
/** The alarm's period. With none, the relayer sets no alarm and replaces only when `reconcile` is called. */
|
|
10
|
+
readonly pollIntervalMs?: number;
|
|
11
|
+
/** A submission still pending after this long is named by `health` (default ten minutes): without a fee bump, a transaction sent too cheap stays stuck. */
|
|
12
|
+
readonly stuckAfterMs?: number;
|
|
13
|
+
}
|
|
14
|
+
export interface Relayed {
|
|
15
|
+
readonly id: string;
|
|
16
|
+
readonly hash: Hex;
|
|
17
|
+
readonly nonce: number;
|
|
18
|
+
readonly from: Hex;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* `submitted`: the node holds it. `included`: mined, success. `reverted`: mined, failed. `dropped`: no receipt, the node no longer
|
|
22
|
+
* holds it and the nonce is unused (or another call took the nonce, which nothing can undo).
|
|
23
|
+
*/
|
|
24
|
+
export type RelayState = "submitted" | "included" | "reverted" | "dropped";
|
|
25
|
+
export interface RelayStatus {
|
|
26
|
+
readonly id: string;
|
|
27
|
+
readonly nonce: number;
|
|
28
|
+
/** The current transaction. */
|
|
29
|
+
readonly hash: Hex;
|
|
30
|
+
readonly state: RelayState;
|
|
31
|
+
/** The hashes it replaced, oldest first: always empty until fee-bump replacement exists (`design/later.md`). */
|
|
32
|
+
readonly replaces: ReadonlyArray<Hex>;
|
|
33
|
+
/** Why the last attempt to send it again failed (a fee cap reached, a node that refuses), when one did. */
|
|
34
|
+
readonly problem?: string;
|
|
35
|
+
}
|
|
36
|
+
export interface Replaced {
|
|
37
|
+
readonly id: string;
|
|
38
|
+
readonly nonce: number;
|
|
39
|
+
readonly oldHash: Hex;
|
|
40
|
+
readonly newHash: Hex;
|
|
41
|
+
}
|
|
42
|
+
/** A submission the node has been sent again, the same signed bytes (its hash does not change). */
|
|
43
|
+
export interface Rebroadcast {
|
|
44
|
+
readonly id: string;
|
|
45
|
+
readonly nonce: number;
|
|
46
|
+
readonly hash: Hex;
|
|
47
|
+
}
|
|
48
|
+
/** A nonce pending past the deadline: named, with how long it has been pending, so a stuck transaction is seen and not silent. */
|
|
49
|
+
export interface Stuck {
|
|
50
|
+
readonly id: string;
|
|
51
|
+
readonly nonce: number;
|
|
52
|
+
readonly pendingMs: number;
|
|
53
|
+
}
|
|
54
|
+
export interface RelayerHealth {
|
|
55
|
+
readonly stuckAfterMs: number;
|
|
56
|
+
/** Lowest nonce first: everything behind the first one waits for it. */
|
|
57
|
+
readonly stuck: ReadonlyArray<Stuck>;
|
|
58
|
+
}
|
|
59
|
+
/** What the Worker calls on a relayer, over Durable Object RPC. */
|
|
60
|
+
export interface RelayerApi {
|
|
61
|
+
configure(config: RelayerConfig): Promise<{
|
|
62
|
+
readonly address: Hex;
|
|
63
|
+
}>;
|
|
64
|
+
relay(call: {
|
|
65
|
+
readonly to: Hex;
|
|
66
|
+
readonly data: Hex;
|
|
67
|
+
}): Promise<Relayed>;
|
|
68
|
+
status(id: string): Promise<RelayStatus>;
|
|
69
|
+
/** `replaced` is always empty: there is no fee-bump replacement yet (`design/later.md`). `rebroadcast` is what was sent again. */
|
|
70
|
+
reconcile(): Promise<{
|
|
71
|
+
readonly replaced: ReadonlyArray<Replaced>;
|
|
72
|
+
readonly rebroadcast: ReadonlyArray<Rebroadcast>;
|
|
73
|
+
}>;
|
|
74
|
+
health(): Promise<RelayerHealth>;
|
|
75
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { Thing } from "orthograph";
|
|
3
|
+
import type { Commit, Stored } from "@orthograph/language-effect";
|
|
4
|
+
export declare const actorFind: (actors: DurableObjectNamespace, thing: Thing, table: string, id: string) => Effect.Effect<Stored | undefined>;
|
|
5
|
+
/** An actor commit: every write is to one instance, because one actor owns one instance (D2 #38). */
|
|
6
|
+
export declare const actorCommit: (actors: DurableObjectNamespace, { writes, entries }: Commit, tableOf: (thing: Thing) => string) => Effect.Effect<import("@orthograph/language-effect").Committed, never, never>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// The Worker's side of an actor: name it from the thing's table and the instance id, then find or commit over RPC.
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { decodeRow, encodeFields } from "./rows.js";
|
|
4
|
+
const stubOf = (actors, table, id) => actors.get(actors.idFromName(`${table}:${id}`));
|
|
5
|
+
export const actorFind = (actors, thing, table, id) => Effect.gen(function* () {
|
|
6
|
+
const found = yield* Effect.promise(() => stubOf(actors, table, id).find());
|
|
7
|
+
if (!found)
|
|
8
|
+
return undefined;
|
|
9
|
+
const { instance } = yield* decodeRow(thing, { ...found.row, ...(found.state !== null ? { state: found.state } : {}) });
|
|
10
|
+
return { instance, version: found.version };
|
|
11
|
+
});
|
|
12
|
+
/** An actor commit: every write is to one instance, because one actor owns one instance (D2 #38). */
|
|
13
|
+
export const actorCommit = (actors, { writes, entries }, tableOf) => Effect.gen(function* () {
|
|
14
|
+
const ids = new Set(writes.map((w) => (w.kind === "insert" ? String(w.fields["id"]) : w.id)));
|
|
15
|
+
if (ids.size !== 1)
|
|
16
|
+
return yield* Effect.die(new Error("an actor commit writes exactly one instance"));
|
|
17
|
+
const first = writes[0];
|
|
18
|
+
const id = [...ids][0];
|
|
19
|
+
const wire = yield* Effect.forEach(writes, (w) => w.kind === "insert"
|
|
20
|
+
? Effect.map(encodeFields(w.thing, w.fields, false), (row) => ({ kind: "insert", row, state: w.state ?? null }))
|
|
21
|
+
: Effect.map(encodeFields(w.thing, w.changes, true), (changes) => ({ kind: "update", version: w.version, changes, state: w.state ?? null })));
|
|
22
|
+
const journal = entries.map((e) => ({ ...e, fields: JSON.stringify(e.fields) }));
|
|
23
|
+
return yield* Effect.promise(() => stubOf(actors, tableOf(first.thing), id).commit(wire, journal));
|
|
24
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { SqlClient } from "effect/sql";
|
|
3
|
+
import type { D1Client } from "@effect/sql-d1";
|
|
4
|
+
import type { Commit, NamedRule, Write } from "@orthograph/language-effect";
|
|
5
|
+
/** A database a store lives in: its SQL client and its D1 client, from one binding. */
|
|
6
|
+
export interface Db {
|
|
7
|
+
readonly sql: SqlClient.SqlClient;
|
|
8
|
+
readonly d1: D1Client.D1Client;
|
|
9
|
+
}
|
|
10
|
+
export declare const commitD1: ({ sql, d1 }: Db, tableOf: (thing: Write["thing"]) => string, { writes, entries, request, lists, reads }: Commit, rules?: ReadonlyArray<NamedRule>) => Effect.Effect<"committed" | "conflict", never, never>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// One commit to one database: the call's inserts, its guarded updates, its journal entries and its request key, as one D1 batch. A guard that lost, or a unique index that refused (G5), is a `conflict`: the call runs again.
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { encodeFields, lostGuard } from "./rows.js";
|
|
4
|
+
import { filtersOf } from "./list.js";
|
|
5
|
+
import { lostUnique } from "./unique.js";
|
|
6
|
+
/** #1045: how many read rows one guard statement holds, two bound values each, under D1's 100. */
|
|
7
|
+
const READS_PER_STATEMENT = 40;
|
|
8
|
+
export const commitD1 = ({ sql, d1 }, tableOf, { writes, entries, request, lists = [], reads = [] }, rules = []) => {
|
|
9
|
+
/**
|
|
10
|
+
* #764: a list's rows count as read. Before the call's own writes, the rows matching the list's `where` and `state` must still be the ones it read, at
|
|
11
|
+
* the same versions (their `id:version`, sorted by id). When they moved, a row of the table gets a NULL version, as a lost update guard does, and the
|
|
12
|
+
* batch fails as a `conflict`. A table with no rows has nothing that moved: rows are never deleted.
|
|
13
|
+
*/
|
|
14
|
+
const guardOf = ({ thing, where, state, rows }) => Effect.gen(function* () {
|
|
15
|
+
const table = sql(tableOf(thing));
|
|
16
|
+
const conditions = yield* filtersOf(sql, { thing, where, state });
|
|
17
|
+
const filter = conditions.length > 0 ? sql ` WHERE ${sql.and(conditions)}` : sql ``;
|
|
18
|
+
const read = [...rows].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)).map((r) => `${r.id}:${r.version}`).join(",");
|
|
19
|
+
const now = sql `COALESCE((SELECT group_concat("id" || ':' || "version", ',' ORDER BY "id") FROM ${table}${filter}), '')`;
|
|
20
|
+
return sql `UPDATE ${table} SET "version" = NULL WHERE rowid = (SELECT min(rowid) FROM ${table}) AND ${now} <> ${read}`;
|
|
21
|
+
});
|
|
22
|
+
/**
|
|
23
|
+
* #1045: so does each row the call found. Per table, a few rows a statement (D1 binds at most 100 values): a row whose version moved on gets a NULL
|
|
24
|
+
* version, and the batch fails as a `conflict` before any write. The store hands in only rows of this database's tables. A read row that is gone matches
|
|
25
|
+
* nothing here, where the in-memory store calls it a `conflict`: the two agree only because no write deletes a row.
|
|
26
|
+
*/
|
|
27
|
+
const readGuards = (reads) => {
|
|
28
|
+
const byTable = new Map();
|
|
29
|
+
for (const r of reads) {
|
|
30
|
+
const table = tableOf(r.thing);
|
|
31
|
+
(byTable.get(table) ?? byTable.set(table, []).get(table)).push(r);
|
|
32
|
+
}
|
|
33
|
+
return [...byTable].flatMap(([name, rows]) => Array.from({ length: Math.ceil(rows.length / READS_PER_STATEMENT) }, (_, i) => rows.slice(i * READS_PER_STATEMENT, (i + 1) * READS_PER_STATEMENT)).map((chunk) => sql `UPDATE ${sql(name)} SET "version" = NULL WHERE ${sql.or(chunk.map(({ id, version }) => sql `("id" = ${id} AND "version" <> ${version})`))}`));
|
|
34
|
+
};
|
|
35
|
+
const statementOf = (w) => Effect.gen(function* () {
|
|
36
|
+
const table = sql(tableOf(w.thing));
|
|
37
|
+
if (w.kind === "insert") {
|
|
38
|
+
const row = yield* encodeFields(w.thing, w.fields, false);
|
|
39
|
+
return sql `INSERT INTO ${table} ${sql.insert({ ...row, ...(w.state ? { state: w.state } : {}), version: 0 })}`;
|
|
40
|
+
}
|
|
41
|
+
const row = { ...(yield* encodeFields(w.thing, w.changes, true)), ...(w.state ? { state: w.state } : {}) };
|
|
42
|
+
// The guard: a stale version becomes NULL on a NOT NULL column, which fails the whole batch (D2 #36).
|
|
43
|
+
const guard = sql `"version" = CASE WHEN "version" = ${w.version} THEN "version" + 1 ELSE NULL END`;
|
|
44
|
+
return Object.keys(row).length > 0
|
|
45
|
+
? sql `UPDATE ${table} SET ${sql.update(row)}, ${guard} WHERE "id" = ${w.id}`
|
|
46
|
+
: sql `UPDATE ${table} SET ${guard} WHERE "id" = ${w.id}`;
|
|
47
|
+
});
|
|
48
|
+
const journalOf = (e) => sql `INSERT INTO "_journal" ${sql.insert({ trace: e.trace, operation: e.operation, move: e.move, subject: e.subject, event: e.event, fields: JSON.stringify(e.fields) })}`;
|
|
49
|
+
return Effect.gen(function* () {
|
|
50
|
+
const keep = request ? [sql `INSERT INTO "_requests" ${sql.insert({ key: request.key, answer: request.answer })}`] : [];
|
|
51
|
+
const changes = [...(yield* Effect.forEach(writes, statementOf)), ...entries.map(journalOf), ...keep];
|
|
52
|
+
if (changes.length === 0)
|
|
53
|
+
return "committed";
|
|
54
|
+
const statements = [...(yield* Effect.forEach(lists, guardOf)), ...readGuards(reads), ...changes];
|
|
55
|
+
return yield* d1.batch(statements).pipe(Effect.as("committed"), Effect.catch((e) => (lostGuard(e) || lostUnique(e, writes, tableOf, rules) ? Effect.succeed("conflict") : Effect.die(e))));
|
|
56
|
+
});
|
|
57
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { SqlClient } from "effect/sql";
|
|
3
|
+
import type { ListQuery, Page } from "@orthograph/language-effect";
|
|
4
|
+
/** The equality filters a list asks for, as columns: its known fields encoded, and its state. A key the thing has no field for is left out. */
|
|
5
|
+
export declare const filtersOf: (sql: SqlClient.SqlClient, { thing, where, state }: Pick<ListQuery, "thing" | "where" | "state">) => Effect.Effect<import("effect/sql/Statement").Statement<import("effect/sql/SqlConnection").Row>[], never, never>;
|
|
6
|
+
/**
|
|
7
|
+
* One more row than the page is fetched, to know whether another page follows. The cursor is the last kept row's rowid:
|
|
8
|
+
* the next page starts after it, so rows made meanwhile never shift a page (unlike an offset). Each row's rowid is its place, and comes with its version.
|
|
9
|
+
*/
|
|
10
|
+
export declare const listRows: (sql: SqlClient.SqlClient, table: string, { thing, where, state, order, limit, after }: ListQuery) => Effect.Effect<Page>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// A page of a thing's rows: filtered by the fields it is asked for, in the order the rows were made (SQLite's rowid).
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { decodeRow, encodeFields } from "./rows.js";
|
|
4
|
+
/** The equality filters a list asks for, as columns: its known fields encoded, and its state. A key the thing has no field for is left out. */
|
|
5
|
+
export const filtersOf = (sql, { thing, where, state }) => Effect.map(encodeFields(thing, Object.fromEntries(Object.entries(where).filter(([k]) => k in thing.fields)), true), (encoded) => [
|
|
6
|
+
...Object.entries(encoded).map(([k, v]) => sql `${sql(k)} = ${v}`),
|
|
7
|
+
...(state !== undefined ? [sql `"state" = ${state}`] : []),
|
|
8
|
+
]);
|
|
9
|
+
/**
|
|
10
|
+
* One more row than the page is fetched, to know whether another page follows. The cursor is the last kept row's rowid:
|
|
11
|
+
* the next page starts after it, so rows made meanwhile never shift a page (unlike an offset). Each row's rowid is its place, and comes with its version.
|
|
12
|
+
*/
|
|
13
|
+
export const listRows = (sql, table, { thing, where, state, order, limit, after }) => Effect.gen(function* () {
|
|
14
|
+
const conditions = [
|
|
15
|
+
...(yield* filtersOf(sql, { thing, where, state })),
|
|
16
|
+
...(after !== undefined ? [order === "newest" ? sql `rowid < ${Number(after)}` : sql `rowid > ${Number(after)}`] : []),
|
|
17
|
+
];
|
|
18
|
+
const filter = conditions.length > 0 ? sql ` WHERE ${sql.and(conditions)}` : sql ``;
|
|
19
|
+
const direction = order === "newest" ? sql `DESC` : sql `ASC`;
|
|
20
|
+
const rows = (yield* sql `SELECT rowid AS "_cursor", * FROM ${sql(table)}${filter} ORDER BY rowid ${direction} LIMIT ${limit + 1}`.pipe(Effect.orDie));
|
|
21
|
+
const kept = rows.slice(0, limit);
|
|
22
|
+
const decoded = yield* Effect.forEach(kept, (row) => decodeRow(thing, row));
|
|
23
|
+
return {
|
|
24
|
+
items: decoded.map((r) => r.instance),
|
|
25
|
+
rows: decoded.map((r, i) => ({ version: r.version, place: Number(kept[i]["_cursor"]) })),
|
|
26
|
+
next: rows.length > limit ? String(kept[kept.length - 1]["_cursor"]) : null,
|
|
27
|
+
};
|
|
28
|
+
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { Thing } from "orthograph";
|
|
3
|
+
import type { Instance } from "@orthograph/language-effect";
|
|
4
|
+
/** A stored row back to an instance: its fields decoded, its state kept. */
|
|
5
|
+
export declare const decodeRow: (thing: Thing, row: Record<string, unknown>) => Effect.Effect<{
|
|
6
|
+
instance: Instance;
|
|
7
|
+
version: number;
|
|
8
|
+
}, never, never>;
|
|
9
|
+
/** Some fields of an instance, encoded: all of them for an insert, the changed ones for an update. */
|
|
10
|
+
export declare const encodeFields: (thing: Thing, fields: Instance, partial: boolean) => Effect.Effect<{
|
|
11
|
+
[k: string]: {} | null | undefined;
|
|
12
|
+
}, never, never>;
|
|
13
|
+
/** Did this failure come from a version guard that lost? (`version` set to NULL on a `NOT NULL` column.) */
|
|
14
|
+
export declare const lostGuard: (error: unknown) => boolean;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// A thing's rows in their wire form: every field as its schema encodes it (text for ids and amounts).
|
|
2
|
+
import { Effect, Schema } from "effect";
|
|
3
|
+
import { fromColumns, structOf, toColumn } from "orthograph/server";
|
|
4
|
+
const codecOf = (thing, keys) => structOf(keys ? Object.fromEntries(keys.map((k) => [k, thing.fields[k]])) : thing.fields);
|
|
5
|
+
// How each column holds its field (STO-23) is shared with prove's world reader: `toColumn` and `fromColumns` in `orthograph/server`.
|
|
6
|
+
/** A stored row back to an instance: its fields decoded, its state kept. */
|
|
7
|
+
export const decodeRow = (thing, row) => Effect.gen(function* () {
|
|
8
|
+
const fields = yield* Schema.decodeUnknownEffect(codecOf(thing))(fromColumns(thing, row));
|
|
9
|
+
const instance = (typeof row["state"] === "string" ? { ...fields, state: row["state"] } : fields);
|
|
10
|
+
return { instance, version: Number(row["version"] ?? 0) };
|
|
11
|
+
}).pipe(Effect.orDie);
|
|
12
|
+
/** Some fields of an instance, encoded: all of them for an insert, the changed ones for an update. */
|
|
13
|
+
export const encodeFields = (thing, fields, partial) => Effect.gen(function* () {
|
|
14
|
+
const keys = Object.keys(fields).filter((k) => k !== "state");
|
|
15
|
+
const values = Object.fromEntries(keys.map((k) => [k, fields[k]]));
|
|
16
|
+
const encoded = yield* Schema.encodeEffect(codecOf(thing, partial ? keys : undefined))(values);
|
|
17
|
+
return Object.fromEntries(Object.entries(encoded).map(([k, v]) => [k, toColumn(thing, k, v)]));
|
|
18
|
+
}).pipe(Effect.orDie);
|
|
19
|
+
/** Did this failure come from a version guard that lost? (`version` set to NULL on a `NOT NULL` column.) */
|
|
20
|
+
export const lostGuard = (error) => {
|
|
21
|
+
// D1's message sits a few causes down: SqlError, then its UnknownError, then D1's own Error.
|
|
22
|
+
for (let e = error, depth = 0; e !== undefined && e !== null && depth < 8; e = e.cause, depth++) {
|
|
23
|
+
const message = String(e.message ?? e);
|
|
24
|
+
// A stale version, or another call that committed the same request key first: either way, run the call again.
|
|
25
|
+
if (/NOT NULL constraint failed: [\w"]+\.version\b/.test(message) || /UNIQUE constraint failed: _requests\.key/.test(message))
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
return false;
|
|
29
|
+
};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { NamedRule, Write } from "@orthograph/language-effect";
|
|
2
|
+
/** Did this failure come from the unique index of a rule over one of these writes' things? */
|
|
3
|
+
export declare const lostUnique: (error: unknown, writes: ReadonlyArray<Write>, tableOf: (thing: Write["thing"]) => string, rules?: ReadonlyArray<NamedRule>) => boolean;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** The columns a thing's rules are over: each declared rule's key (from the model's invariants). */
|
|
2
|
+
const columnsOf = (thing, table, rules) => [
|
|
3
|
+
...rules.filter(({ rule }) => rule.fields[0].of === thing).flatMap(({ rule }) => rule.fields.map((f) => f.key)),
|
|
4
|
+
].map((field) => `${table}.${field}`);
|
|
5
|
+
/** Did this failure come from the unique index of a rule over one of these writes' things? */
|
|
6
|
+
export const lostUnique = (error, writes, tableOf, rules = []) => {
|
|
7
|
+
const columns = new Set(writes.flatMap((w) => columnsOf(w.thing, tableOf(w.thing), rules)));
|
|
8
|
+
if (columns.size === 0)
|
|
9
|
+
return false;
|
|
10
|
+
for (let e = error, depth = 0; e !== undefined && e !== null && depth < 8; e = e.cause, depth++) {
|
|
11
|
+
const message = String(e.message ?? e);
|
|
12
|
+
const failed = /UNIQUE constraint failed: ([^:]+)/.exec(message)?.[1];
|
|
13
|
+
if (failed && failed.split(",").some((c) => columns.has(c.trim().replaceAll('"', ""))))
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
return false;
|
|
17
|
+
};
|