From e5f1989c37e91fb7d6495cf21eff2f1d397e198d Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Tue, 20 Oct 2026 20:22:48 -0600 Subject: [PATCH] couple quick patches --- CHANGELOG.md | 14 ++++- apps/web/src/app/(marketing)/stats/page.tsx | 49 +++++++++++---- apps/web/src/app/api/health/inbound/route.ts | 15 +++++ .../src/components/marketing/DevSection.tsx | 56 ++++------------- apps/web/src/server/aws/ses-receiving.ts | 10 +++ apps/web/src/server/jobs/inbound-job.ts | 21 ++++++- apps/web/src/server/service/inbound-canary.ts | 48 ++++++++++++++ .../server/service/inbound-health-service.ts | 63 +++++++++++++++++++ .../inbound-health-service.unit.test.ts | 29 +++++++++ .../web/src/server/service/inbound-service.ts | 18 +++++- .../service/inbound-service.unit.test.ts | 15 ++++- .../server/service/public-stats-service.ts | 34 ++++++++-- 12 files changed, 306 insertions(+), 66 deletions(-) create mode 100644 apps/web/src/app/api/health/inbound/route.ts create mode 100644 apps/web/src/server/service/inbound-canary.ts create mode 100644 apps/web/src/server/service/inbound-health-service.ts create mode 100644 apps/web/src/server/service/inbound-health-service.unit.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a2faaa..f4fc017 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 --- +## [0.9.1] - 2026-10-21 + +### Added +- **Receiving on the stats page**: emails received, DMARC reports read and the messages they covered over the last 30 days, with a daily chart +- **Receiving health check** at `/api/health/inbound` for status pages. A test email is sent to a hosted address every 10 minutes, so the check covers the whole receiving path, along with the receipt rule and the processing queue + +### Fixed +- The website no longer stops responding to taps on phones while the homepage loads. Code samples are now highlighted on the server instead of in the browser + +--- + ## [0.9.0] - 2026-10-20 ### Added @@ -1044,7 +1055,8 @@ Initial public beta release of ByteSend: an all-in-one email infrastructure plat --- -[Unreleased]: https://github.com/ByteSendApp/ByteSend/compare/v0.9.0...HEAD +[Unreleased]: https://github.com/ByteSendApp/ByteSend/compare/v0.9.1...HEAD +[0.9.1]: https://github.com/ByteSendApp/ByteSend/compare/v0.9.0...v0.9.1 [0.9.0]: https://github.com/ByteSendApp/ByteSend/compare/v0.8.0...v0.9.0 [0.8.0]: https://github.com/ByteSendApp/ByteSend/compare/v0.7.0...v0.8.0 [0.7.0]: https://github.com/ByteSendApp/ByteSend/compare/v0.6.0...v0.7.0 diff --git a/apps/web/src/app/(marketing)/stats/page.tsx b/apps/web/src/app/(marketing)/stats/page.tsx index 488bf08..613a9d4 100644 --- a/apps/web/src/app/(marketing)/stats/page.tsx +++ b/apps/web/src/app/(marketing)/stats/page.tsx @@ -10,7 +10,7 @@ export const dynamic = "force-dynamic"; export const metadata: Metadata = { title: "Open stats – ByteSend", - description: "Live, aggregate numbers from ByteSend: emails sent, delivery rate, deliverability health and uptime.", + description: "Live, aggregate numbers from ByteSend: emails sent and received, delivery rate, deliverability health and uptime.", alternates: { canonical: "https://bytesend.cloud/stats" }, }; @@ -47,23 +47,25 @@ function StatTile({ value, label, hint }: { value: string; label: string; hint?: ); } -function VolumeChart({ days }: { days: PublicStatsDay[] }) { - const max = Math.max(1, ...days.map((day) => day.sent)); +function VolumeChart({ days, metric = "sent" }: { days: PublicStatsDay[]; metric?: "sent" | "received" }) { + const gradientId = `stats-bar-${metric}`; + const max = Math.max(1, ...days.map((day) => day[metric])); const width = 600; const height = 160; const gap = 4; const barWidth = (width - gap * (days.length - 1)) / days.length; return ( - + - - - + + + {days.map((day, index) => { - const barHeight = day.sent === 0 ? 2 : Math.max(3, (day.sent / max) * height); + const value = day[metric]; + const barHeight = value === 0 ? 2 : Math.max(3, (value / max) * height); return ( - {`${formatDay(day.date)}: ${full.format(day.sent)} sent`} + {`${formatDay(day.date)}: ${full.format(value)} ${metric}`} ); })} @@ -166,6 +168,28 @@ export default async function StatsPage() { + +
+

