@tofound/billing 0.0.0-stage → 0.1.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 +46 -0
- package/LICENSE +3 -0
- package/README.md +34 -2
- 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 +165 -0
- package/dist/domain/types.js +18 -0
- package/dist/drizzle/index.d.ts +3 -0
- package/dist/drizzle/index.js +3 -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/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 +20 -0
- package/dist/index.js +18 -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/port.d.ts +201 -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/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 +11 -0
- package/dist/stores/testing.js +11 -0
- package/docs/API.md +198 -0
- package/docs/SCHEMA.md +108 -0
- package/package.json +75 -4
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Drizzle schema factory — the `billing.schema-factory` contract.
|
|
3
|
+
*
|
|
4
|
+
* The library never ships SQL. A host re-exports the tables from its own
|
|
5
|
+
* `schema.ts` (so its drizzle-kit glob sees them) and generates its own
|
|
6
|
+
* migration with `db:generate`. Rules every library table follows
|
|
7
|
+
* (docs/SCHEMA.md): new tables and indexes only, evolved later only with
|
|
8
|
+
* nullable columns without a volatile default, never `GENERATED … STORED`,
|
|
9
|
+
* never a statement on a host table. `checkAdditiveDdl` enforces them on
|
|
10
|
+
* generated SQL.
|
|
11
|
+
*/
|
|
12
|
+
import { sql } from 'drizzle-orm';
|
|
13
|
+
import { bigint, check, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex, varchar, } from 'drizzle-orm/pg-core';
|
|
14
|
+
export const DEFAULT_PREFIX = 'billing_';
|
|
15
|
+
/**
|
|
16
|
+
* Declares a table under the factory's schema and prefix. Other library
|
|
17
|
+
* modules (inbox, checkout sessions, purchases, terms) declare their tables
|
|
18
|
+
* through this so one host config names and places all of them.
|
|
19
|
+
*/
|
|
20
|
+
export function billingTableBuilder(config) {
|
|
21
|
+
const prefix = config.prefix ?? DEFAULT_PREFIX;
|
|
22
|
+
if (!/^[a-z][a-z0-9_]*$/.test(prefix)) {
|
|
23
|
+
throw new Error(`billing schema prefix must be lower snake case, got ${JSON.stringify(prefix)}`);
|
|
24
|
+
}
|
|
25
|
+
const table = (config.schema ? config.schema.table.bind(config.schema) : pgTable);
|
|
26
|
+
return {
|
|
27
|
+
prefix,
|
|
28
|
+
/** `prefix + name`: use for index and constraint names too. */
|
|
29
|
+
name: (name) => `${prefix}${name}`,
|
|
30
|
+
table,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** The ledger tables: one balance row per account and the append-only entries. */
|
|
34
|
+
export function createBillingTables(config) {
|
|
35
|
+
const b = billingTableBuilder(config);
|
|
36
|
+
const billingAccounts = b.table(b.name('accounts'), {
|
|
37
|
+
accountId: config.accountId('account_id'),
|
|
38
|
+
balance: bigint('balance', { mode: 'number' }).notNull().default(0),
|
|
39
|
+
seq: bigint('seq', { mode: 'number' }).notNull().default(0),
|
|
40
|
+
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
|
41
|
+
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
|
42
|
+
}, (t) => [
|
|
43
|
+
primaryKey({ name: b.name('accounts_pk'), columns: [t.accountId] }),
|
|
44
|
+
check(b.name('accounts_balance_nonneg'), sql `${t.balance} >= 0`),
|
|
45
|
+
]);
|
|
46
|
+
const billingEntries = b.table(b.name('entries'), {
|
|
47
|
+
id: varchar('id', { length: 64 }).primaryKey(),
|
|
48
|
+
accountId: config.accountId('account_id'),
|
|
49
|
+
seq: bigint('seq', { mode: 'number' }).notNull(),
|
|
50
|
+
delta: bigint('delta', { mode: 'number' }).notNull(),
|
|
51
|
+
balanceAfter: bigint('balance_after', { mode: 'number' }).notNull(),
|
|
52
|
+
kind: varchar('kind', { length: 32 }).notNull(),
|
|
53
|
+
reason: text('reason'),
|
|
54
|
+
idempotencyKey: text('idempotency_key').notNull(),
|
|
55
|
+
sourceType: varchar('source_type', { length: 64 }),
|
|
56
|
+
sourceId: text('source_id'),
|
|
57
|
+
reversesId: varchar('reverses_id', { length: 64 }),
|
|
58
|
+
meta: jsonb('meta').$type(),
|
|
59
|
+
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
|
60
|
+
}, (t) => [
|
|
61
|
+
uniqueIndex(b.name('entries_idempotency_key_uq')).on(t.idempotencyKey),
|
|
62
|
+
uniqueIndex(b.name('entries_account_seq_uq')).on(t.accountId, t.seq),
|
|
63
|
+
// NULLs are distinct, so this is "UNIQUE when not null" (design §4.3).
|
|
64
|
+
uniqueIndex(b.name('entries_reverses_id_uq')).on(t.reversesId),
|
|
65
|
+
check(b.name('entries_balance_after_nonneg'), sql `${t.balanceAfter} >= 0`),
|
|
66
|
+
]);
|
|
67
|
+
return { billingAccounts, billingEntries };
|
|
68
|
+
}
|
|
69
|
+
/** A default that is not a constant: computed per row, so ADD COLUMN rewrites the table. */
|
|
70
|
+
const VOLATILE_DEFAULT = /\b(?:"?[a-z_][a-z0-9_]*"?\s*\.\s*)?"?(now|random|gen_random_uuid|uuid_generate_v[14]|clock_timestamp|statement_timestamp|transaction_timestamp|timeofday|nextval|txid_current)"?\s*\(|\b(current_timestamp|current_date|current_time|localtimestamp|localtime)\b/i;
|
|
71
|
+
/** Column types and clauses that fill every existing row from a sequence. */
|
|
72
|
+
const SEQUENCE_FILL = /\b(small|big)?serial\b|\bserial[248]\b|\bgenerated\s+(always|by\s+default)\s+as\s+identity\b/i;
|
|
73
|
+
const IDENT = String.raw `(?:"[^"]+"|[a-z_][a-z0-9_$]*)`;
|
|
74
|
+
const QUALIFIED = String.raw `(?:${IDENT}\s*\.\s*)?(${IDENT})`;
|
|
75
|
+
function unquote(ident) {
|
|
76
|
+
return ident.startsWith('"') ? ident.slice(1, -1) : ident.toLowerCase();
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Split on `separator` outside quotes and parentheses. A dollar-quoted body
|
|
80
|
+
* (functions, DO blocks) is not parsed: it stays in one piece and is then
|
|
81
|
+
* reported as `unrecognized`.
|
|
82
|
+
*/
|
|
83
|
+
function splitTopLevel(text, separator) {
|
|
84
|
+
if (text.includes('$$'))
|
|
85
|
+
return [text];
|
|
86
|
+
const parts = [];
|
|
87
|
+
let depth = 0;
|
|
88
|
+
let quote = null;
|
|
89
|
+
let start = 0;
|
|
90
|
+
for (let i = 0; i < text.length; i++) {
|
|
91
|
+
const c = text[i];
|
|
92
|
+
if (quote) {
|
|
93
|
+
if (c === quote)
|
|
94
|
+
quote = null;
|
|
95
|
+
}
|
|
96
|
+
else if (c === '"' || c === "'")
|
|
97
|
+
quote = c;
|
|
98
|
+
else if (c === '(')
|
|
99
|
+
depth++;
|
|
100
|
+
else if (c === ')')
|
|
101
|
+
depth--;
|
|
102
|
+
else if (c === separator && depth === 0) {
|
|
103
|
+
parts.push(text.slice(start, i));
|
|
104
|
+
start = i + 1;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
parts.push(text.slice(start));
|
|
108
|
+
return parts.map((p) => p.trim()).filter(Boolean);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Check generated migration statements against the library's additive rules.
|
|
112
|
+
* `statements` are the SQL of one migration (drizzle-kit output split on
|
|
113
|
+
* `--> statement-breakpoint`, or a custom migration); an element holding
|
|
114
|
+
* several `;`-separated statements is checked statement by statement.
|
|
115
|
+
* Returns every violation; empty = safe. Unknown shapes fail closed.
|
|
116
|
+
*/
|
|
117
|
+
export function checkAdditiveDdl(statements, options) {
|
|
118
|
+
const library = new Set(options.libraryTables);
|
|
119
|
+
const violations = [];
|
|
120
|
+
const all = statements.flatMap((raw) => splitTopLevel(raw, ';'));
|
|
121
|
+
const created = new Set();
|
|
122
|
+
const createTable = new RegExp(String.raw `^create\s+table\s+(?:if\s+not\s+exists\s+)?${QUALIFIED}`, 'i');
|
|
123
|
+
for (const statement of all) {
|
|
124
|
+
const m = createTable.exec(statement);
|
|
125
|
+
if (m?.[1])
|
|
126
|
+
created.add(unquote(m[1]));
|
|
127
|
+
}
|
|
128
|
+
const flag = (rule, statement, message) => violations.push({ rule, statement, message });
|
|
129
|
+
const alterTable = new RegExp(String.raw `^alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${QUALIFIED}\s+(.*)$`, 'is');
|
|
130
|
+
const createIndex = new RegExp(String.raw `^create\s+(?:unique\s+)?index\s+(concurrently\s+)?(?:if\s+not\s+exists\s+)?${IDENT}?\s*on\s+(?:only\s+)?${QUALIFIED}`, 'i');
|
|
131
|
+
const addColumn = new RegExp(String.raw `^add\s+(?:column\s+)?(?:if\s+not\s+exists\s+)?${IDENT}\s+\S`, 'i');
|
|
132
|
+
const addConstraint = /^add\s+(?:constraint\s+\S+\s+)?(primary\s+key|unique|check|foreign\s+key|exclude)\b/i;
|
|
133
|
+
for (const statement of all) {
|
|
134
|
+
if (/\bgenerated\s+always\s+as\s*\(.*\)\s*stored\b/is.test(statement)) {
|
|
135
|
+
flag('generated_stored', statement, 'GENERATED … STORED rewrites the table; use a nullable column + trigger + batched backfill');
|
|
136
|
+
}
|
|
137
|
+
if (/^create\s+schema\b/i.test(statement))
|
|
138
|
+
continue;
|
|
139
|
+
// The migration preamble the rules require (docs/SCHEMA.md).
|
|
140
|
+
if (/^set\s+(local\s+)?(lock_timeout|statement_timeout)\b/i.test(statement))
|
|
141
|
+
continue;
|
|
142
|
+
const ct = createTable.exec(statement);
|
|
143
|
+
if (ct?.[1]) {
|
|
144
|
+
const table = unquote(ct[1]);
|
|
145
|
+
if (!library.has(table))
|
|
146
|
+
flag('non_library_table', statement, `creates ${table}, which is not a library table`);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const ci = createIndex.exec(statement);
|
|
150
|
+
if (ci?.[2]) {
|
|
151
|
+
const table = unquote(ci[2]);
|
|
152
|
+
if (!library.has(table))
|
|
153
|
+
flag('non_library_table', statement, `indexes host table ${table}`);
|
|
154
|
+
else if (!created.has(table) && !ci[1]) {
|
|
155
|
+
flag('blocking_index', statement, `index on existing ${table} blocks writes; use CREATE INDEX CONCURRENTLY in a custom migration`);
|
|
156
|
+
}
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const at = alterTable.exec(statement);
|
|
160
|
+
if (at?.[1]) {
|
|
161
|
+
const table = unquote(at[1]);
|
|
162
|
+
if (!library.has(table)) {
|
|
163
|
+
flag('non_library_table', statement, `alters host table ${table}`);
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const isNew = created.has(table);
|
|
167
|
+
for (const action of splitTopLevel(at[2] ?? '', ','))
|
|
168
|
+
checkAlterAction(table, isNew, action, statement);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
if (/^(drop|truncate|delete|update|insert|alter|rename|comment|grant|revoke)\b/i.test(statement)) {
|
|
172
|
+
flag('destructive', statement, 'only CREATE TABLE / CREATE INDEX / ADD COLUMN / ADD CONSTRAINT are additive');
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
flag('unrecognized', statement, 'statement is not one the additive rules recognise');
|
|
176
|
+
}
|
|
177
|
+
return violations;
|
|
178
|
+
function checkAlterAction(table, isNew, action, statement) {
|
|
179
|
+
const constraint = addConstraint.exec(action);
|
|
180
|
+
if (constraint?.[1] || /^add\s+constraint\b/i.test(action)) {
|
|
181
|
+
if (isNew)
|
|
182
|
+
return;
|
|
183
|
+
const kind = (constraint?.[1] ?? '').toLowerCase();
|
|
184
|
+
if (/^(primary|unique|exclude)/.test(kind)) {
|
|
185
|
+
// Builds an index under ACCESS EXCLUSIVE unless it adopts a prebuilt one.
|
|
186
|
+
if (!/\busing\s+index\b/i.test(action)) {
|
|
187
|
+
flag('blocking_index', statement, `${kind.toUpperCase()} on existing ${table} builds an index under lock; CREATE UNIQUE INDEX CONCURRENTLY, then ADD CONSTRAINT … USING INDEX`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
else if (!/\bnot\s+valid\b/i.test(action)) {
|
|
191
|
+
flag('validating_constraint', statement, `constraint on existing ${table} scans it under lock; add it NOT VALID and VALIDATE separately`);
|
|
192
|
+
}
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (addColumn.test(action)) {
|
|
196
|
+
if (VOLATILE_DEFAULT.test(action) || SEQUENCE_FILL.test(action)) {
|
|
197
|
+
flag('volatile_default', statement, 'ADD COLUMN with a per-row (volatile or sequence) default rewrites every row');
|
|
198
|
+
}
|
|
199
|
+
if (!isNew && /\bnot\s+null\b/i.test(action)) {
|
|
200
|
+
flag('not_null_add_column', statement, 'ADD COLUMN on an existing table must be nullable');
|
|
201
|
+
}
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
flag('destructive', statement, `ALTER TABLE ${table} ${action.split(/\s+/).slice(0, 3).join(' ')} is not additive`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { PgDatabase, PgTable, PgQueryResultHKT, PgTransaction } from 'drizzle-orm/pg-core';
|
|
2
|
+
import type { LedgerStore } from '../ports/ledger-store.js';
|
|
3
|
+
/** Any Drizzle Postgres database (postgres-js, node-postgres, …). */
|
|
4
|
+
export type AnyPgDatabase = PgDatabase<PgQueryResultHKT, any, any>;
|
|
5
|
+
/** A transaction of that database, as handed to `db.transaction(fn)`. */
|
|
6
|
+
export type AnyPgTransaction = PgTransaction<PgQueryResultHKT, any, any>;
|
|
7
|
+
export interface DrizzleLedgerStoreOptions {
|
|
8
|
+
db: AnyPgDatabase;
|
|
9
|
+
/** The host's factory tables (`createBillingTables(...)`), whatever its account column type. */
|
|
10
|
+
tables: {
|
|
11
|
+
billingAccounts: PgTable;
|
|
12
|
+
billingEntries: PgTable;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Postgres `LedgerStore` over the factory tables. `bind(tx)` takes the host's
|
|
17
|
+
* own Drizzle transaction, so a posting commits or rolls back with the host's
|
|
18
|
+
* other writes. Expects READ COMMITTED (the Postgres default).
|
|
19
|
+
*/
|
|
20
|
+
export declare function createDrizzleLedgerStore(options: DrizzleLedgerStoreOptions): LedgerStore<AnyPgTransaction>;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { and, desc, eq, lt } from 'drizzle-orm';
|
|
2
|
+
/**
|
|
3
|
+
* Postgres `LedgerStore` over the factory tables. `bind(tx)` takes the host's
|
|
4
|
+
* own Drizzle transaction, so a posting commits or rolls back with the host's
|
|
5
|
+
* other writes. Expects READ COMMITTED (the Postgres default).
|
|
6
|
+
*/
|
|
7
|
+
export function createDrizzleLedgerStore(options) {
|
|
8
|
+
const { db } = options;
|
|
9
|
+
// The account column's TS type is whatever the host's builder declares; the
|
|
10
|
+
// library only ever writes and reads the subject id as a string.
|
|
11
|
+
const accounts = options.tables.billingAccounts;
|
|
12
|
+
const entries = options.tables.billingEntries;
|
|
13
|
+
const toEntry = (row) => ({
|
|
14
|
+
id: row.id,
|
|
15
|
+
accountId: String(row.accountId),
|
|
16
|
+
seq: row.seq,
|
|
17
|
+
delta: row.delta,
|
|
18
|
+
balanceAfter: row.balanceAfter,
|
|
19
|
+
kind: row.kind,
|
|
20
|
+
reason: row.reason,
|
|
21
|
+
idempotencyKey: row.idempotencyKey,
|
|
22
|
+
sourceType: row.sourceType,
|
|
23
|
+
sourceId: row.sourceId,
|
|
24
|
+
reversesId: row.reversesId,
|
|
25
|
+
meta: row.meta ?? null,
|
|
26
|
+
createdAt: row.createdAt,
|
|
27
|
+
});
|
|
28
|
+
const reader = (ex) => ({
|
|
29
|
+
async getAccount(accountId) {
|
|
30
|
+
const [row] = await ex
|
|
31
|
+
.select({ accountId: accounts.accountId, balance: accounts.balance, seq: accounts.seq })
|
|
32
|
+
.from(accounts)
|
|
33
|
+
.where(eq(accounts.accountId, accountId));
|
|
34
|
+
return row ? { accountId: String(row.accountId), balance: row.balance, seq: row.seq } : null;
|
|
35
|
+
},
|
|
36
|
+
async getEntry(id) {
|
|
37
|
+
const [row] = await ex.select().from(entries).where(eq(entries.id, id));
|
|
38
|
+
return row ? toEntry(row) : null;
|
|
39
|
+
},
|
|
40
|
+
async findEntryByKey(key) {
|
|
41
|
+
const [row] = await ex.select().from(entries).where(eq(entries.idempotencyKey, key));
|
|
42
|
+
return row ? toEntry(row) : null;
|
|
43
|
+
},
|
|
44
|
+
async listEntries(accountId, opts) {
|
|
45
|
+
const scope = eq(entries.accountId, accountId);
|
|
46
|
+
const rows = await ex
|
|
47
|
+
.select()
|
|
48
|
+
.from(entries)
|
|
49
|
+
.where(opts.beforeSeq === undefined ? scope : and(scope, lt(entries.seq, opts.beforeSeq)))
|
|
50
|
+
.orderBy(desc(entries.seq))
|
|
51
|
+
.limit(opts.limit);
|
|
52
|
+
return rows.map(toEntry);
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
const bind = (tx) => {
|
|
56
|
+
async function selectForUpdate(accountId) {
|
|
57
|
+
const [row] = await tx
|
|
58
|
+
.select({ accountId: accounts.accountId, balance: accounts.balance, seq: accounts.seq })
|
|
59
|
+
.from(accounts)
|
|
60
|
+
.where(eq(accounts.accountId, accountId))
|
|
61
|
+
.for('update');
|
|
62
|
+
return row ? { accountId: String(row.accountId), balance: row.balance, seq: row.seq } : null;
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
...reader(tx),
|
|
66
|
+
async lockAccount(accountId) {
|
|
67
|
+
// One round trip once the account exists; the insert only runs for a new one.
|
|
68
|
+
const locked = await selectForUpdate(accountId);
|
|
69
|
+
if (locked)
|
|
70
|
+
return locked;
|
|
71
|
+
const created = await tx
|
|
72
|
+
.insert(accounts)
|
|
73
|
+
.values({ accountId: accountId, balance: 0, seq: 0 })
|
|
74
|
+
.onConflictDoNothing({ target: accounts.accountId })
|
|
75
|
+
.returning({ accountId: accounts.accountId });
|
|
76
|
+
// Our own uncommitted insert is already ours; a concurrent creator's
|
|
77
|
+
// committed row is visible to the next statement under READ COMMITTED.
|
|
78
|
+
if (created.length === 1)
|
|
79
|
+
return { accountId, balance: 0, seq: 0 };
|
|
80
|
+
const row = await selectForUpdate(accountId);
|
|
81
|
+
if (!row)
|
|
82
|
+
throw new Error(`billing account ${accountId} vanished after insert-or-lock`);
|
|
83
|
+
return row;
|
|
84
|
+
},
|
|
85
|
+
async findReversalOf(entryId) {
|
|
86
|
+
const [row] = await tx.select().from(entries).where(eq(entries.reversesId, entryId));
|
|
87
|
+
return row ? toEntry(row) : null;
|
|
88
|
+
},
|
|
89
|
+
async appendEntry(entry) {
|
|
90
|
+
const inserted = await tx
|
|
91
|
+
.insert(entries)
|
|
92
|
+
.values({
|
|
93
|
+
id: entry.id,
|
|
94
|
+
accountId: entry.accountId,
|
|
95
|
+
seq: entry.seq,
|
|
96
|
+
delta: entry.delta,
|
|
97
|
+
balanceAfter: entry.balanceAfter,
|
|
98
|
+
kind: entry.kind,
|
|
99
|
+
reason: entry.reason,
|
|
100
|
+
idempotencyKey: entry.idempotencyKey,
|
|
101
|
+
sourceType: entry.sourceType,
|
|
102
|
+
sourceId: entry.sourceId,
|
|
103
|
+
reversesId: entry.reversesId,
|
|
104
|
+
meta: entry.meta,
|
|
105
|
+
createdAt: entry.createdAt,
|
|
106
|
+
})
|
|
107
|
+
.onConflictDoNothing()
|
|
108
|
+
.returning({ id: entries.id });
|
|
109
|
+
return { inserted: inserted.length === 1 };
|
|
110
|
+
},
|
|
111
|
+
async setAccountState(state) {
|
|
112
|
+
await tx
|
|
113
|
+
.update(accounts)
|
|
114
|
+
.set({ balance: state.balance, seq: state.seq, updatedAt: new Date() })
|
|
115
|
+
.where(eq(accounts.accountId, state.accountId));
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
return {
|
|
120
|
+
transaction: (fn) => db.transaction((tx) => fn(tx)),
|
|
121
|
+
bind,
|
|
122
|
+
reader: () => reader(db),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { AccountId, BillingEvent } from '../domain/types.js';
|
|
2
|
+
import type { LedgerOps } from '../ledger/ledger.js';
|
|
3
|
+
import type { NormalizedEvent, PurchaseChangedEvent, PurchaseCompletedEvent, VerifiedDelivery } from '../providers/port.js';
|
|
4
|
+
import type { IngestTx } from './ports.js';
|
|
5
|
+
export type ApplyStatus = 'applied' | 'ignored' | 'needs_review';
|
|
6
|
+
export interface ApplyResult {
|
|
7
|
+
status: ApplyStatus;
|
|
8
|
+
reason?: string;
|
|
9
|
+
/** No session or purchase on this host owns the event (the `onUnmatched` hook may forward it). */
|
|
10
|
+
unmatched?: boolean;
|
|
11
|
+
/** Ledger events to emit after commit. */
|
|
12
|
+
events?: BillingEvent[];
|
|
13
|
+
/** Reversal facts for the host's shortfall policy. */
|
|
14
|
+
reversal?: PurchaseReversed;
|
|
15
|
+
}
|
|
16
|
+
export interface PurchaseReversed {
|
|
17
|
+
accountId: AccountId;
|
|
18
|
+
provider: string;
|
|
19
|
+
externalId: string;
|
|
20
|
+
/** Credits actually taken back. */
|
|
21
|
+
clawedBack: number;
|
|
22
|
+
/** Credits the balance could not cover. */
|
|
23
|
+
shortfall: number;
|
|
24
|
+
}
|
|
25
|
+
/** What a host handler gets for event kinds the library does not apply itself (P1: subscriptions). */
|
|
26
|
+
export interface ApplyContext<TTx = unknown> {
|
|
27
|
+
tx: TTx;
|
|
28
|
+
ledger: LedgerOps;
|
|
29
|
+
delivery: VerifiedDelivery;
|
|
30
|
+
now: Date;
|
|
31
|
+
}
|
|
32
|
+
export type EventHandler<TTx = unknown> = (event: NormalizedEvent, ctx: ApplyContext<TTx>) => Promise<ApplyResult>;
|
|
33
|
+
interface Deps {
|
|
34
|
+
tx: IngestTx;
|
|
35
|
+
ledger: LedgerOps;
|
|
36
|
+
delivery: VerifiedDelivery;
|
|
37
|
+
now: Date;
|
|
38
|
+
newId: () => string;
|
|
39
|
+
}
|
|
40
|
+
export declare function applyPurchaseCompleted(event: PurchaseCompletedEvent, d: Deps): Promise<ApplyResult>;
|
|
41
|
+
/**
|
|
42
|
+
* `purchase.reversed` / `purchase.reinstated`. Only an event newer than the
|
|
43
|
+
* purchase's watermark changes it, so redelivered or out-of-order events
|
|
44
|
+
* cannot regress state; whatever order capture, reversal and reinstatement
|
|
45
|
+
* arrive in, the purchase ends where the newest event puts it.
|
|
46
|
+
*/
|
|
47
|
+
export declare function applyPurchaseChanged(event: PurchaseChangedEvent, d: Deps): Promise<ApplyResult>;
|
|
48
|
+
export {};
|