sailfork / t3code-github / packages/ source-control-bitbucket/ src/ server/ BitbucketApi.ts

import * as Clock from "effect/Clock";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import {
  NonNegativeInt,
  requireSettingsSecretLiteral,
  SettingsSecretUnresolvedError,
  SourceControlProviderKind,
  TrimmedNonEmptyString,
  type ServerSettings,
  type SourceControlProviderAuth,
  type SourceControlProviderInfo,
  type SourceControlRepositoryCloneUrls,
  type SourceControlRepositoryVisibility,
} from "@t3tools/contracts";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { sanitizeBranchFragment } from "@t3tools/shared/git";
import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
import { recognizeRemoteWith } from "@t3tools/source-control-core/shared/definition";
import { definition } from "../shared/definition.ts";

import {
  BitbucketPullRequestListSchema,
  BitbucketPullRequestSchema,
  normalizeBitbucketPullRequestRecord,
  type NormalizedBitbucketPullRequestRecord,
} from "./bitbucketPullRequests.ts";
import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";

import * as BitbucketClient from "../shared/definition.ts";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";

const DEFAULT_API_BASE_URL = "https://api.bitbucket.org/2.0";
const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
const MAX_REDIRECTS = 3;
const BITBUCKET_API_REQUEST_TIMEOUT = "30 seconds";
/** A sweep over many branches would otherwise reach Bitbucket as one burst of lookups. */
const CONCURRENCY = 4;

