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

ShellStream.ts

411 lines13.6 KB

1import type {
2 ApplicationStoredEvent,
3 OrchestrationProjectShell,
4 OrchestrationV2ArchivedShellStreamItem,
5 OrchestrationV2ShellSnapshot,
6 OrchestrationV2ThreadShell,
7 OrchestrationV2ThreadShellSnapshot,
8 OrchestrationV2ShellStreamItem,
9 OrchestrationV2StoredEvent,
10} from "@t3tools/contracts";
11import {
12 OrchestrationProjectShell as ProjectShellSchema,
13 OrchestrationV2ThreadShell as ThreadShellSchema,
14} from "@t3tools/contracts";
15import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
16import type * as Arr from "effect/Array";
17import type * as Cause from "effect/Cause";
18import * as Clock from "effect/Clock";
19import * as Deferred from "effect/Deferred";
20import * as Effect from "effect/Effect";
21import * as Exit from "effect/Exit";
22import * as Queue from "effect/Queue";
23import * as Schema from "effect/Schema";
24import type * as SqlClient from "effect/sql/SqlClient";
25import * as Stream from "effect/Stream";
26​
27import { bufferLatestLiveStream } from "./LiveStreamBudget.ts";
28​
29type ShellDelta = Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>;
30​
31/** Snapshots, synchronization, and enrichment markers must bypass full-state coalescing. */
32export const bufferShellLiveStream = <E, R>(
33 source: Stream.Stream<ShellDelta, E, R>,
34 limits?: { readonly maxItems?: number; readonly maxSerializedBytes?: number },
35) =>
36 bufferLatestLiveStream(
37 source,
38 (item) => {
39 switch (item.kind) {
40 case "project.updated":
41 return `project:${item.project.id}`;
42 case "project.removed":
43 return `project:${item.projectId}`;
44 case "thread.updated":
45 return `thread:${item.location}:${item.thread.id}`;
46 case "thread.removed":
47 return `thread:${item.location}:${item.threadId}`;
48 }
49 },
50 limits,
51 );
52​
53export function buildActiveShellSnapshot(input: {
54 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
55 readonly threads: OrchestrationV2ThreadShellSnapshot;
56 readonly snapshotSequence: number;
57}): OrchestrationV2ShellSnapshot {
58 return {
59 schemaVersion: input.threads.schemaVersion,
60 snapshotSequence: input.snapshotSequence,
61 projects: input.projects,
62 threads: input.threads.threads,
63 archivedThreads: [],
64 };
66​
67/**
68 * One transaction covers the reads so they agree; the threads are decoded after it commits,
69 * because the server shares one SQLite connection and decoding a large shell takes longer than
70 * reading it.
71 */
72export const loadShellSnapshotParts = Effect.fn("ShellStream.loadShellSnapshotParts")(function* <
73 E1,
74 E2,
75 E3,
76 E4,
77>(input: {
78 readonly sql: SqlClient.SqlClient;
79 readonly readThreads: Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E2>, E1>;
80 readonly listProjects: Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, E3>;
81 readonly latestSequence: Effect.Effect<number, E4>;
82}) {
83 const read = yield* input.sql
84 .withTransaction(
85 Effect.all({
86 decodeThreads: input.readThreads,
87 projects: input.listProjects,
88 snapshotSequence: input.latestSequence,
89 }),
90 )
91 .pipe(NodeSqliteClient.readOnly);
92 return {
93 projects: read.projects,
94 threads: yield* read.decodeThreads,
95 snapshotSequence: read.snapshotSequence,
96 };
97});
98​
99export type ShellApplicationEvent =
100 | Pick<
101 Extract<ApplicationStoredEvent, { readonly aggregateKind: "project" }>,
102 "aggregateKind" | "aggregateId" | "type" | "sequence"
103 >
104 | {
105 readonly sequence: number;
106 readonly event: Pick<OrchestrationV2StoredEvent["event"], "threadId">;
107 };
108​
109/** Shell updates refetch an aggregate; drop transcript bodies before retaining an event. */
110export function toShellApplicationEvent(stored: ApplicationStoredEvent): ShellApplicationEvent {
111 return "aggregateKind" in stored
112 ? {
113 aggregateKind: stored.aggregateKind,
114 aggregateId: stored.aggregateId,
115 type: stored.type,
116 sequence: stored.sequence,
117 }
118 : { sequence: stored.sequence, event: { threadId: stored.event.threadId } };
120​
121export function coalesceShellApplicationEvents<A extends ShellApplicationEvent>(
122 events: ReadonlyArray<A>,
123): ReadonlyArray<A> {
124 const latestByAggregate = new Map<string, A>();
125 for (const stored of events) {
126 const key =
127 "aggregateKind" in stored
128 ? `project:${stored.aggregateId}`
129 : `thread:${stored.event.threadId}`;
130 latestByAggregate.set(key, stored);
131 }
132 return Array.from(latestByAggregate.values()).sort(
133 (left, right) => left.sequence - right.sequence,
134 );
136​
137/**
138 * Prevents a newer marked enrichment from landing before the unmarked authoritative initial
139 * snapshot.
140 */
141export function composeShellStreamWithEnrichment<A, E, R, A2, E2, R2, A3, E3, R3>(input: {
142 readonly initial: Stream.Stream<A, E, R>;
143 readonly tail: Stream.Stream<A2, E2, R2>;
144 readonly enrichment: Stream.Stream<A3, E3, R3>;
145}): Stream.Stream<A | A2 | A3, E | E2 | E3, R | R2 | R3> {
146 const merged = Stream.fromPull(
147 Effect.gen(function* () {
148 const output = yield* Queue.bounded<
149 {
150 readonly items: Arr.NonEmptyReadonlyArray<A2 | A3>;
151 readonly acknowledged?: Deferred.Deferred<void>;
152 },
153 E2 | E3 | Cause.Done
154 >(0);
155 yield* Effect.addFinalizer(() => Queue.shutdown(output));
156 let remaining = 2;
157 const drain = (effect: Effect.Effect<void, E2 | E3, R2 | R3>) =>
158 effect.pipe(
159 Effect.exit,
160 Effect.flatMap((exit) =>
161 Exit.isFailure(exit)
162 ? Queue.failCause(output, exit.cause)
163 : --remaining === 0
164 ? Queue.end(output)
165 : Effect.void,
166 ),
167 Effect.forkScoped,
168 );
169 yield* drain(
170 input.tail.pipe(
171 Stream.runForEachArray((items) =>
172 Effect.gen(function* () {
173 const acknowledged = yield* Deferred.make<void>();
174 yield* Queue.offer(output, { items, acknowledged });
175 yield* Deferred.await(acknowledged);
176 }),
177 ),
178 ),
179 );
180 // Keep draining the sliding enrichment subscription after each handoff,
181 // as Stream.merge does, while only the budgeted tail waits for an ACK.
182 yield* drain(
183 input.enrichment.pipe(Stream.runForEachArray((items) => Queue.offer(output, { items }))),
184 );
185 let previous: Deferred.Deferred<void> | undefined;
186 // Stream.merge pulls ahead after handing off each batch. Wait for the next
187 // downstream pull so shell delivery keeps that batch charged until its RPC ACK.
188 // @effect-diagnostics-next-line returnEffectInGen:off - Stream.fromPull needs the pull effect as its result.
189 return Effect.gen(function* () {
190 if (previous) yield* Deferred.succeed(previous, undefined);
191 const next = yield* Queue.take(output);
192 previous = next.acknowledged;
193 return next.items;
194 });
195 }),
196 ).pipe(Stream.scoped);
197 return Stream.concat(input.initial, merged);
199​
200const sameProjects = Schema.toEquivalence(Schema.Array(ProjectShellSchema));
201​
202export function dedupeShellEnrichment<E, R>(
203 stream: Stream.Stream<OrchestrationV2ShellStreamItem, E, R>,
204): Stream.Stream<OrchestrationV2ShellStreamItem, E, R> {
205 return Stream.suspend(() => {
206 let previous:
207 | {
208 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
209 readonly roots: ReadonlySet<string>;
210 }
211 | undefined;
212 return stream.pipe(
213 Stream.filter((item) => {
214 if (item.kind !== "snapshot") {
215 if (item.kind === "project.updated" || item.kind === "project.removed")
216 previous = undefined;
217 return true;
218 }
219 if (
220 item.resolvedRepositoryIdentityRoots === undefined ||
221 item.snapshot.threads.length > 0 ||
222 item.snapshot.archivedThreads.length > 0
223 ) {
224 previous = undefined;
225 return true;
226 }
227 const roots = new Set(item.resolvedRepositoryIdentityRoots);
228 const prior = previous;
229 if (
230 prior !== undefined &&
231 roots.size === prior.roots.size &&
232 [...roots].every((root) => prior.roots.has(root)) &&
233 sameProjects(prior.projects, item.snapshot.projects)
234 )
235 return false;
236 previous = { projects: item.snapshot.projects, roots };
237 return true;
238 }),
239 );
240 });
242​
243export function shellStreamItemFromEnrichmentRefresh(input: {
244 readonly snapshot: OrchestrationV2ShellSnapshot;
245 readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>;
246}): Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
247 const resolvedRepositoryIdentityRoots = [
248 ...new Set(input.changes.map((change) => change.workspaceRoot)),
249 ];
250 return {
251 kind: "snapshot",
252 snapshot: {
253 ...input.snapshot,
254 projects: input.snapshot.projects.filter((project) =>
255 resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
256 ),
257 threads: [],
258 archivedThreads: [],
259 },
260 resolvedRepositoryIdentityRoots,
261 };
263​
264export function shellStreamItemsFromInitialSnapshot(input: {
265 readonly snapshot: OrchestrationV2ShellSnapshot;
266 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
267}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
268 const authoritative = {
269 kind: "snapshot" as const,
270 snapshot: input.snapshot,
271 };
272 if (input.resolvedRepositoryIdentityRoots.length === 0) {
273 return [authoritative];
274 }
275 return [
276 authoritative,
277 {
278 kind: "snapshot" as const,
279 snapshot: {
280 ...input.snapshot,
281 projects: input.snapshot.projects.filter((project) =>
282 input.resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
283 ),
284 threads: [],
285 archivedThreads: [],
286 },
287 resolvedRepositoryIdentityRoots: [...new Set(input.resolvedRepositoryIdentityRoots)],
288 },
289 ];
291​
292export function shellStreamItemsFromResumeSnapshot(input: {
293 readonly snapshot: OrchestrationV2ShellSnapshot;
294 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
295}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
296 return shellStreamItemsFromInitialSnapshot(input).filter(
297 (item) => item.resolvedRepositoryIdentityRoots !== undefined,
298 );
300​
301const sameThreadShell = Schema.toEquivalence(ThreadShellSchema);
302​
303const UNCHANGED_THREAD_SHELL_RESEND_MS = 5_000;
304​
305/**
306 * A skipped delta leaves the client cursor behind, and a resume replays the events after that
307 * cursor. So an unchanged shell is still sent once its last send is
308 * `UNCHANGED_THREAD_SHELL_RESEND_MS` old.
309 */
310export function skipUnchangedThreadShells<A extends OrchestrationV2ShellStreamItem, E, R>(
311 stream: Stream.Stream<A, E, R>,
312): Stream.Stream<A, E, R> {
313 return Stream.suspend(() => {
314 const lastSent = new Map<
315 OrchestrationV2ThreadShell["id"],
316 { readonly thread: OrchestrationV2ThreadShell; readonly sentAt: number }
317 >();
318 return stream.pipe(
319 Stream.filterEffect((item) =>
320 Effect.map(Clock.currentTimeMillis, (now) => {
321 if (item.kind === "thread.removed") {
322 lastSent.delete(item.threadId);
323 return true;
324 }
325 if (item.kind !== "thread.updated") return true;
326 const previous = lastSent.get(item.thread.id);
327 if (
328 previous !== undefined &&
329 now - previous.sentAt < UNCHANGED_THREAD_SHELL_RESEND_MS &&
330 sameThreadShell(
331 { ...item.thread, updatedAt: previous.thread.updatedAt },
332 previous.thread,
333 )
334 ) {
335 return false;
336 }
337 lastSent.set(item.thread.id, { thread: item.thread, sentAt: now });
338 return true;
339 }),
340 ),
341 );
342 });
344​
345export function coalesceStoredThreadEvents(
346 events: ReadonlyArray<OrchestrationV2StoredEvent>,
347): ReadonlyArray<OrchestrationV2StoredEvent> {
348 const latestByThreadId = new Map<string, OrchestrationV2StoredEvent>();
349 for (const stored of events) {
350 latestByThreadId.set(stored.event.threadId, stored);
351 }
352 return Array.from(latestByThreadId.values()).sort(
353 (left, right) => left.sequence - right.sequence,
354 );
356​
357export function shellStreamItemFromThreadShell(input: {
358 readonly stored: Extract<ShellApplicationEvent, { readonly event: unknown }>;
359 readonly shell: OrchestrationV2ThreadShell | null;
360}): Extract<
361 OrchestrationV2ShellStreamItem,
362 { readonly kind: "thread.updated" | "thread.removed" }
363> {
364 if (input.shell !== null) {
365 if (input.shell.archivedAt !== null) {
366 return {
367 kind: "thread.removed",
368 sequence: input.stored.sequence,
369 location: "active",
370 threadId: input.shell.id,
371 };
372 }
373 return {
374 kind: "thread.updated",
375 sequence: input.stored.sequence,
376 location: "active",
377 thread: input.shell,
378 };
379 }
380​
381 return {
382 kind: "thread.removed",
383 sequence: input.stored.sequence,
384 location: "active",
385 threadId: input.stored.event.threadId,
386 };
388​
389export function archivedShellStreamItemFromThreadShell(input: {
390 readonly stored: OrchestrationV2StoredEvent;
391 readonly shell: OrchestrationV2ThreadShell | null;
392}): Exclude<OrchestrationV2ArchivedShellStreamItem, { readonly kind: "snapshot" }> | null {
393 if (input.shell !== null && input.shell.archivedAt !== null) {
394 return {
395 kind: "thread.updated",
396 sequence: input.stored.sequence,
397 thread: input.shell,
398 };
399 }
400 if (
401 input.stored.event.type === "thread.unarchived" ||
402 (input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null)
403 ) {
404 return {
405 kind: "thread.removed",
406 sequence: input.stored.sequence,
407 threadId: input.stored.event.threadId,
408 };
409 }
410 return null;