@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/store.d.ts CHANGED
@@ -1,40 +1,55 @@
1
- import { type SettleAnswer } from "./answers.js";
2
- export declare const SCHEMA = "CREATE TABLE IF NOT EXISTS settlement (\n network text NOT NULL,\n id text NOT NULL,\n answer jsonb,\n until timestamptz NOT NULL,\n since bigint,\n PRIMARY KEY (network, id)\n)";
1
+ import { type OperatorLog, type SettleAnswer } from "./answers.js";
2
+ /** The table, and the index the sweep reads: the rows whose answer is final, by `until`. */
3
+ export declare const SCHEMA = "CREATE TABLE IF NOT EXISTS settlement (\n network text NOT NULL,\n id text NOT NULL,\n answer jsonb,\n until timestamptz NOT NULL,\n since bigint,\n unread bigint[] NOT NULL DEFAULT '{}',\n PRIMARY KEY (network, id)\n);\nCREATE INDEX IF NOT EXISTS settlement_final_until ON settlement (until) WHERE answer IS NOT NULL AND answer->>'errorReason' IS DISTINCT FROM 'settlement_pending'";
3
4
  /** The bound on acquiring a connection, on each query as the client waits for it, and on each statement in the server. */
4
5
  export declare const STORE_TIMEOUT_MS = 5000;
5
- /** How long a row is kept after `until`. */
6
+ /** How long a row whose answer is final is kept after `until`. */
6
7
  export declare const KEEP_AFTER_UNTIL_MS: number;
7
8
  /**
8
9
  * What the table holds for an id: nothing, a claim whose answer is not written yet, or the answer. `since` is, for a
9
- * Polkadot extrinsic, the first block not yet shown at finality to lack it: at the claim, the block after the finalized
10
- * head read before validation (never before the era's birth), and later moved on past blocks read at finality that do
11
- * not hold it. It is null for Tron.
10
+ * Polkadot extrinsic, the first block the scan has not yet read at finality: at the claim, the block after the finalized
11
+ * head read before validation (never before the era's birth), and later moved on past the blocks read at finality. It
12
+ * is null for Tron. `unread` is, for a Polkadot extrinsic, the finalized blocks below `since` that could not be read:
13
+ * none of them is shown to lack the extrinsic, so each is read again. It is empty for Tron.
12
14
  */
13
15
  export type Stored = {
14
16
  state: "none";
15
17
  } | {
16
18
  state: "claimed";
17
19
  since: number | null;
20
+ unread: number[];
18
21
  } | {
19
22
  state: "answered";
20
23
  answer: SettleAnswer;
21
24
  since: number | null;
25
+ unread: number[];
22
26
  };
23
27
  export interface SettlementStore {
24
28
  read(network: string, id: string): Promise<Stored>;
25
29
  /** True when this call inserted the row, and so owns the submission. */
26
30
  claim(network: string, id: string, until: Date, since?: number): Promise<boolean>;
27
- /** Writes the answer unless the row already holds a final one. */
28
- answer(network: string, id: string, answer: SettleAnswer): Promise<void>;
29
- /** Removes a claim that has no answer: the claimant submitted nothing. True when a row was removed. */
30
- release(network: string, id: string): Promise<boolean>;
31
- /** Moves `since` on to `block`, never back. */
32
- advance(network: string, id: string, block: number): Promise<void>;
33
- /** Drops the rows whose `until` is more than `KEEP_AFTER_UNTIL_MS` past. */
31
+ /** Writes the answer unless the row already holds a final one. True when this call wrote it. */
32
+ answer(network: string, id: string, answer: SettleAnswer): Promise<boolean>;
33
+ /**
34
+ * Moves `since` on to `to`, never back, after a scan that read every finalized block from `from` up to `to` except
35
+ * `unread`, and read `resolved`, blocks of the stored `unread` it read again. The stored `unread` gains `unread`,
36
+ * and keeps every block this scan did not read: a concurrent scan's record is never lost.
37
+ */
38
+ advance(network: string, id: string, scan: {
39
+ from: number;
40
+ to: number;
41
+ unread: number[];
42
+ resolved: number[];
43
+ }): Promise<void>;
44
+ /** Drops the rows whose answer is final and whose `until` is more than `KEEP_AFTER_UNTIL_MS` past. */
34
45
  drop(): Promise<void>;
35
46
  close(): Promise<void>;
36
47
  }
