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

OrchestrationEngineHarness.integration.ts

413 lines15.0 KB

1import fs from "node:fs";
2import os from "node:os";
3import path from "node:path";
4import { execFileSync } from "node:child_process";
5​
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import {
8 ApprovalRequestId,
9 type OrchestrationEvent,
10 type OrchestrationThread,
11} from "@t3tools/contracts";
12import {
13 Effect,
14 Exit,
15 Layer,
16 ManagedRuntime,
17 Option,
18 Schedule,
19 Schema,
20 Scope,
21 Stream,
22} from "effect";
23​
24import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
25import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
26import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
27import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
28import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
29import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
30import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
31import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts";
32import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
33import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
34import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
35import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
36import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
37import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
38import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
39import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
40import { ProviderService } from "../src/provider/Services/ProviderService.ts";
41import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
42import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
43import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
44import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
45import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
46import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
47import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
48import {
49 OrchestrationEngineService,
50 type OrchestrationEngineShape,
51} from "../src/orchestration/Services/OrchestrationEngine.ts";
52import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
53import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
54​
55import {
56 makeTestProviderAdapterHarness,
57 type TestProviderAdapterHarness,
58} from "./TestProviderAdapter.integration.ts";
59import { ServerConfig } from "../src/config.ts";
60​
61function runGit(cwd: string, args: ReadonlyArray<string>) {
62 return execFileSync("git", args, {
63 cwd,
64 stdio: ["ignore", "pipe", "pipe"],
65 encoding: "utf8",
66 });
68​
69function initializeGitWorkspace(cwd: string) {
70 runGit(cwd, ["init", "--initial-branch=main"]);
71 runGit(cwd, ["config", "user.email", "test@example.com"]);
72 runGit(cwd, ["config", "user.name", "Test User"]);
73 fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
74 runGit(cwd, ["add", "."]);
75 runGit(cwd, ["commit", "-m", "Initial"]);
77​
78export function gitRefExists(cwd: string, ref: string): boolean {
79 try {
80 runGit(cwd, ["show-ref", "--verify", "--quiet", ref]);
81 return true;
82 } catch {
83 return false;
84 }
86​
87export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
88 return runGit(cwd, ["show", `${ref}:${filePath}`]);
90​
91class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()(
92 "WaitForTimeoutError",
93 {
94 description: Schema.String,
95 },
96) {}
97​
98function waitFor<A, E>(
99 read: Effect.Effect<A, E>,
100 predicate: (value: A) => boolean,
101 description: string,
102 timeoutMs?: number,
103): Effect.Effect<A, never>;
104function waitFor<A, B extends A, E>(
105 read: Effect.Effect<A, E>,
106 predicate: (value: A) => value is B,
107 description: string,
108 timeoutMs?: number,
109): Effect.Effect<B, never>;
110function waitFor<A, E>(
111 read: Effect.Effect<A, E>,
112 predicate: (value: A) => boolean,
113 description: string,
114 timeoutMs = 3000,
115): Effect.Effect<A, never> {
116 const RETRY_SIGNAL = "wait_for_retry";
117 const retryIntervalMs = 10;
118 const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
119 const retrySchedule = Schedule.spaced(`${retryIntervalMs} millis`);
120​
121 return read.pipe(
122 Effect.filterOrFail(predicate, () => RETRY_SIGNAL),
123 Effect.retry({
124 schedule: retrySchedule,
125 times: maxRetries,
126 while: (error) => error === RETRY_SIGNAL,
127 }),
128 Effect.mapError((error) =>
129 error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error,
130 ),
131 Effect.orDie,
132 );
134​
135class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<OrchestrationHarnessRuntimeError>()(
136 "OrchestrationHarnessRuntimeError",
137 {
138 operation: Schema.String,
139 cause: Schema.optional(Schema.Defect),
140 },
141) {}
142​
143const tryRuntimePromise = <A>(operation: string, run: () => Promise<A>) =>
144 Effect.tryPromise({
145 try: run,
146 catch: (cause) => new OrchestrationHarnessRuntimeError({ operation, cause }),
147 });
148​
149export interface OrchestrationIntegrationHarness {
150 readonly rootDir: string;
151 readonly workspaceDir: string;
152 readonly dbPath: string;
153 readonly adapterHarness: TestProviderAdapterHarness;
154 readonly engine: OrchestrationEngineShape;
155 readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
156 readonly providerService: ProviderService["Service"];
157 readonly checkpointStore: CheckpointStore["Service"];
158 readonly checkpointRepository: ProjectionCheckpointRepository["Service"];
159 readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];
160 readonly waitForThread: (
161 threadId: string,
162 predicate: (thread: OrchestrationThread) => boolean,
163 timeoutMs?: number,
164 ) => Effect.Effect<OrchestrationThread, never>;
165 readonly waitForDomainEvent: (
166 predicate: (event: OrchestrationEvent) => boolean,
167 timeoutMs?: number,
168 ) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
169 readonly waitForPendingApproval: (
170 requestId: string,
171 predicate: (row: {
172 readonly status: "pending" | "resolved";
173 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
174 readonly resolvedAt: string | null;
175 }) => boolean,
176 timeoutMs?: number,
177 ) => Effect.Effect<
178 {
179 readonly status: "pending" | "resolved";
180 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
181 readonly resolvedAt: string | null;
182 },
183 never
184 >;
185 readonly dispose: Effect.Effect<void, never>;
187​
188export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
189 const sleep = (ms: number) => Effect.sleep(ms);
190 const adapterHarness = yield* makeTestProviderAdapterHarness;
191​
192 const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
193 const workspaceDir = path.join(rootDir, "workspace");
194 const stateDir = path.join(rootDir, "state");
195 const dbPath = path.join(stateDir, "state.sqlite");
196 fs.mkdirSync(workspaceDir, { recursive: true });
197 fs.mkdirSync(stateDir, { recursive: true });
198 initializeGitWorkspace(workspaceDir);
199​
200 const registry: typeof ProviderAdapterRegistry.Service = {
201 getByProvider: (provider) =>
202 provider === "codex"
203 ? Effect.succeed(adapterHarness.adapter)
204 : Effect.fail(new ProviderUnsupportedError({ provider })),
205 listProviders: () => Effect.succeed(["codex"]),
206 };
207​
208 const persistenceLayer = makeSqlitePersistenceLive(dbPath);
209 const orchestrationLayer = OrchestrationEngineLive.pipe(
210 Layer.provide(OrchestrationProjectionPipelineLive),
211 Layer.provide(OrchestrationEventStoreLive),
212 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
213 );
214 const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
215 Layer.provide(ProviderSessionRuntimeRepositoryLive),
216 );
217 const providerLayer = makeProviderServiceLive().pipe(
218 Layer.provide(providerSessionDirectoryLayer),
219 Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
220 );
221​
222 const runtimeServicesLayer = Layer.mergeAll(
223 orchestrationLayer,
224 OrchestrationProjectionSnapshotQueryLive,
225 ProjectionCheckpointRepositoryLive,
226 ProjectionPendingApprovalRepositoryLive,
227 CheckpointStoreLive,
228 providerLayer,
229 );
230 const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
231 Layer.provideMerge(runtimeServicesLayer),
232 );
233 const gitCoreLayer = Layer.succeed(GitCore, {
234 renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
235 Effect.succeed({ branch: input.newBranch }),
236 } as unknown as GitCoreShape);
237 const textGenerationLayer = Layer.succeed(TextGeneration, {
238 generateBranchName: () => Effect.succeed({ branch: null }),
239 } as unknown as TextGenerationShape);
240 const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
241 Layer.provideMerge(runtimeServicesLayer),
242 Layer.provideMerge(gitCoreLayer),
243 Layer.provideMerge(textGenerationLayer),
244 );
245 const checkpointReactorLayer = CheckpointReactorLive.pipe(
246 Layer.provideMerge(runtimeServicesLayer),
247 );
248 const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
249 Layer.provideMerge(runtimeIngestionLayer),
250 Layer.provideMerge(providerCommandReactorLayer),
251 Layer.provideMerge(checkpointReactorLayer),
252 );
253 const layer = orchestrationReactorLayer.pipe(
254 Layer.provide(persistenceLayer),
255 Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
256 Layer.provideMerge(NodeServices.layer),
257 );
258​
259 const runtime = ManagedRuntime.make(layer);
260 const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
261 runtime.runPromise(Effect.service(OrchestrationEngineService)),
262 ).pipe(Effect.orDie);
263 const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
264 runtime.runPromise(Effect.service(OrchestrationReactor)),
265 ).pipe(Effect.orDie);
266 const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
267 runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
268 ).pipe(Effect.orDie);
269 const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
270 runtime.runPromise(Effect.service(ProviderService)),
271 ).pipe(Effect.orDie);
272 const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
273 runtime.runPromise(Effect.service(CheckpointStore)),
274 ).pipe(Effect.orDie);
275 const checkpointRepository = yield* tryRuntimePromise(
276 "load ProjectionCheckpointRepository service",
277 () => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
278 ).pipe(Effect.orDie);
279 const pendingApprovalRepository = yield* tryRuntimePromise(
280 "load ProjectionPendingApprovalRepository service",
281 () => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
282 ).pipe(Effect.orDie);
283​
284 const scope = yield* Scope.make("sequential");
285 yield* tryRuntimePromise("start OrchestrationReactor", () =>
286 runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
287 ).pipe(Effect.orDie);
288 yield* sleep(10);
289​
290 const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
291 threadId,
292 predicate,
293 timeoutMs,
294 ) =>
295 waitFor(
296 snapshotQuery
297 .getSnapshot()
298 .pipe(
299 Effect.map(
300 (snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
301 ),
302 ),
303 (thread): thread is OrchestrationThread => thread !== null && predicate(thread),
304 `projected thread '${threadId}'`,
305 timeoutMs,
306 ) as Effect.Effect<OrchestrationThread, never>;
307​
308 const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
309 predicate,
310 timeoutMs,
311 ) =>
312 waitFor(
313 Stream.runCollect(engine.readEvents(0)).pipe(
314 Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
315 ),
316 (events) => events.some(predicate),
317 "domain event",
318 timeoutMs,
319 );
320​
321 const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
322 requestId,
323 predicate,
324 timeoutMs,
325 ) =>
326 waitFor(
327 pendingApprovalRepository
328 .getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
329 .pipe(
330 Effect.map((row) =>
331 Option.match(row, {
332 onNone: () => null,
333 onSome: (value) => ({
334 status: value.status,
335 decision: value.decision,
336 resolvedAt: value.resolvedAt,
337 }),
338 }),
339 ),
340 ),
341 (
342 row,
343 ): row is {
344 readonly status: "pending" | "resolved";
345 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
346 readonly resolvedAt: string | null;
347 } => row !== null && predicate(row),
348 `pending approval '${requestId}'`,
349 timeoutMs,
350 ) as Effect.Effect<
351 {
352 readonly status: "pending" | "resolved";
353 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
354 readonly resolvedAt: string | null;
355 },
356 never
357 >;
358​
359 let disposed = false;
360 const dispose = Effect.gen(function* () {
361 if (disposed) {
362 return;
363 }
364 disposed = true;
365​
366 const shutdown = Effect.gen(function* () {
367 const stopAllExit = yield* Effect.exit(
368 Effect.promise(() => runtime.runPromise(providerService.stopAll())),
369 );
370 const closeScopeExit = yield* Effect.exit(
371 Effect.promise(() => Effect.runPromise(Scope.close(scope, Exit.void))),
372 );
373 const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
374​
375 const failureCause = Exit.isFailure(stopAllExit)
376 ? stopAllExit.cause
377 : Exit.isFailure(closeScopeExit)
378 ? closeScopeExit.cause
379 : Exit.isFailure(disposeRuntimeExit)
380 ? disposeRuntimeExit.cause
381 : null;
382​
383 if (failureCause) {
384 return yield* Effect.failCause(failureCause);
385 }
386 });
387​
388 yield* shutdown.pipe(
389 Effect.ensuring(
390 Effect.sync(() => {
391 fs.rmSync(rootDir, { recursive: true, force: true });
392 }),
393 ),
394 );
395 });
396​
397 return {
398 rootDir,
399 workspaceDir,
400 dbPath,
401 adapterHarness,
402 engine,
403 snapshotQuery,
404 providerService,
405 checkpointStore,
406 checkpointRepository,
407 pendingApprovalRepository,
408 waitForThread,
409 waitForDomainEvent,
410 waitForPendingApproval,
411 dispose,
412 } satisfies OrchestrationIntegrationHarness;
413});