@totemsdk/edge-adapters 0.1.1 → 0.2.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.
- package/dist/artifact-cache.d.ts +36 -0
- package/dist/artifact-cache.js +82 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +15 -1
- package/dist/liquidity.d.ts +1 -1
- package/dist/liquidity.js +1 -1
- package/dist/negotiation-transport.d.ts +50 -0
- package/dist/negotiation-transport.js +122 -0
- package/dist/payment-l1.d.ts +1 -1
- package/dist/purchase-authority.d.ts +42 -0
- package/dist/purchase-authority.js +79 -0
- package/dist/purchase-lookup.d.ts +44 -0
- package/dist/purchase-lookup.js +60 -0
- package/dist/purchase-payment.d.ts +78 -0
- package/dist/purchase-payment.js +108 -0
- package/dist/sqlite-commerce-store.d.ts +69 -0
- package/dist/sqlite-commerce-store.js +416 -0
- package/package.json +32 -27
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* purchase-payment.ts — PurchasePaymentPort adapter with an atomic claim.
|
|
3
|
+
*
|
|
4
|
+
* Wraps any EdgePaymentPort (L1 Minima, L2 Omnia, hosted) and adds a stable
|
|
5
|
+
* idempotency-key claim so a retry after a lost response never double-pays.
|
|
6
|
+
*
|
|
7
|
+
* The idempotency key is the stable purchase operation identity
|
|
8
|
+
* (`purchaseId:agreementId:payment`) supplied by the purchasing layer. The
|
|
9
|
+
* wrapper records an atomic pending marker (claim) *before* it invokes the
|
|
10
|
+
* underlying payment port; only the caller that wins the claim pays. A retry
|
|
11
|
+
* with the same key returns the prior result without re-invoking the port, and
|
|
12
|
+
* a concurrent duplicate never double-pays — it either replays the completed
|
|
13
|
+
* outcome or surfaces `PAYMENT_STATE_UNKNOWN` for an in-flight claim.
|
|
14
|
+
*
|
|
15
|
+
* Final exactly-once still depends on the payment system's own reconciliation:
|
|
16
|
+
* if the process dies between the port accepting the payment and the outcome
|
|
17
|
+
* being recorded, the key stays `pending`, and retries return
|
|
18
|
+
* `PAYMENT_STATE_UNKNOWN` rather than risking a second payment. The owner
|
|
19
|
+
* reconciles that window against the payment ledger.
|
|
20
|
+
*/
|
|
21
|
+
import type { EdgeOperationResult } from '@totemsdk/edge';
|
|
22
|
+
import { type CasStore, type StorageAdapterWithCapabilities, type WriteAckMode } from '@totemsdk/storage';
|
|
23
|
+
export interface PaymentResult {
|
|
24
|
+
txpowId?: string;
|
|
25
|
+
}
|
|
26
|
+
export interface PaymentPortLike {
|
|
27
|
+
pay(params: {
|
|
28
|
+
recipient: string;
|
|
29
|
+
amount: string;
|
|
30
|
+
tokenId?: string;
|
|
31
|
+
memo?: string;
|
|
32
|
+
idempotencyKey?: string;
|
|
33
|
+
}): Promise<EdgeOperationResult<PaymentResult>>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Idempotency claim record. `pending` is written atomically before the port
|
|
37
|
+
* call; `completed` records the outcome. A `pending` key is never re-claimed
|
|
38
|
+
* automatically — that is the double-pay guard.
|
|
39
|
+
*/
|
|
40
|
+
export type PurchasePaymentClaimRecord = {
|
|
41
|
+
phase: 'pending';
|
|
42
|
+
claimedAt: number;
|
|
43
|
+
} | {
|
|
44
|
+
phase: 'completed';
|
|
45
|
+
result: EdgeOperationResult<PaymentResult>;
|
|
46
|
+
completedAt: number;
|
|
47
|
+
};
|
|
48
|
+
/** The durable idempotency store must support conditional (CAS) writes. */
|
|
49
|
+
export type PurchasePaymentStore = StorageAdapterWithCapabilities & CasStore;
|
|
50
|
+
export interface PurchasePaymentAdapterConfig {
|
|
51
|
+
/** The underlying payment port (L1/L2/hosted). */
|
|
52
|
+
port: PaymentPortLike;
|
|
53
|
+
/**
|
|
54
|
+
* Optional claim store. When omitted, a dev in-memory store is used (no
|
|
55
|
+
* crash guarantees and no cross-instance dedup). A durable CAS-capable
|
|
56
|
+
* store (e.g. a `@totemsdk/storage` FileStore/SqliteStore) makes retries
|
|
57
|
+
* safe across restarts and processes. No silent downgrade: a supplied
|
|
58
|
+
* store is asserted CAS-capable and `durably-acknowledged` unless
|
|
59
|
+
* `requireAckMode` opts into a weaker acknowledgment.
|
|
60
|
+
*/
|
|
61
|
+
store?: PurchasePaymentStore;
|
|
62
|
+
/** Key namespace prefix; default `totem_payment:v1:`. */
|
|
63
|
+
namespace?: string;
|
|
64
|
+
/** Required write acknowledgment for a supplied store; default `durably-acknowledged`. */
|
|
65
|
+
requireAckMode?: WriteAckMode;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Create a PurchasePaymentPort with an atomic idempotency-key claim.
|
|
69
|
+
*/
|
|
70
|
+
export declare function createPurchasePaymentAdapter(config: PurchasePaymentAdapterConfig): {
|
|
71
|
+
pay(params: {
|
|
72
|
+
recipient: string;
|
|
73
|
+
amount: string;
|
|
74
|
+
tokenId?: string;
|
|
75
|
+
memo?: string;
|
|
76
|
+
idempotencyKey?: string;
|
|
77
|
+
}): Promise<EdgeOperationResult<PaymentResult>>;
|
|
78
|
+
};
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* purchase-payment.ts — PurchasePaymentPort adapter with an atomic claim.
|
|
4
|
+
*
|
|
5
|
+
* Wraps any EdgePaymentPort (L1 Minima, L2 Omnia, hosted) and adds a stable
|
|
6
|
+
* idempotency-key claim so a retry after a lost response never double-pays.
|
|
7
|
+
*
|
|
8
|
+
* The idempotency key is the stable purchase operation identity
|
|
9
|
+
* (`purchaseId:agreementId:payment`) supplied by the purchasing layer. The
|
|
10
|
+
* wrapper records an atomic pending marker (claim) *before* it invokes the
|
|
11
|
+
* underlying payment port; only the caller that wins the claim pays. A retry
|
|
12
|
+
* with the same key returns the prior result without re-invoking the port, and
|
|
13
|
+
* a concurrent duplicate never double-pays — it either replays the completed
|
|
14
|
+
* outcome or surfaces `PAYMENT_STATE_UNKNOWN` for an in-flight claim.
|
|
15
|
+
*
|
|
16
|
+
* Final exactly-once still depends on the payment system's own reconciliation:
|
|
17
|
+
* if the process dies between the port accepting the payment and the outcome
|
|
18
|
+
* being recorded, the key stays `pending`, and retries return
|
|
19
|
+
* `PAYMENT_STATE_UNKNOWN` rather than risking a second payment. The owner
|
|
20
|
+
* reconciles that window against the payment ledger.
|
|
21
|
+
*/
|
|
22
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
+
exports.createPurchasePaymentAdapter = createPurchasePaymentAdapter;
|
|
24
|
+
const storage_1 = require("@totemsdk/storage");
|
|
25
|
+
const DEFAULT_NAMESPACE = 'totem_payment:v1:';
|
|
26
|
+
/** In-process serialization so concurrent claims never double-pay on one store. */
|
|
27
|
+
const locks = new WeakMap();
|
|
28
|
+
function withPaymentLock(store, fn) {
|
|
29
|
+
const tail = locks.get(store);
|
|
30
|
+
const next = tail ? tail.then(fn, fn) : fn();
|
|
31
|
+
const settled = next.catch(() => undefined);
|
|
32
|
+
locks.set(store, settled);
|
|
33
|
+
return next;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Create a PurchasePaymentPort with an atomic idempotency-key claim.
|
|
37
|
+
*/
|
|
38
|
+
function createPurchasePaymentAdapter(config) {
|
|
39
|
+
const { port } = config;
|
|
40
|
+
const namespace = config.namespace ?? DEFAULT_NAMESPACE;
|
|
41
|
+
const store = config.store ??
|
|
42
|
+
new storage_1.MemoryStore(); // dev mode — volatile, process-local
|
|
43
|
+
if (config.store) {
|
|
44
|
+
// No silent downgrade: a consumer-supplied store must be able to claim
|
|
45
|
+
// (CAS) and acknowledge durable writes unless explicitly opted out.
|
|
46
|
+
(0, storage_1.assertCapabilities)(store, {
|
|
47
|
+
conditional: true,
|
|
48
|
+
acknowledge: config.requireAckMode ?? 'durably-acknowledged',
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const keyFor = (idempotencyKey) => namespace + idempotencyKey;
|
|
52
|
+
return {
|
|
53
|
+
async pay(params) {
|
|
54
|
+
const key = params.idempotencyKey;
|
|
55
|
+
if (!key) {
|
|
56
|
+
// No idempotency possible without a stable key — pass straight through.
|
|
57
|
+
return port.pay(params);
|
|
58
|
+
}
|
|
59
|
+
// The whole claim→pay→complete path is serialized per store so that N
|
|
60
|
+
// concurrent same-key callers resolve consistently: the winner pays, and
|
|
61
|
+
// every loser replays the completed outcome rather than racing the
|
|
62
|
+
// in-flight window.
|
|
63
|
+
return withPaymentLock(store, async () => {
|
|
64
|
+
const claimKey = keyFor(key);
|
|
65
|
+
// Atomic claim: exactly one caller wins `pending`; concurrent duplicates
|
|
66
|
+
// either replay a completed outcome or get PAYMENT_STATE_UNKNOWN.
|
|
67
|
+
const claim = await store.conditionalUpdate(claimKey, (current) => {
|
|
68
|
+
if (current === null || current === undefined) {
|
|
69
|
+
return { next: { phase: 'pending', claimedAt: Date.now() } };
|
|
70
|
+
}
|
|
71
|
+
return { abort: 'already-claimed' };
|
|
72
|
+
});
|
|
73
|
+
if (!claim.applied) {
|
|
74
|
+
const existing = await store.get(claimKey);
|
|
75
|
+
if (existing && existing.phase === 'completed') {
|
|
76
|
+
return existing.result;
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
ok: false,
|
|
80
|
+
errorCode: 'PAYMENT_STATE_UNKNOWN',
|
|
81
|
+
error: `payment for idempotency key '${key}' is already in flight`,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
let result;
|
|
85
|
+
try {
|
|
86
|
+
result = await port.pay(params);
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
result = {
|
|
90
|
+
ok: false,
|
|
91
|
+
errorCode: 'PAYMENT_STATE_UNKNOWN',
|
|
92
|
+
error: `payment port threw: ${err.message}`,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
// Record the outcome only if we still own the pending claim.
|
|
96
|
+
await store.conditionalUpdate(claimKey, (current) => {
|
|
97
|
+
if (current !== null && current !== undefined && current.phase === 'pending') {
|
|
98
|
+
return {
|
|
99
|
+
next: { phase: 'completed', result, completedAt: Date.now() },
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
return { abort: 'gone' };
|
|
103
|
+
});
|
|
104
|
+
return result;
|
|
105
|
+
});
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sqlite-commerce-store.ts — Production SQLite-backed CommerceStore.
|
|
3
|
+
*
|
|
4
|
+
* Implements the five durable commerce contracts over ONE SQLite database:
|
|
5
|
+
* NegotiationStore, PurchaseStore, ReplayLedger, PrincipalNegotiationStore,
|
|
6
|
+
* OutboxStore.
|
|
7
|
+
*
|
|
8
|
+
* The database connection, journal/busy pragmas, transaction lifecycle, and
|
|
9
|
+
* CAS kinematics are owned by the shared `SqliteStore` primitive from
|
|
10
|
+
* `@totemsdk/storage/sqlite` (RFC-007 §4.2). All consumer mutations run through
|
|
11
|
+
* `transactionalSync` (atomic multi-statement batches) or the generalized
|
|
12
|
+
* `transitionAndEnqueue` (revision-CAS update + outbox-style enqueue in one
|
|
13
|
+
* commit). Table schemas and row shapes are unchanged ("records unchanged in
|
|
14
|
+
* shape").
|
|
15
|
+
*
|
|
16
|
+
* The critical guarantee — `transitionAndEnqueue` (negotiation CAS + outbox
|
|
17
|
+
* enqueue) — maps to ONE transaction on the shared primitive:
|
|
18
|
+
*
|
|
19
|
+
* BEGIN
|
|
20
|
+
* UPDATE negotiations SET ... WHERE negotiation_id=? AND revision=?
|
|
21
|
+
* INSERT INTO outbox (...) VALUES (...)
|
|
22
|
+
* COMMIT (or ROLLBACK on CAS miss — nothing is enqueued)
|
|
23
|
+
*
|
|
24
|
+
* Uses WAL mode + busy_timeout for concurrent runtime use. Does NOT persist
|
|
25
|
+
* private keys — only stable references/IDs.
|
|
26
|
+
*
|
|
27
|
+
* All statements use positional `?` parameters so the same SQL runs on the
|
|
28
|
+
* real better-sqlite3 native binding and the node:sqlite jest mock.
|
|
29
|
+
*/
|
|
30
|
+
import type { NegotiationStore, PrincipalNegotiationStore, PurchaseStore } from '@totemsdk/edge';
|
|
31
|
+
import type { ReplayLedger } from '@totemsdk/edge';
|
|
32
|
+
import type { OutboxStore } from '@totemsdk/edge';
|
|
33
|
+
/** Aggregated durable commerce store. */
|
|
34
|
+
export interface CommerceStore {
|
|
35
|
+
negotiations: NegotiationStore;
|
|
36
|
+
purchases: PurchaseStore;
|
|
37
|
+
replay: ReplayLedger;
|
|
38
|
+
principals: PrincipalNegotiationStore;
|
|
39
|
+
outbox: OutboxStore;
|
|
40
|
+
}
|
|
41
|
+
export interface SQLiteCommerceStoreConfig {
|
|
42
|
+
/** File path, or ':memory:' for ephemeral. */
|
|
43
|
+
filename: string;
|
|
44
|
+
/** WAL mode (default true). */
|
|
45
|
+
wal?: boolean;
|
|
46
|
+
/** Busy timeout ms (default 5000). */
|
|
47
|
+
busyTimeoutMs?: number;
|
|
48
|
+
}
|
|
49
|
+
export declare class SQLiteCommerceStore implements CommerceStore {
|
|
50
|
+
readonly negotiations: NegotiationStore;
|
|
51
|
+
readonly purchases: PurchaseStore;
|
|
52
|
+
readonly replay: ReplayLedger;
|
|
53
|
+
readonly principals: PrincipalNegotiationStore;
|
|
54
|
+
readonly outbox: OutboxStore;
|
|
55
|
+
private readonly store;
|
|
56
|
+
constructor(config: SQLiteCommerceStoreConfig);
|
|
57
|
+
close(): void;
|
|
58
|
+
private createNegotiationStore;
|
|
59
|
+
private createPurchaseStore;
|
|
60
|
+
private createReplayLedger;
|
|
61
|
+
private createPrincipalStore;
|
|
62
|
+
private createOutboxStore;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Create a SQLite-backed CommerceStore.
|
|
66
|
+
*
|
|
67
|
+
* @param config filename (or ':memory:') + WAL/busy options.
|
|
68
|
+
*/
|
|
69
|
+
export declare function createSQLiteCommerceStore(config: SQLiteCommerceStoreConfig): SQLiteCommerceStore;
|
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* sqlite-commerce-store.ts — Production SQLite-backed CommerceStore.
|
|
4
|
+
*
|
|
5
|
+
* Implements the five durable commerce contracts over ONE SQLite database:
|
|
6
|
+
* NegotiationStore, PurchaseStore, ReplayLedger, PrincipalNegotiationStore,
|
|
7
|
+
* OutboxStore.
|
|
8
|
+
*
|
|
9
|
+
* The database connection, journal/busy pragmas, transaction lifecycle, and
|
|
10
|
+
* CAS kinematics are owned by the shared `SqliteStore` primitive from
|
|
11
|
+
* `@totemsdk/storage/sqlite` (RFC-007 §4.2). All consumer mutations run through
|
|
12
|
+
* `transactionalSync` (atomic multi-statement batches) or the generalized
|
|
13
|
+
* `transitionAndEnqueue` (revision-CAS update + outbox-style enqueue in one
|
|
14
|
+
* commit). Table schemas and row shapes are unchanged ("records unchanged in
|
|
15
|
+
* shape").
|
|
16
|
+
*
|
|
17
|
+
* The critical guarantee — `transitionAndEnqueue` (negotiation CAS + outbox
|
|
18
|
+
* enqueue) — maps to ONE transaction on the shared primitive:
|
|
19
|
+
*
|
|
20
|
+
* BEGIN
|
|
21
|
+
* UPDATE negotiations SET ... WHERE negotiation_id=? AND revision=?
|
|
22
|
+
* INSERT INTO outbox (...) VALUES (...)
|
|
23
|
+
* COMMIT (or ROLLBACK on CAS miss — nothing is enqueued)
|
|
24
|
+
*
|
|
25
|
+
* Uses WAL mode + busy_timeout for concurrent runtime use. Does NOT persist
|
|
26
|
+
* private keys — only stable references/IDs.
|
|
27
|
+
*
|
|
28
|
+
* All statements use positional `?` parameters so the same SQL runs on the
|
|
29
|
+
* real better-sqlite3 native binding and the node:sqlite jest mock.
|
|
30
|
+
*/
|
|
31
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
32
|
+
exports.SQLiteCommerceStore = void 0;
|
|
33
|
+
exports.createSQLiteCommerceStore = createSQLiteCommerceStore;
|
|
34
|
+
const sqlite_1 = require("@totemsdk/storage/sqlite");
|
|
35
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
36
|
+
// Serialization helpers
|
|
37
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
38
|
+
function toJson(value) {
|
|
39
|
+
return JSON.stringify(value, (_key, v) => (typeof v === 'bigint' ? v.toString() : v));
|
|
40
|
+
}
|
|
41
|
+
function fromJson(json) {
|
|
42
|
+
return JSON.parse(json);
|
|
43
|
+
}
|
|
44
|
+
/** Reconstruct a NegotiationRecord, restoring bigint fields. */
|
|
45
|
+
function rowToNegotiation(row) {
|
|
46
|
+
const record = fromJson(row.record_json);
|
|
47
|
+
return {
|
|
48
|
+
...record,
|
|
49
|
+
cumulativeWork: BigInt(String(record.cumulativeWork ?? '0')),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function negotiationToRow(record) {
|
|
53
|
+
return {
|
|
54
|
+
negotiation_id: record.negotiationId,
|
|
55
|
+
record_json: toJson(record),
|
|
56
|
+
revision: record.revision,
|
|
57
|
+
state: record.state,
|
|
58
|
+
principal: record.principal,
|
|
59
|
+
updated_at: record.updatedAt,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function rowToPurchase(row) {
|
|
63
|
+
return fromJson(row.record_json);
|
|
64
|
+
}
|
|
65
|
+
function purchaseToRow(record) {
|
|
66
|
+
return {
|
|
67
|
+
purchase_id: record.purchaseId,
|
|
68
|
+
record_json: toJson(record),
|
|
69
|
+
revision: record.revision,
|
|
70
|
+
status: record.status,
|
|
71
|
+
updated_at: record.updatedAt,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function rowToReplay(row) {
|
|
75
|
+
if (row.state === 'COMPLETED') {
|
|
76
|
+
return {
|
|
77
|
+
state: 'COMPLETED',
|
|
78
|
+
outcome: fromJson(row.outcome_json ?? '{}'),
|
|
79
|
+
completedAt: row.completed_at ?? 0,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
state: 'PROCESSING',
|
|
84
|
+
claimedAt: row.claimed_at,
|
|
85
|
+
...(row.lease_until !== null ? { leaseUntil: row.lease_until } : {}),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function rowToOutbox(row) {
|
|
89
|
+
return {
|
|
90
|
+
messageId: row.message_id,
|
|
91
|
+
recipient: row.recipient,
|
|
92
|
+
message: fromJson(row.payload),
|
|
93
|
+
enqueuedAt: row.enqueued_at,
|
|
94
|
+
...(row.delivered_at !== null ? { deliveredAt: row.delivered_at } : {}),
|
|
95
|
+
attempts: row.attempts,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
99
|
+
// Schema (unchanged — "records unchanged in shape")
|
|
100
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
101
|
+
const SCHEMA = `
|
|
102
|
+
CREATE TABLE IF NOT EXISTS negotiations (
|
|
103
|
+
negotiation_id TEXT PRIMARY KEY,
|
|
104
|
+
record_json TEXT NOT NULL,
|
|
105
|
+
revision INTEGER NOT NULL,
|
|
106
|
+
state TEXT NOT NULL,
|
|
107
|
+
principal TEXT NOT NULL,
|
|
108
|
+
updated_at INTEGER NOT NULL
|
|
109
|
+
);
|
|
110
|
+
CREATE INDEX IF NOT EXISTS idx_negotiations_principal ON negotiations(principal);
|
|
111
|
+
CREATE INDEX IF NOT EXISTS idx_negotiations_state ON negotiations(state);
|
|
112
|
+
|
|
113
|
+
CREATE TABLE IF NOT EXISTS purchases (
|
|
114
|
+
purchase_id TEXT PRIMARY KEY,
|
|
115
|
+
record_json TEXT NOT NULL,
|
|
116
|
+
revision INTEGER NOT NULL,
|
|
117
|
+
status TEXT NOT NULL,
|
|
118
|
+
updated_at INTEGER NOT NULL
|
|
119
|
+
);
|
|
120
|
+
CREATE INDEX IF NOT EXISTS idx_purchases_status ON purchases(status);
|
|
121
|
+
|
|
122
|
+
CREATE TABLE IF NOT EXISTS replay (
|
|
123
|
+
message_id TEXT PRIMARY KEY,
|
|
124
|
+
state TEXT NOT NULL,
|
|
125
|
+
claimed_at INTEGER NOT NULL,
|
|
126
|
+
lease_until INTEGER,
|
|
127
|
+
outcome_json TEXT,
|
|
128
|
+
completed_at INTEGER
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
CREATE TABLE IF NOT EXISTS principal_slots (
|
|
132
|
+
principal TEXT NOT NULL,
|
|
133
|
+
negotiation_id TEXT NOT NULL,
|
|
134
|
+
opened_at INTEGER NOT NULL,
|
|
135
|
+
PRIMARY KEY (principal, negotiation_id)
|
|
136
|
+
);
|
|
137
|
+
CREATE INDEX IF NOT EXISTS idx_principal_slots_principal ON principal_slots(principal);
|
|
138
|
+
|
|
139
|
+
CREATE TABLE IF NOT EXISTS principal_cooldown (
|
|
140
|
+
principal TEXT PRIMARY KEY,
|
|
141
|
+
cooldown_until INTEGER NOT NULL
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
CREATE TABLE IF NOT EXISTS outbox (
|
|
145
|
+
message_id TEXT PRIMARY KEY,
|
|
146
|
+
recipient TEXT NOT NULL,
|
|
147
|
+
payload TEXT NOT NULL,
|
|
148
|
+
enqueued_at INTEGER NOT NULL,
|
|
149
|
+
delivered_at INTEGER,
|
|
150
|
+
attempts INTEGER NOT NULL DEFAULT 0
|
|
151
|
+
);
|
|
152
|
+
CREATE INDEX IF NOT EXISTS idx_outbox_undelivered ON outbox(delivered_at);
|
|
153
|
+
`;
|
|
154
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
155
|
+
// SQLite CommerceStore
|
|
156
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
157
|
+
class SQLiteCommerceStore {
|
|
158
|
+
constructor(config) {
|
|
159
|
+
this.store = new sqlite_1.SqliteStore(config.filename, {
|
|
160
|
+
createKvTable: false,
|
|
161
|
+
wal: config.wal,
|
|
162
|
+
busyTimeoutMs: config.busyTimeoutMs ?? 5000,
|
|
163
|
+
});
|
|
164
|
+
this.store.transactionalSync((tx) => tx.exec(SCHEMA));
|
|
165
|
+
this.negotiations = this.createNegotiationStore();
|
|
166
|
+
this.purchases = this.createPurchaseStore();
|
|
167
|
+
this.replay = this.createReplayLedger();
|
|
168
|
+
this.principals = this.createPrincipalStore();
|
|
169
|
+
this.outbox = this.createOutboxStore();
|
|
170
|
+
}
|
|
171
|
+
close() {
|
|
172
|
+
void this.store.close();
|
|
173
|
+
}
|
|
174
|
+
// ── NegotiationStore ──────────────────────────────────────────────────────
|
|
175
|
+
createNegotiationStore() {
|
|
176
|
+
const store = this.store;
|
|
177
|
+
const INSERT_SQL = `
|
|
178
|
+
INSERT INTO negotiations (negotiation_id, record_json, revision, state, principal, updated_at)
|
|
179
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
180
|
+
`;
|
|
181
|
+
const GET_SQL = `SELECT * FROM negotiations WHERE negotiation_id = ?`;
|
|
182
|
+
const CAS_SQL = `
|
|
183
|
+
UPDATE negotiations
|
|
184
|
+
SET record_json = ?, revision = ?, state = ?, updated_at = ?
|
|
185
|
+
WHERE negotiation_id = ? AND revision = ?
|
|
186
|
+
`;
|
|
187
|
+
const LIST_RECOVERABLE_SQL = `
|
|
188
|
+
SELECT * FROM negotiations WHERE state NOT IN ('AGREED','REJECTED','CANCELLED','EXHAUSTED','EXPIRED')
|
|
189
|
+
`;
|
|
190
|
+
return {
|
|
191
|
+
async create(record) {
|
|
192
|
+
const row = negotiationToRow(record);
|
|
193
|
+
store.transactionalSync((tx) => {
|
|
194
|
+
tx.run(INSERT_SQL, row.negotiation_id, row.record_json, row.revision, row.state, row.principal, row.updated_at);
|
|
195
|
+
});
|
|
196
|
+
},
|
|
197
|
+
async get(negotiationId) {
|
|
198
|
+
const row = store.transactionalSync((tx) => tx.get(GET_SQL, negotiationId));
|
|
199
|
+
return row ? rowToNegotiation(row) : undefined;
|
|
200
|
+
},
|
|
201
|
+
async compareAndSet(negotiationId, expectedRevision, next) {
|
|
202
|
+
const row = negotiationToRow(next);
|
|
203
|
+
const touched = store.transactionalSync((tx) => tx.run(CAS_SQL, row.record_json, row.revision, row.state, row.updated_at, negotiationId, expectedRevision));
|
|
204
|
+
return touched === 1;
|
|
205
|
+
},
|
|
206
|
+
async transitionAndEnqueue(negotiationId, expectedRevision, next, outboxMessages) {
|
|
207
|
+
// Generalized transitionAndEnqueue: CAS the negotiation and enqueue
|
|
208
|
+
// every outbox message in ONE transaction (rollback on CAS miss).
|
|
209
|
+
const row = negotiationToRow(next);
|
|
210
|
+
const now = Date.now();
|
|
211
|
+
return store.transitionAndEnqueue({
|
|
212
|
+
casUpdateSql: CAS_SQL,
|
|
213
|
+
casUpdateParams: [
|
|
214
|
+
row.record_json, row.revision, row.state, row.updated_at,
|
|
215
|
+
negotiationId, expectedRevision,
|
|
216
|
+
],
|
|
217
|
+
enqueueSql: `
|
|
218
|
+
INSERT OR REPLACE INTO outbox (message_id, recipient, payload, enqueued_at, attempts)
|
|
219
|
+
VALUES (?, ?, ?, ?, 0)
|
|
220
|
+
`,
|
|
221
|
+
enqueueRows: outboxMessages.map((m) => [m.messageId, m.recipient, m.payload, now]),
|
|
222
|
+
});
|
|
223
|
+
},
|
|
224
|
+
async listRecoverable() {
|
|
225
|
+
const rows = store.transactionalSync((tx) => tx.all(LIST_RECOVERABLE_SQL));
|
|
226
|
+
return rows.map(rowToNegotiation);
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
// ── PurchaseStore ─────────────────────────────────────────────────────────
|
|
231
|
+
createPurchaseStore() {
|
|
232
|
+
const store = this.store;
|
|
233
|
+
const INSERT_SQL = `
|
|
234
|
+
INSERT INTO purchases (purchase_id, record_json, revision, status, updated_at)
|
|
235
|
+
VALUES (?, ?, ?, ?, ?)
|
|
236
|
+
`;
|
|
237
|
+
const GET_SQL = `SELECT * FROM purchases WHERE purchase_id = ?`;
|
|
238
|
+
const CAS_SQL = `
|
|
239
|
+
UPDATE purchases
|
|
240
|
+
SET record_json = ?, revision = ?, status = ?, updated_at = ?
|
|
241
|
+
WHERE purchase_id = ? AND revision = ?
|
|
242
|
+
`;
|
|
243
|
+
const LIST_RECOVERABLE_SQL = `
|
|
244
|
+
SELECT * FROM purchases WHERE status NOT IN ('COMPLETED','FAILED','CANCELLED')
|
|
245
|
+
`;
|
|
246
|
+
return {
|
|
247
|
+
async create(record) {
|
|
248
|
+
const row = purchaseToRow(record);
|
|
249
|
+
store.transactionalSync((tx) => {
|
|
250
|
+
tx.run(INSERT_SQL, row.purchase_id, row.record_json, row.revision, row.status, row.updated_at);
|
|
251
|
+
});
|
|
252
|
+
},
|
|
253
|
+
async get(purchaseId) {
|
|
254
|
+
const row = store.transactionalSync((tx) => tx.get(GET_SQL, purchaseId));
|
|
255
|
+
return row ? rowToPurchase(row) : undefined;
|
|
256
|
+
},
|
|
257
|
+
async compareAndSet(purchaseId, expectedRevision, next) {
|
|
258
|
+
const row = purchaseToRow(next);
|
|
259
|
+
const touched = store.transactionalSync((tx) => tx.run(CAS_SQL, row.record_json, row.revision, row.status, row.updated_at, purchaseId, expectedRevision));
|
|
260
|
+
return touched === 1;
|
|
261
|
+
},
|
|
262
|
+
async listRecoverable() {
|
|
263
|
+
const rows = store.transactionalSync((tx) => tx.all(LIST_RECOVERABLE_SQL));
|
|
264
|
+
return rows.map(rowToPurchase);
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
// ── ReplayLedger ──────────────────────────────────────────────────────────
|
|
269
|
+
createReplayLedger() {
|
|
270
|
+
const store = this.store;
|
|
271
|
+
const GET_SQL = `SELECT * FROM replay WHERE message_id = ?`;
|
|
272
|
+
const INSERT_PROCESSING_SQL = `
|
|
273
|
+
INSERT INTO replay (message_id, state, claimed_at, lease_until)
|
|
274
|
+
VALUES (?, 'PROCESSING', ?, ?)
|
|
275
|
+
`;
|
|
276
|
+
const UPDATE_PROCESSING_SQL = `
|
|
277
|
+
UPDATE replay SET claimed_at = ?, lease_until = ? WHERE message_id = ? AND state = 'PROCESSING'
|
|
278
|
+
`;
|
|
279
|
+
const COMPLETE_SQL = `
|
|
280
|
+
UPDATE replay SET state = 'COMPLETED', outcome_json = ?, completed_at = ?
|
|
281
|
+
WHERE message_id = ?
|
|
282
|
+
`;
|
|
283
|
+
return {
|
|
284
|
+
async claim(messageId, receivedAt, leaseMs = 30000) {
|
|
285
|
+
return store.transactionalSync((tx) => {
|
|
286
|
+
const row = tx.get(GET_SQL, messageId);
|
|
287
|
+
if (!row) {
|
|
288
|
+
tx.run(INSERT_PROCESSING_SQL, messageId, receivedAt, receivedAt + leaseMs);
|
|
289
|
+
return { claimed: true };
|
|
290
|
+
}
|
|
291
|
+
if (row.state === 'COMPLETED') {
|
|
292
|
+
return { claimed: false, entry: rowToReplay(row) };
|
|
293
|
+
}
|
|
294
|
+
// PROCESSING — reclaim if lease expired.
|
|
295
|
+
if (row.lease_until !== null && receivedAt > row.lease_until) {
|
|
296
|
+
tx.run(UPDATE_PROCESSING_SQL, receivedAt, receivedAt + leaseMs, messageId);
|
|
297
|
+
return { claimed: true, reclaimed: true };
|
|
298
|
+
}
|
|
299
|
+
return { claimed: false, entry: rowToReplay(row) };
|
|
300
|
+
});
|
|
301
|
+
},
|
|
302
|
+
async complete(messageId, outcome) {
|
|
303
|
+
store.transactionalSync((tx) => {
|
|
304
|
+
tx.run(COMPLETE_SQL, toJson(outcome), Date.now(), messageId);
|
|
305
|
+
});
|
|
306
|
+
},
|
|
307
|
+
async get(messageId) {
|
|
308
|
+
const row = store.transactionalSync((tx) => tx.get(GET_SQL, messageId));
|
|
309
|
+
return row ? rowToReplay(row) : undefined;
|
|
310
|
+
},
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
// ── PrincipalNegotiationStore ────────────────────────────────────────────
|
|
314
|
+
createPrincipalStore() {
|
|
315
|
+
const store = this.store;
|
|
316
|
+
const INSERT_SLOT_SQL = `
|
|
317
|
+
INSERT INTO principal_slots (principal, negotiation_id, opened_at) VALUES (?, ?, ?)
|
|
318
|
+
`;
|
|
319
|
+
const DELETE_SLOT_SQL = `
|
|
320
|
+
DELETE FROM principal_slots WHERE principal = ? AND negotiation_id = ?
|
|
321
|
+
`;
|
|
322
|
+
const SLOTS_FOR_SQL = `SELECT * FROM principal_slots WHERE principal = ?`;
|
|
323
|
+
const GET_COOLDOWN_SQL = `SELECT cooldown_until FROM principal_cooldown WHERE principal = ?`;
|
|
324
|
+
const SET_COOLDOWN_SQL = `
|
|
325
|
+
INSERT OR REPLACE INTO principal_cooldown (principal, cooldown_until) VALUES (?, ?)
|
|
326
|
+
`;
|
|
327
|
+
return {
|
|
328
|
+
async tryOpen(principal, negotiationId, now, limits) {
|
|
329
|
+
// Atomic on the shared transaction primitive: check cooldown, window,
|
|
330
|
+
// concurrency, then consume — two concurrent opens cannot both pass.
|
|
331
|
+
return store.transactionalSync((tx) => {
|
|
332
|
+
const cooldownRow = tx.get(GET_COOLDOWN_SQL, principal);
|
|
333
|
+
if (cooldownRow && now < cooldownRow.cooldown_until) {
|
|
334
|
+
return { allowed: false, reason: 'COOLDOWN' };
|
|
335
|
+
}
|
|
336
|
+
const slots = tx.all(SLOTS_FOR_SQL, principal);
|
|
337
|
+
const recent = slots.filter((s) => now - s.opened_at < limits.windowMs);
|
|
338
|
+
if (recent.length >= limits.maxNegotiationsPerWindow) {
|
|
339
|
+
return { allowed: false, reason: 'WINDOW_LIMIT' };
|
|
340
|
+
}
|
|
341
|
+
if (slots.length >= limits.maxConcurrentNegotiations) {
|
|
342
|
+
return { allowed: false, reason: 'CONCURRENCY_LIMIT' };
|
|
343
|
+
}
|
|
344
|
+
tx.run(INSERT_SLOT_SQL, principal, negotiationId, now);
|
|
345
|
+
return { allowed: true };
|
|
346
|
+
});
|
|
347
|
+
},
|
|
348
|
+
async close(principal, negotiationId) {
|
|
349
|
+
store.transactionalSync((tx) => {
|
|
350
|
+
tx.run(DELETE_SLOT_SQL, principal, negotiationId);
|
|
351
|
+
});
|
|
352
|
+
},
|
|
353
|
+
async reconcile(principal, activeNegotiationIds) {
|
|
354
|
+
store.transactionalSync((tx) => {
|
|
355
|
+
const slots = tx.all(SLOTS_FOR_SQL, principal);
|
|
356
|
+
const active = new Set(activeNegotiationIds);
|
|
357
|
+
for (const slot of slots) {
|
|
358
|
+
if (!active.has(slot.negotiation_id)) {
|
|
359
|
+
tx.run(DELETE_SLOT_SQL, principal, slot.negotiation_id);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
},
|
|
364
|
+
async getCooldownUntil(principal) {
|
|
365
|
+
const row = store.transactionalSync((tx) => tx.get(GET_COOLDOWN_SQL, principal));
|
|
366
|
+
return row?.cooldown_until ?? 0;
|
|
367
|
+
},
|
|
368
|
+
async setCooldownUntil(principal, until) {
|
|
369
|
+
store.transactionalSync((tx) => {
|
|
370
|
+
tx.run(SET_COOLDOWN_SQL, principal, until);
|
|
371
|
+
});
|
|
372
|
+
},
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
// ── OutboxStore ───────────────────────────────────────────────────────────
|
|
376
|
+
createOutboxStore() {
|
|
377
|
+
const store = this.store;
|
|
378
|
+
const ENQUEUE_SQL = `
|
|
379
|
+
INSERT OR REPLACE INTO outbox (message_id, recipient, payload, enqueued_at, attempts)
|
|
380
|
+
VALUES (?, ?, ?, ?, ?)
|
|
381
|
+
`;
|
|
382
|
+
const LIST_UNDELIVERED_SQL = `SELECT * FROM outbox WHERE delivered_at IS NULL`;
|
|
383
|
+
const MARK_DELIVERED_SQL = `UPDATE outbox SET delivered_at = ? WHERE message_id = ?`;
|
|
384
|
+
const RECORD_ATTEMPT_SQL = `UPDATE outbox SET attempts = attempts + 1 WHERE message_id = ?`;
|
|
385
|
+
return {
|
|
386
|
+
async enqueue(entry) {
|
|
387
|
+
store.transactionalSync((tx) => {
|
|
388
|
+
tx.run(ENQUEUE_SQL, entry.messageId, entry.recipient, toJson(entry.message), entry.enqueuedAt, entry.attempts);
|
|
389
|
+
});
|
|
390
|
+
},
|
|
391
|
+
async listUndelivered() {
|
|
392
|
+
const rows = store.transactionalSync((tx) => tx.all(LIST_UNDELIVERED_SQL));
|
|
393
|
+
return rows.map(rowToOutbox);
|
|
394
|
+
},
|
|
395
|
+
async markDelivered(messageId, deliveredAt) {
|
|
396
|
+
store.transactionalSync((tx) => {
|
|
397
|
+
tx.run(MARK_DELIVERED_SQL, deliveredAt, messageId);
|
|
398
|
+
});
|
|
399
|
+
},
|
|
400
|
+
async recordAttempt(messageId) {
|
|
401
|
+
store.transactionalSync((tx) => {
|
|
402
|
+
tx.run(RECORD_ATTEMPT_SQL, messageId);
|
|
403
|
+
});
|
|
404
|
+
},
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
exports.SQLiteCommerceStore = SQLiteCommerceStore;
|
|
409
|
+
/**
|
|
410
|
+
* Create a SQLite-backed CommerceStore.
|
|
411
|
+
*
|
|
412
|
+
* @param config filename (or ':memory:') + WAL/busy options.
|
|
413
|
+
*/
|
|
414
|
+
function createSQLiteCommerceStore(config) {
|
|
415
|
+
return new SQLiteCommerceStore(config);
|
|
416
|
+
}
|