From e7fa667376be2acd299737fa48e77d8329675415 Mon Sep 17 00:00:00 2001 From: Will McLemore Date: Wed, 25 Nov 2026 09:08:56 -0600 Subject: [PATCH] perf(gmail): improve API efficiency, atomic labels, audit accuracy, and HTTP retry resilience --- src/drafts-audit.ts | 8 +- src/gmail-service.ts | 299 +++++++++++++++++-------- test/drafts-audit.test.js | 240 ++++++++++++++++++++ test/gmail-service-perf.test.js | 385 ++++++++++++++++++++++++++++++++ 4 files changed, 840 insertions(+), 92 deletions(-) create mode 100644 test/gmail-service-perf.test.js diff --git a/src/drafts-audit.ts b/src/drafts-audit.ts index 1d3c5ed..29b0181 100644 --- a/src/drafts-audit.ts +++ b/src/drafts-audit.ts @@ -129,8 +129,10 @@ export function hasOverlappingRecipients(a: Mailbox[], b: Mailbox[]): boolean { return false; } +const MAX_SENT_SEARCH_RECIPIENTS = 5; + export function buildSentSearchQuery(normalizedSubject: string, recipients: Mailbox[]): string | null { - const emails = extractEmailAddresses(recipients); + const emails = extractEmailAddresses(recipients).slice(0, MAX_SENT_SEARCH_RECIPIENTS); const cleanSubject = normalizedSubject.replace(/"/g, " ").replace(/\s+/g, " ").trim(); if (!cleanSubject && emails.length === 0) return null; @@ -138,8 +140,10 @@ export function buildSentSearchQuery(normalizedSubject: string, recipients: Mail if (cleanSubject) { parts.push(`subject:"${cleanSubject}"`); } - if (emails.length > 0) { + if (emails.length === 1) { parts.push(`to:${emails[0]}`); + } else if (emails.length > 1) { + parts.push(`(${emails.map((email) => `to:${email}`).join(" OR ")})`); } return parts.join(" "); } diff --git a/src/gmail-service.ts b/src/gmail-service.ts index 3d3fdcf..6e3b328 100644 --- a/src/gmail-service.ts +++ b/src/gmail-service.ts @@ -149,6 +149,69 @@ export function canonicalReplySubject(requestedSubject: string, sourceSubject: s } export const MAX_TOTAL_ATTACHMENT_BYTES = 25 * 1024 * 1024; +export const DEFAULT_HTTP_TIMEOUT_MS = 30_000; +export const DEFAULT_CONCURRENCY = 5; +export const METADATA_HEADERS = ["From", "To", "Cc", "Subject", "Date"]; + +export const GMAIL_CLIENT_RETRY_CONFIG = { + retry: 3, + retryDelay: 250, + retryDelayMultiplier: 2, + maxRetryDelay: 10_000, + noResponseRetries: 2, + // Only retry idempotent HTTP methods; never auto-retry POST (sends/draft creates) + // so transient errors cannot produce duplicate outbound emails. + httpMethodsToRetry: ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"], + statusCodesToRetry: [ + [429, 429], + [500, 599], + ], +}; + +export async function mapWithConcurrency( + items: readonly T[], + concurrency: number, + worker: (item: T, index: number) => Promise, +): Promise { + if (items.length === 0) return []; + const limit = Math.max(1, Math.min(Math.floor(concurrency), items.length)); + const results = new Array(items.length); + let nextIndex = 0; + let failed = false; + + const runWorker = async (): Promise => { + while (!failed) { + const currentIndex = nextIndex++; + if (currentIndex >= items.length) return; + try { + results[currentIndex] = await worker(items[currentIndex], currentIndex); + } catch (err) { + failed = true; + throw err; + } + } + }; + + await Promise.all(Array.from({ length: limit }, () => runWorker())); + return results; +} + +export function isGmailNotFoundError(error: unknown): boolean { + if (!error || typeof error !== "object") return false; + const err = error as { + code?: unknown; + status?: unknown; + response?: { status?: unknown; data?: { error?: { code?: unknown } } }; + }; + return ( + err.code === 404 || + err.code === "404" || + err.status === 404 || + err.response?.status === 404 || + err.response?.data?.error?.code === 404 + ); +} + const MIME_ENCODED_WORD_PREFIX = "=?UTF-8?B?"; const MIME_ENCODED_WORD_SUFFIX = "?="; // 39 raw UTF-8 bytes => 52 base64 chars => 64-char encoded-word (<= 75 per RFC 2047, @@ -441,13 +504,30 @@ export class GmailService { ); } - const oauth2Client = new OAuth2Client(clientId, clientSecret, "http://localhost"); + const oauth2Client = new OAuth2Client({ + clientId, + clientSecret, + redirectUri: "http://localhost", + transporterOptions: { + timeout: DEFAULT_HTTP_TIMEOUT_MS, + }, + }); oauth2Client.setCredentials({ refresh_token: account.oauth2.refreshToken, }); - const gmail = google.gmail({ version: "v1", auth: oauth2Client }); + const gmail = google.gmail({ + version: "v1", + auth: oauth2Client, + timeout: DEFAULT_HTTP_TIMEOUT_MS, + retry: true, + retryConfig: { + ...GMAIL_CLIENT_RETRY_CONFIG, + httpMethodsToRetry: [...GMAIL_CLIENT_RETRY_CONFIG.httpMethodsToRetry], + statusCodesToRetry: GMAIL_CLIENT_RETRY_CONFIG.statusCodesToRetry.map((range) => [...range]), + }, + }); this.gmailClients.set(email, gmail); } @@ -463,13 +543,17 @@ export class GmailService { pageToken, }); - const threads = response.data.threads || []; - const detailedThreads: GmailThread[] = []; - - for (const thread of threads) { - const detail = (await this.getThread(email, thread.id, false)) as GmailThread; - detailedThreads.push(detail); - } + const rawThreads: GmailThread[] = response.data.threads || []; + const threads = rawThreads.filter((thread): thread is GmailThread & { id: string } => Boolean(thread.id)); + const detailedThreads = await mapWithConcurrency(threads, DEFAULT_CONCURRENCY, async (thread) => { + const detailResp = await gmail.users.threads.get({ + userId: "me", + id: thread.id, + format: "metadata", + metadataHeaders: METADATA_HEADERS, + }); + return detailResp.data as GmailThread; + }); return { threads: detailedThreads.map((thread) => ({ @@ -542,6 +626,7 @@ export class GmailService { inlineData: att.inlineData, filename: att.filename, partPath: att.partPath, + size: att.size, })), ); @@ -580,6 +665,7 @@ export class GmailService { inlineData?: string; filename: string; partPath: string; + size?: number; }>, ): Promise { const gmail = this.getGmailClient(email); @@ -622,18 +708,15 @@ export class GmailService { throw new Error("Attachment has no attachmentId or inline data"); } - if (fs.existsSync(filePath)) { - const existingSize = fs.statSync(filePath).size; - const attachmentInfo = await gmail.users.messages.attachments.get({ - userId: "me", - messageId: attachment.messageId, - id: attachment.attachmentId, - }); - - if (existingSize === attachmentInfo.data.size) { - results.push({ success: true, filename: attachment.filename, path: filePath, cached: true }); - continue; - } + const existingSize = fs.existsSync(filePath) ? fs.statSync(filePath).size : null; + if ( + existingSize !== null && + typeof attachment.size === "number" && + attachment.size > 0 && + existingSize === attachment.size + ) { + results.push({ success: true, filename: attachment.filename, path: filePath, cached: true }); + continue; } const response = await gmail.users.messages.attachments.get({ @@ -642,7 +725,12 @@ export class GmailService { id: attachment.attachmentId, }); - const data = Buffer.from(response.data.data, "base64url"); + const data = Buffer.from(response.data.data || "", "base64url"); + if (existingSize !== null && existingSize === data.length) { + results.push({ success: true, filename: attachment.filename, path: filePath, cached: true }); + continue; + } + fs.writeFileSync(filePath, data, { mode: 0o600 }); fs.chmodSync(filePath, 0o600); @@ -666,22 +754,24 @@ export class GmailService { removeLabels: string[] = [], ): Promise { const gmail = this.getGmailClient(email); + const normalizedAdd = [...new Set(addLabels.map((l) => l.trim()).filter(Boolean))]; + const normalizedRemove = [...new Set(removeLabels.map((l) => l.trim()).filter(Boolean))]; const results: LabelOperationResult[] = []; for (const threadId of threadIds) { try { - if (addLabels.length > 0) { - await gmail.users.threads.modify({ - userId: "me", - id: threadId, - requestBody: { addLabelIds: addLabels }, - }); - } - if (removeLabels.length > 0) { + if (normalizedAdd.length > 0 || normalizedRemove.length > 0) { + const requestBody: gmail_v1.Schema$ModifyThreadRequest = {}; + if (normalizedAdd.length > 0) { + requestBody.addLabelIds = normalizedAdd; + } + if (normalizedRemove.length > 0) { + requestBody.removeLabelIds = normalizedRemove; + } await gmail.users.threads.modify({ userId: "me", id: threadId, - requestBody: { removeLabelIds: removeLabels }, + requestBody, }); } results.push({ threadId, success: true }); @@ -732,14 +822,19 @@ export class GmailService { const draftStubs: GmailDraft[] = listResp.data.drafts || []; if (draftStubs.length === 0) break; - for (const stub of draftStubs) { - if (!stub.id) continue; + const validStubs = draftStubs.filter((stub): stub is GmailDraft & { id: string } => Boolean(stub.id)); + const stubsToFetch = + parsedOlderThan.cutoffMs === null ? validStubs.slice(0, maxResults - rawItems.length) : validStubs; + const fetchedDrafts = await mapWithConcurrency(stubsToFetch, DEFAULT_CONCURRENCY, async (stub) => { const draftResp = await gmail.users.drafts.get({ userId: "me", id: stub.id, format: "full", }); - const draft: GmailDraft = draftResp.data; + return { stub, draft: draftResp.data as GmailDraft }; + }); + + for (const { stub, draft } of fetchedDrafts) { const msg = draft.message; const headerDate = msg ? this.getHeaderValue(msg, "date") : undefined; const internalDateMs = parseMessageDateMs(msg?.internalDate, headerDate); @@ -785,67 +880,84 @@ export class GmailService { } if (checkSent && rawItems.length > 0) { - const threadCache = new Map(); - const sentQueryCache = new Map(); - const messageCache = new Map(); - - const fetchThread = async (threadId: string): Promise => { - if (threadCache.has(threadId)) return threadCache.get(threadId) ?? null; - try { - const resp = await gmail.users.threads.get({ - userId: "me", - id: threadId, - format: "metadata", - metadataHeaders: ["From", "To", "Cc", "Subject", "Date"], - }); - const thread: GmailThread = resp.data; - threadCache.set(threadId, thread); - return thread; - } catch { - threadCache.set(threadId, null); - return null; - } + const threadCache = new Map>(); + const sentQueryCache = new Map>(); + const messageCache = new Map>(); + + const fetchThread = (threadId: string): Promise => { + const cached = threadCache.get(threadId); + if (cached) return cached; + const pending = (async (): Promise => { + try { + const resp = await gmail.users.threads.get({ + userId: "me", + id: threadId, + format: "metadata", + metadataHeaders: METADATA_HEADERS, + }); + return resp.data as GmailThread; + } catch (err) { + if (isGmailNotFoundError(err)) { + return null; + } + threadCache.delete(threadId); + throw err; + } + })(); + threadCache.set(threadId, pending); + return pending; }; - const fetchMessageMetadata = async (messageId: string): Promise => { - if (messageCache.has(messageId)) return messageCache.get(messageId) ?? null; - try { - const resp = await gmail.users.messages.get({ - userId: "me", - id: messageId, - format: "metadata", - metadataHeaders: ["From", "To", "Cc", "Subject", "Date"], - }); - const message: GmailMessage = resp.data; - messageCache.set(messageId, message); - return message; - } catch { - messageCache.set(messageId, null); - return null; - } + const fetchMessageMetadata = (messageId: string): Promise => { + const cached = messageCache.get(messageId); + if (cached) return cached; + const pending = (async (): Promise => { + try { + const resp = await gmail.users.messages.get({ + userId: "me", + id: messageId, + format: "metadata", + metadataHeaders: METADATA_HEADERS, + }); + return resp.data as GmailMessage; + } catch (err) { + if (isGmailNotFoundError(err)) { + return null; + } + messageCache.delete(messageId); + throw err; + } + })(); + messageCache.set(messageId, pending); + return pending; }; - const searchSentMessages = async (query: string): Promise => { - if (sentQueryCache.has(query)) return sentQueryCache.get(query) || []; - const resp = await gmail.users.messages.list({ - userId: "me", - q: query, - maxResults: 10, - }); - const stubs: GmailMessage[] = resp.data.messages || []; - const messages: GmailMessage[] = []; - for (const stub of stubs) { - if (!stub.id) continue; - const msg = await fetchMessageMetadata(stub.id); - if (msg && isSentMessage(msg)) { - messages.push(msg); + const searchSentMessages = (query: string): Promise => { + const cached = sentQueryCache.get(query); + if (cached) return cached; + const pending = (async (): Promise => { + try { + const resp = await gmail.users.messages.list({ + userId: "me", + q: query, + maxResults: 10, + }); + const rawStubs: GmailMessage[] = resp.data.messages || []; + const stubs = rawStubs.filter((stub): stub is GmailMessage & { id: string } => Boolean(stub.id)); + const fetched = await mapWithConcurrency(stubs, DEFAULT_CONCURRENCY, (stub) => + fetchMessageMetadata(stub.id), + ); + return fetched.filter((msg): msg is GmailMessage => Boolean(msg && isSentMessage(msg))); + } catch (err) { + sentQueryCache.delete(query); + throw err; } - } - sentQueryCache.set(query, messages); - return messages; + })(); + sentQueryCache.set(query, pending); + return pending; }; - for (const item of rawItems) { + await mapWithConcurrency(rawItems, DEFAULT_CONCURRENCY, async (item) => { const candidatesById = new Map(); if (item.thread_id) { @@ -940,7 +1052,7 @@ export class GmailService { item.sent_candidates = [...candidatesById.values()].sort( (a, b) => (b.internal_date_ms ?? -1) - (a.internal_date_ms ?? -1), ); - } + }); } const drafts = classifyDraftAuditItems(rawItems, checkSent); @@ -977,7 +1089,14 @@ export class GmailService { } resolveLabelIds(labels: string[], nameToId: Map): string[] { - return labels.map((l) => nameToId.get(l.toLowerCase()) || l); + return [ + ...new Set( + labels + .map((l) => l.trim()) + .filter(Boolean) + .map((l) => nameToId.get(l.toLowerCase()) || l), + ), + ]; } private async resolveReplyTarget( diff --git a/test/drafts-audit.test.js b/test/drafts-audit.test.js index 330e75d..830e957 100644 --- a/test/drafts-audit.test.js +++ b/test/drafts-audit.test.js @@ -103,6 +103,246 @@ test("buildSentSearchQuery uses normalized subject and primary recipient", () => assert.equal(buildSentSearchQuery("", []), null); }); +test("buildSentSearchQuery matches multiple To/Cc recipients with OR and caps at 5 unique emails", () => { + assert.equal( + buildSentSearchQuery("settlement update", [ + { name: "Alice", email: "alice@example.com" }, + { name: "Bob", email: "BOB@example.com" }, + { name: "Alice Dup", email: "alice@example.com" }, + ]), + 'in:sent subject:"settlement update" (to:alice@example.com OR to:bob@example.com)', + ); + + const sevenRecipients = Array.from({ length: 7 }, (_, i) => ({ + name: `User ${i + 1}`, + email: `user${i + 1}@example.com`, + })); + assert.equal( + buildSentSearchQuery("group notice", sevenRecipients), + 'in:sent subject:"group notice" (to:user1@example.com OR to:user2@example.com OR to:user3@example.com OR to:user4@example.com OR to:user5@example.com)', + ); +}); + +test("auditDrafts finds sent duplicate sent to a CC recipient via multi-recipient search", async () => { + const twoDaysAgo = String(NOW_MS - 2 * DAY_MS); + const queries = []; + const { gmail } = makeFakeGmail({ + draftsList: [{ id: "r-cc-dup" }], + draftsById: { + "r-cc-dup": { + id: "r-cc-dup", + message: { + id: "m-cc-draft", + threadId: "t-cc-draft", + internalDate: twoDaysAgo, + labelIds: ["DRAFT"], + payload: { + headers: [ + { name: "To", value: "primary@example.com" }, + { name: "Cc", value: "secondary@example.com" }, + { name: "Subject", value: "Closing docs" }, + ], + }, + }, + }, + }, + threadsById: { + "t-cc-draft": { + id: "t-cc-draft", + messages: [{ id: "m-cc-draft", threadId: "t-cc-draft", labelIds: ["DRAFT"], internalDate: twoDaysAgo }], + }, + }, + sentSearch: (q) => { + queries.push(q); + if (q.includes("to:secondary@example.com")) { + return [{ id: "m-sent-to-cc" }]; + } + return []; + }, + messagesById: { + "m-sent-to-cc": { + id: "m-sent-to-cc", + threadId: "t-sent-separate", + labelIds: ["SENT"], + internalDate: String(NOW_MS - 1.5 * DAY_MS), + payload: { + headers: [ + { name: "To", value: "secondary@example.com" }, + { name: "Subject", value: "Closing docs" }, + ], + }, + }, + }, + }); + + const service = new GmailService(); + service.gmailClients.set("will@mclemoreauction.com", gmail); + const result = await service.auditDrafts("will@mclemoreauction.com", { + olderThan: "1d", + checkSent: true, + nowMs: NOW_MS, + }); + + assert.equal(queries.length, 1); + assert.equal(queries[0], 'in:sent subject:"closing docs" (to:primary@example.com OR to:secondary@example.com)'); + assert.equal(result.drafts[0].disposition, "likely_duplicate_sent"); + assert.equal(result.drafts[0].sent_candidates[0].message_id, "m-sent-to-cc"); + assert.equal(result.drafts[0].sent_candidates[0].match_kind, "subject_and_recipient"); +}); + +test("auditDrafts returns null on 404 thread/message lookups but propagates 401 and 429 errors", async () => { + const twoDaysAgo = String(NOW_MS - 2 * DAY_MS); + const baseDraft = { + id: "r-err", + message: { + id: "m-err", + threadId: "t-err", + internalDate: twoDaysAgo, + labelIds: ["DRAFT"], + payload: { + headers: [ + { name: "To", value: "client@example.com" }, + { name: "Subject", value: "Status update" }, + ], + }, + }, + }; + + // Genuine 404 on threads.get and messages.get is handled gracefully + const notFoundErr = Object.assign(new Error("Not Found"), { code: 404, response: { status: 404 } }); + const { gmail: gmail404 } = makeFakeGmail({ + draftsList: [{ id: "r-err" }], + draftsById: { "r-err": baseDraft }, + sentSearch: () => [{ id: "m-vanished" }], + }); + gmail404.users.threads.get = async () => { + throw notFoundErr; + }; + gmail404.users.messages.get = async () => { + throw notFoundErr; + }; + + const svc404 = new GmailService(); + svc404.gmailClients.set("will@mclemoreauction.com", gmail404); + const res404 = await svc404.auditDrafts("will@mclemoreauction.com", { + olderThan: "1d", + checkSent: true, + nowMs: NOW_MS, + }); + assert.equal(res404.drafts.length, 1); + assert.equal(res404.drafts[0].disposition, "not_proven_duplicate"); + + // 401 on threads.get must propagate, NEVER silently produce not_proven_duplicate + const authErr = Object.assign(new Error("Invalid Credentials"), { code: 401, response: { status: 401 } }); + const { gmail: gmail401 } = makeFakeGmail({ + draftsList: [{ id: "r-err" }], + draftsById: { "r-err": baseDraft }, + }); + gmail401.users.threads.get = async () => { + throw authErr; + }; + const svc401 = new GmailService(); + svc401.gmailClients.set("will@mclemoreauction.com", gmail401); + await assert.rejects( + () => svc401.auditDrafts("will@mclemoreauction.com", { olderThan: "1d", checkSent: true, nowMs: NOW_MS }), + /Invalid Credentials/, + ); + + // 429 on messages.get must propagate, NEVER silently produce not_proven_duplicate + const rateLimitErr = Object.assign(new Error("Rate Limit Exceeded"), { status: 429, response: { status: 429 } }); + const { gmail: gmail429 } = makeFakeGmail({ + draftsList: [{ id: "r-err" }], + draftsById: { "r-err": baseDraft }, + threadsById: { + "t-err": { id: "t-err", messages: [{ id: "m-err", threadId: "t-err", labelIds: ["DRAFT"] }] }, + }, + sentSearch: () => [{ id: "m-sent-1" }], + }); + gmail429.users.messages.get = async () => { + throw rateLimitErr; + }; + const svc429 = new GmailService(); + svc429.gmailClients.set("will@mclemoreauction.com", gmail429); + await assert.rejects( + () => svc429.auditDrafts("will@mclemoreauction.com", { olderThan: "1d", checkSent: true, nowMs: NOW_MS }), + /Rate Limit Exceeded/, + ); +}); + +test("auditDrafts fetches drafts and threads with bounded concurrency while preserving order", async () => { + const twoDaysAgo = String(NOW_MS - 2 * DAY_MS); + const count = 12; + const draftsList = Array.from({ length: count }, (_, i) => ({ id: `r-${i}` })); + const draftsById = {}; + const threadsById = {}; + for (let i = 0; i < count; i++) { + draftsById[`r-${i}`] = { + id: `r-${i}`, + message: { + id: `m-${i}`, + threadId: `t-${i}`, + internalDate: twoDaysAgo, + labelIds: ["DRAFT"], + payload: { + headers: [ + { name: "To", value: `user${i}@example.com` }, + { name: "Subject", value: `Draft ${i}` }, + ], + }, + }, + }; + threadsById[`t-${i}`] = { + id: `t-${i}`, + messages: [{ id: `m-${i}`, threadId: `t-${i}`, labelIds: ["DRAFT"], internalDate: twoDaysAgo }], + }; + } + + let draftInFlight = 0; + let maxDraftInFlight = 0; + let threadInFlight = 0; + let maxThreadInFlight = 0; + + const { gmail } = makeFakeGmail({ draftsList, draftsById, threadsById }); + const origDraftGet = gmail.users.drafts.get; + gmail.users.drafts.get = async (params) => { + draftInFlight++; + maxDraftInFlight = Math.max(maxDraftInFlight, draftInFlight); + await new Promise((r) => setTimeout(r, 15 - (Number(params.id.slice(2)) % 5) * 2)); + try { + return await origDraftGet(params); + } finally { + draftInFlight--; + } + }; + const origThreadGet = gmail.users.threads.get; + gmail.users.threads.get = async (params) => { + threadInFlight++; + maxThreadInFlight = Math.max(maxThreadInFlight, threadInFlight); + await new Promise((r) => setTimeout(r, 15 - (Number(params.id.slice(2)) % 5) * 2)); + try { + return await origThreadGet(params); + } finally { + threadInFlight--; + } + }; + + const service = new GmailService(); + service.gmailClients.set("will@mclemoreauction.com", gmail); + const result = await service.auditDrafts("will@mclemoreauction.com", { + olderThan: "1d", + checkSent: true, + nowMs: NOW_MS, + }); + + assert.equal(result.drafts.length, count); + assert.deepEqual( + result.drafts.map((d) => d.draft_id), + draftsList.map((d) => d.id), + ); + assert.ok(maxDraftInFlight >= 2 && maxDraftInFlight <= 5, `Expected 2..5 concurrent draft fetches, got ${maxDraftInFlight}`); + assert.ok(maxThreadInFlight >= 2 && maxThreadInFlight <= 5, `Expected 2..5 concurrent thread fetches, got ${maxThreadInFlight}`); +}); + test("auditDrafts classifies all 4 dispositions, extracts attachments, and makes zero mutating calls", async () => { const twoDaysAgo = String(NOW_MS - 2 * DAY_MS); const threeDaysAgo = String(NOW_MS - 3 * DAY_MS); diff --git a/test/gmail-service-perf.test.js b/test/gmail-service-perf.test.js new file mode 100644 index 0000000..a9e9c1d --- /dev/null +++ b/test/gmail-service-perf.test.js @@ -0,0 +1,385 @@ +import assert from "node:assert/strict"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import test from "node:test"; +import { + DEFAULT_CONCURRENCY, + DEFAULT_HTTP_TIMEOUT_MS, + GMAIL_CLIENT_RETRY_CONFIG, + GmailService, + METADATA_HEADERS, + isGmailNotFoundError, +} from "../dist/gmail-service.js"; + +function withTempDir(fn) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "gmcli-perf-test-")); + return Promise.resolve() + .then(() => fn(dir)) + .finally(() => { + fs.rmSync(dir, { recursive: true, force: true }); + }); +} + +test("downloadAttachments hits cache with 0 API calls when expected size matches disk", async () => { + await withTempDir(async (dir) => { + const attachmentDir = path.join(dir, "attachments"); + const payload = Buffer.from("cached-pdf-content"); + let apiCalls = 0; + + const gmail = { + users: { + messages: { + attachments: { + get: async () => { + apiCalls++; + return { data: { size: payload.length, data: payload.toString("base64url") } }; + }, + }, + }, + }, + }; + + const service = new GmailService({ configDir: dir, attachmentDir }); + service.gmailClients.set("test@example.com", gmail); + + // First download populates cache (1 API call) + const first = await service.downloadAttachments("test@example.com", [ + { + messageId: "msg123", + attachmentId: "att1234567890", + filename: "report.pdf", + partPath: "0.1", + size: payload.length, + }, + ]); + assert.equal(first[0].success, true); + assert.equal(first[0].cached, false); + assert.equal(apiCalls, 1); + + // Second download with matching size must make ZERO API calls + const second = await service.downloadAttachments("test@example.com", [ + { + messageId: "msg123", + attachmentId: "att1234567890", + filename: "report.pdf", + partPath: "0.1", + size: payload.length, + }, + ]); + assert.equal(second[0].success, true); + assert.equal(second[0].cached, true); + assert.equal(second[0].path, first[0].path); + assert.equal(apiCalls, 1, "Expected 0 additional attachments.get calls on size-matched cache hit"); + }); +}); + +test("downloadAttachments fetches ONCE (not twice) on cache size mismatch or unknown size", async () => { + await withTempDir(async (dir) => { + const attachmentDir = path.join(dir, "attachments"); + fs.mkdirSync(attachmentDir, { recursive: true, mode: 0o700 }); + + const freshPayload = Buffer.from("full-valid-attachment-bytes"); + let apiCalls = 0; + + const gmail = { + users: { + messages: { + attachments: { + get: async () => { + apiCalls++; + return { data: { size: freshPayload.length, data: freshPayload.toString("base64url") } }; + }, + }, + }, + }, + }; + + const service = new GmailService({ configDir: dir, attachmentDir }); + service.gmailClients.set("test@example.com", gmail); + + // Pre-populate a truncated/corrupt cached file on disk + const expectedPath = path.join(attachmentDir, "msg456_att99999_invoice.pdf"); + fs.writeFileSync(expectedPath, Buffer.from("short"), { mode: 0o600 }); + + // 1) Mismatched known size -> exactly 1 API call, overwrites stale file + const resMismatch = await service.downloadAttachments("test@example.com", [ + { + messageId: "msg456", + attachmentId: "att99999abcdef", + filename: "invoice.pdf", + partPath: "0.1", + size: freshPayload.length, + }, + ]); + assert.equal(resMismatch[0].success, true); + assert.equal(resMismatch[0].cached, false); + assert.equal(apiCalls, 1, "Expected exactly 1 attachments.get call on cache mismatch, not 2"); + assert.deepEqual(fs.readFileSync(expectedPath), freshPayload); + + // 2) Unknown size (size omitted) with matching disk file -> exactly 1 API call, returns cached: true + apiCalls = 0; + const resUnknownMatch = await service.downloadAttachments("test@example.com", [ + { + messageId: "msg456", + attachmentId: "att99999abcdef", + filename: "invoice.pdf", + partPath: "0.1", + }, + ]); + assert.equal(resUnknownMatch[0].success, true); + assert.equal(resUnknownMatch[0].cached, true); + assert.equal(apiCalls, 1, "Expected exactly 1 attachments.get call when expected size is unknown"); + }); +}); + +test("getThread(--download) forwards part size so repeat downloads make 0 attachment API calls", async () => { + await withTempDir(async (dir) => { + const attachmentDir = path.join(dir, "attachments"); + const content = Buffer.from("hello-thread-attachment"); + let attachmentCalls = 0; + + const gmail = { + users: { + threads: { + get: async () => ({ + data: { + id: "t-1", + messages: [ + { + id: "m-1", + payload: { + parts: [ + { + filename: "doc.txt", + mimeType: "text/plain", + body: { attachmentId: "att-abc12345", size: content.length }, + }, + ], + }, + }, + ], + }, + }), + }, + messages: { + attachments: { + get: async () => { + attachmentCalls++; + return { data: { size: content.length, data: content.toString("base64url") } }; + }, + }, + }, + }, + }; + + const service = new GmailService({ configDir: dir, attachmentDir }); + service.gmailClients.set("test@example.com", gmail); + + const first = await service.getThread("test@example.com", "t-1", true); + assert.equal(first.length, 1); + assert.equal(first[0].cached, false); + assert.equal(attachmentCalls, 1); + + const second = await service.getThread("test@example.com", "t-1", true); + assert.equal(second.length, 1); + assert.equal(second[0].cached, true); + assert.equal(attachmentCalls, 1); + }); +}); + +test("modifyLabels sends addLabelIds and removeLabelIds in one atomic call and trims whitespace", async () => { + const modifyCalls = []; + const gmail = { + users: { + threads: { + modify: async (params) => { + modifyCalls.push(params); + return { data: { id: params.id } }; + }, + }, + }, + }; + + const service = new GmailService(); + service.gmailClients.set("test@example.com", gmail); + + // Verify resolveLabelIds trims whitespace and drops empties + const nameToId = new Map([ + ["work", "Label_Work"], + ["tax", "Label_Tax"], + ["unread", "UNREAD"], + ]); + const resolvedAdd = service.resolveLabelIds(" Work , Tax , , Work ".split(","), nameToId); + assert.deepEqual(resolvedAdd, ["Label_Work", "Label_Tax"]); + + // Verify modifyLabels trims raw inputs and merges add + remove into a SINGLE request + const results = await service.modifyLabels( + "test@example.com", + ["t-1", "t-2"], + [" Label_Work ", " ", "Label_Tax", "Label_Work"], + [" UNREAD ", "", " INBOX "], + ); + + assert.deepEqual(results, [ + { threadId: "t-1", success: true }, + { threadId: "t-2", success: true }, + ]); + assert.equal(modifyCalls.length, 2, "Expected 1 atomic threads.modify call per thread"); + assert.deepEqual(modifyCalls[0], { + userId: "me", + id: "t-1", + requestBody: { + addLabelIds: ["Label_Work", "Label_Tax"], + removeLabelIds: ["UNREAD", "INBOX"], + }, + }); + assert.deepEqual(modifyCalls[1], { + userId: "me", + id: "t-2", + requestBody: { + addLabelIds: ["Label_Work", "Label_Tax"], + removeLabelIds: ["UNREAD", "INBOX"], + }, + }); + + // Whitespace-only labels make zero API calls + modifyCalls.length = 0; + const noop = await service.modifyLabels("test@example.com", ["t-3"], [" ", ""], [""]); + assert.deepEqual(noop, [{ threadId: "t-3", success: true }]); + assert.equal(modifyCalls.length, 0); +}); + +test("searchThreads uses format=metadata + metadataHeaders and preserves order under bounded concurrency", async () => { + const threadCount = 12; + const listThreads = Array.from({ length: threadCount }, (_, i) => ({ id: `t-${i}` })); + const getCalls = []; + let inFlight = 0; + let maxInFlight = 0; + + const gmail = { + users: { + threads: { + list: async () => ({ + data: { + threads: listThreads, + nextPageToken: "next-page-123", + }, + }), + get: async (params) => { + getCalls.push(params); + inFlight++; + maxInFlight = Math.max(maxInFlight, inFlight); + // Reverse delay so later threads resolve faster than earlier threads + const idx = Number(params.id.slice(2)); + await new Promise((r) => setTimeout(r, (threadCount - idx) * 3)); + try { + return { + data: { + id: params.id, + historyId: `h-${idx}`, + messages: [ + { + id: `m-${idx}`, + threadId: params.id, + labelIds: ["INBOX"], + snippet: `snippet ${idx}`, + historyId: `mh-${idx}`, + internalDate: String(1700000000000 + idx), + payload: { + headers: [ + { name: "From", value: `sender${idx}@example.com` }, + { name: "To", value: "me@example.com" }, + { name: "Subject", value: `Subject ${idx}` }, + { name: "Date", value: "Mon, 20 Apr 2026 10:00:00 +0000" }, + ], + }, + }, + ], + }, + }; + } finally { + inFlight--; + } + }, + }, + }, + }; + + const service = new GmailService(); + service.gmailClients.set("test@example.com", gmail); + + const result = await service.searchThreads("test@example.com", "in:inbox", threadCount); + + assert.equal(result.nextPageToken, "next-page-123"); + assert.equal(result.threads.length, threadCount); + assert.deepEqual( + result.threads.map((t) => t.id), + listThreads.map((t) => t.id), + "Threads must preserve list order despite out-of-order async completion", + ); + assert.equal(result.threads[0].messages[0].from, "sender0@example.com"); + assert.equal(result.threads[0].messages[0].to, "me@example.com"); + assert.equal(result.threads[0].messages[0].subject, "Subject 0"); + assert.equal(result.threads[0].messages[0].hasAttachments, false); + + assert.equal(getCalls.length, threadCount); + for (const call of getCalls) { + assert.equal(call.format, "metadata"); + assert.deepEqual(call.metadataHeaders, METADATA_HEADERS); + } + assert.ok( + maxInFlight >= 2 && maxInFlight <= DEFAULT_CONCURRENCY, + `Expected 2..${DEFAULT_CONCURRENCY} concurrent requests, got ${maxInFlight}`, + ); +}); + +test("getGmailClient configures HTTP timeout and safe retryConfig excluding POST", async () => { + await withTempDir(async (dir) => { + const service = new GmailService({ configDir: dir }); + service.setCredentials("test-client-id", "test-client-secret"); + service.accountStorage.addAccount({ + email: "retry-test@example.com", + oauth2: { + clientId: "test-client-id", + clientSecret: "test-client-secret", + refreshToken: "test-refresh-token", + }, + }); + + const gmail = service.getGmailClient("retry-test@example.com"); + const opts = gmail.context._options; + + assert.equal(opts.timeout, DEFAULT_HTTP_TIMEOUT_MS); + assert.equal(opts.timeout, 30_000); + assert.equal(opts.retry, true); + assert.equal(opts.retryConfig.retry, GMAIL_CLIENT_RETRY_CONFIG.retry); + assert.deepEqual(opts.retryConfig.statusCodesToRetry, [ + [429, 429], + [500, 599], + ]); + assert.deepEqual(opts.retryConfig.httpMethodsToRetry, ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]); + assert.equal( + opts.retryConfig.httpMethodsToRetry.includes("POST"), + false, + "POST must never be auto-retried to prevent duplicate sends/drafts", + ); + assert.equal(opts.auth.transporter.defaults.timeout, DEFAULT_HTTP_TIMEOUT_MS); + }); +}); + +test("isGmailNotFoundError identifies 404 responses and rejects auth/rate-limit/network errors", () => { + assert.equal(isGmailNotFoundError({ code: 404 }), true); + assert.equal(isGmailNotFoundError({ code: "404" }), true); + assert.equal(isGmailNotFoundError({ status: 404 }), true); + assert.equal(isGmailNotFoundError({ response: { status: 404 } }), true); + assert.equal(isGmailNotFoundError({ response: { data: { error: { code: 404 } } } }), true); + + assert.equal(isGmailNotFoundError({ code: 401, response: { status: 401 } }), false); + assert.equal(isGmailNotFoundError({ code: 403, response: { status: 403 } }), false); + assert.equal(isGmailNotFoundError({ status: 429, response: { status: 429 } }), false); + assert.equal(isGmailNotFoundError({ status: 503, response: { status: 503 } }), false); + assert.equal(isGmailNotFoundError({ code: "ECONNRESET" }), false); + assert.equal(isGmailNotFoundError(new Error("Thread not found")), false); + assert.equal(isGmailNotFoundError(null), false); +});