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
15 changes: 15 additions & 0 deletions CosmosDBShell.Tests/CommandTests/MakeContainerCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,21 @@ namespace CosmosShell.Tests.CommandTests;

public class MakeContainerCommandTests
{
[Theory]
[InlineData("{")]
[InlineData("null")]
[InlineData("""{"defaultLanguage":" ","fullTextPaths":[{"path":"/description","language":"en-US"}]}""")]
[InlineData("""{"defaultLanguage":"en-US","fullTextPaths":[]}""")]
[InlineData("""{"defaultLanguage":"en-US","fullTextPaths":[{"path":"description","language":"en-US"}]}""")]
[InlineData("""{"defaultLanguage":"en-US","fullTextPaths":[{"path":"/description"}]}""")]
[InlineData("""{"defaultLanguage":"en-US","fullTextPaths":[{"path":"/description","language":"en-US","unexpected":true}]}""")]
[InlineData("""{"defaultLanguage":"en-US","fullTextPaths":[{"path":"/description","language":"en-US"},{"path":"/description","language":"fr-FR"}]}""")]
public void FullTextPolicy_RejectsInvalidInput(string json)
{
Assert.ThrowsAny<System.Text.Json.JsonException>(() =>
Azure.Data.Cosmos.Shell.Core.ContainerFullTextPolicyInput.Parse(json));
}

[Fact]
public void CreateContainerProperties_HierarchicalPartitionKey_KeepsAllPaths()
{
Expand Down
60 changes: 60 additions & 0 deletions CosmosDBShell.Tests/CommandTests/ResourceCreationResultTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,66 @@ namespace CosmosShell.Tests.CommandTests;
[Collection(ConsoleOutputTestCollection.Name)]
public class ResourceCreationResultTests
{
private const string FullTextPolicyJson = """{"defaultLanguage":"en-US","fullTextPaths":[{"path":"/description","language":"en-US"}]}""";

[Fact]
public async Task FullTextPolicy_ArmRejectsBeforeAnyResourceCall()
{
using var shell = ShellInterpreter.CreateInstance();
var context = ConfigureArm();
context.Account.ClearReceivedCalls();
shell.State = new ConnectedState(Substitute.For<CosmosClient>(), context);
var command = new MakeContainerCommand { Name = "Items", PartitionKey = "/pk", Database = "db", FullTextPolicyJson = FullTextPolicyJson };

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

Assert.Contains("not supported on the Azure Resource Manager route", error.Message);
Assert.Empty(context.Account.ReceivedCalls());
}

[Fact]
public async Task FullTextPolicy_ExistingContainerRemainsExisting()
{
using var shell = ShellInterpreter.CreateInstance();
var client = Substitute.For<CosmosClient>();
ConfigureDataPlane(client, created: false);
shell.State = new ConnectedState(client);
var command = new MakeContainerCommand { Name = "Items", PartitionKey = "/pk", Database = "db", FullTextPolicyJson = FullTextPolicyJson };

var state = await command.ExecuteAsync(shell, new CommandState(), "mkcon", TestContext.Current.CancellationToken);

var result = Assert.IsType<ShellJson>(state.Result).Value;
Assert.False(result.GetProperty("created").GetBoolean());
Assert.Equal("existing", result.GetProperty("outcome").GetString());
}

[Fact]
public async Task FullTextPolicy_ServiceRejectionIsNotRetriedWithoutPolicy()
{
using var shell = ShellInterpreter.CreateInstance();
var client = Substitute.For<CosmosClient>();
ConfigureDataPlane(client, created: true);
var database = client.GetDatabase("db");
const string message = "Full-text search is not supported on this account.";
var error = new CosmosException(message, HttpStatusCode.BadRequest, 0, "test", 0);
database.CreateContainerIfNotExistsAsync(Arg.Any<ContainerProperties>(), Arg.Any<ThroughputProperties>(), Arg.Any<RequestOptions>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ContainerResponse>(error));
shell.State = new ConnectedState(client);
var command = new MakeContainerCommand { Name = "Items", PartitionKey = "/pk", Database = "db", FullTextPolicyJson = FullTextPolicyJson };

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

Assert.Contains(message, actual.Message);
await database.Received(1).CreateContainerIfNotExistsAsync(
Arg.Is<ContainerProperties>(properties => properties.FullTextPolicy != null),
Arg.Any<ThroughputProperties>(),
Arg.Any<RequestOptions>(),
Arg.Any<CancellationToken>());
await database.ReceivedWithAnyArgs(1).CreateContainerIfNotExistsAsync(default!, default(ThroughputProperties), default, TestContext.Current.CancellationToken);
}

public static IEnumerable<object?[]> CreationCases()
{
foreach (var container in new[] { false, true })
Expand Down
92 changes: 92 additions & 0 deletions CosmosDBShell.Tests/ToolOperationsCallToolTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,98 @@ private static JsonElement Json(string raw)
return document.RootElement.Clone();
}

[Theory]
[InlineData("mkcon", false)]
[InlineData("create", false)]
[InlineData("mkcon", true)]
[InlineData("create", true)]
public async Task ContainerCreation_ForwardsFullTextPolicy(string command, bool useMcp)
{
const string policy = """{"defaultLanguage":"en-US","fullTextPaths":[{"path":"/description","language":"en-US"},{"path":"/notes/[]","language":"fr-FR"}]}""";
var shell = ShellInterpreter.Instance;
var originalState = shell.State;
var client = Substitute.For<CosmosClient>();
client.Endpoint.Returns(new Uri("https://example.invalid"));
var db = Substitute.For<Database>();
var dbResponse = Substitute.For<DatabaseResponse>();
dbResponse.StatusCode.Returns(System.Net.HttpStatusCode.OK);
db.ReadAsync(cancellationToken: Arg.Any<CancellationToken>()).Returns(dbResponse);
client.GetDatabase("shop").Returns(db);
var response = Substitute.For<ContainerResponse>();
response.StatusCode.Returns(System.Net.HttpStatusCode.Created);
response.Container.Id.Returns("products");
ContainerProperties? sent = null;
db.CreateContainerIfNotExistsAsync(Arg.Any<ContainerProperties>(), Arg.Any<ThroughputProperties>(), Arg.Any<RequestOptions>(), Arg.Any<CancellationToken>())
.Returns(call =>
{
sent = call.Arg<ContainerProperties>();
return response;
});

try
{
shell.State = new DatabaseState("shop", client);
if (useMcp)
{
var tool = this.CreateToolOperations();
var tools = await tool.ListToolsHandler(ListContext(), TestContext.Current.CancellationToken);
var schema = Assert.Single(tools.Tools, entry => entry.Name == command).InputSchema;
Assert.Equal("object", schema.GetProperty("properties").GetProperty("full-text-policy").GetProperty("type").GetString());
var arguments = new Dictionary<string, JsonElement>
{
["name"] = Json("\"products\""),
["partition_key"] = Json("\"/tenantId\""),
["full-text-policy"] = Json(policy),
};
if (command == "create")
{
arguments["item"] = Json("\"container\"");
}

var result = await tool.CallToolHandler(CallContext(command, arguments), TestContext.Current.CancellationToken);
Assert.False(result.IsError == true, Assert.IsType<TextContentBlock>(Assert.Single(result.Content)).Text);
}
else
{
var verb = command == "create" ? "create container" : "mkcon";
var result = await shell.ExecuteCommandAsync($"{verb} products /tenantId --full-text-policy='{policy}'", TestContext.Current.CancellationToken);
Assert.False(result.IsError, result.GenerateOutputText());
}

var actual = Assert.IsType<FullTextPolicy>(sent?.FullTextPolicy);
Assert.Equal("en-US", actual.DefaultLanguage);
Assert.Collection(
actual.FullTextPaths,
first => Assert.Equal(("/description", "en-US"), (first.Path, first.Language)),
second => Assert.Equal(("/notes/[]", "fr-FR"), (second.Path, second.Language)));
}
finally
{
shell.State = originalState;
}
}

[Theory]
[InlineData("null")]
[InlineData("\"{}\"")]
[InlineData("[]")]
public async Task ContainerCreation_McpRequiresAnObject(string policy)
{
var arguments = new Dictionary<string, JsonElement>
{
["name"] = Json("\"products\""),
["partition_key"] = Json("\"/tenantId\""),
["full-text-policy"] = Json(policy),
};
var result = await this.CreateToolOperations().CallToolHandler(CallContext("mkcon", arguments), TestContext.Current.CancellationToken);
var (isError, root, document) = ReadResult(result);
using (document)
{
Assert.True(isError);
Assert.Contains("Expected a JSON object", root.GetProperty("error").GetString());
}
}

private static (bool IsError, JsonElement Root, JsonDocument Document) ReadResult(CallToolResult result)
{
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content)).Text;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,20 @@ internal class CreateCommand : CosmosCommand
[CosmosOption("index_policy", "ip")]
public string? IndexPolicy { get; init; }

[CosmosOption(ContainerFullTextPolicyInput.OptionName)]
public string? FullTextPolicyJson { get; init; }

[CosmosOption("force", "upsert")]
public bool? Force { get; init; }

public async override Task<CommandState> ExecuteAsync(ShellInterpreter shell, CommandState commandState, string commandText, CancellationToken token)
{
var item = (this.Item ?? string.Empty).ToUpper();
if (this.FullTextPolicyJson is not null && !IsContainer(item))
{
throw CommandException.Usage("create", MessageService.GetString("command-create-error-full-text-policy-container-only"));
}

if (IsItem(item))
{
var mkItemCmd = new MakeItemCommand()
Expand Down Expand Up @@ -93,6 +101,7 @@ public async override Task<CommandState> ExecuteAsync(ShellInterpreter shell, Co
MaxRU = this.MaxRU,
Database = this.Database,
IndexPolicy = this.IndexPolicy,
FullTextPolicyJson = this.FullTextPolicyJson,
},
shell,
token);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ internal class MakeContainerCommand : CosmosCommand, IStateVisitor<CommandState,
[CosmosOption("index_policy", "ip")]
public string? IndexPolicy { get; init; }

[CosmosOption(ContainerFullTextPolicyInput.OptionName)]
public string? FullTextPolicyJson { get; init; }

public async override Task<CommandState> ExecuteAsync(ShellInterpreter shell, CommandState commandState, string commandText, CancellationToken token)
{
return await shell.State.AcceptAsync(this, shell, token);
Expand Down Expand Up @@ -146,6 +149,24 @@ Task<CommandState> IStateVisitor<CommandState, ShellInterpreter>.VisitContainerS

private async Task<CommandState> CreateContainerInDatabaseAsync(ConnectedState state, ShellInterpreter shell, string databaseName, CancellationToken token)
{
FullTextPolicy? fullTextPolicy = null;
if (this.FullTextPolicyJson is not null)
{
try
{
fullTextPolicy = ContainerFullTextPolicyInput.Parse(this.FullTextPolicyJson);
}
catch (Exception ex) when (ex is JsonException or ArgumentException)
{
throw CommandException.Usage("mkcon", MessageService.GetArgsString("command-mkcon-error-invalid-full-text-policy", "detail", ex.Message), ex);
}

if (state.ArmContext is not null)
{
throw CommandException.Usage("mkcon", MessageService.GetString("command-mkcon-error-full-text-policy-arm"));
}
}

// Validate database exists
await ValidateDatabaseExistsAsync(state, databaseName, "mkcon", token);

Expand All @@ -162,7 +183,8 @@ private async Task<CommandState> CreateContainerInDatabaseAsync(ConnectedState s
this.IndexPolicy,
this.Scale,
this.MaxRU,
token);
token,
fullTextPolicy);
}
catch (InvalidIndexingPolicyJsonException ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace Azure.Data.Cosmos.Shell.Core;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using Azure.Data.Cosmos.Shell.Util;
using global::Azure;
using global::Azure.ResourceManager.CosmosDB.Models;

Expand Down Expand Up @@ -70,8 +71,14 @@ public async Task<ResourceCreationResult> CreateContainerAsync(
string? indexPolicyJson,
string? scale,
int? maxRu,
CancellationToken token)
CancellationToken token,
Microsoft.Azure.Cosmos.FullTextPolicy? fullTextPolicy = null)
{
if (fullTextPolicy is not null)
{
throw new NotSupportedException(MessageService.GetString("command-mkcon-error-full-text-policy-arm"));
}

CosmosDBIndexingPolicy? parsedIndex = null;
if (!string.IsNullOrWhiteSpace(indexPolicyJson))
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------

namespace Azure.Data.Cosmos.Shell.Core;

using System.Collections.ObjectModel;
using System.Text.Json;
using Microsoft.Azure.Cosmos;

internal static class ContainerFullTextPolicyInput
{
public const string OptionName = "full-text-policy";

public static FullTextPolicy Parse(string json)
{
using var document = JsonDocument.Parse(json);
var root = document.RootElement;
ValidateProperties(root, "defaultLanguage", "fullTextPaths");
var defaultLanguage = ReadString(root, "defaultLanguage");
if (!root.TryGetProperty("fullTextPaths", out var paths) || paths.ValueKind != JsonValueKind.Array || paths.GetArrayLength() == 0)
{
throw new JsonException("'fullTextPaths' must be a non-empty array.");
}

var entries = new Collection<FullTextPath>();
var seenPaths = new HashSet<string>(StringComparer.Ordinal);
foreach (var entry in paths.EnumerateArray())
{
ValidateProperties(entry, "path", "language");
var path = ReadString(entry, "path");
if (path.Length < 2 || path[0] != '/' || !seenPaths.Add(path))
{
throw new JsonException("Each full-text path must start with '/', name a property, and appear only once.");
}

entries.Add(new FullTextPath { Path = path, Language = ReadString(entry, "language") });
}

return new FullTextPolicy { DefaultLanguage = defaultLanguage, FullTextPaths = entries };
}

private static void ValidateProperties(JsonElement element, string first, string second)
{
if (element.ValueKind != JsonValueKind.Object)
{
throw new JsonException("Expected a JSON object.");
}

var names = new HashSet<string>(StringComparer.Ordinal);
foreach (var property in element.EnumerateObject())
{
if ((property.Name != first && property.Name != second) || !names.Add(property.Name))
{
throw new JsonException($"Expected only '{first}' and '{second}', each specified once.");
}
}
}

private static string ReadString(JsonElement element, string name)
{
if (!element.TryGetProperty(name, out var value) || value.ValueKind != JsonValueKind.String
|| value.GetString() is not { } text || string.IsNullOrWhiteSpace(text))
{
throw new JsonException($"'{name}' must be a non-blank string.");
}

return text;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Azure.Data.Cosmos.Shell.Core;

using Azure.Data.Cosmos.Shell.States;
using Microsoft.Azure.Cosmos;

/// <summary>
/// Resource access facade for database and container operations. Commands use this
Expand Down Expand Up @@ -47,9 +48,10 @@ public static Task<ResourceCreationResult> CreateContainerAsync(
string? indexPolicyJson,
string? scale,
int? maxRu,
CancellationToken token)
CancellationToken token,
FullTextPolicy? fullTextPolicy = null)
{
return For(state).CreateContainerAsync(databaseName, containerName, partitionKeyPaths, uniqueKey, indexPolicyJson, scale, maxRu, token);
return For(state).CreateContainerAsync(databaseName, containerName, partitionKeyPaths, uniqueKey, indexPolicyJson, scale, maxRu, token, fullTextPolicy);
}

public static Task DeleteDatabaseAsync(ConnectedState state, string databaseName, CancellationToken token)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ public async Task<ResourceCreationResult> CreateContainerAsync(
string? indexPolicyJson,
string? scale,
int? maxRu,
CancellationToken token)
CancellationToken token,
FullTextPolicy? fullTextPolicy = null)
{
var props = partitionKeyPaths.Count > 1
? new ContainerProperties(containerName, partitionKeyPaths.ToList())
Expand All @@ -119,6 +120,11 @@ public async Task<ResourceCreationResult> CreateContainerAsync(
props.IndexingPolicy = ParseIndexingPolicy(indexPolicyJson);
}

if (fullTextPolicy is not null)
{
props.FullTextPolicy = fullTextPolicy;
}

var database = client.GetDatabase(databaseName);
var response = await CreateWithServerlessFallbackAsync(
scale,
Expand Down
Loading