@tofound/billing 0.0.0-stage → 0.2.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/CHANGELOG.md +122 -0
- package/LICENSE +3 -0
- package/README.md +79 -2
- package/dist/catalog/catalog.d.ts +115 -0
- package/dist/catalog/catalog.js +201 -0
- package/dist/domain/errors.d.ts +14 -0
- package/dist/domain/errors.js +21 -0
- package/dist/domain/money.d.ts +21 -0
- package/dist/domain/money.js +77 -0
- package/dist/domain/types.d.ts +167 -0
- package/dist/domain/types.js +18 -0
- package/dist/drizzle/index.d.ts +5 -0
- package/dist/drizzle/index.js +5 -0
- package/dist/drizzle/schema-factory.d.ts +586 -0
- package/dist/drizzle/schema-factory.js +206 -0
- package/dist/drizzle/store.d.ts +20 -0
- package/dist/drizzle/store.js +124 -0
- package/dist/entitlement/resolve.d.ts +76 -0
- package/dist/entitlement/resolve.js +122 -0
- package/dist/inbox/apply.d.ts +48 -0
- package/dist/inbox/apply.js +299 -0
- package/dist/inbox/conformance.d.ts +20 -0
- package/dist/inbox/conformance.js +254 -0
- package/dist/inbox/drizzle.d.ts +14 -0
- package/dist/inbox/drizzle.js +203 -0
- package/dist/inbox/ingest.d.ts +108 -0
- package/dist/inbox/ingest.js +404 -0
- package/dist/inbox/memory.d.ts +13 -0
- package/dist/inbox/memory.js +172 -0
- package/dist/inbox/ports.d.ts +150 -0
- package/dist/inbox/ports.js +1 -0
- package/dist/inbox/redact.d.ts +2 -0
- package/dist/inbox/redact.js +47 -0
- package/dist/inbox/schema.d.ts +1158 -0
- package/dist/inbox/schema.js +90 -0
- package/dist/inbox/watermark.d.ts +13 -0
- package/dist/inbox/watermark.js +6 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +27 -0
- package/dist/ledger/ledger.d.ts +47 -0
- package/dist/ledger/ledger.js +224 -0
- package/dist/ports/index.d.ts +2 -0
- package/dist/ports/index.js +1 -0
- package/dist/ports/ledger-store.d.ts +53 -0
- package/dist/ports/ledger-store.js +1 -0
- package/dist/ports/runtime.d.ts +9 -0
- package/dist/ports/runtime.js +1 -0
- package/dist/providers/polar/events.d.ts +17 -0
- package/dist/providers/polar/events.js +213 -0
- package/dist/providers/polar/index.d.ts +50 -0
- package/dist/providers/polar/index.js +271 -0
- package/dist/providers/polar/signature.d.ts +23 -0
- package/dist/providers/polar/signature.js +52 -0
- package/dist/providers/port.d.ts +207 -0
- package/dist/providers/port.js +30 -0
- package/dist/providers/sepay/index.d.ts +34 -0
- package/dist/providers/sepay/index.js +241 -0
- package/dist/providers/sepay/order.d.ts +32 -0
- package/dist/providers/sepay/order.js +69 -0
- package/dist/providers/sepay/signature.d.ts +8 -0
- package/dist/providers/sepay/signature.js +51 -0
- package/dist/quote/conformance.d.ts +16 -0
- package/dist/quote/conformance.js +39 -0
- package/dist/quote/index.d.ts +3 -0
- package/dist/quote/index.js +3 -0
- package/dist/quote/steps.d.ts +54 -0
- package/dist/quote/steps.js +103 -0
- package/dist/quote/waterfall.d.ts +98 -0
- package/dist/quote/waterfall.js +82 -0
- package/dist/renewal/renewal.d.ts +69 -0
- package/dist/renewal/renewal.js +198 -0
- package/dist/stores/conformance.d.ts +22 -0
- package/dist/stores/conformance.js +269 -0
- package/dist/stores/memory.d.ts +19 -0
- package/dist/stores/memory.js +137 -0
- package/dist/stores/testing.d.ts +13 -0
- package/dist/stores/testing.js +13 -0
- package/dist/terms/conformance.d.ts +17 -0
- package/dist/terms/conformance.js +198 -0
- package/dist/terms/decide.d.ts +97 -0
- package/dist/terms/decide.js +176 -0
- package/dist/terms/drizzle.d.ts +12 -0
- package/dist/terms/drizzle.js +131 -0
- package/dist/terms/memory.d.ts +23 -0
- package/dist/terms/memory.js +126 -0
- package/dist/terms/plans.d.ts +85 -0
- package/dist/terms/plans.js +331 -0
- package/dist/terms/ports.d.ts +55 -0
- package/dist/terms/ports.js +1 -0
- package/dist/terms/rules.d.ts +11 -0
- package/dist/terms/rules.js +36 -0
- package/dist/terms/schema.d.ts +711 -0
- package/dist/terms/schema.js +70 -0
- package/dist/terms/snapshot.d.ts +20 -0
- package/dist/terms/snapshot.js +134 -0
- package/dist/terms/types.d.ts +85 -0
- package/dist/terms/types.js +4 -0
- package/docs/API.md +417 -0
- package/docs/SCHEMA.md +163 -0
- package/package.json +80 -4
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { AccountId } from '../domain/types.js';
|
|
2
|
+
import type { LedgerStore } from '../ports/ledger-store.js';
|
|
3
|
+
/**
|
|
4
|
+
* The store conformance suite (`billing.ports` contract check). Every
|
|
5
|
+
* `LedgerStore` — memory, the Drizzle store, a host's adapter over legacy
|
|
6
|
+
* tables — must pass all of it. Framework-agnostic: each case throws on
|
|
7
|
+
* failure, so a host wires it into its own runner:
|
|
8
|
+
*
|
|
9
|
+
* for (const c of ledgerConformanceCases) test(c.name, () => c.run(target))
|
|
10
|
+
*/
|
|
11
|
+
export interface LedgerConformanceTarget<TTx = unknown> {
|
|
12
|
+
store: LedgerStore<TTx>;
|
|
13
|
+
/** A fresh, never-used account id of the host's type (uuid, text …). */
|
|
14
|
+
newAccountId(): string;
|
|
15
|
+
}
|
|
16
|
+
export interface ConformanceCase {
|
|
17
|
+
name: string;
|
|
18
|
+
run<TTx>(target: LedgerConformanceTarget<TTx>): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
/** Checks I1, I2, I6 and seq contiguity for one account; throws on violation. */
|
|
21
|
+
export declare function assertLedgerInvariants<TTx>(store: LedgerStore<TTx>, accountId: AccountId): Promise<void>;
|
|
22
|
+
export declare const ledgerConformanceCases: readonly ConformanceCase[];
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import { isBillingError } from '../domain/errors.js';
|
|
2
|
+
import { createLedger } from '../ledger/ledger.js';
|
|
3
|
+
/** Checks I1, I2, I6 and seq contiguity for one account; throws on violation. */
|
|
4
|
+
export async function assertLedgerInvariants(store, accountId) {
|
|
5
|
+
const reader = store.reader();
|
|
6
|
+
const account = await reader.getAccount(accountId);
|
|
7
|
+
const entries = (await reader.listEntries(accountId, { limit: 1_000_000 })).reverse();
|
|
8
|
+
let balance = 0;
|
|
9
|
+
entries.forEach((entry, i) => {
|
|
10
|
+
check(entry.seq === i + 1, `seq ${entry.seq} at position ${i + 1} (I1 contiguity)`);
|
|
11
|
+
balance += entry.delta;
|
|
12
|
+
check(entry.balanceAfter === balance, `entry ${entry.seq} balanceAfter ${entry.balanceAfter} ≠ running Σ ${balance} (I1)`);
|
|
13
|
+
check(entry.balanceAfter >= 0, `entry ${entry.seq} balanceAfter ${entry.balanceAfter} < 0 (I2)`);
|
|
14
|
+
});
|
|
15
|
+
const expected = account?.balance ?? 0;
|
|
16
|
+
check(expected === balance, `account balance ${expected} ≠ Σ delta ${balance} (I6)`);
|
|
17
|
+
check((account?.seq ?? 0) === entries.length, `account seq ${account?.seq} ≠ entry count ${entries.length}`);
|
|
18
|
+
}
|
|
19
|
+
function check(ok, message) {
|
|
20
|
+
if (!ok)
|
|
21
|
+
throw new Error(`ledger conformance: ${message}`);
|
|
22
|
+
}
|
|
23
|
+
function equal(actual, expected, what) {
|
|
24
|
+
check(Object.is(actual, expected) || actual === expected, `${what}: expected ${String(expected)}, got ${String(actual)}`);
|
|
25
|
+
}
|
|
26
|
+
async function rejects(promise, code, what) {
|
|
27
|
+
try {
|
|
28
|
+
await promise;
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
check(isBillingError(error, code), `${what}: expected ${code}, got ${error instanceof Error ? error.message : String(error)}`);
|
|
32
|
+
return error.details;
|
|
33
|
+
}
|
|
34
|
+
throw new Error(`ledger conformance: ${what}: expected ${code}, but it resolved`);
|
|
35
|
+
}
|
|
36
|
+
const ROLLBACK = new Error('conformance rollback');
|
|
37
|
+
export const ledgerConformanceCases = [
|
|
38
|
+
{
|
|
39
|
+
name: 'credits and debits keep balance = last balanceAfter = Σ delta with contiguous seq',
|
|
40
|
+
async run({ store, newAccountId }) {
|
|
41
|
+
const ledger = createLedger({ store });
|
|
42
|
+
const a = newAccountId();
|
|
43
|
+
await ledger.credit({ accountId: a, kind: 'topup', amount: 1_000, idempotencyKey: `t:${a}:1` });
|
|
44
|
+
await ledger.debit({ accountId: a, kind: 'spend', amount: 300, idempotencyKey: `t:${a}:2`, reason: 'job', source: { type: 'job', id: 'j1' } });
|
|
45
|
+
const last = await ledger.credit({ accountId: a, kind: 'grant', amount: 50, idempotencyKey: `t:${a}:3`, meta: { note: 'welcome' } });
|
|
46
|
+
equal(last.entry.seq, 3, 'seq');
|
|
47
|
+
equal(last.entry.balanceAfter, 750, 'balanceAfter');
|
|
48
|
+
equal(await ledger.balance(a), 750, 'balance');
|
|
49
|
+
const page = await ledger.entries(a);
|
|
50
|
+
equal(page.entries.length, 3, 'entries');
|
|
51
|
+
equal(page.entries[1]?.sourceType, 'job', 'sourceType round-trip');
|
|
52
|
+
equal(page.entries[1]?.reason, 'job', 'reason round-trip');
|
|
53
|
+
equal(page.entries[0]?.meta?.note, 'welcome', 'meta round-trip');
|
|
54
|
+
await assertLedgerInvariants(store, a);
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
name: 'the same key with the same intent replays the original entry (I3)',
|
|
59
|
+
async run({ store, newAccountId }) {
|
|
60
|
+
const ledger = createLedger({ store });
|
|
61
|
+
const a = newAccountId();
|
|
62
|
+
const first = await ledger.credit({ accountId: a, kind: 'topup', amount: 500, idempotencyKey: `r:${a}` });
|
|
63
|
+
const again = await ledger.credit({ accountId: a, kind: 'topup', amount: 500, idempotencyKey: `r:${a}` });
|
|
64
|
+
equal(again.replayed, true, 'replayed');
|
|
65
|
+
equal(again.entry.id, first.entry.id, 'entry id');
|
|
66
|
+
equal(again.events.length, 0, 'replay events');
|
|
67
|
+
equal(await ledger.balance(a), 500, 'balance after replay');
|
|
68
|
+
await assertLedgerInvariants(store, a);
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
name: 'the same key with a different account, amount or kind fails idempotency_mismatch (I3)',
|
|
73
|
+
async run({ store, newAccountId }) {
|
|
74
|
+
const ledger = createLedger({ store });
|
|
75
|
+
const a = newAccountId();
|
|
76
|
+
const b = newAccountId();
|
|
77
|
+
const key = `m:${a}`;
|
|
78
|
+
await ledger.credit({ accountId: a, kind: 'topup', amount: 500, idempotencyKey: key });
|
|
79
|
+
await rejects(ledger.credit({ accountId: a, kind: 'topup', amount: 501, idempotencyKey: key }), 'idempotency_mismatch', 'amount');
|
|
80
|
+
await rejects(ledger.credit({ accountId: b, kind: 'topup', amount: 500, idempotencyKey: key }), 'idempotency_mismatch', 'account');
|
|
81
|
+
await rejects(ledger.credit({ accountId: a, kind: 'grant', amount: 500, idempotencyKey: key }), 'idempotency_mismatch', 'kind');
|
|
82
|
+
await rejects(ledger.debit({ accountId: a, kind: 'topup', amount: 500, idempotencyKey: key }), 'idempotency_mismatch', 'direction');
|
|
83
|
+
equal(await ledger.balance(b), 0, 'other account untouched');
|
|
84
|
+
await assertLedgerInvariants(store, a);
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
name: 'a debit never overdraws: insufficient_credits carries balance, required, shortfall (I2)',
|
|
89
|
+
async run({ store, newAccountId }) {
|
|
90
|
+
const ledger = createLedger({ store });
|
|
91
|
+
const a = newAccountId();
|
|
92
|
+
await ledger.credit({ accountId: a, kind: 'topup', amount: 100, idempotencyKey: `o:${a}:1` });
|
|
93
|
+
const details = await rejects(ledger.debit({ accountId: a, kind: 'spend', amount: 130, idempotencyKey: `o:${a}:2` }), 'insufficient_credits', 'overdraft');
|
|
94
|
+
equal(details['balance'], 100, 'details.balance');
|
|
95
|
+
equal(details['required'], 130, 'details.required');
|
|
96
|
+
equal(details['shortfall'], 30, 'details.shortfall');
|
|
97
|
+
equal(await ledger.balance(a), 100, 'balance unchanged');
|
|
98
|
+
equal(await store.reader().findEntryByKey(`o:${a}:2`), null, 'no entry written');
|
|
99
|
+
// A fresh account cannot go negative either.
|
|
100
|
+
await rejects(ledger.debit({ accountId: newAccountId(), kind: 'spend', amount: 1, idempotencyKey: `o:${a}:3` }), 'insufficient_credits', 'empty account');
|
|
101
|
+
await assertLedgerInvariants(store, a);
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
name: 'debitUpTo posts min(balance, amount), records the shortfall and replays',
|
|
106
|
+
async run({ store, newAccountId }) {
|
|
107
|
+
const ledger = createLedger({ store });
|
|
108
|
+
const a = newAccountId();
|
|
109
|
+
await ledger.credit({ accountId: a, kind: 'topup', amount: 30, idempotencyKey: `u:${a}:1` });
|
|
110
|
+
const r = await ledger.debitUpTo({ accountId: a, kind: 'refund', amount: 50, idempotencyKey: `u:${a}:2` });
|
|
111
|
+
equal(r.entry.delta, -30, 'posted');
|
|
112
|
+
equal(r.shortfall, 20, 'shortfall');
|
|
113
|
+
equal((r.entry.meta?.['debitUpTo']).shortfall, 20, 'recorded shortfall');
|
|
114
|
+
const again = await ledger.debitUpTo({ accountId: a, kind: 'refund', amount: 50, idempotencyKey: `u:${a}:2` });
|
|
115
|
+
equal(again.replayed, true, 'replayed');
|
|
116
|
+
equal(again.shortfall, 20, 'replayed shortfall');
|
|
117
|
+
await rejects(ledger.debitUpTo({ accountId: a, kind: 'refund', amount: 60, idempotencyKey: `u:${a}:2` }), 'idempotency_mismatch', 'different request');
|
|
118
|
+
const empty = await ledger.debitUpTo({ accountId: a, kind: 'refund', amount: 10, idempotencyKey: `u:${a}:3` });
|
|
119
|
+
equal(empty.entry.delta, 0, 'zero posting at balance 0');
|
|
120
|
+
equal(empty.shortfall, 10, 'full shortfall');
|
|
121
|
+
equal(empty.events.length, 0, 'no event for a zero posting');
|
|
122
|
+
await assertLedgerInvariants(store, a);
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
name: 'reverse posts one counter-entry of at most |original| (I5)',
|
|
127
|
+
async run({ store, newAccountId }) {
|
|
128
|
+
const ledger = createLedger({ store });
|
|
129
|
+
const a = newAccountId();
|
|
130
|
+
const top = await ledger.credit({ accountId: a, kind: 'topup', amount: 200, idempotencyKey: `v:${a}:1` });
|
|
131
|
+
const spend = await ledger.debit({ accountId: a, kind: 'spend', amount: 80, idempotencyKey: `v:${a}:2` });
|
|
132
|
+
await rejects(ledger.reverse({ entryId: spend.entry.id, amount: 81, idempotencyKey: `v:${a}:x` }), 'reversal_exceeds_original', 'too much');
|
|
133
|
+
const back = await ledger.reverse({ entryId: spend.entry.id, idempotencyKey: `v:${a}:3` });
|
|
134
|
+
equal(back.entry.delta, 80, 'refunds the spend');
|
|
135
|
+
equal(back.entry.kind, 'reversal', 'kind');
|
|
136
|
+
equal(back.entry.reversesId, spend.entry.id, 'reversesId');
|
|
137
|
+
const replay = await ledger.reverse({ entryId: spend.entry.id, idempotencyKey: `v:${a}:3` });
|
|
138
|
+
equal(replay.replayed, true, 'replayed reversal');
|
|
139
|
+
await rejects(ledger.reverse({ entryId: spend.entry.id, idempotencyKey: `v:${a}:4` }), 'already_reversed', 'second reversal');
|
|
140
|
+
const partial = await ledger.reverse({ entryId: top.entry.id, amount: 150, idempotencyKey: `v:${a}:5` });
|
|
141
|
+
equal(partial.entry.delta, -150, 'partial claw-back');
|
|
142
|
+
await rejects(ledger.reverse({ entryId: 'missing-entry', idempotencyKey: `v:${a}:6` }), 'entry_not_found', 'unknown entry');
|
|
143
|
+
equal(await ledger.balance(a), 50, 'balance');
|
|
144
|
+
const b = newAccountId();
|
|
145
|
+
const big = await ledger.credit({ accountId: b, kind: 'topup', amount: 100, idempotencyKey: `v:${b}:1` });
|
|
146
|
+
await ledger.debit({ accountId: b, kind: 'spend', amount: 90, idempotencyKey: `v:${b}:2` });
|
|
147
|
+
await rejects(ledger.reverse({ entryId: big.entry.id, idempotencyKey: `v:${b}:3` }), 'insufficient_credits', 'claw-back past zero');
|
|
148
|
+
await assertLedgerInvariants(store, a);
|
|
149
|
+
await assertLedgerInvariants(store, b);
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
{
|
|
153
|
+
name: 'a posting inside a host transaction rolls back with it',
|
|
154
|
+
async run({ store, newAccountId }) {
|
|
155
|
+
const ledger = createLedger({ store });
|
|
156
|
+
const a = newAccountId();
|
|
157
|
+
let events = [];
|
|
158
|
+
try {
|
|
159
|
+
await store.transaction(async (tx) => {
|
|
160
|
+
const r = await ledger.in(tx).credit({ accountId: a, kind: 'topup', amount: 100, idempotencyKey: `h:${a}` });
|
|
161
|
+
events = r.events;
|
|
162
|
+
equal(await ledger.in(tx).balance(a), 100, 'visible inside the transaction');
|
|
163
|
+
throw ROLLBACK;
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
if (error !== ROLLBACK)
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
equal(events.length, 1, 'in(tx) returns its events to the host');
|
|
171
|
+
equal(await ledger.balance(a), 0, 'balance after rollback');
|
|
172
|
+
equal(await store.reader().findEntryByKey(`h:${a}`), null, 'entry after rollback');
|
|
173
|
+
const ok = await store.transaction((tx) => ledger.in(tx).credit({ accountId: a, kind: 'topup', amount: 100, idempotencyKey: `h:${a}` }));
|
|
174
|
+
equal(ok.replayed, false, 'key reusable after rollback');
|
|
175
|
+
await assertLedgerInvariants(store, a);
|
|
176
|
+
},
|
|
177
|
+
},
|
|
178
|
+
{
|
|
179
|
+
name: 'concurrent spends never double-debit',
|
|
180
|
+
async run({ store, newAccountId }) {
|
|
181
|
+
const ledger = createLedger({ store });
|
|
182
|
+
const a = newAccountId();
|
|
183
|
+
await ledger.credit({ accountId: a, kind: 'topup', amount: 100, idempotencyKey: `c:${a}:0` });
|
|
184
|
+
const results = await Promise.allSettled(Array.from({ length: 20 }, (_, i) => ledger.debit({ accountId: a, kind: 'spend', amount: 15, idempotencyKey: `c:${a}:${i + 1}` })));
|
|
185
|
+
const ok = results.filter((r) => r.status === 'fulfilled').length;
|
|
186
|
+
const short = results.filter((r) => r.status === 'rejected' && isBillingError(r.reason, 'insufficient_credits')).length;
|
|
187
|
+
equal(ok, 6, 'successful spends');
|
|
188
|
+
equal(short, 14, 'insufficient spends');
|
|
189
|
+
equal(await ledger.balance(a), 10, 'balance');
|
|
190
|
+
await assertLedgerInvariants(store, a);
|
|
191
|
+
},
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
name: 'concurrent posts of one key write one entry',
|
|
195
|
+
async run({ store, newAccountId }) {
|
|
196
|
+
const ledger = createLedger({ store });
|
|
197
|
+
const a = newAccountId();
|
|
198
|
+
const results = await Promise.all(Array.from({ length: 10 }, () => ledger.credit({ accountId: a, kind: 'topup', amount: 70, idempotencyKey: `k:${a}` })));
|
|
199
|
+
equal(new Set(results.map((r) => r.entry.id)).size, 1, 'one entry id');
|
|
200
|
+
equal(results.filter((r) => !r.replayed).length, 1, 'one original');
|
|
201
|
+
equal(await ledger.balance(a), 70, 'balance');
|
|
202
|
+
await assertLedgerInvariants(store, a);
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
name: 'a key raced across two accounts is written once',
|
|
207
|
+
async run({ store, newAccountId }) {
|
|
208
|
+
const ledger = createLedger({ store });
|
|
209
|
+
const a = newAccountId();
|
|
210
|
+
const b = newAccountId();
|
|
211
|
+
const key = `x:${a}`;
|
|
212
|
+
const results = await Promise.allSettled([
|
|
213
|
+
ledger.credit({ accountId: a, kind: 'topup', amount: 10, idempotencyKey: key }),
|
|
214
|
+
ledger.credit({ accountId: b, kind: 'topup', amount: 10, idempotencyKey: key }),
|
|
215
|
+
]);
|
|
216
|
+
equal(results.filter((r) => r.status === 'fulfilled').length, 1, 'one winner');
|
|
217
|
+
const loser = results.find((r) => r.status === 'rejected');
|
|
218
|
+
check(loser?.status === 'rejected' && isBillingError(loser.reason, 'idempotency_mismatch'), 'loser fails idempotency_mismatch');
|
|
219
|
+
equal((await ledger.balance(a)) + (await ledger.balance(b)), 10, 'credited once in total');
|
|
220
|
+
await assertLedgerInvariants(store, a);
|
|
221
|
+
await assertLedgerInvariants(store, b);
|
|
222
|
+
},
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
name: 'invalid postings are rejected before anything is written',
|
|
226
|
+
async run({ store, newAccountId }) {
|
|
227
|
+
const ledger = createLedger({ store });
|
|
228
|
+
const a = newAccountId();
|
|
229
|
+
for (const amount of [0, -5, 1.5, Number.MAX_SAFE_INTEGER + 2, Number.NaN]) {
|
|
230
|
+
await rejects(ledger.credit({ accountId: a, kind: 'topup', amount, idempotencyKey: `i:${a}:${amount}` }), 'invalid_amount', `amount ${amount}`);
|
|
231
|
+
}
|
|
232
|
+
await rejects(ledger.credit({ accountId: a, kind: 'reversal', amount: 1, idempotencyKey: `i:${a}:k` }), 'invalid_input', 'reversal via post');
|
|
233
|
+
await rejects(ledger.credit({ accountId: a, kind: 'bogus', amount: 1, idempotencyKey: `i:${a}:k` }), 'invalid_input', 'unknown kind');
|
|
234
|
+
await rejects(ledger.credit({ accountId: a, kind: 'topup', amount: 1, idempotencyKey: '' }), 'invalid_input', 'missing key');
|
|
235
|
+
await ledger.credit({ accountId: a, kind: 'topup', amount: Number.MAX_SAFE_INTEGER, idempotencyKey: `i:${a}:max` });
|
|
236
|
+
await rejects(ledger.credit({ accountId: a, kind: 'topup', amount: 1, idempotencyKey: `i:${a}:over` }), 'balance_overflow', 'overflow');
|
|
237
|
+
await assertLedgerInvariants(store, a);
|
|
238
|
+
},
|
|
239
|
+
},
|
|
240
|
+
{
|
|
241
|
+
name: 'entries page newest first by seq',
|
|
242
|
+
async run({ store, newAccountId }) {
|
|
243
|
+
const ledger = createLedger({ store });
|
|
244
|
+
const a = newAccountId();
|
|
245
|
+
for (let i = 1; i <= 5; i++)
|
|
246
|
+
await ledger.credit({ accountId: a, kind: 'grant', amount: i, idempotencyKey: `p:${a}:${i}` });
|
|
247
|
+
const first = await ledger.entries(a, { limit: 2 });
|
|
248
|
+
equal(first.entries.map((e) => e.seq).join(','), '5,4', 'page 1');
|
|
249
|
+
const second = await ledger.entries(a, { limit: 2, beforeSeq: first.nextBeforeSeq ?? 0 });
|
|
250
|
+
equal(second.entries.map((e) => e.seq).join(','), '3,2', 'page 2');
|
|
251
|
+
const third = await ledger.entries(a, { limit: 2, beforeSeq: second.nextBeforeSeq ?? 0 });
|
|
252
|
+
equal(third.entries.map((e) => e.seq).join(','), '1', 'page 3');
|
|
253
|
+
equal(third.nextBeforeSeq, null, 'exhausted');
|
|
254
|
+
},
|
|
255
|
+
},
|
|
256
|
+
{
|
|
257
|
+
name: 'the event sink hears committed postings only',
|
|
258
|
+
async run({ store, newAccountId }) {
|
|
259
|
+
const heard = [];
|
|
260
|
+
const ledger = createLedger({ store, events: (e) => void heard.push(e) });
|
|
261
|
+
const a = newAccountId();
|
|
262
|
+
await ledger.credit({ accountId: a, kind: 'topup', amount: 40, idempotencyKey: `e:${a}:1` });
|
|
263
|
+
await ledger.debit({ accountId: a, kind: 'spend', amount: 15, idempotencyKey: `e:${a}:2` });
|
|
264
|
+
await ledger.debit({ accountId: a, kind: 'spend', amount: 15, idempotencyKey: `e:${a}:2` });
|
|
265
|
+
await rejects(ledger.debit({ accountId: a, kind: 'spend', amount: 99, idempotencyKey: `e:${a}:3` }), 'insufficient_credits', 'failed');
|
|
266
|
+
equal(heard.map((e) => e.type).join(','), 'credited,debited', 'events');
|
|
267
|
+
},
|
|
268
|
+
},
|
|
269
|
+
];
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AccountId, LedgerEntry } from '../domain/types.js';
|
|
2
|
+
import type { LedgerStore } from '../ports/ledger-store.js';
|
|
3
|
+
/**
|
|
4
|
+
* An open memory transaction. Writes are staged and applied on commit, so a
|
|
5
|
+
* throw anywhere in the host's callback leaves the store untouched.
|
|
6
|
+
*/
|
|
7
|
+
export interface MemoryTx {
|
|
8
|
+
readonly id: number;
|
|
9
|
+
}
|
|
10
|
+
export interface MemoryLedgerStore extends LedgerStore<MemoryTx> {
|
|
11
|
+
/** Committed entries of one account, oldest first (test inspection). */
|
|
12
|
+
dump(accountId: AccountId): LedgerEntry[];
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* In-process `LedgerStore` for tests and hosts' unit suites. Transactions are
|
|
16
|
+
* serialized by one store-wide mutex — the memory analogue of the account row
|
|
17
|
+
* lock — and pass the same conformance suite as the Postgres store.
|
|
18
|
+
*/
|
|
19
|
+
export declare function createMemoryLedgerStore(): MemoryLedgerStore;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-process `LedgerStore` for tests and hosts' unit suites. Transactions are
|
|
3
|
+
* serialized by one store-wide mutex — the memory analogue of the account row
|
|
4
|
+
* lock — and pass the same conformance suite as the Postgres store.
|
|
5
|
+
*/
|
|
6
|
+
export function createMemoryLedgerStore() {
|
|
7
|
+
const accounts = new Map();
|
|
8
|
+
const entries = new Map();
|
|
9
|
+
const byKey = new Map();
|
|
10
|
+
const byReversal = new Map();
|
|
11
|
+
const byAccount = new Map();
|
|
12
|
+
let tail = Promise.resolve();
|
|
13
|
+
let nextTx = 1;
|
|
14
|
+
const clone = (value) => structuredClone(value);
|
|
15
|
+
const committed = {
|
|
16
|
+
async getAccount(accountId) {
|
|
17
|
+
const a = accounts.get(accountId);
|
|
18
|
+
return a ? { ...a } : null;
|
|
19
|
+
},
|
|
20
|
+
async getEntry(id) {
|
|
21
|
+
const e = entries.get(id);
|
|
22
|
+
return e ? clone(e) : null;
|
|
23
|
+
},
|
|
24
|
+
async findEntryByKey(key) {
|
|
25
|
+
const id = byKey.get(key);
|
|
26
|
+
return id ? clone(entries.get(id)) : null;
|
|
27
|
+
},
|
|
28
|
+
async listEntries(accountId, options) {
|
|
29
|
+
return list(byAccount.get(accountId) ?? [], options);
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
function list(rows, options) {
|
|
33
|
+
return rows
|
|
34
|
+
.filter((e) => options.beforeSeq === undefined || e.seq < options.beforeSeq)
|
|
35
|
+
.sort((a, b) => b.seq - a.seq)
|
|
36
|
+
.slice(0, options.limit)
|
|
37
|
+
.map(clone);
|
|
38
|
+
}
|
|
39
|
+
function staged(tx) {
|
|
40
|
+
const s = tx;
|
|
41
|
+
if (!s.open)
|
|
42
|
+
throw new Error('memory ledger transaction is closed');
|
|
43
|
+
return s;
|
|
44
|
+
}
|
|
45
|
+
function bind(tx) {
|
|
46
|
+
const own = (id) => staged(tx).entries.find((e) => e.id === id);
|
|
47
|
+
return {
|
|
48
|
+
async getAccount(accountId) {
|
|
49
|
+
const s = staged(tx).accounts.get(accountId);
|
|
50
|
+
return s ? { ...s } : committed.getAccount(accountId);
|
|
51
|
+
},
|
|
52
|
+
async getEntry(id) {
|
|
53
|
+
const e = own(id);
|
|
54
|
+
return e ? clone(e) : committed.getEntry(id);
|
|
55
|
+
},
|
|
56
|
+
async findEntryByKey(key) {
|
|
57
|
+
const e = staged(tx).entries.find((x) => x.idempotencyKey === key);
|
|
58
|
+
return e ? clone(e) : committed.findEntryByKey(key);
|
|
59
|
+
},
|
|
60
|
+
async listEntries(accountId, options) {
|
|
61
|
+
const rows = [...(byAccount.get(accountId) ?? []), ...staged(tx).entries.filter((e) => e.accountId === accountId)];
|
|
62
|
+
return list(rows, options);
|
|
63
|
+
},
|
|
64
|
+
async lockAccount(accountId) {
|
|
65
|
+
const s = staged(tx);
|
|
66
|
+
const current = s.accounts.get(accountId) ?? accounts.get(accountId) ?? { accountId, balance: 0, seq: 0 };
|
|
67
|
+
s.accounts.set(accountId, { ...current });
|
|
68
|
+
return { ...current };
|
|
69
|
+
},
|
|
70
|
+
async findReversalOf(entryId) {
|
|
71
|
+
const e = staged(tx).entries.find((x) => x.reversesId === entryId);
|
|
72
|
+
if (e)
|
|
73
|
+
return clone(e);
|
|
74
|
+
const id = byReversal.get(entryId);
|
|
75
|
+
return id ? clone(entries.get(id)) : null;
|
|
76
|
+
},
|
|
77
|
+
async appendEntry(entry) {
|
|
78
|
+
const s = staged(tx);
|
|
79
|
+
const clash = (e) => e.idempotencyKey === entry.idempotencyKey ||
|
|
80
|
+
(entry.reversesId !== null && e.reversesId === entry.reversesId) ||
|
|
81
|
+
(e.accountId === entry.accountId && e.seq === entry.seq) ||
|
|
82
|
+
e.id === entry.id;
|
|
83
|
+
if (s.entries.some(clash) ||
|
|
84
|
+
byKey.has(entry.idempotencyKey) ||
|
|
85
|
+
entries.has(entry.id) ||
|
|
86
|
+
(entry.reversesId !== null && byReversal.has(entry.reversesId)) ||
|
|
87
|
+
// Committed seqs are contiguous 1..n, so a clash is any seq ≤ the last.
|
|
88
|
+
entry.seq <= (byAccount.get(entry.accountId)?.at(-1)?.seq ?? 0)) {
|
|
89
|
+
return { inserted: false };
|
|
90
|
+
}
|
|
91
|
+
if (entry.balanceAfter < 0)
|
|
92
|
+
throw new Error('check constraint: balance_after must be >= 0');
|
|
93
|
+
s.entries.push(clone(entry));
|
|
94
|
+
return { inserted: true };
|
|
95
|
+
},
|
|
96
|
+
async setAccountState(state) {
|
|
97
|
+
if (state.balance < 0)
|
|
98
|
+
throw new Error('check constraint: balance must be >= 0');
|
|
99
|
+
staged(tx).accounts.set(state.accountId, { ...state });
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function commit(s) {
|
|
104
|
+
for (const [id, state] of s.accounts)
|
|
105
|
+
accounts.set(id, state);
|
|
106
|
+
for (const entry of s.entries) {
|
|
107
|
+
entries.set(entry.id, entry);
|
|
108
|
+
byKey.set(entry.idempotencyKey, entry.id);
|
|
109
|
+
if (entry.reversesId)
|
|
110
|
+
byReversal.set(entry.reversesId, entry.id);
|
|
111
|
+
const rows = byAccount.get(entry.accountId) ?? [];
|
|
112
|
+
rows.push(entry);
|
|
113
|
+
byAccount.set(entry.accountId, rows);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
async transaction(fn) {
|
|
118
|
+
let release;
|
|
119
|
+
const turn = tail;
|
|
120
|
+
tail = new Promise((resolve) => (release = resolve));
|
|
121
|
+
await turn;
|
|
122
|
+
const s = { id: nextTx++, accounts: new Map(), entries: [], open: true };
|
|
123
|
+
try {
|
|
124
|
+
const result = await fn(s);
|
|
125
|
+
commit(s);
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
s.open = false;
|
|
130
|
+
release();
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
bind,
|
|
134
|
+
reader: () => committed,
|
|
135
|
+
dump: (accountId) => (byAccount.get(accountId) ?? []).map(clone),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@tofound/billing/testing` — the kit hosts use to prove their own stores
|
|
3
|
+
* and charge paths: the store conformance suite, the ledger invariant check,
|
|
4
|
+
* the quote/settle conformance assertion, the ingest and term store
|
|
5
|
+
* conformance suites and the memory stores.
|
|
6
|
+
*/
|
|
7
|
+
export { assertLedgerInvariants, ledgerConformanceCases, type ConformanceCase, type LedgerConformanceTarget, } from './conformance.js';
|
|
8
|
+
export { createMemoryLedgerStore, type MemoryLedgerStore, type MemoryTx } from './memory.js';
|
|
9
|
+
export { assertQuoteMatchesSettlement, type ObservedSettlement } from '../quote/conformance.js';
|
|
10
|
+
export { ingestConformanceCases, type IngestConformanceCase, type IngestConformanceTarget } from '../inbox/conformance.js';
|
|
11
|
+
export { createMemoryIngestStore, type MemoryIngestStore } from '../inbox/memory.js';
|
|
12
|
+
export { termConformanceCases, type TermConformanceCase, type TermConformanceTarget } from '../terms/conformance.js';
|
|
13
|
+
export { createMemoryTermStore, type MemoryTermStore } from '../terms/memory.js';
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@tofound/billing/testing` — the kit hosts use to prove their own stores
|
|
3
|
+
* and charge paths: the store conformance suite, the ledger invariant check,
|
|
4
|
+
* the quote/settle conformance assertion, the ingest and term store
|
|
5
|
+
* conformance suites and the memory stores.
|
|
6
|
+
*/
|
|
7
|
+
export { assertLedgerInvariants, ledgerConformanceCases, } from './conformance.js';
|
|
8
|
+
export { createMemoryLedgerStore } from './memory.js';
|
|
9
|
+
export { assertQuoteMatchesSettlement } from '../quote/conformance.js';
|
|
10
|
+
export { ingestConformanceCases } from '../inbox/conformance.js';
|
|
11
|
+
export { createMemoryIngestStore } from '../inbox/memory.js';
|
|
12
|
+
export { termConformanceCases } from '../terms/conformance.js';
|
|
13
|
+
export { createMemoryTermStore } from '../terms/memory.js';
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { TermStore } from './ports.js';
|
|
2
|
+
/**
|
|
3
|
+
* The term store conformance suite. Every `TermStore` — memory, the Drizzle
|
|
4
|
+
* store, a host adapter — must pass all of it. Each case throws on failure:
|
|
5
|
+
*
|
|
6
|
+
* for (const c of termConformanceCases) test(c.name, () => c.run(target))
|
|
7
|
+
*/
|
|
8
|
+
export interface TermConformanceTarget<TTx = unknown> {
|
|
9
|
+
store: TermStore<TTx>;
|
|
10
|
+
/** A fresh, never-used account id of the host's type. */
|
|
11
|
+
newAccountId(): string;
|
|
12
|
+
}
|
|
13
|
+
export interface TermConformanceCase {
|
|
14
|
+
name: string;
|
|
15
|
+
run<TTx>(target: TermConformanceTarget<TTx>): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export declare const termConformanceCases: TermConformanceCase[];
|