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 <noreply@anthropic.com>
This commit is contained in:
parent
ec04f3ddb5
commit
d8aed72e3e
@ -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:*",
|
||||
|
||||
@ -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 =
|
||||
|
||||
@ -53,7 +53,24 @@ async function main(): Promise<void> {
|
||||
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();
|
||||
|
||||
@ -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,
|
||||
];
|
||||
}
|
||||
|
||||
28
apps/worker/src/jobs/subscription-charge.ts
Normal file
28
apps/worker/src/jobs/subscription-charge.ts
Normal file
@ -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<JobResult> {
|
||||
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 };
|
||||
},
|
||||
};
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -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);
|
||||
|
||||
85
apps/worker/src/wiring/onchain-billing.ts
Normal file
85
apps/worker/src/wiring/onchain-billing.ts
Normal file
@ -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<OnchainBillingRuntime | null> {
|
||||
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;
|
||||
}
|
||||
@ -7,6 +7,8 @@
|
||||
"types": ["node"]
|
||||
},
|
||||
"references": [
|
||||
{ "path": "../../packages/dunning" },
|
||||
{ "path": "../../packages/onchain-billing" },
|
||||
{ "path": "../../packages/common" },
|
||||
{ "path": "../../packages/solana" },
|
||||
{ "path": "../../packages/zcash" },
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user