diff --git a/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs b/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs index 3e8ab943..8ab6d454 100644 --- a/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs +++ b/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs @@ -4,13 +4,22 @@ namespace CosmosShell.Tests.CommandTests; +using System.Net; +using System.Text; 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.Parser; using Azure.Data.Cosmos.Shell.States; using Azure.Data.Cosmos.Shell.Util; +using Azure.ResourceManager; +using Azure.ResourceManager.CosmosDB; using Microsoft.Azure.Cosmos; +using ModelContextProtocol.Protocol; +using NSubstitute; /// /// Offline unit tests for . These cover the @@ -20,6 +29,122 @@ namespace CosmosShell.Tests.CommandTests; /// public class InfoCommandTests { + private const string GroupedUniqueKeys = """{"uniqueKeys":[{"paths":["/sku"]},{"paths":["/supplierId","/supplierProductCode"]}]}"""; + private const string EmptyUniqueKeys = """{"uniqueKeys":[]}"""; + private const string MissingConstraintPaths = """{"uniqueKeys":[{"paths":["/sku"]},{}]}"""; + private const string EmptyConstraintPaths = """{"uniqueKeys":[{"paths":["/sku"]},{"paths":[]}]}"""; + + [Theory] + [InlineData(false, GroupedUniqueKeys)] + [InlineData(false, EmptyUniqueKeys)] + [InlineData(false, null)] + [InlineData(false, "{}")] + [InlineData(false, MissingConstraintPaths)] + [InlineData(false, EmptyConstraintPaths)] + [InlineData(true, GroupedUniqueKeys)] + [InlineData(true, EmptyUniqueKeys)] + [InlineData(true, null)] + [InlineData(true, "{}")] + [InlineData(true, MissingConstraintPaths)] + [InlineData(true, EmptyConstraintPaths)] + public async Task Info_ProjectsObservedUniqueKeyPolicyToCliAndMcp(bool useArm, string? policy) + { + const string databaseName = "shop"; + const string containerName = "products"; + var client = Substitute.For(); + var database = Substitute.For(); + var container = Substitute.For(); + client.GetDatabase(databaseName).Returns(database); + database.GetContainer(containerName).Returns(container); + var databaseRead = Substitute.For(); + databaseRead.StatusCode.Returns(HttpStatusCode.OK); + database.ReadAsync(cancellationToken: Arg.Any()).Returns(databaseRead); + var containerRead = Substitute.For(); + containerRead.StatusCode.Returns(HttpStatusCode.OK); + containerRead.Headers.Returns(new Headers { ["x-ms-resource-usage"] = "documentsCount=42" }); + container.ReadContainerAsync(Arg.Any(), Arg.Any()).Returns(containerRead); + + var resource = """{"id":"products","partitionKey":{"paths":["/tenant"],"kind":"Hash"},"analyticalStorageTtl":3600"""; + resource += policy is null ? "}" : $",\"uniqueKeyPolicy\":{policy}}}"; + ArmCosmosContext? context = null; + if (useArm) + { + var account = Substitute.For(); + var databases = Substitute.For(); + var armDatabase = Substitute.For(); + var containers = Substitute.For(); + var armContainer = Substitute.For(); + account.GetCosmosDBSqlDatabases().Returns(databases); + databases.GetIfExistsAsync(databaseName, Arg.Any()) + .Returns((NullableResponse)Response.FromValue(armDatabase, Substitute.For())); + armDatabase.GetCosmosDBSqlContainers().Returns(containers); + containers.GetIfExistsAsync(containerName, Arg.Any()) + .Returns((NullableResponse)Response.FromValue(armContainer, Substitute.For())); + armContainer.Data.Returns(CosmosArmResourceProvider.ReadArmModel( + """{"properties":{"resource":""" + resource + "}}")); + var throughput = Substitute.For(); + throughput.GetAsync(Arg.Any()) + .Returns(Task.FromException>(new RequestFailedException(404, "No dedicated throughput"))); + armContainer.GetCosmosDBSqlContainerThroughputSetting().Returns(throughput); + var id = new ResourceIdentifier("/subscriptions/s/resourceGroups/rg/providers/Microsoft.DocumentDB/databaseAccounts/a"); + context = new ArmCosmosContext(Substitute.For(), id, "s", "rg", "a", new Uri("https://a.documents.azure.com"), account); + } + else + { + container.ReadContainerStreamAsync(cancellationToken: Arg.Any()) + .Returns(_ => new ResponseMessage(HttpStatusCode.OK) { Content = new MemoryStream(Encoding.UTF8.GetBytes(resource)) }); + container.ReadThroughputAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException(ScriptMocks.NotFound())); + } + + using var shell = ShellInterpreter.CreateInstance(); + shell.State = new ConnectedState(client, context); + var command = new InfoCommand { Database = databaseName, Container = containerName, Format = "json" }; + var result = await command.ExecuteAsync(shell, new CommandState(), "info", TestContext.Current.CancellationToken); + + 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); + AssertPolicy(cli.RootElement); + AssertPolicy(mcp.RootElement.GetProperty("result")); + + void AssertPolicy(JsonElement output) + { + Assert.Equal(containerName, output.GetProperty("id").GetString()); + Assert.Equal("/tenant", Assert.Single(output.GetProperty("partitionKey").EnumerateArray()).GetString()); + Assert.Equal(3600, output.GetProperty("analyticalTTL").GetInt64()); + Assert.Equal(42, output.GetProperty("documentCount").GetInt64()); + var actual = output.GetProperty("uniqueKeyPolicy"); + if (policy is null or "{}" or MissingConstraintPaths or EmptyConstraintPaths) + { + Assert.Equal(JsonValueKind.Null, actual.ValueKind); + } + else + { + using var expected = JsonDocument.Parse(policy); + Assert.True(JsonElement.DeepEquals(expected.RootElement, actual)); + } + } + } + + [Fact] + public async Task ContainerSettings_FailedReadIsNotReportedAsAnEmptyPolicy() + { + var client = Substitute.For(); + var database = Substitute.For(); + var container = Substitute.For(); + client.GetDatabase("shop").Returns(database); + database.GetContainer("products").Returns(container); + container.ReadContainerStreamAsync(cancellationToken: Arg.Any()) + .Returns(_ => new ResponseMessage(HttpStatusCode.Forbidden)); + var operations = new DataPlaneCosmosResourceOperations(client); + + var exception = await Assert.ThrowsAsync(() => + operations.GetContainerSettingsAsync("shop", "products", TestContext.Current.CancellationToken)); + + Assert.Equal(HttpStatusCode.Forbidden, exception.StatusCode); + } + [Fact] public async Task Info_Disconnected_ThrowsNotConnected() { diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs index 8a55b8fa..353af2bd 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs @@ -782,6 +782,9 @@ private async Task ShowContainerSettingsAsync(ShellInterpreter she mcpTable["id"] = view.ContainerName; mcpTable["partitionKey"] = view.PartitionKeyPaths; mcpTable["analyticalTTL"] = view.AnalyticalStorageTtl; + mcpTable["uniqueKeyPolicy"] = view.UniqueKeyPolicy is { } uniqueKeyPolicy + ? new { uniqueKeys = uniqueKeyPolicy.UniqueKeys.Select(key => new { paths = key.Paths }).ToArray() } + : null; string ttl; if (view.AnalyticalStorageTtl == null || diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs index 6ddc1289..9327799f 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs @@ -9,6 +9,7 @@ namespace Azure.Data.Cosmos.Shell.Core; using System.Runtime.CompilerServices; using global::Azure; using global::Azure.ResourceManager.CosmosDB.Models; +using Newtonsoft.Json.Linq; internal sealed class ArmCosmosResourceOperations(ArmCosmosContext context) : ICosmosResourceOperations { @@ -157,7 +158,8 @@ public async Task GetContainerSettingsAsync(string databa throughputError, GeospatialType: null, FullTextPolicy: null, - IndexingPolicy: indexingView); + IndexingPolicy: indexingView, + UniqueKeyPolicy: ContainerUniqueKeyPolicyView.FromResource(JObject.Parse(CosmosArmResourceProvider.WriteArmModel(armResource)))); } public async Task GetIndexingPolicyJsonAsync(string databaseName, string containerName, CancellationToken token) diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerSettingsView.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerSettingsView.cs index 62b667f0..9f41ce93 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerSettingsView.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerSettingsView.cs @@ -14,4 +14,5 @@ internal sealed record ContainerSettingsView( string? ThroughputErrorMessage, string? GeospatialType, ContainerFullTextPolicyView? FullTextPolicy, - ContainerIndexingPolicyView? IndexingPolicy); + ContainerIndexingPolicyView? IndexingPolicy, + ContainerUniqueKeyPolicyView? UniqueKeyPolicy); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyPolicyView.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyPolicyView.cs new file mode 100644 index 00000000..78cfad75 --- /dev/null +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyPolicyView.cs @@ -0,0 +1,32 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace Azure.Data.Cosmos.Shell.Core; + +using Newtonsoft.Json.Linq; + +internal sealed record ContainerUniqueKeyPolicyView(IReadOnlyList UniqueKeys) +{ + public static ContainerUniqueKeyPolicyView? FromResource(JObject resource) + { + if (resource["uniqueKeyPolicy"] is not JObject policy || policy["uniqueKeys"] is not JArray keys) + { + return null; + } + + var constraints = new List(keys.Count); + foreach (var key in keys) + { + if (key is not JObject constraint || constraint["paths"] is not JArray paths + || paths.Count == 0 || paths.Any(path => path.Type != JTokenType.String)) + { + return null; + } + + constraints.Add(new ContainerUniqueKeyView(paths.Values().Select(path => path!).ToArray())); + } + + return new ContainerUniqueKeyPolicyView(constraints); + } +} diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyView.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyView.cs new file mode 100644 index 00000000..795507cf --- /dev/null +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyView.cs @@ -0,0 +1,7 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace Azure.Data.Cosmos.Shell.Core; + +internal sealed record ContainerUniqueKeyView(IReadOnlyList Paths); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs index 55de07e0..cfe6e534 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs @@ -9,6 +9,7 @@ namespace Azure.Data.Cosmos.Shell.Core; using Azure.Data.Cosmos.Shell.Util; using Microsoft.Azure.Cosmos; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; internal sealed class DataPlaneCosmosResourceOperations(CosmosClient client) : ICosmosResourceOperations { @@ -166,16 +167,27 @@ public async Task> GetPartitionKeyPathsAsync(string databa public async Task GetContainerSettingsAsync(string databaseName, string containerName, CancellationToken token) { - var dpResponse = await client.GetDatabase(databaseName).GetContainer(containerName).ReadContainerAsync(cancellationToken: token); - RequestChargeContext.Record(dpResponse.RequestCharge); - var properties = GetContainerPropertiesOrThrow(dpResponse); + var container = client.GetDatabase(databaseName).GetContainer(containerName); + using var dpResponse = await container.ReadContainerStreamAsync(cancellationToken: token); + dpResponse.EnsureSuccessStatusCode(); + RequestChargeContext.Record(dpResponse.Headers.RequestCharge); + if (dpResponse.Content is null) + { + throw new ShellException(MessageService.GetString("error-unable_to_read_container")); + } + + using var streamReader = new StreamReader(dpResponse.Content); + using var jsonReader = new JsonTextReader(streamReader) { DateParseHandling = DateParseHandling.None }; + var resource = await JObject.LoadAsync(jsonReader, token); + var properties = resource.ToObject() + ?? throw new ShellException(MessageService.GetString("error-unable_to_read_container")); int? dpMin = null; int? dpMax = null; ThroughputAvailability dpAvailability = ThroughputAvailability.Available; string? dpError = null; try { - var throughputResponse = await client.GetDatabase(databaseName).GetContainer(containerName).ReadThroughputAsync(new RequestOptions(), token); + var throughputResponse = await container.ReadThroughputAsync(new RequestOptions(), token); RequestChargeContext.Record(throughputResponse.RequestCharge); dpMin = throughputResponse.MinThroughput; dpMax = throughputResponse.Resource?.AutoscaleMaxThroughput ?? throughputResponse.Resource?.Throughput ?? dpMin; @@ -226,6 +238,8 @@ public async Task GetContainerSettingsAsync(string databa indexingPolicy.VectorIndexes?.Count ?? 0); } + // The SDK getter creates an empty policy if the service omitted it. + var uniqueKeyPolicy = ContainerUniqueKeyPolicyView.FromResource(resource); return new ContainerSettingsView( properties.Id, properties.PartitionKeyPaths?.ToArray() ?? (properties.PartitionKeyPath != null ? [properties.PartitionKeyPath] : []), @@ -236,7 +250,8 @@ public async Task GetContainerSettingsAsync(string databa dpError, geospatialType, fullTextView, - indexingView); + indexingView, + uniqueKeyPolicy); } public async Task GetIndexingPolicyJsonAsync(string databaseName, string containerName, CancellationToken token) diff --git a/docs/commands.md b/docs/commands.md index 8fecd4c4..2d7392da 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1875,7 +1875,11 @@ Options: The default interactive report is rendered as tables. Use `--format json` for a machine-readable JSON object; redirecting `info` output to a file also writes JSON -so CI and scripts can parse the result directly. When `--format table` is combined +so CI and scripts can parse the result directly. Container JSON includes the +observed `uniqueKeyPolicy` on data-plane and Azure Resource Manager connections. +Each entry in `uniqueKeys` contains the `paths` of one constraint. An empty +`uniqueKeys` array means the service reported no constraints; `uniqueKeyPolicy: null` +means no policy could be observed from the response. When `--format table` is combined with redirection, the report is written to the file as a plain-text grid instead of the rich console layout. The `--partitions` and `--detailed` options issue queries against the data and therefore consume diff --git a/docs/mcp.md b/docs/mcp.md index 798c714c..c387872d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -159,6 +159,8 @@ For single-item deletions, prefer `rm` with `key: "id"`, `partition-key`, and `d Database and container resource actions are executed through Azure Resource Manager when an ARM context is attached (Entra ID connections). MCP sessions connected with account keys, emulator credentials, or static data-plane tokens fall back to the Cosmos DB data plane for these actions. +Container `info` results include the observed [`uniqueKeyPolicy`](commands.md#info) on both routes, preserving the grouping of paths into constraints. A `null` policy means it was unavailable in the response, not that the container has no constraints. + 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).