Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Bound Stripe webhook dedupe retention

rcourtmana5b2a037cbe4
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index a99257a93a..4104b9feeb 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -339,7 +339,12 @@ Insights`, rather than reviving generic `AI Patrol` or `AI ... analysis`
`max_monitored_systems` entitlement row, and
`monitored_system_capacity.mode = unlimited` once runtime usage is
available.
-9. Keep the maintained Pulse Account portal bundle source-synced with
+9. Keep Stripe webhook idempotency state bounded in the control-plane
+ registry: `internal/cloudcp/registry/registry.go` may retain `stripe_events`
+ rows long enough to suppress duplicate deliveries and reclaim stale
+ in-flight work, but it must prune expired processed or abandoned rows so
+ webhook dedupe does not grow without bound on disk.
+10. Keep the maintained Pulse Account portal bundle source-synced with
`internal/cloudcp/portal/frontend/`: any slice that changes the portal
frontend hash or emitted manifest must rebuild
`internal/cloudcp/portal/dist/build_manifest.json` and keep
@@ -1663,6 +1668,12 @@ checkout provisioning: long-running `checkout.session.completed` tenant
provisioning must complete under an explicit background timeout instead of
depending on the inbound Stripe request context surviving long enough for first
boot and health polling.
+That same Stripe webhook boundary also owns bounded idempotency retention in
+the control-plane registry. `internal/cloudcp/registry/registry.go` may keep
+dedupe rows long enough to suppress duplicate Stripe deliveries and reclaim
+stale in-flight attempts, but it must prune expired processed or abandoned
+`stripe_events` rows instead of letting webhook idempotency state grow without
+bound on disk.
That same paid relay onboarding boundary now also owns QR-token lifecycle on
the supported Pulse Mobile pairing surface. `RelaySettingsPanel.tsx`,
`RelayPairingSection.tsx`, and `useRelaySettingsPanelState.ts` may revoke a
diff --git a/internal/cloudcp/registry/registry.go b/internal/cloudcp/registry/registry.go
index 8be1b8099d..f6aee1f511 100644
--- a/internal/cloudcp/registry/registry.go
+++ b/internal/cloudcp/registry/registry.go
@@ -20,7 +20,11 @@ type TenantRegistry struct {
db *sql.DB
}
-const stripeEventProcessingLeaseSeconds int64 = 120
+const (
+ stripeEventProcessingLeaseSeconds int64 = 120
+ stripeEventRetention = 30 * 24 * time.Hour
+ stripeEventRetentionSeconds int64 = int64(stripeEventRetention / time.Second)
+)
func canonicalizeRegistryPlanVersion(planVersion string) string {
return pkglicensing.CanonicalizePlanVersion(strings.TrimSpace(planVersion))
@@ -116,6 +120,8 @@ func (r *TenantRegistry) initSchema() error {
processed_at INTEGER,
processing_error TEXT
);
+ CREATE INDEX IF NOT EXISTS idx_stripe_events_processed_at ON stripe_events(processed_at);
+ CREATE INDEX IF NOT EXISTS idx_stripe_events_received_at ON stripe_events(received_at);
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
@@ -282,6 +288,12 @@ func (r *TenantRegistry) initSchema() error {
return fmt.Errorf("migrate stripe_events: add processing_started_at: %w", err)
}
}
+ if _, err := r.db.Exec(`CREATE INDEX IF NOT EXISTS idx_stripe_events_processed_at ON stripe_events(processed_at)`); err != nil {
+ return fmt.Errorf("migrate stripe_events: add processed_at index: %w", err)
+ }
+ if _, err := r.db.Exec(`CREATE INDEX IF NOT EXISTS idx_stripe_events_received_at ON stripe_events(received_at)`); err != nil {
+ return fmt.Errorf("migrate stripe_events: add received_at index: %w", err)
+ }
// Migration: add grace_started_at to stripe_accounts if missing.
hasGraceStartedAt, err := r.tableHasColumn("stripe_accounts", "grace_started_at")
@@ -2011,6 +2023,9 @@ func (r *TenantRegistry) RecordStripeEvent(eventID, eventType string) (alreadyPr
}()
now := time.Now().UTC().Unix()
+ if err := pruneStripeEventsTx(tx, now); err != nil {
+ return false, err
+ }
// INSERT OR IGNORE avoids driver-specific error parsing for duplicates.
res, err := tx.Exec(`
@@ -2122,6 +2137,22 @@ func (r *TenantRegistry) MarkStripeEventProcessed(eventID string, processingErro
return nil
}
+func pruneStripeEventsTx(tx *sql.Tx, nowUnix int64) error {
+ if tx == nil {
+ return fmt.Errorf("stripe event prune transaction is required")
+ }
+ cutoff := nowUnix - stripeEventRetentionSeconds
+ if _, err := tx.Exec(`
+ DELETE FROM stripe_events
+ WHERE (processed_at IS NOT NULL AND processed_at < ?)
+ OR (processed_at IS NULL AND received_at < ?)`,
+ cutoff, cutoff,
+ ); err != nil {
+ return fmt.Errorf("prune stale stripe events: %w", err)
+ }
+ return nil
+}
+
func scanAccount(s scanner) (*Account, error) {
var a Account
var kind string
diff --git a/internal/cloudcp/registry/registry_test.go b/internal/cloudcp/registry/registry_test.go
index 756c3e48a4..8f98df14a8 100644
--- a/internal/cloudcp/registry/registry_test.go
+++ b/internal/cloudcp/registry/registry_test.go
@@ -1419,3 +1419,78 @@ func TestStripeEventReclaimsStaleInFlight(t *testing.T) {
t.Fatalf("expected stale in-flight event to be reclaimed for processing")
}
}
+
+func TestStripeEventPrunesExpiredRows(t *testing.T) {
+ reg := newTestRegistry(t)
+
+ now := time.Now().UTC().Unix()
+ stale := now - stripeEventRetentionSeconds - 60
+ recent := now - stripeEventRetentionSeconds/2
+
+ for _, stmt := range []struct {
+ id string
+ eventType string
+ receivedAt int64
+ processingStarted any
+ processedAt any
+ processingError any
+ }{
+ {
+ id: "evt_stale_processed",
+ eventType: "customer.subscription.updated",
+ receivedAt: stale,
+ processingStarted: nil,
+ processedAt: stale,
+ processingError: nil,
+ },
+ {
+ id: "evt_stale_pending",
+ eventType: "invoice.payment_failed",
+ receivedAt: stale,
+ processingStarted: nil,
+ processedAt: nil,
+ processingError: nil,
+ },
+ {
+ id: "evt_recent_processed",
+ eventType: "checkout.session.completed",
+ receivedAt: recent,
+ processingStarted: nil,
+ processedAt: recent,
+ processingError: nil,
+ },
+ } {
+ if _, err := reg.db.Exec(`
+ INSERT INTO stripe_events (
+ stripe_event_id, event_type, received_at, processing_started_at, processed_at, processing_error
+ ) VALUES (?, ?, ?, ?, ?, ?)`,
+ stmt.id, stmt.eventType, stmt.receivedAt, stmt.processingStarted, stmt.processedAt, stmt.processingError,
+ ); err != nil {
+ t.Fatalf("insert seed stripe event %s: %v", stmt.id, err)
+ }
+ }
+
+ already, err := reg.RecordStripeEvent("evt_new", "customer.subscription.updated")
+ if err != nil {
+ t.Fatalf("RecordStripeEvent: %v", err)
+ }
+ if already {
+ t.Fatal("expected new event to remain processable")
+ }
+
+ assertStripeEventExists := func(eventID string, want bool) {
+ t.Helper()
+ var count int
+ if err := reg.db.QueryRow(`SELECT COUNT(*) FROM stripe_events WHERE stripe_event_id = ?`, eventID).Scan(&count); err != nil {
+ t.Fatalf("query stripe event %s: %v", eventID, err)
+ }
+ if got := count == 1; got != want {
+ t.Fatalf("stripe event %s exists=%v, want %v", eventID, got, want)
+ }
+ }
+
+ assertStripeEventExists("evt_stale_processed", false)
+ assertStripeEventExists("evt_stale_pending", false)
+ assertStripeEventExists("evt_recent_processed", true)
+ assertStripeEventExists("evt_new", true)
+}