@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,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Drizzle tables of the inbox, checkout sessions and purchases. Declared
|
|
3
|
+
* through `billingTableBuilder`, so they take the host's schema and prefix
|
|
4
|
+
* like the ledger tables, and follow the same additive rules (docs/SCHEMA.md,
|
|
5
|
+
* `checkAdditiveDdl`): new tables and indexes only.
|
|
6
|
+
*/
|
|
7
|
+
import { sql } from 'drizzle-orm';
|
|
8
|
+
import { bigint, check, index, integer, jsonb, text, timestamp, uniqueIndex, varchar } from 'drizzle-orm/pg-core';
|
|
9
|
+
import { billingTableBuilder, DEFAULT_PREFIX } from '../drizzle/schema-factory.js';
|
|
10
|
+
export function createIngestTables(config) {
|
|
11
|
+
const b = billingTableBuilder(config);
|
|
12
|
+
const tz = (name) => timestamp(name, { withTimezone: true });
|
|
13
|
+
const billingInbox = b.table(b.name('inbox'), {
|
|
14
|
+
id: varchar('id', { length: 64 }).primaryKey(),
|
|
15
|
+
provider: varchar('provider', { length: 16 }).notNull(),
|
|
16
|
+
environment: varchar('environment', { length: 16 }).notNull(),
|
|
17
|
+
eventId: text('event_id').notNull(),
|
|
18
|
+
eventType: varchar('event_type', { length: 128 }).notNull(),
|
|
19
|
+
subjectRef: text('subject_ref'),
|
|
20
|
+
status: varchar('status', { length: 16 }).notNull(),
|
|
21
|
+
attempts: integer('attempts').notNull().default(0),
|
|
22
|
+
deliveryCount: integer('delivery_count').notNull().default(1),
|
|
23
|
+
nextAttemptAt: tz('next_attempt_at'),
|
|
24
|
+
lastError: text('last_error'),
|
|
25
|
+
reason: text('reason'),
|
|
26
|
+
payload: jsonb('payload').notNull(),
|
|
27
|
+
occurredAt: tz('occurred_at').notNull(),
|
|
28
|
+
receivedAt: tz('received_at').notNull(),
|
|
29
|
+
lastReceivedAt: tz('last_received_at').notNull(),
|
|
30
|
+
processedAt: tz('processed_at'),
|
|
31
|
+
updatedAt: tz('updated_at').notNull().defaultNow(),
|
|
32
|
+
}, (t) => [
|
|
33
|
+
uniqueIndex(b.name('inbox_provider_event_uq')).on(t.provider, t.eventId),
|
|
34
|
+
// The sweeper: `status in (received, failed) and next_attempt_at <= now`.
|
|
35
|
+
// Partial: final rows clear next_attempt_at, so the index holds only work.
|
|
36
|
+
index(b.name('inbox_due_idx')).on(t.status, t.nextAttemptAt).where(sql `${t.nextAttemptAt} is not null`),
|
|
37
|
+
// Operator lists (needs_review, dead) newest first.
|
|
38
|
+
index(b.name('inbox_status_received_idx')).on(t.status, t.receivedAt),
|
|
39
|
+
]);
|
|
40
|
+
const billingCheckoutSessions = b.table(b.name('checkout_sessions'), {
|
|
41
|
+
id: varchar('id', { length: 64 }).primaryKey(),
|
|
42
|
+
accountId: config.accountId('account_id'),
|
|
43
|
+
provider: varchar('provider', { length: 16 }).notNull(),
|
|
44
|
+
environment: varchar('environment', { length: 16 }).notNull(),
|
|
45
|
+
status: varchar('status', { length: 16 }).notNull(),
|
|
46
|
+
currency: varchar('currency', { length: 3 }).notNull(),
|
|
47
|
+
amountMinor: bigint('amount_minor', { mode: 'number' }).notNull(),
|
|
48
|
+
credits: bigint('credits', { mode: 'number' }).notNull(),
|
|
49
|
+
productRef: text('product_ref'),
|
|
50
|
+
externalId: text('external_id'),
|
|
51
|
+
expiresAt: tz('expires_at').notNull(),
|
|
52
|
+
completedAt: tz('completed_at'),
|
|
53
|
+
meta: jsonb('meta').$type(),
|
|
54
|
+
createdAt: tz('created_at').notNull().defaultNow(),
|
|
55
|
+
updatedAt: tz('updated_at').notNull().defaultNow(),
|
|
56
|
+
}, (t) => [
|
|
57
|
+
index(b.name('checkout_sessions_account_idx')).on(t.accountId, t.createdAt),
|
|
58
|
+
check(b.name('checkout_sessions_amount_pos'), sql `${t.amountMinor} > 0 and ${t.credits} > 0`),
|
|
59
|
+
]);
|
|
60
|
+
const billingPurchases = b.table(b.name('purchases'), {
|
|
61
|
+
id: varchar('id', { length: 64 }).primaryKey(),
|
|
62
|
+
accountId: config.accountId('account_id'),
|
|
63
|
+
provider: varchar('provider', { length: 16 }).notNull(),
|
|
64
|
+
environment: varchar('environment', { length: 16 }).notNull(),
|
|
65
|
+
externalId: text('external_id').notNull(),
|
|
66
|
+
checkoutSessionId: varchar('checkout_session_id', { length: 64 }),
|
|
67
|
+
status: varchar('status', { length: 16 }).notNull(),
|
|
68
|
+
currency: varchar('currency', { length: 3 }).notNull(),
|
|
69
|
+
amountMinor: bigint('amount_minor', { mode: 'number' }).notNull(),
|
|
70
|
+
credits: bigint('credits', { mode: 'number' }).notNull().default(0),
|
|
71
|
+
creditEntryId: varchar('credit_entry_id', { length: 64 }),
|
|
72
|
+
clawedBack: bigint('clawed_back', { mode: 'number' }).notNull().default(0),
|
|
73
|
+
shortfall: bigint('shortfall', { mode: 'number' }).notNull().default(0),
|
|
74
|
+
reversals: integer('reversals').notNull().default(0),
|
|
75
|
+
lastEventAt: tz('last_event_at'),
|
|
76
|
+
lastEventRef: text('last_event_ref'),
|
|
77
|
+
meta: jsonb('meta').$type(),
|
|
78
|
+
createdAt: tz('created_at').notNull().defaultNow(),
|
|
79
|
+
updatedAt: tz('updated_at').notNull().defaultNow(),
|
|
80
|
+
}, (t) => [
|
|
81
|
+
uniqueIndex(b.name('purchases_provider_external_uq')).on(t.provider, t.environment, t.externalId),
|
|
82
|
+
index(b.name('purchases_account_idx')).on(t.accountId, t.createdAt),
|
|
83
|
+
index(b.name('purchases_checkout_session_idx')).on(t.checkoutSessionId),
|
|
84
|
+
]);
|
|
85
|
+
return { billingInbox, billingCheckoutSessions, billingPurchases };
|
|
86
|
+
}
|
|
87
|
+
/** Unqualified table names for `checkAdditiveDdl({libraryTables})`. */
|
|
88
|
+
export function ingestTableNames(prefix = DEFAULT_PREFIX) {
|
|
89
|
+
return ['inbox', 'checkout_sessions', 'purchases'].map((n) => `${prefix}${n}`);
|
|
90
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider watermarks (design §6 ordering): a state change applies only when
|
|
3
|
+
* its event is newer than the last one applied, so redelivered or
|
|
4
|
+
* out-of-order events cannot regress state. Ties on time break on the event
|
|
5
|
+
* ref; the same event again is never "newer", which makes re-application a
|
|
6
|
+
* no-op. Purchases use it for reversal ⇄ reinstatement; terms (P2) for
|
|
7
|
+
* subscription snapshots.
|
|
8
|
+
*/
|
|
9
|
+
export interface Watermark {
|
|
10
|
+
at: Date;
|
|
11
|
+
ref: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function isNewer(current: Watermark | null, incoming: Watermark): boolean;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@tofound/billing` — public entry (the `billing.public-api` contract).
|
|
3
|
+
* Drizzle tables and the Postgres store live in `@tofound/billing/drizzle`;
|
|
4
|
+
* conformance kits in `@tofound/billing/testing`. The library reads no env,
|
|
5
|
+
* logs nothing and carries no HTTP framework (D14).
|
|
6
|
+
*/
|
|
7
|
+
export * from './domain/types.js';
|
|
8
|
+
export { BillingError, insufficientCredits, isBillingError } from './domain/errors.js';
|
|
9
|
+
export { assertMinor, creditUnit, CURRENCY_EXPONENT, divRound, formatMinor, money, mulDivRound } from './domain/money.js';
|
|
10
|
+
export { createLedger, type Ledger, type LedgerOps, type LedgerOptions } from './ledger/ledger.js';
|
|
11
|
+
export type { BillingEventSink, Clock, EntryListOptions, IdGenerator, LedgerReader, LedgerStore, LedgerTx, } from './ports/index.js';
|
|
12
|
+
export { createMemoryLedgerStore, type MemoryLedgerStore, type MemoryTx } from './stores/memory.js';
|
|
13
|
+
export { createWaterfall, creditsStep, freeStep, quotaStep, type QuotaPool, type SettleContext, type SettleOptions, type Settled, type StepContext, type StepPlan, type Waterfall, type WaterfallConfig, type WaterfallStep, } from './quote/index.js';
|
|
14
|
+
export * from './providers/port.js';
|
|
15
|
+
export { createIngest, type CreateCheckoutInput, type Ingest, type IngestEvent, type IngestEventSink, type IngestOptions, type IngestPolicy, type IngestResult, type SweepResult, type UnmatchedHook, } from './inbox/ingest.js';
|
|
16
|
+
export type { ApplyContext, ApplyResult, ApplyStatus, EventHandler, PurchaseReversed } from './inbox/apply.js';
|
|
17
|
+
export { FINAL_INBOX_STATUSES, type CheckoutSession, type CheckoutSessionPatch, type CheckoutSessionStatus, type InboxListOptions, type InboxPatch, type InboxRow, type InboxStatus, type IngestReader, type IngestStore, type IngestTx, type Purchase, type PurchasePatch, type PurchaseStatus, } from './inbox/ports.js';
|
|
18
|
+
export { createMemoryIngestStore, type MemoryIngestStore } from './inbox/memory.js';
|
|
19
|
+
export { isSensitiveKey, redactPayload } from './inbox/redact.js';
|
|
20
|
+
export { isNewer, type Watermark } from './inbox/watermark.js';
|
|
21
|
+
export { DEFAULT_POLICIES, defineCatalog, type Catalog, type CatalogPolicies, type CatalogSpec, type CreditOffer, type CreditPack, type CreditPackSpec, type MarketSpec, type PackProvider, type Plan, type PlanOffer, type PlanSpec, type ProductMatch, type ProviderOffer, type ReversalShortfallPolicy, type UpgradeProration, } from './catalog/catalog.js';
|
|
22
|
+
export * from './terms/types.js';
|
|
23
|
+
export type { TermListOptions, TermReader, TermStore, TermTx } from './terms/ports.js';
|
|
24
|
+
export { addDays, addTermMonths, isRenewalDue, renewalDueAt, renews } from './terms/rules.js';
|
|
25
|
+
export { createMemoryTermStore, type MemoryTermStore, type MemoryTransactor } from './terms/memory.js';
|
|
26
|
+
export { decidePlanPurchase, itemsOf, supersedeRefund, type PlanDecision, type PlanQuoteKind, type PlanRequest, type TermEffect, } from './terms/decide.js';
|
|
27
|
+
export { createPlans, type PlanOps, type PlanPurchaseInput, type PlanPurchaseResult, type PlanQuote, type Plans, type PlansEvent, type PlansEventSink, type PlansOptions, type TermUpdateResult, } from './terms/plans.js';
|
|
28
|
+
export { createSnapshotHandler, type SnapshotHandlerOptions } from './terms/snapshot.js';
|
|
29
|
+
export { entitledUntil, isEntitled, resolveEntitlement, type Entitlement, type EntitlementRenewal, type EntitlementStatus, type EntitlementWarning, type EntitlementWarningCode, type ResolveOptions, } from './entitlement/resolve.js';
|
|
30
|
+
export { createRenewal, type RenewalEvent, type RenewalOps, type RenewalOptions, type RenewalOutcome, type RenewalResult, type RenewalRun, type RenewalService, } from './renewal/renewal.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@tofound/billing` — public entry (the `billing.public-api` contract).
|
|
3
|
+
* Drizzle tables and the Postgres store live in `@tofound/billing/drizzle`;
|
|
4
|
+
* conformance kits in `@tofound/billing/testing`. The library reads no env,
|
|
5
|
+
* logs nothing and carries no HTTP framework (D14).
|
|
6
|
+
*/
|
|
7
|
+
export * from './domain/types.js';
|
|
8
|
+
export { BillingError, insufficientCredits, isBillingError } from './domain/errors.js';
|
|
9
|
+
export { assertMinor, creditUnit, CURRENCY_EXPONENT, divRound, formatMinor, money, mulDivRound } from './domain/money.js';
|
|
10
|
+
export { createLedger } from './ledger/ledger.js';
|
|
11
|
+
export { createMemoryLedgerStore } from './stores/memory.js';
|
|
12
|
+
export { createWaterfall, creditsStep, freeStep, quotaStep, } from './quote/index.js';
|
|
13
|
+
export * from './providers/port.js';
|
|
14
|
+
export { createIngest, } from './inbox/ingest.js';
|
|
15
|
+
export { FINAL_INBOX_STATUSES, } from './inbox/ports.js';
|
|
16
|
+
export { createMemoryIngestStore } from './inbox/memory.js';
|
|
17
|
+
export { isSensitiveKey, redactPayload } from './inbox/redact.js';
|
|
18
|
+
export { isNewer } from './inbox/watermark.js';
|
|
19
|
+
export { DEFAULT_POLICIES, defineCatalog, } from './catalog/catalog.js';
|
|
20
|
+
export * from './terms/types.js';
|
|
21
|
+
export { addDays, addTermMonths, isRenewalDue, renewalDueAt, renews } from './terms/rules.js';
|
|
22
|
+
export { createMemoryTermStore } from './terms/memory.js';
|
|
23
|
+
export { decidePlanPurchase, itemsOf, supersedeRefund, } from './terms/decide.js';
|
|
24
|
+
export { createPlans, } from './terms/plans.js';
|
|
25
|
+
export { createSnapshotHandler } from './terms/snapshot.js';
|
|
26
|
+
export { entitledUntil, isEntitled, resolveEntitlement, } from './entitlement/resolve.js';
|
|
27
|
+
export { createRenewal, } from './renewal/renewal.js';
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type AccountId, type BillingEvent, type DebitUpToResult, type EntryPage, type LedgerEntry, type PostInput, type PostResult, type ReverseInput } from '../domain/types.js';
|
|
2
|
+
import type { LedgerStore } from '../ports/ledger-store.js';
|
|
3
|
+
import type { BillingEventSink, Clock, IdGenerator } from '../ports/runtime.js';
|
|
4
|
+
export interface LedgerOptions<TTx> {
|
|
5
|
+
store: LedgerStore<TTx>;
|
|
6
|
+
clock?: Clock;
|
|
7
|
+
ids?: IdGenerator;
|
|
8
|
+
/**
|
|
9
|
+
* Receives events after commit of transactions the ledger itself opened.
|
|
10
|
+
* Delivery is at most once: the posting is already durable, so a sink
|
|
11
|
+
* error never fails it — it goes to `onEventError` and the remaining
|
|
12
|
+
* events are still delivered. Hosts that need guaranteed delivery post
|
|
13
|
+
* under `ledger.in(tx)` and write the returned events to their own outbox.
|
|
14
|
+
*/
|
|
15
|
+
events?: BillingEventSink;
|
|
16
|
+
onEventError?: (error: unknown, event: BillingEvent) => void;
|
|
17
|
+
}
|
|
18
|
+
/** Ledger operations; the same set runs in the ledger's own or a host transaction. */
|
|
19
|
+
export interface LedgerOps {
|
|
20
|
+
/** Post `+amount`. */
|
|
21
|
+
credit(input: PostInput): Promise<PostResult>;
|
|
22
|
+
/** Post `−amount`; throws `insufficient_credits` rather than overdraw. */
|
|
23
|
+
debit(input: PostInput): Promise<PostResult>;
|
|
24
|
+
/** Post `−min(balance, amount)` and report the shortfall (provider clawbacks). */
|
|
25
|
+
debitUpTo(input: PostInput): Promise<DebitUpToResult>;
|
|
26
|
+
/** Counter-entry (kind `reversal`) of at most |original delta|, once per entry. */
|
|
27
|
+
reverse(input: ReverseInput): Promise<PostResult>;
|
|
28
|
+
/** Current balance; 0 for an account that never posted. */
|
|
29
|
+
balance(accountId: AccountId): Promise<number>;
|
|
30
|
+
/** The entry posted under `idempotencyKey`, if any. */
|
|
31
|
+
findByKey(idempotencyKey: string): Promise<LedgerEntry | null>;
|
|
32
|
+
}
|
|
33
|
+
export interface Ledger<TTx = unknown> extends LedgerOps {
|
|
34
|
+
/** The same operations inside a transaction the host already holds. */
|
|
35
|
+
in(tx: TTx): LedgerOps;
|
|
36
|
+
entries(accountId: AccountId, options?: {
|
|
37
|
+
limit?: number;
|
|
38
|
+
beforeSeq?: number;
|
|
39
|
+
}): Promise<EntryPage>;
|
|
40
|
+
getEntry(id: string): Promise<LedgerEntry | null>;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Single-entry, append-only ledger (design §4.3). Every posting runs:
|
|
44
|
+
* lock the account (insert-or-lock, taken last) → look the key up → append
|
|
45
|
+
* the entry → update the materialized balance and seq.
|
|
46
|
+
*/
|
|
47
|
+
export declare function createLedger<TTx>(options: LedgerOptions<TTx>): Ledger<TTx>;
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { BillingError, insufficientCredits } from '../domain/errors.js';
|
|
3
|
+
import { assertMinor } from '../domain/money.js';
|
|
4
|
+
import { ENTRY_KINDS, } from '../domain/types.js';
|
|
5
|
+
const KINDS = new Set(ENTRY_KINDS);
|
|
6
|
+
const MAX_PAGE = 500;
|
|
7
|
+
/**
|
|
8
|
+
* Single-entry, append-only ledger (design §4.3). Every posting runs:
|
|
9
|
+
* lock the account (insert-or-lock, taken last) → look the key up → append
|
|
10
|
+
* the entry → update the materialized balance and seq.
|
|
11
|
+
*/
|
|
12
|
+
export function createLedger(options) {
|
|
13
|
+
const { store } = options;
|
|
14
|
+
const clock = options.clock ?? { now: () => new Date() };
|
|
15
|
+
const ids = options.ids ?? randomUUID;
|
|
16
|
+
const ops = (tx) => ({
|
|
17
|
+
credit: (input) => post(tx, input, 'credit'),
|
|
18
|
+
debit: (input) => post(tx, input, 'debit'),
|
|
19
|
+
debitUpTo: (input) => post(tx, input, 'debit_up_to'),
|
|
20
|
+
reverse: (input) => reverse(tx, input),
|
|
21
|
+
balance: async (accountId) => (await tx.getAccount(accountId))?.balance ?? 0,
|
|
22
|
+
findByKey: (key) => tx.findEntryByKey(key),
|
|
23
|
+
});
|
|
24
|
+
async function own(run) {
|
|
25
|
+
const result = await store.transaction((tx) => run(ops(store.bind(tx))));
|
|
26
|
+
if (options.events) {
|
|
27
|
+
for (const event of result.events) {
|
|
28
|
+
try {
|
|
29
|
+
await options.events(event);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
options.onEventError?.(error, event);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
async function post(tx, input, direction) {
|
|
39
|
+
validatePost(input);
|
|
40
|
+
const sign = direction === 'credit' ? 1 : -1;
|
|
41
|
+
const account = await tx.lockAccount(input.accountId);
|
|
42
|
+
const intent = {
|
|
43
|
+
accountId: input.accountId,
|
|
44
|
+
kind: input.kind,
|
|
45
|
+
requested: sign * input.amount,
|
|
46
|
+
reversesId: null,
|
|
47
|
+
};
|
|
48
|
+
const existing = await tx.findEntryByKey(input.idempotencyKey);
|
|
49
|
+
if (existing)
|
|
50
|
+
return replay(existing, intent, direction);
|
|
51
|
+
let delta = sign * input.amount;
|
|
52
|
+
let meta = input.meta ?? null;
|
|
53
|
+
let shortfall = 0;
|
|
54
|
+
if (direction === 'debit_up_to') {
|
|
55
|
+
const posted = Math.min(account.balance, input.amount);
|
|
56
|
+
shortfall = input.amount - posted;
|
|
57
|
+
delta = posted === 0 ? 0 : -posted;
|
|
58
|
+
meta = { ...(meta ?? {}), debitUpTo: { requested: input.amount, shortfall } };
|
|
59
|
+
}
|
|
60
|
+
else if (direction === 'debit' && account.balance < input.amount) {
|
|
61
|
+
throw insufficientCredits({ balance: account.balance, required: input.amount, shortfall: input.amount - account.balance });
|
|
62
|
+
}
|
|
63
|
+
const entry = await append(tx, account, {
|
|
64
|
+
kind: input.kind,
|
|
65
|
+
delta,
|
|
66
|
+
idempotencyKey: input.idempotencyKey,
|
|
67
|
+
reason: input.reason ?? null,
|
|
68
|
+
sourceType: input.source?.type ?? null,
|
|
69
|
+
sourceId: input.source?.id ?? null,
|
|
70
|
+
reversesId: null,
|
|
71
|
+
meta,
|
|
72
|
+
}, intent, direction);
|
|
73
|
+
if ('replayed' in entry)
|
|
74
|
+
return entry.replayed;
|
|
75
|
+
const result = { entry, replayed: false, events: eventsOf(entry) };
|
|
76
|
+
return direction === 'debit_up_to' ? { ...result, requested: input.amount, shortfall } : result;
|
|
77
|
+
}
|
|
78
|
+
async function reverse(tx, input) {
|
|
79
|
+
if (!input.entryId || !input.idempotencyKey) {
|
|
80
|
+
throw new BillingError('invalid_input', 'reverse needs entryId and idempotencyKey');
|
|
81
|
+
}
|
|
82
|
+
const original = await tx.getEntry(input.entryId);
|
|
83
|
+
if (!original)
|
|
84
|
+
throw new BillingError('entry_not_found', `entry ${input.entryId} not found`, { entryId: input.entryId });
|
|
85
|
+
const magnitude = Math.abs(original.delta);
|
|
86
|
+
if (magnitude === 0) {
|
|
87
|
+
throw new BillingError('invalid_input', `entry ${original.id} moved no credits; there is nothing to reverse`, { entryId: original.id });
|
|
88
|
+
}
|
|
89
|
+
const amount = input.amount ?? magnitude;
|
|
90
|
+
assertMinor(amount, 'amount', { positive: true });
|
|
91
|
+
if (amount > magnitude) {
|
|
92
|
+
throw new BillingError('reversal_exceeds_original', `reversal ${amount} exceeds |${original.delta}|`, {
|
|
93
|
+
entryId: original.id,
|
|
94
|
+
amount,
|
|
95
|
+
original: original.delta,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
const account = await tx.lockAccount(original.accountId);
|
|
99
|
+
const delta = original.delta > 0 ? -amount : amount;
|
|
100
|
+
const intent = { accountId: original.accountId, kind: 'reversal', requested: delta, reversesId: original.id };
|
|
101
|
+
const existing = await tx.findEntryByKey(input.idempotencyKey);
|
|
102
|
+
if (existing)
|
|
103
|
+
return replay(existing, intent, 'credit');
|
|
104
|
+
const prior = await tx.findReversalOf(original.id);
|
|
105
|
+
if (prior) {
|
|
106
|
+
throw new BillingError('already_reversed', `entry ${original.id} was already reversed by ${prior.id}`, {
|
|
107
|
+
entryId: original.id,
|
|
108
|
+
reversalId: prior.id,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
if (delta < 0 && account.balance < amount) {
|
|
112
|
+
throw insufficientCredits({ balance: account.balance, required: amount, shortfall: amount - account.balance });
|
|
113
|
+
}
|
|
114
|
+
const entry = await append(tx, account, {
|
|
115
|
+
kind: 'reversal',
|
|
116
|
+
delta,
|
|
117
|
+
idempotencyKey: input.idempotencyKey,
|
|
118
|
+
reason: input.reason ?? original.reason,
|
|
119
|
+
sourceType: original.sourceType,
|
|
120
|
+
sourceId: original.sourceId,
|
|
121
|
+
reversesId: original.id,
|
|
122
|
+
meta: input.meta ?? null,
|
|
123
|
+
}, intent, 'credit');
|
|
124
|
+
if ('replayed' in entry)
|
|
125
|
+
return entry.replayed;
|
|
126
|
+
return { entry, replayed: false, events: eventsOf(entry) };
|
|
127
|
+
}
|
|
128
|
+
/** Append under the held account lock; a unique conflict resolves to replay or a typed error. */
|
|
129
|
+
async function append(tx, account, draft, intent, direction) {
|
|
130
|
+
const balanceAfter = account.balance + draft.delta;
|
|
131
|
+
if (!Number.isSafeInteger(balanceAfter)) {
|
|
132
|
+
throw new BillingError('balance_overflow', `balance ${account.balance} + ${draft.delta} leaves the safe integer range`);
|
|
133
|
+
}
|
|
134
|
+
const entry = {
|
|
135
|
+
id: ids(),
|
|
136
|
+
accountId: account.accountId,
|
|
137
|
+
seq: account.seq + 1,
|
|
138
|
+
balanceAfter,
|
|
139
|
+
createdAt: clock.now(),
|
|
140
|
+
...draft,
|
|
141
|
+
};
|
|
142
|
+
const { inserted } = await tx.appendEntry(entry);
|
|
143
|
+
if (!inserted) {
|
|
144
|
+
// Another transaction committed this key (or this reversal) first.
|
|
145
|
+
const winner = await tx.findEntryByKey(draft.idempotencyKey);
|
|
146
|
+
if (winner)
|
|
147
|
+
return { replayed: replay(winner, intent, direction) };
|
|
148
|
+
if (draft.reversesId !== null) {
|
|
149
|
+
throw new BillingError('already_reversed', `entry ${draft.reversesId} was already reversed`, { entryId: draft.reversesId });
|
|
150
|
+
}
|
|
151
|
+
// The account lock rules out a seq race, so this is a duplicate entry id
|
|
152
|
+
// (a host IdGenerator that repeats) or a store not honouring the lock.
|
|
153
|
+
throw new Error(`ledger store refused entry ${entry.id} (account ${entry.accountId}, seq ${entry.seq}): id or seq already taken`);
|
|
154
|
+
}
|
|
155
|
+
await tx.setAccountState({ accountId: account.accountId, balance: balanceAfter, seq: entry.seq });
|
|
156
|
+
return entry;
|
|
157
|
+
}
|
|
158
|
+
return {
|
|
159
|
+
// Top-level postings open their own transaction per call.
|
|
160
|
+
credit: (input) => own((o) => o.credit(input)),
|
|
161
|
+
debit: (input) => own((o) => o.debit(input)),
|
|
162
|
+
debitUpTo: (input) => own((o) => o.debitUpTo(input)),
|
|
163
|
+
reverse: (input) => own((o) => o.reverse(input)),
|
|
164
|
+
balance: async (accountId) => (await store.reader().getAccount(accountId))?.balance ?? 0,
|
|
165
|
+
findByKey: (key) => store.reader().findEntryByKey(key),
|
|
166
|
+
in: (tx) => ops(store.bind(tx)),
|
|
167
|
+
async entries(accountId, page = {}) {
|
|
168
|
+
for (const [name, value] of [['limit', page.limit], ['beforeSeq', page.beforeSeq]]) {
|
|
169
|
+
if (value !== undefined && !Number.isSafeInteger(value)) {
|
|
170
|
+
throw new BillingError('invalid_input', `${name} must be an integer, got ${value}`, { [name]: value });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const limit = Math.min(Math.max(page.limit ?? 50, 1), MAX_PAGE);
|
|
174
|
+
const entries = await store.reader().listEntries(accountId, {
|
|
175
|
+
limit: limit + 1,
|
|
176
|
+
...(page.beforeSeq === undefined ? {} : { beforeSeq: page.beforeSeq }),
|
|
177
|
+
});
|
|
178
|
+
const more = entries.length > limit;
|
|
179
|
+
const shown = more ? entries.slice(0, limit) : entries;
|
|
180
|
+
return { entries: shown, nextBeforeSeq: more ? (shown.at(-1)?.seq ?? null) : null };
|
|
181
|
+
},
|
|
182
|
+
getEntry: (id) => store.reader().getEntry(id),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
function validatePost(input) {
|
|
186
|
+
if (!input.accountId)
|
|
187
|
+
throw new BillingError('invalid_input', 'accountId is required');
|
|
188
|
+
if (!input.idempotencyKey)
|
|
189
|
+
throw new BillingError('invalid_input', 'idempotencyKey is required');
|
|
190
|
+
if (!KINDS.has(input.kind) || input.kind === 'reversal') {
|
|
191
|
+
throw new BillingError('invalid_input', `kind ${JSON.stringify(input.kind)} cannot be posted directly`, { kind: input.kind });
|
|
192
|
+
}
|
|
193
|
+
assertMinor(input.amount, 'amount', { positive: true });
|
|
194
|
+
}
|
|
195
|
+
/** I3: same key + same intent → the original entry; anything else → `idempotency_mismatch`. */
|
|
196
|
+
function replay(existing, intent, direction) {
|
|
197
|
+
const recorded = direction === 'debit_up_to' ? requestedOf(existing) : existing.delta;
|
|
198
|
+
const same = existing.accountId === intent.accountId &&
|
|
199
|
+
existing.kind === intent.kind &&
|
|
200
|
+
existing.reversesId === intent.reversesId &&
|
|
201
|
+
recorded === intent.requested;
|
|
202
|
+
if (!same) {
|
|
203
|
+
throw new BillingError('idempotency_mismatch', `idempotency key ${existing.idempotencyKey} was posted with a different intent`, {
|
|
204
|
+
idempotencyKey: existing.idempotencyKey,
|
|
205
|
+
entryId: existing.id,
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
const result = { entry: existing, replayed: true, events: [] };
|
|
209
|
+
if (direction !== 'debit_up_to')
|
|
210
|
+
return result;
|
|
211
|
+
const requested = -intent.requested;
|
|
212
|
+
return { ...result, requested, shortfall: requested + existing.delta };
|
|
213
|
+
}
|
|
214
|
+
function requestedOf(entry) {
|
|
215
|
+
const record = entry.meta?.['debitUpTo'];
|
|
216
|
+
return typeof record?.requested === 'number' ? -record.requested : null;
|
|
217
|
+
}
|
|
218
|
+
function eventsOf(entry) {
|
|
219
|
+
if (entry.delta > 0)
|
|
220
|
+
return [{ type: 'credited', accountId: entry.accountId, entry }];
|
|
221
|
+
if (entry.delta < 0)
|
|
222
|
+
return [{ type: 'debited', accountId: entry.accountId, entry }];
|
|
223
|
+
return [];
|
|
224
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { AccountId, AccountState, LedgerEntry } from '../domain/types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Persistence port of the ledger — part of the `billing.ports` contract.
|
|
4
|
+
*
|
|
5
|
+
* A store exposes its native transaction type `TTx` (a Drizzle transaction,
|
|
6
|
+
* a memory transaction, a Lohi adapter's transaction) so a host can post
|
|
7
|
+
* inside a transaction it already holds. Every implementation must pass the
|
|
8
|
+
* store conformance suite (`@tofound/billing/testing`).
|
|
9
|
+
*
|
|
10
|
+
* Isolation: postings assume READ COMMITTED (each statement sees rows
|
|
11
|
+
* committed before it), which is what makes "lock the account, then look the
|
|
12
|
+
* key up" observe a concurrent winner.
|
|
13
|
+
*/
|
|
14
|
+
export interface LedgerStore<TTx = unknown> {
|
|
15
|
+
/** Run `fn` in a new transaction; commit on resolve, roll back on throw. */
|
|
16
|
+
transaction<T>(fn: (tx: TTx) => Promise<T>): Promise<T>;
|
|
17
|
+
/** Ledger operations bound to an open transaction. */
|
|
18
|
+
bind(tx: TTx): LedgerTx;
|
|
19
|
+
/** Unlocked reads outside any transaction. */
|
|
20
|
+
reader(): LedgerReader;
|
|
21
|
+
}
|
|
22
|
+
export interface EntryListOptions {
|
|
23
|
+
limit: number;
|
|
24
|
+
/** Only entries with `seq < beforeSeq` (older pages). */
|
|
25
|
+
beforeSeq?: number;
|
|
26
|
+
}
|
|
27
|
+
export interface LedgerReader {
|
|
28
|
+
getAccount(accountId: AccountId): Promise<AccountState | null>;
|
|
29
|
+
getEntry(id: string): Promise<LedgerEntry | null>;
|
|
30
|
+
findEntryByKey(idempotencyKey: string): Promise<LedgerEntry | null>;
|
|
31
|
+
/** Newest first. */
|
|
32
|
+
listEntries(accountId: AccountId, options: EntryListOptions): Promise<LedgerEntry[]>;
|
|
33
|
+
}
|
|
34
|
+
export interface LedgerTx extends LedgerReader {
|
|
35
|
+
/**
|
|
36
|
+
* Lock the account row for the rest of the transaction (`SELECT … FOR
|
|
37
|
+
* UPDATE`), creating it first when missing (balance 0, seq 0). The ledger
|
|
38
|
+
* takes this lock last, after any host, inbox, purchase or term rows.
|
|
39
|
+
*/
|
|
40
|
+
lockAccount(accountId: AccountId): Promise<AccountState>;
|
|
41
|
+
/** The reversal of `entryId`, if one exists. */
|
|
42
|
+
findReversalOf(entryId: string): Promise<LedgerEntry | null>;
|
|
43
|
+
/**
|
|
44
|
+
* Append one entry. A unique conflict (idempotency key, `reverses_id`)
|
|
45
|
+
* must not throw or abort the transaction: it answers `{inserted:false}`
|
|
46
|
+
* and writes nothing (`INSERT … ON CONFLICT DO NOTHING`).
|
|
47
|
+
*/
|
|
48
|
+
appendEntry(entry: LedgerEntry): Promise<{
|
|
49
|
+
inserted: boolean;
|
|
50
|
+
}>;
|
|
51
|
+
/** Persist the account's new balance and seq; the row is locked. */
|
|
52
|
+
setAccountState(state: AccountState): Promise<void>;
|
|
53
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { BillingEvent } from '../domain/types.js';
|
|
2
|
+
/** Time source; inject a fixed clock in tests. */
|
|
3
|
+
export interface Clock {
|
|
4
|
+
now(): Date;
|
|
5
|
+
}
|
|
6
|
+
/** Entry id generator; defaults to `crypto.randomUUID`. */
|
|
7
|
+
export type IdGenerator = () => string;
|
|
8
|
+
/** Receives domain events after the ledger's own transaction commits. */
|
|
9
|
+
export type BillingEventSink = (event: BillingEvent) => void | Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { NormalizedEvent } from '../port.js';
|
|
2
|
+
export interface PolarEnvelope {
|
|
3
|
+
type: string;
|
|
4
|
+
timestamp?: unknown;
|
|
5
|
+
data: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
export interface NormalizeOptions {
|
|
8
|
+
/** Polar product id → catalog productRef. */
|
|
9
|
+
products: Readonly<Record<string, string>>;
|
|
10
|
+
/** Our checkout session ids, as carried in `metadata.checkout_id`. */
|
|
11
|
+
checkoutPattern: RegExp;
|
|
12
|
+
}
|
|
13
|
+
/** The provider's watermark: when Polar last changed the object, else when it was created or sent. */
|
|
14
|
+
export declare function occurredAtOf(envelope: PolarEnvelope, fallback: Date): Date;
|
|
15
|
+
/** The server-issued external customer id (design §4.1). */
|
|
16
|
+
export declare function externalCustomerOf(data: Record<string, unknown>): string | null;
|
|
17
|
+
export declare function normalizePolarEvent(envelope: PolarEnvelope, occurredAt: Date, options: NormalizeOptions): NormalizedEvent;
|