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

ThreadSettlementService.ts

637 lines25.0 KB

1import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
2import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
3import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
4import {
5 CommandId,
6 type ThreadId,
7 type OrchestrationV2DomainEvent,
8 type OrchestrationV2ThreadShell,
9} from "@t3tools/contracts";
10import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as Crypto from "effect/Crypto";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Schedule from "effect/Schedule";
19import type * as Scope from "effect/Scope";
20import * as Stream from "effect/Stream";
21​
22import * as GitManager from "../git/GitManager.ts";
23import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
24import * as PullRequestService from "../pullRequest/PullRequestService.ts";
25import * as ServerSettings from "../serverSettings.ts";
26import { forkParked } from "../serverActivation.ts";
27import * as TerminalManager from "../terminal/Manager.ts";
28import * as ProjectStore from "./ProjectStore.ts";
29import * as Orchestrator from "./Orchestrator.ts";
30import * as ProjectionStore from "./ProjectionStore.ts";
31​
32export interface SettlementPullRequest {
33 readonly state: "open" | "closed" | "merged";
34 readonly closedAt?: string | null;
35 readonly mergedAt?: string | null;
37​
38const DAY_MS = 24 * 60 * 60 * 1_000;
39export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
40​
41function toMillis(value: DateTime.Utc | null | undefined): number | null {
42 return value == null ? null : DateTime.toEpochMillis(value);
44​
45function latestMillis(values: ReadonlyArray<number | null>): number | null {
46 let latest: number | null = null;
47 for (const value of values) {
48 if (value === null) continue;
49 if (latest === null || value > latest) latest = value;
50 }
51 return latest;
53​
54function canonicalRepositoryKey(key: string): string {
55 return key
56 .replace(
57 /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
58 "dev.azure.com/$1/$2/_git/$3",
59 )
60 .replace(
61 /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
62 "dev.azure.com/$1/$2/_git/$3",
63 );
65​
66function pullRequestMatchesProject(
67 pullRequest: GitManager.GitBranchPullRequest,
68 project: {
69 readonly repositoryIdentity?: { readonly canonicalKey: string } | null | undefined;
70 },
71): boolean {
72 return (
73 pullRequest.repositoryKey !== null &&
74 project.repositoryIdentity != null &&
75 canonicalRepositoryKey(pullRequest.repositoryKey) ===
76 canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
77 );
79​
80/**
81 * Absolute age bounds client clock skew in both directions and stops stale
82 * pre-adoption data from blocking the thread forever.
83 */
84export function threadHasQueuedTurnStart(
85 thread: Pick<
86 OrchestrationV2ThreadShell,
87 | "latestUserMessageAt"
88 | "latestRunRequestedAt"
89 | "latestRunStartedAt"
90 | "latestRunCompletedAt"
91 | "latestRunId"
92 | "status"
93 >,
94 nowMs: number,
95): boolean {
96 const messageAtMs = toMillis(thread.latestUserMessageAt);
97 if (messageAtMs === null || thread.status === "failed") return false;
98 const age = nowMs - messageAtMs;
99 if (Number.isNaN(age) || Math.abs(age) > QUEUED_TURN_START_GRACE_MS) return false;
100 if (thread.latestRunId === null) return true;
101 return [
102 toMillis(thread.latestRunRequestedAt),
103 toMillis(thread.latestRunStartedAt),
104 toMillis(thread.latestRunCompletedAt),
105 ].every((value) => value === null || value < messageAtMs);
107​
108function pullRequestSettles(
109 thread: Pick<
110 ProjectionStore.ProjectionSettlementCandidate,
111 "createdAt" | "latestUserAuthoredMessageAt"
112 >,
113 pullRequest: SettlementPullRequest,
114 autoSettleOnMerge: boolean,
115): boolean {
116 if (pullRequest.state !== "closed" && (pullRequest.state !== "merged" || !autoSettleOnMerge)) {
117 return false;
118 }
119 const terminalAt = pullRequest.state === "merged" ? pullRequest.mergedAt : pullRequest.closedAt;
120 if (terminalAt == null) return false;
121 const userAnchorMs = latestMillis([
122 toMillis(thread.createdAt),
123 toMillis(thread.latestUserAuthoredMessageAt),
124 ]);
125 if (userAnchorMs === null) return false;
126 const pullRequestAtMs = Date.parse(terminalAt);
127 if (Number.isNaN(pullRequestAtMs)) return false;
128 return pullRequestAtMs >= userAnchorMs;
130​
131export function isAutoSettlementCandidate(
132 thread: Omit<ProjectionStore.ProjectionSettlementCandidate, "latestUserAuthoredMessageAt">,
133 nowMs: number,
134): boolean {
135 if (thread.archivedAt !== null || thread.settledOverride !== null) return false;
136 if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false;
137 if (thread.pendingRuntimeRequest !== null) return false;
138 if (thread.activityRunStatus != null) return false;
139 if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return false;
140 if (threadHasQueuedTurnStart(thread, nowMs)) return false;
141 const snoozedUntilMs = toMillis(thread.snoozedUntil);
142 if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return true;
143 const snoozedAtMs = toMillis(thread.snoozedAt);
144 const completedAtMs = toMillis(thread.latestRunCompletedAt);
145 const wokeOnError =
146 thread.status === "failed" &&
147 (snoozedAtMs === null || (completedAtMs !== null && completedAtMs > snoozedAtMs));
148 const wokeOnCompletion =
149 snoozedAtMs !== null && completedAtMs !== null && completedAtMs > snoozedAtMs;
150 return wokeOnError || wokeOnCompletion;
152​
153/**
154 * Server twin of the client's `effectiveSnoozed`, so agents and the sidebar agree on what is
155 * snoozed.
156 */
157export function isSnoozed(
158 thread: Pick<
159 ProjectionStore.ProjectionSettlementCandidate,
160 "snoozedUntil" | "snoozedAt" | "latestRunCompletedAt" | "status" | "pendingRuntimeRequest"
161 >,
162 nowMs: number,
163): boolean {
164 const snoozedUntilMs = toMillis(thread.snoozedUntil);
165 if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return false;
166 if (thread.pendingRuntimeRequest !== null) return false;
167 const snoozedAtMs = toMillis(thread.snoozedAt);
168 const completedAtMs = toMillis(thread.latestRunCompletedAt);
169 const wokeOnError =
170 thread.status === "failed" &&
171 (snoozedAtMs === null || (completedAtMs !== null && completedAtMs > snoozedAtMs));
172 const wokeOnCompletion =
173 thread.status === "completed" &&
174 snoozedAtMs !== null &&
175 completedAtMs !== null &&
176 completedAtMs > snoozedAtMs;
177 return !wokeOnError && !wokeOnCompletion;
179​
180export function resolveAutoSettlementAt(input: {
181 readonly thread: ProjectionStore.ProjectionSettlementCandidate;
182 readonly pullRequest: SettlementPullRequest | null;
183 readonly nowMs: number;
184 readonly autoSettleAfterDays: number | null;
185 readonly autoSettleOnMerge: boolean;
186 readonly autoSettleKeepPullRequests?: boolean;
187}): DateTime.Utc | null {
188 const { thread } = input;
189 let pullRequest = input.pullRequest;
190 const links = visibleThreadPullRequests(thread.pullRequests ?? []);
191 if (links.some((link) => link.snapshot === null || link.snapshot.state === "open")) return null;
192 if (links.length > 0) {
193 const terminalAt = (link: (typeof links)[number]) => {
194 const snapshot = link.snapshot;
195 const value = snapshot?.state === "merged" ? snapshot.mergedAt : snapshot?.closedAt;
196 const timestamp = Date.parse(value ?? "");
197 return Number.isNaN(timestamp) ? Number.NEGATIVE_INFINITY : timestamp;
198 };
199 const latest = links.reduce((current, candidate) =>
200 terminalAt(candidate) > terminalAt(current) ? candidate : current,
201 );
202 pullRequest =
203 latest.snapshot === null
204 ? null
205 : {
206 state: latest.snapshot.state,
207 mergedAt: latest.snapshot.mergedAt ?? null,
208 closedAt: latest.snapshot.closedAt ?? null,
209 };
210 }
211 if (!isAutoSettlementCandidate(thread, input.nowMs)) return null;
212 const activityAtMs = latestMillis([
213 toMillis(thread.latestUserMessageAt),
214 toMillis(thread.latestRunRequestedAt),
215 toMillis(thread.latestRunStartedAt),
216 toMillis(thread.latestRunCompletedAt),
217 ]);
218 if (pullRequest !== null && pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) {
219 return activityAtMs === null ? thread.createdAt : DateTime.makeUnsafe(activityAtMs);
220 }
221 const hasPullRequest =
222 pullRequest !== null || thread.linkedPullRequest != null || thread.branchPullRequest != null;
223 if (input.autoSettleKeepPullRequests === true && hasPullRequest) return null;
224 if (input.autoSettleAfterDays === null || activityAtMs === null) return null;
225 const snoozedUntilMs = toMillis(thread.snoozedUntil);
226 const timerWakeAtMs =
227 snoozedUntilMs !== null && snoozedUntilMs <= input.nowMs ? snoozedUntilMs : null;
228 const inactivityAtMs =
229 latestMillis([activityAtMs, toMillis(thread.lastSnoozeWakeAt), timerWakeAtMs]) ?? activityAtMs;
230 return inactivityAtMs < input.nowMs - input.autoSettleAfterDays * DAY_MS
231 ? DateTime.makeUnsafe(inactivityAtMs)
232 : null;
234​
235export class ThreadSettlementServiceV2 extends Context.Service<
236 ThreadSettlementServiceV2,
237 {
238 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
239 readonly drain: Effect.Effect<void>;
240 }
241>()("t3/orchestration-v2/ThreadSettlementService/ThreadSettlementServiceV2") {}
242​
243function autoSettlementConfigured(settings: import("@t3tools/contracts").ServerSettings): boolean {
244 if (settings.sidebarAutoSettleOnMerge || settings.sidebarAutoSettleAfterDays !== null) {
245 return true;
246 }
247 return Object.values(settings.projectSettingsOverrides).some(
248 (entry) =>
249 entry.sidebarAutoSettleOnMerge === true ||
250 (entry.sidebarAutoSettleAfterDays !== undefined && entry.sidebarAutoSettleAfterDays !== null),
251 );
253​
254/** @internal Exported for tests. */
255export function autoSettlementSettingsKey(
256 settings: import("@t3tools/contracts").ServerSettings,
257): string {
258 return JSON.stringify([
259 settings.sidebarAutoSettleOnMerge,
260 settings.sidebarAutoSettleAfterDays,
261 settings.sidebarAutoSettleKeepPullRequests,
262 Object.entries(settings.projectSettingsOverrides)
263 .filter(
264 ([, entry]) =>
265 entry.sidebarAutoSettleOnMerge !== undefined ||
266 entry.sidebarAutoSettleAfterDays !== undefined ||
267 entry.sidebarAutoSettleKeepPullRequests !== undefined,
268 )
269 .sort(([left], [right]) => left.localeCompare(right))
270 .map(([projectId, entry]) => [
271 projectId,
272 entry.sidebarAutoSettleOnMerge ?? "inherit",
273 entry.sidebarAutoSettleAfterDays === undefined
274 ? "inherit"
275 : entry.sidebarAutoSettleAfterDays,
276 entry.sidebarAutoSettleKeepPullRequests ?? "inherit",
277 ]),
278 ]);
280​
281export const make = Effect.gen(function* () {
282 const orchestrator = yield* Orchestrator.OrchestratorV2;
283 const projections = yield* ProjectionStore.ProjectionStoreV2;
284 const projectStore = yield* ProjectStore.ProjectStoreV2;
285 const settingsService = yield* ServerSettings.ServerSettingsService;
286 const git = yield* GitManager.GitManager;
287 const pullRequests = yield* PullRequestService.PullRequestService;
288 const crypto = yield* Crypto.Crypto;
289 const fileSystem = yield* FileSystem.FileSystem;
290 const terminals = yield* TerminalManager.TerminalManager;
291 const projectScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
292 // Settling a settled thread re-emits thread.settled with the same settledAt,
293 // so this keeps the settle action to one run per settlement.
294 const settleActionRunAt = new Map<ThreadId, number>();
295​
296 const sweep = Effect.fn("ThreadSettlementServiceV2.sweep")(function* (
297 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
298 threadId?: ThreadId,
299 ) {
300 const settings = yield* settingsService.getSettings;
301 if (!autoSettlementConfigured(settings)) {
302 return;
303 }
304 const threads = yield* projections.getSettlementCandidates(threadId);
305 if (threads.length === 0) return;
306 const projectShells = yield* projectStore.listShells();
307 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
308 const projects = new Map(projectShells.map((project) => [project.id, project]));
309 // A merge event re-sweeps every candidate, not just the threads linked to
310 // the merged pull request: most threads carry no link and settle from
311 // their branch lookup, which would otherwise wait for the next minute's
312 // sweep on a possibly stale cached answer.
313 const candidates = threads.filter((thread) => isAutoSettlementCandidate(thread, nowMs));
314​
315 const settleThread = Effect.fn("ThreadSettlementServiceV2.settleThread")(
316 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
317 const currentSettings = resolveProjectSettings(
318 yield* settingsService.getSettings,
319 thread.projectId,
320 ).settings;
321 const decisionNow = yield* DateTime.now;
322 const settledAt = resolveAutoSettlementAt({
323 thread,
324 pullRequest,
325 nowMs: DateTime.toEpochMillis(decisionNow),
326 autoSettleAfterDays: currentSettings.sidebarAutoSettleAfterDays,
327 autoSettleOnMerge: currentSettings.sidebarAutoSettleOnMerge,
328 autoSettleKeepPullRequests: currentSettings.sidebarAutoSettleKeepPullRequests,
329 });
330 if (settledAt === null) return thread;
331 const uuid = yield* crypto.randomUUIDv4();
332 yield* orchestrator.dispatch({
333 type: "thread.auto-settle",
334 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
335 threadId: thread.id,
336 snapshotAt: thread.updatedAt,
337 settledAt,
338 });
339 return null;
340 },
341 (effect, thread) =>
342 effect.pipe(
343 Effect.catchCause((cause) =>
344 Cause.hasInterruptsOnly(cause)
345 ? Effect.failCause(cause)
346 : Effect.logWarning("automatic thread settlement skipped", {
347 threadId: thread.id,
348 cause: Cause.pretty(cause),
349 }).pipe(Effect.as(null)),
350 ),
351 ),
352 );
353​
354 const lookupCandidates = (yield* Effect.forEach(
355 candidates,
356 (thread) => settleThread(thread, null),
357 { concurrency: 8 },
358 ))
359 .filter((thread) => thread !== null)
360 .filter((thread) => visibleThreadPullRequests(thread.pullRequests ?? []).length === 0);
361 const lookupCwdByThreadId = new Map<string, string>();
362 yield* Effect.forEach(
363 lookupCandidates,
364 (thread) =>
365 Effect.gen(function* () {
366 const project = projects.get(thread.projectId);
367 if (project === undefined || thread.branch === null) return;
368 const worktreeExists =
369 thread.worktreePath !== null &&
370 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
371 lookupCwdByThreadId.set(
372 thread.id,
373 worktreeExists && thread.worktreePath !== null
374 ? thread.worktreePath
375 : project.workspaceRoot,
376 );
377 }),
378 { concurrency: 8, discard: true },
379 );
380 if (mergedPullRequest !== null) {
381 // The merge just confirmed a terminal state the lookup caches can still
382 // call open (branch answers live two minutes, the sweep runs every
383 // minute). Drop the swept checkouts' cached answers so the merge settles
384 // its branch threads now instead of on a later sweep.
385 const cwds = [...new Set(lookupCwdByThreadId.values())];
386 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
387 concurrency: 8,
388 discard: true,
389 });
390 }
391 const lookupKey = (thread: (typeof lookupCandidates)[number]) => {
392 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
393 if (reference != null) {
394 return JSON.stringify([
395 "linked",
396 reference.projectId,
397 reference.repository,
398 reference.number,
399 lookupCwdByThreadId.get(thread.id),
400 thread.branch,
401 ]);
402 }
403 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
404 const cwd = lookupCwdByThreadId.get(thread.id);
405 return JSON.stringify(
406 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
407 );
408 };
409 const groups = Map.groupBy(lookupCandidates, lookupKey);
410​
411 const wouldSettle = Effect.fn("ThreadSettlementServiceV2.wouldSettle")(function* (
412 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
413 pullRequest: SettlementPullRequest,
414 ) {
415 const currentSettings = yield* settingsService.getSettings;
416 const decisionNow = yield* DateTime.now;
417 return group.some((thread) => {
418 const { settings } = resolveProjectSettings(currentSettings, thread.projectId);
419 return (
420 resolveAutoSettlementAt({
421 thread,
422 pullRequest,
423 nowMs: DateTime.toEpochMillis(decisionNow),
424 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
425 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
426 autoSettleKeepPullRequests: settings.sidebarAutoSettleKeepPullRequests,
427 }) !== null
428 );
429 });
430 });
431​
432 const pullRequestFor = Effect.fn("ThreadSettlementServiceV2.pullRequestFor")(function* (
433 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
434 ) {
435 const thread = group[0]!;
436 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
437 if (reference != null) {
438 // The event carries the merged state, so only the threads linked to
439 // that exact pull request settle from it. Every other linked thread
440 // falls through to a fresh summary lookup below: the merge sweep
441 // covers all candidates, and an unrelated merge must never settle
442 // them.
443 const matchesMerge =
444 mergedPullRequest !== null &&
445 reference.projectId === mergedPullRequest.projectId &&
446 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
447 reference.number === mergedPullRequest.number;
448 if (!matchesMerge && !projects.has(reference.projectId)) {
449 return yield* Effect.die(new Error("linked pull request project not found"));
450 }
451 const summary = matchesMerge
452 ? ({
453 state: "merged",
454 closedAt: null,
455 mergedAt: mergedPullRequest.mergedAt,
456 } satisfies SettlementPullRequest)
457 : yield* pullRequests.summary(
458 {
459 projectId: reference.projectId,
460 repository: reference.repository,
461 number: reference.number,
462 },
463 { recoverTransientFailure: false },
464 );
465 const terminal = {
466 state: summary.state,
467 closedAt: summary.closedAt ?? null,
468 mergedAt: summary.mergedAt ?? null,
469 } satisfies SettlementPullRequest;
470 const cwd = lookupCwdByThreadId.get(thread.id);
471 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
472 if (!(yield* wouldSettle(group, terminal))) return undefined;
473 const current = yield* git.branchPullRequest(
474 { cwd, branch: thread.branch },
475 { refresh: true },
476 );
477 const project = projects.get(thread.projectId);
478 if (
479 current?.state === "open" &&
480 project !== undefined &&
481 pullRequestMatchesProject(current, project)
482 ) {
483 return current;
484 }
485 }
486 return terminal;
487 }
488 if (thread.branch === null) return null;
489 const cwd = lookupCwdByThreadId.get(thread.id);
490 if (cwd === undefined) {
491 return yield* Effect.die(new Error("thread project not found"));
492 }
493 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
494 });
495​
496 yield* Effect.forEach(
497 groups.values(),
498 (group) =>
499 Effect.gen(function* () {
500 const pullRequest = yield* pullRequestFor(group);
501 if (pullRequest === undefined) return;
502 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
503 discard: true,
504 });
505 }).pipe(
506 Effect.catchCause((cause) =>
507 Cause.hasInterruptsOnly(cause)
508 ? Effect.failCause(cause)
509 : Effect.logWarning("automatic thread settlement skipped", {
510 threadIds: group.map((thread) => thread.id),
511 cause: Cause.pretty(cause),
512 }),
513 ),
514 ),
515 { concurrency: 8, discard: true },
516 );
517 });
518​
519 const runSweep = (
520 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
521 threadId?: ThreadId,
522 ) =>
523 sweep(mergedPullRequest, threadId).pipe(
524 Effect.catchCause((cause) =>
525 Cause.hasInterruptsOnly(cause)
526 ? Effect.failCause(cause)
527 : Effect.logWarning("automatic thread settlement sweep failed", {
528 cause: Cause.pretty(cause),
529 }),
530 ),
531 );
532 const worker = yield* makeDrainableWorker((threadId: ThreadId | undefined) =>
533 runSweep(null, threadId),
534 );
535​
536 // Then the project's settle script runs in the thread's own worktree; a
537 // thread in the shared checkout skips it, because other threads may still be
538 // working there.
539 const cleanUpSettledThread = Effect.fn("ThreadSettlementServiceV2.cleanUpSettledThread")(
540 function* (threadId: ThreadId) {
541 const settled = yield* projections.getThread(threadId);
542 if (settled.settledOverride !== "settled") return;
543 yield* terminals.closeIdle({ threadId });
544 const worktreePath = settled.worktreePath;
545 if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return;
546 // Closing and the worktree check wait on I/O. A thread re-engaged
547 // meanwhile is working again, so its worktree is no place for cleanup.
548 const thread = yield* projections.getThread(threadId);
549 if (thread.settledOverride !== "settled") return;
550 const settledAtMs = toMillis(thread.settledAt);
551 if (settledAtMs === null || settleActionRunAt.get(threadId) === settledAtMs) return;
552 const run = yield* projectScripts.runForThread({
553 threadId,
554 projectId: thread.projectId,
555 worktreePath,
556 trigger: "settle",
557 observeCompletion: {},
558 });
559 settleActionRunAt.set(threadId, settledAtMs);
560 if (run.status === "started" && run.completion) {
561 yield* run.completion.pipe(Effect.forkDetach);
562 }
563 },
564 (effect, threadId) =>
565 effect.pipe(
566 Effect.catchCause((cause) =>
567 Cause.hasInterruptsOnly(cause)
568 ? Effect.failCause(cause)
569 : Effect.logWarning("cleaning up a settled thread failed", {
570 threadId,
571 cause: Cause.pretty(cause),
572 }),
573 ),
574 ),
575 );
576​
577 const processEvent = (event: OrchestrationV2DomainEvent) => {
578 switch (event.type) {
579 case "thread.settled":
580 return cleanUpSettledThread(event.threadId);
581 case "thread.pull-request-link-updated":
582 case "thread.pull-request-synced":
583 case "provider-session.detached":
584 return worker.enqueue(event.threadId);
585 case "provider-session.updated":
586 return event.payload.status !== "starting" && event.payload.status !== "running"
587 ? worker.enqueue(event.threadId)
588 : Effect.void;
589 case "run.updated":
590 return ["completed", "interrupted", "failed", "cancelled", "rolled_back"].includes(
591 event.payload.status,
592 )
593 ? worker.enqueue(event.threadId)
594 : Effect.void;
595 default:
596 return Effect.void;
597 }
598 };
599​
600 const start: ThreadSettlementServiceV2["Service"]["start"] = Effect.fn(
601 "ThreadSettlementServiceV2.start",
602 )(function* () {
603 const settingsChanges = yield* settingsService.subscribeChanges;
604 const mergedPullRequests = yield* pullRequests.subscribeMerges;
605 const events = orchestrator.streamDomainEvents;
606 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
607 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
608 yield* forkParked(
609 Effect.gen(function* () {
610 yield* worker.enqueue(undefined);
611 yield* worker.drain;
612 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
613 );
614 yield* forkParked(
615 Stream.runForEach(settingsChanges, (settings) => {
616 const key = autoSettlementSettingsKey(settings);
617 if (key === lastSettlementSettings) {
618 return Effect.void;
619 }
620 lastSettlementSettings = key;
621 return worker.enqueue(undefined);
622 }),
623 );
624 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
625 yield* forkParked(
626 Stream.runForEach(events, processEvent).pipe(
627 Effect.catchCause((cause) =>
628 Effect.logWarning("Thread settlement event stream failed", { cause }),
629 ),
630 ),
631 );
632 });
633​
634 return { start, drain: worker.drain } satisfies ThreadSettlementServiceV2["Service"];
635});
636​
637export const layer = Layer.effect(ThreadSettlementServiceV2, make);