Cloudflare WorkersSwiftUICatch

Idempotent Multi-Tenant Webhook Fan-Out and Stopping FAMILY_SHARED Double-Counting in Catch

Inside Catch's Cloudflare Workers backend and SwiftUI client fixes for 1.1.0: notificationUUID + push_state delivery idempotency, D1 64 KB / 100-bind guards, excluding FAMILY_SHARED from revenue, 12-hour CONSUMPTION_REQUEST cleanup, and a macOS NavigationLink layout loop.

Catch runs its backend on Cloudflare Workers, D1, and KV, paired with a single-target SwiftUI app across iOS, iPadOS, and macOS. While wrapping up 1.1.0 fixes alongside App Store review, we uncovered several sharp bugs across webhook delivery, revenue math, D1 limits, and SwiftUI window focus.

Multi-Tenant Fan-Out Idempotency and D1 Hard Limits

A single Catch workspace can hold multiple team members, each owning up to 10 devices with independent quiet hours, sandbox toggles, per-app mutes, and chime.caf sound preferences. Because Apple retries failed webhooks for up to six-plus days (forcing MIN_RETENTION_DAYS = 7), worker/src/hook.js enforces idempotency at three layers:

  1. Atomic insert + daily cap: payload.notificationUUID serves as the primary key alongside DAILY_EVENT_CAP = 1000 inside one INSERT OR IGNORE INTO events ... SELECT ... WHERE (SELECT COUNT(*) ... ) < ? statement so concurrent bursts cannot overshoot quota.
  2. Per-device delivery ledger: Events start with push_state = 'pending'. Inside fanOut(), hook.js queries event_deliveries first, skips (user_id, token) pairs already delivered, pushes via APNs only to remaining devices, and records completions with env.DB.batch.
  3. Deliberate status codes: push_state flips to 'sent' only when zero retryable failures remain; transient APNs errors return 500, failed forward_url deliveries (10_000 ms timeout, redirect: 'manual' so a 307 cannot loop back to /hook/<token>) return 503, and unknown tokens or VerifyError signatures return 200 (logging invalid payloads to a 7-day, 50-row-per-workspace dead_letters table).

Two Cloudflare D1 limits also required explicit guards. readLimited() caps incoming /hook bodies at MAX_BODY_BYTES = 64 * 1024 (real V2 three-part JWS payloads run ~20–30 KB), returning 413 without writing dead_letters so one account cannot fill D1 with multi-megabyte junk. And because D1 caps SQL statements at 100 bound parameters, fanOut() chunks devices queries into batches of 90 user IDs.

Why a ¥68 Family Purchase Counted as ¥136

We initially assumed FAMILY_SHARED notifications carried a 0 price. Inspecting real payloads proved otherwise: Apple sends the family member’s FAMILY_SHARED notification with the full original item price, not zero.

For a ¥68 one-time purchase, the buyer receives a notification for ¥68, and each family member receives a second notification also carrying ¥68 (and every family subscription renewal repeats the pattern). Counting both doubled a ¥68 sale to ¥136 and rang the cash-register chime twice.

We fixed both sides together:

  • hook.js skips event.ownership_type === "FAMILY_SHARED" during push fan-out and marks push_state = 'skipped'.
  • worker/src/stats.js filters MONEY_SCOPE with AND ownership_type IS NOT 'FAMILY_SHARED' and blocks it in isIncomeEvent(). Because stats aggregate at query time, historical totals updated immediately, while by_type still surfaces a family_shared count so StatsView.swift can note “Family Shared: N”, EventDetailView.swift dims the price with an explanation, and CSV exports include an ownership column.
  • eventPrice() also handles REFUND_PRORATED using revocationPercentage (100000 = 100%), and REFUND_REVERSED looks up the prior REFUND amount rather than blindly crediting the full item price.

Purging 12-Hour CONSUMPTION_REQUEST IDs via Hourly Cron

Catch deliberately discards customer identifiers (appAccountToken and originalTransactionId are never stored). The sole exception is CONSUMPTION_REQUEST, where Apple’s PUT /inApps/v2/transactions/consumption/{transactionId} endpoint requires transactionId within a 12-hour response window.

hook.js inserts transaction_id into consumption_requests only if event.ts + 12 * 3600 > now. In worker/src/index.js, an hourly cron (0 * * * *) deletes expired rows (deadline < now) independently of the daily retention cleanup, and listEvents applies AND c.deadline > ? on its LEFT JOIN so expired IDs stop serving immediately even between cron ticks.

Three SwiftUI Client Bugs Caught While Recording the Demo

Recording the 1.1.0 (8) iPad and Mac walkthrough exposed three subtle client bugs:

  1. macOS layout infinite loop (NSGenericException): Opening Send Consumption Info from Views/EventDetailView.swift and switching focus to another window crashed AppKit minutes later. Reading @Environment(\.dismiss) directly inside EventDetailView.body alongside a NavigationLink carrying an onSent closure caused navigation updates to invalidate dismiss, recompute body, re-register the closure-backed NavigationLink, and loop endlessly once unfocused. Moving the two filter buttons into a private FilterShortcuts subview isolated dismiss and stopped the loop.
  2. Silent CSV failure on macOS: Catch-macOS.entitlements was missing com.apple.security.files.user-selected.read-write, blocking the save panel entirely.
  3. 1e-16 float residuals overflowing Int: In Views/StatsView.swift, DeltaLabel computed ((current - prev) / abs(prev) * 100).rounded() and cast it to Int. Floating-point subtraction residuals like 1e-16 blew past Int.max and crashed. Snapping abs($0) < 0.005 to 0, clamping deltas to [-999_999, 999_999], and checking previous_complete from stats.js fixed both the crash and misleading comparisons on truncated periods.
✦

Comments

  • Loading…

Comments are reviewed before publishing; email is visible only to me.