From f761067180aca2d8ef898c7f33706abe57f4885f Mon Sep 17 00:00:00 2001 From: Max B Date: Thu, 19 Nov 2026 19:56:06 +0100 Subject: [PATCH 1/2] fix(bitbucket): the list shows each open pull request's merge state --- ...tbucketPullRequestProvider.listing.test.ts | 240 ++++++++++++++++++ .../server/BitbucketPullRequestProvider.ts | 62 ++++- 2 files changed, 290 insertions(+), 12 deletions(-) diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.listing.test.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.listing.test.ts index bfb1447d02dbb..f0b18c740a10c 100644 --- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.listing.test.ts +++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.listing.test.ts @@ -1,11 +1,37 @@ +import { SourceControlProviderKind } from "@t3tools/contracts"; 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 TestClock from "effect/testing/TestClock"; +import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import * as BitbucketApi from "./BitbucketApi.ts"; import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts"; import * as BitbucketPullRequestProvider from "./BitbucketPullRequestProvider.ts"; +const pullRequestRow = (id: number, state = "OPEN", headSha = `sha${id}`, baseBranch = "main") => ({ + id, + title: `Pull request ${id}`, + state, + created_on: "2026-10-11T00:00:00.000000+00:00", + updated_on: "2026-10-11T00:00:00.000000+00:00", + source: { branch: { name: `feat/${id}` }, commit: { hash: headSha } }, + destination: { branch: { name: baseBranch } }, + links: { html: { href: `https://bitbucket.org/acme/web/pull-requests/${id}` } }, +}); + +const listInput = { + cwd: "/w", + repository: "acme/web", + host: "bitbucket.org", + state: "all", + involvement: "all", + viewer: "bilal", + limit: 10, +} as const; + it.effect("pages through rows that share an update instant by excluding those already sent", () => Effect.gen(function* () { // Bitbucket stamps to the microsecond; 3 shares 1 and 2's millisecond but sorts after them. @@ -31,6 +57,9 @@ it.effect("pages through rows that share an update instant by excluding those al Layer.provide( Layer.mock(BitbucketApi.BitbucketApi)({ request: ({ url }) => { + if (url.includes("/conflicts")) { + return Effect.succeed({ body: JSON.stringify({ values: [] }), truncated: false }); + } const filter = new URL(url, "https://api.bitbucket.org").searchParams.get("q") ?? ""; filters.push(filter); @@ -102,3 +131,214 @@ it.effect("pages through rows that share an update instant by excluding those al assert.isFalse(last.truncated); }), ); + +it.effect("reads each open row's merge state, which a listing does not carry", () => + Effect.gen(function* () { + const urls: string[] = []; + let headSha = "sha1"; + let baseBranch = "main"; + const provider = yield* BitbucketPullRequestProvider.make.pipe( + Effect.provide( + BitbucketPullRequestApi.layer.pipe( + Layer.provide( + Layer.mock(BitbucketApi.BitbucketApi)({ + request: ({ url }) => { + urls.push(url); + const conflicts = /pullrequests\/(\d+)\/conflicts/.exec(url); + if (conflicts === null) { + return Effect.succeed({ + body: JSON.stringify({ + values: [ + pullRequestRow(1, "OPEN", headSha, baseBranch), + pullRequestRow(2), + pullRequestRow(3), + pullRequestRow(4, "MERGED"), + pullRequestRow(5, "DECLINED"), + ], + }), + truncated: false, + }); + } + if (conflicts[1] === "3") { + return Effect.fail( + new BitbucketApi.BitbucketResponseError({ + operation: "request", + status: 500, + responseBodyLength: 0, + }), + ); + } + return Effect.succeed({ + body: JSON.stringify({ + values: conflicts[1] === "1" && headSha === "sha1" ? [{ path: "a.ts" }] : [], + }), + truncated: false, + }); + }, + }), + ), + ), + ), + ); + const list = (repository: string = listInput.repository) => + provider.listChangeRequests({ ...listInput, repository }); + const conflictNumbers = () => + urls + .filter((url) => url.includes("/conflicts")) + .map((url) => /pullrequests\/(\d+)/.exec(url)?.[1]); + + const first = yield* list(); + + assert.deepStrictEqual( + first.items.map((item) => item.mergeability), + ["conflicting", "mergeable", "unknown", "unknown", "unknown"], + ); + assert.deepStrictEqual(conflictNumbers(), ["1", "2", "3"]); + + // A second listing reuses the answers it already has; only the failed read is retried. + urls.length = 0; + yield* list(); + assert.deepStrictEqual(conflictNumbers(), ["3"]); + + headSha = "new-head"; + urls.length = 0; + const pushed = yield* list(); + assert.strictEqual(pushed.items[0]?.mergeability, "mergeable"); + assert.deepStrictEqual(conflictNumbers(), ["1", "3"]); + + // Retargeting keeps the head but changes what it merges into. + baseBranch = "release"; + urls.length = 0; + yield* list(); + assert.deepStrictEqual(conflictNumbers(), ["1", "3"]); + + urls.length = 0; + yield* list("acme/other"); + assert.deepStrictEqual(conflictNumbers(), ["1", "2", "3"]); + assert.isTrue(urls.every((url) => url.startsWith("/repositories/acme/other/"))); + + yield* TestClock.adjust("599 seconds"); + urls.length = 0; + yield* list(); + assert.deepStrictEqual(conflictNumbers(), ["3"]); + + yield* TestClock.adjust("1 second"); + urls.length = 0; + yield* list(); + assert.deepStrictEqual(conflictNumbers(), ["1", "2", "3"]); + }), +); + +it.effect("bounds conflict reads to five and shares pending lookups across lists", () => + Effect.gen(function* () { + const release = yield* Deferred.make(); + const fiveStarted = yield* Deferred.make(); + const bothListed = yield* Deferred.make(); + let active = 0; + let maximum = 0; + let conflictReads = 0; + let listings = 0; + const provider = yield* BitbucketPullRequestProvider.make.pipe( + Effect.provide( + BitbucketPullRequestApi.layer.pipe( + Layer.provide( + Layer.mock(BitbucketApi.BitbucketApi)({ + request: ({ url }) => + Effect.gen(function* () { + if (!url.includes("/conflicts")) { + listings++; + if (listings === 2) yield* Deferred.succeed(bothListed, undefined); + return { + body: JSON.stringify({ + values: Array.from({ length: 7 }, (_, index) => pullRequestRow(index + 1)), + }), + truncated: false, + }; + } + active++; + conflictReads++; + maximum = Math.max(maximum, active); + if (active === 5) yield* Deferred.succeed(fiveStarted, undefined); + yield* Deferred.await(release); + active--; + return { body: JSON.stringify({ values: [] }), truncated: false }; + }), + }), + ), + ), + ), + ); + const lists = yield* Effect.all( + [provider.listChangeRequests(listInput), provider.listChangeRequests(listInput)], + { concurrency: 2 }, + ).pipe(Effect.forkChild); + yield* Deferred.await(bothListed); + yield* Deferred.await(fiveStarted); + yield* Deferred.succeed(release, undefined); + const batches = yield* Fiber.join(lists); + assert.strictEqual(maximum, 5); + assert.strictEqual(conflictReads, 7); + for (const batch of batches) { + assert.deepStrictEqual( + batch.items.map((item) => item.number), + [1, 2, 3, 4, 5, 6, 7], + ); + assert.isTrue(batch.items.every((item) => item.mergeability === "mergeable")); + } + }), +); + +it.effect.each(["response", "body read", "paused"] as const)( + "preserves %s rate limits from a listing's conflict reads", + (variant) => + Effect.gen(function* () { + const error = + variant === "response" + ? new BitbucketApi.BitbucketResponseError({ + operation: "request", + status: 429, + responseBodyLength: 0, + retryAt: 120_000, + }) + : variant === "body read" + ? new BitbucketApi.BitbucketResponseBodyReadError({ + operation: "request", + status: 429, + cause: new Error("stream failed"), + retryAt: 120_000, + }) + : new SourceControlRateLimit.SourceControlRateLimitPausedError({ + provider: SourceControlProviderKind.make("bitbucket"), + host: "bitbucket.org", + retryAt: 120_000, + }); + let limited = true; + const provider = yield* BitbucketPullRequestProvider.make.pipe( + Effect.provide( + BitbucketPullRequestApi.layer.pipe( + Layer.provide( + Layer.mock(BitbucketApi.BitbucketApi)({ + request: ({ url }) => + url.includes("/conflicts") + ? limited + ? Effect.fail(error) + : Effect.succeed({ body: JSON.stringify({ values: [] }), truncated: false }) + : Effect.succeed({ + body: JSON.stringify({ values: [pullRequestRow(1)] }), + truncated: false, + }), + }), + ), + ), + ), + ); + const failure = yield* Effect.flip(provider.listChangeRequests(listInput)); + assert.strictEqual(failure.reason, "rate-limited"); + assert.strictEqual(failure.retryAt, 120_000); + assert.strictEqual(failure.operation, "listChangeRequests"); + assert.strictEqual(failure.cause, error); + limited = false; + const recovered = yield* provider.listChangeRequests(listInput); + assert.strictEqual(recovered.items[0]?.mergeability, "mergeable"); + }), +); diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts index 545a4be55e36b..5543c49a9f7c8 100644 --- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts +++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts @@ -1,5 +1,8 @@ import { resolvePullRequestAuthorFilter, 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 { rollupCheckStatuses } from "@t3tools/source-control-core/server/pullRequestChecks"; import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts"; @@ -17,6 +20,12 @@ import { import type { BitbucketPullRequest } from "./bitbucketPullRequestJson.ts"; import { definition } from "../shared/definition.ts"; +// Each open row costs one read, so answers live long enough that refreshes stay well inside the +// hourly quota; the destination branch moving on is the staleness this bounds. +const MERGEABILITY_TTL = Duration.minutes(10); +const MERGEABILITY_CAPACITY = 1000; +const MERGEABILITY_READS = 5; + const CAPABILITIES: PullRequestCapabilities = { diff: true, comment: true, @@ -171,6 +180,18 @@ export const make = Effect.gen(function* () { }); }; + // Listings omit conflicts; reuse reads until the head or target branch changes or the TTL expires. + const mergeabilities = yield* Cache.makeWith( + (key: string) => { + const [repository, number] = JSON.parse(key) as [string, number, string, string]; + return api.getMergeability({ repository, number }); + }, + { + capacity: MERGEABILITY_CAPACITY, + timeToLive: (exit) => (Exit.isSuccess(exit) ? MERGEABILITY_TTL : Duration.zero), + }, + ); + const provider: PullRequestProviderApi = { kind: SourceControlProviderKind.make("bitbucket"), capabilities: CAPABILITIES, @@ -180,9 +201,9 @@ export const make = Effect.gen(function* () { getViewer: () => api.getViewer().pipe(Effect.mapError(fail("getViewer"))), - listChangeRequests: (input) => - api - .listPullRequests({ + listChangeRequests: Effect.fn("BitbucketPullRequestProvider.listChangeRequests")( + function* (input) { + const batch = yield* api.listPullRequests({ repository: input.repository, state: input.state, limit: input.limit, @@ -193,15 +214,32 @@ export const make = Effect.gen(function* () { ? undefined : resolvePullRequestAuthorFilter(input.filters.author, input.viewer), draft: input.filters?.draft === undefined ? undefined : input.filters.draft === "only", - }) - .pipe( - Effect.mapError(fail("listChangeRequests")), - Effect.map((batch) => ({ - items: batch.items.map(toChangeRequest), - truncated: batch.truncated, - continues: true, - })), - ), + }); + const items = yield* Effect.forEach( + batch.items, + (pullRequest) => { + if (pullRequest.state !== "open") return Effect.succeed(toChangeRequest(pullRequest)); + return recoverRead( + Cache.get( + mergeabilities, + JSON.stringify([ + input.repository, + pullRequest.number, + pullRequest.headSha ?? "", + pullRequest.baseBranch, + ]), + ), + "unknown" as const, + ).pipe( + Effect.map((mergeability) => ({ ...toChangeRequest(pullRequest), mergeability })), + ); + }, + { concurrency: MERGEABILITY_READS }, + ); + return { items, truncated: batch.truncated, continues: true }; + }, + Effect.mapError(fail("listChangeRequests")), + ), getChangeRequestChecks: (input) => Effect.all([api.getPullRequest(input), api.listChecks(input)], { concurrency: 2 }).pipe( From 07342c4e1bebf2337ccf6d27de5ac3bf1ff8552c Mon Sep 17 00:00:00 2001 From: Max B Date: Thu, 19 Nov 2026 20:52:56 +0100 Subject: [PATCH 2/2] fix(bitbucket): do not cache a merge state for a row without a head revision --- ...tbucketPullRequestProvider.listing.test.ts | 42 +++++++++++++++++++ .../server/BitbucketPullRequestProvider.ts | 27 ++++++------ 2 files changed, 57 insertions(+), 12 deletions(-) diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.listing.test.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.listing.test.ts index f0b18c740a10c..10e58a14d72ff 100644 --- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.listing.test.ts +++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.listing.test.ts @@ -342,3 +342,45 @@ it.effect.each(["response", "body read", "paused"] as const)( assert.strictEqual(recovered.items[0]?.mergeability, "mergeable"); }), ); + +it.effect("reads a row without a head revision every time instead of caching its merge state", () => + Effect.gen(function* () { + const { source: _source, ...withoutHead } = pullRequestRow(1); + const row = { ...withoutHead, source: { branch: { name: "feat/1" } } }; + let conflicts: ReadonlyArray = []; + let reads = 0; + const provider = yield* BitbucketPullRequestProvider.make.pipe( + Effect.provide( + BitbucketPullRequestApi.layer.pipe( + Layer.provide( + Layer.mock(BitbucketApi.BitbucketApi)({ + request: ({ url }) => { + if (url.includes("/conflicts")) { + reads += 1; + return Effect.succeed({ + body: JSON.stringify({ values: conflicts }), + truncated: false, + }); + } + return Effect.succeed({ + body: JSON.stringify({ values: [row] }), + truncated: false, + }); + }, + }), + ), + ), + ), + ); + + const first = yield* provider.listChangeRequests(listInput); + conflicts = [{ path: "a.ts" }]; + const second = yield* provider.listChangeRequests(listInput); + + assert.deepStrictEqual( + [first.items[0]?.mergeability, second.items[0]?.mergeability], + ["mergeable", "conflicting"], + ); + assert.strictEqual(reads, 2); + }), +); diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts index 5543c49a9f7c8..e31fb172ac447 100644 --- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts +++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts @@ -219,18 +219,21 @@ export const make = Effect.gen(function* () { batch.items, (pullRequest) => { if (pullRequest.state !== "open") return Effect.succeed(toChangeRequest(pullRequest)); - return recoverRead( - Cache.get( - mergeabilities, - JSON.stringify([ - input.repository, - pullRequest.number, - pullRequest.headSha ?? "", - pullRequest.baseBranch, - ]), - ), - "unknown" as const, - ).pipe( + // Without a head revision a pushed change cannot invalidate a cached answer, so + // such a row is read every time rather than risking a stale "mergeable". + const read = + pullRequest.headSha === null + ? api.getMergeability({ repository: input.repository, number: pullRequest.number }) + : Cache.get( + mergeabilities, + JSON.stringify([ + input.repository, + pullRequest.number, + pullRequest.headSha, + pullRequest.baseBranch, + ]), + ); + return recoverRead(read, "unknown" as const).pipe( Effect.map((mergeability) => ({ ...toChangeRequest(pullRequest), mergeability })), ); },