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

BitbucketApi.test.ts

806 lines27.0 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { assert, it, vi } from "@effect/vitest";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as ConfigProvider from "effect/ConfigProvider";
5import * as DateTime from "effect/DateTime";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as Schema from "effect/Schema";
14import * as TestClock from "effect/testing/TestClock";
15import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
16​
17import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
18import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
19import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
20​
21import * as BitbucketApi from "./BitbucketApi.ts";
22​
23type HostGit = SourceControlHost.SourceControlHost["Service"]["git"];
24​
25const isBitbucketRepositoryLocatorError = Schema.is(BitbucketApi.BitbucketRepositoryLocatorError);
26​
27const bitbucketPullRequest = {
28 id: 42,
29 title: "Add Bitbucket provider",
30 state: "OPEN",
31 updated_on: "2026-01-02T00:00:00.000Z",
32 links: {
33 html: {
34 href: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
35 },
36 },
37 source: {
38 branch: { name: "feature/source-control" },
39 repository: {
40 full_name: "octocat/t3code",
41 workspace: { slug: "octocat" },
42 },
43 },
44 destination: {
45 branch: { name: "main" },
46 repository: {
47 full_name: "pingdotgg/t3code",
48 workspace: { slug: "pingdotgg" },
49 },
50 },
51};
52​
53const repositoryJson = {
54 full_name: "pingdotgg/t3code",
55 links: {
56 html: { href: "https://bitbucket.org/pingdotgg/t3code" },
57 clone: [
58 { name: "https", href: "https://bitbucket.org/pingdotgg/t3code.git" },
59 { name: "ssh", href: "git@bitbucket.org:pingdotgg/t3code.git" },
60 ],
61 },
62 mainbranch: { name: "main" },
63};
64​
65function makeLayer(input: {
66 readonly response: (request: HttpClientRequest.HttpClientRequest) => Response;
67 /** Holds the answer until it resolves, in place of answering at once. */
68 readonly answer?: (response: Response) => Effect.Effect<Response>;
69 readonly requestFailure?: (
70 request: HttpClientRequest.HttpClientRequest,
71 ) => HttpClientError.HttpClientError;
72 readonly stall?: boolean;
73 readonly git?: Partial<HostGit>;
74 readonly env?: Record<string, string>;
75}) {
76 const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) =>
77 input.stall
78 ? Effect.never
79 : input.requestFailure
80 ? Effect.fail(input.requestFailure(request))
81 : (input.answer ?? Effect.succeed)(input.response(request)).pipe(
82 Effect.map((response) => HttpClientResponse.fromWeb(request, response)),
83 ),
84 );
85 const gitMock = {
86 readConfigValue: vi.fn<HostGit["readConfigValue"]>(() =>
87 Effect.succeed<string | null>("git@bitbucket.org:pingdotgg/t3code.git"),
88 ),
89 resolvePrimaryRemoteName: vi.fn<HostGit["resolvePrimaryRemoteName"]>(() =>
90 Effect.succeed("origin"),
91 ),
92 ensureRemote: vi.fn<HostGit["ensureRemote"]>(() => Effect.succeed("octocat")),
93 fetchRemoteBranch: vi.fn<HostGit["fetchRemoteBranch"]>(() => Effect.void),
94 fetchRemoteTrackingBranch: vi.fn<HostGit["fetchRemoteTrackingBranch"]>(() => Effect.void),
95 setBranchUpstream: vi.fn<HostGit["setBranchUpstream"]>(() => Effect.void),
96 switchRef: vi.fn<HostGit["switchRef"]>((request) =>
97 Effect.succeed({ refName: request.refName }),
98 ),
99 listLocalBranchNames: vi.fn<HostGit["listLocalBranchNames"]>(() => Effect.succeed([])),
100 };
101 const git = {
102 ...gitMock,
103 ...input.git,
104 } satisfies Partial<HostGit>;
105​
106 const listRemotes = vi.fn(() =>
107 Effect.succeed({
108 remotes: [
109 {
110 name: "origin",
111 url: "git@bitbucket.org:pingdotgg/t3code.git",
112 pushUrl: Option.none(),
113 isPrimary: true,
114 },
115 ],
116 freshness: {
117 source: "live-local" as const,
118 observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"),
119 expiresAt: Option.none(),
120 },
121 }),
122 );
123 // The outer effect resolves the repository; the inner one lists its remotes.
124 const resolve = vi.fn((_cwd: string) => Effect.succeed(Effect.suspend(listRemotes)));
125​
126 const layer = BitbucketApi.layer.pipe(
127 Layer.provide(SourceControlRateLimit.layer),
128 Layer.provide(
129 Layer.succeed(
130 HttpClient.HttpClient,
131 HttpClient.make((request) => execute(request)),
132 ),
133 ),
134 Layer.provide(
135 ConfigProvider.layer(
136 ConfigProvider.fromEnv({
137 env: input.env ?? {
138 T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0",
139 T3CODE_BITBUCKET_EMAIL: "user@example.com",
140 T3CODE_BITBUCKET_API_TOKEN: "token",
141 },
142 }),
143 ),
144 ),
145 Layer.provideMerge(TestSourceControlHost.layer({ git: { ...git, remotes: resolve } })),
146 Layer.provideMerge(NodeServices.layer),
147 );
148​
149 return { execute, git: gitMock, resolve, listRemotes, layer };
151​
152it.effect("parses pull request responses from the Bitbucket REST API", () => {
153 const { execute, layer } = makeLayer({
154 response: () =>
155 Response.json({
156 ...bitbucketPullRequest,
157 }),
158 });
159​
160 return Effect.gen(function* () {
161 const bitbucket = yield* BitbucketApi.BitbucketApi;
162 const result = yield* bitbucket.getPullRequest({
163 cwd: "/repo",
164 reference: "#42",
165 });
166​
167 assert.deepStrictEqual(result, {
168 number: 42,
169 title: "Add Bitbucket provider",
170 url: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
171 baseRefName: "main",
172 headRefName: "feature/source-control",
173 state: "open",
174 updatedAt: Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
175 isCrossRepository: true,
176 headRepositoryNameWithOwner: "octocat/t3code",
177 headRepositoryOwnerLogin: "octocat",
178 });
179 assert.strictEqual(
180 execute.mock.calls[0]?.[0].url,
181 "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests/42",
182 );
183 }).pipe(Effect.provide(layer));
184});
185​
186it.effect("lists pull requests with Bitbucket state and source branch query params", () => {
187 const { execute, layer } = makeLayer({
188 response: () =>
189 Response.json({
190 values: [
191 {
192 ...bitbucketPullRequest,
193 id: 7,
194 state: "MERGED",
195 source: {
196 branch: { name: "feature/merged" },
197 repository: { full_name: "pingdotgg/t3code" },
198 },
199 },
200 ],
201 }),
202 });
203​
204 return Effect.gen(function* () {
205 const bitbucket = yield* BitbucketApi.BitbucketApi;
206 const result = yield* bitbucket.listPullRequests({
207 cwd: "/repo",
208 headSelector: "origin:feature/merged",
209 state: "merged",
210 limit: 10,
211 });
212​
213 assert.strictEqual(result[0]?.state, "merged");
214 const request = execute.mock.calls[0]?.[0];
215 assert.strictEqual(
216 request?.url,
217 "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests",
218 );
219 assert.deepStrictEqual(request?.urlParams.params, [
220 ["pagelen", "10"],
221 ["sort", "-updated_on"],
222 ["q", 'source.branch.name = "feature/merged" AND state = "MERGED"'],
223 ["state", "MERGED"],
224 ]);
225 }).pipe(Effect.provide(layer));
226});
227​
228it.effect("reads repository clone URLs and default branch", () => {
229 const { layer } = makeLayer({
230 response: (request) =>
231 Response.json(
232 request.url.endsWith("/branching-model")
233 ? {
234 development: {
235 branch: { name: "main" },
236 name: "main",
237 use_mainbranch: true,
238 },
239 }
240 : repositoryJson,
241 ),
242 });
243​
244 return Effect.gen(function* () {
245 const bitbucket = yield* BitbucketApi.BitbucketApi;
246 const cloneUrls = yield* bitbucket.getRepositoryCloneUrls({
247 cwd: "/repo",
248 repository: "pingdotgg/t3code",
249 });
250 const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
251​
252 assert.deepStrictEqual(cloneUrls, {
253 nameWithOwner: "pingdotgg/t3code",
254 url: "https://bitbucket.org/pingdotgg/t3code.git",
255 sshUrl: "git@bitbucket.org:pingdotgg/t3code.git",
256 });
257 assert.strictEqual(defaultBranch, "main");
258 }).pipe(Effect.provide(layer));
259});
260​
261it.effect.each([false, true])(
262 "rejects invalid explicit repositories before fallback, context=%s",
263 (withContext) => {
264 const { execute, resolve, listRemotes, layer } = makeLayer({
265 response: () => Response.json(repositoryJson),
266 });
267​
268 return Effect.gen(function* () {
269 const bitbucket = yield* BitbucketApi.BitbucketApi;
270 for (const repository of ["t3code", "", " \t "]) {
271 const error = yield* bitbucket
272 .getRepositoryCloneUrls({
273 cwd: "/repo",
274 repository,
275 ...(withContext
276 ? {
277 context: {
278 provider: {
279 kind: SourceControlProviderKind.make("bitbucket"),
280 name: "Bitbucket",
281 baseUrl: "https://bitbucket.org",
282 },
283 remoteName: "origin",
284 remoteUrl: "git@bitbucket.org:pingdotgg/t3code.git",
285 },
286 }
287 : {}),
288 })
289 .pipe(Effect.match({ onFailure: (error) => error, onSuccess: () => null }));
290​
291 assert.instanceOf(error, BitbucketApi.BitbucketRepositoryLocatorError);
292 assert.strictEqual(
293 isBitbucketRepositoryLocatorError(error) ? error.repository : null,
294 repository,
295 );
296 assert.strictEqual(resolve.mock.calls.length, 0);
297 assert.strictEqual(listRemotes.mock.calls.length, 0);
298 assert.strictEqual(execute.mock.calls.length, 0);
299 }
300 }).pipe(Effect.provide(layer));
301 },
302);
303​
304it.effect("prefers an explicit repository and uses context when the repository is omitted", () => {
305 const { execute, resolve, listRemotes, layer } = makeLayer({
306 response: (request) =>
307 Response.json(request.url.endsWith("/branching-model") ? {} : repositoryJson),
308 });
309​
310 return Effect.gen(function* () {
311 const bitbucket = yield* BitbucketApi.BitbucketApi;
312 const context = {
313 provider: {
314 kind: SourceControlProviderKind.make("bitbucket"),
315 name: "Bitbucket",
316 baseUrl: "https://bitbucket.org",
317 },
318 remoteName: "origin",
319 remoteUrl: "git@bitbucket.org:another/context.git",
320 };
321 for (const repository of ["pingdotgg/t3code", "https://bitbucket.org/pingdotgg/t3code.git"]) {
322 yield* bitbucket.getRepositoryCloneUrls({ cwd: "/repo", context, repository });
323 }
324 yield* bitbucket.getDefaultBranch({ cwd: "/repo", context });
325​
326 assert.deepStrictEqual(
327 execute.mock.calls.map(([request]) => request.url).toSorted(),
328 [
329 "https://api.test.local/2.0/repositories/pingdotgg/t3code",
330 "https://api.test.local/2.0/repositories/pingdotgg/t3code",
331 "https://api.test.local/2.0/repositories/another/context",
332 "https://api.test.local/2.0/repositories/another/context/branching-model",
333 ].toSorted(),
334 );
335 assert.strictEqual(resolve.mock.calls.length, 0);
336 assert.strictEqual(listRemotes.mock.calls.length, 0);
337 }).pipe(Effect.provide(layer));
338});
339​
340it.effect(
341 "prefers the Bitbucket branching model development branch as the default PR target",
342 () => {
343 const { execute, layer } = makeLayer({
344 response: (request) =>
345 Response.json(
346 request.url.endsWith("/branching-model")
347 ? {
348 development: {
349 branch: { name: "develop" },
350 name: "develop",
351 use_mainbranch: false,
352 },
353 }
354 : repositoryJson,
355 ),
356 });
357​
358 return Effect.gen(function* () {
359 const bitbucket = yield* BitbucketApi.BitbucketApi;
360 const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
361​
362 assert.strictEqual(defaultBranch, "develop");
363 assert.deepStrictEqual(
364 execute.mock.calls.map((call) => call[0].url).toSorted(),
365 [
366 "https://api.test.local/2.0/repositories/pingdotgg/t3code",
367 "https://api.test.local/2.0/repositories/pingdotgg/t3code/branching-model",
368 ].toSorted(),
369 );
370 }).pipe(Effect.provide(layer));
371 },
372);
373​
374it.effect(
375 "falls back to the repository main branch when the Bitbucket development branch is invalid",
376 () => {
377 const { layer } = makeLayer({
378 response: (request) =>
379 Response.json(
380 request.url.endsWith("/branching-model")
381 ? {
382 development: {
383 name: "develop",
384 use_mainbranch: false,
385 is_valid: false,
386 },
387 }
388 : repositoryJson,
389 ),
390 });
391​
392 return Effect.gen(function* () {
393 const bitbucket = yield* BitbucketApi.BitbucketApi;
394 const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
395​
396 assert.strictEqual(defaultBranch, "main");
397 }).pipe(Effect.provide(layer));
398 },
399);
400​
401it.effect("creates pull requests using the official REST payload shape", () => {
402 const { execute, layer } = makeLayer({
403 response: () => Response.json(bitbucketPullRequest),
404 });
405​
406 return Effect.gen(function* () {
407 const fileSystem = yield* FileSystem.FileSystem;
408 const bodyFile = yield* fileSystem.makeTempFileScoped({ prefix: "bitbucket-pr-body-" });
409 yield* fileSystem.writeFileString(bodyFile, "PR body");
410​
411 const bitbucket = yield* BitbucketApi.BitbucketApi;
412 yield* bitbucket.createPullRequest({
413 cwd: "/repo",
414 baseBranch: "main",
415 headSelector: "owner:feature/provider",
416 title: "Provider PR",
417 bodyFile,
418 });
419​
420 const request = execute.mock.calls[0]?.[0];
421 assert.strictEqual(
422 request?.url,
423 "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests",
424 );
425 assert.strictEqual(request?.method, "POST");
426 assert.ok(request);
427 const rawBody = (request.body as { readonly body?: Uint8Array }).body;
428 assert.ok(rawBody);
429 assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), {
430 title: "Provider PR",
431 description: "PR body",
432 source: {
433 branch: { name: "feature/provider" },
434 repository: { full_name: "owner/t3code" },
435 },
436 destination: {
437 branch: { name: "main" },
438 },
439 });
440 }).pipe(Effect.provide(layer), Effect.scoped);
441});
442​
443it.effect("reports the account Bitbucket confirms for the configured credential", () => {
444 const { layer } = makeLayer({
445 response: () => Response.json({ username: "bitbucket-user" }),
446 });
447​
448 return Effect.gen(function* () {
449 const bitbucket = yield* BitbucketApi.BitbucketApi;
450 const auth = yield* bitbucket.probeAuth;
451 assert.strictEqual(auth.status, "authenticated");
452 assert.deepStrictEqual(auth.account, Option.some("bitbucket-user"));
453 assert.deepStrictEqual(auth.host, Option.some("bitbucket.org"));
454 }).pipe(Effect.provide(layer));
455});
456​
457it.effect("prefers credentials saved in settings over the environment, without a restart", () => {
458 const { execute, layer } = makeLayer({
459 response: () => Response.json({ username: "bitbucket-user" }),
460 });
461 const lastAuthorization = () => execute.mock.calls.at(-1)?.[0].headers.authorization;
462 const basic = (user: string, password: string) => `Basic ${btoa(`${user}:${password}`)}`;
463​
464 return Effect.gen(function* () {
465 const bitbucket = yield* BitbucketApi.BitbucketApi;
466 const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
467​
468 yield* bitbucket.probeAuth;
469 assert.strictEqual(lastAuthorization(), basic("user@example.com", "token"));
470​
471 yield* settings.update({
472 sourceControlHosts: {
473 bitbucket: { email: "saved@example.com", apiToken: "saved-api-token" },
474 },
475 });
476 yield* bitbucket.probeAuth;
477 assert.strictEqual(lastAuthorization(), basic("saved@example.com", "saved-api-token"));
478​
479 yield* settings.update({
480 sourceControlHosts: { bitbucket: { accessToken: "saved-access-token" } },
481 });
482 yield* bitbucket.probeAuth;
483 assert.strictEqual(lastAuthorization(), "Bearer saved-access-token");
484​
485 yield* settings.update({
486 sourceControlHosts: { bitbucket: { accessToken: "", apiToken: "" } },
487 });
488 yield* bitbucket.probeAuth;
489 assert.strictEqual(lastAuthorization(), basic("user@example.com", "token"));
490 }).pipe(Effect.provide(layer));
491});
492​
493it.effect("never puts a saved token that is unsafe for an HTTP header on the wire", () => {
494 const { execute, layer } = makeLayer({
495 response: () => Response.json({ username: "bitbucket-user" }),
496 });
497​
498 return Effect.gen(function* () {
499 const bitbucket = yield* BitbucketApi.BitbucketApi;
500 const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
501​
502 // Fetch would reject this header with an error quoting the token, and that error reaches
503 // clients. The unusable token is ignored, so the environment credential is used instead.
504 yield* settings.update({
505 sourceControlHosts: { bitbucket: { accessToken: "saved\ntoken" } },
506 });
507 yield* bitbucket.probeAuth;
508 assert.strictEqual(
509 execute.mock.calls.at(-1)?.[0].headers.authorization,
510 `Basic ${btoa("user@example.com:token")}`,
511 );
512 }).pipe(Effect.provide(layer));
513});
514​
515it.effect("reports saved credentials as configured when Bitbucket cannot confirm them", () => {
516 const { execute, layer } = makeLayer({
517 response: () => new Response(null, { status: 401 }),
518 env: { T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0" },
519 });
520​
521 return Effect.gen(function* () {
522 const bitbucket = yield* BitbucketApi.BitbucketApi;
523 const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
524​
525 assert.strictEqual((yield* bitbucket.probeAuth).status, "unauthenticated");
526 assert.strictEqual(execute.mock.calls.length, 0);
527​
528 yield* settings.update({
529 sourceControlHosts: { bitbucket: { accessToken: "saved-access-token" } },
530 });
531 assert.deepStrictEqual(yield* bitbucket.probeAuth, {
532 status: "unknown",
533 account: Option.none(),
534 host: Option.some("bitbucket.org"),
535 detail: Option.some("An access token is configured."),
536 });
537 }).pipe(Effect.provide(layer));
538});
539​
540it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => {
541 const responseBody = '{"error":{"message":"credential=secret-value"}}';
542 const { layer } = makeLayer({
543 response: () => new Response(responseBody, { status: 403 }),
544 });
545​
546 return Effect.gen(function* () {
547 const bitbucket = yield* BitbucketApi.BitbucketApi;
548 const error = yield* bitbucket
549 .checkoutPullRequest({ cwd: "/repo", reference: "42" })
550 .pipe(Effect.flip);
551​
552 assert.instanceOf(error, BitbucketApi.BitbucketResponseError);
553 assert.strictEqual(error.operation, "getPullRequest");
554 assert.strictEqual(error.status, 403);
555 assert.strictEqual(error.responseBodyLength, responseBody.length);
556 assert.notProperty(error, "responseBody");
557 assert.strictEqual(
558 error.message,
559 "Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 403.",
560 );
561 assert.notInclude(error.message, "secret-value");
562 }).pipe(Effect.provide(layer));
563});
564​
565it.effect("checks out fork pull requests through an ensured fork remote", () => {
566 const { git, layer } = makeLayer({
567 response: (request) => {
568 if (request.url.endsWith("/repositories/octocat/t3code")) {
569 return Response.json({
570 ...repositoryJson,
571 full_name: "octocat/t3code",
572 links: {
573 html: { href: "https://bitbucket.org/octocat/t3code" },
574 clone: [
575 { name: "https", href: "https://bitbucket.org/octocat/t3code.git" },
576 { name: "ssh", href: "git@bitbucket.org:octocat/t3code.git" },
577 ],
578 },
579 });
580 }
581 return Response.json({
582 ...bitbucketPullRequest,
583 source: {
584 branch: { name: "main" },
585 repository: {
586 full_name: "octocat/t3code",
587 workspace: { slug: "octocat" },
588 },
589 },
590 });
591 },
592 });
593​
594 return Effect.gen(function* () {
595 const bitbucket = yield* BitbucketApi.BitbucketApi;
596 yield* bitbucket.checkoutPullRequest({
597 cwd: "/repo",
598 reference: "42",
599 force: true,
600 });
601​
602 assert.deepStrictEqual(git.ensureRemote.mock.calls[0]?.[0], {
603 cwd: "/repo",
604 preferredName: "octocat",
605 url: "git@bitbucket.org:octocat/t3code.git",
606 });
607 assert.deepStrictEqual(git.fetchRemoteBranch.mock.calls[0]?.[0], {
608 cwd: "/repo",
609 remoteName: "octocat",
610 remoteBranch: "main",
611 localBranch: "t3code/pr-42/main",
612 });
613 assert.deepStrictEqual(git.setBranchUpstream.mock.calls[0]?.[0], {
614 cwd: "/repo",
615 branch: "t3code/pr-42/main",
616 remoteName: "octocat",
617 remoteBranch: "main",
618 });
619 assert.deepStrictEqual(git.switchRef.mock.calls[0]?.[0], {
620 cwd: "/repo",
621 refName: "t3code/pr-42/main",
622 });
623 }).pipe(Effect.provide(layer));
624});
625​
626it.effect("refuses a url that points away from the configured Bitbucket", () => {
627 const { layer, execute } = makeLayer({ response: () => new Response("{}", { status: 200 }) });
628 return Effect.gen(function* () {
629 const bitbucket = yield* BitbucketApi.BitbucketApi;
630​
631 const error = yield* Effect.flip(
632 bitbucket.request({ method: "GET", url: "https://attacker.example/2.0/repositories" }),
633 );
634​
635 assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
636 assert.strictEqual(execute.mock.calls.length, 0);
637 }).pipe(Effect.provide(layer));
638});
639​
640it.effect("keeps only the host of a url it refuses, never its query", () =>
641 Effect.gen(function* () {
642 const bitbucket = yield* BitbucketApi.BitbucketApi;
643​
644 const error = yield* Effect.flip(
645 bitbucket.request({
646 method: "GET",
647 url: "https://attacker.example/asset?signature=secret-token",
648 }),
649 );
650​
651 assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
652 assert.strictEqual(
653 error._tag === "BitbucketUntrustedUrlError" ? error.host : "",
654 "https://attacker.example",
655 );
656 assert.notInclude(error.message, "secret-token");
657 }).pipe(Effect.provide(makeLayer({ response: () => new Response("{}", { status: 200 }) }).layer)),
658);
659​
660it.effect("does not follow a redirect off the configured Bitbucket", () =>
661 Effect.gen(function* () {
662 const bitbucket = yield* BitbucketApi.BitbucketApi;
663​
664 const error = yield* Effect.flip(
665 bitbucket.request({ method: "GET", url: "/repositories/acme/web/pullrequests/1/diff" }),
666 );
667​
668 assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
669 }).pipe(
670 Effect.provide(
671 makeLayer({
672 response: () =>
673 new Response(null, {
674 status: 302,
675 headers: { location: "https://attacker.example/stolen" },
676 }),
677 }).layer,
678 ),
679 ),
680);
681​
682it.effect("follows a redirect that stays on the configured Bitbucket", () =>
683 Effect.gen(function* () {
684 const bitbucket = yield* BitbucketApi.BitbucketApi;
685​
686 const result = yield* bitbucket.request({
687 method: "GET",
688 url: "/repositories/acme/web/pullrequests/1/diff",
689 });
690​
691 assert.strictEqual(result.body, "diff --git a/a.ts b/a.ts");
692 assert.isFalse(result.truncated);
693 }).pipe(
694 Effect.provide(
695 makeLayer({
696 response: (request) =>
697 request.url.endsWith("/pullrequests/1/diff")
698 ? new Response(null, {
699 status: 302,
700 headers: { location: "https://api.test.local/2.0/repositories/acme/web/diff/abc" },
701 })
702 : new Response("diff --git a/a.ts b/a.ts", { status: 200 }),
703 }).layer,
704 ),
705 ),
706);
707​
708it.effect("cuts a response short rather than reading an unbounded diff into memory", () =>
709 Effect.gen(function* () {
710 const bitbucket = yield* BitbucketApi.BitbucketApi;
711​
712 const result = yield* bitbucket.request({
713 method: "GET",
714 url: "/repositories/acme/web/pullrequests/1/diff",
715 maxBytes: 8,
716 });
717​
718 assert.strictEqual(result.body, "12345678");
719 assert.isTrue(result.truncated);
720 }).pipe(
721 Effect.provide(
722 makeLayer({ response: () => new Response("1234567890", { status: 200 }) }).layer,
723 ),
724 ),
725);
726​
727it.effect("pauses background reads after a 429 until Bitbucket's retry-after passes", () => {
728 let answered = 0;
729 const { execute, layer } = makeLayer({
730 response: () => {
731 answered += 1;
732 return answered === 1
733 ? new Response("Rate limit exceeded", { status: 429, headers: { "retry-after": "60" } })
734 : Response.json({ values: [] });
735 },
736 });
737​
738 return Effect.gen(function* () {
739 const bitbucket = yield* BitbucketApi.BitbucketApi;
740 const lookup = bitbucket.listPullRequests({
741 cwd: "/repo",
742 headSelector: "feature/a",
743 state: "all",
744 });
745​
746 yield* Effect.flip(lookup);
747 const paused = yield* Effect.flip(lookup);
748 // Keyed by the repository host, where PullRequestService records its own backoff.
749 assert.deepInclude(paused, {
750 _tag: "SourceControlRateLimitPausedError",
751 host: "bitbucket.org",
752 retryAt: 60_000,
753 });
754 assert.strictEqual(execute.mock.calls.length, 1);
755​
756 // A user waiting on an answer is not held back by the background pause, and their success
757 // does not end it early.
758 yield* lookup.pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
759 yield* bitbucket.request({
760 method: "POST",
761 url: "/repositories/acme/web/pullrequests/1/approve",
762 });
763​
764 yield* TestClock.adjust("59 seconds");
765 assert.strictEqual((yield* Effect.flip(lookup))._tag, "SourceControlRateLimitPausedError");
766​
767 yield* TestClock.adjust("1 second");
768 yield* lookup;
769 }).pipe(Effect.provide(layer));
770});
771​
772it.effect("keeps a sweep over many branches to a few Bitbucket requests at a time", () =>
773 Effect.gen(function* () {
774 const started = yield* Queue.unbounded<void>();
775 const release = yield* Deferred.make<void>();
776 let inFlight = 0;
777 let peak = 0;
778 const { layer } = makeLayer({
779 response: () => Response.json({ values: [] }),
780 answer: (response) =>
781 Effect.gen(function* () {
782 inFlight += 1;
783 peak = Math.max(peak, inFlight);
784 yield* Queue.offer(started, undefined);
785 yield* Deferred.await(release);
786 inFlight -= 1;
787 return response;
788 }),
789 });
790​
791 yield* Effect.gen(function* () {
792 const bitbucket = yield* BitbucketApi.BitbucketApi;
793 const sweep = yield* Effect.forEach(
794 Array.from({ length: 12 }, (_, index) => `feature/${index}`),
795 (branch) =>
796 bitbucket.listPullRequests({ cwd: "/repo", headSelector: branch, state: "all" }),
797 { concurrency: "unbounded", discard: true },
798 ).pipe(Effect.forkChild);
799 for (let index = 0; index < 4; index += 1) yield* Queue.take(started);
800 yield* Deferred.succeed(release, undefined);
801 yield* Fiber.join(sweep);
802 }).pipe(Effect.provide(layer));
803​
804 assert.strictEqual(peak, 4);
805 }),
806);