@azure/cosmos 4.5.0-alpha.20250717.1 → 4.5.0-alpha.20250718.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/browser/CosmosClient.d.ts.map +1 -1
  2. package/dist/browser/CosmosClient.js +3 -0
  3. package/dist/browser/CosmosClient.js.map +1 -1
  4. package/dist/browser/client/ChangeFeed/ChangeFeedForPartitionKey.d.ts.map +1 -1
  5. package/dist/browser/client/ChangeFeed/ChangeFeedForPartitionKey.js +4 -0
  6. package/dist/browser/client/ChangeFeed/ChangeFeedForPartitionKey.js.map +1 -1
  7. package/dist/browser/client/Item/Items.d.ts.map +1 -1
  8. package/dist/browser/client/Item/Items.js +9 -0
  9. package/dist/browser/client/Item/Items.js.map +1 -1
  10. package/dist/browser/encryption/EncryptionKeyStoreProvider.d.ts.map +1 -1
  11. package/dist/browser/encryption/EncryptionKeyStoreProvider.js +2 -1
  12. package/dist/browser/encryption/EncryptionKeyStoreProvider.js.map +1 -1
  13. package/dist/browser/globalPartitionEndpointManager.d.ts.map +1 -1
  14. package/dist/browser/globalPartitionEndpointManager.js +8 -9
  15. package/dist/browser/globalPartitionEndpointManager.js.map +1 -1
  16. package/dist/browser/request/request.d.ts.map +1 -1
  17. package/dist/browser/request/request.js +3 -3
  18. package/dist/browser/request/request.js.map +1 -1
  19. package/dist/browser/retry/timeoutFailoverRetryPolicy.d.ts.map +1 -1
  20. package/dist/browser/retry/timeoutFailoverRetryPolicy.js +3 -3
  21. package/dist/browser/retry/timeoutFailoverRetryPolicy.js.map +1 -1
  22. package/dist/browser/utils/time.d.ts +8 -0
  23. package/dist/browser/utils/time.d.ts.map +1 -1
  24. package/dist/browser/utils/time.js +19 -0
  25. package/dist/browser/utils/time.js.map +1 -1
  26. package/dist/commonjs/CosmosClient.d.ts.map +1 -1
  27. package/dist/commonjs/CosmosClient.js +3 -0
  28. package/dist/commonjs/CosmosClient.js.map +1 -1
  29. package/dist/commonjs/client/ChangeFeed/ChangeFeedForPartitionKey.d.ts.map +1 -1
  30. package/dist/commonjs/client/ChangeFeed/ChangeFeedForPartitionKey.js +4 -0
  31. package/dist/commonjs/client/ChangeFeed/ChangeFeedForPartitionKey.js.map +1 -1
  32. package/dist/commonjs/client/Item/Items.d.ts.map +1 -1
  33. package/dist/commonjs/client/Item/Items.js +9 -0
  34. package/dist/commonjs/client/Item/Items.js.map +1 -1
  35. package/dist/commonjs/encryption/Cache/ProtectedDataEncryptionKeyCache.d.ts.map +1 -1
  36. package/dist/commonjs/encryption/Cache/ProtectedDataEncryptionKeyCache.js +2 -1
  37. package/dist/commonjs/encryption/Cache/ProtectedDataEncryptionKeyCache.js.map +1 -1
  38. package/dist/commonjs/encryption/EncryptionKeyStoreProvider.d.ts.map +1 -1
  39. package/dist/commonjs/encryption/EncryptionKeyStoreProvider.js +2 -1
  40. package/dist/commonjs/encryption/EncryptionKeyStoreProvider.js.map +1 -1
  41. package/dist/commonjs/globalPartitionEndpointManager.d.ts.map +1 -1
  42. package/dist/commonjs/globalPartitionEndpointManager.js +8 -9
  43. package/dist/commonjs/globalPartitionEndpointManager.js.map +1 -1
  44. package/dist/commonjs/request/request.d.ts.map +1 -1
  45. package/dist/commonjs/request/request.js +3 -3
  46. package/dist/commonjs/request/request.js.map +1 -1
  47. package/dist/commonjs/retry/timeoutFailoverRetryPolicy.d.ts.map +1 -1
  48. package/dist/commonjs/retry/timeoutFailoverRetryPolicy.js +3 -3
  49. package/dist/commonjs/retry/timeoutFailoverRetryPolicy.js.map +1 -1
  50. package/dist/commonjs/tsdoc-metadata.json +11 -11
  51. package/dist/commonjs/utils/time.d.ts +8 -0
  52. package/dist/commonjs/utils/time.d.ts.map +1 -1
  53. package/dist/commonjs/utils/time.js +20 -0
  54. package/dist/commonjs/utils/time.js.map +1 -1
  55. package/dist/esm/CosmosClient.d.ts.map +1 -1
  56. package/dist/esm/CosmosClient.js +3 -0
  57. package/dist/esm/CosmosClient.js.map +1 -1
  58. package/dist/esm/client/ChangeFeed/ChangeFeedForPartitionKey.d.ts.map +1 -1
  59. package/dist/esm/client/ChangeFeed/ChangeFeedForPartitionKey.js +4 -0
  60. package/dist/esm/client/ChangeFeed/ChangeFeedForPartitionKey.js.map +1 -1
  61. package/dist/esm/client/Item/Items.d.ts.map +1 -1
  62. package/dist/esm/client/Item/Items.js +9 -0
  63. package/dist/esm/client/Item/Items.js.map +1 -1
  64. package/dist/esm/encryption/Cache/ProtectedDataEncryptionKeyCache.d.ts.map +1 -1
  65. package/dist/esm/encryption/Cache/ProtectedDataEncryptionKeyCache.js +2 -1
  66. package/dist/esm/encryption/Cache/ProtectedDataEncryptionKeyCache.js.map +1 -1
  67. package/dist/esm/encryption/EncryptionKeyStoreProvider.d.ts.map +1 -1
  68. package/dist/esm/encryption/EncryptionKeyStoreProvider.js +2 -1
  69. package/dist/esm/encryption/EncryptionKeyStoreProvider.js.map +1 -1
  70. package/dist/esm/globalPartitionEndpointManager.d.ts.map +1 -1
  71. package/dist/esm/globalPartitionEndpointManager.js +8 -9
  72. package/dist/esm/globalPartitionEndpointManager.js.map +1 -1
  73. package/dist/esm/request/request.d.ts.map +1 -1
  74. package/dist/esm/request/request.js +3 -3
  75. package/dist/esm/request/request.js.map +1 -1
  76. package/dist/esm/retry/timeoutFailoverRetryPolicy.d.ts.map +1 -1
  77. package/dist/esm/retry/timeoutFailoverRetryPolicy.js +3 -3
  78. package/dist/esm/retry/timeoutFailoverRetryPolicy.js.map +1 -1
  79. package/dist/esm/utils/time.d.ts +8 -0
  80. package/dist/esm/utils/time.d.ts.map +1 -1
  81. package/dist/esm/utils/time.js +19 -0
  82. package/dist/esm/utils/time.js.map +1 -1
  83. package/dist/react-native/CosmosClient.d.ts.map +1 -1
  84. package/dist/react-native/CosmosClient.js +3 -0
  85. package/dist/react-native/CosmosClient.js.map +1 -1
  86. package/dist/react-native/client/ChangeFeed/ChangeFeedForPartitionKey.d.ts.map +1 -1
  87. package/dist/react-native/client/ChangeFeed/ChangeFeedForPartitionKey.js +4 -0
  88. package/dist/react-native/client/ChangeFeed/ChangeFeedForPartitionKey.js.map +1 -1
  89. package/dist/react-native/client/Item/Items.d.ts.map +1 -1
  90. package/dist/react-native/client/Item/Items.js +9 -0
  91. package/dist/react-native/client/Item/Items.js.map +1 -1
  92. package/dist/react-native/encryption/Cache/ProtectedDataEncryptionKeyCache.d.ts.map +1 -1
  93. package/dist/react-native/encryption/Cache/ProtectedDataEncryptionKeyCache.js +2 -1
  94. package/dist/react-native/encryption/Cache/ProtectedDataEncryptionKeyCache.js.map +1 -1
  95. package/dist/react-native/encryption/EncryptionKeyStoreProvider.d.ts.map +1 -1
  96. package/dist/react-native/encryption/EncryptionKeyStoreProvider.js +2 -1
  97. package/dist/react-native/encryption/EncryptionKeyStoreProvider.js.map +1 -1
  98. package/dist/react-native/globalPartitionEndpointManager.d.ts.map +1 -1
  99. package/dist/react-native/globalPartitionEndpointManager.js +8 -9
  100. package/dist/react-native/globalPartitionEndpointManager.js.map +1 -1
  101. package/dist/react-native/request/request.d.ts.map +1 -1
  102. package/dist/react-native/request/request.js +3 -3
  103. package/dist/react-native/request/request.js.map +1 -1
  104. package/dist/react-native/retry/timeoutFailoverRetryPolicy.d.ts.map +1 -1
  105. package/dist/react-native/retry/timeoutFailoverRetryPolicy.js +3 -3
  106. package/dist/react-native/retry/timeoutFailoverRetryPolicy.js.map +1 -1
  107. package/dist/react-native/utils/time.d.ts +8 -0
  108. package/dist/react-native/utils/time.d.ts.map +1 -1
  109. package/dist/react-native/utils/time.js +19 -0
  110. package/dist/react-native/utils/time.js.map +1 -1
  111. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"Items.js","sourceRoot":"","sources":["../../../../src/client/Item/Items.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAGjE,OAAO,EACL,SAAS,EACT,UAAU,EACV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C,wBAAwB,CACrC,SAAS,CAAC,UAAU,CAAC,2BAA2B,EAChD,KAAK,CACN,CAAC;gBACJ,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,MAAM,eAAe,GAAG,IAAI,aAAa,CACvC,iEAAiE,KAAK,CAAC,OAAO,EAAE,CACjF,CAAC;oBACF,eAAe,CAAC,IAAI,GAAG,WAAW,CAAC,kBAAkB,CAAC;oBACtD,MAAM,eAAe,CAAC;gBACxB,CAAC;YACH,CAAC;YACD,OAAO,QAAQ,CAAC;QAClB,CAAC,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;IACzB,CAAC;IAEO,KAAK,CAAC,yBAAyB,CACrC,UAA4B;QAE5B,IAAI,6BAA6B,GAAG,CAAC,CAAC;QACtC,MAAM,mBAAmB,GAAqB,EAAE,CAAC;QACjD,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;YACnC,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE,YAAY,EAAE,GAC3E,MAAM,qBAAqB,CACzB,IAAI,CAAC,SAAS,CAAC,mBAAmB,EAClC,SAAS,EACT,6BAA6B,CAC9B,CAAC;YACJ,6BAA6B,GAAG,YAAY,CAAC;YAC7C,mBAAmB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACxC,CAAC;QACD,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,6BAA6B,EAAE,CAAC;IAC5E,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { ChangeFeedIterator } from \"../../ChangeFeedIterator.js\";\nimport type { ChangeFeedOptions } from \"../../ChangeFeedOptions.js\";\nimport type { ClientContext } from \"../../ClientContext.js\";\nimport {\n Constants,\n copyObject,\n getIdFromLink,\n getPathFromLink,\n isItemResourceValid,\n ResourceType,\n StatusCodes,\n SubStatusCodes,\n} from \"../../common/index.js\";\nimport { extractPartitionKeys, setPartitionKeyIfUndefined } from \"../../extractPartitionKey.js\";\nimport type { FetchFunctionCallback, SqlQuerySpec } from \"../../queryExecutionContext/index.js\";\nimport { QueryIterator } from \"../../queryIterator.js\";\nimport type { FeedOptions, RequestOptions, Response } from \"../../request/index.js\";\nimport type { Container, PartitionKeyRange } from \"../Container/index.js\";\nimport { Item } from \"./Item.js\";\nimport type { ItemDefinition } from \"./ItemDefinition.js\";\nimport { ItemResponse } from \"./ItemResponse.js\";\nimport type {\n Batch,\n OperationResponse,\n OperationInput,\n BulkOptions,\n BulkOperationResponse,\n Operation,\n BulkOperationResult,\n} from \"../../utils/batch.js\";\nimport {\n isKeyInRange,\n prepareOperations,\n decorateBatchOperation,\n splitBatchBasedOnBodySize,\n encryptOperationInput,\n} from \"../../utils/batch.js\";\nimport { assertNotUndefined, isPrimitivePartitionKeyValue } from \"../../utils/typeChecks.js\";\nimport { hashPartitionKey } from \"../../utils/hashing/hash.js\";\nimport { PartitionKeyRangeCache, QueryRange } from \"../../routing/index.js\";\nimport type {\n PartitionKey,\n PartitionKeyDefinition,\n PartitionKeyInternal,\n} from \"../../documents/index.js\";\nimport { convertToInternalPartitionKey } from \"../../documents/index.js\";\nimport type {\n ChangeFeedPullModelIterator,\n ChangeFeedIteratorOptions,\n} from \"../../client/ChangeFeed/index.js\";\nimport { validateChangeFeedIteratorOptions } from \"../../client/ChangeFeed/changeFeedUtils.js\";\nimport type { DiagnosticNodeInternal } from \"../../diagnostics/DiagnosticNodeInternal.js\";\nimport { DiagnosticNodeType } from \"../../diagnostics/DiagnosticNodeInternal.js\";\nimport {\n getEmptyCosmosDiagnostics,\n withDiagnostics,\n addDiagnosticChild,\n} from \"../../utils/diagnostics.js\";\nimport { randomUUID } from \"@azure/core-util\";\nimport { computePartitionKeyRangeId, readPartitionKeyDefinition } from \"../ClientUtils.js\";\nimport { ChangeFeedIteratorBuilder } from \"../ChangeFeed/ChangeFeedIteratorBuilder.js\";\nimport type { EncryptionQueryBuilder } from \"../../encryption/index.js\";\nimport type { EncryptionSqlParameter } from \"../../encryption/EncryptionQueryBuilder.js\";\nimport type { Resource } from \"../Resource.js\";\nimport { TypeMarker } from \"../../encryption/enums/TypeMarker.js\";\nimport { EncryptionItemQueryIterator } from \"../../encryption/EncryptionItemQueryIterator.js\";\nimport { ErrorResponse } from \"../../request/index.js\";\nimport { BulkHelper } from \"../../bulk/BulkHelper.js\";\n\n/**\n * @hidden\n */\nfunction isChangeFeedOptions(options: unknown): options is ChangeFeedOptions {\n return options && !(isPrimitivePartitionKeyValue(options) || Array.isArray(options));\n}\n\n/**\n * Operations for creating new items, and reading/querying all items\n *\n * @see {@link Item} for reading, replacing, or deleting an existing container; use `.item(id)`.\n */\nexport class Items {\n private partitionKeyRangeCache: PartitionKeyRangeCache;\n /**\n * Create an instance of {@link Items} linked to the parent {@link Container}.\n * @param container - The parent container.\n * @hidden\n */\n constructor(\n public readonly container: Container,\n private readonly clientContext: ClientContext,\n ) {\n this.partitionKeyRangeCache = this.clientContext.partitionKeyRangeCache;\n }\n\n /**\n * Queries all items.\n * @param query - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Read all items to array.\n * ```ts snippet:ItemsQueryItems\n * import { CosmosClient, SqlQuerySpec } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const querySpec: SqlQuerySpec = {\n * query: `SELECT * FROM Families f WHERE f.lastName = @lastName`,\n * parameters: [{ name: \"@lastName\", value: \"Hendricks\" }],\n * };\n * const { resources: items } = await container.items.query(querySpec).fetchAll();\n * ```\n */\n\n //\n public query(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<any>;\n /**\n * Queries all items.\n * @param query - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Read all items to array.\n * ```ts snippet:ItemsQueryItems\n * import { CosmosClient, SqlQuerySpec } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const querySpec: SqlQuerySpec = {\n * query: `SELECT * FROM Families f WHERE f.lastName = @lastName`,\n * parameters: [{ name: \"@lastName\", value: \"Hendricks\" }],\n * };\n * const { resources: items } = await container.items.query(querySpec).fetchAll();\n * ```\n */\n public query<T>(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;\n public query<T>(query: string | SqlQuerySpec, options: FeedOptions = {}): QueryIterator<T> {\n const path = getPathFromLink(this.container.url, ResourceType.item);\n const id = getIdFromLink(this.container.url);\n\n const fetchFunction: FetchFunctionCallback = async (\n diagnosticNode: DiagnosticNodeInternal,\n innerOptions: FeedOptions,\n correlatedActivityId: string,\n ) => {\n let internalPartitionKey: PartitionKeyInternal | undefined;\n if (options.partitionKey) {\n internalPartitionKey = convertToInternalPartitionKey(options.partitionKey);\n }\n const isPartitionLevelFailOverEnabled = this.clientContext.isPartitionLevelFailOverEnabled();\n const partitionKeyRangeId = await computePartitionKeyRangeId(\n diagnosticNode,\n internalPartitionKey,\n this.partitionKeyRangeCache,\n isPartitionLevelFailOverEnabled,\n this.container,\n );\n\n const response = await this.clientContext.queryFeed({\n path,\n resourceType: ResourceType.item,\n resourceId: id,\n resultFn: (result) => (result ? result.Documents : []),\n query,\n options: innerOptions,\n partitionKey: options.partitionKey,\n diagnosticNode,\n correlatedActivityId: correlatedActivityId,\n partitionKeyRangeId,\n });\n return response;\n };\n let iterator: QueryIterator<T>;\n if (this.clientContext.enableEncryption) {\n iterator = new EncryptionItemQueryIterator(\n this.clientContext,\n query,\n options,\n fetchFunction,\n this.container,\n );\n } else {\n iterator = new QueryIterator<T>(\n this.clientContext,\n query,\n options,\n fetchFunction,\n this.container.url,\n ResourceType.item,\n );\n }\n return iterator;\n }\n /**\n * Queries all items in an encrypted container.\n * @param queryBuilder - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to build a query on encrypted properties.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Read all items to array.\n * ```ts snippet:ItemsQueryEncryptedItems\n * import { CosmosClient, EncryptionQueryBuilder } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const queryBuilder = new EncryptionQueryBuilder(\n * `SELECT firstname FROM Families f WHERE f.lastName = @lastName`,\n * );\n * queryBuilder.addParameter(\"@lastName\", \"Hendricks\", \"/lastname\");\n * const queryIterator = await container.items.getEncryptionQueryIterator(queryBuilder);\n * const { resources: items } = await queryIterator.fetchAll();\n * ```\n */\n public async getEncryptionQueryIterator(\n queryBuilder: EncryptionQueryBuilder,\n options: FeedOptions = {},\n ): Promise<QueryIterator<ItemDefinition>> {\n const encryptionSqlQuerySpec = queryBuilder.toEncryptionSqlQuerySpec();\n const sqlQuerySpec = await this.buildSqlQuerySpec(encryptionSqlQuerySpec);\n const iterator = this.query<ItemDefinition>(sqlQuerySpec, options);\n return iterator;\n }\n\n private async buildSqlQuerySpec(encryptionSqlQuerySpec: SqlQuerySpec): Promise<SqlQuerySpec> {\n let encryptionParameters = encryptionSqlQuerySpec.parameters as EncryptionSqlParameter[];\n const sqlQuerySpec: SqlQuerySpec = {\n query: encryptionSqlQuerySpec.query,\n parameters: [],\n };\n // returns copy to avoid encryption of original parameters passed\n encryptionParameters = copyObject(encryptionParameters);\n for (const parameter of encryptionParameters) {\n let value: any;\n if (parameter.type !== undefined || parameter.type !== TypeMarker.Null) {\n value = await this.container.encryptionProcessor.encryptQueryParameter(\n parameter.path,\n parameter.value,\n parameter.path === \"/id\",\n parameter.type,\n );\n }\n sqlQuerySpec.parameters.push({ name: parameter.name, value: value });\n }\n return sqlQuerySpec;\n }\n\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n *\n * @deprecated Use `getChangeFeedIterator` instead.\n *\n * @example Read from the beginning of the change feed.\n * ```ts snippet:ignore\n * const iterator = items.readChangeFeed({ startFromBeginning: true });\n * const firstPage = await iterator.fetchNext();\n * const firstPageResults = firstPage.result\n * const secondPage = await iterator.fetchNext();\n * ```\n */\n public readChangeFeed(\n partitionKey: PartitionKey,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<any>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n *\n */\n public readChangeFeed(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<any>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n */\n public readChangeFeed<T>(\n partitionKey: PartitionKey,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<T>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n */\n public readChangeFeed<T>(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<T>;\n public readChangeFeed<T>(\n partitionKeyOrChangeFeedOptions?: PartitionKey | ChangeFeedOptions,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<T> {\n if (isChangeFeedOptions(partitionKeyOrChangeFeedOptions)) {\n return this.changeFeed(partitionKeyOrChangeFeedOptions);\n } else {\n return this.changeFeed(partitionKeyOrChangeFeedOptions, changeFeedOptions);\n }\n }\n\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n * @example Read from the beginning of the change feed.\n * ```ts snippet:ignore\n * const iterator = items.readChangeFeed({ startFromBeginning: true });\n * const firstPage = await iterator.fetchNext();\n * const firstPageResults = firstPage.result\n * const secondPage = await iterator.fetchNext();\n * ```\n */\n public changeFeed(\n partitionKey: PartitionKey,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<any>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n */\n public changeFeed(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<any>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n */\n public changeFeed<T>(\n partitionKey: PartitionKey,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<T>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n */\n public changeFeed<T>(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<T>;\n public changeFeed<T>(\n partitionKeyOrChangeFeedOptions?: PartitionKey | ChangeFeedOptions,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<T> {\n let partitionKey: PartitionKey;\n if (!changeFeedOptions && isChangeFeedOptions(partitionKeyOrChangeFeedOptions)) {\n partitionKey = undefined;\n changeFeedOptions = partitionKeyOrChangeFeedOptions;\n } else if (\n partitionKeyOrChangeFeedOptions !== undefined &&\n !isChangeFeedOptions(partitionKeyOrChangeFeedOptions)\n ) {\n partitionKey = partitionKeyOrChangeFeedOptions;\n }\n\n if (!changeFeedOptions) {\n changeFeedOptions = {};\n }\n\n const path = getPathFromLink(this.container.url, ResourceType.item);\n const id = getIdFromLink(this.container.url);\n return new ChangeFeedIterator<T>(this.clientContext, id, path, partitionKey, changeFeedOptions);\n }\n\n /**\n * Returns an iterator to iterate over pages of changes. The iterator returned can be used to fetch changes for a single partition key, feed range or an entire container.\n *\n * @example\n * ```ts snippet:ReadmeSampleChangeFeedPullModelIteratorPartitionKey\n * import {\n * CosmosClient,\n * PartitionKeyDefinitionVersion,\n * PartitionKeyKind,\n * ChangeFeedStartFrom,\n * } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const containerDefinition = {\n * id: \"Test Database\",\n * partitionKey: {\n * paths: [\"/name\", \"/address/zip\"],\n * version: PartitionKeyDefinitionVersion.V2,\n * kind: PartitionKeyKind.MultiHash,\n * },\n * };\n * const { container } = await database.containers.createIfNotExists(containerDefinition);\n *\n * const partitionKey = \"some-partition-Key-value\";\n * const options = {\n * changeFeedStartFrom: ChangeFeedStartFrom.Beginning(partitionKey),\n * };\n *\n * const iterator = container.items.getChangeFeedIterator(options);\n *\n * while (iterator.hasMoreResults) {\n * const response = await iterator.readNext();\n * // process this response\n * }\n * ```\n */\n public getChangeFeedIterator<T>(\n changeFeedIteratorOptions?: ChangeFeedIteratorOptions,\n ): ChangeFeedPullModelIterator<T> {\n const cfOptions = changeFeedIteratorOptions !== undefined ? changeFeedIteratorOptions : {};\n validateChangeFeedIteratorOptions(cfOptions);\n const iterator = new ChangeFeedIteratorBuilder<T>(\n cfOptions,\n this.clientContext,\n this.container,\n this.partitionKeyRangeCache,\n );\n return iterator;\n }\n\n /**\n * Read all items.\n *\n * There is no set schema for JSON items. They may contain any number of custom properties.\n *\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Read all items to array.\n * ```ts snippet:ItemsReadAll\n * import { CosmosClient } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const { resources: containerList } = await container.items.readAll().fetchAll();\n * ```\n */\n public readAll(options?: FeedOptions): QueryIterator<ItemDefinition>;\n /**\n * Read all items.\n *\n * Any provided type, T, is not necessarily enforced by the SDK.\n * You may get more or less properties and it's up to your logic to enforce it.\n *\n * There is no set schema for JSON items. They may contain any number of custom properties.\n *\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Read all items to array.\n * ```ts snippet:ItemsReadAll\n * import { CosmosClient } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const { resources: containerList } = await container.items.readAll().fetchAll();\n * ```\n */\n public readAll<T extends ItemDefinition>(options?: FeedOptions): QueryIterator<T>;\n public readAll<T extends ItemDefinition>(options?: FeedOptions): QueryIterator<T> {\n return this.query<T>(\"SELECT * from c\", options);\n }\n\n /**\n * Create an item.\n *\n * Any provided type, T, is not necessarily enforced by the SDK.\n * You may get more or less properties and it's up to your logic to enforce it.\n *\n * There is no set schema for JSON items. They may contain any number of custom properties.\n *\n * @param body - Represents the body of the item. Can contain any number of user defined properties.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Create an item.\n * ```ts snippet:ContainerItems\n * import { CosmosClient } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const { resource: createdItem } = await container.items.create({\n * id: \"<item id>\",\n * properties: {},\n * });\n * ```\n */\n public async create<T extends ItemDefinition = any>(\n body: T,\n options: RequestOptions = {},\n ): Promise<ItemResponse<T>> {\n // Generate random document id if the id is missing in the payload and\n // options.disableAutomaticIdGeneration != true\n\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n if ((body.id === undefined || body.id === \"\") && !options.disableAutomaticIdGeneration) {\n body.id = randomUUID();\n }\n const partitionKeyDefinition = await readPartitionKeyDefinition(\n diagnosticNode,\n this.container,\n );\n let partitionKey = extractPartitionKeys(body, partitionKeyDefinition);\n let response: Response<T & Resource>;\n try {\n if (this.clientContext.enableEncryption) {\n await this.container.checkAndInitializeEncryption();\n options.containerRid = this.container._rid;\n // returns copy to avoid encryption of original body passed\n body = copyObject(body);\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n );\n const { body: encryptedBody, propertiesEncryptedCount } =\n await this.container.encryptionProcessor.encrypt(body);\n body = encryptedBody;\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n propertiesEncryptedCount,\n );\n\n partitionKey = extractPartitionKeys(body, partitionKeyDefinition);\n }\n const err = {};\n if (!isItemResourceValid(body, err)) {\n throw err;\n }\n const path = getPathFromLink(this.container.url, ResourceType.item);\n const id = getIdFromLink(this.container.url);\n\n const isPartitionLevelFailOverEnabled =\n this.clientContext.isPartitionLevelFailOverEnabled();\n const partitionKeyRangeId = await computePartitionKeyRangeId(\n diagnosticNode,\n partitionKey,\n this.partitionKeyRangeCache,\n isPartitionLevelFailOverEnabled,\n this.container,\n partitionKeyDefinition,\n );\n\n response = await this.clientContext.create<T>({\n body,\n path,\n resourceType: ResourceType.item,\n resourceId: id,\n diagnosticNode,\n options,\n partitionKey,\n partitionKeyRangeId,\n });\n } catch (error: any) {\n if (this.clientContext.enableEncryption) {\n // Todo: internally retry post policy refresh\n await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(error);\n }\n throw error;\n }\n\n if (this.clientContext.enableEncryption) {\n // try block for decrypting response. This is done so that we can throw special error message in case of decryption failure\n try {\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n );\n const { body: decryptedResult, propertiesDecryptedCount } =\n await this.container.encryptionProcessor.decrypt(response.result);\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n propertiesDecryptedCount,\n );\n response.result = decryptedResult;\n partitionKey = extractPartitionKeys(response.result, partitionKeyDefinition);\n } catch (error) {\n const decryptionError = new ErrorResponse(\n `Item creation was successful but response decryption failed: + ${error.message}`,\n );\n decryptionError.code = StatusCodes.ServiceUnavailable;\n throw decryptionError;\n }\n }\n const ref = new Item(\n this.container,\n (response.result as any).id,\n this.clientContext,\n partitionKey,\n );\n return new ItemResponse(\n response.result,\n response.headers,\n response.code,\n response.substatus,\n ref,\n getEmptyCosmosDiagnostics(),\n );\n }, this.clientContext);\n }\n\n /**\n * Upsert an item.\n *\n * There is no set schema for JSON items. They may contain any number of custom properties.\n *\n * @param body - Represents the body of the item. Can contain any number of user defined properties.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n */\n public async upsert(\n body: unknown,\n options?: RequestOptions,\n ): Promise<ItemResponse<ItemDefinition>>;\n /**\n * Upsert an item.\n *\n * Any provided type, T, is not necessarily enforced by the SDK.\n * You may get more or less properties and it's up to your logic to enforce it.\n *\n * There is no set schema for JSON items. They may contain any number of custom properties.\n *\n * @param body - Represents the body of the item. Can contain any number of user defined properties.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Upsert an item.\n * ```ts snippet:ItemsUpsert\n * import { CosmosClient } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const { resource: createdItem1 } = await container.items.create({\n * id: \"<item id 1>\",\n * properties: {},\n * });\n *\n * const { resource: upsertItem1 } = await container.items.upsert({\n * id: \"<item id 1>\",\n * updated_properties: {},\n * });\n *\n * const { resource: upsertItem2 } = await container.items.upsert({\n * id: \"<item id 2>\",\n * properties: {},\n * });\n * ```\n */\n public async upsert<T extends ItemDefinition>(\n body: T,\n options?: RequestOptions,\n ): Promise<ItemResponse<T>>;\n public async upsert<T extends ItemDefinition>(\n body: T,\n options: RequestOptions = {},\n ): Promise<ItemResponse<T>> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n // Generate random document id if the id is missing in the payload and\n // options.disableAutomaticIdGeneration != true\n if ((body.id === undefined || body.id === \"\") && !options.disableAutomaticIdGeneration) {\n body.id = randomUUID();\n }\n\n const partitionKeyDefinition = await readPartitionKeyDefinition(\n diagnosticNode,\n this.container,\n );\n let partitionKey = extractPartitionKeys(body, partitionKeyDefinition);\n let response: Response<T & Resource>;\n try {\n if (this.clientContext.enableEncryption) {\n // returns copy to avoid encryption of original body passed\n body = copyObject(body);\n options = options || {};\n await this.container.checkAndInitializeEncryption();\n options.containerRid = this.container._rid;\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n );\n const { body: encryptedBody, propertiesEncryptedCount } =\n await this.container.encryptionProcessor.encrypt(body);\n body = encryptedBody;\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n propertiesEncryptedCount,\n );\n partitionKey = extractPartitionKeys(body, partitionKeyDefinition);\n }\n\n const err = {};\n if (!isItemResourceValid(body, err)) {\n throw err;\n }\n\n const path = getPathFromLink(this.container.url, ResourceType.item);\n const id = getIdFromLink(this.container.url);\n\n const isPartitionLevelFailOverEnabled =\n this.clientContext.isPartitionLevelFailOverEnabled();\n const partitionKeyRangeId = await computePartitionKeyRangeId(\n diagnosticNode,\n partitionKey,\n this.partitionKeyRangeCache,\n isPartitionLevelFailOverEnabled,\n this.container,\n partitionKeyDefinition,\n );\n\n response = await this.clientContext.upsert<T>({\n body,\n path,\n resourceType: ResourceType.item,\n resourceId: id,\n options,\n partitionKey,\n diagnosticNode,\n partitionKeyRangeId,\n });\n } catch (error: any) {\n if (this.clientContext.enableEncryption) {\n await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(error);\n }\n throw error;\n }\n if (this.clientContext.enableEncryption) {\n try {\n // try block for decrypting response. This is done so that we can throw special error message in case of decryption failure\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n );\n const { body: decryptedResult, propertiesDecryptedCount } =\n await this.container.encryptionProcessor.decrypt(response.result);\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n propertiesDecryptedCount,\n );\n response.result = decryptedResult;\n partitionKey = extractPartitionKeys(response.result, partitionKeyDefinition);\n } catch (error) {\n const decryptionError = new ErrorResponse(\n `Item upsert was successful but response decryption failed: + ${error.message}`,\n );\n decryptionError.code = StatusCodes.ServiceUnavailable;\n throw decryptionError;\n }\n }\n\n const ref = new Item(\n this.container,\n (response.result as any).id,\n this.clientContext,\n partitionKey,\n );\n return new ItemResponse(\n response.result,\n response.headers,\n response.code,\n response.substatus,\n ref,\n getEmptyCosmosDiagnostics(),\n );\n }, this.clientContext);\n }\n\n /**\n * Execute bulk operations on items.\n * @param operations - List of operations\n * @param options - used for modifying the request\n * @returns list of operation results corresponding to the operations\n *\n * @example\n * ```ts snippet:ItemsExecuteBulkOperations\n * import { CosmosClient, OperationInput } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const operations: OperationInput[] = [\n * {\n * operationType: \"Create\",\n * resourceBody: { id: \"doc1\", name: \"sample\", key: \"A\" },\n * },\n * {\n * operationType: \"Upsert\",\n * partitionKey: \"A\",\n * resourceBody: { id: \"doc2\", name: \"other\", key: \"A\" },\n * },\n * ];\n *\n * await container.items.executeBulkOperations(operations);\n * ```\n */\n public async executeBulkOperations(\n operations: OperationInput[],\n options: RequestOptions = {},\n ): Promise<BulkOperationResult[]> {\n const bulkHelper = new BulkHelper(\n this.container,\n this.clientContext,\n this.partitionKeyRangeCache,\n options,\n );\n return bulkHelper.execute(operations);\n }\n\n /**\n * Execute bulk operations on items.\n * @deprecated Use `executeBulkOperations` instead.\n *\n * Bulk takes an array of Operations which are typed based on what the operation does.\n * The choices are: Create, Upsert, Read, Replace, and Delete\n *\n * Usage example:\n * ```ts snippet:ItemsBulk\n * import { CosmosClient, OperationInput } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * // partitionKey is optional at the top level if present in the resourceBody\n * const operations: OperationInput[] = [\n * {\n * operationType: \"Create\",\n * resourceBody: { id: \"doc1\", name: \"sample\", key: \"A\" },\n * },\n * {\n * operationType: \"Upsert\",\n * partitionKey: \"A\",\n * resourceBody: { id: \"doc2\", name: \"other\", key: \"A\" },\n * },\n * ];\n *\n * await container.items.bulk(operations);\n * ```\n *\n * @param operations - List of operations. Limit 100\n * @param bulkOptions - Optional options object to modify bulk behavior. Pass \\{ continueOnError: false \\} to stop executing operations when one fails. (Defaults to true)\n * @param options - Used for modifying the request.\n */\n public async bulk(\n operations: OperationInput[],\n bulkOptions?: BulkOptions,\n options?: RequestOptions,\n ): Promise<BulkOperationResponse> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n const partitionKeyRanges = (\n await this.partitionKeyRangeCache.onCollectionRoutingMap(this.container.url, diagnosticNode)\n ).getOrderedParitionKeyRanges();\n\n const partitionKeyDefinition = await readPartitionKeyDefinition(\n diagnosticNode,\n this.container,\n );\n\n if (this.clientContext.enableEncryption) {\n // returns copy to avoid encryption of original operations body passed\n operations = copyObject(operations);\n options = options || {};\n await this.container.checkAndInitializeEncryption();\n options.containerRid = this.container._rid;\n diagnosticNode.beginEncryptionDiagnostics(Constants.Encryption.DiagnosticsEncryptOperation);\n const { operations: encryptedOperations, totalPropertiesEncryptedCount } =\n await this.bulkBatchEncryptionHelper(operations);\n operations = encryptedOperations;\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n totalPropertiesEncryptedCount,\n );\n }\n\n const batches: Batch[] = partitionKeyRanges.map((keyRange: PartitionKeyRange) => {\n return {\n min: keyRange.minInclusive,\n max: keyRange.maxExclusive,\n rangeId: keyRange.id,\n indexes: [] as number[],\n operations: [] as Operation[],\n };\n });\n\n this.groupOperationsBasedOnPartitionKey(operations, partitionKeyDefinition, options, batches);\n\n const path = getPathFromLink(this.container.url, ResourceType.item);\n\n const orderedResponses: OperationResponse[] = [];\n // split batches based on cumulative size of operations\n const batchMap = batches\n .filter((batch: Batch) => batch.operations.length)\n .flatMap((batch: Batch) => splitBatchBasedOnBodySize(batch));\n\n await Promise.all(\n this.executeBatchOperations(\n batchMap,\n path,\n bulkOptions,\n options,\n diagnosticNode,\n orderedResponses,\n partitionKeyDefinition,\n ),\n );\n const response: any = orderedResponses;\n response.diagnostics = diagnosticNode.toDiagnostic(this.clientContext.getClientConfig());\n return response;\n }, this.clientContext);\n }\n\n private executeBatchOperations(\n batchMap: Batch[],\n path: string,\n bulkOptions: BulkOptions,\n options: RequestOptions,\n diagnosticNode: DiagnosticNodeInternal,\n orderedResponses: OperationResponse[],\n partitionKeyDefinition: PartitionKeyDefinition,\n ): Promise<void>[] {\n return batchMap.map(async (batch: Batch) => {\n if (batch.operations.length > 100) {\n throw new Error(\"Cannot run bulk request with more than 100 operations per partition\");\n }\n let response: Response<OperationResponse[]>;\n try {\n response = await addDiagnosticChild(\n async (childNode: DiagnosticNodeInternal) =>\n this.clientContext.bulk({\n body: batch.operations,\n partitionKeyRangeId: batch.rangeId,\n path,\n resourceId: this.container.url,\n bulkOptions,\n options,\n diagnosticNode: childNode,\n }),\n diagnosticNode,\n DiagnosticNodeType.BATCH_REQUEST,\n );\n response.result.forEach((operationResponse: OperationResponse, index: number) => {\n orderedResponses[batch.indexes[index]] = operationResponse;\n });\n } catch (err: any) {\n if (this.clientContext.enableEncryption) {\n await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(err);\n }\n // In the case of 410 errors, we need to recompute the partition key ranges\n // and redo the batch request, however, 410 errors occur for unsupported\n // partition key types as well since we don't support them, so for now we throw\n if (err.code === StatusCodes.Gone) {\n const isPartitionSplit =\n err.substatus === SubStatusCodes.PartitionKeyRangeGone ||\n err.substatus === SubStatusCodes.CompletingSplit;\n\n if (isPartitionSplit) {\n const queryRange = new QueryRange(batch.min, batch.max, true, false);\n const overlappingRanges = await this.partitionKeyRangeCache.getOverlappingRanges(\n this.container.url,\n queryRange,\n diagnosticNode,\n true,\n );\n if (overlappingRanges.length < 1) {\n throw new Error(\"Partition split/merge detected but no overlapping ranges found.\");\n }\n // Handles both merge (overlappingRanges.length === 1) and split (overlappingRanges.length > 1) cases.\n if (overlappingRanges.length >= 1) {\n // const splitBatches: Batch[] = [];\n const newBatches: Batch[] = this.createNewBatches(\n overlappingRanges,\n batch,\n partitionKeyDefinition,\n );\n\n await Promise.all(\n this.executeBatchOperations(\n newBatches,\n path,\n bulkOptions,\n options,\n diagnosticNode,\n orderedResponses,\n partitionKeyDefinition,\n ),\n );\n }\n } else {\n throw new Error(\n \"Partition key error. An operation has an unsupported partitionKey type\" +\n err.message,\n );\n }\n } else {\n throw new Error(`Bulk request errored with: ${err.message}`);\n }\n }\n if (response) {\n try {\n if (this.clientContext.enableEncryption) {\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n );\n let count = 0;\n for (const result of response.result) {\n if (result.resourceBody) {\n const { body, propertiesDecryptedCount } =\n await this.container.encryptionProcessor.decrypt(result.resourceBody);\n result.resourceBody = body;\n count += propertiesDecryptedCount;\n }\n }\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n count,\n );\n }\n } catch (error) {\n const decryptionError = new ErrorResponse(\n `Batch response was received but response decryption failed: + ${error.message}`,\n );\n decryptionError.code = StatusCodes.ServiceUnavailable;\n throw decryptionError;\n }\n response.result.forEach((operationResponse: OperationResponse, index: number) => {\n orderedResponses[batch.indexes[index]] = operationResponse;\n });\n }\n });\n }\n\n /**\n * Function to create new batches based of partition key Ranges.\n *\n * @param overlappingRanges - Overlapping partition key ranges.\n * @param batch - Batch to be split.\n * @param partitionKeyDefinition - PartitionKey definition of container.\n * @returns Array of new batches.\n */\n private createNewBatches(\n overlappingRanges: PartitionKeyRange[],\n batch: Batch,\n partitionKeyDefinition: PartitionKeyDefinition,\n ): Batch[] {\n const newBatches: Batch[] = overlappingRanges.map((keyRange: PartitionKeyRange) => {\n return {\n min: keyRange.minInclusive,\n max: keyRange.maxExclusive,\n rangeId: keyRange.id,\n indexes: [] as number[],\n operations: [] as Operation[],\n };\n });\n let indexValue = 0;\n batch.operations.forEach((operation) => {\n const partitionKey = JSON.parse(operation.partitionKey);\n const hashed = hashPartitionKey(\n assertNotUndefined(\n partitionKey,\n \"undefined value for PartitionKey is not expected during grouping of bulk operations.\",\n ),\n partitionKeyDefinition,\n );\n const batchForKey = assertNotUndefined(\n newBatches.find((newBatch: Batch) => {\n return isKeyInRange(newBatch.min, newBatch.max, hashed);\n }),\n \"No suitable Batch found.\",\n );\n batchForKey.operations.push(operation);\n batchForKey.indexes.push(batch.indexes[indexValue]);\n indexValue++;\n });\n return newBatches;\n }\n\n /**\n * Function to create batches based of partition key Ranges.\n * @param operations - operations to group\n * @param partitionDefinition - PartitionKey definition of container.\n * @param options - Request options for bulk request.\n * @param batches - Groups to be filled with operations.\n */\n private groupOperationsBasedOnPartitionKey(\n operations: OperationInput[],\n partitionDefinition: PartitionKeyDefinition,\n options: RequestOptions | undefined,\n batches: Batch[],\n ) {\n operations.forEach((operationInput, index: number) => {\n const { operation, partitionKey } = prepareOperations(\n operationInput,\n partitionDefinition,\n options,\n );\n const hashed = hashPartitionKey(\n assertNotUndefined(\n partitionKey,\n \"undefined value for PartitionKey is not expected during grouping of bulk operations.\",\n ),\n partitionDefinition,\n );\n const batchForKey = assertNotUndefined(\n batches.find((batch: Batch) => {\n return isKeyInRange(batch.min, batch.max, hashed);\n }),\n \"No suitable Batch found.\",\n );\n batchForKey.operations.push(operation);\n batchForKey.indexes.push(index);\n });\n }\n\n /**\n * Execute transactional batch operations on items.\n *\n * Batch takes an array of Operations which are typed based on what the operation does. Batch is transactional and will rollback all operations if one fails.\n * The choices are: Create, Upsert, Read, Replace, and Delete\n *\n * Usage example:\n * ```ts snippet:ItemsBatch\n * import { CosmosClient, OperationInput } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * // The partitionKey is a required second argument. If it’s undefined, it defaults to the expected partition key format.\n * const operations: OperationInput[] = [\n * {\n * operationType: \"Create\",\n * resourceBody: { id: \"doc1\", name: \"sample\", key: \"A\" },\n * },\n * {\n * operationType: \"Upsert\",\n * resourceBody: { id: \"doc2\", name: \"other\", key: \"A\" },\n * },\n * ];\n *\n * await container.items.batch(operations, \"A\");\n * ```\n *\n * @param operations - List of operations. Limit 100\n * @param options - Used for modifying the request\n */\n public async batch(\n operations: OperationInput[],\n partitionKey?: PartitionKey,\n options?: RequestOptions,\n ): Promise<Response<OperationResponse[]>> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n operations.map((operation) => decorateBatchOperation(operation, options));\n partitionKey = await setPartitionKeyIfUndefined(diagnosticNode, this.container, partitionKey);\n const path = getPathFromLink(this.container.url, ResourceType.item);\n\n if (operations.length > 100) {\n throw new Error(\"Cannot run batch request with more than 100 operations per partition\");\n }\n let response: Response<OperationResponse[]>;\n try {\n if (this.clientContext.enableEncryption) {\n // returns copy to avoid encryption of original operations body passed\n operations = copyObject(operations);\n options = options || {};\n await this.container.checkAndInitializeEncryption();\n options.containerRid = this.container._rid;\n let count = 0;\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n );\n if (partitionKey) {\n const partitionKeyInternal = convertToInternalPartitionKey(partitionKey);\n const { partitionKeyList, encryptedCount } =\n await this.container.encryptionProcessor.getEncryptedPartitionKeyValue(\n partitionKeyInternal,\n );\n partitionKey = partitionKeyList;\n count += encryptedCount;\n }\n const { operations: encryptedOperations, totalPropertiesEncryptedCount } =\n await this.bulkBatchEncryptionHelper(operations);\n operations = encryptedOperations;\n count += totalPropertiesEncryptedCount;\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n count,\n );\n }\n\n const isPartitionLevelFailOverEnabled =\n this.clientContext.isPartitionLevelFailOverEnabled();\n const partitionKeyRangeId = await computePartitionKeyRangeId(\n diagnosticNode,\n partitionKey,\n this.partitionKeyRangeCache,\n isPartitionLevelFailOverEnabled,\n this.container,\n );\n\n response = await this.clientContext.batch({\n body: operations,\n partitionKey,\n path,\n resourceId: this.container.url,\n options,\n diagnosticNode,\n partitionKeyRangeId,\n });\n } catch (err: any) {\n if (this.clientContext.enableEncryption) {\n await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(err);\n }\n throw new Error(`Batch request error: ${err.message}`);\n }\n if (this.clientContext.enableEncryption) {\n try {\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n );\n let count = 0;\n for (const result of response.result) {\n if (result.resourceBody) {\n const { body, propertiesDecryptedCount } =\n await this.container.encryptionProcessor.decrypt(result.resourceBody);\n result.resourceBody = body;\n count += propertiesDecryptedCount;\n }\n }\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n count,\n );\n } catch (error) {\n const decryptionError = new ErrorResponse(\n `Batch response was received but response decryption failed: + ${error.message}`,\n );\n decryptionError.code = StatusCodes.ServiceUnavailable;\n throw decryptionError;\n }\n }\n return response;\n }, this.clientContext);\n }\n\n private async bulkBatchEncryptionHelper(\n operations: OperationInput[],\n ): Promise<{ operations: OperationInput[]; totalPropertiesEncryptedCount: number }> {\n let totalPropertiesEncryptedCount = 0;\n const encryptedOperations: OperationInput[] = [];\n for (const operation of operations) {\n const { operation: encryptedOp, totalPropertiesEncryptedCount: updatedCount } =\n await encryptOperationInput(\n this.container.encryptionProcessor,\n operation,\n totalPropertiesEncryptedCount,\n );\n totalPropertiesEncryptedCount = updatedCount;\n encryptedOperations.push(encryptedOp);\n }\n return { operations: encryptedOperations, totalPropertiesEncryptedCount };\n }\n}\n"]}
