Closer/functions/dist/notifications/pruneTokens.js

124 lines
5.3 KiB
JavaScript
Raw Normal View History

"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.isDeadTokenError = isDeadTokenError;
exports.selectDeadTokens = selectDeadTokens;
exports.pruneDeadTokens = pruneDeadTokens;
const admin = __importStar(require("firebase-admin"));
/**
* FCM error codes that mean a token is *permanently* dead and safe to delete.
*
* Deliberately narrow. We only prune on errors that unambiguously blame the TOKEN:
* - `registration-token-not-registered` the app was uninstalled / data-cleared / token rotated.
* - `invalid-registration-token` the token string itself is malformed.
* We intentionally do NOT include `messaging/invalid-argument` or any transient/server error
* (`unavailable`, `internal`, `quota-exceeded`, auth issues): those can be caused by a bad *payload*
* or a temporary outage, and treating them as dead would let one bug wipe every user's tokens.
*/
const DEAD_TOKEN_CODES = new Set([
'messaging/registration-token-not-registered',
'messaging/invalid-registration-token',
]);
/** Extract the `messaging/*` code from a firebase-admin messaging rejection, wherever it lives. */
function messagingErrorCode(reason) {
var _a, _b;
const r = reason;
const code = (_b = (_a = r === null || r === void 0 ? void 0 : r.errorInfo) === null || _a === void 0 ? void 0 : _a.code) !== null && _b !== void 0 ? _b : r === null || r === void 0 ? void 0 : r.code;
return typeof code === 'string' ? code : undefined;
}
/** True only when an FCM send rejection means the token is permanently invalid (safe to delete). */
function isDeadTokenError(reason) {
const code = messagingErrorCode(reason);
return code !== undefined && DEAD_TOKEN_CODES.has(code);
}
/**
* Pure: given the same `tokens` array and `Promise.allSettled` results a caller already has, return the
* distinct token strings that FCM reported as permanently dead. Index `i` in results maps to `tokens[i]`.
*/
function selectDeadTokens(tokens, results) {
const dead = new Set();
results.forEach((r, i) => {
const token = tokens[i];
if (r.status === 'rejected' && token && isDeadTokenError(r.reason))
dead.add(token);
});
return [...dead];
}
/**
* Best-effort removal of tokens FCM reported as permanently dead. Pass the `tokens` array and the
* `Promise.allSettled` results from the send you just performed; any dead token is deleted from the
* user's `fcmTokens` subcollection and cleared from the legacy `fcmToken` field if it matches.
*
* Never throws pruning is housekeeping and must never fail the notification path it runs after.
* Returns the number of token records removed.
*/
async function pruneDeadTokens(db, uid, tokens, results) {
var _a;
const dead = new Set(selectDeadTokens(tokens, results));
if (dead.size === 0)
return 0;
try {
const userRef = db.collection('users').doc(uid);
const [tokenSnap, userDoc] = await Promise.all([
userRef.collection('fcmTokens').get(),
userRef.get(),
]);
const batch = db.batch();
let removed = 0;
tokenSnap.docs.forEach((d) => {
var _a;
const t = (_a = d.data()) === null || _a === void 0 ? void 0 : _a.token;
if (typeof t === 'string' && dead.has(t)) {
batch.delete(d.ref);
removed++;
}
});
const legacy = (_a = userDoc.data()) === null || _a === void 0 ? void 0 : _a.fcmToken;
if (typeof legacy === 'string' && dead.has(legacy)) {
batch.update(userRef, { fcmToken: admin.firestore.FieldValue.delete() });
removed++;
}
if (removed > 0) {
await batch.commit();
console.log(`[pruneDeadTokens] uid=${uid} removed ${removed} dead token(s)`);
}
return removed;
}
catch (e) {
console.warn(`[pruneDeadTokens] uid=${uid} prune failed (ignored):`, e);
return 0;
}
}
//# sourceMappingURL=pruneTokens.js.map