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