mirror of
https://github.com/juherr/kill-the-news.git
synced 2026-06-21 06:13:48 +00:00
refactor: separate Feed domain state from persistence DTO
Move four DDD tensions on the Feed aggregate to ground: - #1 The aggregate now holds a domain FeedState (camelCase) instead of the snake_case FeedConfig DTO; infrastructure/feed-mapper.ts owns the FeedState<->FeedConfig/FeedListItem translation as the sole snake_case site outside the HTTP edge. - #3 Replace the edit() recomputeExpiry control flag with a Lifetime VO: passing a lifetime recomputes expiry, omitting it preserves the current one (the dashboard quick-edit path). - #4 Domain events carry their own feedId; dispatchFeedEvents centralizes the drain+dispatch in the application layer (no more manual pullEvents at call sites), keeping infra->application dependency direction intact. - #6 Rename FeedId.fromTrusted to FeedId.unchecked to make the absence of revalidation explicit. Adds Lifetime + feed-mapper round-trip tests. 353 tests green, tsc clean, wrangler dry-run OK. Docs (CLAUDE.md) synced. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -6,7 +6,7 @@ export class EmailParser {
|
||||
* Extract the feed id from an inbound recipient address. Returns a validated
|
||||
* `FeedId` value object (not a raw string) so the most untrusted input in the
|
||||
* system — an address typed by a sender — is guarded at the parse boundary and
|
||||
* never needs `FeedId.fromTrusted` downstream.
|
||||
* never needs `FeedId.unchecked` downstream.
|
||||
*/
|
||||
static extractFeedId(emailAddress: string): FeedId | null {
|
||||
return FeedId.parse(emailAddress);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { FeedId } from "./value-objects/feed-id";
|
||||
|
||||
/**
|
||||
* Domain events the Feed aggregate records when it mutates. They describe *what
|
||||
* happened* in business terms; the application layer decides which side effects
|
||||
* to run (counters, WebSub pings, favicon caching) via a dispatcher. This keeps
|
||||
* the aggregate ignorant of infrastructure and the orchestration code free of
|
||||
* scattered, inline side effects.
|
||||
* happened* in business terms and carry their own `feedId`, so the application
|
||||
* dispatcher can route side effects (counters, WebSub pings, favicon caching)
|
||||
* without the caller threading the id back in. This keeps the aggregate ignorant
|
||||
* of infrastructure and the orchestration code free of scattered, inline effects.
|
||||
*
|
||||
* Only mutations that currently have side effects emit events — feed creation
|
||||
* and email ingestion. Edits and removals carry no side effect, so they emit
|
||||
@@ -12,5 +14,5 @@
|
||||
* outside this mechanism by design — they have no aggregate event to ride on.
|
||||
*/
|
||||
export type FeedEvent =
|
||||
| { type: "FeedCreated" }
|
||||
| { type: "EmailIngested"; iconDomain?: string };
|
||||
| { type: "FeedCreated"; feedId: FeedId }
|
||||
| { type: "EmailIngested"; feedId: FeedId; iconDomain?: string };
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* The Feed aggregate's internal config state, in domain (camelCase) vocabulary.
|
||||
* This is deliberately NOT the persistence shape: the snake_case `FeedConfig`
|
||||
* DTO is an infrastructure concern, and the translation between the two lives in
|
||||
* `infrastructure/feed-mapper.ts`. The domain never speaks the storage dialect.
|
||||
*
|
||||
* `expiresAt` is an absolute instant (epoch ms) already resolved from a
|
||||
* `Lifetime`; the aggregate stores the resolved value, not the policy.
|
||||
*/
|
||||
export interface FeedState {
|
||||
title: string;
|
||||
description?: string;
|
||||
language: string;
|
||||
author?: string;
|
||||
allowedSenders: string[];
|
||||
blockedSenders: string[];
|
||||
createdAt: number;
|
||||
updatedAt?: number;
|
||||
expiresAt?: number;
|
||||
}
|
||||
@@ -3,10 +3,12 @@ import { createMockEnv } from "../test/setup";
|
||||
import { Feed, CreateFeedInput } from "./feed.aggregate";
|
||||
import { FeedRepository } from "../infrastructure/feed-repository";
|
||||
import { FeedId } from "./value-objects/feed-id";
|
||||
import { Lifetime } from "./value-objects/lifetime";
|
||||
import { FeedState } from "./feed-state";
|
||||
import { Clock } from "./clock";
|
||||
import type { Env, EmailMetadata } from "../types";
|
||||
|
||||
const FID = FeedId.fromTrusted("a.b.42");
|
||||
const FID = FeedId.unchecked("a.b.42");
|
||||
|
||||
const mockEnv = () => createMockEnv() as unknown as Env;
|
||||
|
||||
@@ -22,6 +24,15 @@ const createInput = (
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const state = (overrides: Partial<FeedState> = {}): FeedState => ({
|
||||
title: "T",
|
||||
language: "en",
|
||||
allowedSenders: [],
|
||||
blockedSenders: [],
|
||||
createdAt: 0,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const entry = (overrides: Partial<EmailMetadata> = {}): EmailMetadata => ({
|
||||
key: "feed:a.b.42:1",
|
||||
subject: "Hello",
|
||||
@@ -39,43 +50,41 @@ describe("Feed.create", () => {
|
||||
expect(feed.emails).toEqual([]);
|
||||
});
|
||||
|
||||
it("resolves expiry from the supplied ttlHours using the injected clock", () => {
|
||||
it("resolves expiry from the supplied lifetime using the injected clock", () => {
|
||||
const NOW = 1_000_000;
|
||||
const feed = Feed.create(FID, createInput(), {
|
||||
clock: fixedClock(NOW),
|
||||
ttlHours: 2,
|
||||
lifetime: Lifetime.ofHours(2),
|
||||
});
|
||||
expect(feed.createdAt).toBe(NOW);
|
||||
expect(feed.updatedAt).toBe(NOW);
|
||||
expect(feed.expiresAt).toBe(NOW + 2 * 3_600_000);
|
||||
});
|
||||
|
||||
it("trusts only deps.ttlHours, not the client lifetimeHours field", () => {
|
||||
it("trusts only deps.lifetime, not the client lifetimeHours field", () => {
|
||||
// The aggregate no longer parses lifetime policy: the application resolves
|
||||
// the effective ttlHours (env override etc.) and hands it in.
|
||||
const feed = Feed.create(FID, createInput({ lifetimeHours: 9999 }), {
|
||||
ttlHours: undefined,
|
||||
});
|
||||
// the effective Lifetime (env override etc.) and hands it in.
|
||||
const feed = Feed.create(FID, createInput({ lifetimeHours: 9999 }));
|
||||
expect(feed.expiresAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it("treats a non-positive ttlHours as no expiry", () => {
|
||||
it("treats a non-positive lifetime as no expiry", () => {
|
||||
expect(
|
||||
Feed.create(FID, createInput(), { ttlHours: 0 }).expiresAt,
|
||||
Feed.create(FID, createInput(), { lifetime: Lifetime.ofHours(0) })
|
||||
.expiresAt,
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
Feed.create(FID, createInput(), { ttlHours: -5 }).expiresAt,
|
||||
Feed.create(FID, createInput(), { lifetime: Lifetime.ofHours(-5) })
|
||||
.expiresAt,
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Feed.isExpired / accepts", () => {
|
||||
it("reports expiry against the configured instant", () => {
|
||||
const feed = Feed.reconstitute(
|
||||
FID,
|
||||
{ title: "T", language: "en", created_at: 0, expires_at: 100 },
|
||||
{ emails: [] },
|
||||
);
|
||||
const feed = Feed.reconstitute(FID, state({ expiresAt: 100 }), {
|
||||
emails: [],
|
||||
});
|
||||
expect(feed.isExpired(50)).toBe(false);
|
||||
expect(feed.isExpired(150)).toBe(true);
|
||||
});
|
||||
@@ -83,7 +92,7 @@ describe("Feed.isExpired / accepts", () => {
|
||||
it("uses the injected clock when no instant is supplied", () => {
|
||||
const feed = Feed.reconstitute(
|
||||
FID,
|
||||
{ title: "T", language: "en", created_at: 0, expires_at: 100 },
|
||||
state({ expiresAt: 100 }),
|
||||
{ emails: [] },
|
||||
fixedClock(150),
|
||||
);
|
||||
@@ -93,12 +102,7 @@ describe("Feed.isExpired / accepts", () => {
|
||||
it("applies the sender policy", () => {
|
||||
const feed = Feed.reconstitute(
|
||||
FID,
|
||||
{
|
||||
title: "T",
|
||||
language: "en",
|
||||
created_at: 0,
|
||||
allowed_senders: ["good@example.com"],
|
||||
},
|
||||
state({ allowedSenders: ["good@example.com"] }),
|
||||
{ emails: [] },
|
||||
);
|
||||
expect(feed.accepts(["good@example.com"])).toBe("accepted");
|
||||
@@ -107,28 +111,28 @@ describe("Feed.isExpired / accepts", () => {
|
||||
});
|
||||
|
||||
describe("Feed.edit", () => {
|
||||
it("recomputes expiry only when asked", () => {
|
||||
it("recomputes expiry only when a lifetime is supplied", () => {
|
||||
const NOW = 5_000_000;
|
||||
const FUTURE = NOW + 10 * 3_600_000;
|
||||
const feed = Feed.reconstitute(
|
||||
FID,
|
||||
{ title: "T", language: "en", created_at: 0, expires_at: FUTURE },
|
||||
state({ expiresAt: FUTURE }),
|
||||
{ emails: [] },
|
||||
fixedClock(NOW),
|
||||
);
|
||||
|
||||
feed.edit({ title: "T2" }, { recomputeExpiry: false });
|
||||
expect(feed.expiresAt).toBe(FUTURE); // preserved
|
||||
feed.edit({ title: "T2" }); // no lifetime ⇒ expiry preserved
|
||||
expect(feed.expiresAt).toBe(FUTURE);
|
||||
expect(feed.updatedAt).toBe(NOW);
|
||||
|
||||
feed.edit({ title: "T3" }, { recomputeExpiry: true, ttlHours: 1 });
|
||||
feed.edit({ title: "T3" }, { lifetime: Lifetime.ofHours(1) });
|
||||
expect(feed.expiresAt).toBe(NOW + 3_600_000);
|
||||
});
|
||||
|
||||
it("refuses to edit an already-expired feed", () => {
|
||||
const feed = Feed.reconstitute(
|
||||
FID,
|
||||
{ title: "T", language: "en", created_at: 0, expires_at: 100 },
|
||||
state({ expiresAt: 100 }),
|
||||
{ emails: [] },
|
||||
fixedClock(200),
|
||||
);
|
||||
@@ -138,13 +142,9 @@ describe("Feed.edit", () => {
|
||||
|
||||
describe("Feed.ingest", () => {
|
||||
it("prepends the entry, tracks icon/unsub and trims to the byte budget", () => {
|
||||
const feed = Feed.reconstitute(
|
||||
FID,
|
||||
{ title: "T", language: "en", created_at: 0 },
|
||||
{
|
||||
emails: [entry({ key: "old", size: 400 })],
|
||||
},
|
||||
);
|
||||
const feed = Feed.reconstitute(FID, state(), {
|
||||
emails: [entry({ key: "old", size: 400 })],
|
||||
});
|
||||
|
||||
const { dropped } = feed.ingest(entry({ key: "new", size: 400 }), {
|
||||
maxBytes: 500,
|
||||
@@ -162,11 +162,7 @@ describe("Feed.ingest", () => {
|
||||
});
|
||||
|
||||
it("always keeps the just-ingested entry, even when it alone is oversized", () => {
|
||||
const feed = Feed.reconstitute(
|
||||
FID,
|
||||
{ title: "T", language: "en", created_at: 0 },
|
||||
{ emails: [] },
|
||||
);
|
||||
const feed = Feed.reconstitute(FID, state(), { emails: [] });
|
||||
|
||||
const { dropped } = feed.ingest(entry({ key: "huge", size: 999 }), {
|
||||
maxBytes: 1,
|
||||
@@ -179,17 +175,13 @@ describe("Feed.ingest", () => {
|
||||
|
||||
describe("Feed.removeEmails", () => {
|
||||
it("drops matching keys and returns the removed entries", () => {
|
||||
const feed = Feed.reconstitute(
|
||||
FID,
|
||||
{ title: "T", language: "en", created_at: 0 },
|
||||
{
|
||||
emails: [
|
||||
entry({ key: "k1" }),
|
||||
entry({ key: "k2" }),
|
||||
entry({ key: "k3" }),
|
||||
],
|
||||
},
|
||||
);
|
||||
const feed = Feed.reconstitute(FID, state(), {
|
||||
emails: [
|
||||
entry({ key: "k1" }),
|
||||
entry({ key: "k2" }),
|
||||
entry({ key: "k3" }),
|
||||
],
|
||||
});
|
||||
|
||||
const { removed } = feed.removeEmails(["k1", "k3", "missing"]);
|
||||
expect(removed.map((e) => e.key).sort()).toEqual(["k1", "k3"]);
|
||||
@@ -200,35 +192,31 @@ describe("Feed.removeEmails", () => {
|
||||
describe("Feed events", () => {
|
||||
it("records FeedCreated on create and drains it once", () => {
|
||||
const feed = Feed.create(FID, createInput());
|
||||
expect(feed.pullEvents()).toEqual([{ type: "FeedCreated" }]);
|
||||
expect(feed.pullEvents()).toEqual([{ type: "FeedCreated", feedId: FID }]);
|
||||
// Draining clears: a second pull is empty.
|
||||
expect(feed.pullEvents()).toEqual([]);
|
||||
});
|
||||
|
||||
it("records EmailIngested (with icon domain) on ingest", () => {
|
||||
const feed = Feed.reconstitute(
|
||||
FID,
|
||||
{ title: "T", language: "en", created_at: 0 },
|
||||
{ emails: [] },
|
||||
);
|
||||
const feed = Feed.reconstitute(FID, state(), { emails: [] });
|
||||
feed.ingest(entry({ key: "k" }), {
|
||||
maxBytes: 1_000_000,
|
||||
iconDomain: "example.com",
|
||||
});
|
||||
expect(feed.pullEvents()).toEqual([
|
||||
{ type: "EmailIngested", iconDomain: "example.com" },
|
||||
{ type: "EmailIngested", feedId: FID, iconDomain: "example.com" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("emits no events for edit / removeEmails", () => {
|
||||
const feed = Feed.reconstitute(
|
||||
FID,
|
||||
{ title: "T", language: "en", created_at: 0, expires_at: 9_999_999_999 },
|
||||
state({ expiresAt: 9_999_999_999 }),
|
||||
{ emails: [entry({ key: "k1" })] },
|
||||
fixedClock(1000),
|
||||
);
|
||||
feed.edit({ title: "X" }, { recomputeExpiry: false });
|
||||
feed.edit({ description: "Y" }, { recomputeExpiry: false });
|
||||
feed.edit({ title: "X" });
|
||||
feed.edit({ description: "Y" });
|
||||
feed.removeEmails(["k1"]);
|
||||
expect(feed.pullEvents()).toEqual([]);
|
||||
});
|
||||
@@ -253,6 +241,6 @@ describe("FeedRepository.load / save round-trip", () => {
|
||||
|
||||
it("returns null when the feed has no config", async () => {
|
||||
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||
expect(await repo.load(FeedId.fromTrusted("missing"))).toBeNull();
|
||||
expect(await repo.load(FeedId.unchecked("missing"))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,32 +1,10 @@
|
||||
import {
|
||||
FeedConfig,
|
||||
FeedMetadata,
|
||||
EmailMetadata,
|
||||
FeedListItem,
|
||||
} from "../types";
|
||||
import { FeedMetadata, EmailMetadata } from "../types";
|
||||
import { FeedState } from "./feed-state";
|
||||
import { FeedId } from "./value-objects/feed-id";
|
||||
import { Lifetime } from "./value-objects/lifetime";
|
||||
import { SenderPolicy, SenderDecision } from "./value-objects/sender-policy";
|
||||
import { Clock, systemClock } from "./clock";
|
||||
import { FeedEvent } from "./events";
|
||||
import { isExpired } from "./feed";
|
||||
|
||||
const HOUR_MS = 3_600_000;
|
||||
|
||||
/**
|
||||
* Resolve a feed's `expires_at` from an already-resolved lifetime (hours) and a
|
||||
* current instant. Returns undefined when no positive lifetime applies (the feed
|
||||
* never expires). Which lifetime applies (client request vs. server-side
|
||||
* override, env parsing) is the application layer's call — the aggregate only
|
||||
* receives the resolved number. File-private: the aggregate is its sole user.
|
||||
*/
|
||||
function resolveExpiresAt(
|
||||
ttlHours: number | undefined,
|
||||
now: number,
|
||||
): number | undefined {
|
||||
return ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0
|
||||
? now + ttlHours * HOUR_MS
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export interface CreateFeedInput {
|
||||
title: string;
|
||||
@@ -34,6 +12,7 @@ export interface CreateFeedInput {
|
||||
language: string;
|
||||
allowedSenders: string[];
|
||||
blockedSenders: string[];
|
||||
/** Raw client-requested lifetime; the application resolves it into a `Lifetime`. */
|
||||
lifetimeHours?: number;
|
||||
}
|
||||
|
||||
@@ -48,24 +27,23 @@ export interface UpdateFeedInput {
|
||||
|
||||
/**
|
||||
* Dependencies the aggregate needs from the outside but must not reach for
|
||||
* itself: a clock (never ambient `Date.now()`) and an already-resolved feed
|
||||
* lifetime. The application layer decides the lifetime — parsing env config and
|
||||
* applying any server-side `FEED_TTL_HOURS` override — and hands the result in.
|
||||
* itself: a clock (never ambient `Date.now()`) and an already-resolved
|
||||
* `Lifetime`. The application layer decides the lifetime — parsing env config and
|
||||
* applying any server-side `FEED_TTL_HOURS` override — and hands the VO in.
|
||||
*/
|
||||
export interface CreateFeedDeps {
|
||||
clock?: Clock;
|
||||
/** Effective lifetime in hours, already resolved by the application. */
|
||||
ttlHours?: number;
|
||||
/** Effective lifetime, already resolved by the application. */
|
||||
lifetime?: Lifetime;
|
||||
}
|
||||
|
||||
export interface EditFeedDeps {
|
||||
/** Effective lifetime in hours, already resolved by the application. */
|
||||
ttlHours?: number;
|
||||
/**
|
||||
* Whether to recompute expiry at all. False preserves the current expiry
|
||||
* (mirrors the old "no server TTL and no client lifetime ⇒ leave as-is").
|
||||
* Effective lifetime, already resolved by the application. Its *presence* means
|
||||
* "recompute expiry"; its absence preserves the current expiry — which covers
|
||||
* the dashboard's title/description quick-edit.
|
||||
*/
|
||||
recomputeExpiry?: boolean;
|
||||
lifetime?: Lifetime;
|
||||
}
|
||||
|
||||
export interface IngestOptions {
|
||||
@@ -83,17 +61,19 @@ export interface IngestOptions {
|
||||
* deliberately sit *outside* the aggregate — the caller flushes them alongside
|
||||
* `FeedRepository.save`/`saveMetadata`.
|
||||
*
|
||||
* I/O-free and time-free: load and persist state through `FeedRepository`; time
|
||||
* comes from an injected `Clock`. KV has no multi-key transaction, so a future
|
||||
* Durable Object keyed by feed id would wrap load→mutate→save to serialise
|
||||
* concurrent writers (see email-processor.ts).
|
||||
* Its config is held as domain `FeedState` (camelCase), never the snake_case
|
||||
* persistence DTO — `FeedRepository` translates via `feed-mapper.ts`. I/O-free
|
||||
* and time-free: load and persist through the repository; time comes from an
|
||||
* injected `Clock`. KV has no multi-key transaction, so a future Durable Object
|
||||
* keyed by feed id would wrap load→mutate→save to serialise concurrent writers
|
||||
* (see email-processor.ts).
|
||||
*/
|
||||
export class Feed {
|
||||
private readonly _events: FeedEvent[] = [];
|
||||
|
||||
private constructor(
|
||||
readonly id: FeedId,
|
||||
private _config: FeedConfig,
|
||||
private _state: FeedState,
|
||||
private _metadata: FeedMetadata,
|
||||
private readonly clock: Clock,
|
||||
) {}
|
||||
@@ -106,60 +86,60 @@ export class Feed {
|
||||
): Feed {
|
||||
const clock = deps.clock ?? systemClock;
|
||||
const now = clock.now();
|
||||
const expiresAt = resolveExpiresAt(deps.ttlHours, now);
|
||||
const config: FeedConfig = {
|
||||
const expiresAt = (deps.lifetime ?? Lifetime.never).resolveExpiry(now);
|
||||
const state: FeedState = {
|
||||
title: input.title,
|
||||
description: input.description,
|
||||
language: input.language,
|
||||
allowed_senders: input.allowedSenders,
|
||||
blocked_senders: input.blockedSenders,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
...(expiresAt !== undefined ? { expires_at: expiresAt } : {}),
|
||||
allowedSenders: input.allowedSenders,
|
||||
blockedSenders: input.blockedSenders,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
expiresAt,
|
||||
};
|
||||
const feed = new Feed(id, config, { emails: [] }, clock);
|
||||
feed._events.push({ type: "FeedCreated" });
|
||||
const feed = new Feed(id, state, { emails: [] }, clock);
|
||||
feed._events.push({ type: "FeedCreated", feedId: id });
|
||||
return feed;
|
||||
}
|
||||
|
||||
/** Rebuild an aggregate from persisted state. */
|
||||
/** Rebuild an aggregate from persisted (already-mapped) domain state. */
|
||||
static reconstitute(
|
||||
id: FeedId,
|
||||
config: FeedConfig,
|
||||
state: FeedState,
|
||||
metadata: FeedMetadata,
|
||||
clock: Clock = systemClock,
|
||||
): Feed {
|
||||
return new Feed(id, config, metadata, clock);
|
||||
return new Feed(id, state, metadata, clock);
|
||||
}
|
||||
|
||||
// ── Intention-revealing reads ─────────────────────────────────────────────
|
||||
// The aggregate exposes named fields and copies of its collections, never the
|
||||
// raw `config`/`metadata` objects — a shallow `Readonly<…>` would still let a
|
||||
// caller mutate the arrays inside. Persistence reads `toConfigSnapshot()` /
|
||||
// `toMetadataSnapshot()`; the registry reads `summary()`.
|
||||
// raw `state`/`metadata` objects — a shallow `Readonly<…>` would still let a
|
||||
// caller mutate the arrays inside. Persistence reads `state()` /
|
||||
// `toMetadataSnapshot()`; the mapper derives the DTOs.
|
||||
|
||||
get title(): string {
|
||||
return this._config.title;
|
||||
return this._state.title;
|
||||
}
|
||||
|
||||
get description(): string | undefined {
|
||||
return this._config.description;
|
||||
return this._state.description;
|
||||
}
|
||||
|
||||
get language(): string {
|
||||
return this._config.language;
|
||||
return this._state.language;
|
||||
}
|
||||
|
||||
get createdAt(): number {
|
||||
return this._config.created_at;
|
||||
return this._state.createdAt;
|
||||
}
|
||||
|
||||
get updatedAt(): number | undefined {
|
||||
return this._config.updated_at;
|
||||
return this._state.updatedAt;
|
||||
}
|
||||
|
||||
get expiresAt(): number | undefined {
|
||||
return this._config.expires_at;
|
||||
return this._state.expiresAt;
|
||||
}
|
||||
|
||||
get iconDomain(): string | undefined {
|
||||
@@ -167,11 +147,11 @@ export class Feed {
|
||||
}
|
||||
|
||||
allowedSenders(): string[] {
|
||||
return [...(this._config.allowed_senders ?? [])];
|
||||
return [...this._state.allowedSenders];
|
||||
}
|
||||
|
||||
blockedSenders(): string[] {
|
||||
return [...(this._config.blocked_senders ?? [])];
|
||||
return [...this._state.blockedSenders];
|
||||
}
|
||||
|
||||
/** A copy of the email index — mutating it never touches aggregate state. */
|
||||
@@ -184,21 +164,15 @@ export class Feed {
|
||||
return { ...(this._metadata.unsubscribe ?? {}) };
|
||||
}
|
||||
|
||||
/** The projection stored in the global `feeds:list` registry. */
|
||||
summary(): FeedListItem {
|
||||
return {
|
||||
id: this.id.value,
|
||||
title: this._config.title,
|
||||
description: this._config.description,
|
||||
expires_at: this._config.expires_at,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Persistence snapshots (repository-only) ───────────────────────────────
|
||||
|
||||
/** A serialisable copy of the config for the repository to persist. */
|
||||
toConfigSnapshot(): FeedConfig {
|
||||
return { ...this._config };
|
||||
/** A copy of the domain config state for the repository to map + persist. */
|
||||
state(): FeedState {
|
||||
return {
|
||||
...this._state,
|
||||
allowedSenders: [...this._state.allowedSenders],
|
||||
blockedSenders: [...this._state.blockedSenders],
|
||||
};
|
||||
}
|
||||
|
||||
/** A serialisable copy of the email index for the repository to persist. */
|
||||
@@ -217,13 +191,15 @@ export class Feed {
|
||||
}
|
||||
|
||||
isExpired(now: number = this.clock.now()): boolean {
|
||||
return isExpired(this._config, now);
|
||||
// The shared `isExpired` predicate (domain/feed.ts) lives on the read path
|
||||
// and speaks the persistence DTO; the aggregate checks its own domain state.
|
||||
return this._state.expiresAt !== undefined && this._state.expiresAt <= now;
|
||||
}
|
||||
|
||||
accepts(senders: string[]): SenderDecision {
|
||||
return SenderPolicy.fromLists(
|
||||
this._config.allowed_senders,
|
||||
this._config.blocked_senders,
|
||||
this._state.allowedSenders,
|
||||
this._state.blockedSenders,
|
||||
).decide(senders);
|
||||
}
|
||||
|
||||
@@ -249,7 +225,11 @@ export class Feed {
|
||||
};
|
||||
}
|
||||
|
||||
this._events.push({ type: "EmailIngested", iconDomain: opts.iconDomain });
|
||||
this._events.push({
|
||||
type: "EmailIngested",
|
||||
feedId: this.id,
|
||||
iconDomain: opts.iconDomain,
|
||||
});
|
||||
return this.trimToByteBudget(opts.maxBytes);
|
||||
}
|
||||
|
||||
@@ -287,11 +267,11 @@ export class Feed {
|
||||
|
||||
/**
|
||||
* The single edit path. Apply the patch (only the fields it carries) and
|
||||
* recompute expiry from the application-supplied lifetime when asked — an
|
||||
* absent recompute preserves the current expiry, which covers the dashboard's
|
||||
* title/description quick-edit (`recomputeExpiry: false`). Rejects an
|
||||
* already-expired feed without mutating it, so a quick-edit can no more touch
|
||||
* an expired feed than a full edit can.
|
||||
* recompute expiry when the application supplies a `Lifetime` — an absent
|
||||
* lifetime preserves the current expiry, which covers the dashboard's
|
||||
* title/description quick-edit. Rejects an already-expired feed without
|
||||
* mutating it, so a quick-edit can no more touch an expired feed than a full
|
||||
* edit can.
|
||||
*/
|
||||
edit(
|
||||
patch: UpdateFeedInput,
|
||||
@@ -300,23 +280,23 @@ export class Feed {
|
||||
if (this.isExpired()) return { status: "expired" };
|
||||
|
||||
const now = this.clock.now();
|
||||
const expiresAt = deps.recomputeExpiry
|
||||
? resolveExpiresAt(deps.ttlHours, now)
|
||||
: this._config.expires_at;
|
||||
const expiresAt = deps.lifetime
|
||||
? deps.lifetime.resolveExpiry(now)
|
||||
: this._state.expiresAt;
|
||||
|
||||
if (patch.title !== undefined) this._config.title = patch.title;
|
||||
if (patch.title !== undefined) this._state.title = patch.title;
|
||||
if (patch.description !== undefined) {
|
||||
this._config.description = patch.description;
|
||||
this._state.description = patch.description;
|
||||
}
|
||||
if (patch.language !== undefined) this._config.language = patch.language;
|
||||
if (patch.language !== undefined) this._state.language = patch.language;
|
||||
if (patch.allowedSenders !== undefined) {
|
||||
this._config.allowed_senders = patch.allowedSenders;
|
||||
this._state.allowedSenders = patch.allowedSenders;
|
||||
}
|
||||
if (patch.blockedSenders !== undefined) {
|
||||
this._config.blocked_senders = patch.blockedSenders;
|
||||
this._state.blockedSenders = patch.blockedSenders;
|
||||
}
|
||||
this._config.updated_at = now;
|
||||
this._config.expires_at = expiresAt;
|
||||
this._state.updatedAt = now;
|
||||
this._state.expiresAt = expiresAt;
|
||||
|
||||
return { status: "ok" };
|
||||
}
|
||||
|
||||
@@ -17,11 +17,13 @@ export class FeedId {
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap an id we already trust — a value we minted ourselves and round-tripped
|
||||
* through our own links or KV keys (route params, the feed list, email keys).
|
||||
* No validation: a wrong id simply misses in KV and 404s, exactly as before.
|
||||
* Wrap a string as a FeedId WITHOUT revalidating it. The caller asserts the id
|
||||
* originated from our own minting — a route param echoing a stored id, a
|
||||
* `feeds:list` entry, or an email/KV key. The name is deliberately blunt: a
|
||||
* wrong id is not rejected here, it simply misses in KV and 404s downstream.
|
||||
* Untrusted external input (an inbound address) must go through `parse` instead.
|
||||
*/
|
||||
static fromTrusted(value: string): FeedId {
|
||||
static unchecked(value: string): FeedId {
|
||||
return new FeedId(value);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { Lifetime } from "./lifetime";
|
||||
|
||||
const NOW = 1_000_000;
|
||||
const HOUR = 3_600_000;
|
||||
|
||||
describe("Lifetime", () => {
|
||||
it("resolves a positive lifetime to an absolute expiry", () => {
|
||||
expect(Lifetime.ofHours(2).resolveExpiry(NOW)).toBe(NOW + 2 * HOUR);
|
||||
});
|
||||
|
||||
it("never expires for Lifetime.never", () => {
|
||||
expect(Lifetime.never.resolveExpiry(NOW)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("treats non-positive or non-finite hours as no expiry", () => {
|
||||
expect(Lifetime.ofHours(0).resolveExpiry(NOW)).toBeUndefined();
|
||||
expect(Lifetime.ofHours(-5).resolveExpiry(NOW)).toBeUndefined();
|
||||
expect(Lifetime.ofHours(NaN).resolveExpiry(NOW)).toBeUndefined();
|
||||
expect(Lifetime.ofHours(Infinity).resolveExpiry(NOW)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
const HOUR_MS = 3_600_000;
|
||||
|
||||
/**
|
||||
* A feed's lifetime as a value object: either a positive number of hours or
|
||||
* "never". `resolveExpiry(now)` turns it into an absolute `expires_at` instant
|
||||
* (or undefined for a feed that never expires).
|
||||
*
|
||||
* Which lifetime applies — client request vs. server-side `FEED_TTL_HOURS`
|
||||
* override — is the application layer's policy; it builds the VO and hands it to
|
||||
* the aggregate. The aggregate never parses env config or reaches for a clock to
|
||||
* compute expiry itself.
|
||||
*/
|
||||
export class Lifetime {
|
||||
private constructor(private readonly hours: number | undefined) {}
|
||||
|
||||
/** A finite, positive lifetime. Non-positive/non-finite inputs collapse to never. */
|
||||
static ofHours(hours: number): Lifetime {
|
||||
return new Lifetime(hours);
|
||||
}
|
||||
|
||||
/** A feed that never expires. */
|
||||
static readonly never = new Lifetime(undefined);
|
||||
|
||||
/** The absolute expiry instant for this lifetime, or undefined if it never expires. */
|
||||
resolveExpiry(now: number): number | undefined {
|
||||
return this.hours !== undefined &&
|
||||
Number.isFinite(this.hours) &&
|
||||
this.hours > 0
|
||||
? now + this.hours * HOUR_MS
|
||||
: undefined;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user