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
191 changes: 191 additions & 0 deletions CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// ------------------------------------------------------------
// 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.Parser;
using Azure.Data.Cosmos.Shell.States;
using Azure.ResourceManager;
using Azure.ResourceManager.CosmosDB;
using Microsoft.Azure.Cosmos;
using ModelContextProtocol.Protocol;
using Newtonsoft.Json;
using NSubstitute;

public class FullTextPolicyReadbackTests
{
public static IEnumerable<object?[]> PolicyCases()
{
string?[] policies =
[
"""{"defaultLanguage":"en-US","fullTextPaths":[{"path":"/description","language":"en-US"},{"path":"/title","language":"de-DE"},{"path":"/notes"}]}""",
"""{"defaultLanguage":"fr-FR","fullTextPaths":[]}""",
"""{"defaultLanguage":"en-US"}""",
"""{"fullTextPaths":[{"path":"/description","language":"en-US"}]}""",
"null",
null,
];
foreach (var arm in new[] { false, true })
{
foreach (var mcp in new[] { false, true })
{
foreach (var policy in policies)
{
yield return [arm, mcp, policy];
}
}
}
}

[Theory]
[MemberData(nameof(PolicyCases))]
public async Task Info_PreservesCompletePolicyAndLegacyPathsAcrossBackends(bool arm, bool mcp, string? policy)
{
using var shell = ShellInterpreter.CreateInstance();
shell.State = CreateState(arm, policy);
shell.IsMcpInvocation = mcp;
var command = new InfoCommand
{
Database = "db",
Container = "Items",
Format = "json",
};

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

var root = Assert.IsType<ShellJson>(result.Result).Value;
if (mcp)
{
var response = McpResponseFactory.CreateSuccess(result, shell.State);
Assert.False(response.IsError);
using var envelope = JsonDocument.Parse(Assert.IsType<TextContentBlock>(Assert.Single(response.Content)).Text);
Assert.Equal(root.GetRawText(), envelope.RootElement.GetProperty("result").GetRawText());
}

var details = root.GetProperty("fullTextPolicyDetails");
if (policy is null || policy == "null")
{
Assert.Equal(JsonValueKind.Null, details.ValueKind);
Assert.False(root.TryGetProperty("fullTextPolicy", out _));
return;
}

using var expected = JsonDocument.Parse(policy);
var expectedLanguage = expected.RootElement.TryGetProperty("defaultLanguage", out var language)
? language.GetString()
: null;
Assert.Equal(expectedLanguage, details.GetProperty("defaultLanguage").GetString());
var expectedPaths = expected.RootElement.TryGetProperty("fullTextPaths", out var expectedPathArray)
? expectedPathArray.EnumerateArray().ToArray()
: [];
var paths = details.GetProperty("fullTextPaths").EnumerateArray().ToArray();
Assert.Equal(expectedPaths.Length, paths.Length);
for (var i = 0; i < paths.Length; i++)
{
Assert.Equal(expectedPaths[i].GetProperty("path").GetString(), paths[i].GetProperty("path").GetString());
var expectedPathLanguage = expectedPaths[i].TryGetProperty("language", out var pathLanguage)
? pathLanguage.GetString()
: null;
Assert.Equal(expectedPathLanguage, paths[i].GetProperty("language").GetString());
}

Assert.Equal(details.GetProperty("fullTextPaths").GetRawText(), root.GetProperty("fullTextPolicy").GetRawText());
}

[Theory]
[InlineData(false, 403)]
[InlineData(true, 403)]
[InlineData(false, 501)]
[InlineData(true, 501)]
public async Task Info_MetadataReadFailureIsNotReportedAsAbsentPolicy(bool arm, int status)
{
using var shell = ShellInterpreter.CreateInstance();
shell.State = CreateState(arm, null, status);
var command = new InfoCommand { Database = "db", Container = "Items", Format = "json" };
var state = new CommandState();

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

Assert.Contains("metadata unavailable", error.Message, StringComparison.Ordinal);
Assert.Null(state.Result);
}

private static ConnectedState CreateState(bool arm, string? policy, int? failureStatus = null)
{
var resourceJson = $$"""
{"id":"Items","partitionKey":{"paths":["/id"],"kind":"Hash"}{{(policy is null ? string.Empty : ",\"fullTextPolicy\":" + policy)}}}
""";
var client = Substitute.For<CosmosClient>();
var database = Substitute.For<Database>();
var container = Substitute.For<Container>();
client.GetDatabase("db").Returns(database);
database.GetContainer("Items").Returns(container);
var databaseResponse = Substitute.For<DatabaseResponse>();
databaseResponse.StatusCode.Returns(HttpStatusCode.OK);
database.ReadAsync(Arg.Any<RequestOptions>(), Arg.Any<CancellationToken>()).Returns(databaseResponse);
var metadata = Substitute.For<ContainerResponse>();
metadata.Resource.Returns(JsonConvert.DeserializeObject<ContainerProperties>(resourceJson)!);
metadata.Headers.Returns(new Headers());
metadata.StatusCode.Returns(HttpStatusCode.OK);
if (!arm && failureStatus.HasValue)
{
container.ReadContainerAsync(Arg.Any<ContainerRequestOptions>(), Arg.Any<CancellationToken>())
.Returns(
_ => Task.FromResult(metadata),
_ => Task.FromException<ContainerResponse>(new CosmosException("metadata unavailable", (HttpStatusCode)failureStatus.Value, 0, "test", 0)));
}
else
{
container.ReadContainerAsync(Arg.Any<ContainerRequestOptions>(), Arg.Any<CancellationToken>()).Returns(metadata);
}

container.ReadThroughputAsync(Arg.Any<RequestOptions>(), Arg.Any<CancellationToken>())
.Returns<Task<ThroughputResponse>>(_ => throw new CosmosException("not configured", HttpStatusCode.NotFound, 0, "test", 0));
if (!arm)
{
return new ConnectedState(client);
}

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);
armDatabase.GetCosmosDBSqlContainers().Returns(containers);
databases.GetIfExistsAsync("db", Arg.Any<CancellationToken>())
.Returns(Task.FromResult<NullableResponse<CosmosDBSqlDatabaseResource>>(Response.FromValue(armDatabase, Substitute.For<Response>())));
armContainer.Data.Returns(CosmosArmResourceProvider.ReadArmModel<CosmosDBSqlContainerData>(
"""{"properties":{"resource":""" + resourceJson + "}}"));
NullableResponse<CosmosDBSqlContainerResource> containerResponse = Response.FromValue(armContainer, Substitute.For<Response>());
if (failureStatus.HasValue)
{
containers.GetIfExistsAsync("Items", Arg.Any<CancellationToken>())
.Returns(
_ => Task.FromResult(containerResponse),
_ => Task.FromException<NullableResponse<CosmosDBSqlContainerResource>>(new RequestFailedException(failureStatus.Value, "metadata unavailable")));
}
else
{
containers.GetIfExistsAsync("Items", Arg.Any<CancellationToken>())
.Returns(Task.FromResult(containerResponse));
}

var throughput = Substitute.For<CosmosDBSqlContainerThroughputSettingResource>();
armContainer.GetCosmosDBSqlContainerThroughputSetting().Returns(throughput);
throughput.GetAsync(Arg.Any<CancellationToken>())
.Returns<Task<Azure.Response<CosmosDBSqlContainerThroughputSettingResource>>>(_ => throw new RequestFailedException(404, "not configured"));
var id = new ResourceIdentifier("/subscriptions/s/resourceGroups/rg/providers/Microsoft.DocumentDB/databaseAccounts/a");
var context = new ArmCosmosContext(Substitute.For<ArmClient>(), id, "s", "rg", "a", new Uri("https://a.documents.azure.com"), account);
return new ConnectedState(client, context);
}
}
6 changes: 6 additions & 0 deletions CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,7 @@ private async Task<CommandState> ShowContainerSettingsAsync(ShellInterpreter she
ShellInterpreter.Instance.Output.MarkupLine(ShellMessageKind.Result, Theme.FormatSectionHeader(MessageService.GetString("command-settings-fulltext-title")));
}

