@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,404 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ingest service (design §6): one path from a provider delivery to the
|
|
3
|
+
* ledger. `handle` verifies (nothing stored on failure), records the redacted
|
|
4
|
+
* delivery in the inbox, then normalizes and applies it in one transaction
|
|
5
|
+
* — inbox → checkout session → purchase → account, the ledger last.
|
|
6
|
+
*
|
|
7
|
+
* - A final row (`applied`, `ignored`, `needs_review`, `dead`) answers a
|
|
8
|
+
* redelivery `duplicate` and is never re-applied, except by `replay`.
|
|
9
|
+
* - A thrown error rolls the apply back: a `BillingError` is permanent
|
|
10
|
+
* (`needs_review`, acknowledged); anything else is transient (`failed`,
|
|
11
|
+
* 5xx so the provider redelivers, and `sweep` retries it with backoff
|
|
12
|
+
* until `maxAttempts`, then `dead` plus an alert).
|
|
13
|
+
* - A row left `received` by a crash is due after `staleAfterMs` and is
|
|
14
|
+
* re-entered by `sweep`.
|
|
15
|
+
* - Every money effect is keyed in the ledger, so a race between `handle`,
|
|
16
|
+
* `sweep` and `replay` still credits once.
|
|
17
|
+
*/
|
|
18
|
+
import { randomUUID } from 'node:crypto';
|
|
19
|
+
import { isBillingError } from '../domain/errors.js';
|
|
20
|
+
import { isCheckoutCapable, isPurchaseVerifier, isVerifyError, ProviderConfigError, } from '../providers/port.js';
|
|
21
|
+
import { applyPurchaseChanged, applyPurchaseCompleted, } from './apply.js';
|
|
22
|
+
import { FINAL_INBOX_STATUSES } from './ports.js';
|
|
23
|
+
import { redactPayload } from './redact.js';
|
|
24
|
+
const DEFAULT_MAX_ATTEMPTS = 8;
|
|
25
|
+
const DEFAULT_STALE_AFTER_MS = 5 * 60_000;
|
|
26
|
+
const defaultBackoff = (attempt) => Math.min(30_000 * 2 ** (attempt - 1), 6 * 3_600_000);
|
|
27
|
+
export function createIngest(options) {
|
|
28
|
+
const { store, ledger } = options;
|
|
29
|
+
const clock = options.clock ?? { now: () => new Date() };
|
|
30
|
+
const ids = options.ids ?? randomUUID;
|
|
31
|
+
const maxAttempts = options.policy?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
32
|
+
const backoff = options.policy?.backoff ?? defaultBackoff;
|
|
33
|
+
const staleAfterMs = options.policy?.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;
|
|
34
|
+
if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1)
|
|
35
|
+
throw new ProviderConfigError('invalid_policy', 'maxAttempts must be ≥ 1');
|
|
36
|
+
const adapters = new Map();
|
|
37
|
+
for (const adapter of options.adapters) {
|
|
38
|
+
if (adapters.has(adapter.id))
|
|
39
|
+
throw new ProviderConfigError('duplicate_adapter', `two adapters for ${adapter.id}`);
|
|
40
|
+
adapters.set(adapter.id, adapter);
|
|
41
|
+
}
|
|
42
|
+
const adapterFor = (provider) => {
|
|
43
|
+
const adapter = adapters.get(provider);
|
|
44
|
+
if (!adapter)
|
|
45
|
+
throw new ProviderConfigError('unknown_provider', `no adapter registered for ${provider}`);
|
|
46
|
+
return adapter;
|
|
47
|
+
};
|
|
48
|
+
async function emit(events) {
|
|
49
|
+
if (!options.events)
|
|
50
|
+
return;
|
|
51
|
+
for (const event of events) {
|
|
52
|
+
try {
|
|
53
|
+
await options.events(event);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
// Reported after commit; a failing sink must not turn success into a retry.
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const webhook = (row, outcome, reason) => ({
|
|
61
|
+
type: 'billing.webhook',
|
|
62
|
+
provider: row.provider,
|
|
63
|
+
eventType: row.eventType,
|
|
64
|
+
eventId: row.eventId,
|
|
65
|
+
outcome,
|
|
66
|
+
reason,
|
|
67
|
+
});
|
|
68
|
+
/** Store the delivery (or count a redelivery) in its own short transaction. */
|
|
69
|
+
async function receive(adapter, delivery) {
|
|
70
|
+
const now = clock.now();
|
|
71
|
+
const payload = adapter.redact ? adapter.redact(delivery.payload) : redactPayload(delivery.payload);
|
|
72
|
+
const row = {
|
|
73
|
+
id: ids(),
|
|
74
|
+
provider: delivery.provider,
|
|
75
|
+
environment: delivery.environment,
|
|
76
|
+
eventId: delivery.eventId,
|
|
77
|
+
eventType: delivery.eventType,
|
|
78
|
+
subjectRef: delivery.subjectRef ?? null,
|
|
79
|
+
status: 'received',
|
|
80
|
+
attempts: 0,
|
|
81
|
+
deliveryCount: 1,
|
|
82
|
+
nextAttemptAt: new Date(now.getTime() + staleAfterMs),
|
|
83
|
+
lastError: null,
|
|
84
|
+
reason: null,
|
|
85
|
+
payload: payload ?? {},
|
|
86
|
+
occurredAt: delivery.occurredAt,
|
|
87
|
+
receivedAt: now,
|
|
88
|
+
lastReceivedAt: now,
|
|
89
|
+
processedAt: null,
|
|
90
|
+
};
|
|
91
|
+
return store.transaction((tx) => store.bind(tx).receive(row));
|
|
92
|
+
}
|
|
93
|
+
/** The delivery as `normalize` sees it on every run: rebuilt from the stored redacted row. */
|
|
94
|
+
const storedDelivery = (row) => ({
|
|
95
|
+
provider: row.provider,
|
|
96
|
+
environment: row.environment,
|
|
97
|
+
eventId: row.eventId,
|
|
98
|
+
eventType: row.eventType,
|
|
99
|
+
occurredAt: row.occurredAt,
|
|
100
|
+
payload: row.payload,
|
|
101
|
+
...(row.subjectRef ? { subjectRef: row.subjectRef } : {}),
|
|
102
|
+
});
|
|
103
|
+
async function applyEvent(event, tx, delivery, now) {
|
|
104
|
+
const ops = ledger.in(tx);
|
|
105
|
+
const handler = options.handlers?.[event.kind];
|
|
106
|
+
if (handler)
|
|
107
|
+
return handler(event, { tx, ledger: ops, delivery, now });
|
|
108
|
+
const deps = { tx: store.bind(tx), ledger: ops, delivery, now, newId: ids };
|
|
109
|
+
switch (event.kind) {
|
|
110
|
+
case 'purchase.completed':
|
|
111
|
+
return applyPurchaseCompleted(event, deps);
|
|
112
|
+
case 'purchase.reversed':
|
|
113
|
+
case 'purchase.reinstated':
|
|
114
|
+
return applyPurchaseChanged(event, deps);
|
|
115
|
+
case 'ignored':
|
|
116
|
+
return { status: 'ignored', reason: event.reason };
|
|
117
|
+
case 'needs_review':
|
|
118
|
+
return { status: 'needs_review', reason: event.reason };
|
|
119
|
+
case 'subscription.snapshot':
|
|
120
|
+
// Terms arrive in P2; until a handler is wired, keep it for a replay.
|
|
121
|
+
return { status: 'needs_review', reason: 'no_handler:subscription.snapshot' };
|
|
122
|
+
default:
|
|
123
|
+
return { status: 'ignored', reason: `no_handler:${event.kind}` };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** Worst status wins: needs_review > applied > ignored. */
|
|
127
|
+
function combine(results) {
|
|
128
|
+
if (results.length === 0)
|
|
129
|
+
return { status: 'ignored', reason: 'no_events' };
|
|
130
|
+
const pick = results.find((r) => r.status === 'needs_review') ?? results.find((r) => r.status === 'applied') ?? results[0];
|
|
131
|
+
const reason = pick.reason ?? results.find((r) => r.reason)?.reason;
|
|
132
|
+
const reversal = results.find((r) => r.reversal)?.reversal;
|
|
133
|
+
return {
|
|
134
|
+
status: pick.status,
|
|
135
|
+
...(reason ? { reason } : {}),
|
|
136
|
+
unmatched: results.every((r) => r.unmatched === true),
|
|
137
|
+
events: results.flatMap((r) => r.events ?? []),
|
|
138
|
+
...(reversal ? { reversal } : {}),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Normalize and apply one stored row. `manual` (replay) re-opens a final
|
|
143
|
+
* `needs_review`/`dead` row with a fresh retry budget.
|
|
144
|
+
*/
|
|
145
|
+
async function process(row, manual) {
|
|
146
|
+
const adapter = adapterFor(row.provider);
|
|
147
|
+
const delivery = storedDelivery(row);
|
|
148
|
+
const now = clock.now();
|
|
149
|
+
try {
|
|
150
|
+
const events = await adapter.normalize(delivery, { now });
|
|
151
|
+
const result = await store.transaction(async (tx) => {
|
|
152
|
+
const itx = store.bind(tx);
|
|
153
|
+
const locked = await itx.lockInbox(row.provider, row.eventId);
|
|
154
|
+
if (!locked)
|
|
155
|
+
return null;
|
|
156
|
+
const reopen = manual && (locked.status === 'needs_review' || locked.status === 'dead');
|
|
157
|
+
if (FINAL_INBOX_STATUSES.has(locked.status) && !reopen)
|
|
158
|
+
return { status: 'ignored', skipped: locked };
|
|
159
|
+
const applied = combine(await sequential(events, (event) => applyEvent(event, tx, delivery, now)));
|
|
160
|
+
await itx.updateInbox(locked.id, {
|
|
161
|
+
status: applied.status,
|
|
162
|
+
attempts: (reopen ? 0 : locked.attempts) + 1,
|
|
163
|
+
nextAttemptAt: null,
|
|
164
|
+
lastError: null,
|
|
165
|
+
reason: applied.reason ?? null,
|
|
166
|
+
processedAt: now,
|
|
167
|
+
});
|
|
168
|
+
return applied;
|
|
169
|
+
});
|
|
170
|
+
if (!result)
|
|
171
|
+
throw new Error(`inbox row ${row.provider}/${row.eventId} not found`);
|
|
172
|
+
if (result.skipped) {
|
|
173
|
+
await emit([webhook(row, 'duplicate', result.skipped.reason)]);
|
|
174
|
+
return { status: 'duplicate', eventId: row.eventId, ...(result.skipped.reason ? { reason: result.skipped.reason } : {}) };
|
|
175
|
+
}
|
|
176
|
+
const after = [...(result.events ?? []), webhook(row, result.status, result.reason ?? null)];
|
|
177
|
+
if (result.reversal)
|
|
178
|
+
after.push({ type: 'refund_applied', ...result.reversal });
|
|
179
|
+
if (result.status === 'needs_review') {
|
|
180
|
+
after.push({ type: 'billing.alert', alert: 'inbox_needs_review', provider: row.provider, eventId: row.eventId, reason: result.reason ?? null });
|
|
181
|
+
}
|
|
182
|
+
await emit(after);
|
|
183
|
+
return {
|
|
184
|
+
status: result.status,
|
|
185
|
+
eventId: row.eventId,
|
|
186
|
+
...(result.reason ? { reason: result.reason } : {}),
|
|
187
|
+
...(result.unmatched ? { unmatched: true } : {}),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
return fail(row, error, manual);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/** Record a failed attempt: permanent → needs_review; transient → failed with backoff, or dead. */
|
|
195
|
+
async function fail(row, error, manual) {
|
|
196
|
+
const now = clock.now();
|
|
197
|
+
const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
198
|
+
const permanent = isBillingError(error);
|
|
199
|
+
const marked = await store.transaction(async (tx) => {
|
|
200
|
+
const itx = store.bind(tx);
|
|
201
|
+
const locked = await itx.lockInbox(row.provider, row.eventId);
|
|
202
|
+
if (!locked)
|
|
203
|
+
return null;
|
|
204
|
+
const reopen = manual && (locked.status === 'needs_review' || locked.status === 'dead');
|
|
205
|
+
// A concurrent run finished it meanwhile: its outcome stands.
|
|
206
|
+
if (FINAL_INBOX_STATUSES.has(locked.status) && !reopen)
|
|
207
|
+
return { ...locked, skipped: true };
|
|
208
|
+
const attempts = (reopen ? 0 : locked.attempts) + 1;
|
|
209
|
+
const status = permanent ? 'needs_review' : attempts >= maxAttempts ? 'dead' : 'failed';
|
|
210
|
+
const patch = {
|
|
211
|
+
status,
|
|
212
|
+
attempts,
|
|
213
|
+
nextAttemptAt: status === 'failed' ? new Date(now.getTime() + backoff(attempts)) : null,
|
|
214
|
+
lastError: message.slice(0, 2000),
|
|
215
|
+
reason: permanent ? `billing_error:${error.code}` : null,
|
|
216
|
+
processedAt: now,
|
|
217
|
+
};
|
|
218
|
+
await itx.updateInbox(locked.id, patch);
|
|
219
|
+
return { ...locked, ...patch, skipped: false };
|
|
220
|
+
});
|
|
221
|
+
if (!marked)
|
|
222
|
+
throw error;
|
|
223
|
+
if (marked.skipped) {
|
|
224
|
+
await emit([webhook(row, 'duplicate', marked.reason)]);
|
|
225
|
+
return { status: 'duplicate', eventId: row.eventId };
|
|
226
|
+
}
|
|
227
|
+
const status = marked.status;
|
|
228
|
+
const events = [webhook(row, status, marked.reason ?? message)];
|
|
229
|
+
if (status !== 'failed') {
|
|
230
|
+
events.push({
|
|
231
|
+
type: 'billing.alert',
|
|
232
|
+
alert: status === 'dead' ? 'inbox_dead' : 'inbox_needs_review',
|
|
233
|
+
provider: row.provider,
|
|
234
|
+
eventId: row.eventId,
|
|
235
|
+
reason: marked.reason ?? message,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
await emit(events);
|
|
239
|
+
return { status, eventId: row.eventId, reason: marked.reason ?? 'transient_error' };
|
|
240
|
+
}
|
|
241
|
+
/** Receive then process; a redelivery of a final row is `duplicate`. */
|
|
242
|
+
async function ingestDelivery(adapter, delivery) {
|
|
243
|
+
let received;
|
|
244
|
+
try {
|
|
245
|
+
received = await receive(adapter, delivery);
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
// Not even recorded: the provider must redeliver.
|
|
249
|
+
await emit([webhook(delivery, 'failed', error instanceof Error ? error.message : String(error))]);
|
|
250
|
+
return { status: 'failed', eventId: delivery.eventId, reason: 'inbox_unavailable' };
|
|
251
|
+
}
|
|
252
|
+
const { row, inserted } = received;
|
|
253
|
+
if (!inserted && FINAL_INBOX_STATUSES.has(row.status)) {
|
|
254
|
+
await emit([webhook(row, 'duplicate', row.reason)]);
|
|
255
|
+
return {
|
|
256
|
+
status: 'duplicate',
|
|
257
|
+
eventId: row.eventId,
|
|
258
|
+
...(row.reason ? { reason: row.reason } : {}),
|
|
259
|
+
...(row.reason === 'no_match' ? { unmatched: true } : {}),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
return process(row, false);
|
|
263
|
+
}
|
|
264
|
+
return {
|
|
265
|
+
async handle(provider, req) {
|
|
266
|
+
const adapter = adapterFor(provider);
|
|
267
|
+
let delivery;
|
|
268
|
+
try {
|
|
269
|
+
delivery = await adapter.verify(req);
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
if (!isVerifyError(error)) {
|
|
273
|
+
// e.g. a certificate fetch failed: nothing stored, the provider retries.
|
|
274
|
+
await emit([{ type: 'billing.webhook', provider, eventType: null, eventId: null, outcome: 'failed', reason: 'verify_error' }]);
|
|
275
|
+
const outcome = { status: 'failed', reason: 'verify_error' };
|
|
276
|
+
return { ...outcome, response: adapter.respond(outcome) };
|
|
277
|
+
}
|
|
278
|
+
await emit([{ type: 'billing.webhook', provider, eventType: null, eventId: null, outcome: 'verify_failed', reason: error.code }]);
|
|
279
|
+
const outcome = { status: error.code, reason: error.message };
|
|
280
|
+
return { ...outcome, response: adapter.respond(outcome) };
|
|
281
|
+
}
|
|
282
|
+
const { unmatched, ...outcome } = await ingestDelivery(adapter, delivery);
|
|
283
|
+
if (unmatched && options.onUnmatched && (outcome.status === 'ignored' || outcome.status === 'duplicate')) {
|
|
284
|
+
try {
|
|
285
|
+
const relay = await options.onUnmatched({ provider, request: req, delivery });
|
|
286
|
+
if (relay)
|
|
287
|
+
outcome.relay = relay;
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
const failed = { status: 'failed', eventId: delivery.eventId, reason: 'unmatched_hook_failed' };
|
|
291
|
+
return { ...failed, response: adapter.respond(failed) };
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return { ...outcome, response: adapter.respond(outcome) };
|
|
295
|
+
},
|
|
296
|
+
async confirm(provider, proof) {
|
|
297
|
+
const adapter = adapterFor(provider);
|
|
298
|
+
if (!isPurchaseVerifier(adapter))
|
|
299
|
+
throw new ProviderConfigError('not_verifiable', `${provider} cannot verify purchases`);
|
|
300
|
+
const delivery = await adapter.verifyPurchase(proof);
|
|
301
|
+
if (!delivery)
|
|
302
|
+
return { status: 'ignored', reason: 'not_paid' };
|
|
303
|
+
const { unmatched: _, ...outcome } = await ingestDelivery(adapter, delivery);
|
|
304
|
+
return outcome;
|
|
305
|
+
},
|
|
306
|
+
async replay(provider, eventId) {
|
|
307
|
+
const row = await store.reader().getInbox(provider, eventId);
|
|
308
|
+
if (!row)
|
|
309
|
+
throw new ProviderConfigError('inbox_row_not_found', `no inbox row ${provider}/${eventId}`);
|
|
310
|
+
if (row.status === 'applied' || row.status === 'ignored') {
|
|
311
|
+
await emit([webhook(row, 'duplicate', row.reason)]);
|
|
312
|
+
return { status: 'duplicate', eventId, ...(row.reason ? { reason: row.reason } : {}) };
|
|
313
|
+
}
|
|
314
|
+
const { unmatched: _, ...outcome } = await process(row, true);
|
|
315
|
+
return outcome;
|
|
316
|
+
},
|
|
317
|
+
async sweep(opts = {}) {
|
|
318
|
+
const now = opts.now ?? clock.now();
|
|
319
|
+
// Only rows this ingest has an adapter for: another deployment's rows
|
|
320
|
+
// must not stall the queue head.
|
|
321
|
+
const due = await store.reader().listDue(now, opts.limit ?? 100, [...adapters.keys()]);
|
|
322
|
+
const result = { processed: 0, applied: 0, failed: 0, dead: 0 };
|
|
323
|
+
for (const row of due) {
|
|
324
|
+
let outcome;
|
|
325
|
+
try {
|
|
326
|
+
outcome = await process(row, false);
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
// The store could not even record the failure; the row stays due
|
|
330
|
+
// for the next sweep, and the rows behind it still run.
|
|
331
|
+
outcome = { status: 'failed', eventId: row.eventId };
|
|
332
|
+
}
|
|
333
|
+
result.processed++;
|
|
334
|
+
if (outcome.status === 'applied')
|
|
335
|
+
result.applied++;
|
|
336
|
+
else if (outcome.status === 'failed')
|
|
337
|
+
result.failed++;
|
|
338
|
+
else if (outcome.status === 'dead')
|
|
339
|
+
result.dead++;
|
|
340
|
+
}
|
|
341
|
+
return result;
|
|
342
|
+
},
|
|
343
|
+
async createCheckout(input) {
|
|
344
|
+
const adapter = adapterFor(input.provider);
|
|
345
|
+
if (!isCheckoutCapable(adapter))
|
|
346
|
+
throw new ProviderConfigError('not_checkout_capable', `${input.provider} has no checkout`);
|
|
347
|
+
if (!Number.isSafeInteger(input.credits) || input.credits <= 0) {
|
|
348
|
+
throw new ProviderConfigError('invalid_credits', 'credits must be a positive safe integer');
|
|
349
|
+
}
|
|
350
|
+
if (!Number.isSafeInteger(input.amount.amountMinor) || input.amount.amountMinor <= 0) {
|
|
351
|
+
throw new ProviderConfigError('invalid_amount', 'amount must be a positive safe integer');
|
|
352
|
+
}
|
|
353
|
+
const now = clock.now();
|
|
354
|
+
const session = {
|
|
355
|
+
id: ids(),
|
|
356
|
+
accountId: input.accountId,
|
|
357
|
+
provider: input.provider,
|
|
358
|
+
environment: adapter.environment,
|
|
359
|
+
status: 'pending',
|
|
360
|
+
amount: { ...input.amount },
|
|
361
|
+
credits: input.credits,
|
|
362
|
+
productRef: input.productRef ?? null,
|
|
363
|
+
externalId: null,
|
|
364
|
+
expiresAt: new Date(now.getTime() + (input.ttlMs ?? 30 * 60_000)),
|
|
365
|
+
completedAt: null,
|
|
366
|
+
meta: input.meta ?? null,
|
|
367
|
+
createdAt: now,
|
|
368
|
+
updatedAt: now,
|
|
369
|
+
};
|
|
370
|
+
// Sign first: a provider refusal leaves no orphan session behind.
|
|
371
|
+
const redirect = await adapter.createCheckout({
|
|
372
|
+
sessionId: session.id,
|
|
373
|
+
accountId: session.accountId,
|
|
374
|
+
amount: session.amount,
|
|
375
|
+
description: input.description,
|
|
376
|
+
successUrl: input.successUrl,
|
|
377
|
+
errorUrl: input.errorUrl,
|
|
378
|
+
cancelUrl: input.cancelUrl,
|
|
379
|
+
productRef: session.productRef,
|
|
380
|
+
});
|
|
381
|
+
await store.transaction((tx) => store.bind(tx).insertSession(session));
|
|
382
|
+
return { session, redirect };
|
|
383
|
+
},
|
|
384
|
+
async closeCheckout(sessionId, status) {
|
|
385
|
+
return store.transaction(async (tx) => {
|
|
386
|
+
const itx = store.bind(tx);
|
|
387
|
+
const session = await itx.lockSession(sessionId);
|
|
388
|
+
if (!session)
|
|
389
|
+
return null;
|
|
390
|
+
if (session.status !== 'pending')
|
|
391
|
+
return session;
|
|
392
|
+
await itx.updateSession(sessionId, { status });
|
|
393
|
+
return itx.getSession(sessionId);
|
|
394
|
+
});
|
|
395
|
+
},
|
|
396
|
+
reader: () => store.reader(),
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
async function sequential(items, fn) {
|
|
400
|
+
const out = [];
|
|
401
|
+
for (const item of items)
|
|
402
|
+
out.push(await fn(item));
|
|
403
|
+
return out;
|
|
404
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { MemoryLedgerStore, MemoryTx } from '../stores/memory.js';
|
|
2
|
+
import type { InboxRow, IngestStore } from './ports.js';
|
|
3
|
+
export interface MemoryIngestStore extends IngestStore<MemoryTx> {
|
|
4
|
+
/** Committed inbox rows, oldest first (test inspection). */
|
|
5
|
+
dumpInbox(): InboxRow[];
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* In-process `IngestStore` paired with a memory ledger store: it runs inside
|
|
9
|
+
* that store's transactions (one store-wide mutex, the memory analogue of
|
|
10
|
+
* row locks) and commits its staged rows in the same step, so an inbox row,
|
|
11
|
+
* a purchase and a ledger entry land together or not at all.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createMemoryIngestStore(ledgerStore: MemoryLedgerStore): MemoryIngestStore;
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
const inboxKey = (provider, eventId) => `${provider}\u0000${eventId}`;
|
|
2
|
+
const purchaseKey = (provider, environment, externalId) => `${provider}\u0000${environment}\u0000${externalId}`;
|
|
3
|
+
/**
|
|
4
|
+
* In-process `IngestStore` paired with a memory ledger store: it runs inside
|
|
5
|
+
* that store's transactions (one store-wide mutex, the memory analogue of
|
|
6
|
+
* row locks) and commits its staged rows in the same step, so an inbox row,
|
|
7
|
+
* a purchase and a ledger entry land together or not at all.
|
|
8
|
+
*/
|
|
9
|
+
export function createMemoryIngestStore(ledgerStore) {
|
|
10
|
+
const inbox = new Map();
|
|
11
|
+
const sessions = new Map();
|
|
12
|
+
const purchases = new Map();
|
|
13
|
+
const staging = new WeakMap();
|
|
14
|
+
const clone = (value) => structuredClone(value);
|
|
15
|
+
const committed = {
|
|
16
|
+
async getInbox(provider, eventId) {
|
|
17
|
+
const row = inbox.get(inboxKey(provider, eventId));
|
|
18
|
+
return row ? clone(row) : null;
|
|
19
|
+
},
|
|
20
|
+
async listInbox(options) {
|
|
21
|
+
return listInbox([...inbox.values()], options);
|
|
22
|
+
},
|
|
23
|
+
async listDue(now, limit, providers) {
|
|
24
|
+
return [...inbox.values()]
|
|
25
|
+
.filter((r) => (r.status === 'received' || r.status === 'failed') && r.nextAttemptAt !== null && r.nextAttemptAt <= now)
|
|
26
|
+
.filter((r) => !providers || providers.includes(r.provider))
|
|
27
|
+
.sort((a, b) => a.nextAttemptAt.getTime() - b.nextAttemptAt.getTime())
|
|
28
|
+
.slice(0, limit)
|
|
29
|
+
.map(clone);
|
|
30
|
+
},
|
|
31
|
+
async getSession(id) {
|
|
32
|
+
const s = sessions.get(id);
|
|
33
|
+
return s ? clone(s) : null;
|
|
34
|
+
},
|
|
35
|
+
async getPurchase(provider, environment, externalId) {
|
|
36
|
+
const p = purchases.get(purchaseKey(provider, environment, externalId));
|
|
37
|
+
return p ? clone(p) : null;
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
function listInbox(rows, options) {
|
|
41
|
+
return rows
|
|
42
|
+
.filter((r) => !options.statuses || options.statuses.includes(r.status))
|
|
43
|
+
.filter((r) => !options.receivedBefore || r.receivedAt < options.receivedBefore)
|
|
44
|
+
.sort((a, b) => b.receivedAt.getTime() - a.receivedAt.getTime())
|
|
45
|
+
.slice(0, options.limit)
|
|
46
|
+
.map(clone);
|
|
47
|
+
}
|
|
48
|
+
function staged(tx) {
|
|
49
|
+
let s = staging.get(tx);
|
|
50
|
+
if (!s) {
|
|
51
|
+
s = { inbox: new Map(), sessions: new Map(), purchases: new Map() };
|
|
52
|
+
staging.set(tx, s);
|
|
53
|
+
}
|
|
54
|
+
return s;
|
|
55
|
+
}
|
|
56
|
+
function bind(tx) {
|
|
57
|
+
// Reads inside the transaction see its own staged writes first.
|
|
58
|
+
const readInbox = (key) => staged(tx).inbox.get(key) ?? inbox.get(key);
|
|
59
|
+
const readSession = (id) => staged(tx).sessions.get(id) ?? sessions.get(id);
|
|
60
|
+
const readPurchase = (key) => staged(tx).purchases.get(key) ?? purchases.get(key);
|
|
61
|
+
const inboxById = (id) => {
|
|
62
|
+
for (const [key, row] of [...staged(tx).inbox, ...inbox])
|
|
63
|
+
if (row.id === id)
|
|
64
|
+
return { key, row };
|
|
65
|
+
return null;
|
|
66
|
+
};
|
|
67
|
+
const purchaseById = (id) => {
|
|
68
|
+
for (const [key, row] of [...staged(tx).purchases, ...purchases])
|
|
69
|
+
if (row.id === id)
|
|
70
|
+
return { key, row };
|
|
71
|
+
return null;
|
|
72
|
+
};
|
|
73
|
+
return {
|
|
74
|
+
async getInbox(provider, eventId) {
|
|
75
|
+
const row = readInbox(inboxKey(provider, eventId));
|
|
76
|
+
return row ? clone(row) : null;
|
|
77
|
+
},
|
|
78
|
+
async listInbox(options) {
|
|
79
|
+
const merged = new Map([...inbox, ...staged(tx).inbox]);
|
|
80
|
+
return listInbox([...merged.values()], options);
|
|
81
|
+
},
|
|
82
|
+
listDue: committed.listDue,
|
|
83
|
+
async getSession(id) {
|
|
84
|
+
const s = readSession(id);
|
|
85
|
+
return s ? clone(s) : null;
|
|
86
|
+
},
|
|
87
|
+
async getPurchase(provider, environment, externalId) {
|
|
88
|
+
const p = readPurchase(purchaseKey(provider, environment, externalId));
|
|
89
|
+
return p ? clone(p) : null;
|
|
90
|
+
},
|
|
91
|
+
async receive(row) {
|
|
92
|
+
const key = inboxKey(row.provider, row.eventId);
|
|
93
|
+
const existing = readInbox(key);
|
|
94
|
+
if (existing) {
|
|
95
|
+
const counted = { ...clone(existing), deliveryCount: existing.deliveryCount + 1, lastReceivedAt: row.lastReceivedAt };
|
|
96
|
+
staged(tx).inbox.set(key, counted);
|
|
97
|
+
return { row: clone(counted), inserted: false };
|
|
98
|
+
}
|
|
99
|
+
staged(tx).inbox.set(key, clone(row));
|
|
100
|
+
return { row: clone(row), inserted: true };
|
|
101
|
+
},
|
|
102
|
+
async lockInbox(provider, eventId) {
|
|
103
|
+
const row = readInbox(inboxKey(provider, eventId));
|
|
104
|
+
return row ? clone(row) : null;
|
|
105
|
+
},
|
|
106
|
+
async updateInbox(id, patch) {
|
|
107
|
+
const found = inboxById(id);
|
|
108
|
+
if (found)
|
|
109
|
+
staged(tx).inbox.set(found.key, { ...clone(found.row), ...patch });
|
|
110
|
+
},
|
|
111
|
+
async insertSession(session) {
|
|
112
|
+
if (readSession(session.id))
|
|
113
|
+
throw new Error(`checkout session ${session.id} already exists`);
|
|
114
|
+
staged(tx).sessions.set(session.id, clone(session));
|
|
115
|
+
},
|
|
116
|
+
async lockSession(id) {
|
|
117
|
+
const s = readSession(id);
|
|
118
|
+
return s ? clone(s) : null;
|
|
119
|
+
},
|
|
120
|
+
async updateSession(id, patch) {
|
|
121
|
+
const s = readSession(id);
|
|
122
|
+
if (s)
|
|
123
|
+
staged(tx).sessions.set(id, { ...clone(s), ...patch, updatedAt: new Date() });
|
|
124
|
+
},
|
|
125
|
+
async lockPurchase(provider, environment, externalId) {
|
|
126
|
+
const p = readPurchase(purchaseKey(provider, environment, externalId));
|
|
127
|
+
return p ? clone(p) : null;
|
|
128
|
+
},
|
|
129
|
+
async insertPurchase(purchase) {
|
|
130
|
+
const key = purchaseKey(purchase.provider, purchase.environment, purchase.externalId);
|
|
131
|
+
if (readPurchase(key) || purchaseById(purchase.id))
|
|
132
|
+
return { inserted: false };
|
|
133
|
+
staged(tx).purchases.set(key, clone(purchase));
|
|
134
|
+
return { inserted: true };
|
|
135
|
+
},
|
|
136
|
+
async updatePurchase(id, patch) {
|
|
137
|
+
const found = purchaseById(id);
|
|
138
|
+
if (found)
|
|
139
|
+
staged(tx).purchases.set(found.key, { ...clone(found.row), ...patch, updatedAt: new Date() });
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function commit(tx) {
|
|
144
|
+
const s = staging.get(tx);
|
|
145
|
+
if (!s)
|
|
146
|
+
return;
|
|
147
|
+
for (const [key, row] of s.inbox)
|
|
148
|
+
inbox.set(key, row);
|
|
149
|
+
for (const [id, session] of s.sessions)
|
|
150
|
+
sessions.set(id, session);
|
|
151
|
+
for (const [key, purchase] of s.purchases)
|
|
152
|
+
purchases.set(key, purchase);
|
|
153
|
+
staging.delete(tx);
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
// The ledger store commits its own staged entries right after `fn`
|
|
157
|
+
// resolves; committing ours at the end of `fn` makes the pair atomic.
|
|
158
|
+
transaction: (fn) => ledgerStore.transaction(async (tx) => {
|
|
159
|
+
try {
|
|
160
|
+
const result = await fn(tx);
|
|
161
|
+
commit(tx);
|
|
162
|
+
return result;
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
staging.delete(tx);
|
|
166
|
+
}
|
|
167
|
+
}),
|
|
168
|
+
bind,
|
|
169
|
+
reader: () => committed,
|
|
170
|
+
dumpInbox: () => [...inbox.values()].sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime()).map(clone),
|
|
171
|
+
};
|
|
172
|
+
}
|