Receiving

+ Last {window.days} days (UTC) +
+

+ Mail arriving at ByteSend inboxes, and the DMARC reports we read for teams' domains. +

+
+ + + +
+
+ +
+ {formatDay(stats.daily[0]!.date)} + {formatDay(stats.daily[stats.daily.length - 1]!.date)} +
+
+ +

Deliverability health

@@ -212,7 +236,8 @@ export default async function StatsPage() {

Figures combine transactional and marketing email across all ByteSend Cloud teams. Self-hosted instances are not - included. Rates are calculated against emails sent in the window; days are in UTC. + included. Rates are calculated against emails sent in the window; days are in UTC. Received email counts mail kept + in team inboxes; DMARC reports aren't counted as received email.

diff --git a/apps/web/src/app/api/health/inbound/route.ts b/apps/web/src/app/api/health/inbound/route.ts new file mode 100644 index 0000000..0f6ce5b --- /dev/null +++ b/apps/web/src/app/api/health/inbound/route.ts @@ -0,0 +1,15 @@ +import { checkInboundHealth } from "~/server/service/inbound-health-service"; +import { isInboundEnabled } from "~/server/service/inbound-storage"; +import { NO_STORE, isAuthorized } from "../ses/shared"; + +export const dynamic = "force-dynamic"; + +export async function GET(request: Request) { + if (!isInboundEnabled()) { + return Response.json({ error: "Receiving isn't set up on this instance" }, { status: 404, headers: NO_STORE }); + } + + const health = await checkInboundHealth(); + const body = isAuthorized(request) ? health : { status: health.status, checkedAt: health.checkedAt }; + return Response.json(body, { status: health.status === "down" ? 503 : 200, headers: NO_STORE }); +} diff --git a/apps/web/src/components/marketing/DevSection.tsx b/apps/web/src/components/marketing/DevSection.tsx index fd2207a..4f27e63 100644 --- a/apps/web/src/components/marketing/DevSection.tsx +++ b/apps/web/src/components/marketing/DevSection.tsx @@ -1,17 +1,11 @@ -"use client"; - import React from "react"; -import { useEffect, useState } from "react"; import Link from "next/link"; import { highlightCode, type HighlightLang } from "~/lib/highlighter"; -import { useTheme } from "@bytesend/ui"; import { Button } from "@bytesend/ui/src/button"; import { LangToggle } from "~/components/marketing/CodeLangToggle"; import { CheckIcon } from "~/components/marketing/HomeIcons"; -export function DevSection() { - const { resolvedTheme } = useTheme(); - +export async function DevSection() { const APP_URL = "/login"; const containerId = "dev-lang-snippets"; @@ -143,6 +137,15 @@ puts res.body`; { key: "rb", label: "Ruby", kind: "rb", shikiLang: "ruby", code: RUBY_SNIPPET, file: "send_email.rb" }, ]; + const highlighted = await Promise.all( + languages.map((lang) => + highlightCode(lang.code, { + lang: lang.shikiLang, + themes: { dark: "catppuccin-mocha", light: "catppuccin-latte" }, + }).catch(() => ""), + ), + ); + return (
@@ -212,7 +215,7 @@ puts res.body`;
{lang.file}
- +
))} @@ -222,41 +225,8 @@ puts res.body`; ); } -function HighlightedSnippet({ code, lang, theme }: { code: string; lang: HighlightLang; theme?: string }) { - const [html, setHtml] = useState(""); - const [loading, setLoading] = useState(true); - const shikiTheme = theme === "light" ? "catppuccin-latte" : "catppuccin-mocha"; - - useEffect(() => { - let mounted = true; - - async function highlight() { - try { - const highlighted = await highlightCode(code, { lang, theme: shikiTheme }); - - if (mounted) { - setHtml(highlighted); - } - } catch { - if (mounted) { - setHtml(""); - } - } finally { - if (mounted) { - setLoading(false); - } - } - } - - setLoading(true); - void highlight(); - - return () => { - mounted = false; - }; - }, [code, lang, shikiTheme]); - - if (loading || !html) { +function CodeSnippet({ code, html }: { code: string; html: string }) { + if (!html) { return (
                 {code}
diff --git a/apps/web/src/server/aws/ses-receiving.ts b/apps/web/src/server/aws/ses-receiving.ts
index f1c9531..25c521c 100644
--- a/apps/web/src/server/aws/ses-receiving.ts
+++ b/apps/web/src/server/aws/ses-receiving.ts
@@ -29,6 +29,16 @@ export function inboundMxHost(region: string = env.INBOUND_REGION) {
   return `inbound-smtp.${region}.amazonaws.com`;
 }
 
+export async function getReceivingRuleState(region: string = env.INBOUND_REGION) {
+  const active = await getClassicClient(region).send(new DescribeActiveReceiptRuleSetCommand({}));
+  const rule = active.Rules?.find((r) => r.Name === INBOUND_RULE);
+  return {
+    ruleSetActive: active.Metadata?.Name === INBOUND_RULE_SET,
+    ruleEnabled: Boolean(rule?.Enabled),
+    notifiesTopic: Boolean(rule?.Actions?.some((action) => action.S3Action?.TopicArn)),
+  };
+}
+
 export async function ensureReceivingRules({
   region = env.INBOUND_REGION,
   bucket = env.INBOUND_S3_BUCKET,
diff --git a/apps/web/src/server/jobs/inbound-job.ts b/apps/web/src/server/jobs/inbound-job.ts
index 4c0c116..2e6e24b 100644
--- a/apps/web/src/server/jobs/inbound-job.ts
+++ b/apps/web/src/server/jobs/inbound-job.ts
@@ -4,6 +4,7 @@ import { DEFAULT_QUEUE_OPTIONS, INBOUND_CLEANUP_QUEUE, INBOUND_QUEUE } from "../
 import { logger } from "../logger/log";
 import { deleteExpiredInbound, processInbound, type SesInboundNotification } from "../service/inbound-service";
 import { deleteExpiredDmarcReports } from "../service/dmarc-service";
+import { INBOUND_CANARY_INTERVAL_MS, inboundCanaryAddress, sendInboundCanary } from "../service/inbound-canary";
 
 let inboundQueue: Queue | null = null;
 let initialized = false;
@@ -26,6 +27,11 @@ export async function enqueueInbound(notification: SesInboundNotification) {
   });
 }
 
+export async function getInboundQueueCounts() {
+  const counts = await getInboundQueue().getJobCounts("waiting", "active", "delayed", "failed");
+  return { waiting: counts.waiting ?? 0, active: counts.active ?? 0, delayed: counts.delayed ?? 0, failed: counts.failed ?? 0 };
+}
+
 export async function initInboundJobs() {
   if (initialized) return;
   const connection = getRedis();
@@ -43,7 +49,11 @@ export async function initInboundJobs() {
   const cleanupQueue = new Queue(INBOUND_CLEANUP_QUEUE, { connection, prefix: BULL_PREFIX, skipVersionCheck: true });
   const cleanupWorker = new Worker(
     INBOUND_CLEANUP_QUEUE,
-    async () => {
+    async (job) => {
+      if (job.name === "canary") {
+        await sendInboundCanary();
+        return;
+      }
       const deleted = await deleteExpiredInbound();
       const reports = await deleteExpiredDmarcReports();
       logger.info({ deleted, reports }, "[InboundJob]: Removed expired received mail and DMARC reports");
@@ -52,6 +62,15 @@ export async function initInboundJobs() {
   );
   cleanupWorker.on("failed", (job, err) => logger.error({ err, jobId: job?.id }, "[InboundJob]: Cleanup failed"));
   await cleanupQueue.upsertJobScheduler("inbound-cleanup-daily", { pattern: "40 3 * * *", tz: "UTC" }, { opts: { ...DEFAULT_QUEUE_OPTIONS } });
+  if (inboundCanaryAddress()) {
+    await cleanupQueue.upsertJobScheduler(
+      "inbound-canary",
+      { every: INBOUND_CANARY_INTERVAL_MS },
+      { name: "canary", opts: { ...DEFAULT_QUEUE_OPTIONS } },
+    );
+  } else {
+    await cleanupQueue.removeJobScheduler("inbound-canary");
+  }
 
   initialized = true;
 }
diff --git a/apps/web/src/server/service/inbound-canary.ts b/apps/web/src/server/service/inbound-canary.ts
new file mode 100644
index 0000000..3bc59de
--- /dev/null
+++ b/apps/web/src/server/service/inbound-canary.ts
@@ -0,0 +1,48 @@
+import { env } from "~/env";
+import { logger } from "../logger/log";
+import { getRedis, redisKey } from "../redis";
+
+export const INBOUND_CANARY_INTERVAL_MS = 10 * 60 * 1000;
+export const INBOUND_CANARY_SLUG = "status-canary";
+const FIRST_SENT_KEY = "inbound:canary:first-sent";
+const LAST_SENT_KEY = "inbound:canary:last-sent";
+const LAST_SEEN_KEY = "inbound:canary:last-seen";
+
+export function inboundCanaryAddress() {
+  return env.INBOUND_HOSTED_DOMAIN ? `${INBOUND_CANARY_SLUG}@${env.INBOUND_HOSTED_DOMAIN.toLowerCase()}` : null;
+}
+
+export function isInboundCanary(address: string) {
+  const canary = inboundCanaryAddress();
+  return canary !== null && address.trim().toLowerCase() === canary;
+}
+
+export async function recordInboundCanary() {
+  await getRedis().set(redisKey(LAST_SEEN_KEY), String(Date.now()));
+}
+
+export async function sendInboundCanary() {
+  const address = inboundCanaryAddress();
+  if (!address) return;
+  const { sendMail } = await import("../mailer");
+  const sentAt = new Date().toISOString();
+  await sendMail(
+    address,
+    `ByteSend receiving check ${sentAt}`,
+    `Automated receiving check sent at ${sentAt}.`,
+    `