mcpTable["fullTextPolicyDetails"] = null;
if (view.FullTextPolicy is { } fullText)
{
Table? fullTextTable = null;
Expand Down Expand Up @@ -869,6 +870,11 @@ private async Task<CommandState> ShowContainerSettingsAsync(ShellInterpreter she
}

mcpTable["fullTextPolicy"] = mcpPaths;
mcpTable["fullTextPolicyDetails"] = new Dictionary<string, object?>
{
{ "defaultLanguage", fullText.DefaultLanguage },
{ "fullTextPaths", mcpPaths },
};
if (fullTextTable is not null)
{
fullTextTable.HideHeaders();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,14 @@ public async Task<ContainerSettingsView> GetContainerSettingsAsync(string databa
}

var armResource = resource.Data.Resource;
ContainerFullTextPolicyView? fullTextView = null;
if (armResource.FullTextPolicy is { } fullTextPolicy)
{
fullTextView = new ContainerFullTextPolicyView(
fullTextPolicy.DefaultLanguage,
fullTextPolicy.FullTextPaths.Select(p => new ContainerFullTextPathView(p.Path, p.Language)).ToArray());
}

ContainerIndexingPolicyView? indexingView = null;
if (armResource.IndexingPolicy is { } indexingPolicy)
{
Expand All @@ -156,7 +164,7 @@ public async Task<ContainerSettingsView> GetContainerSettingsAsync(string databa
throughputAvailability,
throughputError,
GeospatialType: null,
FullTextPolicy: null,
FullTextPolicy: fullTextView,
IndexingPolicy: indexingView);
}

Expand Down
13 changes: 13 additions & 0 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -1890,6 +1890,19 @@ Manager control-plane operations do not consume Cosmos DB request units. When
`$sessionRequestChargeWarningThreshold` is positive, `session.requestChargeWarningThreshold` reports the
configured warning threshold. This command is read-only.

Container JSON and MCP results include `fullTextPolicyDetails`, containing the
observed `defaultLanguage` and `fullTextPaths` entries (`path` and `language`).
This is available on both data-plane and Azure Resource Manager connections.
An observed absent policy is represented by `fullTextPolicyDetails: null`; a
failed or unsupported container-metadata read returns an error, not an absent
policy. A configured policy with no paths still returns an object with an empty
`fullTextPaths` array.

For compatibility, `fullTextPolicy` retains its existing path-array shape and
is omitted when no policy is present. Consumers needing the complete policy
should use the additive `fullTextPolicyDetails` field; consumers requiring an
exact set of JSON fields must accept this new field.

### help

Show help for commands.
Expand Down
Loading