Files
HealthLog/prisma/migrations/0080_v1449_push_attempts/migration.sql
T
Marc-André Bombeck f92e644154 chore(release): v1.4.49 — audit-backlog closure + server reminder suppression + diagnostic endpoint + analytics cold-path fix
Bundles the deferred v1.4.47 Mediums + Lows with the v1.4.48-deferred items
into a single release. Headline: server-side suppression of MEDICATION_REMINDER
APNs for iOS clients that own their local reminders (closes GH #206), a
push_attempts table backing /api/admin/notifications/diagnostic, and a sweep
of v1.4.48 QA forward-findings.

Performance (the user-visible win):
- /api/analytics cold-fallback path splits the heavy single-statement
  aggregate into two parallel queries. The linearly composable columns
  (count / min / max / mean) keep the full-partition scan; the windowed
  7 / 30 / 90-day avg / slope / r² columns take a 90-day outer cap so
  the planner does an index range scan on (user_id, type, measured_at)
  instead of a full-partition sequential scan. Output is bit-identical;
  cold slim slice drops from multi-second to sub-second on tenants with
  large measurement partitions.

Server-side notifications:
- GET + PATCH /api/auth/me/notification-prefs with deep-merge semantics.
  Initial category medication.clientManaged: boolean (default false). Cron
  medicationReminderJob skips dose-due APNs when the flag is true,
  emitting a medication_reminder.suppressed_client_managed wide-event
  annotation per skip.
- push_attempts table backs the diagnostic endpoint. Every APNS /
  Web-Push / Telegram / NTFY sender writes a fire-and-forget row.
  Daily 03:35 Europe/Berlin cleanup prunes rows older than 90 days.
- /api/admin/notifications/diagnostic — admin-only endpoint surfacing
  device APNs token presence (masked), channel config presence, and
  recent push attempts. Registered in OpenAPI.
- Per-channel APNs "Send test" button now fires with
  eventType: "MEDICATION_REMINDER" so the dispatcher's time-sensitive +
  priority-10 branch runs. A successful self-test now exercises the
  exact path production reminders take; an unsuccessful one points the
  user at iOS Settings → Time Sensitive Notifications rather than
  appearing to be a server-side bug.

Withings reliability:
- OAuth callback consumes the nonce atomically (delete-first with
  P2025 catch for the replay branch). The previous read-then-delete
  pattern allowed a race between two concurrent callbacks.
- ?reason=state redirect differentiated into csrf1 / replay / expired /
  cross_user so operators can tell mismatch types apart without DB
  shell access.
- connect endpoint rate-limited to 10/60s/user; row-create failures
  redirect to a consistent error surface.

Observability hardening:
- redactSensitiveFields(body) denylist helper covers password / token /
  secret / apiKey / authorization / csrfState / nonce, recursive,
  case-insensitive. Caught: /api/devices invalid_format issues were
  echoing apnsToken values verbatim into the audit log.
- sanitiseZodIssues(issues, { stripValuesFromMessage: true }) overload
  applied to 14 audit-log sites.

Migrations: 0079 (notification_prefs), 0080 (push_attempts).

Tests: 4815 → 5272 unit + integration. Workout-batch integration suite
that had been red on main since v1.4.45 (three release commits shipped
through it) now green again — updated to match v1.4.42 cross-source
dedup semantics.

Resolves PR #207.
2026-05-23 12:51:41 +02:00

77 lines
3.6 KiB
SQL

-- v1.4.49 — per-attempt push-delivery ledger.
--
-- The /api/admin/notifications/diagnostic endpoint shipped in
-- v1.4.48 carries a `recentPushAttempts` shape but returned an empty
-- array because no persistent table backed the field. This migration
-- adds the table; the matching app-side changes wire fire-and-forget
-- writes from every sender (APNS, web-push, Telegram, NTFY) and swap
-- the diagnostic stub for a real query.
--
-- Schema design:
-- * `id` — cuid surrogate key. There is no natural deduplication
-- key — the same (user, channel, event-type) tuple can fire
-- multiple times legitimately (e.g. two MEDICATION_REMINDERs in
-- a day on different schedules).
-- * `channel` — dispatcher `ChannelType` string ("APNS" |
-- "WEB_PUSH" | "TELEGRAM" | "NTFY").
-- * `event_type` — dispatcher payload `eventType` string. Stored
-- as plain text so future event-type additions
-- never require a follow-up migration.
-- * `result` — "ok" | "error" | "skipped". `skipped` covers
-- the soft "no recipient" / "config missing"
-- cases the sender contracts surface today.
-- * `reason` — sender-side reason on error/skip results,
-- null on `ok`. For APNS this is Apple's reason
-- code (`BadDeviceToken`, `Unregistered`, …).
-- * `created_at` — DEFAULT now(); the diagnostic endpoint orders
-- by this column DESC + maps to the response
-- shape's `at` ISO string.
--
-- Index strategy: `(user_id, created_at DESC)` matches the only
-- documented read path — the diagnostic endpoint pulls the trailing
-- 20 rows per user ordered by recency. The PRIMARY KEY on `id` is
-- never queried by the application; it's there to give the row a
-- stable identity for the retention sweep's WHERE clause.
--
-- Retention: a daily pg-boss schedule (`push-attempt-cleanup` queue,
-- cron `35 3 * * *` Europe/Berlin) deletes rows older than 90 days.
-- The cutoff lines up with the mood-reminder dispatch ledger window
-- (v1.4.38.2) — both surfaces are behavioural footprints we keep
-- long enough to debug a duplicate-push report (~one billing cycle)
-- but no longer. See `handlePushAttemptCleanup` in
-- `src/lib/jobs/reminder-worker.ts`.
--
-- Idempotent guards (`IF NOT EXISTS` on the table + index, plus the
-- `DO $$ … duplicate_object` block on the FK) match the pattern used
-- by 0070 / 0071 / 0072 / 0074 / 0078 so reruns are safe in
-- environments where the migration has already been applied.
--
-- Reversibility: down migration is `DROP TABLE IF EXISTS
-- "push_attempts" CASCADE;`. The data is purely diagnostic — no
-- reader outside the admin endpoint queries it — so a roll-back
-- only loses observability, never user-visible state.
CREATE TABLE IF NOT EXISTS "push_attempts" (
"id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"channel" TEXT NOT NULL,
"event_type" TEXT NOT NULL,
"result" TEXT NOT NULL,
"reason" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "push_attempts_pkey" PRIMARY KEY ("id")
);
CREATE INDEX IF NOT EXISTS "push_attempts_user_id_created_at_desc_idx"
ON "push_attempts" ("user_id", "created_at" DESC);
DO $$ BEGIN
ALTER TABLE "push_attempts"
ADD CONSTRAINT "push_attempts_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION
WHEN duplicate_object THEN NULL;
END $$;