Open History to see the last commit
1import {
2 type MilestoneEvent,
3 type MilestoneFilter,
4 type MilestoneId,
5 milestoneMatches,
6} from "@t3tools/contracts";
7import * as Clock from "effect/Clock";
8import * as Context from "effect/Context";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as PubSub from "effect/PubSub";
12import type * as Scope from "effect/Scope";
13import * as Stream from "effect/Stream";
14import { routineSpan } from "@t3tools/shared/observability";
15
16// Enough for a client that was away for a while to catch up; older news is in the stores.
17const KEPT = 1_000;
18// Ids outlive the events they name, so a late repeat of an evicted milestone is still one.
19const IDS_KEPT = 4 * KEPT;
20// A subscriber this far behind loses its oldest milestones, not the server's memory.
21const SUBSCRIBER_BACKLOG = 256;
22const RECENT_LIMIT = 200;
23
24/** A milestone and the cursor that reads on after it. */
25export interface PositionedMilestone {
26 readonly event: MilestoneEvent;
27 readonly cursor: string;
28}
29
30/**
31 * Where a cursor read starts. `null` starts from now. A cursor from before a restart or no longer
32 * kept starts at the oldest kept milestone; `maxAgeMs` skips those older than that.
33 */
34export interface MilestoneReadOptions {
35 readonly cursor: string | null;
36 readonly maxAgeMs?: number | undefined;
37 readonly filter?: MilestoneFilter | undefined;
38}
39
40/** What a follower reads after its start: a milestone, a position passed without one, or a gap. */
41export type MilestoneFollowItem =
42 | ({ readonly _tag: "Milestone" } & PositionedMilestone)
43 | { readonly _tag: "Position"; readonly cursor: string }
44 | { readonly _tag: "Gap"; readonly cursor: string };
45
46export class MilestoneHub extends Context.Service<
47 MilestoneHub,
48 {
49 /** Publishing an id seen before does nothing, so a feeder may repeat itself. */
50 readonly publish: (event: MilestoneEvent) => Effect.Effect<void>;
51 /**
52 * Milestones published from now on that match `filter`. Subscribed when this runs, so a caller
53 * catching up subscribes first, then reads `recent`, and drops ids it already has.
54 */
55 readonly subscribe: (
56 filter?: MilestoneFilter,
57 ) => Effect.Effect<Stream.Stream<MilestoneEvent>, never, Scope.Scope>;
58 /**
59 * Kept milestones, oldest first: those after `sinceId`, or the newest. `truncated` says the
60 * answer is incomplete: `sinceId` is no longer kept, or `limit` cut it short.
61 */
62 readonly recent: (options?: {
63 readonly sinceId?: MilestoneId | undefined;
64 readonly limit?: number | undefined;
65 readonly filter?: MilestoneFilter | undefined;
66 }) => Effect.Effect<{
67 readonly events: ReadonlyArray<MilestoneEvent>;
68 readonly truncated: boolean;
69 }>;
70 /**
71 * Matching milestones after a cursor, at most `limit`. `cursor` reads on from there: after the
72 * last one returned when `hasMore`, otherwise from now. `truncated` says some were skipped.
73 */
74 readonly read: (options: MilestoneReadOptions & { readonly limit: number }) => Effect.Effect<{
75 readonly events: ReadonlyArray<PositionedMilestone>;
76 readonly cursor: string;
77 readonly truncated: boolean;
78 readonly hasMore: boolean;
79 }>;
80 /** The milestones `read` would return, then live ones, each once. */
81 readonly follow: (options: MilestoneReadOptions) => Effect.Effect<
82 {
83 readonly cursor: string;
84 readonly truncated: boolean;
85 readonly items: Stream.Stream<MilestoneFollowItem>;
86 },
87 never,
88 Scope.Scope
89 >;
90 }
91>()("t3/milestones/MilestoneHub") {}
92
93interface Kept {
94 readonly event: MilestoneEvent;
95 readonly seq: number;
96}
97
98const make = Effect.gen(function* () {
99 const pubsub = yield* PubSub.sliding<Kept>(SUBSCRIBER_BACKLOG);
100 const kept: Array<Kept> = [];
101 const seen = new Set<MilestoneId>();
102 let seq = 0;
103 // Sequence numbers restart with the server; the epoch tells an old cursor from a new one.
104 const epoch = (yield* Clock.currentTimeMillis).toString(36);
105 const cursorAt = (at: number) => `${epoch}.${at}`;
106 const seqOf = (cursor: string) => {
107 const [cursorEpoch, at] = cursor.split(".");
108 const value = Number(at);
109 return cursorEpoch === epoch && Number.isSafeInteger(value) && value >= 0 && value <= seq
110 ? value
111 : undefined;
112 };
113
114 const remember = (event: MilestoneEvent) => {
115 if (seen.has(event.id)) return undefined;
116 seen.add(event.id);
117 if (seen.size > IDS_KEPT) seen.delete(seen.values().next().value!);
118 const entry = { event, seq: ++seq };
119 kept.push(entry);
120 if (kept.length > KEPT) kept.shift();
121 return entry;
122 };
123
124 // The kept milestones after the cursor, and whether milestones after it were skipped.
125 const after = (options: MilestoneReadOptions, now: number) => {
126 if (options.cursor === null) return { entries: [], truncated: false };
127 const from = seqOf(options.cursor);
128 const oldest = kept[0]?.seq ?? seq + 1;
129 let entries = from === undefined ? kept : kept.filter((entry) => entry.seq > from);
130 let truncated = from === undefined || from < oldest - 1;
131 if (options.maxAgeMs !== undefined) {
132 // Kept in publication order, which `occurredAt` need not follow, so each one is checked.
133 const floor = now - options.maxAgeMs;
134 const young = entries.filter((entry) => Date.parse(entry.event.occurredAt) >= floor);
135 truncated ||= young.length < entries.length;
136 entries = young;
137 }
138 return { entries, truncated };
139 };
140
141 const positioned = (entry: Kept): PositionedMilestone => ({
142 event: entry.event,
143 cursor: cursorAt(entry.seq),
144 });
145
146 const subscribe = Effect.fn("MilestoneHub.subscribe")(function* (filter?: MilestoneFilter) {
147 const subscription = yield* PubSub.subscribe(pubsub);
148 return Stream.fromSubscription(subscription).pipe(
149 Stream.map((entry) => entry.event),
150 Stream.filter((event) => milestoneMatches(event, filter)),
151 );
152 });
153
154 const recent: MilestoneHub["Service"]["recent"] = Effect.fn("MilestoneHub.recent")(function* (
155 options = {},
156 ) {
157 const limit = Math.max(1, Math.min(options.limit ?? RECENT_LIMIT, KEPT));
158 const at =
159 options.sinceId === undefined
160 ? -1
161 : kept.findIndex((entry) => entry.event.id === options.sinceId);
162 const gap = options.sinceId !== undefined && at === -1;
163 const matching = kept
164 .slice(at + 1)
165 .map((entry) => entry.event)
166 .filter((event) => milestoneMatches(event, options.filter));
167 // Paging forward from a known id; otherwise the newest, as there is no place to start.
168 const events =
169 options.sinceId !== undefined && !gap ? matching.slice(0, limit) : matching.slice(-limit);
170 return yield* Effect.succeed({ events, truncated: gap || events.length < matching.length });
171 });
172
173 const read: MilestoneHub["Service"]["read"] = Effect.fn("MilestoneHub.read")(function* (options) {
174 const from = after(options, yield* Clock.currentTimeMillis);
175 const matching = from.entries.filter((entry) => milestoneMatches(entry.event, options.filter));
176 const events = matching.slice(0, Math.max(1, options.limit));
177 const hasMore = events.length < matching.length;
178 return {
179 events: events.map(positioned),
180 cursor: hasMore ? cursorAt(events.at(-1)!.seq) : cursorAt(seq),
181 truncated: from.truncated,
182 hasMore,
183 };
184 });
185
186 return MilestoneHub.of({
187 publish: Effect.fn("MilestoneHub.publish", { attributes: routineSpan })(function* (event) {
188 const entry = remember(event);
189 if (entry === undefined) return;
190 yield* PubSub.publish(pubsub, entry);
191 }),
192 subscribe,
193 recent,
194 read,
195 follow: Effect.fn("MilestoneHub.follow")(function* (options) {
196 // Subscribed before reading the buffer, so nothing published in between is lost.
197 const live = Stream.fromSubscription(yield* PubSub.subscribe(pubsub));
198 const caught = yield* read({ ...options, limit: KEPT });
199 const first = caught.events[0];
200 let last = seqOf(caught.cursor)!;
201 const items = live.pipe(
202 Stream.flatMap((entry) => {
203 if (entry.seq <= last) return Stream.empty;
204 // A follower that fell behind the subscriber backlog lost the milestones in between.
205 const gap = entry.seq > last + 1;
206 last = entry.seq;
207 const item: MilestoneFollowItem = milestoneMatches(entry.event, options.filter)
208 ? { _tag: "Milestone", ...positioned(entry) }
209 : { _tag: "Position", cursor: cursorAt(entry.seq) };
210 return Stream.fromIterable(
211 gap ? [{ _tag: "Gap" as const, cursor: cursorAt(entry.seq - 1) }, item] : [item],
212 );
213 }),
214 );
215 return {
216 // The position before the first replayed milestone, which each one then advances.
217 cursor: first === undefined ? caught.cursor : cursorAt(seqOf(first.cursor)! - 1),
218 truncated: caught.truncated,
219 items: Stream.fromIterable<MilestoneFollowItem>([
220 ...caught.events.map((event): MilestoneFollowItem => ({ _tag: "Milestone", ...event })),
221 // Replay checked past its last match; told after it, so no client skips a replayed one.
222 ...(first !== undefined && caught.events.at(-1)!.cursor !== caught.cursor
223 ? [{ _tag: "Position" as const, cursor: caught.cursor }]
224 : []),
225 ]).pipe(Stream.concat(items)),
226 };
227 }),
228 });
229});
230
231export const layer = Layer.effect(MilestoneHub, make);