Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadDeletionReactor.ts

124 lines4.4 KB

1import type { OrchestrationEvent } from "@t3tools/contracts";
2import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Stream from "effect/Stream";
7import * as SubscriptionRef from "effect/SubscriptionRef";
8​
9import { ProviderService } from "../../provider/Services/ProviderService.ts";
10import * as TerminalManager from "../../terminal/Manager.ts";
11import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
12import {
13 ThreadDeletionReactor,
14 type ThreadDeletionReactorShape,
15} from "../Services/ThreadDeletionReactor.ts";
16import { forkParked } from "../../serverActivation.ts";
17​
18type ThreadDeletedEvent = Extract<OrchestrationEvent, { type: "thread.deleted" }>;
19​
20export const logCleanupCauseUnlessInterrupted = <R, E>({
21 effect,
22 message,
23 threadId,
24}: {
25 readonly effect: Effect.Effect<void, E, R>;
26 readonly message: string;
27 readonly threadId: ThreadDeletedEvent["payload"]["threadId"];
28}): Effect.Effect<void, E, R> =>
29 effect.pipe(
30 Effect.catchCause((cause) => {
31 if (Cause.hasInterruptsOnly(cause)) {
32 return Effect.failCause(cause);
33 }
34 return Effect.logDebug(message, {
35 threadId,
36 cause: Cause.pretty(cause),
37 });
38 }),
39 );
40​
41const make = Effect.gen(function* () {
42 const orchestrationEngine = yield* OrchestrationEngineService;
43 const providerService = yield* ProviderService;
44 const terminalManager = yield* TerminalManager.TerminalManager;
45​
46 const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
47 logCleanupCauseUnlessInterrupted({
48 effect: providerService.stopSession({ threadId }),
49 message: "thread deletion cleanup skipped provider session stop",
50 threadId,
51 });
52​
53 const closeThreadTerminals = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
54 logCleanupCauseUnlessInterrupted({
55 effect: terminalManager.close({ threadId, deleteHistory: true }),
56 message: "thread deletion cleanup skipped terminal close",
57 threadId,
58 });
59​
60 const processThreadDeleted = Effect.fn("processThreadDeleted")(function* (
61 event: ThreadDeletedEvent,
62 ) {
63 const { threadId } = event.payload;
64 yield* stopProviderSession(threadId);
65 yield* closeThreadTerminals(threadId);
66 });
67​
68 const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>
69 processThreadDeleted(event).pipe(
70 Effect.catchCause((cause) => {
71 if (Cause.hasInterruptsOnly(cause)) {
72 return Effect.failCause(cause);
73 }
74 return Effect.logWarning("thread deletion reactor failed to process event", {
75 eventType: event.type,
76 threadId: event.payload.threadId,
77 cause: Cause.pretty(cause),
78 });
79 }),
80 );
81​
82 const worker = yield* makeDrainableWorker(processThreadDeletedSafely);
83​
84 // Highest event sequence the subscriber has handed to the worker. Waiting
85 // through a successful thread.created sequence covers every deletion that
86 // was ahead of that create in the engine queue; the worker drain then covers
87 // the in-flight cleanup.
88 const seenSequence = yield* SubscriptionRef.make(0);
89 const noteSeen = (sequence: number) =>
90 SubscriptionRef.update(seenSequence, (seen) => Math.max(seen, sequence));
91​
92 const start: ThreadDeletionReactorShape["start"] = Effect.fn("start")(function* () {
93 yield* forkParked(
94 Stream.runForEach(
95 orchestrationEngine.streamDomainEvents.pipe(
96 // Events that landed before the subscription are not replayed, so
97 // start the watermark at the current head instead of zero.
98 Stream.onStart(orchestrationEngine.latestSequence.pipe(Effect.flatMap(noteSeen))),
99 ),
100 (event) =>
101 (event.type === "thread.deleted" ? worker.enqueue(event) : Effect.void).pipe(
102 Effect.andThen(noteSeen(event.sequence)),
103 ),
104 ),
105 );
106 });
107​
108 const drainThrough: ThreadDeletionReactorShape["drainThrough"] = Effect.fn(
109 "ThreadDeletionReactor.drainThrough",
110 )(function* (target) {
111 yield* SubscriptionRef.changes(seenSequence).pipe(
112 Stream.filter((seen) => seen >= target),
113 Stream.runHead,
114 );
115 yield* worker.drain;
116 });
117​
118 return {
119 start,
120 drainThrough,
121 } satisfies ThreadDeletionReactorShape;
122});
123​
124export const ThreadDeletionReactorLive = Layer.effect(ThreadDeletionReactor, make);