Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>
/// Offline unit tests for <see cref="InfoCommand"/>. These cover the
Expand All @@ -20,6 +29,122 @@ namespace CosmosShell.Tests.CommandTests;
/// </summary>
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<CosmosClient>();
var database = Substitute.For<Database>();
var container = Substitute.For<Container>();
client.GetDatabase(databaseName).Returns(database);
database.GetContainer(containerName).Returns(container);
var databaseRead = Substitute.For<DatabaseResponse>();
databaseRead.StatusCode.Returns(HttpStatusCode.OK);
database.ReadAsync(cancellationToken: Arg.Any<CancellationToken>()).Returns(databaseRead);
var containerRead = Substitute.For<ContainerResponse>();
containerRead.StatusCode.Returns(HttpStatusCode.OK);
containerRead.Headers.Returns(new Headers { ["x-ms-resource-usage"] = "documentsCount=42" });
container.ReadContainerAsync(Arg.Any<ContainerRequestOptions>(), Arg.Any<CancellationToken>()).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<CosmosDBAccountResource>();
var databases = Substitute.For<CosmosDBSqlDatabaseCollection>();
var armDatabase = Substitute.For<CosmosDBSqlDatabaseResource>();
var containers = Substitute.For<CosmosDBSqlContainerCollection>();
var armContainer = Substitute.For<CosmosDBSqlContainerResource>();
account.GetCosmosDBSqlDatabases().Returns(databases);
databases.GetIfExistsAsync(databaseName, Arg.Any<CancellationToken>())
.Returns((NullableResponse<CosmosDBSqlDatabaseResource>)Response.FromValue(armDatabase, Substitute.For<Response>()));
armDatabase.GetCosmosDBSqlContainers().Returns(containers);
containers.GetIfExistsAsync(containerName, Arg.Any<CancellationToken>())
.Returns((NullableResponse<CosmosDBSqlContainerResource>)Response.FromValue(armContainer, Substitute.For<Response>()));
armContainer.Data.Returns(CosmosArmResourceProvider.ReadArmModel<CosmosDBSqlContainerData>(
"""{"properties":{"resource":""" + resource + "}}"));
var throughput = Substitute.For<CosmosDBSqlContainerThroughputSettingResource>();
throughput.GetAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromException<Azure.Response<CosmosDBSqlContainerThroughputSettingResource>>(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<ArmClient>(), id, "s", "rg", "a", new Uri("https://a.documents.azure.com"), account);
}
else
{
container.ReadContainerStreamAsync(cancellationToken: Arg.Any<CancellationToken>())
.Returns(_ => new ResponseMessage(HttpStatusCode.OK) { Content = new MemoryStream(Encoding.UTF8.GetBytes(resource)) });
container.ReadThroughputAsync(Arg.Any<Microsoft.Azure.Cosmos.RequestOptions>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ThroughputResponse>(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<TextContentBlock>(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<CosmosClient>();
var database = Substitute.For<Database>();
var container = Substitute.For<Container>();
client.GetDatabase("shop").Returns(database);
database.GetContainer("products").Returns(container);
container.ReadContainerStreamAsync(cancellationToken: Arg.Any<CancellationToken>())
.Returns(_ => new ResponseMessage(HttpStatusCode.Forbidden));
var operations = new DataPlaneCosmosResourceOperations(client);

var exception = await Assert.ThrowsAsync<CosmosException>(() =>
operations.GetContainerSettingsAsync("shop", "products", TestContext.Current.CancellationToken));

Assert.Equal(HttpStatusCode.Forbidden, exception.StatusCode);
}

[Fact]
public async Task Info_Disconnected_ThrowsNotConnected()
{
Expand Down
3 changes: 3 additions & 0 deletions CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -782,6 +782,9 @@ private async Task<CommandState> 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 ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -157,7 +158,8 @@ public async Task<ContainerSettingsView> GetContainerSettingsAsync(string databa
throughputError,
GeospatialType: null,
FullTextPolicy: null,
IndexingPolicy: indexingView);
IndexingPolicy: indexingView,
UniqueKeyPolicy: ContainerUniqueKeyPolicyView.FromResource(JObject.Parse(CosmosArmResourceProvider.WriteArmModel(armResource))));
}

public async Task<string> GetIndexingPolicyJsonAsync(string databaseName, string containerName, CancellationToken token)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ internal sealed record ContainerSettingsView(
string? ThroughputErrorMessage,
string? GeospatialType,
ContainerFullTextPolicyView? FullTextPolicy,
ContainerIndexingPolicyView? IndexingPolicy);
ContainerIndexingPolicyView? IndexingPolicy,
ContainerUniqueKeyPolicyView? UniqueKeyPolicy);
Original file line number Diff line number Diff line change
@@ -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<ContainerUniqueKeyView> 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<ContainerUniqueKeyView>(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;
Comment thread
mkrueger marked this conversation as resolved.
Resolved
}

constraints.Add(new ContainerUniqueKeyView(paths.Values<string>().Select(path => path!).ToArray()));
}

