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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +2 -2
  3. package/dist/index.d.ts +21 -0
  4. package/dist/index.js +12 -0
  5. package/dist/modules/actors/internal/tables.d.ts +1 -0
  6. package/dist/modules/actors/internal/tables.js +5 -0
  7. package/dist/modules/actors/service.d.ts +18 -0
  8. package/dist/modules/actors/service.js +51 -0
  9. package/dist/modules/actors/types.d.ts +35 -0
  10. package/dist/modules/actors/types.js +1 -0
  11. package/dist/modules/auth/internal/instance.d.ts +4462 -0
  12. package/dist/modules/auth/internal/instance.js +36 -0
  13. package/dist/modules/auth/internal/oauth.d.ts +20 -0
  14. package/dist/modules/auth/internal/oauth.js +70 -0
  15. package/dist/modules/auth/internal/options.d.ts +4886 -0
  16. package/dist/modules/auth/internal/options.js +75 -0
  17. package/dist/modules/auth/internal/schema.d.ts +2 -0
  18. package/dist/modules/auth/internal/schema.js +41 -0
  19. package/dist/modules/auth/internal/world-token.d.ts +15 -0
  20. package/dist/modules/auth/internal/world-token.js +40 -0
  21. package/dist/modules/auth/service.d.ts +9 -0
  22. package/dist/modules/auth/service.js +96 -0
  23. package/dist/modules/auth/types.d.ts +75 -0
  24. package/dist/modules/auth/types.js +1 -0
  25. package/dist/modules/clock/internal/date.d.ts +17 -0
  26. package/dist/modules/clock/internal/date.js +45 -0
  27. package/dist/modules/clock/internal/door.d.ts +2 -0
  28. package/dist/modules/clock/internal/door.js +49 -0
  29. package/dist/modules/clock/internal/state.d.ts +5 -0
  30. package/dist/modules/clock/internal/state.js +78 -0
  31. package/dist/modules/clock/service.d.ts +2 -0
  32. package/dist/modules/clock/service.js +36 -0
  33. package/dist/modules/clock/types.d.ts +152 -0
  34. package/dist/modules/clock/types.js +1 -0
  35. package/dist/modules/database/service.d.ts +2 -0
  36. package/dist/modules/database/service.js +6 -0
  37. package/dist/modules/database/types.d.ts +7 -0
  38. package/dist/modules/database/types.js +1 -0
  39. package/dist/modules/follower/internal/entries.d.ts +9 -0
  40. package/dist/modules/follower/internal/entries.js +20 -0
  41. package/dist/modules/follower/internal/health.d.ts +18 -0
  42. package/dist/modules/follower/internal/health.js +27 -0
  43. package/dist/modules/follower/internal/outbox.d.ts +26 -0
  44. package/dist/modules/follower/internal/outbox.js +35 -0
  45. package/dist/modules/follower/internal/poll.d.ts +21 -0
  46. package/dist/modules/follower/internal/poll.js +23 -0
  47. package/dist/modules/follower/service.d.ts +31 -0
  48. package/dist/modules/follower/service.js +87 -0
  49. package/dist/modules/follower/types.d.ts +71 -0
  50. package/dist/modules/follower/types.js +4 -0
  51. package/dist/modules/inbound/internal/accept.d.ts +26 -0
  52. package/dist/modules/inbound/internal/accept.js +10 -0
  53. package/dist/modules/inbound/internal/read.d.ts +10 -0
  54. package/dist/modules/inbound/internal/read.js +26 -0
  55. package/dist/modules/inbound/internal/same.d.ts +1 -0
  56. package/dist/modules/inbound/internal/same.js +12 -0
  57. package/dist/modules/inbound/internal/verify.d.ts +6 -0
  58. package/dist/modules/inbound/internal/verify.js +57 -0
  59. package/dist/modules/inbound/service.d.ts +2 -0
  60. package/dist/modules/inbound/service.js +110 -0
  61. package/dist/modules/inbound/types.d.ts +28 -0
  62. package/dist/modules/inbound/types.js +1 -0
  63. package/dist/modules/journal/service.d.ts +2 -0
  64. package/dist/modules/journal/service.js +23 -0
  65. package/dist/modules/journal/types.d.ts +8 -0
  66. package/dist/modules/journal/types.js +1 -0
  67. package/dist/modules/relayer/internal/adopt.d.ts +19 -0
  68. package/dist/modules/relayer/internal/adopt.js +34 -0
  69. package/dist/modules/relayer/internal/check.d.ts +16 -0
  70. package/dist/modules/relayer/internal/check.js +141 -0
  71. package/dist/modules/relayer/internal/health.d.ts +5 -0
  72. package/dist/modules/relayer/internal/health.js +7 -0
  73. package/dist/modules/relayer/internal/live.d.ts +26 -0
  74. package/dist/modules/relayer/internal/live.js +25 -0
  75. package/dist/modules/relayer/internal/relay.d.ts +22 -0
  76. package/dist/modules/relayer/internal/relay.js +44 -0
  77. package/dist/modules/relayer/internal/store.d.ts +41 -0
  78. package/dist/modules/relayer/internal/store.js +44 -0
  79. package/dist/modules/relayer/service.d.ts +58 -0
  80. package/dist/modules/relayer/service.js +124 -0
  81. package/dist/modules/relayer/types.d.ts +75 -0
  82. package/dist/modules/relayer/types.js +1 -0
  83. package/dist/modules/store/internal/actors.d.ts +6 -0
  84. package/dist/modules/store/internal/actors.js +24 -0
  85. package/dist/modules/store/internal/commit.d.ts +10 -0
  86. package/dist/modules/store/internal/commit.js +57 -0
  87. package/dist/modules/store/internal/list.d.ts +10 -0
  88. package/dist/modules/store/internal/list.js +28 -0
  89. package/dist/modules/store/internal/rows.d.ts +14 -0
  90. package/dist/modules/store/internal/rows.js +29 -0
  91. package/dist/modules/store/internal/unique.d.ts +3 -0
  92. package/dist/modules/store/internal/unique.js +17 -0
  93. package/dist/modules/store/service.d.ts +2 -0
  94. package/dist/modules/store/service.js +71 -0
  95. package/dist/modules/store/types.d.ts +36 -0
  96. package/dist/modules/store/types.js +1 -0
  97. package/dist/modules/telemetry/internal/exporters.d.ts +21 -0
  98. package/dist/modules/telemetry/internal/exporters.js +66 -0
  99. package/dist/modules/telemetry/service.d.ts +2 -0
  100. package/dist/modules/telemetry/service.js +52 -0
  101. package/dist/modules/telemetry/types.d.ts +36 -0
  102. package/dist/modules/telemetry/types.js +1 -0
  103. package/dist/modules/timers/internal/controller.d.ts +13 -0
  104. package/dist/modules/timers/internal/controller.js +63 -0
  105. package/dist/modules/timers/internal/count.d.ts +39 -0
  106. package/dist/modules/timers/internal/count.js +105 -0
  107. package/dist/modules/timers/internal/limits.d.ts +4 -0
  108. package/dist/modules/timers/internal/limits.js +8 -0
  109. package/dist/modules/timers/internal/table.d.ts +52 -0
  110. package/dist/modules/timers/internal/table.js +181 -0
  111. package/dist/modules/timers/service.d.ts +12 -0
  112. package/dist/modules/timers/service.js +136 -0
  113. package/dist/modules/timers/types.d.ts +82 -0
  114. package/dist/modules/timers/types.js +1 -0
  115. package/dist/modules/world/internal/entry.d.ts +34 -0
  116. package/dist/modules/world/internal/entry.js +69 -0
  117. package/dist/modules/world/internal/facts.d.ts +5 -0
  118. package/dist/modules/world/internal/facts.js +31 -0
  119. package/dist/modules/world/internal/fence.d.ts +9 -0
  120. package/dist/modules/world/internal/fence.js +90 -0
  121. package/dist/modules/world/internal/front-door.d.ts +5 -0
  122. package/dist/modules/world/internal/front-door.js +50 -0
  123. package/dist/modules/world/internal/leases.d.ts +33 -0
  124. package/dist/modules/world/internal/leases.js +79 -0
  125. package/dist/modules/world/internal/reset.d.ts +6 -0
  126. package/dist/modules/world/internal/reset.js +24 -0
  127. package/dist/modules/world/internal/work.d.ts +11 -0
  128. package/dist/modules/world/internal/work.js +73 -0
  129. package/dist/modules/world/internal/worlds.d.ts +7 -0
  130. package/dist/modules/world/internal/worlds.js +48 -0
  131. package/dist/modules/world/service.d.ts +80 -0
  132. package/dist/modules/world/service.js +209 -0
  133. package/dist/modules/world/types.d.ts +47 -0
  134. package/dist/modules/world/types.js +1 -0
  135. package/package.json +41 -3
