diff --git a/lib/emailCloudflare.ts b/lib/emailCloudflare.ts index abd70f8c..2187744a 100644 --- a/lib/emailCloudflare.ts +++ b/lib/emailCloudflare.ts @@ -9,10 +9,18 @@ type FetchFn = typeof fetch; export type InboxArea = '/messages' | '/archive'; export type ListedMessage = { id: string; to: string; from: string; size: number; receivedAt: string }; -type ListPage = { messages: ListedMessage[]; cursor: string | null; complete: boolean }; +type ListPage = { messages?: ListedMessage[]; cursor?: string | null; complete?: boolean; unchanged?: boolean; rev?: string }; const MAX_PAGES = 50; // 5000 messages at 100 per page +// Cloudflare KV's free plan allows 1,000 lists a day, and the worker is polled every few minutes by +// several callers. The worker stamps each listing with a change marker (`rev`) and answers "unchanged" +// (one cheap KV read) when a caller sends the marker it last saw. The last full listing is kept per +// worker and area; it is trusted for an hour at most, since mail that expires from KV changes no +// marker. A worker without the marker never sends `rev`, so nothing is cached and every call lists. +const REV_MAX_AGE_MS = 60 * 60 * 1000; +const listCache = new Map(); + function endpoint(creds: CloudflareCreds, path: string): string { return creds.url.replace(/\/+$/, '') + path; } @@ -21,9 +29,10 @@ function headers(creds: CloudflareCreds): HeadersInit { return { Authorization: `Bearer ${creds.token}` }; } -async function listPage(creds: CloudflareCreds, fetchFn: FetchFn, cursor: string | null, limit: number, area: InboxArea = '/messages'): Promise { +async function listPage(creds: CloudflareCreds, fetchFn: FetchFn, cursor: string | null, limit: number, area: InboxArea = '/messages', rev?: string): Promise { const qs = new URLSearchParams({ limit: String(limit) }); if (cursor) qs.set('cursor', cursor); + if (rev && !cursor) qs.set('rev', rev); const res = await fetchFn(endpoint(creds, `${area}?${qs}`), { headers: headers(creds) }); if (!res.ok) throw new Error(`Cloudflare inbox list failed: HTTP ${res.status}`); return (await res.json()) as ListPage; @@ -42,17 +51,27 @@ export async function testCloudflare(creds: CloudflareCreds, fetchFn: FetchFn = */ export type ParsedCache = Map; -/** Every message in the inbox (metadata only), following the worker's cursor. */ +/** Every message in the inbox (metadata only), following the worker's cursor. Unchanged since the last call: no KV list. */ export async function listCloudflareMessages(creds: CloudflareCreds, fetchFn: FetchFn = fetch, area: InboxArea = '/messages'): Promise { + const cacheKey = `${endpoint(creds, '')}|${area}`; + const cached = listCache.get(cacheKey); + const fresh = cached && Date.now() - cached.at < REV_MAX_AGE_MS ? cached : undefined; const all: ListedMessage[] = []; let cursor: string | null = null; + let rev: string | undefined; for (let i = 0; i < MAX_PAGES; i++) { - const page: ListPage = await listPage(creds, fetchFn, cursor, 100, area); - all.push(...page.messages); + const page: ListPage = await listPage(creds, fetchFn, cursor, 100, area, i === 0 ? fresh?.rev : undefined); + if (i === 0) { + if (page.unchanged && fresh) return [...fresh.messages]; + rev = typeof page.rev === 'string' && page.rev ? page.rev : undefined; + } + all.push(...(page.messages ?? [])); if (page.complete || !page.cursor) break; cursor = page.cursor; } - return all; + if (rev) listCache.set(cacheKey, { rev, at: Date.now(), messages: all }); + else listCache.delete(cacheKey); + return [...all]; } /** One message's raw MIME, or null when it is gone or unreadable. */ diff --git a/lib/orderInboxAddy.test.ts b/lib/orderInboxAddy.test.ts index e2899c8c..a32fa457 100644 --- a/lib/orderInboxAddy.test.ts +++ b/lib/orderInboxAddy.test.ts @@ -12,13 +12,17 @@ const ORDER = '111-2223334-4445556'; const SECRET = 'whsec-e2e'; function fakeKV() { - const store = new Map(); + const store = new Map(); return { store, - async put(key: string, value: Uint8Array, opts: { metadata?: unknown }) { store.set(key, { value, opts }); }, - async get(key: string) { + async put(key: string, value: Uint8Array | string, opts?: { metadata?: unknown }) { store.set(key, { value, opts: opts ?? {} }); }, + async get(key: string, type?: string) { const e = store.get(key); - return e ? e.value.buffer.slice(e.value.byteOffset, e.value.byteOffset + e.value.byteLength) : null; + if (!e) return null; + const v = e.value; + if (typeof v === 'string') return v; + if (type === 'text') return new TextDecoder().decode(v); + return v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength); }, async delete(key: string) { store.delete(key); }, async list({ prefix, limit }: { prefix: string; limit: number }) { diff --git a/workers/order-inbox/src/handlers.js b/workers/order-inbox/src/handlers.js index d5f39e95..d88f4333 100644 --- a/workers/order-inbox/src/handlers.js +++ b/workers/order-inbox/src/handlers.js @@ -10,6 +10,28 @@ export const MAX_LIMIT = 100; // went wrong and the email is needed again. export const ARCHIVE_TTL_SECONDS = 7 * 24 * 60 * 60; export const ARCHIVE_PREFIX = 'a:'; +// One small key, rewritten on every change to the inbox or archive (new mail, +// archive copy, delete). A poller that sends the value it last saw gets +// "unchanged" for one KV read instead of a KV list (lists are capped at +// 1,000/day on the free plan, reads at 100,000/day). Outside both prefixes, so +// no listing ever returns it. No TTL: it must outlive quiet periods. +export const REV_KEY = 'meta:rev'; + +/** The current change marker, or '' when nothing has been written yet. */ +export async function readRev(env) { + return (await env.ORDER_MAIL.get(REV_KEY, 'text')) ?? ''; +} + +/** + * Record that the inbox or archive changed. Best effort: a failed write (KV + * limits one key to one write per second) must not lose the mail, and the + * tracker re-lists at least hourly regardless of the marker. + */ +export async function bumpRev(env, now = new Date(), uuid = () => crypto.randomUUID()) { + try { + await env.ORDER_MAIL.put(REV_KEY, `${now.getTime().toString(36)}-${uuid().slice(0, 8)}`); + } catch { /* the hourly full list covers it */ } +} /** Read a ReadableStream fully; null when it exceeds `max` bytes. */ export async function readStream(stream, max) { @@ -50,6 +72,7 @@ export async function handleEmail(message, env, now = new Date(), uuid = () => c expirationTtl: TTL_SECONDS, metadata: { to: message.to, from: message.from, size: raw.byteLength, receivedAt }, }); + await bumpRev(env, now, uuid); return key; } @@ -203,6 +226,7 @@ export async function handleAddyWebhook(request, env, now = new Date()) { expirationTtl: TTL_SECONDS, metadata: { to: recipient, from: typeof p.from === 'string' ? p.from : '', size: raw.byteLength, receivedAt }, }); + await bumpRev(env, now); return new Response(null, { status: 204 }); } @@ -227,6 +251,11 @@ export async function handleFetch(request, env) { const n = Number.parseInt(url.searchParams.get('limit') ?? '', 10); const limit = Number.isFinite(n) && n > 0 ? Math.min(n, MAX_LIMIT) : MAX_LIMIT; const cursor = url.searchParams.get('cursor') || undefined; + // Read before listing: a write that lands during the list leaves the marker ahead of + // what the caller stores, so the next poll lists again instead of missing it. + const rev = await readRev(env); + const seen = url.searchParams.get('rev'); + if (!cursor && seen && rev && seen === rev) return json({ unchanged: true, rev }); const res = await env.ORDER_MAIL.list({ prefix, limit, cursor }); const messages = res.keys.map(k => ({ id: k.name, @@ -236,7 +265,7 @@ export async function handleFetch(request, env) { receivedAt: k.metadata?.receivedAt ?? '', ...(k.metadata?.processedAt ? { processedAt: k.metadata.processedAt } : {}), })); - return json({ messages, cursor: res.list_complete ? null : (res.cursor ?? null), complete: Boolean(res.list_complete) }); + return json({ messages, cursor: res.list_complete ? null : (res.cursor ?? null), complete: Boolean(res.list_complete), rev }); } if (url.pathname.startsWith(`${base}/`)) { @@ -252,6 +281,7 @@ export async function handleFetch(request, env) { if (request.method === 'DELETE') { if (prefix === KEY_PREFIX && url.searchParams.get('purge') !== '1') await archive(env, id); await env.ORDER_MAIL.delete(id); + await bumpRev(env); return new Response(null, { status: 204 }); } } diff --git a/workers/order-inbox/src/handlers.test.js b/workers/order-inbox/src/handlers.test.js index 924049c1..9d6846ff 100644 --- a/workers/order-inbox/src/handlers.test.js +++ b/workers/order-inbox/src/handlers.test.js @@ -1,16 +1,17 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { handleEmail, handleFetch, MAX_RAW_BYTES, TTL_SECONDS } from './handlers.js'; +import { handleEmail, handleFetch, MAX_RAW_BYTES, TTL_SECONDS, REV_KEY } from './handlers.js'; function fakeKV() { const store = new Map(); return { store, async put(key, value, opts) { store.set(key, { value, opts }); }, - async get(key) { + async get(key, type) { const e = store.get(key); if (!e) return null; const v = e.value; + if (type === 'text') return typeof v === 'string' ? v : new TextDecoder().decode(v); return v instanceof ArrayBuffer ? v.slice(0) : v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength); }, async getWithMetadata(key) { @@ -46,6 +47,9 @@ function msg(body, extra = {}) { }; } +// The change marker is bookkeeping, not mail. +const mailCount = env => [...env.ORDER_MAIL.store.keys()].filter(k => k !== REV_KEY).length; + const req = (path, init = {}, token = 'tok') => new Request('https://w.example.test' + path, { ...init, headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), ...init.headers } }); @@ -67,7 +71,7 @@ test('email over 24 MiB is rejected and not stored', async () => { const m = msg('', { raw: new ReadableStream({ start(c) { c.enqueue(big); c.close(); } }) }); assert.equal(await handleEmail(m, env), null); assert.equal(m.rejected, 'message too large'); - assert.equal(env.ORDER_MAIL.store.size, 0); + assert.equal(mailCount(env), 0); const m2 = msg('x', { rawSize: MAX_RAW_BYTES + 1 }); await handleEmail(m2, env); assert.equal(m2.rejected, 'message too large'); @@ -93,7 +97,7 @@ test('list paginates with cursor and caps limit', async () => { assert.equal(r2.messages.length, 1); assert.equal(r2.complete, true); let seenLimit = 0; - const spy = { PULL_TOKEN: 'tok', ORDER_MAIL: { list: async o => { seenLimit = o.limit; return { keys: [], list_complete: true }; } } }; + const spy = { PULL_TOKEN: 'tok', ORDER_MAIL: { get: async () => null, list: async o => { seenLimit = o.limit; return { keys: [], list_complete: true }; } } }; await handleFetch(req('/messages?limit=5000'), spy); assert.equal(seenLimit, 100); }); @@ -141,15 +145,15 @@ test('delete keeps a 7-day archive copy; purge=1 and archive delete do not', asy // Deleting from the archive is final. assert.equal((await handleFetch(req('/archive/' + encodeURIComponent(akey), { method: 'DELETE' }), env)).status, 204); - assert.equal(env.ORDER_MAIL.store.size, 0); + assert.equal(mailCount(env), 0); // purge=1 skips the archive. const k2 = await handleEmail(msg('other'), env, new Date('2026-02-04T00:00:00.000Z'), () => 'def'); assert.equal((await handleFetch(req('/messages/' + encodeURIComponent(k2) + '?purge=1', { method: 'DELETE' }), env)).status, 204); - assert.equal(env.ORDER_MAIL.store.size, 0); + assert.equal(mailCount(env), 0); // A missing id still answers 204 and archives nothing. assert.equal((await handleFetch(req('/messages/' + encodeURIComponent('m:gone'), { method: 'DELETE' }), env)).status, 204); - assert.equal(env.ORDER_MAIL.store.size, 0); + assert.equal(mailCount(env), 0); // The archive needs the bearer token too. assert.equal((await handleFetch(req('/archive', {}, 'nope'), env)).status, 401); }); @@ -211,7 +215,7 @@ test('addy: signed forward is stored under the mapped orders address', async () const env = ADDY_ENV(); const res = await handleFetch(await addyReq(env, '/addy/sam', addyPayload()), env); assert.equal(res.status, 204); - const keys = [...env.ORDER_MAIL.store.keys()]; + const keys = [...env.ORDER_MAIL.store.keys()].filter(k => k !== REV_KEY); assert.deepEqual(keys, [`${KEY_PREFIX}2026-11-15T21:00:00.000Z:addy-${'a'.repeat(64)}`]); const e = env.ORDER_MAIL.store.get(keys[0]); assert.equal(e.opts.expirationTtl, TTL_SECONDS); @@ -233,7 +237,7 @@ test('addy: retry of the same payload overwrites instead of duplicating', async for (let i = 0; i < 3; i++) { assert.equal((await handleFetch(await addyReq(env, '/addy/sam', addyPayload()), env)).status, 204); } - assert.equal(env.ORDER_MAIL.store.size, 1); + assert.equal(mailCount(env), 1); }); test('addy: bad, missing, or wrong-secret signatures are 401 and store nothing', async () => { @@ -245,7 +249,7 @@ test('addy: bad, missing, or wrong-secret signatures are 401 and store nothing', const good = await addyReq(env, '/addy/sam', addyPayload()); const tampered = new Request(good.url, { method: 'POST', headers: good.headers, body: JSON.stringify(addyPayload({ subject: 'x' })) }); assert.equal((await handleFetch(tampered, env)).status, 401); - assert.equal(env.ORDER_MAIL.store.size, 0); + assert.equal(mailCount(env), 0); }); test('addy: unknown user, unset secret, and non-POST are not webhook hits', async () => { @@ -256,7 +260,7 @@ test('addy: unknown user, unset secret, and non-POST are not webhook hits', asyn assert.equal((await handleFetch(await addyReq(noSecret, '/addy/sam', addyPayload(), { secret: 'x' }), noSecret)).status, 404); // GET on the path still needs the bearer token like every other route. assert.equal((await handleFetch(req('/addy/sam', {}, null), env)).status, 401); - assert.equal(env.ORDER_MAIL.store.size, 0); + assert.equal(mailCount(env), 0); }); test('addy: per-user secret overrides the shared one', async () => { @@ -271,7 +275,7 @@ test('addy: replies, sends, and other events are acknowledged but not stored', a for (const over of [{ email_type: 'reply' }, { email_type: 'send' }, { event: 'something.else' }]) { assert.equal((await handleFetch(await addyReq(env, '/addy/sam', addyPayload(over)), env)).status, 204); } - assert.equal(env.ORDER_MAIL.store.size, 0); + assert.equal(mailCount(env), 0); }); test('addy: invalid JSON is 400, oversize is 413', async () => { @@ -282,7 +286,7 @@ test('addy: invalid JSON is 400, oversize is 413', async () => { const big = 'x'.repeat(4 * 1024 * 1024 + 1); const r2 = new Request('https://w.example.test/addy/sam', { method: 'POST', body: big, headers: { 'x-addy-signature': await hmacHex('whsec-test', big) } }); assert.equal((await handleFetch(r2, env)).status, 413); - assert.equal(env.ORDER_MAIL.store.size, 0); + assert.equal(mailCount(env), 0); }); test('addy: recipient lookup is by local part, case-insensitive', () => {