return new ContainerUniqueKeyPolicyView(constraints);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------

namespace Azure.Data.Cosmos.Shell.Core;

internal sealed record ContainerUniqueKeyView(IReadOnlyList<string> Paths);
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -166,16 +167,27 @@ public async Task<IReadOnlyList<string>> GetPartitionKeyPathsAsync(string databa

public async Task<ContainerSettingsView> 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<ContainerProperties>()
?? 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;
Expand Down Expand Up @@ -226,6 +238,8 @@ public async Task<ContainerSettingsView> 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] : []),
Expand All @@ -236,7 +250,8 @@ public async Task<ContainerSettingsView> GetContainerSettingsAsync(string databa
dpError,
geospatialType,
fullTextView,
indexingView);
indexingView,
uniqueKeyPolicy);
}

public async Task<string> GetIndexingPolicyJsonAsync(string databaseName, string containerName, CancellationToken token)
Expand Down
6 changes: 5 additions & 1 deletion docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -1879,7 +1879,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
Expand Down
2 changes: 2 additions & 0 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
3 changes: 2 additions & 1 deletion tests/cli-contracts/cases/emulator/command-smoke.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
"minThroughput": 400,
"maxThroughput": 400,
"analyticalTTL": null,
"uniqueKeyPolicy": null,
"geospatialType": "Geography",
"documentCount": 1,
"dataSizeKb": null,
Expand All @@ -83,7 +84,7 @@
"/session/chargedOperationCount": {"type": "integer", "minimum": 1}
}
},
"throughput.json": {"mode": "json", "expected": {"scope": "container", "resource": "items", "mode": "manual", "throughput": 400, "autoscaleMaxThroughput": null, "minThroughput": 400}},
"throughput.json": {"mode": "json", "expected": {"scope": "container", "resource": "items", "mode": "manual", "throughput": 400, "autoscaleMaxThroughput": null, "minThroughput": 400, "isReplacePending": null}},
"stderr.txt": {"mode": "empty"}
}
},
Expand Down
1 change: 1 addition & 0 deletions tests/cli-contracts/migration-map.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@
"CosmosDBShell.Tests/CommandTests/SprocCommandExecutionTests.cs",
"CosmosDBShell.Tests/CommandTests/SprocCommandTests.cs",
"CosmosDBShell.Tests/CommandTests/ThroughputCommandTests.cs",
"CosmosDBShell.Tests/CommandTests/ThroughputReplacementStatusTests.cs",
"CosmosDBShell.Tests/CommandTests/TriggerCommandExecutionTests.cs",
"CosmosDBShell.Tests/CommandTests/TriggerCommandTests.cs",
"CosmosDBShell.Tests/CommandTests/TtlCommandTests.cs",
Expand Down
36 changes: 36 additions & 0 deletions tests/cli-contracts/test_reviewed_expectations.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,39 @@ def test_user_redirect_contract_rejects_json_with_whitespace(tmp_path):
result.write_text(f'{{"status": "error", "error": "{message}"}}', encoding="utf-8")
with pytest.raises(AssertionError, match="unexpected"):
compare_file(result, spec)


@pytest.mark.parametrize(
"filename,field,invalid_values",
[
("info.json", "uniqueKeyPolicy", [{}, {"uniqueKeys": []}]),
("throughput.json", "isReplacePending", [False, True]),
],
)
def test_emulator_metadata_contract_preserves_unavailable_values(tmp_path, filename, field, invalid_values):
cases = parse_json(
(CASES.parent / "emulator" / "command-smoke.json").read_text(encoding="utf-8")
)["cases"]
spec = next(
case for case in cases if case["id"] == "emulator-info-and-throughput-at-container-scope"
)["files"][filename]
payload = {**spec["expected"], field: None}
if filename == "info.json":
payload.update(
dataSizeKb=0,
totalSizeKb=1,
session={"requestCharge": 1, "chargedOperationCount": 1},
)
result = tmp_path / filename
result.write_text(json_text(payload), encoding="utf-8")
compare_file(result, spec)

for value in invalid_values:
result.write_text(json_text({**payload, field: value}), encoding="utf-8")
with pytest.raises(AssertionError):
compare_file(result, spec)

del payload[field]
result.write_text(json_text(payload), encoding="utf-8")
with pytest.raises(AssertionError):
compare_file(result, spec)