add per-device FCM outcome log for alert search pushes
Record each device attempted in an AlertSearch digest send in alert_push_device_sends, with the FCM message id or error code and a sanitized detail. FCM accepting a message does not mean the device displayed it. - alert_push_sends remains the DID-level daily-cap record, unchanged - device rows link to it when one exists - a failed device-log write is logged and does not change the send result or retry FCM - push:watch adds a Device attempts view (key 5) and a per-DID summary, still read-only
This commit is contained in:
@@ -65,13 +65,13 @@ if (matches.length !== 1) {
|
||||
}
|
||||
|
||||
const row = matches[0];
|
||||
const status = await sendAlertSearchPushToDevice(row.fcmToken, {
|
||||
const outcome = await sendAlertSearchPushToDevice(row.fcmToken, {
|
||||
title: TITLE,
|
||||
body: BODY,
|
||||
});
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
status,
|
||||
status: outcome.status,
|
||||
deviceId: row.deviceId,
|
||||
platform: row.platform,
|
||||
tokenSuffix: maskToken(row.fcmToken),
|
||||
@@ -80,4 +80,4 @@ console.log(
|
||||
dataType: "alert_search",
|
||||
})
|
||||
);
|
||||
process.exit(status === "sent" ? 0 : 1);
|
||||
process.exit(outcome.status === "sent" ? 0 : 1);
|
||||
|
||||
+135
-14
@@ -1,8 +1,19 @@
|
||||
import {
|
||||
alertPushDeviceSendsDb,
|
||||
type AlertPushDeviceSendInput,
|
||||
} from "../db/alertPushDeviceSendsSqlite.js";
|
||||
import { alertPushSendsDb } from "../db/alertPushSendsSqlite.js";
|
||||
import { db } from "../db/fcmTokensSqlite.js";
|
||||
import { pushSameDayResendDids } from "../env.js";
|
||||
import { utcCalendarDay } from "../services/alertAuthorization.js";
|
||||
import { errorMessage } from "../util/formatElapsed.js";
|
||||
import {
|
||||
FCM_ERROR_CODE_MAX_CHARS,
|
||||
FCM_ERROR_DETAIL_MAX_CHARS,
|
||||
FCM_MESSAGE_ID_MAX_CHARS,
|
||||
sanitizeFcmDiagnostic,
|
||||
type FcmSendResult,
|
||||
} from "../util/fcmOutcome.js";
|
||||
import {
|
||||
ALERT_SEARCH_UPDATE_CATEGORIES,
|
||||
countAlertSearchUpdates,
|
||||
@@ -26,16 +37,24 @@ export type AlertSearchNotificationContent = {
|
||||
cursorParam?: string;
|
||||
};
|
||||
|
||||
/** A plain status, or the FCM message id / error captured from that send. */
|
||||
export type AlertSearchSendOutcome = "sent" | "failed" | FcmSendResult;
|
||||
|
||||
export type AlertSearchTokenSender = (
|
||||
fcmToken: string,
|
||||
content: AlertSearchNotificationContent
|
||||
) => Promise<"sent" | "failed">;
|
||||
) => Promise<AlertSearchSendOutcome>;
|
||||
|
||||
export type AlertSearchNotifyDeps = {
|
||||
listTokens?: (userId: string) => Promise<string[]>;
|
||||
send?: AlertSearchTokenSender;
|
||||
/** Cap window uses this instant's UTC day. Tests pass a fixed clock. */
|
||||
now?: Date;
|
||||
/**
|
||||
* Writes the per-device diagnostic rows. A failure here is logged and does
|
||||
* not change the send result or the daily-cap row. Tests can make it throw.
|
||||
*/
|
||||
recordDeviceAttempts?: (rows: readonly AlertPushDeviceSendInput[]) => Promise<void>;
|
||||
};
|
||||
|
||||
export type AlertSearchNotifyResult = {
|
||||
@@ -145,23 +164,90 @@ export function isAlertSearchNotificationEligible(
|
||||
);
|
||||
}
|
||||
|
||||
/** This identity's registered FCM tokens, each once. */
|
||||
export async function listRegisteredTokens(userId: string): Promise<string[]> {
|
||||
type AttemptedDevice = {
|
||||
token: string;
|
||||
deviceId: string;
|
||||
platform: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Registrations actually eligible for a send, one per distinct token.
|
||||
* The first row returned for a token wins, matching `getByUserId` order.
|
||||
* A later row that repeats the token is not attempted.
|
||||
*/
|
||||
export async function listRegisteredDevices(userId: string): Promise<AttemptedDevice[]> {
|
||||
const rows = await db.getByUserId(userId);
|
||||
const seen = new Set<string>();
|
||||
const tokens: string[] = [];
|
||||
const devices: AttemptedDevice[] = [];
|
||||
for (const row of rows) {
|
||||
if (seen.has(row.fcmToken)) continue;
|
||||
seen.add(row.fcmToken);
|
||||
tokens.push(row.fcmToken);
|
||||
devices.push({ token: row.fcmToken, deviceId: row.deviceId, platform: row.platform });
|
||||
}
|
||||
return tokens;
|
||||
return devices;
|
||||
}
|
||||
|
||||
/** This identity's registered FCM tokens, each once. */
|
||||
export async function listRegisteredTokens(userId: string): Promise<string[]> {
|
||||
return (await listRegisteredDevices(userId)).map((row) => row.token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map an overridden token list back onto the registration that owns each
|
||||
* token. The same first-row-wins rule decides which device id is logged.
|
||||
* A token with no registration is still sent, and is not logged: there is
|
||||
* no device row to attach.
|
||||
*/
|
||||
async function resolveListedTokens(
|
||||
userId: string,
|
||||
tokens: readonly string[]
|
||||
): Promise<Array<{ token: string; deviceId: string | null; platform: string | null }>> {
|
||||
const rows = await db.getByUserId(userId);
|
||||
const byToken = new Map<string, { deviceId: string; platform: string }>();
|
||||
for (const row of rows) {
|
||||
if (byToken.has(row.fcmToken)) continue;
|
||||
byToken.set(row.fcmToken, { deviceId: row.deviceId, platform: row.platform });
|
||||
}
|
||||
return tokens.map((token) => {
|
||||
const row = byToken.get(token);
|
||||
return {
|
||||
token,
|
||||
deviceId: row?.deviceId ?? null,
|
||||
platform: row?.platform ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function asOutcome(value: AlertSearchSendOutcome): FcmSendResult {
|
||||
if (value === "sent" || value === "failed") return { status: value };
|
||||
return value;
|
||||
}
|
||||
|
||||
function cleanField(value: string | undefined, token: string, maxChars: number): string | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const text = sanitizeFcmDiagnostic(value, token, maxChars);
|
||||
return text.length === 0 ? undefined : text;
|
||||
}
|
||||
|
||||
/** Keep success ids and failure text, and strip the token that was sent. */
|
||||
function persistedOutcome(outcome: FcmSendResult, token: string): FcmSendResult {
|
||||
if (outcome.status === "sent") {
|
||||
const messageId = cleanField(outcome.messageId, token, FCM_MESSAGE_ID_MAX_CHARS);
|
||||
return messageId === undefined ? { status: "sent" } : { status: "sent", messageId };
|
||||
}
|
||||
const errorCode = cleanField(outcome.errorCode, token, FCM_ERROR_CODE_MAX_CHARS);
|
||||
const errorDetail = cleanField(outcome.errorDetail, token, FCM_ERROR_DETAIL_MAX_CHARS);
|
||||
return {
|
||||
status: "failed",
|
||||
...(errorCode === undefined ? {} : { errorCode }),
|
||||
...(errorDetail === undefined ? {} : { errorDetail }),
|
||||
};
|
||||
}
|
||||
|
||||
async function defaultSend(
|
||||
fcmToken: string,
|
||||
content: AlertSearchNotificationContent
|
||||
): Promise<"sent" | "failed"> {
|
||||
): Promise<FcmSendResult> {
|
||||
const { sendAlertSearchPushToDevice } = await import(
|
||||
"../services/pushService.js"
|
||||
);
|
||||
@@ -208,29 +294,64 @@ export async function deliverAlertSearchNotification(
|
||||
return { eligible: true, sent: 0, failed: 0, capped: true };
|
||||
}
|
||||
|
||||
const listTokens = deps.listTokens ?? listRegisteredTokens;
|
||||
const send = deps.send ?? defaultSend;
|
||||
const tokens = await listTokens(result.userId);
|
||||
const targets = deps.listTokens
|
||||
? await resolveListedTokens(result.userId, await deps.listTokens(result.userId))
|
||||
: await listRegisteredDevices(result.userId);
|
||||
let sent = 0;
|
||||
let failed = 0;
|
||||
const attemptedAt = now.toISOString();
|
||||
const attempts: AlertPushDeviceSendInput[] = [];
|
||||
|
||||
for (const token of tokens) {
|
||||
for (const target of targets) {
|
||||
let outcome: FcmSendResult;
|
||||
try {
|
||||
const status = await send(token, content);
|
||||
if (status === "sent") sent += 1;
|
||||
outcome = persistedOutcome(asOutcome(await send(target.token, content)), target.token);
|
||||
if (outcome.status === "sent") sent += 1;
|
||||
else failed += 1;
|
||||
} catch (err) {
|
||||
failed += 1;
|
||||
log.error("[AlertSearchNotify] Send threw:", errorMessage(err));
|
||||
outcome = persistedOutcome(
|
||||
{ status: "failed", errorDetail: errorMessage(err) },
|
||||
target.token
|
||||
);
|
||||
}
|
||||
if (target.deviceId === null) continue;
|
||||
attempts.push({
|
||||
userId: result.userId,
|
||||
deviceId: target.deviceId,
|
||||
platform: target.platform,
|
||||
pushSendId: null,
|
||||
attemptedAt,
|
||||
outcome: outcome.status,
|
||||
fcmMessageId: outcome.messageId ?? null,
|
||||
fcmErrorCode: outcome.errorCode ?? null,
|
||||
errorDetail: outcome.errorDetail ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
// The DID-level row is still written only when Firebase accepted at least
|
||||
// one device, and only after those sends. Device rows do not count toward
|
||||
// the cap. A diagnostic-write failure must not undo this row or resend.
|
||||
let pushSendId: string | null = null;
|
||||
if (sent > 0) {
|
||||
await alertPushSendsDb.append({
|
||||
pushSendId = await alertPushSendsDb.append({
|
||||
userId: result.userId,
|
||||
batchId: result.batchId,
|
||||
sentAt: now.toISOString(),
|
||||
sentAt: attemptedAt,
|
||||
});
|
||||
}
|
||||
if (pushSendId !== null) {
|
||||
for (const attempt of attempts) attempt.pushSendId = pushSendId;
|
||||
}
|
||||
if (attempts.length > 0) {
|
||||
const record = deps.recordDeviceAttempts ?? ((rows) => alertPushDeviceSendsDb.appendMany(rows));
|
||||
try {
|
||||
await record(attempts);
|
||||
} catch (err) {
|
||||
log.error("[AlertSearchNotify] Per-device outcome log failed:", errorMessage(err));
|
||||
}
|
||||
}
|
||||
return { eligible: true, sent, failed };
|
||||
}
|
||||
|
||||
@@ -111,7 +111,8 @@ async function deliverPush(
|
||||
const { sendAlertSearchPushToDevice } = await import(
|
||||
"../services/pushService.js"
|
||||
);
|
||||
return sendAlertSearchPushToDevice(token, c);
|
||||
const outcome = await sendAlertSearchPushToDevice(token, c);
|
||||
return outcome.status;
|
||||
});
|
||||
let sent = 0;
|
||||
let failed = 0;
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
FCM_ERROR_CODE_MAX_CHARS,
|
||||
FCM_ERROR_DETAIL_MAX_CHARS,
|
||||
FCM_MESSAGE_ID_MAX_CHARS,
|
||||
sanitizeFcmDiagnostic,
|
||||
} from "../util/fcmOutcome.js";
|
||||
import { ALERT_PUSH_SEND_RETENTION_DAYS } from "./alertPushSendsSqlite.js";
|
||||
import { getDatabase } from "./sqlite.js";
|
||||
|
||||
/**
|
||||
* One attempted device in an AlertSearch digest send.
|
||||
* `outcome` is `sent` when Firebase accepted the message and `failed` when it
|
||||
* rejected it. This is not the daily-cap row and not a display receipt.
|
||||
* `pushSendId` is the `alert_push_sends` id when that DID-level row was
|
||||
* written, and null when every attempted device failed.
|
||||
*/
|
||||
export type AlertPushDeviceSendInput = {
|
||||
userId: string;
|
||||
deviceId: string;
|
||||
platform: string | null;
|
||||
pushSendId: string | null;
|
||||
attemptedAt: string;
|
||||
outcome: "sent" | "failed";
|
||||
fcmMessageId: string | null;
|
||||
fcmErrorCode: string | null;
|
||||
errorDetail: string | null;
|
||||
};
|
||||
|
||||
function storedText(value: string | null, maxChars: number): string | null {
|
||||
if (value === null) return null;
|
||||
const text = sanitizeFcmDiagnostic(value, undefined, maxChars);
|
||||
return text.length === 0 ? null : text;
|
||||
}
|
||||
|
||||
/** Per-device FCM outcomes for AlertSearch digest sends. Not used by the daily cap. */
|
||||
export const alertPushDeviceSendsDb = {
|
||||
/**
|
||||
* Record the devices that were actually included in one send.
|
||||
* Rows for this identity older than the shared retention window are dropped.
|
||||
* Callers must already have removed registration tokens from the text fields.
|
||||
*/
|
||||
async appendMany(rows: readonly AlertPushDeviceSendInput[]): Promise<void> {
|
||||
if (rows.length === 0) return;
|
||||
const db = getDatabase();
|
||||
const latestByUser = new Map<string, string>();
|
||||
for (const row of rows) {
|
||||
const current = latestByUser.get(row.userId);
|
||||
if (current === undefined || row.attemptedAt > current) {
|
||||
latestByUser.set(row.userId, row.attemptedAt);
|
||||
}
|
||||
}
|
||||
db.transaction(() => {
|
||||
const insert = db.prepare(
|
||||
`INSERT INTO alert_push_device_sends (
|
||||
id, user_id, device_id, platform, push_send_id, attempted_at,
|
||||
outcome, fcm_message_id, fcm_error_code, error_detail
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
);
|
||||
for (const row of rows) {
|
||||
const outcome = row.outcome === "sent" ? "sent" : "failed";
|
||||
insert.run(
|
||||
randomUUID(),
|
||||
row.userId,
|
||||
row.deviceId,
|
||||
storedText(row.platform, FCM_ERROR_DETAIL_MAX_CHARS),
|
||||
row.pushSendId,
|
||||
row.attemptedAt,
|
||||
outcome,
|
||||
outcome === "sent" ? storedText(row.fcmMessageId, FCM_MESSAGE_ID_MAX_CHARS) : null,
|
||||
outcome === "failed" ? storedText(row.fcmErrorCode, FCM_ERROR_CODE_MAX_CHARS) : null,
|
||||
outcome === "failed" ? storedText(row.errorDetail, FCM_ERROR_DETAIL_MAX_CHARS) : null
|
||||
);
|
||||
}
|
||||
const prune = db.prepare(
|
||||
`DELETE FROM alert_push_device_sends WHERE user_id = ? AND attempted_at < ?`
|
||||
);
|
||||
for (const [userId, attemptedAt] of latestByUser) {
|
||||
const parsed = Date.parse(attemptedAt);
|
||||
if (Number.isNaN(parsed)) continue;
|
||||
const cutoff = new Date(
|
||||
parsed - ALERT_PUSH_SEND_RETENTION_DAYS * 24 * 60 * 60 * 1000
|
||||
).toISOString();
|
||||
prune.run(userId, cutoff);
|
||||
}
|
||||
})();
|
||||
},
|
||||
};
|
||||
@@ -11,21 +11,23 @@ export const alertPushSendsDb = {
|
||||
userId: string;
|
||||
batchId?: string | null;
|
||||
sentAt?: string;
|
||||
}): Promise<void> {
|
||||
}): Promise<string> {
|
||||
const sentAt = input.sentAt ?? new Date().toISOString();
|
||||
const cutoff = new Date(
|
||||
Date.parse(sentAt) - ALERT_PUSH_SEND_RETENTION_DAYS * 24 * 60 * 60 * 1000
|
||||
).toISOString();
|
||||
const id = randomUUID();
|
||||
const db = getDatabase();
|
||||
db.transaction(() => {
|
||||
db.prepare(
|
||||
`INSERT INTO alert_push_sends (id, user_id, batch_id, sent_at)
|
||||
VALUES (?, ?, ?, ?)`
|
||||
).run(randomUUID(), input.userId, input.batchId ?? null, sentAt);
|
||||
).run(id, input.userId, input.batchId ?? null, sentAt);
|
||||
db.prepare(
|
||||
`DELETE FROM alert_push_sends WHERE user_id = ? AND sent_at < ?`
|
||||
).run(input.userId, cutoff);
|
||||
})();
|
||||
return id;
|
||||
},
|
||||
|
||||
/** Sends to this identity at or after `sinceIso`. */
|
||||
|
||||
@@ -333,6 +333,32 @@ CREATE TABLE IF NOT EXISTS alert_push_sends (
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_alert_push_sends_user_sent
|
||||
ON alert_push_sends (user_id, sent_at);
|
||||
|
||||
-- One row per registered device included in an AlertSearch FCM send.
|
||||
-- outcome is sent when Firebase accepted the message and failed when it
|
||||
-- rejected it. Neither means the device displayed the notification.
|
||||
-- push_send_id matches alert_push_sends when that DID-level row exists
|
||||
-- (at least one device was accepted). It is null when every device failed,
|
||||
-- because no DID-level row is written in that case. The daily cap does not
|
||||
-- read this table. Tokens, JWTs, and notification bodies are not stored.
|
||||
CREATE TABLE IF NOT EXISTS alert_push_device_sends (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
device_id TEXT NOT NULL,
|
||||
platform TEXT,
|
||||
push_send_id TEXT,
|
||||
attempted_at TEXT NOT NULL,
|
||||
outcome TEXT NOT NULL,
|
||||
fcm_message_id TEXT,
|
||||
fcm_error_code TEXT,
|
||||
error_detail TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_alert_push_device_sends_user_attempted
|
||||
ON alert_push_device_sends (user_id, attempted_at);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_alert_push_device_sends_device_attempted
|
||||
ON alert_push_device_sends (device_id, attempted_at);
|
||||
`;
|
||||
|
||||
let database: Database.Database | null = null;
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { errorMessage, formatElapsedMs } from "../util/formatElapsed.js";
|
||||
import {
|
||||
FCM_MESSAGE_ID_MAX_CHARS,
|
||||
fcmFailureParts,
|
||||
sanitizeFcmDiagnostic,
|
||||
type FcmSendResult,
|
||||
} from "../util/fcmOutcome.js";
|
||||
import { maskToken } from "../util/maskToken.js";
|
||||
import {
|
||||
ALERT_SEARCH_FCM_TYPE,
|
||||
@@ -9,27 +15,31 @@ import { messaging } from "./firebase.js";
|
||||
import { log } from "../util/log.js";
|
||||
|
||||
export { ALERT_SEARCH_FCM_TYPE };
|
||||
export type { FcmSendResult };
|
||||
|
||||
/**
|
||||
* User-visible AlertSearch digest push.
|
||||
* `sent` means Firebase accepted the message. It does not mean the device
|
||||
* displayed it. The message id and error fields are safe to persist.
|
||||
*/
|
||||
export async function sendAlertSearchPushToDevice(
|
||||
fcmToken: string,
|
||||
content: AlertSearchFcmContent
|
||||
): Promise<"sent" | "failed"> {
|
||||
): Promise<FcmSendResult> {
|
||||
const suffix = maskToken(fcmToken);
|
||||
const sendStarted = Date.now();
|
||||
log.info("[AlertSearchPush] Send attempt, token suffix:", suffix);
|
||||
|
||||
try {
|
||||
await messaging.send(buildAlertSearchFcmMessage(fcmToken, content));
|
||||
const rawId = await messaging.send(buildAlertSearchFcmMessage(fcmToken, content));
|
||||
const messageId = sanitizeFcmDiagnostic(String(rawId), fcmToken, FCM_MESSAGE_ID_MAX_CHARS);
|
||||
log.info(
|
||||
"[AlertSearchPush] Send completed in",
|
||||
formatElapsedMs(Date.now() - sendStarted) + ",",
|
||||
"token suffix:",
|
||||
suffix
|
||||
);
|
||||
return "sent";
|
||||
return messageId.length === 0 ? { status: "sent" } : { status: "sent", messageId };
|
||||
} catch (err) {
|
||||
log.error(
|
||||
"[AlertSearchPush] Send failed in",
|
||||
@@ -38,6 +48,6 @@ export async function sendAlertSearchPushToDevice(
|
||||
suffix + ":",
|
||||
errorMessage(err)
|
||||
);
|
||||
return "failed";
|
||||
return { status: "failed", ...fcmFailureParts(err, fcmToken) };
|
||||
}
|
||||
}
|
||||
|
||||
+210
-11
@@ -6,8 +6,11 @@
|
||||
*
|
||||
* alert_push_sends is one row per DID when a push reached at least one device.
|
||||
* It is not per-device delivery, not an FCM result, and not proof the
|
||||
* notification was displayed. last_notified_at is raw stored metadata and is
|
||||
* not a delivery indicator. A registration quiet for 30 days is a warning, not
|
||||
* notification was displayed. alert_push_device_sends is one row per device
|
||||
* Firebase accepted or rejected. Accepted means Firebase took the message,
|
||||
* not that the device received, displayed, or opened it. Those rows are not
|
||||
* the daily cap. last_notified_at is raw stored metadata and is not a
|
||||
* delivery indicator. A registration quiet for 30 days is a warning, not
|
||||
* proof that Firebase invalidated the token.
|
||||
*
|
||||
* pnpm run push:watch
|
||||
@@ -21,7 +24,7 @@
|
||||
* a snapshot and exits; stdout that is not a TTY does the same. The database
|
||||
* is opened read-only and is never created or migrated here.
|
||||
*
|
||||
* Keys: 1/2/3/4 or Tab switch view, j/k or arrows move, Enter expands,
|
||||
* Keys: 1/2/3/4/5 or Tab switch view, j/k or arrows move, Enter expands,
|
||||
* Esc goes back, q quits.
|
||||
*/
|
||||
import path from "node:path";
|
||||
@@ -37,6 +40,7 @@ export const PUSH_WATCH_TABLES = [
|
||||
"alert_authorization_jwts",
|
||||
"alert_search_cursors",
|
||||
"alert_push_sends",
|
||||
"alert_push_device_sends",
|
||||
] as const;
|
||||
|
||||
/** Platforms the client model names. The route still stores any other string. */
|
||||
@@ -50,6 +54,8 @@ const WEEK_MS = 7 * DAY_MS;
|
||||
|
||||
const SEND_LIMITATION =
|
||||
"alert_push_sends is a DID-level record written when a push reached at least one device. It does not record which device, FCM errors, or that the notification was displayed.";
|
||||
const DEVICE_ATTEMPT_LIMITATION =
|
||||
"alert_push_device_sends is one row per registered device included in an AlertSearch FCM send. Accepted means Firebase took the message. It does not mean the device received, displayed, or opened it. These rows are not the daily-cap record; alert_push_sends is.";
|
||||
const STALE_LIMITATION =
|
||||
"A registration not updated for 30 days is a warning only, not proof that Firebase invalidated the token.";
|
||||
const LAST_NOTIFIED_LIMITATION =
|
||||
@@ -341,6 +347,26 @@ export type PushSendInput = {
|
||||
sentAt: string;
|
||||
};
|
||||
|
||||
/** One device Firebase accepted or rejected. No token, JWT, or message body. */
|
||||
export type DeviceAttemptInput = {
|
||||
userId: string;
|
||||
deviceId: string;
|
||||
platform: string | null;
|
||||
pushSendId: string | null;
|
||||
attemptedAt: string;
|
||||
outcome: string;
|
||||
fcmMessageId: string | null;
|
||||
fcmErrorCode: string | null;
|
||||
errorDetail: string | null;
|
||||
};
|
||||
|
||||
export type DeviceAttemptSummary = {
|
||||
total: number;
|
||||
succeeded: number;
|
||||
failed: number;
|
||||
mostRecentAt?: string;
|
||||
};
|
||||
|
||||
export type RegistrationView = {
|
||||
id: string;
|
||||
userId: string;
|
||||
@@ -466,6 +492,8 @@ export type Snapshot = {
|
||||
last24h: number;
|
||||
last7d: number;
|
||||
};
|
||||
deviceAttempts: DeviceAttemptInput[];
|
||||
deviceAttemptSummary: DeviceAttemptSummary;
|
||||
};
|
||||
|
||||
export type BuildInput = {
|
||||
@@ -477,6 +505,7 @@ export type BuildInput = {
|
||||
jwts: readonly JwtInput[];
|
||||
cursors: readonly CursorInfo[];
|
||||
sends: readonly PushSendInput[];
|
||||
deviceAttempts: readonly DeviceAttemptInput[];
|
||||
};
|
||||
|
||||
export function summarizeJwts(jwts: readonly JwtInput[], today: string): JwtSummary {
|
||||
@@ -599,6 +628,37 @@ function compareSends(a: PushSendInput, b: PushSendInput): number {
|
||||
return a.userId < b.userId ? -1 : a.userId > b.userId ? 1 : 0;
|
||||
}
|
||||
|
||||
function compareAttempts(a: DeviceAttemptInput, b: DeviceAttemptInput): number {
|
||||
const at = Date.parse(a.attemptedAt);
|
||||
const bt = Date.parse(b.attemptedAt);
|
||||
if (!Number.isNaN(at) && !Number.isNaN(bt) && at !== bt) return bt - at;
|
||||
if (a.attemptedAt !== b.attemptedAt) return a.attemptedAt < b.attemptedAt ? 1 : -1;
|
||||
if (a.deviceId !== b.deviceId) return a.deviceId < b.deviceId ? -1 : 1;
|
||||
return a.userId < b.userId ? -1 : a.userId > b.userId ? 1 : 0;
|
||||
}
|
||||
|
||||
/** Counts every stored attempt. The most recent one is the latest at or before now. */
|
||||
export function summarizeDeviceAttempts(
|
||||
rows: readonly DeviceAttemptInput[],
|
||||
now: Date
|
||||
): DeviceAttemptSummary {
|
||||
let succeeded = 0;
|
||||
let failed = 0;
|
||||
for (const row of rows) {
|
||||
if (row.outcome === "sent") succeeded += 1;
|
||||
else if (row.outcome === "failed") failed += 1;
|
||||
}
|
||||
return {
|
||||
total: rows.length,
|
||||
succeeded,
|
||||
failed,
|
||||
mostRecentAt: latestParsedIso(
|
||||
rows.map((row) => row.attemptedAt),
|
||||
now.getTime()
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Union of DIDs across the push tables. A DID with a registration and no
|
||||
* batch stays in the list, and so does the reverse. Token text is masked
|
||||
@@ -628,6 +688,7 @@ export function buildSnapshot(input: BuildInput): Snapshot {
|
||||
const jwtsByDid = groupBy(input.jwts, (row) => row.userId);
|
||||
const cursorsByDid = new Map(input.cursors.map((row) => [row.userId, row]));
|
||||
const sendsByDid = groupBy(input.sends, (row) => row.userId);
|
||||
const attemptsByDid = groupBy(input.deviceAttempts, (row) => row.userId);
|
||||
|
||||
const didIds = new Set<string>([
|
||||
...regsByDid.keys(),
|
||||
@@ -635,6 +696,7 @@ export function buildSnapshot(input: BuildInput): Snapshot {
|
||||
...jwtsByDid.keys(),
|
||||
...cursorsByDid.keys(),
|
||||
...sendsByDid.keys(),
|
||||
...attemptsByDid.keys(),
|
||||
]);
|
||||
const focusFound = focus === undefined || didIds.has(focus);
|
||||
const selected = [...didIds]
|
||||
@@ -734,6 +796,14 @@ export function buildSnapshot(input: BuildInput): Snapshot {
|
||||
didsWithoutUsableToday: dids.filter((did) => !did.usableToday).length,
|
||||
};
|
||||
|
||||
const deviceAttempts = (
|
||||
focus === undefined
|
||||
? input.deviceAttempts
|
||||
: input.deviceAttempts.filter((row) => row.userId === focus)
|
||||
)
|
||||
.slice()
|
||||
.sort(compareAttempts);
|
||||
|
||||
return {
|
||||
dbPath: input.dbPath,
|
||||
now,
|
||||
@@ -758,6 +828,8 @@ export function buildSnapshot(input: BuildInput): Snapshot {
|
||||
last24h: countParsedSince(sends.map((send) => send.sentAt), now, DAY_MS),
|
||||
last7d: countParsedSince(sends.map((send) => send.sentAt), now, WEEK_MS),
|
||||
},
|
||||
deviceAttempts,
|
||||
deviceAttemptSummary: summarizeDeviceAttempts(deviceAttempts, now),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -931,6 +1003,10 @@ export function didOverview(did: DidReport, snapshot: Snapshot): string[] {
|
||||
`Push sends (7d): ${did.pushes7d}`,
|
||||
`Push send records: ${did.sendCount}`,
|
||||
SEND_LIMITATION,
|
||||
...deviceAttemptSummaryLines(
|
||||
snapshot.deviceAttempts.filter((row) => row.userId === did.did),
|
||||
snapshot.now
|
||||
),
|
||||
];
|
||||
if (flags.length > 0) lines.push(`Flags: ${flags.join(" ")}`);
|
||||
if (did.todayJwt !== undefined && !did.todayJwtOnLatest) {
|
||||
@@ -1050,6 +1126,56 @@ export function authorizationDetail(did: DidReport, snapshot: Snapshot): string[
|
||||
return lines;
|
||||
}
|
||||
|
||||
function deviceAttemptSummaryLines(rows: readonly DeviceAttemptInput[], now: Date): string[] {
|
||||
const summary = summarizeDeviceAttempts(rows, now);
|
||||
return [
|
||||
`Device attempts: ${summary.total}`,
|
||||
`Device attempts accepted by FCM: ${summary.succeeded}`,
|
||||
`Device attempts rejected by FCM: ${summary.failed}`,
|
||||
`Most recent device attempt: ${summary.mostRecentAt ?? "none"}`,
|
||||
DEVICE_ATTEMPT_LIMITATION,
|
||||
];
|
||||
}
|
||||
|
||||
function fcmOutcomeLabel(outcome: string): string {
|
||||
if (outcome === "sent") return "accepted";
|
||||
if (outcome === "failed") return "rejected";
|
||||
return outcome;
|
||||
}
|
||||
|
||||
export function deviceAttemptLine(row: DeviceAttemptInput): string {
|
||||
return [
|
||||
stamp(row.attemptedAt),
|
||||
abbreviateMiddle(row.userId),
|
||||
abbreviateMiddle(row.deviceId, 8, 4),
|
||||
row.platform ?? "-",
|
||||
`fcm=${fcmOutcomeLabel(row.outcome)}`,
|
||||
row.fcmMessageId ? `id=${row.fcmMessageId}` : "id=-",
|
||||
row.fcmErrorCode ?? "",
|
||||
row.errorDetail ?? "",
|
||||
]
|
||||
.filter((part) => part.length > 0)
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
export function deviceAttemptDetail(row: DeviceAttemptInput): string[] {
|
||||
const label = row.outcome === "sent"
|
||||
? "accepted (FCM accepted the message; not proof the device displayed it)"
|
||||
: fcmOutcomeLabel(row.outcome);
|
||||
return [
|
||||
`attempted_at: ${row.attemptedAt}`,
|
||||
`DID: ${show(row.userId)}`,
|
||||
`Device ID: ${show(row.deviceId)}`,
|
||||
`Platform: ${row.platform ?? "-"}`,
|
||||
`FCM outcome: ${label}`,
|
||||
`FCM message ID: ${row.fcmMessageId ?? "-"}`,
|
||||
`FCM error code: ${row.fcmErrorCode ?? "-"}`,
|
||||
`Error detail: ${row.errorDetail ?? "-"}`,
|
||||
`DID-level push send id: ${row.pushSendId ?? "-"}`,
|
||||
DEVICE_ATTEMPT_LIMITATION,
|
||||
];
|
||||
}
|
||||
|
||||
export function sendDetail(send: PushSendInput, snapshot: Snapshot): string[] {
|
||||
const did = snapshot.dids.find((row) => row.did === send.userId);
|
||||
return [
|
||||
@@ -1076,6 +1202,14 @@ export function didDetail(did: DidReport, snapshot: Snapshot): string[] {
|
||||
? ["(none)"]
|
||||
: did.recentSends.slice(0, 30).flatMap((send) => ["", ...sendDetail(send, snapshot)])),
|
||||
...(did.recentSends.length > 30 ? [`(showing 30 of ${did.recentSends.length} sends)`] : []),
|
||||
"",
|
||||
"Device attempts for this DID:",
|
||||
...(snapshot.deviceAttempts.filter((row) => row.userId === did.did).length === 0
|
||||
? ["(none)"]
|
||||
: snapshot.deviceAttempts
|
||||
.filter((row) => row.userId === did.did)
|
||||
.slice(0, 30)
|
||||
.flatMap((row) => ["", ...deviceAttemptDetail(row)])),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1129,6 +1263,7 @@ export function formatOnce(snapshot: Snapshot): string {
|
||||
REG_KEY_LIMITATION,
|
||||
AUTH_LIMITATION,
|
||||
CURSOR_LIMITATION,
|
||||
DEVICE_ATTEMPT_LIMITATION,
|
||||
];
|
||||
if (snapshot.focusDid !== undefined) {
|
||||
lines.push(`Focus DID ${snapshot.focusDid}`);
|
||||
@@ -1191,6 +1326,28 @@ export function formatOnce(snapshot: Snapshot): string {
|
||||
} else {
|
||||
pushLimited(lines, snapshot.sends.map(sendLine), ONCE_SEND_LIMIT, "sends");
|
||||
}
|
||||
lines.push("", "== Device attempts ==");
|
||||
lines.push(DEVICE_ATTEMPT_LIMITATION);
|
||||
lines.push(...deviceAttemptSummaryLines(snapshot.deviceAttempts, snapshot.now));
|
||||
if (snapshot.focusDid !== undefined && !snapshot.focusFound) {
|
||||
lines.push("(none)");
|
||||
} else if (snapshot.focusDid !== undefined) {
|
||||
if (snapshot.deviceAttempts.length === 0) lines.push("(none)");
|
||||
for (const row of snapshot.deviceAttempts.slice(0, ONCE_SEND_LIMIT)) {
|
||||
lines.push(...deviceAttemptDetail(row));
|
||||
lines.push("");
|
||||
}
|
||||
if (snapshot.deviceAttempts.length > ONCE_SEND_LIMIT) {
|
||||
lines.push(`(showing ${ONCE_SEND_LIMIT} of ${snapshot.deviceAttempts.length} device attempts)`);
|
||||
}
|
||||
} else {
|
||||
pushLimited(
|
||||
lines,
|
||||
snapshot.deviceAttempts.map(deviceAttemptLine),
|
||||
ONCE_SEND_LIMIT,
|
||||
"device attempts"
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -1249,6 +1406,18 @@ type SendDb = {
|
||||
sent_at: string;
|
||||
};
|
||||
|
||||
type DeviceAttemptDb = {
|
||||
user_id: string;
|
||||
device_id: string;
|
||||
platform: string | null;
|
||||
push_send_id: string | null;
|
||||
attempted_at: string;
|
||||
outcome: string;
|
||||
fcm_message_id: string | null;
|
||||
fcm_error_code: string | null;
|
||||
error_detail: string | null;
|
||||
};
|
||||
|
||||
function mapTestMode(value: number | null): boolean | null {
|
||||
if (value === null) return null;
|
||||
return value !== 0;
|
||||
@@ -1349,6 +1518,26 @@ export function loadSnapshot(
|
||||
sentAt: row.sent_at,
|
||||
}));
|
||||
|
||||
const deviceAttempts = (
|
||||
db
|
||||
.prepare(
|
||||
`SELECT user_id, device_id, platform, push_send_id, attempted_at,
|
||||
outcome, fcm_message_id, fcm_error_code, error_detail
|
||||
FROM alert_push_device_sends`
|
||||
)
|
||||
.all() as DeviceAttemptDb[]
|
||||
).map((row): DeviceAttemptInput => ({
|
||||
userId: row.user_id,
|
||||
deviceId: row.device_id,
|
||||
platform: row.platform,
|
||||
pushSendId: row.push_send_id,
|
||||
attemptedAt: row.attempted_at,
|
||||
outcome: row.outcome,
|
||||
fcmMessageId: row.fcm_message_id,
|
||||
fcmErrorCode: row.fcm_error_code,
|
||||
errorDetail: row.error_detail,
|
||||
}));
|
||||
|
||||
return buildSnapshot({
|
||||
dbPath: options.dbPath,
|
||||
now: options.now,
|
||||
@@ -1358,6 +1547,7 @@ export function loadSnapshot(
|
||||
jwts,
|
||||
cursors,
|
||||
sends,
|
||||
deviceAttempts,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1444,13 +1634,14 @@ function missingTableMessage(dbPath: string, missing: readonly string[]): string
|
||||
|
||||
// ---- interactive ----
|
||||
|
||||
type View = "dids" | "registrations" | "authorizations" | "sends";
|
||||
const VIEWS: View[] = ["dids", "registrations", "authorizations", "sends"];
|
||||
type View = "dids" | "registrations" | "authorizations" | "sends" | "attempts";
|
||||
const VIEWS: View[] = ["dids", "registrations", "authorizations", "sends", "attempts"];
|
||||
const VIEW_TITLES: Record<View, string> = {
|
||||
dids: "1 DIDs",
|
||||
registrations: "2 Registrations",
|
||||
authorizations: "3 Authorizations",
|
||||
sends: "4 Push sends",
|
||||
attempts: "5 Device attempts",
|
||||
};
|
||||
|
||||
const ESC = "\x1b[";
|
||||
@@ -1463,7 +1654,8 @@ function listLines(snapshot: Snapshot, view: View): string[] {
|
||||
.filter((did) => did.batchCount > 0 || did.orphanJwts.length > 0)
|
||||
.map(authorizationLine);
|
||||
}
|
||||
return snapshot.sends.map(sendLine);
|
||||
if (view === "sends") return snapshot.sends.map(sendLine);
|
||||
return snapshot.deviceAttempts.map(deviceAttemptLine);
|
||||
}
|
||||
|
||||
function subheader(snapshot: Snapshot, view: View): string {
|
||||
@@ -1473,7 +1665,9 @@ function subheader(snapshot: Snapshot, view: View): string {
|
||||
}
|
||||
if (view === "registrations") return `${findingsLine(snapshot)} ${STALE_LIMITATION}`;
|
||||
if (view === "authorizations") return AUTH_LIMITATION;
|
||||
return SEND_LIMITATION;
|
||||
if (view === "sends") return SEND_LIMITATION;
|
||||
const summary = snapshot.deviceAttemptSummary;
|
||||
return `Device attempts ${summary.total} accepted ${summary.succeeded} rejected ${summary.failed} most recent ${summary.mostRecentAt ?? "none"} ${DEVICE_ATTEMPT_LIMITATION}`;
|
||||
}
|
||||
|
||||
function interactive(
|
||||
@@ -1487,8 +1681,8 @@ function interactive(
|
||||
const state = {
|
||||
dbPath,
|
||||
view: "dids" as View,
|
||||
selected: { dids: 0, registrations: 0, authorizations: 0, sends: 0 },
|
||||
top: { dids: 0, registrations: 0, authorizations: 0, sends: 0 },
|
||||
selected: { dids: 0, registrations: 0, authorizations: 0, sends: 0, attempts: 0 },
|
||||
top: { dids: 0, registrations: 0, authorizations: 0, sends: 0, attempts: 0 },
|
||||
detail: undefined as string[] | undefined,
|
||||
detailTop: 0,
|
||||
status: focusDid === undefined ? "" : initial.focusFound ? `focus ${abbreviateMiddle(focusDid)}` : "focus DID not found",
|
||||
@@ -1551,7 +1745,7 @@ function interactive(
|
||||
screen += `${selected ? `${ESC}7m` : ""}${fit(line, width)}${selected ? `${ESC}0m` : ""}\n`;
|
||||
});
|
||||
screen += `${ESC}${height};1H${ESC}7m${fit(
|
||||
`${lines.length} rows 1/2/3/4 Tab view j/k move Enter details q quit ${state.status}`,
|
||||
`${lines.length} rows 1/2/3/4/5 Tab view j/k move Enter details q quit ${state.status}`,
|
||||
width
|
||||
)}${ESC}0m`;
|
||||
out(screen);
|
||||
@@ -1584,6 +1778,9 @@ function interactive(
|
||||
if (rows[index]) state.detail = authorizationDetail(rows[index], snap);
|
||||
}
|
||||
if (state.view === "sends" && snap.sends[index]) state.detail = sendDetail(snap.sends[index], snap);
|
||||
if (state.view === "attempts" && snap.deviceAttempts[index]) {
|
||||
state.detail = deviceAttemptDetail(snap.deviceAttempts[index]);
|
||||
}
|
||||
state.detailTop = 0;
|
||||
}
|
||||
|
||||
@@ -1604,7 +1801,9 @@ function interactive(
|
||||
}
|
||||
const view = state.view;
|
||||
if (key === "q") quit();
|
||||
else if (key === "1" || key === "2" || key === "3" || key === "4") state.view = VIEWS[Number(key) - 1];
|
||||
else if (key === "1" || key === "2" || key === "3" || key === "4" || key === "5") {
|
||||
state.view = VIEWS[Number(key) - 1];
|
||||
}
|
||||
else if (key === "\t") state.view = VIEWS[(VIEWS.indexOf(view) + 1) % VIEWS.length];
|
||||
else if (key === "j" || key === `${ESC}B`) state.selected[view] += 1;
|
||||
else if (key === "k" || key === `${ESC}A`) state.selected[view] = Math.max(0, state.selected[view] - 1);
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Shapes and cleanup for an FCM send result that we may store.
|
||||
* Firebase accepting a message is not proof the device displayed it.
|
||||
* Nothing here keeps a registration token, a JWT, or a notification body.
|
||||
*/
|
||||
|
||||
export const FCM_ERROR_DETAIL_MAX_CHARS = 200;
|
||||
export const FCM_ERROR_CODE_MAX_CHARS = 80;
|
||||
export const FCM_MESSAGE_ID_MAX_CHARS = 200;
|
||||
|
||||
/** Shorter strings are not distinctive enough to treat as a leaked token. */
|
||||
const MIN_SECRET_CHARS = 8;
|
||||
|
||||
export type FcmSendResult = {
|
||||
status: "sent" | "failed";
|
||||
/** Present when Firebase accepted the message and returned an id. */
|
||||
messageId?: string;
|
||||
/** Firebase error code, such as messaging/registration-token-not-registered. */
|
||||
errorCode?: string;
|
||||
/** Short sanitized description. Never a raw token or credential. */
|
||||
errorDetail?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Collapse whitespace and control characters, drop a known secret, and
|
||||
* truncate. An empty result means there is nothing useful to store.
|
||||
*/
|
||||
export function sanitizeFcmDiagnostic(
|
||||
value: string,
|
||||
secret?: string,
|
||||
maxChars: number = FCM_ERROR_DETAIL_MAX_CHARS
|
||||
): string {
|
||||
let text = value.replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim();
|
||||
if (secret !== undefined && secret.length >= MIN_SECRET_CHARS && text.includes(secret)) {
|
||||
text = text.split(secret).join("[redacted]");
|
||||
}
|
||||
if (text.length <= maxChars) return text;
|
||||
if (maxChars <= 1) return text.slice(0, maxChars);
|
||||
return `${text.slice(0, maxChars - 1)}…`;
|
||||
}
|
||||
|
||||
function optionalDiagnostic(value: string | undefined, secret: string | undefined, maxChars: number): string | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const text = sanitizeFcmDiagnostic(value, secret, maxChars);
|
||||
return text.length === 0 ? undefined : text;
|
||||
}
|
||||
|
||||
/** Error code and detail from a thrown FCM failure, with the token removed. */
|
||||
export function fcmFailureParts(
|
||||
err: unknown,
|
||||
token?: string
|
||||
): Pick<FcmSendResult, "errorCode" | "errorDetail"> {
|
||||
let code: string | undefined;
|
||||
if (typeof err === "object" && err !== null && "code" in err) {
|
||||
const value = (err as { code?: unknown }).code;
|
||||
if (typeof value === "string" && value.length > 0) code = value;
|
||||
}
|
||||
const message = err instanceof Error && err.message.length > 0
|
||||
? err.message
|
||||
: typeof err === "string" && err.length > 0
|
||||
? err
|
||||
: "Unknown error";
|
||||
return {
|
||||
errorCode: optionalDiagnostic(code, token, FCM_ERROR_CODE_MAX_CHARS),
|
||||
errorDetail: optionalDiagnostic(message, token, FCM_ERROR_DETAIL_MAX_CHARS),
|
||||
};
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, it } from "node:test";
|
||||
import { db as fcmDb } from "../../src/db/fcmTokensSqlite.js";
|
||||
import { closeDatabase } from "../../src/db/sqlite.js";
|
||||
import { closeDatabase, getDatabase } from "../../src/db/sqlite.js";
|
||||
import type { DailyAlertSearchResult } from "../../src/alertSearch/daily.js";
|
||||
import type { AlertSearchDigest } from "../../src/alertSearch/digest.js";
|
||||
import {
|
||||
@@ -363,3 +363,289 @@ describe("push daily cap", () => {
|
||||
});
|
||||
});
|
||||
|
||||
type DeviceSendRow = {
|
||||
user_id: string;
|
||||
device_id: string;
|
||||
platform: string | null;
|
||||
push_send_id: string | null;
|
||||
attempted_at: string;
|
||||
outcome: string;
|
||||
fcm_message_id: string | null;
|
||||
fcm_error_code: string | null;
|
||||
error_detail: string | null;
|
||||
};
|
||||
|
||||
type DidSendRow = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
batch_id: string | null;
|
||||
sent_at: string;
|
||||
};
|
||||
|
||||
function deviceSendRows(): DeviceSendRow[] {
|
||||
return getDatabase()
|
||||
.prepare(
|
||||
`SELECT user_id, device_id, platform, push_send_id, attempted_at,
|
||||
outcome, fcm_message_id, fcm_error_code, error_detail
|
||||
FROM alert_push_device_sends
|
||||
ORDER BY device_id`
|
||||
)
|
||||
.all() as DeviceSendRow[];
|
||||
}
|
||||
|
||||
function didSendRows(): DidSendRow[] {
|
||||
return getDatabase()
|
||||
.prepare(`SELECT id, user_id, batch_id, sent_at FROM alert_push_sends ORDER BY sent_at`)
|
||||
.all() as DidSendRow[];
|
||||
}
|
||||
|
||||
describe("per-device FCM outcome log", () => {
|
||||
let dir: string;
|
||||
let previousDataDir: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
previousDataDir = process.env.NOTIFY_DATA_DIR;
|
||||
dir = await mkdtemp(path.join(tmpdir(), "alert-search-device-log-"));
|
||||
process.env.NOTIFY_DATA_DIR = dir;
|
||||
closeDatabase();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
closeDatabase();
|
||||
if (previousDataDir === undefined) delete process.env.NOTIFY_DATA_DIR;
|
||||
else process.env.NOTIFY_DATA_DIR = previousDataDir;
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function register(deviceId: string, fcmToken: string, platform: string): Promise<void> {
|
||||
await fcmDb.upsert({
|
||||
userId: USER,
|
||||
deviceId,
|
||||
fcmToken,
|
||||
platform,
|
||||
updatedAt: new Date("2026-09-08T08:00:00.000Z"),
|
||||
});
|
||||
}
|
||||
|
||||
it("records one accepted device and links it to the single DID-level row", async () => {
|
||||
await register("phone-ok", "token-ok", "ios");
|
||||
const now = new Date("2026-09-08T09:00:00.000Z");
|
||||
const result = await deliverAlertSearchNotification(daily(), {
|
||||
now,
|
||||
send: async () => ({ status: "sent", messageId: "projects/app/messages/msg-ok" }),
|
||||
});
|
||||
assert.equal(result.sent, 1);
|
||||
assert.equal(result.failed, 0);
|
||||
const dids = didSendRows();
|
||||
const devices = deviceSendRows();
|
||||
assert.equal(dids.length, 1);
|
||||
assert.equal(dids[0].user_id, USER);
|
||||
assert.equal(dids[0].batch_id, "batch-1");
|
||||
assert.equal(dids[0].sent_at, now.toISOString());
|
||||
assert.equal(await alertPushSendsDb.countSince(USER, "2026-09-08T00:00:00.000Z"), 1);
|
||||
assert.equal(devices.length, 1);
|
||||
assert.equal(devices[0].device_id, "phone-ok");
|
||||
assert.equal(devices[0].platform, "ios");
|
||||
assert.equal(devices[0].outcome, "sent");
|
||||
assert.equal(devices[0].fcm_message_id, "projects/app/messages/msg-ok");
|
||||
assert.equal(devices[0].fcm_error_code, null);
|
||||
assert.equal(devices[0].error_detail, null);
|
||||
assert.equal(devices[0].push_send_id, dids[0].id);
|
||||
assert.equal(devices[0].attempted_at, now.toISOString());
|
||||
});
|
||||
|
||||
it("records one rejection and does not write a DID-level cap row", async () => {
|
||||
await register("phone-bad", "token-bad", "android");
|
||||
const result = await deliverAlertSearchNotification(daily(), {
|
||||
now: new Date("2026-09-08T09:00:00.000Z"),
|
||||
send: async () => ({
|
||||
status: "failed",
|
||||
errorCode: "messaging/registration-token-not-registered",
|
||||
errorDetail: "token-bad is not registered",
|
||||
}),
|
||||
});
|
||||
assert.equal(result.sent, 0);
|
||||
assert.equal(result.failed, 1);
|
||||
assert.equal(didSendRows().length, 0);
|
||||
assert.equal(await alertPushSendsDb.countSince(USER, "2026-09-08T00:00:00.000Z"), 0);
|
||||
const devices = deviceSendRows();
|
||||
assert.equal(devices.length, 1);
|
||||
assert.equal(devices[0].outcome, "failed");
|
||||
assert.equal(devices[0].push_send_id, null);
|
||||
assert.equal(devices[0].fcm_message_id, null);
|
||||
assert.equal(devices[0].fcm_error_code, "messaging/registration-token-not-registered");
|
||||
assert.equal(devices[0].error_detail?.includes("token-bad"), false);
|
||||
assert.match(devices[0].error_detail ?? "", /\[redacted\]/);
|
||||
});
|
||||
|
||||
it("maps mixed FCM results onto the devices that were sent, and leaves the rest out", async () => {
|
||||
await register("phone-a", "token-aaaa-1111", "ios");
|
||||
await register("phone-b", "token-bbbb-2222", "android");
|
||||
await register("phone-c", "token-cccc-3333", "web");
|
||||
const calls: string[] = [];
|
||||
const result = await deliverAlertSearchNotification(daily(), {
|
||||
now: new Date("2026-09-08T09:00:00.000Z"),
|
||||
listTokens: async () => ["token-bbbb-2222", "token-aaaa-1111"],
|
||||
send: async (token) => {
|
||||
calls.push(token);
|
||||
if (token === "token-aaaa-1111") return { status: "sent" as const, messageId: "msg-for-a" };
|
||||
if (token === "token-bbbb-2222") {
|
||||
return {
|
||||
status: "failed" as const,
|
||||
errorCode: "messaging/invalid-argument",
|
||||
errorDetail: "nope token-bbbb-2222",
|
||||
messageId: "not-a-success-id",
|
||||
};
|
||||
}
|
||||
throw new Error(`unexpected ${token}`);
|
||||
},
|
||||
});
|
||||
assert.deepEqual(calls, ["token-bbbb-2222", "token-aaaa-1111"]);
|
||||
assert.equal(result.sent, 1);
|
||||
assert.equal(result.failed, 1);
|
||||
const dids = didSendRows();
|
||||
assert.equal(dids.length, 1);
|
||||
assert.equal(await alertPushSendsDb.countSince(USER, "2026-09-08T00:00:00.000Z"), 1);
|
||||
const devices = deviceSendRows();
|
||||
assert.deepEqual(devices.map((row) => row.device_id), ["phone-a", "phone-b"]);
|
||||
const accepted = devices.find((row) => row.device_id === "phone-a");
|
||||
const rejected = devices.find((row) => row.device_id === "phone-b");
|
||||
assert.ok(accepted && rejected);
|
||||
assert.equal(accepted.outcome, "sent");
|
||||
assert.equal(accepted.platform, "ios");
|
||||
assert.equal(accepted.fcm_message_id, "msg-for-a");
|
||||
assert.equal(accepted.fcm_error_code, null);
|
||||
assert.equal(accepted.push_send_id, dids[0].id);
|
||||
assert.equal(rejected.outcome, "failed");
|
||||
assert.equal(rejected.platform, "android");
|
||||
assert.equal(rejected.fcm_message_id, null);
|
||||
assert.equal(rejected.fcm_error_code, "messaging/invalid-argument");
|
||||
assert.equal(rejected.error_detail?.includes("token-bbbb-2222"), false);
|
||||
assert.equal(rejected.push_send_id, dids[0].id);
|
||||
|
||||
const capped = await deliverAlertSearchNotification(daily(), {
|
||||
now: new Date("2026-09-08T10:00:00.000Z"),
|
||||
listTokens: async () => ["token-aaaa-1111", "token-bbbb-2222", "token-cccc-3333"],
|
||||
send: async () => {
|
||||
throw new Error("cap should have stopped the send");
|
||||
},
|
||||
});
|
||||
assert.equal(capped.sent, 0);
|
||||
assert.equal(capped.capped, true);
|
||||
assert.equal(didSendRows().length, 1);
|
||||
assert.equal(deviceSendRows().length, 2);
|
||||
assert.equal(await alertPushSendsDb.countSince(USER, "2026-09-08T00:00:00.000Z"), 1);
|
||||
});
|
||||
|
||||
it("logs the registration that owns a duplicated token and not the other row", async () => {
|
||||
const nowIso = "2026-09-08T08:00:00.000Z";
|
||||
const token = "shared-token-value";
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO fcm_registrations (
|
||||
id, user_id, device_id, fcm_token, platform, test_mode, created_at, updated_at, last_notified_at
|
||||
) VALUES (?, ?, ?, ?, ?, NULL, ?, ?, NULL)`
|
||||
)
|
||||
.run("reg-first", USER, "device-first", token, "ios", nowIso, nowIso);
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO fcm_registrations (
|
||||
id, user_id, device_id, fcm_token, platform, test_mode, created_at, updated_at, last_notified_at
|
||||
) VALUES (?, ?, ?, ?, ?, NULL, ?, ?, NULL)`
|
||||
)
|
||||
.run("reg-second", USER, "device-second", token, "android", nowIso, nowIso);
|
||||
const first = (await fcmDb.getByUserId(USER))[0];
|
||||
assert.ok(first);
|
||||
const sent: string[] = [];
|
||||
const result = await deliverAlertSearchNotification(daily(), {
|
||||
now: new Date("2026-09-08T09:00:00.000Z"),
|
||||
send: async (value) => {
|
||||
sent.push(value);
|
||||
return { status: "sent", messageId: "msg-shared" };
|
||||
},
|
||||
});
|
||||
assert.equal(result.sent, 1);
|
||||
assert.equal(result.failed, 0);
|
||||
assert.deepEqual(sent, [token]);
|
||||
const devices = deviceSendRows();
|
||||
assert.equal(devices.length, 1);
|
||||
assert.equal(devices[0].device_id, first.deviceId);
|
||||
assert.equal(devices[0].platform, first.platform);
|
||||
assert.equal(didSendRows().length, 1);
|
||||
});
|
||||
|
||||
it("stores nulls when the FCM result omits the message id and error fields", async () => {
|
||||
await register("phone-ok", "token-ok", "ios");
|
||||
await register("phone-bad", "token-bad", "web");
|
||||
const result = await deliverAlertSearchNotification(daily(), {
|
||||
now: new Date("2026-09-08T09:00:00.000Z"),
|
||||
send: async (token) => (token === "token-ok" ? { status: "sent" } : { status: "failed" }),
|
||||
});
|
||||
assert.equal(result.sent, 1);
|
||||
assert.equal(result.failed, 1);
|
||||
const devices = deviceSendRows();
|
||||
const accepted = devices.find((row) => row.device_id === "phone-ok");
|
||||
const rejected = devices.find((row) => row.device_id === "phone-bad");
|
||||
assert.ok(accepted && rejected);
|
||||
assert.equal(accepted.fcm_message_id, null);
|
||||
assert.equal(accepted.fcm_error_code, null);
|
||||
assert.equal(accepted.error_detail, null);
|
||||
assert.equal(rejected.fcm_message_id, null);
|
||||
assert.equal(rejected.fcm_error_code, null);
|
||||
assert.equal(rejected.error_detail, null);
|
||||
});
|
||||
|
||||
it("truncates a thrown error and does not persist the token", async () => {
|
||||
await register("phone-bad", "token-secret-value", "ios");
|
||||
const result = await deliverAlertSearchNotification(daily(), {
|
||||
now: new Date("2026-09-08T09:00:00.000Z"),
|
||||
send: async () => {
|
||||
throw new Error(`boom token-secret-value ${"z".repeat(400)}`);
|
||||
},
|
||||
});
|
||||
assert.equal(result.sent, 0);
|
||||
assert.equal(result.failed, 1);
|
||||
assert.equal(didSendRows().length, 0);
|
||||
const devices = deviceSendRows();
|
||||
assert.equal(devices.length, 1);
|
||||
assert.equal(devices[0].outcome, "failed");
|
||||
assert.equal(devices[0].error_detail?.includes("token-secret-value"), false);
|
||||
assert.match(devices[0].error_detail ?? "", /\[redacted\]/);
|
||||
assert.equal(devices[0].error_detail?.length, 200);
|
||||
});
|
||||
|
||||
it("keeps a successful send when the diagnostic write fails and does not resend", async () => {
|
||||
await register("phone-ok", "token-ok", "ios");
|
||||
let sends = 0;
|
||||
const result = await deliverAlertSearchNotification(daily(), {
|
||||
now: new Date("2026-09-08T09:00:00.000Z"),
|
||||
send: async () => {
|
||||
sends += 1;
|
||||
return { status: "sent", messageId: "msg-kept" };
|
||||
},
|
||||
recordDeviceAttempts: async () => {
|
||||
throw new Error("disk full");
|
||||
},
|
||||
});
|
||||
assert.equal(result.eligible, true);
|
||||
assert.equal(result.sent, 1);
|
||||
assert.equal(result.failed, 0);
|
||||
assert.equal(sends, 1);
|
||||
assert.equal(didSendRows().length, 1);
|
||||
assert.equal(await alertPushSendsDb.countSince(USER, "2026-09-08T00:00:00.000Z"), 1);
|
||||
assert.equal(deviceSendRows().length, 0);
|
||||
});
|
||||
|
||||
it("does not log a token that has no registration", async () => {
|
||||
const result = await deliverAlertSearchNotification(daily(), {
|
||||
now: new Date("2026-09-08T09:00:00.000Z"),
|
||||
listTokens: async () => ["unregistered-token"],
|
||||
send: async () => "sent",
|
||||
});
|
||||
assert.equal(result.sent, 1);
|
||||
assert.equal(result.failed, 0);
|
||||
assert.equal(didSendRows().length, 1);
|
||||
assert.equal(deviceSendRows().length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, it } from "node:test";
|
||||
import { alertPushDeviceSendsDb } from "../../src/db/alertPushDeviceSendsSqlite.js";
|
||||
import { ALERT_PUSH_SEND_RETENTION_DAYS } from "../../src/db/alertPushSendsSqlite.js";
|
||||
import { closeDatabase, getDatabase } from "../../src/db/sqlite.js";
|
||||
|
||||
describe("alert_push_device_sends", () => {
|
||||
let dir: string;
|
||||
let previousDataDir: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
previousDataDir = process.env.NOTIFY_DATA_DIR;
|
||||
dir = await mkdtemp(path.join(tmpdir(), "alert-push-device-sends-"));
|
||||
process.env.NOTIFY_DATA_DIR = dir;
|
||||
closeDatabase();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
closeDatabase();
|
||||
if (previousDataDir === undefined) delete process.env.NOTIFY_DATA_DIR;
|
||||
else process.env.NOTIFY_DATA_DIR = previousDataDir;
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("creates the table and the lookup indexes", () => {
|
||||
const db = getDatabase();
|
||||
const columns = db.prepare(`PRAGMA table_info(alert_push_device_sends)`).all() as { name: string }[];
|
||||
assert.deepEqual(
|
||||
columns.map((column) => column.name),
|
||||
[
|
||||
"id",
|
||||
"user_id",
|
||||
"device_id",
|
||||
"platform",
|
||||
"push_send_id",
|
||||
"attempted_at",
|
||||
"outcome",
|
||||
"fcm_message_id",
|
||||
"fcm_error_code",
|
||||
"error_detail",
|
||||
]
|
||||
);
|
||||
assert.equal(columns.some((column) => column.name === "fcm_token"), false);
|
||||
|
||||
const indexes = db.prepare(`PRAGMA index_list(alert_push_device_sends)`).all() as { name: string }[];
|
||||
const names = indexes.map((index) => index.name);
|
||||
assert.equal(names.includes("idx_alert_push_device_sends_user_attempted"), true);
|
||||
assert.equal(names.includes("idx_alert_push_device_sends_device_attempted"), true);
|
||||
const userIndex = db
|
||||
.prepare(`PRAGMA index_info(idx_alert_push_device_sends_user_attempted)`)
|
||||
.all() as { name: string }[];
|
||||
const deviceIndex = db
|
||||
.prepare(`PRAGMA index_info(idx_alert_push_device_sends_device_attempted)`)
|
||||
.all() as { name: string }[];
|
||||
assert.deepEqual(
|
||||
userIndex.map((column) => column.name),
|
||||
["user_id", "attempted_at"]
|
||||
);
|
||||
assert.deepEqual(
|
||||
deviceIndex.map((column) => column.name),
|
||||
["device_id", "attempted_at"]
|
||||
);
|
||||
|
||||
const capColumns = db.prepare(`PRAGMA table_info(alert_push_sends)`).all() as { name: string }[];
|
||||
assert.deepEqual(
|
||||
capColumns.map((column) => column.name),
|
||||
["id", "user_id", "batch_id", "sent_at"]
|
||||
);
|
||||
});
|
||||
|
||||
it("stores one success and one failure and truncates a long error", async () => {
|
||||
const longDetail = "e".repeat(500);
|
||||
await alertPushDeviceSendsDb.appendMany([
|
||||
{
|
||||
userId: "did:example:one",
|
||||
deviceId: "phone-ok",
|
||||
platform: "ios",
|
||||
pushSendId: "send-1",
|
||||
attemptedAt: "2026-11-13T14:00:00.000Z",
|
||||
outcome: "sent",
|
||||
fcmMessageId: "projects/app/messages/msg-1",
|
||||
fcmErrorCode: "should-not-stick",
|
||||
errorDetail: "should-not-stick",
|
||||
},
|
||||
{
|
||||
userId: "did:example:one",
|
||||
deviceId: "phone-bad",
|
||||
platform: "android",
|
||||
pushSendId: null,
|
||||
attemptedAt: "2026-11-13T14:00:00.000Z",
|
||||
outcome: "failed",
|
||||
fcmMessageId: "should-not-stick",
|
||||
fcmErrorCode: null,
|
||||
errorDetail: longDetail,
|
||||
},
|
||||
]);
|
||||
const rows = getDatabase()
|
||||
.prepare(
|
||||
`SELECT device_id, platform, push_send_id, outcome, fcm_message_id, fcm_error_code, error_detail
|
||||
FROM alert_push_device_sends ORDER BY device_id`
|
||||
)
|
||||
.all() as {
|
||||
device_id: string;
|
||||
platform: string | null;
|
||||
push_send_id: string | null;
|
||||
outcome: string;
|
||||
fcm_message_id: string | null;
|
||||
fcm_error_code: string | null;
|
||||
error_detail: string | null;
|
||||
}[];
|
||||
assert.equal(rows.length, 2);
|
||||
assert.equal(rows[0].device_id, "phone-bad");
|
||||
assert.equal(rows[0].outcome, "failed");
|
||||
assert.equal(rows[0].fcm_message_id, null);
|
||||
assert.equal(rows[0].fcm_error_code, null);
|
||||
assert.equal(rows[0].error_detail?.length, 200);
|
||||
assert.equal(rows[0].error_detail?.endsWith("…"), true);
|
||||
assert.equal(rows[1].device_id, "phone-ok");
|
||||
assert.equal(rows[1].platform, "ios");
|
||||
assert.equal(rows[1].push_send_id, "send-1");
|
||||
assert.equal(rows[1].outcome, "sent");
|
||||
assert.equal(rows[1].fcm_message_id, "projects/app/messages/msg-1");
|
||||
assert.equal(rows[1].fcm_error_code, null);
|
||||
assert.equal(rows[1].error_detail, null);
|
||||
const capRows = getDatabase().prepare(`SELECT COUNT(*) AS n FROM alert_push_sends`).get() as { n: number };
|
||||
assert.equal(capRows.n, 0);
|
||||
});
|
||||
|
||||
it("drops this identity's device rows past the retention window", async () => {
|
||||
const recent = "2026-11-13T14:00:00.000Z";
|
||||
const stale = new Date(
|
||||
Date.parse(recent) - (ALERT_PUSH_SEND_RETENTION_DAYS + 1) * 24 * 60 * 60 * 1000
|
||||
).toISOString();
|
||||
await alertPushDeviceSendsDb.appendMany([
|
||||
{
|
||||
userId: "did:example:old",
|
||||
deviceId: "old-phone",
|
||||
platform: "ios",
|
||||
pushSendId: null,
|
||||
attemptedAt: stale,
|
||||
outcome: "failed",
|
||||
fcmMessageId: null,
|
||||
fcmErrorCode: "messaging/internal-error",
|
||||
errorDetail: "old",
|
||||
},
|
||||
]);
|
||||
await alertPushDeviceSendsDb.appendMany([
|
||||
{
|
||||
userId: "did:example:old",
|
||||
deviceId: "new-phone",
|
||||
platform: "ios",
|
||||
pushSendId: null,
|
||||
attemptedAt: recent,
|
||||
outcome: "sent",
|
||||
fcmMessageId: "msg-new",
|
||||
fcmErrorCode: null,
|
||||
errorDetail: null,
|
||||
},
|
||||
]);
|
||||
const rows = getDatabase()
|
||||
.prepare(`SELECT device_id FROM alert_push_device_sends WHERE user_id = ?`)
|
||||
.all("did:example:old") as { device_id: string }[];
|
||||
assert.deepEqual(rows.map((row) => row.device_id), ["new-phone"]);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import Database from "better-sqlite3";
|
||||
import {
|
||||
type BatchInput,
|
||||
type BuildInput,
|
||||
type DeviceAttemptInput,
|
||||
type JwtInput,
|
||||
type RegistrationInput,
|
||||
STALE_REGISTRATION_MS,
|
||||
@@ -29,6 +30,7 @@ import {
|
||||
maskFcmToken,
|
||||
pickLatestBatch,
|
||||
selectStatusJwt,
|
||||
summarizeDeviceAttempts,
|
||||
utcCalendarDay,
|
||||
} from "../../src/tools/pushWatch.js";
|
||||
|
||||
@@ -317,6 +319,7 @@ describe("per-DID aggregation", () => {
|
||||
{ userId: "did:example:edges", batchId: null, sentAt: at(1) },
|
||||
{ userId: "did:example:edges", batchId: null, sentAt: "not-a-timestamp" },
|
||||
],
|
||||
deviceAttempts: [],
|
||||
});
|
||||
const did = snapshot.dids.find((row) => row.did === "did:example:edges");
|
||||
assert.ok(did);
|
||||
@@ -329,6 +332,74 @@ describe("per-DID aggregation", () => {
|
||||
assert.equal(snapshot.sendSummary.total, 5);
|
||||
});
|
||||
|
||||
it("summarizes per-device attempts without treating a future row as the latest", () => {
|
||||
const attempts: DeviceAttemptInput[] = [
|
||||
{
|
||||
userId: "did:example:only-attempts",
|
||||
deviceId: "phone-a",
|
||||
platform: "ios",
|
||||
pushSendId: "send-1",
|
||||
attemptedAt: "2026-11-13T14:00:00.000Z",
|
||||
outcome: "sent",
|
||||
fcmMessageId: "projects/app/messages/msg-1",
|
||||
fcmErrorCode: null,
|
||||
errorDetail: null,
|
||||
},
|
||||
{
|
||||
userId: "did:example:only-attempts",
|
||||
deviceId: "phone-b",
|
||||
platform: "android",
|
||||
pushSendId: null,
|
||||
attemptedAt: "2026-11-13T16:00:00.000Z",
|
||||
outcome: "failed",
|
||||
fcmMessageId: null,
|
||||
fcmErrorCode: "messaging/invalid-argument",
|
||||
errorDetail: "registration rejected",
|
||||
},
|
||||
];
|
||||
const summary = summarizeDeviceAttempts(attempts, NOW);
|
||||
assert.equal(summary.total, 2);
|
||||
assert.equal(summary.succeeded, 1);
|
||||
assert.equal(summary.failed, 1);
|
||||
assert.equal(summary.mostRecentAt, "2026-11-13T14:00:00.000Z");
|
||||
|
||||
const added = buildSnapshot({ ...fixture(), deviceAttempts: attempts });
|
||||
assert.equal(added.summary.uniqueDids, 11);
|
||||
assert.equal(added.deviceAttemptSummary.total, 2);
|
||||
|
||||
const text = formatOnce(
|
||||
buildSnapshot({
|
||||
dbPath: "/tmp/push-watch-attempts.sqlite",
|
||||
now: NOW,
|
||||
focusDid: "did:example:only-attempts",
|
||||
registrations: [],
|
||||
batches: [],
|
||||
jwts: [],
|
||||
cursors: [],
|
||||
sends: [],
|
||||
deviceAttempts: attempts,
|
||||
})
|
||||
);
|
||||
assert.match(text, /== Device attempts ==/);
|
||||
assert.match(text, /Device attempts: 2/);
|
||||
assert.match(text, /Device attempts accepted by FCM: 1/);
|
||||
assert.match(text, /Device attempts rejected by FCM: 1/);
|
||||
assert.match(text, /Most recent device attempt: 2026-11-13T14:00:00.000Z/);
|
||||
assert.match(text, /phone-a/);
|
||||
assert.match(text, /phone-b/);
|
||||
assert.match(text, /projects\/app\/messages\/msg-1/);
|
||||
assert.match(text, /messaging\/invalid-argument/);
|
||||
assert.match(text, /registration rejected/);
|
||||
assert.match(text, /== Push sends ==/);
|
||||
assert.match(text, /alert_push_sends is a DID-level record/);
|
||||
assert.equal(text.includes("raw-token"), false);
|
||||
|
||||
const empty = formatOnce(buildSnapshot({ ...fixture(), focusDid: "did:example:reg" }));
|
||||
assert.match(empty, /Device attempts: 0/);
|
||||
assert.match(empty, /Most recent device attempt: none/);
|
||||
assert.match(empty, /== Device attempts ==[\s\S]*\(none\)/);
|
||||
});
|
||||
|
||||
it("focuses one DID without turning a missing authorization into expired", () => {
|
||||
const reg = buildSnapshot({ ...fixture(), focusDid: "did:example:reg" });
|
||||
const text = formatOnce(reg);
|
||||
@@ -564,6 +635,81 @@ describe("push:watch CLI", () => {
|
||||
assert.match(result.stderr, /initialize the schema/);
|
||||
assert.equal(logicalDump(partial), before);
|
||||
});
|
||||
|
||||
it("names a database that has not gained the per-device send table", () => {
|
||||
const dbPath = createDatabase(() => {});
|
||||
const db = new Database(dbPath);
|
||||
db.exec("DROP TABLE alert_push_device_sends");
|
||||
db.close();
|
||||
const before = logicalDump(dbPath);
|
||||
const result = run(["--once", "--db", dbPath]);
|
||||
assert.equal(result.status, 1);
|
||||
assert.match(result.stderr, /alert_push_device_sends/);
|
||||
assert.match(result.stderr, /initialize the schema/);
|
||||
assert.equal(logicalDump(dbPath), before);
|
||||
});
|
||||
|
||||
it("prints per-device FCM outcomes without writing or showing the token", () => {
|
||||
const secret = "raw-fcm-token-should-stay-out";
|
||||
const dbPath = createDatabase((db) => {
|
||||
insertRegistration(db, {
|
||||
userId: "did:example:device",
|
||||
deviceId: "phone-1",
|
||||
fcmToken: secret,
|
||||
platform: "ios",
|
||||
});
|
||||
db.prepare(
|
||||
`INSERT INTO alert_push_sends (id, user_id, batch_id, sent_at)
|
||||
VALUES ('send-1', 'did:example:device', 'batch-1', ?)`
|
||||
).run(NOW.toISOString());
|
||||
const insert = db.prepare(
|
||||
`INSERT INTO alert_push_device_sends (
|
||||
id, user_id, device_id, platform, push_send_id, attempted_at,
|
||||
outcome, fcm_message_id, fcm_error_code, error_detail
|
||||
) VALUES (?, 'did:example:device', ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
);
|
||||
insert.run(
|
||||
"a1",
|
||||
"phone-1",
|
||||
"ios",
|
||||
"send-1",
|
||||
"2026-11-12T14:00:00.000Z",
|
||||
"sent",
|
||||
"projects/app/messages/msg-1",
|
||||
null,
|
||||
null
|
||||
);
|
||||
insert.run(
|
||||
"a2",
|
||||
"phone-2",
|
||||
"android",
|
||||
null,
|
||||
"2026-11-12T13:00:00.000Z",
|
||||
"failed",
|
||||
null,
|
||||
"messaging/registration-token-not-registered",
|
||||
"registration rejected"
|
||||
);
|
||||
});
|
||||
const before = logicalDump(dbPath);
|
||||
const hash = hashFile(dbPath);
|
||||
const result = run(["--once", "--db", dbPath, "--did", "did:example:device"]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /== Device attempts ==/);
|
||||
assert.match(result.stdout, /Device attempts: 2/);
|
||||
assert.match(result.stdout, /Device attempts accepted by FCM: 1/);
|
||||
assert.match(result.stdout, /Device attempts rejected by FCM: 1/);
|
||||
assert.match(result.stdout, /Most recent device attempt: 2026-11-12T14:00:00.000Z/);
|
||||
assert.match(result.stdout, /phone-1/);
|
||||
assert.match(result.stdout, /phone-2/);
|
||||
assert.match(result.stdout, /projects\/app\/messages\/msg-1/);
|
||||
assert.match(result.stdout, /messaging\/registration-token-not-registered/);
|
||||
assert.match(result.stdout, /registration rejected/);
|
||||
assert.match(result.stdout, /alert_push_sends is a DID-level record/);
|
||||
assert.equal(result.stdout.includes(secret), false);
|
||||
assert.equal(logicalDump(dbPath), before);
|
||||
assert.equal(hashFile(dbPath), hash);
|
||||
});
|
||||
});
|
||||
|
||||
const SCHEMA = `
|
||||
@@ -616,6 +762,18 @@ CREATE TABLE alert_push_sends (
|
||||
batch_id TEXT,
|
||||
sent_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE alert_push_device_sends (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
device_id TEXT NOT NULL,
|
||||
platform TEXT,
|
||||
push_send_id TEXT,
|
||||
attempted_at TEXT NOT NULL,
|
||||
outcome TEXT NOT NULL,
|
||||
fcm_message_id TEXT,
|
||||
fcm_error_code TEXT,
|
||||
error_detail TEXT
|
||||
);
|
||||
`;
|
||||
|
||||
function registration(partial: Partial<RegistrationInput> & Pick<RegistrationInput, "userId">): RegistrationInput {
|
||||
@@ -783,6 +941,7 @@ function fixture(): BuildInput {
|
||||
}),
|
||||
],
|
||||
sends,
|
||||
deviceAttempts: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import {
|
||||
FCM_ERROR_CODE_MAX_CHARS,
|
||||
FCM_ERROR_DETAIL_MAX_CHARS,
|
||||
fcmFailureParts,
|
||||
sanitizeFcmDiagnostic,
|
||||
} from "../../src/util/fcmOutcome.js";
|
||||
|
||||
const TOKEN = "fcm-token-abcdefghij";
|
||||
|
||||
describe("FCM diagnostic text", () => {
|
||||
it("removes a registration token and collapses control characters", () => {
|
||||
const text = sanitizeFcmDiagnostic(`bad\n\t${TOKEN}\r twice ${TOKEN}`, TOKEN);
|
||||
assert.equal(text.includes(TOKEN), false);
|
||||
assert.equal(text, "bad [redacted] twice [redacted]");
|
||||
});
|
||||
|
||||
it("truncates a long description", () => {
|
||||
const text = sanitizeFcmDiagnostic("x".repeat(FCM_ERROR_DETAIL_MAX_CHARS + 40));
|
||||
assert.equal(text.length, FCM_ERROR_DETAIL_MAX_CHARS);
|
||||
assert.equal(text.endsWith("…"), true);
|
||||
assert.equal(text.startsWith("x"), true);
|
||||
});
|
||||
|
||||
it("keeps a short error code and drops an empty message", () => {
|
||||
const err = new Error(" ");
|
||||
(err as { code?: string }).code = "messaging/invalid-argument";
|
||||
const parts = fcmFailureParts(err);
|
||||
assert.equal(parts.errorCode, "messaging/invalid-argument");
|
||||
assert.equal(parts.errorDetail, undefined);
|
||||
});
|
||||
|
||||
it("omits a missing error code and strips the token from the message", () => {
|
||||
const err = new Error(`rejected ${TOKEN} now`);
|
||||
const parts = fcmFailureParts(err, TOKEN);
|
||||
assert.equal(parts.errorCode, undefined);
|
||||
assert.equal(parts.errorDetail, "rejected [redacted] now");
|
||||
assert.equal(parts.errorDetail?.includes(TOKEN), false);
|
||||
});
|
||||
|
||||
it("truncates an oversized error code", () => {
|
||||
const err = new Error("no");
|
||||
(err as { code?: string }).code = "c".repeat(FCM_ERROR_CODE_MAX_CHARS + 10);
|
||||
const parts = fcmFailureParts(err);
|
||||
assert.equal(parts.errorCode?.length, FCM_ERROR_CODE_MAX_CHARS);
|
||||
assert.equal(parts.errorCode?.endsWith("…"), true);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user