Files
mailflare/server/runtime/queue.ts
T
Oday BakkourandClaude Fable 5.1 f0dc5a16fc feat(self-host): run Mailflare as a Docker container on any host
Adds a second runtime next to Cloudflare Workers. One Node process serves
the Next app, a realtime WebSocket hub, the job queues, the backup schedule
and an SMTP listener; SQLite and local files replace D1 and R2. The
application code is unchanged: the runtime builds an object with the same
binding interfaces (`server/runtime/`) and publishes it before Next starts,
so `getEnv()` hands route handlers the same shape on both platforms.

Runtime (server/)
- `sqlite-database.ts`: the D1 API over better-sqlite3, so Drizzle's D1
  driver, the raw `env.DB.prepare` callers, the FTS5 index and its triggers
  all work as-is. Migrations are applied from drizzle/migrations at start,
  recorded in `d1_migrations` like Wrangler does.
- `file-bucket.ts`: the R2 API over a directory, with metadata sidecars and
  byte ranges. `mailer.ts`: the send_email builder over nodemailer (any SMTP
  relay) or Cloudflare's Email Sending REST API; generates the Message-ID so
  threading matches Workers. `queue.ts`: in-process queues with the same
  retry policy. `realtime.ts`: per-user WebSocket fan-out in place of the
  Durable Object. `misc.ts`: rate limiter and ASSETS fetcher.
- `smtp.ts`: inbound SMTP on port 25 via smtp-server; reject rules answer
  550, forward rules relay the raw message through the outbound SMTP.
- `index.ts`: the custom server; `scripts/build-server.mjs` bundles it with
  esbuild to dist/server.mjs.

Application changes
- `src/lib/runtime.ts` + `getEnv()` prefer the Node env when present.
- `src/lib/email/intake.ts` factors the Worker email handler's logic so the
  SMTP listener and the new signed `/api/inbound` webhook share it.
- Domains without Cloudflare credentials are recorded with zone id
  "manual": Cloudflare calls no-op, the domain is active at once, and the
  DNS page lists MX/SPF/DMARC records to create. Setup checks, the domains
  page copy and the self-update button adapt to the runtime; `/api/auth/me`
  exposes `runtime` and `managesDns`.
- `APP_URL` overrides the origin for reset links and the JMAP session
  behind a proxy. The direct `getCloudflareContext` import in the update
  route is replaced with `getEnv()`.

Deployment
- Dockerfile (multi-stage, 1.1 GB, Workers toolchain pruned), compose file,
  `.env.docker.example`, `docs/self-hosting.md`, README section.
- `deploy/cloudflare-email-relay`: a Worker that keeps MX on Cloudflare
  Email Routing and posts messages to the server with an HMAC signature,
  acting on the reject/forward decision it returns.

Verified on a fresh data directory and again inside the built image:
migrations apply, first-run setup and registration work with no Cloudflare
credentials, mail over SMTP lands in the inbox with the raw copy on disk,
a reject rule answers 550, a send through SMTP_URL loops back and is stored
as sent and received, an inbound reply threads with the sent copy, FTS
search finds body text, a backup completes to the volume, the WebSocket
delivers a push, the relay webhook rejects a bad signature and returns
store/reject decisions, JMAP serves a session with the APP_URL origin.
Container healthcheck reports healthy. tsc (11) and eslint (105) unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PGeWDVSkXtVEmDAN2AtB9h
2026-09-12 14:34:11 +03:00

68 lines
2.1 KiB
TypeScript

/**
* The Queue producer API with an in-process consumer. Delivery order and the
* retry policy match wrangler.jsonc (three retries, ten seconds apart on
* failure). Jobs live in memory: inbound mail is already on disk before it is
* enqueued, so a restart at worst leaves a message unprocessed in the blob
* store, never lost.
*/
export type QueueConsumer = (body: unknown) => Promise<void>;
type Pending = { body: unknown; attempts: number };
export class InProcessQueue {
private consumer: QueueConsumer | null = null;
private readonly maxRetries: number;
private readonly timers = new Set<ReturnType<typeof setTimeout>>();
constructor(readonly name: string, options?: { maxRetries?: number }) {
this.maxRetries = options?.maxRetries ?? 3;
}
setConsumer(consumer: QueueConsumer) {
this.consumer = consumer;
}
async send(body: unknown, options?: { delaySeconds?: number }) {
this.schedule({ body, attempts: 0 }, (options?.delaySeconds ?? 0) * 1000);
}
async sendBatch(messages: Iterable<{ body: unknown; delaySeconds?: number }>) {
for (const message of messages) await this.send(message.body, { delaySeconds: message.delaySeconds });
}
async metrics() {
return { backlogCount: this.timers.size };
}
private schedule(pending: Pending, delayMs: number) {
const timer = setTimeout(() => {
this.timers.delete(timer);
void this.deliver(pending);
}, delayMs);
this.timers.add(timer);
}
private async deliver(pending: Pending) {
if (!this.consumer) {
this.schedule(pending, 1000);
return;
}
try {
await this.consumer(pending.body);
} catch (error) {
console.error(`Queue ${this.name}: job failed`, error);
if (pending.attempts < this.maxRetries) this.schedule({ body: pending.body, attempts: pending.attempts + 1 }, 10_000);
else console.error(`Queue ${this.name}: giving up after ${this.maxRetries} retries`, pending.body);
}
}
stop() {
for (const timer of this.timers) clearTimeout(timer);
this.timers.clear();
}
}
export function openQueue<T>(name: string): Queue<T> & InProcessQueue {
return new InProcessQueue(name) as unknown as Queue<T> & InProcessQueue;
}