@@ -0,0 +1,10 @@
1
+ import { Option } from "effect";
2
+ import type { AdapterDoor } from "orthograph";
3
+ /** The body as JSON, or nothing when it is not JSON. */
4
+ export declare const jsonOf: (raw: string) => Option.Option<unknown>;
5
+ /** `issue_comment` is `issueComment`; a name with no underscore is its own. */
6
+ export declare const camel: (written: string) => string;
7
+ /** Where the door's rule says the event's name is: a header, or a path into the body. Undefined where it is not there. */
8
+ export declare const eventNameOf: (rule: AdapterDoor["event"], headers: Headers, body: unknown) => string | undefined;
9
+ /** The answer to a handshake: the body's own `answer`, when its `field` is `is`. */
10
+ export declare const challengeOf: (rule: AdapterDoor["challenge"], body: unknown) => string | undefined;
@@ -0,0 +1,26 @@
1
+ // What a verified delivery says: its body as JSON, its event's name (the sender writes `issue_comment`, the adapter says `issueComment`),
2
+ // and whether it is the handshake a sender sends to see the door answer.
3
+ import { Option, Schema } from "effect";
4
+ const parseJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
5
+ const asRecord = (x) => (typeof x === "object" && x !== null && !Array.isArray(x) ? x : undefined);
6
+ /** The body as JSON, or nothing when it is not JSON. */
7
+ export const jsonOf = (raw) => parseJson(raw);
8
+ /** `issue_comment` is `issueComment`; a name with no underscore is its own. */
9
+ export const camel = (written) => written.replace(/_([a-z0-9])/g, (_m, c) => c.toUpperCase());
10
+ /** Where the door's rule says the event's name is: a header, or a path into the body. Undefined where it is not there. */
11
+ export const eventNameOf = (rule, headers, body) => {
12
+ if ("header" in rule) {
13
+ const given = headers.get(rule.header);
14
+ return given === null || given === "" ? undefined : camel(given);
15
+ }
16
+ const found = rule.path.reduce((at, key) => asRecord(at)?.[key], body);
17
+ return typeof found === "string" && found !== "" ? camel(found) : undefined;
18
+ };
19
+ /** The answer to a handshake: the body's own `answer`, when its `field` is `is`. */
20
+ export const challengeOf = (rule, body) => {
21
+ const given = asRecord(body);
22
+ if (rule === undefined || given === undefined || given[rule.field] !== rule.is)
23
+ return undefined;
24
+ const answer = given[rule.answer];
25
+ return typeof answer === "string" ? answer : undefined;
26
+ };
@@ -0,0 +1 @@
1
+ export declare const sameValue: (a: unknown, b: unknown) => boolean;
@@ -0,0 +1,12 @@
1
+ // Whether two copies of an event's object say the same (GOAL17-repeat-mismatch): compared as values, whatever their key order, and a key
2
+ // that is absent is the same as one that is `undefined`, as JSON has it.
3
+ const isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
4
+ export const sameValue = (a, b) => {
5
+ if (Array.isArray(a) || Array.isArray(b))
6
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => sameValue(x, b[i]));
7
+ if (isRecord(a) && isRecord(b)) {
8
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
9
+ return [...keys].every((k) => sameValue(a[k], b[k]));
10
+ }
11
+ return Object.is(a, b);
12
+ };
@@ -0,0 +1,6 @@
1
+ import { Effect } from "effect";
2
+ import type { AdapterDoor } from "orthograph";
3
+ type Rule = AdapterDoor["verify"];
4
+ /** True only when every part is there and the signature is the sender's: a missing secret, header, prefix, stale time or wrong digest is false. */
5
+ export declare const verified: (rule: Rule, secret: string | undefined, headers: Headers, body: Uint8Array) => Effect.Effect<boolean>;
6
+ export {};
@@ -0,0 +1,57 @@
1
+ // Whether a delivery is signed as its sender signs: HMAC-SHA256 over the raw bytes (GitHub), or over `<version>:<timestamp>:<bytes>`
2
+ // with a timestamp inside a window (Slack's v0); or RSA PKCS#1 v1.5 under a public key over SHA256("<t>.<bytes>") (Bridge's
3
+ // `t=<ms>,v0=<base64>`, G16-adapter-mounts call 2). The comparison is the platform's constant-time `verify`, never `===`.
4
+ import { Clock, Effect } from "effect";
5
+ const text = new TextEncoder();
6
+ const HEX = /^[0-9a-f]{64}$/i;
7
+ const bytesOf = (hex) => Uint8Array.from(hex.match(/../g) ?? [], (pair) => parseInt(pair, 16));
8
+ const joined = (head, body) => {
9
+ const out = new Uint8Array(head.length + body.length);
10
+ out.set(head, 0);
11
+ out.set(body, head.length);
12
+ return out;
13
+ };
14
+ // Bridge's header exactly: `t` in milliseconds as written, then `v0` in strict, padded base64. Anything more or less is refused.
15
+ const BRIDGE = /^t=(\d{1,15}),v0=((?:[A-Za-z0-9+/]{4})+|(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=))$/;
16
+ const PEM = /^-----BEGIN PUBLIC KEY-----([A-Za-z0-9+/=\s]+)-----END PUBLIC KEY-----$/;
17
+ const decoded = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
18
+ /** Bridge's signature: the PEM's SPKI imported for RSASSA-PKCS1-v1_5, verifying SHA256("<t>.<body>") (which it hashes once more). */
19
+ const rsaVerified = (rule, pem, headers, body) => Effect.gen(function* () {
20
+ const parts = BRIDGE.exec(headers.get(rule.header) ?? "");
21
+ const key = PEM.exec(pem.trim());
22
+ if (parts === null || key === null)
23
+ return false;
24
+ const [, t = "", v0 = ""] = parts;
25
+ const now = yield* Clock.currentTimeMillis;
26
+ // Written as "not inside", so a window that is not a number refuses rather than turning itself off.
27
+ if (!(Math.abs(now - Number(t)) <= rule.within * 1000))
28
+ return false;
29
+ const publicKey = yield* Effect.tryPromise(() => crypto.subtle.importKey("spki", decoded((key[1] ?? "").replace(/\s+/g, "")), { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]));
30
+ const digest = yield* Effect.promise(() => crypto.subtle.digest("SHA-256", joined(text.encode(`${t}.`), body)));
31
+ return yield* Effect.tryPromise(() => crypto.subtle.verify("RSASSA-PKCS1-v1_5", publicKey, decoded(v0), digest));
32
+ }).pipe(Effect.orElseSucceed(() => false));
33
+ const hmacVerified = (rule, secret, headers, body) => Effect.gen(function* () {
34
+ const given = headers.get(rule.header);
35
+ if (given === null || !given.startsWith(rule.prefix))
36
+ return false;
37
+ const digest = given.slice(rule.prefix.length);
38
+ if (!HEX.test(digest))
39
+ return false;
40
+ let signed = joined(new Uint8Array(0), body);
41
+ if (rule.signs !== "body") {
42
+ const stamp = rule.timestamp === undefined ? null : headers.get(rule.timestamp.header);
43
+ if (rule.timestamp === undefined || stamp === null || !/^\d{1,12}$/.test(stamp))
44
+ return false;
45
+ const now = yield* Clock.currentTimeMillis;
46
+ if (Math.abs(now / 1000 - Number(stamp)) > rule.timestamp.within)
47
+ return false;
48
+ signed = joined(text.encode(`${rule.signs.version}:${stamp}:`), body);
49
+ }
50
+ return yield* Effect.promise(() => crypto.subtle.importKey("raw", text.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]).then((key) => crypto.subtle.verify("HMAC", key, bytesOf(digest), signed)));
51
+ });
52
+ /** True only when every part is there and the signature is the sender's: a missing secret, header, prefix, stale time or wrong digest is false. */
53
+ export const verified = (rule, secret, headers, body) => {
54
+ if (secret === undefined || secret === "")
55
+ return Effect.succeed(false);
56
+ return "scheme" in rule ? rsaVerified(rule, secret, headers, body) : hmacVerified(rule, secret, headers, body);
57
+ };
@@ -0,0 +1,2 @@
1
+ import type { InboundApi } from "./types.ts";
2
+ export declare const Inbound: InboundApi;
@@ -0,0 +1,110 @@
1
+ import { Effect, Option, Schema } from "effect";
2
+ import { accept } from "./internal/accept.js";
3
+ import { sameValue } from "./internal/same.js";
4
+ import { camel, challengeOf, eventNameOf, jsonOf } from "./internal/read.js";
5
+ import { verified } from "./internal/verify.js";
6
+ const PREFIX = "/_in/";
7
+ const TRACEPARENT = /^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/;
8
+ const json = (body, status = 200, headers) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } });
9
+ /** The delivery's trace: the caller's, which the Worker's telemetry has already put on the request. */
10
+ const traceOf = (request) => request.headers.get("traceparent")?.match(TRACEPARENT)?.[1] ?? crypto.randomUUID().replaceAll("-", "");
11
+ /** A span named for the outcome, so a journey reads `in.<mount>.accepted`, `.seen`, `.refused` or `.ignored` (M5-checks call 4). */
12
+ const outcome = (mount, name) => Effect.void.pipe(Effect.withSpan(`in.${mount}.${name}`));
13
+ /**
14
+ * The door runs before any connection's configuration is known, so a mapping sees a context that notes every read of its configuration or `me`
15
+ * (and answers it with nothing a real account has). A mapping that decides by the event alone is believed; an `undefined` from one that read the
16
+ * context is not, and the delivery is taken, so a context the door made up never drops a real event. The hop to `trigger.receive` maps it again
17
+ * with the connection's own.
18
+ */
19
+ const doorContext = () => {
20
+ const seen = { read: false };
21
+ const part = () => new Proxy({}, { get: () => { seen.read = true; return undefined; } });
22
+ return { seen, ctx: { config: part(), me: part() } };
23
+ };
24
+ /** Whether any active source of the mount takes this delivery: a mapping that makes a trigger, or one that closes a thread. A mapping that fails takes it, so a defect never loses an event. */
25
+ const taken = (door, name, payload) => door.sources.length === 0
26
+ ? Effect.succeed(true)
27
+ : Effect.forEach(door.sources, (kind) => {
28
+ const spec = kind.spec;
29
+ const { seen, ctx } = doorContext();
30
+ return Effect.try({
31
+ try: () => spec?.on?.[name]?.(payload, ctx) !== undefined || seen.read || spec?.closed?.[name]?.(payload) !== undefined,
32
+ catch: () => true,
33
+ }).pipe(Effect.catch(() => Effect.succeed(true)));
34
+ }).pipe(Effect.map((each) => each.some(Boolean)));
35
+ /** The body as the event's schema judges it: without the parts that only say who delivered it. */
36
+ const judged = (body, envelope) => envelope === undefined || typeof body !== "object" || body === null ? body : Object.fromEntries(Object.entries(body).filter(([k]) => !envelope.includes(k)));
37
+ /**
38
+ * A repeat whose object says something other than the kept row's is still `seen` and writes nothing, but never silently (M5-reach-out Q2.2,
39
+ * GOAL17-repeat-mismatch): a span `in.mismatch` that ends as an error, with its `defect` naming the mount and the event's id, never the payload.
40
+ */
41
+ const mismatch = (mount, id) => {
42
+ const defect = `in.${mount}: a repeat of ${id} says something other than the kept event; the kept one stands`;
43
+ return Effect.fail(new Error(defect)).pipe(Effect.withSpan("in.mismatch", { attributes: { defect, "error.tag": "RepeatMismatch", "event.id": id } }), Effect.catch(() => Effect.void));
44
+ };
45
+ /** The object each payload names, by its own event's adapter (a Slack message kept as `message` and repeated as `appMention`), or undefined when it names none. */
46
+ const objectOf = (door, name, payload) => {
47
+ const event = door.adapter.events[name];
48
+ return event?.object === undefined ? undefined : Effect.runSync(Effect.try(() => event.object(payload)).pipe(Effect.orElseSucceed(() => undefined)));
49
+ };
50
+ const deliver = (door, options, request) => Effect.gen(function* () {
51
+ const rule = door.adapter.door;
52
+ if (rule === undefined)
53
+ return json({ error: "not found" }, 404);
54
+ const raw = new Uint8Array(yield* Effect.promise(() => request.arrayBuffer()));
55
+ const secret = options.secrets[door.secret];
56
+ if (!(yield* verified(rule.verify, typeof secret === "string" ? secret : undefined, request.headers, raw))) {
57
+ yield* outcome(door.mount, "refused");
58
+ return json({ _tag: "BadSignature" }, 401);
59
+ }
60
+ const body = jsonOf(new TextDecoder().decode(raw));
61
+ const parsed = Option.getOrUndefined(body);
62
+ const handshake = challengeOf(rule.challenge, parsed);
63
+ if (handshake !== undefined)
64
+ return json({ challenge: handshake });
65
+ const name = eventNameOf(rule.event, request.headers, parsed);
66
+ const event = name === undefined || !door.events.includes(name) ? undefined : door.adapter.events[name];
67
+ const decoded = event === undefined || name === undefined ? Option.none() : Schema.decodeUnknownOption(event.schema)(judged(parsed, rule.envelope));
68
+ // A type the mount leaves out, a type nobody knows, and an included event that does not decode are each acknowledged and written nowhere:
69
+ // a 4xx would have the sender retry for days (M5-reach-out Q2.2).
70
+ if (event === undefined || name === undefined || Option.isNone(decoded) || event.id === undefined) {
71
+ if (event !== undefined && name !== undefined)
72
+ yield* Effect.logWarning(`in.${door.mount}: ${name} does not decode, or its adapter names no identity for it`);
73
+ yield* outcome(door.mount, "ignored");
74
+ return json({ ignored: true });
75
+ }
76
+ if (!(yield* taken(door, name, decoded.value))) {
77
+ yield* outcome(door.mount, "ignored");
78
+ return json({ ignored: true });
79
+ }
80
+ // A payload the schema allows may still lack what the identity reads: that is a delivery to ignore with a warning, never a 500.
81
+ const named = yield* Effect.try({ try: () => ({ id: `${door.mount}:${event.id(decoded.value)}`, actor: event.actor?.(decoded.value) }), catch: (e) => e }).pipe(Effect.option);
82
+ if (Option.isNone(named)) {
83
+ yield* Effect.logWarning(`in.${door.mount}: ${name} has no identity to read in this payload`);
84
+ yield* outcome(door.mount, "ignored");
85
+ return json({ ignored: true });
86
+ }
87
+ const settled = yield* accept(options.db, { id: named.value.id, trace: traceOf(request), mount: door.mount, event: name, fields: parsed, actor: named.value.actor });
88
+ // A repeat is compared on the event's object, never the envelope; the kept row is left as it came.
89
+ if (settled.settled === "seen" && event.object !== undefined) {
90
+ const keptEvent = settled.kept === undefined ? undefined : door.adapter.events[camel(settled.kept.event)];
91
+ if (settled.kept === undefined)
92
+ yield* Effect.logWarning(`in.${door.mount}: the kept row of ${named.value.id} could not be read, so its repeat was not compared`);
93
+ else if (keptEvent?.object !== undefined && !sameValue(objectOf(door, camel(settled.kept.event), settled.kept.fields), objectOf(door, name, parsed)))
94
+ yield* mismatch(door.mount, named.value.id);
95
+ }
96
+ yield* outcome(door.mount, settled.settled);
97
+ return json(settled.settled === "accepted" ? { accepted: true } : { seen: true });
98
+ }).pipe(Effect.withSpan(`in.${door.mount}`));
99
+ export const Inbound = {
100
+ handle: (options, request, context) => {
101
+ const mount = new URL(request.url).pathname.slice(PREFIX.length).replace(/\/$/, "");
102
+ const door = options.doors.find((d) => d.mount === mount);
103
+ if (door === undefined)
104
+ return Promise.resolve(json({ error: "not found" }, 404));
105
+ if (request.method !== "POST")
106
+ return Promise.resolve(json({ error: "method not allowed" }, 405, { allow: "POST" }));
107
+ const run = deliver(door, options, request);
108
+ return Effect.runPromise(context === undefined ? run : Effect.provideContext(run, context));
109
+ },
110
+ };
@@ -0,0 +1,28 @@
1
+ import type { Context } from "effect";
2
+ import type { Adapter, SourceKind } from "orthograph";
3
+ /** One door: the mount it is for, the adapter that says how it verifies and reads, the events the mount includes, and the secret's name in the environment. */
4
+ export interface Door {
5
+ readonly mount: string;
6
+ readonly adapter: Adapter<any, any, any>;
7
+ readonly events: ReadonlyArray<string>;
8
+ /** The active sources that map this adapter's events: a delivery none of them takes (a comment deleted, an issue labeled) is acknowledged and ignored. None: every included event is taken. */
9
+ readonly sources: ReadonlyArray<SourceKind<any>>;
10
+ /** `<MOUNT>_WEBHOOK_SIGNING`: the binding that holds the signing secret. */
11
+ readonly secret: string;
12
+ }
13
+ export interface InboundOptions {
14
+ readonly doors: ReadonlyArray<Door>;
15
+ /** The default database: the inbox is its journal. */
16
+ readonly db: D1Database;
17
+ /** The Worker's bindings, from which each door's secret is read by name. */
18
+ readonly secrets: Readonly<Record<string, unknown>>;
19
+ }
20
+ export interface InboundApi {
21
+ /**
22
+ * One request to `/_in/<mount>`. 404 for a mount without a door, 405 for any method but POST, 401 `{ _tag: "BadSignature" }`
23
+ * for a signature that does not verify (nothing written), and otherwise 200 with `{ accepted: true }`, `{ seen: true }`
24
+ * or `{ ignored: true }` (or a handshake's answer). Each delivery is judged by the event's own identity, never the
25
+ * sender's delivery id; an accepted one is one row of the journal, in the request's trace.
26
+ */
27
+ readonly handle: (options: InboundOptions, request: Request, context?: Context.Context<never>) => Promise<Response>;
28
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { JournalD1Api } from "./types.ts";
2
+ export declare const JournalD1: JournalD1Api;
@@ -0,0 +1,23 @@
1
+ import { Effect, Layer } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+ import { Journal } from "@orthograph/language-effect";
4
+ const entryOf = (r) => ({ ...r, fields: JSON.parse(r.fields) });
5
+ export const JournalD1 = {
6
+ layer: Layer.effect(Journal, Effect.gen(function* () {
7
+ const sql = yield* SqlClient.SqlClient;
8
+ return Journal.of({
9
+ ofTrace: (trace) => sql `SELECT * FROM "_journal" WHERE "trace" = ${trace} ORDER BY "seq"`.pipe(Effect.map((rows) => rows.map(entryOf)), Effect.orDie),
10
+ });
11
+ })),
12
+ // Each declared store keeps its own `_journal`; a trace's entries are the default's, then each store's, each in its own order.
13
+ across: (stores) => Layer.effect(Journal, Effect.gen(function* () {
14
+ const sql = yield* SqlClient.SqlClient;
15
+ return Journal.of({
16
+ ofTrace: (trace) => Effect.gen(function* () {
17
+ const home = yield* sql `SELECT * FROM "_journal" WHERE "trace" = ${trace} ORDER BY "seq"`;
18
+ const apart = yield* Effect.forEach(stores, (db) => Effect.promise(() => db.prepare(`SELECT * FROM "_journal" WHERE "trace" = ? ORDER BY "seq"`).bind(trace).all()));
19
+ return [...home, ...apart.flatMap((a) => a.results)].map(entryOf);
20
+ }).pipe(Effect.orDie),
21
+ });
22
+ })),
23
+ };
@@ -0,0 +1,8 @@
1
+ import type { Layer } from "effect";
2
+ import type { SqlClient } from "effect/sql";
3
+ import type { Journal } from "@orthograph/language-effect";
4
+ export interface JournalD1Api {
5
+ readonly layer: Layer.Layer<Journal, never, SqlClient.SqlClient>;
6
+ /** The default database's journal and that of each declared database store (K3), which keeps its own. */
7
+ readonly across: (stores: ReadonlyArray<D1Database>) => Layer.Layer<Journal, never, SqlClient.SqlClient>;
8
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import { isDefinite } from "@orthograph/chain-evm/device";
2
+ import { Effect } from "effect";
3
+ import type { Live } from "./live.ts";
4
+ import type { Row, Store } from "./store.ts";
5
+ /** The hash a row holds while it has no transaction yet (a fill that is waiting to be sent). */
6
+ export declare const NO_HASH: `0x${string}`;
7
+ /** A row with no bytes: its nonce is held for a fill (its call was never signed, or could not be sent). */
8
+ export declare const unsent: (row: Row) => boolean;
9
+ /** Whether a failure ends its call for good. The port decides (`isDefinite`): the relayer does not classify errors itself. */
10
+ export declare const definite: typeof isDefinite;
11
+ /** What a failure says, for a row's note and for nothing else: no value that was given is in it. */
12
+ export declare const reason: (error: unknown) => string;
13
+ /**
14
+ * After a restart, before any call is served: every open row takes back the reservation of its own nonce, lowest first. A row with bytes
15
+ * is resumed from them; a row without bytes (a fill waiting) is held. Bytes that can no longer be read turn the row into a fill, since
16
+ * that nonce may be unused on the chain. Nothing else is swallowed: a nonce another reservation already holds means the relayer's two
17
+ * records disagree, and that is a defect to surface.
18
+ */
19
+ export declare const register: (live: Live, store: Store) => Effect.Effect<undefined, never, never>;
@@ -0,0 +1,34 @@
1
+ // What the relayer's store owns: every open row holds its own nonce reservation, and on a restart each takes it back before any call is served.
2
+ import { ChainRefusal, isDefinite } from "@orthograph/chain-evm/device";
3
+ import { Effect } from "effect";
4
+ /** The hash a row holds while it has no transaction yet (a fill that is waiting to be sent). */
5
+ export const NO_HASH = `0x${"0".repeat(64)}`;
6
+ /** A row with no bytes: its nonce is held for a fill (its call was never signed, or could not be sent). */
7
+ export const unsent = (row) => row.serialized === "0x";
8
+ /** Whether a failure ends its call for good. The port decides (`isDefinite`): the relayer does not classify errors itself. */
9
+ export const definite = isDefinite;
10
+ /** What a failure says, for a row's note and for nothing else: no value that was given is in it. */
11
+ export const reason = (error) => error instanceof ChainRefusal ? `refused: ${error.code} ${error.name}`
12
+ : typeof error === "object" && error !== null && "message" in error && typeof error.message === "string" ? error.message : "the send failed";
13
+ /**
14
+ * After a restart, before any call is served: every open row takes back the reservation of its own nonce, lowest first. A row with bytes
15
+ * is resumed from them; a row without bytes (a fill waiting) is held. Bytes that can no longer be read turn the row into a fill, since
16
+ * that nonce may be unused on the chain. Nothing else is swallowed: a nonce another reservation already holds means the relayer's two
17
+ * records disagree, and that is a defect to surface.
18
+ */
19
+ export const register = (live, store) => Effect.gen(function* () {
20
+ const { port, key, held } = live;
21
+ for (const row of store.open()) {
22
+ const signed = unsent(row) ? undefined : yield* port.resume(row.serialized, row.fromBlock).pipe(Effect.catch((error) => error.kind === "signing" ? Effect.succeed(undefined) : Effect.fail(error)));
23
+ if (signed !== undefined) {
24
+ const reservation = port.reservationOf(signed.prepared);
25
+ if (reservation === undefined)
26
+ return yield* Effect.die(new Error("a resumed transaction has no reservation"));
27
+ held.set(row.id, { reservation, signed });
28
+ continue;
29
+ }
30
+ if (!unsent(row))
31
+ store.toFill(row.id, "its signed bytes can no longer be read");
32
+ held.set(row.id, { reservation: yield* port.hold(key.address, row.nonce) });
33
+ }
34
+ }).pipe(Effect.orDie);
@@ -0,0 +1,16 @@
1
+ import { ChainFault } from "@orthograph/chain-evm/device";
2
+ import { Effect } from "effect";
3
+ import type { Rebroadcast, RelayStatus } from "../types.ts";
4
+ import type { Parts } from "./live.ts";
5
+ /** What a submission is now, read from the chain. Only a mined answer is written down: it cannot change back. */
6
+ export declare const status: (parts: Parts, id: string) => Effect.Effect<RelayStatus, ChainFault, never>;
7
+ /**
8
+ * Every submission that may still change is read from the chain, lowest nonce first, and every dropped one is sent again, the same bytes. The
9
+ * caller holds the reconcile lock: an alarm that comes while a call is reconciling waits, then finds nothing left to send. A submission a `relay`
10
+ * call is still working on is left to that call. One that cannot be read or sent now is left for the next time, with the reason on its row
11
+ * (`status` shows it as `problem`). `replaced` is empty: there is no fee-bump replacement yet (`design/later.md`).
12
+ */
13
+ export declare const reconcile: (parts: Parts) => Effect.Effect<{
14
+ replaced: never[];
15
+ rebroadcast: Rebroadcast[];
16
+ }, never, never>;
@@ -0,0 +1,141 @@
1
+ // Reading the chain about what was sent: `status` for one submission, `reconcile` for all of those that may still change. The alarm
2
+ // runs `reconcile`, so a transaction the node dropped is sent again, byte for byte, whether or not anyone asks.
3
+ import { ChainFault } from "@orthograph/chain-evm/device";
4
+ import { Effect } from "effect";
5
+ import { definite, reason, unsent } from "./adopt.js";
6
+ const shown = (state) => (state === "lost" ? "dropped" : state === "submitting" ? "submitted" : state);
7
+ const view = (row, state = shown(row.state)) => ({
8
+ id: row.id, nonce: row.nonce, hash: row.hash, state, replaces: [], ...(row.note === "" ? {} : { problem: row.note }),
9
+ });
10
+ /** Where the chain says this submission's transaction stands. None when the relayer holds no transaction for it. */
11
+ const standing = (parts, row) => {
12
+ const signed = parts.live.held.get(row.id)?.signed;
13
+ if (signed === undefined)
14
+ return Effect.succeed(undefined);
15
+ const { from, transaction } = signed.prepared;
16
+ return parts.live.port.probe({
17
+ hash: row.hash, from, nonce: row.nonce, fromBlock: row.fromBlock,
18
+ ...(transaction.to == null ? {} : { to: transaction.to }),
19
+ ...(transaction.data === undefined ? {} : { data: transaction.data }),
20
+ ...(transaction.value === undefined ? {} : { value: transaction.value }),
21
+ });
22
+ };
23
+ /** A submission that can no longer change: it is written down, and its reservation is left to the allocator, which lets it go once the node's count has passed the nonce. */
24
+ const end = (parts, row, state) => {
25
+ parts.store.setState(row.id, state);
26
+ parts.live.held.delete(row.id);
27
+ };
28
+ /** What a submission is now, read from the chain. Only a mined answer is written down: it cannot change back. */
29
+ export const status = (parts, id) => Effect.gen(function* () {
30
+ const row = parts.store.find(id);
31
+ if (row === undefined)
32
+ return yield* new ChainFault({ kind: "configuration", message: "this relayer has sent no submission with that id" });
33
+ if (row.state === "included" || row.state === "reverted" || row.state === "lost")
34
+ return view(row);
35
+ const now = yield* standing(parts, row);
36
+ switch (now?._tag) {
37
+ case "Included":
38
+ end(parts, row, "included");
39
+ return view(row, "included");
40
+ case "Reverted":
41
+ end(parts, row, "reverted");
42
+ return view(row, "reverted");
43
+ case "Dropped": return view(row, "dropped");
44
+ case "Replaced": return view(row, "dropped");
45
+ default: return view(parts.store.find(id) ?? row);
46
+ }
47
+ });
48
+ /**
49
+ * The node no longer holds the transaction and its nonce is unused: send the same signed bytes again. Sending them is safe at any moment (the
50
+ * port answers "already known" and a nonce used by this hash as success, and registers the broadcast if it never got to). A rebroadcast is
51
+ * refused only on the node's pool checks (a balance that is short, a fee below the floor), and those can clear: so a failure of any kind keeps
52
+ * the row's bytes and reservation, notes the reason, and leaves it for the next alarm. Only a call refused while it is being relayed (the caller
53
+ * got the error) becomes a fill. A row stuck this way shows in `health` once it is past its deadline.
54
+ */
55
+ const rebroadcast = (parts, row) => Effect.gen(function* () {
56
+ const { live, store } = parts;
57
+ const held = live.held.get(row.id);
58
+ if (held?.signed === undefined)
59
+ return undefined;
60
+ const submission = yield* live.port.submit(held.signed);
61
+ store.sent(row.id, submission.fromBlock);
62
+ return { id: row.id, nonce: row.nonce, hash: row.hash };
63
+ });
64
+ /**
65
+ * A row kept only for its nonce (its call could not be sent): when the node shows the nonce unused, send a zero-value transfer from the
66
+ * relayer to itself at it, from the row's own reservation, so what is queued behind it goes through. A nonce someone else used needs
67
+ * nothing. A fill the node refuses keeps the reservation (the port keeps it on a rejection), so the next alarm tries again.
68
+ */
69
+ const fillNow = (parts, row) => Effect.gen(function* () {
70
+ const { live, store } = parts;
71
+ const { port, key } = live;
72
+ const held = live.held.get(row.id);
73
+ if (held === undefined)
74
+ return undefined;
75
+ const now = yield* port.probe({ hash: row.hash, from: key.address, nonce: row.nonce, fromBlock: row.fromBlock, to: key.address, data: "0x", value: 0n });
76
+ switch (now._tag) {
77
+ case "Included":
78
+ end(parts, row, "included");
79
+ return undefined;
80
+ case "Reverted":
81
+ end(parts, row, "reverted");
82
+ return undefined;
83
+ case "Replaced":
84
+ end(parts, row, "lost");
85
+ return undefined;
86
+ case "Held": return undefined;
87
+ case "Dropped": {
88
+ const signed = yield* port.fill(held.reservation, key.signer);
89
+ const submission = yield* port.submit(signed).pipe(Effect.catch((error) => definite(error) ? Effect.fail(error) : Effect.succeed(undefined)));
90
+ live.held.set(row.id, { reservation: held.reservation, signed });
91
+ store.filled(row.id, signed.hash, signed.serialized, submission?.fromBlock ?? 0n);
92
+ return undefined;
93
+ }
94
+ }
95
+ });
96
+ const settle = (parts, row) => Effect.gen(function* () {
97
+ if (unsent(row))
98
+ return yield* fillNow(parts, row);
99
+ const now = yield* standing(parts, row);
100
+ switch (now?._tag) {
101
+ case "Included":
102
+ end(parts, row, "included");
103
+ return undefined;
104
+ case "Reverted":
105
+ end(parts, row, "reverted");
106
+ return undefined;
107
+ case "Held":
108
+ if (row.state !== "submitted")
109
+ parts.store.setState(row.id, "submitted");
110
+ if (row.note !== "")
111
+ parts.store.note(row.id, "");
112
+ return undefined;
113
+ case "Replaced":
114
+ end(parts, row, "lost");
115
+ return undefined; // a different call took the nonce
116
+ case "Dropped": return yield* rebroadcast(parts, row);
117
+ case undefined: return undefined;
118
+ }
119
+ });
120
+ /**
121
+ * Every submission that may still change is read from the chain, lowest nonce first, and every dropped one is sent again, the same bytes. The
122
+ * caller holds the reconcile lock: an alarm that comes while a call is reconciling waits, then finds nothing left to send. A submission a `relay`
123
+ * call is still working on is left to that call. One that cannot be read or sent now is left for the next time, with the reason on its row
124
+ * (`status` shows it as `problem`). `replaced` is empty: there is no fee-bump replacement yet (`design/later.md`).
125
+ */
126
+ export const reconcile = (parts) => Effect.gen(function* () {
127
+ const sent = [];
128
+ for (const row of parts.store.open()) {
129
+ if (parts.live.inflight.has(row.id))
130
+ continue;
131
+ // A row stuck on the same refusal is noted once, when it sticks: the note is written again only if the reason changes, and it is cleared when the row moves.
132
+ const done = yield* settle(parts, row).pipe(Effect.catch((error) => Effect.sync(() => {
133
+ if (row.note !== reason(error))
134
+ parts.store.note(row.id, reason(error));
135
+ return undefined;
136
+ })));
137
+ if (done !== undefined)
138
+ sent.push(done);
139
+ }
140
+ return { replaced: [], rebroadcast: sent };
141
+ });
@@ -0,0 +1,5 @@
1
+ import type { RelayerHealth } from "../types.ts";
2
+ import type { Store } from "./store.ts";
3
+ export declare const STUCK_AFTER_MS = 600000;
4
+ /** The open submissions older than the deadline at `now` (epoch milliseconds on the Clock), lowest nonce first. */
5
+ export declare const health: (store: Store, now: number) => RelayerHealth;
@@ -0,0 +1,7 @@
1
+ export const STUCK_AFTER_MS = 600_000;
2
+ /** The open submissions older than the deadline at `now` (epoch milliseconds on the Clock), lowest nonce first. */
3
+ export const health = (store, now) => {
4
+ const stuckAfterMs = store.config()?.stuckAfterMs ?? STUCK_AFTER_MS;
5
+ const stuck = store.open().filter((row) => now - row.createdAt > stuckAfterMs).map((row) => ({ id: row.id, nonce: row.nonce, pendingMs: now - row.createdAt }));
6
+ return { stuckAfterMs, stuck };
7
+ };
@@ -0,0 +1,26 @@
1
+ import { ChainFault, type ChainPort, type Key, type NonceReservation, type Signed } from "@orthograph/chain-evm/device";
2
+ import { Effect } from "effect";
3
+ import type { RelayerConfig } from "../types.ts";
4
+ import type { Store } from "./store.ts";
5
+ /** What the relayer holds for one open submission: its reservation, from the moment the nonce was taken, and its current signed transaction once it has one. */
6
+ export interface Held {
7
+ readonly reservation: NonceReservation;
8
+ readonly signed?: Signed;
9
+ }
10
+ export interface Live {
11
+ readonly key: Key;
12
+ readonly port: ChainPort;
13
+ /** Submission id to what is held for it. Every open submission is here, so its nonce stays its own: only its reservation is ever filled or replaced. */
14
+ readonly held: Map<string, Held>;
15
+ /** Submissions a `relay` call is still working on (preparing, signing, sending): the alarm leaves them to that call. */
16
+ readonly inflight: Set<string>;
17
+ }
18
+ /** What each piece of the relayer's work is given: the live parts, the store, and the way to ask for the next alarm. */
19
+ export interface Parts {
20
+ readonly live: Live;
21
+ readonly store: Store;
22
+ readonly arm: Effect.Effect<void>;
23
+ }
24
+ /** Fail with the message a caller may see: what went wrong, never a value that was given. */
25
+ export declare const describe: (error: unknown) => string;
26
+ export declare const startLive: (config: RelayerConfig, secret: string | undefined, store: Store) => Effect.Effect<Live, ChainFault, import("@orthograph/language-effect").Timers>;
@@ -0,0 +1,25 @@
1
+ // What the relayer builds once it has its configuration and its key: the chain port, the key, and the signed transaction it holds
2
+ // for each submission that may still change (the port replaces from these). Built again after a restart from what the store kept.
3
+ import { ChainFault, Keys, makeChainPort } from "@orthograph/chain-evm/device";
4
+ import { Effect, Redacted } from "effect";
5
+ import { register } from "./adopt.js";
6
+ /** Fail with the message a caller may see: what went wrong, never a value that was given. */
7
+ export const describe = (error) => {
8
+ if (error instanceof ChainFault)
9
+ return `${error.kind}: ${error.message}`;
10
+ if (typeof error === "object" && error !== null && "_tag" in error && error._tag === "ChainRefusal") {
11
+ const refusal = error;
12
+ return `refused: ${refusal.code} ${refusal.name}`;
13
+ }
14
+ return error instanceof Error ? error.message : "the relayer failed";
15
+ };
16
+ export const startLive = (config, secret, store) => Effect.gen(function* () {
17
+ if (secret === undefined || secret === "")
18
+ return yield* new ChainFault({ kind: "configuration", message: "the relayer has no key: bind RELAYER_KEY" });
19
+ const key = yield* Keys.fromSecret(Redacted.make(secret));
20
+ const port = yield* makeChainPort({ chainId: config.chainId, rpcUrl: config.rpcUrl, rpcTimeoutMs: 30_000, keepOnReject: true });
21
+ const live = { key, port, held: new Map(), inflight: new Set() };
22
+ // Before any call is served, every open row takes its own nonce back. A failure here is a defect, not something to carry on past.
23
+ yield* register(live, store);
24
+ return live;
25
+ });
@@ -0,0 +1,22 @@
1
+ import type { Hex } from "@orthograph/chain-evm/device";
2
+ import { Effect } from "effect";
3
+ import type { Parts } from "./live.ts";
4
+ /**
5
+ * The relayer's store owns its nonces. The moment `prepare` reserves one, a row is written for it (its nonce, no bytes yet), before
6
+ * 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
7
+ * 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
8
+ * behind it are not stuck. The caller still gets the error. The nonce is released only once the node's count is past it.
9
+ *
10
+ * 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
11
+ * 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
12
+ * alarm leaves the row alone. A call is at-least-once: a caller that got no answer should ask `status` before it relays again.
13
+ */
14
+ export declare const relay: (parts: Parts, call: {
15
+ readonly to: Hex;
16
+ readonly data: Hex;
17
+ }) => Effect.Effect<{
18
+ id: string;
19
+ hash: `0x${string}`;
20
+ nonce: number;
21
+ from: `0x${string}`;
22
+ }, unknown, never>;