Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -914,7 +914,7 @@ describe("core environment orchestration", () => {
.toBe("error");
expect(
getPreparingEnvironment(harness.db, second.id)?.statusMessage,
).toContain("another thread is using this workspace");
).toContain("Workspace is being prepared by another thread");
expect(switched).toEqual(["release"]);
expect(fixture.row()).toMatchObject({
hostId: fixture.host.id,
Expand Down Expand Up @@ -1818,3 +1818,92 @@ it("keeps a shared workspace ready when its preparing owner cancels before attac
expect(remove).not.toHaveBeenCalled();
});
});

it("serializes concurrent branchless checkout attaches until the first thread is bound", async () =>
withTestHarness(async (harness) => {
const fake = createFakePluginHost({
pluginId: "environment-project-checkout",
experimental_callHostRpc: (call) => {
if (call.method !== "attach") throw new Error("Unexpected host call");
return { status: "attached", path: "/tmp/project", branchName: "main" };
},
});
try {
const module = z
.object({
default: z.custom<(bb: BbPluginApi) => Promise<void>>(
(value) => typeof value === "function",
),
})
.parse(
await import(
new URL(
"../../../../../plugins/environment-project-checkout/server.ts",
import.meta.url,
).href
),
);
await module.default(fake.bb);
const provider =
fake.harness.registrations.environmentProviders.get("project-checkout");
if (!provider) throw new Error("Missing checkout provider");
let claimAttempts = 0;
let competingClaim = () => {};
const competing = new Promise<void>((resolve) => {
competingClaim = resolve;
});
const fixture = setup(harness, {
id: provider.id,
create: (context) =>
provider.create({
...context,
experimental_claimPath: async (path) => {
const claimed = await context.experimental_claimPath(path);
if (++claimAttempts === 2) competingClaim();
return claimed;
},
}),
remove: provider.remove,
requires: { projectCheckout: true },
});
fixture.context.projectCheckout = {
path: "/tmp/project",
experimental_ownsPath: false,
};
fixture.context.inputs = {};
const existing = createEnvironment(harness.db, harness.hub, {
projectId: fixture.context.project.id,
hostId: fixture.host.id,
path: "/tmp/project",
status: "ready",
providerOwnsPath: false,
});
fixture.ask();
await fixture.settled();
expect(fixture.row().id).toBe(existing.id);
expect(fixture.row().claimPath).toBe("/tmp/project");
const competitor = seedThread(harness.deps, {
projectId: fixture.context.project.id,
status: "starting",
});
prepareProviderEnvironment(harness.deps, fixture.record, {
...fixture.context,
thread: toThreadResponseFromThread(harness.deps, {
thread: competitor,
}),
});
await competing;
fixture.attach();
await expect
.poll(() => {
const row = getPreparingEnvironment(harness.db, competitor.id);
return { status: row?.status, message: row?.statusMessage };
})
.toMatchObject({ status: "ready" });
const second = getPreparingEnvironment(harness.db, competitor.id);
expect(second?.id).toBe(existing.id);
markProviderEnvironmentAttached(harness.db, competitor.id, existing.id);
} finally {
await fake.harness.lifecycle.dispose();
}
}));
63 changes: 62 additions & 1 deletion plugins/environment-project-checkout/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
makeHostResponse,
makeThreadResponse,
} from "@get-bb/plugin-sdk/testing";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { PROJECT_CHECKOUT_ENVIRONMENT_PROVIDER_ID } from "./provider-id.js";
import plugin from "./server.js";

Expand Down Expand Up @@ -322,3 +322,64 @@ it.each([false, true])(
}
},
);

it.each(["branch", "timeout", "abort"] as const)(
"ends a blocked path claim on %s without attaching",
async (mode) => {
const hostCall = vi.fn(() => {
throw new Error("Unexpected host call");
});
const { bb, harness } = createFakePluginHost({
pluginId: "environment-project-checkout",
experimental_callHostRpc: hostCall,
});
const controller = new AbortController();
const claim = vi.fn(async () => false);
try {
await plugin(bb);
const provider = harness.registrations.environmentProviders.get(
PROJECT_CHECKOUT_ENVIRONMENT_PROVIDER_ID,
);
if (!provider) throw new Error("Missing provider");
vi.useFakeTimers();
const result = provider.create({
project: PROJECT,
host: HOST,
projectCheckout: { path: CHECKOUT_PATH, experimental_ownsPath: false },
gitRemote: null,
inputs:
mode === "branch"
? { branch: { kind: "existing", name: "release" } }
: {},
thread: makeThreadResponse(),
suggestedBranchName: "bb/test",
attempt: 1,
pathKey: "blocked",
rebuild: false,
experimental_claimPath: claim,
previous: null,
report: { step() {}, log() {} },
signal: controller.signal,
});
if (mode === "abort") {
const assertion = expect(result).rejects.toThrow();
controller.abort();
await assertion;
} else {
if (mode === "timeout") {
vi.setSystemTime(Date.now() + 15 * 60 * 1000);
await vi.advanceTimersByTimeAsync(50);
}
await expect(result).resolves.toMatchObject({
status: "failed",
message: "Workspace is being prepared by another thread",
});
}
expect(hostCall).not.toHaveBeenCalled();
if (mode === "branch") expect(claim).toHaveBeenCalledTimes(1);
} finally {
vi.useRealTimers();
await harness.lifecycle.dispose();
}
},
);
17 changes: 11 additions & 6 deletions plugins/environment-project-checkout/server.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { setTimeout as delay } from "node:timers/promises";
import type { BbPluginApi } from "@get-bb/plugin-sdk";
import type { PluginEnvironmentProviderProgress } from "@get-bb/plugin-sdk/environment-provider";
import { reportHostProgress } from "bb-environment-provider-host/progress";
Expand Down Expand Up @@ -183,12 +184,16 @@ export default async function checkoutPlugin(bb: BbPluginApi): Promise<void> {
const hostId = context.host.id;
const path = context.inputs.path ?? context.projectCheckout.path;
const branchInput = context.inputs.branch;
if (!(await context.experimental_claimPath(path))) {
return {
status: "failed",

message: LIVE_THREAD_MESSAGE,
};
const claimDeadline = Date.now() + ATTACH_TIMEOUT_MS;
while (!(await context.experimental_claimPath(path))) {
context.signal.throwIfAborted();
if (branchInput !== undefined || Date.now() >= claimDeadline) {
return {
status: "failed",
message: "Workspace is being prepared by another thread",
};
}
await delay(50, undefined, { signal: context.signal });
}
if (
branchInput !== undefined &&
Expand Down
Loading