fix(pull-requests): shared state + not settling? (#9332)
Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
1 parent
48ba76bc26
commit
854541a04e
9 files changed
+440
-166
No files matched your search
@@ -25,7 +25,10 @@ import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import { GitManager } from "../git/GitManager.ts";
|
||||
import { PullRequestService } from "../pullRequest/PullRequestService.ts";
|
||||
import {
|
||||
PullRequestService,
|
||||
type PullRequestMergeEvent,
|
||||
} from "../pullRequest/PullRequestService.ts";
|
||||
import { ServerActivation } from "../serverActivation.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { OrchestrationCommandInvariantError } from "./Errors.ts";
|
||||
@@ -143,6 +146,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
|
||||
const snapshotReads = yield* Queue.unbounded<number>();
|
||||
const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
|
||||
const settingsChanges = yield* PubSub.unbounded<ServerSettings>();
|
||||
const mergedPullRequests = yield* PubSub.unbounded<PullRequestMergeEvent>();
|
||||
const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
|
||||
const branchCalls = yield* Ref.make<
|
||||
ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
|
||||
@@ -168,7 +172,6 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
|
||||
Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
|
||||
Effect.andThen(options.branchPullRequest?.(input) ?? Effect.succeed(null)),
|
||||
);
|
||||
|
||||
const pullRequestSummary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
|
||||
@@ -217,7 +220,12 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
|
||||
),
|
||||
}),
|
||||
Layer.mock(GitManager)({ branchPullRequest }),
|
||||
Layer.mock(PullRequestService)({ summary: pullRequestSummary }),
|
||||
Layer.mock(PullRequestService)({
|
||||
summary: pullRequestSummary,
|
||||
subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
|
||||
Effect.map((subscription) => Stream.fromSubscription(subscription)),
|
||||
),
|
||||
}),
|
||||
Layer.mock(OrchestrationEngineService)({
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch,
|
||||
@@ -239,6 +247,12 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
|
||||
summaryCalls,
|
||||
summaryRecovery,
|
||||
updateSettings,
|
||||
publishMerge: PubSub.publish(mergedPullRequests, {
|
||||
projectId: PROJECT_ID,
|
||||
repository: "owner/repository",
|
||||
number: 42,
|
||||
mergedAt: NOW,
|
||||
}),
|
||||
layer: ThreadSettlementReactor.layer.pipe(Layer.provide(dependencies)),
|
||||
};
|
||||
});
|
||||
@@ -373,6 +387,60 @@ describe("ThreadSettlementReactor", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reevaluates immediately after a pull request merge", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* TestClock.setTime(Date.parse(NOW));
|
||||
const periodicLookupStarted = yield* Deferred.make<void>();
|
||||
const releasePeriodicLookup = yield* Deferred.make<void>();
|
||||
const mergedThreadSettled = yield* Deferred.make<void>();
|
||||
const branchLookupCount = yield* Ref.make(0);
|
||||
const fixture = yield* makeHarness({
|
||||
snapshot: makeSnapshot([
|
||||
makeThread("merged-in-app", {
|
||||
linkedPullRequest: {
|
||||
projectId: PROJECT_ID,
|
||||
repository: "owner/repository",
|
||||
number: 42,
|
||||
url: "https://example.test/owner/repository/pull/42",
|
||||
},
|
||||
}),
|
||||
makeThread("slow-periodic-lookup", { branch: "another-feature" }),
|
||||
]),
|
||||
branchPullRequest: () =>
|
||||
Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
|
||||
Effect.flatMap((count) =>
|
||||
count === 1
|
||||
? Effect.succeed({ state: "open" as const, updatedAt: NOW })
|
||||
: Deferred.succeed(periodicLookupStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releasePeriodicLookup)),
|
||||
Effect.as({ state: "open" as const, updatedAt: NOW }),
|
||||
),
|
||||
),
|
||||
),
|
||||
onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
||||
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
||||
yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
|
||||
yield* Deferred.await(periodicLookupStarted);
|
||||
|
||||
yield* fixture.publishMerge;
|
||||
yield* Deferred.await(mergedThreadSettled);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
(yield* Ref.get(fixture.commands)).map((command) => command.threadId),
|
||||
[ThreadId.make("merged-in-app")],
|
||||
);
|
||||
yield* Deferred.succeed(releasePeriodicLookup, undefined);
|
||||
yield* reactor.drain;
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses fresh settlement settings after lookup and ignores unrelated changes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -38,11 +38,22 @@ export const make = Effect.gen(function* () {
|
||||
const pullRequests = yield* PullRequestService.PullRequestService;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
const sweep = Effect.fn("ThreadSettlementReactor.sweep")(function* () {
|
||||
const sweep = Effect.fn("ThreadSettlementReactor.sweep")(function* (
|
||||
mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
|
||||
) {
|
||||
const snapshot = yield* snapshots.getShellSnapshot();
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
|
||||
const candidates = snapshot.threads.filter((thread) => isAutoSettlementCandidate(thread, now));
|
||||
const candidates = snapshot.threads.filter(
|
||||
(thread) =>
|
||||
isAutoSettlementCandidate(thread, now) &&
|
||||
(mergedPullRequest === null ||
|
||||
(thread.linkedPullRequest != null &&
|
||||
thread.linkedPullRequest.projectId === mergedPullRequest.projectId &&
|
||||
thread.linkedPullRequest.repository.toLowerCase() ===
|
||||
mergedPullRequest.repository.toLowerCase() &&
|
||||
thread.linkedPullRequest.number === mergedPullRequest.number)),
|
||||
);
|
||||
const lookupKey = (thread: (typeof candidates)[number]) => {
|
||||
if (thread.linkedPullRequest != null) {
|
||||
return JSON.stringify([
|
||||
@@ -66,6 +77,12 @@ export const make = Effect.gen(function* () {
|
||||
thread: (typeof candidates)[number],
|
||||
) {
|
||||
if (thread.linkedPullRequest != null) {
|
||||
if (mergedPullRequest !== null) {
|
||||
return {
|
||||
state: "merged",
|
||||
updatedAt: mergedPullRequest.mergedAt,
|
||||
} satisfies SettlementPullRequest;
|
||||
}
|
||||
if (!projects.has(thread.linkedPullRequest.projectId)) {
|
||||
return yield* Effect.die(new Error("linked pull request project not found"));
|
||||
}
|
||||
@@ -145,8 +162,8 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
});
|
||||
|
||||
const worker = yield* makeDrainableWorker(() =>
|
||||
sweep().pipe(
|
||||
const runSweep = (mergedPullRequest: PullRequestService.PullRequestMergeEvent | null) =>
|
||||
sweep(mergedPullRequest).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.failCause(cause)
|
||||
@@ -154,13 +171,14 @@ export const make = Effect.gen(function* () {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
);
|
||||
const worker = yield* makeDrainableWorker(() => runSweep(null));
|
||||
|
||||
const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
|
||||
"ThreadSettlementReactor.start",
|
||||
)(function* () {
|
||||
const settingsChanges = yield* settingsService.subscribeChanges;
|
||||
const mergedPullRequests = yield* pullRequests.subscribeMerges;
|
||||
const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
|
||||
let lastAfterDays = initialSettings.sidebarAutoSettleAfterDays;
|
||||
let lastOnMerge = initialSettings.sidebarAutoSettleOnMerge;
|
||||
@@ -183,6 +201,7 @@ export const make = Effect.gen(function* () {
|
||||
return worker.enqueue(undefined);
|
||||
}),
|
||||
);
|
||||
yield* forkParked(Stream.runForEach(mergedPullRequests, runSweep));
|
||||
});
|
||||
|
||||
return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import type {
|
||||
OrchestrationProjectShell,
|
||||
@@ -1002,6 +1005,41 @@ it.effect("refuses an action the host never claimed it could run", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("publishes a successful merge for immediate settlement", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const mergedAt = "2026-09-03T02:00:00.000Z";
|
||||
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
|
||||
const service = yield* makeService({
|
||||
projects: [
|
||||
project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
|
||||
],
|
||||
providers: [
|
||||
fakeProvider("github", {
|
||||
runAction: () => TestClock.setTime(Date.parse(mergedAt)),
|
||||
}),
|
||||
],
|
||||
});
|
||||
const merges = yield* service.subscribeMerges;
|
||||
const observedMerge = yield* Stream.runHead(merges).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
|
||||
yield* service.runAction({
|
||||
...reference,
|
||||
repository: " ACME/WEB ",
|
||||
action: "merge",
|
||||
mergeMethod: "merge",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), {
|
||||
...reference,
|
||||
mergedAt,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("refuses an action this viewer may not take, and says what access it takes", () =>
|
||||
Effect.gen(function* () {
|
||||
let ran: string | null = null;
|
||||
@@ -3192,6 +3230,32 @@ it.effect("does not ask the host again for a linked summary it already holds", (
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reuses an observed merged state for strict settlement reads", () =>
|
||||
Effect.gen(function* () {
|
||||
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
|
||||
const service = yield* makeService({
|
||||
projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
|
||||
providers: [
|
||||
fakeProvider("github", {
|
||||
getChangeRequest: () =>
|
||||
Effect.succeed({
|
||||
...hostedChangeRequest("merged body", 4),
|
||||
state: "merged",
|
||||
updatedAt: "2026-07-03T00:00:00Z",
|
||||
}),
|
||||
getChangeRequestSummary: () => Effect.die("strict merged state must not refresh"),
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
yield* service.detail(reference);
|
||||
|
||||
const summary = yield* service.summary(reference, { recoverTransientFailure: false });
|
||||
assert.strictEqual(summary.state, "merged");
|
||||
assert.strictEqual(summary.updatedAt, "2026-07-03T00:00:00Z");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not let a stale detail reopen overwrite a fresher linked summary", () =>
|
||||
Effect.gen(function* () {
|
||||
const gate = yield* Deferred.make<void>();
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import * as Cache from "effect/Cache";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import {
|
||||
PullRequestOperationError,
|
||||
PullRequestUnavailableError,
|
||||
@@ -63,6 +67,10 @@ import {
|
||||
} from "./PullRequestProvider.ts";
|
||||
import { PullRequestProviderRegistry } from "./PullRequestProviderRegistry.ts";
|
||||
|
||||
export interface PullRequestMergeEvent extends PullRequestRef {
|
||||
readonly mergedAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rows per repository when the client does not ask for a page size, and rows per slice when a
|
||||
* listing is carried on from a cursor.
|
||||
@@ -135,6 +143,11 @@ export class PullRequestService extends Context.Service<
|
||||
input: PullRequestRef,
|
||||
options?: { readonly recoverTransientFailure?: boolean },
|
||||
) => Effect.Effect<PullRequestSummary, PullRequestError>;
|
||||
readonly subscribeMerges: Effect.Effect<
|
||||
Stream.Stream<PullRequestMergeEvent>,
|
||||
never,
|
||||
Scope.Scope
|
||||
>;
|
||||
readonly detail: (input: PullRequestRef) => Effect.Effect<PullRequestDetail, PullRequestError>;
|
||||
readonly activity: (
|
||||
input: PullRequestRef,
|
||||
@@ -517,6 +530,7 @@ export function repositoryIdentityOf(project: OrchestrationProjectShell): string
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const mergedPullRequests = yield* PubSub.sliding<PullRequestMergeEvent>(64);
|
||||
const registry = yield* PullRequestProviderRegistry;
|
||||
const projections = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
|
||||
@@ -1410,9 +1424,9 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const runAction: PullRequestService["Service"]["runAction"] = (input) =>
|
||||
const runAction = (input: PullRequestActionInput): Effect.Effect<string, PullRequestError> =>
|
||||
requireProject(input).pipe(
|
||||
Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
|
||||
Effect.flatMap((project): Effect.Effect<string, PullRequestError> => {
|
||||
// The surface hides what a host cannot do, and this refuses it as well: a request that
|
||||
// reached here anyway must not be handed to a provider that never claimed the action.
|
||||
if (!project.api.capabilities.actions.includes(input.action)) {
|
||||
@@ -1454,7 +1468,7 @@ export const make = Effect.gen(function* () {
|
||||
// have to say yes. The second is asked last, because it costs a request and the checks
|
||||
// above do not.
|
||||
return viewerPermissionsOf(project, input, "runAction").pipe(
|
||||
Effect.flatMap((viewer): Effect.Effect<void, PullRequestError> => {
|
||||
Effect.flatMap((viewer): Effect.Effect<string, PullRequestError> => {
|
||||
if (!viewer.actions.includes(input.action)) {
|
||||
return Effect.fail(
|
||||
new PullRequestOperationError({
|
||||
@@ -1484,7 +1498,10 @@ export const make = Effect.gen(function* () {
|
||||
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
|
||||
...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
|
||||
})
|
||||
.pipe(Effect.mapError(toPullRequestError("runAction")));
|
||||
.pipe(
|
||||
Effect.mapError(toPullRequestError("runAction")),
|
||||
Effect.as(project.repository),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}),
|
||||
@@ -2151,9 +2168,13 @@ export const make = Effect.gen(function* () {
|
||||
const summary: PullRequestService["Service"]["summary"] = (input, options) => {
|
||||
const key = refCacheKey(input);
|
||||
const cached = Cache.get(summaryCache, key);
|
||||
return options?.recoverTransientFailure === false
|
||||
? cached.pipe(Effect.tap((value) => lastGoodSummary.record(key, value)))
|
||||
: lastGoodSummary.serveHeld(key, cached, "reuse");
|
||||
if (options?.recoverTransientFailure !== false) {
|
||||
return lastGoodSummary.serveHeld(key, cached, "reuse");
|
||||
}
|
||||
const held = lastGoodSummary.peek(key);
|
||||
return held?.state === "merged"
|
||||
? Effect.succeed(held)
|
||||
: cached.pipe(Effect.tap((value) => lastGoodSummary.record(key, value)));
|
||||
};
|
||||
|
||||
// Keys serialize positionally and parse back in the lookup, so the cache is the only holder
|
||||
@@ -2391,17 +2412,35 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
);
|
||||
const runActionAndInvalidate: PullRequestService["Service"]["runAction"] = Effect.fn(
|
||||
"PullRequestService.runActionAndInvalidate",
|
||||
)(function* (input) {
|
||||
const repository = yield* runAction(input);
|
||||
bumpRefEpoch({ ...input, repository });
|
||||
listingsEpoch = ++epochCounter;
|
||||
if (input.action === "merge") {
|
||||
yield* PubSub.publish(mergedPullRequests, {
|
||||
projectId: input.projectId,
|
||||
repository,
|
||||
number: input.number,
|
||||
mergedAt: DateTime.formatIso(yield* DateTime.now),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return PullRequestService.of({
|
||||
list,
|
||||
listStats,
|
||||
summary,
|
||||
subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
|
||||
Effect.map((subscription) => Stream.fromSubscription(subscription)),
|
||||
),
|
||||
detail,
|
||||
activity,
|
||||
threadComments,
|
||||
diff,
|
||||
diffFileContents,
|
||||
runAction: invalidatedByMutation(runAction),
|
||||
runAction: runActionAndInvalidate,
|
||||
update: invalidatedByMutation(update),
|
||||
comment: invalidatedByMutation(comment),
|
||||
updateComment: invalidatedByMutation(updateComment),
|
||||
|
||||
Reference in new issue
Block a user