Open History to see the last commit
1import { it } from "@effect/vitest";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as PubSub from "effect/PubSub";
6import * as Queue from "effect/Queue";
7import * as Stream from "effect/Stream";
8import { describe, expect } from "vite-plus/test";
9
10import {
11 bufferLiveStream,
12 makeLiveStreamBudget,
13 replayAndBufferLiveEvents,
14 type RetainedLiveItem,
15} from "./LiveStreamBudget.ts";
16
17describe("LiveStreamBudget", () => {
18 it.effect("closes the source without releasing a batch still waiting for an ACK", () =>
19 Effect.scoped(
20 Effect.gen(function* () {
21 const budget = yield* makeLiveStreamBudget({ maxItems: 3 });
22 const queue = yield* Queue.unbounded<RetainedLiveItem<{ text: string }>>();
23 const sourceClosed = yield* Deferred.make<void>();
24 const first = yield* budget.retain({ text: "first" });
25 const second = yield* budget.retain({ text: "second" });
26 const third = yield* budget.retain({ text: "third" });
27 yield* Queue.offerAll(queue, [first, second, third]);
28 yield* Effect.scoped(
29 Effect.gen(function* () {
30 const pull = yield* Stream.toPull(
31 budget.deliver(
32 Stream.fromQueue(queue).pipe(
33 Stream.rechunk(1),
34 Stream.ensuring(Deferred.succeed(sourceClosed, undefined)),
35 ),
36 ),
37 );
38 expect(yield* pull).toEqual([{ text: "first" }]);
39 expect(yield* Queue.size(queue)).toBe(0);
40 expect((yield* budget.usage).retainedItems).toBe(3);
41 const overflow = yield* budget.retain({ text: "fourth" }).pipe(Effect.result);
42 expect(overflow._tag).toBe("Failure");
43 yield* Deferred.await(sourceClosed);
44 yield* budget.closed;
45 expect((yield* budget.usage).retainedItems).toBe(1);
46 }),
47 );
48 expect(yield* budget.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
49 }),
50 ),
51 );
52});
53
54it.effect("stops draining a slow subscriber when its unacknowledged tail fills", () =>
55 Effect.scoped(
56 Effect.gen(function* () {
57 const input = yield* Queue.unbounded<{ text: string }>();
58 const sourceClosed = yield* Deferred.make<void>();
59 const pull = yield* Stream.toPull(
60 bufferLiveStream(
61 Stream.fromQueue(input).pipe(Stream.ensuring(Deferred.succeed(sourceClosed, undefined))),
62 { maxItems: 2 },
63 ),
64 );
65 yield* Queue.offer(input, { text: "first" });
66 expect(yield* pull).toEqual([{ text: "first" }]);
67 yield* Queue.offerAll(input, [{ text: "second" }, { text: "third" }]);
68 yield* Deferred.await(sourceClosed);
69 const next = yield* pull.pipe(Effect.result);
70 expect(next._tag).toBe("Failure");
71 if (next._tag === "Failure") expect(next.failure._tag).toBe("LiveStreamBufferError");
72 }),
73 ),
74);
75
76type Event = { readonly sequence: number; readonly text: string; readonly threadId?: string };
77
78describe("replayAndBufferLiveEvents", () => {
79 it.effect.each(["high-water", "replay"] as const)(
80 "unsubscribes and cancels a blocked %s read on live overflow",
81 (phase) =>
82 Effect.scoped(
83 Effect.gen(function* () {
84 const pubsub = yield* PubSub.unbounded<Event>();
85 const subscribed = yield* Deferred.make<PubSub.Subscription<Event>>();
86 const readStarted = yield* Deferred.make<void>();
87 const readClosed = yield* Deferred.make<void>();
88 const blockedRead = Deferred.succeed(readStarted, undefined).pipe(
89 Effect.andThen(Effect.never),
90 Effect.ensuring(Deferred.succeed(readClosed, undefined)),
91 );
92 const pull = yield* Stream.toPull(
93 replayAndBufferLiveEvents(
94 {
95 subscribe: PubSub.subscribe(pubsub).pipe(
96 Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)),
97 ),
98 latestSequence:
99 phase === "high-water" ? blockedRead.pipe(Effect.as(0)) : Effect.succeed(0),
100 replay: () => (phase === "replay" ? Stream.fromEffect(blockedRead) : Stream.empty),
101 },
102 { maxItems: 2 },
103 ),
104 );
105 const reader = yield* pull.pipe(Effect.result, Effect.forkScoped);
106 yield* Deferred.await(readStarted);
107 yield* PubSub.publishAll(pubsub, [
108 { sequence: 1, text: "one" },
109 { sequence: 2, text: "two" },
110 { sequence: 3, text: "overflow" },
111 ]);
112 yield* (yield* Deferred.await(subscribed)).shutdownHook.await;
113 yield* Deferred.await(readClosed);
114 const result = yield* Fiber.join(reader);
115 expect(result._tag).toBe("Failure");
116 if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
117 expect(yield* PubSub.size(pubsub)).toBe(0);
118 yield* PubSub.publish(pubsub, { sequence: 4, text: "after overflow" });
119 expect(yield* PubSub.size(pubsub)).toBe(0);
120 }),
121 ),
122 );
123
124 it.effect.each(["items", "bytes"] as const)(
125 "counts an unacknowledged replay batch toward the live %s limit",
126 (limit) =>
127 Effect.scoped(
128 Effect.gen(function* () {
129 const pubsub = yield* PubSub.unbounded<Event>();
130 const subscribed = yield* Deferred.make<PubSub.Subscription<Event>>();
131 const replayed = { sequence: 1, text: "replay" };
132 const live = { sequence: 2, text: "live" };
133 const pull = yield* Stream.toPull(
134 replayAndBufferLiveEvents(
135 {
136 subscribe: PubSub.subscribe(pubsub).pipe(
137 Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)),
138 ),
139 latestSequence: Effect.succeed(1),
140 replay: () => Stream.succeed(replayed),
141 },
142 limit === "items"
143 ? { maxItems: 1 }
144 : {
145 maxSerializedBytes: 40,
146 },
147 ),
148 );
149 expect(yield* pull).toEqual([replayed]);
150 yield* PubSub.publish(pubsub, live);
151 yield* (yield* Deferred.await(subscribed)).shutdownHook.await;
152 expect(yield* PubSub.size(pubsub)).toBe(0);
153 const result = yield* pull.pipe(Effect.result);
154 expect(result._tag).toBe("Failure");
155 if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
156 }),
157 ),
158 );
159
160 it.effect("lets a fast reader replay a database page larger than both buffer limits", () =>
161 Effect.scoped(
162 Effect.gen(function* () {
163 const pubsub = yield* PubSub.unbounded<Event>();
164 const events = Array.from({ length: 20 }, (_, index) => ({
165 sequence: index + 1,
166 text: "historical event",
167 }));
168 const replayed = yield* replayAndBufferLiveEvents(
169 {
170 subscribe: PubSub.subscribe(pubsub),
171 latestSequence: Effect.succeed(20),
172 replay: () => Stream.fromIterable(events),
173 },
174 { maxItems: 2, maxSerializedBytes: 100 },
175 ).pipe(Stream.take(20), Stream.runCollect);
176 expect(replayed).toEqual(events);
177 expect(yield* PubSub.size(pubsub)).toBe(0);
178 }),
179 ),
180 );
181
182 it.effect(
183 "filters unrelated events before buffering and deduplicates the replay/live overlap",
184 () =>
185 Effect.scoped(
186 Effect.gen(function* () {
187 const pubsub = yield* PubSub.unbounded<Event>();
188 const highWaterStarted = yield* Deferred.make<void>();
189 const highWater = yield* Deferred.make<number>();
190 const first = { sequence: 1, text: "first", threadId: "selected" };
191 const overlap = { sequence: 2, text: "overlap", threadId: "selected" };
192 const last = { sequence: 10, text: "last", threadId: "selected" };
193 const reader = yield* replayAndBufferLiveEvents(
194 {
195 subscribe: PubSub.subscribe(pubsub),
196 latestSequence: Deferred.succeed(highWaterStarted, undefined).pipe(
197 Effect.andThen(Deferred.await(highWater)),
198 ),
199 replay: () => Stream.make(first, overlap),
200 filter: (event) => event.threadId === "selected",
201 },
202 { maxItems: 4 },
203 ).pipe(Stream.take(3), Stream.runCollect, Effect.forkScoped);
204 yield* Deferred.await(highWaterStarted);
205 yield* PubSub.publishAll(pubsub, [
206 overlap,
207 ...Array.from({ length: 6 }, (_, index) => ({
208 sequence: index + 3,
209 text: "unrelated",
210 threadId: "other",
211 })),
212 last,
213 ]);
214 yield* Deferred.succeed(highWater, 2);
215 expect(yield* Fiber.join(reader)).toEqual([first, overlap, last]);
216 expect(yield* PubSub.size(pubsub)).toBe(0);
217 }),
218 ),
219 );
220
221 it.effect(
222 "caps raw and projected stages while projection and client acknowledgement are blocked",
223 () =>
224 Effect.scoped(
225 Effect.gen(function* () {
226 const pubsub = yield* PubSub.unbounded<Event>();
227 const subscribed = yield* Deferred.make<PubSub.Subscription<Event>>();
228 const projectionStarted = yield* Deferred.make<void>();
229 const projectionClosed = yield* Deferred.make<void>();
230 const releaseProjection = yield* Deferred.make<void>();
231 const source = replayAndBufferLiveEvents(
232 {
233 subscribe: PubSub.subscribe(pubsub).pipe(
234 Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)),
235 ),
236 latestSequence: Effect.succeed(0),
237 replay: () => Stream.empty,
238 },
239 { maxItems: 2 },
240 ).pipe(
241 Stream.mapEffect((event) =>
242 event.sequence === 3
243 ? Deferred.succeed(projectionStarted, undefined).pipe(
244 Effect.andThen(Deferred.await(releaseProjection)),
245 Effect.as(event),
246 )
247 : Effect.succeed(event),
248 ),
249 Stream.ensuring(Deferred.succeed(projectionClosed, undefined)),
250 );
251 const pull = yield* Stream.toPull(bufferLiveStream(source, { maxItems: 2 }));
252 const firstPull = yield* pull.pipe(Effect.forkScoped);
253 const subscription = yield* Deferred.await(subscribed);
254 yield* PubSub.publish(pubsub, { sequence: 1, text: "awaiting ACK" });
255 expect(yield* Fiber.join(firstPull)).toEqual([{ sequence: 1, text: "awaiting ACK" }]);
256 yield* PubSub.publish(pubsub, { sequence: 2, text: "projected tail" });
257 yield* PubSub.publish(pubsub, { sequence: 3, text: "projecting" });
258 yield* Deferred.await(projectionStarted);
259 yield* PubSub.publishAll(pubsub, [
260 { sequence: 4, text: "raw tail" },
261 { sequence: 5, text: "overflow" },
262 ]);
263 yield* subscription.shutdownHook.await;
264 expect(yield* PubSub.size(pubsub)).toBe(0);
265 yield* Deferred.succeed(releaseProjection, undefined);
266 yield* Deferred.await(projectionClosed);
267 const result = yield* pull.pipe(Effect.result);
268 expect(result._tag).toBe("Failure");
269 if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
270 }),
271 ),
272 );
273});