diff --git a/.github/agents/msdata-direct-sync-agent.agent.md b/.github/agents/msdata-direct-sync-agent.agent.md new file mode 100644 index 0000000000..2bffc3cfbb --- /dev/null +++ b/.github/agents/msdata-direct-sync-agent.agent.md @@ -0,0 +1,490 @@ +# Copilot Agent: msdata/direct Branch Sync +## Azure Cosmos DB .NET SDK (azure-cosmos-dotnet-v3) + +--- + +## Quick Start Prompt + +**Copy-paste this prompt to start the sync workflow:** + +``` +Follow the msdata/direct sync agent plan in .github/agents/msdata-direct-sync-agent.agent.md + +Sync the msdata/direct branch with the latest v3 master and msdata direct codebase. +``` + +**What the agent will do:** +1. Verify environment setup (git, .NET SDK, repo clones) +2. Prompt for msdata CosmosDB repo path +3. Create feature branch from `msdata/direct` +4. Merge latest `master` into feature branch +5. Run `msdata_sync.ps1` to sync direct package files +6. **Verify sync completeness** — scan msdata source dirs for files missed by the script and auto-copy them +7. Build and validate +8. Create PR to `msdata/direct` with proper formatting +9. Monitor CI pipeline + +--- + +## 0. Prerequisites + +### 0.1 Required Tools + +```yaml +required_tools: + git: + verify: "git --version" + minimum: "2.x" + + dotnet_sdk: + verify: "dotnet --version" + minimum: "8.0" + + gh_cli: + verify: "gh auth status" + purpose: "PR creation and monitoring" + setup: "gh auth login --web" + + powershell: + verify: "$PSVersionTable.PSVersion" + minimum: "5.1" +``` + +### 0.2 Required Repository Clones + +```yaml +required_repos: + azure_cosmos_dotnet_v3: + url: "https://github.com/Azure/azure-cosmos-dotnet-v3.git" + required_branches: + - master + - msdata/direct + verify: "git branch -a | Select-String 'msdata/direct'" + + msdata_cosmosdb: + description: "Internal CosmosDB repository (msdata)" + note: "User will be prompted for local path at runtime" + required_branch: "master" + verify: "Test-Path " +``` + +### 0.3 Verification Checklist + +```markdown +## Pre-Sync Verification + +- [ ] git installed and configured: `git config user.name` +- [ ] .NET SDK installed: `dotnet --version` +- [ ] gh CLI authenticated: `gh auth status` +- [ ] v3 repo cloned with msdata/direct branch available +- [ ] msdata CosmosDB repo cloned and on master branch +``` + +--- + +## 1. Core Principles + +> ⚠️ **These principles apply to ALL phases of the sync workflow.** + +```yaml +sync_principles: + rules: + - "ALWAYS verify each phase before proceeding to the next" + - "ALWAYS accept incoming master changes when resolving merge conflicts" + - "NEVER force-push to msdata/direct directly" + - "ALWAYS create PRs as draft first" + - "ALWAYS run a clean build before creating the PR" + - "Prompt user for input when paths or decisions are needed" + + evidence_required: + merge_complete: "Git merge output showing success or resolved conflicts" + sync_complete: "msdata_sync.ps1 output showing all files copied" + build_passed: "dotnet build output showing 'Build succeeded. 0 Error(s)'" + pr_created: "PR URL from gh pr create" +``` + +--- + +## 2. Workflow Phases + +### Phase 1: Environment Setup & Validation + +**Goal:** Ensure all prerequisites are met and gather required user input. + +```yaml +phase_1_steps: + step_1_verify_tools: + commands: + - "git --version" + - "dotnet --version" + - "gh auth status" + action: "If any tool is missing, guide user through installation" + + step_2_verify_v3_repo: + commands: + - "git remote -v" + - "git fetch origin --quiet" + - "git branch -a | Select-String 'msdata/direct'" + verify: "origin points to Azure/azure-cosmos-dotnet-v3 and msdata/direct exists" + + step_3_prompt_msdata_path: + action: "Ask user for local path to msdata CosmosDB repo" + question: "What is the local path to your msdata CosmosDB repository clone?" + examples: + - "Q:\\CosmosDB" + - "C:\\repos\\CosmosDB" + - "E:\\src\\CosmosDB" + validation: "Test-Path && Test-Path \\sdk" + + step_4_verify_msdata_repo: + commands: + - "cd && git status" + - "cd && git branch --show-current" + action: "Ensure msdata repo is on master and up to date" + fix: "cd && git checkout master && git pull" +``` + +### Phase 2: Branch Preparation + +**Goal:** Create a feature branch from `msdata/direct` and merge latest `master`. + +```yaml +phase_2_steps: + step_1_update_branches: + commands: + - "git fetch origin master:master --quiet" + - "git fetch origin msdata/direct --quiet" + verify: "Both branches are up to date with remote" + + step_2_create_feature_branch: + description: "Create feature branch from msdata/direct" + naming_convention: "users//update_msdata_direct_" + commands: + - "git checkout msdata/direct" + - 'git checkout -b users//update_msdata_direct_' + example: "git checkout -b users/nalutripician/update_msdata_direct_03_03_2026" + get_username: "git config user.name or gh api user --jq '.login'" + get_date: "(Get-Date).ToString('MM_dd_yyyy')" + + step_3_merge_master: + commands: + - "git merge master" + expect: "Merge conflicts are likely" + + step_4_resolve_conflicts: + strategy: "Accept incoming master changes for most conflicts" + commands: + - "git checkout --theirs " + - "git add " + - "git merge --continue" + manual_review_needed: + - "Files in Microsoft.Azure.Cosmos/src/direct/ — these may need careful review" + - "Project files (.csproj) — ensure both sets of changes are preserved" + - "Directory.Build.props — version numbers need careful handling" + notes: + - "If conflicts are too complex, ask user for guidance" + - "Document all conflict resolutions for PR description" +``` + +### Phase 3: msdata File Sync + +**Goal:** Copy latest Microsoft.Azure.Cosmos.Direct files from msdata repo. + +```yaml +phase_3_steps: + step_1_locate_sync_script: + path: "Microsoft.Azure.Cosmos/src/direct/msdata_sync.ps1" + verify: "Test-Path Microsoft.Azure.Cosmos/src/direct/msdata_sync.ps1" + fallback: "If script doesn't exist after merge, check msdata/direct branch directly" + + step_2_configure_sync_script: + description: "Update msdata_sync.ps1 with user-provided msdata repo path" + action: "Replace the $baseDir value with the user-provided path" + pattern: '$baseDir = "\\CosmosDB"' + replacement: '$baseDir = ""' + important: "Do NOT commit this path change — revert after sync" + + step_3_run_sync_script: + commands: + - "cd Microsoft.Azure.Cosmos/src/direct" + - ".\\msdata_sync.ps1" + expect: "Console output showing files being copied" + success_indicator: "Script completes without Write-Error lines" + + step_4_verify_and_copy_missing_files: + description: > + IMPORTANT: msdata_sync.ps1 only copies files that already exist locally. + New files added in the msdata repo will be silently missed. This step + performs a reverse scan of all msdata source directories and auto-copies + any .cs files that are not yet present in the v3 direct/ folder. + msdata_source_directories: + - "\\Product\\SDK\\.net\\Microsoft.Azure.Cosmos.Direct\\src\\" + - "\\Product\\Microsoft.Azure.Documents\\Common\\SharedFiles\\" + - "\\Product\\Microsoft.Azure.Documents\\SharedFiles\\Routing\\" + - "\\Product\\Microsoft.Azure.Documents\\SharedFiles\\Rntbd2\\" + - "\\Product\\Microsoft.Azure.Documents\\SharedFiles\\Rntbd\\" + - "\\Product\\Microsoft.Azure.Documents\\SharedFiles\\Rntbd\\rntbdtokens\\" + - "\\Product\\SDK\\.net\\Microsoft.Azure.Documents.Client\\LegacyXPlatform\\" + - "\\Product\\Cosmos\\Core\\Core.Trace\\" + - "\\Product\\Cosmos\\Core\\Core\\Utilities\\" + - "\\Product\\Microsoft.Azure.Documents\\SharedFiles\\" + - "\\Product\\Microsoft.Azure.Documents\\SharedFiles\\Collections\\" + - "\\Product\\Microsoft.Azure.Documents\\SharedFiles\\Query\\" + - "\\Product\\Microsoft.Azure.Documents\\SharedFiles\\Management\\" + exclude_files: + - "AssemblyKeys.cs" + - "BaseTransportClient.cs" + - "CpuReaderBase.cs" + - "LinuxCpuReader.cs" + - "MemoryLoad.cs" + - "MemoryLoadHistory.cs" + - "UnsupportedCpuReader.cs" + - "WindowsCpuReader.cs" + - "msdata_sync.ps1" + procedure: + - step: "For each msdata source directory, list all .cs files" + command: 'Get-ChildItem "\\" -Filter "*.cs" -File -ErrorAction SilentlyContinue' + - step: "For each .cs file found, check if it already exists in Microsoft.Azure.Cosmos/src/direct/" + note: "Files from the Rntbd2 source dir go into the direct/rntbd2/ subdirectory" + - step: "If the file does NOT exist locally and is NOT in the exclude list, copy it" + command: 'Copy-Item "\\\\" -Destination "Microsoft.Azure.Cosmos/src/direct/" -Force' + - step: "Log every file that was auto-copied so it can be included in the PR description" + - step: "After all directories are scanned, report a summary" + success_criteria: "No new files remain uncopied from any msdata source directory" + notes: + - "The Rntbd2 directory is special — its files go to direct/rntbd2/, not direct/" + - "TransportClient.cs, RMResources.Designer.cs, and RMResources.resx are handled separately by the sync script and should be skipped in this check" + - "If any files are copied, re-run msdata_sync.ps1 afterward to ensure consistency" + - "If using the helper script, this verification runs automatically as part of the Sync phase" + + step_5_revert_script_path: + description: "Revert the $baseDir change in msdata_sync.ps1" + commands: + - "git checkout -- Microsoft.Azure.Cosmos/src/direct/msdata_sync.ps1" + verify: "git diff Microsoft.Azure.Cosmos/src/direct/msdata_sync.ps1 shows no changes" +``` + +### Phase 4: Build Validation + +**Goal:** Verify the merged and synced code builds successfully. + +```yaml +phase_4_steps: + step_1_clean_build: + command: "dotnet build Microsoft.Azure.Cosmos.sln -c Release" + expected: "Build succeeded. 0 Error(s)" + timeout: "5-10 minutes" + + step_2_fix_build_errors: + description: "If build fails, investigate and fix errors" + common_issues: + missing_files: + symptom: "CS file not found or type not defined" + fix: "Check if file was missed during sync, copy from msdata repo" + namespace_conflicts: + symptom: "Ambiguous reference or namespace conflict" + fix: "Check using statements, resolve with fully qualified names" + api_changes: + symptom: "Method signature mismatch" + fix: "Update to match latest API from master or direct" + action: "Fix errors, rebuild, repeat until clean" + + step_3_verify_build: + command: "dotnet build Microsoft.Azure.Cosmos.sln -c Release" + required: "Build MUST succeed before proceeding" + evidence: "Capture build output as proof" +``` + +### Phase 5: PR Creation & Submission + +**Goal:** Push the feature branch and create a properly formatted PR. + +```yaml +phase_5_steps: + step_1_stage_and_commit: + commands: + - "git add -A" + - 'git commit -m "[Internal] Direct package: Adds msdata/direct update from master"' + verify: "git status shows clean working tree" + + step_2_push_branch: + command: "git push origin users//update_msdata_direct_" + verify: "Push succeeds without errors" + + step_3_create_pr: + command: | + gh pr create --draft \ + --base msdata/direct \ + --title "[Internal] Direct package: Adds msdata/direct update from master" \ + --body "" + pr_description_template: | + # Pull Request Template + + ## Description + + Syncs the `msdata/direct` branch with: + - Latest `master` branch (v3 SDK changes) + - Latest `Microsoft.Azure.Cosmos.Direct` files from msdata CosmosDB repo + + ### Changes Include + - Merged latest `master` branch into `msdata/direct` + - Updated `Microsoft.Azure.Cosmos.Direct` files via `msdata_sync.ps1` + - Resolved merge conflicts (accepted master changes) + - Build validated: `dotnet build` passes + + ## Type of change + + - [x] New feature (non-breaking change which adds functionality) + + ## Validation + + - [x] Local build passes (`dotnet build Microsoft.Azure.Cosmos.sln -c Release`) + + reviewers: + - "kirillg" + - "khdang" + - "adityasa" + - "sboshra" + - "FabianMeiswinkel" + - "leminh98" + - "neildsh" + + step_4_monitor_ci: + description: "Monitor the azure-pipelines-msdata-direct.yml pipeline" + commands: + - "gh pr checks " + action: "Wait for CI to complete, investigate failures if any" + pipeline: "azure-pipelines-msdata-direct.yml" + + step_5_mark_ready: + condition: "All CI checks pass" + command: "gh pr ready " + action: "Convert from draft to ready for review" +``` + +--- + +## 3. Helper Script + +A companion PowerShell script is available at `tools/msdata-direct-sync-helper.ps1` to automate the mechanical parts of this workflow. + +```yaml +helper_script: + path: "tools/msdata-direct-sync-helper.ps1" + + usage: | + # Full automated workflow + .\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" + + # Individual phases + .\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" -Phase Setup + .\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" -Phase Branch + .\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" -Phase Sync + .\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" -Phase Build + .\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" -Phase PR + + parameters: + MsdataRepoPath: "Path to local msdata CosmosDB repo clone (required)" + Phase: "Run a specific phase only (optional; default runs all)" + GitHubUsername: "GitHub username for branch naming (optional; auto-detected)" + SkipBuild: "Skip build validation phase (optional; not recommended)" +``` + +--- + +## 4. Troubleshooting + +### Common Merge Conflicts + +```yaml +merge_conflicts: + directory_build_props: + description: "Version number conflicts between master and msdata/direct" + resolution: "Accept master version numbers, they are the source of truth" + + csproj_files: + description: "Project file conflicts from both sides adding references" + resolution: "Manually merge to include all references from both sides" + + direct_files: + description: "Files in src/direct/ modified on both branches" + resolution: "Accept msdata/direct version — these will be overwritten by msdata_sync.ps1" +``` + +### Build Failures After Sync + +```yaml +build_failures: + missing_type_or_namespace: + symptom: "error CS0246: The type or namespace name 'X' could not be found" + causes: + - "File not copied by msdata_sync.ps1" + - "New file added in msdata but not in sync script" + fix: "Locate file in msdata repo, copy manually to src/direct/" + + duplicate_definitions: + symptom: "error CS0111: Type already defines a member" + causes: + - "Same file exists in both master and direct" + fix: "Remove the duplicate, keep the direct version" + + api_incompatibility: + symptom: "error CS1501: No overload for method" + causes: + - "Direct package API changed" + fix: "Update calling code to match new API signature" +``` + +### msdata_sync.ps1 Errors + +```yaml +sync_script_errors: + file_not_found: + symptom: "Write-Error: False" + cause: "File exists in sync script list but not in msdata repo" + fix: "File may have been renamed or removed — check msdata repo history" + + permission_denied: + symptom: "Access to the path is denied" + cause: "File is read-only or locked" + fix: "Close any editors, remove read-only flag: attrib -r " + + path_not_found: + symptom: "Cannot find path 'Q:\\CosmosDB\\...'" + cause: "$baseDir not set correctly" + fix: "Verify msdata repo path and update $baseDir in script" +``` + +--- + +## 5. Sample Pull Requests + +Reference these PRs for expected format and scope: + +| PR | Title | Date | Scope | +|----|-------|------|-------| +| [#5612](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5612) | [Internal] Direct package: Adds msdata/direct update from master | Feb 2026 | 545 files, 76K additions | +| [#3776](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/3776) | [Internal] Msdata/Direct: Refactors msdata/direct with v3 master and Direct v3.30.4 | Mar 2023 | 155 files, 13K additions | +| [#3726](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/3726) | [Internal] Msdata/Direct: Refactors msdata branch with latest v3 and direct release | Feb 2023 | 361 files, 27K additions | + +--- + +## 6. CI Pipeline + +The `azure-pipelines-msdata-direct.yml` pipeline runs automatically on PRs targeting `msdata/direct*` branches. It includes: + +```yaml +ci_pipeline: + trigger: "PR to msdata/direct*" + jobs: + - "Static analysis tools" + - "CTL build" + - "Samples build" + - "msdata test suite (Release)" + - "Internal build" + - "Preview msdata build" + - "Thin client build" + variables: + test_filter: '--filter "TestCategory!=Flaky & TestCategory!=Quarantine & TestCategory!=Functional"' + vm_image: "windows-latest" +``` diff --git a/Directory.Build.props b/Directory.Build.props index befacdace9..40f6d2ad35 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,7 +1,7 @@ - 3.57.0 - 3.58.0 + 3.58.0 + 3.59.0 preview.0 3.42.2 1.0.0 diff --git a/Microsoft.Azure.Cosmos/contracts/API_3.58.0.txt b/Microsoft.Azure.Cosmos/contracts/API_3.58.0.txt new file mode 100644 index 0000000000..1b74a6908e --- /dev/null +++ b/Microsoft.Azure.Cosmos/contracts/API_3.58.0.txt @@ -0,0 +1,1774 @@ +namespace Microsoft.Azure.Cosmos +{ + public class AccountConsistency + { + public AccountConsistency(); + public ConsistencyLevel DefaultConsistencyLevel { get; } + public int MaxStalenessIntervalInSeconds { get; } + public int MaxStalenessPrefix { get; } + } + public class AccountProperties + { + public AccountConsistency Consistency { get; } + public string ETag { get; } + public string Id { get; } + public IEnumerable ReadableRegions { get; } + public IEnumerable WritableRegions { get; } + } + public class AccountRegion + { + public AccountRegion(); + public string Endpoint { get; } + public string Name { get; } + } + public abstract class AvailabilityStrategy + { + public static AvailabilityStrategy CrossRegionHedgingStrategy(TimeSpan threshold, Nullable thresholdStep, bool enableMultiWriteRegionHedge=false); + public static AvailabilityStrategy DisabledStrategy(); + } + public sealed class BoundingBoxProperties + { + public BoundingBoxProperties(); + public double Xmax { get; set; } + public double Xmin { get; set; } + public double Ymax { get; set; } + public double Ymin { get; set; } + } + public abstract class ChangeFeedEstimator + { + protected ChangeFeedEstimator(); + public abstract FeedIterator GetCurrentStateIterator(ChangeFeedEstimatorRequestOptions changeFeedEstimatorRequestOptions=null); + } + public sealed class ChangeFeedEstimatorRequestOptions + { + public ChangeFeedEstimatorRequestOptions(); + public Nullable MaxItemCount { get; set; } + } + public abstract class ChangeFeedMode + { + public static ChangeFeedMode Incremental { get; } + public static ChangeFeedMode LatestVersion { get; } + } + public abstract class ChangeFeedProcessor + { + protected ChangeFeedProcessor(); + public abstract Task StartAsync(); + public abstract Task StopAsync(); + } + public class ChangeFeedProcessorBuilder + { + public ChangeFeedProcessor Build(); + public ChangeFeedProcessorBuilder WithErrorNotification(Container.ChangeFeedMonitorErrorDelegate errorDelegate); + public virtual ChangeFeedProcessorBuilder WithInMemoryLeaseContainer(); + public ChangeFeedProcessorBuilder WithInstanceName(string instanceName); + public ChangeFeedProcessorBuilder WithLeaseAcquireNotification(Container.ChangeFeedMonitorLeaseAcquireDelegate acquireDelegate); + public ChangeFeedProcessorBuilder WithLeaseConfiguration(Nullable acquireInterval=default(Nullable), Nullable expirationInterval=default(Nullable), Nullable renewInterval=default(Nullable)); + public ChangeFeedProcessorBuilder WithLeaseContainer(Container leaseContainer); + public ChangeFeedProcessorBuilder WithLeaseReleaseNotification(Container.ChangeFeedMonitorLeaseReleaseDelegate releaseDelegate); + public ChangeFeedProcessorBuilder WithMaxItems(int maxItemCount); + public ChangeFeedProcessorBuilder WithPollInterval(TimeSpan pollInterval); + public ChangeFeedProcessorBuilder WithStartTime(DateTime startTime); + } + public abstract class ChangeFeedProcessorContext + { + protected ChangeFeedProcessorContext(); + public abstract CosmosDiagnostics Diagnostics { get; } + public abstract FeedRange FeedRange { get; } + public abstract Headers Headers { get; } + public abstract string LeaseToken { get; } + } + public sealed class ChangeFeedProcessorState + { + public ChangeFeedProcessorState(string leaseToken, long estimatedLag, string instanceName); + public long EstimatedLag { get; } + public string InstanceName { get; } + public string LeaseToken { get; } + } + public class ChangeFeedProcessorUserException : Exception + { + public ChangeFeedProcessorUserException(Exception originalException, ChangeFeedProcessorContext context); + protected ChangeFeedProcessorUserException(SerializationInfo info, StreamingContext context); + public ChangeFeedProcessorContext ChangeFeedProcessorContext { get; } + public override void GetObjectData(SerializationInfo info, StreamingContext context); + } + public sealed class ChangeFeedRequestOptions : RequestOptions + { + public ChangeFeedRequestOptions(); + public new string IfMatchEtag { get; set; } + public new string IfNoneMatchEtag { get; set; } + public Nullable PageSizeHint { get; set; } + } + public abstract class ChangeFeedStartFrom + { + public static ChangeFeedStartFrom Beginning(); + public static ChangeFeedStartFrom Beginning(FeedRange feedRange); + public static ChangeFeedStartFrom ContinuationToken(string continuationToken); + public static ChangeFeedStartFrom Now(); + public static ChangeFeedStartFrom Now(FeedRange feedRange); + public static ChangeFeedStartFrom Time(DateTime dateTimeUtc); + public static ChangeFeedStartFrom Time(DateTime dateTimeUtc, FeedRange feedRange); + } + public sealed class ClientEncryptionIncludedPath + { + public ClientEncryptionIncludedPath(); + public string ClientEncryptionKeyId { get; set; } + public string EncryptionAlgorithm { get; set; } + public string EncryptionType { get; set; } + public string Path { get; set; } + } + public abstract class ClientEncryptionKey + { + protected ClientEncryptionKey(); + public abstract string Id { get; } + public abstract Task ReadAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceAsync(ClientEncryptionKeyProperties clientEncryptionKeyProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + } + public class ClientEncryptionKeyProperties : IEquatable + { + protected ClientEncryptionKeyProperties(); + public ClientEncryptionKeyProperties(string id, string encryptionAlgorithm, byte[] wrappedDataEncryptionKey, EncryptionKeyWrapMetadata encryptionKeyWrapMetadata); + public Nullable CreatedTime { get; } + public string EncryptionAlgorithm { get; } + public EncryptionKeyWrapMetadata EncryptionKeyWrapMetadata { get; } + public string ETag { get; } + public string Id { get; } + public Nullable LastModified { get; } + public virtual string SelfLink { get; } + public byte[] WrappedDataEncryptionKey { get; } + public bool Equals(ClientEncryptionKeyProperties other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public class ClientEncryptionKeyResponse : Response + { + protected ClientEncryptionKeyResponse(); + public override string ActivityId { get; } + public virtual ClientEncryptionKey ClientEncryptionKey { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override ClientEncryptionKeyProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator ClientEncryptionKey (ClientEncryptionKeyResponse response); + } + public sealed class ClientEncryptionPolicy + { + public ClientEncryptionPolicy(IEnumerable includedPaths); + public ClientEncryptionPolicy(IEnumerable includedPaths, int policyFormatVersion); + public IEnumerable IncludedPaths { get; } + public int PolicyFormatVersion { get; } + } + public sealed class CompositePath + { + public CompositePath(); + public CompositePathSortOrder Order { get; set; } + public string Path { get; set; } + } + public enum CompositePathSortOrder + { + Ascending = 0, + Descending = 1, + } + public sealed class ComputedProperty + { + public ComputedProperty(); + public string Name { get; set; } + public string Query { get; set; } + } + public class ConflictProperties + { + public ConflictProperties(); + public string Id { get; } + public OperationKind OperationKind { get; } + public string SelfLink { get; } + } + public enum ConflictResolutionMode + { + Custom = 1, + LastWriterWins = 0, + } + public class ConflictResolutionPolicy + { + public ConflictResolutionPolicy(); + public ConflictResolutionMode Mode { get; set; } + public string ResolutionPath { get; set; } + public string ResolutionProcedure { get; set; } + } + public abstract class Conflicts + { + protected Conflicts(); + public abstract Task DeleteAsync(ConflictProperties conflict, PartitionKey partitionKey, CancellationToken cancellationToken=default(CancellationToken)); + public abstract FeedIterator GetConflictQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetConflictQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetConflictQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetConflictQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract T ReadConflictContent(ConflictProperties conflict); + public abstract Task> ReadCurrentAsync(ConflictProperties conflict, PartitionKey partitionKey, CancellationToken cancellationToken=default(CancellationToken)); + } + public enum ConnectionMode + { + Direct = 1, + Gateway = 0, + } + public enum ConsistencyLevel + { + BoundedStaleness = 1, + ConsistentPrefix = 4, + Eventual = 3, + Session = 2, + Strong = 0, + } + public abstract class Container + { + protected Container(); + public abstract Conflicts Conflicts { get; } + public abstract Database Database { get; } + public abstract string Id { get; } + public abstract Scripts Scripts { get; } + public abstract Task> CreateItemAsync(T item, Nullable partitionKey=default(Nullable), ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateItemStreamAsync(Stream streamPayload, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract TransactionalBatch CreateTransactionalBatch(PartitionKey partitionKey); + public virtual Task DeleteAllItemsByPartitionKeyStreamAsync(PartitionKey partitionKey, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteContainerAsync(ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteContainerStreamAsync(ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> DeleteItemAsync(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteItemStreamAsync(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract ChangeFeedEstimator GetChangeFeedEstimator(string processorName, Container leaseContainer); + public abstract ChangeFeedProcessorBuilder GetChangeFeedEstimatorBuilder(string processorName, Container.ChangesEstimationHandler estimationDelegate, Nullable estimationPeriod=default(Nullable)); + public abstract FeedIterator GetChangeFeedIterator(ChangeFeedStartFrom changeFeedStartFrom, ChangeFeedMode changeFeedMode, ChangeFeedRequestOptions changeFeedRequestOptions=null); + public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder(string processorName, Container.ChangeFeedStreamHandler onChangesDelegate); + public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilderWithManualCheckpoint(string processorName, Container.ChangeFeedStreamHandlerWithManualCheckpoint onChangesDelegate); + public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilderWithManualCheckpoint(string processorName, Container.ChangeFeedHandlerWithManualCheckpoint onChangesDelegate); + public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder(string processorName, Container.ChangeFeedHandler onChangesDelegate); + public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder(string processorName, Container.ChangesHandler onChangesDelegate); + public abstract FeedIterator GetChangeFeedStreamIterator(ChangeFeedStartFrom changeFeedStartFrom, ChangeFeedMode changeFeedMode, ChangeFeedRequestOptions changeFeedRequestOptions=null); + public abstract Task> GetFeedRangesAsync(CancellationToken cancellationToken=default(CancellationToken)); + public abstract IOrderedQueryable GetItemLinqQueryable(bool allowSynchronousQueryExecution=false, string continuationToken=null, QueryRequestOptions requestOptions=null, CosmosLinqSerializerOptions linqSerializerOptions=null); + public abstract FeedIterator GetItemQueryIterator(FeedRange feedRange, QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetItemQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetItemQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetItemQueryStreamIterator(FeedRange feedRange, QueryDefinition queryDefinition, string continuationToken, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetItemQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetItemQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract Task> PatchItemAsync(string id, PartitionKey partitionKey, IReadOnlyList patchOperations, PatchItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task PatchItemStreamAsync(string id, PartitionKey partitionKey, IReadOnlyList patchOperations, PatchItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadContainerAsync(ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadContainerStreamAsync(ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ReadItemAsync(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadItemStreamAsync(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ReadManyItemsAsync(IReadOnlyList> items, ReadManyRequestOptions readManyRequestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadManyItemsStreamAsync(IReadOnlyList> items, ReadManyRequestOptions readManyRequestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadThroughputAsync(RequestOptions requestOptions, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ReadThroughputAsync(CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceContainerAsync(ContainerProperties containerProperties, ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceContainerStreamAsync(ContainerProperties containerProperties, ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ReplaceItemAsync(T item, string id, Nullable partitionKey=default(Nullable), ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceItemStreamAsync(Stream streamPayload, string id, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceThroughputAsync(ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceThroughputAsync(int throughput, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> UpsertItemAsync(T item, Nullable partitionKey=default(Nullable), ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task UpsertItemStreamAsync(Stream streamPayload, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public delegate Task ChangeFeedHandlerWithManualCheckpoint(ChangeFeedProcessorContext context, IReadOnlyCollection changes, Func checkpointAsync, CancellationToken cancellationToken); + public delegate Task ChangeFeedHandler(ChangeFeedProcessorContext context, IReadOnlyCollection changes, CancellationToken cancellationToken); + public delegate Task ChangeFeedMonitorErrorDelegate(string leaseToken, Exception exception); + public delegate Task ChangeFeedMonitorLeaseAcquireDelegate(string leaseToken); + public delegate Task ChangeFeedMonitorLeaseReleaseDelegate(string leaseToken); + public delegate Task ChangeFeedStreamHandler(ChangeFeedProcessorContext context, Stream changes, CancellationToken cancellationToken); + public delegate Task ChangeFeedStreamHandlerWithManualCheckpoint(ChangeFeedProcessorContext context, Stream changes, Func checkpointAsync, CancellationToken cancellationToken); + public delegate Task ChangesEstimationHandler(long estimatedPendingChanges, CancellationToken cancellationToken); + public delegate Task ChangesHandler(IReadOnlyCollection changes, CancellationToken cancellationToken); + } + public class ContainerProperties + { + public ContainerProperties(); + public ContainerProperties(string id, IReadOnlyList partitionKeyPaths); + public ContainerProperties(string id, string partitionKeyPath); + public Nullable AnalyticalStoreTimeToLiveInSeconds { get; set; } + public ClientEncryptionPolicy ClientEncryptionPolicy { get; set; } + public Collection ComputedProperties { get; set; } + public ConflictResolutionPolicy ConflictResolutionPolicy { get; set; } + public Nullable DefaultTimeToLive { get; set; } + public string ETag { get; } + public FullTextPolicy FullTextPolicy { get; set; } + public GeospatialConfig GeospatialConfig { get; set; } + public string Id { get; set; } + public IndexingPolicy IndexingPolicy { get; set; } + public Nullable LastModified { get; } + public Nullable PartitionKeyDefinitionVersion { get; set; } + public string PartitionKeyPath { get; set; } + public IReadOnlyList PartitionKeyPaths { get; set; } + public string SelfLink { get; } + public string TimeToLivePropertyPath { get; set; } + public UniqueKeyPolicy UniqueKeyPolicy { get; set; } + public VectorEmbeddingPolicy VectorEmbeddingPolicy { get; set; } + } + public class ContainerRequestOptions : RequestOptions + { + public ContainerRequestOptions(); + public bool PopulateQuotaInfo { get; set; } + } + public class ContainerResponse : Response + { + protected ContainerResponse(); + public override string ActivityId { get; } + public virtual Container Container { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override ContainerProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator Container (ContainerResponse response); + } + public class CosmosClient : IDisposable + { + protected CosmosClient(); + public CosmosClient(string accountEndpoint, AzureKeyCredential authKeyOrResourceTokenCredential, CosmosClientOptions clientOptions=null); + public CosmosClient(string accountEndpoint, TokenCredential tokenCredential, CosmosClientOptions clientOptions=null); + public CosmosClient(string connectionString, CosmosClientOptions clientOptions=null); + public CosmosClient(string accountEndpoint, string authKeyOrResourceToken, CosmosClientOptions clientOptions=null); + public virtual CosmosClientOptions ClientOptions { get; } + public virtual Uri Endpoint { get; } + public virtual CosmosResponseFactory ResponseFactory { get; } + public static Task CreateAndInitializeAsync(string accountEndpoint, AzureKeyCredential authKeyOrResourceTokenCredential, IReadOnlyList> containers, CosmosClientOptions cosmosClientOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public static Task CreateAndInitializeAsync(string accountEndpoint, TokenCredential tokenCredential, IReadOnlyList> containers, CosmosClientOptions cosmosClientOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public static Task CreateAndInitializeAsync(string connectionString, IReadOnlyList> containers, CosmosClientOptions cosmosClientOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public static Task CreateAndInitializeAsync(string accountEndpoint, string authKeyOrResourceToken, IReadOnlyList> containers, CosmosClientOptions cosmosClientOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public virtual Task CreateDatabaseAsync(string id, ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public virtual Task CreateDatabaseAsync(string id, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public virtual Task CreateDatabaseIfNotExistsAsync(string id, ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public virtual Task CreateDatabaseIfNotExistsAsync(string id, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public virtual Task CreateDatabaseStreamAsync(DatabaseProperties databaseProperties, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public void Dispose(); + protected virtual void Dispose(bool disposing); + public virtual Container GetContainer(string databaseId, string containerId); + public virtual Database GetDatabase(string id); + public virtual FeedIterator GetDatabaseQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public virtual FeedIterator GetDatabaseQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public virtual FeedIterator GetDatabaseQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public virtual FeedIterator GetDatabaseQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public virtual Task ReadAccountAsync(); + } + public class CosmosClientOptions + { + public CosmosClientOptions(); + public IEnumerable AccountInitializationCustomEndpoints { get; set; } + public bool AllowBulkExecution { get; set; } + public string ApplicationName { get; set; } + public IReadOnlyList ApplicationPreferredRegions { get; set; } + public string ApplicationRegion { get; set; } + public AvailabilityStrategy AvailabilityStrategy { get; set; } + public ConnectionMode ConnectionMode { get; set; } + public Nullable ConsistencyLevel { get; set; } + public CosmosClientTelemetryOptions CosmosClientTelemetryOptions { get; set; } + public Collection CustomHandlers { get; } + public Nullable EnableContentResponseOnWrite { get; set; } + public bool EnableTcpConnectionEndpointRediscovery { get; set; } + public IFaultInjector FaultInjector { get; set; } + public int GatewayModeMaxConnectionLimit { get; set; } + public Func HttpClientFactory { get; set; } + public Nullable IdleTcpConnectionTimeout { get; set; } + public bool LimitToEndpoint { get; set; } + public Nullable MaxRequestsPerTcpConnection { get; set; } + public Nullable MaxRetryAttemptsOnRateLimitedRequests { get; set; } + public Nullable MaxRetryWaitTimeOnRateLimitedRequests { get; set; } + public Nullable MaxTcpConnectionsPerEndpoint { get; set; } + public Nullable OpenTcpConnectionTimeout { get; set; } + public Nullable PortReuseMode { get; set; } + public Nullable PriorityLevel { get; set; } + public TimeSpan RequestTimeout { get; set; } + public CosmosSerializer Serializer { get; set; } + public CosmosSerializationOptions SerializerOptions { get; set; } + public Func ServerCertificateCustomValidationCallback { get; set; } + public Nullable TokenCredentialBackgroundRefreshInterval { get; set; } + public JsonSerializerOptions UseSystemTextJsonSerializerWithOptions { get; set; } + public IWebProxy WebProxy { get; set; } + } + public class CosmosClientTelemetryOptions + { + public CosmosClientTelemetryOptions(); + public CosmosThresholdOptions CosmosThresholdOptions { get; set; } + public bool DisableDistributedTracing { get; set; } + public bool DisableSendingMetricsToService { get; set; } + public QueryTextMode QueryTextMode { get; set; } + } + public abstract class CosmosDiagnostics + { + protected CosmosDiagnostics(); + public virtual TimeSpan GetClientElapsedTime(); + public abstract IReadOnlyList> GetContactedRegions(); + public virtual int GetFailedRequestCount(); + public virtual ServerSideCumulativeMetrics GetQueryMetrics(); + public virtual Nullable GetStartTimeUtc(); + public abstract override string ToString(); + } + public class CosmosException : Exception, ICloneable + { + public CosmosException(string message, HttpStatusCode statusCode, int subStatusCode, string activityId, double requestCharge); + public virtual string ActivityId { get; } + public virtual CosmosDiagnostics Diagnostics { get; } + public virtual Headers Headers { get; } + public override string Message { get; } + public virtual double RequestCharge { get; } + public virtual string ResponseBody { get; } + public virtual Nullable RetryAfter { get; } + public override string StackTrace { get; } + public virtual HttpStatusCode StatusCode { get; } + public virtual int SubStatusCode { get; } + public object Clone(); + public override string ToString(); + public virtual bool TryGetHeader(string headerName, out string value); + } + public abstract class CosmosLinqSerializer : CosmosSerializer + { + protected CosmosLinqSerializer(); + public abstract string SerializeMemberName(MemberInfo memberInfo); + } + public sealed class CosmosLinqSerializerOptions + { + public CosmosLinqSerializerOptions(); + public CosmosPropertyNamingPolicy PropertyNamingPolicy { get; set; } + } + public class CosmosOperationCanceledException : OperationCanceledException, ICloneable + { + public CosmosOperationCanceledException(OperationCanceledException originalException, CosmosDiagnostics diagnostics); + protected CosmosOperationCanceledException(SerializationInfo info, StreamingContext context); + public override IDictionary Data { get; } + public CosmosDiagnostics Diagnostics { get; } + public override string HelpLink { get; set; } + public override string Message { get; } + public override string Source { get; set; } + public override string StackTrace { get; } + public object Clone(); + public override Exception GetBaseException(); + public override void GetObjectData(SerializationInfo info, StreamingContext context); + public override string ToString(); + } + public enum CosmosPropertyNamingPolicy + { + CamelCase = 1, + Default = 0, + } + public abstract class CosmosResponseFactory + { + protected CosmosResponseFactory(); + public abstract FeedResponse CreateItemFeedResponse(ResponseMessage responseMessage); + public abstract ItemResponse CreateItemResponse(ResponseMessage responseMessage); + public abstract StoredProcedureExecuteResponse CreateStoredProcedureExecuteResponse(ResponseMessage responseMessage); + } + public sealed class CosmosSerializationOptions + { + public CosmosSerializationOptions(); + public bool IgnoreNullValues { get; set; } + public bool Indented { get; set; } + public CosmosPropertyNamingPolicy PropertyNamingPolicy { get; set; } + } + public abstract class CosmosSerializer + { + protected CosmosSerializer(); + public abstract T FromStream(Stream stream); + public abstract Stream ToStream(T input); + } + public class CosmosThresholdOptions + { + public CosmosThresholdOptions(); + public TimeSpan NonPointOperationLatencyThreshold { get; set; } + public Nullable PayloadSizeThresholdInBytes { get; set; } + public TimeSpan PointOperationLatencyThreshold { get; set; } + public Nullable RequestChargeThreshold { get; set; } + } + public abstract class Database + { + protected Database(); + public abstract CosmosClient Client { get; } + public abstract string Id { get; } + public abstract Task CreateClientEncryptionKeyAsync(ClientEncryptionKeyProperties clientEncryptionKeyProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerAsync(ContainerProperties containerProperties, ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerAsync(ContainerProperties containerProperties, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerAsync(string id, string partitionKeyPath, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerIfNotExistsAsync(ContainerProperties containerProperties, ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerIfNotExistsAsync(ContainerProperties containerProperties, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerIfNotExistsAsync(string id, string partitionKeyPath, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerStreamAsync(ContainerProperties containerProperties, ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerStreamAsync(ContainerProperties containerProperties, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateUserAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract ContainerBuilder DefineContainer(string name, string partitionKeyPath); + public abstract Task DeleteAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteStreamAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract ClientEncryptionKey GetClientEncryptionKey(string id); + public abstract FeedIterator GetClientEncryptionKeyQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract Container GetContainer(string id); + public abstract FeedIterator GetContainerQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetContainerQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetContainerQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetContainerQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract User GetUser(string id); + public abstract FeedIterator GetUserQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetUserQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract Task ReadAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadStreamAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadThroughputAsync(RequestOptions requestOptions, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ReadThroughputAsync(CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceThroughputAsync(ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceThroughputAsync(int throughput, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task UpsertUserAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + } + public class DatabaseProperties + { + public DatabaseProperties(); + public DatabaseProperties(string id); + public string ETag { get; } + public string Id { get; set; } + public Nullable LastModified { get; } + public string SelfLink { get; } + } + public class DatabaseResponse : Response + { + protected DatabaseResponse(); + public override string ActivityId { get; } + public virtual Database Database { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override DatabaseProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator Database (DatabaseResponse response); + } + public enum DataType + { + LineString = 3, + MultiPolygon = 5, + Number = 0, + Point = 2, + Polygon = 4, + String = 1, + } + public class DedicatedGatewayRequestOptions + { + public DedicatedGatewayRequestOptions(); + public Nullable BypassIntegratedCache { get; set; } + public Nullable MaxIntegratedCacheStaleness { get; set; } + } + public enum DistanceFunction + { + Cosine = 1, + DotProduct = 2, + Euclidean = 0, + } + public class Embedding : IEquatable + { + public Embedding(); + public VectorDataType DataType { get; set; } + public int Dimensions { get; set; } + public DistanceFunction DistanceFunction { get; set; } + public string Path { get; set; } + public bool Equals(Embedding that); + public void ValidateEmbeddingPath(); + } + public class EncryptionKeyWrapMetadata : IEquatable + { + public EncryptionKeyWrapMetadata(EncryptionKeyWrapMetadata source); + public EncryptionKeyWrapMetadata(string type, string name, string value, string algorithm); + public string Algorithm { get; } + public string Name { get; } + public string Type { get; } + public string Value { get; } + public bool Equals(EncryptionKeyWrapMetadata other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class ExcludedPath + { + public ExcludedPath(); + public string Path { get; set; } + } + public abstract class FeedIterator : IDisposable + { + protected FeedIterator(); + public abstract bool HasMoreResults { get; } + public void Dispose(); + protected virtual void Dispose(bool disposing); + public abstract Task ReadNextAsync(CancellationToken cancellationToken=default(CancellationToken)); + } + public abstract class FeedIterator : IDisposable + { + protected FeedIterator(); + public abstract bool HasMoreResults { get; } + public void Dispose(); + protected virtual void Dispose(bool disposing); + public abstract Task> ReadNextAsync(CancellationToken cancellationToken=default(CancellationToken)); + } + public abstract class FeedRange + { + protected FeedRange(); + public static FeedRange FromJsonString(string toStringValue); + public static FeedRange FromPartitionKey(PartitionKey partitionKey); + public abstract string ToJsonString(); + } + public abstract class FeedResponse : IEnumerable, IEnumerable + { + protected FeedResponse(); + public override string ActivityId { get; } + public abstract string ContinuationToken { get; } + public abstract int Count { get; } + public override string ETag { get; } + public abstract string IndexMetrics { get; } + public virtual string QueryAdvice { get; } + public override double RequestCharge { get; } + public abstract IEnumerator GetEnumerator(); + IEnumerator System.Collections.IEnumerable.GetEnumerator(); + } + public sealed class FullTextIndexPath + { + public FullTextIndexPath(); + public string Path { get; set; } + } + public class FullTextPath : IEquatable + { + public FullTextPath(); + public string Language { get; set; } + public string Path { get; set; } + public bool Equals(FullTextPath that); + public void ValidateFullTextPath(); + } + public sealed class FullTextPolicy + { + public FullTextPolicy(); + public string DefaultLanguage { get; set; } + public Collection FullTextPaths { get; set; } + } + public enum FullTextScoreScope + { + Global = 0, + Local = 1, + } + public sealed class GeospatialConfig + { + public GeospatialConfig(); + public GeospatialConfig(GeospatialType geospatialType); + public GeospatialType GeospatialType { get; set; } + } + public enum GeospatialType + { + Geography = 0, + Geometry = 1, + } + public class Headers : IEnumerable + { + public Headers(); + public virtual string ActivityId { get; } + public virtual string ContentLength { get; set; } + public virtual string ContentType { get; } + public virtual string ContinuationToken { get; } + public virtual string ETag { get; } + public virtual string this[string headerName] { get; set; } + public virtual string Location { get; } + public virtual double RequestCharge { get; } + public virtual string Session { get; } + public virtual void Add(string headerName, IEnumerable values); + public virtual void Add(string headerName, string value); + public virtual string[] AllKeys(); + public virtual string Get(string headerName); + public virtual IEnumerator GetEnumerator(); + public virtual T GetHeaderValue(string headerName); + public virtual string GetValueOrDefault(string headerName); + public virtual void Remove(string headerName); + public virtual void Set(string headerName, string value); + IEnumerator System.Collections.IEnumerable.GetEnumerator(); + public virtual bool TryGetValue(string headerName, out string value); + } + public sealed class IncludedPath + { + public IncludedPath(); + public string Path { get; set; } + } + public enum IndexingDirective + { + Default = 0, + Exclude = 2, + Include = 1, + } + public enum IndexingMode + { + Consistent = 0, + Lazy = 1, + None = 2, + } + public sealed class IndexingPolicy + { + public IndexingPolicy(); + public bool Automatic { get; set; } + public Collection> CompositeIndexes { get; } + public Collection ExcludedPaths { get; } + public Collection FullTextIndexes { get; set; } + public Collection IncludedPaths { get; } + public IndexingMode IndexingMode { get; set; } + public Collection SpatialIndexes { get; } + public Collection VectorIndexes { get; set; } + } + public enum IndexKind + { + Hash = 0, + Range = 1, + Spatial = 2, + } + public class ItemRequestOptions : RequestOptions + { + public ItemRequestOptions(); + public Nullable ConsistencyLevel { get; set; } + public DedicatedGatewayRequestOptions DedicatedGatewayRequestOptions { get; set; } + public Nullable EnableContentResponseOnWrite { get; set; } + public Nullable IndexingDirective { get; set; } + public IEnumerable PostTriggers { get; set; } + public IEnumerable PreTriggers { get; set; } + public string SessionToken { get; set; } + } + public class ItemResponse : Response + { + protected ItemResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override T Resource { get; } + public override HttpStatusCode StatusCode { get; } + } + public enum OperationKind + { + Create = 1, + Delete = 3, + Invalid = 0, + Read = 4, + Replace = 2, + } + public struct PartitionKey : IEquatable + { + public static readonly PartitionKey None; + public static readonly PartitionKey Null; + public static readonly string SystemKeyName; + public static readonly string SystemKeyPath; + public PartitionKey(bool partitionKeyValue); + public PartitionKey(double partitionKeyValue); + public PartitionKey(string partitionKeyValue); + public bool Equals(PartitionKey other); + public override bool Equals(object obj); + public override int GetHashCode(); + public static bool operator ==(PartitionKey left, PartitionKey right); + public static bool operator !=(PartitionKey left, PartitionKey right); + public override string ToString(); + } + public sealed class PartitionKeyBuilder + { + public PartitionKeyBuilder(); + public PartitionKeyBuilder Add(bool val); + public PartitionKeyBuilder Add(double val); + public PartitionKeyBuilder Add(string val); + public PartitionKeyBuilder AddNoneType(); + public PartitionKeyBuilder AddNullValue(); + public PartitionKey Build(); + } + public enum PartitionKeyDefinitionVersion + { + V1 = 1, + V2 = 2, + } + public sealed class PatchItemRequestOptions : ItemRequestOptions + { + public PatchItemRequestOptions(); + public string FilterPredicate { get; set; } + } + public abstract class PatchOperation + { + protected PatchOperation(); + public virtual string From { get; set; } + public abstract PatchOperationType OperationType { get; } + public abstract string Path { get; } + public static PatchOperation Add(string path, T value); + public static PatchOperation Increment(string path, double value); + public static PatchOperation Increment(string path, long value); + public static PatchOperation Move(string from, string path); + public static PatchOperation Remove(string path); + public static PatchOperation Replace(string path, T value); + public static PatchOperation Set(string path, T value); + public virtual bool TrySerializeValueParameter(CosmosSerializer cosmosSerializer, out Stream valueParam); + } + public enum PatchOperationType + { + Add = 0, + Increment = 4, + Move = 5, + Remove = 1, + Replace = 2, + Set = 3, + } + public abstract class PatchOperation : PatchOperation + { + protected PatchOperation(); + public abstract T Value { get; } + } + public abstract class Permission + { + protected Permission(); + public abstract string Id { get; } + public abstract Task DeleteAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadAsync(Nullable tokenExpiryInSeconds=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceAsync(PermissionProperties permissionProperties, Nullable tokenExpiryInSeconds=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + } + public enum PermissionMode : byte + { + All = (byte)2, + Read = (byte)1, + } + public class PermissionProperties + { + public PermissionProperties(string id, PermissionMode permissionMode, Container container, PartitionKey resourcePartitionKey, string itemId); + public PermissionProperties(string id, PermissionMode permissionMode, Container container, Nullable resourcePartitionKey=default(Nullable)); + public string ETag { get; } + public string Id { get; } + public Nullable LastModified { get; } + public PermissionMode PermissionMode { get; } + public Nullable ResourcePartitionKey { get; set; } + public string ResourceUri { get; } + public string SelfLink { get; } + public string Token { get; } + } + public class PermissionResponse : Response + { + protected PermissionResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public virtual Permission Permission { get; } + public override double RequestCharge { get; } + public override PermissionProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator Permission (PermissionResponse response); + } + public enum PortReuseMode + { + PrivatePortPool = 1, + ReuseUnicastPort = 0, + } + public enum PriorityLevel + { + High = 1, + Low = 2, + } + public class QueryDefinition + { + public QueryDefinition(string query); + public string QueryText { get; } + public IReadOnlyList> GetQueryParameters(); + public QueryDefinition WithParameter(string name, object value); + public QueryDefinition WithParameterStream(string name, Stream valueStream); + } + public class QueryRequestOptions : RequestOptions + { + public QueryRequestOptions(); + public Nullable ConsistencyLevel { get; set; } + public DedicatedGatewayRequestOptions DedicatedGatewayRequestOptions { get; set; } + public Nullable EnableLowPrecisionOrderBy { get; set; } + public bool EnableOptimisticDirectExecution { get; set; } + public Nullable EnableScanInQuery { get; set; } + public FullTextScoreScope FullTextScoreScope { get; set; } + public Nullable MaxBufferedItemCount { get; set; } + public Nullable MaxConcurrency { get; set; } + public Nullable MaxItemCount { get; set; } + public Nullable PartitionKey { get; set; } + public Nullable PopulateIndexMetrics { get; set; } + public Nullable PopulateQueryAdvice { get; set; } + public QueryTextMode QueryTextMode { get; set; } + public Nullable ResponseContinuationTokenLimitInKb { get; set; } + public string SessionToken { get; set; } + } + public enum QueryTextMode + { + All = 2, + None = 0, + ParameterizedOnly = 1, + } + public class ReadManyRequestOptions : RequestOptions + { + public ReadManyRequestOptions(); + public Nullable ConsistencyLevel { get; set; } + public string SessionToken { get; set; } + } + public static class Regions + { + public const string AustraliaCentral = "Australia Central"; + public const string AustraliaCentral2 = "Australia Central 2"; + public const string AustraliaEast = "Australia East"; + public const string AustraliaSoutheast = "Australia Southeast"; + public const string AustriaEast = "Austria East"; + public const string BelgiumCentral = "Belgium Central"; + public const string BleuFranceCentral = "Bleu France Central"; + public const string BleuFranceSouth = "Bleu France South"; + public const string BrazilSouth = "Brazil South"; + public const string BrazilSoutheast = "Brazil Southeast"; + public const string CanadaCentral = "Canada Central"; + public const string CanadaEast = "Canada East"; + public const string CentralIndia = "Central India"; + public const string CentralUS = "Central US"; + public const string CentralUSEUAP = "Central US EUAP"; + public const string ChileCentral = "Chile Central"; + public const string ChinaEast = "China East"; + public const string ChinaEast2 = "China East 2"; + public const string ChinaEast3 = "China East 3"; + public const string ChinaNorth = "China North"; + public const string ChinaNorth2 = "China North 2"; + public const string ChinaNorth3 = "China North 3"; + public const string DelosCloudGermanyCentral = "Delos Cloud Germany Central"; + public const string DelosCloudGermanyNorth = "Delos Cloud Germany North"; + public const string DenmarkEast = "Denmark East"; + public const string EastAsia = "East Asia"; + public const string EastUS = "East US"; + public const string EastUS2 = "East US 2"; + public const string EastUS2EUAP = "East US 2 EUAP"; + public const string EastUS3 = "East US 3"; + public const string EastUSSLV = "East US SLV"; + public const string FranceCentral = "France Central"; + public const string FranceSouth = "France South"; + public const string GermanyNorth = "Germany North"; + public const string GermanyWestCentral = "Germany West Central"; + public const string IndiaSouthCentral = "India South Central"; + public const string IndonesiaCentral = "Indonesia Central"; + public const string IsraelCentral = "Israel Central"; + public const string IsraelNorthwest = "Israel Northwest"; + public const string ItalyNorth = "Italy North"; + public const string JapanEast = "Japan East"; + public const string JapanWest = "Japan West"; + public const string JioIndiaCentral = "Jio India Central"; + public const string JioIndiaWest = "Jio India West"; + public const string KoreaCentral = "Korea Central"; + public const string KoreaSouth = "Korea South"; + public const string MalaysiaSouth = "Malaysia South"; + public const string MalaysiaWest = "Malaysia West"; + public const string MexicoCentral = "Mexico Central"; + public const string NewZealandNorth = "New Zealand North"; + public const string NorthCentralUS = "North Central US"; + public const string NortheastUS5 = "Northeast US 5"; + public const string NorthEurope = "North Europe"; + public const string NorwayEast = "Norway East"; + public const string NorwayWest = "Norway West"; + public const string PolandCentral = "Poland Central"; + public const string QatarCentral = "Qatar Central"; + public const string SingaporeCentral = "Singapore Central"; + public const string SingaporeNorth = "Singapore North"; + public const string SouthAfricaNorth = "South Africa North"; + public const string SouthAfricaWest = "South Africa West"; + public const string SouthCentralUS = "South Central US"; + public const string SouthCentralUS2 = "South Central US 2"; + public const string SoutheastAsia = "Southeast Asia"; + public const string SoutheastUS = "Southeast US"; + public const string SoutheastUS3 = "Southeast US 3"; + public const string SoutheastUS5 = "Southeast US 5"; + public const string SouthIndia = "South India"; + public const string SouthwestUS = "Southwest US"; + public const string SpainCentral = "Spain Central"; + public const string SwedenCentral = "Sweden Central"; + public const string SwedenSouth = "Sweden South"; + public const string SwitzerlandNorth = "Switzerland North"; + public const string SwitzerlandWest = "Switzerland West"; + public const string TaiwanNorth = "Taiwan North"; + public const string TaiwanNorthwest = "Taiwan Northwest"; + public const string UAECentral = "UAE Central"; + public const string UAENorth = "UAE North"; + public const string UKSouth = "UK South"; + public const string UKWest = "UK West"; + public const string USDoDCentral = "USDoD Central"; + public const string USDoDEast = "USDoD East"; + public const string USGovArizona = "USGov Arizona"; + public const string USGovTexas = "USGov Texas"; + public const string USGovVirginia = "USGov Virginia"; + public const string USNatEast = "USNat East"; + public const string USNatWest = "USNat West"; + public const string USSecEast = "USSec East"; + public const string USSecWest = "USSec West"; + public const string USSecWestCentral = "USSec West Central"; + public const string WestCentralUS = "West Central US"; + public const string WestEurope = "West Europe"; + public const string WestIndia = "West India"; + public const string WestUS = "West US"; + public const string WestUS2 = "West US 2"; + public const string WestUS3 = "West US 3"; + } + public abstract class RequestHandler + { + protected RequestHandler(); + public RequestHandler InnerHandler { get; set; } + public virtual Task SendAsync(RequestMessage request, CancellationToken cancellationToken); + } + public class RequestMessage : IDisposable + { + public RequestMessage(); + public RequestMessage(HttpMethod method, Uri requestUri); + public virtual Stream Content { get; set; } + public virtual Headers Headers { get; } + public virtual HttpMethod Method { get; } + public virtual Dictionary Properties { get; } + public virtual Uri RequestUri { get; } + public void Dispose(); + protected virtual void Dispose(bool disposing); + } + public class RequestOptions + { + public RequestOptions(); + public Action AddRequestHeaders { get; set; } + public AvailabilityStrategy AvailabilityStrategy { get; set; } + public CosmosThresholdOptions CosmosThresholdOptions { get; set; } + public List ExcludeRegions { get; set; } + public string IfMatchEtag { get; set; } + public string IfNoneMatchEtag { get; set; } + public Nullable PriorityLevel { get; set; } + public IReadOnlyDictionary Properties { get; set; } + public RequestOptions ShallowCopy(); + } + public class ResponseMessage : IDisposable + { + public ResponseMessage(); + public ResponseMessage(HttpStatusCode statusCode, RequestMessage requestMessage=null, string errorMessage=null); + public virtual Stream Content { get; set; } + public virtual string ContinuationToken { get; } + public virtual CosmosDiagnostics Diagnostics { get; set; } + public virtual string ErrorMessage { get; } + public virtual Headers Headers { get; } + public string IndexMetrics { get; } + public virtual bool IsSuccessStatusCode { get; } + public virtual RequestMessage RequestMessage { get; } + public virtual HttpStatusCode StatusCode { get; } + public void Dispose(); + protected virtual void Dispose(bool disposing); + public virtual ResponseMessage EnsureSuccessStatusCode(); + } + public abstract class Response + { + protected Response(); + public abstract string ActivityId { get; } + public abstract CosmosDiagnostics Diagnostics { get; } + public abstract string ETag { get; } + public abstract Headers Headers { get; } + public abstract double RequestCharge { get; } + public abstract T Resource { get; } + public abstract HttpStatusCode StatusCode { get; } + public static implicit operator T (Response response); + } + public abstract class ServerSideCumulativeMetrics + { + protected ServerSideCumulativeMetrics(); + public abstract ServerSideMetrics CumulativeMetrics { get; } + public abstract IReadOnlyList PartitionedMetrics { get; } + public abstract double TotalRequestCharge { get; } + } + public abstract class ServerSideMetrics + { + protected ServerSideMetrics(); + public abstract TimeSpan DocumentLoadTime { get; } + public abstract TimeSpan DocumentWriteTime { get; } + public abstract double IndexHitRatio { get; } + public abstract TimeSpan IndexLookupTime { get; } + public abstract long OutputDocumentCount { get; } + public abstract long OutputDocumentSize { get; } + public abstract TimeSpan QueryPreparationTime { get; } + public abstract long RetrievedDocumentCount { get; } + public abstract long RetrievedDocumentSize { get; } + public abstract TimeSpan RuntimeExecutionTime { get; } + public abstract TimeSpan TotalTime { get; } + public abstract TimeSpan VMExecutionTime { get; } + } + public abstract class ServerSidePartitionedMetrics + { + protected ServerSidePartitionedMetrics(); + public abstract string FeedRange { get; } + public abstract Nullable PartitionKeyRangeId { get; } + public abstract double RequestCharge { get; } + public abstract ServerSideMetrics ServerSideMetrics { get; } + } + public sealed class SpatialPath + { + public SpatialPath(); + public BoundingBoxProperties BoundingBox { get; set; } + public string Path { get; set; } + public Collection SpatialTypes { get; } + } + public enum SpatialType + { + LineString = 1, + MultiPolygon = 3, + Point = 0, + Polygon = 2, + } + public class ThroughputProperties + { + public Nullable AutoscaleMaxThroughput { get; } + public string ETag { get; } + public Nullable LastModified { get; } + public string SelfLink { get; } + public Nullable Throughput { get; } + public static ThroughputProperties CreateAutoscaleThroughput(int autoscaleMaxThroughput); + public static ThroughputProperties CreateManualThroughput(int throughput); + } + public class ThroughputResponse : Response + { + protected ThroughputResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public Nullable IsReplacePending { get; } + public Nullable MinThroughput { get; } + public override double RequestCharge { get; } + public override ThroughputProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator ThroughputProperties (ThroughputResponse response); + } + public abstract class TransactionalBatch + { + protected TransactionalBatch(); + public abstract TransactionalBatch CreateItemStream(Stream streamPayload, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch CreateItem(T item, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch DeleteItem(string id, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract Task ExecuteAsync(TransactionalBatchRequestOptions requestOptions, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ExecuteAsync(CancellationToken cancellationToken=default(CancellationToken)); + public abstract TransactionalBatch PatchItem(string id, IReadOnlyList patchOperations, TransactionalBatchPatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch ReadItem(string id, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch ReplaceItemStream(string id, Stream streamPayload, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch ReplaceItem(string id, T item, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch UpsertItemStream(Stream streamPayload, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch UpsertItem(T item, TransactionalBatchItemRequestOptions requestOptions=null); + } + public class TransactionalBatchItemRequestOptions : RequestOptions + { + public TransactionalBatchItemRequestOptions(); + public Nullable EnableContentResponseOnWrite { get; set; } + public Nullable IndexingDirective { get; set; } + } + public class TransactionalBatchOperationResult + { + protected TransactionalBatchOperationResult(); + public virtual string ETag { get; } + public virtual bool IsSuccessStatusCode { get; } + public virtual Stream ResourceStream { get; } + public virtual TimeSpan RetryAfter { get; } + public virtual HttpStatusCode StatusCode { get; } + } + public class TransactionalBatchOperationResult : TransactionalBatchOperationResult + { + protected TransactionalBatchOperationResult(); + public virtual T Resource { get; set; } + } + public class TransactionalBatchPatchItemRequestOptions : TransactionalBatchItemRequestOptions + { + public TransactionalBatchPatchItemRequestOptions(); + public string FilterPredicate { get; set; } + } + public class TransactionalBatchRequestOptions : RequestOptions + { + public TransactionalBatchRequestOptions(); + public Nullable ConsistencyLevel { get; set; } + public string SessionToken { get; set; } + } + public class TransactionalBatchResponse : IDisposable, IEnumerable, IEnumerable, IReadOnlyCollection, IReadOnlyList + { + protected TransactionalBatchResponse(); + public virtual string ActivityId { get; } + public virtual int Count { get; } + public virtual CosmosDiagnostics Diagnostics { get; } + public virtual string ErrorMessage { get; } + public virtual Headers Headers { get; } + public virtual bool IsSuccessStatusCode { get; } + public virtual TransactionalBatchOperationResult this[int index] { get; } + public virtual double RequestCharge { get; } + public virtual Nullable RetryAfter { get; } + public virtual HttpStatusCode StatusCode { get; } + public void Dispose(); + protected virtual void Dispose(bool disposing); + public virtual IEnumerator GetEnumerator(); + public virtual TransactionalBatchOperationResult GetOperationResultAtIndex(int index); + IEnumerator System.Collections.IEnumerable.GetEnumerator(); + } + public class UniqueKey + { + public UniqueKey(); + public Collection Paths { get; } + } + public sealed class UniqueKeyPolicy + { + public UniqueKeyPolicy(); + public Collection UniqueKeys { get; } + } + public abstract class User + { + protected User(); + public abstract string Id { get; } + public abstract Task CreatePermissionAsync(PermissionProperties permissionProperties, Nullable tokenExpiryInSeconds=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Permission GetPermission(string id); + public abstract FeedIterator GetPermissionQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetPermissionQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract Task ReadAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceAsync(UserProperties userProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task UpsertPermissionAsync(PermissionProperties permissionProperties, Nullable tokenExpiryInSeconds=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + } + public class UserProperties + { + protected UserProperties(); + public UserProperties(string id); + public string ETag { get; } + public string Id { get; set; } + public Nullable LastModified { get; } + public string SelfLink { get; } + } + public class UserResponse : Response + { + protected UserResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override UserProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public virtual User User { get; } + public static implicit operator User (UserResponse response); + } + public enum VectorDataType + { + Float16 = 3, + Float32 = 0, + Int8 = 2, + Uint8 = 1, + } + public sealed class VectorEmbeddingPolicy + { + public readonly Collection Embeddings; + public VectorEmbeddingPolicy(Collection embeddings); + } + public sealed class VectorIndexPath + { + public VectorIndexPath(); + public int IndexingSearchListSize { get; set; } + public string Path { get; set; } + public VectorIndexType Type { get; set; } + public string[] VectorIndexShardKey { get; set; } + } + public enum VectorIndexType + { + DiskANN = 1, + Flat = 0, + QuantizedFlat = 2, + } +} +namespace Microsoft.Azure.Cosmos.FaultInjection +{ + public interface IFaultInjector + { + } +} +namespace Microsoft.Azure.Cosmos.Fluent +{ + public sealed class ClientEncryptionPolicyDefinition + { + public ContainerBuilder Attach(); + public ClientEncryptionPolicyDefinition WithIncludedPath(ClientEncryptionIncludedPath path); + } + public class CompositeIndexDefinition + { + public T Attach(); + public CompositeIndexDefinition Path(string path); + public CompositeIndexDefinition Path(string path, CompositePathSortOrder sortOrder); + } + public class ComputedPropertiesDefinition + { + public T Attach(); + public ComputedPropertiesDefinition WithComputedProperty(string name, string query); + } + public class ConflictResolutionDefinition + { + public ContainerBuilder Attach(); + public ConflictResolutionDefinition WithCustomStoredProcedureResolution(string conflictResolutionProcedure); + public ConflictResolutionDefinition WithLastWriterWinsResolution(string conflictResolutionPath); + } + public class ContainerBuilder : ContainerDefinition + { + protected ContainerBuilder(); + public ContainerBuilder(Database database, string name, string partitionKeyPath); + public new ContainerProperties Build(); + public Task CreateAsync(ThroughputProperties throughputProperties, CancellationToken cancellationToken=default(CancellationToken)); + public Task CreateAsync(Nullable throughput=default(Nullable), CancellationToken cancellationToken=default(CancellationToken)); + public Task CreateIfNotExistsAsync(ThroughputProperties throughputProperties, CancellationToken cancellationToken=default(CancellationToken)); + public Task CreateIfNotExistsAsync(Nullable throughput=default(Nullable), CancellationToken cancellationToken=default(CancellationToken)); + public ClientEncryptionPolicyDefinition WithClientEncryptionPolicy(); + public ClientEncryptionPolicyDefinition WithClientEncryptionPolicy(int policyFormatVersion); + public ConflictResolutionDefinition WithConflictResolution(); + public FullTextPolicyDefinition WithFullTextPolicy(string defaultLanguage, Collection fullTextPaths); + public UniqueKeyDefinition WithUniqueKey(); + public VectorEmbeddingPolicyDefinition WithVectorEmbeddingPolicy(Collection embeddings); + } + public abstract class ContainerDefinition where T : ContainerDefinition + { + public ContainerDefinition(); + public ContainerProperties Build(); + public ComputedPropertiesDefinition WithComputedProperties(); + public T WithDefaultTimeToLive(int defaultTtlInSeconds); + public T WithDefaultTimeToLive(TimeSpan defaultTtlTimeSpan); + public IndexingPolicyDefinition WithIndexingPolicy(); + public T WithPartitionKeyDefinitionVersion(PartitionKeyDefinitionVersion partitionKeyDefinitionVersion); + public T WithTimeToLivePropertyPath(string propertyPath); + } + public class CosmosClientBuilder + { + public CosmosClientBuilder(string connectionString); + public CosmosClientBuilder(string accountEndpoint, AzureKeyCredential authKeyOrResourceTokenCredential); + public CosmosClientBuilder(string accountEndpoint, TokenCredential tokenCredential); + public CosmosClientBuilder(string accountEndpoint, string authKeyOrResourceToken); + public CosmosClientBuilder AddCustomHandlers(params RequestHandler[] customHandlers); + public CosmosClient Build(); + public Task BuildAndInitializeAsync(IReadOnlyList> containers, CancellationToken cancellationToken=default(CancellationToken)); + public CosmosClientBuilder WithApplicationName(string applicationName); + public CosmosClientBuilder WithApplicationPreferredRegions(IReadOnlyList applicationPreferredRegions); + public CosmosClientBuilder WithApplicationRegion(string applicationRegion); + public CosmosClientBuilder WithAvailabilityStrategy(AvailabilityStrategy strategy); + public CosmosClientBuilder WithBulkExecution(bool enabled); + public CosmosClientBuilder WithClientTelemetryOptions(CosmosClientTelemetryOptions options); + public CosmosClientBuilder WithConnectionModeDirect(); + public CosmosClientBuilder WithConnectionModeDirect(Nullable idleTcpConnectionTimeout=default(Nullable), Nullable openTcpConnectionTimeout=default(Nullable), Nullable maxRequestsPerTcpConnection=default(Nullable), Nullable maxTcpConnectionsPerEndpoint=default(Nullable), Nullable portReuseMode=default(Nullable), Nullable enableTcpConnectionEndpointRediscovery=default(Nullable)); + public CosmosClientBuilder WithConnectionModeGateway(Nullable maxConnectionLimit=default(Nullable), IWebProxy webProxy=null); + public CosmosClientBuilder WithConsistencyLevel(ConsistencyLevel consistencyLevel); + public CosmosClientBuilder WithContentResponseOnWrite(bool contentResponseOnWrite); + public CosmosClientBuilder WithCustomAccountEndpoints(IEnumerable customAccountEndpoints); + public CosmosClientBuilder WithCustomSerializer(CosmosSerializer cosmosJsonSerializer); + public CosmosClientBuilder WithFaultInjection(IFaultInjector faultInjector); + public CosmosClientBuilder WithHttpClientFactory(Func httpClientFactory); + public CosmosClientBuilder WithLimitToEndpoint(bool limitToEndpoint); + public CosmosClientBuilder WithPriorityLevel(PriorityLevel priorityLevel); + public CosmosClientBuilder WithRequestTimeout(TimeSpan requestTimeout); + public CosmosClientBuilder WithSerializerOptions(CosmosSerializationOptions cosmosSerializerOptions); + public CosmosClientBuilder WithSystemTextJsonSerializerOptions(JsonSerializerOptions serializerOptions); + public CosmosClientBuilder WithThrottlingRetryOptions(TimeSpan maxRetryWaitTimeOnThrottledRequests, int maxRetryAttemptsOnThrottledRequests); + } + public class FullTextIndexDefinition + { + public FullTextIndexDefinition(T parent, Action attachCallback); + public T Attach(); + public FullTextIndexDefinition Path(string path); + } + public class FullTextPolicyDefinition + { + public FullTextPolicyDefinition(ContainerBuilder parent, string defaultLanguage, Collection fullTextPaths, Action attachCallback); + public ContainerBuilder Attach(); + } + public class IndexingPolicyDefinition + { + public IndexingPolicyDefinition(); + public T Attach(); + public IndexingPolicyDefinition WithAutomaticIndexing(bool enabled); + public CompositeIndexDefinition> WithCompositeIndex(); + public PathsDefinition> WithExcludedPaths(); + public FullTextIndexDefinition> WithFullTextIndex(); + public PathsDefinition> WithIncludedPaths(); + public IndexingPolicyDefinition WithIndexingMode(IndexingMode indexingMode); + public SpatialIndexDefinition> WithSpatialIndex(); + public VectorIndexDefinition> WithVectorIndex(); + } + public class PathsDefinition + { + public T Attach(); + public PathsDefinition Path(string path); + } + public class SpatialIndexDefinition + { + public T Attach(); + public SpatialIndexDefinition Path(string path); + public SpatialIndexDefinition Path(string path, params SpatialType[] spatialTypes); + } + public class UniqueKeyDefinition + { + public ContainerBuilder Attach(); + public UniqueKeyDefinition Path(string path); + } + public class VectorEmbeddingPolicyDefinition + { + public VectorEmbeddingPolicyDefinition(ContainerBuilder parent, Collection embeddings, Action attachCallback); + public ContainerBuilder Attach(); + } + public class VectorIndexDefinition + { + public VectorIndexDefinition(T parent, Action attachCallback); + public T Attach(); + public VectorIndexDefinition Path(string path, VectorIndexType indexType); + } +} +namespace Microsoft.Azure.Cosmos.Linq +{ + public static class CosmosLinq + { + public static object InvokeUserDefinedFunction(string udfName, params object[] arguments); + } + public static class CosmosLinqExtensions + { + public static bool ArrayContainsAll(this IEnumerable obj, params object[] values); + public static bool ArrayContainsAny(this IEnumerable obj, params object[] values); + public static Task> AverageAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> AverageAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> AverageAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> AverageAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> AverageAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> AverageAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> AverageAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> AverageAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> AverageAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> AverageAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> CountAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static int DocumentId(this object obj); + public static bool FullTextContains(this object obj, string search); + public static bool FullTextContainsAll(this object obj, params string[] searches); + public static bool FullTextContainsAny(this object obj, params string[] searches); + public static double FullTextScore(this TSource obj, params string[] terms); + public static string GetIndexMetrics(this Response response); + public static bool IsArray(this object obj); + public static bool IsBool(this object obj); + public static bool IsDefined(this object obj); + public static bool IsNull(this object obj); + public static bool IsNumber(this object obj); + public static bool IsObject(this object obj); + public static bool IsPrimitive(this object obj); + public static bool IsString(this object obj); + public static Task> MaxAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> MinAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static IOrderedQueryable OrderByRank(this IQueryable source, Expression> scoreFunction); + public static bool RegexMatch(this object obj, string regularExpression); + public static bool RegexMatch(this object obj, string regularExpression, string searchModifier); + public static double RRF(params double[] scoringFunctions); + public static double RRF(double[] scoringFunctions, double[] weights); + public static Task> SumAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> SumAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> SumAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> SumAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> SumAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> SumAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> SumAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> SumAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> SumAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> SumAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static FeedIterator ToFeedIterator(this IQueryable query); + public static QueryDefinition ToQueryDefinition(this IQueryable query); + public static FeedIterator ToStreamIterator(this IQueryable query); + public static double VectorDistance(this byte[] vector1, byte[] vector2, bool isBruteForce, CosmosLinqExtensions.VectorDistanceOptions options); + public static double VectorDistance(this sbyte[] vector1, sbyte[] vector2, bool isBruteForce, CosmosLinqExtensions.VectorDistanceOptions options); + public static double VectorDistance(this float[] vector1, float[] vector2, bool isBruteForce, CosmosLinqExtensions.VectorDistanceOptions options); + public sealed class VectorDistanceOptions + { + public VectorDistanceOptions(); + public Nullable DataType { get; set; } + public Nullable DistanceFunction { get; set; } + public Nullable SearchListSizeMultiplier { get; set; } + } + } +} +namespace Microsoft.Azure.Cosmos.Scripts +{ + public abstract class Scripts + { + protected Scripts(); + public abstract Task CreateStoredProcedureAsync(StoredProcedureProperties storedProcedureProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateStoredProcedureStreamAsync(StoredProcedureProperties storedProcedureProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateTriggerAsync(TriggerProperties triggerProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateTriggerStreamAsync(TriggerProperties triggerProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateUserDefinedFunctionAsync(UserDefinedFunctionProperties userDefinedFunctionProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateUserDefinedFunctionStreamAsync(UserDefinedFunctionProperties userDefinedFunctionProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteStoredProcedureAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteStoredProcedureStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteTriggerAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteTriggerStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteUserDefinedFunctionAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteUserDefinedFunctionStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ExecuteStoredProcedureAsync(string storedProcedureId, PartitionKey partitionKey, dynamic parameters, StoredProcedureRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ExecuteStoredProcedureStreamAsync(string storedProcedureId, PartitionKey partitionKey, dynamic parameters, StoredProcedureRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ExecuteStoredProcedureStreamAsync(string storedProcedureId, Stream streamPayload, PartitionKey partitionKey, StoredProcedureRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract FeedIterator GetStoredProcedureQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetStoredProcedureQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetStoredProcedureQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetStoredProcedureQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetTriggerQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetTriggerQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetTriggerQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetTriggerQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetUserDefinedFunctionQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetUserDefinedFunctionQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetUserDefinedFunctionQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetUserDefinedFunctionQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract Task ReadStoredProcedureAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadStoredProcedureStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadTriggerAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadTriggerStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadUserDefinedFunctionAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadUserDefinedFunctionStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceStoredProcedureAsync(StoredProcedureProperties storedProcedureProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceStoredProcedureStreamAsync(StoredProcedureProperties storedProcedureProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceTriggerAsync(TriggerProperties triggerProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceTriggerStreamAsync(TriggerProperties triggerProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceUserDefinedFunctionAsync(UserDefinedFunctionProperties userDefinedFunctionProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceUserDefinedFunctionStreamAsync(UserDefinedFunctionProperties userDefinedFunctionProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + } + public class StoredProcedureExecuteResponse : Response + { + protected StoredProcedureExecuteResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override T Resource { get; } + public virtual string ScriptLog { get; } + public virtual string SessionToken { get; } + public override HttpStatusCode StatusCode { get; } + } + public class StoredProcedureProperties + { + public StoredProcedureProperties(); + public StoredProcedureProperties(string id, string body); + public string Body { get; set; } + public string ETag { get; } + public string Id { get; set; } + public Nullable LastModified { get; } + public string SelfLink { get; } + } + public class StoredProcedureRequestOptions : RequestOptions + { + public StoredProcedureRequestOptions(); + public Nullable ConsistencyLevel { get; set; } + public bool EnableScriptLogging { get; set; } + public string SessionToken { get; set; } + } + public class StoredProcedureResponse : Response + { + protected StoredProcedureResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override StoredProcedureProperties Resource { get; } + public virtual string SessionToken { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator StoredProcedureProperties (StoredProcedureResponse response); + } + public enum TriggerOperation : short + { + All = (short)0, + Create = (short)1, + Delete = (short)3, + Replace = (short)4, + Update = (short)2, + Upsert = (short)5, + } + public class TriggerProperties + { + public TriggerProperties(); + public string Body { get; set; } + public string ETag { get; } + public string Id { get; set; } + public string SelfLink { get; } + public TriggerOperation TriggerOperation { get; set; } + public TriggerType TriggerType { get; set; } + } + public class TriggerResponse : Response + { + protected TriggerResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override TriggerProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator TriggerProperties (TriggerResponse response); + } + public enum TriggerType : byte + { + Post = (byte)1, + Pre = (byte)0, + } + public class UserDefinedFunctionProperties + { + public UserDefinedFunctionProperties(); + public string Body { get; set; } + public string ETag { get; } + public string Id { get; set; } + public string SelfLink { get; } + } + public class UserDefinedFunctionResponse : Response + { + protected UserDefinedFunctionResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override UserDefinedFunctionProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator UserDefinedFunctionProperties (UserDefinedFunctionResponse response); + } +} +namespace Microsoft.Azure.Cosmos.Spatial +{ + public sealed class BoundingBox : IEquatable + { + public BoundingBox(Position min, Position max); + public Position Max { get; } + public Position Min { get; } + public bool Equals(BoundingBox other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public abstract class Crs + { + protected Crs(CrsType type); + public static Crs Default { get; } + public CrsType Type { get; } + public static Crs Unspecified { get; } + public static LinkedCrs Linked(string href); + public static LinkedCrs Linked(string href, string type); + public static NamedCrs Named(string name); + } + public enum CrsType + { + Linked = 1, + Named = 0, + Unspecified = 2, + } + public abstract class Geometry + { + protected Geometry(GeometryType type, GeometryParams geometryParams); + public IDictionary AdditionalProperties { get; } + public BoundingBox BoundingBox { get; } + public Crs Crs { get; } + public GeometryType Type { get; } + public double Distance(Geometry to); + public override bool Equals(object obj); + public override int GetHashCode(); + public bool Intersects(Geometry geometry2); + public bool IsValid(); + public GeometryValidationResult IsValidDetailed(); + public bool Within(Geometry outer); + } + public class GeometryParams + { + public GeometryParams(); + public IDictionary AdditionalProperties { get; set; } + public BoundingBox BoundingBox { get; set; } + public Crs Crs { get; set; } + } + public enum GeometryShape + { + GeometryCollection = 6, + LineString = 2, + MultiLineString = 3, + MultiPoint = 1, + MultiPolygon = 5, + Point = 0, + Polygon = 4, + } + public enum GeometryType + { + GeometryCollection = 6, + LineString = 2, + MultiLineString = 3, + MultiPoint = 1, + MultiPolygon = 5, + Point = 0, + Polygon = 4, + } + public class GeometryValidationResult + { + public GeometryValidationResult(); + public bool IsValid { get; } + public string Reason { get; } + } + public sealed class LinearRing : IEquatable + { + public LinearRing(IList coordinates); + public ReadOnlyCollection Positions { get; } + public bool Equals(LinearRing other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class LineString : Geometry, IEquatable + { + public LineString(IList coordinates); + public LineString(IList coordinates, GeometryParams geometryParams); + public ReadOnlyCollection Positions { get; } + public bool Equals(LineString other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class LinkedCrs : Crs, IEquatable + { + public string Href { get; } + public string HrefType { get; } + public bool Equals(LinkedCrs other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class MultiPolygon : Geometry, IEquatable + { + public MultiPolygon(IList polygons); + public MultiPolygon(IList polygons, GeometryParams geometryParams); + public ReadOnlyCollection Polygons { get; } + public bool Equals(MultiPolygon other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class NamedCrs : Crs, IEquatable + { + public string Name { get; } + public bool Equals(NamedCrs other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class Point : Geometry, IEquatable + { + public Point(Position position); + public Point(Position position, GeometryParams geometryParams); + public Point(double longitude, double latitude); + public Position Position { get; } + public bool Equals(Point other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class Polygon : Geometry, IEquatable + { + public Polygon(IList rings); + public Polygon(IList rings, GeometryParams geometryParams); + public Polygon(IList externalRingPositions); + public ReadOnlyCollection Rings { get; } + public bool Equals(Polygon other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class PolygonCoordinates : IEquatable + { + public PolygonCoordinates(IList rings); + public ReadOnlyCollection Rings { get; } + public bool Equals(PolygonCoordinates other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class Position : IEquatable + { + public Position(IList coordinates); + public Position(double longitude, double latitude); + public Position(double longitude, double latitude, Nullable altitude); + public Nullable Altitude { get; } + public ReadOnlyCollection Coordinates { get; } + public double Latitude { get; } + public double Longitude { get; } + public bool Equals(Position other); + public override bool Equals(object obj); + public override int GetHashCode(); + } +} diff --git a/Microsoft.Azure.Cosmos/contracts/API_3.59.0-preview.0.txt b/Microsoft.Azure.Cosmos/contracts/API_3.59.0-preview.0.txt new file mode 100644 index 0000000000..1ae52c0597 --- /dev/null +++ b/Microsoft.Azure.Cosmos/contracts/API_3.59.0-preview.0.txt @@ -0,0 +1,1942 @@ +namespace Microsoft.Azure.Cosmos +{ + public class AccountConsistency + { + public AccountConsistency(); + public ConsistencyLevel DefaultConsistencyLevel { get; } + public int MaxStalenessIntervalInSeconds { get; } + public int MaxStalenessPrefix { get; } + } + public class AccountProperties + { + public AccountConsistency Consistency { get; } + public string ETag { get; } + public string Id { get; } + public IEnumerable ReadableRegions { get; } + public IEnumerable WritableRegions { get; } + } + public class AccountRegion + { + public AccountRegion(); + public string Endpoint { get; } + public string Name { get; } + } + public abstract class AvailabilityStrategy + { + public static AvailabilityStrategy CrossRegionHedgingStrategy(TimeSpan threshold, Nullable thresholdStep, bool enableMultiWriteRegionHedge=false); + public static AvailabilityStrategy DisabledStrategy(); + } + public sealed class BoundingBoxProperties + { + public BoundingBoxProperties(); + public double Xmax { get; set; } + public double Xmin { get; set; } + public double Ymax { get; set; } + public double Ymin { get; set; } + } + public abstract class ChangeFeedEstimator + { + protected ChangeFeedEstimator(); + public abstract FeedIterator GetCurrentStateIterator(ChangeFeedEstimatorRequestOptions changeFeedEstimatorRequestOptions=null); + } + public sealed class ChangeFeedEstimatorRequestOptions + { + public ChangeFeedEstimatorRequestOptions(); + public Nullable MaxItemCount { get; set; } + } + public class ChangeFeedItem + { + public ChangeFeedItem(); + public T Current { get; set; } + public ChangeFeedMetadata Metadata { get; set; } + public T Previous { get; set; } + } + public class ChangeFeedMetadata + { + public ChangeFeedMetadata(); + public DateTime ConflictResolutionTimestamp { get; } + public string Id { get; } + public bool IsTimeToLiveExpired { get; } + public long Lsn { get; } + public ChangeFeedOperationType OperationType { get; } + public Dictionary PartitionKey { get; } + public long PreviousLsn { get; } + } + public abstract class ChangeFeedMode + { + public static ChangeFeedMode AllVersionsAndDeletes { get; } + public static ChangeFeedMode Incremental { get; } + public static ChangeFeedMode LatestVersion { get; } + } + public enum ChangeFeedOperationType + { + Create = 0, + Delete = 2, + Replace = 1, + } + public sealed class ChangeFeedPolicy + { + public ChangeFeedPolicy(); + public static TimeSpan FullFidelityNoRetention { get; } + public TimeSpan FullFidelityRetention { get; set; } + } + public abstract class ChangeFeedProcessor + { + protected ChangeFeedProcessor(); + public abstract Task StartAsync(); + public abstract Task StopAsync(); + } + public class ChangeFeedProcessorBuilder + { + public ChangeFeedProcessor Build(); + public ChangeFeedProcessorBuilder WithErrorNotification(Container.ChangeFeedMonitorErrorDelegate errorDelegate); + public virtual ChangeFeedProcessorBuilder WithInMemoryLeaseContainer(); + public ChangeFeedProcessorBuilder WithInstanceName(string instanceName); + public ChangeFeedProcessorBuilder WithLeaseAcquireNotification(Container.ChangeFeedMonitorLeaseAcquireDelegate acquireDelegate); + public ChangeFeedProcessorBuilder WithLeaseConfiguration(Nullable acquireInterval=default(Nullable), Nullable expirationInterval=default(Nullable), Nullable renewInterval=default(Nullable)); + public ChangeFeedProcessorBuilder WithLeaseContainer(Container leaseContainer); + public ChangeFeedProcessorBuilder WithLeaseReleaseNotification(Container.ChangeFeedMonitorLeaseReleaseDelegate releaseDelegate); + public ChangeFeedProcessorBuilder WithMaxItems(int maxItemCount); + public ChangeFeedProcessorBuilder WithPollInterval(TimeSpan pollInterval); + public ChangeFeedProcessorBuilder WithStartTime(DateTime startTime); + } + public abstract class ChangeFeedProcessorContext + { + protected ChangeFeedProcessorContext(); + public abstract CosmosDiagnostics Diagnostics { get; } + public abstract FeedRange FeedRange { get; } + public abstract Headers Headers { get; } + public abstract string LeaseToken { get; } + } + public sealed class ChangeFeedProcessorState + { + public ChangeFeedProcessorState(string leaseToken, long estimatedLag, string instanceName); + public long EstimatedLag { get; } + public string InstanceName { get; } + public string LeaseToken { get; } + } + public class ChangeFeedProcessorUserException : Exception + { + public ChangeFeedProcessorUserException(Exception originalException, ChangeFeedProcessorContext context); + protected ChangeFeedProcessorUserException(SerializationInfo info, StreamingContext context); + public ChangeFeedProcessorContext ChangeFeedProcessorContext { get; } + public override void GetObjectData(SerializationInfo info, StreamingContext context); + } + public sealed class ChangeFeedRequestOptions : RequestOptions + { + public ChangeFeedRequestOptions(); + public new string IfMatchEtag { get; set; } + public new string IfNoneMatchEtag { get; set; } + public Nullable PageSizeHint { get; set; } + public Nullable ReadConsistencyStrategy { get; set; } + } + public abstract class ChangeFeedStartFrom + { + public static ChangeFeedStartFrom Beginning(); + public static ChangeFeedStartFrom Beginning(FeedRange feedRange); + public static ChangeFeedStartFrom ContinuationToken(string continuationToken); + public static ChangeFeedStartFrom Now(); + public static ChangeFeedStartFrom Now(FeedRange feedRange); + public static ChangeFeedStartFrom Time(DateTime dateTimeUtc); + public static ChangeFeedStartFrom Time(DateTime dateTimeUtc, FeedRange feedRange); + } + public sealed class ClientEncryptionIncludedPath + { + public ClientEncryptionIncludedPath(); + public string ClientEncryptionKeyId { get; set; } + public string EncryptionAlgorithm { get; set; } + public string EncryptionType { get; set; } + public string Path { get; set; } + } + public abstract class ClientEncryptionKey + { + protected ClientEncryptionKey(); + public abstract string Id { get; } + public abstract Task ReadAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceAsync(ClientEncryptionKeyProperties clientEncryptionKeyProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + } + public class ClientEncryptionKeyProperties : IEquatable + { + protected ClientEncryptionKeyProperties(); + public ClientEncryptionKeyProperties(string id, string encryptionAlgorithm, byte[] wrappedDataEncryptionKey, EncryptionKeyWrapMetadata encryptionKeyWrapMetadata); + public Nullable CreatedTime { get; } + public string EncryptionAlgorithm { get; } + public EncryptionKeyWrapMetadata EncryptionKeyWrapMetadata { get; } + public string ETag { get; } + public string Id { get; } + public Nullable LastModified { get; } + public virtual string SelfLink { get; } + public byte[] WrappedDataEncryptionKey { get; } + public bool Equals(ClientEncryptionKeyProperties other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public class ClientEncryptionKeyResponse : Response + { + protected ClientEncryptionKeyResponse(); + public override string ActivityId { get; } + public virtual ClientEncryptionKey ClientEncryptionKey { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override ClientEncryptionKeyProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator ClientEncryptionKey (ClientEncryptionKeyResponse response); + } + public sealed class ClientEncryptionPolicy + { + public ClientEncryptionPolicy(IEnumerable includedPaths); + public ClientEncryptionPolicy(IEnumerable includedPaths, int policyFormatVersion); + public IEnumerable IncludedPaths { get; } + public int PolicyFormatVersion { get; } + } + public sealed class CompositePath + { + public CompositePath(); + public CompositePathSortOrder Order { get; set; } + public string Path { get; set; } + } + public enum CompositePathSortOrder + { + Ascending = 0, + Descending = 1, + } + public sealed class ComputedProperty + { + public ComputedProperty(); + public string Name { get; set; } + public string Query { get; set; } + } + public class ConflictProperties + { + public ConflictProperties(); + public string Id { get; } + public OperationKind OperationKind { get; } + public string SelfLink { get; } + } + public enum ConflictResolutionMode + { + Custom = 1, + LastWriterWins = 0, + } + public class ConflictResolutionPolicy + { + public ConflictResolutionPolicy(); + public ConflictResolutionMode Mode { get; set; } + public string ResolutionPath { get; set; } + public string ResolutionProcedure { get; set; } + } + public abstract class Conflicts + { + protected Conflicts(); + public abstract Task DeleteAsync(ConflictProperties conflict, PartitionKey partitionKey, CancellationToken cancellationToken=default(CancellationToken)); + public abstract FeedIterator GetConflictQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetConflictQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetConflictQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetConflictQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract T ReadConflictContent(ConflictProperties conflict); + public abstract Task> ReadCurrentAsync(ConflictProperties conflict, PartitionKey partitionKey, CancellationToken cancellationToken=default(CancellationToken)); + } + public enum ConnectionMode + { + Direct = 1, + Gateway = 0, + } + public enum ConsistencyLevel + { + BoundedStaleness = 1, + ConsistentPrefix = 4, + Eventual = 3, + Session = 2, + Strong = 0, + } + public abstract class Container + { + protected Container(); + public abstract Conflicts Conflicts { get; } + public abstract Database Database { get; } + public abstract string Id { get; } + public abstract Scripts Scripts { get; } + public abstract Task> CreateItemAsync(T item, Nullable partitionKey=default(Nullable), ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateItemStreamAsync(Stream streamPayload, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract TransactionalBatch CreateTransactionalBatch(PartitionKey partitionKey); + public virtual Task DeleteAllItemsByPartitionKeyStreamAsync(PartitionKey partitionKey, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteContainerAsync(ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteContainerStreamAsync(ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> DeleteItemAsync(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteItemStreamAsync(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract ChangeFeedEstimator GetChangeFeedEstimator(string processorName, Container leaseContainer); + public abstract ChangeFeedProcessorBuilder GetChangeFeedEstimatorBuilder(string processorName, Container.ChangesEstimationHandler estimationDelegate, Nullable estimationPeriod=default(Nullable)); + public abstract FeedIterator GetChangeFeedIterator(ChangeFeedStartFrom changeFeedStartFrom, ChangeFeedMode changeFeedMode, ChangeFeedRequestOptions changeFeedRequestOptions=null); + public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder(string processorName, Container.ChangeFeedStreamHandler onChangesDelegate); + public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilderWithAllVersionsAndDeletes(string processorName, Container.ChangeFeedHandler> onChangesDelegate); + public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilderWithManualCheckpoint(string processorName, Container.ChangeFeedStreamHandlerWithManualCheckpoint onChangesDelegate); + public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilderWithManualCheckpoint(string processorName, Container.ChangeFeedHandlerWithManualCheckpoint onChangesDelegate); + public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder(string processorName, Container.ChangeFeedHandler onChangesDelegate); + public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder(string processorName, Container.ChangesHandler onChangesDelegate); + public abstract FeedIterator GetChangeFeedStreamIterator(ChangeFeedStartFrom changeFeedStartFrom, ChangeFeedMode changeFeedMode, ChangeFeedRequestOptions changeFeedRequestOptions=null); + public abstract Task> GetFeedRangesAsync(CancellationToken cancellationToken=default(CancellationToken)); + public abstract IOrderedQueryable GetItemLinqQueryable(bool allowSynchronousQueryExecution=false, string continuationToken=null, QueryRequestOptions requestOptions=null, CosmosLinqSerializerOptions linqSerializerOptions=null); + public abstract FeedIterator GetItemQueryIterator(FeedRange feedRange, QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetItemQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetItemQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetItemQueryStreamIterator(FeedRange feedRange, QueryDefinition queryDefinition, string continuationToken, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetItemQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetItemQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract Task> GetPartitionKeyRangesAsync(FeedRange feedRange, CancellationToken cancellationToken=default(CancellationToken)); + public virtual Task IsFeedRangePartOfAsync(FeedRange x, FeedRange y, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> PatchItemAsync(string id, PartitionKey partitionKey, IReadOnlyList patchOperations, PatchItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task PatchItemStreamAsync(string id, PartitionKey partitionKey, IReadOnlyList patchOperations, PatchItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadContainerAsync(ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadContainerStreamAsync(ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ReadItemAsync(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadItemStreamAsync(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ReadManyItemsAsync(IReadOnlyList> items, ReadManyRequestOptions readManyRequestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadManyItemsStreamAsync(IReadOnlyList> items, ReadManyRequestOptions readManyRequestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadThroughputAsync(RequestOptions requestOptions, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ReadThroughputAsync(CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceContainerAsync(ContainerProperties containerProperties, ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceContainerStreamAsync(ContainerProperties containerProperties, ContainerRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ReplaceItemAsync(T item, string id, Nullable partitionKey=default(Nullable), ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceItemStreamAsync(Stream streamPayload, string id, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceThroughputAsync(ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceThroughputAsync(int throughput, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task SemanticRerankAsync(string rerankContext, IEnumerable documents, IDictionary options=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> UpsertItemAsync(T item, Nullable partitionKey=default(Nullable), ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task UpsertItemStreamAsync(Stream streamPayload, PartitionKey partitionKey, ItemRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public delegate Task ChangeFeedHandlerWithManualCheckpoint(ChangeFeedProcessorContext context, IReadOnlyCollection changes, Func checkpointAsync, CancellationToken cancellationToken); + public delegate Task ChangeFeedHandler(ChangeFeedProcessorContext context, IReadOnlyCollection changes, CancellationToken cancellationToken); + public delegate Task ChangeFeedMonitorErrorDelegate(string leaseToken, Exception exception); + public delegate Task ChangeFeedMonitorLeaseAcquireDelegate(string leaseToken); + public delegate Task ChangeFeedMonitorLeaseReleaseDelegate(string leaseToken); + public delegate Task ChangeFeedStreamHandler(ChangeFeedProcessorContext context, Stream changes, CancellationToken cancellationToken); + public delegate Task ChangeFeedStreamHandlerWithManualCheckpoint(ChangeFeedProcessorContext context, Stream changes, Func checkpointAsync, CancellationToken cancellationToken); + public delegate Task ChangesEstimationHandler(long estimatedPendingChanges, CancellationToken cancellationToken); + public delegate Task ChangesHandler(IReadOnlyCollection changes, CancellationToken cancellationToken); + } + public class ContainerProperties + { + public ContainerProperties(); + public ContainerProperties(string id, IReadOnlyList partitionKeyPaths); + public ContainerProperties(string id, string partitionKeyPath); + public Nullable AnalyticalStoreTimeToLiveInSeconds { get; set; } + public ChangeFeedPolicy ChangeFeedPolicy { get; set; } + public ClientEncryptionPolicy ClientEncryptionPolicy { get; set; } + public Collection ComputedProperties { get; set; } + public ConflictResolutionPolicy ConflictResolutionPolicy { get; set; } + public Nullable DefaultTimeToLive { get; set; } + public string ETag { get; } + public FullTextPolicy FullTextPolicy { get; set; } + public GeospatialConfig GeospatialConfig { get; set; } + public string Id { get; set; } + public IndexingPolicy IndexingPolicy { get; set; } + public Nullable LastModified { get; } + public Nullable PartitionKeyDefinitionVersion { get; set; } + public string PartitionKeyPath { get; set; } + public IReadOnlyList PartitionKeyPaths { get; set; } + public string SelfLink { get; } + public string TimeToLivePropertyPath { get; set; } + public UniqueKeyPolicy UniqueKeyPolicy { get; set; } + public VectorEmbeddingPolicy VectorEmbeddingPolicy { get; set; } + } + public class ContainerRequestOptions : RequestOptions + { + public ContainerRequestOptions(); + public bool PopulateQuotaInfo { get; set; } + } + public class ContainerResponse : Response + { + protected ContainerResponse(); + public override string ActivityId { get; } + public virtual Container Container { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override ContainerProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator Container (ContainerResponse response); + } + public class CosmosClient : IDisposable + { + protected CosmosClient(); + public CosmosClient(string accountEndpoint, AzureKeyCredential authKeyOrResourceTokenCredential, CosmosClientOptions clientOptions=null); + public CosmosClient(string accountEndpoint, TokenCredential tokenCredential, CosmosClientOptions clientOptions=null); + public CosmosClient(string connectionString, CosmosClientOptions clientOptions=null); + public CosmosClient(string accountEndpoint, string authKeyOrResourceToken, CosmosClientOptions clientOptions=null); + public virtual CosmosClientOptions ClientOptions { get; } + public virtual Uri Endpoint { get; } + public virtual CosmosResponseFactory ResponseFactory { get; } + public static Task CreateAndInitializeAsync(string accountEndpoint, AzureKeyCredential authKeyOrResourceTokenCredential, IReadOnlyList> containers, CosmosClientOptions cosmosClientOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public static Task CreateAndInitializeAsync(string accountEndpoint, TokenCredential tokenCredential, IReadOnlyList> containers, CosmosClientOptions cosmosClientOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public static Task CreateAndInitializeAsync(string connectionString, IReadOnlyList> containers, CosmosClientOptions cosmosClientOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public static Task CreateAndInitializeAsync(string accountEndpoint, string authKeyOrResourceToken, IReadOnlyList> containers, CosmosClientOptions cosmosClientOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public virtual Task CreateDatabaseAsync(string id, ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public virtual Task CreateDatabaseAsync(string id, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public virtual Task CreateDatabaseIfNotExistsAsync(string id, ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public virtual Task CreateDatabaseIfNotExistsAsync(string id, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public virtual Task CreateDatabaseStreamAsync(DatabaseProperties databaseProperties, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public void Dispose(); + protected virtual void Dispose(bool disposing); + public virtual Container GetContainer(string databaseId, string containerId); + public virtual Database GetDatabase(string id); + public virtual FeedIterator GetDatabaseQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public virtual FeedIterator GetDatabaseQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public virtual FeedIterator GetDatabaseQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public virtual FeedIterator GetDatabaseQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public virtual Task ReadAccountAsync(); + } + public class CosmosClientOptions + { + public CosmosClientOptions(); + public IEnumerable AccountInitializationCustomEndpoints { get; set; } + public bool AllowBulkExecution { get; set; } + public string ApplicationName { get; set; } + public IReadOnlyList ApplicationPreferredRegions { get; set; } + public string ApplicationRegion { get; set; } + public AvailabilityStrategy AvailabilityStrategy { get; set; } + public ConnectionMode ConnectionMode { get; set; } + public Nullable ConsistencyLevel { get; set; } + public CosmosClientTelemetryOptions CosmosClientTelemetryOptions { get; set; } + public Collection CustomHandlers { get; } + public Nullable EnableContentResponseOnWrite { get; set; } + public bool EnableRemoteRegionPreferredForSessionRetry { get; set; } + public bool EnableTcpConnectionEndpointRediscovery { get; set; } + public IFaultInjector FaultInjector { get; set; } + public int GatewayModeMaxConnectionLimit { get; set; } + public Func HttpClientFactory { get; set; } + public Nullable IdleTcpConnectionTimeout { get; set; } + public bool LimitToEndpoint { get; set; } + public Nullable MaxRequestsPerTcpConnection { get; set; } + public Nullable MaxRetryAttemptsOnRateLimitedRequests { get; set; } + public Nullable MaxRetryWaitTimeOnRateLimitedRequests { get; set; } + public Nullable MaxTcpConnectionsPerEndpoint { get; set; } + public Nullable OpenTcpConnectionTimeout { get; set; } + public Nullable PortReuseMode { get; set; } + public Nullable PriorityLevel { get; set; } + public Nullable ReadConsistencyStrategy { get; set; } + public TimeSpan RequestTimeout { get; set; } + public CosmosSerializer Serializer { get; set; } + public CosmosSerializationOptions SerializerOptions { get; set; } + public Func ServerCertificateCustomValidationCallback { get; set; } + public Nullable ThroughputBucket { get; set; } + public Nullable TokenCredentialBackgroundRefreshInterval { get; set; } + public JsonSerializerOptions UseSystemTextJsonSerializerWithOptions { get; set; } + public IWebProxy WebProxy { get; set; } + } + public class CosmosClientTelemetryOptions + { + public CosmosClientTelemetryOptions(); + public CosmosThresholdOptions CosmosThresholdOptions { get; set; } + public bool DisableDistributedTracing { get; set; } + public bool DisableSendingMetricsToService { get; set; } + public bool IsClientMetricsEnabled { get; set; } + public NetworkMetricsOptions NetworkMetricsOptions { get; set; } + public OperationMetricsOptions OperationMetricsOptions { get; set; } + public QueryTextMode QueryTextMode { get; set; } + } + public sealed class CosmosDbClientMetrics + { + public CosmosDbClientMetrics(); + public static class HistogramBuckets + { + public static readonly double[] RequestLatencyBuckets; + public static readonly double[] RequestUnitBuckets; + public static readonly double[] RowCountBuckets; + } + public static class NetworkMetrics + { + public const string MeterName = "Azure.Cosmos.Client.Request"; + public const string Version = "1.0.0"; + public static class Description + { + public const string BackendLatency = "Backend Latency (for direct mode)."; + public const string ChannelAquisitionLatency = "The duration of the successfully established outbound TCP connections. i.e. Channel Aquisition Time (for direct mode)."; + public const string Latency = "Duration of client requests."; + public const string ReceivedTimeLatency = "Time spent on 'Received' stage (for direct mode)."; + public const string RequestBodySize = "Size of client request body."; + public const string ResponseBodySize = "Size of client response body."; + public const string TransitTimeLatency = "Time spent on the wire (for direct mode)."; + } + public static class Name + { + public const string BackendLatency = "azure.cosmosdb.client.request.service_duration"; + public const string ChannelAquisitionLatency = "azure.cosmosdb.client.request.channel_aquisition.duration"; + public const string Latency = "azure.cosmosdb.client.request.duration"; + public const string ReceivedTimeLatency = "azure.cosmosdb.client.request.received.duration"; + public const string RequestBodySize = "azure.cosmosdb.client.request.body.size"; + public const string ResponseBodySize = "azure.cosmosdb.client.response.body.size"; + public const string TransitTimeLatency = "azure.cosmosdb.client.request.transit.duration"; + } + public static class Unit + { + public const string Bytes = "bytes"; + public const string Sec = "s"; + } + } + public static class OperationMetrics + { + public const string MeterName = "Azure.Cosmos.Client.Operation"; + public const string Version = "1.0.0"; + public static class Description + { + public const string ActiveInstances = "Number of active SDK client instances."; + public const string Latency = "Total end-to-end duration of the operation"; + public const string RequestCharge = "Total request units per operation (sum of RUs for all requested needed when processing an operation)"; + public const string RowCount = "For feed operations (query, readAll, readMany, change feed) batch operations this meter capture the actual item count in responses from the service"; + } + public static class Name + { + public const string ActiveInstances = "azure.cosmosdb.client.active_instance.count"; + public const string Latency = "db.client.operation.duration"; + public const string RequestCharge = "azure.cosmosdb.client.operation.request_charge"; + public const string RowCount = "db.client.response.returned_rows"; + } + public static class Unit + { + public const string Instance = "{instance}"; + public const string Item = "{item}"; + public const string RequestUnit = "{request_unit}"; + public const string Sec = "s"; + } + } + } + public abstract class CosmosDiagnostics + { + protected CosmosDiagnostics(); + public virtual TimeSpan GetClientElapsedTime(); + public abstract IReadOnlyList> GetContactedRegions(); + public virtual int GetFailedRequestCount(); + public virtual ServerSideCumulativeMetrics GetQueryMetrics(); + public virtual Nullable GetStartTimeUtc(); + public abstract override string ToString(); + } + public class CosmosException : Exception, ICloneable + { + public CosmosException(string message, HttpStatusCode statusCode, int subStatusCode, string activityId, double requestCharge); + public virtual string ActivityId { get; } + public virtual CosmosDiagnostics Diagnostics { get; } + public virtual Headers Headers { get; } + public override string Message { get; } + public virtual double RequestCharge { get; } + public virtual string ResponseBody { get; } + public virtual Nullable RetryAfter { get; } + public override string StackTrace { get; } + public virtual HttpStatusCode StatusCode { get; } + public virtual int SubStatusCode { get; } + public object Clone(); + public override string ToString(); + public virtual bool TryGetHeader(string headerName, out string value); + } + public abstract class CosmosLinqSerializer : CosmosSerializer + { + protected CosmosLinqSerializer(); + public abstract string SerializeMemberName(MemberInfo memberInfo); + } + public sealed class CosmosLinqSerializerOptions + { + public CosmosLinqSerializerOptions(); + public CosmosPropertyNamingPolicy PropertyNamingPolicy { get; set; } + } + public class CosmosOperationCanceledException : OperationCanceledException, ICloneable + { + public CosmosOperationCanceledException(OperationCanceledException originalException, CosmosDiagnostics diagnostics); + protected CosmosOperationCanceledException(SerializationInfo info, StreamingContext context); + public override IDictionary Data { get; } + public CosmosDiagnostics Diagnostics { get; } + public override string HelpLink { get; set; } + public override string Message { get; } + public override string Source { get; set; } + public override string StackTrace { get; } + public object Clone(); + public override Exception GetBaseException(); + public override void GetObjectData(SerializationInfo info, StreamingContext context); + public override string ToString(); + } + public enum CosmosPropertyNamingPolicy + { + CamelCase = 1, + Default = 0, + } + public abstract class CosmosResponseFactory + { + protected CosmosResponseFactory(); + public abstract FeedResponse CreateItemFeedResponse(ResponseMessage responseMessage); + public abstract ItemResponse CreateItemResponse(ResponseMessage responseMessage); + public abstract StoredProcedureExecuteResponse CreateStoredProcedureExecuteResponse(ResponseMessage responseMessage); + } + public sealed class CosmosSerializationOptions + { + public CosmosSerializationOptions(); + public bool IgnoreNullValues { get; set; } + public bool Indented { get; set; } + public CosmosPropertyNamingPolicy PropertyNamingPolicy { get; set; } + } + public abstract class CosmosSerializer + { + protected CosmosSerializer(); + public abstract T FromStream(Stream stream); + public abstract Stream ToStream(T input); + } + public class CosmosThresholdOptions + { + public CosmosThresholdOptions(); + public TimeSpan NonPointOperationLatencyThreshold { get; set; } + public Nullable PayloadSizeThresholdInBytes { get; set; } + public TimeSpan PointOperationLatencyThreshold { get; set; } + public Nullable RequestChargeThreshold { get; set; } + } + public abstract class Database + { + protected Database(); + public abstract CosmosClient Client { get; } + public abstract string Id { get; } + public abstract Task CreateClientEncryptionKeyAsync(ClientEncryptionKeyProperties clientEncryptionKeyProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerAsync(ContainerProperties containerProperties, ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerAsync(ContainerProperties containerProperties, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerAsync(string id, string partitionKeyPath, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerIfNotExistsAsync(ContainerProperties containerProperties, ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerIfNotExistsAsync(ContainerProperties containerProperties, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerIfNotExistsAsync(string id, string partitionKeyPath, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerStreamAsync(ContainerProperties containerProperties, ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateContainerStreamAsync(ContainerProperties containerProperties, Nullable throughput=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateUserAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract ContainerBuilder DefineContainer(string name, string partitionKeyPath); + public abstract Task DeleteAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteStreamAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract ClientEncryptionKey GetClientEncryptionKey(string id); + public abstract FeedIterator GetClientEncryptionKeyQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract Container GetContainer(string id); + public abstract FeedIterator GetContainerQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetContainerQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetContainerQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetContainerQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract User GetUser(string id); + public abstract FeedIterator GetUserQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetUserQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract Task ReadAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadStreamAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadThroughputAsync(RequestOptions requestOptions, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ReadThroughputAsync(CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceThroughputAsync(ThroughputProperties throughputProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceThroughputAsync(int throughput, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task UpsertUserAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + } + public class DatabaseProperties + { + public DatabaseProperties(); + public DatabaseProperties(string id); + public string ETag { get; } + public string Id { get; set; } + public Nullable LastModified { get; } + public string SelfLink { get; } + } + public class DatabaseResponse : Response + { + protected DatabaseResponse(); + public override string ActivityId { get; } + public virtual Database Database { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override DatabaseProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator Database (DatabaseResponse response); + } + public enum DataType + { + LineString = 3, + MultiPolygon = 5, + Number = 0, + Point = 2, + Polygon = 4, + String = 1, + } + public class DedicatedGatewayRequestOptions + { + public DedicatedGatewayRequestOptions(); + public Nullable BypassIntegratedCache { get; set; } + public Nullable MaxIntegratedCacheStaleness { get; set; } + } + public enum DistanceFunction + { + Cosine = 1, + DotProduct = 2, + Euclidean = 0, + } + public class Embedding : IEquatable + { + public Embedding(); + public VectorDataType DataType { get; set; } + public int Dimensions { get; set; } + public DistanceFunction DistanceFunction { get; set; } + public string Path { get; set; } + public bool Equals(Embedding that); + public void ValidateEmbeddingPath(); + } + public class EncryptionKeyWrapMetadata : IEquatable + { + public EncryptionKeyWrapMetadata(EncryptionKeyWrapMetadata source); + public EncryptionKeyWrapMetadata(string type, string name, string value, string algorithm); + public string Algorithm { get; } + public string Name { get; } + public string Type { get; } + public string Value { get; } + public bool Equals(EncryptionKeyWrapMetadata other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class ExcludedPath + { + public ExcludedPath(); + public string Path { get; set; } + } + public abstract class FeedIterator : IDisposable + { + protected FeedIterator(); + public abstract bool HasMoreResults { get; } + public void Dispose(); + protected virtual void Dispose(bool disposing); + public abstract Task ReadNextAsync(CancellationToken cancellationToken=default(CancellationToken)); + } + public abstract class FeedIterator : IDisposable + { + protected FeedIterator(); + public abstract bool HasMoreResults { get; } + public void Dispose(); + protected virtual void Dispose(bool disposing); + public abstract Task> ReadNextAsync(CancellationToken cancellationToken=default(CancellationToken)); + } + public abstract class FeedRange + { + protected FeedRange(); + public static FeedRange FromJsonString(string toStringValue); + public static FeedRange FromPartitionKey(PartitionKey partitionKey); + public abstract string ToJsonString(); + } + public abstract class FeedResponse : IEnumerable, IEnumerable + { + protected FeedResponse(); + public override string ActivityId { get; } + public abstract string ContinuationToken { get; } + public abstract int Count { get; } + public override string ETag { get; } + public abstract string IndexMetrics { get; } + public virtual string QueryAdvice { get; } + public override double RequestCharge { get; } + public abstract IEnumerator GetEnumerator(); + IEnumerator System.Collections.IEnumerable.GetEnumerator(); + } + public sealed class FullTextIndexPath + { + public FullTextIndexPath(); + public string Path { get; set; } + } + public class FullTextPath : IEquatable + { + public FullTextPath(); + public string Language { get; set; } + public string Path { get; set; } + public bool Equals(FullTextPath that); + public void ValidateFullTextPath(); + } + public sealed class FullTextPolicy + { + public FullTextPolicy(); + public string DefaultLanguage { get; set; } + public Collection FullTextPaths { get; set; } + } + public enum FullTextScoreScope + { + Global = 0, + Local = 1, + } + public sealed class GeospatialConfig + { + public GeospatialConfig(); + public GeospatialConfig(GeospatialType geospatialType); + public GeospatialType GeospatialType { get; set; } + } + public enum GeospatialType + { + Geography = 0, + Geometry = 1, + } + public class Headers : IEnumerable + { + public Headers(); + public virtual string ActivityId { get; } + public virtual string ContentLength { get; set; } + public virtual string ContentType { get; } + public virtual string ContinuationToken { get; } + public virtual string ETag { get; } + public virtual string this[string headerName] { get; set; } + public virtual string Location { get; } + public virtual double RequestCharge { get; } + public virtual string Session { get; } + public virtual void Add(string headerName, IEnumerable values); + public virtual void Add(string headerName, string value); + public virtual string[] AllKeys(); + public virtual string Get(string headerName); + public virtual IEnumerator GetEnumerator(); + public virtual T GetHeaderValue(string headerName); + public virtual string GetValueOrDefault(string headerName); + public virtual void Remove(string headerName); + public virtual void Set(string headerName, string value); + IEnumerator System.Collections.IEnumerable.GetEnumerator(); + public virtual bool TryGetValue(string headerName, out string value); + } + public sealed class IncludedPath + { + public IncludedPath(); + public string Path { get; set; } + } + public enum IndexingDirective + { + Default = 0, + Exclude = 2, + Include = 1, + } + public enum IndexingMode + { + Consistent = 0, + Lazy = 1, + None = 2, + } + public sealed class IndexingPolicy + { + public IndexingPolicy(); + public bool Automatic { get; set; } + public Collection> CompositeIndexes { get; } + public Collection ExcludedPaths { get; } + public Collection FullTextIndexes { get; set; } + public Collection IncludedPaths { get; } + public IndexingMode IndexingMode { get; set; } + public Collection SpatialIndexes { get; } + public Collection VectorIndexes { get; set; } + } + public enum IndexKind + { + Hash = 0, + Range = 1, + Spatial = 2, + } + public class ItemRequestOptions : RequestOptions + { + public ItemRequestOptions(); + public Nullable ConsistencyLevel { get; set; } + public DedicatedGatewayRequestOptions DedicatedGatewayRequestOptions { get; set; } + public Nullable EnableContentResponseOnWrite { get; set; } + public Nullable IndexingDirective { get; set; } + public IEnumerable PostTriggers { get; set; } + public IEnumerable PreTriggers { get; set; } + public Nullable ReadConsistencyStrategy { get; set; } + public string SessionToken { get; set; } + } + public class ItemResponse : Response + { + protected ItemResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override T Resource { get; } + public override HttpStatusCode StatusCode { get; } + } + public class NetworkMetricsOptions + { + public NetworkMetricsOptions(); + public IDictionary CustomDimensions { get; set; } + public Nullable IncludeRoutingId { get; set; } + } + public enum OperationKind + { + Create = 1, + Delete = 3, + Invalid = 0, + Read = 4, + Replace = 2, + } + public class OperationMetricsOptions + { + public OperationMetricsOptions(); + public IDictionary CustomDimensions { get; set; } + public Nullable IncludeRegion { get; set; } + } + public struct PartitionKey : IEquatable + { + public static readonly PartitionKey None; + public static readonly PartitionKey Null; + public static readonly string SystemKeyName; + public static readonly string SystemKeyPath; + public PartitionKey(bool partitionKeyValue); + public PartitionKey(double partitionKeyValue); + public PartitionKey(string partitionKeyValue); + public bool Equals(PartitionKey other); + public override bool Equals(object obj); + public override int GetHashCode(); + public static bool operator ==(PartitionKey left, PartitionKey right); + public static bool operator !=(PartitionKey left, PartitionKey right); + public override string ToString(); + } + public sealed class PartitionKeyBuilder + { + public PartitionKeyBuilder(); + public PartitionKeyBuilder Add(bool val); + public PartitionKeyBuilder Add(double val); + public PartitionKeyBuilder Add(string val); + public PartitionKeyBuilder AddNoneType(); + public PartitionKeyBuilder AddNullValue(); + public PartitionKey Build(); + } + public enum PartitionKeyDefinitionVersion + { + V1 = 1, + V2 = 2, + } + public sealed class PatchItemRequestOptions : ItemRequestOptions + { + public PatchItemRequestOptions(); + public string FilterPredicate { get; set; } + } + public abstract class PatchOperation + { + protected PatchOperation(); + public virtual string From { get; set; } + public abstract PatchOperationType OperationType { get; } + public abstract string Path { get; } + public static PatchOperation Add(string path, T value); + public static PatchOperation Increment(string path, double value); + public static PatchOperation Increment(string path, long value); + public static PatchOperation Move(string from, string path); + public static PatchOperation Remove(string path); + public static PatchOperation Replace(string path, T value); + public static PatchOperation Set(string path, T value); + public virtual bool TrySerializeValueParameter(CosmosSerializer cosmosSerializer, out Stream valueParam); + } + public enum PatchOperationType + { + Add = 0, + Increment = 4, + Move = 5, + Remove = 1, + Replace = 2, + Set = 3, + } + public abstract class PatchOperation : PatchOperation + { + protected PatchOperation(); + public abstract T Value { get; } + } + public abstract class Permission + { + protected Permission(); + public abstract string Id { get; } + public abstract Task DeleteAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadAsync(Nullable tokenExpiryInSeconds=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceAsync(PermissionProperties permissionProperties, Nullable tokenExpiryInSeconds=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + } + public enum PermissionMode : byte + { + All = (byte)2, + Read = (byte)1, + } + public class PermissionProperties + { + public PermissionProperties(string id, PermissionMode permissionMode, Container container, PartitionKey resourcePartitionKey, string itemId); + public PermissionProperties(string id, PermissionMode permissionMode, Container container, Nullable resourcePartitionKey=default(Nullable)); + public string ETag { get; } + public string Id { get; } + public Nullable LastModified { get; } + public PermissionMode PermissionMode { get; } + public Nullable ResourcePartitionKey { get; set; } + public string ResourceUri { get; } + public string SelfLink { get; } + public string Token { get; } + } + public class PermissionResponse : Response + { + protected PermissionResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public virtual Permission Permission { get; } + public override double RequestCharge { get; } + public override PermissionProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator Permission (PermissionResponse response); + } + public enum PortReuseMode + { + PrivatePortPool = 1, + ReuseUnicastPort = 0, + } + public enum PriorityLevel + { + High = 1, + Low = 2, + } + public enum QuantizerType + { + Product = 0, + Spherical = 1, + } + public class QueryDefinition + { + public QueryDefinition(string query); + public string QueryText { get; } + public IReadOnlyList> GetQueryParameters(); + public QueryDefinition WithParameter(string name, object value); + public QueryDefinition WithParameterStream(string name, Stream valueStream); + } + public class QueryRequestOptions : RequestOptions + { + public QueryRequestOptions(); + public Nullable ConsistencyLevel { get; set; } + public DedicatedGatewayRequestOptions DedicatedGatewayRequestOptions { get; set; } + public Nullable EnableLowPrecisionOrderBy { get; set; } + public bool EnableOptimisticDirectExecution { get; set; } + public Nullable EnableScanInQuery { get; set; } + public FullTextScoreScope FullTextScoreScope { get; set; } + public Nullable MaxBufferedItemCount { get; set; } + public Nullable MaxConcurrency { get; set; } + public Nullable MaxItemCount { get; set; } + public Nullable PartitionKey { get; set; } + public Nullable PopulateIndexMetrics { get; set; } + public Nullable PopulateQueryAdvice { get; set; } + public QueryTextMode QueryTextMode { get; set; } + public Nullable ReadConsistencyStrategy { get; set; } + public Nullable ResponseContinuationTokenLimitInKb { get; set; } + public string SessionToken { get; set; } + } + public enum QueryTextMode + { + All = 2, + None = 0, + ParameterizedOnly = 1, + } + public enum ReadConsistencyStrategy + { + Eventual = 1, + GlobalStrong = 4, + LatestCommitted = 3, + Session = 2, + } + public class ReadManyRequestOptions : RequestOptions + { + public ReadManyRequestOptions(); + public Nullable ConsistencyLevel { get; set; } + public Nullable ReadConsistencyStrategy { get; set; } + public string SessionToken { get; set; } + } + public static class Regions + { + public const string AustraliaCentral = "Australia Central"; + public const string AustraliaCentral2 = "Australia Central 2"; + public const string AustraliaEast = "Australia East"; + public const string AustraliaSoutheast = "Australia Southeast"; + public const string AustriaEast = "Austria East"; + public const string BelgiumCentral = "Belgium Central"; + public const string BleuFranceCentral = "Bleu France Central"; + public const string BleuFranceSouth = "Bleu France South"; + public const string BrazilSouth = "Brazil South"; + public const string BrazilSoutheast = "Brazil Southeast"; + public const string CanadaCentral = "Canada Central"; + public const string CanadaEast = "Canada East"; + public const string CentralIndia = "Central India"; + public const string CentralUS = "Central US"; + public const string CentralUSEUAP = "Central US EUAP"; + public const string ChileCentral = "Chile Central"; + public const string ChinaEast = "China East"; + public const string ChinaEast2 = "China East 2"; + public const string ChinaEast3 = "China East 3"; + public const string ChinaNorth = "China North"; + public const string ChinaNorth2 = "China North 2"; + public const string ChinaNorth3 = "China North 3"; + public const string DelosCloudGermanyCentral = "Delos Cloud Germany Central"; + public const string DelosCloudGermanyNorth = "Delos Cloud Germany North"; + public const string DenmarkEast = "Denmark East"; + public const string EastAsia = "East Asia"; + public const string EastUS = "East US"; + public const string EastUS2 = "East US 2"; + public const string EastUS2EUAP = "East US 2 EUAP"; + public const string EastUS3 = "East US 3"; + public const string EastUSSLV = "East US SLV"; + public const string FranceCentral = "France Central"; + public const string FranceSouth = "France South"; + public const string GermanyNorth = "Germany North"; + public const string GermanyWestCentral = "Germany West Central"; + public const string IndiaSouthCentral = "India South Central"; + public const string IndonesiaCentral = "Indonesia Central"; + public const string IsraelCentral = "Israel Central"; + public const string IsraelNorthwest = "Israel Northwest"; + public const string ItalyNorth = "Italy North"; + public const string JapanEast = "Japan East"; + public const string JapanWest = "Japan West"; + public const string JioIndiaCentral = "Jio India Central"; + public const string JioIndiaWest = "Jio India West"; + public const string KoreaCentral = "Korea Central"; + public const string KoreaSouth = "Korea South"; + public const string MalaysiaSouth = "Malaysia South"; + public const string MalaysiaWest = "Malaysia West"; + public const string MexicoCentral = "Mexico Central"; + public const string NewZealandNorth = "New Zealand North"; + public const string NorthCentralUS = "North Central US"; + public const string NortheastUS5 = "Northeast US 5"; + public const string NorthEurope = "North Europe"; + public const string NorwayEast = "Norway East"; + public const string NorwayWest = "Norway West"; + public const string PolandCentral = "Poland Central"; + public const string QatarCentral = "Qatar Central"; + public const string SingaporeCentral = "Singapore Central"; + public const string SingaporeNorth = "Singapore North"; + public const string SouthAfricaNorth = "South Africa North"; + public const string SouthAfricaWest = "South Africa West"; + public const string SouthCentralUS = "South Central US"; + public const string SouthCentralUS2 = "South Central US 2"; + public const string SoutheastAsia = "Southeast Asia"; + public const string SoutheastUS = "Southeast US"; + public const string SoutheastUS3 = "Southeast US 3"; + public const string SoutheastUS5 = "Southeast US 5"; + public const string SouthIndia = "South India"; + public const string SouthwestUS = "Southwest US"; + public const string SpainCentral = "Spain Central"; + public const string SwedenCentral = "Sweden Central"; + public const string SwedenSouth = "Sweden South"; + public const string SwitzerlandNorth = "Switzerland North"; + public const string SwitzerlandWest = "Switzerland West"; + public const string TaiwanNorth = "Taiwan North"; + public const string TaiwanNorthwest = "Taiwan Northwest"; + public const string UAECentral = "UAE Central"; + public const string UAENorth = "UAE North"; + public const string UKSouth = "UK South"; + public const string UKWest = "UK West"; + public const string USDoDCentral = "USDoD Central"; + public const string USDoDEast = "USDoD East"; + public const string USGovArizona = "USGov Arizona"; + public const string USGovTexas = "USGov Texas"; + public const string USGovVirginia = "USGov Virginia"; + public const string USNatEast = "USNat East"; + public const string USNatWest = "USNat West"; + public const string USSecEast = "USSec East"; + public const string USSecWest = "USSec West"; + public const string USSecWestCentral = "USSec West Central"; + public const string WestCentralUS = "West Central US"; + public const string WestEurope = "West Europe"; + public const string WestIndia = "West India"; + public const string WestUS = "West US"; + public const string WestUS2 = "West US 2"; + public const string WestUS3 = "West US 3"; + } + public abstract class RequestHandler + { + protected RequestHandler(); + public RequestHandler InnerHandler { get; set; } + public virtual Task SendAsync(RequestMessage request, CancellationToken cancellationToken); + } + public class RequestMessage : IDisposable + { + public RequestMessage(); + public RequestMessage(HttpMethod method, Uri requestUri); + public virtual Stream Content { get; set; } + public virtual Headers Headers { get; } + public virtual HttpMethod Method { get; } + public virtual Dictionary Properties { get; } + public virtual Uri RequestUri { get; } + public void Dispose(); + protected virtual void Dispose(bool disposing); + } + public class RequestOptions + { + public RequestOptions(); + public Action AddRequestHeaders { get; set; } + public AvailabilityStrategy AvailabilityStrategy { get; set; } + public CosmosThresholdOptions CosmosThresholdOptions { get; set; } + public List ExcludeRegions { get; set; } + public string IfMatchEtag { get; set; } + public string IfNoneMatchEtag { get; set; } + public NetworkMetricsOptions NetworkMetricsOptions { get; set; } + public OperationMetricsOptions OperationMetricsOptions { get; set; } + public Nullable PriorityLevel { get; set; } + public IReadOnlyDictionary Properties { get; set; } + public Nullable ThroughputBucket { get; set; } + public RequestOptions ShallowCopy(); + } + public class RerankScore + { + public RerankScore(string document, double score, int index); + public string Document { get; } + public int Index { get; } + public double Score { get; } + } + public class ResponseMessage : IDisposable + { + public ResponseMessage(); + public ResponseMessage(HttpStatusCode statusCode, RequestMessage requestMessage=null, string errorMessage=null); + public virtual Stream Content { get; set; } + public virtual string ContinuationToken { get; } + public virtual CosmosDiagnostics Diagnostics { get; set; } + public virtual string ErrorMessage { get; } + public virtual Headers Headers { get; } + public string IndexMetrics { get; } + public virtual bool IsSuccessStatusCode { get; } + public virtual RequestMessage RequestMessage { get; } + public virtual HttpStatusCode StatusCode { get; } + public void Dispose(); + protected virtual void Dispose(bool disposing); + public virtual ResponseMessage EnsureSuccessStatusCode(); + } + public abstract class Response + { + protected Response(); + public abstract string ActivityId { get; } + public abstract CosmosDiagnostics Diagnostics { get; } + public abstract string ETag { get; } + public abstract Headers Headers { get; } + public abstract double RequestCharge { get; } + public abstract T Resource { get; } + public abstract HttpStatusCode StatusCode { get; } + public static implicit operator T (Response response); + } + public class SemanticRerankResult + { + public HttpResponseHeaders Headers { get; } + public Dictionary Latency { get; } + public IReadOnlyList RerankScores { get; } + public Dictionary TokenUseage { get; } + } + public abstract class ServerSideCumulativeMetrics + { + protected ServerSideCumulativeMetrics(); + public abstract ServerSideMetrics CumulativeMetrics { get; } + public abstract IReadOnlyList PartitionedMetrics { get; } + public abstract double TotalRequestCharge { get; } + } + public abstract class ServerSideMetrics + { + protected ServerSideMetrics(); + public abstract TimeSpan DocumentLoadTime { get; } + public abstract TimeSpan DocumentWriteTime { get; } + public abstract double IndexHitRatio { get; } + public abstract TimeSpan IndexLookupTime { get; } + public abstract long OutputDocumentCount { get; } + public abstract long OutputDocumentSize { get; } + public abstract TimeSpan QueryPreparationTime { get; } + public abstract long RetrievedDocumentCount { get; } + public abstract long RetrievedDocumentSize { get; } + public abstract TimeSpan RuntimeExecutionTime { get; } + public abstract TimeSpan TotalTime { get; } + public abstract TimeSpan VMExecutionTime { get; } + } + public abstract class ServerSidePartitionedMetrics + { + protected ServerSidePartitionedMetrics(); + public abstract string FeedRange { get; } + public abstract Nullable PartitionKeyRangeId { get; } + public abstract double RequestCharge { get; } + public abstract ServerSideMetrics ServerSideMetrics { get; } + } + public sealed class SpatialPath + { + public SpatialPath(); + public BoundingBoxProperties BoundingBox { get; set; } + public string Path { get; set; } + public Collection SpatialTypes { get; } + } + public enum SpatialType + { + LineString = 1, + MultiPolygon = 3, + Point = 0, + Polygon = 2, + } + public class ThroughputProperties + { + public Nullable AutoscaleMaxThroughput { get; } + public string ETag { get; } + public Nullable LastModified { get; } + public string SelfLink { get; } + public Nullable Throughput { get; } + public static ThroughputProperties CreateAutoscaleThroughput(int autoscaleMaxThroughput); + public static ThroughputProperties CreateManualThroughput(int throughput); + } + public class ThroughputResponse : Response + { + protected ThroughputResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public Nullable IsReplacePending { get; } + public Nullable MinThroughput { get; } + public override double RequestCharge { get; } + public override ThroughputProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator ThroughputProperties (ThroughputResponse response); + } + public abstract class TransactionalBatch + { + protected TransactionalBatch(); + public abstract TransactionalBatch CreateItemStream(Stream streamPayload, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch CreateItem(T item, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch DeleteItem(string id, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract Task ExecuteAsync(TransactionalBatchRequestOptions requestOptions, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ExecuteAsync(CancellationToken cancellationToken=default(CancellationToken)); + public abstract TransactionalBatch PatchItem(string id, IReadOnlyList patchOperations, TransactionalBatchPatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch ReadItem(string id, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch ReplaceItemStream(string id, Stream streamPayload, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch ReplaceItem(string id, T item, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch UpsertItemStream(Stream streamPayload, TransactionalBatchItemRequestOptions requestOptions=null); + public abstract TransactionalBatch UpsertItem(T item, TransactionalBatchItemRequestOptions requestOptions=null); + } + public class TransactionalBatchItemRequestOptions : RequestOptions + { + public TransactionalBatchItemRequestOptions(); + public Nullable EnableContentResponseOnWrite { get; set; } + public Nullable IndexingDirective { get; set; } + } + public class TransactionalBatchOperationResult + { + protected TransactionalBatchOperationResult(); + public virtual string ETag { get; } + public virtual bool IsSuccessStatusCode { get; } + public virtual Stream ResourceStream { get; } + public virtual TimeSpan RetryAfter { get; } + public virtual HttpStatusCode StatusCode { get; } + } + public class TransactionalBatchOperationResult : TransactionalBatchOperationResult + { + protected TransactionalBatchOperationResult(); + public virtual T Resource { get; set; } + } + public class TransactionalBatchPatchItemRequestOptions : TransactionalBatchItemRequestOptions + { + public TransactionalBatchPatchItemRequestOptions(); + public string FilterPredicate { get; set; } + } + public class TransactionalBatchRequestOptions : RequestOptions + { + public TransactionalBatchRequestOptions(); + public Nullable ConsistencyLevel { get; set; } + public string SessionToken { get; set; } + } + public class TransactionalBatchResponse : IDisposable, IEnumerable, IEnumerable, IReadOnlyCollection, IReadOnlyList + { + protected TransactionalBatchResponse(); + public virtual string ActivityId { get; } + public virtual int Count { get; } + public virtual CosmosDiagnostics Diagnostics { get; } + public virtual string ErrorMessage { get; } + public virtual Headers Headers { get; } + public virtual bool IsSuccessStatusCode { get; } + public virtual TransactionalBatchOperationResult this[int index] { get; } + public virtual double RequestCharge { get; } + public virtual Nullable RetryAfter { get; } + public virtual HttpStatusCode StatusCode { get; } + public void Dispose(); + protected virtual void Dispose(bool disposing); + public virtual IEnumerator GetEnumerator(); + public virtual TransactionalBatchOperationResult GetOperationResultAtIndex(int index); + IEnumerator System.Collections.IEnumerable.GetEnumerator(); + } + public class UniqueKey + { + public UniqueKey(); + public Collection Paths { get; } + } + public sealed class UniqueKeyPolicy + { + public UniqueKeyPolicy(); + public Collection UniqueKeys { get; } + } + public abstract class User + { + protected User(); + public abstract string Id { get; } + public abstract Task CreatePermissionAsync(PermissionProperties permissionProperties, Nullable tokenExpiryInSeconds=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Permission GetPermission(string id); + public abstract FeedIterator GetPermissionQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetPermissionQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract Task ReadAsync(RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceAsync(UserProperties userProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task UpsertPermissionAsync(PermissionProperties permissionProperties, Nullable tokenExpiryInSeconds=default(Nullable), RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + } + public class UserProperties + { + protected UserProperties(); + public UserProperties(string id); + public string ETag { get; } + public string Id { get; set; } + public Nullable LastModified { get; } + public string SelfLink { get; } + } + public class UserResponse : Response + { + protected UserResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override UserProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public virtual User User { get; } + public static implicit operator User (UserResponse response); + } + public enum VectorDataType + { + Float16 = 3, + Float32 = 0, + Int8 = 2, + Uint8 = 1, + } + public sealed class VectorEmbeddingPolicy + { + public readonly Collection Embeddings; + public VectorEmbeddingPolicy(Collection embeddings); + } + public sealed class VectorIndexPath + { + public VectorIndexPath(); + public int IndexingSearchListSize { get; set; } + public string Path { get; set; } + public int QuantizationByteSize { get; set; } + public Nullable QuantizerType { get; set; } + public VectorIndexType Type { get; set; } + public string[] VectorIndexShardKey { get; set; } + } + public enum VectorIndexType + { + DiskANN = 1, + Flat = 0, + QuantizedFlat = 2, + } +} +namespace Microsoft.Azure.Cosmos.FaultInjection +{ + public interface IFaultInjector + { + } +} +namespace Microsoft.Azure.Cosmos.Fluent +{ + public class ChangeFeedPolicyDefinition + { + public ContainerBuilder Attach(); + } + public sealed class ClientEncryptionPolicyDefinition + { + public ContainerBuilder Attach(); + public ClientEncryptionPolicyDefinition WithIncludedPath(ClientEncryptionIncludedPath path); + } + public class CompositeIndexDefinition + { + public T Attach(); + public CompositeIndexDefinition Path(string path); + public CompositeIndexDefinition Path(string path, CompositePathSortOrder sortOrder); + } + public class ComputedPropertiesDefinition + { + public T Attach(); + public ComputedPropertiesDefinition WithComputedProperty(string name, string query); + } + public class ConflictResolutionDefinition + { + public ContainerBuilder Attach(); + public ConflictResolutionDefinition WithCustomStoredProcedureResolution(string conflictResolutionProcedure); + public ConflictResolutionDefinition WithLastWriterWinsResolution(string conflictResolutionPath); + } + public class ContainerBuilder : ContainerDefinition + { + protected ContainerBuilder(); + public ContainerBuilder(Database database, string name, string partitionKeyPath); + public new ContainerProperties Build(); + public Task CreateAsync(ThroughputProperties throughputProperties, CancellationToken cancellationToken=default(CancellationToken)); + public Task CreateAsync(Nullable throughput=default(Nullable), CancellationToken cancellationToken=default(CancellationToken)); + public Task CreateIfNotExistsAsync(ThroughputProperties throughputProperties, CancellationToken cancellationToken=default(CancellationToken)); + public Task CreateIfNotExistsAsync(Nullable throughput=default(Nullable), CancellationToken cancellationToken=default(CancellationToken)); + public ChangeFeedPolicyDefinition WithChangeFeedPolicy(TimeSpan retention); + public ClientEncryptionPolicyDefinition WithClientEncryptionPolicy(); + public ClientEncryptionPolicyDefinition WithClientEncryptionPolicy(int policyFormatVersion); + public ConflictResolutionDefinition WithConflictResolution(); + public FullTextPolicyDefinition WithFullTextPolicy(string defaultLanguage, Collection fullTextPaths); + public UniqueKeyDefinition WithUniqueKey(); + public VectorEmbeddingPolicyDefinition WithVectorEmbeddingPolicy(Collection embeddings); + } + public abstract class ContainerDefinition where T : ContainerDefinition + { + public ContainerDefinition(); + public ContainerProperties Build(); + public ComputedPropertiesDefinition WithComputedProperties(); + public T WithDefaultTimeToLive(int defaultTtlInSeconds); + public T WithDefaultTimeToLive(TimeSpan defaultTtlTimeSpan); + public IndexingPolicyDefinition WithIndexingPolicy(); + public T WithPartitionKeyDefinitionVersion(PartitionKeyDefinitionVersion partitionKeyDefinitionVersion); + public T WithTimeToLivePropertyPath(string propertyPath); + } + public class CosmosClientBuilder + { + public CosmosClientBuilder(string connectionString); + public CosmosClientBuilder(string accountEndpoint, AzureKeyCredential authKeyOrResourceTokenCredential); + public CosmosClientBuilder(string accountEndpoint, TokenCredential tokenCredential); + public CosmosClientBuilder(string accountEndpoint, string authKeyOrResourceToken); + public CosmosClientBuilder AddCustomHandlers(params RequestHandler[] customHandlers); + public CosmosClient Build(); + public Task BuildAndInitializeAsync(IReadOnlyList> containers, CancellationToken cancellationToken=default(CancellationToken)); + public CosmosClientBuilder WithApplicationName(string applicationName); + public CosmosClientBuilder WithApplicationPreferredRegions(IReadOnlyList applicationPreferredRegions); + public CosmosClientBuilder WithApplicationRegion(string applicationRegion); + public CosmosClientBuilder WithAvailabilityStrategy(AvailabilityStrategy strategy); + public CosmosClientBuilder WithBulkExecution(bool enabled); + public CosmosClientBuilder WithClientTelemetryOptions(CosmosClientTelemetryOptions options); + public CosmosClientBuilder WithConnectionModeDirect(); + public CosmosClientBuilder WithConnectionModeDirect(Nullable idleTcpConnectionTimeout=default(Nullable), Nullable openTcpConnectionTimeout=default(Nullable), Nullable maxRequestsPerTcpConnection=default(Nullable), Nullable maxTcpConnectionsPerEndpoint=default(Nullable), Nullable portReuseMode=default(Nullable), Nullable enableTcpConnectionEndpointRediscovery=default(Nullable)); + public CosmosClientBuilder WithConnectionModeGateway(Nullable maxConnectionLimit=default(Nullable), IWebProxy webProxy=null); + public CosmosClientBuilder WithConsistencyLevel(ConsistencyLevel consistencyLevel); + public CosmosClientBuilder WithContentResponseOnWrite(bool contentResponseOnWrite); + public CosmosClientBuilder WithCustomAccountEndpoints(IEnumerable customAccountEndpoints); + public CosmosClientBuilder WithCustomSerializer(CosmosSerializer cosmosJsonSerializer); + public CosmosClientBuilder WithEnableRemoteRegionPreferredForSessionRetry(bool enableRemoteRegionPreferredForSessionRetry); + public CosmosClientBuilder WithFaultInjection(IFaultInjector faultInjector); + public CosmosClientBuilder WithHttpClientFactory(Func httpClientFactory); + public CosmosClientBuilder WithLimitToEndpoint(bool limitToEndpoint); + public CosmosClientBuilder WithPriorityLevel(PriorityLevel priorityLevel); + public CosmosClientBuilder WithReadConsistencyStrategy(ReadConsistencyStrategy readConsistencyStrategy); + public CosmosClientBuilder WithRequestTimeout(TimeSpan requestTimeout); + public CosmosClientBuilder WithSerializerOptions(CosmosSerializationOptions cosmosSerializerOptions); + public CosmosClientBuilder WithSystemTextJsonSerializerOptions(JsonSerializerOptions serializerOptions); + public CosmosClientBuilder WithThrottlingRetryOptions(TimeSpan maxRetryWaitTimeOnThrottledRequests, int maxRetryAttemptsOnThrottledRequests); + public CosmosClientBuilder WithThroughputBucket(int throughputBucket); + } + public class FullTextIndexDefinition + { + public FullTextIndexDefinition(T parent, Action attachCallback); + public T Attach(); + public FullTextIndexDefinition Path(string path); + } + public class FullTextPolicyDefinition + { + public FullTextPolicyDefinition(ContainerBuilder parent, string defaultLanguage, Collection fullTextPaths, Action attachCallback); + public ContainerBuilder Attach(); + } + public class IndexingPolicyDefinition + { + public IndexingPolicyDefinition(); + public T Attach(); + public IndexingPolicyDefinition WithAutomaticIndexing(bool enabled); + public CompositeIndexDefinition> WithCompositeIndex(); + public PathsDefinition> WithExcludedPaths(); + public FullTextIndexDefinition> WithFullTextIndex(); + public PathsDefinition> WithIncludedPaths(); + public IndexingPolicyDefinition WithIndexingMode(IndexingMode indexingMode); + public SpatialIndexDefinition> WithSpatialIndex(); + public VectorIndexDefinition> WithVectorIndex(); + } + public class PathsDefinition + { + public T Attach(); + public PathsDefinition Path(string path); + } + public class SpatialIndexDefinition + { + public T Attach(); + public SpatialIndexDefinition Path(string path); + public SpatialIndexDefinition Path(string path, params SpatialType[] spatialTypes); + } + public class UniqueKeyDefinition + { + public ContainerBuilder Attach(); + public UniqueKeyDefinition Path(string path); + } + public class VectorEmbeddingPolicyDefinition + { + public VectorEmbeddingPolicyDefinition(ContainerBuilder parent, Collection embeddings, Action attachCallback); + public ContainerBuilder Attach(); + } + public class VectorIndexDefinition + { + public VectorIndexDefinition(T parent, Action attachCallback); + public T Attach(); + public VectorIndexDefinition Path(string path, VectorIndexType indexType); + public VectorIndexDefinition WithIndexingSearchListSize(int indexingSearchListSize); + public VectorIndexDefinition WithQuantizationByteSize(int quantizationByteSize); + public VectorIndexDefinition WithQuantizerType(QuantizerType quantizerType); + public VectorIndexDefinition WithVectorIndexShardKey(string[] vectorIndexShardKey); + } +} +namespace Microsoft.Azure.Cosmos.Linq +{ + public static class CosmosLinq + { + public static object InvokeUserDefinedFunction(string udfName, params object[] arguments); + } + public static class CosmosLinqExtensions + { + public static bool ArrayContainsAll(this IEnumerable obj, params object[] values); + public static bool ArrayContainsAny(this IEnumerable obj, params object[] values); + public static Task> AverageAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> AverageAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> AverageAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> AverageAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> AverageAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> AverageAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> AverageAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> AverageAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> AverageAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> AverageAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> CountAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static int DocumentId(this object obj); + public static bool FullTextContains(this object obj, string search); + public static bool FullTextContainsAll(this object obj, params string[] searches); + public static bool FullTextContainsAny(this object obj, params string[] searches); + public static double FullTextScore(this TSource obj, params string[] terms); + public static string GetIndexMetrics(this Response response); + public static bool IsArray(this object obj); + public static bool IsBool(this object obj); + public static bool IsDefined(this object obj); + public static bool IsNull(this object obj); + public static bool IsNumber(this object obj); + public static bool IsObject(this object obj); + public static bool IsPrimitive(this object obj); + public static bool IsString(this object obj); + public static Task> MaxAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> MinAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static IOrderedQueryable OrderByRank(this IQueryable source, Expression> scoreFunction); + public static bool RegexMatch(this object obj, string regularExpression); + public static bool RegexMatch(this object obj, string regularExpression, string searchModifier); + public static double RRF(params double[] scoringFunctions); + public static double RRF(double[] scoringFunctions, double[] weights); + public static Task> SumAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> SumAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> SumAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> SumAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> SumAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> SumAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> SumAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> SumAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task>> SumAsync(this IQueryable> source, CancellationToken cancellationToken=default(CancellationToken)); + public static Task> SumAsync(this IQueryable source, CancellationToken cancellationToken=default(CancellationToken)); + public static FeedIterator ToFeedIterator(this IQueryable query); + public static QueryDefinition ToQueryDefinition(this IQueryable query); + public static QueryDefinition ToQueryDefinition(this IQueryable query, IDictionary namedParameters); + public static FeedIterator ToStreamIterator(this IQueryable query); + public static double VectorDistance(this byte[] vector1, byte[] vector2, bool isBruteForce, CosmosLinqExtensions.VectorDistanceOptions options); + public static double VectorDistance(this sbyte[] vector1, sbyte[] vector2, bool isBruteForce, CosmosLinqExtensions.VectorDistanceOptions options); + public static double VectorDistance(this float[] vector1, float[] vector2, bool isBruteForce, CosmosLinqExtensions.VectorDistanceOptions options); + public sealed class VectorDistanceOptions + { + public VectorDistanceOptions(); + public Nullable DataType { get; set; } + public Nullable DistanceFunction { get; set; } + public Nullable SearchListSizeMultiplier { get; set; } + } + } +} +namespace Microsoft.Azure.Cosmos.Scripts +{ + public abstract class Scripts + { + protected Scripts(); + public abstract Task CreateStoredProcedureAsync(StoredProcedureProperties storedProcedureProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateStoredProcedureStreamAsync(StoredProcedureProperties storedProcedureProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateTriggerAsync(TriggerProperties triggerProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateTriggerStreamAsync(TriggerProperties triggerProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateUserDefinedFunctionAsync(UserDefinedFunctionProperties userDefinedFunctionProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task CreateUserDefinedFunctionStreamAsync(UserDefinedFunctionProperties userDefinedFunctionProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteStoredProcedureAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteStoredProcedureStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteTriggerAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteTriggerStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteUserDefinedFunctionAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task DeleteUserDefinedFunctionStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task> ExecuteStoredProcedureAsync(string storedProcedureId, PartitionKey partitionKey, dynamic parameters, StoredProcedureRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ExecuteStoredProcedureStreamAsync(string storedProcedureId, PartitionKey partitionKey, dynamic parameters, StoredProcedureRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ExecuteStoredProcedureStreamAsync(string storedProcedureId, Stream streamPayload, PartitionKey partitionKey, StoredProcedureRequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract FeedIterator GetStoredProcedureQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetStoredProcedureQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetStoredProcedureQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetStoredProcedureQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetTriggerQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetTriggerQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetTriggerQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetTriggerQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetUserDefinedFunctionQueryIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetUserDefinedFunctionQueryIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetUserDefinedFunctionQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract FeedIterator GetUserDefinedFunctionQueryStreamIterator(string queryText=null, string continuationToken=null, QueryRequestOptions requestOptions=null); + public abstract Task ReadStoredProcedureAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadStoredProcedureStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadTriggerAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadTriggerStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadUserDefinedFunctionAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReadUserDefinedFunctionStreamAsync(string id, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceStoredProcedureAsync(StoredProcedureProperties storedProcedureProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceStoredProcedureStreamAsync(StoredProcedureProperties storedProcedureProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceTriggerAsync(TriggerProperties triggerProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceTriggerStreamAsync(TriggerProperties triggerProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceUserDefinedFunctionAsync(UserDefinedFunctionProperties userDefinedFunctionProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + public abstract Task ReplaceUserDefinedFunctionStreamAsync(UserDefinedFunctionProperties userDefinedFunctionProperties, RequestOptions requestOptions=null, CancellationToken cancellationToken=default(CancellationToken)); + } + public class StoredProcedureExecuteResponse : Response + { + protected StoredProcedureExecuteResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override T Resource { get; } + public virtual string ScriptLog { get; } + public virtual string SessionToken { get; } + public override HttpStatusCode StatusCode { get; } + } + public class StoredProcedureProperties + { + public StoredProcedureProperties(); + public StoredProcedureProperties(string id, string body); + public string Body { get; set; } + public string ETag { get; } + public string Id { get; set; } + public Nullable LastModified { get; } + public string SelfLink { get; } + } + public class StoredProcedureRequestOptions : RequestOptions + { + public StoredProcedureRequestOptions(); + public Nullable ConsistencyLevel { get; set; } + public bool EnableScriptLogging { get; set; } + public string SessionToken { get; set; } + } + public class StoredProcedureResponse : Response + { + protected StoredProcedureResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override StoredProcedureProperties Resource { get; } + public virtual string SessionToken { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator StoredProcedureProperties (StoredProcedureResponse response); + } + public enum TriggerOperation : short + { + All = (short)0, + Create = (short)1, + Delete = (short)3, + Replace = (short)4, + Update = (short)2, + Upsert = (short)5, + } + public class TriggerProperties + { + public TriggerProperties(); + public string Body { get; set; } + public string ETag { get; } + public string Id { get; set; } + public string SelfLink { get; } + public TriggerOperation TriggerOperation { get; set; } + public TriggerType TriggerType { get; set; } + } + public class TriggerResponse : Response + { + protected TriggerResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override TriggerProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator TriggerProperties (TriggerResponse response); + } + public enum TriggerType : byte + { + Post = (byte)1, + Pre = (byte)0, + } + public class UserDefinedFunctionProperties + { + public UserDefinedFunctionProperties(); + public string Body { get; set; } + public string ETag { get; } + public string Id { get; set; } + public string SelfLink { get; } + } + public class UserDefinedFunctionResponse : Response + { + protected UserDefinedFunctionResponse(); + public override string ActivityId { get; } + public override CosmosDiagnostics Diagnostics { get; } + public override string ETag { get; } + public override Headers Headers { get; } + public override double RequestCharge { get; } + public override UserDefinedFunctionProperties Resource { get; } + public override HttpStatusCode StatusCode { get; } + public static implicit operator UserDefinedFunctionProperties (UserDefinedFunctionResponse response); + } +} +namespace Microsoft.Azure.Cosmos.Spatial +{ + public sealed class BoundingBox : IEquatable + { + public BoundingBox(Position min, Position max); + public Position Max { get; } + public Position Min { get; } + public bool Equals(BoundingBox other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public abstract class Crs + { + protected Crs(CrsType type); + public static Crs Default { get; } + public CrsType Type { get; } + public static Crs Unspecified { get; } + public static LinkedCrs Linked(string href); + public static LinkedCrs Linked(string href, string type); + public static NamedCrs Named(string name); + } + public enum CrsType + { + Linked = 1, + Named = 0, + Unspecified = 2, + } + public abstract class Geometry + { + protected Geometry(GeometryType type, GeometryParams geometryParams); + public IDictionary AdditionalProperties { get; } + public BoundingBox BoundingBox { get; } + public Crs Crs { get; } + public GeometryType Type { get; } + public double Distance(Geometry to); + public override bool Equals(object obj); + public override int GetHashCode(); + public bool Intersects(Geometry geometry2); + public bool IsValid(); + public GeometryValidationResult IsValidDetailed(); + public bool Within(Geometry outer); + } + public class GeometryParams + { + public GeometryParams(); + public IDictionary AdditionalProperties { get; set; } + public BoundingBox BoundingBox { get; set; } + public Crs Crs { get; set; } + } + public enum GeometryShape + { + GeometryCollection = 6, + LineString = 2, + MultiLineString = 3, + MultiPoint = 1, + MultiPolygon = 5, + Point = 0, + Polygon = 4, + } + public enum GeometryType + { + GeometryCollection = 6, + LineString = 2, + MultiLineString = 3, + MultiPoint = 1, + MultiPolygon = 5, + Point = 0, + Polygon = 4, + } + public class GeometryValidationResult + { + public GeometryValidationResult(); + public bool IsValid { get; } + public string Reason { get; } + } + public sealed class LinearRing : IEquatable + { + public LinearRing(IList coordinates); + public ReadOnlyCollection Positions { get; } + public bool Equals(LinearRing other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class LineString : Geometry, IEquatable + { + public LineString(IList coordinates); + public LineString(IList coordinates, GeometryParams geometryParams); + public ReadOnlyCollection Positions { get; } + public bool Equals(LineString other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class LinkedCrs : Crs, IEquatable + { + public string Href { get; } + public string HrefType { get; } + public bool Equals(LinkedCrs other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class MultiPolygon : Geometry, IEquatable + { + public MultiPolygon(IList polygons); + public MultiPolygon(IList polygons, GeometryParams geometryParams); + public ReadOnlyCollection Polygons { get; } + public bool Equals(MultiPolygon other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class NamedCrs : Crs, IEquatable + { + public string Name { get; } + public bool Equals(NamedCrs other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class Point : Geometry, IEquatable + { + public Point(Position position); + public Point(Position position, GeometryParams geometryParams); + public Point(double longitude, double latitude); + public Position Position { get; } + public bool Equals(Point other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class Polygon : Geometry, IEquatable + { + public Polygon(IList rings); + public Polygon(IList rings, GeometryParams geometryParams); + public Polygon(IList externalRingPositions); + public ReadOnlyCollection Rings { get; } + public bool Equals(Polygon other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class PolygonCoordinates : IEquatable + { + public PolygonCoordinates(IList rings); + public ReadOnlyCollection Rings { get; } + public bool Equals(PolygonCoordinates other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public sealed class Position : IEquatable + { + public Position(IList coordinates); + public Position(double longitude, double latitude); + public Position(double longitude, double latitude, Nullable altitude); + public Nullable Altitude { get; } + public ReadOnlyCollection Coordinates { get; } + public double Latitude { get; } + public double Longitude { get; } + public bool Equals(Position other); + public override bool Equals(object obj); + public override int GetHashCode(); + } +} diff --git a/Microsoft.Azure.Cosmos/src/GatewayStoreModel.cs b/Microsoft.Azure.Cosmos/src/GatewayStoreModel.cs index 3123eed0ba..db8a549387 100644 --- a/Microsoft.Azure.Cosmos/src/GatewayStoreModel.cs +++ b/Microsoft.Azure.Cosmos/src/GatewayStoreModel.cs @@ -101,10 +101,10 @@ await GatewayStoreModel.ApplySessionTokenAsync( request.RequestContext.RegionName = regionName; } - bool isPPAFEnabled = this.IsPartitionLevelFailoverEnabled(); - // This is applicable for both per partition automatic failover and per partition circuit breaker. - if ((isPPAFEnabled || this.isThinClientEnabled) - && !ReplicatedResourceClient.IsMasterResource(request.ResourceType) + bool isPPAFEnabled = this.IsPartitionLevelFailoverEnabled(); + // This is applicable for both per partition automatic failover and per partition circuit breaker. + if ((isPPAFEnabled || this.isThinClientEnabled) + && !ReplicatedResourceClient.IsMasterResource(request.ResourceType) && (request.ResourceType.IsPartitioned() || request.ResourceType == ResourceType.StoredProcedure)) { (bool isSuccess, PartitionKeyRange partitionKeyRange) = await TryResolvePartitionKeyRangeAsync( @@ -563,7 +563,8 @@ internal static bool IsOperationSupportedByThinClient(DocumentServiceRequest req || request.OperationType == OperationType.Upsert || request.OperationType == OperationType.Replace || request.OperationType == OperationType.Delete - || request.OperationType == OperationType.Query)) + || request.OperationType == OperationType.Query + || request.OperationType == OperationType.QueryPlan)) { return true; } diff --git a/Microsoft.Azure.Cosmos/src/Query/v3Query/CosmosQueryClientCore.cs b/Microsoft.Azure.Cosmos/src/Query/v3Query/CosmosQueryClientCore.cs index 8f3c7ca366..d210dae18d 100644 --- a/Microsoft.Azure.Cosmos/src/Query/v3Query/CosmosQueryClientCore.cs +++ b/Microsoft.Azure.Cosmos/src/Query/v3Query/CosmosQueryClientCore.cs @@ -173,8 +173,8 @@ public override async Task> ExecuteItemQueryAsync( resourceType, message, trace); - } - + } + public override async Task ExecuteQueryPlanRequestAsync( string resourceUri, ResourceType resourceType, @@ -209,7 +209,20 @@ public override async Task ExecuteQueryPlanReques { // Syntax exception are argument exceptions and thrown to the user. message.EnsureSuccessStatusCode(); - partitionedQueryExecutionInfo = this.clientContext.SerializerCore.FromStream(message.Content); + + if (this.documentClient.isThinClientEnabled) + { + ContainerProperties containerProperties = await this.clientContext.GetCachedContainerPropertiesAsync( + resourceUri, trace, cancellationToken); + + partitionedQueryExecutionInfo = ThinClientQueryPlanHelper.DeserializeQueryPlanResponse( + message.Content, + containerProperties.PartitionKey); + } + else + { + partitionedQueryExecutionInfo = this.clientContext.SerializerCore.FromStream(message.Content); + } } return partitionedQueryExecutionInfo; diff --git a/Microsoft.Azure.Cosmos/src/SqlObjects/SqlFunctionCallScalarExpression.cs b/Microsoft.Azure.Cosmos/src/SqlObjects/SqlFunctionCallScalarExpression.cs index 01ef4e60e5..33bd903090 100644 --- a/Microsoft.Azure.Cosmos/src/SqlObjects/SqlFunctionCallScalarExpression.cs +++ b/Microsoft.Azure.Cosmos/src/SqlObjects/SqlFunctionCallScalarExpression.cs @@ -102,7 +102,9 @@ sealed class SqlFunctionCallScalarExpression : SqlScalarExpression { Names.IsNumber, Identifiers.IsNumber }, { Names.IsObject, Identifiers.IsObject }, { Names.IsPrimitive, Identifiers.IsPrimitive }, - { Names.IsString, Identifiers.IsString }, + { Names.IsString, Identifiers.IsString }, + { Names.LastSubstringAfter, Identifiers.LastSubstringAfter }, + { Names.LastSubstringBefore, Identifiers.LastSubstringBefore }, { Names.Left, Identifiers.Left }, { Names.Length, Identifiers.Length }, { Names.Like, Identifiers.Like }, @@ -143,7 +145,9 @@ sealed class SqlFunctionCallScalarExpression : SqlScalarExpression { Names.StringToNull, Identifiers.StringToNull }, { Names.StringToNumber, Identifiers.StringToNumber }, { Names.StringToObject, Identifiers.StringToObject }, - { Names.Substring, Identifiers.Substring }, + { Names.Substring, Identifiers.Substring }, + { Names.SubstringAfter, Identifiers.SubstringAfter }, + { Names.SubstringBefore, Identifiers.SubstringBefore }, { Names.Sum, Identifiers.Sum }, { Names.Tan, Identifiers.Tan }, { Names.TicksToDateTime, Identifiers.TicksToDateTime }, @@ -350,7 +354,9 @@ public static class Names public const string IsObject = "IS_OBJECT"; public const string IsPrimitive = "IS_PRIMITIVE"; public const string IsString = "IS_STRING"; - public const string LastIndexOf = "LastIndexOf"; + public const string LastIndexOf = "LastIndexOf"; + public const string LastSubstringAfter = "LastSubstringAfter"; + public const string LastSubstringBefore = "LastSubstringBefore"; public const string Left = "LEFT"; public const string Length = "LENGTH"; public const string Like = "LIKE"; @@ -398,7 +404,9 @@ public static class Names public const string StringToNull = "StringToNull"; public const string StringToNumber = "StringToNumber"; public const string StringToObject = "StringToObject"; - public const string Substring = "SUBSTRING"; + public const string Substring = "SUBSTRING"; + public const string SubstringAfter = "SubstringAfter"; + public const string SubstringBefore = "SubstringBefore"; public const string Sum = "SUM"; public const string Tan = "TAN"; public const string TicksToDateTime = "TicksToDateTime"; @@ -528,7 +536,9 @@ public static class Identifiers public static readonly SqlIdentifier IsObject = SqlIdentifier.Create(Names.IsObject); public static readonly SqlIdentifier IsPrimitive = SqlIdentifier.Create(Names.IsPrimitive); public static readonly SqlIdentifier IsString = SqlIdentifier.Create(Names.IsString); - public static readonly SqlIdentifier LastIndexOf = SqlIdentifier.Create(Names.LastIndexOf); + public static readonly SqlIdentifier LastIndexOf = SqlIdentifier.Create(Names.LastIndexOf); + public static readonly SqlIdentifier LastSubstringAfter = SqlIdentifier.Create(Names.LastSubstringAfter); + public static readonly SqlIdentifier LastSubstringBefore = SqlIdentifier.Create(Names.LastSubstringBefore); public static readonly SqlIdentifier Left = SqlIdentifier.Create(Names.Left); public static readonly SqlIdentifier Length = SqlIdentifier.Create(Names.Length); public static readonly SqlIdentifier Like = SqlIdentifier.Create(Names.Like); @@ -576,7 +586,9 @@ public static class Identifiers public static readonly SqlIdentifier StringToNull = SqlIdentifier.Create(Names.StringToNull); public static readonly SqlIdentifier StringToNumber = SqlIdentifier.Create(Names.StringToNumber); public static readonly SqlIdentifier StringToObject = SqlIdentifier.Create(Names.StringToObject); - public static readonly SqlIdentifier Substring = SqlIdentifier.Create(Names.Substring); + public static readonly SqlIdentifier Substring = SqlIdentifier.Create(Names.Substring); + public static readonly SqlIdentifier SubstringAfter = SqlIdentifier.Create(Names.SubstringAfter); + public static readonly SqlIdentifier SubstringBefore = SqlIdentifier.Create(Names.SubstringBefore); public static readonly SqlIdentifier Sum = SqlIdentifier.Create(Names.Sum); public static readonly SqlIdentifier Tan = SqlIdentifier.Create(Names.Tan); public static readonly SqlIdentifier TicksToDateTime = SqlIdentifier.Create(Names.TicksToDateTime); diff --git a/Microsoft.Azure.Cosmos/src/ThinClientQueryPlanHelper.cs b/Microsoft.Azure.Cosmos/src/ThinClientQueryPlanHelper.cs new file mode 100644 index 0000000000..6edb6c21a0 --- /dev/null +++ b/Microsoft.Azure.Cosmos/src/ThinClientQueryPlanHelper.cs @@ -0,0 +1,162 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +namespace Microsoft.Azure.Cosmos.Query.Core.QueryPlan +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Text.Json; + using Newtonsoft.Json; + using PartitionKeyDefinition = Documents.PartitionKeyDefinition; + using PartitionKeyInternal = Documents.Routing.PartitionKeyInternal; + + /// + /// Handles conversion of thin client query plan responses where query ranges + /// are returned in PartitionKeyInternal format instead of EPK hex strings. + /// Mirrors the conversion logic in . + /// + /// + /// Uses System.Text.Json for primary parsing and structural validation. + /// Newtonsoft.Json is used only for deserializing QueryInfo, HybridSearchQueryInfo, + /// and Range<PartitionKeyInternal> because these types and their deep type hierarchies + /// (including the external Direct package types) use Newtonsoft [JsonProperty] attributes + /// and [JsonObject(MemberSerialization.OptIn)] semantics that have no System.Text.Json equivalent. + /// + internal static class ThinClientQueryPlanHelper + { + private static readonly Newtonsoft.Json.JsonSerializerSettings NewtonsoftSettings = + new Newtonsoft.Json.JsonSerializerSettings + { + DateParseHandling = Newtonsoft.Json.DateParseHandling.None, + MaxDepth = 64, + }; + + /// + /// Deserializes a thin client query plan response stream into a + /// with EPK string ranges. + /// The response contains query ranges in PartitionKeyInternal format + /// which are converted to EPK hex strings and sorted. + /// + /// The response stream containing the raw query plan JSON. + /// The partition key definition for the container. + /// with sorted EPK string ranges. + /// Thrown when or is null. + /// Thrown when the response JSON is malformed or missing required properties. + public static PartitionedQueryExecutionInfo DeserializeQueryPlanResponse( + Stream stream, + PartitionKeyDefinition partitionKeyDefinition) + { + if (stream == null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (partitionKeyDefinition == null) + { + throw new ArgumentNullException(nameof(partitionKeyDefinition)); + } + + using JsonDocument doc = JsonDocument.Parse(stream); + JsonElement root = doc.RootElement; + + if (root.ValueKind != JsonValueKind.Object) + { + throw new FormatException( + $"Thin client query plan response must be a JSON object, but was {root.ValueKind}."); + } + + // Validate and extract queryRanges (required) + if (!root.TryGetProperty("queryRanges", out JsonElement queryRangesElement)) + { + throw new FormatException( + "Thin client query plan response is missing the required 'queryRanges' property."); + } + + if (queryRangesElement.ValueKind != JsonValueKind.Array) + { + throw new FormatException( + $"Expected 'queryRanges' to be a JSON array, but was {queryRangesElement.ValueKind}."); + } + + if (queryRangesElement.GetArrayLength() == 0) + { + throw new FormatException( + "Thin client query plan response 'queryRanges' array must not be empty."); + } + + // Deserialize QueryInfo using Newtonsoft because QueryInfo uses + // [JsonObject(MemberSerialization.OptIn)] and Newtonsoft-only [JsonProperty] attributes. + QueryInfo queryInfo = null; + if (root.TryGetProperty("queryInfo", out JsonElement queryInfoElement) + && queryInfoElement.ValueKind != JsonValueKind.Null) + { + queryInfo = Newtonsoft.Json.JsonConvert.DeserializeObject( + queryInfoElement.GetRawText(), + ThinClientQueryPlanHelper.NewtonsoftSettings); + } + + // Deserialize HybridSearchQueryInfo using Newtonsoft (same constraint as QueryInfo). + HybridSearchQueryInfo hybridSearchQueryInfo = null; + if (root.TryGetProperty("hybridSearchQueryInfo", out JsonElement hybridElement) + && hybridElement.ValueKind != JsonValueKind.Null) + { + hybridSearchQueryInfo = Newtonsoft.Json.JsonConvert.DeserializeObject( + hybridElement.GetRawText(), + ThinClientQueryPlanHelper.NewtonsoftSettings); + } + + // Parse and convert query ranges to EPK string ranges. + // Range requires Newtonsoft because PartitionKeyInternal + // is from the external Direct package with Newtonsoft-based serialization. + List> effectiveRanges = + new List>(queryRangesElement.GetArrayLength()); + + foreach (JsonElement rangeElement in queryRangesElement.EnumerateArray()) + { + if (rangeElement.ValueKind != JsonValueKind.Object) + { + throw new FormatException( + $"Each query range must be a JSON object, but was {rangeElement.ValueKind}."); + } + + if (!rangeElement.TryGetProperty("min", out _)) + { + throw new FormatException( + "Query range is missing the required 'min' property."); + } + + if (!rangeElement.TryGetProperty("max", out _)) + { + throw new FormatException( + "Query range is missing the required 'max' property."); + } + + Documents.Routing.Range internalRange = + Newtonsoft.Json.JsonConvert.DeserializeObject>( + rangeElement.GetRawText(), + ThinClientQueryPlanHelper.NewtonsoftSettings); + + if (internalRange == null) + { + throw new FormatException( + "Failed to deserialize query range from thin client response."); + } + + effectiveRanges.Add(PartitionKeyInternal.GetEffectivePartitionKeyRange( + partitionKeyDefinition, + internalRange)); + } + + effectiveRanges.Sort(Documents.Routing.Range.MinComparer.Instance); + + return new PartitionedQueryExecutionInfo() + { + QueryInfo = queryInfo, + QueryRanges = effectiveRanges, + HybridSearchQueryInfo = hybridSearchQueryInfo, + }; + } + } +} \ No newline at end of file diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/CosmosItemThinClientTests.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/CosmosItemThinClientTests.cs index 7cbd053101..d34866a6ca 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/CosmosItemThinClientTests.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/CosmosItemThinClientTests.cs @@ -31,12 +31,12 @@ public class CosmosItemThinClientTests private MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer cosmosSystemTextJsonSerializer; private const int ItemCount = 100; - [TestInitialize] - public async Task TestInitAsync() - { - Environment.SetEnvironmentVariable(ConfigurationManager.ThinClientModeEnabled, "True"); + [TestInitialize] + public async Task TestInitAsync() + { + Environment.SetEnvironmentVariable(ConfigurationManager.ThinClientModeEnabled, "True"); this.connectionString = Environment.GetEnvironmentVariable("COSMOSDB_THINCLIENT"); - + if (string.IsNullOrEmpty(this.connectionString)) { Assert.Fail("Set environment variable COSMOSDB_THINCLIENT to run the tests"); @@ -188,183 +188,227 @@ public async Task RegionalDatabaseAccountNameIsEmptyInPayload() [TestCategory("ThinClient")] public async Task TestThinClientWithExecuteStoredProcedureAsync() { - Environment.SetEnvironmentVariable(ConfigurationManager.ThinClientModeEnabled, "true"); + CosmosClient localClient = null; + Database localDatabase = null; - JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions + try { - PropertyNamingPolicy = null, - PropertyNameCaseInsensitive = true, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }; - this.cosmosSystemTextJsonSerializer = new MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer(jsonSerializerOptions); + Environment.SetEnvironmentVariable(ConfigurationManager.ThinClientModeEnabled, "true"); - this.client = new CosmosClient( - this.connectionString, - new CosmosClientOptions() - { - ConnectionMode = ConnectionMode.Gateway, - Serializer = this.cosmosSystemTextJsonSerializer, - }); + JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = null, + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + CosmosSystemTextJsonSerializer localSerializer = new MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer(jsonSerializerOptions); - string uniqueDbName = "TestDbStoreProc_" + Guid.NewGuid().ToString(); - this.database = await this.client.CreateDatabaseIfNotExistsAsync(uniqueDbName); - string uniqueContainerName = "TestDbStoreProcContainer_" + Guid.NewGuid().ToString(); - this.container = await this.database.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); + localClient = new CosmosClient( + this.connectionString, + new CosmosClientOptions() + { + ConnectionMode = ConnectionMode.Gateway, + Serializer = localSerializer, + }); + string uniqueDbName = "TestDbStoreProc_" + Guid.NewGuid().ToString(); + localDatabase = await localClient.CreateDatabaseIfNotExistsAsync(uniqueDbName); + string uniqueContainerName = "TestDbStoreProcContainer_" + Guid.NewGuid().ToString(); + Container localContainer = await localDatabase.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); - string sprocId = "testSproc_" + Guid.NewGuid().ToString(); - string sprocBody = @"function(itemToCreate) { - var context = getContext(); - var collection = context.getCollection(); - var response = context.getResponse(); + + string sprocId = "testSproc_" + Guid.NewGuid().ToString(); + string sprocBody = @"function(itemToCreate) { + var context = getContext(); + var collection = context.getCollection(); + var response = context.getResponse(); - if (!itemToCreate) throw new Error('Item is undefined or null.'); + if (!itemToCreate) throw new Error('Item is undefined or null.'); - // Create a document - var accepted = collection.createDocument( - collection.getSelfLink(), - itemToCreate, - function(err, newItem) { - if (err) throw err; - - // Query the created document - var query = 'SELECT * FROM c WHERE c.id = ""' + newItem.id + '""'; - var isAccepted = collection.queryDocuments( + // Create a document + var accepted = collection.createDocument( collection.getSelfLink(), - query, - function(queryErr, documents) { - if (queryErr) throw queryErr; - response.setBody({ - created: newItem, - queried: documents[0] - }); - } - ); - if (!isAccepted) throw 'Query not accepted'; - }); + itemToCreate, + function(err, newItem) { + if (err) throw err; + + // Query the created document + var query = 'SELECT * FROM c WHERE c.id = ""' + newItem.id + '""'; + var isAccepted = collection.queryDocuments( + collection.getSelfLink(), + query, + function(queryErr, documents) { + if (queryErr) throw queryErr; + response.setBody({ + created: newItem, + queried: documents[0] + }); + } + ); + if (!isAccepted) throw 'Query not accepted'; + }); - if (!accepted) throw new Error('Create was not accepted.'); - }"; + if (!accepted) throw new Error('Create was not accepted.'); + }"; - // Create stored procedure - Scripts.StoredProcedureResponse createResponse = await this.container.Scripts.CreateStoredProcedureAsync( - new Scripts.StoredProcedureProperties(sprocId, sprocBody)); - Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode); + // Create stored procedure + Scripts.StoredProcedureResponse createResponse = await localContainer.Scripts.CreateStoredProcedureAsync( + new Scripts.StoredProcedureProperties(sprocId, sprocBody)); + Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode); - // Execute stored procedure - string testPartitionId = Guid.NewGuid().ToString(); - TestObject testItem = new TestObject - { - Id = Guid.NewGuid().ToString(), - Pk = testPartitionId, - Other = "Created by Stored Procedure" - }; + // Execute stored procedure + string testPartitionId = Guid.NewGuid().ToString(); + TestObject testItem = new TestObject + { + Id = Guid.NewGuid().ToString(), + Pk = testPartitionId, + Other = "Created by Stored Procedure" + }; - Scripts.StoredProcedureExecuteResponse executeResponse = - await this.container.Scripts.ExecuteStoredProcedureAsync( - sprocId, - new PartitionKey(testPartitionId), - new dynamic[] { testItem }); + Scripts.StoredProcedureExecuteResponse executeResponse = + await localContainer.Scripts.ExecuteStoredProcedureAsync( + sprocId, + new PartitionKey(testPartitionId), + new dynamic[] { testItem }); - Assert.AreEqual(HttpStatusCode.OK, executeResponse.StatusCode); - Assert.IsNotNull(executeResponse.Resource); - string diagnostics = executeResponse.Diagnostics.ToString(); - Assert.IsTrue(diagnostics.Contains("|F4"), "Diagnostics User Agent should contain '|F4' for ThinClient"); + Assert.AreEqual(HttpStatusCode.OK, executeResponse.StatusCode); + Assert.IsNotNull(executeResponse.Resource); + string diagnostics = executeResponse.Diagnostics.ToString(); + Assert.IsTrue(diagnostics.Contains("|F4"), "Diagnostics User Agent should contain '|F4' for ThinClient"); - // Delete stored procedure - await this.container.Scripts.DeleteStoredProcedureAsync(sprocId); + // Delete stored procedure + await localContainer.Scripts.DeleteStoredProcedureAsync(sprocId); + } + finally + { + if (localDatabase != null) + { + try + { + await localDatabase.DeleteAsync(); + } + catch { } + } + + if (localClient != null) + { + localClient.Dispose(); + } + } } - [TestMethod] - [TestCategory("ThinClient")] - public async Task TestThinClientWithExecuteStoredProcedureStreamAsync() + [TestMethod] + [TestCategory("ThinClient")] + public async Task TestThinClientWithExecuteStoredProcedureStreamAsync() { - Environment.SetEnvironmentVariable(ConfigurationManager.ThinClientModeEnabled, "true"); - - JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions - { - PropertyNamingPolicy = null, - PropertyNameCaseInsensitive = true, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }; - this.cosmosSystemTextJsonSerializer = new MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer(jsonSerializerOptions); - - this.client = new CosmosClient( - this.connectionString, - new CosmosClientOptions() - { - ConnectionMode = ConnectionMode.Gateway, - Serializer = this.cosmosSystemTextJsonSerializer, - }); - - string uniqueDbName = "TestDbStoreProc_" + Guid.NewGuid().ToString(); - this.database = await this.client.CreateDatabaseIfNotExistsAsync(uniqueDbName); - string uniqueContainerName = "TestDbStoreProcContainer_" + Guid.NewGuid().ToString(); - this.container = await this.database.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); - - - string sprocId = "testSproc_" + Guid.NewGuid().ToString(); - string sprocBody = @"function(itemToCreate) { - var context = getContext(); - var collection = context.getCollection(); - var response = context.getResponse(); - - if (!itemToCreate) throw new Error('Item is undefined or null.'); - - // Create a document - var accepted = collection.createDocument( - collection.getSelfLink(), - itemToCreate, - function(err, newItem) { - if (err) throw err; - - // Query the created document - var query = 'SELECT * FROM c WHERE c.id = ""' + newItem.id + '""'; - var isAccepted = collection.queryDocuments( - collection.getSelfLink(), - query, - function(queryErr, documents) { - if (queryErr) throw queryErr; - response.setBody({ - created: newItem, - queried: documents[0] - }); - } - ); - if (!isAccepted) throw 'Query not accepted'; - }); - - if (!accepted) throw new Error('Create was not accepted.'); - }"; - - // Create stored procedure - Scripts.StoredProcedureResponse createResponse = await this.container.Scripts.CreateStoredProcedureAsync( - new Scripts.StoredProcedureProperties(sprocId, sprocBody)); - Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode); - - // Execute stored procedure - string testPartitionId = Guid.NewGuid().ToString(); - TestObject testItem = new TestObject - { - Id = Guid.NewGuid().ToString(), - Pk = testPartitionId, - Other = "Created by Stored Procedure" - }; - - using (ResponseMessage executeResponse = - await this.container.Scripts.ExecuteStoredProcedureStreamAsync( - sprocId, - new PartitionKey(testPartitionId), - new dynamic[] { testItem })) - { - Assert.AreEqual(HttpStatusCode.OK, executeResponse.StatusCode); - Assert.IsNotNull(executeResponse.Content); - string diagnostics = executeResponse.Diagnostics.ToString(); - Assert.IsTrue(diagnostics.Contains("|F4"), "Diagnostics User Agent should contain '|F4' for ThinClient"); - } - - // Delete stored procedure - await this.container.Scripts.DeleteStoredProcedureAsync(sprocId); + CosmosClient localClient = null; + Database localDatabase = null; + + try + { + Environment.SetEnvironmentVariable(ConfigurationManager.ThinClientModeEnabled, "true"); + + JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = null, + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + CosmosSystemTextJsonSerializer localSerializer = new MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer(jsonSerializerOptions); + + localClient = new CosmosClient( + this.connectionString, + new CosmosClientOptions() + { + ConnectionMode = ConnectionMode.Gateway, + Serializer = localSerializer, + }); + + string uniqueDbName = "TestDbStoreProc_" + Guid.NewGuid().ToString(); + localDatabase = await localClient.CreateDatabaseIfNotExistsAsync(uniqueDbName); + string uniqueContainerName = "TestDbStoreProcContainer_" + Guid.NewGuid().ToString(); + Container localContainer = await localDatabase.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); + + + string sprocId = "testSproc_" + Guid.NewGuid().ToString(); + string sprocBody = @"function(itemToCreate) { + var context = getContext(); + var collection = context.getCollection(); + var response = context.getResponse(); + + if (!itemToCreate) throw new Error('Item is undefined or null.'); + + // Create a document + var accepted = collection.createDocument( + collection.getSelfLink(), + itemToCreate, + function(err, newItem) { + if (err) throw err; + + // Query the created document + var query = 'SELECT * FROM c WHERE c.id = ""' + newItem.id + '""'; + var isAccepted = collection.queryDocuments( + collection.getSelfLink(), + query, + function(queryErr, documents) { + if (queryErr) throw queryErr; + response.setBody({ + created: newItem, + queried: documents[0] + }); + } + ); + if (!isAccepted) throw 'Query not accepted'; + }); + + if (!accepted) throw new Error('Create was not accepted.'); + }"; + + // Create stored procedure + Scripts.StoredProcedureResponse createResponse = await localContainer.Scripts.CreateStoredProcedureAsync( + new Scripts.StoredProcedureProperties(sprocId, sprocBody)); + Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode); + + // Execute stored procedure + string testPartitionId = Guid.NewGuid().ToString(); + TestObject testItem = new TestObject + { + Id = Guid.NewGuid().ToString(), + Pk = testPartitionId, + Other = "Created by Stored Procedure" + }; + + using (ResponseMessage executeResponse = + await localContainer.Scripts.ExecuteStoredProcedureStreamAsync( + sprocId, + new PartitionKey(testPartitionId), + new dynamic[] { testItem })) + { + Assert.AreEqual(HttpStatusCode.OK, executeResponse.StatusCode); + Assert.IsNotNull(executeResponse.Content); + string diagnostics = executeResponse.Diagnostics.ToString(); + Assert.IsTrue(diagnostics.Contains("|F4"), "Diagnostics User Agent should contain '|F4' for ThinClient"); + } + + // Delete stored procedure + await localContainer.Scripts.DeleteStoredProcedureAsync(sprocId); + } + finally + { + if (localDatabase != null) + { + try + { + await localDatabase.DeleteAsync(); + } + catch { } + } + + if (localClient != null) + { + localClient.Dispose(); + } + } } [TestMethod] @@ -426,42 +470,65 @@ public async Task CreateItemsTest() [TestCategory("ThinClient")] public async Task CreateItemsTestWithThinClientFlagEnabledAndAccountDisabled() { - Environment.SetEnvironmentVariable(ConfigurationManager.ThinClientModeEnabled, "True"); - string authKey = Utils.ConfigurationManager.AppSettings["MasterKey"]; - string endpoint = Utils.ConfigurationManager.AppSettings["GatewayEndpoint"]; - AzureKeyCredential masterKeyCredential = new AzureKeyCredential(authKey); + CosmosClient localClient = null; + Database localDatabase = null; + Container localContainer = null; - JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions + try { - PropertyNamingPolicy = null, - PropertyNameCaseInsensitive = true, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }; - this.cosmosSystemTextJsonSerializer = new MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer(jsonSerializerOptions); - - this.client = new CosmosClient( - endpoint, - masterKeyCredential, - new CosmosClientOptions() - { - ConnectionMode = ConnectionMode.Gateway, - Serializer = this.cosmosSystemTextJsonSerializer, - }); + Environment.SetEnvironmentVariable(ConfigurationManager.ThinClientModeEnabled, "True"); + string authKey = Utils.ConfigurationManager.AppSettings["MasterKey"]; + string endpoint = Utils.ConfigurationManager.AppSettings["GatewayEndpoint"]; + AzureKeyCredential masterKeyCredential = new AzureKeyCredential(authKey); - string uniqueDbName = "TestDb2_" + Guid.NewGuid().ToString(); - this.database = await this.client.CreateDatabaseIfNotExistsAsync(uniqueDbName); - string uniqueContainerName = "TestContainer2_" + Guid.NewGuid().ToString(); - this.container = await this.database.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); - - string pk = "pk_create"; - IEnumerable items = this.GenerateItems(pk); - - foreach (TestObject item in items) + JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = null, + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + CosmosSystemTextJsonSerializer localSerializer = new MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer(jsonSerializerOptions); + + localClient = new CosmosClient( + endpoint, + masterKeyCredential, + new CosmosClientOptions() + { + ConnectionMode = ConnectionMode.Gateway, + Serializer = localSerializer, + }); + + string uniqueDbName = "TestDb2_" + Guid.NewGuid().ToString(); + localDatabase = await localClient.CreateDatabaseIfNotExistsAsync(uniqueDbName); + string uniqueContainerName = "TestContainer2_" + Guid.NewGuid().ToString(); + localContainer = await localDatabase.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); + + string pk = "pk_create"; + IEnumerable items = this.GenerateItems(pk); + + foreach (TestObject item in items) + { + ItemResponse response = await localContainer.CreateItemAsync(item, new PartitionKey(item.Pk)); + Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); + string diagnostics = response.Diagnostics.ToString(); + Assert.IsFalse(diagnostics.Contains("|F4"), "Diagnostics User Agent should NOT contain '|F4' for Gateway"); + } + } + finally { - ItemResponse response = await this.container.CreateItemAsync(item, new PartitionKey(item.Pk)); - Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); - string diagnostics = response.Diagnostics.ToString(); - Assert.IsFalse(diagnostics.Contains("|F4"), "Diagnostics User Agent should NOT contain '|F4' for Gateway"); + if (localDatabase != null) + { + try + { + await localDatabase.DeleteAsync(); + } + catch { } + } + + if (localClient != null) + { + localClient.Dispose(); + } } } @@ -469,42 +536,65 @@ public async Task CreateItemsTestWithThinClientFlagEnabledAndAccountDisabled() [TestCategory("ThinClient")] public async Task CreateItemsTestWithDirectMode_ThinClientFlagEnabledAndAccountEnabled() { - JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions + CosmosClient localClient = null; + Database localDatabase = null; + Container localContainer = null; + + try { - PropertyNamingPolicy = null, - PropertyNameCaseInsensitive = true, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }; - this.cosmosSystemTextJsonSerializer = new MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer(jsonSerializerOptions); + JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = null, + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + CosmosSystemTextJsonSerializer localSerializer = new MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer(jsonSerializerOptions); - this.client = new CosmosClient( - this.connectionString, - new CosmosClientOptions() - { - ConnectionMode = ConnectionMode.Direct, - Serializer = this.cosmosSystemTextJsonSerializer, - }); + localClient = new CosmosClient( + this.connectionString, + new CosmosClientOptions() + { + ConnectionMode = ConnectionMode.Direct, + Serializer = localSerializer, + }); - string uniqueDbName = "TestDb2_" + Guid.NewGuid().ToString(); - this.database = await this.client.CreateDatabaseIfNotExistsAsync(uniqueDbName); - string uniqueContainerName = "TestContainer2_" + Guid.NewGuid().ToString(); - this.container = await this.database.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); + string uniqueDbName = "TestDb2_" + Guid.NewGuid().ToString(); + localDatabase = await localClient.CreateDatabaseIfNotExistsAsync(uniqueDbName); + string uniqueContainerName = "TestContainer2_" + Guid.NewGuid().ToString(); + localContainer = await localDatabase.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); - string pk = "pk_create"; - IEnumerable items = this.GenerateItems(pk); + string pk = "pk_create"; + IEnumerable items = this.GenerateItems(pk); - foreach (TestObject item in items) + foreach (TestObject item in items) + { + ItemResponse response = await localContainer.CreateItemAsync(item, new PartitionKey(item.Pk)); + Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); + JsonDocument doc = JsonDocument.Parse(response.Diagnostics.ToString()); + string connectionMode = doc.RootElement + .GetProperty("data") + .GetProperty("Client Configuration") + .GetProperty("ConnectionMode") + .GetString(); + + Assert.AreEqual("Direct", connectionMode, "Diagnostics should have ConnectionMode set to 'Direct'"); + } + } + finally { - ItemResponse response = await this.container.CreateItemAsync(item, new PartitionKey(item.Pk)); - Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); - JsonDocument doc = JsonDocument.Parse(response.Diagnostics.ToString()); - string connectionMode = doc.RootElement - .GetProperty("data") - .GetProperty("Client Configuration") - .GetProperty("ConnectionMode") - .GetString(); - - Assert.AreEqual("Direct", connectionMode, "Diagnostics should have ConnectionMode set to 'Direct'"); + if (localDatabase != null) + { + try + { + await localDatabase.DeleteAsync(); + } + catch { } + } + + if (localClient != null) + { + localClient.Dispose(); + } } } @@ -512,38 +602,61 @@ public async Task CreateItemsTestWithDirectMode_ThinClientFlagEnabledAndAccountE [TestCategory("ThinClient")] public async Task CreateItemsTestWithThinClientFlagDisabledAccountEnabled() { - Environment.SetEnvironmentVariable(ConfigurationManager.ThinClientModeEnabled, "False"); + CosmosClient localClient = null; + Database localDatabase = null; + Container localContainer = null; - JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions + try { - PropertyNamingPolicy = null, - PropertyNameCaseInsensitive = true, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }; - this.cosmosSystemTextJsonSerializer = new MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer(jsonSerializerOptions); + Environment.SetEnvironmentVariable(ConfigurationManager.ThinClientModeEnabled, "False"); - this.client = new CosmosClient( - this.connectionString, - new CosmosClientOptions() - { - ConnectionMode = ConnectionMode.Gateway, - Serializer = this.cosmosSystemTextJsonSerializer, - }); + JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = null, + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + CosmosSystemTextJsonSerializer localSerializer = new MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer(jsonSerializerOptions); - string uniqueDbName = "TestDbTCDisabled_" + Guid.NewGuid().ToString(); - this.database = await this.client.CreateDatabaseIfNotExistsAsync(uniqueDbName); - string uniqueContainerName = "TestContainerTCDisabled_" + Guid.NewGuid().ToString(); - this.container = await this.database.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); + localClient = new CosmosClient( + this.connectionString, + new CosmosClientOptions() + { + ConnectionMode = ConnectionMode.Gateway, + Serializer = localSerializer, + }); - string pk = "pk_create"; - IEnumerable items = this.GenerateItems(pk); + string uniqueDbName = "TestDbTCDisabled_" + Guid.NewGuid().ToString(); + localDatabase = await localClient.CreateDatabaseIfNotExistsAsync(uniqueDbName); + string uniqueContainerName = "TestContainerTCDisabled_" + Guid.NewGuid().ToString(); + localContainer = await localDatabase.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); - foreach (TestObject item in items) + string pk = "pk_create"; + IEnumerable items = this.GenerateItems(pk); + + foreach (TestObject item in items) + { + ItemResponse response = await localContainer.CreateItemAsync(item, new PartitionKey(item.Pk)); + Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); + string diagnostics = response.Diagnostics.ToString(); + Assert.IsFalse(diagnostics.Contains("|F4"), "Diagnostics User Agent should NOT contain '|F4' for Gateway"); + } + } + finally { - ItemResponse response = await this.container.CreateItemAsync(item, new PartitionKey(item.Pk)); - Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); - string diagnostics = response.Diagnostics.ToString(); - Assert.IsFalse(diagnostics.Contains("|F4"), "Diagnostics User Agent should NOT contain '|F4' for Gateway"); + if (localDatabase != null) + { + try + { + await localDatabase.DeleteAsync(); + } + catch { } + } + + if (localClient != null) + { + localClient.Dispose(); + } } } @@ -764,77 +877,150 @@ public async Task QueryItemsTest() [TestCategory("ThinClient")] public async Task QueryItemsTestWithStrongConsistency() { - string connectionString = ConfigurationManager.GetEnvironmentVariable("COSMOSDB_THINCLIENTSTRONG", string.Empty); - if (string.IsNullOrEmpty(connectionString)) + CosmosClient localClient = null; + Database localDatabase = null; + + try { - Assert.Fail("Set environment variable COSMOSDB_THINCLIENTSTRONG to run the tests"); - } - this.client = new CosmosClient( - connectionString, - new CosmosClientOptions() - { - ConnectionMode = ConnectionMode.Gateway, - RequestTimeout = TimeSpan.FromSeconds(60), - ConsistencyLevel = Microsoft.Azure.Cosmos.ConsistencyLevel.Strong - }); - - string uniqueDbName = "TestDbTC_" + Guid.NewGuid().ToString(); - this.database = await this.client.CreateDatabaseIfNotExistsAsync(uniqueDbName); - string uniqueContainerName = "TestContainerTC_" + Guid.NewGuid().ToString(); - this.container = await this.database.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); + string connectionString = ConfigurationManager.GetEnvironmentVariable("COSMOSDB_THINCLIENTSTRONG", string.Empty); + if (string.IsNullOrEmpty(connectionString)) + { + Assert.Fail("Set environment variable COSMOSDB_THINCLIENTSTRONG to run the tests"); + } - string pk = "pk_query"; - List items = this.GenerateItems(pk).ToList(); + localClient = new CosmosClient( + connectionString, + new CosmosClientOptions() + { + ConnectionMode = ConnectionMode.Gateway, + RequestTimeout = TimeSpan.FromSeconds(60), + ConsistencyLevel = Microsoft.Azure.Cosmos.ConsistencyLevel.Strong + }); + + string uniqueDbName = "TestDbTC_" + Guid.NewGuid().ToString(); + localDatabase = await localClient.CreateDatabaseIfNotExistsAsync(uniqueDbName); + string uniqueContainerName = "TestContainerTC_" + Guid.NewGuid().ToString(); + Container localContainer = await localDatabase.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); + + string pk = "pk_query"; + List items = this.GenerateItems(pk).ToList(); + + List itemsCreated = new List(); + foreach (TestObject item in items) + { + try + { + ItemResponse response = await localContainer.CreateItemAsync(item, new PartitionKey(item.Pk)); + if (response.StatusCode == HttpStatusCode.Created) + { + itemsCreated.Add(item); + } + } + catch (CosmosException) + { + } + } - List createdItems = await this.CreateItemsSafeAsync(items); + string query = $"SELECT * FROM c WHERE c.pk = '{pk}'"; + FeedIterator iterator = localContainer.GetItemQueryIterator(query); - string query = $"SELECT * FROM c WHERE c.pk = '{pk}'"; - FeedIterator iterator = this.container.GetItemQueryIterator(query); + int count = 0; + while (iterator.HasMoreResults) + { + FeedResponse response = await iterator.ReadNextAsync(); + count += response.Count; + } - int count = 0; - while (iterator.HasMoreResults) - { - FeedResponse response = await iterator.ReadNextAsync(); - count += response.Count; + Assert.AreEqual(itemsCreated.Count, count); } + finally + { + if (localDatabase != null) + { + try + { + await localDatabase.DeleteAsync(); + } + catch { } + } - Assert.AreEqual(createdItems.Count, count); + if (localClient != null) + { + localClient.Dispose(); + } + } } [TestMethod] [TestCategory("ThinClient")] public async Task QueryItemsTestWithSessionConsistency() { - this.client = new CosmosClient( - this.connectionString, - new CosmosClientOptions() - { - ConnectionMode = ConnectionMode.Gateway, - RequestTimeout = TimeSpan.FromSeconds(60), - ConsistencyLevel = Microsoft.Azure.Cosmos.ConsistencyLevel.Session - }); - - string uniqueDbName = "TestDbTC_" + Guid.NewGuid().ToString(); - this.database = await this.client.CreateDatabaseIfNotExistsAsync(uniqueDbName); - string uniqueContainerName = "TestContainerTC_" + Guid.NewGuid().ToString(); - this.container = await this.database.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); + CosmosClient localClient = null; + Database localDatabase = null; - string pk = "pk_query"; - List items = this.GenerateItems(pk).ToList(); + try + { + localClient = new CosmosClient( + this.connectionString, + new CosmosClientOptions() + { + ConnectionMode = ConnectionMode.Gateway, + RequestTimeout = TimeSpan.FromSeconds(60), + ConsistencyLevel = Microsoft.Azure.Cosmos.ConsistencyLevel.Session + }); + + string uniqueDbName = "TestDbTC_" + Guid.NewGuid().ToString(); + localDatabase = await localClient.CreateDatabaseIfNotExistsAsync(uniqueDbName); + string uniqueContainerName = "TestContainerTC_" + Guid.NewGuid().ToString(); + Container localContainer = await localDatabase.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); + + string pk = "pk_query"; + List items = this.GenerateItems(pk).ToList(); + + List itemsCreated = new List(); + foreach (TestObject item in items) + { + try + { + ItemResponse response = await localContainer.CreateItemAsync(item, new PartitionKey(item.Pk)); + if (response.StatusCode == HttpStatusCode.Created) + { + itemsCreated.Add(item); + } + } + catch (CosmosException) + { + } + } - List createdItems = await this.CreateItemsSafeAsync(items); + string query = $"SELECT * FROM c WHERE c.pk = '{pk}'"; + FeedIterator iterator = localContainer.GetItemQueryIterator(query); - string query = $"SELECT * FROM c WHERE c.pk = '{pk}'"; - FeedIterator iterator = this.container.GetItemQueryIterator(query); + int count = 0; + while (iterator.HasMoreResults) + { + FeedResponse response = await iterator.ReadNextAsync(); + count += response.Count; + } - int count = 0; - while (iterator.HasMoreResults) - { - FeedResponse response = await iterator.ReadNextAsync(); - count += response.Count; + Assert.AreEqual(itemsCreated.Count, count); } + finally + { + if (localDatabase != null) + { + try + { + await localDatabase.DeleteAsync(); + } + catch { } + } - Assert.AreEqual(createdItems.Count, count); + if (localClient != null) + { + localClient.Dispose(); + } + } } [TestMethod] @@ -927,87 +1113,247 @@ public async Task TransactionalBatchCreateItemsTest() } } - [TestMethod] - [TestCategory("ThinClient")] - public async Task RegionalFailoverWithHttpRequestException_EnsuresThinClientHeaderInRefreshRequest() - { - // Arrange - Environment.SetEnvironmentVariable(ConfigurationManager.ThinClientModeEnabled, "True"); - - bool headerFoundInRefreshRequest = false; - int accountRefreshCount = 0; - bool hasThrown = false; - - JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions - { - PropertyNamingPolicy = null, - PropertyNameCaseInsensitive = true, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }; - CosmosSystemTextJsonSerializer serializer = new CosmosSystemTextJsonSerializer(jsonSerializerOptions); - - FaultInjectionDelegatingHandler faultHandler = new FaultInjectionDelegatingHandler( - (request) => - { - // Check for account refresh requests (GET to "/" with HTTP/1.1) - if (request.Method == HttpMethod.Get && - request.RequestUri.AbsolutePath == "/" && - request.Version == new Version(1, 1)) - { - accountRefreshCount++; - - // Only check header after we've thrown the exception - if (hasThrown) - { - if (request.Headers.TryGetValues( - ThinClientConstants.EnableThinClientEndpointDiscoveryHeaderName, - out IEnumerable headerValues)) - { - if (headerValues.Contains("True")) - { - headerFoundInRefreshRequest = true; - } - } - } - } - - // Throw HttpRequestException only ONCE on ThinClient POST requests - if (!hasThrown && - request.Method == HttpMethod.Post && - request.Version == new Version(2, 0)) - { - hasThrown = true; - throw new HttpRequestException("Simulated endpoint failure"); - } - }); - - CosmosClientBuilder builder = new CosmosClientBuilder(this.connectionString) - .WithConnectionModeGateway() - .WithCustomSerializer(serializer) - .WithHttpClientFactory(() => new HttpClient(faultHandler)); - - using CosmosClient client = builder.Build(); - - string uniqueDbName = "TestFailoverDb_" + Guid.NewGuid().ToString(); - Database database = await client.CreateDatabaseIfNotExistsAsync(uniqueDbName); - string uniqueContainerName = "TestFailoverContainer_" + Guid.NewGuid().ToString(); - Container container = await database.CreateContainerIfNotExistsAsync(uniqueContainerName, "/pk"); - - string pk = "pk_failover_test"; - TestObject testItem = this.GenerateItems(pk).First(); - - // Act - CreateItemAsync will fail once, then SDK retries and succeeds - ItemResponse response = await container.CreateItemAsync(testItem, new PartitionKey(testItem.Pk)); - - // Assert - Assert.AreEqual(HttpStatusCode.Created, response.StatusCode, "Request should succeed after retry"); - Assert.IsTrue(hasThrown, "Exception should have been thrown once"); - Assert.IsTrue(headerFoundInRefreshRequest, "Account refresh after HttpRequestException should contain thin client header"); - - // Cleanup - await database.DeleteAsync(); - } - + [TestMethod] + [TestCategory("ThinClient")] + public async Task TestThinClientQueryPlanWithOrderBy() + { + List items = new List(); + string commonPk = "pk_orderby_test_" + Guid.NewGuid().ToString(); + + try + { + Environment.SetEnvironmentVariable(ConfigurationManager.BypassQueryParsing, Boolean.TrueString); + + for (int i = 0; i < 5; i++) + { + items.Add(new TestObject + { + Id = Guid.NewGuid().ToString(), + Pk = commonPk, + Other = $"Item_{i:D3}", + }); + } + + List createdItems = await this.CreateItemsSafeAsync(items); + Assert.AreEqual(5, createdItems.Count, "All items should be created"); + + // Execute ORDER BY query - this requires QueryPlan and EPK range conversion + string query = "SELECT * FROM c WHERE c.pk = @pk ORDER BY c.other DESC"; + QueryDefinition queryDef = new QueryDefinition(query).WithParameter("@pk", commonPk); + + FeedIterator iterator = this.container.GetItemQueryIterator(queryDef); + + List results = new List(); + int pageCount = 0; + + while (iterator.HasMoreResults) + { + FeedResponse response = await iterator.ReadNextAsync(); + results.AddRange(response); + pageCount++; + + string diagnostics = response.Diagnostics.ToString(); + Assert.IsTrue(diagnostics.Contains("|F4"), $"Page {pageCount}: Should use ThinClient"); + } + + Assert.AreEqual(5, results.Count, "Should return all 5 items"); + + } + finally + { + Environment.SetEnvironmentVariable(ConfigurationManager.BypassQueryParsing, null); + + foreach (TestObject item in items) + { + try + { + await this.container.DeleteItemAsync(item.Id, new PartitionKey(item.Pk)); + } + catch { } + } + } + } + + [TestMethod] + [TestCategory("ThinClient")] + public async Task TestThinClientQueryPlanCrossPartitionWithFilter() + { + List items = new List(); + string baseGuid = Guid.NewGuid().ToString(); + + try + { + Environment.SetEnvironmentVariable(ConfigurationManager.BypassQueryParsing, "True"); + + string[] partitionKeys = { + $"pk_filter_1_{baseGuid}", + $"pk_filter_2_{baseGuid}", + $"pk_filter_3_{baseGuid}" + }; + + for (int pkIndex = 0; pkIndex < partitionKeys.Length; pkIndex++) + { + for (int i = 0; i < 3; i++) + { + items.Add(new TestObject + { + Id = Guid.NewGuid().ToString(), + Pk = partitionKeys[pkIndex], + Other = $"Value_{i}", + }); + } + } + + List createdItems = await this.CreateItemsSafeAsync(items); + Assert.AreEqual(9, createdItems.Count, "All 9 items should be created"); + + string query = "SELECT * FROM c ORDER BY c._ts"; + + FeedIterator iterator = this.container.GetItemQueryIterator(query); + + List results = new List(); + int pageCount = 0; + + while (iterator.HasMoreResults) + { + FeedResponse response = await iterator.ReadNextAsync(); + results.AddRange(response); + pageCount++; + + string diagnostics = response.Diagnostics.ToString(); + Assert.IsTrue(diagnostics.Contains("|F4"), $"Page {pageCount}: Should use ThinClient"); + } + + Assert.IsTrue(results.Count >= 9, + $"Should return at least 9 items, got {results.Count}"); + + int foundCount = 0; + foreach (TestObject item in createdItems) + { + if (results.Any(r => r.Id == item.Id)) + { + foundCount++; + } + } + + Assert.IsTrue(foundCount >= 9, + $"Should find all 9 test items in results, found {foundCount}"); + + } + finally + { + Environment.SetEnvironmentVariable(ConfigurationManager.BypassQueryParsing, null); + + foreach (TestObject item in items) + { + try + { + await this.container.DeleteItemAsync(item.Id, new PartitionKey(item.Pk)); + } + catch { } + } + } + } + + [TestMethod] + [TestCategory("ThinClient")] + public async Task TestThinClientQueryPlanMultiPartitionFanout() + { + List items = new List(); + string baseGuid = Guid.NewGuid().ToString(); + + try + { + Environment.SetEnvironmentVariable(ConfigurationManager.BypassQueryParsing, Boolean.TrueString); + + // Create items across many distinct partition keys to ensure multi-partition fanout + int partitionCount = 10; + int itemsPerPartition = 3; + + for (int pkIndex = 0; pkIndex < partitionCount; pkIndex++) + { + string pk = $"pk_fanout_{pkIndex}_{baseGuid}"; + for (int i = 0; i < itemsPerPartition; i++) + { + items.Add(new TestObject + { + Id = Guid.NewGuid().ToString(), + Pk = pk, + Other = $"Partition_{pkIndex}_Item_{i}", + }); + } + } + + int totalExpected = partitionCount * itemsPerPartition; + List createdItems = await this.CreateItemsSafeAsync(items); + Assert.AreEqual(totalExpected, createdItems.Count, $"All {totalExpected} items should be created"); + + // Execute a cross-partition ORDER BY query (requires QueryPlan + fanout) + string query = "SELECT * FROM c WHERE STARTSWITH(c.other, 'Partition_') ORDER BY c.other ASC"; + + // Run query via ThinClient mode + FeedIterator thinClientIterator = this.container.GetItemQueryIterator(query); + + List thinClientResults = new List(); + while (thinClientIterator.HasMoreResults) + { + FeedResponse response = await thinClientIterator.ReadNextAsync(); + thinClientResults.AddRange(response); + + string diagnostics = response.Diagnostics.ToString(); + Assert.IsTrue(diagnostics.Contains("|F4"), "Should use ThinClient mode"); + } + + // Verify all items are returned + int foundCount = createdItems.Count(created => + thinClientResults.Any(r => r.Id == created.Id)); + Assert.AreEqual(totalExpected, foundCount, + $"Should find all {totalExpected} test items in fanout results, found {foundCount}"); + + // Compare with Gateway mode results to verify correctness + using CosmosClient gatewayClient = new CosmosClient( + this.connectionString, + new CosmosClientOptions() + { + ConnectionMode = ConnectionMode.Gateway, + Serializer = this.cosmosSystemTextJsonSerializer, + }); + + Container gatewayContainer = gatewayClient.GetContainer(this.database.Id, this.container.Id); + FeedIterator gatewayIterator = gatewayContainer.GetItemQueryIterator(query); + + List gatewayResults = new List(); + while (gatewayIterator.HasMoreResults) + { + FeedResponse response = await gatewayIterator.ReadNextAsync(); + gatewayResults.AddRange(response); + } + + // ThinClient and Gateway should return the same item count + Assert.AreEqual(gatewayResults.Count, thinClientResults.Count, + $"ThinClient ({thinClientResults.Count}) and Gateway ({gatewayResults.Count}) should return the same number of items."); + + // Verify both results contain the same item IDs + HashSet thinClientIds = new HashSet(thinClientResults.Select(r => r.Id)); + HashSet gatewayIds = new HashSet(gatewayResults.Select(r => r.Id)); + Assert.IsTrue(thinClientIds.SetEquals(gatewayIds), + "ThinClient and Gateway should return the same set of items."); + } + finally + { + Environment.SetEnvironmentVariable(ConfigurationManager.BypassQueryParsing, null); + + foreach (TestObject item in items) + { + try + { + await this.container.DeleteItemAsync(item.Id, new PartitionKey(item.Pk)); + } + catch { } + } + } + } + /// /// DelegatingHandler that intercepts HTTP requests and can inject faults /// diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/BaselineTest/TestBaseline/SqlObjectVisitorBaselineTests.SqlFunctionCalls.xml b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/BaselineTest/TestBaseline/SqlObjectVisitorBaselineTests.SqlFunctionCalls.xml index c96170c087..c54faca13c 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/BaselineTest/TestBaseline/SqlObjectVisitorBaselineTests.SqlFunctionCalls.xml +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/BaselineTest/TestBaseline/SqlObjectVisitorBaselineTests.SqlFunctionCalls.xml @@ -1,4634 +1,4770 @@ - - - - _COMPARE_BSON_BINARYDATA - - - - - - -1302450251 - - - - - - _COMPARE_OBJECTS - - - - - - 1834671385 - - - - - - _M_EVAL_EQ - - - - - - -937798776 - - - - - - _M_EVAL_GT - - - - - - -937689624 - - - - - - _M_EVAL_GTE - - - - - - 148219533 - - - - - - _M_EVAL_IN - - - - - - -1737483201 - - - - - - _M_EVAL_LT - - - - - - -934760921 - - - - - - _M_EVAL_LTE - - - - - - 30540149 - - - - - - _M_EVAL_NEQ - - - - - - 49027154 - - - - - - _M_EVAL_NIN - - - - - - -258213395 - - - - - - _ObjectToArray - - - - - - -236268680 - - - - - - _PROXY_PROJECTION - - - - - - 610013180 - - - - - - _REGEX_MATCH - - - - - - -962904190 - - - - - - _ST_DISTANCE - - - - - - -1605852852 - - - - - - _ST_INTERSECTS - - - - - - -652359528 - - - - - - _ST_WITHIN - - - - - - 172593400 - - - - - - _TRY_ARRAY_CONTAINS - - - - - - 1151335009 - - - - - - ABS - - - - - - 948101022 - - - - - - ACOS - - - - - - 1660875890 - - - - - - ALL - - - - - - 948025334 - - - - - - ANY - - - - - - 948017723 - - - - - - ARRAY - - - - - - 1424287333 - - - - - - ARRAY_AVG - - - - - - 323897902 - - - - - - ARRAY_CONCAT - - - - - - -1615943767 - - - - - - ARRAY_CONTAINS - - - - - - -854810616 - - - - - - ARRAY_LENGTH - - - - - - -2104916661 - - - - - - ARRAY_SLICE - - - - - - -1823352982 - - - - - - ASIN - - - - - - 1734029734 - - - - - - ATAN - - - - - - 1730393998 - - - - - - ATN2 - - - - - - 1730444475 - - - - - - AVG - - - - - - 950772724 - - - - - - C_BINARY - - - - - - 1210908139 - - - - - - C_FLOAT32 - - - - - - -472685730 - - - - - - C_FLOAT64 - - - - - - -472681688 - - - - - - C_GUID - - - - - - -1807738202 - - - - - - C_INT16 - - - - - - -384520670 - - - - - - C_INT32 - - - - - - -384524651 - - - - - - C_INT64 - - - - - - -384155345 - - - - - - C_INT8 - - - - - - -1805552873 - - - - - - C_LIST - - - - - - 1591190418 - - - - - - C_LISTCONTAINS - - - - - - 1693035758 - - - - - - C_MAP - - - - - - 1391965105 - - - - - - C_MAPCONTAINS - - - - - - 893948196 - - - - - - C_MAPCONTAINSKEY - - - - - - -1848028241 - - - - - - C_MAPCONTAINSVALUE - - - - - - -1676685015 - - - - - - C_SET - - - - - - 1490943678 - - - - - - C_SETCONTAINS - - - - - - -1431746769 - - - - - - C_TUPLE - - - - - - 1511703250 - - - - - - C_UDT - - - - - - -1775923376 - - - - - - C_UINT32 - - - - - - 1491911555 - - - - - - CEILING - - - - - - 326203514 - - - - - - CONCAT - - - - - - -551258348 - - - - - - CONTAINS - - - - - - -1074519824 - - - - - - COS - - - - - - 950901151 - - - - - - COT - - - - - - 950887618 - - - - - - COUNT - - - - - - 1275248890 - - - - - - DateTimeAdd - - - - - - 1610287731 - - - - - - DateTimeBin - - - - - - -2042557462 - - - - - - DateTimeFormat - - - - - - -366443220 - - - - - - DateTimeDiff - - - - - - -1313869462 - - - - - - DateTimeFromParts - - - - - - 1715858645 - - - - - - DateTimePart - - - - - - 77619208 - - - - - - DateTimeToTicks - - - - - - -447006820 - - - - - - DateTimeToTimestamp - - - - - - 292597322 - - - - - - DAY - - - - - - 730252520 - - - - - - DEGREES - - - - - - -1010818131 - - - - - - DOCUMENTID - - - - - - -1119491048 - - - - - - ENDSWITH - - - - - - 1310545128 - - - - - - EXP - - - - - - 1188489945 - - - - - - FLOOR - - - - - - 1595010801 - - - - - - GetCurrentDateTime - - - - - - 628961137 - - - - - - GetCurrentTicks - - - - - - 767789568 - - - - - - GetCurrentTimestamp - - - - - - -108724186 - - - - - - IIF - - - - - - 1912853209 - - - - - - INDEX_OF - - - - - - -490611053 - - - - - - IS_ARRAY - - - - - - -605857869 - - - - - - IS_BOOL - - - - - - -1031205701 - - - - - - IS_DATETIME - - - - - - -1529891165 - - - - - - IS_DEFINED - - - - - - -673974177 - - - - - - IS_FINITE_NUMBER - - - - - - 1858549009 - - - - - - IS_NULL - - - - - - 1695544283 - - - - - - IS_NUMBER - - - - - - 499272998 - - - - - - IS_OBJECT - - - - - - 1190524845 - - - - - - IS_PRIMITIVE - - - - - - -25700510 - - - - - - IS_STRING - - - - - - 197369964 - - - - - - LastIndexOf - - - - - - -1618285648 - - - - - - LEFT - - - - - - 677167842 - - - - - - LENGTH - - - - - - 189371521 - - - - - - LIKE - - - - - - -535385742 - - - - - - LOG - - - - - - 951983273 - - - - - - LOG10 - - - - - - -1007856584 - - - - - - LOWER - - - - - - -1008756110 - - - - - - LTRIM - - - - - - -1298153349 - - - - - - MAX - - - - - - 951557458 - - - - - - MIN - - - - - - 951572494 - - - - - - MONTH - - - - - - -1384364250 - - - - - - ObjectToArray - - - - - - 1958364769 - - - - - - PI - - - - - - 759877112 - - - - - - POWER - - - - - - -2065410283 - - - - - - RADIANS - - - - - - 2096097273 - - - - - - RAND - - - - - - -1422123156 - - - - - - REPLACE - - - - - - 611232669 - - - - - - REPLICATE - - - - - - -1759231678 - - - - - - REVERSE - - - - - - -716026956 - - - - - - RIGHT - - - - - - 891700551 - - - - - - ROUND - - - - - - 1845634331 - - - - - - RTRIM - - - - - - -1534507744 - - - - - - SetDifference - - - - - - 1109260146 - - - - - - SetEqual - - - - - - -2058439928 - - - - - - SetIntersect - - - - - - -644124670 - - - - - - SetUnion - - - - - - 1177661016 - - - - - - SIGN - - - - - - 1835961124 - - - - - - SIN - - - - - - 951887607 - - - - - - SQRT - - - - - - 2142163143 - - - - - - SQUARE - - - - - - -67058548 - - - - - - STARTSWITH - - - - - - 820442350 - - - - - - ST_DISTANCE - - - - - - 1233749487 - - - - - - ST_INTERSECTS - - - - - - 1992127418 - - - - - - ST_ISVALID - - - - - - -488760339 - - - - - - ST_ISVALIDDETAILED - - - - - - 202371336 - - - - - - ST_WITHIN - - - - - - 1288817159 - - - - - - StringEquals - - - - - - 67992629 - - - - - - StringJoin - - - - - - 379070440 - - - - - - StringSplit - - - - - - 1939927191 - - - - - - StringToArray - - - - - - 470263213 - - - - - - StringToBoolean - - - - - - -1874642418 - - - - - - StringToNull - - - - - - -970438357 - - - - - - StringToNumber - - - - - - 1152869235 - - - - - - StringToObject - - - - - - 72615192 - - - - - - SUBSTRING - - - - - - -1893316890 - - - - - - SUM - - - - - - 1189519259 - - - - - - TAN - - - - - - 1189160248 - - - - - - TicksToDateTime - - - - - - 688550720 - - - - - - TimestampToDateTime - - - - - - -721974150 - - - - - - ToString - - - - - - -1554853341 - - - - - - TRIM - - - - - - -1513216505 - - - - - - TRUNC - - - - - - -1614924416 - - - - - - UPPER - - - - - - 2018810216 - - - - - - VectorDistance - - - - - - 341383158 - - - - - - YEAR - - - - - - 1895825496 - - - + + + + _COMPARE_BSON_BINARYDATA + + + + + + -1302450251 + + + + + + _COMPARE_OBJECTS + + + + + + 1834671385 + + + + + + _M_EVAL_EQ + + + + + + -937798776 + + + + + + _M_EVAL_GT + + + + + + -937689624 + + + + + + _M_EVAL_GTE + + + + + + 148219533 + + + + + + _M_EVAL_IN + + + + + + -1737483201 + + + + + + _M_EVAL_LT + + + + + + -934760921 + + + + + + _M_EVAL_LTE + + + + + + 30540149 + + + + + + _M_EVAL_NEQ + + + + + + 49027154 + + + + + + _M_EVAL_NIN + + + + + + -258213395 + + + + + + _ObjectToArray + + + + + + -236268680 + + + + + + _PROXY_PROJECTION + + + + + + 610013180 + + + + + + _REGEX_MATCH + + + + + + -962904190 + + + + + + _ST_DISTANCE + + + + + + -1605852852 + + + + + + _ST_INTERSECTS + + + + + + -652359528 + + + + + + _ST_WITHIN + + + + + + 172593400 + + + + + + _TRY_ARRAY_CONTAINS + + + + + + 1151335009 + + + + + + ABS + + + + + + 948101022 + + + + + + ACOS + + + + + + 1660875890 + + + + + + ALL + + + + + + 948025334 + + + + + + ANY + + + + + + 948017723 + + + + + + ARRAY + + + + + + 1424287333 + + + + + + ARRAY_AVG + + + + + + 323897902 + + + + + + ARRAY_CONCAT + + + + + + -1615943767 + + + + + + ARRAY_CONTAINS + + + + + + -854810616 + + + + + + ARRAY_LENGTH + + + + + + -2104916661 + + + + + + ARRAY_SLICE + + + + + + -1823352982 + + + + + + ASIN + + + + + + 1734029734 + + + + + + ATAN + + + + + + 1730393998 + + + + + + ATN2 + + + + + + 1730444475 + + + + + + AVG + + + + + + 950772724 + + + + + + C_BINARY + + + + + + 1210908139 + + + + + + C_FLOAT32 + + + + + + -472685730 + + + + + + C_FLOAT64 + + + + + + -472681688 + + + + + + C_GUID + + + + + + -1807738202 + + + + + + C_INT16 + + + + + + -384520670 + + + + + + C_INT32 + + + + + + -384524651 + + + + + + C_INT64 + + + + + + -384155345 + + + + + + C_INT8 + + + + + + -1805552873 + + + + + + C_LIST + + + + + + 1591190418 + + + + + + C_LISTCONTAINS + + + + + + 1693035758 + + + + + + C_MAP + + + + + + 1391965105 + + + + + + C_MAPCONTAINS + + + + + + 893948196 + + + + + + C_MAPCONTAINSKEY + + + + + + -1848028241 + + + + + + C_MAPCONTAINSVALUE + + + + + + -1676685015 + + + + + + C_SET + + + + + + 1490943678 + + + + + + C_SETCONTAINS + + + + + + -1431746769 + + + + + + C_TUPLE + + + + + + 1511703250 + + + + + + C_UDT + + + + + + -1775923376 + + + + + + C_UINT32 + + + + + + 1491911555 + + + + + + CEILING + + + + + + 326203514 + + + + + + CONCAT + + + + + + -551258348 + + + + + + CONTAINS + + + + + + -1074519824 + + + + + + COS + + + + + + 950901151 + + + + + + COT + + + + + + 950887618 + + + + + + COUNT + + + + + + 1275248890 + + + + + + DateTimeAdd + + + + + + 1610287731 + + + + + + DateTimeBin + + + + + + -2042557462 + + + + + + DateTimeFormat + + + + + + -366443220 + + + + + + DateTimeDiff + + + + + + -1313869462 + + + + + + DateTimeFromParts + + + + + + 1715858645 + + + + + + DateTimePart + + + + + + 77619208 + + + + + + DateTimeToTicks + + + + + + -447006820 + + + + + + DateTimeToTimestamp + + + + + + 292597322 + + + + + + DAY + + + + + + 730252520 + + + + + + DEGREES + + + + + + -1010818131 + + + + + + DOCUMENTID + + + + + + -1119491048 + + + + + + ENDSWITH + + + + + + 1310545128 + + + + + + EXP + + + + + + 1188489945 + + + + + + FLOOR + + + + + + 1595010801 + + + + + + GetCurrentDateTime + + + + + + 628961137 + + + + + + GetCurrentTicks + + + + + + 767789568 + + + + + + GetCurrentTimestamp + + + + + + -108724186 + + + + + + IIF + + + + + + 1912853209 + + + + + + INDEX_OF + + + + + + -490611053 + + + + + + IS_ARRAY + + + + + + -605857869 + + + + + + IS_BOOL + + + + + + -1031205701 + + + + + + IS_DATETIME + + + + + + -1529891165 + + + + + + IS_DEFINED + + + + + + -673974177 + + + + + + IS_FINITE_NUMBER + + + + + + 1858549009 + + + + + + IS_NULL + + + + + + 1695544283 + + + + + + IS_NUMBER + + + + + + 499272998 + + + + + + IS_OBJECT + + + + + + 1190524845 + + + + + + IS_PRIMITIVE + + + + + + -25700510 + + + + + + IS_STRING + + + + + + 197369964 + + + + + + LastIndexOf + + + + + + -1618285648 + + + + + + LastSubstringAfter + + + + + + 441842242 + + + + + + LastSubstringBefore + + + + + + 1887256552 + + + + + + LEFT + + + + + + 677167842 + + + + + + LENGTH + + + + + + 189371521 + + + + + + LIKE + + + + + + -535385742 + + + + + + LOG + + + + + + 951983273 + + + + + + LOG10 + + + + + + -1007856584 + + + + + + LOWER + + + + + + -1008756110 + + + + + + LTRIM + + + + + + -1298153349 + + + + + + MAX + + + + + + 951557458 + + + + + + MIN + + + + + + 951572494 + + + + + + MONTH + + + + + + -1384364250 + + + + + + ObjectToArray + + + + + + 1958364769 + + + + + + PI + + + + + + 759877112 + + + + + + POWER + + + + + + -2065410283 + + + + + + RADIANS + + + + + + 2096097273 + + + + + + RAND + + + + + + -1422123156 + + + + + + REPLACE + + + + + + 611232669 + + + + + + REPLICATE + + + + + + -1759231678 + + + + + + REVERSE + + + + + + -716026956 + + + + + + RIGHT + + + + + + 891700551 + + + + + + ROUND + + + + + + 1845634331 + + + + + + RTRIM + + + + + + -1534507744 + + + + + + SetDifference + + + + + + 1109260146 + + + + + + SetEqual + + + + + + -2058439928 + + + + + + SetIntersect + + + + + + -644124670 + + + + + + SetUnion + + + + + + 1177661016 + + + + + + SIGN + + + + + + 1835961124 + + + + + + SIN + + + + + + 951887607 + + + + + + SQRT + + + + + + 2142163143 + + + + + + SQUARE + + + + + + -67058548 + + + + + + STARTSWITH + + + + + + 820442350 + + + + + + ST_DISTANCE + + + + + + 1233749487 + + + + + + ST_INTERSECTS + + + + + + 1992127418 + + + + + + ST_ISVALID + + + + + + -488760339 + + + + + + ST_ISVALIDDETAILED + + + + + + 202371336 + + + + + + ST_WITHIN + + + + + + 1288817159 + + + + + + StringEquals + + + + + + 67992629 + + + + + + StringJoin + + + + + + 379070440 + + + + + + StringSplit + + + + + + 1939927191 + + + + + + StringToArray + + + + + + 470263213 + + + + + + StringToBoolean + + + + + + -1874642418 + + + + + + StringToNull + + + + + + -970438357 + + + + + + StringToNumber + + + + + + 1152869235 + + + + + + StringToObject + + + + + + 72615192 + + + + + + SUBSTRING + + + + + + -1893316890 + + + + + + SubstringAfter + + + + + + 1519983960 + + + + + + SubstringBefore + + + + + + 516840642 + + + + + + SUM + + + + + + 1189519259 + + + + + + TAN + + + + + + 1189160248 + + + + + + TicksToDateTime + + + + + + 688550720 + + + + + + TimestampToDateTime + + + + + + -721974150 + + + + + + ToString + + + + + + -1554853341 + + + + + + TRIM + + + + + + -1513216505 + + + + + + TRUNC + + + + + + -1614924416 + + + + + + UPPER + + + + + + 2018810216 + + + + + + VectorDistance + + + + + + 341383158 + + + + + + YEAR + + + + + + 1895825496 + + + \ No newline at end of file diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/GatewayStoreModelTest.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/GatewayStoreModelTest.cs index ba3eaaeb81..38ba61c481 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/GatewayStoreModelTest.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/GatewayStoreModelTest.cs @@ -1333,7 +1333,7 @@ public async Task ThinClient_ProcessMessageAsync_WithUnsupportedOperations_Shoul .ReturnsAsync(successResponse); DocumentServiceRequest request = DocumentServiceRequest.Create( - operationType: OperationType.QueryPlan, + operationType: OperationType.ReadFeed, resourceType: ResourceType.Document, resourceId: "NH1uAJ6ANm0=", body: null, diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/SqlObjects/SqlObjectVisitorBaselineTests.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/SqlObjects/SqlObjectVisitorBaselineTests.cs index cba3cfb796..30928ea280 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/SqlObjects/SqlObjectVisitorBaselineTests.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/SqlObjects/SqlObjectVisitorBaselineTests.cs @@ -795,7 +795,19 @@ public void SqlFunctionCalls() SqlFunctionCallScalarExpression.CreateBuiltin( SqlFunctionCallScalarExpression.Identifiers.LastIndexOf, SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("ABCDABCDABC")), - SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("ABC")))), + SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("ABC")))), + new SqlObjectVisitorInput( + SqlFunctionCallScalarExpression.Names.LastSubstringAfter, + SqlFunctionCallScalarExpression.CreateBuiltin( + SqlFunctionCallScalarExpression.Identifiers.LastSubstringAfter, + SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("Hello world")), + SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("o")))), + new SqlObjectVisitorInput( + SqlFunctionCallScalarExpression.Names.LastSubstringBefore, + SqlFunctionCallScalarExpression.CreateBuiltin( + SqlFunctionCallScalarExpression.Identifiers.LastSubstringBefore, + SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("Hello world")), + SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("o")))), new SqlObjectVisitorInput( SqlFunctionCallScalarExpression.Names.Left, SqlFunctionCallScalarExpression.CreateBuiltin( @@ -1061,7 +1073,19 @@ public void SqlFunctionCalls() SqlFunctionCallScalarExpression.Identifiers.Substring, SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("Hello")), SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(1)), - SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(2)))), + SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(2)))), + new SqlObjectVisitorInput( + SqlFunctionCallScalarExpression.Names.SubstringAfter, + SqlFunctionCallScalarExpression.CreateBuiltin( + SqlFunctionCallScalarExpression.Identifiers.SubstringAfter, + SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("Hello world")), + SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("o")))), + new SqlObjectVisitorInput( + SqlFunctionCallScalarExpression.Names.SubstringBefore, + SqlFunctionCallScalarExpression.CreateBuiltin( + SqlFunctionCallScalarExpression.Identifiers.SubstringBefore, + SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("Hello world")), + SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("o")))), new SqlObjectVisitorInput( SqlFunctionCallScalarExpression.Names.Sum, SqlFunctionCallScalarExpression.CreateBuiltin( diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/ThinClientStoreClientTests.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/ThinClientStoreClientTests.cs index 7e400450a8..d97bb331ae 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/ThinClientStoreClientTests.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/ThinClientStoreClientTests.cs @@ -4,21 +4,25 @@ namespace Microsoft.Azure.Cosmos.Tests { - using System; - using System.Collections.ObjectModel; - using System.IO; - using System.Linq; + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.IO; + using System.Linq; using System.Net; - using System.Net.Http; + using System.Net.Http; using System.Text; using System.Threading; - using System.Threading.Tasks; - using Microsoft.Azure.Cosmos.Routing; - using Microsoft.Azure.Cosmos.Telemetry; - using Microsoft.Azure.Cosmos.Tracing; + using System.Threading.Tasks; + using Microsoft.Azure.Cosmos.Query.Core.QueryPlan; + using Microsoft.Azure.Cosmos.Routing; + using Microsoft.Azure.Cosmos.Telemetry; + using Microsoft.Azure.Cosmos.Tracing; using Microsoft.Azure.Documents; - using Microsoft.VisualStudio.TestTools.UnitTesting; - using Moq; + using Microsoft.Azure.Documents.Routing; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Newtonsoft.Json; [TestClass] public class ThinClientStoreClientTests @@ -391,6 +395,133 @@ public void Constructor_ShouldThrowArgumentNullException_WhenUserAgentContainerI StringAssert.Contains(ex.Message, "UserAgentContainer cannot be null"); } + #region ThinClientQueryPlanHelper Tests + + private static readonly PartitionKeyDefinition HashPartitionKeyDefinition = new PartitionKeyDefinition() + { + Paths = new Collection() { "/id" }, + Kind = PartitionKind.Hash, + }; + + [TestMethod] + [DynamicData(nameof(GetQueryPlanJsonTestCases), DynamicDataSourceType.Method)] + public void DeserializeQueryPlanResponse_ConsistentWithQueryPartitionProvider(string queryPlanJson, string description) + { + // Deserialize via ThinClientQueryPlanHelper (stream-based, as used in thin client mode) + PartitionedQueryExecutionInfo thinClientResult; + using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(queryPlanJson))) + { + thinClientResult = ThinClientQueryPlanHelper.DeserializeQueryPlanResponse( + stream, + HashPartitionKeyDefinition); + } + + // Deserialize via QueryPartitionProvider (string-based, as used in gateway/service-interop mode) + QueryPartitionProvider queryPartitionProvider = new QueryPartitionProvider( + new Dictionary() { { "maxSqlQueryInputLength", 524288 } }); + + PartitionedQueryExecutionInfoInternal queryInfoInternal = + JsonConvert.DeserializeObject( + queryPlanJson, + new JsonSerializerSettings { DateParseHandling = DateParseHandling.None, MaxDepth = 64 }); + + PartitionedQueryExecutionInfo providerResult = queryPartitionProvider.ConvertPartitionedQueryExecutionInfo( + queryInfoInternal, + HashPartitionKeyDefinition); + + // Assert: Both paths must produce identical EPK ranges + Assert.AreEqual(providerResult.QueryRanges.Count, thinClientResult.QueryRanges.Count, description); + for (int i = 0; i < providerResult.QueryRanges.Count; i++) + { + Assert.AreEqual(providerResult.QueryRanges[i].Min, thinClientResult.QueryRanges[i].Min, $"{description} - range[{i}].Min"); + Assert.AreEqual(providerResult.QueryRanges[i].Max, thinClientResult.QueryRanges[i].Max, $"{description} - range[{i}].Max"); + Assert.AreEqual(providerResult.QueryRanges[i].IsMinInclusive, thinClientResult.QueryRanges[i].IsMinInclusive, $"{description} - range[{i}].IsMinInclusive"); + Assert.AreEqual(providerResult.QueryRanges[i].IsMaxInclusive, thinClientResult.QueryRanges[i].IsMaxInclusive, $"{description} - range[{i}].IsMaxInclusive"); + } + } + + private static IEnumerable GetQueryPlanJsonTestCases() + { + // Full range (cross-partition query) + yield return new object[] + { + @"{""queryInfo"":{""distinctType"":""None"",""top"":null,""offset"":null,""limit"":null,""orderBy"":[],""orderByExpressions"":[],""groupByExpressions"":[],""groupByAliases"":[],""aggregates"":[""CountIf""],""groupByAliasToAggregateType"":{},""rewrittenQuery"":""SELECT VALUE [{\""item\"": COUNTIF(c.valid)}]\nFROM c"",""hasSelectValue"":true,""dCountInfo"":null,""hasNonStreamingOrderBy"":false},""queryRanges"":[{""min"":[],""max"":""Infinity"",""isMinInclusive"":true,""isMaxInclusive"":false}]}", + "Full range with aggregate" + }; + + // Point query (single partition key) + yield return new object[] + { + @"{""queryInfo"":{""distinctType"":""None"",""top"":null,""offset"":null,""limit"":null,""orderBy"":[""Descending""],""orderByExpressions"":[],""groupByExpressions"":[],""groupByAliases"":[],""aggregates"":[],""groupByAliasToAggregateType"":{},""rewrittenQuery"":"""",""hasSelectValue"":false,""dCountInfo"":null,""hasNonStreamingOrderBy"":false},""queryRanges"":[{""min"":[""testValue""],""max"":[""testValue""],""isMinInclusive"":true,""isMaxInclusive"":true}]}", + "Point query with ORDER BY" + }; + + // HybridSearchQueryInfo + yield return new object[] + { + @"{""hybridSearchQueryInfo"":{""globalStatisticsQuery"":""SELECT COUNT(1) AS documentCount, [] AS fullTextStatistics\nFROM c"",""componentQueryInfos"":[],""componentWithoutPayloadQueryInfos"":[],""projectionQueryInfo"":null,""componentWeights"":null,""skip"":null,""take"":10,""requiresGlobalStatistics"":false},""queryRanges"":[{""min"":[],""max"":""Infinity"",""isMinInclusive"":true,""isMaxInclusive"":false}]}", + "HybridSearchQueryInfo" + }; + } + + [TestMethod] + public void DeserializeQueryPlanResponse_MultipleRanges_SortsOutput() + { + // Multiple ranges in deliberate reverse order to verify sorting + string queryPlanJson = @"{""queryInfo"":{""distinctType"":""None"",""top"":null,""offset"":null,""limit"":null,""orderBy"":[],""orderByExpressions"":[],""groupByExpressions"":[],""groupByAliases"":[],""aggregates"":[],""groupByAliasToAggregateType"":{},""rewrittenQuery"":"""",""hasSelectValue"":false,""dCountInfo"":null,""hasNonStreamingOrderBy"":false},""queryRanges"":[{""min"":[""zzz""],""max"":[""zzz""],""isMinInclusive"":true,""isMaxInclusive"":true},{""min"":[""aaa""],""max"":[""aaa""],""isMinInclusive"":true,""isMaxInclusive"":true},{""min"":[""mmm""],""max"":[""mmm""],""isMinInclusive"":true,""isMaxInclusive"":true}]}"; + + using Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(queryPlanJson)); + + PartitionedQueryExecutionInfo result = ThinClientQueryPlanHelper.DeserializeQueryPlanResponse( + stream, + HashPartitionKeyDefinition); + + Assert.AreEqual(3, result.QueryRanges.Count); + for (int i = 0; i < result.QueryRanges.Count - 1; i++) + { + Assert.IsTrue( + string.Compare(result.QueryRanges[i].Min, result.QueryRanges[i + 1].Min, StringComparison.Ordinal) <= 0, + $"Ranges should be sorted: range[{i}].Min='{result.QueryRanges[i].Min}' should be <= range[{i + 1}].Min='{result.QueryRanges[i + 1].Min}'"); + } + } + + [TestMethod] + public void DeserializeQueryPlanResponse_InvalidInputs_FailsFast() + { + Assert.ThrowsException( + () => ThinClientQueryPlanHelper.DeserializeQueryPlanResponse(null, HashPartitionKeyDefinition), + "Null stream should throw"); + + using (Stream validStream = new MemoryStream(Encoding.UTF8.GetBytes("{}"))) + { + Assert.ThrowsException( + () => ThinClientQueryPlanHelper.DeserializeQueryPlanResponse(validStream, null), + "Null partitionKeyDefinition should throw"); + } + + using (Stream badJson = new MemoryStream(Encoding.UTF8.GetBytes("not valid json {{{"))) + { + try + { + ThinClientQueryPlanHelper.DeserializeQueryPlanResponse(badJson, HashPartitionKeyDefinition); + Assert.Fail("Malformed JSON should throw"); + } + catch (System.Text.Json.JsonException) + { + // Expected - System.Text.Json throws JsonException or a derived type for malformed JSON + } + } + + using (Stream nullJson = new MemoryStream(Encoding.UTF8.GetBytes("null"))) + { + Assert.ThrowsException( + () => ThinClientQueryPlanHelper.DeserializeQueryPlanResponse(nullJson, HashPartitionKeyDefinition), + "JSON null should throw FormatException"); + } + } + + #endregion + private ContainerProperties GetMockContainerProperties() { ContainerProperties containerProperties = new ContainerProperties diff --git a/changelog.md b/changelog.md index 8e43f01e9c..9d0bc8404d 100644 --- a/changelog.md +++ b/changelog.md @@ -1,6 +1,6 @@ ## Recommended version -The **minimum recommended version is [3.51.0](#3.51.0)**. +The **minimum recommended version is [3.57.0](#3.57.0)**. Make sure that your applications, when using the .NET V3 SDK, are using at least the version described here to have all the critical fixes. With the release of [3.47.0](#3.47.0), it is now best practice to include a cross regional hedging availability strategy when using the Azure Cosmos DB .NET SDK. For more information about cross regional hedging, see [here](https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/docs/Cross%20Region%20Request%20Hedging.md). @@ -15,6 +15,27 @@ Preview features are treated as a separate branch and will not be included in th The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +### [3.59.0-preview.0](https://www.nuget.org/packages/Microsoft.Azure.Cosmos/3.59.0-preview.0) - 2026-3-17 + +#### Added +- [5685](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5685) Read Consistency Strategy: Adds Read Consistency Strategy option for read requests +- [5634](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5634) Semantic Reranking: Adds response body in semantic reranking error responses +- [5502](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5502) VectorIndex Policy: Adds support for QuantizerType in IndexingPolicy + +### [3.58.0](https://www.nuget.org/packages/Microsoft.Azure.Cosmos/3.58.0) - 2026-3-17 + +#### Added +- [5447](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5447) Per Partition Automatic Failover: Adds Hub Region Processing Only While Routing Requests Failed with 404/1002 for single master accounts +- [5582](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5582) Query: Adds ability to choose global vs local/focused statistics for FullTextScore +- [5693](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5693) ThinClient Integration: Adds Enable Multiple Http2 connection on SocketsHttpHandler +- [5614](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5614) ThinClient Integration: Adds support for QueryPlan in thinclient mode +- [5610](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5610) Refactors N-Region Synchronous Commit feature to use IServiceConfigurationReaderVNext interface. + +#### Fixed +- [5597](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5597) CosmosClient: Fixes ObjectDisposedException message when client is disposed during request +- [5650](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5650) Batch: Fixes null ErrorMessage when promoting status from MultiStatus response +- [5651](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5651) Serializer: Fixes unsafe stream cast in FromStream + ### [3.58.0-preview.1](https://www.nuget.org/packages/Microsoft.Azure.Cosmos/3.58.0-preview.1) - 2026-2-20 ### [3.57.1](https://www.nuget.org/packages/Microsoft.Azure.Cosmos/3.57.1) - 2026-2-20 diff --git a/docs/sync_up_msdata_direct.md b/docs/sync_up_msdata_direct.md index 9c416aa65b..28d2ffb425 100644 --- a/docs/sync_up_msdata_direct.md +++ b/docs/sync_up_msdata_direct.md @@ -89,5 +89,38 @@ Once the feature branch builds successfully, it's time to submit the PR to `msda ## Sample Pull Requests to Sync-up msdata direct +- [[Internal] Direct package: Adds msdata/direct update from master](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/5612) - [[Internal] Msdata/Direct: Refactors msdata branch with latest v3 and direct release](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/3726) -- [[Internal] Msdata/Direct: Refactors msdata/direct branch with latest v3 master and Cosmos.Direct v3.30.4](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/3776) \ No newline at end of file +- [[Internal] Msdata/Direct: Refactors msdata/direct branch with latest v3 master and Cosmos.Direct v3.30.4](https://github.com/Azure/azure-cosmos-dotnet-v3/pull/3776) + +## Automated Workflow (Recommended) + +For a faster and more reliable sync process, use the Copilot agent and helper script: + +### Option 1: Copilot Agent (AI-Assisted) + +Use the Copilot agent at [`.github/agents/msdata-direct-sync-agent.agent.md`](../.github/agents/msdata-direct-sync-agent.agent.md) for a guided, AI-assisted workflow. Start with this prompt: + +``` +Follow the msdata/direct sync agent plan in .github/agents/msdata-direct-sync-agent.agent.md + +Sync the msdata/direct branch with the latest v3 master and msdata direct codebase. +``` + +The agent handles: environment validation, branch creation, master merge, conflict resolution, msdata file sync, build validation, and PR creation. + +### Option 2: PowerShell Helper Script + +Run the helper script at [`tools/msdata-direct-sync-helper.ps1`](../tools/msdata-direct-sync-helper.ps1) for full automation: + +```powershell +# Full workflow (all phases) +.\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" + +# Run individual phases +.\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" -Phase Setup +.\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" -Phase Branch +.\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" -Phase Sync +.\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" -Phase Build +.\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" -Phase PR +``` \ No newline at end of file diff --git a/tools/msdata-direct-sync-helper.ps1 b/tools/msdata-direct-sync-helper.ps1 new file mode 100644 index 0000000000..0414f12e67 --- /dev/null +++ b/tools/msdata-direct-sync-helper.ps1 @@ -0,0 +1,651 @@ +<# +.SYNOPSIS + Helper script for syncing the msdata/direct branch with latest v3 master and msdata CosmosDB repo. + +.DESCRIPTION + Automates the mechanical parts of the msdata/direct sync workflow: + - Validates prerequisites (git, dotnet CLI, gh CLI) + - Creates feature branch with correct naming convention + - Merges master into the feature branch + - Configures and runs msdata_sync.ps1 + - Runs build validation + - Optionally creates a PR + + See .github/agents/msdata-direct-sync-agent.agent.md for the full workflow documentation. + See docs/sync_up_msdata_direct.md for background on the sync process. + +.PARAMETER MsdataRepoPath + Path to the local msdata CosmosDB repository clone. Required for the Sync phase. + +.PARAMETER Phase + Run a specific phase only. Valid values: Setup, Branch, Sync, Build, PR, All. + Default: All (runs all phases sequentially). + +.PARAMETER GitHubUsername + GitHub username for branch naming. If not provided, auto-detected via gh CLI or git config. + +.PARAMETER SkipBuild + Skip the build validation phase. Not recommended but useful for re-runs. + +.EXAMPLE + .\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" + +.EXAMPLE + .\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "C:\repos\CosmosDB" -Phase Sync + +.EXAMPLE + .\tools\msdata-direct-sync-helper.ps1 -MsdataRepoPath "Q:\CosmosDB" -GitHubUsername "nalutripician" +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory = $false)] + [string]$MsdataRepoPath, + + [Parameter(Mandatory = $false)] + [ValidateSet("Setup", "Branch", "Sync", "Build", "PR", "All")] + [string]$Phase = "All", + + [Parameter(Mandatory = $false)] + [string]$GitHubUsername, + + [Parameter(Mandatory = $false)] + [switch]$SkipBuild +) + +$ErrorActionPreference = "Stop" +$script:RepoRoot = git rev-parse --show-toplevel 2>$null +if (-not $script:RepoRoot) { + Write-Error "This script must be run from within the azure-cosmos-dotnet-v3 repository." + exit 1 +} + +$script:DateStamp = (Get-Date).ToString("MM_dd_yyyy") +$script:BranchName = $null +$script:PhaseResults = @{} + +# ============================================================================ +# Helper Functions +# ============================================================================ + +function Write-Phase { + param([string]$PhaseName, [string]$Message) + Write-Host "" + Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Cyan + Write-Host " Phase: $PhaseName" -ForegroundColor Cyan + Write-Host " $Message" -ForegroundColor Gray + Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Cyan + Write-Host "" +} + +function Write-Step { + param([int]$Number, [string]$Description) + Write-Host " [$Number] $Description" -ForegroundColor Yellow +} + +function Write-Success { + param([string]$Message) + Write-Host " ✅ $Message" -ForegroundColor Green +} + +function Write-Failure { + param([string]$Message) + Write-Host " ❌ $Message" -ForegroundColor Red +} + +function Write-Info { + param([string]$Message) + Write-Host " ℹ️ $Message" -ForegroundColor Gray +} + +function Get-GitHubUsername { + if ($GitHubUsername) { + return $GitHubUsername + } + + # Try gh CLI first + try { + $username = gh api user --jq '.login' 2>$null + if ($username) { + Write-Info "Detected GitHub username via gh CLI: $username" + return $username + } + } catch { } + + # Fall back to git config + $username = git config user.name 2>$null + if ($username) { + Write-Info "Using git config user.name: $username" + return $username + } + + Write-Failure "Could not detect GitHub username. Please provide -GitHubUsername parameter." + exit 1 +} + +# ============================================================================ +# Phase: Setup — Validate prerequisites +# ============================================================================ + +function Invoke-SetupPhase { + Write-Phase "Setup" "Validating prerequisites and environment" + + # Step 1: Check git + Write-Step 1 "Checking git..." + $gitVersion = git --version 2>$null + if ($LASTEXITCODE -ne 0) { + Write-Failure "git is not installed or not in PATH" + return $false + } + Write-Success "git: $gitVersion" + + # Step 2: Check dotnet + Write-Step 2 "Checking .NET SDK..." + $dotnetVersion = dotnet --version 2>$null + if ($LASTEXITCODE -ne 0) { + Write-Failure ".NET SDK is not installed or not in PATH" + return $false + } + Write-Success ".NET SDK: $dotnetVersion" + + # Step 3: Check gh CLI + Write-Step 3 "Checking GitHub CLI..." + $ghStatus = gh auth status 2>&1 + if ($LASTEXITCODE -ne 0) { + Write-Failure "GitHub CLI is not authenticated. Run: gh auth login --web" + return $false + } + Write-Success "GitHub CLI: authenticated" + + # Step 4: Check we're in the right repo + Write-Step 4 "Checking repository..." + $remote = git remote get-url origin 2>$null + if ($remote -notmatch "azure-cosmos-dotnet-v3") { + Write-Failure "Not in the azure-cosmos-dotnet-v3 repository. Remote: $remote" + return $false + } + Write-Success "Repository: azure-cosmos-dotnet-v3" + + # Step 5: Check msdata/direct branch exists + Write-Step 5 "Checking msdata/direct branch..." + $branches = git branch -a 2>$null + if ($branches -notmatch "msdata/direct") { + Write-Info "Fetching remote branches..." + git fetch origin msdata/direct --quiet 2>$null + } + $branches = git branch -a 2>$null + if ($branches -notmatch "msdata/direct") { + Write-Failure "msdata/direct branch not found. Check remote." + return $false + } + Write-Success "msdata/direct branch exists" + + # Step 6: Check msdata repo path (if needed for Sync phase) + if ($MsdataRepoPath) { + Write-Step 6 "Checking msdata CosmosDB repo path..." + if (-not (Test-Path $MsdataRepoPath)) { + Write-Failure "msdata repo path not found: $MsdataRepoPath" + return $false + } + Write-Success "msdata repo path: $MsdataRepoPath" + } else { + Write-Step 6 "msdata repo path not provided (required for Sync phase)" + Write-Info "Use -MsdataRepoPath parameter when running Sync phase" + } + + Write-Success "All prerequisites validated!" + $script:PhaseResults["Setup"] = "passed" + return $true +} + +# ============================================================================ +# Phase: Branch — Create feature branch and merge master +# ============================================================================ + +function Invoke-BranchPhase { + Write-Phase "Branch" "Creating feature branch and merging master" + + $username = Get-GitHubUsername + $script:BranchName = "users/$username/update_msdata_direct_$script:DateStamp" + + # Step 1: Fetch latest + Write-Step 1 "Fetching latest branches from origin..." + git fetch origin master --quiet 2>$null + git fetch origin msdata/direct --quiet 2>$null + Write-Success "Fetched latest master and msdata/direct" + + # Step 2: Check if branch already exists + Write-Step 2 "Checking for existing feature branch..." + $existingBranch = git branch -a 2>$null | Select-String $script:BranchName + if ($existingBranch) { + Write-Info "Feature branch already exists: $($script:BranchName)" + Write-Info "Checking out existing branch..." + git checkout $script:BranchName 2>$null + Write-Success "Checked out existing branch" + $script:PhaseResults["Branch"] = "passed" + return $true + } + + # Step 3: Create feature branch from msdata/direct + Write-Step 3 "Creating feature branch: $($script:BranchName)" + git checkout origin/msdata/direct -b $script:BranchName 2>$null + if ($LASTEXITCODE -ne 0) { + Write-Failure "Failed to create feature branch" + return $false + } + Write-Success "Created branch: $($script:BranchName)" + + # Step 4: Merge master + Write-Step 4 "Merging master into feature branch..." + $mergeOutput = git merge origin/master --no-edit 2>&1 + if ($LASTEXITCODE -ne 0) { + Write-Info "Merge conflicts detected. Listing conflicted files:" + $conflicts = git diff --name-only --diff-filter=U 2>$null + if ($conflicts) { + foreach ($file in $conflicts) { + Write-Host " CONFLICT: $file" -ForegroundColor Red + } + } + Write-Host "" + Write-Info "Attempting auto-resolution (accept master changes)..." + + # Try to auto-resolve by accepting master (theirs) changes + foreach ($file in $conflicts) { + git checkout --theirs $file 2>$null + git add $file 2>$null + } + + # Check if all conflicts are resolved + $remainingConflicts = git diff --name-only --diff-filter=U 2>$null + if ($remainingConflicts) { + Write-Failure "Some conflicts could not be auto-resolved:" + foreach ($file in $remainingConflicts) { + Write-Host " MANUAL: $file" -ForegroundColor Red + } + Write-Info "Please resolve remaining conflicts manually, then run: git merge --continue" + return $false + } + + git merge --continue --no-edit 2>$null + Write-Success "All conflicts resolved and merge completed" + } else { + Write-Success "Merge completed without conflicts" + } + + $script:PhaseResults["Branch"] = "passed" + return $true +} + +# ============================================================================ +# Phase: Sync — Run msdata_sync.ps1 +# ============================================================================ + +# Known msdata source directories (must match $sourceDir in msdata_sync.ps1) +$script:MsdataSourceDirs = @( + "\Product\SDK\.net\Microsoft.Azure.Cosmos.Direct\src\", + "\Product\Microsoft.Azure.Documents\Common\SharedFiles\", + "\Product\Microsoft.Azure.Documents\SharedFiles\Routing\", + "\Product\Microsoft.Azure.Documents\SharedFiles\Rntbd2\", + "\Product\Microsoft.Azure.Documents\SharedFiles\Rntbd\", + "\Product\Microsoft.Azure.Documents\SharedFiles\Rntbd\rntbdtokens\", + "\Product\SDK\.net\Microsoft.Azure.Documents.Client\LegacyXPlatform\", + "\Product\Cosmos\Core\Core.Trace\", + "\Product\Cosmos\Core\Core\Utilities\", + "\Product\Microsoft.Azure.Documents\SharedFiles\", + "\Product\Microsoft.Azure.Documents\SharedFiles\Collections\", + "\Product\Microsoft.Azure.Documents\SharedFiles\Query\", + "\Product\Microsoft.Azure.Documents\SharedFiles\Management\" +) + +# Files excluded from sync (must match $exclueList in msdata_sync.ps1) +$script:SyncExcludeList = @( + "AssemblyKeys.cs", + "BaseTransportClient.cs", + "CpuReaderBase.cs", + "LinuxCpuReader.cs", + "MemoryLoad.cs", + "MemoryLoadHistory.cs", + "UnsupportedCpuReader.cs", + "WindowsCpuReader.cs", + "msdata_sync.ps1" +) + +# Files handled separately by msdata_sync.ps1 (special-case copies) +$script:SpecialCaseFiles = @( + "TransportClient.cs", + "RMResources.Designer.cs", + "RMResources.resx" +) + +function Invoke-PostSyncVerification { + param( + [Parameter(Mandatory)] + [string]$MsdataPath, + [Parameter(Mandatory)] + [string]$DirectDir + ) + + Write-Step 4 "Verifying sync completeness — scanning msdata source directories for missing files..." + + $missingFiles = @() + $copiedFiles = @() + $rntbd2Dir = Join-Path $DirectDir "rntbd2" + + foreach ($sourceDir in $script:MsdataSourceDirs) { + $fullSourceDir = Join-Path $MsdataPath $sourceDir + if (-not (Test-Path $fullSourceDir)) { + Write-Info "Source directory not found (skipping): $sourceDir" + continue + } + + $isRntbd2 = $sourceDir -match "\\Rntbd2\\" + $targetDir = if ($isRntbd2) { $rntbd2Dir } else { $DirectDir } + + $sourceFiles = Get-ChildItem $fullSourceDir -Filter "*.cs" -File -ErrorAction SilentlyContinue + foreach ($file in $sourceFiles) { + $fileName = $file.Name + + # Skip excluded and special-case files + if ($script:SyncExcludeList -contains $fileName) { continue } + if ($script:SpecialCaseFiles -contains $fileName) { continue } + + $targetPath = Join-Path $targetDir $fileName + if (-not (Test-Path $targetPath)) { + $missingFiles += @{ Name = $fileName; Source = $file.FullName; Target = $targetDir; SourceDir = $sourceDir } + } + } + } + + if ($missingFiles.Count -eq 0) { + Write-Success "Post-sync verification passed — no missing files detected" + return $true + } + + Write-Info "Found $($missingFiles.Count) file(s) in msdata that are missing from v3 direct/:" + foreach ($missing in $missingFiles) { + Write-Host " MISSING: $($missing.Name) (from $($missing.SourceDir))" -ForegroundColor Yellow + } + + Write-Info "Auto-copying missing files..." + foreach ($missing in $missingFiles) { + try { + if (-not (Test-Path $missing.Target)) { + New-Item -ItemType Directory -Path $missing.Target -Force | Out-Null + } + Copy-Item $missing.Source -Destination $missing.Target -Force + $copiedFiles += $missing.Name + Write-Success "Copied: $($missing.Name) -> $($missing.Target)" + } catch { + Write-Failure "Failed to copy $($missing.Name): $_" + } + } + + if ($copiedFiles.Count -gt 0) { + Write-Host "" + Write-Success "Auto-copied $($copiedFiles.Count) missing file(s):" + foreach ($f in $copiedFiles) { + Write-Host " + $f" -ForegroundColor Green + } + } + + return $true +} + +function Invoke-SyncPhase { + Write-Phase "Sync" "Syncing Microsoft.Azure.Cosmos.Direct files from msdata repo" + + if (-not $MsdataRepoPath) { + Write-Failure "msdata repo path is required for Sync phase. Use -MsdataRepoPath parameter." + return $false + } + + if (-not (Test-Path $MsdataRepoPath)) { + Write-Failure "msdata repo path not found: $MsdataRepoPath" + return $false + } + + $syncScript = Join-Path $script:RepoRoot "Microsoft.Azure.Cosmos" "src" "direct" "msdata_sync.ps1" + + # Step 1: Locate sync script + Write-Step 1 "Locating msdata_sync.ps1..." + if (-not (Test-Path $syncScript)) { + Write-Failure "msdata_sync.ps1 not found at: $syncScript" + Write-Info "This file should exist after merging msdata/direct. Check the merge step." + return $false + } + Write-Success "Found: $syncScript" + + # Step 2: Configure sync script with msdata repo path + Write-Step 2 "Configuring msdata_sync.ps1 with repo path..." + $scriptContent = Get-Content $syncScript -Raw + $originalContent = $scriptContent + + # Replace the $baseDir line with user-provided path + $normalizedPath = $MsdataRepoPath.TrimEnd('\', '/') + $scriptContent = $scriptContent -replace '\$baseDir\s*=\s*"[^"]*"', "`$baseDir = `"$normalizedPath`"" + + Set-Content $syncScript -Value $scriptContent + Write-Success "Configured `$baseDir = `"$normalizedPath`"" + + # Step 3: Run sync script + Write-Step 3 "Running msdata_sync.ps1..." + $directDir = Join-Path $script:RepoRoot "Microsoft.Azure.Cosmos" "src" "direct" + Push-Location $directDir + try { + $syncOutput = & $syncScript 2>&1 + $syncOutput | ForEach-Object { Write-Host " $_" } + + # Check for errors in output + $errors = $syncOutput | Where-Object { $_ -match "Write-Error|False$" } + if ($errors) { + Write-Failure "Some files failed to sync:" + foreach ($err in $errors) { + Write-Host " ERROR: $err" -ForegroundColor Red + } + Write-Info "Please copy missing files manually from msdata repo, then re-run the Sync phase." + } else { + Write-Success "All files synced successfully" + } + } finally { + Pop-Location + } + + # Step 4: Verify sync completeness and auto-copy missing files + $verifyResult = Invoke-PostSyncVerification -MsdataPath $normalizedPath -DirectDir $directDir + if (-not $verifyResult) { + Write-Failure "Post-sync verification failed" + # Still revert the script before returning + Set-Content $syncScript -Value $originalContent + return $false + } + + # Step 5: Revert script path change (don't commit the local path) + Write-Step 5 "Reverting msdata_sync.ps1 path change..." + Set-Content $syncScript -Value $originalContent + Write-Success "Reverted msdata_sync.ps1 to original state" + + $script:PhaseResults["Sync"] = "passed" + return $true +} + +# ============================================================================ +# Phase: Build — Validate the build +# ============================================================================ + +function Invoke-BuildPhase { + Write-Phase "Build" "Building solution to validate sync" + + if ($SkipBuild) { + Write-Info "Build phase skipped (-SkipBuild flag)" + $script:PhaseResults["Build"] = "skipped" + return $true + } + + $solutionPath = Join-Path $script:RepoRoot "Microsoft.Azure.Cosmos.sln" + + # Step 1: Clean build + Write-Step 1 "Running clean build..." + Push-Location $script:RepoRoot + try { + $buildOutput = dotnet build $solutionPath -c Release 2>&1 + $exitCode = $LASTEXITCODE + + # Show last few lines of build output + $buildOutput | Select-Object -Last 10 | ForEach-Object { Write-Host " $_" } + + if ($exitCode -ne 0) { + Write-Failure "Build failed with exit code $exitCode" + Write-Info "Review build errors above and fix before proceeding." + Write-Info "Common fixes:" + Write-Info " - Missing files: copy from msdata repo" + Write-Info " - Namespace conflicts: resolve using statements" + Write-Info " - API changes: update method signatures" + return $false + } + + Write-Success "Build succeeded!" + } finally { + Pop-Location + } + + $script:PhaseResults["Build"] = "passed" + return $true +} + +# ============================================================================ +# Phase: PR — Create pull request +# ============================================================================ + +function Invoke-PRPhase { + Write-Phase "PR" "Creating pull request to msdata/direct" + + $username = Get-GitHubUsername + if (-not $script:BranchName) { + $script:BranchName = "users/$username/update_msdata_direct_$script:DateStamp" + } + + # Step 1: Stage and commit + Write-Step 1 "Staging and committing changes..." + Push-Location $script:RepoRoot + try { + git add -A 2>$null + $status = git status --porcelain 2>$null + if ($status) { + git commit -m "[Internal] Direct package: Adds msdata/direct update from master" 2>$null + if ($LASTEXITCODE -ne 0) { + Write-Failure "Commit failed" + return $false + } + Write-Success "Changes committed" + } else { + Write-Info "No new changes to commit" + } + + # Step 2: Push branch + Write-Step 2 "Pushing branch to origin..." + git push origin $script:BranchName 2>$null + if ($LASTEXITCODE -ne 0) { + Write-Failure "Push failed" + return $false + } + Write-Success "Branch pushed: $($script:BranchName)" + + # Step 3: Create PR + Write-Step 3 "Creating draft pull request..." + $prBody = @" +# Pull Request Template + +## Description + +Syncs the ``msdata/direct`` branch with: +- Latest ``master`` branch (v3 SDK changes) +- Latest ``Microsoft.Azure.Cosmos.Direct`` files from msdata CosmosDB repo + +### Changes Include +- Merged latest ``master`` branch into ``msdata/direct`` +- Updated ``Microsoft.Azure.Cosmos.Direct`` files via ``msdata_sync.ps1`` +- Resolved merge conflicts (accepted master changes) +- Build validated: ``dotnet build`` passes + +## Type of change + +- [x] New feature (non-breaking change which adds functionality) + +## Validation + +- [x] Local build passes (``dotnet build Microsoft.Azure.Cosmos.sln -c Release``) +"@ + + $prUrl = gh pr create --draft ` + --base "msdata/direct" ` + --title "[Internal] Direct package: Adds msdata/direct update from master" ` + --body $prBody ` + --reviewer "kirillg,khdang,adityasa,sboshra,FabianMeiswinkel,leminh98,neildsh" 2>&1 + + if ($LASTEXITCODE -ne 0) { + Write-Failure "PR creation failed: $prUrl" + return $false + } + + Write-Success "Draft PR created: $prUrl" + Write-Info "Monitor CI: gh pr checks " + Write-Info "Mark ready when CI passes: gh pr ready " + + } finally { + Pop-Location + } + + $script:PhaseResults["PR"] = "passed" + return $true +} + +# ============================================================================ +# Main Execution +# ============================================================================ + +Write-Host "" +Write-Host "╔═══════════════════════════════════════════════════════════════╗" -ForegroundColor Magenta +Write-Host "║ msdata/direct Branch Sync Helper ║" -ForegroundColor Magenta +Write-Host "║ Azure Cosmos DB .NET SDK v3 ║" -ForegroundColor Magenta +Write-Host "╚═══════════════════════════════════════════════════════════════╝" -ForegroundColor Magenta +Write-Host "" + +$phases = switch ($Phase) { + "Setup" { @("Setup") } + "Branch" { @("Branch") } + "Sync" { @("Sync") } + "Build" { @("Build") } + "PR" { @("PR") } + "All" { @("Setup", "Branch", "Sync", "Build", "PR") } +} + +foreach ($p in $phases) { + $result = switch ($p) { + "Setup" { Invoke-SetupPhase } + "Branch" { Invoke-BranchPhase } + "Sync" { Invoke-SyncPhase } + "Build" { Invoke-BuildPhase } + "PR" { Invoke-PRPhase } + } + + if (-not $result) { + Write-Host "" + Write-Failure "Phase '$p' failed. Fix the issue and re-run with -Phase $p" + Write-Host "" + exit 1 + } +} + +# Summary +Write-Host "" +Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Green +Write-Host " Summary" -ForegroundColor Green +Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Green +foreach ($key in $script:PhaseResults.Keys) { + $status = $script:PhaseResults[$key] + $icon = if ($status -eq "passed") { "✅" } elseif ($status -eq "skipped") { "⏭️" } else { "❌" } + Write-Host " $icon $key`: $status" +} +Write-Host "" +Write-Success "msdata/direct sync complete!" +Write-Host ""