37
- export declare function openStore(url: string): Promise<SettlementStore>;
48
+ /**
49
+ * Opens the pool and creates the table. `log` receives an error the pool reports for an idle connection, and a sweep
50
+ * that fails; the sweep runs again a minute later.
51
+ */
52
+ export declare function openStore(url: string, log?: OperatorLog): Promise<SettlementStore>;
38
53
  /**
39
54
  * The part of `settleWaitMs` kept for writing the answer once the wait for the chain ends: a second, or a quarter of a
40
55
  * shorter wait. The node calls and the waits end that much before the deadline, so the answer is stored, then given.
package/dist/store.js CHANGED
@@ -1,27 +1,41 @@
1
1
  /**
2
2
  * The deduplication table: one row per settled payment, keyed by network and transaction id, holding the answer the
3
- * first `/settle` gave. A row is claimed by one conditional insert, so concurrent settles of one payment submit once.
4
- * A final answer is never replaced; a pending one is replaced by what a later read of the chain shows. A row is kept
5
- * until `KEEP_AFTER_UNTIL_MS` after its validity window has ended, so a repeat in that time reads the stored answer and
6
- * the chain before anything is verified again. Every call to the database is bounded by `STORE_TIMEOUT_MS`.
3
+ * first `/settle` gave. A row is claimed by one conditional insert, so concurrent settles of one payment submit once,
4
+ * and a claim is never removed: a submission the node refuses, or that cannot have reached it, is stored as the row's
5
+ * answer. A final answer is never replaced; a pending one is replaced by what a later read of the chain shows, or by
6
+ * the stored answer to a broadcast or submission the node refused or never received. A row whose answer is final is
7
+ * kept until `KEEP_AFTER_UNTIL_MS` after its validity window has ended, so a repeat in that time reads the stored
8
+ * answer before the expiration check and the node reads are made again. A row whose answer is not final (a claim with
9
+ * no answer yet, or `settlement_pending`) is kept until a read of the chain, or the answer to a refused or unsent
10
+ * broadcast or submission, makes it final, so a repeat never finds its id missing. Every call to the database is
11
+ * bounded by `STORE_TIMEOUT_MS`.
7
12
  */
8
13
  import pg from "pg";
9
- import { isPending } from "./answers.js";
14
+ import { isPending, operatorLine } from "./answers.js";
10
15
  import { within } from "./http.js";
16
+ /** A row's answer is final when it is written and is not `settlement_pending`. */
17
+ const FINAL = "answer IS NOT NULL AND answer->>'errorReason' IS DISTINCT FROM 'settlement_pending'";
18
+ /** The table, and the index the sweep reads: the rows whose answer is final, by `until`. */
11
19
  export const SCHEMA = `CREATE TABLE IF NOT EXISTS settlement (
12
20
  network text NOT NULL,
13
21
  id text NOT NULL,
14
22
  answer jsonb,
15
23
  until timestamptz NOT NULL,
16
24
  since bigint,
25
+ unread bigint[] NOT NULL DEFAULT '{}',
17
26
  PRIMARY KEY (network, id)
18
- )`;
27
+ );
28
+ CREATE INDEX IF NOT EXISTS settlement_final_until ON settlement (until) WHERE ${FINAL}`;
19
29
  /** The bound on acquiring a connection, on each query as the client waits for it, and on each statement in the server. */
20
30
  export const STORE_TIMEOUT_MS = 5_000;
21
- /** How long a row is kept after `until`. */
31
+ /** How long a row whose answer is final is kept after `until`. */
22
32
  export const KEEP_AFTER_UNTIL_MS = 24 * 60 * 60 * 1000;
23
33
  const DROP_EVERY_MS = 60_000;
24
- export async function openStore(url) {
34
+ /**
35
+ * Opens the pool and creates the table. `log` receives an error the pool reports for an idle connection, and a sweep
36
+ * that fails; the sweep runs again a minute later.
37
+ */
38
+ export async function openStore(url, log = operatorLine) {
25
39
  const pool = new pg.Pool({
26
40
  connectionString: url,
27
41
  max: 10,
@@ -29,38 +43,41 @@ export async function openStore(url) {
29
43
  query_timeout: STORE_TIMEOUT_MS,
30
44
  statement_timeout: STORE_TIMEOUT_MS,
31
45
  });
32
- pool.on("error", () => { });
46
+ pool.on("error", (e) => log({ event: "store-connection-error" }, e));
33
47
  await pool.query(SCHEMA);
34
48
  const store = {
35
49
  async read(network, id) {
36
- const r = await pool.query("SELECT answer, since FROM settlement WHERE network = $1 AND id = $2", [network, id]);
50
+ const r = await pool.query("SELECT answer, since, unread FROM settlement WHERE network = $1 AND id = $2", [network, id]);
37
51
  const row = r.rows[0];
38
52
  if (row === undefined)
39
53
  return { state: "none" };
40
54
  const since = row.since === null ? null : Number(row.since);
41
- return row.answer === null ? { state: "claimed", since } : { state: "answered", answer: row.answer, since };
55
+ const unread = row.unread.map(Number);
56
+ return row.answer === null
57
+ ? { state: "claimed", since, unread }
58
+ : { state: "answered", answer: row.answer, since, unread };
42
59
  },
43
60
  async claim(network, id, until, since) {
44
61
  const r = await pool.query("INSERT INTO settlement (network, id, answer, until, since) VALUES ($1, $2, NULL, $3, $4) ON CONFLICT DO NOTHING", [network, id, until.toISOString(), since ?? null]);
45
62
  return r.rowCount === 1;
46
63
  },
47
64
  async answer(network, id, answer) {
48
- await pool.query(`UPDATE settlement SET answer = $3 WHERE network = $1 AND id = $2
65
+ const r = await pool.query(`UPDATE settlement SET answer = $3 WHERE network = $1 AND id = $2
49
66
  AND (answer IS NULL OR answer->>'errorReason' = 'settlement_pending')${isPending(answer) ? " AND answer IS NULL" : ""}`, [network, id, JSON.stringify(answer)]);
