Skip to content
TypeScript

fix(gitlab): share merge request reads across detail and checks (#24392)

Julius Marminge2c119bd975de
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index 6c6c8215aa3..2b4d2f68c55 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -2189,6 +2189,98 @@ it.effect("does not revive old summaries when project epochs are evicted", () =>
}),
);
+it.effect("a refresh or a finished turn drops the provider's own change request reads", () =>
+ Effect.gen(function* () {
+ const forgotten: Array<{ readonly repository: string; readonly number?: number } | undefined> =
+ [];
+ const service = yield* makeService({
+ projects: [
+ project({
+ id: "p1",
+ title: "web",
+ workspaceRoot: "/a",
+ repository: "acme/web",
+ provider: "gitlab",
+ }),
+ ],
+ providers: [
+ fakeProvider(SourceControlProviderKind.make("gitlab"), {
+ forgetChangeRequestReads: (scope) => Effect.sync(() => void forgotten.push(scope)),
+ }),
+ ],
+ });
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+
+ yield* service.invalidate({ reference });
+ yield* service.refreshAfterTurn(reference.projectId);
+ yield* service.invalidate({});
+
+ assert.deepStrictEqual(forgotten, [
+ { repository: "acme/web", number: 1 },
+ undefined,
+ undefined,
+ ]);
+ }),
+);
+
+it.effect("a read during a refresh cannot keep the provider's old change request", () =>
+ Effect.gen(function* () {
+ let hostTitle = "old";
+ let held: string | undefined;
+ let gate:
+ | { readonly entered: Deferred.Deferred<void>; readonly release: Deferred.Deferred<void> }
+ | undefined;
+ const service = yield* makeService({
+ projects: [
+ project({
+ id: "p1",
+ title: "web",
+ workspaceRoot: "/a",
+ repository: "acme/web",
+ provider: "gitlab",
+ }),
+ ],
+ providers: [
+ fakeProvider(SourceControlProviderKind.make("gitlab"), {
+ getChangeRequest: () =>
+ Effect.sync(() => {
+ held ??= hostTitle;
+ return { ...hostedChangeRequest("body"), title: held };
+ }),
+ forgetChangeRequestReads: () =>
+ Effect.gen(function* () {
+ if (gate !== undefined) {
+ yield* Deferred.succeed(gate.entered, undefined);
+ yield* Deferred.await(gate.release);
+ }
+ held = undefined;
+ }),
+ }),
+ ],
+ });
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+ const refreshWithReadInBetween = (refresh: Effect.Effect<void>) =>
+ Effect.gen(function* () {
+ gate = { entered: yield* Deferred.make<void>(), release: yield* Deferred.make<void>() };
+ const running = yield* refresh.pipe(Effect.forkChild());
+ yield* Deferred.await(gate.entered);
+ yield* service.detail(reference);
+ yield* Deferred.succeed(gate.release, undefined);
+ yield* Fiber.join(running);
+ gate = undefined;
+ });
+
+ assert.strictEqual((yield* service.detail(reference)).title, "old");
+ hostTitle = "after turn";
+ yield* refreshWithReadInBetween(service.refreshAfterTurn(reference.projectId));
+ assert.strictEqual((yield* service.detail(reference)).title, "after turn");
+
+ hostTitle = "after refresh";
+ yield* refreshWithReadInBetween(service.invalidate({ reference }));
+ assert.strictEqual((yield* service.detail(reference)).title, "after refresh");
+ }),
+);
+
it.effect("close and reopen notify subscribed readers after invalidating their cached state", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index 854d182f155..9f18426be19 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -528,6 +528,9 @@ function withRateLimitBackoff(
listChangeRequestStats: wrap("listChangeRequestStats", api.listChangeRequestStats),
}),
getChangeRequest: wrap("getChangeRequest", api.getChangeRequest),
+ ...(api.forgetChangeRequestReads === undefined
+ ? {}
+ : { forgetChangeRequestReads: api.forgetChangeRequestReads }),
...(api.getChangeRequestPreview === undefined
? {}
: { getChangeRequestPreview: wrap("getChangeRequestPreview", api.getChangeRequestPreview) }),
@@ -3423,6 +3426,13 @@ export const make = Effect.gen(function* () {
return { stats: [...held, ...result.stats] };
});
+ const forgetProviderReads = (scope?: { readonly repository: string; readonly number?: number }) =>
+ Effect.forEach(
+ registry.kinds,
+ (kind) => registry.get(kind)?.forgetChangeRequestReads?.(scope) ?? Effect.void,
+ { discard: true },
+ );
+
const invalidate: PullRequestService["Service"]["invalidate"] = Effect.fn(
"PullRequestService.invalidate",
)(function* (input, options) {
@@ -3438,13 +3448,15 @@ export const make = Effect.gen(function* () {
if (reference !== undefined) {
yield* canonicalRef(reference).pipe(
Effect.flatMap((ref) =>
- readCache
- .invalidate(refScope(ref))
- .pipe(Effect.andThen(Effect.sync(() => bumpRefEpoch(ref)))),
+ forgetProviderReads({ repository: ref.repository, number: ref.number }).pipe(
+ Effect.andThen(readCache.invalidate(refScope(ref))),
+ Effect.andThen(Effect.sync(() => bumpRefEpoch(ref))),
+ ),
),
Effect.ignore,
);
} else {
+ yield* forgetProviderReads();
listingsEpoch = ++epochCounter;
everyFileRevisionEpoch = ++epochCounter;
viewersByHost.clear();
@@ -3455,22 +3467,27 @@ export const make = Effect.gen(function* () {
}
});
- const refreshAfterTurn: PullRequestService["Service"]["refreshAfterTurn"] = (projectId) =>
- Effect.suspend(() => {
- listingsEpoch = ++epochCounter;
- projectEpochs.delete(projectId);
- if (projectEpochs.size >= REF_EPOCH_CAPACITY) {
- const oldest = projectEpochs.keys().next().value;
- if (oldest !== undefined) {
- projectEpochFloor = projectEpochs.get(oldest)!;
- projectEpochs.delete(oldest);
- }
+ const refreshAfterTurn: PullRequestService["Service"]["refreshAfterTurn"] = Effect.fn(
+ "PullRequestService.refreshAfterTurn",
+ )(function* (projectId) {
+ // Everything the provider holds, not just the project's repository: a turn can touch a
+ // change request reached through another repository, and no epoch may move until those
+ // reads are gone, or a reader in between keeps the old one under the new epoch.
+ yield* forgetProviderReads();
+ listingsEpoch = ++epochCounter;
+ projectEpochs.delete(projectId);
+ if (projectEpochs.size >= REF_EPOCH_CAPACITY) {
+ const oldest = projectEpochs.keys().next().value;
+ if (oldest !== undefined) {
+ projectEpochFloor = projectEpochs.get(oldest)!;
+ projectEpochs.delete(oldest);
}
- projectEpochs.set(projectId, listingsEpoch);
- return readCache
- .invalidate(`project:${projectId}`)
- .pipe(Effect.andThen(SubscriptionRef.set(pullRequestRefreshes, listingsEpoch)));
- });
+ }
+ projectEpochs.set(projectId, listingsEpoch);
+ const epoch = listingsEpoch;
+ yield* readCache.invalidate(`project:${projectId}`);
+ yield* SubscriptionRef.set(pullRequestRefreshes, epoch);
+ });
const invalidatedByMutation =
<I extends PullRequestRef>(
diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts
index 46fc8fd48b0..63dfe8db7a8 100644
--- a/packages/source-control-core/src/server/PullRequestProvider.ts
+++ b/packages/source-control-core/src/server/PullRequestProvider.ts
@@ -353,6 +353,16 @@ export interface PullRequestProviderApi {
input: ProviderRepositoryRef & { readonly number: number },
) => Effect.Effect<ProviderChangeRequestDetail, PullRequestProviderError>;
+ /**
+ * For a provider that holds change request reads of its own: called when the service drops its
+ * reads, so a refresh or a finished turn reaches the host. No scope forgets everything; a scope
+ * without a number forgets the repository's change requests.
+ */
+ readonly forgetChangeRequestReads?: (scope?: {
+ readonly repository: string;
+ readonly number?: number;
+ }) => Effect.Effect<void>;
+
readonly getChangeRequestPreview?: (
input: ProviderRepositoryRef & { readonly number: number },
) => Effect.Effect<
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
index 6eec9ccd091..cc6bab6c53f 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
@@ -1,6 +1,7 @@
import { assert, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import * as TestClock from "effect/testing/TestClock";
import * as GitLabCli from "./GitLabCli.ts";
import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
@@ -122,6 +123,157 @@ describe("getChangeRequest base freshness", () => {
);
});
+describe("merge request reads", () => {
+ const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
+ const detail = {
+ number: 7,
+ title: "Merge request 7",
+ url: "https://gitlab.com/acme/web/-/merge_requests/7",
+ author: null,
+ headBranch: "feat/page",
+ baseBranch: "main",
+ state: "open" as const,
+ isDraft: false,
+ mergeability: "mergeable" as const,
+ additions: 0,
+ deletions: 0,
+ createdAt: "2026-07-01T00:00:00Z",
+ updatedAt: "2026-07-02T00:00:00Z",
+ reviewRequestLogins: [],
+ labels: [],
+ body: "",
+ changedFiles: 1,
+ mergedAt: null,
+ closedAt: null,
+ reviewers: [],
+ checks: [],
+ viewerCanMerge: true,
+ reviewerIds: [],
+ };
+
+ const countingProvider = Effect.gen(function* () {
+ const calls = { detail: 0, mergeCapabilities: 0 };
+ const host = { viewerCanMerge: true };
+ const provider = yield* make.pipe(
+ Effect.provide(
+ Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
+ getMergeRequestDetail: (input) =>
+ Effect.sync(() => {
+ calls.detail += 1;
+ return { ...detail, number: input.number, viewerCanMerge: host.viewerCanMerge };
+ }),
+ getProjectMergeCapabilities: () =>
+ Effect.sync(() => {
+ calls.mergeCapabilities += 1;
+ return { merge: true, squash: true, rebase: true };
+ }),
+ runMergeRequestAction: () => Effect.void,
+ }),
+ ),
+ );
+ const checks = provider.getChangeRequestChecks;
+ const forget = provider.forgetChangeRequestReads;
+ if (checks === undefined || forget === undefined) {
+ return yield* Effect.die("GitLab answers checks and forgets its reads");
+ }
+ return { provider, checks, forget, calls, host };
+ });
+
+ it.effect("asks for a project's merge methods once across its merge requests", () =>
+ Effect.gen(function* () {
+ const { provider, calls } = yield* countingProvider;
+
+ yield* provider.getChangeRequest(reference);
+ yield* provider.getChangeRequest(reference);
+ yield* provider.getChangeRequest({ ...reference, number: 8 });
+
+ expect(calls.mergeCapabilities).toBe(1);
+ }),
+ );
+
+ it.effect("answers checks from the merge request the detail just read", () =>
+ Effect.gen(function* () {
+ const { provider, checks, calls } = yield* countingProvider;
+
+ yield* provider.getChangeRequest(reference);
+ yield* checks(reference);
+
+ expect(calls.detail).toBe(1);
+ }),
+ );
+
+ it.effect("reads a merge request again after a write to it", () =>
+ Effect.gen(function* () {
+ const { provider, checks, calls } = yield* countingProvider;
+
+ yield* provider.getChangeRequest(reference);
+ yield* provider.runAction({ ...reference, action: "ready" });
+ yield* checks(reference);
+
+ expect(calls.detail).toBe(2);
+ }),
+ );
+
+ it.effect("does not share reads between checkouts", () =>
+ Effect.gen(function* () {
+ const { provider, calls } = yield* countingProvider;
+
+ yield* provider.getChangeRequest(reference);
+ yield* provider.getChangeRequest({ ...reference, cwd: "/other" });
+
+ expect(calls).toEqual({ detail: 2, mergeCapabilities: 2 });
+ }),
+ );
+
+ it.effect("reads a merge request again once a minute has passed", () =>
+ Effect.gen(function* () {
+ const { provider, calls } = yield* countingProvider;
+
+ yield* provider.getChangeRequest(reference);
+ yield* TestClock.adjust("61 seconds");
+ yield* provider.getChangeRequest(reference);
+
+ expect(calls.detail).toBe(2);
+ }),
+ );
+
+ it.effect("answers viewer permissions from the host, not the page's read", () =>
+ Effect.gen(function* () {
+ const { provider, host } = yield* countingProvider;
+
+ host.viewerCanMerge = false;
+ yield* provider.getChangeRequest(reference);
+ host.viewerCanMerge = true;
+ const granted = yield* provider.getViewerPermissions(reference);
+ host.viewerCanMerge = false;
+ const revoked = yield* provider.getViewerPermissions(reference);
+
+ expect(granted.actions).toContain("merge");
+ expect(revoked.actions).not.toContain("merge");
+ }),
+ );
+
+ it.effect("reads a merge request again once its reads are forgotten", () =>
+ Effect.gen(function* () {
+ const { provider, checks, forget, calls } = yield* countingProvider;
+ const other = { ...reference, repository: "acme/api" };
+
+ yield* provider.getChangeRequest(reference);
+ yield* provider.getChangeRequest(other);
+ yield* forget({ repository: "ACME/web", number: 7 });
+ yield* checks(reference);
+ yield* checks(other);
+ expect(calls.detail).toBe(3);
+
+ yield* forget({ repository: "acme/web" });
+ yield* checks(reference);
+ yield* forget();
+ yield* checks(other);
+ expect(calls.detail).toBe(5);
+ }),
+ );
+});
+
describe("optional activity reads", () => {
const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
const comment = {
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
index a9856f907eb..79c3d43c019 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
@@ -1,5 +1,8 @@
import { SourceControlProviderKind } from "@t3tools/contracts";
+import * as Cache from "effect/Cache";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
import type {
PullRequestCapabilities,
PullRequestReaction,
@@ -72,6 +75,16 @@ export function gitLabViewerPermissions(input: {
};
}
+/**
+ * One page view asks for the detail and then its checks within a second, and the poll that
+ * follows asks again. A minute keeps those to one `glab` call without hiding a pipeline for long;
+ * a refresh or a finished turn drops it sooner through `forgetChangeRequestReads`.
+ */
+const MERGE_REQUEST_DETAIL_TTL = Duration.minutes(1);
+/** A project's merge methods change in its settings, which nobody does between page views. */
+const PROJECT_MERGE_CAPABILITIES_TTL = Duration.minutes(15);
+const READ_CACHE_CAPACITY = 256;
+
function gitLabProviderFailure(
error: GitLabPullRequestCli.GitLabPullRequestCliError,
): PullRequestProviderFailure {
@@ -85,6 +98,55 @@ function gitLabProviderFailure(
export const make = Effect.gen(function* () {
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ // Keyed on the checkout as well: `glab` picks the host and the account to answer as from the
+ // checkout's remote and config, so two checkouts may read the same project as different people.
+ const mergeRequestDetails = yield* Cache.makeWith(
+ (key: string) => {
+ const [cwd, repository, number] = JSON.parse(key) as [string, string, number];
+ return cli.getMergeRequestDetail({ cwd, repository, number });
+ },
+ {
+ capacity: READ_CACHE_CAPACITY,
+ timeToLive: (exit) => (Exit.isSuccess(exit) ? MERGE_REQUEST_DETAIL_TTL : Duration.zero),
+ },
+ );
+ const projectMergeCapabilities = yield* Cache.makeWith(
+ (key: string) => {
+ const [cwd, repository] = JSON.parse(key) as [string, string];
+ return cli.getProjectMergeCapabilities({ cwd, repository });
+ },
+ {
+ capacity: READ_CACHE_CAPACITY,
+ timeToLive: (exit) => (Exit.isSuccess(exit) ? PROJECT_MERGE_CAPABILITIES_TTL : Duration.zero),
+ },
+ );
+
+ const detailKey = (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly number: number;
+ }) => JSON.stringify([input.cwd, input.repository, input.number]);
+ const mergeRequestDetail = (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly number: number;
+ }) => Cache.get(mergeRequestDetails, detailKey(input));
+
+ // Dropped on both sides, as the service does with its own reads: a read that starts while the
+ // write is in flight must not outlive it.
+ const writing =
+ <
+ I extends { readonly cwd: string; readonly repository: string; readonly number: number },
+ A,
+ E,
+ >(
+ write: (input: I) => Effect.Effect<A, E>,
+ ) =>
+ (input: I): Effect.Effect<A, E> => {
+ const invalidate = Cache.invalidate(mergeRequestDetails, detailKey(input));
+ return invalidate.pipe(Effect.andThen(write(input)), Effect.ensuring(invalidate));
+ };
+
const fail = (operation: string) => (error: GitLabPullRequestCli.GitLabPullRequestCliError) =>
new PullRequestProviderError({
provider: SourceControlProviderKind.make("gitlab"),
@@ -138,7 +200,7 @@ export const make = Effect.gen(function* () {
),
getChangeRequestChecks: (input) =>
- cli.getMergeRequestDetail(input).pipe(
+ mergeRequestDetail(input).pipe(
Effect.map(({ state, checks }) => ({ state, checks })),
Effect.mapError(fail("getChangeRequestChecks")),
),
@@ -153,8 +215,8 @@ export const make = Effect.gen(function* () {
getChangeRequest: (input) =>
Effect.all(
[
- cli.getMergeRequestDetail(input),
- cli.getProjectMergeCapabilities({ cwd: input.cwd, repository: input.repository }),
+ mergeRequestDetail(input),
+ Cache.get(projectMergeCapabilities, JSON.stringify([input.cwd, input.repository])),
],
{ concurrency: 2 },
).pipe(
@@ -209,11 +271,31 @@ export const make = Effect.gen(function* () {
})),
),
+ // Straight from the host, never the shared read: this is what a write is refused or let
+ // through on, and access granted or withdrawn within the minute must count.
getViewerPermissions: (input) =>
cli
.getMergeRequestDetail(input)
.pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitLabViewerPermissions)),
+ forgetChangeRequestReads: (scope) =>
+ Cache.keys(mergeRequestDetails).pipe(
+ Effect.flatMap((keys) =>
+ Effect.forEach(
+ Array.from(keys).filter((key) => {
+ if (scope === undefined) return true;
+ const [, repository, number] = JSON.parse(key) as [string, string, number];
+ return (
+ repository.toLowerCase() === scope.repository.toLowerCase() &&
+ (scope.number === undefined || number === scope.number)
+ );
+ }),
+ (key) => Cache.invalidate(mergeRequestDetails, key),
+ { discard: true },
+ ),
+ ),
+ ),
+
getDiff: (input) => cli.getMergeRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
getDiffFileContents: (input) =>
@@ -245,7 +327,7 @@ export const make = Effect.gen(function* () {
.listProjectUsers({ cwd: input.cwd, repository: input.repository, search: input.query })
.pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
- setReviewerRequest: (input) =>
+ setReviewerRequest: writing((input) =>
cli
.setReviewerRequest({
cwd: input.cwd,
@@ -255,8 +337,9 @@ export const make = Effect.gen(function* () {
requested: input.requested,
})
.pipe(Effect.mapError(fail("setReviewerRequest"))),
+ ),
- runAction: (input) =>
+ runAction: writing((input) =>
cli
.runMergeRequestAction({
cwd: input.cwd,
@@ -266,8 +349,9 @@ export const make = Effect.gen(function* () {
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
})
.pipe(Effect.mapError(fail("runAction"))),
+ ),
- updateChangeRequest: (input) =>
+ updateChangeRequest: writing((input) =>
cli
.updateMergeRequest({
cwd: input.cwd,
@@ -277,10 +361,13 @@ export const make = Effect.gen(function* () {
...(input.body === undefined ? {} : { description: input.body }),
})
.pipe(Effect.mapError(fail("updateChangeRequest"))),
+ ),
- comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
+ comment: writing((input) =>
+ cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
+ ),
- updateComment: (input) =>
+ updateComment: writing((input) =>
cli
.updateNote({
cwd: input.cwd,
@@ -290,10 +377,13 @@ export const make = Effect.gen(function* () {
body: input.body,
})
.pipe(Effect.mapError(fail("updateComment"))),
+ ),
- submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
+ submitReview: writing((input) =>
+ cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
+ ),
- replyToThread: (input) =>
+ replyToThread: writing((input) =>
cli
.replyToDiscussion({
cwd: input.cwd,
@@ -303,8 +393,9 @@ export const make = Effect.gen(function* () {
body: input.body,
})
.pipe(Effect.mapError(fail("replyToThread"))),
+ ),
- setReaction: (input) =>
+ setReaction: writing((input) =>
cli
.setReaction({
cwd: input.cwd,
@@ -315,8 +406,9 @@ export const make = Effect.gen(function* () {
reacted: input.reacted,
})
.pipe(Effect.mapError(fail("setReaction"))),
+ ),
- setThreadResolution: (input) =>
+ setThreadResolution: writing((input) =>
cli
.setDiscussionResolution({
cwd: input.cwd,
@@ -326,6 +418,7 @@ export const make = Effect.gen(function* () {
resolved: input.resolved,
})
.pipe(Effect.mapError(fail("setThreadResolution"))),
+ ),
};
return provider;