const BitbucketApiEnvConfig = Config.all({
  baseUrl: Config.String("T3CODE_BITBUCKET_API_BASE_URL").pipe(
    Config.withDefault(DEFAULT_API_BASE_URL),
  ),
  accessToken: Config.String("T3CODE_BITBUCKET_ACCESS_TOKEN").pipe(Config.option),
  email: Config.String("T3CODE_BITBUCKET_EMAIL").pipe(Config.option),
  apiToken: Config.String("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
});

// Server and Data Center use a different API; a custom Cloud endpoint must be explicit.
export const BitbucketServesHost = Config.String("T3CODE_BITBUCKET_API_BASE_URL").pipe(
  Config.option,
  Config.map(
    (baseUrl) => (host: string) =>
      Option.isSome(baseUrl) || host === "bitbucket.org" || host.endsWith(".bitbucket.org"),
  ),
);

const BitbucketApiOperation = Schema.Literals([
  "resolveRepository",
  "getRepository",
  "getBranchingModel",
  "getPullRequest",
  "listPullRequests",
  "createRepository",
  "createPullRequest",
  "probeAuth",
  "checkoutPullRequest",
  "request",
]);
type BitbucketApiOperation = typeof BitbucketApiOperation.Type;

export class BitbucketRepositoryLocatorError extends Schema.TaggedError<BitbucketRepositoryLocatorError>()(
  "BitbucketRepositoryLocatorError",
  {
    repository: Schema.String,
  },
) {
  static readonly detail = "Bitbucket repositories must be specified as workspace/repository.";

  get detail(): string {
    return BitbucketRepositoryLocatorError.detail;
  }

  get userFacingDetail(): string {
    return BitbucketRepositoryLocatorError.detail;
  }

  override get message(): string {
    return `Bitbucket API failed: ${this.detail}`;
  }
}

export class BitbucketRequestError extends Schema.TaggedError<BitbucketRequestError>()(
  "BitbucketRequestError",
  {
    operation: BitbucketApiOperation,
    cause: Schema.Defect(),
  },
) {
  get detail(): string {
    return "Failed to send the Bitbucket request.";
  }

  override get message(): string {
    return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
  }
}

export class BitbucketResponseError extends Schema.TaggedError<BitbucketResponseError>()(
  "BitbucketResponseError",
  {
    operation: BitbucketApiOperation,
    status: Schema.Int,
    responseBodyLength: NonNegativeInt,
    retryAt: Schema.optional(Schema.Number),
  },
) {
  get detail(): string {
    return `Bitbucket returned HTTP ${this.status}.`;
  }

  override get message(): string {
    return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
  }
}

export class BitbucketResponseBodyReadError extends Schema.TaggedError<BitbucketResponseBodyReadError>()(
  "BitbucketResponseBodyReadError",
  {
    operation: BitbucketApiOperation,
    status: Schema.Int,
    retryAt: Schema.optional(Schema.Number),
    cause: Schema.Defect(),
  },
) {
  get detail(): string {
    return `Bitbucket returned HTTP ${this.status}.`;
  }

  override get message(): string {
    return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
  }
}

export class BitbucketResponseDecodeError extends Schema.TaggedError<BitbucketResponseDecodeError>()(
  "BitbucketResponseDecodeError",
  {
    operation: BitbucketApiOperation,
    status: Schema.Int,
    cause: Schema.Defect(),
  },
) {
  get detail(): string {
    return "Bitbucket returned invalid JSON for the requested resource.";
  }

  override get message(): string {
    return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
  }
}

export class BitbucketRepositoryVcsResolveError extends Schema.TaggedError<BitbucketRepositoryVcsResolveError>()(
  "BitbucketRepositoryVcsResolveError",
  {
    cwd: Schema.String,
    cause: Schema.Defect(),
  },
) {
  get detail(): string {
    return `Failed to resolve VCS repository for ${this.cwd}.`;
  }

  override get message(): string {
    return `Bitbucket API failed in resolveRepository: ${this.detail}`;
  }
}

export class BitbucketRepositoryRemotesListError extends Schema.TaggedError<BitbucketRepositoryRemotesListError>()(
  "BitbucketRepositoryRemotesListError",
  {
    cwd: Schema.String,
    cause: Schema.Defect(),
  },
) {
  get detail(): string {
    return `Failed to list remotes for ${this.cwd}.`;
  }

  override get message(): string {
    return `Bitbucket API failed in resolveRepository: ${this.detail}`;
  }
}

export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedError<BitbucketRepositoryRemoteNotFoundError>()(
  "BitbucketRepositoryRemoteNotFoundError",
  {
    cwd: Schema.String,
  },
) {
  get detail(): string {
    return `No Bitbucket repository remote was detected for ${this.cwd}.`;
  }

  override get message(): string {
    return `Bitbucket API failed in resolveRepository: ${this.detail}`;
  }
}

export class BitbucketPullRequestBodyReadError extends Schema.TaggedError<BitbucketPullRequestBodyReadError>()(
  "BitbucketPullRequestBodyReadError",
  {
    cwd: Schema.String,
    bodyFile: Schema.String,
    cause: Schema.Defect(),
  },
) {
  get detail(): string {
    return `Failed to read pull request body file ${this.bodyFile}.`;
  }

  override get message(): string {
    return `Bitbucket API failed in createPullRequest: ${this.detail}`;
  }
}

export class BitbucketCheckoutError extends Schema.TaggedError<BitbucketCheckoutError>()(
  "BitbucketCheckoutError",
  {
    cwd: Schema.String,
    reference: Schema.String,
    cause: Schema.Defect(),
  },
) {
  get detail(): string {
    return "Failed to check out the Bitbucket pull request.";
  }

  override get message(): string {
    return `Bitbucket API failed in checkoutPullRequest: ${this.detail}`;
  }
}

/** Reject response-supplied URLs that could leak credentials. */
export class BitbucketUntrustedUrlError extends Schema.TaggedError<BitbucketUntrustedUrlError>()(
  "BitbucketUntrustedUrlError",
  {
    /** Host only; signed URL queries can contain credentials. */
    host: Schema.String,
  },
) {
  get detail(): string {
    return `The response pointed at ${this.host}, outside the configured Bitbucket.`;
  }

  override get message(): string {
    return `Bitbucket API failed in request: ${this.detail}`;
  }
}

export const BitbucketApiError = Schema.Union([
  BitbucketUntrustedUrlError,
  BitbucketRepositoryLocatorError,
  BitbucketRequestError,
  BitbucketResponseError,
  BitbucketResponseBodyReadError,
  BitbucketResponseDecodeError,
  BitbucketRepositoryVcsResolveError,
  BitbucketRepositoryRemotesListError,
  BitbucketRepositoryRemoteNotFoundError,
  BitbucketPullRequestBodyReadError,
  BitbucketCheckoutError,
  SourceControlRateLimit.SourceControlRateLimitPausedError,
  SettingsSecretUnresolvedError,
]);
export type BitbucketApiError = typeof BitbucketApiError.Type;
const isBitbucketApiError = Schema.is(BitbucketApiError);

const RawBitbucketRepositorySchema = Schema.Struct({
  full_name: TrimmedNonEmptyString,
  links: Schema.Struct({
    html: Schema.optional(
      Schema.Struct({
        href: TrimmedNonEmptyString,
      }),
    ),
    clone: Schema.optional(
      Schema.Array(
        Schema.Struct({
          name: TrimmedNonEmptyString,
          href: TrimmedNonEmptyString,
        }),
      ),
    ),
  }),
  mainbranch: Schema.optional(
    Schema.NullOr(
      Schema.Struct({
        name: TrimmedNonEmptyString,
      }),
    ),
  ),
});

const RawBitbucketBranchingModelSchema = Schema.Struct({
  development: Schema.optional(
    Schema.Struct({
      branch: Schema.optional(
        Schema.NullOr(
          Schema.Struct({
            name: Schema.optional(TrimmedNonEmptyString),
          }),
        ),
      ),
      is_valid: Schema.optional(Schema.Boolean),
      name: Schema.optional(Schema.NullOr(Schema.String)),
      use_mainbranch: Schema.optional(Schema.Boolean),
    }),
  ),
});

const BitbucketUserSchema = Schema.Struct({
  username: Schema.optional(TrimmedNonEmptyString),
  display_name: Schema.optional(TrimmedNonEmptyString),
  account_id: Schema.optional(TrimmedNonEmptyString),
});

export interface BitbucketRepositoryLocator {
  readonly workspace: string;
  readonly repoSlug: string;
}

export class BitbucketApi extends Context.Service<
  BitbucketApi,
  {
    readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;

    readonly request: (input: {
      readonly method: "GET" | "POST" | "PUT" | "DELETE";
      readonly url: string;
      readonly body?: string;
      readonly maxBytes?: number;
    }) => Effect.Effect<{ readonly body: string; readonly truncated: boolean }, BitbucketApiError>;
    readonly listPullRequests: (input: {
      readonly cwd: string;
      readonly context?: SourceControlProvider.SourceControlProviderContext;
      readonly headSelector: string;
      readonly source?: SourceControlProvider.SourceControlRefSelector;
      readonly state: "open" | "closed" | "merged" | "all";
      readonly limit?: number;
    }) => Effect.Effect<ReadonlyArray<NormalizedBitbucketPullRequestRecord>, BitbucketApiError>;
    readonly getPullRequest: (input: {
      readonly cwd: string;
      readonly context?: SourceControlProvider.SourceControlProviderContext;
      readonly reference: string;
    }) => Effect.Effect<NormalizedBitbucketPullRequestRecord, BitbucketApiError>;
    readonly getRepositoryCloneUrls: (input: {
      readonly cwd: string;
      readonly context?: SourceControlProvider.SourceControlProviderContext;
      readonly repository: string;
    }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
    readonly createRepository: (input: {
      readonly cwd: string;
      readonly repository: string;
      readonly visibility: SourceControlRepositoryVisibility;
    }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
    readonly createPullRequest: (input: {
      readonly cwd: string;
      readonly context?: SourceControlProvider.SourceControlProviderContext;
      readonly baseBranch: string;
      readonly headSelector: string;
      readonly source?: SourceControlProvider.SourceControlRefSelector;
      readonly target?: SourceControlProvider.SourceControlRefSelector;
      readonly title: string;
      readonly bodyFile: string;
    }) => Effect.Effect<void, BitbucketApiError>;
    readonly getDefaultBranch: (input: {
      readonly cwd: string;
      readonly context?: SourceControlProvider.SourceControlProviderContext;
    }) => Effect.Effect<string | null, BitbucketApiError>;
    readonly checkoutPullRequest: (input: {
      readonly cwd: string;
      readonly context?: SourceControlProvider.SourceControlProviderContext;
      readonly reference: string;
      readonly force?: boolean;
    }) => Effect.Effect<void, BitbucketApiError>;
  }
>()("@t3tools/source-control-bitbucket/server/BitbucketApi") {}

function nonEmpty(value: string | undefined): Option.Option<string> {
  const trimmed = value?.trim();
  return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}

function normalizeChangeRequestId(reference: string): string {
  const trimmed = reference.trim().replace(/^#/, "");
  const urlMatch = /(?:pull-requests|pullrequests|pull-request|pull|pr)\/(\d+)(?:\D.*)?$/i.exec(
    trimmed,
  );
  return urlMatch?.[1] ?? trimmed;
}

function sourceWorkspace(input: {
  readonly headSelector: string;
  readonly source?: SourceControlProvider.SourceControlRefSelector;
}): string | undefined {
  if (input.source?.owner) return input.source.owner;
  return SourceControlProvider.parseSourceControlOwnerRef(input.headSelector)?.owner;
}

function toBitbucketStates(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
  switch (state) {
    case "open":
      return ["OPEN"];
    case "closed":
      return ["DECLINED", "SUPERSEDED"];
    case "merged":
      return ["MERGED"];
    case "all":
      return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
  }
}

function bitbucketQueryString(filters: ReadonlyArray<string>): string {
  return filters.join(" AND ");
}

function bitbucketStateFilter(states: ReadonlyArray<string>): string {
  return states.length === 1
    ? `state = "${states[0]}"`
    : `(${states.map((state) => `state = "${state}"`).join(" OR ")})`;
}

function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator | null {
  const normalized = value.trim().replace(/\.git$/u, "");
  const parts = normalized.split("/").filter((part) => part.length > 0);
  if (parts.length < 2) return null;
  const workspace = parts.at(-2);
  const repoSlug = parts.at(-1);
  return workspace && repoSlug ? { workspace, repoSlug } : null;
}

function requireRepositoryLocator(
  repository: string,
): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
  const locator = parseBitbucketRepositorySlug(repository);
  return locator
    ? Effect.succeed(locator)
    : Effect.fail(
        new BitbucketRepositoryLocatorError({
          repository,
        }),
      );
}

function parseBitbucketRemoteUrl(remoteUrl: string): BitbucketRepositoryLocator | null {
  const trimmed = remoteUrl.trim();
  const scpMatch = /^[a-zA-Z0-9._-]+@[^:/]+:(.+)$/.exec(trimmed);
  if (scpMatch?.[1]) {
    return parseBitbucketRepositorySlug(scpMatch[1]);
  }

  try {
    return parseBitbucketRepositorySlug(new URL(trimmed).pathname);
  } catch {
    return null;
  }
}

function normalizeRepositoryCloneUrls(
  raw: typeof RawBitbucketRepositorySchema.Type,
): SourceControlRepositoryCloneUrls {
  const httpClone =
    raw.links.clone?.find((entry) => entry.name.toLowerCase() === "https")?.href ??
    raw.links.html?.href;
  const sshClone = raw.links.clone?.find((entry) => entry.name.toLowerCase() === "ssh")?.href;

  return {
    nameWithOwner: raw.full_name,
    url: httpClone ?? raw.links.html?.href ?? raw.full_name,
    sshUrl: sshClone ?? httpClone ?? raw.full_name,
  };
}

function defaultChangeRequestTargetBranch(input: {
  readonly repository: typeof RawBitbucketRepositorySchema.Type;
  readonly branchingModel: typeof RawBitbucketBranchingModelSchema.Type | null;
}): string | null {
  const repositoryMainBranch = input.repository.mainbranch?.name ?? null;
  const development = input.branchingModel?.development;
  if (!development || development.use_mainbranch === true || development.is_valid === false) {
    return repositoryMainBranch;
  }

  const developmentBranch = development.branch?.name?.trim() ?? development.name?.trim() ?? "";
  if (developmentBranch.length === 0 || developmentBranch === "null") {
    return repositoryMainBranch;
  }

  return developmentBranch;
}

function shouldPreferSshRemote(originRemoteUrl: string | null): boolean {
  if (!originRemoteUrl) return false;
  return isSshRemoteUrl(originRemoteUrl);
}

function selectCloneUrl(input: {
  readonly cloneUrls: SourceControlRepositoryCloneUrls;
  readonly originRemoteUrl: string | null;
}): string {
  return shouldPreferSshRemote(input.originRemoteUrl)
    ? input.cloneUrls.sshUrl
    : input.cloneUrls.url;
}

function checkoutBranchName(input: {
  readonly pullRequestId: number;
  readonly headBranch: string;
  readonly isCrossRepository: boolean;
}): string {
  if (!input.isCrossRepository) {
    return input.headBranch;
  }

  return `t3code/pr-${input.pullRequestId}/${sanitizeBranchFragment(input.headBranch)}`;
}

function repositoryNameWithOwner(
  repository: Schema.Schema.Type<typeof BitbucketPullRequestSchema>["source"]["repository"],
): string | null {
  const fullName = repository?.full_name?.trim() ?? "";
  return fullName.length > 0 ? fullName : null;
}

function repositoryOwnerName(repositoryName: string): string {
  return repositoryName.split("/")[0]?.trim() || "bitbucket";
}

type BitbucketCredential =
  | { readonly kind: "access-token"; readonly accessToken: string }
  | { readonly kind: "api-token"; readonly email: string; readonly apiToken: string };

/** Invalid header values can throw errors containing credentials; treat them as unset. */
const HEADER_SAFE = /^[\x21-\x7e]+$/u;

function credentialFrom(input: {
  readonly accessToken: string;
  readonly email: string;
  readonly apiToken: string;
}): BitbucketCredential | null {
  if (HEADER_SAFE.test(input.accessToken)) {
    return { kind: "access-token", accessToken: input.accessToken };
  }
  if (HEADER_SAFE.test(input.email) && HEADER_SAFE.test(input.apiToken)) {
    return { kind: "api-token", email: input.email, apiToken: input.apiToken };
  }
  return null;
}

const resolveCredential = Effect.fn("BitbucketApi.resolveCredential")(function* (
  settings: BitbucketClient.BitbucketSettings,
  secretProviders: ServerSettings["secretProviders"],
  env: Config.Success<typeof BitbucketApiEnvConfig>,
) {
  const accessToken = yield* requireSettingsSecretLiteral(settings.accessToken, secretProviders);
  const apiToken = HEADER_SAFE.test(accessToken)
    ? ""
    : yield* requireSettingsSecretLiteral(settings.apiToken, secretProviders);
  return (
    credentialFrom({ accessToken, email: settings.email, apiToken }) ??
    credentialFrom({
      accessToken: Option.getOrElse(env.accessToken, () => ""),
      email: Option.getOrElse(env.email, () => ""),
      apiToken: Option.getOrElse(env.apiToken, () => ""),
    })
  );
});

function authFromCredential(credential: BitbucketCredential | null): SourceControlProviderAuth {
  if (credential?.kind === "access-token") {
    return {
      status: "unknown",
      account: Option.none(),
      host: Option.some("bitbucket.org"),
      detail: Option.some("An access token is configured."),
    };
  }

  if (credential?.kind === "api-token") {
    return {
      status: "unknown",
      account: Option.some(credential.email),
      host: Option.some("bitbucket.org"),
      detail: Option.some("An API token is configured."),
    };
  }

  return {
    status: "unauthenticated",
    account: Option.none(),
    host: Option.some("bitbucket.org"),
    detail: Option.some(
      "Add a Bitbucket token in Settings → Source Control, or set the T3CODE_BITBUCKET_* environment variables on the server.",
    ),
  };
}

function originOf(value: string): string | null {
  try {
    return new URL(value).origin;
  } catch {
    return null;
  }
}

const responseError = Effect.fn("BitbucketApi.responseError")(function* (
  operation: BitbucketApiOperation,
  response: HttpClientResponse.HttpClientResponse,
): Effect.fn.Return<never, BitbucketApiError> {
  const now = yield* Clock.currentTimeMillis;
  const retryAt = SourceControlRateLimit.retryAtFromHeader(response.headers["retry-after"], now);
  const collected = yield* collectUint8StreamText({
    stream: response.stream,
    maxBytes: DEFAULT_MAX_RESPONSE_BYTES,
  }).pipe(
    Effect.mapError(
      (cause) =>
        new BitbucketResponseBodyReadError({
          operation,
          status: response.status,
          retryAt,
          cause,
        }),
    ),
  );
  return yield* new BitbucketResponseError({
    operation,
    status: response.status,
    responseBodyLength: collected.text.length,
    retryAt,
  });
});

/** @public */
export const make = Effect.gen(function* () {
  const config = yield* BitbucketApiEnvConfig;
  const host = yield* SourceControlHost.SourceControlHost;
  const git = host.git;
  const httpClient = yield* HttpClient.HttpClient;
  const fileSystem = yield* FileSystem.FileSystem;
  const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
  const slots = yield* Semaphore.make(CONCURRENCY);
  // The repository host PullRequestService keys its own backoff under, so both share one pause.
  const rateLimitKey = {
    provider: SourceControlProviderKind.make("bitbucket"),
    host: "bitbucket.org",
  };

  const servesHost = yield* BitbucketServesHost;

  const servesProvider = (provider: SourceControlProviderInfo | null) =>
    provider?.kind === "bitbucket" && servesHost(URL.parse(provider.baseUrl)?.hostname ?? "");

  const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;

  const currentCredential = host.settings.getWithSecrets(BitbucketClient.definition.kind).pipe(
    Effect.map((settings) => ({
      bitbucket: readSourceControlHostSettings(
        BitbucketClient.settings,
        settings.sourceControlHosts[BitbucketClient.definition.kind],
      ),
      secretProviders: settings.secretProviders,
    })),
    Effect.catch((error) =>
      // No cause: a settings decode error can quote a hand-edited token.
      Effect.logWarning("failed to read Bitbucket credentials from settings", {
        operation: error.operation,
      }).pipe(
        Effect.as({
          bitbucket: readSourceControlHostSettings(BitbucketClient.settings, {}),
          secretProviders: {},
        }),
      ),
    ),
    Effect.flatMap(({ bitbucket, secretProviders }) =>
      resolveCredential(bitbucket, secretProviders, config),
    ),
  );

  const withAuth = (request: HttpClientRequest.HttpClientRequest) =>
    currentCredential.pipe(
      Effect.map((credential) =>
        credential === null
          ? request
          : credential.kind === "access-token"
            ? request.pipe(HttpClientRequest.bearerToken(credential.accessToken))
            : request.pipe(HttpClientRequest.basicAuth(credential.email, credential.apiToken)),
      ),
    );

  /**
   * Every request waits for one of the shared slots, then honors the pause a 429 starts for the
   * whole host. Each queued lookup would otherwise spend its own 429 and keep the quota exhausted.
   * Background reads fail at once while paused; a write or an interactive read has a user waiting
   * on it, so it still goes out.
   */
  const throttled = Effect.fn("BitbucketApi.throttled")(
    function* <A, R>(method: string, effect: Effect.Effect<A, BitbucketApiError, R>) {
      const interactive = yield* SourceControlRateLimit.Interactive;
      const lease = yield* limits.check(
        rateLimitKey,
        interactive || method !== "GET" ? { allowPaused: true } : undefined,
      );
      return yield* effect.pipe(
        Effect.tap(() => limits.recordSuccess({ ...rateLimitKey, lease })),
        Effect.tapError((error) =>
          (error._tag === "BitbucketResponseError" ||
            error._tag === "BitbucketResponseBodyReadError") &&
          error.status === 429
            ? limits.recordRateLimit({ ...rateLimitKey, lease, retryAt: error.retryAt })
            : Effect.void,
        ),
      );
    },
    (effect) => slots.withPermit(effect),
  );

  const decodeResponse = <S extends Schema.Top>(
    operation: BitbucketApiOperation,
    schema: S,
    response: HttpClientResponse.HttpClientResponse,
  ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
    HttpClientResponse.matchStatus({
      "2xx": (success) =>
        HttpClientResponse.schemaBodyJson(schema)(success).pipe(
          Effect.mapError(
            (cause) =>
              new BitbucketResponseDecodeError({
                operation,
                status: success.status,
                cause,
              }),
          ),
        ),
      orElse: (failed) => responseError(operation, failed),
    })(response);

  const executeJson = <S extends Schema.Top>(
    operation: BitbucketApiOperation,
    request: HttpClientRequest.HttpClientRequest,
    schema: S,
  ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
    throttled(
      request.method,
      withAuth(request.pipe(HttpClientRequest.acceptJson)).pipe(
        Effect.flatMap((authed) =>
          httpClient
            .execute(authed)
            .pipe(Effect.mapError((cause) => new BitbucketRequestError({ operation, cause }))),
        ),
        Effect.flatMap((response) => decodeResponse(operation, schema, response)),
        Effect.timeout(BITBUCKET_API_REQUEST_TIMEOUT),
        Effect.catchTags({
          TimeoutError: (cause) => Effect.fail(new BitbucketRequestError({ operation, cause })),
        }),
      ),
    );

  const resolveRepository = Effect.fn("BitbucketApi.resolveRepository")(function* (input: {
    readonly cwd: string;
    readonly reference?: string;
    readonly context?: SourceControlProvider.SourceControlProviderContext;
    readonly repository?: string;
  }) {
    if (input.context?.provider.kind === "bitbucket" && !servesProvider(input.context.provider)) {
      // Falling back to another remote could act on a different repository.
      return yield* new BitbucketRepositoryRemoteNotFoundError({ cwd: input.cwd });
    }
    if (input.repository !== undefined) {
      return yield* requireRepositoryLocator(input.repository);
    }

    const url = input.reference ? URL.parse(input.reference) : null;
    const link = url ? definition.parseChangeRequestUrl(url) : null;
    if (link) return yield* requireRepositoryLocator(link.repository);

    const fromContext =
      input.context?.provider.kind === "bitbucket"
        ? parseBitbucketRemoteUrl(input.context.remoteUrl)
        : null;
    if (fromContext) return fromContext;

    const listRemotes = yield* git.remotes(input.cwd).pipe(
      Effect.mapError(
        (cause) =>
          new BitbucketRepositoryVcsResolveError({
            cwd: input.cwd,
            cause,
          }),
      ),
    );
    const remotes = yield* listRemotes.pipe(
      Effect.mapError(
        (cause) =>
          new BitbucketRepositoryRemotesListError({
            cwd: input.cwd,
            cause,
          }),
      ),
    );

    for (const remote of remotes.remotes) {
      if (!servesProvider(recognizeRemoteWith(definition, remote.url))) continue;
      const parsed = parseBitbucketRemoteUrl(remote.url);
      if (parsed) return parsed;
    }

    return yield* new BitbucketRepositoryRemoteNotFoundError({
      cwd: input.cwd,
    });
  });

  const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>
    executeJson(
      "getRepository",
      HttpClientRequest.get(
        apiUrl(
          `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
        ),
      ),
      RawBitbucketRepositorySchema,
    );

  const getRepository = (input: {
    readonly cwd: string;
    readonly context?: SourceControlProvider.SourceControlProviderContext;
    readonly repository?: string;
  }) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));

  const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>
    executeJson(
      "getBranchingModel",
      HttpClientRequest.get(
        apiUrl(
          `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,
        ),
      ),
      RawBitbucketBranchingModelSchema,
    );

  const getRawPullRequestFromRepository = (
    repository: BitbucketRepositoryLocator,
    reference: string,
  ) =>
    executeJson(
      "getPullRequest",
      HttpClientRequest.get(
        apiUrl(
          `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests/${encodeURIComponent(normalizeChangeRequestId(reference))}`,
        ),
      ),
      BitbucketPullRequestSchema,
    );

  const getRawPullRequest = (input: {
    readonly cwd: string;
    readonly context?: SourceControlProvider.SourceControlProviderContext;
    readonly reference: string;
  }) =>
    resolveRepository(input).pipe(
      Effect.flatMap((repository) => getRawPullRequestFromRepository(repository, input.reference)),
    );

  const readConfigValueNullable = (cwd: string, key: string) =>
    git.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));

  const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
    readonly cwd: string;
    readonly context?: SourceControlProvider.SourceControlProviderContext;
    readonly destinationRepository: BitbucketRepositoryLocator;
    readonly sourceRepositoryName: string;
    readonly isCrossRepository: boolean;
  }) {
    if (!input.isCrossRepository) {
      const context = input.context?.provider.kind === "bitbucket" ? input.context : undefined;
      const remoteName =
        context?.remoteName ??
        (yield* git.resolvePrimaryRemoteName(input.cwd).pipe(Effect.orElseSucceed(() => null)));
      if (remoteName) {
        const remoteUrl =
          context?.remoteUrl ??
          (yield* readConfigValueNullable(input.cwd, `remote.${remoteName}.url`));
        const repository =
          remoteUrl && (context || recognizeRemoteWith(definition, remoteUrl))
            ? parseBitbucketRemoteUrl(remoteUrl)
            : null;
        if (
          repository &&
          `${repository.workspace}/${repository.repoSlug}`.toLowerCase() ===
            input.sourceRepositoryName.toLowerCase()
        ) {
          return remoteName;
        }
      }
    }

    const cloneUrls = yield* getRepository({
      cwd: input.cwd,
      repository: input.sourceRepositoryName,
      ...(input.context ? { context: input.context } : {}),
    }).pipe(Effect.map(normalizeRepositoryCloneUrls));
    const originRemoteUrl = yield* readConfigValueNullable(input.cwd, "remote.origin.url");
    return yield* git.ensureRemote({
      cwd: input.cwd,
      preferredName: input.isCrossRepository
        ? repositoryOwnerName(input.sourceRepositoryName)
        : input.destinationRepository.workspace,
      url: selectCloneUrl({ cloneUrls, originRemoteUrl }),
    });
  });

  const apiOrigin = originOf(config.baseUrl);

  const trustedUrl = (value: string): string | null => {
    if (!/^https?:\/\//u.test(value)) return apiUrl(value);
    const origin = originOf(value);
    return origin !== null && origin === apiOrigin ? value : null;
  };

  /** Redirects forward auth headers; restrict them to the configured Bitbucket. */
  const send = (input: {
    readonly method: "GET" | "POST" | "PUT" | "DELETE";
    readonly url: string;
    readonly body?: string;
    readonly redirects: number;
  }): Effect.Effect<HttpClientResponse.HttpClientResponse, BitbucketApiError> => {
    const url = trustedUrl(input.url);
    if (url === null) {
      return Effect.fail(
        new BitbucketUntrustedUrlError({ host: originOf(input.url) ?? "an unreadable url" }),
      );
    }
    const base =
      input.method === "GET"
        ? HttpClientRequest.get(url)
        : input.method === "POST"
          ? HttpClientRequest.post(url)
          : input.method === "DELETE"
            ? HttpClientRequest.make("DELETE")(url)
            : HttpClientRequest.put(url);
    // Diff endpoints return patches, not JSON.
    const withBody =
      input.body === undefined
        ? base
        : base.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
    return withAuth(withBody).pipe(
      Effect.flatMap((request) =>
        httpClient
          .execute(request)
          .pipe(
            Effect.mapError(
              (cause): BitbucketApiError =>
                new BitbucketRequestError({ operation: "request", cause }),
            ),
          ),
      ),
      Effect.flatMap((response) => {
        const location = response.headers.location;
        if (
          response.status >= 300 &&
          response.status < 400 &&
          location !== undefined &&
          input.redirects < MAX_REDIRECTS
        ) {
          return send({
            ...input,
            url: new URL(location, url).toString(),
            redirects: input.redirects + 1,
          });
        }
        return Effect.succeed(response);
      }),
    );
  };

  const request: BitbucketApi["Service"]["request"] = (input) =>
    throttled(
      input.method,
      send({ ...input, redirects: 0 }).pipe(
        Effect.flatMap((response) =>
          HttpClientResponse.matchStatus({
            // Read through the body stream rather than `text`, so an oversized diff is stopped as
            // it arrives instead of being materialized whole and then cut.
            "2xx": (success) =>
              collectUint8StreamText({
                stream: success.stream,
                maxBytes: input.maxBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
              }).pipe(
                Effect.mapError(
                  (cause) =>
                    new BitbucketResponseBodyReadError({
                      operation: "request",
                      status: success.status,
                      cause,
                    }),
                ),
                Effect.map((collected) => ({
                  body: collected.text,
                  truncated: collected.truncated,
                })),
              ),
            orElse: (failed) => responseError("request", failed),
          })(response),
        ),
        // This also caps redirect hops: no request can finish headers then stall its body forever.
        Effect.timeout(BITBUCKET_API_REQUEST_TIMEOUT),
        Effect.catchTags({
          TimeoutError: (cause) =>
            Effect.fail(new BitbucketRequestError({ operation: "request", cause })),
        }),
      ),
    );

  return BitbucketApi.of({
    request,
    // Bitbucket answers anonymous /user with 401, so without a credential there is nothing to ask.
    probeAuth: currentCredential.pipe(
      Effect.flatMap((credential) =>
        credential === null
          ? Effect.succeed(authFromCredential(null))
          : executeJson(
              "probeAuth",
              HttpClientRequest.get(apiUrl("/user")),
              BitbucketUserSchema,
            ).pipe(
              Effect.map((user) => ({
                status: "authenticated" as const,
                account: nonEmpty(user.username ?? user.display_name ?? user.account_id),
                host: Option.some("bitbucket.org"),
                detail: Option.none<string>(),
              })),
              Effect.catch(() => currentCredential.pipe(Effect.map(authFromCredential))),
            ),
      ),
      Effect.catchTags({
        SettingsSecretUnresolvedError: (error) =>
          Effect.succeed<SourceControlProviderAuth>({
            status: "unauthenticated",
            account: Option.none(),
            host: Option.some("bitbucket.org"),
            detail: Option.some(error.message),
          }),
      }),
    ),
    listPullRequests: Effect.fn("BitbucketApi.listPullRequests")(function (input) {
      return resolveRepository(input).pipe(
        Effect.flatMap((repository) => {
          const states = toBitbucketStates(input.state);
          const query: Record<string, string | ReadonlyArray<string>> = {
            pagelen: String(Math.max(1, Math.min(input.limit ?? 20, 50))),
            sort: "-updated_on",
            q: bitbucketQueryString([
              `source.branch.name = "${SourceControlProvider.sourceBranch(input).replaceAll('"', '\\"')}"`,
              bitbucketStateFilter(states),
            ]),
            state: states,
          };

          return executeJson(
            "listPullRequests",
            HttpClientRequest.get(
              apiUrl(
                `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
              ),
              { urlParams: query },
            ),
            BitbucketPullRequestListSchema,
          );
        }),
        Effect.map((list) => list.values.map(normalizeBitbucketPullRequestRecord)),
      );
    }),
    getPullRequest: Effect.fn("BitbucketApi.getPullRequest")(function (input) {
      return getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord));
    }),
    getRepositoryCloneUrls: Effect.fn("BitbucketApi.getRepositoryCloneUrls")(function (input) {
      return getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls));
    }),
    createRepository: Effect.fn("BitbucketApi.createRepository")(function (input) {
      return requireRepositoryLocator(input.repository).pipe(
        Effect.flatMap((repository) =>
          executeJson(
            "createRepository",
            HttpClientRequest.post(
              apiUrl(
                `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
              ),
            ).pipe(
              HttpClientRequest.bodyJsonUnsafe({
                scm: "git",
                is_private: input.visibility === "private",
              }),
            ),
            RawBitbucketRepositorySchema,
          ),
        ),
        Effect.map(normalizeRepositoryCloneUrls),
      );
    }),
    createPullRequest: Effect.fn("BitbucketApi.createPullRequest")(function* (input) {
      const repository = yield* resolveRepository(input);
      const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
        Effect.mapError(
          (cause) =>
            new BitbucketPullRequestBodyReadError({
              cwd: input.cwd,
              bodyFile: input.bodyFile,
              cause,
            }),
        ),
      );
      const sourceOwner = sourceWorkspace(input);
      const body = {
        title: input.title,
        description,
        source: {
          branch: {
            name: SourceControlProvider.sourceBranch(input),
          },
          ...(sourceOwner
            ? {
                repository: {
                  full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
                },
              }
            : {}),
        },
        destination: {
          branch: {
            name: input.target?.refName ?? input.baseBranch,
          },
        },
      };

      yield* executeJson(
        "createPullRequest",
        HttpClientRequest.post(
          apiUrl(
            `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
          ),
        ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
        BitbucketPullRequestSchema,
      );
    }),
    getDefaultBranch: Effect.fn("BitbucketApi.getDefaultBranch")(function (input) {
      return resolveRepository(input).pipe(
        Effect.flatMap((locator) =>
          Effect.all(
            {
              repository: getRepositoryFromLocator(locator),
              branchingModel: getBranchingModelFromLocator(locator).pipe(
                Effect.orElseSucceed(
                  (): typeof RawBitbucketBranchingModelSchema.Type | null => null,
                ),
              ),
            },
            { concurrency: "unbounded" },
          ),
        ),
        Effect.map(defaultChangeRequestTargetBranch),
      );
    }),
    checkoutPullRequest: Effect.fn("BitbucketApi.checkoutPullRequest")(
      function* (input) {
        const destinationRepository = yield* resolveRepository(input);
        const pullRequest = yield* getRawPullRequestFromRepository(
          destinationRepository,
          input.reference,
        );
        const destinationRepositoryName =
          repositoryNameWithOwner(pullRequest.destination.repository) ??
          `${destinationRepository.workspace}/${destinationRepository.repoSlug}`;
        const sourceRepositoryName =
          repositoryNameWithOwner(pullRequest.source.repository) ?? destinationRepositoryName;
        const isCrossRepository = sourceRepositoryName !== destinationRepositoryName;
        const remoteName = yield* resolveCheckoutRemote({
          cwd: input.cwd,
          destinationRepository,
          sourceRepositoryName,
          isCrossRepository,
          ...(input.context ? { context: input.context } : {}),
        });
        const remoteBranch = pullRequest.source.branch.name;
        const localBranch = checkoutBranchName({
          pullRequestId: pullRequest.id,
          headBranch: remoteBranch,
          isCrossRepository,
        });
        const localBranchNames = yield* git.listLocalBranchNames(input.cwd);
        const localBranchExists = localBranchNames.includes(localBranch);

        if (input.force === true || !localBranchExists) {
          yield* git.fetchRemoteBranch({
            cwd: input.cwd,
            remoteName,
            remoteBranch,
            localBranch,
          });
        } else {
          yield* git.fetchRemoteTrackingBranch({
            cwd: input.cwd,
            remoteName,
            remoteBranch,
          });
        }

        yield* git.setBranchUpstream({
          cwd: input.cwd,
          branch: localBranch,
          remoteName,
          remoteBranch,
        });
        yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
      },
      (effect, input) =>
        effect.pipe(
          Effect.mapError((cause) =>
            isBitbucketApiError(cause)
              ? cause
              : new BitbucketCheckoutError({
                  cwd: input.cwd,
                  reference: input.reference,
                  cause,
                }),
          ),
        ),
    ),
  });
});

export const layer = Layer.effect(BitbucketApi, make);