Automated receiving check sent at ${sentAt}.

`, + ); + const now = String(Date.now()); + await getRedis().set(redisKey(FIRST_SENT_KEY), now, "NX"); + await getRedis().set(redisKey(LAST_SENT_KEY), now); + logger.info({ address }, "[InboundCanary]: Sent"); +} + +export async function getInboundCanaryTimes() { + const [first, sent, seen] = await getRedis().mget(redisKey(FIRST_SENT_KEY), redisKey(LAST_SENT_KEY), redisKey(LAST_SEEN_KEY)); + return { + firstSentAt: first ? Number(first) : null, + lastSentAt: sent ? Number(sent) : null, + lastSeenAt: seen ? Number(seen) : null, + }; +} diff --git a/apps/web/src/server/service/inbound-health-service.ts b/apps/web/src/server/service/inbound-health-service.ts new file mode 100644 index 0000000..1eec0cd --- /dev/null +++ b/apps/web/src/server/service/inbound-health-service.ts @@ -0,0 +1,63 @@ +import { env } from "~/env"; +import { logger } from "../logger/log"; +import { withCache } from "../redis"; +import { getReceivingRuleState } from "../aws/ses-receiving"; +import { getInboundQueueCounts } from "../jobs/inbound-job"; +import { INBOUND_CANARY_INTERVAL_MS, getInboundCanaryTimes, inboundCanaryAddress } from "./inbound-canary"; + +export type InboundHealthStatus = "operational" | "degraded" | "down"; + +const CANARY_DEGRADED_AFTER_MS = INBOUND_CANARY_INTERVAL_MS * 2; +const CANARY_DOWN_AFTER_MS = INBOUND_CANARY_INTERVAL_MS * 4; +const QUEUE_BACKLOG_DEGRADED = 100; + +const worst = (statuses: InboundHealthStatus[]) => + statuses.includes("down") ? "down" : statuses.includes("degraded") ? "degraded" : "operational"; + +export function canaryStatus( + times: { firstSentAt: number | null; lastSeenAt: number | null }, + now = Date.now(), +): InboundHealthStatus { + const reference = times.lastSeenAt ?? times.firstSentAt; + if (reference === null) return "operational"; + const age = now - reference; + if (age >= CANARY_DOWN_AFTER_MS) return "down"; + if (age >= CANARY_DEGRADED_AFTER_MS) return "degraded"; + return "operational"; +} + +export async function checkInboundHealth() { + const checkedAt = new Date().toISOString(); + + const rule = await withCache(`inbound:health:rule:${env.INBOUND_REGION}`, () => getReceivingRuleState(), { ttlSeconds: 300 }).catch( + (error) => { + logger.warn({ err: error }, "[InboundHealth]: Couldn't read the receipt rule"); + return null; + }, + ); + const ruleStatus: InboundHealthStatus = !rule ? "degraded" : rule.ruleSetActive && rule.ruleEnabled && rule.notifiesTopic ? "operational" : "down"; + + const queue = await getInboundQueueCounts().catch(() => null); + const queueStatus: InboundHealthStatus = !queue ? "degraded" : queue.waiting + queue.delayed > QUEUE_BACKLOG_DEGRADED ? "degraded" : "operational"; + + const canaryConfigured = inboundCanaryAddress() !== null; + const canary = canaryConfigured ? await getInboundCanaryTimes() : null; + const canaryHealth: InboundHealthStatus = canary ? canaryStatus(canary) : "operational"; + + return { + status: worst([ruleStatus, queueStatus, canaryHealth]), + checkedAt, + region: env.INBOUND_REGION, + checks: { + receiptRule: { status: ruleStatus, ...(rule ?? {}) }, + queue: { status: queueStatus, ...(queue ?? {}) }, + canary: canary + ? { + status: canaryHealth, + lastSentAt: canary.lastSentAt ? new Date(canary.lastSentAt).toISOString() : null, + lastSeenAt: canary.lastSeenAt ? new Date(canary.lastSeenAt).toISOString() : null, + } + : { status: "operational" as const, configured: false }, + }, + }; +} diff --git a/apps/web/src/server/service/inbound-health-service.unit.test.ts b/apps/web/src/server/service/inbound-health-service.unit.test.ts new file mode 100644 index 0000000..4434dc4 --- /dev/null +++ b/apps/web/src/server/service/inbound-health-service.unit.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("~/env", () => ({ env: { INBOUND_REGION: "us-east-1", INBOUND_HOSTED_DOMAIN: "in.bytesend.test" } })); +vi.mock("../logger/log", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } })); +vi.mock("../redis", () => ({ withCache: vi.fn(), getRedis: vi.fn(), redisKey: (k: string) => k })); +vi.mock("../aws/ses-receiving", () => ({ getReceivingRuleState: vi.fn() })); +vi.mock("../jobs/inbound-job", () => ({ getInboundQueueCounts: vi.fn() })); + +import { canaryStatus } from "./inbound-health-service"; + +const minutes = (n: number) => n * 60 * 1000; +const now = Date.UTC(2026, 9, 21, 12, 0, 0); + +describe("canaryStatus", () => { + it("is operational before any canary has been sent", () => { + expect(canaryStatus({ firstSentAt: null, lastSeenAt: null }, now)).toBe("operational"); + }); + + it("gives a fresh deploy time for the first canary to arrive", () => { + expect(canaryStatus({ firstSentAt: now - minutes(5), lastSeenAt: null }, now)).toBe("operational"); + expect(canaryStatus({ firstSentAt: now - minutes(45), lastSeenAt: null }, now)).toBe("down"); + }); + + it("degrades, then goes down, as the last arrival gets older", () => { + expect(canaryStatus({ firstSentAt: now - minutes(500), lastSeenAt: now - minutes(12) }, now)).toBe("operational"); + expect(canaryStatus({ firstSentAt: now - minutes(500), lastSeenAt: now - minutes(25) }, now)).toBe("degraded"); + expect(canaryStatus({ firstSentAt: now - minutes(500), lastSeenAt: now - minutes(41) }, now)).toBe("down"); + }); +}); diff --git a/apps/web/src/server/service/inbound-service.ts b/apps/web/src/server/service/inbound-service.ts index fae1673..53eff82 100644 --- a/apps/web/src/server/service/inbound-service.ts +++ b/apps/web/src/server/service/inbound-service.ts @@ -11,6 +11,7 @@ import { getInboundStore } from "./inbound-storage"; import { WebhookService } from "./webhook-service"; import { sendEmail } from "./email-service"; import { ingestDmarcMessage, isDmarcRecipient } from "./dmarc-service"; +import { INBOUND_CANARY_SLUG, isInboundCanary, recordInboundCanary } from "./inbound-canary"; export const INBOUND_RETENTION_DAYS = 30; const ATTACHMENT_LINK_TTL_SECONDS = 60 * 60; @@ -220,13 +221,23 @@ async function loadRaw(notification: SesInboundNotification) { export async function processInbound(notification: SesInboundNotification) { const sesId = notification.mail.messageId; + const recipients = notification.receipt.recipients.filter((address) => !isInboundCanary(address)); + if (recipients.length < notification.receipt.recipients.length) { + await recordInboundCanary(); + if (recipients.length === 0) { + const { objectKey } = notification.receipt.action; + if (objectKey) await getInboundStore().remove([objectKey]); + return { stored: 0, reports: 0 }; + } + } + const matches = new Map(); - for (const address of notification.receipt.recipients) { + for (const address of recipients) { const match = await resolveRecipient(address); if (match && !matches.has(match.teamId)) matches.set(match.teamId, match); } if (matches.size === 0) { - logger.info({ sesId, recipients: notification.receipt.recipients }, "[Inbound]: No team for these recipients, dropped"); + logger.info({ sesId, recipients }, "[Inbound]: No team for these recipients, dropped"); return { stored: 0, reports: 0 }; } @@ -334,7 +345,8 @@ function slugify(name: string) { export async function ensureInboundSlug(teamId: number) { const team = await db.team.findUniqueOrThrow({ where: { id: teamId }, select: { name: true, inboundSlug: true } }); if (team.inboundSlug) return team.inboundSlug; - const base = slugify(team.name); + const slugified = slugify(team.name); + const base = slugified === INBOUND_CANARY_SLUG ? `${slugified}-team` : slugified; for (let attempt = 0; attempt < 5; attempt++) { const slug = attempt === 0 ? base : `${base}-${randomBytes(2).toString("hex")}`; try { diff --git a/apps/web/src/server/service/inbound-service.unit.test.ts b/apps/web/src/server/service/inbound-service.unit.test.ts index 1153ce5..0178dbd 100644 --- a/apps/web/src/server/service/inbound-service.unit.test.ts +++ b/apps/web/src/server/service/inbound-service.unit.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -const { mockDb, mockStore, mockEmit, mockSendEmail, mockIngestDmarc, env } = vi.hoisted(() => ({ +const { mockDb, mockStore, mockEmit, mockSendEmail, mockIngestDmarc, mockRecordCanary, env } = vi.hoisted(() => ({ mockDb: { team: { findUnique: vi.fn(), findUniqueOrThrow: vi.fn(), update: vi.fn() }, domain: { findFirst: vi.fn(), findUnique: vi.fn() }, @@ -12,6 +12,7 @@ const { mockDb, mockStore, mockEmit, mockSendEmail, mockIngestDmarc, env } = vi. mockEmit: vi.fn(), mockSendEmail: vi.fn(), mockIngestDmarc: vi.fn(), + mockRecordCanary: vi.fn(), env: { INBOUND_HOSTED_DOMAIN: "in.bytesend.test", INBOUND_REGION: "us-east-1", @@ -28,6 +29,10 @@ vi.mock("./inbound-storage", () => ({ getInboundStore: () => mockStore })); vi.mock("./webhook-service", () => ({ WebhookService: { emit: mockEmit } })); vi.mock("./email-service", () => ({ sendEmail: mockSendEmail })); vi.mock("../aws/ses-receiving", () => ({ INBOUND_RAW_PREFIX: "raw/" })); +vi.mock("./inbound-canary", async (importOriginal) => ({ + ...(await importOriginal()), + recordInboundCanary: mockRecordCanary, +})); vi.mock("./dmarc-service", async (importOriginal) => ({ ...(await importOriginal()), ingestDmarcMessage: mockIngestDmarc, @@ -194,6 +199,14 @@ describe("processInbound", () => { expect(mockDb.inboundEmail.create).not.toHaveBeenCalled(); }); + it("records the status canary without storing it anywhere", async () => { + const result = await processInbound(notification("status-canary@in.bytesend.test", mime({ to: "status-canary@in.bytesend.test" }))); + expect(result).toEqual({ stored: 0, reports: 0 }); + expect(mockRecordCanary).toHaveBeenCalledTimes(1); + expect(mockDb.inboundEmail.create).not.toHaveBeenCalled(); + expect(mockDb.team.findUnique).not.toHaveBeenCalled(); + }); + it("sends mail for the DMARC address to the report parser, not the inbox", async () => { mockIngestDmarc.mockResolvedValue(1); const raw = mime({ to: "acme+dmarc@in.bytesend.test" }); diff --git a/apps/web/src/server/service/public-stats-service.ts b/apps/web/src/server/service/public-stats-service.ts index f22f0c0..23a8e02 100644 --- a/apps/web/src/server/service/public-stats-service.ts +++ b/apps/web/src/server/service/public-stats-service.ts @@ -9,7 +9,7 @@ const CACHE_TTL_SECONDS = 60 * 60; const STATUS_STATS_URL = "https://status.bytesend.cloud/api/status/stats?range=30d"; -export type PublicStatsDay = { date: string; sent: number; delivered: number }; +export type PublicStatsDay = { date: string; sent: number; delivered: number; received: number }; export type PublicStats = { generatedAt: string; @@ -21,6 +21,7 @@ export type PublicStats = { bounced: number; complained: number; }; + inbound: { received: number; dmarcReports: number; dmarcMessages: number }; daily: PublicStatsDay[]; regions: { code: string; label: string }[]; uptime: number | null; @@ -54,6 +55,24 @@ async function getDailyUsage(startKey: string) { `; } +async function getDailyReceived(start: Date) { + return db.$queryRaw>` + SELECT to_char(i."receivedAt", 'YYYY-MM-DD') AS date, COUNT(*)::float8 AS received + FROM "InboundEmail" i + WHERE i."receivedAt" >= ${start} + GROUP BY 1 + `; +} + +async function getDmarcTotals(start: Date) { + const result = await db.dmarcReport.aggregate({ + where: { createdAt: { gte: start } }, + _count: { _all: true }, + _sum: { messageCount: true }, + }); + return { dmarcReports: result._count._all, dmarcMessages: result._sum.messageCount ?? 0 }; +} + async function getActiveRegions() { const settings = await db.sesSetting.findMany({ where: { isActive: true }, @@ -80,18 +99,21 @@ async function computePublicStats(): Promise { const start = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()) - (WINDOW_DAYS - 1) * DAY_MS); const startKey = toDateKey(start); - const [allTime, usage, regions, uptime] = await Promise.all([ + const [allTime, usage, received, dmarc, regions, uptime] = await Promise.all([ getAllTimeTotals(), getDailyUsage(startKey), + getDailyReceived(start), + getDmarcTotals(start), getActiveRegions(), getUptime(), ]); const byDate = new Map(usage.map((row) => [row.date, row])); + const receivedByDate = new Map(received.map((row) => [row.date, row.received])); const daily = Array.from({ length: WINDOW_DAYS }, (_, i) => { const date = toDateKey(new Date(start.getTime() + i * DAY_MS)); const row = byDate.get(date); - return { date, sent: row?.sent ?? 0, delivered: row?.delivered ?? 0 }; + return { date, sent: row?.sent ?? 0, delivered: row?.delivered ?? 0, received: receivedByDate.get(date) ?? 0 }; }); const window = usage.reduce( @@ -105,13 +127,15 @@ async function computePublicStats(): Promise { { days: WINDOW_DAYS, sent: 0, delivered: 0, bounced: 0, complained: 0 }, ); - return { generatedAt: new Date().toISOString(), allTime, window, daily, regions, uptime }; + const inbound = { received: daily.reduce((sum, day) => sum + day.received, 0), ...dmarc }; + + return { generatedAt: new Date().toISOString(), allTime, window, inbound, daily, regions, uptime }; } export const PublicStatsService = { async get(): Promise { try { - return await withCache("public-stats:v1", computePublicStats, { ttlSeconds: CACHE_TTL_SECONDS }); + return await withCache("public-stats:v2", computePublicStats, { ttlSeconds: CACHE_TTL_SECONDS }); } catch (error) { logger.error({ err: error }, "[PublicStats] Cache unavailable, computing directly"); return computePublicStats();