@totemsdk/omnia-host 0.9.0 → 0.11.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.
@@ -1,120 +1,133 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.OperationStore = void 0;
7
- const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
8
4
  const node_crypto_1 = require("node:crypto");
5
+ const sqlite_sync_1 = require("@totemsdk/storage/sqlite-sync");
6
+ const PREFIX = 'omnia:operation:';
7
+ const FORMAT_KEY = 'omnia:store:operation:format';
8
+ const STORE_FORMAT = 1;
9
9
  /**
10
- * CAN-001: operation requests/results can carry `bigint` amounts (e.g. a
11
- * multi-hop route's hop amounts). `JSON.stringify` throws on bigint, so encode
12
- * with a reversible tag and decode it back — the journal never sees a raw
13
- * primitive it cannot persist.
10
+ * CAN-001: operation requests/results can carry `bigint` amounts. The storage
11
+ * codec tags bigints natively, so the record is persisted as-is. Legacy
12
+ * `omnia_operations` rows (JSON with `{$bigint}` tags) are migrated on open.
14
13
  */
15
- function bigintReplacer(_key, value) {
16
- return typeof value === 'bigint' ? { $bigint: value.toString() } : value;
17
- }
18
- function bigintReviver(_key, value) {
19
- if (value !== null &&
20
- typeof value === 'object' &&
21
- typeof value.$bigint === 'string' &&
22
- Object.keys(value).length === 1) {
23
- return BigInt(value.$bigint);
24
- }
25
- return value;
26
- }
27
- function encode(value) {
28
- return value === undefined ? null : JSON.stringify(value, bigintReplacer);
29
- }
30
- function decode(value) {
31
- return value === null ? undefined : JSON.parse(value, bigintReviver);
32
- }
33
- function toRecord(row) {
34
- return {
35
- operationId: row.operation_id,
36
- status: row.status,
37
- createdAt: row.created_at,
38
- updatedAt: row.updated_at,
39
- request: decode(row.request_json),
40
- requestDigest: row.request_digest ?? undefined,
41
- result: decode(row.result_json),
42
- error: row.error ?? undefined,
43
- };
14
+ function decodeLegacy(value) {
15
+ if (value === null)
16
+ return undefined;
17
+ return JSON.parse(value, (_key, nested) => {
18
+ if (nested !== null &&
19
+ typeof nested === 'object' &&
20
+ typeof nested.$bigint === 'string' &&
21
+ Object.keys(nested).length === 1) {
22
+ return BigInt(nested.$bigint);
23
+ }
24
+ return nested;
25
+ });
44
26
  }
45
- /** Durable operation journal with atomic status transitions. */
27
+ /** Durable operation journal with atomic status transitions, via storage SDK. */
46
28
  class OperationStore {
47
- db;
29
+ kv;
48
30
  constructor(dbPath) {
49
- this.db = new better_sqlite3_1.default(dbPath);
50
- this.db.pragma('journal_mode = WAL');
51
- this.db.exec(`
52
- CREATE TABLE IF NOT EXISTS omnia_operations (
53
- operation_id TEXT PRIMARY KEY,
54
- status TEXT NOT NULL,
55
- created_at INTEGER NOT NULL,
56
- updated_at INTEGER NOT NULL,
57
- request_json TEXT,
58
- request_digest TEXT,
59
- result_json TEXT,
60
- error TEXT
61
- )
62
- `);
63
- const columns = this.db.prepare('PRAGMA table_info(omnia_operations)').all();
64
- if (!columns.some((column) => column.name === 'request_digest')) {
65
- this.db.exec('ALTER TABLE omnia_operations ADD COLUMN request_digest TEXT');
31
+ this.kv = new sqlite_sync_1.SyncSqliteStore(dbPath);
32
+ const version = this.kv.get(FORMAT_KEY);
33
+ if (version !== null && version !== STORE_FORMAT) {
34
+ this.kv.close();
35
+ throw new Error(`Unsupported OperationStore format ${version} (this build supports ${STORE_FORMAT}) — refusing to open`);
66
36
  }
37
+ if (version === null)
38
+ this.migrateLegacy();
39
+ }
40
+ migrateLegacy() {
41
+ // One-time migration from the pre-storage direct-SQLite table.
42
+ this.kv.migrateLegacyTable('omnia_operations', (row) => {
43
+ const request = decodeLegacy(row['request_json'] ?? null);
44
+ const result = decodeLegacy(row['result_json'] ?? null);
45
+ const digestValue = row['request_digest'] ? String(row['request_digest']) : undefined;
46
+ const error = row['error'] ? String(row['error']) : undefined;
47
+ const record = {
48
+ operationId: String(row['operation_id']),
49
+ status: row['status'] ?? 'unknown',
50
+ createdAt: Number(row['created_at']),
51
+ updatedAt: Number(row['updated_at']),
52
+ ...(request !== undefined ? { request } : {}),
53
+ ...(digestValue ? { requestDigest: digestValue } : {}),
54
+ ...(result !== undefined ? { result } : {}),
55
+ ...(error ? { error } : {}),
56
+ };
57
+ return { key: PREFIX + record.operationId, value: record };
58
+ });
59
+ this.kv.set(FORMAT_KEY, STORE_FORMAT);
67
60
  }
68
61
  get(operationId) {
69
- const row = this.db.prepare('SELECT * FROM omnia_operations WHERE operation_id = ?').get(operationId);
70
- return row ? toRecord(row) : undefined;
62
+ return this.kv.get(PREFIX + operationId) ?? undefined;
71
63
  }
72
64
  create(operationId, request, now = Date.now()) {
73
- this.db.prepare(`
74
- INSERT OR IGNORE INTO omnia_operations
75
- (operation_id, status, created_at, updated_at, request_json, request_digest)
76
- VALUES (?, 'pending', ?, ?, ?, ?)
77
- `).run(operationId, now, now, encode(request), digest(request));
78
- const record = this.get(operationId);
79
- if (!record)
80
- throw new Error(`Failed to create operation ${operationId}`);
81
- return record;
65
+ return this.kv.transaction(() => {
66
+ const existing = this.get(operationId);
67
+ if (existing)
68
+ return existing;
69
+ const record = {
70
+ operationId,
71
+ status: 'pending',
72
+ createdAt: now,
73
+ updatedAt: now,
74
+ ...(request !== undefined ? { request } : {}),
75
+ requestDigest: digest(request),
76
+ };
77
+ this.kv.set(PREFIX + operationId, record);
78
+ return record;
79
+ });
82
80
  }
83
81
  verifyRequest(operationId, request) {
84
82
  const record = this.get(operationId);
85
83
  return !record?.requestDigest || record.requestDigest === digest(request);
86
84
  }
87
85
  transition(operationId, from, to, patch = {}, now = Date.now()) {
88
- const result = this.db.prepare(`
89
- UPDATE omnia_operations
90
- SET status = ?, updated_at = ?, result_json = ?, error = ?
91
- WHERE operation_id = ? AND status = ?
92
- `).run(to, now, encode(patch.result), patch.error ?? null, operationId, from);
93
- if (result.changes !== 1) {
94
- const current = this.get(operationId);
95
- if (!current)
86
+ return this.kv.transaction(() => {
87
+ const record = this.get(operationId);
88
+ if (!record)
96
89
  throw new Error(`Unknown operation ${operationId}`);
97
- throw new Error(`Operation ${operationId} expected status ${from} but is ${current.status}`);
98
- }
99
- return this.get(operationId);
90
+ if (record.status !== from) {
91
+ throw new Error(`Operation ${operationId} expected status ${from} but is ${record.status}`);
92
+ }
93
+ const next = {
94
+ ...record,
95
+ status: to,
96
+ updatedAt: now,
97
+ ...(patch.error !== undefined ? { error: patch.error } : {}),
98
+ ...(patch.result !== undefined ? { result: patch.result } : {}),
99
+ };
100
+ this.kv.set(PREFIX + operationId, next);
101
+ return next;
102
+ });
100
103
  }
101
104
  listByStatus(status) {
102
- const rows = this.db.prepare('SELECT * FROM omnia_operations WHERE status = ? ORDER BY created_at').all(status);
103
- return rows.map(toRecord);
105
+ return this.kv
106
+ .keys()
107
+ .filter((key) => key.startsWith(PREFIX))
108
+ .map((key) => this.kv.get(key))
109
+ .filter((record) => record !== null)
110
+ .filter((record) => record.status === status)
111
+ .sort((a, b) => a.createdAt - b.createdAt);
104
112
  }
105
113
  close() {
106
- this.db.close();
114
+ this.kv.close();
107
115
  }
108
116
  }
109
117
  exports.OperationStore = OperationStore;
110
118
  function canonical(value) {
119
+ if (value === undefined)
120
+ return 'undefined';
111
121
  if (typeof value === 'bigint')
112
122
  return `{"$bigint":${JSON.stringify(value.toString())}}`;
113
123
  if (value === null || typeof value !== 'object')
114
- return JSON.stringify(value);
124
+ return JSON.stringify(value) ?? 'null';
115
125
  if (Array.isArray(value))
116
126
  return `[${value.map(canonical).join(',')}]`;
117
- return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`;
127
+ return `{${Object.keys(value)
128
+ .sort()
129
+ .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`)
130
+ .join(',')}}`;
118
131
  }
119
132
  function digest(value) {
120
133
  return (0, node_crypto_1.createHash)('sha256').update(canonical(value)).digest('hex');
@@ -1,10 +1,11 @@
1
1
  import { type OmniaChannel, type ChannelSigner } from '@totemsdk/omnia';
2
- /** SQLite-backed Map facade accepted by @totemsdk/omnia's ChannelStore type. */
2
+ /**
3
+ * Synchronous Map facade accepted by @totemsdk/omnia's ChannelStore type,
4
+ * persisted through `@totemsdk/storage` (`SyncSqliteStore`, same codec/envelope
5
+ * as `SqliteStore`). Legacy `omnia_channels` tables are migrated on open.
6
+ */
3
7
  export declare class SqliteChannelStore extends Map<string, OmniaChannel> {
4
- private readonly db;
5
- private readonly readStatement;
6
- private readonly writeStatement;
7
- private readonly deleteStatement;
8
+ private readonly kv;
8
9
  /**
9
10
  * CAN-002: a recovered channel loses `localSigner` (it is not serializable),
10
11
  * so the router's `counterpartPkd()` cannot tell which party is local and
@@ -15,6 +16,8 @@ export declare class SqliteChannelStore extends Map<string, OmniaChannel> {
15
16
  /** Attach the host's signer so recovered channels carry it (CAN-002). */
16
17
  setLocalSigner(signer?: ChannelSigner): void;
17
18
  private rebind;
19
+ private channelKeys;
20
+ private idOf;
18
21
  get(channelId: string): OmniaChannel | undefined;
19
22
  set(channelId: string, channel: OmniaChannel): this;
20
23
  has(channelId: string): boolean;
@@ -1,11 +1,11 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.SqliteChannelStore = void 0;
7
- const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
4
+ const sqlite_sync_1 = require("@totemsdk/storage/sqlite-sync");
8
5
  const omnia_1 = require("@totemsdk/omnia");
6
+ const PREFIX = 'omnia:channel:';
7
+ const FORMAT_KEY = 'omnia:store:channel:format';
8
+ const STORE_FORMAT = 1;
9
9
  function iterator(values) {
10
10
  let index = 0;
11
11
  return {
@@ -22,12 +22,13 @@ function iterator(values) {
22
22
  },
23
23
  };
24
24
  }
25
- /** SQLite-backed Map facade accepted by @totemsdk/omnia's ChannelStore type. */
25
+ /**
26
+ * Synchronous Map facade accepted by @totemsdk/omnia's ChannelStore type,
27
+ * persisted through `@totemsdk/storage` (`SyncSqliteStore`, same codec/envelope
28
+ * as `SqliteStore`). Legacy `omnia_channels` tables are migrated on open.
29
+ */
26
30
  class SqliteChannelStore extends Map {
27
- db;
28
- readStatement;
29
- writeStatement;
30
- deleteStatement;
31
+ kv;
31
32
  /**
32
33
  * CAN-002: a recovered channel loses `localSigner` (it is not serializable),
33
34
  * so the router's `counterpartPkd()` cannot tell which party is local and
@@ -36,24 +37,20 @@ class SqliteChannelStore extends Map {
36
37
  localSigner;
37
38
  constructor(dbPath) {
38
39
  super();
39
- this.db = new better_sqlite3_1.default(dbPath);
40
- this.db.pragma('journal_mode = WAL');
41
- this.db.exec(`
42
- CREATE TABLE IF NOT EXISTS omnia_channels (
43
- channel_id TEXT PRIMARY KEY,
44
- channel_json TEXT NOT NULL,
45
- updated_at INTEGER NOT NULL
46
- )
47
- `);
48
- this.readStatement = this.db.prepare('SELECT channel_json FROM omnia_channels WHERE channel_id = ?');
49
- this.writeStatement = this.db.prepare(`
50
- INSERT INTO omnia_channels (channel_id, channel_json, updated_at)
51
- VALUES (?, ?, ?)
52
- ON CONFLICT(channel_id) DO UPDATE SET
53
- channel_json = excluded.channel_json,
54
- updated_at = excluded.updated_at
55
- `);
56
- this.deleteStatement = this.db.prepare('DELETE FROM omnia_channels WHERE channel_id = ?');
40
+ this.kv = new sqlite_sync_1.SyncSqliteStore(dbPath);
41
+ const version = this.kv.get(FORMAT_KEY);
42
+ if (version !== null && version !== STORE_FORMAT) {
43
+ this.kv.close();
44
+ throw new Error(`Unsupported SqliteChannelStore format ${version} (this build supports ${STORE_FORMAT}) — refusing to open`);
45
+ }
46
+ if (version === null) {
47
+ // One-time migration from the pre-storage direct-SQLite table.
48
+ this.kv.migrateLegacyTable('omnia_channels', (row) => ({
49
+ key: PREFIX + String(row['channel_id']),
50
+ value: String(row['channel_json']),
51
+ }));
52
+ this.kv.set(FORMAT_KEY, STORE_FORMAT);
53
+ }
57
54
  }
58
55
  /** Attach the host's signer so recovered channels carry it (CAN-002). */
59
56
  setLocalSigner(signer) {
@@ -62,36 +59,42 @@ class SqliteChannelStore extends Map {
62
59
  rebind(channel) {
63
60
  return this.localSigner ? { ...channel, localSigner: this.localSigner } : channel;
64
61
  }
62
+ channelKeys() {
63
+ return this.kv.keys().filter((key) => key.startsWith(PREFIX));
64
+ }
65
+ idOf(key) {
66
+ return key.slice(PREFIX.length);
67
+ }
65
68
  get(channelId) {
66
- const row = this.readStatement.get(channelId);
67
- return row ? this.rebind((0, omnia_1.recoverChannel)(row.channel_json)) : undefined;
69
+ const snapshot = this.kv.get(PREFIX + channelId);
70
+ return snapshot ? this.rebind((0, omnia_1.recoverChannel)(snapshot)) : undefined;
68
71
  }
69
72
  set(channelId, channel) {
70
- this.writeStatement.run(channelId, (0, omnia_1.serializeChannelSnapshot)(channel), Date.now());
73
+ this.kv.set(PREFIX + channelId, (0, omnia_1.serializeChannelSnapshot)(channel));
71
74
  return this;
72
75
  }
73
76
  has(channelId) {
74
- return this.readStatement.get(channelId) !== undefined;
77
+ return this.kv.has(PREFIX + channelId);
75
78
  }
76
79
  delete(channelId) {
77
- return this.deleteStatement.run(channelId).changes > 0;
80
+ return this.kv.remove(PREFIX + channelId);
78
81
  }
79
82
  clear() {
80
- this.db.exec('DELETE FROM omnia_channels');
83
+ for (const key of this.channelKeys())
84
+ this.kv.remove(key);
81
85
  }
82
86
  get size() {
83
- const row = this.db.prepare('SELECT COUNT(*) AS count FROM omnia_channels').get();
84
- return row.count;
87
+ return this.channelKeys().length;
85
88
  }
86
89
  entries() {
87
- const rows = this.db.prepare('SELECT channel_id, channel_json FROM omnia_channels ORDER BY channel_id').iterate();
88
- return iterator(Array.from(rows, (row) => [
89
- row.channel_id,
90
- this.rebind((0, omnia_1.recoverChannel)(row.channel_json)),
91
- ]));
90
+ const rows = this.channelKeys().map((key) => {
91
+ const snapshot = this.kv.get(key);
92
+ return [this.idOf(key), this.rebind((0, omnia_1.recoverChannel)(snapshot))];
93
+ });
94
+ return iterator(rows);
92
95
  }
93
96
  keys() {
94
- return iterator(Array.from(this.entries(), ([channelId]) => channelId));
97
+ return iterator(this.channelKeys().map((key) => this.idOf(key)));
95
98
  }
96
99
  values() {
97
100
  return iterator(Array.from(this.entries(), ([, channel]) => channel));
@@ -104,7 +107,7 @@ class SqliteChannelStore extends Map {
104
107
  callbackfn(value, key, this);
105
108
  }
106
109
  close() {
107
- this.db.close();
110
+ this.kv.close();
108
111
  }
109
112
  }
110
113
  exports.SqliteChannelStore = SqliteChannelStore;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totemsdk/omnia-host",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Durable Omnia node daemon for channel lifecycle, routing, and control APIs",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -17,27 +17,29 @@
17
17
  "files": [
18
18
  "dist",
19
19
  "README.md",
20
- "LICENSE"
20
+ "LICENSE",
21
+ "NOTICE"
21
22
  ],
22
23
  "dependencies": {
23
- "better-sqlite3": "^12.2.0",
24
24
  "ws": "^8.21.1",
25
- "@totemsdk/chain-provider": "^0.3.0",
26
25
  "@totemsdk/core": "^1.4.0",
27
- "@totemsdk/identity": "^1.0.1",
28
- "@totemsdk/omnia": "^2.2.0",
29
- "@totemsdk/manifest": "^2.0.0",
30
- "@totemsdk/omnia-factory": "^0.6.0",
31
- "@totemsdk/omnia-router": "^0.3.0",
32
- "@totemsdk/omnia-splice": "^0.3.0",
33
- "@totemsdk/omnia-vtxo": "^0.6.0",
34
- "@totemsdk/storage": "^0.1.0",
26
+ "@totemsdk/identity": "^1.0.2",
27
+ "@totemsdk/chain-provider": "^0.3.0",
28
+ "@totemsdk/liquidity-bond": "^0.3.1",
29
+ "@totemsdk/manifest": "^2.0.1",
35
30
  "@totemsdk/minima-rpc": "^0.4.0",
31
+ "@totemsdk/omnia": "^2.3.1",
32
+ "@totemsdk/omnia-factory": "^0.7.0",
33
+ "@totemsdk/omnia-router": "^0.4.0",
34
+ "@totemsdk/omnia-pool": "^0.5.3",
35
+ "@totemsdk/omnia-splice": "^0.3.0",
36
+ "@totemsdk/p2p-hub": "^0.1.0",
37
+ "@totemsdk/omnia-vtxo": "^0.6.1",
38
+ "@totemsdk/storage": "^0.2.0",
36
39
  "@totemsdk/wots-lease": "^1.0.1"
37
40
  },
38
41
  "devDependencies": {
39
42
  "@types/jest": "^30.0.0",
40
- "@types/better-sqlite3": "^7.6.13",
41
43
  "@types/node": "^20.19.43",
42
44
  "@types/ws": "^8.5.0",
43
45
  "jest": "^30.4.2",
@@ -51,7 +53,7 @@
51
53
  "publishConfig": {
52
54
  "access": "public"
53
55
  },
54
- "license": "MIT",
56
+ "license": "Apache-2.0",
55
57
  "author": "Totem SDK",
56
58
  "homepage": "https://docs.totem.ing",
57
59
  "repository": {