1
+ {"version":3,"file":"Items.js","sourceRoot":"","sources":["../../../../src/client/Item/Items.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAGjE,OAAO,EACL,SAAS,EACT,UAAU,EACV,aAAa,EACb,eAAe,EACf,mBAAmB,EACnB,YAAY,EACZ,WAAW,EACX,cAAc,GACf,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,oBAAoB,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAEhG,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAGvD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAUjD,OAAO,EACL,YAAY,EACZ,iBAAiB,EACjB,sBAAsB,EACtB,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,kBAAkB,EAAE,4BAA4B,EAAE,MAAM,2BAA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CACN,CAAC;gBACJ,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,MAAM,eAAe,GAAG,IAAI,aAAa,CACvC,iEAAiE,KAAK,CAAC,OAAO,EAAE,CACjF,CAAC;oBACF,eAAe,CAAC,IAAI,GAAG,WAAW,CAAC,kBAAkB,CAAC;oBACtD,MAAM,eAAe,CAAC;gBACxB,CAAC;YACH,CAAC;YACD,OAAO,QAAQ,CAAC;QAClB,CAAC,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;IACzB,CAAC;IAEO,KAAK,CAAC,yBAAyB,CACrC,UAA4B;QAE5B,IAAI,6BAA6B,GAAG,CAAC,CAAC;QACtC,MAAM,mBAAmB,GAAqB,EAAE,CAAC;QACjD,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;YACnC,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE,YAAY,EAAE,GAC3E,MAAM,qBAAqB,CACzB,IAAI,CAAC,SAAS,CAAC,mBAAmB,EAClC,SAAS,EACT,6BAA6B,CAC9B,CAAC;YACJ,6BAA6B,GAAG,YAAY,CAAC;YAC7C,mBAAmB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACxC,CAAC;QACD,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,6BAA6B,EAAE,CAAC;IAC5E,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { ChangeFeedIterator } from \"../../ChangeFeedIterator.js\";\nimport type { ChangeFeedOptions } from \"../../ChangeFeedOptions.js\";\nimport type { ClientContext } from \"../../ClientContext.js\";\nimport {\n Constants,\n copyObject,\n getIdFromLink,\n getPathFromLink,\n isItemResourceValid,\n ResourceType,\n StatusCodes,\n SubStatusCodes,\n} from \"../../common/index.js\";\nimport { extractPartitionKeys, setPartitionKeyIfUndefined } from \"../../extractPartitionKey.js\";\nimport type { FetchFunctionCallback, SqlQuerySpec } from \"../../queryExecutionContext/index.js\";\nimport { QueryIterator } from \"../../queryIterator.js\";\nimport type { FeedOptions, RequestOptions, Response } from \"../../request/index.js\";\nimport type { Container, PartitionKeyRange } from \"../Container/index.js\";\nimport { Item } from \"./Item.js\";\nimport type { ItemDefinition } from \"./ItemDefinition.js\";\nimport { ItemResponse } from \"./ItemResponse.js\";\nimport type {\n Batch,\n OperationResponse,\n OperationInput,\n BulkOptions,\n BulkOperationResponse,\n Operation,\n BulkOperationResult,\n} from \"../../utils/batch.js\";\nimport {\n isKeyInRange,\n prepareOperations,\n decorateBatchOperation,\n splitBatchBasedOnBodySize,\n encryptOperationInput,\n} from \"../../utils/batch.js\";\nimport { assertNotUndefined, isPrimitivePartitionKeyValue } from \"../../utils/typeChecks.js\";\nimport { hashPartitionKey } from \"../../utils/hashing/hash.js\";\nimport { PartitionKeyRangeCache, QueryRange } from \"../../routing/index.js\";\nimport type {\n PartitionKey,\n PartitionKeyDefinition,\n PartitionKeyInternal,\n} from \"../../documents/index.js\";\nimport { convertToInternalPartitionKey } from \"../../documents/index.js\";\nimport type {\n ChangeFeedPullModelIterator,\n ChangeFeedIteratorOptions,\n} from \"../../client/ChangeFeed/index.js\";\nimport { validateChangeFeedIteratorOptions } from \"../../client/ChangeFeed/changeFeedUtils.js\";\nimport type { DiagnosticNodeInternal } from \"../../diagnostics/DiagnosticNodeInternal.js\";\nimport { DiagnosticNodeType } from \"../../diagnostics/DiagnosticNodeInternal.js\";\nimport {\n getEmptyCosmosDiagnostics,\n withDiagnostics,\n addDiagnosticChild,\n} from \"../../utils/diagnostics.js\";\nimport { randomUUID } from \"@azure/core-util\";\nimport { computePartitionKeyRangeId, readPartitionKeyDefinition } from \"../ClientUtils.js\";\nimport { ChangeFeedIteratorBuilder } from \"../ChangeFeed/ChangeFeedIteratorBuilder.js\";\nimport type { EncryptionQueryBuilder } from \"../../encryption/index.js\";\nimport type { EncryptionSqlParameter } from \"../../encryption/EncryptionQueryBuilder.js\";\nimport type { Resource } from \"../Resource.js\";\nimport { TypeMarker } from \"../../encryption/enums/TypeMarker.js\";\nimport { EncryptionItemQueryIterator } from \"../../encryption/EncryptionItemQueryIterator.js\";\nimport { ErrorResponse } from \"../../request/index.js\";\nimport { BulkHelper } from \"../../bulk/BulkHelper.js\";\n\n/**\n * @hidden\n */\nfunction isChangeFeedOptions(options: unknown): options is ChangeFeedOptions {\n return options && !(isPrimitivePartitionKeyValue(options) || Array.isArray(options));\n}\n\n/**\n * Operations for creating new items, and reading/querying all items\n *\n * @see {@link Item} for reading, replacing, or deleting an existing container; use `.item(id)`.\n */\nexport class Items {\n private partitionKeyRangeCache: PartitionKeyRangeCache;\n /**\n * Create an instance of {@link Items} linked to the parent {@link Container}.\n * @param container - The parent container.\n * @hidden\n */\n constructor(\n public readonly container: Container,\n private readonly clientContext: ClientContext,\n ) {\n this.partitionKeyRangeCache = this.clientContext.partitionKeyRangeCache;\n }\n\n /**\n * Queries all items.\n * @param query - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Read all items to array.\n * ```ts snippet:ItemsQueryItems\n * import { CosmosClient, SqlQuerySpec } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const querySpec: SqlQuerySpec = {\n * query: `SELECT * FROM Families f WHERE f.lastName = @lastName`,\n * parameters: [{ name: \"@lastName\", value: \"Hendricks\" }],\n * };\n * const { resources: items } = await container.items.query(querySpec).fetchAll();\n * ```\n */\n\n //\n public query(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<any>;\n /**\n * Queries all items.\n * @param query - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Read all items to array.\n * ```ts snippet:ItemsQueryItems\n * import { CosmosClient, SqlQuerySpec } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const querySpec: SqlQuerySpec = {\n * query: `SELECT * FROM Families f WHERE f.lastName = @lastName`,\n * parameters: [{ name: \"@lastName\", value: \"Hendricks\" }],\n * };\n * const { resources: items } = await container.items.query(querySpec).fetchAll();\n * ```\n */\n public query<T>(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;\n public query<T>(query: string | SqlQuerySpec, options: FeedOptions = {}): QueryIterator<T> {\n const path = getPathFromLink(this.container.url, ResourceType.item);\n const id = getIdFromLink(this.container.url);\n\n const fetchFunction: FetchFunctionCallback = async (\n diagnosticNode: DiagnosticNodeInternal,\n innerOptions: FeedOptions,\n correlatedActivityId: string,\n ) => {\n let internalPartitionKey: PartitionKeyInternal | undefined;\n if (options.partitionKey) {\n internalPartitionKey = convertToInternalPartitionKey(options.partitionKey);\n }\n const isPartitionLevelFailOverEnabled = this.clientContext.isPartitionLevelFailOverEnabled();\n const partitionKeyRangeId = await computePartitionKeyRangeId(\n diagnosticNode,\n internalPartitionKey,\n this.partitionKeyRangeCache,\n isPartitionLevelFailOverEnabled,\n this.container,\n );\n\n const response = await this.clientContext.queryFeed({\n path,\n resourceType: ResourceType.item,\n resourceId: id,\n resultFn: (result) => (result ? result.Documents : []),\n query,\n options: innerOptions,\n partitionKey: options.partitionKey,\n diagnosticNode,\n correlatedActivityId: correlatedActivityId,\n partitionKeyRangeId,\n });\n return response;\n };\n let iterator: QueryIterator<T>;\n if (this.clientContext.enableEncryption) {\n iterator = new EncryptionItemQueryIterator(\n this.clientContext,\n query,\n options,\n fetchFunction,\n this.container,\n );\n } else {\n iterator = new QueryIterator<T>(\n this.clientContext,\n query,\n options,\n fetchFunction,\n this.container.url,\n ResourceType.item,\n );\n }\n return iterator;\n }\n /**\n * Queries all items in an encrypted container.\n * @param queryBuilder - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to build a query on encrypted properties.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Read all items to array.\n * ```ts snippet:ItemsQueryEncryptedItems\n * import { CosmosClient, EncryptionQueryBuilder } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const queryBuilder = new EncryptionQueryBuilder(\n * `SELECT firstname FROM Families f WHERE f.lastName = @lastName`,\n * );\n * queryBuilder.addParameter(\"@lastName\", \"Hendricks\", \"/lastname\");\n * const queryIterator = await container.items.getEncryptionQueryIterator(queryBuilder);\n * const { resources: items } = await queryIterator.fetchAll();\n * ```\n */\n public async getEncryptionQueryIterator(\n queryBuilder: EncryptionQueryBuilder,\n options: FeedOptions = {},\n ): Promise<QueryIterator<ItemDefinition>> {\n const encryptionSqlQuerySpec = queryBuilder.toEncryptionSqlQuerySpec();\n const sqlQuerySpec = await this.buildSqlQuerySpec(encryptionSqlQuerySpec);\n if (this.clientContext.enableEncryption && options.partitionKey) {\n await this.container.checkAndInitializeEncryption();\n const { partitionKeyList, encryptedCount } =\n await this.container.encryptionProcessor.getEncryptedPartitionKeyValue([\n options.partitionKey,\n ] as PartitionKeyInternal);\n if (encryptedCount > 0) {\n options.partitionKey = partitionKeyList[0];\n }\n }\n const iterator = this.query<ItemDefinition>(sqlQuerySpec, options);\n return iterator;\n }\n\n private async buildSqlQuerySpec(encryptionSqlQuerySpec: SqlQuerySpec): Promise<SqlQuerySpec> {\n let encryptionParameters = encryptionSqlQuerySpec.parameters as EncryptionSqlParameter[];\n const sqlQuerySpec: SqlQuerySpec = {\n query: encryptionSqlQuerySpec.query,\n parameters: [],\n };\n // returns copy to avoid encryption of original parameters passed\n encryptionParameters = copyObject(encryptionParameters);\n for (const parameter of encryptionParameters) {\n let value: any;\n if (parameter.type !== undefined || parameter.type !== TypeMarker.Null) {\n value = await this.container.encryptionProcessor.encryptQueryParameter(\n parameter.path,\n parameter.value,\n parameter.path === \"/id\",\n parameter.type,\n );\n }\n sqlQuerySpec.parameters.push({ name: parameter.name, value: value });\n }\n return sqlQuerySpec;\n }\n\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n *\n * @deprecated Use `getChangeFeedIterator` instead.\n *\n * @example Read from the beginning of the change feed.\n * ```ts snippet:ignore\n * const iterator = items.readChangeFeed({ startFromBeginning: true });\n * const firstPage = await iterator.fetchNext();\n * const firstPageResults = firstPage.result\n * const secondPage = await iterator.fetchNext();\n * ```\n */\n public readChangeFeed(\n partitionKey: PartitionKey,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<any>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n *\n */\n public readChangeFeed(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<any>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n */\n public readChangeFeed<T>(\n partitionKey: PartitionKey,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<T>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n */\n public readChangeFeed<T>(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<T>;\n public readChangeFeed<T>(\n partitionKeyOrChangeFeedOptions?: PartitionKey | ChangeFeedOptions,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<T> {\n if (isChangeFeedOptions(partitionKeyOrChangeFeedOptions)) {\n return this.changeFeed(partitionKeyOrChangeFeedOptions);\n } else {\n return this.changeFeed(partitionKeyOrChangeFeedOptions, changeFeedOptions);\n }\n }\n\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n * @example Read from the beginning of the change feed.\n * ```ts snippet:ignore\n * const iterator = items.readChangeFeed({ startFromBeginning: true });\n * const firstPage = await iterator.fetchNext();\n * const firstPageResults = firstPage.result\n * const secondPage = await iterator.fetchNext();\n * ```\n */\n public changeFeed(\n partitionKey: PartitionKey,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<any>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n */\n public changeFeed(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<any>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n */\n public changeFeed<T>(\n partitionKey: PartitionKey,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<T>;\n /**\n * Create a `ChangeFeedIterator` to iterate over pages of changes\n * @deprecated Use `getChangeFeedIterator` instead.\n */\n public changeFeed<T>(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<T>;\n public changeFeed<T>(\n partitionKeyOrChangeFeedOptions?: PartitionKey | ChangeFeedOptions,\n changeFeedOptions?: ChangeFeedOptions,\n ): ChangeFeedIterator<T> {\n let partitionKey: PartitionKey;\n if (!changeFeedOptions && isChangeFeedOptions(partitionKeyOrChangeFeedOptions)) {\n partitionKey = undefined;\n changeFeedOptions = partitionKeyOrChangeFeedOptions;\n } else if (\n partitionKeyOrChangeFeedOptions !== undefined &&\n !isChangeFeedOptions(partitionKeyOrChangeFeedOptions)\n ) {\n partitionKey = partitionKeyOrChangeFeedOptions;\n }\n\n if (!changeFeedOptions) {\n changeFeedOptions = {};\n }\n\n const path = getPathFromLink(this.container.url, ResourceType.item);\n const id = getIdFromLink(this.container.url);\n return new ChangeFeedIterator<T>(this.clientContext, id, path, partitionKey, changeFeedOptions);\n }\n\n /**\n * Returns an iterator to iterate over pages of changes. The iterator returned can be used to fetch changes for a single partition key, feed range or an entire container.\n *\n * @example\n * ```ts snippet:ReadmeSampleChangeFeedPullModelIteratorPartitionKey\n * import {\n * CosmosClient,\n * PartitionKeyDefinitionVersion,\n * PartitionKeyKind,\n * ChangeFeedStartFrom,\n * } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const containerDefinition = {\n * id: \"Test Database\",\n * partitionKey: {\n * paths: [\"/name\", \"/address/zip\"],\n * version: PartitionKeyDefinitionVersion.V2,\n * kind: PartitionKeyKind.MultiHash,\n * },\n * };\n * const { container } = await database.containers.createIfNotExists(containerDefinition);\n *\n * const partitionKey = \"some-partition-Key-value\";\n * const options = {\n * changeFeedStartFrom: ChangeFeedStartFrom.Beginning(partitionKey),\n * };\n *\n * const iterator = container.items.getChangeFeedIterator(options);\n *\n * while (iterator.hasMoreResults) {\n * const response = await iterator.readNext();\n * // process this response\n * }\n * ```\n */\n public getChangeFeedIterator<T>(\n changeFeedIteratorOptions?: ChangeFeedIteratorOptions,\n ): ChangeFeedPullModelIterator<T> {\n const cfOptions = changeFeedIteratorOptions !== undefined ? changeFeedIteratorOptions : {};\n validateChangeFeedIteratorOptions(cfOptions);\n const iterator = new ChangeFeedIteratorBuilder<T>(\n cfOptions,\n this.clientContext,\n this.container,\n this.partitionKeyRangeCache,\n );\n return iterator;\n }\n\n /**\n * Read all items.\n *\n * There is no set schema for JSON items. They may contain any number of custom properties.\n *\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Read all items to array.\n * ```ts snippet:ItemsReadAll\n * import { CosmosClient } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const { resources: containerList } = await container.items.readAll().fetchAll();\n * ```\n */\n public readAll(options?: FeedOptions): QueryIterator<ItemDefinition>;\n /**\n * Read all items.\n *\n * Any provided type, T, is not necessarily enforced by the SDK.\n * You may get more or less properties and it's up to your logic to enforce it.\n *\n * There is no set schema for JSON items. They may contain any number of custom properties.\n *\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Read all items to array.\n * ```ts snippet:ItemsReadAll\n * import { CosmosClient } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const { resources: containerList } = await container.items.readAll().fetchAll();\n * ```\n */\n public readAll<T extends ItemDefinition>(options?: FeedOptions): QueryIterator<T>;\n public readAll<T extends ItemDefinition>(options?: FeedOptions): QueryIterator<T> {\n return this.query<T>(\"SELECT * from c\", options);\n }\n\n /**\n * Create an item.\n *\n * Any provided type, T, is not necessarily enforced by the SDK.\n * You may get more or less properties and it's up to your logic to enforce it.\n *\n * There is no set schema for JSON items. They may contain any number of custom properties.\n *\n * @param body - Represents the body of the item. Can contain any number of user defined properties.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Create an item.\n * ```ts snippet:ContainerItems\n * import { CosmosClient } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const { resource: createdItem } = await container.items.create({\n * id: \"<item id>\",\n * properties: {},\n * });\n * ```\n */\n public async create<T extends ItemDefinition = any>(\n body: T,\n options: RequestOptions = {},\n ): Promise<ItemResponse<T>> {\n // Generate random document id if the id is missing in the payload and\n // options.disableAutomaticIdGeneration != true\n\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n if ((body.id === undefined || body.id === \"\") && !options.disableAutomaticIdGeneration) {\n body.id = randomUUID();\n }\n const partitionKeyDefinition = await readPartitionKeyDefinition(\n diagnosticNode,\n this.container,\n );\n let partitionKey = extractPartitionKeys(body, partitionKeyDefinition);\n let response: Response<T & Resource>;\n try {\n if (this.clientContext.enableEncryption) {\n await this.container.checkAndInitializeEncryption();\n options.containerRid = this.container._rid;\n // returns copy to avoid encryption of original body passed\n body = copyObject(body);\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n );\n const { body: encryptedBody, propertiesEncryptedCount } =\n await this.container.encryptionProcessor.encrypt(body);\n body = encryptedBody;\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n propertiesEncryptedCount,\n );\n\n partitionKey = extractPartitionKeys(body, partitionKeyDefinition);\n }\n const err = {};\n if (!isItemResourceValid(body, err)) {\n throw err;\n }\n const path = getPathFromLink(this.container.url, ResourceType.item);\n const id = getIdFromLink(this.container.url);\n\n const isPartitionLevelFailOverEnabled =\n this.clientContext.isPartitionLevelFailOverEnabled();\n const partitionKeyRangeId = await computePartitionKeyRangeId(\n diagnosticNode,\n partitionKey,\n this.partitionKeyRangeCache,\n isPartitionLevelFailOverEnabled,\n this.container,\n partitionKeyDefinition,\n );\n\n response = await this.clientContext.create<T>({\n body,\n path,\n resourceType: ResourceType.item,\n resourceId: id,\n diagnosticNode,\n options,\n partitionKey,\n partitionKeyRangeId,\n });\n } catch (error: any) {\n if (this.clientContext.enableEncryption) {\n // Todo: internally retry post policy refresh\n await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(error);\n }\n throw error;\n }\n\n if (this.clientContext.enableEncryption) {\n // try block for decrypting response. This is done so that we can throw special error message in case of decryption failure\n try {\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n );\n const { body: decryptedResult, propertiesDecryptedCount } =\n await this.container.encryptionProcessor.decrypt(response.result);\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n propertiesDecryptedCount,\n );\n response.result = decryptedResult;\n partitionKey = extractPartitionKeys(response.result, partitionKeyDefinition);\n } catch (error) {\n const decryptionError = new ErrorResponse(\n `Item creation was successful but response decryption failed: + ${error.message}`,\n );\n decryptionError.code = StatusCodes.ServiceUnavailable;\n throw decryptionError;\n }\n }\n const ref = new Item(\n this.container,\n (response.result as any).id,\n this.clientContext,\n partitionKey,\n );\n return new ItemResponse(\n response.result,\n response.headers,\n response.code,\n response.substatus,\n ref,\n getEmptyCosmosDiagnostics(),\n );\n }, this.clientContext);\n }\n\n /**\n * Upsert an item.\n *\n * There is no set schema for JSON items. They may contain any number of custom properties.\n *\n * @param body - Represents the body of the item. Can contain any number of user defined properties.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n */\n public async upsert(\n body: unknown,\n options?: RequestOptions,\n ): Promise<ItemResponse<ItemDefinition>>;\n /**\n * Upsert an item.\n *\n * Any provided type, T, is not necessarily enforced by the SDK.\n * You may get more or less properties and it's up to your logic to enforce it.\n *\n * There is no set schema for JSON items. They may contain any number of custom properties.\n *\n * @param body - Represents the body of the item. Can contain any number of user defined properties.\n * @param options - Used for modifying the request (for instance, specifying the partition key).\n * @example Upsert an item.\n * ```ts snippet:ItemsUpsert\n * import { CosmosClient } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const { resource: createdItem1 } = await container.items.create({\n * id: \"<item id 1>\",\n * properties: {},\n * });\n *\n * const { resource: upsertItem1 } = await container.items.upsert({\n * id: \"<item id 1>\",\n * updated_properties: {},\n * });\n *\n * const { resource: upsertItem2 } = await container.items.upsert({\n * id: \"<item id 2>\",\n * properties: {},\n * });\n * ```\n */\n public async upsert<T extends ItemDefinition>(\n body: T,\n options?: RequestOptions,\n ): Promise<ItemResponse<T>>;\n public async upsert<T extends ItemDefinition>(\n body: T,\n options: RequestOptions = {},\n ): Promise<ItemResponse<T>> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n // Generate random document id if the id is missing in the payload and\n // options.disableAutomaticIdGeneration != true\n if ((body.id === undefined || body.id === \"\") && !options.disableAutomaticIdGeneration) {\n body.id = randomUUID();\n }\n\n const partitionKeyDefinition = await readPartitionKeyDefinition(\n diagnosticNode,\n this.container,\n );\n let partitionKey = extractPartitionKeys(body, partitionKeyDefinition);\n let response: Response<T & Resource>;\n try {\n if (this.clientContext.enableEncryption) {\n // returns copy to avoid encryption of original body passed\n body = copyObject(body);\n options = options || {};\n await this.container.checkAndInitializeEncryption();\n options.containerRid = this.container._rid;\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n );\n const { body: encryptedBody, propertiesEncryptedCount } =\n await this.container.encryptionProcessor.encrypt(body);\n body = encryptedBody;\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n propertiesEncryptedCount,\n );\n partitionKey = extractPartitionKeys(body, partitionKeyDefinition);\n }\n\n const err = {};\n if (!isItemResourceValid(body, err)) {\n throw err;\n }\n\n const path = getPathFromLink(this.container.url, ResourceType.item);\n const id = getIdFromLink(this.container.url);\n\n const isPartitionLevelFailOverEnabled =\n this.clientContext.isPartitionLevelFailOverEnabled();\n const partitionKeyRangeId = await computePartitionKeyRangeId(\n diagnosticNode,\n partitionKey,\n this.partitionKeyRangeCache,\n isPartitionLevelFailOverEnabled,\n this.container,\n partitionKeyDefinition,\n );\n\n response = await this.clientContext.upsert<T>({\n body,\n path,\n resourceType: ResourceType.item,\n resourceId: id,\n options,\n partitionKey,\n diagnosticNode,\n partitionKeyRangeId,\n });\n } catch (error: any) {\n if (this.clientContext.enableEncryption) {\n await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(error);\n }\n throw error;\n }\n if (this.clientContext.enableEncryption) {\n try {\n // try block for decrypting response. This is done so that we can throw special error message in case of decryption failure\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n );\n const { body: decryptedResult, propertiesDecryptedCount } =\n await this.container.encryptionProcessor.decrypt(response.result);\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n propertiesDecryptedCount,\n );\n response.result = decryptedResult;\n partitionKey = extractPartitionKeys(response.result, partitionKeyDefinition);\n } catch (error) {\n const decryptionError = new ErrorResponse(\n `Item upsert was successful but response decryption failed: + ${error.message}`,\n );\n decryptionError.code = StatusCodes.ServiceUnavailable;\n throw decryptionError;\n }\n }\n\n const ref = new Item(\n this.container,\n (response.result as any).id,\n this.clientContext,\n partitionKey,\n );\n return new ItemResponse(\n response.result,\n response.headers,\n response.code,\n response.substatus,\n ref,\n getEmptyCosmosDiagnostics(),\n );\n }, this.clientContext);\n }\n\n /**\n * Execute bulk operations on items.\n * @param operations - List of operations\n * @param options - used for modifying the request\n * @returns list of operation results corresponding to the operations\n *\n * @example\n * ```ts snippet:ItemsExecuteBulkOperations\n * import { CosmosClient, OperationInput } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * const operations: OperationInput[] = [\n * {\n * operationType: \"Create\",\n * resourceBody: { id: \"doc1\", name: \"sample\", key: \"A\" },\n * },\n * {\n * operationType: \"Upsert\",\n * partitionKey: \"A\",\n * resourceBody: { id: \"doc2\", name: \"other\", key: \"A\" },\n * },\n * ];\n *\n * await container.items.executeBulkOperations(operations);\n * ```\n */\n public async executeBulkOperations(\n operations: OperationInput[],\n options: RequestOptions = {},\n ): Promise<BulkOperationResult[]> {\n const bulkHelper = new BulkHelper(\n this.container,\n this.clientContext,\n this.partitionKeyRangeCache,\n options,\n );\n return bulkHelper.execute(operations);\n }\n\n /**\n * Execute bulk operations on items.\n * @deprecated Use `executeBulkOperations` instead.\n *\n * Bulk takes an array of Operations which are typed based on what the operation does.\n * The choices are: Create, Upsert, Read, Replace, and Delete\n *\n * Usage example:\n * ```ts snippet:ItemsBulk\n * import { CosmosClient, OperationInput } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * // partitionKey is optional at the top level if present in the resourceBody\n * const operations: OperationInput[] = [\n * {\n * operationType: \"Create\",\n * resourceBody: { id: \"doc1\", name: \"sample\", key: \"A\" },\n * },\n * {\n * operationType: \"Upsert\",\n * partitionKey: \"A\",\n * resourceBody: { id: \"doc2\", name: \"other\", key: \"A\" },\n * },\n * ];\n *\n * await container.items.bulk(operations);\n * ```\n *\n * @param operations - List of operations. Limit 100\n * @param bulkOptions - Optional options object to modify bulk behavior. Pass \\{ continueOnError: false \\} to stop executing operations when one fails. (Defaults to true)\n * @param options - Used for modifying the request.\n */\n public async bulk(\n operations: OperationInput[],\n bulkOptions?: BulkOptions,\n options?: RequestOptions,\n ): Promise<BulkOperationResponse> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n const partitionKeyRanges = (\n await this.partitionKeyRangeCache.onCollectionRoutingMap(this.container.url, diagnosticNode)\n ).getOrderedParitionKeyRanges();\n\n const partitionKeyDefinition = await readPartitionKeyDefinition(\n diagnosticNode,\n this.container,\n );\n\n if (this.clientContext.enableEncryption) {\n // returns copy to avoid encryption of original operations body passed\n operations = copyObject(operations);\n options = options || {};\n await this.container.checkAndInitializeEncryption();\n options.containerRid = this.container._rid;\n diagnosticNode.beginEncryptionDiagnostics(Constants.Encryption.DiagnosticsEncryptOperation);\n const { operations: encryptedOperations, totalPropertiesEncryptedCount } =\n await this.bulkBatchEncryptionHelper(operations);\n operations = encryptedOperations;\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n totalPropertiesEncryptedCount,\n );\n }\n\n const batches: Batch[] = partitionKeyRanges.map((keyRange: PartitionKeyRange) => {\n return {\n min: keyRange.minInclusive,\n max: keyRange.maxExclusive,\n rangeId: keyRange.id,\n indexes: [] as number[],\n operations: [] as Operation[],\n };\n });\n\n this.groupOperationsBasedOnPartitionKey(operations, partitionKeyDefinition, options, batches);\n\n const path = getPathFromLink(this.container.url, ResourceType.item);\n\n const orderedResponses: OperationResponse[] = [];\n // split batches based on cumulative size of operations\n const batchMap = batches\n .filter((batch: Batch) => batch.operations.length)\n .flatMap((batch: Batch) => splitBatchBasedOnBodySize(batch));\n\n await Promise.all(\n this.executeBatchOperations(\n batchMap,\n path,\n bulkOptions,\n options,\n diagnosticNode,\n orderedResponses,\n partitionKeyDefinition,\n ),\n );\n const response: any = orderedResponses;\n response.diagnostics = diagnosticNode.toDiagnostic(this.clientContext.getClientConfig());\n return response;\n }, this.clientContext);\n }\n\n private executeBatchOperations(\n batchMap: Batch[],\n path: string,\n bulkOptions: BulkOptions,\n options: RequestOptions,\n diagnosticNode: DiagnosticNodeInternal,\n orderedResponses: OperationResponse[],\n partitionKeyDefinition: PartitionKeyDefinition,\n ): Promise<void>[] {\n return batchMap.map(async (batch: Batch) => {\n if (batch.operations.length > 100) {\n throw new Error(\"Cannot run bulk request with more than 100 operations per partition\");\n }\n let response: Response<OperationResponse[]>;\n try {\n response = await addDiagnosticChild(\n async (childNode: DiagnosticNodeInternal) =>\n this.clientContext.bulk({\n body: batch.operations,\n partitionKeyRangeId: batch.rangeId,\n path,\n resourceId: this.container.url,\n bulkOptions,\n options,\n diagnosticNode: childNode,\n }),\n diagnosticNode,\n DiagnosticNodeType.BATCH_REQUEST,\n );\n response.result.forEach((operationResponse: OperationResponse, index: number) => {\n orderedResponses[batch.indexes[index]] = operationResponse;\n });\n } catch (err: any) {\n if (this.clientContext.enableEncryption) {\n await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(err);\n }\n // In the case of 410 errors, we need to recompute the partition key ranges\n // and redo the batch request, however, 410 errors occur for unsupported\n // partition key types as well since we don't support them, so for now we throw\n if (err.code === StatusCodes.Gone) {\n const isPartitionSplit =\n err.substatus === SubStatusCodes.PartitionKeyRangeGone ||\n err.substatus === SubStatusCodes.CompletingSplit;\n\n if (isPartitionSplit) {\n const queryRange = new QueryRange(batch.min, batch.max, true, false);\n const overlappingRanges = await this.partitionKeyRangeCache.getOverlappingRanges(\n this.container.url,\n queryRange,\n diagnosticNode,\n true,\n );\n if (overlappingRanges.length < 1) {\n throw new Error(\"Partition split/merge detected but no overlapping ranges found.\");\n }\n // Handles both merge (overlappingRanges.length === 1) and split (overlappingRanges.length > 1) cases.\n if (overlappingRanges.length >= 1) {\n // const splitBatches: Batch[] = [];\n const newBatches: Batch[] = this.createNewBatches(\n overlappingRanges,\n batch,\n partitionKeyDefinition,\n );\n\n await Promise.all(\n this.executeBatchOperations(\n newBatches,\n path,\n bulkOptions,\n options,\n diagnosticNode,\n orderedResponses,\n partitionKeyDefinition,\n ),\n );\n }\n } else {\n throw new Error(\n \"Partition key error. An operation has an unsupported partitionKey type\" +\n err.message,\n );\n }\n } else {\n throw new Error(`Bulk request errored with: ${err.message}`);\n }\n }\n if (response) {\n try {\n if (this.clientContext.enableEncryption) {\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n );\n let count = 0;\n for (const result of response.result) {\n if (result.resourceBody) {\n const { body, propertiesDecryptedCount } =\n await this.container.encryptionProcessor.decrypt(result.resourceBody);\n result.resourceBody = body;\n count += propertiesDecryptedCount;\n }\n }\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n count,\n );\n }\n } catch (error) {\n const decryptionError = new ErrorResponse(\n `Batch response was received but response decryption failed: + ${error.message}`,\n );\n decryptionError.code = StatusCodes.ServiceUnavailable;\n throw decryptionError;\n }\n response.result.forEach((operationResponse: OperationResponse, index: number) => {\n orderedResponses[batch.indexes[index]] = operationResponse;\n });\n }\n });\n }\n\n /**\n * Function to create new batches based of partition key Ranges.\n *\n * @param overlappingRanges - Overlapping partition key ranges.\n * @param batch - Batch to be split.\n * @param partitionKeyDefinition - PartitionKey definition of container.\n * @returns Array of new batches.\n */\n private createNewBatches(\n overlappingRanges: PartitionKeyRange[],\n batch: Batch,\n partitionKeyDefinition: PartitionKeyDefinition,\n ): Batch[] {\n const newBatches: Batch[] = overlappingRanges.map((keyRange: PartitionKeyRange) => {\n return {\n min: keyRange.minInclusive,\n max: keyRange.maxExclusive,\n rangeId: keyRange.id,\n indexes: [] as number[],\n operations: [] as Operation[],\n };\n });\n let indexValue = 0;\n batch.operations.forEach((operation) => {\n const partitionKey = JSON.parse(operation.partitionKey);\n const hashed = hashPartitionKey(\n assertNotUndefined(\n partitionKey,\n \"undefined value for PartitionKey is not expected during grouping of bulk operations.\",\n ),\n partitionKeyDefinition,\n );\n const batchForKey = assertNotUndefined(\n newBatches.find((newBatch: Batch) => {\n return isKeyInRange(newBatch.min, newBatch.max, hashed);\n }),\n \"No suitable Batch found.\",\n );\n batchForKey.operations.push(operation);\n batchForKey.indexes.push(batch.indexes[indexValue]);\n indexValue++;\n });\n return newBatches;\n }\n\n /**\n * Function to create batches based of partition key Ranges.\n * @param operations - operations to group\n * @param partitionDefinition - PartitionKey definition of container.\n * @param options - Request options for bulk request.\n * @param batches - Groups to be filled with operations.\n */\n private groupOperationsBasedOnPartitionKey(\n operations: OperationInput[],\n partitionDefinition: PartitionKeyDefinition,\n options: RequestOptions | undefined,\n batches: Batch[],\n ) {\n operations.forEach((operationInput, index: number) => {\n const { operation, partitionKey } = prepareOperations(\n operationInput,\n partitionDefinition,\n options,\n );\n const hashed = hashPartitionKey(\n assertNotUndefined(\n partitionKey,\n \"undefined value for PartitionKey is not expected during grouping of bulk operations.\",\n ),\n partitionDefinition,\n );\n const batchForKey = assertNotUndefined(\n batches.find((batch: Batch) => {\n return isKeyInRange(batch.min, batch.max, hashed);\n }),\n \"No suitable Batch found.\",\n );\n batchForKey.operations.push(operation);\n batchForKey.indexes.push(index);\n });\n }\n\n /**\n * Execute transactional batch operations on items.\n *\n * Batch takes an array of Operations which are typed based on what the operation does. Batch is transactional and will rollback all operations if one fails.\n * The choices are: Create, Upsert, Read, Replace, and Delete\n *\n * Usage example:\n * ```ts snippet:ItemsBatch\n * import { CosmosClient, OperationInput } from \"@azure/cosmos\";\n *\n * const endpoint = \"https://your-account.documents.azure.com\";\n * const key = \"<database account masterkey>\";\n * const client = new CosmosClient({ endpoint, key });\n *\n * const { database } = await client.databases.createIfNotExists({ id: \"Test Database\" });\n *\n * const { container } = await database.containers.createIfNotExists({ id: \"Test Container\" });\n *\n * // The partitionKey is a required second argument. If it’s undefined, it defaults to the expected partition key format.\n * const operations: OperationInput[] = [\n * {\n * operationType: \"Create\",\n * resourceBody: { id: \"doc1\", name: \"sample\", key: \"A\" },\n * },\n * {\n * operationType: \"Upsert\",\n * resourceBody: { id: \"doc2\", name: \"other\", key: \"A\" },\n * },\n * ];\n *\n * await container.items.batch(operations, \"A\");\n * ```\n *\n * @param operations - List of operations. Limit 100\n * @param options - Used for modifying the request\n */\n public async batch(\n operations: OperationInput[],\n partitionKey?: PartitionKey,\n options?: RequestOptions,\n ): Promise<Response<OperationResponse[]>> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n operations.map((operation) => decorateBatchOperation(operation, options));\n partitionKey = await setPartitionKeyIfUndefined(diagnosticNode, this.container, partitionKey);\n const path = getPathFromLink(this.container.url, ResourceType.item);\n\n if (operations.length > 100) {\n throw new Error(\"Cannot run batch request with more than 100 operations per partition\");\n }\n let response: Response<OperationResponse[]>;\n try {\n if (this.clientContext.enableEncryption) {\n // returns copy to avoid encryption of original operations body passed\n operations = copyObject(operations);\n options = options || {};\n await this.container.checkAndInitializeEncryption();\n options.containerRid = this.container._rid;\n let count = 0;\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n );\n if (partitionKey) {\n const partitionKeyInternal = convertToInternalPartitionKey(partitionKey);\n const { partitionKeyList, encryptedCount } =\n await this.container.encryptionProcessor.getEncryptedPartitionKeyValue(\n partitionKeyInternal,\n );\n partitionKey = partitionKeyList;\n count += encryptedCount;\n }\n const { operations: encryptedOperations, totalPropertiesEncryptedCount } =\n await this.bulkBatchEncryptionHelper(operations);\n operations = encryptedOperations;\n count += totalPropertiesEncryptedCount;\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsEncryptOperation,\n count,\n );\n }\n\n const isPartitionLevelFailOverEnabled =\n this.clientContext.isPartitionLevelFailOverEnabled();\n const partitionKeyRangeId = await computePartitionKeyRangeId(\n diagnosticNode,\n partitionKey,\n this.partitionKeyRangeCache,\n isPartitionLevelFailOverEnabled,\n this.container,\n );\n\n response = await this.clientContext.batch({\n body: operations,\n partitionKey,\n path,\n resourceId: this.container.url,\n options,\n diagnosticNode,\n partitionKeyRangeId,\n });\n } catch (err: any) {\n if (this.clientContext.enableEncryption) {\n await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(err);\n }\n throw new Error(`Batch request error: ${err.message}`);\n }\n if (this.clientContext.enableEncryption) {\n try {\n diagnosticNode.beginEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n );\n let count = 0;\n for (const result of response.result) {\n if (result.resourceBody) {\n const { body, propertiesDecryptedCount } =\n await this.container.encryptionProcessor.decrypt(result.resourceBody);\n result.resourceBody = body;\n count += propertiesDecryptedCount;\n }\n }\n diagnosticNode.endEncryptionDiagnostics(\n Constants.Encryption.DiagnosticsDecryptOperation,\n count,\n );\n } catch (error) {\n const decryptionError = new ErrorResponse(\n `Batch response was received but response decryption failed: + ${error.message}`,\n );\n decryptionError.code = StatusCodes.ServiceUnavailable;\n throw decryptionError;\n }\n }\n return response;\n }, this.clientContext);\n }\n\n private async bulkBatchEncryptionHelper(\n operations: OperationInput[],\n ): Promise<{ operations: OperationInput[]; totalPropertiesEncryptedCount: number }> {\n let totalPropertiesEncryptedCount = 0;\n const encryptedOperations: OperationInput[] = [];\n for (const operation of operations) {\n const { operation: encryptedOp, totalPropertiesEncryptedCount: updatedCount } =\n await encryptOperationInput(\n this.container.encryptionProcessor,\n operation,\n totalPropertiesEncryptedCount,\n );\n totalPropertiesEncryptedCount = updatedCount;\n encryptedOperations.push(encryptedOp);\n }\n return { operations: encryptedOperations, totalPropertiesEncryptedCount };\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"EncryptionKeyStoreProvider.d.ts","sourceRoot":"","sources":["../../../src/encryption/EncryptionKeyStoreProvider.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC/D;;GAEG;AACH,qBAAa,0BAA0B;IASnC,OAAO,CAAC,wBAAwB;IAChC,OAAO,CAAC,eAAe;IATlB,0BAA0B,EAAE,MAAM,CAAc;IAEvD,cAAc,EAAE,MAAM,CAAC,OAAO,CAAC;IAGxB,2BAA2B,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;IAC/D,YAAY,EAAE,MAAM,CAAC;gBAElB,wBAAwB,EAAE,qBAAqB,EAC/C,eAAe,EAAE,MAAM;IASpB,OAAO,CAClB,eAAe,EAAE,MAAM,EACvB,SAAS,EAAE,sBAAsB,EACjC,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,MAAM,CAAC;IAUL,SAAS,CACpB,eAAe,EAAE,MAAM,EACvB,SAAS,EAAE,sBAAsB,EACjC,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC;YAsBJ,qBAAqB;CAapC"}
1
+ {"version":3,"file":"EncryptionKeyStoreProvider.d.ts","sourceRoot":"","sources":["../../../src/encryption/EncryptionKeyStoreProvider.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC/D;;GAEG;AACH,qBAAa,0BAA0B;IASnC,OAAO,CAAC,wBAAwB;IAChC,OAAO,CAAC,eAAe;IATlB,0BAA0B,EAAE,MAAM,CAAc;IAEvD,cAAc,EAAE,MAAM,CAAC,OAAO,CAAC;IAGxB,2BAA2B,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;IAC/D,YAAY,EAAE,MAAM,CAAC;gBAElB,wBAAwB,EAAE,qBAAqB,EAC/C,eAAe,EAAE,MAAM;IASpB,OAAO,CAClB,eAAe,EAAE,MAAM,EACvB,SAAS,EAAE,sBAAsB,EACjC,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,MAAM,CAAC;IAUL,SAAS,CACpB,eAAe,EAAE,MAAM,EACvB,SAAS,EAAE,sBAAsB,EACjC,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC;YAsBJ,qBAAqB;CAapC"}
@@ -1,6 +1,7 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT License.
3
3
  import { Constants } from "../common/index.js";
4
+ import { startBackgroundTask } from "../utils/time.js";
4
5
  /**
5
6
  * Class to store encryption keys in unwrapped form and provide an interface for wrapping and unwrapping the keys.
6
7
  */
@@ -34,7 +35,7 @@ export class EncryptionKeyStoreProvider {
34
35
  return this.unwrappedEncryptionKeyCache[encryptionKeyId][1];
35
36
  }
36
37
  async clearCacheOnTtlExpiry() {
37
- this.cacheRefresher = setInterval(() => {
38
+ this.cacheRefresher = startBackgroundTask(async () => {
38
39
  const now = new Date();
39
40
  for (const key in this.unwrappedEncryptionKeyCache) {
40
41
  if (now.getTime() - this.unwrappedEncryptionKeyCache[key][0].getTime() >
@@ -1 +1 @@
1
- {"version":3,"file":"EncryptionKeyStoreProvider.js","sourceRoot":"","sources":["../../../src/encryption/EncryptionKeyStoreProvider.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAG/C;;GAEG;AACH,MAAM,OAAO,0BAA0B;IAQrC,YACU,wBAA+C,EAC/C,eAAuB;QADvB,6BAAwB,GAAxB,wBAAwB,CAAuB;QAC/C,oBAAe,GAAf,eAAe,CAAQ;QAT1B,+BAA0B,GAAW,UAAU,CAAC;QAWrD,IAAI,CAAC,wBAAwB,GAAG,wBAAwB,CAAC;QACzD,IAAI,CAAC,YAAY,GAAG,wBAAwB,CAAC,yBAAyB,CAAC;QACvE,IAAI,CAAC,2BAA2B,GAAG,EAAE,CAAC;QACtC,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,qBAAqB,EAAE,CAAC;IAC/B,CAAC;IAEM,KAAK,CAAC,OAAO,CAClB,eAAuB,EACvB,SAAiC,EACjC,GAAW;QAEX,MAAM,aAAa,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;QAC1C,MAAM,oBAAoB,GAAG,MAAM,IAAI,CAAC,wBAAwB,CAAC,OAAO,CACtE,eAAe,EACf,SAAS,EACT,aAAa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oBACD,OAAO,IAAI,CAAC,2BAA2B,CAAC,GAAG,CAAC,CAAC;gBAC/C,CAAC;YACH,CAAC;QACH,CAAC,EAAE,SAAS,CAAC,kCAAkC,CAAC,CAAC;IACnD,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { Constants } from \"../common/index.js\";\nimport type { EncryptionKeyResolver } from \"./EncryptionKeyResolver/index.js\";\nimport type { KeyEncryptionAlgorithm } from \"./enums/index.js\";\n/**\n * Class to store encryption keys in unwrapped form and provide an interface for wrapping and unwrapping the keys.\n */\nexport class EncryptionKeyStoreProvider {\n public RsaOaepEncryptionAlgorithm: string = \"RSA-OAEP\";\n // interval for clear cache to run\n cacheRefresher: NodeJS.Timeout;\n\n // cache to store the unwrapped encryption key. Key is the path of the encryption key\n public unwrappedEncryptionKeyCache: { [key: string]: [Date, Buffer] };\n public providerName: string;\n constructor(\n private keyEncryptionKeyResolver: EncryptionKeyResolver,\n private cacheTimeToLive: number,\n ) {\n this.keyEncryptionKeyResolver = keyEncryptionKeyResolver;\n this.providerName = keyEncryptionKeyResolver.encryptionKeyResolverName;\n this.unwrappedEncryptionKeyCache = {};\n this.cacheTimeToLive = cacheTimeToLive;\n this.clearCacheOnTtlExpiry();\n }\n\n public async wrapKey(\n encryptionKeyId: string,\n algorithm: KeyEncryptionAlgorithm,\n key: Buffer,\n ): Promise<Buffer> {\n const uInt8ArrayKey = new Uint8Array(key);\n const wrappedEncryptionKey = await this.keyEncryptionKeyResolver.wrapKey(\n encryptionKeyId,\n algorithm,\n uInt8ArrayKey,\n );\n return Buffer.from(wrappedEncryptionKey);\n }\n\n public async unwrapKey(\n encryptionKeyId: string,\n algorithm: KeyEncryptionAlgorithm,\n wrappedKey: Buffer,\n ): Promise<Buffer> {\n if (this.cacheTimeToLive === 0) {\n const res = await this.keyEncryptionKeyResolver.unwrapKey(\n encryptionKeyId,\n algorithm,\n wrappedKey,\n );\n return Buffer.from(res);\n }\n if (!this.unwrappedEncryptionKeyCache[encryptionKeyId]) {\n const wrappedKeyUint8Array = new Uint8Array(wrappedKey);\n const plainEncryptionKey = await this.keyEncryptionKeyResolver.unwrapKey(\n encryptionKeyId,\n algorithm,\n wrappedKeyUint8Array,\n );\n const plainEncryptionKeyBuffer = Buffer.from(plainEncryptionKey);\n this.unwrappedEncryptionKeyCache[encryptionKeyId] = [new Date(), plainEncryptionKeyBuffer];\n }\n return this.unwrappedEncryptionKeyCache[encryptionKeyId][1];\n }\n\n private async clearCacheOnTtlExpiry(): Promise<void> {\n this.cacheRefresher = setInterval(() => {\n const now = new Date();\n for (const key in this.unwrappedEncryptionKeyCache) {\n if (\n now.getTime() - this.unwrappedEncryptionKeyCache[key][0].getTime() >\n this.cacheTimeToLive\n ) {\n delete this.unwrappedEncryptionKeyCache[key];\n }\n }\n }, Constants.EncryptionCacheRefreshIntervalInMs);\n }\n}\n"]}
1
+ {"version":3,"file":"EncryptionKeyStoreProvider.js","sourceRoot":"","sources":["../../../src/encryption/EncryptionKeyStoreProvider.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAGvD;;GAEG;AACH,MAAM,OAAO,0BAA0B;IAQrC,YACU,wBAA+C,EAC/C,eAAuB;QADvB,6BAAwB,GAAxB,wBAAwB,CAAuB;QAC/C,oBAAe,GAAf,eAAe,CAAQ;QAT1B,+BAA0B,GAAW,UAAU,CAAC;QAWrD,IAAI,CAAC,wBAAwB,GAAG,wBAAwB,CAAC;QACzD,IAAI,CAAC,YAAY,GAAG,wBAAwB,CAAC,yBAAyB,CAAC;QACvE,IAAI,CAAC,2BAA2B,GAAG,EAAE,CAAC;QACtC,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,qBAAqB,EAAE,CAAC;IAC/B,CAAC;IAEM,KAAK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C;YACvB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,2BAA2B,EAAE,CAAC;gBACnD,IACE,GAAG,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,2BAA2B,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE;oBAClE,IAAI,CAAC,eAAe,EACpB,CAAC;oBACD,OAAO,IAAI,CAAC,2BAA2B,CAAC,GAAG,CAAC,CAAC;gBAC/C,CAAC;YACH,CAAC;QACH,CAAC,EAAE,SAAS,CAAC,kCAAkC,CAAC,CAAC;IACnD,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { Constants } from \"../common/index.js\";\nimport { startBackgroundTask } from \"../utils/time.js\";\nimport type { EncryptionKeyResolver } from \"./EncryptionKeyResolver/index.js\";\nimport type { KeyEncryptionAlgorithm } from \"./enums/index.js\";\n/**\n * Class to store encryption keys in unwrapped form and provide an interface for wrapping and unwrapping the keys.\n */\nexport class EncryptionKeyStoreProvider {\n public RsaOaepEncryptionAlgorithm: string = \"RSA-OAEP\";\n // interval for clear cache to run\n cacheRefresher: NodeJS.Timeout;\n\n // cache to store the unwrapped encryption key. Key is the path of the encryption key\n public unwrappedEncryptionKeyCache: { [key: string]: [Date, Buffer] };\n public providerName: string;\n constructor(\n private keyEncryptionKeyResolver: EncryptionKeyResolver,\n private cacheTimeToLive: number,\n ) {\n this.keyEncryptionKeyResolver = keyEncryptionKeyResolver;\n this.providerName = keyEncryptionKeyResolver.encryptionKeyResolverName;\n this.unwrappedEncryptionKeyCache = {};\n this.cacheTimeToLive = cacheTimeToLive;\n this.clearCacheOnTtlExpiry();\n }\n\n public async wrapKey(\n encryptionKeyId: string,\n algorithm: KeyEncryptionAlgorithm,\n key: Buffer,\n ): Promise<Buffer> {\n const uInt8ArrayKey = new Uint8Array(key);\n const wrappedEncryptionKey = await this.keyEncryptionKeyResolver.wrapKey(\n encryptionKeyId,\n algorithm,\n uInt8ArrayKey,\n );\n return Buffer.from(wrappedEncryptionKey);\n }\n\n public async unwrapKey(\n encryptionKeyId: string,\n algorithm: KeyEncryptionAlgorithm,\n wrappedKey: Buffer,\n ): Promise<Buffer> {\n if (this.cacheTimeToLive === 0) {\n const res = await this.keyEncryptionKeyResolver.unwrapKey(\n encryptionKeyId,\n algorithm,\n wrappedKey,\n );\n return Buffer.from(res);\n }\n if (!this.unwrappedEncryptionKeyCache[encryptionKeyId]) {\n const wrappedKeyUint8Array = new Uint8Array(wrappedKey);\n const plainEncryptionKey = await this.keyEncryptionKeyResolver.unwrapKey(\n encryptionKeyId,\n algorithm,\n wrappedKeyUint8Array,\n );\n const plainEncryptionKeyBuffer = Buffer.from(plainEncryptionKey);\n this.unwrappedEncryptionKeyCache[encryptionKeyId] = [new Date(), plainEncryptionKeyBuffer];\n }\n return this.unwrappedEncryptionKeyCache[encryptionKeyId][1];\n }\n\n private async clearCacheOnTtlExpiry(): Promise<void> {\n this.cacheRefresher = startBackgroundTask(async () => {\n const now = new Date();\n for (const key in this.unwrappedEncryptionKeyCache) {\n if (\n now.getTime() - this.unwrappedEncryptionKeyCache[key][0].getTime() >\n this.cacheTimeToLive\n ) {\n delete this.unwrappedEncryptionKeyCache[key];\n }\n }\n }, Constants.EncryptionCacheRefreshIntervalInMs);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"globalPartitionEndpointManager.d.ts","sourceRoot":"","sources":["../../src/globalPartitionEndpointManager.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,sBAAsB,EAGtB,KAAK,cAAc,EACpB,MAAM,YAAY,CAAC;AAKpB;;;GAGG;AACH,qBAAa,8BAA8B;IAiBvC,OAAO,CAAC,qBAAqB;IAhB/B,OAAO,CAAC,QAAQ,CAAC,mCAAmC,CAA6C;IACjG,OAAO,CAAC,QAAQ,CAAC,0CAA0C,CAGzD;IACF,OAAO,CAAC,4BAA4B,CAAU;IAC9C,OAAO,CAAC,kCAAkC,CAAU;IACpD,OAAO,CAAC,kBAAkB,CAAW;IAC9B,uBAAuB,EAAE,MAAM,CAAC;IACvC,OAAO,CAAC,yCAAyC,CAAiB;IA2BlE;;;;OAIG;IACU,yBAAyB,CACpC,cAAc,EAAE,cAAc,EAC9B,cAAc,EAAE,sBAAsB,GACrC,OAAO,CAAC,OAAO,CAAC;IA6BnB;;;OAGG;IACU,oCAAoC,CAC/C,cAAc,EAAE,cAAc,EAC9B,cAAc,EAAE,sBAAsB,GACrC,OAAO,CAAC,cAAc,CAAC;IAiC1B;;;OAGG;IACI,OAAO,IAAI,IAAI;YAMR,8CAA8C;IA2D5D;;;OAGG;YACW,uCAAuC;IA6CrD,yEAAyE;YAC3D,qCAAqC;IA2BnD,0FAA0F;YAC5E,qCAAqC;IAmBnD;;;;OAIG;IACH,OAAO,CAAC,iDAAiD;IAazD;;;;OAIG;IACH,OAAO,CAAC,gDAAgD;IAexD;;;;;;OAMG;YACW,wDAAwD;IA8BtE;;;;;;;;OAQG;IACH,OAAO,CAAC,kCAAkC;IAY1C;;;;;OAKG;YACW,8CAA8C;CAmB7D"}
1
+ {"version":3,"file":"globalPartitionEndpointManager.d.ts","sourceRoot":"","sources":["../../src/globalPartitionEndpointManager.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,sBAAsB,EAGtB,KAAK,cAAc,EACpB,MAAM,YAAY,CAAC;AAMpB;;;GAGG;AACH,qBAAa,8BAA8B;IAiBvC,OAAO,CAAC,qBAAqB;IAhB/B,OAAO,CAAC,QAAQ,CAAC,mCAAmC,CAA6C;IACjG,OAAO,CAAC,QAAQ,CAAC,0CAA0C,CAGzD;IACF,OAAO,CAAC,4BAA4B,CAAU;IAC9C,OAAO,CAAC,kCAAkC,CAAU;IACpD,OAAO,CAAC,kBAAkB,CAAW;IAC9B,uBAAuB,EAAE,MAAM,CAAC;IACvC,OAAO,CAAC,yCAAyC,CAAiB;IA2BlE;;;;OAIG;IACU,yBAAyB,CACpC,cAAc,EAAE,cAAc,EAC9B,cAAc,EAAE,sBAAsB,GACrC,OAAO,CAAC,OAAO,CAAC;IA6BnB;;;OAGG;IACU,oCAAoC,CAC/C,cAAc,EAAE,cAAc,EAC9B,cAAc,EAAE,sBAAsB,GACrC,OAAO,CAAC,cAAc,CAAC;IAiC1B;;;OAGG;IACI,OAAO,IAAI,IAAI;YAMR,8CAA8C;IA2D5D;;;OAGG;YACW,uCAAuC;IA6CrD,yEAAyE;YAC3D,qCAAqC;IA2BnD,0FAA0F;YAC5E,qCAAqC;IAmBnD;;;;OAIG;IACH,OAAO,CAAC,iDAAiD;IAazD;;;;OAIG;IACH,OAAO,CAAC,gDAAgD;IAexD;;;;;;OAMG;YACW,wDAAwD;IA8BtE;;;;;;;;OAQG;IACH,OAAO,CAAC,kCAAkC;IAU1C;;;;;OAKG;YACW,8CAA8C;CAmB7D"}
@@ -4,6 +4,7 @@ import { OperationType, ResourceType, isReadRequest } from "./common/index.js";
4
4
  import { Constants, } from "./index.js";
5
5
  import { PartitionKeyRangeFailoverInfo } from "./PartitionKeyRangeFailoverInfo.js";
6
6
  import { normalizeEndpoint } from "./utils/checkURL.js";
7
+ import { startBackgroundTask } from "./utils/time.js";
7
8
  import { assertNotUndefined } from "./utils/typeChecks.js";
8
9
  /**
9
10
  * @hidden
@@ -243,15 +244,13 @@ export class GlobalPartitionEndpointManager {
243
244
  * The loop runs at a defined interval specified by Constants.StalePartitionUnavailabilityRefreshIntervalInMs.
244
245
  */
245
246
  initiateCircuitBreakerFailbackLoop() {
246
- this.circuitBreakerFailbackBackgroundRefresher = setInterval(() => {
247
- (async () => {
248
- try {
249
- await this.openConnectionToUnhealthyEndpointsWithFailback();
250
- }
251
- catch (err) {
252
- console.error("Failed to open connection to unhealthy endpoints: ", err);
253
- }
254
- })();
247
+ this.circuitBreakerFailbackBackgroundRefresher = startBackgroundTask(async () => {
248
+ try {
249
+ await this.openConnectionToUnhealthyEndpointsWithFailback();
250
+ }
251
+ catch (err) {
252
+ console.error("Failed to open connection to unhealthy endpoints: ", err);
253
+ }
255
254
  }, Constants.StalePartitionUnavailabilityRefreshIntervalInMs);
256
255
  }
257
256
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"globalPartitionEndpointManager.js","sourceRoot":"","sources":["../../src/globalPartitionEndpointManager.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,EACL,SAAS,GAKV,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D;;;GAGG;AACH,MAAM,OAAO,8BAA8B;IAYzC;;OAEG;IACH,YACE,OAA4B,EACpB,qBAA4C;QAA5C,0BAAqB,GAArB,qBAAqB,CAAuB;QAEpD,IAAI,CAAC,mCAAmC,GAAG,IAAI,GAAG,EAAyC,CAAC;QAC5F,IAAI,CAAC,0CAA0C,GAAG,IAAI,GAAG,EAGtD,CAAC;QAEJ,IAAI,CAAC,4BAA4B,GAAG,OAAO,CAAC,gBAAgB,CAAC,4BAA4B,CAAC;QAC1F,IAAI,CAAC,kCAAkC;YACrC,OAAO,CAAC,gBAAgB,CAAC,kCAAkC;gBAC3D,OAAO,CAAC,gBAAgB,CAAC,4BAA4B,CAAC;QAExD,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,gBAAgB,CAAC,kBAAkB,CAAC;QACtE,IAAI,CAAC,uBAAuB,GAAG,IAAI,CAAC,kBAAkB,CAAC,CAAC,CAAC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5F,IAAI,IAAI,CAAC,kCAAkC,EAAE,CAAC;YAC5C,IAAI,CAAC,kCAAkC,EAAE,CAAC;QAC5C,CAAC;IACH,CAAC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IACK,kCAAkC;QACxC,IAAI,CAAC,yCAAyC,GAAG,WAAW,CAAC,GAAG,EAAE;YAChE,CAAC,KAAK,IAAI,EAAE;gBACV,IAAI,CAAC;oBACH,MAAM,IAAI,CAAC,8CAA8C,EAAE,CAAC;gBAC9D,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,OAAO,CAAC,KAAK,CAAC,oDAAoD,EAAE,GAAG,CAAC,CAAC;gBAC3E,CAAC;YACH,CAAC,CAAC,EAAE,CAAC;QACP,CAAC,EAAE,SAAS,CAAC,+CAA+C,CAAC,CAAC;IAChE,CAAC;IAED;;;;;OAKG;IACK,KAAK,CAAC,8CAA8C;QAC1D,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,0CAA0C,CAAC,IAAI,EAAE,EAAE,CAAC;YAC7E,MAAM,iBAAiB,GAAG,IAAI,CAAC,0CAA0C,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;YACvF,IAAI,CAAC,iBAAiB;gBAAE,SAAS;YAEjC,MAAM,EAAE,uBAAuB,EAAE,GAC/B,MAAM,iBAAiB,CAAC,mCAAmC,EAAE,CAAC;YAChE,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;YAEvB,IACE,GAAG,CAAC,OAAO,EAAE,GAAG,uBAAuB;gBACvC,SAAS,CAAC,0CAA0C,EACpD,CAAC;gBACD,6FAA6F;gBAC7F,qDAAqD;gBACrD,IAAI,CAAC,0CAA0C,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YAClE,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport { OperationType, ResourceType, isReadRequest } from \"./common/index.js\";\nimport {\n Constants,\n DiagnosticNodeInternal,\n type CosmosClientOptions,\n type GlobalEndpointManager,\n type RequestContext,\n} from \"./index.js\";\nimport { PartitionKeyRangeFailoverInfo } from \"./PartitionKeyRangeFailoverInfo.js\";\nimport { normalizeEndpoint } from \"./utils/checkURL.js\";\nimport { assertNotUndefined } from \"./utils/typeChecks.js\";\n\n/**\n * @hidden\n * This class is used to failover single partitions to different regions.\n */\nexport class GlobalPartitionEndpointManager {\n private readonly partitionKeyRangeToLocationForWrite: Map<string, PartitionKeyRangeFailoverInfo>;\n private readonly partitionKeyRangeToLocationForReadAndWrite: Map<\n string,\n PartitionKeyRangeFailoverInfo\n >;\n private enablePartitionLevelFailover: boolean;\n private enablePartitionLevelCircuitBreaker: boolean;\n private preferredLocations: string[];\n public preferredLocationsCount: number;\n private circuitBreakerFailbackBackgroundRefresher: NodeJS.Timeout;\n\n /**\n * @internal\n */\n constructor(\n options: CosmosClientOptions,\n private globalEndpointManager: GlobalEndpointManager,\n ) {\n this.partitionKeyRangeToLocationForWrite = new Map<string, PartitionKeyRangeFailoverInfo>();\n this.partitionKeyRangeToLocationForReadAndWrite = new Map<\n string,\n PartitionKeyRangeFailoverInfo\n >();\n\n this.enablePartitionLevelFailover = options.connectionPolicy.enablePartitionLevelFailover;\n this.enablePartitionLevelCircuitBreaker =\n options.connectionPolicy.enablePartitionLevelCircuitBreaker ||\n options.connectionPolicy.enablePartitionLevelFailover;\n\n this.preferredLocations = options.connectionPolicy.preferredLocations;\n this.preferredLocationsCount = this.preferredLocations ? this.preferredLocations.length : 0;\n if (this.enablePartitionLevelCircuitBreaker) {\n this.initiateCircuitBreakerFailbackLoop();\n }\n }\n\n /**\n * Checks eligibility of the request for partition failover and\n * tries to mark the endpoint unavailable for the partition key range. Future\n * requests will be routed to the next location if available.\n */\n public async tryPartitionLevelFailover(\n requestContext: RequestContext,\n diagnosticNode: DiagnosticNodeInternal,\n ): Promise<boolean> {\n if (!(await this.isRequestEligibleForPartitionFailover(requestContext, true))) {\n return false;\n }\n\n const isRequestEligibleForPerPartitionAutomaticFailover =\n this.isRequestEligibleForPerPartitionAutomaticFailover(requestContext);\n const isRequestEligibleForPartitionLevelCircuitBreaker =\n this.isRequestEligibleForPartitionLevelCircuitBreaker(requestContext);\n\n if (\n isRequestEligibleForPerPartitionAutomaticFailover ||\n (isRequestEligibleForPartitionLevelCircuitBreaker &&\n (await this.incrementFailureCounterAndCheckFailover(\n requestContext,\n isRequestEligibleForPerPartitionAutomaticFailover,\n isRequestEligibleForPartitionLevelCircuitBreaker,\n )))\n ) {\n return this.tryMarkEndpointUnavailableForPartitionKeyRange(\n requestContext,\n diagnosticNode,\n isRequestEligibleForPerPartitionAutomaticFailover,\n isRequestEligibleForPartitionLevelCircuitBreaker,\n );\n }\n return false;\n }\n\n /**\n * Updates the DocumentServiceRequest routing location to point\n * new a location based if a partition level failover occurred.\n */\n public async tryAddPartitionLevelLocationOverride(\n requestContext: RequestContext,\n diagnosticNode: DiagnosticNodeInternal,\n ): Promise<RequestContext> {\n if (!(await this.isRequestEligibleForPartitionFailover(requestContext, false))) {\n return requestContext;\n }\n\n const partitionKeyRangeId = requestContext.partitionKeyRangeId;\n\n if (this.isRequestEligibleForPerPartitionAutomaticFailover(requestContext)) {\n if (this.partitionKeyRangeToLocationForWrite.has(partitionKeyRangeId)) {\n const partitionFailOver = this.partitionKeyRangeToLocationForWrite.get(partitionKeyRangeId);\n requestContext.endpoint = partitionFailOver.getCurrentEndPoint();\n diagnosticNode.recordEndpointResolution(requestContext.endpoint);\n return requestContext;\n }\n } else if (this.isRequestEligibleForPartitionLevelCircuitBreaker(requestContext)) {\n if (this.partitionKeyRangeToLocationForReadAndWrite.has(partitionKeyRangeId)) {\n const partitionFailOver =\n this.partitionKeyRangeToLocationForReadAndWrite.get(partitionKeyRangeId);\n\n const canCircuitBreakerTriggerPartitionFailOver =\n await partitionFailOver.canCircuitBreakerTriggerPartitionFailOver(\n isReadRequest(requestContext.operationType),\n );\n if (canCircuitBreakerTriggerPartitionFailOver) {\n requestContext.endpoint = partitionFailOver.getCurrentEndPoint();\n diagnosticNode.recordEndpointResolution(requestContext.endpoint);\n return requestContext;\n }\n }\n }\n return requestContext;\n }\n\n /**\n * This method clears the background refresher for circuit breaker failback\n * and stops the periodic checks for unhealthy endpoints.\n */\n public dispose(): void {\n if (this.circuitBreakerFailbackBackgroundRefresher) {\n clearTimeout(this.circuitBreakerFailbackBackgroundRefresher);\n }\n }\n\n private async tryMarkEndpointUnavailableForPartitionKeyRange(\n requestContext: RequestContext,\n diagnosticNode: DiagnosticNodeInternal,\n isRequestEligibleForPerPartitionAutomaticFailover: boolean,\n isRequestEligibleForPartitionLevelCircuitBreaker: boolean,\n ): Promise<boolean> {\n const partitionKeyRangeId = requestContext.partitionKeyRangeId;\n const failedEndPoint = requestContext.endpoint;\n\n const readLocations = await this.globalEndpointManager.getReadLocations();\n const readEndPoints: string[] = [];\n\n if (isRequestEligibleForPerPartitionAutomaticFailover) {\n // For any single master write accounts, the next locations to fail over will be the read regions configured at the account level.\n for (const location of readLocations) {\n readEndPoints.push(location.databaseAccountEndpoint);\n }\n return this.tryAddOrUpdatePartitionFailoverInfoAndMoveToNextLocation(\n partitionKeyRangeId,\n failedEndPoint,\n readEndPoints,\n this.partitionKeyRangeToLocationForWrite,\n diagnosticNode,\n );\n } else if (isRequestEligibleForPartitionLevelCircuitBreaker) {\n // For the read requests or multi-master write requests, the next locations to fail over will be the preferred locations\n // configured at the account level plus any other read locations that are not already in the preferred locations.\n if (this.preferredLocations && this.preferredLocations.length > 0) {\n for (const preferredLocation of this.preferredLocations) {\n const location = readLocations.find(\n (loc) => normalizeEndpoint(loc.name) === normalizeEndpoint(preferredLocation),\n );\n if (location) {\n readEndPoints.push(location.databaseAccountEndpoint);\n }\n }\n\n // Add the rest of the locations not already added\n for (const location of readLocations) {\n if (!readEndPoints.includes(location.databaseAccountEndpoint)) {\n readEndPoints.push(location.databaseAccountEndpoint);\n }\n }\n } else {\n for (const location of readLocations) {\n readEndPoints.push(location.databaseAccountEndpoint);\n }\n }\n return this.tryAddOrUpdatePartitionFailoverInfoAndMoveToNextLocation(\n partitionKeyRangeId,\n failedEndPoint,\n readEndPoints,\n this.partitionKeyRangeToLocationForReadAndWrite,\n diagnosticNode,\n );\n }\n return false;\n }\n\n /**\n * Increments the failure counter for the specified partition and checks if the partition can fail over.\n * This method is used to determine if a partition should be failed over based on the number of request failures.\n */\n private async incrementFailureCounterAndCheckFailover(\n requestContext: RequestContext,\n isRequestEligibleForPerPartitionAutomaticFailover: boolean,\n isRequestEligibleForPartitionLevelCircuitBreaker: boolean,\n ): Promise<boolean> {\n const partitionKeyRangeId = requestContext.partitionKeyRangeId;\n const failedEndPoint = requestContext.endpoint;\n let partitionKeyRangeFailoverInfo: PartitionKeyRangeFailoverInfo;\n\n if (isRequestEligibleForPerPartitionAutomaticFailover) {\n if (!this.partitionKeyRangeToLocationForWrite.has(partitionKeyRangeId)) {\n // If the partition key range is not already in the map, add it\n const failoverInfo = new PartitionKeyRangeFailoverInfo(failedEndPoint);\n this.partitionKeyRangeToLocationForWrite.set(partitionKeyRangeId, failoverInfo);\n }\n partitionKeyRangeFailoverInfo =\n this.partitionKeyRangeToLocationForWrite.get(partitionKeyRangeId);\n } else if (isRequestEligibleForPartitionLevelCircuitBreaker) {\n if (!this.partitionKeyRangeToLocationForReadAndWrite.has(partitionKeyRangeId)) {\n // If the partition key range is not already in the map, add it\n const failoverInfo = new PartitionKeyRangeFailoverInfo(failedEndPoint);\n this.partitionKeyRangeToLocationForReadAndWrite.set(partitionKeyRangeId, failoverInfo);\n }\n partitionKeyRangeFailoverInfo =\n this.partitionKeyRangeToLocationForReadAndWrite.get(partitionKeyRangeId);\n } else {\n return false;\n }\n\n assertNotUndefined(\n partitionKeyRangeFailoverInfo,\n \"partitionKeyRangeFailoverInfo should be set if failover flags are true.\",\n );\n\n const currentTimeInMilliseconds = Date.now();\n await partitionKeyRangeFailoverInfo.incrementRequestFailureCounts(\n isReadRequest(requestContext.operationType),\n currentTimeInMilliseconds,\n );\n\n return partitionKeyRangeFailoverInfo.canCircuitBreakerTriggerPartitionFailOver(\n isReadRequest(requestContext.operationType),\n );\n }\n\n /** Validates if the given request is eligible for partition failover. */\n private async isRequestEligibleForPartitionFailover(\n requestContext: RequestContext,\n shouldValidateFailedLocation: boolean,\n ): Promise<boolean> {\n if (\n !requestContext ||\n !requestContext.operationType ||\n !requestContext.resourceType ||\n !requestContext.partitionKeyRangeId\n ) {\n return false;\n }\n\n const canUsePartitionLevelFailoverLocations = await this.canUsePartitionLevelFailoverLocations(\n requestContext.operationType,\n requestContext.resourceType,\n );\n if (!canUsePartitionLevelFailoverLocations) {\n return false;\n }\n\n if (shouldValidateFailedLocation && !requestContext.endpoint) {\n return false;\n }\n return true;\n }\n\n /** Determines if partition level failover locations can be used for the given request. */\n private async canUsePartitionLevelFailoverLocations(\n operationType?: OperationType,\n resourceType?: ResourceType,\n ): Promise<boolean> {\n const readEndPoints = await this.globalEndpointManager.getReadEndpoints();\n if (readEndPoints.length <= 1) {\n return false;\n }\n if (\n resourceType === ResourceType.item ||\n (resourceType === ResourceType.sproc && operationType === OperationType.Execute)\n ) {\n // Right now, for single-master only reads are supported for circuit breaker, and writes are supported for automatic.\n // failover. For multi master, both reads and writes are supported. Hence return true for both the cases.\n return true;\n }\n return false;\n }\n\n /**\n * Determines if a request is eligible for per-partition automatic failover.\n * A request is eligible if it is a write request, partition level failover is enabled,\n * and the global endpoint manager cannot use multiple write locations for the request.\n */\n private isRequestEligibleForPerPartitionAutomaticFailover(\n requestContext: RequestContext,\n ): boolean {\n return (\n this.enablePartitionLevelFailover &&\n !isReadRequest(requestContext.operationType) &&\n !this.globalEndpointManager.canUseMultipleWriteLocations(\n requestContext.resourceType,\n requestContext.operationType,\n )\n );\n }\n\n /**\n * Determines if a request is eligible for partition-level circuit breaker.\n * This method checks if partition-level circuit breaker is enabled, and if the request is a read-only request or\n * the global endpoint manager can use multiple write locations for the request.\n */\n private isRequestEligibleForPartitionLevelCircuitBreaker(\n requestContext: RequestContext,\n ): boolean {\n if (!this.enablePartitionLevelCircuitBreaker) {\n return false;\n }\n if (isReadRequest(requestContext.operationType)) {\n return true;\n }\n return this.globalEndpointManager.canUseMultipleWriteLocations(\n requestContext.resourceType,\n requestContext.operationType,\n );\n }\n\n /**\n * Attempts to add or update the partition failover information and move to the next available location.\n * This method checks if the current location for the partition key range has failed and updates the failover\n * information to route the request to the next available location. If all locations have been tried, it removes\n * the failover information for the partition key range. Return True if the failover information was successfully\n * updated and the request was routed to a new location, otherwise false.\n */\n private async tryAddOrUpdatePartitionFailoverInfoAndMoveToNextLocation(\n partitionKeyRangeId: string,\n failedEndPoint: string,\n nextEndPoints: readonly string[],\n partitionKeyRangeToLocation: Map<string, PartitionKeyRangeFailoverInfo>,\n diagnosticNode: DiagnosticNodeInternal,\n ): Promise<boolean> {\n if (!partitionKeyRangeToLocation.has(partitionKeyRangeId)) {\n // If the partition key range is not already in the map, add it\n const failoverInfo = new PartitionKeyRangeFailoverInfo(failedEndPoint);\n partitionKeyRangeToLocation.set(partitionKeyRangeId, failoverInfo);\n }\n const partitionFailOver = partitionKeyRangeToLocation.get(partitionKeyRangeId);\n\n // Will return true if it was able to update to a new region\n if (\n await partitionFailOver.tryMoveNextLocation(\n nextEndPoints,\n failedEndPoint,\n diagnosticNode,\n partitionKeyRangeId,\n )\n ) {\n return true;\n }\n // All the locations have been tried. Remove the override information\n partitionKeyRangeToLocation.delete(partitionKeyRangeId);\n return false;\n }\n\n /**\n * Initiates a background loop that periodically checks for unhealthy endpoints\n * and attempts to open connections to them. If a connection is successfully\n * established, it initiates a failback to the original location for the partition key range.\n * This is useful for scenarios where a partition key range has been marked as unavailable\n * due to a circuit breaker, and we want to periodically check if the original location\n * has become healthy again.\n * The loop runs at a defined interval specified by Constants.StalePartitionUnavailabilityRefreshIntervalInMs.\n */\n private initiateCircuitBreakerFailbackLoop(): void {\n this.circuitBreakerFailbackBackgroundRefresher = setInterval(() => {\n (async () => {\n try {\n await this.openConnectionToUnhealthyEndpointsWithFailback();\n } catch (err) {\n console.error(\"Failed to open connection to unhealthy endpoints: \", err);\n }\n })();\n }, Constants.StalePartitionUnavailabilityRefreshIntervalInMs);\n }\n\n /**\n * Attempts to open connections to unhealthy endpoints and initiates failback if the connections are successful.\n * This method checks the partition key ranges that have failed locations and tries to re-establish connections\n * to those locations. If a connection is successfully re-established, it initiates a failback to the original\n * location for the partition key range.\n */\n private async openConnectionToUnhealthyEndpointsWithFailback(): Promise<void> {\n for (const pkRange of this.partitionKeyRangeToLocationForReadAndWrite.keys()) {\n const partitionFailover = this.partitionKeyRangeToLocationForReadAndWrite.get(pkRange);\n if (!partitionFailover) continue;\n\n const { firstRequestFailureTime } =\n await partitionFailover.snapshotPartitionFailoverTimestamps();\n const now = new Date();\n\n if (\n now.getTime() - firstRequestFailureTime >\n Constants.AllowedPartitionUnavailabilityDurationInMs\n ) {\n // Un-deterministically marking the original failed endpoint for the PkRange back to healthy.\n // Initiate Failback to the original failed location.\n this.partitionKeyRangeToLocationForReadAndWrite.delete(pkRange);\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"globalPartitionEndpointManager.js","sourceRoot":"","sources":["../../src/globalPartitionEndpointManager.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,EACL,SAAS,GAKV,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D;;;GAGG;AACH,MAAM,OAAO,8BAA8B;IAYzC;;OAEG;IACH,YACE,OAA4B,EACpB,qBAA4C;QAA5C,0BAAqB,GAArB,qBAAqB,CAAuB;QAEpD,IAAI,CAAC,mCAAmC,GAAG,IAAI,GAAG,EAAyC,CAAC;QAC5F,IAAI,CAAC,0CAA0C,GAAG,IAAI,GAAG,EAGtD,CAAC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OAAO,EAAE,GAAG,uBAAuB;gBACvC,SAAS,CAAC,0CAA0C,EACpD,CAAC;gBACD,6FAA6F;gBAC7F,qDAAqD;gBACrD,IAAI,CAAC,0CAA0C,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YAClE,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport { OperationType, ResourceType, isReadRequest } from \"./common/index.js\";\nimport {\n Constants,\n DiagnosticNodeInternal,\n type CosmosClientOptions,\n type GlobalEndpointManager,\n type RequestContext,\n} from \"./index.js\";\nimport { PartitionKeyRangeFailoverInfo } from \"./PartitionKeyRangeFailoverInfo.js\";\nimport { normalizeEndpoint } from \"./utils/checkURL.js\";\nimport { startBackgroundTask } from \"./utils/time.js\";\nimport { assertNotUndefined } from \"./utils/typeChecks.js\";\n\n/**\n * @hidden\n * This class is used to failover single partitions to different regions.\n */\nexport class GlobalPartitionEndpointManager {\n private readonly partitionKeyRangeToLocationForWrite: Map<string, PartitionKeyRangeFailoverInfo>;\n private readonly partitionKeyRangeToLocationForReadAndWrite: Map<\n string,\n PartitionKeyRangeFailoverInfo\n >;\n private enablePartitionLevelFailover: boolean;\n private enablePartitionLevelCircuitBreaker: boolean;\n private preferredLocations: string[];\n public preferredLocationsCount: number;\n private circuitBreakerFailbackBackgroundRefresher: NodeJS.Timeout;\n\n /**\n * @internal\n */\n constructor(\n options: CosmosClientOptions,\n private globalEndpointManager: GlobalEndpointManager,\n ) {\n this.partitionKeyRangeToLocationForWrite = new Map<string, PartitionKeyRangeFailoverInfo>();\n this.partitionKeyRangeToLocationForReadAndWrite = new Map<\n string,\n PartitionKeyRangeFailoverInfo\n >();\n\n this.enablePartitionLevelFailover = options.connectionPolicy.enablePartitionLevelFailover;\n this.enablePartitionLevelCircuitBreaker =\n options.connectionPolicy.enablePartitionLevelCircuitBreaker ||\n options.connectionPolicy.enablePartitionLevelFailover;\n\n this.preferredLocations = options.connectionPolicy.preferredLocations;\n this.preferredLocationsCount = this.preferredLocations ? this.preferredLocations.length : 0;\n if (this.enablePartitionLevelCircuitBreaker) {\n this.initiateCircuitBreakerFailbackLoop();\n }\n }\n\n /**\n * Checks eligibility of the request for partition failover and\n * tries to mark the endpoint unavailable for the partition key range. Future\n * requests will be routed to the next location if available.\n */\n public async tryPartitionLevelFailover(\n requestContext: RequestContext,\n diagnosticNode: DiagnosticNodeInternal,\n ): Promise<boolean> {\n if (!(await this.isRequestEligibleForPartitionFailover(requestContext, true))) {\n return false;\n }\n\n const isRequestEligibleForPerPartitionAutomaticFailover =\n this.isRequestEligibleForPerPartitionAutomaticFailover(requestContext);\n const isRequestEligibleForPartitionLevelCircuitBreaker =\n this.isRequestEligibleForPartitionLevelCircuitBreaker(requestContext);\n\n if (\n isRequestEligibleForPerPartitionAutomaticFailover ||\n (isRequestEligibleForPartitionLevelCircuitBreaker &&\n (await this.incrementFailureCounterAndCheckFailover(\n requestContext,\n isRequestEligibleForPerPartitionAutomaticFailover,\n isRequestEligibleForPartitionLevelCircuitBreaker,\n )))\n ) {\n return this.tryMarkEndpointUnavailableForPartitionKeyRange(\n requestContext,\n diagnosticNode,\n isRequestEligibleForPerPartitionAutomaticFailover,\n isRequestEligibleForPartitionLevelCircuitBreaker,\n );\n }\n return false;\n }\n\n /**\n * Updates the DocumentServiceRequest routing location to point\n * new a location based if a partition level failover occurred.\n */\n public async tryAddPartitionLevelLocationOverride(\n requestContext: RequestContext,\n diagnosticNode: DiagnosticNodeInternal,\n ): Promise<RequestContext> {\n if (!(await this.isRequestEligibleForPartitionFailover(requestContext, false))) {\n return requestContext;\n }\n\n const partitionKeyRangeId = requestContext.partitionKeyRangeId;\n\n if (this.isRequestEligibleForPerPartitionAutomaticFailover(requestContext)) {\n if (this.partitionKeyRangeToLocationForWrite.has(partitionKeyRangeId)) {\n const partitionFailOver = this.partitionKeyRangeToLocationForWrite.get(partitionKeyRangeId);\n requestContext.endpoint = partitionFailOver.getCurrentEndPoint();\n diagnosticNode.recordEndpointResolution(requestContext.endpoint);\n return requestContext;\n }\n } else if (this.isRequestEligibleForPartitionLevelCircuitBreaker(requestContext)) {\n if (this.partitionKeyRangeToLocationForReadAndWrite.has(partitionKeyRangeId)) {\n const partitionFailOver =\n this.partitionKeyRangeToLocationForReadAndWrite.get(partitionKeyRangeId);\n\n const canCircuitBreakerTriggerPartitionFailOver =\n await partitionFailOver.canCircuitBreakerTriggerPartitionFailOver(\n isReadRequest(requestContext.operationType),\n );\n if (canCircuitBreakerTriggerPartitionFailOver) {\n requestContext.endpoint = partitionFailOver.getCurrentEndPoint();\n diagnosticNode.recordEndpointResolution(requestContext.endpoint);\n return requestContext;\n }\n }\n }\n return requestContext;\n }\n\n /**\n * This method clears the background refresher for circuit breaker failback\n * and stops the periodic checks for unhealthy endpoints.\n */\n public dispose(): void {\n if (this.circuitBreakerFailbackBackgroundRefresher) {\n clearTimeout(this.circuitBreakerFailbackBackgroundRefresher);\n }\n }\n\n private async tryMarkEndpointUnavailableForPartitionKeyRange(\n requestContext: RequestContext,\n diagnosticNode: DiagnosticNodeInternal,\n isRequestEligibleForPerPartitionAutomaticFailover: boolean,\n isRequestEligibleForPartitionLevelCircuitBreaker: boolean,\n ): Promise<boolean> {\n const partitionKeyRangeId = requestContext.partitionKeyRangeId;\n const failedEndPoint = requestContext.endpoint;\n\n const readLocations = await this.globalEndpointManager.getReadLocations();\n const readEndPoints: string[] = [];\n\n if (isRequestEligibleForPerPartitionAutomaticFailover) {\n // For any single master write accounts, the next locations to fail over will be the read regions configured at the account level.\n for (const location of readLocations) {\n readEndPoints.push(location.databaseAccountEndpoint);\n }\n return this.tryAddOrUpdatePartitionFailoverInfoAndMoveToNextLocation(\n partitionKeyRangeId,\n failedEndPoint,\n readEndPoints,\n this.partitionKeyRangeToLocationForWrite,\n diagnosticNode,\n );\n } else if (isRequestEligibleForPartitionLevelCircuitBreaker) {\n // For the read requests or multi-master write requests, the next locations to fail over will be the preferred locations\n // configured at the account level plus any other read locations that are not already in the preferred locations.\n if (this.preferredLocations && this.preferredLocations.length > 0) {\n for (const preferredLocation of this.preferredLocations) {\n const location = readLocations.find(\n (loc) => normalizeEndpoint(loc.name) === normalizeEndpoint(preferredLocation),\n );\n if (location) {\n readEndPoints.push(location.databaseAccountEndpoint);\n }\n }\n\n // Add the rest of the locations not already added\n for (const location of readLocations) {\n if (!readEndPoints.includes(location.databaseAccountEndpoint)) {\n readEndPoints.push(location.databaseAccountEndpoint);\n }\n }\n } else {\n for (const location of readLocations) {\n readEndPoints.push(location.databaseAccountEndpoint);\n }\n }\n return this.tryAddOrUpdatePartitionFailoverInfoAndMoveToNextLocation(\n partitionKeyRangeId,\n failedEndPoint,\n readEndPoints,\n this.partitionKeyRangeToLocationForReadAndWrite,\n diagnosticNode,\n );\n }\n return false;\n }\n\n /**\n * Increments the failure counter for the specified partition and checks if the partition can fail over.\n * This method is used to determine if a partition should be failed over based on the number of request failures.\n */\n private async incrementFailureCounterAndCheckFailover(\n requestContext: RequestContext,\n isRequestEligibleForPerPartitionAutomaticFailover: boolean,\n isRequestEligibleForPartitionLevelCircuitBreaker: boolean,\n ): Promise<boolean> {\n const partitionKeyRangeId = requestContext.partitionKeyRangeId;\n const failedEndPoint = requestContext.endpoint;\n let partitionKeyRangeFailoverInfo: PartitionKeyRangeFailoverInfo;\n\n if (isRequestEligibleForPerPartitionAutomaticFailover) {\n if (!this.partitionKeyRangeToLocationForWrite.has(partitionKeyRangeId)) {\n // If the partition key range is not already in the map, add it\n const failoverInfo = new PartitionKeyRangeFailoverInfo(failedEndPoint);\n this.partitionKeyRangeToLocationForWrite.set(partitionKeyRangeId, failoverInfo);\n }\n partitionKeyRangeFailoverInfo =\n this.partitionKeyRangeToLocationForWrite.get(partitionKeyRangeId);\n } else if (isRequestEligibleForPartitionLevelCircuitBreaker) {\n if (!this.partitionKeyRangeToLocationForReadAndWrite.has(partitionKeyRangeId)) {\n // If the partition key range is not already in the map, add it\n const failoverInfo = new PartitionKeyRangeFailoverInfo(failedEndPoint);\n this.partitionKeyRangeToLocationForReadAndWrite.set(partitionKeyRangeId, failoverInfo);\n }\n partitionKeyRangeFailoverInfo =\n this.partitionKeyRangeToLocationForReadAndWrite.get(partitionKeyRangeId);\n } else {\n return false;\n }\n\n assertNotUndefined(\n partitionKeyRangeFailoverInfo,\n \"partitionKeyRangeFailoverInfo should be set if failover flags are true.\",\n );\n\n const currentTimeInMilliseconds = Date.now();\n await partitionKeyRangeFailoverInfo.incrementRequestFailureCounts(\n isReadRequest(requestContext.operationType),\n currentTimeInMilliseconds,\n );\n\n return partitionKeyRangeFailoverInfo.canCircuitBreakerTriggerPartitionFailOver(\n isReadRequest(requestContext.operationType),\n );\n }\n\n /** Validates if the given request is eligible for partition failover. */\n private async isRequestEligibleForPartitionFailover(\n requestContext: RequestContext,\n shouldValidateFailedLocation: boolean,\n ): Promise<boolean> {\n if (\n !requestContext ||\n !requestContext.operationType ||\n !requestContext.resourceType ||\n !requestContext.partitionKeyRangeId\n ) {\n return false;\n }\n\n const canUsePartitionLevelFailoverLocations = await this.canUsePartitionLevelFailoverLocations(\n requestContext.operationType,\n requestContext.resourceType,\n );\n if (!canUsePartitionLevelFailoverLocations) {\n return false;\n }\n\n if (shouldValidateFailedLocation && !requestContext.endpoint) {\n return false;\n }\n return true;\n }\n\n /** Determines if partition level failover locations can be used for the given request. */\n private async canUsePartitionLevelFailoverLocations(\n operationType?: OperationType,\n resourceType?: ResourceType,\n ): Promise<boolean> {\n const readEndPoints = await this.globalEndpointManager.getReadEndpoints();\n if (readEndPoints.length <= 1) {\n return false;\n }\n if (\n resourceType === ResourceType.item ||\n (resourceType === ResourceType.sproc && operationType === OperationType.Execute)\n ) {\n // Right now, for single-master only reads are supported for circuit breaker, and writes are supported for automatic.\n // failover. For multi master, both reads and writes are supported. Hence return true for both the cases.\n return true;\n }\n return false;\n }\n\n /**\n * Determines if a request is eligible for per-partition automatic failover.\n * A request is eligible if it is a write request, partition level failover is enabled,\n * and the global endpoint manager cannot use multiple write locations for the request.\n */\n private isRequestEligibleForPerPartitionAutomaticFailover(\n requestContext: RequestContext,\n ): boolean {\n return (\n this.enablePartitionLevelFailover &&\n !isReadRequest(requestContext.operationType) &&\n !this.globalEndpointManager.canUseMultipleWriteLocations(\n requestContext.resourceType,\n requestContext.operationType,\n )\n );\n }\n\n /**\n * Determines if a request is eligible for partition-level circuit breaker.\n * This method checks if partition-level circuit breaker is enabled, and if the request is a read-only request or\n * the global endpoint manager can use multiple write locations for the request.\n */\n private isRequestEligibleForPartitionLevelCircuitBreaker(\n requestContext: RequestContext,\n ): boolean {\n if (!this.enablePartitionLevelCircuitBreaker) {\n return false;\n }\n if (isReadRequest(requestContext.operationType)) {\n return true;\n }\n return this.globalEndpointManager.canUseMultipleWriteLocations(\n requestContext.resourceType,\n requestContext.operationType,\n );\n }\n\n /**\n * Attempts to add or update the partition failover information and move to the next available location.\n * This method checks if the current location for the partition key range has failed and updates the failover\n * information to route the request to the next available location. If all locations have been tried, it removes\n * the failover information for the partition key range. Return True if the failover information was successfully\n * updated and the request was routed to a new location, otherwise false.\n */\n private async tryAddOrUpdatePartitionFailoverInfoAndMoveToNextLocation(\n partitionKeyRangeId: string,\n failedEndPoint: string,\n nextEndPoints: readonly string[],\n partitionKeyRangeToLocation: Map<string, PartitionKeyRangeFailoverInfo>,\n diagnosticNode: DiagnosticNodeInternal,\n ): Promise<boolean> {\n if (!partitionKeyRangeToLocation.has(partitionKeyRangeId)) {\n // If the partition key range is not already in the map, add it\n const failoverInfo = new PartitionKeyRangeFailoverInfo(failedEndPoint);\n partitionKeyRangeToLocation.set(partitionKeyRangeId, failoverInfo);\n }\n const partitionFailOver = partitionKeyRangeToLocation.get(partitionKeyRangeId);\n\n // Will return true if it was able to update to a new region\n if (\n await partitionFailOver.tryMoveNextLocation(\n nextEndPoints,\n failedEndPoint,\n diagnosticNode,\n partitionKeyRangeId,\n )\n ) {\n return true;\n }\n // All the locations have been tried. Remove the override information\n partitionKeyRangeToLocation.delete(partitionKeyRangeId);\n return false;\n }\n\n /**\n * Initiates a background loop that periodically checks for unhealthy endpoints\n * and attempts to open connections to them. If a connection is successfully\n * established, it initiates a failback to the original location for the partition key range.\n * This is useful for scenarios where a partition key range has been marked as unavailable\n * due to a circuit breaker, and we want to periodically check if the original location\n * has become healthy again.\n * The loop runs at a defined interval specified by Constants.StalePartitionUnavailabilityRefreshIntervalInMs.\n */\n private initiateCircuitBreakerFailbackLoop(): void {\n this.circuitBreakerFailbackBackgroundRefresher = startBackgroundTask(async () => {\n try {\n await this.openConnectionToUnhealthyEndpointsWithFailback();\n } catch (err) {\n console.error(\"Failed to open connection to unhealthy endpoints: \", err);\n }\n }, Constants.StalePartitionUnavailabilityRefreshIntervalInMs);\n }\n\n /**\n * Attempts to open connections to unhealthy endpoints and initiates failback if the connections are successful.\n * This method checks the partition key ranges that have failed locations and tries to re-establish connections\n * to those locations. If a connection is successfully re-established, it initiates a failback to the original\n * location for the partition key range.\n */\n private async openConnectionToUnhealthyEndpointsWithFailback(): Promise<void> {\n for (const pkRange of this.partitionKeyRangeToLocationForReadAndWrite.keys()) {\n const partitionFailover = this.partitionKeyRangeToLocationForReadAndWrite.get(pkRange);\n if (!partitionFailover) continue;\n\n const { firstRequestFailureTime } =\n await partitionFailover.snapshotPartitionFailoverTimestamps();\n const now = new Date();\n\n if (\n now.getTime() - firstRequestFailureTime >\n Constants.AllowedPartitionUnavailabilityDurationInMs\n ) {\n // Un-deterministically marking the original failed endpoint for the PkRange back to healthy.\n // Initiate Failback to the original failed location.\n this.partitionKeyRangeToLocationForReadAndWrite.delete(pkRange);\n }\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../../../src/request/request.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,UAAU,EAEV,aAAa,EACb,YAAY,EAEb,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CA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C;AAClE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,EAAiB,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,YAAY,CAAC;AAgBlF,cAAc;AACd,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAKpF;AAED;;GAEG;AACH,UAAU,iBAAiB;IACzB,aAAa,EAAE,mBAAmB,CAAC;IACnC,cAAc,EAAE,aAAa,CAAC;IAC9B,IAAI,EAAE,UAAU,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,YAAY,CAAC;IAC3B,OAAO,EAAE,cAAc,GAAG,WAAW,CAAC;IACtC,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,yBAAyB,CAAC,EAAE,OAAO,CAAC;IACpC,YAAY,CAAC,EAAE,oBAAoB,CAAC;CACrC;AAID;;GAEG;AACH,wBAAsB,UAAU,CAAC,EAC/B,aAAa,EACb,cAAc,EACd,IAAI,EACJ,IAAI,EACJ,UAAU,EACV,YAAY,EACZ,OAAY,EACZ,aAAa,EACb,mBAAmB,EACnB,yBAAyB,EACzB,YAAY,GACb,EAAE,iBAAiB,GAAG,OAAO,CAAC,aAAa,CAAC,CAoM5C"}
@@ -134,6 +134,9 @@ export async function getHeaders({ clientOptions, defaultHeaders, verb, path, re
134
134
  if (partitionKey !== undefined && !headers[Constants.HttpHeaders.PartitionKey]) {
135
135
  headers[Constants.HttpHeaders.PartitionKey] = jsonStringifyAndEscapeNonASCII(partitionKey);
136
136
  }
137
+ else if (partitionKeyRangeId !== undefined) {
138
+ headers[Constants.HttpHeaders.PartitionKeyRangeID] = partitionKeyRangeId;
139
+ }
137
140
  if (clientOptions.key || clientOptions.tokenProvider) {
138
141
  headers[Constants.HttpHeaders.XDate] = new Date().toUTCString();
139
142
  }
@@ -145,9 +148,6 @@ export async function getHeaders({ clientOptions, defaultHeaders, verb, path, re
145
148
  if (!headers[Constants.HttpHeaders.Accept]) {
146
149
  headers[Constants.HttpHeaders.Accept] = JsonContentType;
147
150
  }
148
- if (partitionKeyRangeId !== undefined) {
149
- headers[Constants.HttpHeaders.PartitionKeyRangeID] = partitionKeyRangeId;
150
- }
151
151
  if (options.enableScriptLogging) {
152
152
  headers[Constants.HttpHeaders.EnableScriptLogging] = options.enableScriptLogging;
153
153
  }