@integraledger/profile-facilitator 0.1.0 → 0.3.0

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/dist/http.d.ts CHANGED
@@ -3,21 +3,48 @@ import type { IncomingMessage, ServerResponse } from "node:http";
3
3
  export declare const NODE_TIMEOUT_MS = 5000;
4
4
  export declare const NODE_MAX_BYTES: number;
5
5
  export declare const REQUEST_MAX_BYTES: number;
6
- /** Why a node call gave no answer. `sent` is false only when the request cannot have reached the node. */
6
+ /**
7
+ * Why a node call gave no answer. `sent` is false only when the request cannot have reached the node. `spent` is a call
8
+ * whose deadline left it no time: it is not sent.
9
+ */
7
10
  export declare class NodeError extends Error {
8
- readonly code: "timeout" | "transport" | "http-status" | "too-large" | "malformed";
11
+ readonly code: "timeout" | "transport" | "http-status" | "too-large" | "malformed" | "spent";
9
12
  readonly sent: boolean;
10
- constructor(code: "timeout" | "transport" | "http-status" | "too-large" | "malformed", sent: boolean, detail: string);
13
+ constructor(code: "timeout" | "transport" | "http-status" | "too-large" | "malformed" | "spent", sent: boolean, detail: string, options?: ErrorOptions);
11
14
  }
12
- /** POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and the size bound. */
13
- export declare function postJson(url: string, body: unknown, timeoutMs?: number): Promise<unknown>;
14
- /** Reads a request body of at most 64 KiB as JSON; undefined when it is larger or is not JSON. */
15
+ /** A node call, by the name its caller gives it, that was not sent because its deadline left it no time. */
16
+ export interface Spent {
17
+ spent: string;
18
+ }
19
+ /** True for a node call that was not sent because its deadline left it no time. */
20
+ export declare function isSpent(e: unknown): boolean;
21
+ /**
22
+ * POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and `maxBytes` (4 MiB unless given). A
23
+ * timeout that leaves no time sends nothing: the call fails as `spent`.
24
+ */
25
+ export declare function postJson(url: string, body: unknown, timeoutMs?: number, maxBytes?: number): Promise<unknown>;
26
+ /**
27
+ * Reads a request body of at most 64 KiB as JSON: `tooLarge` when it is larger, `left` when the request ends before
28
+ * its body does (the client left), and undefined when it is not JSON.
29
+ */
15
30
  export declare function readRequestJson(req: IncomingMessage): Promise<{
16
31
  json: unknown;
17
32
  } | {
18
33
  tooLarge: true;
34
+ } | {
35
+ left: true;
19
36
  } | undefined>;
20
37
  export declare function sendJson(res: ServerResponse, status: number, body: unknown): void;
21
38
  export declare function sleep(ms: number): Promise<void>;
22
39
  /** `p`'s outcome, or a `timeout` NodeError once `ms` has passed first. */
23
40
  export declare function within<T>(p: Promise<T>, ms: number): Promise<T>;
41
+ /**
42
+ * A fixed number of slots shared by the callers that hold one. `take` gives a slot within `ms`, as the function that
43
+ * gives it back (a second call does nothing), or undefined when none is free in time. A slot given back goes to the
44
+ * longest waiter first.
45
+ */
46
+ export declare class Slots {
47
+ #private;
48
+ constructor(count: number);
49
+ take(ms: number): Promise<(() => void) | undefined>;
50
+ }
package/dist/http.js CHANGED
@@ -6,19 +6,31 @@ const UNSENT = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH"
6
6
  function isObject(v) {
7
7
  return typeof v === "object" && v !== null;
8
8
  }
