@optimystic/db-core 1.5.0 → 1.6.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.
Files changed (157) hide show
  1. package/README.md +336 -336
  2. package/dist/src/cluster/structs.d.ts +37 -0
  3. package/dist/src/cluster/structs.d.ts.map +1 -1
  4. package/dist/src/cluster/structs.js +13 -0
  5. package/dist/src/cluster/structs.js.map +1 -1
  6. package/dist/src/collection/collection.d.ts +44 -4
  7. package/dist/src/collection/collection.d.ts.map +1 -1
  8. package/dist/src/collection/collection.js +95 -14
  9. package/dist/src/collection/collection.js.map +1 -1
  10. package/dist/src/log/log.d.ts +41 -8
  11. package/dist/src/log/log.d.ts.map +1 -1
  12. package/dist/src/log/log.js +15 -10
  13. package/dist/src/log/log.js.map +1 -1
  14. package/dist/src/testing/test-transactor.d.ts +36 -0
  15. package/dist/src/testing/test-transactor.d.ts.map +1 -1
  16. package/dist/src/testing/test-transactor.js +49 -0
  17. package/dist/src/testing/test-transactor.js.map +1 -1
  18. package/dist/src/transaction/coordinator.d.ts.map +1 -1
  19. package/dist/src/transaction/coordinator.js +26 -9
  20. package/dist/src/transaction/coordinator.js.map +1 -1
  21. package/package.json +1 -1
  22. package/src/blocks/block-store.ts +31 -31
  23. package/src/blocks/block-types.ts +11 -11
  24. package/src/blocks/index.ts +5 -5
  25. package/src/blocks/structs.ts +17 -17
  26. package/src/btree/btree.ts +872 -872
  27. package/src/btree/independent-trunk.ts +53 -53
  28. package/src/btree/index.ts +5 -5
  29. package/src/btree/key-range.ts +15 -15
  30. package/src/btree/keyset.ts +6 -6
  31. package/src/btree/nodes.ts +25 -25
  32. package/src/btree/path.ts +37 -37
  33. package/src/btree/tree-block.ts +11 -11
  34. package/src/btree/trunk.ts +14 -14
  35. package/src/chain/chain-nodes.ts +26 -26
  36. package/src/chain/chain.ts +349 -349
  37. package/src/chain/index.ts +3 -3
  38. package/src/cluster/i-cluster.ts +6 -6
  39. package/src/cluster/index.ts +3 -3
  40. package/src/cluster/structs.ts +38 -0
  41. package/src/cohort-topic/addressing.ts +120 -120
  42. package/src/cohort-topic/antidos/bootstrap-evidence.ts +106 -106
  43. package/src/cohort-topic/antidos/index.ts +5 -5
  44. package/src/cohort-topic/antidos/rate-limiter.ts +210 -210
  45. package/src/cohort-topic/antidos/replay-guard.ts +146 -146
  46. package/src/cohort-topic/antidos/topic-budget.ts +160 -160
  47. package/src/cohort-topic/antiflood/index.ts +2 -2
  48. package/src/cohort-topic/antiflood/invariants.ts +108 -108
  49. package/src/cohort-topic/antiflood/jitter.ts +117 -117
  50. package/src/cohort-topic/coldstart.ts +237 -237
  51. package/src/cohort-topic/dmax.ts +88 -88
  52. package/src/cohort-topic/gossip/bus.ts +254 -254
  53. package/src/cohort-topic/gossip/index.ts +3 -3
  54. package/src/cohort-topic/gossip/records.ts +45 -45
  55. package/src/cohort-topic/gossip/view.ts +91 -91
  56. package/src/cohort-topic/index.ts +20 -20
  57. package/src/cohort-topic/load/barometer.ts +134 -134
  58. package/src/cohort-topic/load/index.ts +1 -1
  59. package/src/cohort-topic/member-engine.ts +430 -430
  60. package/src/cohort-topic/membership/index.ts +3 -3
  61. package/src/cohort-topic/membership/publisher.ts +163 -163
  62. package/src/cohort-topic/membership/source.ts +41 -41
  63. package/src/cohort-topic/ports.ts +157 -157
  64. package/src/cohort-topic/promotion.ts +477 -477
  65. package/src/cohort-topic/registration/bytes.ts +37 -37
  66. package/src/cohort-topic/registration/handoff.ts +154 -154
  67. package/src/cohort-topic/registration/index.ts +6 -6
  68. package/src/cohort-topic/registration/renewal.ts +495 -495
  69. package/src/cohort-topic/registration/sharding.ts +61 -61
  70. package/src/cohort-topic/registration/store.ts +81 -81
  71. package/src/cohort-topic/registration/types.ts +91 -91
  72. package/src/cohort-topic/ring-hash.ts +50 -50
  73. package/src/cohort-topic/service.ts +416 -416
  74. package/src/cohort-topic/sig/index.ts +2 -2
  75. package/src/cohort-topic/sig/payloads.ts +59 -59
  76. package/src/cohort-topic/sig/threshold.ts +64 -64
  77. package/src/cohort-topic/tiers.ts +74 -74
  78. package/src/cohort-topic/traffic.ts +233 -233
  79. package/src/cohort-topic/walk.ts +326 -326
  80. package/src/cohort-topic/willingness.ts +237 -237
  81. package/src/cohort-topic/wire/index.ts +18 -18
  82. package/src/cohort-topic/wire/payloads.ts +126 -126
  83. package/src/collection/action.ts +48 -48
  84. package/src/collection/collection-type-registry.ts +37 -37
  85. package/src/collection/collection.ts +2203 -2118
  86. package/src/collection/index.ts +4 -4
  87. package/src/collections/diary/index.ts +2 -2
  88. package/src/collections/diary/struct.ts +3 -3
  89. package/src/collections/index.ts +2 -2
  90. package/src/collections/tree/collection-trunk.ts +25 -25
  91. package/src/collections/tree/index.ts +2 -2
  92. package/src/collections/tree/readme.md +55 -55
  93. package/src/log/index.ts +2 -2
  94. package/src/log/log.ts +304 -268
  95. package/src/log/struct.ts +165 -165
  96. package/src/matchmaking/capability-filter.ts +45 -45
  97. package/src/matchmaking/config.ts +98 -98
  98. package/src/matchmaking/index.ts +21 -21
  99. package/src/matchmaking/multi-cohort-seeker.ts +234 -234
  100. package/src/matchmaking/provider.ts +123 -123
  101. package/src/matchmaking/query-eval.ts +105 -105
  102. package/src/matchmaking/seeker-walk.ts +127 -127
  103. package/src/matchmaking/seeker.ts +86 -86
  104. package/src/matchmaking/topic-anchor.ts +90 -90
  105. package/src/matchmaking/voting-quorum.ts +394 -394
  106. package/src/network/i-peer-network.ts +25 -25
  107. package/src/network/repo-protocol.ts +13 -13
  108. package/src/network/types.ts +37 -37
  109. package/src/reactivity/backfill.ts +220 -220
  110. package/src/reactivity/backpressure.ts +191 -191
  111. package/src/reactivity/checkpoint.ts +308 -308
  112. package/src/reactivity/config.ts +172 -172
  113. package/src/reactivity/dedupe.ts +132 -132
  114. package/src/reactivity/forwarder.ts +87 -87
  115. package/src/reactivity/index.ts +34 -34
  116. package/src/reactivity/notification.ts +123 -123
  117. package/src/reactivity/policy.ts +79 -79
  118. package/src/reactivity/push-state.ts +310 -310
  119. package/src/reactivity/recover.ts +153 -153
  120. package/src/reactivity/replay-buffer.ts +141 -141
  121. package/src/reactivity/resume.ts +549 -549
  122. package/src/reactivity/rotation.ts +415 -415
  123. package/src/reactivity/subscriber.ts +132 -132
  124. package/src/reactivity/subscription.ts +66 -66
  125. package/src/reactivity/topic-anchor.ts +71 -71
  126. package/src/reactivity/verify.ts +73 -73
  127. package/src/reactivity/wire-validate.ts +13 -13
  128. package/src/testing/async-wait.ts +65 -65
  129. package/src/testing/index.ts +2 -2
  130. package/src/testing/test-transactor.ts +62 -0
  131. package/src/transaction/actions-engine.ts +68 -68
  132. package/src/transaction/coordinator.ts +28 -11
  133. package/src/transaction/index.ts +52 -52
  134. package/src/transaction/operations-hash.ts +196 -196
  135. package/src/transaction/read-dependency-collector.ts +78 -78
  136. package/src/transaction/session.ts +238 -238
  137. package/src/transaction/transaction.ts +442 -442
  138. package/src/transaction/validator.ts +197 -197
  139. package/src/transactor/block-floors.ts +126 -126
  140. package/src/transactor/index.ts +6 -6
  141. package/src/transactor/network-transactor.ts +1545 -1545
  142. package/src/transform/atomic-proxy.ts +92 -92
  143. package/src/transform/cache-source.ts +370 -370
  144. package/src/transform/helpers.ts +164 -164
  145. package/src/transform/index.ts +7 -7
  146. package/src/transform/struct.ts +21 -21
  147. package/src/utility/actor.ts +62 -62
  148. package/src/utility/backoff.ts +95 -95
  149. package/src/utility/batch-coordinator.ts +191 -191
  150. package/src/utility/ensured.ts +32 -32
  151. package/src/utility/groupby.ts +18 -18
  152. package/src/utility/hash-string.ts +14 -14
  153. package/src/utility/is-record-empty.ts +5 -5
  154. package/src/utility/latches.ts +42 -42
  155. package/src/utility/lru-map.ts +60 -60
  156. package/src/utility/nameof.ts +7 -7
  157. package/src/utility/pending.ts +43 -43
