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