Documentation
¶
Overview ¶
Package testclock owns the TestClock resource: a tenant-scoped frozen-time simulator used to walk test-mode subscriptions through full billing lifecycles (trials, cycles, dunning retries) in compressed wall-clock time.
Clocks exist only in test mode. A live-mode caller cannot create, advance or attach one: the handler answers 403 to a live key (requireTestMode), and the table's CHECK (livemode = false) refuses a live row.
Index ¶
- Constants
- Variables
- type AdvanceInput
- type AuditEmitter
- type AuditRow
- type BillingRunner
- type ClawbackRetrier
- type CreateInput
- type CreditExpirer
- type CustomerReader
- type Deps
- type DunningProcessor
- type Handler
- type PauseResumer
- type PostgresStore
- func (s *PostgresStore) CompleteAdvance(ctx context.Context, tenantID, id string, summary domain.AdvanceSummary) (domain.TestClock, error)
- func (s *PostgresStore) Create(ctx context.Context, tenantID string, clk domain.TestClock, auditRow AuditRow) (domain.TestClock, error)
- func (s *PostgresStore) Delete(ctx context.Context, tenantID, id string, auditRow AuditRow) error
- func (s *PostgresStore) Get(ctx context.Context, tenantID, id string) (domain.TestClock, error)
- func (s *PostgresStore) List(ctx context.Context, tenantID string, limit, offset int) ([]domain.TestClock, int, error)
- func (s *PostgresStore) ListAdvancingForCatchup(ctx context.Context, limit int) ([]domain.TestClock, error)
- func (s *PostgresStore) MarkAdvancing(ctx context.Context, tenantID, id string, newFrozenTime time.Time, ...) (domain.TestClock, error)
- func (s *PostgresStore) MarkFailed(ctx context.Context, tenantID, id, reason string, ...) (domain.TestClock, error)
- func (s *PostgresStore) ResolveSim(ctx context.Context, tenantID, id string) (clock.Sim, bool, error)
- func (s *PostgresStore) RetryFromFailed(ctx context.Context, tenantID, id string, auditRow AuditRow) (domain.TestClock, error)
- func (s *PostgresStore) TouchAdvancing(ctx context.Context, tenantID, id string) error
- type Service
- func (s *Service) Advance(ctx context.Context, tenantID, id string, input AdvanceInput) (domain.TestClock, error)
- func (s *Service) CatchupTick(ctx context.Context)
- func (s *Service) Create(ctx context.Context, tenantID string, input CreateInput) (domain.TestClock, error)
- func (s *Service) Delete(ctx context.Context, tenantID, id string) error
- func (s *Service) Get(ctx context.Context, tenantID, id string) (domain.TestClock, error)
- func (s *Service) List(ctx context.Context, tenantID string, limit, offset int) ([]domain.TestClock, int, error)
- func (s *Service) ListAttachedCustomers(ctx context.Context, tenantID, clockID string, limit, offset int) ([]domain.Customer, int, error)
- func (s *Service) RetryAdvance(ctx context.Context, tenantID, id string) (domain.TestClock, error)
- func (s *Service) RunAdvancing(ctx context.Context) (int, error)
- func (s *Service) RunCatchupLoop(ctx context.Context, gate leader.Gate)
- type Store
- type TaxRetrier
- type TrialExpirer
Constants ¶
const ( // CatchupTickInterval is the testclock_catchup role's cadence. The // runner polls at min(interval, leader.MaxPoll). An advance starts // within about one interval when no other catch-up is running; // otherwise it waits for the passes ahead of it, each up to // CatchupPassDeadline. A tick with no advancing clock is one fenced // SELECT. CatchupTickInterval = 2 * time.Second // CatchupPassDeadline bounds one catch-up pass on one clock. A pass that // has not finished by then ends the advance in internal_failure, with a // reason that names the clock's time, and Retry advance runs it again. // One pass covers the whole advance, so it is generous. CatchupPassDeadline = 10 * time.Minute )
Variables ¶
var ( // ErrCatchupFenceLost: the clock is still advancing, but this run no // longer holds the testclock_catchup lease. The current leader runs the // clock's pass again. ErrCatchupFenceLost = errors.New("testclock: the catch-up lease was lost; the current leader runs this clock") // ErrClockNoLongerAdvancing: the clock is gone, or out of advancing — // another run completed or failed it, or the tenant deleted it. ErrClockNoLongerAdvancing = errors.New("testclock: the clock is no longer advancing") )
The outcomes of a fenced catch-up write (TouchAdvancing, CompleteAdvance, MarkFailed) that changed no row. Neither is a failure of the advance: the run stops, logs, and leaves the clock as it is.
Functions ¶
This section is empty.
Types ¶
type AdvanceInput ¶
type AuditEmitter ¶ added in v0.10.0
AuditEmitter writes an audit row on the caller's transaction (ADR-090). Implemented by *audit.Logger.
type AuditRow ¶ added in v0.10.0
AuditRow writes the audit row of an operator's change to a clock on the change's transaction, so the change is saved only with its row: an error rolls the change back. It gets the clock row as the change left it, or, for a delete, the row the delete removed.
type BillingRunner ¶
type BillingRunner interface {
RunCycleForClock(ctx context.Context, tenantID, clockID string, batchSize int) (int, []error)
// RetryPendingChargesForClock retries auto-charge attempts on
// clock-pinned invoices flagged auto_charge_pending=true. Called
// during catchup AFTER period generation, so customers who attached
// a payment method since the last advance get charged as part of
// THIS advance, not on a future wall-clock tick. ADR-029 Phase 1.
RetryPendingChargesForClock(ctx context.Context, tenantID, clockID string, limit int) (int, []error)
// ScanThresholdsForClock fires early-invoice (Stripe-parity billing-
// thresholds) invoices for clock-pinned subs whose running cycle
// subtotal has crossed a configured threshold. Runs during catchup
// after period generation; without it, the wall-clock cron would
// (incorrectly) fire threshold invoices on clock-pinned subs.
// ADR-029 Phase 3.
ScanThresholdsForClock(ctx context.Context, tenantID, clockID string, batchSize int) (int, []error)
}
BillingRunner is the narrow hook the service uses to drive a billing catchup after a clock advance. In production billing.Engine satisfies it (via RunCycleForClock); tests can stub with a spy that records calls.
Post-ADR-028 disjoint flows: the catchup uses RunCycleForClock, which scopes to subs pinned to ONE clock. The wall-clock cron's generic RunCycle is a different code path and never touches clock-pinned subs. This separation removes the SKIP-LOCKED race and the drip-bill artifact that the dual-flow design produced.
The per-sub period loop in billSubscription handles multi-year catchup internally — one call per sub processes all due periods.
type ClawbackRetrier ¶
type ClawbackRetrier interface {
RetryPendingClawbackIssueForClock(ctx context.Context, tenantID, clockID string, frozenTime time.Time, batch int) (int, []error)
}
ClawbackRetrier is the narrow hook the catchup orchestrator uses to issue a clock's DEFERRED simulated clawback drafts — a downgrade clawback whose source invoice was in-flight (ADR-059 defer) when created and has since settled. Implemented by *creditnote.Service via RetryPendingClawbackIssueForClock. Takes frozenTime so Issue() stamps the credit note and its ledger / tax effects in simulated time. ADR-029 disjoint flows.
type CreateInput ¶
type CreditExpirer ¶
type CreditExpirer interface {
ExpireCreditsForClock(ctx context.Context, tenantID, clockID string, frozenTime time.Time) (int, []error)
}
CreditExpirer is the narrow hook the catchup orchestrator uses to expire grants belonging to clock-pinned customers. ADR-029 Phase 4. Takes frozenTime explicitly so the per-grant `expires_at < now` comparison happens in simulated time, not wall-clock.
type CustomerReader ¶
type CustomerReader interface {
ListByTestClockID(ctx context.Context, tenantID, clockID string, limit, offset int) ([]domain.Customer, int, error)
}
CustomerReader is the narrow hook the service uses to list customers pinned to a clock. The customer domain owns the customers table — including the encrypt-at-rest wrapper around display_name / email — so testclock reads through this interface instead of joining the table directly. That way every caller of the "attached customers" surface gets the same decrypted view that every other read path (customer detail page, customer list, etc.) does.
Per-domain rule (docs/architecture.md, "Design rules"): zero cross-domain imports between peer packages; coordination via narrow interfaces only.
type Deps ¶ added in v0.10.0
type Deps struct {
// Billing closes the clock's due periods, collects their invoices and
// fires spend thresholds.
Billing BillingRunner
// Customers reads the clock's customers for its detail page.
Customers CustomerReader
// Trials ends the trials due by the clock's time; without it a
// subscription stays trialing until its next period closes.
Trials TrialExpirer
// Pauses resumes the collection pauses due by the clock's time.
Pauses PauseResumer
// Tax retries tax on the clock's invoices waiting for it. The scheduled
// retry skips clock invoices.
Tax TaxRetrier
// Relief issues the relief credit notes held for the clock's invoices,
// before collection and again after it. The real-time job skips them.
Relief ClawbackRetrier
// Credits expires the clock's credit grants due by its time.
Credits CreditExpirer
// Dunning runs the clock's payment retries due by its time. The
// real-time dunning tick skips clock invoices.
Dunning DunningProcessor
// Audit writes the audit row of an operator's change, in the change's
// transaction.
Audit AuditEmitter
// PassDeadline bounds one catch-up pass; a pass that runs past it fails
// the advance. The router passes CatchupPassDeadline.
PassDeadline time.Duration
}
Deps is everything the service needs. Every field is required: a catch-up that skipped a job would leave the clock ready with that job's work undone, and an operator's change to a clock is saved only with its audit row.
type DunningProcessor ¶
type DunningProcessor interface {
ProcessDueRunsForClock(ctx context.Context, tenantID, clockID string, frozenTime time.Time, limit int) (int, []error)
}
DunningProcessor is the narrow hook the catchup orchestrator uses to advance dunning state for clock-pinned invoices. ADR-029 Phase 5. Takes frozenTime explicitly so the per-run next_action_at compare runs in simulated time.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler exposes /v1/test-clocks. Its requireTestMode answers 403 to a live-mode caller; the table's CHECK (livemode = false) is the second refusal.
func NewHandler ¶
type PauseResumer ¶
type PauseResumer interface {
ProcessExpiredPauseCollectionsForClock(ctx context.Context, tenantID, clockID string, frozenTime time.Time) (int, []error)
}
PauseResumer is the narrow hook the catchup orchestrator uses to auto-resume subs whose pause_collection_resumes_at has elapsed. Implemented by *subscription.Service via ProcessExpiredPauseCollectionsForClock. Runs as Phase 1.2, after cycle billing: a period that ended before resumes_at closes as a draft first, then the pause clears in the same advance. Without this phase a sub whose next_billing_at is still in the future stays paused past resumes_at.
type PostgresStore ¶
type PostgresStore struct {
// contains filtered or unexported fields
}
func NewPostgresStore ¶
func NewPostgresStore(db *postgres.DB) *PostgresStore
func (*PostgresStore) CompleteAdvance ¶
func (s *PostgresStore) CompleteAdvance(ctx context.Context, tenantID, id string, summary domain.AdvanceSummary) (domain.TestClock, error)
CompleteAdvance flips advancing → ready and clears any prior last_failure_reason. The clear matters when the operator retried a failed advance and it succeeded — the dashboard shouldn't keep showing yesterday's error. It writes the advance's summary in the same statement. A catch-up write: fenced on the testclock_catchup lease (fencedMiss gives its errors).
func (*PostgresStore) Delete ¶
Delete tears down a test clock and its ENTIRE simulated customer graph in one transaction (ADR-086, Design B — complete teardown, supersedes ADR-016's soft-delete + detach). After it runs no simulated row survives, so no wall-clock plane (auto-charge, dunning, usage-aggregation, credit-expiry, analytics) can ever act on one — the class the ADR dissolves.
Safety: see clockTeardownStatements — every DELETE is keyed transitively on `test_clock_id = $clock`, and a test clock is always livemode=false, so no live-mode row is reachable; the clock row's own DELETE adds `livemode=false` as belt. Runs under TxTenant (RLS confines it to the tenant).
Idempotent: re-deleting a gone clock returns errs.ErrNotFound.
func (*PostgresStore) List ¶
func (s *PostgresStore) List(ctx context.Context, tenantID string, limit, offset int) ([]domain.TestClock, int, error)
List returns one page of the tenant's test clocks, newest first, and how many clocks the tenant has.
func (*PostgresStore) ListAdvancingForCatchup ¶ added in v0.10.0
func (s *PostgresStore) ListAdvancingForCatchup(ctx context.Context, limit int) ([]domain.TestClock, error)
ListAdvancingForCatchup is the testclock_catchup role's claim list (ADR-140, ADR-114): the clocks in status='advancing' across every tenant, the one whose pass started longest ago first, at most limit. A pass starts with TouchAdvancing, so a clock whose pass was cut off goes to the back. A pass runs to its end, so a long one still holds up the clocks behind it; fairness between clocks comes with the stepped catch-up. The statement proves the lease's fence, so a deposed leader lists nothing. RLS-bypassed (TxBypass): the tick runs for every tenant, before any tenant ctx exists.
func (*PostgresStore) MarkAdvancing ¶
func (*PostgresStore) MarkFailed ¶
func (s *PostgresStore) MarkFailed(ctx context.Context, tenantID, id, reason string, summary domain.AdvanceSummary) (domain.TestClock, error)
MarkFailed flips advancing → internal_failure and persists the reason, cut to about 500 bytes between two characters; the full payload stays in structured slog. It writes the advance's summary so far in the same statement. A catch-up write: fenced on the testclock_catchup lease (fencedMiss gives its errors).
func (*PostgresStore) ResolveSim ¶
func (s *PostgresStore) ResolveSim(ctx context.Context, tenantID, id string) (clock.Sim, bool, error)
ResolveSim answers "is this clock attached-able, and what instant does it stand at?" in ONE read — used by the customer service at customer-create time, which must both validate the pin and bind the new customer's audit row onto the sim axis (ADR-090 §5).
It returns the pair from a single Get precisely so the two halves cannot drift: an "exists?" bool would send the caller back for the instant, and a clock id paired with a separately-fetched instant is the half-truth clock.Sim is designed to make unrepresentable.
ErrNotFound → (zero, false, nil); other errors propagate. Soft-deleted clocks count as not-existing. A clock in any status is attach-able: an advancing or failed clock's frozen_time is already its new time, so the customer joins at it (domain.TestClockStatus says why no status blocks this).
func (*PostgresStore) RetryFromFailed ¶
func (s *PostgresStore) RetryFromFailed(ctx context.Context, tenantID, id string, auditRow AuditRow) (domain.TestClock, error)
RetryFromFailed flips internal_failure → advancing, clearing the failure reason. Frozen_time stays at its current value — the catchup loop is idempotent on subs whose next_billing_at has already passed it. ADR-018.
func (*PostgresStore) TouchAdvancing ¶ added in v0.10.0
func (s *PostgresStore) TouchAdvancing(ctx context.Context, tenantID, id string) error
TouchAdvancing starts a catch-up pass: it moves the clock's updated_at to now, which puts it at the back of the claim list (ListAdvancingForCatchup orders by updated_at), so a clock whose pass keeps being cut off does not hold up the others. A catch-up write: fenced on the testclock_catchup lease and on the clock still advancing (fencedMiss gives its errors).
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service provides the test-clock API surface. Advance and Retry advance only mark the clock; the testclock_catchup leader runs the catch-up on its tick (catchup.go, ADR-140), off the request path.
func NewService ¶
NewService panics when a dependency is missing, so a wiring mistake stops the server at boot instead of skipping a job on every advance or failing every change for want of its audit row.
func (*Service) Advance ¶
func (s *Service) Advance(ctx context.Context, tenantID, id string, input AdvanceInput) (domain.TestClock, error)
Advance moves the clock forward to FrozenTime and marks it advancing. The testclock_catchup leader then runs the catch-up (catchup.go, ADR-140): everything that fell due in the skipped time, for every subscription and invoice on the clock. A large jump (e.g. 3 months forward on a monthly sub) closes multiple cycles — the billing engine loops each sub's periods until it is caught up.
Advance returns as soon as the clock is marked advancing; the leader runs the catch-up on a later tick, after any passes ahead of it. The dashboard polls /v1/test-clocks/{id} every 1.5s while status === 'advancing' to surface the transition. This matches Stripe's Test Clocks shape — the HTTP advance call returns in milliseconds, the catchup runs in the background.
State machine:
ready ──Advance── advancing ──catchup ok── ready
│
└──catchup errored── internal_failure
While in advancing, other callers get 409 from the MarkAdvancing CAS; while in internal_failure, all further advances are blocked until the tenant retries or deletes the clock.
func (*Service) CatchupTick ¶ added in v0.10.0
CatchupTick is the role's tick body (scheduler.WorkFunc). It logs its own errors.
func (*Service) Delete ¶
Delete tears the clock down with its simulated customers (ADR-086). Its audit row names the clock and its time from the row the teardown deletes.
func (*Service) ListAttachedCustomers ¶
func (s *Service) ListAttachedCustomers(ctx context.Context, tenantID, clockID string, limit, offset int) ([]domain.Customer, int, error)
ListAttachedCustomers returns one page of the customers pinned to this clock, and their total — the Stripe-parity "attached customers" surface (ADR-027 Tier 3). 404s if the clock doesn't exist. Reads through the customer domain's CustomerReader so display_name / email arrive decrypted; see CustomerReader doc.
func (*Service) RetryAdvance ¶
RetryAdvance resumes a clock parked in status='internal_failure' from a prior catchup error. Stripe-parity recovery — the catchup loop is idempotent (only processes subs with next_billing_at <= frozen_time), so resuming from where the previous attempt stopped is safe. Frozen_time stays at its current value; the operator's earlier Advance input is preserved by virtue of MarkAdvancing already having stamped frozen_time before the failure. ADR-018.
Like Advance, it only marks the clock advancing again; the testclock_catchup leader runs the catch-up on its next tick.
Refuses to retry from any state other than internal_failure with a 409. A clock currently in 'advancing' is already being caught up; a clock in 'ready' has no failure to retry.
func (*Service) RunAdvancing ¶ added in v0.10.0
RunAdvancing lists the advancing clocks with the role's fenced claim list and runs one catch-up pass on each, the one touched longest ago first. It returns how many clocks it ran. When ctx ends (a shutdown, or the lease lost) it stops before the next clock, and those clocks stay advancing for the next leader. A clock's failure is the clock's: it is recorded on the clock (internal_failure) and logged, and the tick goes on.
type Store ¶
type Store interface {
Create(ctx context.Context, tenantID string, clk domain.TestClock, auditRow AuditRow) (domain.TestClock, error)
Get(ctx context.Context, tenantID, id string) (domain.TestClock, error)
// List returns one page of the clocks, newest first, and how many there are.
List(ctx context.Context, tenantID string, limit, offset int) ([]domain.TestClock, int, error)
Delete(ctx context.Context, tenantID, id string, auditRow AuditRow) error
// MarkAdvancing flips status ready → advancing and simultaneously sets
// the new frozen_time, atomically. It restarts last_advance_summary with
// advanced_from, the frozen_time before this advance. The new
// frozen_time becomes visible immediately — this is what lets the
// catch-up find subs on the clock as "due". Returns errs.InvalidState when the clock is
// not currently ready (prevents overlapping advances).
//
// The new frozen_time must be >= the current frozen_time; the service
// enforces that up-front so we don't ship a regressed-time clock.
MarkAdvancing(ctx context.Context, tenantID, id string, newFrozenTime time.Time, auditRow AuditRow) (domain.TestClock, error)
// TouchAdvancing starts a catch-up pass: it moves the clock to the back
// of the claim list.
TouchAdvancing(ctx context.Context, tenantID, id string) error
// CompleteAdvance flips status advancing → ready at the end of a
// successful catch-up, storing its summary in the same statement. Clears
// any last_failure_reason from a prior failed-then-retried advance.
CompleteAdvance(ctx context.Context, tenantID, id string, summary domain.AdvanceSummary) (domain.TestClock, error)
// MarkFailed flips advancing → internal_failure when a catch-up fails,
// storing its summary so far in the same statement. The reason is
// persisted on the clock row so the dashboard can show "Catchup failed:
// <reason>". The store cuts it to about 500 bytes; the full payload
// stays in structured slog. ADR-018.
MarkFailed(ctx context.Context, tenantID, id, reason string, summary domain.AdvanceSummary) (domain.TestClock, error)
// RetryFromFailed transitions internal_failure → advancing on a
// clock the operator has chosen to retry. Frozen_time is unchanged
// — the catchup loop only processes subs whose next_billing_at <=
// frozen_time, so resuming from where the previous attempt
// stopped is idempotent. The testclock_catchup leader picks the
// clock up on its next tick, like any other advance. ADR-018.
RetryFromFailed(ctx context.Context, tenantID, id string, auditRow AuditRow) (domain.TestClock, error)
// ListAdvancingForCatchup is the testclock_catchup role's claim list:
// the clocks in status='advancing' across ALL tenants, the one touched
// longest ago first, at most limit. The statement proves the lease's
// fence (ADR-114), so a deposed leader lists nothing.
//
// TouchAdvancing, CompleteAdvance and MarkFailed are the catch-up's
// writes: each is fenced on the testclock_catchup lease, and a miss
// returns ErrCatchupFenceLost or ErrClockNoLongerAdvancing.
ListAdvancingForCatchup(ctx context.Context, limit int) ([]domain.TestClock, error)
}
Store is the persistence contract for TestClock rows. Kept narrow: create, read, list, atomic status transitions, atomic advance, delete. Every method is RLS-scoped to one tenant (postgres.TxTenant) except ListAdvancingForCatchup, the catch-up role's list across tenants.
type TaxRetrier ¶
type TaxRetrier interface {
RetryPendingTaxForClock(ctx context.Context, tenantID, clockID string, batch int) (int, []error)
}
TaxRetrier is the narrow hook the catchup orchestrator uses to drive the per-clock tax-retry phase. Implemented by *invoice.Service via RetryPendingTaxForClock. ADR-029 Phase 2.
Returns (processed_count, per-row errors) — same shape as every other phase callback so the orchestrator can collect failures uniformly.
type TrialExpirer ¶
type TrialExpirer interface {
ProcessExpiredTrialsForClock(ctx context.Context, tenantID, clockID string, frozenTime time.Time) (int, []error)
}
TrialExpirer is the narrow hook the catchup orchestrator uses to flip trialing subs whose `trial_end_at` has elapsed in sim time to active — at `trial_end_at`, not at the later cycle close. Implemented by *subscription.Service via ProcessExpiredTrialsForClock. Runs as Phase 0.5 (before cycle billing) so by the time Phase 1 reads the sub list, the status field reflects the actual lifecycle state. Without this phase, status stays 'trialing' for the gap between trial_end_at and the first chargeable cycle close (up to ~30 days for calendar billing).
Directories
¶
| Path | Synopsis |
|---|---|
|
Package testclocktest runs the test-clock catch-up in tests the way the testclock_catchup leader runs it in production (ADR-140).
|
Package testclocktest runs the test-clock catch-up in tests the way the testclock_catchup leader runs it in production (ADR-140). |