Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions .github/workflows/publish-email-queue.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: Publish email queue to npm

on:
push:
tags: ["email-queue-v*"]

permissions:
contents: read
id-token: write

jobs:
publish:
runs-on: ubuntu-latest
env:
EMAIL_QUEUE_TEST_REDIS_URL: redis://127.0.0.1:6379
services:
redis:
image: redis:8-alpine
ports:
- 6379:6379
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 3s
--health-retries 20
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.ref }}
- uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- uses: actions/setup-node@v4
with:
node-version: 22
registry-url: https://registry.npmjs.org
- run: bun install --frozen-lockfile
- run: bun x tsc --noEmit -p tsconfig.json
- run: bun test packages/email-queue/test
- name: Build and check tag version
working-directory: packages/email-queue
run: |
test "${GITHUB_REF_NAME#email-queue-v}" = "$(node -p 'require("./package.json").version')"
bun run build
- name: Publish
working-directory: packages/email-queue
run: npm publish --access public --provenance
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
14 changes: 13 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@ permissions:
jobs:
binaries:
runs-on: ubuntu-latest
env:
EMAIL_QUEUE_TEST_REDIS_URL: redis://127.0.0.1:6379
services:
redis:
image: redis:8-alpine
ports:
- 6379:6379
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 3s
--health-retries 20
steps:
- uses: actions/checkout@v4
with:
Expand All @@ -37,7 +49,7 @@ jobs:
run: bun x tsc --noEmit -p tsconfig.json

- name: Test
run: bun test packages/synconfig/test packages/core/test packages/plugin-outreachgraph/test packages/plugin-crawlproof/test packages/plugin-calendar/test packages/plugin-dashboard/test apps/cli/test apps/web/test
run: bun test packages/synconfig/test packages/core/test packages/email-queue/test packages/plugin-outreachgraph/test packages/plugin-crawlproof/test packages/plugin-calendar/test packages/plugin-dashboard/test apps/cli/test apps/web/test

