Open History to see the last commit
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 * as Clock from "effect/Clock";
17import * as Effect from "effect/Effect";
18import * as Schema from "effect/Schema";
19import type * as SqlClient from "effect/sql/SqlClient";
20import * as Stream from "effect/Stream";
21
22export function buildActiveShellSnapshot(input: {
23 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
24 readonly threads: OrchestrationV2ThreadShellSnapshot;
25 readonly snapshotSequence: number;
26}): OrchestrationV2ShellSnapshot {
27 return {
28 schemaVersion: input.threads.schemaVersion,
29 snapshotSequence: input.snapshotSequence,
30 projects: input.projects,
31 threads: input.threads.threads,
32 archivedThreads: [],
33 };
34}
35
36/**
37 * One transaction covers the reads so they agree; the threads are decoded after it commits,
38 * because the server shares one SQLite connection and decoding a large shell takes longer than
39 * reading it.
40 */
41export const loadShellSnapshotParts = Effect.fn("ShellStream.loadShellSnapshotParts")(function* <
42 E1,
43 E2,
44 E3,
45 E4,
46>(input: {
47 readonly sql: SqlClient.SqlClient;
48 readonly readThreads: Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E2>, E1>;
49 readonly listProjects: Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, E3>;
50 readonly latestSequence: Effect.Effect<number, E4>;
51}) {
52 const read = yield* input.sql
53 .withTransaction(
54 Effect.all({
55 decodeThreads: input.readThreads,
56 projects: input.listProjects,
57 snapshotSequence: input.latestSequence,
58 }),
59 )
60 .pipe(NodeSqliteClient.readOnly);
61 return {
62 projects: read.projects,
63 threads: yield* read.decodeThreads,
64 snapshotSequence: read.snapshotSequence,
65 };
66});
67
68export type ShellApplicationEvent =
69 | Pick<
70 Extract<ApplicationStoredEvent, { readonly aggregateKind: "project" }>,
71 "aggregateKind" | "aggregateId" | "type" | "sequence"
72 >
73 | {
74 readonly sequence: number;
75 readonly event: Pick<OrchestrationV2StoredEvent["event"], "threadId">;
76 };
77
78/** Shell updates refetch an aggregate; drop transcript bodies before retaining an event. */
79export function toShellApplicationEvent(stored: ApplicationStoredEvent): ShellApplicationEvent {
80 return "aggregateKind" in stored
81 ? {
82 aggregateKind: stored.aggregateKind,
83 aggregateId: stored.aggregateId,
84 type: stored.type,
85 sequence: stored.sequence,
86 }
87 : { sequence: stored.sequence, event: { threadId: stored.event.threadId } };
88}
89
90export function coalesceShellApplicationEvents<A extends ShellApplicationEvent>(
91 events: ReadonlyArray<A>,
92): ReadonlyArray<A> {
93 const latestByAggregate = new Map<string, A>();
94 for (const stored of events) {
95 const key =
96 "aggregateKind" in stored
97 ? `project:${stored.aggregateId}`
98 : `thread:${stored.event.threadId}`;
99 latestByAggregate.set(key, stored);
100 }
101 return Array.from(latestByAggregate.values()).sort(
102 (left, right) => left.sequence - right.sequence,
103 );
104}
105
106/**
107 * Prevents a newer marked enrichment from landing before the unmarked authoritative initial
108 * snapshot.
109 */
110export function composeShellStreamWithEnrichment<A, E, R, A2, E2, R2, A3, E3, R3>(input: {
111 readonly initial: Stream.Stream<A, E, R>;
112 readonly tail: Stream.Stream<A2, E2, R2>;
113 readonly enrichment: Stream.Stream<A3, E3, R3>;
114}): Stream.Stream<A | A2 | A3, E | E2 | E3, R | R2 | R3> {
115 return Stream.concat(input.initial, Stream.merge(input.tail, input.enrichment));
116}
117
118const sameProjects = Schema.toEquivalence(Schema.Array(ProjectShellSchema));
119
120export function dedupeShellEnrichment<E, R>(
121 stream: Stream.Stream<OrchestrationV2ShellStreamItem, E, R>,
122): Stream.Stream<OrchestrationV2ShellStreamItem, E, R> {
123 return Stream.suspend(() => {
124 let previous:
125 | {
126 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
127 readonly roots: ReadonlySet<string>;
128 }
129 | undefined;
130 return stream.pipe(
131 Stream.filter((item) => {
132 if (item.kind !== "snapshot") {
133 if (item.kind === "project.updated" || item.kind === "project.removed")
134 previous = undefined;
135 return true;
136 }
137 if (
138 item.resolvedRepositoryIdentityRoots === undefined ||
139 item.snapshot.threads.length > 0 ||
140 item.snapshot.archivedThreads.length > 0
141 ) {
142 previous = undefined;
143 return true;
144 }
145 const roots = new Set(item.resolvedRepositoryIdentityRoots);
146 const prior = previous;
147 if (
148 prior !== undefined &&
149 roots.size === prior.roots.size &&
150 [...roots].every((root) => prior.roots.has(root)) &&
151 sameProjects(prior.projects, item.snapshot.projects)
152 )
153 return false;
154 previous = { projects: item.snapshot.projects, roots };
155 return true;
156 }),
157 );
158 });
159}
160
161export function shellStreamItemFromEnrichmentRefresh(input: {
162 readonly snapshot: OrchestrationV2ShellSnapshot;
163 readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>;
164}): Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
165 const resolvedRepositoryIdentityRoots = [
166 ...new Set(input.changes.map((change) => change.workspaceRoot)),
167 ];
168 return {
169 kind: "snapshot",
170 snapshot: {
171 ...input.snapshot,
172 projects: input.snapshot.projects.filter((project) =>
173 resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
174 ),
175 threads: [],
176 archivedThreads: [],
177 },
178 resolvedRepositoryIdentityRoots,
179 };
180}
181
182export function shellStreamItemsFromInitialSnapshot(input: {
183 readonly snapshot: OrchestrationV2ShellSnapshot;
184 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
185}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
186 const authoritative = {
187 kind: "snapshot" as const,
188 snapshot: input.snapshot,
189 };
190 if (input.resolvedRepositoryIdentityRoots.length === 0) {
191 return [authoritative];
192 }
193 return [
194 authoritative,
195 {
196 kind: "snapshot" as const,
197 snapshot: {
198 ...input.snapshot,
199 projects: input.snapshot.projects.filter((project) =>
200 input.resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
201 ),
202 threads: [],
203 archivedThreads: [],
204 },
205 resolvedRepositoryIdentityRoots: [...new Set(input.resolvedRepositoryIdentityRoots)],
206 },
207 ];
208}
209
210export function shellStreamItemsFromResumeSnapshot(input: {
211 readonly snapshot: OrchestrationV2ShellSnapshot;
212 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
213}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
214 return shellStreamItemsFromInitialSnapshot(input).filter(
215 (item) => item.resolvedRepositoryIdentityRoots !== undefined,
216 );
217}
218
219const sameThreadShell = Schema.toEquivalence(ThreadShellSchema);
220
221const UNCHANGED_THREAD_SHELL_RESEND_MS = 5_000;
222
223/**
224 * A skipped delta leaves the client cursor behind, and a resume replays the events after that
225 * cursor. So an unchanged shell is still sent once its last send is
226 * `UNCHANGED_THREAD_SHELL_RESEND_MS` old.
227 */
228export function skipUnchangedThreadShells<A extends OrchestrationV2ShellStreamItem, E, R>(
229 stream: Stream.Stream<A, E, R>,
230): Stream.Stream<A, E, R> {
231 return Stream.suspend(() => {
232 const lastSent = new Map<
233 OrchestrationV2ThreadShell["id"],
234 { readonly thread: OrchestrationV2ThreadShell; readonly sentAt: number }
235 >();
236 return stream.pipe(
237 Stream.filterEffect((item) =>
238 Effect.map(Clock.currentTimeMillis, (now) => {
239 if (item.kind === "thread.removed") {
240 lastSent.delete(item.threadId);
241 return true;
242 }
243 if (item.kind !== "thread.updated") return true;
244 const previous = lastSent.get(item.thread.id);
245 if (
246 previous !== undefined &&
247 now - previous.sentAt < UNCHANGED_THREAD_SHELL_RESEND_MS &&
248 sameThreadShell(
249 { ...item.thread, updatedAt: previous.thread.updatedAt },
250 previous.thread,
251 )
252 ) {
253 return false;
254 }
255 lastSent.set(item.thread.id, { thread: item.thread, sentAt: now });
256 return true;
257 }),
258 ),
259 );
260 });
261}
262
263export function coalesceStoredThreadEvents(
264 events: ReadonlyArray<OrchestrationV2StoredEvent>,
265): ReadonlyArray<OrchestrationV2StoredEvent> {
266 const latestByThreadId = new Map<string, OrchestrationV2StoredEvent>();
267 for (const stored of events) {
268 latestByThreadId.set(stored.event.threadId, stored);
269 }
270 return Array.from(latestByThreadId.values()).sort(
271 (left, right) => left.sequence - right.sequence,
272 );
273}
274
275export function shellStreamItemFromThreadShell(input: {
276 readonly stored: Extract<ShellApplicationEvent, { readonly event: unknown }>;
277 readonly shell: OrchestrationV2ThreadShell | null;
278}): Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
279 if (input.shell !== null) {
280 if (input.shell.archivedAt !== null) {
281 return {
282 kind: "thread.removed",
283 sequence: input.stored.sequence,
284 location: "active",
285 threadId: input.shell.id,
286 };
287 }
288 return {
289 kind: "thread.updated",
290 sequence: input.stored.sequence,
291 location: "active",
292 thread: input.shell,
293 };
294 }
295
296 return {
297 kind: "thread.removed",
298 sequence: input.stored.sequence,
299 location: "active",
300 threadId: input.stored.event.threadId,
301 };
302}
303
304export function archivedShellStreamItemFromThreadShell(input: {
305 readonly stored: OrchestrationV2StoredEvent;
306 readonly shell: OrchestrationV2ThreadShell | null;
307}): Exclude<OrchestrationV2ArchivedShellStreamItem, { readonly kind: "snapshot" }> | null {
308 if (input.shell !== null && input.shell.archivedAt !== null) {
309 return {
310 kind: "thread.updated",
311 sequence: input.stored.sequence,
312 thread: input.shell,
313 };
314 }
315 if (
316 input.stored.event.type === "thread.unarchived" ||
317 (input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null)
318 ) {
319 return {
320 kind: "thread.removed",
321 sequence: input.stored.sequence,
322 threadId: input.stored.event.threadId,
323 };
324 }
325 return null;
326}