Email for professionals and teams
feat(import): infer read/spam from message headers, faster adaptive IMAP chunks
Hieu Nguyen (Jack)4aaf0661c288
diff --git a/CLAUDE.md b/CLAUDE.mdindex 86ed313..c1b6d94 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -153,7 +153,7 @@ Optional tables are detected with `isMissingTableError` (`src/lib/database-error### Imports are background jobs-`/api/import/messages` (uploads) and `/api/import/imap` only validate and create a row in `import_jobs`, then answer 202 with the job; nothing is imported inside the request. `processImportJob` (`src/lib/import/jobs.ts`) handles one chunk per `import.run` message on `OUTBOUND_QUEUE` (like webhook retries, so no extra binding), records counters and the resume `cursor` on the row, and enqueues the next chunk itself. Uploaded files are split and staged in the bucket as `import-jobs/<id>/<n>.bin` batches (`staging.ts`), deleted as consumed. IMAP jobs read the folder list from `spec`, but the password never touches the database: it rides along in each queue message, so a lost message fails the job instead of resuming. Cancelling flips the status; every chunk's final write is conditional on the job still being active. `sweepImportJobs` (cron / Node scheduler) fails jobs idle for 30 minutes and prunes finished records after 7 days. The import page polls `GET /api/import/jobs`; `DELETE /api/import/jobs/[id]` cancels an active job or dismisses a finished one. `import_jobs` is in `INTERNAL_TABLES`, so backups skip it.+`/api/import/messages` (uploads) and `/api/import/imap` only validate and create a row in `import_jobs`, then answer 202 with the job; nothing is imported inside the request. `processImportJob` (`src/lib/import/jobs.ts`) handles one chunk per `import.run` message on `OUTBOUND_QUEUE` (like webhook retries, so no extra binding), records counters and the resume `cursor` on the row, and enqueues the next chunk itself. Uploaded files are split and staged in the bucket as `import-jobs/<id>/<n>.bin` batches (`staging.ts`), deleted as consumed. IMAP jobs read the folder list from `spec`, but the password never touches the database: it rides along in each queue message, so a lost message fails the job instead of resuming. Cancelling flips the status; every chunk's final write is conditional on the job still being active. `sweepImportJobs` (cron / Node scheduler) fails jobs idle for 30 minutes and prunes finished records after 7 days. The import page polls `GET /api/import/jobs`; `DELETE /api/import/jobs/[id]` cancels an active job or dismisses a finished one. IMAP chunks pipeline their FETCHes (sizes first via `RFC822.SIZE`, then groups bounded by `planImapFetchGroups`). Chunk size is adaptive: `cursor.size` halves when a chunk throws (retried up to 4 times, except credential errors) or when the queue redelivers the message (`attempt` from `msg.attempts`, e.g. a resource-limit 503), and climbs back after clean chunks. `import_jobs` is in `INTERNAL_TABLES`, so backups skip it.### Search is an FTS5 index kept by triggersdiff --git a/public/locales/ar.json b/public/locales/ar.jsonindex ca6d78e..2fc9016 100644--- a/public/locales/ar.json+++ b/public/locales/ar.json@@ -2072,6 +2072,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/bn.json b/public/locales/bn.jsonindex 55dc900..d0aecde 100644--- a/public/locales/bn.json+++ b/public/locales/bn.json@@ -2010,6 +2010,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/de.json b/public/locales/de.jsonindex a4ef76e..f40f368 100644--- a/public/locales/de.json+++ b/public/locales/de.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/es.json b/public/locales/es.jsonindex 5cb79c2..f278f25 100644--- a/public/locales/es.json+++ b/public/locales/es.json@@ -2027,6 +2027,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/fa.json b/public/locales/fa.jsonindex 1afbcac..8feae2c 100644--- a/public/locales/fa.json+++ b/public/locales/fa.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/fr.json b/public/locales/fr.jsonindex aed5c18..146aed8 100644--- a/public/locales/fr.json+++ b/public/locales/fr.json@@ -2027,6 +2027,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/gu.json b/public/locales/gu.jsonindex ef6fdba..91d1a96 100644--- a/public/locales/gu.json+++ b/public/locales/gu.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/ha.json b/public/locales/ha.jsonindex 3db90f1..e0c158b 100644--- a/public/locales/ha.json+++ b/public/locales/ha.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/hi.json b/public/locales/hi.jsonindex 2b172af..a1af00f 100644--- a/public/locales/hi.json+++ b/public/locales/hi.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/id.json b/public/locales/id.jsonindex fb2bb84..4d56110 100644--- a/public/locales/id.json+++ b/public/locales/id.json@@ -1997,6 +1997,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/it.json b/public/locales/it.jsonindex 1dfbcb1..b4f9fb9 100644--- a/public/locales/it.json+++ b/public/locales/it.json@@ -2027,6 +2027,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/ja.json b/public/locales/ja.jsonindex dce1760..1eed98d 100644--- a/public/locales/ja.json+++ b/public/locales/ja.json@@ -1997,6 +1997,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/kn.json b/public/locales/kn.jsonindex 72e9d57..8b1e1d5 100644--- a/public/locales/kn.json+++ b/public/locales/kn.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/ko.json b/public/locales/ko.jsonindex dc221f3..e51c4b5 100644--- a/public/locales/ko.json+++ b/public/locales/ko.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/ml.json b/public/locales/ml.jsonindex c804b33..8a44ef0 100644--- a/public/locales/ml.json+++ b/public/locales/ml.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/mr.json b/public/locales/mr.jsonindex 6c33754..6fd900f 100644--- a/public/locales/mr.json+++ b/public/locales/mr.json@@ -2010,6 +2010,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/ms.json b/public/locales/ms.jsonindex 3bbe87d..e50a278 100644--- a/public/locales/ms.json+++ b/public/locales/ms.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/nl.json b/public/locales/nl.jsonindex a44d9cc..66a286f 100644--- a/public/locales/nl.json+++ b/public/locales/nl.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/pa.json b/public/locales/pa.jsonindex 372d235..057c6c1 100644--- a/public/locales/pa.json+++ b/public/locales/pa.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/pl.json b/public/locales/pl.jsonindex 1edc47c..6a2e7ef 100644--- a/public/locales/pl.json+++ b/public/locales/pl.json@@ -2042,6 +2042,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/pt-BR.json b/public/locales/pt-BR.jsonindex 4236d4f..3ba6836 100644--- a/public/locales/pt-BR.json+++ b/public/locales/pt-BR.json@@ -2027,6 +2027,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/pt-PT.json b/public/locales/pt-PT.jsonindex d247e4f..5e27e2e 100644--- a/public/locales/pt-PT.json+++ b/public/locales/pt-PT.json@@ -2027,6 +2027,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/ru.json b/public/locales/ru.jsonindex 12fa4fc..b3a6a3f 100644--- a/public/locales/ru.json+++ b/public/locales/ru.json@@ -2042,6 +2042,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/si.json b/public/locales/si.jsonindex 2041345..4e6cb02 100644--- a/public/locales/si.json+++ b/public/locales/si.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/sw.json b/public/locales/sw.jsonindex da3dc6f..c00b3ce 100644--- a/public/locales/sw.json+++ b/public/locales/sw.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/ta.json b/public/locales/ta.jsonindex 13193ac..26c4865 100644--- a/public/locales/ta.json+++ b/public/locales/ta.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/te.json b/public/locales/te.jsonindex fbeebd5..9ce3c10 100644--- a/public/locales/te.json+++ b/public/locales/te.json@@ -2010,6 +2010,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/th.json b/public/locales/th.jsonindex f5fb17a..97a1fc0 100644--- a/public/locales/th.json+++ b/public/locales/th.json@@ -2012,6 +2012,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/tr.json b/public/locales/tr.jsonindex a9fcedc..6428f90 100644--- a/public/locales/tr.json+++ b/public/locales/tr.json@@ -1961,6 +1961,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/uk.json b/public/locales/uk.jsonindex cb3e867..d5c4a4c 100644--- a/public/locales/uk.json+++ b/public/locales/uk.json@@ -2042,6 +2042,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/ur.json b/public/locales/ur.jsonindex 5f4731e..c38ae87 100644--- a/public/locales/ur.json+++ b/public/locales/ur.json@@ -2010,6 +2010,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/vi.json b/public/locales/vi.jsonindex 1e85c5f..1270ee6 100644--- a/public/locales/vi.json+++ b/public/locales/vi.json@@ -1997,6 +1997,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/public/locales/zh-CN.json b/public/locales/zh-CN.jsonindex 4db3e72..f0f58ed 100644--- a/public/locales/zh-CN.json+++ b/public/locales/zh-CN.json@@ -1997,6 +1997,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/src/app/(settings)/settings/import/page.tsx b/src/app/(settings)/settings/import/page.tsxindex bf9d3ee..979f92e 100644--- a/src/app/(settings)/settings/import/page.tsx+++ b/src/app/(settings)/settings/import/page.tsx@@ -197,6 +197,8 @@ export default function SettingsImportPage() {</p></div> */}+ <ImportJobs refreshKey={jobsRefresh} />+<section className="space-y-4"><div><h2 className="text-xl font-semibold text-neutral-900">@@ -492,7 +494,6 @@ export default function SettingsImportPage() {</CardContent></div></section>- <ImportJobs refreshKey={jobsRefresh} /></div>);}diff --git a/src/components/settings/import-jobs.tsx b/src/components/settings/import-jobs.tsxindex 5c9d04e..80e4539 100644--- a/src/components/settings/import-jobs.tsx+++ b/src/components/settings/import-jobs.tsx@@ -1,6 +1,7 @@"use client";import { useCallback, useEffect, useRef, useState } from "react";+import { Loader2 } from "lucide-react";import { useLanguage } from "@/components/language-provider";import { Button } from "@/components/ui/button";import type { ImportJobSummary } from "@/lib/import/jobs-types";@@ -63,10 +64,12 @@ export function ImportJobs({ refreshKey }: { refreshKey: number }) {return (<section className="space-y-4" aria-live="polite">- <div>- <h2 className="text-xl font-semibold text-neutral-900">{t("importJobs.title")}</h2>- <p className="mt-1 text-sm text-neutral-500">{t("importJobs.description")}</p>- </div>+ {hasActive && (+ <p className="flex items-center gap-2 text-sm text-neutral-600">+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />+ {t("importJobs.running")}+ </p>+ )}<ul className="space-y-3">{jobs.map((job) => {const percent = getImportJobPercent(job);@@ -111,12 +114,19 @@ export function ImportJobs({ refreshKey }: { refreshKey: number }) {</div>)}<p className="text-xs text-neutral-500">- {t("importJobs.counts", {- processed: job.processed,- total: job.total,- imported: job.imported,- skipped: job.skipped,- })}+ {active && job.total <= 0 ? (+ <span className="inline-flex items-center gap-1.5">+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />+ {t("importJobs.counting")}+ </span>+ ) : (+ t("importJobs.counts", {+ processed: job.processed,+ total: job.total,+ imported: job.imported,+ skipped: job.skipped,+ })+ )}</p>{job.error && (<p className="rounded-lg border border-red-100 bg-red-50 px-3 py-2 text-xs text-red-700">{job.error}</p>diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex f885c64..2fc1d59 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -2018,6 +2018,8 @@"importJobs.description": "Imports keep running on the server, so you can leave this page.","importJobs.started": "Import started. Follow its progress under Imports.","importJobs.waiting": "Waiting to start",+ "importJobs.running": "An import is running",+ "importJobs.counting": "Counting messages…","importJobs.cancel": "Cancel","importJobs.dismiss": "Dismiss","importJobs.status.queued": "Queued",diff --git a/src/lib/import/imap-utils.ts b/src/lib/import/imap-utils.tsindex 2ddd572..7383662 100644--- a/src/lib/import/imap-utils.ts+++ b/src/lib/import/imap-utils.ts@@ -29,6 +29,66 @@ export function selectImapUidBatch(allUids: string[], limit: number, offset: numreturn { uids: allUids.slice(start, end), total, nextOffset };}+/**+ * Messages to fetch in one chunk. `size` is the size the job settled on after+ * earlier trouble; every redelivery of the same queue message (`attempt` > 1,+ * e.g. the Worker died with a resource-limit 503) halves it again.+ */+export function getImapChunkSize(base: number, size: number | undefined, attempt = 1): number {+ const current = Math.min(Math.max(Math.floor(size ?? base) || base, 1), base);+ return Math.max(1, Math.floor(current / 2 ** Math.max(attempt - 1, 0)));+}++/** After a clean chunk, climb back towards `base` gradually rather than all at once. */+export function growImapChunkSize(base: number, size: number): number {+ return size >= base ? base : Math.min(base, size + Math.max(1, Math.floor(size / 2)));+}++/** Errors a smaller batch cannot fix: bad credentials, lost settings. */+export function isPermanentImapError(message: string): boolean {+ return /login|auth|credential|not allowed|unreadable|no longer exists/i.test(message);+}++/** FETCH commands sent back to back, and the raw mail one group may hold before the next is requested. */+const IMAP_PIPELINE_COUNT = 10;+const IMAP_PIPELINE_BYTES = 4 * 1024 * 1024;+// Every fetched message is held in memory and then parsed and stored within one+// Worker request, so a batch stops early once it holds this much raw mail.+export const MAX_IMAP_BATCH_BYTES = 20 * 1024 * 1024;++/**+ * Splits UIDs (newest first) into groups to pipeline, dropping the tail that would+ * push the batch past the memory budget. A UID with an unknown size travels alone.+ */+export function planImapFetchGroups(uids: string[], sizes: Map<string, number>): string[][] {+ const groups: string[][] = [];+ let current: string[] = [];+ let currentBytes = 0;+ let planned = 0;+ for (const uid of uids) {+ if (planned >= MAX_IMAP_BATCH_BYTES) break;+ const size = sizes.get(uid);+ if (size === undefined) {+ if (current.length) groups.push(current);+ groups.push([uid]);+ current = [];+ currentBytes = 0;+ planned = MAX_IMAP_BATCH_BYTES;+ continue;+ }+ current.push(uid);+ currentBytes += size;+ planned += size;+ if (current.length >= IMAP_PIPELINE_COUNT || currentBytes >= IMAP_PIPELINE_BYTES) {+ groups.push(current);+ current = [];+ currentBytes = 0;+ }+ }+ if (current.length) groups.push(current);+ return groups;+}+export function getLiteralLength(line: string): number | null {const match = line.match(/\{(\d+)\}$/);return match ? Number(match[1]) : null;diff --git a/src/lib/import/imap.ts b/src/lib/import/imap.tsindex aa679a6..5be0780 100644--- a/src/lib/import/imap.ts+++ b/src/lib/import/imap.ts@@ -3,6 +3,7 @@ import type { ImapImportInput } from "./imap-types";import {assertSafeImapHost,getLiteralLength,+ planImapFetchGroups,isTaggedCompletion,parseFetchFlags,parseListMailboxName,@@ -11,10 +12,6 @@ import {selectImapUidBatch,} from "./imap-utils";-// Every fetched message is held in memory and then parsed and stored within one-// Worker request, so a batch stops early once it holds this much raw mail.-const MAX_IMAP_BATCH_BYTES = 20 * 1024 * 1024;-type CloudflareSocketConnect = (address: { hostname: string; port: number },options: { secureTransport: "on" | "off"; allowHalfOpen: boolean },@@ -81,10 +78,34 @@ class ImapConnection {}}- async fetchMessage(uid: string): Promise<{ raw: ArrayBuffer; flags: string[] }> {- const tag = this.nextTag();+ /** Sizes in bytes by UID, so a batch can be planned against the memory budget before any body is read. */+ async fetchSizes(uids: string[]): Promise<Map<string, number>> {+ const sizes = new Map<string, number>();+ if (!uids.length) return sizes;+ for (const line of await this.command(`UID FETCH ${uids.join(",")} (RFC822.SIZE)`)) {+ const uid = line.match(/\bUID (\d+)/i)?.[1];+ const size = line.match(/\bRFC822\.SIZE (\d+)/i)?.[1];+ if (uid && size) sizes.set(uid, Number(size));+ }+ return sizes;+ }++ /**+ * Sends every FETCH before reading any reply, so a group costs one round trip+ * instead of one per message. Replies come back in command order.+ */+ async fetchMessages(uids: string[]): Promise<{ uid: string; raw: ArrayBuffer; flags: string[] }[]> {+ const tags = uids.map(() => this.nextTag());// BODY.PEEK[] leaves the source's \Seen flag untouched, unlike RFC822.- await this.write(`${tag} UID FETCH ${uid} (FLAGS BODY.PEEK[])\r\n`);+ await this.write(uids.map((uid, index) => `${tags[index]} UID FETCH ${uid} (FLAGS BODY.PEEK[])\r\n`).join(""));+ const fetched: { uid: string; raw: ArrayBuffer; flags: string[] }[] = [];+ for (const [index, uid] of uids.entries()) {+ fetched.push({ uid, ...(await this.readFetchReply(tags[index])) });+ }+ return fetched;+ }++ private async readFetchReply(tag: string): Promise<{ raw: ArrayBuffer; flags: string[] }> {let raw: ArrayBuffer | null = null;let flags: string[] = [];@@ -195,17 +216,17 @@ export async function fetchImapMessages(input: ImapImportInput): Promise<ImapFetconst searchLines = await imap.command("UID SEARCH ALL");const batch = selectImapUidBatch(searchLines.flatMap(parseSearchUids), input.limit, input.offset);const messages: ImportMessageInput[] = [];- let fetchedBytes = 0;- for (const uid of [...batch.uids].reverse()) {- if (messages.length > 0 && fetchedBytes >= MAX_IMAP_BATCH_BYTES) break;- const { raw, flags } = await imap.fetchMessage(uid);- fetchedBytes += raw.byteLength;- messages.push({- filename: `${input.folder}-${uid}.eml`,- raw,- read: flags.includes("\\SEEN"),- starred: flags.includes("\\FLAGGED"),- });+ const newestFirst = [...batch.uids].reverse();+ const sizes = await imap.fetchSizes(newestFirst);+ for (const group of planImapFetchGroups(newestFirst, sizes)) {+ for (const { uid, raw, flags } of await imap.fetchMessages(group)) {+ messages.push({+ filename: `${input.folder}-${uid}.eml`,+ raw,+ read: flags.includes("\\SEEN"),+ starred: flags.includes("\\FLAGGED"),+ });+ }}await imap.command("LOGOUT").catch(() => undefined);const complete = messages.length === batch.uids.length;diff --git a/src/lib/import/jobs-types.d.ts b/src/lib/import/jobs-types.d.tsindex 1ab22f2..59e8839 100644--- a/src/lib/import/jobs-types.d.ts+++ b/src/lib/import/jobs-types.d.ts@@ -52,10 +52,16 @@ export type ImapImportCursor = {done: number;/** Whether the current source's size was added to the job total. */counted: boolean;+ /** Chunk size after earlier failures; absent means the default. */+ size?: number;+ /** Consecutive failed chunks. */+ failures?: number;};export type ImportJobMessage = {kind: "import.run";jobId: string;imapPassword?: string;+ /** Delivery count from the queue; set by the consumer, never stored. */+ attempt?: number;};diff --git a/src/lib/import/jobs.ts b/src/lib/import/jobs.tsindex 69e9575..2f6a443 100644--- a/src/lib/import/jobs.ts+++ b/src/lib/import/jobs.ts@@ -4,6 +4,7 @@ import { importJobs, mailboxes } from "@/db/schema";import { newId } from "@/lib/ids";import { getImportMessageUserId, parseImportDestination } from "./destination";import { fetchImapMessages } from "./imap";+import { getImapChunkSize, growImapChunkSize, isPermanentImapError } from "./imap-utils";import { deleteStagedImport, importBatchKey, stageImportMessages, unpackImportMessages } from "./staging";import { importMessagesToMailbox } from "./service";import type {@@ -21,6 +22,8 @@ const ACTIVE = ["queued", "running"] as const;const MAX_STORED_ERRORS = 20;/** IMAP messages fetched per queue message; the connection is reopened for each. */const IMAP_CHUNK_SIZE = 50;+/** Consecutive failed IMAP chunks, each retried smaller, before the job gives up. */+const MAX_IMAP_FAILURES = 4;const STALE_AFTER_MS = 30 * 60 * 1000;const KEEP_FINISHED_MS = 7 * 24 * 60 * 60 * 1000;@@ -178,7 +181,8 @@ export async function cancelOrDismissImportJob(env: CloudflareEnv, userId: strin}/** Runs one chunk of a job and queues the next. Never throws for import failures; they land on the job. */-export async function processImportJob(env: CloudflareEnv, message: ImportJobMessage): Promise<void> {+export async function processImportJob(env: CloudflareEnv, delivered: ImportJobMessage): Promise<void> {+ const { attempt, ...message } = delivered;const db = getDb(env);const [job] = await db.select().from(importJobs).where(eq(importJobs.id, message.jobId)).limit(1);if (!job || (job.status !== "queued" && job.status !== "running")) return;@@ -192,14 +196,16 @@ export async function processImportJob(env: CloudflareEnv, message: ImportJobMeslet chunk: Chunk;try {- chunk = job.kind === "file" ? await runFileChunk(env, job) : await runImapChunk(env, job, message.imapPassword);+ chunk = job.kind === "file" ? await runFileChunk(env, job) : await runImapChunk(env, job, message.imapPassword, attempt);} catch (error) {+ const reason = error instanceof Error ? error.message : "Import failed";+ if (job.kind === "imap" && (await retryImapChunkSmaller(env, job, message, reason))) return;const now = new Date();await db.update(importJobs).set({status: "failed",- error: error instanceof Error ? error.message : "Import failed",+ error: reason,finishedAt: now,updatedAt: now,})@@ -232,6 +238,33 @@ export async function processImportJob(env: CloudflareEnv, message: ImportJobMesif (!chunk.done) await enqueue(env, message);}+/** Records the failure, halves the chunk size and queues the same chunk again. False when the job should fail instead. */+async function retryImapChunkSmaller(+ env: CloudflareEnv,+ job: JobRow,+ message: ImportJobMessage,+ reason: string,+): Promise<boolean> {+ if (isPermanentImapError(reason)) return false;+ const cursor = parseJson<ImapImportCursor>(job.cursor, { source: 0, done: 0, counted: false });+ const failures = (cursor.failures ?? 0) + 1;+ if (failures >= MAX_IMAP_FAILURES) return false;+ const spec = parseJson<ImapImportSpec | null>(job.spec, null);+ const base = spec ? imapBaseChunkSize(spec, cursor) : IMAP_CHUNK_SIZE;+ const next: ImapImportCursor = { ...cursor, failures, size: Math.max(1, Math.floor(getImapChunkSize(base, cursor.size) / 2)) };+ const recorded = await getDb(env)+ .update(importJobs)+ .set({ cursor: JSON.stringify(next), updatedAt: new Date() })+ .where(and(eq(importJobs.id, job.id), inArray(importJobs.status, [...ACTIVE])))+ .returning({ id: importJobs.id });+ if (recorded.length) await enqueue(env, message);+ return true;+}++function imapBaseChunkSize(spec: ImapImportSpec, cursor: ImapImportCursor): number {+ return Math.min(IMAP_CHUNK_SIZE, spec.importAll ? spec.limit : spec.limit - cursor.done);+}+async function getImportUserId(env: CloudflareEnv, job: JobRow, destinationValue: string): Promise<string> {const [mailbox] = await getDb(env).select({ userId: mailboxes.userId })@@ -259,7 +292,12 @@ async function runFileChunk(env: CloudflareEnv, job: JobRow): Promise<Chunk> {return { result, cursor: { batch: next }, totalDelta: 0, done: next >= spec.batches, consumedKey: key };}-async function runImapChunk(env: CloudflareEnv, job: JobRow, password: string | undefined): Promise<Chunk> {+async function runImapChunk(+ env: CloudflareEnv,+ job: JobRow,+ password: string | undefined,+ attempt?: number,+): Promise<Chunk> {if (!password) throw new Error("IMAP credentials were lost; start the import again");const spec = parseJson<ImapImportSpec | null>(job.spec, null);if (!spec) throw new Error("Import settings are unreadable");@@ -268,7 +306,8 @@ async function runImapChunk(env: CloudflareEnv, job: JobRow, password: string |const empty: ImportMailboxResult = { imported: 0, skipped: 0, errors: [] };if (!source) return { result: empty, cursor, totalDelta: 0, done: true };- const batchSize = Math.min(IMAP_CHUNK_SIZE, spec.importAll ? spec.limit : spec.limit - cursor.done);+ const base = imapBaseChunkSize(spec, cursor);+ const batchSize = base > 0 ? getImapChunkSize(base, cursor.size, attempt) : 0;const fetched =batchSize > 0? await fetchImapMessages({@@ -293,15 +332,16 @@ async function runImapChunk(env: CloudflareEnv, job: JobRow, password: string |: empty;const done = cursor.done + fetched.messages.length;+ const grown = batchSize > 0 ? growImapChunkSize(IMAP_CHUNK_SIZE, batchSize) : undefined;const totalDelta = cursor.counted ? 0 : spec.importAll ? fetched.total : Math.min(spec.limit, fetched.total);const sourceFinished = fetched.nextOffset === null || fetched.messages.length === 0 || (!spec.importAll && done >= spec.limit);if (!sourceFinished) {- return { result, cursor: { source: cursor.source, done, counted: true }, totalDelta, done: false };+ return { result, cursor: { source: cursor.source, done, counted: true, size: grown }, totalDelta, done: false };}const nextSource = cursor.source + 1;return {result,- cursor: { source: nextSource, done: 0, counted: false },+ cursor: { source: nextSource, done: 0, counted: false, size: grown },totalDelta,done: nextSource >= spec.sources.length,};diff --git a/src/lib/import/message-hints-utils.ts b/src/lib/import/message-hints-utils.tsnew file mode 100644index 0000000..3cacf69--- /dev/null+++ b/src/lib/import/message-hints-utils.ts@@ -0,0 +1,57 @@+// The explicit extension lets the node:test suite load this file directly.+// @ts-expect-error TS5097: allowImportingTsExtensions is off+import { mapGmailLabels, parseGmailLabels } from "./gmail-takeout-utils.ts";+import type { ImportDestination } from "./destination-types";++export type ImportMessageHints = {+ read?: boolean;+ starred?: boolean;+ /** Set only when the message itself says it belongs in spam or trash. */+ section?: "spam" | "trash";+};++function readHeaders(raw: ArrayBuffer): string {+ const bytes = new Uint8Array(raw);+ let end = Math.min(bytes.length, 64 * 1024);+ for (let index = 0; index < end - 1; index += 1) {+ if (bytes[index] === 10 && (bytes[index + 1] === 10 || (bytes[index + 1] === 13 && bytes[index + 2] === 10))) {+ end = index;+ break;+ }+ }+ return new TextDecoder().decode(bytes.subarray(0, end)).replace(/\r?\n[ \t]+/g, " ");+}++/**+ * Exports carry their own state: mbox `Status`, Gmail labels, spam-filter verdicts.+ * Used where the upload gave no per-message flags.+ */+export function getImportMessageHints(raw: ArrayBuffer): ImportMessageHints {+ const hints: ImportMessageHints = {};+ const headers = readHeaders(raw);++ const status = headers.match(/^Status:[ \t]*(.*)$/im);+ if (status) hints.read = status[1].toUpperCase().includes("R");++ const labels = parseGmailLabels(new Uint8Array(raw));+ if (labels.length) {+ const placement = mapGmailLabels(labels, { folders: false });+ hints.read = placement.read;+ hints.starred = placement.starred;+ const destination = placement.destination;+ if (destination.type === "system" && (destination.section === "spam" || destination.section === "trash")) {+ hints.section = destination.section;+ }+ }++ if (!hints.section && /^X-Spam-Flag:[ \t]*yes\b/im.test(headers)) hints.section = "spam";+ return hints;+}++/** A hint only refines the default destination; a section or folder the user picked is kept. */+export function applyImportHints(destination: ImportDestination, hints: ImportMessageHints): ImportDestination {+ if (hints.section && destination.type === "system" && destination.section === "inbox") {+ return { type: "system", section: hints.section };+ }+ return destination;+}diff --git a/src/lib/import/service.ts b/src/lib/import/service.tsindex 1caf466..662080c 100644--- a/src/lib/import/service.ts+++ b/src/lib/import/service.ts@@ -9,6 +9,7 @@ import { upsertContactFromAddress } from "@/lib/contacts/service";import { newId } from "@/lib/ids";import { getImportMessagePlacement } from "./destination";import type { ImportDestination } from "./destination-types";+import { applyImportHints, getImportMessageHints } from "./message-hints-utils";import type { ImportMailboxResult, ImportMessageInput } from "./types";export async function importMessagesToMailbox(@@ -81,7 +82,10 @@ async function importMessageToMailbox(const fromAddr = parsed.fromAddr ?? "unknown";const toAddr = parsed.toAddr ?? "";const createdAt = parsed.date ?? new Date();- const placement = getImportMessagePlacement(input.destination);+ const hints = getImportMessageHints(input.raw);+ const placement = getImportMessagePlacement(applyImportHints(input.destination, hints));+ const read = input.read ?? hints.read ?? placement.direction === "outbound";+ const starred = input.starred ?? hints.starred ?? false;await db.insert(messages).values({id: messageId,@@ -100,8 +104,8 @@ async function importMessageToMailbox(htmlBody: parsed.html,rawR2Key,status: placement.status,- read: input.read ?? placement.direction === "outbound",- starred: input.starred ?? false,+ read,+ starred,threadId: await resolveThreadId(db, {mailboxId: input.mailboxId,messageId: parsed.messageId,diff --git a/tests/imap-chunk-size.test.mjs b/tests/imap-chunk-size.test.mjsnew file mode 100644index 0000000..a6cc6a8--- /dev/null+++ b/tests/imap-chunk-size.test.mjs@@ -0,0 +1,37 @@+import assert from "node:assert/strict";+import test from "node:test";++import { getImapChunkSize, planImapFetchGroups, growImapChunkSize, isPermanentImapError } from "../src/lib/import/imap-utils.ts";++test("chunk size defaults to the base and never exceeds it", () => {+ assert.equal(getImapChunkSize(50, undefined), 50);+ assert.equal(getImapChunkSize(50, 500), 50);+});++test("each redelivery halves the chunk, down to one message", () => {+ assert.equal(getImapChunkSize(50, undefined, 2), 25);+ assert.equal(getImapChunkSize(50, 20, 3), 5);+ assert.equal(getImapChunkSize(50, 3, 9), 1);+});++test("a clean chunk climbs back towards the base", () => {+ assert.equal(growImapChunkSize(50, 1), 2);+ assert.equal(growImapChunkSize(50, 20), 30);+ assert.equal(growImapChunkSize(50, 40), 50);+ assert.equal(growImapChunkSize(50, 50), 50);+});++test("credential errors are not retried smaller", () => {+ assert.equal(isPermanentImapError("IMAP command failed: A0002 NO [AUTHENTICATIONFAILED] Invalid credentials"), true);+ assert.equal(isPermanentImapError("IMAP connection closed unexpectedly"), false);+});++test("fetch groups pipeline small mail, split big mail and drop the tail past the budget", () => {+ const mb = 1024 * 1024;+ const uids = ["5", "4", "3", "2", "1"];+ const small = new Map(uids.map((uid) => [uid, 1000]));+ assert.deepEqual(planImapFetchGroups(uids, small), [uids]);+ const big = new Map([["5", 8 * mb], ["4", 2 * mb], ["3", 8 * mb], ["2", 8 * mb], ["1", 8 * mb]]);+ assert.deepEqual(planImapFetchGroups(uids, big).flat(), ["5", "4", "3", "2"]);+ assert.deepEqual(planImapFetchGroups(["2", "1"], new Map([["1", 5]])), [["2"]]);+});diff --git a/tests/imap-fetch.test.mjs b/tests/imap-fetch.test.mjsindex 926e412..1256971 100644--- a/tests/imap-fetch.test.mjs+++ b/tests/imap-fetch.test.mjs@@ -68,22 +68,28 @@ function startServer(messages) {send("* OK ready\r\n");const writable = new WritableStream({write(chunk) {- const line = Buffer.from(chunk).toString().trim();- commands.push(line);- const [tag, ...rest] = line.split(" ");- const command = rest.join(" ");- if (command.startsWith("UID SEARCH")) send(`* SEARCH ${Object.keys(messages).join(" ")}\r\n`);- const fetch = command.match(/^UID FETCH (\d+)/);- if (fetch) {- const { body, flags, flagsAfterBody } = messages[fetch[1]];- const head = `* ${fetch[1]} FETCH (UID ${fetch[1]} `;- send(- flagsAfterBody- ? Buffer.concat([Buffer.from(`${head}BODY[] {${body.length}}\r\n`), body, Buffer.from(` FLAGS (${flags}))\r\n`)])- : Buffer.concat([Buffer.from(`${head}FLAGS (${flags}) BODY[] {${body.length}}\r\n`), body, Buffer.from(")\r\n")]),- );+ // Pipelined commands arrive in one write, so answer each line in order.+ for (const line of Buffer.from(chunk).toString().split("\r\n").filter(Boolean)) {+ commands.push(line);+ const [tag, ...rest] = line.split(" ");+ const command = rest.join(" ");+ if (command.startsWith("UID SEARCH")) send(`* SEARCH ${Object.keys(messages).join(" ")}\r\n`);+ const sizes = command.match(/^UID FETCH ([\d,]+) \(RFC822\.SIZE\)/);+ if (sizes) {+ for (const uid of sizes[1].split(",")) send(`* ${uid} FETCH (UID ${uid} RFC822.SIZE ${messages[uid].body.length})\r\n`);+ }+ const fetch = command.match(/^UID FETCH (\d+) \(FLAGS/);+ if (fetch) {+ const { body, flags, flagsAfterBody } = messages[fetch[1]];+ const head = `* ${fetch[1]} FETCH (UID ${fetch[1]} `;+ send(+ flagsAfterBody+ ? Buffer.concat([Buffer.from(`${head}BODY[] {${body.length}}\r\n`), body, Buffer.from(` FLAGS (${flags}))\r\n`)])+ : Buffer.concat([Buffer.from(`${head}FLAGS (${flags}) BODY[] {${body.length}}\r\n`), body, Buffer.from(")\r\n")]),+ );+ }+ send(`${tag} OK done\r\n`);}- send(`${tag} OK done\r\n`);},});return { readable, writable };@@ -125,7 +131,8 @@ test("imports keep read and starred state without marking the source read", asyn);assert.ok(commands.some((line) => line.includes("EXAMINE")));assert.ok(!commands.some((line) => / SELECT /.test(line)));- assert.ok(commands.filter((line) => line.includes("UID FETCH")).every((line) => line.includes("BODY.PEEK[]")));+ assert.ok(commands.filter((line) => line.includes("FLAGS BODY")).every((line) => line.includes("BODY.PEEK[]")));+ assert.equal(commands.filter((line) => line.includes("RFC822.SIZE")).length, 1);});test("large messages arrive intact and a batch stops at the byte budget", async () => {diff --git a/tests/import-message-hints.test.mjs b/tests/import-message-hints.test.mjsnew file mode 100644index 0000000..b5f4e13--- /dev/null+++ b/tests/import-message-hints.test.mjs@@ -0,0 +1,26 @@+import test from "node:test";+import assert from "node:assert/strict";+import { applyImportHints, getImportMessageHints } from "../src/lib/import/message-hints-utils.ts";++const raw = (headers) => new TextEncoder().encode(`${headers}\n\nbody`).buffer;++test("mbox Status header sets read state", () => {+ assert.equal(getImportMessageHints(raw("Status: RO\nSubject: a")).read, true);+ assert.equal(getImportMessageHints(raw("Status: O\nSubject: a")).read, false);+ assert.equal(getImportMessageHints(raw("Subject: a")).read, undefined);+});++test("Gmail labels and spam flag pick spam or trash", () => {+ assert.equal(getImportMessageHints(raw("X-Gmail-Labels: Spam,Unread")).section, "spam");+ assert.equal(getImportMessageHints(raw("X-Gmail-Labels: Spam,Unread")).read, false);+ assert.equal(getImportMessageHints(raw("X-Gmail-Labels: Trash")).section, "trash");+ assert.equal(getImportMessageHints(raw("X-Spam-Flag: YES")).section, "spam");+ assert.equal(getImportMessageHints(raw("X-Gmail-Labels: Inbox")).section, undefined);+});++test("hints only refine the inbox destination", () => {+ const spam = { section: "spam" };+ assert.deepEqual(applyImportHints({ type: "system", section: "inbox" }, spam), { type: "system", section: "spam" });+ assert.deepEqual(applyImportHints({ type: "system", section: "sent" }, spam), { type: "system", section: "sent" });+ assert.deepEqual(applyImportHints({ type: "folder", folderId: "f" }, spam), { type: "folder", folderId: "f" });+});diff --git a/worker.ts b/worker.tsindex b7f15ba..2d72196 100644--- a/worker.ts+++ b/worker.ts@@ -115,7 +115,7 @@ export default {} else if (isWebhookRetryMessage(msg.body)) {await processWebhookRetry(env, msg.body as WebhookRetryMessage);} else if (isImportJobMessage(msg.body)) {- await processImportJob(env, msg.body);+ await processImportJob(env, { ...msg.body, attempt: msg.attempts });} else if (typeof msg.body === "object" && msg.body !== null && (msg.body as { kind?: unknown }).kind === "email.scheduled") {await processOutboundQueue(env, msg.body as OutboundQueueMessage);} else {