-
Notifications
You must be signed in to change notification settings - Fork 97
feat(billing): stop ingestion once an org is 3 days overdue and never paid #152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Makisuo
wants to merge
11
commits into
main
Choose a base branch
from
feature/ingest-suspend-overdue-unpaid
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
2f80f91
feat(billing): stop ingestion once an org is 3 days overdue and never…
Makisuo f0475b8
Merge remote-tracking branch 'origin/main' into feature/ingest-suspen…
Makisuo d1988d8
fix(billing): reject stale Svix webhook timestamps (anti-replay)
Makisuo 9a88e1a
fix(ingest): include org_billing_suspensions join in startup probe
Makisuo a1ef8ec
fix(billing): use platform crypto.timingSafeEqual for webhook signatu…
Makisuo 6dc3d4b
Merge remote-tracking branch 'origin/main' into feature/ingest-suspen…
Makisuo 6e392f4
fix(ingest): enforce billing suspension on gRPC and session-replay paths
Makisuo e8d924d
Merge remote-tracking branch 'origin/main' into feature/ingest-suspen…
Makisuo 0806f87
Merge remote-tracking branch 'origin/main' into feature/ingest-suspen…
Makisuo 4325553
Merge remote-tracking branch 'origin/main' into feature/ingest-suspen…
Makisuo ac87160
Merge remote-tracking branch 'origin/main' into feature/ingest-suspen…
Makisuo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| import * as MapleCloudflareSDK from "@maple-dev/effect-sdk/cloudflare" | ||
| import { WorkerConfigProviderLayer, WorkerEnvironment } from "@maple/effect-cloudflare" | ||
| import { Cause, Effect, Layer } from "effect" | ||
| import { layerPg } from "./lib/DatabasePgLive" | ||
| import { Env } from "./lib/Env" | ||
| import { BillingSuspensionService } from "./services/BillingSuspensionService" | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Per-invocation runtime for the daily billing-suspension reconcile cron. | ||
| // Mirrors `vcs-sync-runtime.ts`: its own light layer graph (NOT the fetch | ||
| // path's MainLive) so the cron invocation stays within the startup CPU budget. | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| const telemetry = MapleCloudflareSDK.make({ | ||
| serviceName: "maple-api", | ||
| serviceNamespace: "backend", | ||
| repositoryUrl: "https://github.com/Makisuo/maple", | ||
| }) | ||
|
|
||
| export const buildBillingSuspensionLayer = (_env: Record<string, unknown>) => { | ||
| const ConfigLive = WorkerConfigProviderLayer | ||
| const EnvLive = Env.layer.pipe(Layer.provide(ConfigLive)) | ||
| const DatabaseLive = layerPg.pipe(Layer.provide(WorkerEnvironment.layer)) | ||
| const Base = Layer.mergeAll(EnvLive, DatabaseLive, WorkerEnvironment.layer) | ||
|
|
||
| const ServiceLive = BillingSuspensionService.layer.pipe(Layer.provide(Base)) | ||
|
|
||
| return ServiceLive.pipe(Layer.provideMerge(telemetry.layer), Layer.provideMerge(ConfigLive)) | ||
| } | ||
|
|
||
| export const flushBillingTelemetry = (env: Record<string, unknown>) => telemetry.flush(env) | ||
|
|
||
| // The cron program: scan the overdue set, promote/clear per the policy. | ||
| export const runBillingSuspensionReconcile = Effect.gen(function* () { | ||
| const service = yield* BillingSuspensionService | ||
| const result = yield* service.runReconcile() | ||
| yield* Effect.annotateCurrentSpan({ | ||
| "billing.reconcile.scanned": result.scanned, | ||
| "billing.reconcile.suspended": result.suspended, | ||
| "billing.reconcile.cleared": result.cleared, | ||
| "billing.reconcile.outcome": "completed", | ||
| }) | ||
| yield* Effect.logInfo("[billing] suspension reconcile tick complete").pipe( | ||
| Effect.annotateLogs({ | ||
| scanned: result.scanned, | ||
| suspended: result.suspended, | ||
| cleared: result.cleared, | ||
| }), | ||
| ) | ||
| }).pipe( | ||
| // tapCause lets the cause propagate so `withSpan` marks the tick as Error. | ||
| Effect.tapCause((cause) => | ||
| Effect.annotateCurrentSpan({ "billing.reconcile.outcome": "failed" }).pipe( | ||
| Effect.flatMap(() => | ||
| Effect.logError("[billing] suspension reconcile tick failed").pipe( | ||
| Effect.annotateLogs({ error: Cause.pretty(cause) }), | ||
| ), | ||
| ), | ||
| ), | ||
| ), | ||
| Effect.withSpan("BillingSuspensionReconcile.tick"), | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| import { autumnHandler, type CustomerData } from "autumn-js/backend" | ||
| import { Effect, Schema } from "effect" | ||
| import { BillingUpstreamError } from "@maple/domain/http" | ||
|
|
||
| // Shared, dependency-free primitives for speaking the internal `autumn-js/backend` | ||
| // contract. Extracted from billing.http.ts so non-HTTP callers (the billing | ||
| // reconcile cron, the Autumn webhook receiver) reuse the exact same call path | ||
| // instead of re-implementing it. The HTTP billing group still owns the per-org | ||
| // edge cache (`readCustomerCached`) — that stays in billing.http.ts. | ||
|
|
||
| export type AutumnResult = Awaited<ReturnType<typeof autumnHandler>> | ||
|
|
||
| // `autumnHandler` matches its route by `method` + `path`, always POST against | ||
| // `${DEFAULT_PATH_PREFIX}/${route}` (= /api/autumn/<route>) regardless of which | ||
| // Maple endpoint fronts it, so every call here speaks that internal contract. | ||
| export const AUTUMN_PATH_PREFIX = "/api/autumn" | ||
|
|
||
| export const makeCallAutumn = | ||
| (secretKey: string | undefined) => | ||
| ( | ||
| route: string, | ||
| body: unknown, | ||
| customerId: string | undefined, | ||
| customerData?: CustomerData, | ||
| ): Effect.Effect<AutumnResult, BillingUpstreamError> => | ||
| secretKey === undefined | ||
| ? Effect.fail(new BillingUpstreamError({ message: "Billing is not configured" })) | ||
| : Effect.tryPromise({ | ||
| try: () => | ||
| autumnHandler({ | ||
| request: { url: `${AUTUMN_PATH_PREFIX}/${route}`, method: "POST", body }, | ||
| customerId, | ||
| customerData, | ||
| clientOptions: { secretKey }, | ||
| }), | ||
| catch: (error) => | ||
| new BillingUpstreamError({ | ||
| message: error instanceof Error ? error.message : String(error), | ||
| }), | ||
| }) | ||
|
|
||
| // Surface a readable message for a non-2xx Autumn response (it carries a | ||
| // `{ message }` / `{ error }` body) so the client error isn't an opaque 502. | ||
| const upstreamMessage = (result: AutumnResult): string => { | ||
| const body = result.response as { message?: unknown; error?: unknown } | null | ||
| const message = body?.message ?? body?.error | ||
| return typeof message === "string" ? message : `Billing request failed (${result.statusCode})` | ||
| } | ||
|
|
||
| export const ensureOk = (result: AutumnResult): Effect.Effect<unknown, BillingUpstreamError> => | ||
| result.statusCode >= 200 && result.statusCode < 300 | ||
| ? Effect.succeed(result.response) | ||
| : Effect.fail(new BillingUpstreamError({ message: upstreamMessage(result) })) | ||
|
|
||
| export const decodeUpstream = <S extends Schema.Top>( | ||
| schema: S, | ||
| value: unknown, | ||
| ): Effect.Effect<S["Type"], BillingUpstreamError, S["DecodingServices"]> => | ||
| Schema.decodeUnknownEffect(schema)(value).pipe( | ||
| Effect.mapError( | ||
| (error) => new BillingUpstreamError({ message: `Unexpected billing response: ${error}` }), | ||
| ), | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.