9
- /** Why a node call gave no answer. `sent` is false only when the request cannot have reached the node. */
9
+ /**
10
+ * Why a node call gave no answer. `sent` is false only when the request cannot have reached the node. `spent` is a call
11
+ * whose deadline left it no time: it is not sent.
12
+ */
10
13
  export class NodeError extends Error {
11
14
  code;
12
15
  sent;
13
- constructor(code, sent, detail) {
14
- super(`${code}: ${detail}`);
16
+ constructor(code, sent, detail, options) {
17
+ super(`${code}: ${detail}`, options);
15
18
  this.code = code;
16
19
  this.sent = sent;
17
20
  }
18
21
  }
19
- /** POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and the size bound. */
20
- export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS) {
21
- const ms = Number.isFinite(timeoutMs) ? Math.max(1, Math.ceil(Math.min(timeoutMs, NODE_TIMEOUT_MS))) : NODE_TIMEOUT_MS;
22
+ /** True for a node call that was not sent because its deadline left it no time. */
23
+ export function isSpent(e) {
24
+ return e instanceof NodeError && e.code === "spent";
25
+ }
26
+ /**
27
+ * POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and `maxBytes` (4 MiB unless given). A
28
+ * timeout that leaves no time sends nothing: the call fails as `spent`.
29
+ */
30
+ export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS, maxBytes = NODE_MAX_BYTES) {
31
+ if (timeoutMs <= 0)
32
+ throw new NodeError("spent", false, url);
33
+ const ms = Number.isFinite(timeoutMs) ? Math.ceil(Math.min(timeoutMs, NODE_TIMEOUT_MS)) : NODE_TIMEOUT_MS;
22
34
  const signal = AbortSignal.timeout(ms);
23
35
  let res;
24
36
  try {
@@ -31,24 +43,24 @@ export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS) {
31
43
  }
32
44
  catch (e) {
33
45
  if (signal.aborted)
34
- throw new NodeError("timeout", true, url);
35
- const cause = e instanceof Error && isObject(e.cause) ? e.cause["code"] : undefined;
36
- const unsent = typeof cause === "string" && UNSENT.has(cause);
37
- throw new NodeError("transport", !unsent, e instanceof Error ? e.message : String(e));
46
+ throw new NodeError("timeout", true, url, { cause: e });
47
+ const code = e instanceof Error && isObject(e.cause) ? e.cause["code"] : undefined;
48
+ const unsent = typeof code === "string" && UNSENT.has(code);
49
+ throw new NodeError("transport", !unsent, e instanceof Error ? e.message : String(e), { cause: e });
38
50
  }
39
- const bytes = await readBounded(res, signal);
51
+ const bytes = await readBounded(res, signal, maxBytes);
40
52
  if (res.status < 200 || res.status > 299)
41
53
  throw new NodeError("http-status", true, `status ${res.status}`);
42
54
  try {
43
55
  return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
44
56
  }
45
- catch {
46
- throw new NodeError("malformed", true, "the answer is not JSON");
57
+ catch (e) {
58
+ throw new NodeError("malformed", true, "the answer is not JSON", { cause: e });
47
59
  }
48
60
  }
49
- async function readBounded(res, signal) {
61
+ async function readBounded(res, signal, maxBytes) {
50
62
  const declared = Number(res.headers.get("content-length"));
51
- if (Number.isFinite(declared) && declared > NODE_MAX_BYTES) {
63
+ if (Number.isFinite(declared) && declared > maxBytes) {
52
64
  await res.body?.cancel();
53
65
  throw new NodeError("too-large", true, `content-length ${declared}`);
54
66
  }
@@ -63,9 +75,9 @@ async function readBounded(res, signal) {
63
75
  if (done)
64
76
  break;
65
77
  total += value.byteLength;
66
- if (total > NODE_MAX_BYTES) {
78
+ if (total > maxBytes) {
67
79
  await reader.cancel();
68
- throw new NodeError("too-large", true, `more than ${NODE_MAX_BYTES} bytes`);
80
+ throw new NodeError("too-large", true, `more than ${maxBytes} bytes`);
69
81
  }
70
82
  parts.push(value);
71
83
  }
@@ -74,8 +86,8 @@ async function readBounded(res, signal) {
74
86
  if (e instanceof NodeError)
75
87
  throw e;
76
88
  if (signal.aborted)
77
- throw new NodeError("timeout", true, "reading the answer");
78
- throw new NodeError("transport", true, e instanceof Error ? e.message : String(e));
89
+ throw new NodeError("timeout", true, "reading the answer", { cause: e });
90
+ throw new NodeError("transport", true, e instanceof Error ? e.message : String(e), { cause: e });
79
91
  }
80
92
  const out = new Uint8Array(total);
81
93
  let at = 0;
@@ -85,24 +97,33 @@ async function readBounded(res, signal) {
85
97
  }
86
98
  return out;
87
99
  }
88
- /** Reads a request body of at most 64 KiB as JSON; undefined when it is larger or is not JSON. */
100
+ /**
101
+ * Reads a request body of at most 64 KiB as JSON: `tooLarge` when it is larger, `left` when the request ends before
102
+ * its body does (the client left), and undefined when it is not JSON.
103
+ */
89
104
  export async function readRequestJson(req) {
90
105
  const declared = Number(req.headers["content-length"]);
91
106
  if (Number.isFinite(declared) && declared > REQUEST_MAX_BYTES)
92
107
  return { tooLarge: true };
93
108
  const parts = [];
94
109
  let total = 0;
95
- for await (const chunk of req) {
96
- const b = chunk;
97
- total += b.byteLength;
98
- if (total > REQUEST_MAX_BYTES)
99
- return { tooLarge: true };
100
- parts.push(b);
110
+ try {
111
+ for await (const chunk of req) {
112
+ const b = chunk;
113
+ total += b.byteLength;
114
+ if (total > REQUEST_MAX_BYTES)
115
+ return { tooLarge: true };
116
+ parts.push(b);
117
+ }
118
+ }
119
+ catch {
120
+ return { left: true };
101
121
  }
102
122
  try {
103
123
  return { json: JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(parts))) };
104
124
  }
105
125
  catch {
126
+ // The client's own body is not JSON: refused `invalid_payload` to that client.
106
127
  return undefined;
107
128
  }
108
129
  }
@@ -129,3 +150,49 @@ export async function within(p, ms) {
129
150
  clearTimeout(timer);
130
151
  }
131
152
  }
153
+ /**
154
+ * A fixed number of slots shared by the callers that hold one. `take` gives a slot within `ms`, as the function that
155
+ * gives it back (a second call does nothing), or undefined when none is free in time. A slot given back goes to the
156
+ * longest waiter first.
157
+ */
158
+ export class Slots {
159
+ #free;
160
+ #waiting = [];
161
+ constructor(count) {
162
+ this.#free = count;
163
+ }
164
+ take(ms) {
165
+ if (this.#free > 0) {
166
+ this.#free -= 1;
167
+ return Promise.resolve(this.#release());
168
+ }
169
+ if (!(ms > 0))
170
+ return Promise.resolve(undefined);
171
+ return new Promise((resolve) => {
172
+ const wake = (release) => {
173
+ clearTimeout(timer);
174
+ resolve(release);
175
+ };
176
+ const timer = setTimeout(() => {
177
+ const at = this.#waiting.indexOf(wake);
178
+ if (at >= 0)
179
+ this.#waiting.splice(at, 1);
180
+ resolve(undefined);
181
+ }, ms);
182
+ this.#waiting.push(wake);
183
+ });
184
+ }
185
+ #release() {
186
+ let given = false;
187
+ return () => {
188
+ if (given)
189
+ return;
190
+ given = true;
191
+ const next = this.#waiting.shift();
192
+ if (next === undefined)
193
+ this.#free += 1;
194
+ else
195
+ next(this.#release());
196
+ };
197
+ }
198
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { type PolkadotNetwork } from "@integraledger/lcp/polkadot";
2
- export type { SettleAnswer, VerifyAnswer } from "./answers.js";
3
2
  export interface ProfileFacilitatorConfig {
4
3
  /** "host:port" */
5
4
  listen: string;
@@ -19,6 +18,21 @@ export interface ProfileFacilitatorConfig {
19
18
  };
20
19
  /** How long `/settle` waits for inclusion before answering `settlement_pending`; default 30 000. */
21
20
  settleWaitMs: number;
21
+ /**
22
+ * Receives every entry for the operator: what the facilitator saw that its answer does not carry, with `network`,
23
+ * `payer` and `transaction` naming the payment where they are known. `cause` is the error that caused the entry,
24
+ * when there is one; the answer to the client is the same either way, and carries nothing from it. Called once per
25
+ * entry; what it throws, or a promise it returns that rejects, goes to the default with an `operator-log-failed`
26
+ * entry. Default: one JSON line per entry on standard error, the cause as its `cause` (name, message, stack and its
27
+ * own `cause` chain).
28
+ */
29
+ operatorLog?: (entry: {
30
+ event: string;
31
+ network?: string;
32
+ payer?: string;
33
+ transaction?: string;
34
+ [field: string]: unknown;
35
+ }, cause?: unknown) => void;
22
36
  }
23
37
  export declare function serveProfileFacilitator(c: ProfileFacilitatorConfig): Promise<{
24
38
  close(): Promise<void>;
package/dist/index.js CHANGED
@@ -7,12 +7,19 @@
7
7
  import { createServer } from "node:http";
8
8
  import { LCP_ASSETS_REMARK } from "@integraledger/lcp/polkadot";
9
9
  import { LCP_TRC20_MEMO } from "@integraledger/lcp/tron";
10
- import { failed, readRequest } from "./answers.js";
10
+ import { failed, guarded, invalid, isObject, operatorLine, readRequest, } from "./answers.js";
11
11
  import { readRequestJson, sendJson } from "./http.js";
12
12
  import { createPolkadot } from "./polkadot.js";
13
13
  import { openStore } from "./store.js";
14
14
  import { createTron } from "./tron.js";
15
+ import { unexpectedSettle, unexpectedVerify } from "./unexpected.js";
15
16
  const DEFAULT_SETTLE_WAIT_MS = 30_000;
17
+ /** The body's `paymentRequirements.network` when it is a string, else "". */
18
+ function networkOf(body) {
19
+ const requirements = isObject(body) ? body["paymentRequirements"] : undefined;
20
+ const network = isObject(requirements) ? requirements["network"] : undefined;
21
+ return typeof network === "string" ? network : "";
22
+ }
16
23
  function hostPort(listen) {
17
24
  const m = /^\[?([^\]]*)\]?:(\d{1,5})$/.exec(listen);
18
25
  const port = m === null ? NaN : Number(m[2]);
@@ -26,9 +33,10 @@ function trimmed(url) {
26
33
  export async function serveProfileFacilitator(c) {
27
34
  const { host, port } = hostPort(c.listen);
28
35
  const settleWaitMs = Number.isFinite(c.settleWaitMs) && c.settleWaitMs > 0 ? c.settleWaitMs : DEFAULT_SETTLE_WAIT_MS;
29
- const store = await openStore(c.store.url);
30
- const tron = createTron((c.tron ?? []).map((n) => ({ ...n, fullNode: trimmed(n.fullNode), solidityNode: trimmed(n.solidityNode) })), store, settleWaitMs);
31
- const polkadot = createPolkadot((c.polkadot ?? []).map((n) => ({ ...n, rpc: trimmed(n.rpc) })), store, settleWaitMs);
36
+ const log = guarded(c.operatorLog ?? operatorLine);
37
+ const store = await openStore(c.store.url, log);
38
+ const tron = createTron((c.tron ?? []).map((n) => ({ ...n, fullNode: trimmed(n.fullNode), solidityNode: trimmed(n.solidityNode) })), store, settleWaitMs, log);
39
+ const polkadot = createPolkadot((c.polkadot ?? []).map((n) => ({ ...n, rpc: trimmed(n.rpc) })), store, settleWaitMs, log);
32
40
  const supported = {
33
41
  kinds: [
34
42
  ...tron.networks.map((network) => ({
@@ -65,23 +73,23 @@ export async function serveProfileFacilitator(c) {
65
73
  try {
66
74
  return await rail.verify(r);
67
75
  }
68
- catch {
69
- return { isValid: false, invalidReason: "unexpected_verify_error" };
76
+ catch (e) {
77
+ return invalid(unexpectedVerify(log, { event: "verify-error", network: r.paymentRequirements.network }, e));
70
78
  }
71
79
  }
72
80
  async function settle(body) {
73
81
  const r = readRequest(body);
74
- const network = typeof r === "string" ? "" : r.paymentRequirements.network;
75
82
  if (typeof r === "string")
76
- return failed(r, "", network);
83
+ return failed(r, "", networkOf(body));
84
+ const network = r.paymentRequirements.network;
77
85
  const rail = railOf(r);
78
86
  if (rail === undefined)
79
87
  return failed("invalid_network", "", network);
80
88
  try {
81
89
  return await rail.settle(r);
82
90
  }
83
- catch {
84
- return failed("unexpected_settle_error", "", network);
91
+ catch (e) {
92
+ return unexpectedSettle(log, { event: "settle-error", network }, e);
85
93
  }
86
94
  }
87
95
  async function handle(req, res) {
@@ -102,6 +110,11 @@ export async function serveProfileFacilitator(c) {
102
110
  req.destroy();
103
111
  return;
104
112
  }
113
+ if (read !== undefined && "left" in read) {
114
+ // The client left before its body was complete: there is no one to answer, and nothing failed here to log.
115
+ res.destroy();
116
+ return;
117
+ }
105
118
  if (path === "/verify") {
106
119
  if (read === undefined)
107
120
  return sendJson(res, 400, { isValid: false, invalidReason: "invalid_payload" });
@@ -112,7 +125,8 @@ export async function serveProfileFacilitator(c) {
112
125
  return sendJson(res, 200, await settle(read.json));
113
126
  }
114
127
  const server = createServer((req, res) => {
115
- handle(req, res).catch(() => {
128
+ handle(req, res).catch((e) => {
129
+ log({ event: "request-error", path: (req.url ?? "").split("?")[0] }, e);
116
130
  if (!res.headersSent)
117
131
  sendJson(res, 500, { error: "internal error" });
118
132
  else
@@ -1,11 +1,19 @@
1
1
  import { type PolkadotNetwork } from "@integraledger/lcp/polkadot";
2
- import { type FacilitatorRequest, type SettleAnswer, type VerifyAnswer } from "./answers.js";
2
+ import { type FacilitatorRequest, type OperatorLog, type SettleAnswer, type VerifyAnswer } from "./answers.js";
3
+ import { Slots } from "./http.js";
3
4
  import { type SettlementStore } from "./store.js";
4
5
  export interface PolkadotNode {
5
6
  network: PolkadotNetwork;
6
7
  rpc: string;
7
8
  }
8
- export declare function createPolkadot(nodes: readonly PolkadotNode[], s: SettlementStore, settleWaitMs: number): {
9
+ /**
10
+ * How many `chain_getBlock` reads, each bounded by the runtime's `System.BlockLength`, run at once in this process:
11
+ * for Polkadot Asset Hub's runtime 2005000, at most 4 × 28,504,064 = 114,016,256 bytes of block answers.
12
+ */
13
+ export declare const BLOCK_READS = 4;
14
+ /** The slots of `BLOCK_READS`, shared by every network and every scan in this process. */
15
+ export declare const blockReads: Slots;
16
+ export declare function createPolkadot(nodes: readonly PolkadotNode[], s: SettlementStore, settleWaitMs: number, log: OperatorLog): {
9
17
  verify: (r: FacilitatorRequest) => Promise<VerifyAnswer>;
10
18
  settle: (r: FacilitatorRequest) => Promise<SettleAnswer>;
11
19
  close: () => Promise<void>;