50
- },
51
- async release(network, id) {
52
- const r = await pool.query("DELETE FROM settlement WHERE network = $1 AND id = $2 AND answer IS NULL", [network, id]);
53
67
  return r.rowCount === 1;
54
68
  },
55
- async advance(network, id, block) {
56
- await pool.query("UPDATE settlement SET since = GREATEST(since, $3) WHERE network = $1 AND id = $2", [
57
- network,
58
- id,
59
- block,
60
- ]);
69
+ async advance(network, id, scan) {
70
+ await pool.query(`UPDATE settlement SET since = GREATEST(since, $3),
71
+ unread = ARRAY(
72
+ SELECT DISTINCT u FROM unnest(unread || $5::bigint[]) AS u
73
+ WHERE u = ANY($5::bigint[]) OR NOT (u = ANY($6::bigint[]) OR (u >= $4 AND u < $3))
74
+ ORDER BY u)
75
+ WHERE network = $1 AND id = $2`, [network, id, scan.to, scan.from, scan.unread, scan.resolved]);
61
76
  },
62
77
  async drop() {
63
- await pool.query("DELETE FROM settlement WHERE until + $1 * interval '1 millisecond' < now()", [KEEP_AFTER_UNTIL_MS]);
78
+ await pool.query(`DELETE FROM settlement WHERE until < now() - $1 * interval '1 millisecond' AND ${FINAL}`, [
79
+ KEEP_AFTER_UNTIL_MS,
80
+ ]);
64
81
  },
65
82
  async close() {
66
83
  clearInterval(timer);
@@ -68,7 +85,7 @@ export async function openStore(url) {
68
85
  },
69
86
  };
70
87
  const timer = setInterval(() => {
71
- store.drop().catch(() => { });
88
+ store.drop().catch((e) => log({ event: "store-call-failed", call: "sweep" }, e));
72
89
  }, DROP_EVERY_MS);
73
90
  timer.unref();
74
91
  return store;
package/dist/tron.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { type FacilitatorRequest, type SettleAnswer, type VerifyAnswer } from "./answers.js";
1
+ import { type FacilitatorRequest, type OperatorLog, type SettleAnswer, type VerifyAnswer } from "./answers.js";
2
2
  import { type SettlementStore } from "./store.js";
3
3
  export interface TronNode {
4
4
  network: `tron:${number}`;
5
5
  fullNode: string;
6
6
  solidityNode: string;
7
7
  }
8
- export declare function createTron(nodes: readonly TronNode[], s: SettlementStore, settleWaitMs: number): {
8
+ export declare function createTron(nodes: readonly TronNode[], s: SettlementStore, settleWaitMs: number, log: OperatorLog): {
9
9
  verify: (r: FacilitatorRequest) => Promise<VerifyAnswer>;
10
10
  settle: (r: FacilitatorRequest) => Promise<SettleAnswer>;
11
11
  networks: string[];