# Bun cross-compiles every target from one runner, so there is no build
# matrix and no per-platform runner to keep in step.
Expand Down
77 changes: 60 additions & 17 deletions bun.lock

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion packages/core/src/core/mail/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export interface ResolveOptions extends ProviderDeps {
function queueGuard(sender: MailSender, smtpHost = ""): MailSender {
if (sender.type !== "resend" && !isGoogleSender(sender, smtpHost)) return sender;
return {
id: sender.id, type: sender.type, from: sender.from,
id: sender.id, type: sender.type, from: sender.from, google: isGoogleSender(sender, smtpHost),
batchSize: 1,
send: async (message, context) => {
const url = process.env.EMAIL_QUEUE_REDIS_URL ?? process.env.REDIS_URL ?? "";
Expand Down Expand Up @@ -156,6 +156,9 @@ export async function sendEach(
stop?: () => boolean;
} = {},
): Promise<MailResult[]> {
if (hooks.kind === "bulk" && sender.google) {
throw new Error("Bulk email must use Resend or another bulk provider; Gmail is reserved for one-off correspondence.");
}
const size = sender.sendBatch && sender.batchSize > 1 ? sender.batchSize : 1;
const results: MailResult[] = [];
for (let start = 0; start < messages.length; start += size) {
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/core/mail/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ export interface MailSender {
type: MailProviderType;
/** The sender used when a message names none. */
from?: string;
/** True when the transport routes through a Google mailbox. */
google?: boolean;
/** How many messages one API call may carry. 1 means no batch endpoint is used. */
batchSize: number;
send(message: MailMessage, options?: MailSendOptions): Promise<MailResult>;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/core/newsletter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -831,7 +831,7 @@ async function sendNewsletterUnlocked(id: string, options: SendNewsletterOptions
report.wouldSend.push(options.test);
return report;
}
const result = await sender.send({ ...message, to: [options.test] }, { kind: "bulk" });
const result = await sender.send({ ...message, to: [options.test] }, { kind: "transactional" });
if (result.ok) {
recordSent([{ at: now.toISOString(), kind: "email", to: options.test, via: sender.id, subject: message.subject, ok: true, id: result.id ?? msgId }]);
report.sent.push(options.test);
Expand Down
22 changes: 22 additions & 0 deletions packages/core/test/mail-providers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -594,3 +594,25 @@ test("sendEach batches where it can, calls before/after in order, pauses between
const stopped = await sendEach(batchy, [message(), message(), message()], { after: () => void (stop = true), stop: () => stop });
expect(stopped).toHaveLength(2);
});

test("sendEach refuses Gmail bulk mail before marking recipients pending", async () => {
let markedPending = false;
let delivered = false;
const gmail: MailSender = {
id: "gmail",
type: "smtp",
from: "[email protected]",
google: true,
batchSize: 1,
send: async () => {
delivered = true;
return { ok: true };
},
};
await expect(sendEach(gmail, [message()], {
kind: "bulk",
before: () => void (markedPending = true),
})).rejects.toThrow("Gmail is reserved for one-off correspondence");
expect(markedPending).toBe(false);
expect(delivered).toBe(false);
});
6 changes: 3 additions & 3 deletions packages/email-queue/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# @profullstack/email-queue

BullMQ + Redis rate-limited delivery of Gmail SMTP and Resend. Used by MyNaPoster.
BullMQ + Redis rate-limited delivery for MyNaPoster. Gmail is reserved for one-off correspondence; newsletters and other bulk mail must use Resend or another bulk provider.

## Safety defaults
- Gmail SMTP (including custom-domain mail through smtp.gmail.com): **100 emails per mailbox per 24 hours, one every 10 minutes**.
- Gmail SMTP (including custom-domain mail through smtp.gmail.com): **100 one-off emails per mailbox per 24 hours, one every 10 minutes**. Bulk sends are refused.
- Resend: **1,000 per From address per 24 hours, one per second** (lower according to your actual plan).
- Limits share Redis keys across processes. No provider credentials in jobs.
- Idempotent newsletter delivery keyed by issue + contact, with a retained receipt.
Expand All @@ -18,7 +18,7 @@ per-sender queue and rate limiter. Install Redis before resuming a newsletter bl
Existing Gmail restrictions must clear at Google's discretion.

Run \`bun install\` to resolve the new workspace dependencies and refresh \`bun.lock\` before merging.
Run \`bun run typecheck\` and \`bun test packages/core/test\` against Redis in CI.
Run \`bun run typecheck\` and \`bun test packages/email-queue/test\` against Redis in CI.

**Publish:** \`cd packages/email-queue && bun run build && npm publish --access public\`
before using this package outside the MyNaPoster workspace.
Expand Down
3 changes: 2 additions & 1 deletion packages/email-queue/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"dist"
],
"scripts": {
"build": "tsc -p tsconfig.build.json"
"build": "tsc -p tsconfig.build.json",
"test": "bun test test"
},
"dependencies": {
"bullmq": "^5.58.0",
Expand Down
7 changes: 5 additions & 2 deletions packages/email-queue/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
*/
import { createHash, randomUUID } from "node:crypto";
import { Queue, QueueEvents, Worker } from "bullmq";
import Redis from "ioredis";
import { Redis } from "ioredis";

export type EmailKind = "transactional" | "bulk";
export interface QueuedMessage {
Expand Down Expand Up @@ -100,12 +100,15 @@ export async function queuedDelivery(
options: EmailQueueOptions,
): Promise<DeliveryResult> {
if (!options.redisUrl) throw new Error("EMAIL_QUEUE_REDIS_URL is required; refusing direct Gmail/Resend bulk sending.");
if (kind === "bulk" && isGoogleSender(sender, options.smtpHost)) {
return { ok: false, retryable: false, status: 403, error: "Bulk email must use Resend or another bulk provider; Gmail is reserved for one-off correspondence." };
}
const identity = queueIdentity(sender, options.smtpHost);
const limits = senderLimits(sender, options.smtpHost, options);
const name = "profullstack-email-" + hash(identity).slice(0, 32);
const jobId = mailJobId(identity, message, kind);
const connect = () => new Redis(options.redisUrl, {
maxRetriesPerRequest: null, connectTimeout: 5000, retryStrategy: (attempt) => attempt <= 3 ? Math.min(attempt * 200, 1000) : null,
maxRetriesPerRequest: null, connectTimeout: 5000, retryStrategy: (attempt: number) => attempt <= 3 ? Math.min(attempt * 200, 1000) : null,
});
const producerRedis = connect();
const workerRedis = connect();
Expand Down
153 changes: 153 additions & 0 deletions packages/email-queue/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { describe, expect, it } from "bun:test";
import { randomUUID } from "node:crypto";
import {
isGoogleSender,
mailJobId,
queueIdentity,
queuedDelivery,
senderLimits,
type DeliveryTransport,
type QueuedMessage,
} from "../src/index.ts";

describe("email queue policy", () => {
it("recognizes personal Gmail and Gmail-hosted custom-domain senders", () => {
expect(isGoogleSender({ type: "smtp", from: "[email protected]" }, "smtp.gmail.com")).toBe(true);
expect(isGoogleSender({ type: "smtp", from: "[email protected]" }, "smtp.googlemail.com")).toBe(true);
expect(isGoogleSender({ type: "resend", from: "[email protected]" })).toBe(true);
expect(isGoogleSender({ type: "resend", from: "[email protected]" })).toBe(false);
});

it("enforces conservative sender budgets and never raises them with overrides", () => {
expect(senderLimits({ type: "smtp", from: "[email protected]" }, "smtp.gmail.com")).toEqual({
google: true,
maxPer24Hours: 100,
minGapMs: 600_000,
});
expect(senderLimits({ type: "resend", from: "[email protected]" }, "", {
maxPer24Hours: 10_000,
minGapMs: 1,
})).toEqual({ google: false, maxPer24Hours: 1000, minGapMs: 1000 });
});

it("scopes identity by sender and makes bulk recipient jobs idempotent", () => {
const sender = { id: "resend", type: "resend", from: "News <[email protected]>" };
const identity = queueIdentity(sender);
const base: QueuedMessage = {
from: sender.from,
to: ["[email protected]"],
subject: "Issue 1",
text: "Hello",
dedupeKey: "issue-1:contact-1",
};
expect(identity).toBe("resend|[email protected]");
expect(mailJobId(identity, base, "bulk")).toBe(mailJobId(identity, base, "bulk"));
expect(mailJobId(identity, base, "bulk")).not.toBe(mailJobId("resend|[email protected]", base, "bulk"));
expect(() => mailJobId(identity, { ...base, to: ["[email protected]", "[email protected]"] }, "bulk")).toThrow("exactly one recipient");
});

it("refuses Gmail bulk delivery before connecting to Redis or calling the provider", async () => {
let calls = 0;
const gmail: DeliveryTransport = {
id: "gmail",
type: "smtp",
from: "[email protected]",
async send() {
calls++;
return { ok: true };
},
};
const result = await queuedDelivery(gmail, {
from: gmail.from,
to: ["[email protected]"],
subject: "Bulk must use Resend",
text: "No external delivery",
}, "bulk", { redisUrl: "redis://127.0.0.1:1", smtpHost: "smtp.gmail.com" });
expect(result).toMatchObject({ ok: false, retryable: false, status: 403 });
expect(result.error).toContain("Gmail is reserved for one-off correspondence");
expect(calls).toBe(0);
});
});

const testRedisUrl = process.env.EMAIL_QUEUE_TEST_REDIS_URL;

if (testRedisUrl) {
describe("Redis-backed delivery", () => {
function fakeSender() {
const from = `queue-test-${randomUUID()}@example.test`;
let calls = 0;
const sender: DeliveryTransport = {
id: "fake-resend",
type: "resend",
from,
async send() {
calls++;
return { ok: true, id: `fake-${calls}` };
},
};
return { sender, get calls() { return calls; } };
}

it("delivers once and returns the durable receipt for a repeated issue recipient", async () => {
const fake = fakeSender();
const message: QueuedMessage = {
from: fake.sender.from,
to: [`person-${randomUUID()}@example.test`],
subject: "Queue test",
text: "No external delivery",
dedupeKey: `issue:${randomUUID()}`,
};
const options = { redisUrl: testRedisUrl! };
const first = await queuedDelivery(fake.sender, message, "bulk", options);
const repeated = await queuedDelivery(fake.sender, message, "bulk", options);
expect(first).toEqual({ ok: true, id: "fake-1" });
expect(repeated).toEqual(first);
expect(fake.calls).toBe(1);
});

it("stops at the sender's daily cap without calling the provider again", async () => {
const fake = fakeSender();
const options = { redisUrl: testRedisUrl!, maxPer24Hours: 1, minGapMs: 1000 };
const first = await queuedDelivery(fake.sender, {
from: fake.sender.from,
to: [`person-a-${randomUUID()}@example.test`],
subject: "Queue budget test",
text: "No external delivery",
dedupeKey: `campaign:${randomUUID()}:a`,
}, "bulk", options);
const second = await queuedDelivery(fake.sender, {
from: fake.sender.from,
to: [`person-b-${randomUUID()}@example.test`],
subject: "Queue budget test",
text: "No external delivery",
dedupeKey: `campaign:${randomUUID()}:b`,
}, "bulk", options);
expect(first.ok).toBe(true);
expect(second).toMatchObject({ ok: false, status: 429, retryable: true });
expect(fake.calls).toBe(1);
});

it("records an uncertain provider error as a completed receipt without retrying", async () => {
const fake = fakeSender();
let calls = 0;
fake.sender.send = async () => {
calls++;
throw new Error("connection reset after DATA");
};
const message: QueuedMessage = {
from: fake.sender.from,
to: [`uncertain-${randomUUID()}@example.test`],
subject: "Queue uncertain test",
text: "No external delivery",
dedupeKey: `campaign:${randomUUID()}:uncertain`,
};
const options = { redisUrl: testRedisUrl! };
const first = await queuedDelivery(fake.sender, message, "bulk", options);
const repeated = await queuedDelivery(fake.sender, message, "bulk", options);
expect(first).toMatchObject({ ok: false, retryable: false, status: 0 });
expect(first.error).toContain("Delivery uncertain");
expect(repeated).toEqual(first);
expect(calls).toBe(1);
});
});
}