From d8aed72e3e3c2cfe4a2cf246c2b86becdfd87fed Mon Sep 17 00:00:00 2001 From: caelum0x Date: Tue, 29 Sep 2026 20:19:14 +0300 Subject: [PATCH] feat(worker): subscription-charge job for onchain subscriptions Registers the per-period charge job (WORKER_SUBSCRIPTION_CHARGE_INTERVAL_MS, default 5 min) over the shared onchain-billing runtime and Postgres stores; dunning on failure, entitlement suspension when exhausted, extension on success. No-op until onchain billing is configured. Co-Authored-By: Claude Opus 5.5 --- apps/worker/package.json | 2 + apps/worker/src/config.ts | 3 + apps/worker/src/index.ts | 19 ++++- apps/worker/src/jobs/index.ts | 4 + apps/worker/src/jobs/subscription-charge.ts | 28 +++++++ apps/worker/src/jobs/types.ts | 3 + apps/worker/src/runtime.ts | 13 +++- apps/worker/src/wiring/onchain-billing.ts | 85 +++++++++++++++++++++ apps/worker/tsconfig.json | 2 + 9 files changed, 156 insertions(+), 3 deletions(-) create mode 100644 apps/worker/src/jobs/subscription-charge.ts create mode 100644 apps/worker/src/wiring/onchain-billing.ts diff --git a/apps/worker/package.json b/apps/worker/package.json index 74555f4..8f37bfe 100644 --- a/apps/worker/package.json +++ b/apps/worker/package.json @@ -27,11 +27,13 @@ "@settlekit/database": "workspace:*", "@settlekit/delivery": "workspace:*", "@settlekit/discord": "workspace:*", + "@settlekit/dunning": "workspace:*", "@settlekit/entitlements": "workspace:*", "@settlekit/file-delivery": "workspace:*", "@settlekit/github": "workspace:*", "@settlekit/license-keys": "workspace:*", "@settlekit/notifications": "workspace:*", + "@settlekit/onchain-billing": "workspace:*", "@settlekit/payments": "workspace:*", "@settlekit/payouts": "workspace:*", "@settlekit/persistence": "workspace:*", diff --git a/apps/worker/src/config.ts b/apps/worker/src/config.ts index e2c418a..a01dd8b 100644 --- a/apps/worker/src/config.ts +++ b/apps/worker/src/config.ts @@ -48,6 +48,8 @@ export interface JobIntervals { zcashWatchMs: number; /** How often pending GitHub entitlements from checkout are re-delivered. */ githubDeliveryRetryMs: number; + /** How often due onchain subscription periods are charged. */ + subscriptionChargeMs: number; } /** Circle developer-controlled wallets used to reconcile executed payouts. */ @@ -282,6 +284,7 @@ export function loadConfig(env: Env = process.env): WorkerConfig { payoutReconcileMs: intInRange(env, "WORKER_PAYOUT_RECONCILE_INTERVAL_MS", 60_000, 1_000, 86_400_000), zcashWatchMs: intInRange(env, "WORKER_ZCASH_WATCH_INTERVAL_MS", 90_000, 30_000, 3_600_000), githubDeliveryRetryMs: intInRange(env, "WORKER_GITHUB_RETRY_INTERVAL_MS", 120_000, 10_000, 86_400_000), + subscriptionChargeMs: intInRange(env, "WORKER_SUBSCRIPTION_CHARGE_INTERVAL_MS", 300_000, 10_000, 86_400_000), }; const circleWallets: CircleWalletsConfig | null = diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 9391532..4f2dd31 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -53,7 +53,24 @@ async function main(): Promise { logger.info("worker persistence: in-memory", {}); } - const runtime = buildRuntime({ config, githubApi, discordApi, logger }); + // Onchain subscriptions (Permit2 / spend permission / SPL delegate pulls, + // renewal invoices): built async, before the scheduler, on the same stores. + const { createDb } = await import("@settlekit/database"); + const { createEmailClient } = await import("@settlekit/notifications"); + const { buildWorkerOnchainBilling } = await import("./wiring/onchain-billing.js"); + const { PgWorkerStore } = await import("./db/pg-worker-store.js"); + const { InMemoryWorkerStore } = await import("./stores.js"); + const db = config.database ? createDb(config.database.url) : null; + const stores = db ? new PgWorkerStore(db) : new InMemoryWorkerStore(); + const onchainBilling = await buildWorkerOnchainBilling({ + env: process.env, + stores, + db, + email: createEmailClient({ from: config.email.from, apiKey: config.email.apiKey }), + logger, + }); + + const runtime = buildRuntime({ config, githubApi, discordApi, logger, db, stores, onchainBilling }); const shutdown = runtime.scheduler.installSignalHandlers(); runtime.scheduler.start(); diff --git a/apps/worker/src/jobs/index.ts b/apps/worker/src/jobs/index.ts index ec36646..ac12dd7 100644 --- a/apps/worker/src/jobs/index.ts +++ b/apps/worker/src/jobs/index.ts @@ -19,6 +19,7 @@ export { leptonPayoutSweepJob } from "./lepton-payout-sweep-job.js"; export { leptonStreamRefundJob } from "./lepton-stream-refund-job.js"; export { zcashWatchJob } from "./zcash-watch.js"; export { githubDeliveryRetryJob } from "./github-delivery-retry-job.js"; +export { subscriptionChargeJob } from "./subscription-charge.js"; import type { Job } from "./types.js"; import { deliveryRunnerJob } from "./delivery-runner-job.js"; @@ -36,6 +37,7 @@ import { leptonPayoutSweepJob } from "./lepton-payout-sweep-job.js"; import { leptonStreamRefundJob } from "./lepton-stream-refund-job.js"; import { zcashWatchJob } from "./zcash-watch.js"; import { githubDeliveryRetryJob } from "./github-delivery-retry-job.js"; +import { subscriptionChargeJob } from "./subscription-charge.js"; /** Stable list of the worker's primary scheduled jobs (plan ยง17). */ export const workerJobs = [ @@ -54,6 +56,7 @@ export const workerJobs = [ "lepton-stream-refund", "zcash-watch", "github-delivery-retry", + "subscription-charge", ] as const; export type WorkerJobName = (typeof workerJobs)[number]; @@ -76,5 +79,6 @@ export function allJobs(): Job[] { leptonStreamRefundJob, zcashWatchJob, githubDeliveryRetryJob, + subscriptionChargeJob, ]; } diff --git a/apps/worker/src/jobs/subscription-charge.ts b/apps/worker/src/jobs/subscription-charge.ts new file mode 100644 index 0000000..21554a0 --- /dev/null +++ b/apps/worker/src/jobs/subscription-charge.ts @@ -0,0 +1,28 @@ +/** + * Subscription charge job: collects every due period of every onchain + * subscription (Permit2 / spend permission / SPL delegate pulls, renewal + * invoices) through the shared charge engine. Each (subscription, period) is + * claimed atomically in the store, so overlapping ticks or several worker + * replicas never charge a period twice; failures walk dunning and suspend + * entitlements once it is exhausted; successes extend access. + * No-op until onchain billing is configured. + */ +import type { Job, JobContext, JobResult } from "./types.js"; + +export const subscriptionChargeJob: Job = { + name: "subscription-charge", + async run(ctx: JobContext): Promise { + const billing = ctx.onchainBilling; + if (!billing) return { processed: 0, failed: 0 }; + const summary = await billing.engine.runDue(); + if (summary.processed > 0) { + ctx.logger.info("subscription charges processed", { + processed: summary.processed, + succeeded: summary.succeeded, + failed: summary.failed, + outcomes: summary.outcomes, + }); + } + return { processed: summary.processed, failed: summary.failed }; + }, +}; diff --git a/apps/worker/src/jobs/types.ts b/apps/worker/src/jobs/types.ts index 6b7df35..48e21a7 100644 --- a/apps/worker/src/jobs/types.ts +++ b/apps/worker/src/jobs/types.ts @@ -24,6 +24,7 @@ import type { } from "@settlekit/settlement-core"; import type { RoyaltyLegStore } from "@settlekit/citation-toll"; import type { StreamStore } from "@settlekit/streaming"; +import type { OnchainBillingRuntime } from "@settlekit/onchain-billing"; import type { WorkerConfig } from "../config.js"; import type { WorkerStore } from "../stores.js"; import type { Logger } from "../logger.js"; @@ -74,6 +75,8 @@ export interface JobContext { royaltyLegStore?: RoyaltyLegStore; /** Stream records to refund reserved-but-unused balances from. */ streamStore?: StreamStore; + /** Onchain subscriptions + refunds; absent -> the subscription-charge job no-ops. */ + onchainBilling?: OnchainBillingRuntime; /** Injectable clock for deterministic tests. */ now: () => Date; } diff --git a/apps/worker/src/runtime.ts b/apps/worker/src/runtime.ts index 2f3bffd..34f21dc 100644 --- a/apps/worker/src/runtime.ts +++ b/apps/worker/src/runtime.ts @@ -18,7 +18,7 @@ import type { DiscordApi } from "@settlekit/discord"; import type { HttpSender } from "@settlekit/webhooks"; import { createEmailClient, type EmailTransport } from "@settlekit/notifications"; import type { WorkerConfig } from "./config.js"; -import { createDb } from "@settlekit/database"; +import { createDb, type Database } from "@settlekit/database"; import { InMemoryWorkerStore, type WorkerStore } from "./stores.js"; import { PgWorkerStore } from "./db/pg-worker-store.js"; import { @@ -38,6 +38,7 @@ import type { } from "@settlekit/settlement-core"; import type { RoyaltyLegStore } from "@settlekit/citation-toll"; import type { StreamStore } from "@settlekit/streaming"; +import type { OnchainBillingRuntime } from "@settlekit/onchain-billing"; import { createWalletsClient, type WalletsClient } from "@settlekit/circle-wallets"; import { createLogger, type Logger } from "./logger.js"; import { createArcSettlementProvider } from "./settlement/arc-provider.js"; @@ -59,6 +60,7 @@ import { leptonStreamRefundJob, zcashWatchJob, githubDeliveryRetryJob, + subscriptionChargeJob, type JobContext, } from "./jobs/index.js"; @@ -67,6 +69,8 @@ export interface RuntimeDeps { config: WorkerConfig; githubApi: GitHubApi; discordApi: DiscordApi; + /** Shared database handle (boot passes the one its stores already use). */ + db?: Database | null; /** Pre-built stores (defaults to a fresh in-memory layer). */ stores?: WorkerStore; /** Override the Arc RPC transport (tests inject canned receipts). */ @@ -97,6 +101,8 @@ export interface RuntimeDeps { royaltyLegStore?: RoyaltyLegStore; /** Override the stream store (defaults to Pg when a DB is set). */ streamStore?: StreamStore; + /** Onchain billing runtime (built async by buildWorkerOnchainBilling). */ + onchainBilling?: OnchainBillingRuntime | null; /** Override the clock (deterministic tests). */ now?: () => Date; } @@ -116,7 +122,7 @@ export function buildJobContext(deps: RuntimeDeps): { ctx: JobContext; stores: W // was injected); the process-local in-memory store otherwise. The same db // handle backs the delivery stores so worker-issued license/API keys/file // grants persist to the tables the API reads. - const db = !deps.stores && deps.config.database ? createDb(deps.config.database.url) : null; + const db = deps.db ?? (!deps.stores && deps.config.database ? createDb(deps.config.database.url) : null); const stores = deps.stores ?? (db ? new PgWorkerStore(db) : new InMemoryWorkerStore()); const logger = deps.logger ?? createLogger({ app: "worker" }); const now = deps.now ?? (() => new Date()); @@ -257,6 +263,7 @@ export function buildJobContext(deps: RuntimeDeps): { ctx: JobContext; stores: W ...(settlementProvider !== undefined ? { settlementProvider } : {}), ...(royaltyLegStore !== undefined ? { royaltyLegStore } : {}), ...(streamStore !== undefined ? { streamStore } : {}), + ...(deps.onchainBilling ? { onchainBilling: deps.onchainBilling } : {}), now, }; @@ -309,6 +316,8 @@ export function buildRuntime(deps: RuntimeDeps): WorkerRuntime { { job: zcashWatchJob, intervalMs: intervals.zcashWatchMs }, // No-op until a GitHub App installation id is configured. { job: githubDeliveryRetryJob, intervalMs: intervals.githubDeliveryRetryMs }, + // No-op until onchain billing is configured (operator key / checkout URL). + { job: subscriptionChargeJob, intervalMs: intervals.subscriptionChargeMs }, ]; const scheduler = new Scheduler(scheduled, ctx, logger); diff --git a/apps/worker/src/wiring/onchain-billing.ts b/apps/worker/src/wiring/onchain-billing.ts new file mode 100644 index 0000000..3210bb8 --- /dev/null +++ b/apps/worker/src/wiring/onchain-billing.ts @@ -0,0 +1,85 @@ +/** + * Worker-side onchain billing: the shared @settlekit/onchain-billing runtime + * over the worker's stores (Postgres when DATABASE_URL is set), with access + * hooks that extend / suspend the core subscription, record confirmed + * payments and expire entitlements so access-sync revokes downstream grants. + * Built before the scheduler (Solana key parsing is async); absent config + * leaves the subscription-charge job a no-op. + */ +import type { Database } from "@settlekit/database"; +import { DunningService, InMemoryDunningStore } from "@settlekit/dunning"; +import type { EmailClient } from "@settlekit/notifications"; +import { + InMemoryOnchainBillingStore, + buildOnchainBilling, + createAccessHooks, + type OnchainBillingRuntime, +} from "@settlekit/onchain-billing"; +import { InMemoryCheckoutRepository } from "@settlekit/payments"; +import { + DEFAULT_MERCHANT_ID, + PgCheckoutRepository, + PgDunningStore, + PgOnchainBillingStore, +} from "@settlekit/persistence"; +import type { Env } from "@settlekit/chains"; +import type { WorkerStore } from "../stores.js"; +import type { Logger } from "../logger.js"; + +export interface WorkerOnchainBillingDeps { + env: Env; + stores: WorkerStore; + db: Database | null; + email: EmailClient | null; + logger: Logger; + now?: () => Date; +} + +export async function buildWorkerOnchainBilling(deps: WorkerOnchainBillingDeps): Promise { + const { stores, db, logger } = deps; + const now = deps.now ?? (() => new Date()); + const hooks = createAccessHooks( + { + async getSubscription(id) { + return (await stores.allSubscriptions()).find((s) => s.id === id); + }, + async saveSubscription(subscription) { + await stores.upsertSubscription(subscription); + }, + async entitlementsFor(customerId, productId) { + return (await stores.allEntitlements()).filter((e) => e.customerId === customerId && e.productId === productId); + }, + async saveEntitlement(entitlement) { + await stores.upsertEntitlement(entitlement); + }, + async savePayment(payment) { + await stores.upsertPayment(payment); + }, + }, + { now, onError: (message, meta) => logger.warn(message, meta) }, + ); + const runtime = await buildOnchainBilling({ + env: deps.env, + store: db ? new PgOnchainBillingStore(db) : new InMemoryOnchainBillingStore(), + dunning: new DunningService(db ? new PgDunningStore(db) : new InMemoryDunningStore(), now), + checkouts: db ? new PgCheckoutRepository(db) : new InMemoryCheckoutRepository(), + email: deps.email, + merchantId: DEFAULT_MERCHANT_ID, + hooks, + logger: { + info: (message, meta) => logger.info(message, meta), + warn: (message, meta) => logger.warn(message, meta), + error: (message, meta) => logger.error(message, meta), + }, + now, + }); + if (runtime) { + for (const note of runtime.notes) logger.info("onchain billing", { note }); + logger.info("onchain billing enabled", { + networks: Object.keys(runtime.assets), + operator: runtime.operatorAddress, + solanaDelegate: runtime.solanaDelegate, + }); + } + return runtime; +} diff --git a/apps/worker/tsconfig.json b/apps/worker/tsconfig.json index fc58229..f7cc4fa 100644 --- a/apps/worker/tsconfig.json +++ b/apps/worker/tsconfig.json @@ -7,6 +7,8 @@ "types": ["node"] }, "references": [ + { "path": "../../packages/dunning" }, + { "path": "../../packages/onchain-billing" }, { "path": "../../packages/common" }, { "path": "../../packages/solana" }, { "path": "../../packages/zcash" },