refactor: tighten DDD boundaries on the Feed aggregate

Address five modeling tensions in one pass:

- Encapsulation: the Feed aggregate no longer exposes raw config/metadata
  (a shallow Readonly still leaked mutable arrays). It now offers
  intention-revealing accessors that return copies, plus
  toConfigSnapshot/toMetadataSnapshot for the repository and summary() for
  the global registry.
- feeds:list consistency: FeedRepository.save/saveConfig upsert the registry
  entry from feed.summary(), so services no longer mirror title/description/
  expiry by hand (the old add/updateInList footgun is gone).
- domain/feed.ts: drop the dead applySenderPolicy, internalise resolveExpiresAt
  and trimToByteBudget into the aggregate; feed.ts keeps only the shared
  isExpired predicate used by the read-model routes.
- Single edit path: remove editDetails; edit(patch, deps) is the sole config
  mutation, with a systematic expired guard. Renaming an expired feed now 403s.
- FeedId flows through the application and infrastructure signatures;
  fromTrusted/parse happen once at the edge, .value only at the serialisation
  boundaries (urls, feed-generator, feed-keys, logs, JSON).

347 tests green, tsc clean, Worker bundle builds.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Julien Herr
2026-05-24 13:45:13 +02:00
parent b3d42f6c50
commit ad196f1761
24 changed files with 406 additions and 398 deletions
+12 -2
View File
@@ -9,6 +9,7 @@ import { logger } from "../infrastructure/logger";
import { timingSafeEqual, checkProxyAuth } from "../infrastructure/auth";
import { Layout, clampText } from "./admin/ui";
import { FeedRepository } from "../infrastructure/feed-repository";
import { FeedId } from "../domain/value-objects/feed-id";
import { editFeedDetails } from "../application/feed-service";
import {
feedRssUrl,
@@ -996,12 +997,21 @@ app.post(
try {
const { title, description } = c.req.valid("json");
// In-place edit: only title/description, expiry untouched.
const result = await editFeedDetails(env, feedId, { title, description });
// Quick-edit: only title/description, expiry untouched.
const result = await editFeedDetails(env, FeedId.fromTrusted(feedId), {
title,
description,
});
if (result.status === "not_found") {
return c.json({ error: "Feed not found" }, 404);
}
if (result.status === "expired") {
return c.json(
{ error: "Feed has expired and cannot be modified." },
403,
);
}
return c.json({ success: true });
} catch (error) {
+3 -3
View File
@@ -699,7 +699,7 @@ emailsRouter.post("/feeds/:feedId/emails/bulk-delete", async (c) => {
: c.text("Feed not found", 404);
}
const allowedKeys = new Set(feed.metadata.emails.map((email) => email.key));
const allowedKeys = new Set(feed.emails.map((email) => email.key));
if (wantsJson) {
const body = (await c.req.json().catch(() => null)) as {
@@ -729,7 +729,7 @@ emailsRouter.post("/feeds/:feedId/emails/bulk-delete", async (c) => {
const { ok: deletedOk, failed: failedEmailKeys } =
await deleteKeysWithConcurrency(emailStorage, candidates, 35);
await deleteAttachmentsForEmails(env, feed.metadata.emails, candidates);
await deleteAttachmentsForEmails(env, feed.emails, candidates);
feed.removeEmails(deletedOk);
await repo.saveMetadata(feed);
@@ -757,7 +757,7 @@ emailsRouter.post("/feeds/:feedId/emails/bulk-delete", async (c) => {
candidates,
35,
);
await deleteAttachmentsForEmails(env, feed.metadata.emails, candidates);
await deleteAttachmentsForEmails(env, feed.emails, candidates);
feed.removeEmails(deletedOk);
await repo.saveMetadata(feed);
+19 -11
View File
@@ -335,7 +335,7 @@ feedsRouter.post("/:feedId/edit", async (c) => {
blockedSenders,
});
const result = await editFeed(env, feedId, {
const result = await editFeed(env, FeedId.fromTrusted(feedId), {
title: parsedData.title,
description: parsedData.description,
language: parsedData.language,
@@ -422,7 +422,9 @@ feedsRouter.post("/:feedId/delete", async (c) => {
const wantsJson = (c.req.header("Accept") || "").includes("application/json");
try {
await deleteFeedRecord(env, feedId, (p) => waitUntilSafe(c, p));
await deleteFeedRecord(env, FeedId.fromTrusted(feedId), (p) =>
waitUntilSafe(c, p),
);
if (wantsJson) {
return c.json({ ok: true, feedId });
@@ -456,11 +458,15 @@ feedsRouter.post("/:feedId/purge", async (c) => {
? Number(body?.limit)
: 100;
const step = await purgeFeedKeysStep(emailStorage, feedId, {
cursor,
limit,
bucket: getAttachmentBucket(env),
});
const step = await purgeFeedKeysStep(
emailStorage,
FeedId.fromTrusted(feedId),
{
cursor,
limit,
bucket: getAttachmentBucket(env),
},
);
return c.json({
ok: step.failedKeys.length === 0,
@@ -516,9 +522,10 @@ feedsRouter.post("/bulk-delete", async (c) => {
for (const feedId of parsedFeedIds) {
try {
const id = FeedId.fromTrusted(feedId);
// Read unsubscribe URLs before the feed metadata is deleted.
const urls = await collectUnsubscribeUrls(emailStorage, feedId);
const result = await deleteFeedFastDetailed(emailStorage, feedId);
const urls = await collectUnsubscribeUrls(emailStorage, id);
const result = await deleteFeedFastDetailed(emailStorage, id);
if (!result.ok) {
failures.push({
feedId,
@@ -599,9 +606,10 @@ feedsRouter.post("/bulk-delete", async (c) => {
for (const feedId of parsedFeedIds) {
try {
const id = FeedId.fromTrusted(feedId);
// Read unsubscribe URLs before the feed metadata is deleted.
const urls = await collectUnsubscribeUrls(emailStorage, feedId);
const result = await deleteFeedFastDetailed(emailStorage, feedId);
const urls = await collectUnsubscribeUrls(emailStorage, id);
const result = await deleteFeedFastDetailed(emailStorage, id);
if (result.ok) {
unsubscribeUrls.push(...urls);
okIds.push(feedId);
+8 -9
View File
@@ -209,8 +209,9 @@ apiApp.openapi(
async (c) => {
const env = c.env;
const { feedId } = c.req.valid("param");
const id = FeedId.fromTrusted(feedId);
const body = c.req.valid("json");
const result = await editFeed(env, feedId, {
const result = await editFeed(env, id, {
title: body.title,
description: body.description,
language: body.language,
@@ -222,9 +223,7 @@ apiApp.openapi(
return c.json({ error: "Feed not found" }, 404);
if (result.status === "expired")
return c.json({ error: "Feed has expired and cannot be modified" }, 409);
const metadata = await FeedRepository.from(env).getMetadata(
FeedId.fromTrusted(feedId),
);
const metadata = await FeedRepository.from(env).getMetadata(id);
return c.json(
toFeed(feedId, result.config, metadata?.emails.length ?? 0, env),
200,
@@ -249,8 +248,10 @@ apiApp.openapi(
async (c) => {
const env = c.env;
const { feedId } = c.req.valid("param");
const removed = await deleteFeedRecord(env, feedId, (p) =>
waitUntilSafe(c, p),
const removed = await deleteFeedRecord(
env,
FeedId.fromTrusted(feedId),
(p) => waitUntilSafe(c, p),
);
if (!removed) return c.json({ error: "Feed not found" }, 404);
return c.json({ ok: true }, 200);
@@ -359,9 +360,7 @@ apiApp.openapi(
const { feedId, entryId } = c.req.valid("param");
const receivedAt = parseInt(entryId, 10);
const feed = await repo.load(FeedId.fromTrusted(feedId));
const metaEntry = feed?.metadata.emails.find(
(e) => e.receivedAt === receivedAt,
);
const metaEntry = feed?.emails.find((e) => e.receivedAt === receivedAt);
if (!feed || !metaEntry) return c.json({ error: "Email not found" }, 404);
await repo.deleteEmail(metaEntry.key);
+2 -1
View File
@@ -4,6 +4,7 @@ import { generateAtomFeed } from "../infrastructure/feed-generator";
import { fetchFeedData } from "../application/feed-fetcher";
import { baseUrl, feedAtomUrl } from "../infrastructure/urls";
import { isExpired } from "../domain/feed";
import { FeedId } from "../domain/value-objects/feed-id";
export async function handle(c: Context<{ Bindings: Env }>): Promise<Response> {
try {
@@ -12,7 +13,7 @@ export async function handle(c: Context<{ Bindings: Env }>): Promise<Response> {
return new Response("Feed ID is required", { status: 400 });
}
const feedData = await fetchFeedData(feedId, c.env);
const feedData = await fetchFeedData(FeedId.fromTrusted(feedId), c.env);
if (!feedData) {
return new Response("Feed not found", { status: 404 });
}
+2 -4
View File
@@ -72,12 +72,10 @@ hubRouter.post("/", async (c) => {
);
}
const format = match[1] as "rss" | "atom";
const feedId = match[2];
const feedId = FeedId.fromTrusted(match[2]);
// Verify the feed exists before accepting any subscription
const feedConfig = await FeedRepository.from(env).getConfig(
FeedId.fromTrusted(feedId),
);
const feedConfig = await FeedRepository.from(env).getConfig(feedId);
if (!feedConfig) {
return c.text("Not Found: feed does not exist", 404);
}
+2 -1
View File
@@ -4,6 +4,7 @@ import { generateRssFeed } from "../infrastructure/feed-generator";
import { fetchFeedData } from "../application/feed-fetcher";
import { baseUrl, feedRssUrl } from "../infrastructure/urls";
import { isExpired } from "../domain/feed";
import { FeedId } from "../domain/value-objects/feed-id";
export async function handle(c: Context<{ Bindings: Env }>): Promise<Response> {
try {
@@ -12,7 +13,7 @@ export async function handle(c: Context<{ Bindings: Env }>): Promise<Response> {
return new Response("Feed ID is required", { status: 400 });
}
const feedData = await fetchFeedData(feedId, c.env);
const feedData = await fetchFeedData(FeedId.fromTrusted(feedId), c.env);
if (!feedData) {
return new Response("Feed not found", { status: 404 });
}