Closer/functions/dist/notifications/idempotency.js

75 lines
3.2 KiB
JavaScript
Raw Permalink Normal View History

refactor(functions): B1 migrate 13 Firestore triggers to v2 + harden Migrate all Firestore triggers off the v1 API to firebase-functions/v2/firestore (onDocumentCreated/Updated/Written); context.params→event.params, snap→event.data, change.before/after→event.data.before/after. Region stays us-central1 (global option). Hardening folded in (all reuse in-repo patterns): - Adopt the shared sendPushToUser()/getUserTokens() helper in every trigger, removing ~7 copied token readers and the copied send/prune blocks. FCM tokens are no longer logged in plaintext anywhere here (redacted inside push.ts). - console.* → firebase-functions/logger (structured). - Idempotency: new claimOnce() (atomic create-if-absent marker under couples/{id}/notif_marks) dedupes at-least-once redelivery on the non-idempotent senders (onAnswerWritten/Revealed, onMessageWritten, onCoupleLeave, onEntitlementChanged, onDateReflectionWritten/Revealed, onDateHistoryCreated). Fail-open. onGameSessionUpdate/ onGamePartFinished/notifyOnDateMatch already had transactional claim-flags — preserved. - onRestoreRequested: the plan's "claim" is implemented as the existing 60s time-WINDOW (lastRestorePartnerAlertAt), not a permanent recipientUid marker — a permanent marker would wrongly block legitimate re-requests (restore docs are deleted+recreated by design). Faithful port of onGameSessionUpdate/onGamePartFinished (broad wildcard + allowlist kept); the trigger split and read reorder are deferred to B6 as separate commits. Build clean; 70 tests green (+ new idempotency.test.ts, push token/prune tests). Emulator discovery loads all triggers as v2 in us-central1. firebase-functions still v5.1.1 (v6 bump deferred to B6). dist rebuilt. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:46:17 -05:00
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.claimOnce = claimOnce;
exports.notifMark = notifMark;
const admin = __importStar(require("firebase-admin"));
const log_1 = require("../log");
/** gRPC status for a create() that hit an existing document. */
const ALREADY_EXISTS = 6;
/**
* Best-effort one-time claim for a notification event, keyed by a deterministic marker doc.
*
* Background triggers are delivered AT LEAST ONCE, so a redelivery of the same event would
* otherwise double-send a push. `create()` is an atomic create-if-absent: the first delivery
* writes the marker and returns true; a redelivery finds it present and returns false, so the
* caller skips. Claim right before sending a suppressed (quiet-hours / opted-out) notification
* should not burn a claim.
*
* Fail-OPEN: if create() fails for any reason OTHER than "already claimed", return true and let
* the notification proceed. A rare duplicate is better UX than a silently dropped ping, and it
* keeps an infra blip on the marker write from swallowing every notification. The trade this makes
* explicit: at-least-once at-most-once (a send failure AFTER the claim drops that one push).
*/
async function claimOnce(markRef) {
try {
await markRef.create({ claimedAt: admin.firestore.FieldValue.serverTimestamp() });
return true;
}
catch (e) {
if (e.code === ALREADY_EXISTS)
return false;
log_1.logger.warn('[claimOnce] marker create failed; proceeding without dedupe', {
path: markRef.path,
error: String(e),
});
return true;
}
}
/** Standard per-couple marker ref for a notification event (`couples/{id}/notif_marks/{markId}`). */
function notifMark(db, coupleId, markId) {
return db.collection('couples').doc(coupleId).collection('notif_marks').doc(markId);
}
//# sourceMappingURL=idempotency.js.map