/** * Phase 08 #65 — Push-notification fan-out worker. * * Consumes events emitted via the existing notifications pipeline and * dispatches one APNs / FCM / WebPush call per active DeviceToken for * the recipient user. The worker is intentionally provider-pluggable: * the two SDK adapters (firebase-admin for FCM, node-apn for APNs) are * injected through the `providers` seam so unit tests can mock them * without dragging the actual libraries into Vitest's module graph. * * Provider response codes that signal a permanent invalidation * (`Unregistered`, `InvalidRegistration`, `BadDeviceToken`) flip the * matching DeviceToken's `revokedAt` so subsequent fan-out passes skip * the dead row. * * Bootstrap-time config (apps/worker/src/index.ts) reads: * - FCM_SERVICE_ACCOUNT_JSON (base64 or raw JSON for the FCM key) * - APNS_KEY (PEM contents of the .p8 sign key) * - APNS_KEY_ID (10-char key id from Apple Developer) * - APNS_TEAM_ID (10-char team id) * - APNS_BUNDLE_ID (defaults to de.toolctrl.app) * * @see packages/db/src/device-tokens.server.ts * @see apps/mobile/src/pushRegistration.ts */ import { mapWithConcurrency } from "@toolctrl/foundation"; export type PushTargetPlatform = "ios" | "android" | "web"; export type PushProviderResult = { /** Provider-side message id, when available. */ messageId?: string; /** Whether the provider accepted the push. */ success: boolean; /** Provider error code (e.g. `Unregistered`, `InvalidRegistration`). */ errorCode?: string; }; export type PushPayload = { /** Bearer/user/tenant context — also forwarded to the provider as APS-data. */ userId: string; tenantId: string | null; title: string; body: string; data?: Record; }; export type DeviceTokenRow = { id: string; token: string; userId: string; tenantId: string | null; platform: string; pushProvider: string; revokedAt: Date | null; }; export type PushProviderSeam = { sendFcm: (token: string, payload: PushPayload) => Promise; sendApns: (token: string, payload: PushPayload) => Promise; sendWebPush: (token: string, payload: PushPayload) => Promise; }; export type PushFanOutInput = { payload: PushPayload; /** Lister: active (revokedAt IS NULL) tokens for the recipient. */ tokenLister: (args: { userId: string; tenantId: string | null }) => Promise; /** Provider seam — injected by apps/worker/src/index.ts. */ providers: PushProviderSeam; /** Revoke seam — called when the provider returns a permanent error. */ tokenRevoker: (token: string) => Promise; /** Max active device tokens sent at once. Default is intentionally conservative. */ concurrency?: number; /** Optional logger. */ logger?: { info: (fields: Record, msg: string) => void; warn?: (fields: Record, msg: string) => void; error?: (fields: Record, msg: string) => void; }; }; export type PushFanOutResult = { attempted: number; succeeded: number; revoked: number; failed: number; }; const REVOCATION_ERROR_CODES = new Set([ "Unregistered", "InvalidRegistration", "BadDeviceToken", "DeviceTokenNotForTopic", "messaging/registration-token-not-registered", "messaging/invalid-registration-token", ]); export const PUSH_NOTIFICATION_FAN_OUT_CONCURRENCY = 5; /** * Fan out a single notification to every active device for the user. * * Pure orchestrator — no DB / SDK imports — so it can be unit-tested with * Map-backed stubs. The worker entry point wires the seams against the * real Prisma client and provider SDKs. */ export async function dispatchPushNotification(input: PushFanOutInput): Promise { const tokens = await input.tokenLister({ userId: input.payload.userId, tenantId: input.payload.tenantId }); const active = tokens.filter((row) => row.revokedAt === null); let succeeded = 0; let revoked = 0; let failed = 0; await mapWithConcurrency(active, input.concurrency ?? PUSH_NOTIFICATION_FAN_OUT_CONCURRENCY, async (row) => { const result = await sendForRow(row, input.payload, input.providers); if (result.success) { succeeded += 1; input.logger?.info( { token: redactToken(row.token), platform: row.platform, provider: row.pushProvider, messageId: result.messageId }, "push delivered", ); return; } if (result.errorCode && REVOCATION_ERROR_CODES.has(result.errorCode)) { await input.tokenRevoker(row.token); revoked += 1; input.logger?.warn?.( { token: redactToken(row.token), platform: row.platform, errorCode: result.errorCode }, "push provider reported token revoked", ); return; } failed += 1; input.logger?.error?.( { token: redactToken(row.token), platform: row.platform, errorCode: result.errorCode }, "push delivery failed", ); }); return { attempted: active.length, succeeded, revoked, failed }; } async function sendForRow(row: DeviceTokenRow, payload: PushPayload, providers: PushProviderSeam): Promise { if (row.platform === "ios" || row.pushProvider === "apns") { return providers.sendApns(row.token, payload); } if (row.platform === "android" || row.pushProvider === "fcm") { return providers.sendFcm(row.token, payload); } return providers.sendWebPush(row.token, payload); } /** Redacts everything but the leading 8 chars of a token for log lines. */ export function redactToken(token: string): string { if (token.length <= 8) return `${token.slice(0, 2)}…`; return `${token.slice(0, 8)}…`; } export { REVOCATION_ERROR_CODES };