diff --git a/CosmosDBShell.Tests/CommandTests/ThroughputReplacementStatusTests.cs b/CosmosDBShell.Tests/CommandTests/ThroughputReplacementStatusTests.cs new file mode 100644 index 00000000..ae62f510 --- /dev/null +++ b/CosmosDBShell.Tests/CommandTests/ThroughputReplacementStatusTests.cs @@ -0,0 +1,180 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace CosmosShell.Tests.CommandTests; + +using System.Net; +using System.Text.Json; +using Azure; +using Azure.Core; +using Azure.Data.Cosmos.Shell.Commands; +using Azure.Data.Cosmos.Shell.Core; +using Azure.Data.Cosmos.Shell.Mcp; +using Azure.Data.Cosmos.Shell.States; +using Azure.ResourceManager; +using Azure.ResourceManager.CosmosDB; +using Azure.ResourceManager.CosmosDB.Models; +using Microsoft.Azure.Cosmos; +using ModelContextProtocol.Protocol; +using NSubstitute; +using ModelReaderWriter = System.ClientModel.Primitives.ModelReaderWriter; + +public class ThroughputReplacementStatusTests +{ + [Theory] + [InlineData(false, "show", "True", true)] + [InlineData(true, "show", "false", false)] + [InlineData(false, "show", null, null)] + [InlineData(false, "show", "", null)] + [InlineData(true, "set", "true", true)] + [InlineData(false, "set", "False", false)] + [InlineData(true, "set", null, null)] + [InlineData(true, "set", "unknown", null)] + [InlineData(true, "dry-run", "true", true)] + public async Task DataPlane_ReportsObservedStatus(bool isContainer, string operation, string? pending, bool? expected) + { + var client = Substitute.For(); + var database = Substitute.For(); + var container = Substitute.For(); + client.GetDatabase("db").Returns(database); + database.GetContainer("items").Returns(container); + var databaseRead = Substitute.For(); + var containerRead = Substitute.For(); + databaseRead.StatusCode.Returns(HttpStatusCode.OK); + containerRead.StatusCode.Returns(HttpStatusCode.OK); + database.ReadAsync(cancellationToken: Arg.Any()).Returns(databaseRead); + container.ReadContainerAsync(cancellationToken: Arg.Any()).Returns(containerRead); + + var read = CreateDataPlaneResponse(operation == "set" ? (expected == true ? "false" : "true") : pending); + var write = CreateDataPlaneResponse(pending); + database.ReadThroughputAsync(Arg.Any(), Arg.Any()).Returns(read); + container.ReadThroughputAsync(Arg.Any(), Arg.Any()).Returns(read); + database.ReplaceThroughputAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(write); + container.ReplaceThroughputAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(write); + + await AssertOutputAsync(new ConnectedState(client), isContainer, operation, expected); + } + + [Theory] + [InlineData(false, "show", "True", true)] + [InlineData(true, "show", "false", false)] + [InlineData(false, "show", null, null)] + [InlineData(true, "show", "unknown", null)] + [InlineData(true, "set", "true", true)] + [InlineData(false, "set", "False", false)] + [InlineData(true, "set", null, null)] + public async Task Arm_ReportsObservedStatus(bool isContainer, string operation, string? pending, bool? expected) + { + var account = Substitute.For(); + account.Data.Returns(ModelReaderWriter.Read(BinaryData.FromString("""{"location":"westus"}"""))!); + var databases = Substitute.For(); + var database = Substitute.For(); + account.GetCosmosDBSqlDatabases().Returns(databases); + databases.GetIfExistsAsync("db", Arg.Any()) + .Returns((NullableResponse)Response.FromValue(database, Substitute.For())); + var containers = Substitute.For(); + var container = Substitute.For(); + database.GetCosmosDBSqlContainers().Returns(containers); + containers.GetIfExistsAsync("items", Arg.Any()) + .Returns((NullableResponse)Response.FromValue(container, Substitute.For())); + + var databaseSetting = Substitute.For(); + var containerSetting = Substitute.For(); + database.GetCosmosDBSqlDatabaseThroughputSetting().Returns(databaseSetting); + container.GetCosmosDBSqlContainerThroughputSetting().Returns(containerSetting); + var read = CreateArmData(operation == "set" ? (expected == true ? "false" : "true") : pending); + databaseSetting.Data.Returns(read); + containerSetting.Data.Returns(read); + databaseSetting.GetAsync(Arg.Any()).Returns(Response.FromValue(databaseSetting, Substitute.For())); + containerSetting.GetAsync(Arg.Any()).Returns(Response.FromValue(containerSetting, Substitute.For())); + + var write = CreateArmData(pending); + var updatedDatabase = Substitute.For(); + var updatedContainer = Substitute.For(); + updatedDatabase.Data.Returns(write); + updatedContainer.Data.Returns(write); + var databaseOperation = Substitute.For>(); + var containerOperation = Substitute.For>(); + databaseOperation.Value.Returns(updatedDatabase); + containerOperation.Value.Returns(updatedContainer); + databaseSetting.CreateOrUpdateAsync(WaitUntil.Completed, Arg.Any(), Arg.Any()).Returns(databaseOperation); + containerSetting.CreateOrUpdateAsync(WaitUntil.Completed, Arg.Any(), Arg.Any()).Returns(containerOperation); + + var id = new ResourceIdentifier("/subscriptions/s/resourceGroups/rg/providers/Microsoft.DocumentDB/databaseAccounts/a"); + var context = new ArmCosmosContext(Substitute.For(), id, "s", "rg", "a", new Uri("https://a.documents.azure.com"), account); + await AssertOutputAsync(new ConnectedState(Substitute.For(), context), isContainer, operation, expected); + } + + private static ThroughputResponse CreateDataPlaneResponse(string? pending) + { + var response = Substitute.For(); + var headers = new Headers(); + if (pending is not null) + { + headers.Add("x-ms-offer-replace-pending", pending); + } + + response.Headers.Returns(headers); + response.Resource.Returns(ThroughputProperties.CreateManualThroughput(4000)); + return response; + } + + private static ThroughputSettingData CreateArmData(string? pending) + { + var resource = pending is null ? new { throughput = 4000 } : (object)new { throughput = 4000, offerReplacePending = pending }; + var json = JsonSerializer.Serialize(new { properties = new { resource } }); + return ModelReaderWriter.Read(BinaryData.FromString(json))!; + } + + private static async Task AssertOutputAsync(ConnectedState connection, bool isContainer, string operation, bool? expected) + { + using var shell = ShellInterpreter.CreateInstance(); + shell.State = connection; + var dryRun = operation == "dry-run"; + var command = new ThroughputCommand + { + Subcommand = operation == "show" ? "show" : "set", + Ru = operation == "show" ? null : 4000, + Database = "db", + Container = isContainer ? "items" : null, + DryRun = dryRun, + Yes = true, + }; + var result = await command.ExecuteAsync(shell, new CommandState(), "throughput", TestContext.Current.CancellationToken); + + result.OutputFormat = OutputFormat.JSon; + using var cli = JsonDocument.Parse(result.GenerateOutputText()); + var mcpResult = McpResponseFactory.CreateSuccess(result, shell.State); + using var mcp = JsonDocument.Parse(Assert.IsType(Assert.Single(mcpResult.Content)).Text); + AssertStatus(cli.RootElement); + AssertStatus(mcp.RootElement.GetProperty("result")); + + void AssertStatus(JsonElement payload) + { + Assert.Equal(isContainer ? "container" : "database", payload.GetProperty("scope").GetString()); + if (dryRun) + { + Assert.False(payload.GetProperty("planned").TryGetProperty("isReplacePending", out _)); + payload = payload.GetProperty("current"); + } + + var value = payload.GetProperty("isReplacePending"); + JsonValueKind expectedKind; + if (expected == true) + { + expectedKind = JsonValueKind.True; + } + else if (expected == false) + { + expectedKind = JsonValueKind.False; + } + else + { + expectedKind = JsonValueKind.Null; + } + + Assert.Equal(expectedKind, value.ValueKind); + } + } +} diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ThroughputCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ThroughputCommand.cs index f9e4a6f0..1dfcd572 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ThroughputCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ThroughputCommand.cs @@ -116,6 +116,7 @@ private static CommandState BuildResult(ThroughputView view) ["throughput"] = view.Throughput, ["autoscaleMaxThroughput"] = view.AutoscaleMaxThroughput, ["minThroughput"] = view.MinThroughput, + ["isReplacePending"] = view.IsReplacePending, }; using var jsonDoc = JsonDocument.Parse(root.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); @@ -182,6 +183,7 @@ private static CommandState BuildDryRunResult(ThroughputView current, bool plann ["throughput"] = current.Throughput, ["autoscaleMaxThroughput"] = current.AutoscaleMaxThroughput, ["minThroughput"] = current.MinThroughput, + ["isReplacePending"] = current.IsReplacePending, }, ["planned"] = new JsonObject { diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs index 988125cf..6ddc1289 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs @@ -406,7 +406,8 @@ private static ThroughputView BuildThroughputView(string scope, string resourceN autoscaleMax, min, ThroughputAvailability.Available, - null); + null, + bool.TryParse(info.OfferReplacePending, out var pending) ? pending : null); } private async Task UpdateBucketsAsync(string databaseName, string containerName, int bucketId, int? maxThroughputPercentage, CancellationToken token) diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs index cf7aa04a..55de07e0 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs @@ -404,6 +404,9 @@ private static ThroughputView BuildThroughputView(string scope, string resourceN var resource = response.Resource; int? autoscaleMax = resource?.AutoscaleMaxThroughput; bool isAutoscale = autoscaleMax.HasValue; + + // The SDK's IsReplacePending getter throws on unrecognized header values. + bool? isReplacePending = bool.TryParse(response.Headers?["x-ms-offer-replace-pending"], out var pending) ? pending : null; return new ThroughputView( scope, resourceName, @@ -412,7 +415,8 @@ private static ThroughputView BuildThroughputView(string scope, string resourceN autoscaleMax, response.MinThroughput, ThroughputAvailability.Available, - null); + null, + isReplacePending); } private static ContainerProperties GetContainerPropertiesOrThrow(ContainerResponse response) diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ThroughputView.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ThroughputView.cs index 9a03ab32..b48da7a0 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ThroughputView.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ThroughputView.cs @@ -12,4 +12,5 @@ internal sealed record ThroughputView( int? AutoscaleMaxThroughput, int? MinThroughput, ThroughputAvailability Availability, - string? ErrorMessage); + string? ErrorMessage, + bool? IsReplacePending = null); diff --git a/docs/commands.md b/docs/commands.md index 9790187c..f5d5624e 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1338,6 +1338,8 @@ By default the command targets the current scope: the container when in a contai |`manual `|Switches to manual provisioning at the given RU/s.| |`autoscale `|Switches to autoscale with the given maximum RU/s.| +Structured results for `show` and throughput changes include `isReplacePending`: `true` means the service reports a replacement is pending, `false` means it explicitly reports no pending replacement, and `null` means the service omitted the status or returned an unrecognized value. The field is supported on both data-plane and Azure Resource Manager connections. A successful write or a matching RU/s value alone does not establish that a replacement is complete; use `throughput show` to check the latest reported state. + Throughput changes apply to the resource's own provisioned throughput. Containers inside a shared-throughput database, and serverless accounts, have no dedicated throughput to change. Throughput values are validated before the request is sent: manual RU/s must be at least 400 and a multiple of 100, and autoscale maximum RU/s must be at least 1000 and a multiple of 1000. @@ -1346,7 +1348,7 @@ Switching between `manual` and `autoscale` is a mode migration. Over an Azure AD Write operations (`set`, `manual`, `autoscale`) ask for confirmation before applying, because throughput changes can affect your bill. Pass `--yes` (`-y`/`--force`) to skip the prompt. The prompt is also skipped automatically in non-interactive contexts (MCP, script execution, or piped input). -Pass `--dry-run` with a write subcommand to preview the change without applying it. The command reads the current throughput and reports the current vs. planned mode and RU/s as JSON (and a table interactively); no write is performed and no confirmation is required. +Pass `--dry-run` with a write subcommand to preview the change without applying it. The command reads the current throughput and reports the current vs. planned mode and RU/s as JSON (and a table interactively); no write is performed and no confirmation is required. Only the `current` object includes `isReplacePending`, because the plan has not been submitted. #### Examples diff --git a/docs/mcp.md b/docs/mcp.md index c29217eb..282870a5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -161,6 +161,8 @@ Database and container resource actions are executed through Azure Resource Mana On serverless accounts, `mkdb`, `mkcon`, and their `create` aliases omit throughput when neither `--scale` nor `--ru` is supplied. Explicit throughput options are rejected on serverless accounts for both ARM and data-plane connections. See [database and container creation](commands.md#mkdb). +The `throughput` tool reports `isReplacePending` in read and write results: `true` for a pending replacement, `false` when the service reports none pending, and `null` when the status is unavailable. A successful write does not by itself confirm completion. See [throughput](commands.md#throughput). + For deterministic ARM routing in multi-subscription environments, start the shell with `--connect-subscription` and `--connect-resource-group`. MCP `import` uses the same bounded concurrency as the CLI: up to 16 writes in flight by default, configurable with the `concurrency` argument. Its schema requires a positive integer (`minimum: 1`). Use `concurrency: 1` for sequential, file-order writes. In-flight writes may complete after an error; imports are not transactional. See [import](commands.md#import) for error and cancellation behavior.