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
2 changes: 1 addition & 1 deletion CosmosDBShell.Tests/CommandTests/BulkCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -999,7 +999,7 @@ public async Task JournalFailureDuringSettlementStillDrainsEveryStartedWrite()

var actual = await Assert.ThrowsAsync<UnauthorizedAccessException>(async () => await run.WaitAsync(timeout.Token));
Assert.Same(expected, actual);
Assert.Equal([0L, 1L], settled);
Assert.Equal([0L, 1L], settled.Order());
Assert.Equal(2, summary.Succeeded);
}

Expand Down
192 changes: 192 additions & 0 deletions CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------

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.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_PreservesCompletePolicyAcrossBackends(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());
}

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

Assert.Equal(JsonValueKind.Object, details.ValueKind);
Assert.Equal(2, details.EnumerateObject().Count());
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());
}
}

[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);
container.ReadContainerAsync(Arg.Any<ContainerRequestOptions>(), Arg.Any<CancellationToken>()).Returns(metadata);
if (!arm && failureStatus is int dataPlaneStatusCode)
{
container.ReadContainerStreamAsync(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Task.FromException<ResponseMessage>(new CosmosException("metadata unavailable", (HttpStatusCode)dataPlaneStatusCode, 0, "test", 0)));
}
else
{
container.ReadContainerStreamAsync(cancellationToken: Arg.Any<CancellationToken>())
.Returns(_ => new ResponseMessage(HttpStatusCode.OK) { Content = new MemoryStream(Encoding.UTF8.GetBytes(resourceJson)) });
}

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 is int armStatusCode)
{
containers.GetIfExistsAsync("Items", Arg.Any<CancellationToken>())
.Returns(
_ => Task.FromResult(containerResponse),
_ => Task.FromException<NullableResponse<CosmosDBSqlContainerResource>>(new RequestFailedException(armStatusCode, "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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,7 @@ private async Task<CommandState> ShowContainerSettingsAsync(ShellInterpreter she
ShellInterpreter.Instance.Output.MarkupLine(ShellMessageKind.Result, Theme.FormatSectionHeader(MessageService.GetString("command-settings-fulltext-title")));
}

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

mcpTable["fullTextPolicy"] = mcpPaths;
mcpTable["fullTextPolicy"] = 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 @@ -135,6 +135,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 @@ -157,7 +165,7 @@ public async Task<ContainerSettingsView> GetContainerSettingsAsync(string databa
throughputAvailability,
throughputError,
GeospatialType: null,
FullTextPolicy: null,
FullTextPolicy: fullTextView,
IndexingPolicy: indexingView,
UniqueKeyPolicy: ContainerUniqueKeyPolicyView.FromResource(JObject.Parse(CosmosArmResourceProvider.WriteArmModel(armResource))));
}
Expand Down
11 changes: 11 additions & 0 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -1896,6 +1896,17 @@ 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 a `fullTextPolicy` object, 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 `fullTextPolicy: 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.

`fullTextPolicy` replaces the previous path-array shape. Consumers that iterated
over `fullTextPolicy` directly should now use `fullTextPolicy.fullTextPaths`.

### help

Show help for commands.
Expand Down
Loading