Skip to content
Open
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
26 changes: 26 additions & 0 deletions CosmosDBShell.Tests/CommandTests/CreateCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,32 @@ namespace CosmosShell.Tests.CommandTests;

public class CreateCommandTests
{
private const string UniqueKeyPolicy = """{"uniqueKeys":[{"paths":["/sku"]}]}""";

[Theory]
[InlineData("item", """{"id":"product"}""", UniqueKeyPolicy)]
[InlineData("item", """{"id":"product"}""", "")]
[InlineData("i", """{"id":"product"}""", UniqueKeyPolicy)]
[InlineData("i", """{"id":"product"}""", "")]
[InlineData("database", "ExampleShop", UniqueKeyPolicy)]
[InlineData("database", "ExampleShop", "")]
[InlineData("db", "ExampleShop", UniqueKeyPolicy)]
[InlineData("db", "ExampleShop", "")]
public async Task Create_NonContainerWithUniqueKeyPolicy_ThrowsUsageErrorBeforeConnecting(
string target, string name, string policy)
{
using var shell = ShellInterpreter.CreateInstance();
var parser = new StatementParser($"create {target} '{name}' --unique_key_policy='{policy}'");
var statement = Assert.Single(parser.ParseStatements());

var exception = await Assert.ThrowsAsync<CommandException>(
() => statement.RunAsync(shell, new CommandState(), TestContext.Current.CancellationToken));

Assert.True(exception.IsUsageError);
Assert.Equal("create", exception.Command);
Assert.Contains("The --unique_key_policy option is only valid for `create container`", exception.Message);
}

[Fact]
public async Task MkCon_PositionalPartitionKeyMissing_UsesCustomErrorMessage()
{
Expand Down
128 changes: 126 additions & 2 deletions CosmosDBShell.Tests/CommandTests/ServerlessCreationThroughputTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,108 @@ namespace CosmosShell.Tests.CommandTests;
public class ServerlessCreationThroughputTests
{
private const string ServerlessMessage = "Setting offer throughput or autopilot on container is not supported for serverless accounts.";
private const string UniqueKeysJson = """{"uniqueKeys":[{"paths":["/sku"]},{"paths":["/supplier","/externalCode"]}]}""";

[Theory]
[InlineData("mkcon")]
[InlineData("create container")]
public async Task ContainerCommand_BindsUniquePolicyAndPreservesConstraintsOnDataPlane(string command)
{
using var shell = ShellInterpreter.CreateInstance();
var (client, database) = CreateDataPlaneClient();
shell.State = new DatabaseState("db", client);
ContainerProperties? sent = null;
var created = Substitute.For<ContainerResponse>();
created.StatusCode.Returns(HttpStatusCode.Created);
created.Container.Id.Returns("Items");
database.CreateContainerIfNotExistsAsync(
Arg.Do<ContainerProperties>(properties => sent = properties),
Arg.Any<ThroughputProperties>(), Arg.Any<RequestOptions>(), Arg.Any<CancellationToken>()).Returns(created);

var result = await shell.ExecuteCommandAsync(
$"{command} Items /tenantId --unique_key_policy='{UniqueKeysJson}'", TestContext.Current.CancellationToken);

Assert.False(result.IsError);
Assert.NotNull(sent);
Assert.Collection(sent.UniqueKeyPolicy.UniqueKeys,
key => Assert.Equal(["/sku"], key.Paths),
key => Assert.Equal(["/supplier", "/externalCode"], key.Paths));
}

[Fact]
public async Task DataPlaneCreateContainer_WithUniqueKeys_RejectsExistingContainer()
{
using var shell = ShellInterpreter.CreateInstance();
var (client, database) = CreateDataPlaneClient();
shell.State = new DatabaseState("db", client);
var existing = Substitute.For<ContainerResponse>();
existing.StatusCode.Returns(HttpStatusCode.OK);
database.CreateContainerIfNotExistsAsync(
Arg.Any<ContainerProperties>(), Arg.Any<ThroughputProperties>(), Arg.Any<RequestOptions>(), Arg.Any<CancellationToken>()).Returns(existing);

var command = new MakeContainerCommand { Name = "Items", PartitionKey = "/pk", UniqueKeyPolicy = UniqueKeysJson };
var error = await Assert.ThrowsAsync<CommandException>(
() => command.ExecuteAsync(shell, new CommandState(), "mkcon", TestContext.Current.CancellationToken));

Assert.Contains("already exists", error.Message);
Assert.IsType<ExistingContainerUniqueKeyPolicyException>(error.InnerException);
}

[Theory]
[InlineData("", null)]
[InlineData("null", null)]
[InlineData("""{"uniqueKeys":[]}""", null)]
[InlineData("""{"uniqueKeys":[{"paths":[]}]}""", null)]
[InlineData("""{"uniqueKeys":[{"paths":["sku"]}]}""", null)]
[InlineData("""{"uniqueKeys":[{"paths":[12]}]}""", null)]
[InlineData("""{"uniqueKeys":[{"paths":["/\uD800"]}]}""", null)]
[InlineData("""{"uniqueKeys":[{"paths":["/\uDC00"]}]}""", null)]
[InlineData("""{"uniqueKeys":[{"paths":["/sku","/sku"]}]}""", null)]
[InlineData(UniqueKeysJson, "/id")]
public async Task Mkcon_InvalidUniqueKeyPolicy_IsRejectedBeforeBackendAccess(string json, string? legacy)
{
using var shell = ShellInterpreter.CreateInstance();
var client = Substitute.For<CosmosClient>();
shell.State = new DatabaseState("db", client);
var command = new MakeContainerCommand { Name = "Items", PartitionKey = "/pk", UniqueKeyPolicy = json, UniqueKey = legacy };

await Assert.ThrowsAsync<CommandException>(
() => command.ExecuteAsync(shell, new CommandState(), "mkcon", TestContext.Current.CancellationToken));

client.DidNotReceiveWithAnyArgs().GetDatabase(default!);
}

[Fact]
public void UniqueKeyPolicy_DecodesValidSurrogatePairInPath()
{
var keys = ContainerUniqueKeyPolicy.Parse(null, """{"uniqueKeys":[{"paths":["/\uD83D\uDE80"]}]}""");

Assert.Equal("/\U0001F680", Assert.Single(Assert.Single(keys)));
}

[Theory]
[InlineData(10, 8, false)]
[InlineData(10, 7, true)]
[InlineData(11, 1, false)]
public void UniqueKeyPolicy_EnforcesServiceLimits(int constraints, int firstPathCount, bool valid)
{
var json = System.Text.Json.JsonSerializer.Serialize(new
{
uniqueKeys = Enumerable.Range(0, constraints).Select(i => new
{
paths = Enumerable.Range(0, i == 0 ? firstPathCount : 1).Select(j => $"/p{i}_{j}"),
}),
});

if (valid)
{
Assert.Equal(constraints, ContainerUniqueKeyPolicy.Parse(null, json).Count);
}
else
{
Assert.Throws<CommandException>(() => ContainerUniqueKeyPolicy.Parse(null, json));
}
}

[Fact]
public void CreateUpdateConfig_ServerlessWithoutOptions_OmitsThroughput()
Expand Down Expand Up @@ -141,14 +243,33 @@ public async Task ArmCreateContainer_Serverless_SendsPayloadWithoutThroughput()
.Returns(Substitute.For<ArmOperation<CosmosDBSqlContainerResource>>());

await CosmosArmResourceProvider.CreateContainerAsync(
context, "db", "Items", ["/tenantId", "/userId"], "/email", null, null, null, TestContext.Current.CancellationToken);
context, "db", "Items", ["/tenantId", "/userId"], [["/email"], ["/supplier", "/externalCode"]], null, null, null, TestContext.Current.CancellationToken);

var json = CosmosArmResourceProvider.WriteArmModel(Assert.IsType<CosmosDBSqlContainerCreateOrUpdateContent>(sent));
Assert.DoesNotContain("throughput", json, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("autoscaleSettings", json, StringComparison.OrdinalIgnoreCase);
Assert.Contains("/tenantId", json);
Assert.Contains("/userId", json);
Assert.Contains("/email", json);
using var document = System.Text.Json.JsonDocument.Parse(json);
var keys = document.RootElement.GetProperty("properties").GetProperty("resource").GetProperty("uniqueKeyPolicy").GetProperty("uniqueKeys");
Assert.Equal(2, keys.GetArrayLength());
Assert.Equal("/email", Assert.Single(keys[0].GetProperty("paths").EnumerateArray()).GetString());
Assert.Equal(new[] { "/supplier", "/externalCode" }, keys[1].GetProperty("paths").EnumerateArray().Select(p => p.GetString()));
}

[Fact]
public async Task ArmCreateContainer_WithUniqueKeys_RejectsExistingContainerBeforePut()
{
var (context, containers) = CreateArmContainerContext(Provisioned());
var existing = Substitute.For<CosmosDBSqlContainerResource>();
containers.GetIfExistsAsync("Items", Arg.Any<CancellationToken>())
.Returns(Task.FromResult<NullableResponse<CosmosDBSqlContainerResource>>(Response.FromValue(existing, Substitute.For<Response>())));
var token = TestContext.Current.CancellationToken;

await Assert.ThrowsAsync<ExistingContainerUniqueKeyPolicyException>(() => CosmosArmResourceProvider.CreateContainerAsync(
context, "db", "Items", ["/pk"], [["/sku"], ["/externalCode"]], null, null, null, token));

await containers.DidNotReceiveWithAnyArgs().CreateOrUpdateAsync(default, default!, default!, token);
}

[Fact]
Expand Down Expand Up @@ -466,6 +587,7 @@ private static (DataPlaneCosmosResourceOperations Operations, Database Database,
private static (CosmosClient Client, Database Database) CreateDataPlaneClient()
{
var client = Substitute.For<CosmosClient>();
client.Endpoint.Returns(new Uri("https://example.documents.azure.com"));
var database = Substitute.For<Database>();
var existing = Substitute.For<DatabaseResponse>();
existing.StatusCode.Returns(HttpStatusCode.OK);
Expand All @@ -492,6 +614,8 @@ private static (ArmCosmosContext Context, CosmosDBSqlContainerCollection Contain
.Returns(Task.FromResult<NullableResponse<CosmosDBSqlDatabaseResource>>(
Response.FromValue(database, Substitute.For<Response>())));
var containers = Substitute.For<CosmosDBSqlContainerCollection>();
containers.GetIfExistsAsync("Items", Arg.Any<CancellationToken>())
.Returns(Task.FromResult(Substitute.For<NullableResponse<CosmosDBSqlContainerResource>>()));
database.GetCosmosDBSqlContainers().Returns(containers);
return (context, containers);
}
Expand Down
61 changes: 60 additions & 1 deletion CosmosDBShell.Tests/McpConfirmationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,65 @@ namespace CosmosShell.Tests;
[Collection(CosmosShell.Tests.Shell.ThemeStateTestCollection.Name)]
public class McpConfirmationTests
{
[Theory]
[InlineData("mkcon")]
[InlineData("create")]
public async Task ContainerCreation_OverMcp_BindsUniqueKeyPolicy(string toolName)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
using var host = McpServer.CreateHost(new Program.CosmosShellOptions { McpPort = 0 });
await host.StartAsync(timeout.Token);
var shell = ShellInterpreter.Instance;
var originalState = shell.State;
using var cosmos = Substitute.For<CosmosClient>();
try
{
cosmos.Endpoint.Returns(new Uri("https://example.documents.azure.com"));
var database = Substitute.For<Database>();
cosmos.GetDatabase("db").Returns(database);
var databaseResponse = Substitute.For<DatabaseResponse>();
databaseResponse.StatusCode.Returns(HttpStatusCode.OK);
database.ReadAsync(Arg.Any<RequestOptions>(), Arg.Any<CancellationToken>()).Returns(databaseResponse);
var created = Substitute.For<ContainerResponse>();
created.StatusCode.Returns(HttpStatusCode.Created);
created.Container.Id.Returns("Items");
ContainerProperties? sent = null;
database.CreateContainerIfNotExistsAsync(
Arg.Do<ContainerProperties>(properties => sent = properties),
Arg.Any<ThroughputProperties>(), Arg.Any<RequestOptions>(), Arg.Any<CancellationToken>()).Returns(created);
shell.State = new DatabaseState("db", cosmos);

var address = host.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri(address.TrimEnd('/') + "/") });
await using var client = await McpClient.CreateAsync(transport, cancellationToken: timeout.Token);
var args = new Dictionary<string, object?>
{
["name"] = "Items",
["partition_key"] = "/tenant",
["unique_key_policy"] = """{"uniqueKeys":[{"paths":["/sku"]},{"paths":["/supplier","/externalCode"]}]}""",
};
if (toolName == "create")
{
args["item"] = "container";
}

var result = await client.CallToolAsync(toolName, args, cancellationToken: timeout.Token);

Assert.False(result.IsError);
Assert.NotNull(sent);
Assert.Collection(
sent.UniqueKeyPolicy.UniqueKeys,
key => Assert.Equal(["/sku"], key.Paths),
key => Assert.Equal(["/supplier", "/externalCode"], key.Paths));
}
finally
{
shell.State = originalState;
await host.StopAsync(TestContext.Current.CancellationToken);
}
}

[Theory]
[InlineData("rmcon", "accept", null)]
[InlineData("rmdb", "accept", null)]
Expand Down Expand Up @@ -130,7 +189,7 @@ public async Task ResourceDeletion_OverHttp_RequiresOnlyMcpApproval(string comma
finally
{
await host.StopAsync(TestContext.Current.CancellationToken);
shell.State = originalState;
shell.State = originalState;
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------

namespace Azure.Data.Cosmos.Shell.Commands;

using System.Text.Json;
using Azure.Data.Cosmos.Shell.Core;
using Azure.Data.Cosmos.Shell.Util;

internal static class ContainerUniqueKeyPolicy
{
public static IReadOnlyList<IReadOnlyList<string>> Parse(string? legacy, string? json)
{
var constraints = new List<IReadOnlyList<string>>();
if (json is null)
{
if (string.IsNullOrWhiteSpace(legacy))
{
return constraints;
}

constraints.Add(legacy.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries));
}
else
{
if (legacy is not null)
{
throw CommandException.Usage("mkcon", MessageService.GetString("command-mkcon-error_unique_key_policy_conflict"));
}

try
{
using var document = JsonDocument.Parse(json);
var keys = ReadArrayProperty(document.RootElement, "uniqueKeys");
constraints.AddRange(keys.EnumerateArray().Select(key =>
ReadArrayProperty(key, "paths").EnumerateArray().Select(ReadPath).ToArray()));
}
catch (JsonException ex)
{
throw InvalidPolicy(ex);
}
}

if (constraints.Count is < 1 or > 10
|| constraints.Sum(paths => paths.Count) > 16
|| constraints.Any(paths => paths.Count == 0
|| paths.Any(path => path.Length < 2 || path[0] != '/' || string.IsNullOrWhiteSpace(path[1..]))
|| paths.Distinct(StringComparer.Ordinal).Count() != paths.Count))
{
throw InvalidPolicy();
}

return constraints;
}

private static string ReadPath(JsonElement path)
{
if (path.ValueKind != JsonValueKind.String)
{
throw InvalidPolicy();
}

try
{
return path.GetString()!;
}
catch (InvalidOperationException ex)
{
// JsonDocument defers decoding escaped surrogate pairs until the string is read.
throw InvalidPolicy(ex);
}
}

private static JsonElement ReadArrayProperty(JsonElement element, string name)
{
if (element.ValueKind != JsonValueKind.Object
|| element.EnumerateObject().Count() != 1
|| !element.TryGetProperty(name, out var array)
|| array.ValueKind != JsonValueKind.Array)
{
throw InvalidPolicy();
}

return array;
}

private static CommandException InvalidPolicy(Exception? inner = null)
{
return CommandException.Usage("mkcon", MessageService.GetString("command-mkcon-error_invalid_unique_key_policy"), inner);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ internal class CreateCommand : CosmosCommand
[CosmosParameter("unique_key", IsRequired = false)]
public string? UniqueKey { get; init; }

[CosmosOption("unique_key_policy")]
public string? UniqueKeyPolicy { get; init; }

[CosmosOption("scale", "s")]
public string? Scale { get; init; }

Expand All @@ -52,6 +55,11 @@ internal class CreateCommand : CosmosCommand
public async override Task<CommandState> ExecuteAsync(ShellInterpreter shell, CommandState commandState, string commandText, CancellationToken token)
{
var item = (this.Item ?? string.Empty).ToUpper();
if (this.UniqueKeyPolicy is not null && !IsContainer(item))
{
throw CommandException.Usage("create", MessageService.GetString("command-create-error_unique_key_policy_only_for_containers"));
Comment thread
mkrueger marked this conversation as resolved.
Resolved
}

if (IsItem(item))
{
var mkItemCmd = new MakeItemCommand()
Expand Down Expand Up @@ -89,6 +97,7 @@ public async override Task<CommandState> ExecuteAsync(ShellInterpreter shell, Co
Name = this.Name,
PartitionKey = this.PartitionKey,
UniqueKey = this.UniqueKey,
UniqueKeyPolicy = this.UniqueKeyPolicy,
Scale = this.Scale,
MaxRU = this.MaxRU,
Database = this.Database,
Expand Down
Loading