From d4a57d0a41931e645f1c21d32f5d5b35fb79672e Mon Sep 17 00:00:00 2001 From: John Smith Date: Mon, 16 Nov 2026 12:04:11 +0000 Subject: [PATCH 1/2] fix(pr): report a queued merge instead of printing "" Bitbucket answers POST pullrequests/{id}/merge with 202 when it queues the merge, and names the task only in the Location header. PostAsync dropped headers, so bbx 1.5.0 printed the empty body as "" and exited 0. On 16 Nov 2026 that hid three queued merges: two were dropped and one landed 40 minutes later, with no task ID to follow any of them. pr merge now keeps the Location header, polls task-status (default 120s, --timeout) and prints the merged pull request on success. A merge still pending at the timeout prints "status": "queued" with the task ID, the task-status URL and the follow-up command, and exits 75 (EX_TEMPFAIL) so scripts can tell it from success and from failure. --no-wait returns the queued record at once. merge-status gains --wait/--timeout and accepts either the task ID or the URL that merge prints. deployments changes, the only other 202 write, now says "Queued" rather than "Updated". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014Mjr3Y5biNhSM8Bmg4xfaw --- AGENTS.md | 12 + CHANGELOG.md | 26 ++ README.md | 4 +- docs/api-coverage.md | 13 +- docs/llm-guide.md | 37 ++- src/Bbx/Api/BitbucketClient.cs | 31 +++ src/Bbx/Bbx.csproj | 2 +- src/Bbx/BbxExitException.cs | 11 + src/Bbx/Commands/CommandRunner.cs | 17 +- src/Bbx/Commands/PrCommand.cs | 42 ++- src/Bbx/Features/Common/CommandOutcome.cs | 18 ++ .../ChangeDeploymentEnvironmentHandler.cs | 4 +- .../MergePullRequestHandler.cs | 28 +- .../MergePullRequestRequest.cs | 9 +- .../PullRequestMergeStatus/MergeTask.cs | 121 +++++++++ .../PullRequestMergeStatusHandler.cs | 19 +- .../PullRequestMergeStatusRequest.cs | 11 +- src/Bbx/Program.cs | 5 + .../Features/PullRequests/AsyncMergeTests.cs | 239 ++++++++++++++++++ 19 files changed, 623 insertions(+), 26 deletions(-) create mode 100644 src/Bbx/BbxExitException.cs create mode 100644 src/Bbx/Features/Common/CommandOutcome.cs create mode 100644 src/Bbx/Features/PullRequests/PullRequestMergeStatus/MergeTask.cs create mode 100644 tests/Bbx.Tests/Features/PullRequests/AsyncMergeTests.cs diff --git a/AGENTS.md b/AGENTS.md index 71c39df..519c2de 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -327,6 +327,18 @@ rules below are; it is still the right place to start. existed in either repository to test against. Verified on 2026-09-12 against `crm.promosys` and `velocity.foremost-print.com`. +36. **A merge can answer 202, and the task is named only in `Location`.** + `POST pullrequests/{id}/merge` queues the merge when Bitbucket is slow and + answers 202 with an empty body. `PostAsync` drops headers, so 1.5.0 printed + `""`, exited 0 and lost the task ID (16 Nov 2026; two queued merges were then + dropped without a word, and a third landed 40 minutes later while `pr view` + still said OPEN). `MergePullRequestHandler` uses `PostForResponseAsync` and + polls `merge/task-status/{id}` through `MergeTask`. A merge still pending at + the timeout exits 75 (EX_TEMPFAIL) with the task in its JSON; a handler sets + a non-zero exit while still printing by returning a `CommandOutcome`. Never + test this by merging a real pull request: the 202 path is covered with + faked responses in `AsyncMergeTests`. + ## Live testing If you test against real Bitbucket: diff --git a/CHANGELOG.md b/CHANGELOG.md index 095393d..1918304 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,32 @@ so commit history is the source of truth for the fine grain. Versioning follows [Semantic Versioning](https://semver.org/): `MAJOR.MINOR.PATCH`. +## [1.6.0] + +### Fixed + +- `pr merge` printed `""` and exited 0 when Bitbucket queued the merge (HTTP + 202), so the pull request stayed open and the task ID appeared nowhere. Seen + during the Bitbucket slowdown of 16 Nov 2026, when two queued merges were + dropped without a word. The client now keeps the 202's `Location` header, + where Bitbucket names the task. + +### Added + +- `pr merge` waits for a queued merge by polling its task status, then prints + the merged pull request just as a direct merge does. If the merge is still + pending after `--timeout` seconds (default 120) it prints + `"status": "queued"` with `task_id`, `task_status_url` and the follow-up + command, and exits **75**. A failed task exits 1. `--no-wait` prints the + queued record at once and exits 0. +- `pr merge-status` takes `--wait` and `--timeout`, and `--task-id` now + accepts the `task_status_url` as well as the bare ID. + +### Changed + +- `pipeline deployments changes` says "Queued change" rather than "Updated", + because Bitbucket answers 202 and applies the change later. + ## [1.5.0] ### Changed diff --git a/README.md b/README.md index b140bf7..694e2bc 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Bitbucket has no first-party CLI. `bbx` fills that gap the way `gh` does for GitHub: - **JSON on stdout, diagnostics on stderr.** Pipe straight into `jq` without filtering noise. -- **Exit codes that mean something.** `0` on success, `1` on any failure, so `set -e` and `if !` work. +- **Exit codes that mean something.** `0` on success, `1` on any failure, so `set -e` and `if !` work. `75` means a queued merge has not finished yet. - **One credential.** An Atlassian API token, stored `0600`, with scopes you choose. - **Wide coverage.** Repos, pull requests, branches, tags, commits, source files, downloads, pipelines, snippets, workspaces, projects and users. - **Errors you can act on.** A missing scope tells you which scope and where to re-issue the token. @@ -237,7 +237,7 @@ bbx pr statuses 42 -w myws -r myrepo bbx pr diffstat 42 -w myws -r myrepo # per-file line counts bbx pr conflicts 42 -w myws -r myrepo -bbx pr merge-status 42 --task-id -w myws -r myrepo +bbx pr merge-status 42 --task-id --wait -w myws -r myrepo # follow a queued merge bbx pr activity -w myws -r myrepo # no ID: the whole repository bbx pr comment 42 --body "LGTM" -w myws -r myrepo diff --git a/docs/api-coverage.md b/docs/api-coverage.md index 7176f2a..4208852 100644 --- a/docs/api-coverage.md +++ b/docs/api-coverage.md @@ -32,6 +32,17 @@ Nothing was added except two optional query parameters on `POST .../pipelines/` on-demand runs, `merge_defaults` and `target_branch_to_create`, both covered by `bbx pipeline trigger --yaml` (1.4.0). No other operation, body or response changed. +## Endpoints that answer 202 + +Three operations in the spec can answer 202 Accepted. Checked on 2026-11-16 after +`bbx pr merge` lost a queued merge's task ID: + +| Method | Path | What 202 means | What `bbx` does | +| --- | --- | --- | --- | +| `POST` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/merge` | Merge queued; the task-status URL is in the `Location` header | Before 1.6.0 it printed `""` and exited 0. Now it reads the task ID from `Location` (or `links.self.href`), polls task-status for up to `--timeout` seconds (default 120), and exits 75 with `"status": "queued"` and the task ID if the merge has not finished. `--no-wait` returns the task at once with exit 0 | +| `POST` | `/repositories/{workspace}/{repo_slug}/environments/{environment_uuid}/changes` | Change queued; empty body | `bbx pipeline deployments changes` now says "Queued change" rather than "Updated". There is no task to poll | +| `GET` | `/repositories/{workspace}/{repo_slug}/commit/{commit}/pullrequests` | Pull request links still being indexed; the page may be partial | Left as is. `bbx commit pullrequests` prints what came back | + ## Why things are skipped Four reasons account for every skip. @@ -136,7 +147,7 @@ Three things the spec gets wrong or leaves out: | `POST` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/comments/{comment_id}/resolve` | cover | `bbx pr comment-resolve` | | `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/conflicts` | cover | `bbx pr conflicts` | | `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/diffstat` | cover | `bbx pr diffstat` | -| `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/merge/task-status/{task_id}` | cover | `bbx pr merge-status` | +| `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/merge/task-status/{task_id}` | cover | `bbx pr merge-status`, and `bbx pr merge` polls it after a 202 (1.6.0) | | `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/tasks/{task_id}` | cover | `bbx pr tasks view` | | `DELETE` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pullrequest_id}/properties/{app_key}/{property_name}` | skip | Connect app property; app key unobtainable from a CLI | | `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pullrequest_id}/properties/{app_key}/{property_name}` | skip | Connect app property; app key unobtainable from a CLI | diff --git a/docs/llm-guide.md b/docs/llm-guide.md index d23990c..749dfd1 100644 --- a/docs/llm-guide.md +++ b/docs/llm-guide.md @@ -25,7 +25,10 @@ relevant table. - **exit codes:** `0` on success, `1` on any handled error (`BbxUserException` for user-facing errors like "not authenticated", `HttpRequestException` for network/API failures wrapped with - `"Error: "`). + `"Error: "`). `75` means "not finished yet, check again": only + `pr merge` and `pr merge-status --wait` use it, when Bitbucket has queued + a merge that is still pending at `--timeout`. The JSON on stdout still + carries the task ID. - **No interactive prompts by default for an agent.** Set `BBX_NO_INTERACTIVE=1` or redirect stdin to disable the first-run credential prompt and the `--yes`-less confirmation prompts. @@ -182,7 +185,7 @@ offered; use `remove`. | `view ` | `GET repositories/{ws}/{repo}/pullrequests/{id}` | | `create` | `POST repositories/{ws}/{repo}/pullrequests` — `--title`, `--source`, `--dest`, `--body`, `--close-source-branch`, `--reviewers ` | | `update ` | `PUT repositories/{ws}/{repo}/pullrequests/{id}` — `--title`, `--body`, `--dest`, `--reviewers ...`, `--close-source-branch`, `--no-close-source-branch`. Open pull requests only. | -| `merge ` | `POST .../merge` — `--strategy`, `--message`, `--close-source-branch`, `--yes`. Six strategies: `merge_commit`, `squash`, `fast_forward`, `squash_fast_forward`, `rebase_fast_forward`, `rebase_merge`. Left off, `bbx` reads the destination branch's `default_merge_strategy` (two extra GETs); named explicitly, it is sent straight through with no lookups. May answer 202 with a task ID instead of merging on the spot; read it with `merge-status` | +| `merge ` | `POST .../merge` — `--strategy`, `--message`, `--close-source-branch`, `--yes`. Six strategies: `merge_commit`, `squash`, `fast_forward`, `squash_fast_forward`, `rebase_fast_forward`, `rebase_merge`. Left off, `bbx` reads the destination branch's `default_merge_strategy` (two extra GETs); named explicitly, it is sent straight through with no lookups. Waits for a queued merge: see below. `--no-wait`, `--timeout ` (default 120) | | `approve ` / `unapprove ` | `POST/DELETE .../approve` | | `decline ` | `POST .../decline`. Takes no body, so there is no `--close-source-branch` here: the source branch stays until `bbx branch delete` removes it | | `comments ` / `comment ` | `GET/POST .../comments` — `--body` for `comment`. Each row carries `deleted`; a tombstone reads `deleted: true` with empty `content` | @@ -195,7 +198,7 @@ offered; use `remove`. | `commits ` | `GET .../commits` | | `diffstat ` | `GET .../pullrequests/{id}/diffstat` — per-file line counts, cheaper than the whole diff | | `conflicts ` | `GET .../pullrequests/{id}/conflicts` — answers 403 to an API token | -| `merge-status ` | `GET .../pullrequests/{id}/merge/task-status/{task-id}` — `--task-id` | +| `merge-status ` | `GET .../pullrequests/{id}/merge/task-status/{task-id}` — `--task-id` takes the `task_id` or the `task_status_url` that `merge` printed. `--wait` polls like `merge` does, with `--timeout`. Without `--wait` it prints Bitbucket's status (`PENDING` or `SUCCESS` with `merge_result`) and exits 0 | | `activity []` | `GET .../pullrequests/activity` with no ID, `.../pullrequests/{id}/activity` with one — `--limit` | | `comment-view ` | `GET .../comments/{comment-id}` — `--comment-id` | | `comment-update ` | `PUT .../comments/{comment-id}` — `--comment-id`, `--body` | @@ -203,6 +206,34 @@ offered; use `remove`. | `comment-resolve ` / `comment-unresolve ` | `POST/DELETE .../comments/{comment-id}/resolve` — `--comment-id` | | `tasks view ` | `GET .../tasks/{task-id}` — `--task-id` | +#### Queued merges (202) + +Bitbucket sometimes queues a merge instead of running it inline, most often when +it is slow. It answers 202 and names a task. `pr merge` then polls that task +every 3 seconds: + +| What happens | stdout | Exit | +| --- | --- | --- | +| Merged inline (200), or the queued task finishes | the merged pull request, as before | `0` | +| Still `PENDING` at `--timeout` | `{"status": "queued", "task_id": …, "task_status_url": …, "task_status": "PENDING", "waited_seconds": …, "next": "bbx pr merge-status …"}` | `75` | +| The task fails | the error, on stderr | `1` | +| `--no-wait` | the same `"status": "queued"` record, at once | `0` | + +A queued merge can still land after the timeout, or be dropped: during the +Bitbucket slowdown of 16 Nov 2026 two of three queued merges vanished and the +third landed 40 minutes later. So on exit 75, do not merge again. Follow the +task, which is the command the `next` field holds: + +```bash +bbx pr merge 42 -r myrepo --yes; rc=$? +if [ $rc -eq 75 ]; then + bbx pr merge-status 42 -r myrepo --task-id --wait --timeout 900 +fi +``` + +`pr view` can report `OPEN` for a while after a queued merge has landed. Trust +the task status over it. + `pr update` sends only the flags you pass. Anything you leave out keeps its current value, so you can retitle a pull request without touching its description. An empty `--body ""` clears the description. diff --git a/src/Bbx/Api/BitbucketClient.cs b/src/Bbx/Api/BitbucketClient.cs index 9e345d1..7032444 100644 --- a/src/Bbx/Api/BitbucketClient.cs +++ b/src/Bbx/Api/BitbucketClient.cs @@ -75,6 +75,31 @@ public async Task CopyToAsync(string endpoint, Stream destination, CancellationT public Task PutMultipartAsync(string endpoint, MultipartFormDataContent content, CancellationToken ct = default) => SendForJsonAsync(HttpMethod.Put, endpoint, content, ct); + /// + /// POST and keep the status and Location header, which + /// throws away. The merge endpoint answers 202 + /// when it queues the merge, and the only place it names the task is the + /// Location header; dropping it is how bbx pr merge printed a bare + /// "" and lost the task ID. + /// + public async Task PostForResponseAsync(string endpoint, object? body = null, CancellationToken ct = default) + { + using var response = await SendAsync(HttpMethod.Post, endpoint, JsonContent(body), ct); + await EnsureSuccessAsync(response); + var json = await response.Content.ReadAsStringAsync(ct); + var location = response.Headers.Location; + if (location is { IsAbsoluteUri: false } && response.RequestMessage?.RequestUri is { } requestUri) + location = new Uri(requestUri, location); + + JsonElement parsed = default; + if (!string.IsNullOrWhiteSpace(json)) + { + try { parsed = JsonSerializer.Deserialize(json, JsonOptions); } + catch (JsonException) { } + } + return new ApiResponse((int)response.StatusCode, location, parsed); + } + private static StringContent? JsonContent(object? body) => body is null ? null : new StringContent(JsonSerializer.Serialize(body, JsonOptions), Encoding.UTF8, "application/json"); @@ -279,6 +304,12 @@ public void Dispose() } } +/// +/// A response whose status and Location header matter as well as its body. +/// is the default element (ValueKind Undefined) when there was no JSON body. +/// +public sealed record ApiResponse(int Status, Uri? Location, JsonElement Body); + public class PaginatedResponse { public int Size { get; set; } diff --git a/src/Bbx/Bbx.csproj b/src/Bbx/Bbx.csproj index 27d1d3a..e1da597 100644 --- a/src/Bbx/Bbx.csproj +++ b/src/Bbx/Bbx.csproj @@ -24,7 +24,7 @@ - 1.5.0 + 1.6.0 solrevdev diff --git a/src/Bbx/BbxExitException.cs b/src/Bbx/BbxExitException.cs new file mode 100644 index 0000000..3bb0384 --- /dev/null +++ b/src/Bbx/BbxExitException.cs @@ -0,0 +1,11 @@ +namespace Bbx; + +/// +/// Ends the run with a specific exit code after the command has already printed +/// its JSON. Used when the output is useful but the job is not done, such as a +/// merge still queued when the wait ran out. +/// +public sealed class BbxExitException(int exitCode, string message) : Exception(message) +{ + public int ExitCode { get; } = exitCode; +} diff --git a/src/Bbx/Commands/CommandRunner.cs b/src/Bbx/Commands/CommandRunner.cs index 3cd71ee..fdb0afc 100644 --- a/src/Bbx/Commands/CommandRunner.cs +++ b/src/Bbx/Commands/CommandRunner.cs @@ -1,6 +1,7 @@ using System.Text.Json; using Bbx.Auth; using Bbx.Composition; +using Bbx.Features.Common; namespace Bbx.Commands; @@ -8,7 +9,21 @@ internal static class CommandRunner { public static Task RunJsonAsync(Func> handler) => RunAsync( requireAuth: true, - async () => Console.WriteLine(JsonSerializer.Serialize(NoBodyAsNull(await handler()), JsonOptions.Current))); + async () => + { + object? result = await handler(); + if (result is CommandOutcome outcome) + { + Console.WriteLine(JsonSerializer.Serialize(NoBodyAsNull(outcome.Output), JsonOptions.Current)); + // Print first, then fail: the JSON is what a caller needs to + // follow up (a merge task ID), even when the exit code says + // the job is not finished. + if (outcome.ExitCode != 0) + throw new BbxExitException(outcome.ExitCode, outcome.Message ?? ""); + return; + } + Console.WriteLine(JsonSerializer.Serialize(NoBodyAsNull(result), JsonOptions.Current)); + }); /// /// A write that answers 204 has no body, so the client deserializes it to diff --git a/src/Bbx/Commands/PrCommand.cs b/src/Bbx/Commands/PrCommand.cs index 76bfbf6..005f1ee 100644 --- a/src/Bbx/Commands/PrCommand.cs +++ b/src/Bbx/Commands/PrCommand.cs @@ -148,12 +148,28 @@ public static Command Create(IServiceProvider services) // Merging writes to the destination branch and cannot be undone from // here, so it confirms like the other destructive verbs. var mergeYesOption = new Option("--yes") { Description = "Skip confirmation prompt" }; + // Bitbucket answers 202 when it queues a merge instead of running it + // inline. Waiting is the default so a queued merge that then fails is + // reported, not lost. + var mergeNoWaitOption = new Option("--no-wait") + { + Description = "If Bitbucket queues the merge, print the task ID and return at once (exit 0) " + + "instead of waiting for it.", + }; + var mergeTimeoutOption = new Option("--timeout") + { + Description = "Seconds to wait for a queued merge before giving up with exit code 75. " + + "The merge may still land; follow it with `bbx pr merge-status`.", + DefaultValueFactory = _ => MergeTask.DefaultTimeoutSeconds, + }; mergeCommand.Arguments.Add(mergeIdArg); mergeCommand.Options.Add(strategyOption); mergeCommand.Options.Add(messageOption); mergeCommand.Options.Add(closeSourceMergeOption); mergeCommand.Options.Add(mergeYesOption); - mergeCommand.SetHandler(async (string? workspace, string? repo, int id, string? strategy, string? message, bool closeSource, bool yes) => + mergeCommand.Options.Add(mergeNoWaitOption); + mergeCommand.Options.Add(mergeTimeoutOption); + mergeCommand.SetHandler(async (string? workspace, string? repo, int id, string? strategy, string? message, bool closeSource, bool yes, bool noWait, int timeout) => { var using_ = string.IsNullOrEmpty(strategy) ? "the destination branch's default strategy" @@ -162,8 +178,8 @@ public static Command Create(IServiceProvider services) return; await CommandRunner.RunJsonAsync(() => services.GetRequiredService() - .HandleAsync(new MergePullRequestRequest(workspace, repo, id, strategy, message, closeSource), CommandBinding.CancellationToken)); - }, workspaceOption, repoOption, mergeIdArg, strategyOption, messageOption, closeSourceMergeOption, mergeYesOption); + .HandleAsync(new MergePullRequestRequest(workspace, repo, id, strategy, message, closeSource, !noWait, timeout), CommandBinding.CancellationToken)); + }, workspaceOption, repoOption, mergeIdArg, strategyOption, messageOption, closeSourceMergeOption, mergeYesOption, mergeNoWaitOption, mergeTimeoutOption); command.Subcommands.Add(mergeCommand); var approveCommand = new Command("approve", "Approve a pull request"); @@ -280,14 +296,26 @@ await CommandRunner.RunJsonAsync(() => "Report on a merge that was accepted asynchronously and returned a task ID"); var mergeStatusIdArg = new Argument("id") { Description = "Pull request ID" }; var mergeStatusTaskOption = new Option("--task-id") - { Description = "Merge task ID, as returned by an asynchronous merge", Required = true }; + { + Description = "Merge task ID, or the whole task_status_url, as printed by `bbx pr merge`", + Required = true, + }; + var mergeStatusWaitOption = new Option("--wait") + { Description = "Poll until the merge finishes; exit 75 if it is still queued at --timeout" }; + var mergeStatusTimeoutOption = new Option("--timeout") + { + Description = "Seconds to wait with --wait", + DefaultValueFactory = _ => MergeTask.DefaultTimeoutSeconds, + }; mergeStatusCommand.Arguments.Add(mergeStatusIdArg); mergeStatusCommand.Options.Add(mergeStatusTaskOption); - mergeStatusCommand.SetHandler((string? workspace, string? repo, int id, string taskId) => + mergeStatusCommand.Options.Add(mergeStatusWaitOption); + mergeStatusCommand.Options.Add(mergeStatusTimeoutOption); + mergeStatusCommand.SetHandler((string? workspace, string? repo, int id, string taskId, bool wait, int timeout) => CommandRunner.RunJsonAsync(() => services.GetRequiredService() - .HandleAsync(new PullRequestMergeStatusRequest(workspace, repo, id, taskId), CommandBinding.CancellationToken)), - workspaceOption, repoOption, mergeStatusIdArg, mergeStatusTaskOption); + .HandleAsync(new PullRequestMergeStatusRequest(workspace, repo, id, taskId, wait, timeout), CommandBinding.CancellationToken)), + workspaceOption, repoOption, mergeStatusIdArg, mergeStatusTaskOption, mergeStatusWaitOption, mergeStatusTimeoutOption); command.Subcommands.Add(mergeStatusCommand); var commentViewCommand = new Command("comment-view", "View a single pull request comment"); diff --git a/src/Bbx/Features/Common/CommandOutcome.cs b/src/Bbx/Features/Common/CommandOutcome.cs new file mode 100644 index 0000000..4c083d6 --- /dev/null +++ b/src/Bbx/Features/Common/CommandOutcome.cs @@ -0,0 +1,18 @@ +namespace Bbx.Features.Common; + +/// +/// A handler result that carries an exit code. CommandRunner prints +/// as JSON, then ends the run with +/// and writes to stderr when the code is not zero. +/// +public sealed record CommandOutcome(object? Output, int ExitCode = 0, string? Message = null); + +public static class ExitCodes +{ + /// + /// sysexits EX_TEMPFAIL: not failed, not finished, try again later. A merge + /// still queued when the wait runs out ends with this so a script can tell + /// it from a merge that failed (1). + /// + public const int Pending = 75; +} diff --git a/src/Bbx/Features/Pipelines/ChangeDeploymentEnvironment/ChangeDeploymentEnvironmentHandler.cs b/src/Bbx/Features/Pipelines/ChangeDeploymentEnvironment/ChangeDeploymentEnvironmentHandler.cs index ce2b8a4..f8068f0 100644 --- a/src/Bbx/Features/Pipelines/ChangeDeploymentEnvironment/ChangeDeploymentEnvironmentHandler.cs +++ b/src/Bbx/Features/Pipelines/ChangeDeploymentEnvironment/ChangeDeploymentEnvironmentHandler.cs @@ -31,6 +31,8 @@ public async Task HandleAsync(ChangeDeploymentEnvironmentRequest request await client.PostAsync( $"repositories/{ws}/{repo}/environments/{Uri.EscapeDataString(request.Environment)}/changes/", new { change }, ct); - return $"✓ Updated deployment environment {request.Environment}"; + // Say queued, not updated: a read straight afterwards can still show + // the old values. + return $"✓ Queued change to deployment environment {request.Environment} (Bitbucket applies it in the background)"; } } diff --git a/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestHandler.cs b/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestHandler.cs index aa9cfda..030170c 100644 --- a/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestHandler.cs +++ b/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestHandler.cs @@ -1,12 +1,13 @@ using System.Text.Json; using Bbx.Auth; using Bbx.Features.Common; +using Bbx.Features.PullRequests.PullRequestMergeStatus; namespace Bbx.Features.PullRequests.MergePullRequest; public sealed class MergePullRequestHandler(BitbucketClient client, CredentialManager credentials) { - public async Task HandleAsync(MergePullRequestRequest request, CancellationToken ct) + public async Task HandleAsync(MergePullRequestRequest request, CancellationToken ct) { var (ws, repo) = Resolve.WorkspaceAndRepo(credentials, request.Workspace, request.Repository, "Error: Workspace and repository required."); @@ -21,8 +22,31 @@ public async Task HandleAsync(MergePullRequestRequest request, Canc }; if (!string.IsNullOrEmpty(request.Message)) body["message"] = request.Message; - return await client.PostAsync( + var response = await client.PostForResponseAsync( $"/repositories/{ws}/{repo}/pullrequests/{request.Id}/merge", body, ct); + + // 200 carries the merged pull request. 202 means Bitbucket queued the + // merge and named the task only in the Location header; this used to + // print the empty body as "" and exit 0, leaving the PR open and the + // task ID nowhere (16 Nov 2026, during a Bitbucket slowdown). + if (response.Status != 202) return new CommandOutcome(response.Body); + + var statusUrl = MergeTask.StatusUrl(response); + var taskId = statusUrl is null ? null : MergeTask.IdFrom(statusUrl); + if (taskId is null) + { + return new CommandOutcome( + MergeTask.Queued(ws, repo, request.Id, null, null, null, null), + ExitCodes.Pending, + $"Bitbucket queued the merge of PR #{request.Id} but sent no task link. " + + "Check the pull request's state before merging again."); + } + + if (!request.Wait) + return new CommandOutcome(MergeTask.Queued(ws, repo, request.Id, taskId, statusUrl, null, null)); + + return await MergeTask.WaitAsync(client, ws, repo, request.Id, taskId, statusUrl, + request.TimeoutSeconds, request.PollInterval ?? MergeTask.DefaultInterval, ct); } /// diff --git a/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestRequest.cs b/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestRequest.cs index b2f8114..0db79bd 100644 --- a/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestRequest.cs +++ b/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestRequest.cs @@ -1,9 +1,16 @@ +using Bbx.Features.PullRequests.PullRequestMergeStatus; + namespace Bbx.Features.PullRequests.MergePullRequest; +/// Poll a merge Bitbucket queued (202) until it finishes or the timeout passes. +/// Null for the default. Tests pass zero. public sealed record MergePullRequestRequest( string? Workspace, string? Repository, int Id, string? Strategy, string? Message, - bool CloseSourceBranch); + bool CloseSourceBranch, + bool Wait = true, + int TimeoutSeconds = MergeTask.DefaultTimeoutSeconds, + TimeSpan? PollInterval = null); diff --git a/src/Bbx/Features/PullRequests/PullRequestMergeStatus/MergeTask.cs b/src/Bbx/Features/PullRequests/PullRequestMergeStatus/MergeTask.cs new file mode 100644 index 0000000..132ec47 --- /dev/null +++ b/src/Bbx/Features/PullRequests/PullRequestMergeStatus/MergeTask.cs @@ -0,0 +1,121 @@ +using System.Diagnostics; +using System.Text.Json; +using Bbx.Api; +using Bbx.Features.Common; + +namespace Bbx.Features.PullRequests.PullRequestMergeStatus; + +/// +/// A merge Bitbucket accepted with 202 and runs in the background, and the +/// polling of its task-status endpoint that both pr merge and +/// pr merge-status share. +/// +public static class MergeTask +{ + public const int DefaultTimeoutSeconds = 120; + public static readonly TimeSpan DefaultInterval = TimeSpan.FromSeconds(3); + + private const string Marker = "/task-status/"; + + /// + /// Accept either the bare task ID or the whole task-status URL, so a caller + /// can paste either value that pr merge printed. + /// + public static string IdFrom(string idOrUrl) + { + var value = idOrUrl.Trim(); + var at = value.IndexOf(Marker, StringComparison.OrdinalIgnoreCase); + if (at < 0) return value; + var id = value[(at + Marker.Length)..]; + var end = id.IndexOfAny(['/', '?', '#']); + return Uri.UnescapeDataString(end < 0 ? id : id[..end]); + } + + /// + /// The task-status URL out of a 202: the Location header, which is where the + /// spec puts it, or links.self.href in the body if Bitbucket sent one. + /// + public static string? StatusUrl(ApiResponse response) + { + if (response.Location is { } location) return location.AbsoluteUri; + return response.Body.TryGetObject("links", out var links) + && links.TryGetObject("self", out var self) + ? self.GetStringOrNull("href") + : null; + } + + public static string Endpoint(string ws, string repo, int id, string taskId) => + $"repositories/{ws}/{repo}/pullrequests/{id}/merge/task-status/{Uri.EscapeDataString(taskId)}"; + + /// + /// What a queued merge prints: everything needed to follow it up, and a + /// status nobody can mistake for a finished merge. + /// + public static object Queued(string ws, string repo, int id, string? taskId, string? statusUrl, + string? taskStatus, int? waitedSeconds) => new + { + status = "queued", + pull_request = id, + task_id = taskId, + task_status_url = statusUrl, + task_status = taskStatus, + waited_seconds = waitedSeconds, + next = taskId is null + ? $"bbx pr view {id} -w {ws} -r {repo}" + : $"bbx pr merge-status {id} --task-id {taskId} -w {ws} -r {repo} --wait", + }; + + /// + /// Poll until the task leaves PENDING or the timeout passes. Polls at least + /// once, so a timeout of 0 is a single check. + /// + /// + /// SUCCESS yields the merged pull request, the same body a synchronous merge + /// answers with, so a caller cannot tell the two paths apart. A timeout + /// prints the queued record and exits , + /// because during the 16 Nov 2026 incident queued merges were dropped + /// silently and exit 0 would have hidden that. A failed task answers 400 with + /// an error body, which the client turns into an exception and exit 1. + /// + public static async Task WaitAsync(BitbucketClient client, string ws, string repo, int id, + string taskId, string? statusUrl, int timeoutSeconds, TimeSpan interval, CancellationToken ct) + { + var clock = Stopwatch.StartNew(); + var timeout = TimeSpan.FromSeconds(Math.Max(0, timeoutSeconds)); + while (true) + { + var status = await client.GetAsync(Endpoint(ws, repo, id, taskId), ct); + var state = status.GetStringOrNull("task_status"); + + if (string.Equals(state, "SUCCESS", StringComparison.OrdinalIgnoreCase)) + { + return new CommandOutcome( + status.TryGetObject("merge_result", out var merged) ? merged : status); + } + + if (!string.Equals(state, "PENDING", StringComparison.OrdinalIgnoreCase)) + { + // A 200 that is neither PENDING nor SUCCESS: the spec shows a + // failed task as an error object, so report whatever came back. + var message = status.TryGetObject("error", out var error) + ? error.GetStringOrNull("message") + : null; + return new CommandOutcome(status, 1, + $"Error: merge task {taskId} for PR #{id} did not succeed" + + (message is null ? $" (task_status: {state ?? "missing"})." : $": {message}")); + } + + if (clock.Elapsed + interval > timeout) + { + var waited = (int)Math.Round(clock.Elapsed.TotalSeconds); + return new CommandOutcome( + Queued(ws, repo, id, taskId, statusUrl, state, waited), + ExitCodes.Pending, + $"PR #{id} merge is still queued after {waited}s (task {taskId}). " + + "It may still land. Check again with `bbx pr merge-status`."); + } + + await Task.Delay(interval, ct); + } + } +} diff --git a/src/Bbx/Features/PullRequests/PullRequestMergeStatus/PullRequestMergeStatusHandler.cs b/src/Bbx/Features/PullRequests/PullRequestMergeStatus/PullRequestMergeStatusHandler.cs index 6fcf6ea..413fddf 100644 --- a/src/Bbx/Features/PullRequests/PullRequestMergeStatus/PullRequestMergeStatusHandler.cs +++ b/src/Bbx/Features/PullRequests/PullRequestMergeStatus/PullRequestMergeStatusHandler.cs @@ -7,14 +7,21 @@ namespace Bbx.Features.PullRequests.PullRequestMergeStatus; public sealed class PullRequestMergeStatusHandler(BitbucketClient client, CredentialManager credentials) { - public async Task HandleAsync(PullRequestMergeStatusRequest request, CancellationToken ct) + public async Task HandleAsync(PullRequestMergeStatusRequest request, CancellationToken ct) { var (ws, repo) = Resolve.WorkspaceAndRepo(credentials, request.Workspace, request.Repository, "Error: Workspace and repository required."); - // A merge asked for asynchronously answers 202 with a task ID. This - // reports whether that task has finished. - return await client.GetAsync( - $"repositories/{ws}/{repo}/pullrequests/{request.Id}/merge/task-status/{Uri.EscapeDataString(request.TaskId)}", - ct); + var taskId = MergeTask.IdFrom(request.TaskId); + + if (request.Wait) + { + return await MergeTask.WaitAsync(client, ws, repo, request.Id, taskId, null, + request.TimeoutSeconds, request.PollInterval ?? MergeTask.DefaultInterval, ct); + } + + // Without --wait this reports the task as Bitbucket has it, PENDING + // included, and exits 0: the caller asked for a status, not a result. + return new CommandOutcome( + await client.GetAsync(MergeTask.Endpoint(ws, repo, request.Id, taskId), ct)); } } diff --git a/src/Bbx/Features/PullRequests/PullRequestMergeStatus/PullRequestMergeStatusRequest.cs b/src/Bbx/Features/PullRequests/PullRequestMergeStatus/PullRequestMergeStatusRequest.cs index 3d48af2..88a422e 100644 --- a/src/Bbx/Features/PullRequests/PullRequestMergeStatus/PullRequestMergeStatusRequest.cs +++ b/src/Bbx/Features/PullRequests/PullRequestMergeStatus/PullRequestMergeStatusRequest.cs @@ -1,3 +1,12 @@ namespace Bbx.Features.PullRequests.PullRequestMergeStatus; -public sealed record PullRequestMergeStatusRequest(string? Workspace, string? Repository, int Id, string TaskId); +/// The task ID, or the whole task-status URL. +/// Null for the default. Tests pass zero. +public sealed record PullRequestMergeStatusRequest( + string? Workspace, + string? Repository, + int Id, + string TaskId, + bool Wait = false, + int TimeoutSeconds = MergeTask.DefaultTimeoutSeconds, + TimeSpan? PollInterval = null); diff --git a/src/Bbx/Program.cs b/src/Bbx/Program.cs index 4091da3..e9acd7f 100644 --- a/src/Bbx/Program.cs +++ b/src/Bbx/Program.cs @@ -78,6 +78,11 @@ internal static async Task RunAsync( EnableDefaultExceptionHandler = false, }, cancellationToken); } + catch (BbxExitException ex) + { + if (!string.IsNullOrEmpty(ex.Message)) Console.Error.WriteLine(ex.Message); + return ex.ExitCode; + } catch (BbxUserException ex) { Console.Error.WriteLine(ex.Message); diff --git a/tests/Bbx.Tests/Features/PullRequests/AsyncMergeTests.cs b/tests/Bbx.Tests/Features/PullRequests/AsyncMergeTests.cs new file mode 100644 index 0000000..0f39c58 --- /dev/null +++ b/tests/Bbx.Tests/Features/PullRequests/AsyncMergeTests.cs @@ -0,0 +1,239 @@ +using System.Net; +using System.Text.Json; +using AwesomeAssertions; +using Bbx.Api; +using Bbx.Auth; +using Bbx.Features.Common; +using Bbx.Features.PullRequests.MergePullRequest; +using Bbx.Features.PullRequests.PullRequestMergeStatus; +using Bbx.Tests.TestKit; +using Microsoft.Extensions.DependencyInjection; + +namespace Bbx.Tests.Features.PullRequests; + +// Bitbucket answers a merge with 202 and a task-status link in the Location +// header when it queues the merge. bbx 1.5.0 printed "" and exited 0, so the +// task ID was lost and two queued merges were dropped without anyone knowing +// (16 Nov 2026). Every response here is faked; nothing is merged. +[Collection("Console")] +public sealed class AsyncMergeTests : IDisposable +{ + private const string TaskUrl = + "https://api.bitbucket.org/2.0/repositories/ws/repo/pullrequests/21/merge/task-status/task-abc"; + + private const string Merged = """{"id":21,"state":"MERGED","merge_commit":{"hash":"7339c57"}}"""; + + private readonly IServiceProvider? _originalServices = Program.Services; + + [Fact] + public async Task A_queued_merge_returns_the_task_at_once_with_no_wait() + { + var http = new FakeHttpMessageHandler(); + EnqueueAccepted(http); + + var outcome = await Merge(http, wait: false); + + outcome.ExitCode.Should().Be(0); + var json = Json(outcome.Output); + json.GetProperty("status").GetString().Should().Be("queued"); + json.GetProperty("task_id").GetString().Should().Be("task-abc"); + json.GetProperty("task_status_url").GetString().Should().Be(TaskUrl); + json.GetProperty("next").GetString().Should() + .Be("bbx pr merge-status 21 --task-id task-abc -w ws -r repo --wait"); + http.Calls.Should().HaveCount(1); + } + + [Fact] + public async Task A_queued_merge_is_polled_until_it_succeeds_and_returns_the_merged_pull_request() + { + var http = new FakeHttpMessageHandler(); + EnqueueAccepted(http); + http.Enqueue(HttpStatusCode.OK, """{"task_status":"PENDING"}"""); + http.Enqueue(HttpStatusCode.OK, $$"""{"task_status":"SUCCESS","merge_result":{{Merged}}}"""); + + var outcome = await Merge(http, wait: true, timeoutSeconds: 60); + + outcome.ExitCode.Should().Be(0); + Json(outcome.Output).GetProperty("state").GetString().Should().Be("MERGED"); + http.Calls.Skip(1).Should().AllSatisfy(c => + c.RequestUri!.AbsoluteUri.Should().Be(TaskUrl)); + } + + [Fact] + public async Task A_merge_still_queued_at_the_timeout_prints_the_task_and_exits_pending() + { + var http = new FakeHttpMessageHandler(); + EnqueueAccepted(http); + http.Enqueue(HttpStatusCode.OK, """{"task_status":"PENDING"}"""); + + var outcome = await Merge(http, wait: true, timeoutSeconds: 0); + + outcome.ExitCode.Should().Be(ExitCodes.Pending); + outcome.Message.Should().Contain("task-abc"); + var json = Json(outcome.Output); + json.GetProperty("status").GetString().Should().Be("queued"); + json.GetProperty("task_status").GetString().Should().Be("PENDING"); + } + + // The spec shows a failed task as an error body. A 400 becomes an exception + // and exit 1, as every other API failure does. + [Fact] + public async Task A_queued_merge_that_fails_is_reported_as_a_failure() + { + var http = new FakeHttpMessageHandler(); + EnqueueAccepted(http); + http.Enqueue(HttpStatusCode.BadRequest, """{"type":"error","error":{"message":"Merge failed"}}"""); + + var act = () => Merge(http, wait: true, timeoutSeconds: 60); + + (await act.Should().ThrowAsync()).WithMessage("*Merge failed*"); + } + + [Fact] + public async Task A_task_status_that_is_neither_pending_nor_success_exits_one() + { + var http = new FakeHttpMessageHandler(); + EnqueueAccepted(http); + http.Enqueue(HttpStatusCode.OK, """{"task_status":"FAILED"}"""); + + var outcome = await Merge(http, wait: true, timeoutSeconds: 60); + + outcome.ExitCode.Should().Be(1); + outcome.Message.Should().Contain("FAILED"); + } + + // The spec says Location; the 202 seen during the incident was described + // with links.self. Either one has to yield the task. + [Fact] + public async Task The_task_link_is_read_from_the_body_when_there_is_no_location_header() + { + var http = new FakeHttpMessageHandler(); + http.Enqueue(HttpStatusCode.Accepted, "{\"links\":{\"self\":{\"href\":\"" + TaskUrl + "\"}}}"); + + var outcome = await Merge(http, wait: false); + + Json(outcome.Output).GetProperty("task_id").GetString().Should().Be("task-abc"); + } + + [Fact] + public async Task A_202_with_no_task_link_exits_pending_rather_than_claiming_success() + { + var http = new FakeHttpMessageHandler(); + http.Enqueue(HttpStatusCode.Accepted, ""); + + var outcome = await Merge(http, wait: true, timeoutSeconds: 60); + + outcome.ExitCode.Should().Be(ExitCodes.Pending); + Json(outcome.Output).GetProperty("status").GetString().Should().Be("queued"); + } + + [Fact] + public async Task A_synchronous_merge_still_returns_the_pull_request() + { + var http = new FakeHttpMessageHandler(); + http.Enqueue(HttpStatusCode.OK, Merged); + + var outcome = await Merge(http, wait: true); + + outcome.ExitCode.Should().Be(0); + Json(outcome.Output).GetProperty("id").GetInt32().Should().Be(21); + } + + [Theory] + [InlineData("task-abc")] + [InlineData(TaskUrl)] + [InlineData(TaskUrl + "?x=1")] + public void Merge_status_takes_the_task_id_or_the_url_merge_printed(string given) + { + MergeTask.IdFrom(given).Should().Be("task-abc"); + } + + [Fact] + public async Task Merge_status_can_wait_for_the_task() + { + var http = new FakeHttpMessageHandler(); + http.Enqueue(HttpStatusCode.OK, """{"task_status":"PENDING"}"""); + http.Enqueue(HttpStatusCode.OK, $$"""{"task_status":"SUCCESS","merge_result":{{Merged}}}"""); + + var outcome = await new PullRequestMergeStatusHandler(Client(http), Creds()).HandleAsync( + new PullRequestMergeStatusRequest("ws", "repo", 21, TaskUrl, Wait: true, TimeoutSeconds: 60, + PollInterval: TimeSpan.Zero), + TestContext.Current.CancellationToken); + + Json(outcome.Output).GetProperty("state").GetString().Should().Be("MERGED"); + http.Calls.Should().AllSatisfy(c => c.RequestUri!.AbsoluteUri.Should().Be(TaskUrl)); + } + + // End to end through Program: the JSON reaches stdout and the exit code is + // not zero, which is the pair a script needs. + [Fact] + public async Task The_cli_prints_the_task_and_exits_75_when_the_merge_is_still_queued() + { + var http = new FakeHttpMessageHandler(); + EnqueueAccepted(http); + http.Enqueue(HttpStatusCode.OK, """{"task_status":"PENDING"}"""); + + int exitCode = 0; + var (stdout, stderr) = await CaptureConsole.RunAsync(async () => + exitCode = await Program.RunAsync( + ["pr", "merge", "21", "-w", "ws", "-r", "repo", "--strategy", "merge_commit", "--yes", + "--timeout", "0"], + Provider(http))); + + exitCode.Should().Be(ExitCodes.Pending); + stdout.Should().Contain("\"status\": \"queued\"").And.Contain("\"task_id\": \"task-abc\""); + stdout.Trim().Should().NotBe("\"\""); + stderr.Should().Contain("still queued"); + } + + [Fact] + public async Task The_cli_exits_zero_with_no_wait() + { + var http = new FakeHttpMessageHandler(); + EnqueueAccepted(http); + + int exitCode = -1; + var (stdout, _) = await CaptureConsole.RunAsync(async () => + exitCode = await Program.RunAsync( + ["pr", "merge", "21", "-w", "ws", "-r", "repo", "--strategy", "merge_commit", "--yes", + "--no-wait"], + Provider(http))); + + exitCode.Should().Be(0); + stdout.Should().Contain("\"task_id\": \"task-abc\""); + } + + private static void EnqueueAccepted(FakeHttpMessageHandler http) => + http.EnqueueResponder(_ => + { + var response = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("") }; + response.Headers.Location = new Uri(TaskUrl); + return response; + }); + + private static Task Merge(FakeHttpMessageHandler http, bool wait, int timeoutSeconds = 60) => + new MergePullRequestHandler(Client(http), Creds()).HandleAsync( + new MergePullRequestRequest("ws", "repo", 21, "merge_commit", null, false, wait, timeoutSeconds, + TimeSpan.Zero), + TestContext.Current.CancellationToken); + + private static JsonElement Json(object? value) => JsonSerializer.SerializeToElement(value); + + private static CredentialManager Creds() => + new(new InMemoryCredentialStore(new BbxConfig + { Username = "jane@example.com", ApiToken = "t", DefaultWorkspace = "ws" })); + + private static BitbucketClient Client(FakeHttpMessageHandler http) => + new(TestHttpClientFactory.Create(http), new NullAuthProvider()); + + private static IServiceProvider Provider(FakeHttpMessageHandler http) + { + var services = new ServiceCollection(); + services.AddSingleton(Creds()); + services.AddSingleton(Client(http)); + services.AddTransient(); + return services.BuildServiceProvider(); + } + + public void Dispose() => Program.Services = _originalServices!; +} From d76ba008dc49d1e465aa7dd628749248ef1d0d16 Mon Sep 17 00:00:00 2001 From: John Smith Date: Mon, 16 Nov 2026 12:24:10 +0000 Subject: [PATCH 2/2] fix(pr): request merges async and survive a slow task-status poll Live checks on a throwaway repository during the 16 Nov 2026 slowdown found two more ways to lose a queued merge: - Without ?async=true the merge POST blocked past the 30s client timeout, exiting 1 with the outcome unknown. The handler now asks for async, gives the POST 120s, and says the merge may be queued if it still times out. The timeout moved from HttpClient.Timeout into BitbucketClient so one call can wait longer; it keeps the inner TimeoutException that Program uses to tell a timeout (exit 1) from Ctrl+C (exit 130). - After two minutes of PENDING one task-status poll hung for 30s and the error ended the wait, losing the task ID. Timeouts, 5xx and 429 during a poll are now retried until --timeout; the last one is reported as last_poll_error. 4xx still ends the wait, since 400 is a failed task. The final live run got a real 202, polled PENDING for 600s and exited 75 with the task ID in its JSON. The repository was deleted afterwards. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014Mjr3Y5biNhSM8Bmg4xfaw --- AGENTS.md | 17 +++-- CHANGELOG.md | 10 +++ docs/api-coverage.md | 2 +- docs/llm-guide.md | 17 ++++- src/Bbx/Api/BitbucketClient.cs | 38 ++++++++-- src/Bbx/Composition/ServiceRegistration.cs | 4 +- .../MergePullRequestHandler.cs | 38 ++++++++-- .../PullRequestMergeStatus/MergeTask.cs | 67 ++++++++++++++--- tests/Bbx.Tests/Api/RequestTimeoutTests.cs | 38 ++++++++++ .../Features/PullRequests/AsyncMergeTests.cs | 74 +++++++++++++++++++ .../TestKit/FakeHttpMessageHandler.cs | 11 +++ 11 files changed, 280 insertions(+), 36 deletions(-) create mode 100644 tests/Bbx.Tests/Api/RequestTimeoutTests.cs diff --git a/AGENTS.md b/AGENTS.md index 519c2de..8eb60e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -332,12 +332,17 @@ rules below are; it is still the right place to start. answers 202 with an empty body. `PostAsync` drops headers, so 1.5.0 printed `""`, exited 0 and lost the task ID (16 Nov 2026; two queued merges were then dropped without a word, and a third landed 40 minutes later while `pr view` - still said OPEN). `MergePullRequestHandler` uses `PostForResponseAsync` and - polls `merge/task-status/{id}` through `MergeTask`. A merge still pending at - the timeout exits 75 (EX_TEMPFAIL) with the task in its JSON; a handler sets - a non-zero exit while still printing by returning a `CommandOutcome`. Never - test this by merging a real pull request: the 202 path is covered with - faked responses in `AsyncMergeTests`. + still said OPEN). Without `?async=true` the same POST can also block past the + 30s client timeout, which happened on the same day, so the handler always + sends it and polls instead. `MergePullRequestHandler` uses + `PostForResponseAsync` and polls `merge/task-status/{id}` through + `MergeTask`, which retries a poll that times out or answers 5xx or 429: + live, one poll hung 30s after two minutes of PENDING and aborted the wait. + A merge still pending at the timeout exits 75 (EX_TEMPFAIL) + with the task in its JSON; a handler sets a non-zero exit while still + printing by returning a `CommandOutcome`. Never test this on a live + repository: `AsyncMergeTests` fakes the 202 path, and a live check belongs + on a throwaway repository. ## Live testing diff --git a/CHANGELOG.md b/CHANGELOG.md index 1918304..d6c7559 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,12 +19,22 @@ Versioning follows [Semantic Versioning](https://semver.org/): `MAJOR.MINOR.PATC ### Added +- `pr merge` sends `async=true`. Without it Bitbucket holds the request open + while it merges, and during the slowdown that ran past the 30-second client + timeout and exited 1 with the outcome unknown. Even with `async=true`, + Bitbucket took over 30 seconds to accept a merge during the slowdown, so the + merge request alone now waits up to 120 seconds; every other call keeps 30. + If it still times out, the error says the merge may have been queued. - `pr merge` waits for a queued merge by polling its task status, then prints the merged pull request just as a direct merge does. If the merge is still pending after `--timeout` seconds (default 120) it prints `"status": "queued"` with `task_id`, `task_status_url` and the follow-up command, and exits **75**. A failed task exits 1. `--no-wait` prints the queued record at once and exits 0. +- While waiting, a task-status poll that times out or answers 5xx or 429 is + retried rather than ending the wait, which is what happened live: after two + minutes of PENDING one poll hung for 30 seconds. The queued record carries + the last such error as `last_poll_error`. - `pr merge-status` takes `--wait` and `--timeout`, and `--task-id` now accepts the `task_status_url` as well as the bare ID. diff --git a/docs/api-coverage.md b/docs/api-coverage.md index 4208852..6c98e6b 100644 --- a/docs/api-coverage.md +++ b/docs/api-coverage.md @@ -39,7 +39,7 @@ Three operations in the spec can answer 202 Accepted. Checked on 2026-11-16 afte | Method | Path | What 202 means | What `bbx` does | | --- | --- | --- | --- | -| `POST` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/merge` | Merge queued; the task-status URL is in the `Location` header | Before 1.6.0 it printed `""` and exited 0. Now it reads the task ID from `Location` (or `links.self.href`), polls task-status for up to `--timeout` seconds (default 120), and exits 75 with `"status": "queued"` and the task ID if the merge has not finished. `--no-wait` returns the task at once with exit 0 | +| `POST` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/merge` | Merge queued; the task-status URL is in the `Location` header | Before 1.6.0 it printed `""` and exited 0. Now it sends `async=true` so the 202 comes at once instead of after a wait that can outlast the client timeout, reads the task ID from `Location` (or `links.self.href`), polls task-status for up to `--timeout` seconds (default 120), and exits 75 with `"status": "queued"` and the task ID if the merge has not finished. `--no-wait` returns the task at once with exit 0 | | `POST` | `/repositories/{workspace}/{repo_slug}/environments/{environment_uuid}/changes` | Change queued; empty body | `bbx pipeline deployments changes` now says "Queued change" rather than "Updated". There is no task to poll | | `GET` | `/repositories/{workspace}/{repo_slug}/commit/{commit}/pullrequests` | Pull request links still being indexed; the page may be partial | Left as is. `bbx commit pullrequests` prints what came back | diff --git a/docs/llm-guide.md b/docs/llm-guide.md index 749dfd1..6cd4eee 100644 --- a/docs/llm-guide.md +++ b/docs/llm-guide.md @@ -208,17 +208,26 @@ offered; use `remove`. #### Queued merges (202) -Bitbucket sometimes queues a merge instead of running it inline, most often when -it is slow. It answers 202 and names a task. `pr merge` then polls that task -every 3 seconds: +`pr merge` sends `?async=true`, so Bitbucket queues the merge, answers 202 at +once and names a task. Without it Bitbucket holds the request open while it +merges, and on 16 Nov 2026 that ran past the 30-second client timeout and left +the outcome unknown. Even with `async=true` Bitbucket took over 30 seconds to +accept a merge that day, so the merge request alone waits up to 120 seconds. +`pr merge` then polls the task every 3 seconds: | What happens | stdout | Exit | | --- | --- | --- | | Merged inline (200), or the queued task finishes | the merged pull request, as before | `0` | -| Still `PENDING` at `--timeout` | `{"status": "queued", "task_id": …, "task_status_url": …, "task_status": "PENDING", "waited_seconds": …, "next": "bbx pr merge-status …"}` | `75` | +| Still `PENDING` at `--timeout` | `{"status": "queued", "task_id": …, "task_status_url": …, "task_status": "PENDING", "waited_seconds": …, "last_poll_error": …, "next": "bbx pr merge-status …"}` | `75` | | The task fails | the error, on stderr | `1` | +| The merge request itself times out | a "may still have been queued" error, on stderr | `1` | | `--no-wait` | the same `"status": "queued"` record, at once | `0` | +A poll that times out or answers 5xx or 429 does not end the wait: it says +nothing about the merge, so polling carries on until `--timeout`, and the last +such error appears as `last_poll_error`. A 4xx ends it, because 400 is how +Bitbucket reports a failed task. + A queued merge can still land after the timeout, or be dropped: during the Bitbucket slowdown of 16 Nov 2026 two of three queued merges vanished and the third landed 40 minutes later. So on exit 75, do not merge again. Follow the diff --git a/src/Bbx/Api/BitbucketClient.cs b/src/Bbx/Api/BitbucketClient.cs index 7032444..ea2fb79 100644 --- a/src/Bbx/Api/BitbucketClient.cs +++ b/src/Bbx/Api/BitbucketClient.cs @@ -82,9 +82,10 @@ public async Task CopyToAsync(string endpoint, Stream destination, CancellationT /// Location header; dropping it is how bbx pr merge printed a bare /// "" and lost the task ID. /// - public async Task PostForResponseAsync(string endpoint, object? body = null, CancellationToken ct = default) + public async Task PostForResponseAsync(string endpoint, object? body = null, + CancellationToken ct = default, TimeSpan? timeout = null) { - using var response = await SendAsync(HttpMethod.Post, endpoint, JsonContent(body), ct); + using var response = await SendAsync(HttpMethod.Post, endpoint, JsonContent(body), ct, timeout: timeout); await EnsureSuccessAsync(response); var json = await response.Content.ReadAsStringAsync(ct); var location = response.Headers.Location; @@ -154,11 +155,12 @@ private async Task SendAsync( HttpContent? content, CancellationToken ct, string? accept = null, - HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) + HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead, + TimeSpan? timeout = null) { var current = new Uri(_client.BaseAddress!, NormalizeEndpoint(endpoint)); var response = await SendOnceAsync( - method, current.AbsoluteUri, content, ct, accept, completionOption, IsApiOrigin(current)); + method, current.AbsoluteUri, content, ct, accept, completionOption, IsApiOrigin(current), timeout); // Redirects are followed here rather than by HttpClient because // HttpClient drops the Authorization header when it follows one, which @@ -195,7 +197,8 @@ private async Task SendOnceAsync( CancellationToken ct, string? accept, HttpCompletionOption completionOption, - bool applyAuth = true) + bool applyAuth = true, + TimeSpan? timeout = null) { var request = new HttpRequestMessage(method, url) { @@ -209,9 +212,30 @@ private async Task SendOnceAsync( { await _auth.ApplyAsync(request, ct); } - return await _client.SendAsync(request, completionOption, ct); + var limit = timeout ?? DefaultTimeout; + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct); + deadline.CancelAfter(limit); + try + { + return await _client.SendAsync(request, completionOption, deadline.Token); + } + catch (OperationCanceledException e) when (!ct.IsCancellationRequested) + { + // Keep the shape HttpClient.Timeout used to give: Program tells a + // timeout (exit 1) from Ctrl+C (exit 130) by the inner + // TimeoutException, and a bare cancellation would read as Ctrl+C. + throw new TaskCanceledException( + $"{method} {new Uri(url).AbsolutePath} got no answer within {limit.TotalSeconds:0} seconds.", + new TimeoutException(e.Message, e)); + } } + /// + /// Applied per request rather than through HttpClient.Timeout, so a + /// call that is slow by nature can ask for longer. + /// + public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(30); + private bool IsApiOrigin(Uri target) => Uri.Compare( target, _client.BaseAddress!, @@ -281,7 +305,7 @@ private static async Task EnsureSuccessAsync(HttpResponseMessage response) { } - throw new HttpRequestException(errorMessage); + throw new HttpRequestException(errorMessage, null, response.StatusCode); } private static JsonSerializerOptions JsonOptions => new() diff --git a/src/Bbx/Composition/ServiceRegistration.cs b/src/Bbx/Composition/ServiceRegistration.cs index 5a0c94e..3cc3314 100644 --- a/src/Bbx/Composition/ServiceRegistration.cs +++ b/src/Bbx/Composition/ServiceRegistration.cs @@ -27,7 +27,9 @@ public static IServiceProvider Build() var client = new HttpClient(sp.GetRequiredService(), disposeHandler: false) { BaseAddress = new Uri(BaseUrl), - Timeout = TimeSpan.FromSeconds(30), + // BitbucketClient applies the timeout per request, so one call + // (the merge) can wait longer than the rest. + Timeout = Timeout.InfiniteTimeSpan, }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.UserAgent.ParseAdd("bbx-cli/1.0"); diff --git a/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestHandler.cs b/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestHandler.cs index 030170c..a49a7e2 100644 --- a/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestHandler.cs +++ b/src/Bbx/Features/PullRequests/MergePullRequest/MergePullRequestHandler.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using Bbx.Api; using Bbx.Auth; using Bbx.Features.Common; using Bbx.Features.PullRequests.PullRequestMergeStatus; @@ -22,13 +23,32 @@ public async Task HandleAsync(MergePullRequestRequest request, C }; if (!string.IsNullOrEmpty(request.Message)) body["message"] = request.Message; - var response = await client.PostForResponseAsync( - $"/repositories/{ws}/{repo}/pullrequests/{request.Id}/merge", body, ct); + // async=true makes Bitbucket queue the merge and answer 202 at once. + // Without it Bitbucket holds the request open while it merges, and on + // 16 Nov 2026 that ran past the client's 30s timeout: bbx exited 1 + // with no idea whether the merge had been queued. Polling is ours to + // bound with --timeout; a hung POST is not. + ApiResponse response; + try + { + response = await client.PostForResponseAsync( + $"/repositories/{ws}/{repo}/pullrequests/{request.Id}/merge?async=true", body, ct, + MergeRequestTimeout); + } + catch (OperationCanceledException e) when (e.InnerException is TimeoutException) + { + // The request may have reached Bitbucket, so "try again" could + // merge twice or race a queued merge. Say what is unknown. + throw new BbxUserException( + $"Error: Bitbucket did not answer the merge of PR #{request.Id} in time. The merge may " + + $"still have been queued. Check `bbx pr view {request.Id} -w {ws} -r {repo}` before " + + "merging again."); + } - // 200 carries the merged pull request. 202 means Bitbucket queued the - // merge and named the task only in the Location header; this used to + // 200 carries the merged pull request, in case Bitbucket ignores + // async. 202 names the task only in the Location header; this used to // print the empty body as "" and exit 0, leaving the PR open and the - // task ID nowhere (16 Nov 2026, during a Bitbucket slowdown). + // task ID nowhere. if (response.Status != 202) return new CommandOutcome(response.Body); var statusUrl = MergeTask.StatusUrl(response); @@ -112,6 +132,14 @@ private async Task ResolveStrategyAsync( private const string DefaultStrategy = "merge_commit"; + /// + /// Even with async=true, Bitbucket took over 30s just to accept a merge + /// during the 16 Nov 2026 slowdown (two live runs on throwaway + /// repositories). A timed-out merge is the worst outcome, because nobody + /// knows whether it was queued, so this call gets longer than the rest. + /// + internal static readonly TimeSpan MergeRequestTimeout = TimeSpan.FromSeconds(120); + /// /// Bitbucket accepts merge_commit, squash, fast_forward, squash_fast_forward, /// rebase_fast_forward and rebase_merge. "merge" is what the UI calls a merge diff --git a/src/Bbx/Features/PullRequests/PullRequestMergeStatus/MergeTask.cs b/src/Bbx/Features/PullRequests/PullRequestMergeStatus/MergeTask.cs index 132ec47..9a3457f 100644 --- a/src/Bbx/Features/PullRequests/PullRequestMergeStatus/MergeTask.cs +++ b/src/Bbx/Features/PullRequests/PullRequestMergeStatus/MergeTask.cs @@ -52,7 +52,7 @@ public static string Endpoint(string ws, string repo, int id, string taskId) => /// status nobody can mistake for a finished merge. /// public static object Queued(string ws, string repo, int id, string? taskId, string? statusUrl, - string? taskStatus, int? waitedSeconds) => new + string? taskStatus, int? waitedSeconds, string? lastPollError = null) => new { status = "queued", pull_request = id, @@ -60,6 +60,7 @@ public static object Queued(string ws, string repo, int id, string? taskId, stri task_status_url = statusUrl, task_status = taskStatus, waited_seconds = waitedSeconds, + last_poll_error = lastPollError, next = taskId is null ? $"bbx pr view {id} -w {ws} -r {repo}" : $"bbx pr merge-status {id} --task-id {taskId} -w {ws} -r {repo} --wait", @@ -82,10 +83,30 @@ public static async Task WaitAsync(BitbucketClient client, strin { var clock = Stopwatch.StartNew(); var timeout = TimeSpan.FromSeconds(Math.Max(0, timeoutSeconds)); + string? state = null; + string? lastPollError = null; while (true) { - var status = await client.GetAsync(Endpoint(ws, repo, id, taskId), ct); - var state = status.GetStringOrNull("task_status"); + JsonElement status; + try + { + status = await client.GetAsync(Endpoint(ws, repo, id, taskId), ct); + lastPollError = null; + } + catch (Exception e) when (IsTransient(e, ct)) + { + // Live on 16 Nov 2026 one poll hung past 30s after two minutes + // of PENDING, and aborting there lost the task ID all over + // again. A poll that fails to answer says nothing about the + // merge, so keep going until the caller's timeout. + lastPollError = e.Message; + if (TimedOut(clock, timeout, interval)) + return StillQueued(ws, repo, id, taskId, statusUrl, state, clock, lastPollError); + await Task.Delay(interval, ct); + continue; + } + + state = status.GetStringOrNull("task_status"); if (string.Equals(state, "SUCCESS", StringComparison.OrdinalIgnoreCase)) { @@ -105,17 +126,39 @@ public static async Task WaitAsync(BitbucketClient client, strin + (message is null ? $" (task_status: {state ?? "missing"})." : $": {message}")); } - if (clock.Elapsed + interval > timeout) - { - var waited = (int)Math.Round(clock.Elapsed.TotalSeconds); - return new CommandOutcome( - Queued(ws, repo, id, taskId, statusUrl, state, waited), - ExitCodes.Pending, - $"PR #{id} merge is still queued after {waited}s (task {taskId}). " - + "It may still land. Check again with `bbx pr merge-status`."); - } + if (TimedOut(clock, timeout, interval)) + return StillQueued(ws, repo, id, taskId, statusUrl, state, clock, null); await Task.Delay(interval, ct); } } + + private static bool TimedOut(Stopwatch clock, TimeSpan timeout, TimeSpan interval) => + clock.Elapsed + interval > timeout; + + private static CommandOutcome StillQueued(string ws, string repo, int id, string taskId, string? statusUrl, + string? state, Stopwatch clock, string? lastPollError) + { + var waited = (int)Math.Round(clock.Elapsed.TotalSeconds); + return new CommandOutcome( + Queued(ws, repo, id, taskId, statusUrl, state, waited, lastPollError), + ExitCodes.Pending, + $"PR #{id} merge is still queued after {waited}s (task {taskId}). " + + "It may still land. Check again with `bbx pr merge-status`."); + } + + /// + /// A poll failure that says nothing about the merge: a timeout, a network + /// error, 429 or a 5xx. A 4xx is Bitbucket's answer (400 is how a failed + /// task is reported) and must end the wait. + /// + private static bool IsTransient(Exception e, CancellationToken ct) => e switch + { + OperationCanceledException { InnerException: TimeoutException } => true, + OperationCanceledException => false, + HttpRequestException { StatusCode: null } => true, + HttpRequestException { StatusCode: var code } => + (int)code! >= 500 || (int)code == 429, + _ => false, + } && !ct.IsCancellationRequested; } diff --git a/tests/Bbx.Tests/Api/RequestTimeoutTests.cs b/tests/Bbx.Tests/Api/RequestTimeoutTests.cs new file mode 100644 index 0000000..52a8a6f --- /dev/null +++ b/tests/Bbx.Tests/Api/RequestTimeoutTests.cs @@ -0,0 +1,38 @@ +using AwesomeAssertions; +using Bbx.Api; +using Bbx.Auth; +using Bbx.Tests.TestKit; + +namespace Bbx.Tests.Api; + +// The timeout moved from HttpClient.Timeout into BitbucketClient so the merge +// can wait longer than other calls. Program tells a timeout (exit 1) from +// Ctrl+C (exit 130) by an inner TimeoutException, so that shape must survive. +public class RequestTimeoutTests +{ + [Fact] + public async Task A_request_that_outlasts_its_timeout_fails_as_a_timeout_not_a_cancellation() + { + var http = new FakeHttpMessageHandler { HangNext = true }; + var client = new BitbucketClient(TestHttpClientFactory.Create(http), new NullAuthProvider()); + + var act = () => client.PostForResponseAsync("x", new { }, TestContext.Current.CancellationToken, + TimeSpan.FromMilliseconds(50)); + + var thrown = await act.Should().ThrowAsync(); + thrown.Which.InnerException.Should().BeOfType(); + } + + [Fact] + public async Task A_cancelled_request_still_reads_as_a_cancellation() + { + var http = new FakeHttpMessageHandler { HangNext = true }; + var client = new BitbucketClient(TestHttpClientFactory.Create(http), new NullAuthProvider()); + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); + + var act = () => client.PostForResponseAsync("x", new { }, cts.Token, TimeSpan.FromSeconds(30)); + + var thrown = await act.Should().ThrowAsync(); + thrown.Which.InnerException.Should().NotBeOfType(); + } +} diff --git a/tests/Bbx.Tests/Features/PullRequests/AsyncMergeTests.cs b/tests/Bbx.Tests/Features/PullRequests/AsyncMergeTests.cs index 0f39c58..e988cf9 100644 --- a/tests/Bbx.Tests/Features/PullRequests/AsyncMergeTests.cs +++ b/tests/Bbx.Tests/Features/PullRequests/AsyncMergeTests.cs @@ -43,6 +43,20 @@ public async Task A_queued_merge_returns_the_task_at_once_with_no_wait() http.Calls.Should().HaveCount(1); } + // Without async=true Bitbucket holds the POST open while it merges, and on + // 16 Nov 2026 that outlasted the 30s client timeout, leaving the outcome + // unknown. + [Fact] + public async Task The_merge_is_requested_asynchronously_so_a_slow_bitbucket_cannot_time_it_out() + { + var http = new FakeHttpMessageHandler(); + EnqueueAccepted(http); + + await Merge(http, wait: false); + + http.Calls.Single().RequestUri!.Query.Should().Be("?async=true"); + } + [Fact] public async Task A_queued_merge_is_polled_until_it_succeeds_and_returns_the_merged_pull_request() { @@ -89,6 +103,54 @@ public async Task A_queued_merge_that_fails_is_reported_as_a_failure() (await act.Should().ThrowAsync()).WithMessage("*Merge failed*"); } + // Live on 16 Nov 2026: after two minutes of PENDING one poll hung past the + // 30s request timeout and the whole wait aborted with exit 1. + [Theory] + [InlineData(HttpStatusCode.InternalServerError)] + [InlineData(HttpStatusCode.BadGateway)] + [InlineData(HttpStatusCode.TooManyRequests)] + public async Task A_poll_that_fails_transiently_does_not_end_the_wait(HttpStatusCode failure) + { + var http = new FakeHttpMessageHandler(); + EnqueueAccepted(http); + http.Enqueue(HttpStatusCode.OK, """{"task_status":"PENDING"}"""); + http.Enqueue(failure, """{"error":{"message":"slow"}}"""); + http.Enqueue(HttpStatusCode.OK, $$"""{"task_status":"SUCCESS","merge_result":{{Merged}}}"""); + + var outcome = await Merge(http, wait: true, timeoutSeconds: 60); + + outcome.ExitCode.Should().Be(0); + Json(outcome.Output).GetProperty("state").GetString().Should().Be("MERGED"); + } + + [Fact] + public async Task A_poll_that_hangs_does_not_end_the_wait() + { + var http = new FakeHttpMessageHandler(); + EnqueueAccepted(http); + http.EnqueueResponder(_ => throw new TaskCanceledException("hung", new TimeoutException())); + http.Enqueue(HttpStatusCode.OK, $$"""{"task_status":"SUCCESS","merge_result":{{Merged}}}"""); + + var outcome = await Merge(http, wait: true, timeoutSeconds: 60); + + outcome.ExitCode.Should().Be(0); + } + + [Fact] + public async Task A_poll_that_keeps_failing_still_ends_with_the_task_and_exit_75() + { + var http = new FakeHttpMessageHandler(); + EnqueueAccepted(http); + http.Enqueue(HttpStatusCode.ServiceUnavailable, """{"error":{"message":"down"}}"""); + + var outcome = await Merge(http, wait: true, timeoutSeconds: 0); + + outcome.ExitCode.Should().Be(ExitCodes.Pending); + var json = Json(outcome.Output); + json.GetProperty("task_id").GetString().Should().Be("task-abc"); + json.GetProperty("last_poll_error").GetString().Should().Contain("down"); + } + [Fact] public async Task A_task_status_that_is_neither_pending_nor_success_exits_one() { @@ -127,6 +189,18 @@ public async Task A_202_with_no_task_link_exits_pending_rather_than_claiming_suc Json(outcome.Output).GetProperty("status").GetString().Should().Be("queued"); } + [Fact] + public async Task A_merge_post_that_times_out_says_the_merge_may_still_be_queued() + { + var http = new FakeHttpMessageHandler(); + http.EnqueueResponder(_ => throw new TaskCanceledException( + "timed out", new TimeoutException())); + + var act = () => Merge(http, wait: true); + + (await act.Should().ThrowAsync()).WithMessage("*may still have been queued*"); + } + [Fact] public async Task A_synchronous_merge_still_returns_the_pull_request() { diff --git a/tests/Bbx.Tests/TestKit/FakeHttpMessageHandler.cs b/tests/Bbx.Tests/TestKit/FakeHttpMessageHandler.cs index 9769602..1ab3e48 100644 --- a/tests/Bbx.Tests/TestKit/FakeHttpMessageHandler.cs +++ b/tests/Bbx.Tests/TestKit/FakeHttpMessageHandler.cs @@ -21,6 +21,12 @@ public void EnqueueResponder(Func respo _responders.Enqueue(responder); } + /// + /// Never answer the next request, as a server that has stopped replying. + /// The call ends only when its token is cancelled. + /// + public bool HangNext { get; set; } + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // HttpClient hands the token straight to its handler without checking it @@ -34,6 +40,11 @@ protected override async Task SendAsync(HttpRequestMessage body = await request.Content.ReadAsStringAsync(cancellationToken); } CallBodies.Add(body); + if (HangNext) + { + HangNext = false; + await Task.Delay(Timeout.Infinite, cancellationToken); + } if (_responders.Count == 0) throw new InvalidOperationException($"No scripted response for {request.Method} {request.RequestUri}"); return _responders.Dequeue()(request);