Open History to see the last commit
1import * as Schema from "effect/Schema";
2import * as Arr from "effect/Array";
3import type * as Cause from "effect/Cause";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Queue from "effect/Queue";
8import * as PubSub from "effect/PubSub";
9import * as Scope from "effect/Scope";
10import * as Semaphore from "effect/Semaphore";
11import * as Stream from "effect/Stream";
12
13export class LiveStreamBufferError extends Schema.TaggedError<LiveStreamBufferError>()(
14 "LiveStreamBufferError",
15 { message: Schema.String },
16) {}
17
18export const LIVE_STREAM_MAX_ITEMS = 1_000;
19const LIVE_STREAM_MAX_SERIALIZED_BYTES = 8 * 1024 * 1024;
20
21export interface RetainedLiveItem<A> {
22 readonly value: A;
23 readonly serializedBytes: number;
24}
25
26// Published events are immutable and shared across subscriptions. Measure each
27// object once without keeping the event or its serialized copy alive.
28const serializedSizes = new WeakMap<object, number>();
29
30function serializedSize(value: object): number {
31 const cached = serializedSizes.get(value);
32 if (cached !== undefined) {
33 return cached;
34 }
35 const bytes = Buffer.byteLength(JSON.stringify(value));
36 serializedSizes.set(value, bytes);
37 return bytes;
38}
39
40export const makeLiveStreamBudget = Effect.fn("makeLiveStreamBudget")(function* (limits?: {
41 readonly maxItems?: number;
42 readonly maxSerializedBytes?: number;
43}) {
44 const maxItems = limits?.maxItems ?? LIVE_STREAM_MAX_ITEMS;
45 const maxSerializedBytes = limits?.maxSerializedBytes ?? LIVE_STREAM_MAX_SERIALIZED_BYTES;
46 const failed = yield* Deferred.make<never, LiveStreamBufferError>();
47 const cleanupComplete = yield* Deferred.make<void>();
48 let failure: LiveStreamBufferError | undefined;
49 const retained = new Set<RetainedLiveItem<unknown>>();
50 let retainedSerializedBytes = 0;
51
52 const release = (items: Iterable<RetainedLiveItem<unknown>>) => {
53 for (const item of items) {
54 if (!retained.delete(item)) {
55 continue;
56 }
57 retainedSerializedBytes -= item.serializedBytes;
58 }
59 };
60 yield* Effect.addFinalizer(() =>
61 Effect.sync(() => release(retained)).pipe(
62 Effect.andThen(Deferred.succeed(cleanupComplete, undefined)),
63 ),
64 );
65
66 const check = Effect.suspend(() => (failure ? Effect.fail(failure) : Effect.void));
67
68 const overflow = Effect.fn("LiveStreamBudget.overflow")(function* (
69 nextItems: number,
70 nextSerializedBytes: number,
71 ) {
72 failure ??= new LiveStreamBufferError({
73 message: "The live event buffer is full. Resume from the last received sequence.",
74 });
75 yield* Deferred.fail(failed, failure);
76 yield* Effect.logWarning("orchestration live event buffer is full", {
77 retainedItems: retained.size,
78 retainedSerializedBytes,
79 nextItems,
80 nextSerializedBytes,
81 maxItems,
82 maxSerializedBytes,
83 });
84 return yield* failure;
85 });
86
87 const retain = <A extends object>(value: A, payload: object = value) =>
88 Effect.suspend(() => {
89 if (failure) {
90 return Effect.fail(failure);
91 }
92 const serializedBytes = serializedSize(payload);
93 const nextItems = retained.size + 1;
94 const nextSerializedBytes = retainedSerializedBytes + serializedBytes;
95 if (nextItems > maxItems || nextSerializedBytes > maxSerializedBytes) {
96 return overflow(nextItems, nextSerializedBytes);
97 }
98 const item = { value, serializedBytes };
99 retained.add(item);
100 retainedSerializedBytes = nextSerializedBytes;
101 return Effect.succeed(item);
102 });
103
104 const replace = <A extends object>(
105 previous: ReadonlyArray<RetainedLiveItem<unknown>>,
106 values: ReadonlyArray<A>,
107 payload: (value: A) => object = (value) => value,
108 ) =>
109 Effect.suspend(() => {
110 if (failure) {
111 return Effect.fail(failure);
112 }
113 const next = values.map((value) => ({
114 value,
115 serializedBytes: serializedSize(payload(value)),
116 }));
117 let nextItems = retained.size + next.length;
118 let nextSerializedBytes =
119 retainedSerializedBytes + next.reduce((sum, item) => sum + item.serializedBytes, 0);
120 for (const item of previous) {
121 if (retained.has(item)) {
122 nextItems -= 1;
123 nextSerializedBytes -= item.serializedBytes;
124 }
125 }
126 if (nextItems > maxItems || nextSerializedBytes > maxSerializedBytes) {
127 return overflow(nextItems, nextSerializedBytes);
128 }
129 release(previous);
130 for (const item of next) {
131 retained.add(item);
132 }
133 retainedSerializedBytes = nextSerializedBytes;
134 return Effect.succeed(next);
135 });
136
137 const deliver = <A, E, R>(stream: Stream.Stream<RetainedLiveItem<A>, E, R>) =>
138 Stream.fromPull(
139 Effect.gen(function* () {
140 yield* check;
141 const sourceScope = yield* Scope.fork(yield* Effect.scope);
142 const source = {
143 pull: yield* Stream.toPull(stream).pipe(Scope.provide(sourceScope)),
144 };
145 let inFlight: ReadonlyArray<RetainedLiveItem<A>> = [];
146 yield* Effect.addFinalizer(() =>
147 Effect.sync(() => {
148 release(inFlight);
149 inFlight = [];
150 source.pull = Effect.interrupt;
151 }),
152 );
153 yield* Deferred.await(failed).pipe(
154 Effect.catchTags({
155 LiveStreamBufferError: (error) =>
156 Effect.sync(() => {
157 // A grouped source can retain its own pending chunk. Close it
158 // and release the pull closure without waiting for an RPC ACK.
159 source.pull = Effect.interrupt;
160 }).pipe(
161 Effect.andThen(Scope.close(sourceScope, Exit.fail(error))),
162 Effect.andThen(
163 Effect.sync(() => {
164 const delivered = new Set<RetainedLiveItem<unknown>>(inFlight);
165 for (const item of retained) {
166 if (!delivered.has(item)) {
167 release([item]);
168 }
169 }
170 }),
171 ),
172 Effect.andThen(Deferred.succeed(cleanupComplete, undefined)),
173 ),
174 }),
175 Effect.forkScoped,
176 );
177 // @effect-diagnostics-next-line returnEffectInGen:off - Stream.fromPull needs the pull effect as its result.
178 return Effect.gen(function* () {
179 // RpcServer requests the next batch only after the client ACKs this
180 // one. Removing items from a queue alone does not mean delivery ended.
181 release(inFlight);
182 inFlight = [];
183 yield* check;
184 const items = yield* Effect.raceFirst(source.pull, Deferred.await(failed));
185 inFlight = items;
186 yield* check;
187 return Arr.map(items, (item) => item.value);
188 });
189 }),
190 ).pipe(Stream.scoped);
191
192 return {
193 retain,
194 replace,
195 release,
196 deliver,
197 check,
198 failed: Deferred.await(failed),
199 closed: Deferred.await(cleanupComplete),
200 usage: Effect.sync(() => ({ retainedItems: retained.size, retainedSerializedBytes })),
201 };
202});
203
204type LiveStreamBudget = Effect.Success<ReturnType<typeof makeLiveStreamBudget>>;
205
206type LiveStreamLimits = {
207 readonly maxItems?: number;
208 readonly maxSerializedBytes?: number;
209};
210
211const retainLiveStream = Effect.fn("LiveStreamBudget.retainLiveStream")(function* <
212 A extends object,
213 E,
214 R,
215>(source: Stream.Stream<A, E, R>, budget: LiveStreamBudget) {
216 const queue = yield* Queue.unbounded<
217 RetainedLiveItem<A>,
218 E | LiveStreamBufferError | Cause.Done
219 >();
220 let closed = false;
221 const close = Effect.fn("LiveStreamBudget.close")(function* (error?: LiveStreamBufferError) {
222 if (closed) return;
223 closed = true;
224 budget.release(yield* Queue.clear(queue).pipe(Effect.orElseSucceed(() => [])));
225 if (error) yield* Queue.fail(queue, error);
226 yield* Queue.shutdown(queue);
227 });
228 yield* Effect.addFinalizer(() => close());
229 yield* budget.failed.pipe(Effect.catchTags({ LiveStreamBufferError: close }), Effect.forkScoped);
230 yield* source.pipe(
231 Stream.runForEach((value) =>
232 budget.retain(value).pipe(
233 Effect.flatMap((item) => Queue.offer(queue, item)),
234 Effect.uninterruptible,
235 ),
236 ),
237 Effect.raceFirst(budget.failed),
238 Effect.exit,
239 Effect.flatMap((exit) =>
240 Exit.isFailure(exit) ? Queue.failCause(queue, exit.cause) : Queue.end(queue),
241 ),
242 Effect.forkScoped({ startImmediately: true }),
243 );
244 return Stream.fromQueue(queue);
245});
246
247export const bufferLiveStream = <A extends object, E, R>(
248 source: Stream.Stream<A, E, R>,
249 limits?: LiveStreamLimits,
250) =>
251 Stream.unwrap(
252 Effect.gen(function* () {
253 const budget = yield* makeLiveStreamBudget(limits);
254 return budget.deliver(yield* retainLiveStream(source, budget));
255 }),
256 );
257
258/** Coalesce queued full states; delivered states stay charged until the next pull ACKs them. */
259export const bufferLatestLiveStream = <A extends { readonly sequence: number }, E, R>(
260 source: Stream.Stream<A, E, R>,
261 key: (value: A) => string,
262 limits?: LiveStreamLimits,
263) =>
264 Stream.unwrap(
265 Effect.gen(function* () {
266 const budget = yield* makeLiveStreamBudget(limits);
267 const ready = yield* Queue.bounded<void, E | LiveStreamBufferError | Cause.Done>(1);
268 const mutex = yield* Semaphore.make(1);
269 const pending = new Map<string, RetainedLiveItem<A>>();
270 let closed = false;
271 const close = (error?: LiveStreamBufferError) =>
272 mutex.withPermit(
273 Effect.gen(function* () {
274 if (closed) return;
275 closed = true;
276 budget.release(pending.values());
277 pending.clear();
278 if (error) yield* Queue.fail(ready, error);
279 yield* Queue.shutdown(ready);
280 }),
281 );
282 yield* Effect.addFinalizer(() => close());
283 yield* budget.failed.pipe(
284 Effect.catchTags({ LiveStreamBufferError: close }),
285 Effect.forkScoped,
286 );
287 yield* source.pipe(
288 Stream.runForEach((value) =>
289 mutex.withPermit(
290 Effect.gen(function* () {
291 yield* budget.check;
292 if (closed) return;
293 const identity = key(value);
294 const previous = pending.get(identity);
295 if (previous && previous.value.sequence >= value.sequence) return;
296 const wasEmpty = pending.size === 0;
297 const [item] = yield* budget.replace(previous ? [previous] : [], [value]);
298 pending.set(identity, item!);
299 // Only the empty-to-nonempty transition needs a wakeup; replacements
300 // must not leave another token after this batch has drained.
301 if (wasEmpty) yield* Queue.offer(ready, undefined);
302 }).pipe(Effect.uninterruptible),
303 ),
304 ),
305 Effect.raceFirst(budget.failed),
306 Effect.exit,
307 Effect.flatMap((exit) =>
308 Exit.isFailure(exit) ? Queue.failCause(ready, exit.cause) : Queue.end(ready),
309 ),
310 Effect.forkScoped({ startImmediately: true }),
311 );
312 return budget.deliver(
313 Stream.fromPull(
314 Effect.succeed(
315 Queue.take(ready).pipe(
316 Effect.andThen(
317 mutex.withPermit(
318 Effect.sync(() => {
319 const items = Array.from(pending.values()).sort(
320 (left, right) => left.value.sequence - right.value.sequence,
321 );
322 pending.clear();
323 // Moving to delivery preserves the budget charge until ACK.
324 return items as Arr.NonEmptyArray<RetainedLiveItem<A>>;
325 }),
326 ),
327 ),
328 ),
329 ),
330 ),
331 );
332 }),
333 );
334
335/**
336 * Subscribe and start draining before reading the high-water mark. A blocked
337 * catch-up query or an unacknowledged replay batch must not strand an unbounded
338 * PubSub subscription.
339 */
340type ReplayLiveInput<A extends { readonly sequence: number }, E, R> = {
341 readonly subscribe: Effect.Effect<PubSub.Subscription<A>, never, Scope.Scope>;
342 readonly latestSequence: Effect.Effect<number, E, R>;
343 readonly replay: (throughSequence: number) => Stream.Stream<A, E, R>;
344 readonly afterSequence?: number;
345 readonly filter?: (event: A) => boolean;
346};
347
348export const replayAndBufferLiveEvents = <A extends { readonly sequence: number }, E, R>(
349 input: ReplayLiveInput<A, E, R>,
350 limits?: LiveStreamLimits,
351) => replayAndBufferProjectedLiveEvents({ ...input, project: (event: A) => event }, limits);
352
353export const replayAndBufferProjectedLiveEvents = <
354 A extends { readonly sequence: number },
355 B extends { readonly sequence: number },
356 E,
357 R,
358>(
359 input: ReplayLiveInput<A, E, R> & { readonly project: (event: A) => B },
360 limits?: LiveStreamLimits,
361) =>
362 Stream.unwrap(
363 Effect.gen(function* () {
364 const budget = yield* makeLiveStreamBudget(limits);
365 const subscriptionScope = yield* Scope.fork(yield* Effect.scope);
366 const subscription = yield* input.subscribe.pipe(Scope.provide(subscriptionScope));
367 let throughSequence = input.afterSequence ?? 0;
368 const live = yield* retainLiveStream(
369 // Taking one event at a time avoids retaining an uncharged PubSub batch
370 // while the drain charges events to the budget.
371 Stream.fromEffectRepeat(PubSub.take(subscription)).pipe(
372 Stream.filter(
373 (event) => event.sequence > throughSequence && (input.filter?.(event) ?? true),
374 ),
375 Stream.map(input.project),
376 Stream.ensuring(Scope.close(subscriptionScope, Exit.void)),
377 ),
378 budget,
379 );
380 const replay = Stream.unwrap(
381 input.latestSequence.pipe(
382 Effect.map((highWater) => {
383 throughSequence = Math.max(highWater, input.afterSequence ?? 0);
384 return input.replay(highWater).pipe(
385 // The finite database page is independent of the live tail.
386 // Charge only the item being delivered so a fast reader can
387 // consume a page larger than the budget without overflowing.
388 Stream.rechunk(1),
389 Stream.mapEffect((event) => budget.retain(input.project(event))),
390 );
391 }),
392 ),
393 );
394 return budget.deliver(
395 Stream.concat(
396 replay,
397 live.pipe(
398 Stream.filter((item) => {
399 if (item.value.sequence > throughSequence) return true;
400 budget.release([item]);
401 return false;
402 }),
403 ),
404 ),
405 );
406 }),
407 );