/** * COTTON FETCHES, the reading half (Post CONTRACT row 13; the password's half is src/mail/fetch.ts). On the object's * alarm, each mailbox given to Cotton is read over IMAP: new mail first, then its history newest first, a bounded * number of messages a pass. Each message lands exactly as own-domain mail does (src/mail/mail.ts `arrive`): sealed * to the arrival key at once, its rows the ones the Mac writes for the same message (cotton-rules `mail::arrive` * with what IMAP said of it: Gmail's ids, labels and flags, or a plain server's flags). * * WHICH MAILBOX. Gmail (X-GM-EXT-1): All Mail (the `\All` mailbox), whose labels say inbox, sent, starred and the * rest. Any other server: INBOX. * * THE CURSOR (`mail_fetch_account.cursor`, JSON): the mailbox read, its UIDVALIDITY, the highest UID read (new mail * is above it) and the lowest (history is below it). A new UIDVALIDITY starts again from the top; a message already * kept answers duplicate and keeps nothing more. * * Read with EXAMINE: reading never marks a message read on the server (BODY.PEEK[] too). * * A refused password stops the account (`refused`) until it is given again; any other failure is logged by its kind * alone and tried again at the next pass. */importtype { Arrived } from"./mail.ts";import * as fetch from"./fetch.ts";import { Imap, ImapError, typeDial, typeFetchedasImapFetched } from"./imap.ts";import { fromAddress, headerBlock } from"./acts.ts";import { refuse } from"../http.ts";importtype { Fetched } from"../rules/index.ts";/** How often a mailbox is read for new mail. */exportconst EVERY_MS = 5 * 60_000;/** How soon the next pass comes while history is still being read. */exportconst CARRY_ON_MS = 5_000;/** Messages a pass reads, new and history together: a pass stays well inside an alarm's time. */exportconst PER_PASS = 40;/** Messages asked in one FETCH. */const CHUNK = 10;/** A message larger than this is not fetched (own-domain mail takes 25 MiB). */exportconst MAX_BYTES = 25 * 1024 * 1024;/** The history search reads UIDs in windows of this many, so a large mailbox never answers all its UIDs at once. */const HISTORY_WINDOW = 2000;const LOOPBACK = "127.0.0.1";exportinterfaceFetcherHostextends fetch.FetchHost { dial: Dial;/** Keep one message as own-domain mail is kept, with what IMAP said of it. */ arrive(raw: Uint8Array, address: string, received: number, fetched: Fetched): Promise<Arrived>;/** A connection this account reads on, so removing the password closes it at once; `release` when it is done. */ hold(account: string, conn: { close(): void }): void; release(account: string, conn: { close(): void }): void;/** Whether this object's fetcher must stop now: the account's mail moved to the job beside it (src/mail/fetch_job.ts). */ stopped?(): boolean;}exportinterfaceCursor { box: string; validity: number;/** The highest UID read: new mail is above it. */ high: number;/** The lowest UID read: history is below it; 1 or less when all of it is read. */ low: number;}exportfunction cursorOf(text: string | null): Cursor | null {if (!text) returnnull;try {const c = JSON.parse(text) asCursor;returntypeof c.box === "string" && Number.isInteger(c.validity) && Number.isInteger(c.high) && Number.isInteger(c.low) ? c : null; } catch {returnnull; }}exportinterfacePassResult { account: string; count: number;/** History left to read: the next pass comes soon. */ more: boolean; state: fetch.FetchState;}/** Read every account that is due. Answers how soon the next pass is wanted (ms), or null with no account held. */exportasyncfunction pass(host: FetcherHost): Promise<{ next: number | null; results: PassResult[] }> {const now = host.now();const results: PassResult[] = [];let next: number | null = null;for (const held of fetch.accounts(host.sql)) {if (held.state === "refused" || held.state === "stopped") continue;const more = held.cursor !== null && (cursorOf(held.cursor)?.low ?? 0) > 1;const due = held.last_at === null || more || now - held.last_at >= EVERY_MS;if (due) {const r = await read(host, held.account); results.push(r);if (r.state === "refused") continue; next = Math.min(next ?? Infinity, r.more ? CARRY_ON_MS : EVERY_MS); } else next = Math.min(next ?? Infinity, Math.max(1000, held.last_at! + EVERY_MS - now)); }return { next, results };}/** One account's read: new mail, then history, at most PER_PASS messages. */exportasyncfunction read(host: FetcherHost, account: string): Promise<PassResult> {const held = fetch.held(host.sql, account);if (!held) return { account, count: 0, more: false, state: "stopped" };// The switch thrown on (JOBS OUT 3, L-b): no new login here; the job reads this mailbox now.if (host.stopped?.()) return { account, count: 0, more: false, state: held.state };const sealed = fetch.passwordEnc(host.sql, account);if (!sealed) return { account, count: 0, more: false, state: "stopped" }; fetch.setState(host, account, "live");let imap: Imap | null = null;let count = 0;try {try { imap = await connect(host, held); } catch (e) {if (e instanceofImapError && e.kind === "no") { fetch.setState(host, account, "refused", true); fetch.log(host, account, "failed", 0, "refused");return { account, count: 0, more: false, state: "refused" }; }throw e; }const gmail = imap.gmail;const box = gmail ? ((await imap.special("\\All")) ?? "INBOX") : "INBOX";const selected = await imap.select(box, true);let cursor = cursorOf(held.cursor);if (!cursor || cursor.box !== box || cursor.validity !== selected.uidvalidity) {// From the top: everything below UIDNEXT is history.const top = selected.uidnext !== null ? selected.uidnext - 1 : Math.max(0, ...(await imap.search("ALL"))); cursor = { box, validity: selected.uidvalidity, high: top, low: top + 1 }; fetch.setCursor(host.sql, account, JSON.stringify(cursor)); }const c = cursor;const marks = host.sql.exec<{ mark: string }>("SELECT mark FROM mail_fetch_blocked WHERE account = ?", account).toArray();const blocked = marks.length ? newSet(marks.map((m) => m.mark)) : null;const toTrash: number[] = [];const keep = async (uids: number[], side: "new" | "history") => {for (let i = 0; i < uids.length; i += CHUNK) {const chunk = uids.slice(i, i + CHUNK);const meta = newMap((await imap!.fetch(chunk, false)).map((m) => [m.uid, m]));for (const uid of chunk) {// The switch thrown on mid-pass: stop between messages; the job reads on from the cursor kept so far.if (host.stopped?.()) return;const m = meta.get(uid);if (m && (m.size ?? 0) <= MAX_BYTES) {const [whole] = await imap!.fetch([uid], true);if (whole?.body) {// A sender on this account's own list (an unsubscribe with no one-click): to Trash, not kept.constfrom = fromAddress(headerBlock(whole.body));if (side === "new" && blocked && from && blocked.has(await fetch.senderMark(host.env, host.databaseId, account, from))) { toTrash.push(uid);// Kept until it is moved, so a pass cut by the switch leaves it for the job (JOBS OUT 3, L-b). pendTrash(host.sql, account, c.validity, uid, host.now()); }else {const arrived = await host.arrive(whole.body, held.address, whole.internal ?? host.now(), factsOf(whole, gmail));// Where it is, for the acts that name it by its row (src/mail/acts.ts): numbers only.if (arrived.email) host.sql.exec("INSERT INTO mail_fetch_index (account, email_id, box, validity, uid, msgid) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (account, email_id) DO UPDATE SET box = excluded.box, validity = excluded.validity, uid = excluded.uid, msgid = excluded.msgid", account, arrived.email, box, c.validity, uid, whole.msgid ?? null); count++; } } }// Moved past whether kept or not (gone since the search, or too large): never read again.if (side === "new") c.high = Math.max(c.high, uid);else c.low = Math.min(c.low, uid); fetch.setCursor(host.sql, account, JSON.stringify(c)); } } };// New mail, oldest first, so a pass cut short leaves no gap.const fresh = (await imap.search(`UID ${c.high + 1}:*`)).filter((u) => u > c.high).slice(0, PER_PASS);await keep(fresh, "new");// History, newest first, in windows of UIDs below the lowest read.let budget = PER_PASS - fresh.length;while (budget > 0 && c.low > 1 && !host.stopped?.()) {constfrom = Math.max(1, c.low - HISTORY_WINDOW);const older = (await imap.search(`UID ${from}:${c.low - 1}`)).filter((u) => u < c.low).reverse().slice(0, budget);if (!older.length) { c.low = from; fetch.setCursor(host.sql, account, JSON.stringify(c));continue; }await keep(older, "history"); budget -= older.length; }if (toTrash.length) {// Opened to be written for this alone; never expunged.const uses = await imap.uses();const trash = uses.trash ?? (gmail ? "[Gmail]/Trash" : null);if (trash && (imap.capabilities.has("MOVE") || gmail)) {await imap.select(box);await imap.move(toTrash.join(","), trash, !imap.capabilities.has("MOVE"));for (const uid of toTrash) host.sql.exec("DELETE FROM mail_fetch_trash WHERE account = ? AND validity = ? AND uid = ?", account, c.validity, uid); } }await imap.logout(); imap = null; fetch.setState(host, account, "idle", true);if (count) fetch.log(host, account, "fetched", count, null);return { account, count, more: c.low > 1, state: "idle" }; } catch (e) {// Never the server's words: they may name the mailbox. Only the kind.const said = (e as { code?: unknown }).code;const code = e instanceofImapError ? e.kind : typeof said === "string" && /^[a-z_]{1,40}$/.test(said) ? said : "error";if (fetch.held(host.sql, account)) { fetch.setState(host, account, "idle", true); fetch.log(host, account, "failed", count, code); }return { account, count, more: false, state: "idle" }; } finally {if (imap) { imap.close(); host.release(account, imap); } }}/** How long one alarm holds IDLE on each mailbox before it re-arms (Gmail ends an IDLE after about 29 minutes). */exportconst IDLE_WINDOW_MS = 4 * 60_000;/** * NEW MAIL IN SECONDS (Post's words for Cotton fetches): after a pass, the object holds IDLE on each live mailbox * for a window, and reads at once when the server says new mail exists; then the alarm comes again at once. A * server without IDLE is asked each minute instead. Answers how many came. Any failure ends the window quietly: * the next pass reads and logs. */exportasyncfunction watch(host: FetcherHost, account: string, windowMs = IDLE_WINDOW_MS): Promise<number> {const held = fetch.held(host.sql, account);if (!held || held.state === "refused" || held.state === "stopped" || host.stopped?.()) return0;if ((cursorOf(held.cursor)?.low ?? 2) > 1) return0;const end = Date.now() + windowMs;let count = 0;let imap: Imap | null = null;try { imap = await connect(host, held);const box = imap.gmail ? ((await imap.uses()).all ?? "INBOX") : "INBOX";await imap.select(box, true);while (Date.now() < end) {if (!(await imap.idle(end - Date.now()))) break;if (!fetch.held(host.sql, account) || host.stopped?.()) break; count += (await read(host, account)).count; } } catch {// Closed (the password removed) or dropped: the next pass reads again. } finally {if (imap) { imap.close(); host.release(account, imap); } }return count;}/** A message to move to Trash (a blocked sender's), kept until it is moved: by this pass, or by the job after the switch. */exportfunction pendTrash(sql: SqlStorage, account: string, validity: number, uid: number, at: number): void { sql.exec("INSERT INTO mail_fetch_trash (account, validity, uid, at) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", account, validity, uid, at);}/** The account's mailbox, signed in: the connection held so removing the password closes it at once. A refused password throws ImapError "no". */exportasyncfunction connect(host: FetcherHost, held: fetch.Held): Promise<Imap> {const sealed = fetch.passwordEnc(host.sql, held.account) ?? refuse(404, "not_fetched", "Cotton does not fetch this mail account");const password = await fetch.openPassword(host.env, host.databaseId, held.account, sealed);const imap = awaitImap.open(await host.dial(held.host, held.port, held.host !== LOOPBACK)); host.hold(held.account, imap);try {await imap.login(held.address, password); } catch (e) { imap.close(); host.release(held.account, imap);throw e; }return imap;}/** What the rules take of one fetched message. */exportfunction factsOf(m: ImapFetched, gmail: boolean): Fetched {if (gmail && m.msgid) return { msgid: m.msgid, ...(m.thrid ? { thrid: m.thrid } : {}), labels: m.labels, flags: m.flags, inbox: m.labels.some((l) => l.toLowerCase() === "\\inbox") };return { labels: [], flags: m.flags, inbox: true };}