@@ -1,78 +1,78 @@
1
- import type { BlockId, ReadPurpose } from "../blocks/index.js";
2
- import type { ReadDependency } from "./transaction.js";
3
-
4
- /** One captured read: the highest revision observed for the block, plus its {@link ReadPurpose}. */
5
- type ReadEntry = { revision: number; purpose: ReadPurpose };
6
-
7
- /** Accumulates the read dependencies of one transaction. Keyed by block id. For each id it keeps:
8
- *
9
- * - the HIGHEST revision observed (never downgrades — a re-read from cache must not overwrite a
10
- * higher revision seen earlier), and
11
- * - the read's PURPOSE with value-wins semantics: once a block is recorded as a `value` read from
12
- * ANY path it stays `value`; `navigation` sticks only for a block that was never read as a value.
13
- * This is the exact analogue of the max-wins rule on revision, and it makes the classification
14
- * order-independent (so it is deterministic regardless of cache/timing — required for the
15
- * transaction id and client signature to match across a re-executing validator; Theorem 4).
16
- *
17
- * {@link getReadDependencies} returns only the CONFLICT set (value reads); purely-structural
18
- * `navigation` reads — interior B-tree branches walked through to reach a captured leaf — are
19
- * dropped. See {@link markValue} and docs/correctness.md Theorem 5.
20
- *
21
- * One instance is shared by a collection's {@link TransactorSource} (direct structural reads —
22
- * bootstrap, header) and its {@link CacheSource} (every cache hit/miss), so a block read from
23
- * either layer produces a dependency. Because both feed the same collector, a cache miss records
24
- * the id once from each layer at the same revision/purpose; the merge collapses those to one
25
- * entry. Cleared at each txn boundary. */
26
- export class ReadDependencyCollector {
27
- private reads = new Map<BlockId, ReadEntry>();
28
-
29
- /** Record a read of `blockId` at `revision`. `purpose` defaults to `value` (retained); pass
30
- * `navigation` for an interior structural read that a later {@link markValue} may or may not
31
- * upgrade. Revision is max-wins; purpose is value-wins (see class doc). */
32
- record(blockId: BlockId, revision: number, purpose: ReadPurpose = 'value'): void {
33
- const prev = this.reads.get(blockId);
34
- if (prev === undefined) {
35
- this.reads.set(blockId, { revision, purpose });
36
- return;
37
- }
38
- if (revision > prev.revision) {
39
- prev.revision = revision;
40
- }
41
- // value-wins: a value read anywhere pins the block as value; navigation never downgrades it.
42
- if (purpose === 'value') {
43
- prev.purpose = 'value';
44
- }
45
- }
46
-
47
- /** Upgrade an already-recorded read to `value` (keeping its revision), retaining it in the
48
- * conflict set. The B-tree point-lookup path uses this to mark the terminal leaf — the
49
- * load-bearing read whose content the result depends on — after its interior descent nodes
50
- * were recorded as `navigation`. No-op if the id was never recorded (e.g. a leaf served from
51
- * an uncommitted staged insert, which records no dependency at all). */
52
- markValue(blockId: BlockId): void {
53
- const prev = this.reads.get(blockId);
54
- if (prev) {
55
- prev.purpose = 'value';
56
- }
57
- }
58
-
59
- /** The optimistic-concurrency conflict (read) set: every `value` read, with `navigation`
60
- * reads excluded. Dropping a covered navigation read cannot admit a lost update — any
61
- * concurrent change to the queried result also bumps a retained value read (the target
62
- * leaf) — but it removes the false-positive stale rejections that structural block reads
63
- * otherwise caused (Theorem 5 Bound). Deterministic in query shape, so a coordinator and a
64
- * re-executing validator derive the identical set. */
65
- getReadDependencies(): ReadDependency[] {
66
- const result: ReadDependency[] = [];
67
- for (const [blockId, entry] of this.reads) {
68
- if (entry.purpose === 'value') {
69
- result.push({ blockId, revision: entry.revision });
70
- }
71
- }
72
- return result;
73
- }
74
-
75
- clear(): void {
76
- this.reads.clear();
77
- }
78
- }
1
+ import type { BlockId, ReadPurpose } from "../blocks/index.js";
2
+ import type { ReadDependency } from "./transaction.js";
3
+
4
+ /** One captured read: the highest revision observed for the block, plus its {@link ReadPurpose}. */
5
+ type ReadEntry = { revision: number; purpose: ReadPurpose };
6
+
7
+ /** Accumulates the read dependencies of one transaction. Keyed by block id. For each id it keeps:
8
+ *
9
+ * - the HIGHEST revision observed (never downgrades — a re-read from cache must not overwrite a
10
+ * higher revision seen earlier), and
11
+ * - the read's PURPOSE with value-wins semantics: once a block is recorded as a `value` read from
12
+ * ANY path it stays `value`; `navigation` sticks only for a block that was never read as a value.
13
+ * This is the exact analogue of the max-wins rule on revision, and it makes the classification
14
+ * order-independent (so it is deterministic regardless of cache/timing — required for the
15
+ * transaction id and client signature to match across a re-executing validator; Theorem 4).
16
+ *
17
+ * {@link getReadDependencies} returns only the CONFLICT set (value reads); purely-structural
18
+ * `navigation` reads — interior B-tree branches walked through to reach a captured leaf — are
19
+ * dropped. See {@link markValue} and docs/correctness.md Theorem 5.
20
+ *
21
+ * One instance is shared by a collection's {@link TransactorSource} (direct structural reads —
22
+ * bootstrap, header) and its {@link CacheSource} (every cache hit/miss), so a block read from
23
+ * either layer produces a dependency. Because both feed the same collector, a cache miss records
24
+ * the id once from each layer at the same revision/purpose; the merge collapses those to one
25
+ * entry. Cleared at each txn boundary. */
26
+ export class ReadDependencyCollector {
27
+ private reads = new Map<BlockId, ReadEntry>();
28
+
29
+ /** Record a read of `blockId` at `revision`. `purpose` defaults to `value` (retained); pass
30
+ * `navigation` for an interior structural read that a later {@link markValue} may or may not
31
+ * upgrade. Revision is max-wins; purpose is value-wins (see class doc). */
32
+ record(blockId: BlockId, revision: number, purpose: ReadPurpose = 'value'): void {
33
+ const prev = this.reads.get(blockId);
34
+ if (prev === undefined) {
35
+ this.reads.set(blockId, { revision, purpose });
36
+ return;
37
+ }
38
+ if (revision > prev.revision) {
39
+ prev.revision = revision;
40
+ }
41
+ // value-wins: a value read anywhere pins the block as value; navigation never downgrades it.
42
+ if (purpose === 'value') {
43
+ prev.purpose = 'value';
44
+ }
45
+ }
46
+
47
+ /** Upgrade an already-recorded read to `value` (keeping its revision), retaining it in the
48
+ * conflict set. The B-tree point-lookup path uses this to mark the terminal leaf — the
49
+ * load-bearing read whose content the result depends on — after its interior descent nodes
50
+ * were recorded as `navigation`. No-op if the id was never recorded (e.g. a leaf served from
51
+ * an uncommitted staged insert, which records no dependency at all). */
52
+ markValue(blockId: BlockId): void {
53
+ const prev = this.reads.get(blockId);
54
+ if (prev) {
55
+ prev.purpose = 'value';
56
+ }
57
+ }
58
+
59
+ /** The optimistic-concurrency conflict (read) set: every `value` read, with `navigation`
60
+ * reads excluded. Dropping a covered navigation read cannot admit a lost update — any
61
+ * concurrent change to the queried result also bumps a retained value read (the target
62
+ * leaf) — but it removes the false-positive stale rejections that structural block reads
63
+ * otherwise caused (Theorem 5 Bound). Deterministic in query shape, so a coordinator and a
64
+ * re-executing validator derive the identical set. */
65
+ getReadDependencies(): ReadDependency[] {
66
+ const result: ReadDependency[] = [];
67
+ for (const [blockId, entry] of this.reads) {
68
+ if (entry.purpose === 'value') {
69
+ result.push({ blockId, revision: entry.revision });
70
+ }
71
+ }
72
+ return result;
73
+ }
74
+
75
+ clear(): void {
76
+ this.reads.clear();
77
+ }
78
+ }
@@ -1,238 +1,238 @@
1
- import type { TransactionCoordinator } from "./coordinator.js";
2
- import type { SyncOptions } from "../collection/index.js";
3
- import type { Transaction, ExecutionResult, ITransactionEngine, TransactionStamp, CollectionActions, TransactionSigner } from "./transaction.js";
4
- import { createTransactionStamp, createTransactionId, isTransactionExpired, clientSignaturePayload } from "./transaction.js";
5
-
6
- /**
7
- * TransactionSession manages incremental transaction building.
8
- *
9
- * This is the high-level API for building transactions incrementally:
10
- * - Stamp is created at BEGIN (stable throughout transaction)
11
- * - Execute statements one at a time
12
- * - Engine translates statements to actions (if not already provided)
13
- * - Actions are immediately applied to collections via coordinator.applyActions()
14
- * - On commit, all statements are compiled into a complete Transaction
15
- * - The Transaction is then committed through coordinator.commit() for PEND/COMMIT orchestration
16
- *
17
- * Usage:
18
- * const session = await TransactionSession.create(coordinator, engine);
19
- * await session.execute('INSERT INTO users (id, name) VALUES (?, ?)', [1, 'Alice']);
20
- * await session.execute('SELECT * FROM orders WHERE user_id = ?', [1]);
21
- * const result = await session.commit();
22
- *
23
- * For validation/replay, use engine.execute() directly with a complete Transaction.
24
- */
25
- export class TransactionSession {
26
- private readonly statements: string[] = [];
27
- private readonly stamp: TransactionStamp;
28
- private committed = false;
29
- private rolledBack = false;
30
-
31
- private constructor(
32
- private readonly coordinator: TransactionCoordinator,
33
- private readonly engine: ITransactionEngine,
34
- stamp: TransactionStamp,
35
- private readonly signer?: TransactionSigner
36
- ) {
37
- this.stamp = stamp;
38
- }
39
-
40
- /**
41
- * Create a new TransactionSession.
42
- * Uses async factory because stamp creation requires SHA-256 hashing.
43
- *
44
- * @param signer - Optional client signer. When supplied, commit() stamps the built
45
- * transaction's `signature` over its canonical payload; when omitted the
46
- * transaction is left unsigned (accepted only by nodes with no verifier wired).
47
- */
48
- static async create(
49
- coordinator: TransactionCoordinator,
50
- engine: ITransactionEngine,
51
- peerId: string = 'local',
52
- schemaHash: string = '',
53
- ttlMs?: number,
54
- signer?: TransactionSigner
55
- ): Promise<TransactionSession> {
56
- const stamp = await createTransactionStamp(
57
- peerId,
58
- Date.now(),
59
- schemaHash,
60
- engine.id,
61
- ttlMs
62
- );
63
- return new TransactionSession(coordinator, engine, stamp, signer);
64
- }
65
-
66
- /**
67
- * Execute a statement.
68
- *
69
- * If actions are provided, they are applied directly.
70
- * Otherwise, the engine translates the statement to actions.
71
- *
72
- * @param statement - The statement to execute (engine-specific, e.g., SQL statement)
73
- * @param actions - Optional pre-computed actions (for Quereus module case)
74
- * @returns Execution result with any returned values
75
- */
76
- async execute(statement: string, actions?: CollectionActions[]): Promise<{ success: boolean; error?: string }> {
77
- if (this.committed) {
78
- return { success: false, error: 'Transaction already committed' };
79
- }
80
- if (this.rolledBack) {
81
- return { success: false, error: 'Transaction already rolled back' };
82
- }
83
-
84
- try {
85
- // If actions not provided, enlist engine to translate statement
86
- let actionsToApply: CollectionActions[];
87
- if (actions) {
88
- actionsToApply = actions;
89
- } else {
90
- // Create a temporary transaction with just this statement for translation
91
- const tempTransaction: Transaction = {
92
- stamp: this.stamp,
93
- statements: [statement],
94
- reads: [],
95
- id: 'temp' // Temporary ID for translation only
96
- };
97
- const result = await this.engine.execute(tempTransaction);
98
- if (!result.success || !result.actions) {
99
- return { success: false, error: result.error || 'Failed to translate statement' };
100
- }
101
- actionsToApply = result.actions;
102
- }
103
-
104
- // Apply actions through coordinator
105
- await this.coordinator.applyActions(actionsToApply, this.stamp.id);
106
-
107
- // Accumulate the statement for later compilation
108
- this.statements.push(statement);
109
-
110
- return { success: true };
111
- } catch (error) {
112
- return {
113
- success: false,
114
- error: `Failed to execute statement: ${error instanceof Error ? error.message : String(error)}`
115
- };
116
- }
117
- }
118
-
119
- /**
120
- * Commit the transaction.
121
- *
122
- * Compiles all statements into a complete Transaction and commits through coordinator.
123
- *
124
- * @param options - Optional retry knobs forwarded to {@link TransactionCoordinator.commit}
125
- * (bounded backoff+jitter retry of a clean stale loss). Defaults are safe out of the box.
126
- */
127
- async commit(options?: SyncOptions): Promise<ExecutionResult> {
128
- if (this.committed) {
129
- return { success: false, error: 'Transaction already committed' };
130
- }
131
- if (this.rolledBack) {
132
- return { success: false, error: 'Transaction already rolled back' };
133
- }
134
- if (isTransactionExpired(this.stamp)) {
135
- return { success: false, error: `Transaction expired at ${this.stamp.expiration}` };
136
- }
137
-
138
- // Collect read dependencies from all participating collections
139
- const reads = this.coordinator.getReadDependencies();
140
-
141
- // Create the complete transaction
142
- const transaction: Transaction = {
143
- stamp: this.stamp,
144
- statements: this.statements,
145
- reads,
146
- id: await createTransactionId(this.stamp.id, this.statements, reads)
147
- };
148
-
149
- // Sign the canonical client-signature payload if a signer was supplied. The
150
- // payload covers stamp.id + statements + reads, which are all final now. A signer failure
151
- // (e.g. a wrong-key-type libp2p sign) is caught and surfaced as a clean commit failure BEFORE
152
- // coordinator.commit runs — the transaction object is local and discarded, so a failed sign can
153
- // never leak a partially-built unsigned transaction into consensus.
154
- if (this.signer) {
155
- const payload = clientSignaturePayload(this.stamp.id, this.statements, reads);
156
- try {
157
- transaction.signature = await this.signer(payload);
158
- } catch (error) {
159
- return {
160
- success: false,
161
- error: `Failed to sign transaction: ${error instanceof Error ? error.message : String(error)}`
162
- };
163
- }
164
- }
165
-
166
- // Commit through coordinator (which will orchestrate PEND/COMMIT, with bounded
167
- // backoff+jitter retry of a clean stale loss)
168
- await this.coordinator.commit(transaction, options);
169
-
170
- // Clear read dependencies after successful commit
171
- this.coordinator.clearReadDependencies();
172
-
173
- this.committed = true;
174
- return { success: true };
175
- }
176
-
177
- /**
178
- * Rollback the transaction (undo this session's applied actions).
179
- *
180
- * Delegates to coordinator.rollback(stampId), which restores each collection's staged
181
- * state — tracker transforms AND the pending action queue — to the pre-session snapshot.
182
- * That restore is coordinator-wide rather than session-scoped, which is safe because the
183
- * coordinator permits at most one open stamp: there is no concurrent session whose staged
184
- * state it could discard. Restoring both halves is what keeps this session's actions out
185
- * of the next transaction's durable log entry; see the snapshot contract on
186
- * TransactionCoordinator.stampData.
187
- */
188
- async rollback(): Promise<void> {
189
- if (this.committed) {
190
- throw new Error('Cannot rollback: transaction already committed');
191
- }
192
- if (this.rolledBack) {
193
- throw new Error('Transaction already rolled back');
194
- }
195
-
196
- // Rollback through coordinator
197
- await this.coordinator.rollback(this.stamp.id);
198
- this.coordinator.clearReadDependencies();
199
- this.rolledBack = true;
200
- this.statements.length = 0;
201
- }
202
-
203
- /**
204
- * Get the transaction stamp ID (stable throughout transaction).
205
- */
206
- getStampId(): string {
207
- return this.stamp.id;
208
- }
209
-
210
- /**
211
- * Get the transaction stamp (full metadata).
212
- */
213
- getStamp(): TransactionStamp {
214
- return this.stamp;
215
- }
216
-
217
- /**
218
- * Get the list of accumulated statements.
219
- */
220
- getStatements(): readonly string[] {
221
- return this.statements;
222
- }
223
-
224
- /**
225
- * Check if the transaction has been committed.
226
- */
227
- isCommitted(): boolean {
228
- return this.committed;
229
- }
230
-
231
- /**
232
- * Check if the transaction has been rolled back.
233
- */
234
- isRolledBack(): boolean {
235
- return this.rolledBack;
236
- }
237
- }
238
-
1
+ import type { TransactionCoordinator } from "./coordinator.js";
2
+ import type { SyncOptions } from "../collection/index.js";
3
+ import type { Transaction, ExecutionResult, ITransactionEngine, TransactionStamp, CollectionActions, TransactionSigner } from "./transaction.js";
4
+ import { createTransactionStamp, createTransactionId, isTransactionExpired, clientSignaturePayload } from "./transaction.js";
5
+
6
+ /**
7
+ * TransactionSession manages incremental transaction building.
8
+ *
9
+ * This is the high-level API for building transactions incrementally:
10
+ * - Stamp is created at BEGIN (stable throughout transaction)
11
+ * - Execute statements one at a time
12
+ * - Engine translates statements to actions (if not already provided)
13
+ * - Actions are immediately applied to collections via coordinator.applyActions()
14
+ * - On commit, all statements are compiled into a complete Transaction
15
+ * - The Transaction is then committed through coordinator.commit() for PEND/COMMIT orchestration
16
+ *
17
+ * Usage:
18
+ * const session = await TransactionSession.create(coordinator, engine);
19
+ * await session.execute('INSERT INTO users (id, name) VALUES (?, ?)', [1, 'Alice']);
20
+ * await session.execute('SELECT * FROM orders WHERE user_id = ?', [1]);
21
+ * const result = await session.commit();
22
+ *
23
+ * For validation/replay, use engine.execute() directly with a complete Transaction.
24
+ */
25
+ export class TransactionSession {
26
+ private readonly statements: string[] = [];
27
+ private readonly stamp: TransactionStamp;
28
+ private committed = false;
29
+ private rolledBack = false;
30
+
31
+ private constructor(
32
+ private readonly coordinator: TransactionCoordinator,
33
+ private readonly engine: ITransactionEngine,
34
+ stamp: TransactionStamp,
35
+ private readonly signer?: TransactionSigner
36
+ ) {
37
+ this.stamp = stamp;
38
+ }
39
+
40
+ /**
41
+ * Create a new TransactionSession.
42
+ * Uses async factory because stamp creation requires SHA-256 hashing.
43
+ *
44
+ * @param signer - Optional client signer. When supplied, commit() stamps the built
45
+ * transaction's `signature` over its canonical payload; when omitted the
46
+ * transaction is left unsigned (accepted only by nodes with no verifier wired).
47
+ */
48
+ static async create(
49
+ coordinator: TransactionCoordinator,
50
+ engine: ITransactionEngine,
51
+ peerId: string = 'local',
52
+ schemaHash: string = '',
53
+ ttlMs?: number,
54
+ signer?: TransactionSigner
55
+ ): Promise<TransactionSession> {
56
+ const stamp = await createTransactionStamp(
57
+ peerId,
58
+ Date.now(),
59
+ schemaHash,
60
+ engine.id,
61
+ ttlMs
62
+ );
63
+ return new TransactionSession(coordinator, engine, stamp, signer);
64
+ }
65
+
66
+ /**
67
+ * Execute a statement.
68
+ *
69
+ * If actions are provided, they are applied directly.
70
+ * Otherwise, the engine translates the statement to actions.
71
+ *
72
+ * @param statement - The statement to execute (engine-specific, e.g., SQL statement)
73
+ * @param actions - Optional pre-computed actions (for Quereus module case)
74
+ * @returns Execution result with any returned values
75
+ */
76
+ async execute(statement: string, actions?: CollectionActions[]): Promise<{ success: boolean; error?: string }> {
77
+ if (this.committed) {
78
+ return { success: false, error: 'Transaction already committed' };
79
+ }
80
+ if (this.rolledBack) {
81
+ return { success: false, error: 'Transaction already rolled back' };
82
+ }
83
+
84
+ try {
85
+ // If actions not provided, enlist engine to translate statement
86
+ let actionsToApply: CollectionActions[];
87
+ if (actions) {
88
+ actionsToApply = actions;
89
+ } else {
90
+ // Create a temporary transaction with just this statement for translation
91
+ const tempTransaction: Transaction = {
92
+ stamp: this.stamp,
93
+ statements: [statement],
94
+ reads: [],
95
+ id: 'temp' // Temporary ID for translation only
96
+ };
97
+ const result = await this.engine.execute(tempTransaction);
98
+ if (!result.success || !result.actions) {
99
+ return { success: false, error: result.error || 'Failed to translate statement' };
100
+ }
101
+ actionsToApply = result.actions;
102
+ }
103
+
104
+ // Apply actions through coordinator
105
+ await this.coordinator.applyActions(actionsToApply, this.stamp.id);
106
+
107
+ // Accumulate the statement for later compilation
108
+ this.statements.push(statement);
109
+
110
+ return { success: true };
111
+ } catch (error) {
112
+ return {
113
+ success: false,
114
+ error: `Failed to execute statement: ${error instanceof Error ? error.message : String(error)}`
115
+ };
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Commit the transaction.
121
+ *
122
+ * Compiles all statements into a complete Transaction and commits through coordinator.
123
+ *
124
+ * @param options - Optional retry knobs forwarded to {@link TransactionCoordinator.commit}
125
+ * (bounded backoff+jitter retry of a clean stale loss). Defaults are safe out of the box.
126
+ */
127
+ async commit(options?: SyncOptions): Promise<ExecutionResult> {
128
+ if (this.committed) {
129
+ return { success: false, error: 'Transaction already committed' };
130
+ }
131
+ if (this.rolledBack) {
132
+ return { success: false, error: 'Transaction already rolled back' };
133
+ }
134
+ if (isTransactionExpired(this.stamp)) {
135
+ return { success: false, error: `Transaction expired at ${this.stamp.expiration}` };
136
+ }
137
+
138
+ // Collect read dependencies from all participating collections
139
+ const reads = this.coordinator.getReadDependencies();
140
+
141
+ // Create the complete transaction
142
+ const transaction: Transaction = {
143
+ stamp: this.stamp,
144
+ statements: this.statements,
145
+ reads,
146
+ id: await createTransactionId(this.stamp.id, this.statements, reads)
147
+ };
148
+
149
+ // Sign the canonical client-signature payload if a signer was supplied. The
150
+ // payload covers stamp.id + statements + reads, which are all final now. A signer failure
151
+ // (e.g. a wrong-key-type libp2p sign) is caught and surfaced as a clean commit failure BEFORE
152
+ // coordinator.commit runs — the transaction object is local and discarded, so a failed sign can
153
+ // never leak a partially-built unsigned transaction into consensus.
154
+ if (this.signer) {
155
+ const payload = clientSignaturePayload(this.stamp.id, this.statements, reads);
156
+ try {
157
+ transaction.signature = await this.signer(payload);
158
+ } catch (error) {
159
+ return {
160
+ success: false,
161
+ error: `Failed to sign transaction: ${error instanceof Error ? error.message : String(error)}`
162
+ };
163
+ }
164
+ }
165
+
166
+ // Commit through coordinator (which will orchestrate PEND/COMMIT, with bounded
167
+ // backoff+jitter retry of a clean stale loss)
168
+ await this.coordinator.commit(transaction, options);
169
+
170
+ // Clear read dependencies after successful commit
171
+ this.coordinator.clearReadDependencies();
172
+
173
+ this.committed = true;
174
+ return { success: true };
175
+ }
176
+
177
+ /**
178
+ * Rollback the transaction (undo this session's applied actions).
179
+ *
180
+ * Delegates to coordinator.rollback(stampId), which restores each collection's staged
181
+ * state — tracker transforms AND the pending action queue — to the pre-session snapshot.
182
+ * That restore is coordinator-wide rather than session-scoped, which is safe because the
183
+ * coordinator permits at most one open stamp: there is no concurrent session whose staged
184
+ * state it could discard. Restoring both halves is what keeps this session's actions out
185
+ * of the next transaction's durable log entry; see the snapshot contract on
186
+ * TransactionCoordinator.stampData.
187
+ */
188
+ async rollback(): Promise<void> {
189
+ if (this.committed) {
190
+ throw new Error('Cannot rollback: transaction already committed');
191
+ }
192
+ if (this.rolledBack) {
193
+ throw new Error('Transaction already rolled back');
194
+ }
195
+
196
+ // Rollback through coordinator
197
+ await this.coordinator.rollback(this.stamp.id);
198
+ this.coordinator.clearReadDependencies();
199
+ this.rolledBack = true;
200
+ this.statements.length = 0;
201
+ }
202
+
203
+ /**
204
+ * Get the transaction stamp ID (stable throughout transaction).
205
+ */
206
+ getStampId(): string {
207
+ return this.stamp.id;
208
+ }
209
+
210
+ /**
211
+ * Get the transaction stamp (full metadata).
212
+ */
213
+ getStamp(): TransactionStamp {
214
+ return this.stamp;
215
+ }
216
+
217
+ /**
218
+ * Get the list of accumulated statements.
219
+ */
220
+ getStatements(): readonly string[] {
221
+ return this.statements;
222
+ }
223
+
224
+ /**
225
+ * Check if the transaction has been committed.
226
+ */
227
+ isCommitted(): boolean {
228
+ return this.committed;
229
+ }
230
+
231
+ /**
232
+ * Check if the transaction has been rolled back.
233
+ */
234
+ isRolledBack(): boolean {
235
+ return this.rolledBack;
236
+ }
237
+ }
238
+