@azure/cosmos 4.5.0-alpha.20250717.1 → 4.5.0

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 +4 -4
@@ -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;QA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,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,C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AAoD,EAAE,GAAG,CAAC,CAAC;YAC3E,CAAC;QACH,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 { 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,CAAC;AACrE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;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,oBAAo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AAa,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
  }
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","sourceRoot":"","sources":["../../../src/request/request.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EACL,SAAS,EACT,UAAU,EACV,8BAA8B,EAC9B,aAAa,EACb,YAAY,EACZ,wBAAwB,GACzB,MAAM,oBAAoB,CAAC;AAI5B,OAAO,EAAE,aAAa,EAAyC,MAAM,YAAY,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACp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,EAAE,UAAU,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IAC7F,CAAC;IAED,IACE,YAAY,KAAK,YAAY,CAAC,IAAI;QAClC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,+BAA+B,CAAC;QAC9E,CAAC,OAAO,CAAC,6BAA6B,EACtC,CAAC;QACD,IAAI,aAAa,KAAK,aAAa,CAAC,KAAK,EAAE,CAAC;YAC1C,OAAO,CAAC,SAAS,CAAC,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,mBAAmB,CAAC;QACpF,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,aAAa,CACrB,mGAAmG,CACpG,CAAC;QACJ,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport { setAuthorizationHeader } from \"../auth.js\";\nimport {\n Constants,\n HTTPMethod,\n jsonStringifyAndEscapeNonASCII,\n OperationType,\n ResourceType,\n SDKSupportedCapabilities,\n} from \"../common/index.js\";\nimport type { CosmosClientOptions } from \"../CosmosClientOptions.js\";\nimport type { PartitionKeyInternal } from \"../documents/index.js\";\nimport type { CosmosHeaders } from \"../queryExecutionContext/index.js\";\nimport { ErrorResponse, type FeedOptions, type RequestOptions } from \"./index.js\";\nimport { defaultLogger } from \"../common/logger.js\";\nimport { ChangeFeedMode } from \"../client/ChangeFeed/index.js\";\n// ----------------------------------------------------------------------------\n// Utility methods\n//\n\n/** @hidden */\nfunction javaScriptFriendlyJSONStringify(s: unknown): string {\n // two line terminators (Line separator and Paragraph separator) are not needed to be escaped in JSON\n // but are needed to be escaped in JavaScript.\n return JSON.stringify(s)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\n/** @hidden */\nexport function bodyFromData(data: Buffer | string | Record<string, unknown>): string {\n if (typeof data === \"object\") {\n return javaScriptFriendlyJSONStringify(data);\n }\n return data;\n}\n\n/**\n * @hidden\n */\ninterface GetHeadersOptions {\n clientOptions: CosmosClientOptions;\n defaultHeaders: CosmosHeaders;\n verb: HTTPMethod;\n path: string;\n resourceId: string;\n resourceType: ResourceType;\n options: RequestOptions & FeedOptions;\n operationType?: OperationType;\n partitionKeyRangeId?: string;\n useMultipleWriteLocations?: boolean;\n partitionKey?: PartitionKeyInternal;\n}\n\nconst JsonContentType = \"application/json\";\n\n/**\n * @hidden\n */\nexport async function getHeaders({\n clientOptions,\n defaultHeaders,\n verb,\n path,\n resourceId,\n resourceType,\n options = {},\n operationType,\n partitionKeyRangeId,\n useMultipleWriteLocations,\n partitionKey,\n}: GetHeadersOptions): Promise<CosmosHeaders> {\n const headers: CosmosHeaders = {\n [Constants.HttpHeaders.ResponseContinuationTokenLimitInKB]: 1,\n [Constants.HttpHeaders.EnableCrossPartitionQuery]: true,\n ...defaultHeaders,\n };\n\n // Adding SDKSupportedCapabilities header to hint that SDK supports partition merge\n headers[Constants.HttpHeaders.SDKSupportedCapabilities] = SDKSupportedCapabilities.PartitionMerge;\n\n if (useMultipleWriteLocations) {\n headers[Constants.HttpHeaders.ALLOW_MULTIPLE_WRITES] = true;\n }\n\n if (options.continuationTokenLimitInKB) {\n headers[Constants.HttpHeaders.ResponseContinuationTokenLimitInKB] =\n options.continuationTokenLimitInKB;\n }\n if (options.continuationToken) {\n headers[Constants.HttpHeaders.Continuation] = options.continuationToken;\n } else if (options.continuation) {\n headers[Constants.HttpHeaders.Continuation] = options.continuation;\n }\n\n if (options.preTriggerInclude) {\n headers[Constants.HttpHeaders.PreTriggerInclude] =\n options.preTriggerInclude.constructor === Array\n ? (options.preTriggerInclude as string[]).join(\",\")\n : (options.preTriggerInclude as string);\n }\n\n if (options.postTriggerInclude) {\n headers[Constants.HttpHeaders.PostTriggerInclude] =\n options.postTriggerInclude.constructor === Array\n ? (options.postTriggerInclude as string[]).join(\",\")\n : (options.postTriggerInclude as string);\n }\n\n if (options.offerType) {\n headers[Constants.HttpHeaders.OfferType] = options.offerType;\n }\n\n if (options.offerThroughput) {\n headers[Constants.HttpHeaders.OfferThroughput] = options.offerThroughput;\n }\n\n if (options.maxItemCount) {\n headers[Constants.HttpHeaders.PageSize] = options.maxItemCount;\n }\n\n if (options.accessCondition) {\n if (options.accessCondition.type === \"IfMatch\") {\n headers[Constants.HttpHeaders.IfMatch] = options.accessCondition.condition;\n } else {\n headers[Constants.HttpHeaders.IfNoneMatch] = options.accessCondition.condition;\n }\n }\n\n if (options.useAllVersionsAndDeletesFeed) {\n // headers required for reading feed in allVersionsAndDeletes mode\n headers[Constants.HttpHeaders.A_IM] = ChangeFeedMode.AllVersionsAndDeletes;\n headers[Constants.HttpHeaders.ChangeFeedWireFormatVersion] =\n Constants.AllVersionsAndDeletesChangeFeedWireFormatVersion;\n }\n\n if (options.useIncrementalFeed || options.useLatestVersionFeed) {\n headers[Constants.HttpHeaders.A_IM] = ChangeFeedMode.LatestVersion;\n }\n\n if (options.indexingDirective) {\n headers[Constants.HttpHeaders.IndexingDirective] = options.indexingDirective;\n }\n\n if (options.consistencyLevel) {\n headers[Constants.HttpHeaders.ConsistencyLevel] = options.consistencyLevel;\n }\n\n if (options.priorityLevel) {\n headers[Constants.HttpHeaders.PriorityLevel] = options.priorityLevel;\n }\n\n if (options.throughputBucket) {\n headers[Constants.HttpHeaders.ThroughputBucket] = options.throughputBucket;\n }\n\n if (options.maxIntegratedCacheStalenessInMs && resourceType === ResourceType.item) {\n if (typeof options.maxIntegratedCacheStalenessInMs === \"number\") {\n headers[Constants.HttpHeaders.DedicatedGatewayPerRequestCacheStaleness] =\n options.maxIntegratedCacheStalenessInMs.toString();\n } else {\n defaultLogger.error(\n `RangeError: maxIntegratedCacheStalenessInMs \"${options.maxIntegratedCacheStalenessInMs}\" is not a valid parameter.`,\n );\n headers[Constants.HttpHeaders.DedicatedGatewayPerRequestCacheStaleness] = \"null\";\n }\n }\n\n if (options.bypassIntegratedCache) {\n headers[Constants.HttpHeaders.DedicatedGatewayPerRequestBypassCache] =\n options.bypassIntegratedCache.toString();\n }\n\n if (options.resourceTokenExpirySeconds) {\n headers[Constants.HttpHeaders.ResourceTokenExpiry] = options.resourceTokenExpirySeconds;\n }\n\n if (options.sessionToken) {\n headers[Constants.HttpHeaders.SessionToken] = options.sessionToken;\n }\n\n if (options.enableScanInQuery) {\n headers[Constants.HttpHeaders.EnableScanInQuery] = options.enableScanInQuery;\n }\n\n if (options.populateQuotaInfo) {\n headers[Constants.HttpHeaders.PopulateQuotaInfo] = options.populateQuotaInfo;\n }\n\n if (options.populateQueryMetrics) {\n headers[Constants.HttpHeaders.PopulateQueryMetrics] = options.populateQueryMetrics;\n }\n\n if (\n options.maxDegreeOfParallelism !== undefined &&\n options.maxDegreeOfParallelism !== 0 &&\n options.maxDegreeOfParallelism !== 1\n ) {\n headers[Constants.HttpHeaders.ParallelizeCrossPartitionQuery] = true;\n }\n\n if (options.populateQuotaInfo) {\n headers[Constants.HttpHeaders.PopulateQuotaInfo] = true;\n }\n\n if (partitionKey !== undefined && !headers[Constants.HttpHeaders.PartitionKey]) {\n headers[Constants.HttpHeaders.PartitionKey] = jsonStringifyAndEscapeNonASCII(partitionKey);\n }\n\n if (clientOptions.key || clientOptions.tokenProvider) {\n headers[Constants.HttpHeaders.XDate] = new Date().toUTCString();\n }\n\n if (verb === HTTPMethod.post || verb === HTTPMethod.put) {\n if (!headers[Constants.HttpHeaders.ContentType]) {\n headers[Constants.HttpHeaders.ContentType] = JsonContentType;\n }\n }\n\n if (!headers[Constants.HttpHeaders.Accept]) {\n headers[Constants.HttpHeaders.Accept] = JsonContentType;\n }\n\n if (partitionKeyRangeId !== undefined) {\n headers[Constants.HttpHeaders.PartitionKeyRangeID] = partitionKeyRangeId;\n }\n\n if (options.enableScriptLogging) {\n headers[Constants.HttpHeaders.EnableScriptLogging] = options.enableScriptLogging;\n }\n\n if (options.disableRUPerMinuteUsage) {\n headers[Constants.HttpHeaders.DisableRUPerMinuteUsage] = true;\n }\n\n if (options.populateIndexMetrics) {\n headers[Constants.HttpHeaders.PopulateIndexMetrics] = options.populateIndexMetrics;\n }\n\n if (clientOptions.clientEncryptionOptions) {\n headers[Constants.HttpHeaders.IsClientEncryptedHeader] = true;\n if (options.containerRid) {\n headers[Constants.HttpHeaders.IntendedCollectionHeader] = options.containerRid;\n }\n }\n\n if (\n clientOptions.key ||\n clientOptions.resourceTokens ||\n clientOptions.tokenProvider ||\n clientOptions.permissionFeed\n ) {\n await setAuthorizationHeader(clientOptions, verb, path, resourceId, resourceType, headers);\n }\n\n if (\n resourceType === ResourceType.item &&\n Object.prototype.hasOwnProperty.call(options, \"contentResponseOnWriteEnabled\") &&\n !options.contentResponseOnWriteEnabled\n ) {\n if (operationType === OperationType.Batch) {\n headers[Constants.HttpHeaders.Prefer] = Constants.HttpHeaders.PreferReturnMinimal;\n } else {\n throw new ErrorResponse(\n \"Currently `contentResponseOnWriteEnabled` option is only supported for batch and bulk operations.\",\n );\n }\n }\n return headers;\n}\n"]}
1
+ {"version":3,"file":"request.js","sourceRoot":"","sources":["../../../src/request/request.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EACL,SAAS,EACT,UAAU,EACV,8BAA8B,EAC9B,aAAa,EACb,YAAY,EACZ,wBAAwB,GACzB,MAAM,oBAAoB,CAAC;AAI5B,OAAO,EAAE,aAAa,EAAyC,MAAM,YAAY,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,+EAA+E;AAC/E,kBAAkB;AAClB,EAAE;AAEF,cAAc;AACd,SAAS,+BAA+B,CAAC,CAAU;IACjD,qGAAqG;IACrG,8CAA8C;IAC9C,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;SACrB,OAA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tC,CAAC;QACD,IAAI,aAAa,KAAK,aAAa,CAAC,KAAK,EAAE,CAAC;YAC1C,OAAO,CAAC,SAAS,CAAC,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,mBAAmB,CAAC;QACpF,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,aAAa,CACrB,mGAAmG,CACpG,CAAC;QACJ,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport { setAuthorizationHeader } from \"../auth.js\";\nimport {\n Constants,\n HTTPMethod,\n jsonStringifyAndEscapeNonASCII,\n OperationType,\n ResourceType,\n SDKSupportedCapabilities,\n} from \"../common/index.js\";\nimport type { CosmosClientOptions } from \"../CosmosClientOptions.js\";\nimport type { PartitionKeyInternal } from \"../documents/index.js\";\nimport type { CosmosHeaders } from \"../queryExecutionContext/index.js\";\nimport { ErrorResponse, type FeedOptions, type RequestOptions } from \"./index.js\";\nimport { defaultLogger } from \"../common/logger.js\";\nimport { ChangeFeedMode } from \"../client/ChangeFeed/index.js\";\n// ----------------------------------------------------------------------------\n// Utility methods\n//\n\n/** @hidden */\nfunction javaScriptFriendlyJSONStringify(s: unknown): string {\n // two line terminators (Line separator and Paragraph separator) are not needed to be escaped in JSON\n // but are needed to be escaped in JavaScript.\n return JSON.stringify(s)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\n/** @hidden */\nexport function bodyFromData(data: Buffer | string | Record<string, unknown>): string {\n if (typeof data === \"object\") {\n return javaScriptFriendlyJSONStringify(data);\n }\n return data;\n}\n\n/**\n * @hidden\n */\ninterface GetHeadersOptions {\n clientOptions: CosmosClientOptions;\n defaultHeaders: CosmosHeaders;\n verb: HTTPMethod;\n path: string;\n resourceId: string;\n resourceType: ResourceType;\n options: RequestOptions & FeedOptions;\n operationType?: OperationType;\n partitionKeyRangeId?: string;\n useMultipleWriteLocations?: boolean;\n partitionKey?: PartitionKeyInternal;\n}\n\nconst JsonContentType = \"application/json\";\n\n/**\n * @hidden\n */\nexport async function getHeaders({\n clientOptions,\n defaultHeaders,\n verb,\n path,\n resourceId,\n resourceType,\n options = {},\n operationType,\n partitionKeyRangeId,\n useMultipleWriteLocations,\n partitionKey,\n}: GetHeadersOptions): Promise<CosmosHeaders> {\n const headers: CosmosHeaders = {\n [Constants.HttpHeaders.ResponseContinuationTokenLimitInKB]: 1,\n [Constants.HttpHeaders.EnableCrossPartitionQuery]: true,\n ...defaultHeaders,\n };\n\n // Adding SDKSupportedCapabilities header to hint that SDK supports partition merge\n headers[Constants.HttpHeaders.SDKSupportedCapabilities] = SDKSupportedCapabilities.PartitionMerge;\n\n if (useMultipleWriteLocations) {\n headers[Constants.HttpHeaders.ALLOW_MULTIPLE_WRITES] = true;\n }\n\n if (options.continuationTokenLimitInKB) {\n headers[Constants.HttpHeaders.ResponseContinuationTokenLimitInKB] =\n options.continuationTokenLimitInKB;\n }\n if (options.continuationToken) {\n headers[Constants.HttpHeaders.Continuation] = options.continuationToken;\n } else if (options.continuation) {\n headers[Constants.HttpHeaders.Continuation] = options.continuation;\n }\n\n if (options.preTriggerInclude) {\n headers[Constants.HttpHeaders.PreTriggerInclude] =\n options.preTriggerInclude.constructor === Array\n ? (options.preTriggerInclude as string[]).join(\",\")\n : (options.preTriggerInclude as string);\n }\n\n if (options.postTriggerInclude) {\n headers[Constants.HttpHeaders.PostTriggerInclude] =\n options.postTriggerInclude.constructor === Array\n ? (options.postTriggerInclude as string[]).join(\",\")\n : (options.postTriggerInclude as string);\n }\n\n if (options.offerType) {\n headers[Constants.HttpHeaders.OfferType] = options.offerType;\n }\n\n if (options.offerThroughput) {\n headers[Constants.HttpHeaders.OfferThroughput] = options.offerThroughput;\n }\n\n if (options.maxItemCount) {\n headers[Constants.HttpHeaders.PageSize] = options.maxItemCount;\n }\n\n if (options.accessCondition) {\n if (options.accessCondition.type === \"IfMatch\") {\n headers[Constants.HttpHeaders.IfMatch] = options.accessCondition.condition;\n } else {\n headers[Constants.HttpHeaders.IfNoneMatch] = options.accessCondition.condition;\n }\n }\n\n if (options.useAllVersionsAndDeletesFeed) {\n // headers required for reading feed in allVersionsAndDeletes mode\n headers[Constants.HttpHeaders.A_IM] = ChangeFeedMode.AllVersionsAndDeletes;\n headers[Constants.HttpHeaders.ChangeFeedWireFormatVersion] =\n Constants.AllVersionsAndDeletesChangeFeedWireFormatVersion;\n }\n\n if (options.useIncrementalFeed || options.useLatestVersionFeed) {\n headers[Constants.HttpHeaders.A_IM] = ChangeFeedMode.LatestVersion;\n }\n\n if (options.indexingDirective) {\n headers[Constants.HttpHeaders.IndexingDirective] = options.indexingDirective;\n }\n\n if (options.consistencyLevel) {\n headers[Constants.HttpHeaders.ConsistencyLevel] = options.consistencyLevel;\n }\n\n if (options.priorityLevel) {\n headers[Constants.HttpHeaders.PriorityLevel] = options.priorityLevel;\n }\n\n if (options.throughputBucket) {\n headers[Constants.HttpHeaders.ThroughputBucket] = options.throughputBucket;\n }\n\n if (options.maxIntegratedCacheStalenessInMs && resourceType === ResourceType.item) {\n if (typeof options.maxIntegratedCacheStalenessInMs === \"number\") {\n headers[Constants.HttpHeaders.DedicatedGatewayPerRequestCacheStaleness] =\n options.maxIntegratedCacheStalenessInMs.toString();\n } else {\n defaultLogger.error(\n `RangeError: maxIntegratedCacheStalenessInMs \"${options.maxIntegratedCacheStalenessInMs}\" is not a valid parameter.`,\n );\n headers[Constants.HttpHeaders.DedicatedGatewayPerRequestCacheStaleness] = \"null\";\n }\n }\n\n if (options.bypassIntegratedCache) {\n headers[Constants.HttpHeaders.DedicatedGatewayPerRequestBypassCache] =\n options.bypassIntegratedCache.toString();\n }\n\n if (options.resourceTokenExpirySeconds) {\n headers[Constants.HttpHeaders.ResourceTokenExpiry] = options.resourceTokenExpirySeconds;\n }\n\n if (options.sessionToken) {\n headers[Constants.HttpHeaders.SessionToken] = options.sessionToken;\n }\n\n if (options.enableScanInQuery) {\n headers[Constants.HttpHeaders.EnableScanInQuery] = options.enableScanInQuery;\n }\n\n if (options.populateQuotaInfo) {\n headers[Constants.HttpHeaders.PopulateQuotaInfo] = options.populateQuotaInfo;\n }\n\n if (options.populateQueryMetrics) {\n headers[Constants.HttpHeaders.PopulateQueryMetrics] = options.populateQueryMetrics;\n }\n\n if (\n options.maxDegreeOfParallelism !== undefined &&\n options.maxDegreeOfParallelism !== 0 &&\n options.maxDegreeOfParallelism !== 1\n ) {\n headers[Constants.HttpHeaders.ParallelizeCrossPartitionQuery] = true;\n }\n\n if (options.populateQuotaInfo) {\n headers[Constants.HttpHeaders.PopulateQuotaInfo] = true;\n }\n\n if (partitionKey !== undefined && !headers[Constants.HttpHeaders.PartitionKey]) {\n headers[Constants.HttpHeaders.PartitionKey] = jsonStringifyAndEscapeNonASCII(partitionKey);\n } else if (partitionKeyRangeId !== undefined) {\n headers[Constants.HttpHeaders.PartitionKeyRangeID] = partitionKeyRangeId;\n }\n\n if (clientOptions.key || clientOptions.tokenProvider) {\n headers[Constants.HttpHeaders.XDate] = new Date().toUTCString();\n }\n\n if (verb === HTTPMethod.post || verb === HTTPMethod.put) {\n if (!headers[Constants.HttpHeaders.ContentType]) {\n headers[Constants.HttpHeaders.ContentType] = JsonContentType;\n }\n }\n\n if (!headers[Constants.HttpHeaders.Accept]) {\n headers[Constants.HttpHeaders.Accept] = JsonContentType;\n }\n\n if (options.enableScriptLogging) {\n headers[Constants.HttpHeaders.EnableScriptLogging] = options.enableScriptLogging;\n }\n\n if (options.disableRUPerMinuteUsage) {\n headers[Constants.HttpHeaders.DisableRUPerMinuteUsage] = true;\n }\n\n if (options.populateIndexMetrics) {\n headers[Constants.HttpHeaders.PopulateIndexMetrics] = options.populateIndexMetrics;\n }\n\n if (clientOptions.clientEncryptionOptions) {\n headers[Constants.HttpHeaders.IsClientEncryptedHeader] = true;\n if (options.containerRid) {\n headers[Constants.HttpHeaders.IntendedCollectionHeader] = options.containerRid;\n }\n }\n\n if (\n clientOptions.key ||\n clientOptions.resourceTokens ||\n clientOptions.tokenProvider ||\n clientOptions.permissionFeed\n ) {\n await setAuthorizationHeader(clientOptions, verb, path, resourceId, resourceType, headers);\n }\n\n if (\n resourceType === ResourceType.item &&\n Object.prototype.hasOwnProperty.call(options, \"contentResponseOnWriteEnabled\") &&\n !options.contentResponseOnWriteEnabled\n ) {\n if (operationType === OperationType.Batch) {\n headers[Constants.HttpHeaders.Prefer] = Constants.HttpHeaders.PreferReturnMinimal;\n } else {\n throw new ErrorResponse(\n \"Currently `contentResponseOnWriteEnabled` option is only supported for batch and bulk operations.\",\n );\n }\n }\n return headers;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"timeoutFailoverRetryPolicy.d.ts","sourceRoot":"","sources":["../../../src/retry/timeoutFailoverRetryPolicy.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAEpD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACzE,OAAO,EAAE,UAAU,EAAiB,MAAM,oBAAoB,CAAC;AAC/D,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAE1E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2CAA2C,CAAC;AAE/E,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACzE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0CAA0C,CAAC;AACvF,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;AAEtF;;;;;;GAMG;AACH,qBAAa,0BAA2B,YAAW,WAAW;IAS1D,OAAO,CAAC,qBAAqB;IAC7B,OAAO,CAAC,OAAO;IACf,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,YAAY;IAC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AO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACzE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0CAA0C,CAAC;AACvF,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;AAEtF;;;;;;GAMG;AACH,qBAAa,0BAA2B,YAAW,WAAW;IAS1D,OAAO,CAAC,qBAAqB;IAC7B,OAAO,CAAC,OAAO;IACf,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,YAAY;IACpB,OAAO,CAAC,aAAa;IACrB,OAAO,CAAC,uBAAuB;IAC/B,OAAO,CAAC,4BAA4B;IACpC,OAAO,CAAC,8BAA8B,CAAC;IAfzC,OAAO,CAAC,oBAAoB,CAAO;IACnC,OAAO,CAAC,+BAA+B,CAAK;IACrC,cAAc,SAAK;IACnB,kBAAkB,SAAK;IACvB,OAAO,EAAE,GAAG,CAAC;IACb,gBAAgB,EAAE,GAAG,CAAC;gBAGnB,qBAAqB,EAAE,qBAAqB,EAC5C,OAAO,EAAE,aAAa,EACtB,UAAU,EAAE,UAAU,EACtB,YAAY,EAAE,YAAY,EAC1B,aAAa,EAAE,aAAa,EAC5B,uBAAuB,EAAE,OAAO,EAChC,4BAA4B,EAAE,OAAO,EACrC,8BAA8B,CAAC,EAAE,8BAA8B;IAGzE;;;;OAIG;IACH,OAAO,CAAC,6BAA6B;IASxB,WAAW,CACtB,GAAG,EAAE,aAAa,EAClB,cAAc,EAAE,sBAAsB,EACtC,YAAY,CAAC,EAAE,YAAY,EAC3B,gBAAgB,CAAC,EAAE,MAAM,EACzB,cAAc,CAAC,EAAE,cAAc,GAC9B,OAAO,CAAC,OAAO,CAAC;IAkDnB;;;;OAIG;YACW,iBAAiB;CAyBhC"}
@@ -44,6 +44,9 @@ export class TimeoutFailoverRetryPolicy {
44
44
  if (!retryContext || !locationEndpoint) {
45
45
  return false;
46
46
  }
47
+ if (!this.enableEndPointDiscovery) {
48
+ return false;
49
+ }
47
50
  // Mark the partition as unavailable.
48
51
  // Let the Retry logic decide if the request should be retried
49
52
  if (requestContext && this.globalPartitionEndpointManager) {
@@ -53,9 +56,6 @@ export class TimeoutFailoverRetryPolicy {
53
56
  if (err.code === TimeoutErrorCode && !this.isValidRequestForTimeoutError()) {
54
57
  return false;
55
58
  }
56
- if (!this.enableEndPointDiscovery) {
57
- return false;
58
- }
59
59
  if (err.code === StatusCodes.ServiceUnavailable &&
60
60
  this.failoverRetryCount >= this.maxServiceUnavailableRetryCount) {
61
61
  return false;
@@ -1 +1 @@
1
- {"version":3,"file":"timeoutFailoverRetryPolicy.js","sourceRoot":"","sources":["../../../src/retry/timeoutFailoverRetryPolicy.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAE/D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAGnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAK9D;;;;;;GAMG;AACH,MAAM,OAAO,0BAA0B;IAQrC,YACU,qBAA4C,EAC5C,OAAsB,EACtB,UAAsB,EACtB,YAA0B,EAC1B,aAA4B,EAC5B,uBAAgC,EAChC,4BAAqC,EACrC,8BAA+D;QAP/D,0BAAqB,GAArB,qBAAqB,CAAuB;QAC5C,YAAO,GAAP,OAAO,CAAe;QACtB,eAAU,GAAV,UAAU,CAAY;QACtB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,kBAAa,GAAb,aAAa,CAAe;QAC5B,4BAAuB,GAAvB,uBAAuB,CAAS;QAChC,iCAA4B,GAA5B,4BAA4B,CAAS;QACrC,mCAA8B,GAA9B,8BAA8B,CAAiC;QAfjE,yBAAoB,GAAG,GAAG,CAAC;QAC3B,oCAA+B,GAAG,CAAC,CAAC;QACrC,mBAAc,GAAG,CAAC,CAAC;QACnB,uBAAkB,GAAG,CAAC,CAAC;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C,MAAM,GAAG,CAAC,EAAE,CAAC;oBACpD,aAAa,GAAG,kBAAkB,GAAG,gBAAgB,CAAC,MAAM,CAAC;gBAC/D,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,MAAM,iBAAiB,GAAG,MAAM,IAAI,CAAC,qBAAqB,CAAC,iBAAiB,EAAE,CAAC;gBAC/E,IAAI,iBAAiB,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBACtD,aAAa,GAAG,kBAAkB,GAAG,iBAAiB,CAAC,MAAM,CAAC;gBAChE,CAAC;YACH,CAAC;QACH,CAAC;QACD,OAAO,aAAa,CAAC;IACvB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport type { RetryPolicy } from \"./RetryPolicy.js\";\nimport { StatusCodes } from \"../common/statusCodes.js\";\nimport type { GlobalEndpointManager } from \"../globalEndpointManager.js\";\nimport { HTTPMethod, isReadRequest } from \"../common/index.js\";\nimport type { OperationType, ResourceType } from \"../common/constants.js\";\nimport { Constants } from \"../common/constants.js\";\nimport type { RetryContext } from \"./RetryContext.js\";\nimport type { CosmosHeaders } from \"../queryExecutionContext/CosmosHeaders.js\";\nimport { TimeoutErrorCode } from \"../request/TimeoutError.js\";\nimport type { ErrorResponse, RequestContext } from \"../request/index.js\";\nimport type { DiagnosticNodeInternal } from \"../diagnostics/DiagnosticNodeInternal.js\";\nimport { GlobalPartitionEndpointManager } from \"../globalPartitionEndpointManager.js\";\n\n/**\n * This class TimeoutFailoverRetryPolicy handles retries for read operations\n * (including data plane,metadata, and query plan) in case of request timeouts\n * (TimeoutError) or service unavailability (503 status code) by performing failover\n * and retrying on other regions.\n * @hidden\n */\nexport class TimeoutFailoverRetryPolicy implements RetryPolicy {\n private maxRetryAttemptCount = 120;\n private maxServiceUnavailableRetryCount = 1;\n public retryAfterInMs = 0;\n public failoverRetryCount = 0;\n public request: any;\n public locationEndpoint: any;\n\n constructor(\n private globalEndpointManager: GlobalEndpointManager,\n private headers: CosmosHeaders,\n private methodType: HTTPMethod,\n private resourceType: ResourceType,\n private operationType: OperationType,\n private enableEndPointDiscovery: boolean,\n private enablePartitionLevelFailover: boolean,\n private globalPartitionEndpointManager?: GlobalPartitionEndpointManager,\n ) {}\n\n /**\n * Checks if a timeout request is valid for the timeout failover retry policy.\n * A valid request should be a data plane, metadata, or query plan request.\n * @returns\n */\n private isValidRequestForTimeoutError(): boolean {\n const isQuery = Constants.HttpHeaders.IsQuery in this.headers;\n const isQueryPlan = Constants.HttpHeaders.IsQueryPlan in this.headers;\n if (this.methodType === HTTPMethod.get || isQuery || isQueryPlan) {\n return true;\n }\n return false;\n }\n\n public async shouldRetry(\n err: ErrorResponse,\n diagnosticNode: DiagnosticNodeInternal,\n retryContext?: RetryContext,\n locationEndpoint?: string,\n requestContext?: RequestContext,\n ): Promise<boolean> {\n if (!err) {\n return false;\n }\n if (!retryContext || !locationEndpoint) {\n return false;\n }\n\n // Mark the partition as unavailable.\n // Let the Retry logic decide if the request should be retried\n if (requestContext && this.globalPartitionEndpointManager) {\n await this.globalPartitionEndpointManager.tryPartitionLevelFailover(\n requestContext,\n diagnosticNode,\n );\n }\n\n // Check if the error is a timeout error (TimeoutErrorCode) and if it is not a valid HTTP network timeout request\n if (err.code === TimeoutErrorCode && !this.isValidRequestForTimeoutError()) {\n return false;\n }\n if (!this.enableEndPointDiscovery) {\n return false;\n }\n if (\n err.code === StatusCodes.ServiceUnavailable &&\n this.failoverRetryCount >= this.maxServiceUnavailableRetryCount\n ) {\n return false;\n }\n if (this.failoverRetryCount >= this.maxRetryAttemptCount) {\n return false;\n }\n const canUseMultipleWriteLocations = this.globalEndpointManager.canUseMultipleWriteLocations(\n this.resourceType,\n this.operationType,\n );\n const readRequest = isReadRequest(this.operationType);\n\n if (!canUseMultipleWriteLocations && !readRequest && !this.enablePartitionLevelFailover) {\n // Write requests on single master cannot be retried if partition level failover is disabled.\n // This means there are no other regions available to serve the writes.\n return false;\n }\n this.failoverRetryCount++;\n // Setting the retryLocationIndex to the next available location for retry.\n // The retryLocationIndex is determined based on the failoverRetryCount, starting from zero.\n retryContext.retryLocationServerIndex = await this.findEndpointIndex(this.failoverRetryCount);\n diagnosticNode.addData({ successfulRetryPolicy: \"timeout-failover\" });\n return true;\n }\n\n /**\n * Determines index of endpoint to be used for retry based upon failoverRetryCount and avalable locations\n * @param failoverRetryCount - count of failovers\n * @returns\n */\n private async findEndpointIndex(failoverRetryCount: number): Promise<number> {\n // count of preferred locations specified by user\n const preferredLocationsCount = this.globalEndpointManager.preferredLocationsCount;\n const readRequest = isReadRequest(this.operationType);\n let endpointIndex = 0;\n // If preferredLocationsCount is not zero, it indicates that the user has specified preferred locations.\n if (preferredLocationsCount !== 0) {\n // The endpointIndex is set based on the preferred location and the failover retry count.\n endpointIndex = failoverRetryCount % preferredLocationsCount;\n } else {\n // In the absence of preferred locations, the endpoint selection is based on the failover count and the number of available locations.\n if (readRequest) {\n const getReadEndpoints = await this.globalEndpointManager.getReadEndpoints();\n if (getReadEndpoints && getReadEndpoints.length > 0) {\n endpointIndex = failoverRetryCount % getReadEndpoints.length;\n }\n } else {\n const getWriteEndpoints = await this.globalEndpointManager.getWriteEndpoints();\n if (getWriteEndpoints && getWriteEndpoints.length > 0) {\n endpointIndex = failoverRetryCount % getWriteEndpoints.length;\n }\n }\n }\n return endpointIndex;\n }\n}\n"]}
1
+ {"version":3,"file":"timeoutFailoverRetryPolicy.js","sourceRoot":"","sources":["../../../src/retry/timeoutFailoverRetryPolicy.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAE/D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAGnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAK9D;;;;;;GAMG;AACH,MAAM,OAAO,0BAA0B;I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,CAAC,iBAAiB,CAAC,kBAA0B;QACxD,iDAAiD;QACjD,MAAM,uBAAuB,GAAG,IAAI,CAAC,qBAAqB,CAAC,uBAAuB,CAAC;QACnF,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QACtD,IAAI,aAAa,GAAG,CAAC,CAAC;QACtB,wGAAwG;QACxG,IAAI,uBAAuB,KAAK,CAAC,EAAE,CAAC;YAClC,yFAAyF;YACzF,aAAa,GAAG,kBAAkB,GAAG,uBAAuB,CAAC;QAC/D,CAAC;aAAM,CAAC;YACN,sIAAsI;YACtI,IAAI,WAAW,EAAE,CAAC;gBAChB,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC,qBAAqB,CAAC,gBAAgB,EAAE,CAAC;gBAC7E,IAAI,gBAAgB,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBACpD,aAAa,GAAG,kBAAkB,GAAG,gBAAgB,CAAC,MAAM,CAAC;gBAC/D,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,MAAM,iBAAiB,GAAG,MAAM,IAAI,CAAC,qBAAqB,CAAC,iBAAiB,EAAE,CAAC;gBAC/E,IAAI,iBAAiB,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBACtD,aAAa,GAAG,kBAAkB,GAAG,iBAAiB,CAAC,MAAM,CAAC;gBAChE,CAAC;YACH,CAAC;QACH,CAAC;QACD,OAAO,aAAa,CAAC;IACvB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport type { RetryPolicy } from \"./RetryPolicy.js\";\nimport { StatusCodes } from \"../common/statusCodes.js\";\nimport type { GlobalEndpointManager } from \"../globalEndpointManager.js\";\nimport { HTTPMethod, isReadRequest } from \"../common/index.js\";\nimport type { OperationType, ResourceType } from \"../common/constants.js\";\nimport { Constants } from \"../common/constants.js\";\nimport type { RetryContext } from \"./RetryContext.js\";\nimport type { CosmosHeaders } from \"../queryExecutionContext/CosmosHeaders.js\";\nimport { TimeoutErrorCode } from \"../request/TimeoutError.js\";\nimport type { ErrorResponse, RequestContext } from \"../request/index.js\";\nimport type { DiagnosticNodeInternal } from \"../diagnostics/DiagnosticNodeInternal.js\";\nimport { GlobalPartitionEndpointManager } from \"../globalPartitionEndpointManager.js\";\n\n/**\n * This class TimeoutFailoverRetryPolicy handles retries for read operations\n * (including data plane,metadata, and query plan) in case of request timeouts\n * (TimeoutError) or service unavailability (503 status code) by performing failover\n * and retrying on other regions.\n * @hidden\n */\nexport class TimeoutFailoverRetryPolicy implements RetryPolicy {\n private maxRetryAttemptCount = 120;\n private maxServiceUnavailableRetryCount = 1;\n public retryAfterInMs = 0;\n public failoverRetryCount = 0;\n public request: any;\n public locationEndpoint: any;\n\n constructor(\n private globalEndpointManager: GlobalEndpointManager,\n private headers: CosmosHeaders,\n private methodType: HTTPMethod,\n private resourceType: ResourceType,\n private operationType: OperationType,\n private enableEndPointDiscovery: boolean,\n private enablePartitionLevelFailover: boolean,\n private globalPartitionEndpointManager?: GlobalPartitionEndpointManager,\n ) {}\n\n /**\n * Checks if a timeout request is valid for the timeout failover retry policy.\n * A valid request should be a data plane, metadata, or query plan request.\n * @returns\n */\n private isValidRequestForTimeoutError(): boolean {\n const isQuery = Constants.HttpHeaders.IsQuery in this.headers;\n const isQueryPlan = Constants.HttpHeaders.IsQueryPlan in this.headers;\n if (this.methodType === HTTPMethod.get || isQuery || isQueryPlan) {\n return true;\n }\n return false;\n }\n\n public async shouldRetry(\n err: ErrorResponse,\n diagnosticNode: DiagnosticNodeInternal,\n retryContext?: RetryContext,\n locationEndpoint?: string,\n requestContext?: RequestContext,\n ): Promise<boolean> {\n if (!err) {\n return false;\n }\n if (!retryContext || !locationEndpoint) {\n return false;\n }\n if (!this.enableEndPointDiscovery) {\n return false;\n }\n // Mark the partition as unavailable.\n // Let the Retry logic decide if the request should be retried\n if (requestContext && this.globalPartitionEndpointManager) {\n await this.globalPartitionEndpointManager.tryPartitionLevelFailover(\n requestContext,\n diagnosticNode,\n );\n }\n // Check if the error is a timeout error (TimeoutErrorCode) and if it is not a valid HTTP network timeout request\n if (err.code === TimeoutErrorCode && !this.isValidRequestForTimeoutError()) {\n return false;\n }\n if (\n err.code === StatusCodes.ServiceUnavailable &&\n this.failoverRetryCount >= this.maxServiceUnavailableRetryCount\n ) {\n return false;\n }\n if (this.failoverRetryCount >= this.maxRetryAttemptCount) {\n return false;\n }\n const canUseMultipleWriteLocations = this.globalEndpointManager.canUseMultipleWriteLocations(\n this.resourceType,\n this.operationType,\n );\n const readRequest = isReadRequest(this.operationType);\n\n if (!canUseMultipleWriteLocations && !readRequest && !this.enablePartitionLevelFailover) {\n // Write requests on single master cannot be retried if partition level failover is disabled.\n // This means there are no other regions available to serve the writes.\n return false;\n }\n this.failoverRetryCount++;\n // Setting the retryLocationIndex to the next available location for retry.\n // The retryLocationIndex is determined based on the failoverRetryCount, starting from zero.\n retryContext.retryLocationServerIndex = await this.findEndpointIndex(this.failoverRetryCount);\n diagnosticNode.addData({ successfulRetryPolicy: \"timeout-failover\" });\n return true;\n }\n\n /**\n * Determines index of endpoint to be used for retry based upon failoverRetryCount and avalable locations\n * @param failoverRetryCount - count of failovers\n * @returns\n */\n private async findEndpointIndex(failoverRetryCount: number): Promise<number> {\n // count of preferred locations specified by user\n const preferredLocationsCount = this.globalEndpointManager.preferredLocationsCount;\n const readRequest = isReadRequest(this.operationType);\n let endpointIndex = 0;\n // If preferredLocationsCount is not zero, it indicates that the user has specified preferred locations.\n if (preferredLocationsCount !== 0) {\n // The endpointIndex is set based on the preferred location and the failover retry count.\n endpointIndex = failoverRetryCount % preferredLocationsCount;\n } else {\n // In the absence of preferred locations, the endpoint selection is based on the failover count and the number of available locations.\n if (readRequest) {\n const getReadEndpoints = await this.globalEndpointManager.getReadEndpoints();\n if (getReadEndpoints && getReadEndpoints.length > 0) {\n endpointIndex = failoverRetryCount % getReadEndpoints.length;\n }\n } else {\n const getWriteEndpoints = await this.globalEndpointManager.getWriteEndpoints();\n if (getWriteEndpoints && getWriteEndpoints.length > 0) {\n endpointIndex = failoverRetryCount % getWriteEndpoints.length;\n }\n }\n }\n return endpointIndex;\n }\n}\n"]}
@@ -4,4 +4,12 @@
4
4
  * @returns
5
5
  */
6
6
  export declare function getCurrentTimestampInMs(): number;
7
+ /**
8
+ * @hidden
9
+ * Utility function to start a background task that runs at specified intervals.
10
+ * @param action - A function that returns a Promise, representing the task to be executed.
11
+ * @param intervalMs - The interval in milliseconds at which the task should run.
12
+ * @returns A NodeJS.Timeout object representing the timer for the background task.
13
+ */
14
+ export declare function startBackgroundTask(action: () => Promise<void>, intervalMs: number): NodeJS.Timeout;
7
15
  //# sourceMappingURL=time.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"time.d.ts","sourceRoot":"","sources":["../../../src/utils/time.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AAEH,wBAAgB,uBAAuB,IAAI,MAAM,CAEhD"}
1
+ {"version":3,"file":"time.d.ts","sourceRoot":"","sources":["../../../src/utils/time.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AAEH,wBAAgB,uBAAuB,IAAI,MAAM,CAEhD;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,EAC3B,UAAU,EAAE,MAAM,GACjB,MAAM,CAAC,OAAO,CAWhB"}
@@ -8,4 +8,23 @@
8
8
  export function getCurrentTimestampInMs() {
9
9
  return Date.now();
10
10
  }
11
+ /**
12
+ * @hidden
13
+ * Utility function to start a background task that runs at specified intervals.
14
+ * @param action - A function that returns a Promise, representing the task to be executed.
15
+ * @param intervalMs - The interval in milliseconds at which the task should run.
16
+ * @returns A NodeJS.Timeout object representing the timer for the background task.
17
+ */
18
+ export function startBackgroundTask(action, intervalMs) {
19
+ const timer = setInterval(() => {
20
+ (async () => {
21
+ await action();
22
+ })();
23
+ }, intervalMs);
24
+ // Unref the timer if available to prevent it from keeping the Node.js event loop alive
25
+ if (timer.unref && typeof timer.unref === "function") {
26
+ timer.unref();
27
+ }
28
+ return timer;
29
+ }
11
30
  //# sourceMappingURL=time.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"time.js","sourceRoot":"","sources":["../../../src/utils/time.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;;GAIG;AAEH,MAAM,UAAU,uBAAuB;IACrC,OAAO,IAAI,CAAC,GAAG,EAAE,CAAC;AACpB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * @hidden\n * Utility function to get currentTime in UTC milliseconds.\n * @returns\n */\n\nexport function getCurrentTimestampInMs(): number {\n return Date.now();\n}\n"]}
1
+ {"version":3,"file":"time.js","sourceRoot":"","sources":["../../../src/utils/time.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;;GAIG;AAEH,MAAM,UAAU,uBAAuB;IACrC,OAAO,IAAI,CAAC,GAAG,EAAE,CAAC;AACpB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CACjC,MAA2B,EAC3B,UAAkB;IAElB,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,CAAC,KAAK,IAAI,EAAE;YACV,MAAM,MAAM,EAAE,CAAC;QACjB,CAAC,CAAC,EAAE,CAAC;IACP,CAAC,EAAE,UAAU,CAAC,CAAC;IACf,uFAAuF;IACvF,IAAI,KAAK,CAAC,KAAK,IAAI,OAAO,KAAK,CAAC,KAAK,KAAK,UAAU,EAAE,CAAC;QACrD,KAAK,CAAC,KAAK,EAAE,CAAC;IAChB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * @hidden\n * Utility function to get currentTime in UTC milliseconds.\n * @returns\n */\n\nexport function getCurrentTimestampInMs(): number {\n return Date.now();\n}\n\n/**\n * @hidden\n * Utility function to start a background task that runs at specified intervals.\n * @param action - A function that returns a Promise, representing the task to be executed.\n * @param intervalMs - The interval in milliseconds at which the task should run.\n * @returns A NodeJS.Timeout object representing the timer for the background task.\n */\nexport function startBackgroundTask(\n action: () => Promise<void>,\n intervalMs: number,\n): NodeJS.Timeout {\n const timer = setInterval(() => {\n (async () => {\n await action();\n })();\n }, intervalMs);\n // Unref the timer if available to prevent it from keeping the Node.js event loop alive\n if (timer.unref && typeof timer.unref === \"function\") {\n timer.unref();\n }\n return timer;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"CosmosClient.d.ts","sourceRoot":"","sources":["../../src/CosmosClient.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAKxD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAMpE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AAEtF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAI5D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAKtD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,qBAAa,YAAY;IACvB;;;;;;;;;;;;;;;;OAgBG;IACH,SAAgB,SAAS,EAAE,SAAS,CAAC;IACrC;;;;OAIG;IACH,SAAgB,MAAM,EAAE,MAAM,CAAC;IAC/B,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,iBAAiB,CAAiB;IAO1C;;OAEG;gBACS,gBAAgB,EAAE,MAAM;IACpC;;;OAGG;gBACS,OAAO,EAAE,mBAAmB;IAqGxC,OAAO,CAAC,gCAAgC;IAmB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;;;;;;;;;;;;;;;;GAyBG;AACH,qBAAa,YAAY;IACvB;;;;;;;;;;;;;;;;OAgBG;IACH,SAAgB,SAAS,EAAE,SAAS,CAAC;IACrC;;;;OAIG;IACH,SAAgB,MAAM,EAAE,MAAM,CAAC;IAC/B,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,iBAAiB,CAAiB;IAO1C;;OAEG;gBACS,gBAAgB,EAAE,MAAM;IACpC;;;OAGG;gBACS,OAAO,EAAE,mBAAmB;IA0GxC,OAAO,CAAC,gCAAgC;IAmBxC;;OAEG;IACU,kBAAkB,CAC7B,OAAO,CAAC,EAAE,cAAc,GACvB,OAAO,CAAC,gBAAgB,CAAC,eAAe,CAAC,CAAC;IAM7C;;OAEG;IACU,0BAA0B,CACrC,cAAc,EAAE,sBAAsB,EACtC,OAAO,CAAC,EAAE,cAAc,GACvB,OAAO,CAAC,gBAAgB,CAAC,eAAe,CAAC,CAAC;IAW7C;;;;OAIG;IACU,gBAAgB,IAAI,OAAO,CAAC,MAAM,CAAC;IAMhD;;;;OAIG;IACU,eAAe,IAAI,OAAO,CAAC,MAAM,CAAC;IAM/C;;;;OAIG;IACI,iBAAiB,IAAI,OAAO,CAAC,SAAS,MAAM,EAAE,CAAC;IAItD;;;;OAIG;IACI,gBAAgB,IAAI,OAAO,CAAC,SAAS,MAAM,EAAE,CAAC;IAIrD;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACI,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,QAAQ;IAIrC;;;OAGG;IACI,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,KAAK;IAI/B;;OAEG;IACI,OAAO,IAAI,IAAI;YAWR,6BAA6B;CA8B5C"}
@@ -86,6 +86,9 @@ export class CosmosClient {
86
86
  const globalEndpointManager = new GlobalEndpointManager(optionsOrConnectionString, async (diagnosticNode, opts) => this.getDatabaseAccountInternal(diagnosticNode, opts));
87
87
  if (optionsOrConnectionString.connectionPolicy.enablePartitionLevelFailover ||
88
88
  optionsOrConnectionString.connectionPolicy.enablePartitionLevelCircuitBreaker) {
89
+ if (!optionsOrConnectionString.connectionPolicy.enableEndpointDiscovery) {
90
+ throw new Error("enableEndpointDiscovery must be set to true to use partition level failover or circuit breaker.");
91
+ }
89
92
  this.globalPartitionEndpointManager = new GlobalPartitionEndpointManager(optionsOrConnectionString, globalEndpointManager);
90
93
  }
91
94
  this.clientContext = new ClientContext(optionsOrConnectionString, globalEndpointManager, clientConfig, determineDiagnosticLevel(optionsOrConnectionString.diagnosticLevel, getDiagnosticLevelFromEnvironment()), this.globalPartitionEndpointManager);
@@ -1 +1 @@
1
- {"version":3,"file":"CosmosClient.js","sourceRoot":"","sources":["../../src/CosmosClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAGpD,OAAO,EACL,wBAAwB,EACxB,iCAAiC,GAClC,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAE7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAEnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO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C,CAAC;gBACnE,CAAC,EACD,IAAI,CAAC,aAAa,EAClB,kBAAkB,CAAC,yBAAyB,CAC7C,CAAC;YACJ,CAAC;YAAC,OAAO,CAAM,EAAE,CAAC;gBAChB,OAAO,CAAC,IAAI,CAAC,6BAA6B,EAAE,CAAC,CAAC,CAAC;YACjD,CAAC;QACH,CAAC,EAAE,WAAW,CAAC,CAAC;QAChB,IAAI,IAAI,CAAC,iBAAiB,CAAC,KAAK,IAAI,OAAO,IAAI,CAAC,iBAAiB,CAAC,KAAK,KAAK,UAAU,EAAE,CAAC;YACvF,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,CAAC;QACjC,CAAC;IACH,CAAC;IAED;;;;OAIG;IACI,KAAK,CAAC,mBAAmB,CAAC,aAAqB;QACpD,IAAI,CAAC,aAAa,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;IACrD,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport { Database, Databases } from \"./client/Database/index.js\";\nimport { Offer, Offers } from \"./client/Offer/index.js\";\nimport { ClientContext } from \"./ClientContext.js\";\nimport { parseConnectionString } from \"./common/index.js\";\nimport { Constants } from \"./common/constants.js\";\nimport { getUserAgent } from \"./common/platform.js\";\nimport type { CosmosClientOptions } from \"./CosmosClientOptions.js\";\nimport type { ClientConfigDiagnostic } from \"./CosmosDiagnostics.js\";\nimport {\n determineDiagnosticLevel,\n getDiagnosticLevelFromEnvironment,\n} from \"./diagnostics/index.js\";\nimport type { DiagnosticNodeInternal } from \"./diagnostics/DiagnosticNodeInternal.js\";\nimport { DiagnosticNodeType } from \"./diagnostics/DiagnosticNodeInternal.js\";\nimport type { DatabaseAccount } from \"./documents/index.js\";\nimport { defaultConnectionPolicy } from \"./documents/index.js\";\nimport { EncryptionManager } from \"./encryption/EncryptionManager.js\";\nimport { GlobalEndpointManager } from \"./globalEndpointManager.js\";\nimport type { RequestOptions } from \"./request/index.js\";\nimport { ResourceResponse } from \"./request/index.js\";\nimport { checkURL } from \"./utils/checkURL.js\";\nimport { getEmptyCosmosDiagnostics, withDiagnostics } from \"./utils/diagnostics.js\";\nimport { GlobalPartitionEndpointManager } from \"./globalPartitionEndpointManager.js\";\n\n/**\n * Provides a client-side logical representation of the Azure Cosmos DB database account.\n * This client is used to configure and execute requests in the Azure Cosmos DB database service.\n * @example Instantiate a client and create a new database\n * ```ts snippet:CosmosClientCreate\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 * @example Instantiate a client with custom Connection Policy\n * ```ts snippet:CosmosClientWithConnectionPolicy\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({\n * endpoint,\n * key,\n * connectionPolicy: {\n * requestTimeout: 10000,\n * },\n * });\n * ```\n */\nexport class CosmosClient {\n /**\n * Used for creating new databases, or querying/reading all databases.\n *\n * Use `.database(id)` to read, replace, or delete a specific, existing database by id.\n *\n * @example Create a new database\n * ```ts snippet:CosmosClientDatabases\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 * const { resource: databaseDefinition, database } = await client.databases.create({\n * id: \"<name here>\",\n * });\n * ```\n */\n public readonly databases: Databases;\n /**\n * Used for querying & reading all offers.\n *\n * Use `.offer(id)` to read, or replace existing offers.\n */\n public readonly offers: Offers;\n private clientContext: ClientContext;\n private endpointRefresher: NodeJS.Timeout;\n /**\n * @internal\n */\n private encryptionManager: EncryptionManager;\n /** @internal */\n private globalPartitionEndpointManager: GlobalPartitionEndpointManager;\n /**\n * Creates a new {@link CosmosClient} object from a connection string. Your database connection string can be found in the Azure Portal\n */\n constructor(connectionString: string);\n /**\n * Creates a new {@link CosmosClient} object. See {@link CosmosClientOptions} for more details on what options you can use.\n * @param options - bag of options; require at least endpoint and auth to be configured\n */\n constructor(options: CosmosClientOptions);\n constructor(optionsOrConnectionString: string | CosmosClientOptions) {\n if (typeof optionsOrConnectionString === \"string\") {\n optionsOrConnectionString = parseConnectionString(optionsOrConnectionString);\n } else if (optionsOrConnectionString.connectionString) {\n const { endpoint, key } = parseConnectionString(optionsOrConnectionString.connectionString);\n optionsOrConnectionString.endpoint = endpoint;\n optionsOrConnectionString.key = key;\n }\n\n const endpoint = checkURL(optionsOrConnectionString.endpoint);\n if (!endpoint) {\n throw new Error(\"Invalid endpoint specified\");\n }\n\n if (optionsOrConnectionString.clientEncryptionOptions) {\n if (!optionsOrConnectionString.clientEncryptionOptions.keyEncryptionKeyResolver) {\n throw new Error(\n \"KeyEncryptionKeyResolver needs to be provided to enable client-side encryption.\",\n );\n }\n if (\n optionsOrConnectionString.clientEncryptionOptions.encryptionKeyTimeToLiveInSeconds &&\n optionsOrConnectionString.clientEncryptionOptions.encryptionKeyTimeToLiveInSeconds < 60\n ) {\n throw new Error(\"EncryptionKeyTimeToLiveInSeconds needs to be >= 60 seconds.\");\n }\n this.encryptionManager = new EncryptionManager(\n optionsOrConnectionString.clientEncryptionOptions.keyEncryptionKeyResolver,\n optionsOrConnectionString.clientEncryptionOptions.encryptionKeyTimeToLiveInSeconds,\n );\n }\n\n const clientConfig: ClientConfigDiagnostic =\n this.initializeClientConfigDiagnostic(optionsOrConnectionString);\n\n optionsOrConnectionString.connectionPolicy = Object.assign(\n {},\n defaultConnectionPolicy,\n optionsOrConnectionString.connectionPolicy,\n );\n\n optionsOrConnectionString.defaultHeaders = optionsOrConnectionString.defaultHeaders || {};\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.CacheControl] = \"no-cache\";\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.Version] =\n Constants.CurrentVersion;\n if (optionsOrConnectionString.consistencyLevel !== undefined) {\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.ConsistencyLevel] =\n optionsOrConnectionString.consistencyLevel;\n }\n\n if (optionsOrConnectionString.throughputBucket !== undefined) {\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.ThroughputBucket] =\n optionsOrConnectionString.throughputBucket;\n }\n\n const userAgent = getUserAgent(optionsOrConnectionString);\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.UserAgent] = userAgent;\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.CustomUserAgent] = userAgent;\n\n const globalEndpointManager = new GlobalEndpointManager(\n optionsOrConnectionString,\n async (diagnosticNode: DiagnosticNodeInternal, opts: RequestOptions) =>\n this.getDatabaseAccountInternal(diagnosticNode, opts),\n );\n\n if (\n optionsOrConnectionString.connectionPolicy.enablePartitionLevelFailover ||\n optionsOrConnectionString.connectionPolicy.enablePartitionLevelCircuitBreaker\n ) {\n this.globalPartitionEndpointManager = new GlobalPartitionEndpointManager(\n optionsOrConnectionString,\n globalEndpointManager,\n );\n }\n\n this.clientContext = new ClientContext(\n optionsOrConnectionString,\n globalEndpointManager,\n clientConfig,\n determineDiagnosticLevel(\n optionsOrConnectionString.diagnosticLevel,\n getDiagnosticLevelFromEnvironment(),\n ),\n this.globalPartitionEndpointManager,\n );\n if (\n optionsOrConnectionString.connectionPolicy?.enableEndpointDiscovery &&\n optionsOrConnectionString.connectionPolicy?.enableBackgroundEndpointRefreshing\n ) {\n this.backgroundRefreshEndpointList(\n globalEndpointManager,\n optionsOrConnectionString.connectionPolicy.endpointRefreshRateInMs ||\n defaultConnectionPolicy.endpointRefreshRateInMs,\n );\n }\n\n this.databases = new Databases(this, this.clientContext, this.encryptionManager);\n this.offers = new Offers(this, this.clientContext);\n }\n\n private initializeClientConfigDiagnostic(\n optionsOrConnectionString: CosmosClientOptions,\n ): ClientConfigDiagnostic {\n return {\n endpoint: optionsOrConnectionString.endpoint,\n resourceTokensConfigured: optionsOrConnectionString.resourceTokens !== undefined,\n tokenProviderConfigured: optionsOrConnectionString.tokenProvider !== undefined,\n aadCredentialsConfigured: optionsOrConnectionString.aadCredentials !== undefined,\n connectionPolicyConfigured: optionsOrConnectionString.connectionPolicy !== undefined,\n consistencyLevel: optionsOrConnectionString.consistencyLevel,\n defaultHeaders: optionsOrConnectionString.defaultHeaders,\n agentConfigured: optionsOrConnectionString.agent !== undefined,\n userAgentSuffix: optionsOrConnectionString.userAgentSuffix,\n diagnosticLevel: optionsOrConnectionString.diagnosticLevel,\n pluginsConfigured: optionsOrConnectionString.plugins !== undefined,\n sDKVersion: Constants.SDKVersion,\n };\n }\n\n /**\n * Get information about the current {@link DatabaseAccount} (including which regions are supported, etc.)\n */\n public async getDatabaseAccount(\n options?: RequestOptions,\n ): Promise<ResourceResponse<DatabaseAccount>> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n return this.getDatabaseAccountInternal(diagnosticNode, options);\n }, this.clientContext);\n }\n\n /**\n * @hidden\n */\n public async getDatabaseAccountInternal(\n diagnosticNode: DiagnosticNodeInternal,\n options?: RequestOptions,\n ): Promise<ResourceResponse<DatabaseAccount>> {\n const response = await this.clientContext.getDatabaseAccount(diagnosticNode, options);\n return new ResourceResponse<DatabaseAccount>(\n response.result,\n response.headers,\n response.code,\n getEmptyCosmosDiagnostics(),\n response.substatus,\n );\n }\n\n /**\n * Gets the currently used write endpoint url. Useful for troubleshooting purposes.\n *\n * The url may contain a region suffix (e.g. \"-eastus\") if we're using location specific endpoints.\n */\n public async getWriteEndpoint(): Promise<string> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n return this.clientContext.getWriteEndpoint(diagnosticNode);\n }, this.clientContext);\n }\n\n /**\n * Gets the currently used read endpoint. Useful for troubleshooting purposes.\n *\n * The url may contain a region suffix (e.g. \"-eastus\") if we're using location specific endpoints.\n */\n public async getReadEndpoint(): Promise<string> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n return this.clientContext.getReadEndpoint(diagnosticNode);\n }, this.clientContext);\n }\n\n /**\n * Gets the known write endpoints. Useful for troubleshooting purposes.\n *\n * The urls may contain a region suffix (e.g. \"-eastus\") if we're using location specific endpoints.\n */\n public getWriteEndpoints(): Promise<readonly string[]> {\n return this.clientContext.getWriteEndpoints();\n }\n\n /**\n * Gets the currently used read endpoint. Useful for troubleshooting purposes.\n *\n * The url may contain a region suffix (e.g. \"-eastus\") if we're using location specific endpoints.\n */\n public getReadEndpoints(): Promise<readonly string[]> {\n return this.clientContext.getReadEndpoints();\n }\n\n /**\n * Used for reading, updating, or deleting a existing database by id or accessing containers belonging to that database.\n *\n * This does not make a network call. Use `.read` to get info about the database after getting the {@link Database} object.\n *\n * @param id - The id of the database.\n * @example Create a new container off of an existing database\n * ```ts snippet:CosmosClientDatabaseCreateContainer\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 * const container = client.database(\"<database id>\").containers.create({\n * id: \"<name here>\",\n * });\n * ```\n *\n * @example Delete an existing database\n * ```ts snippet:CosmosClientDatabaseDelete\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 * await client.database(\"<id here>\").delete();\n * ```\n */\n public database(id: string): Database {\n return new Database(this, id, this.clientContext, this.encryptionManager);\n }\n\n /**\n * Used for reading, or updating a existing offer by id.\n * @param id - The id of the offer.\n */\n public offer(id: string): Offer {\n return new Offer(this, id, this.clientContext);\n }\n\n /**\n * Clears background endpoint refresher. Use client.dispose() when destroying the CosmosClient within another process.\n */\n public dispose(): void {\n clearTimeout(this.endpointRefresher);\n if (this.clientContext.enableEncryption) {\n clearTimeout(this.encryptionManager.encryptionKeyStoreProvider.cacheRefresher);\n clearTimeout(this.encryptionManager.protectedDataEncryptionKeyCache.cacheRefresher);\n }\n if (this.globalPartitionEndpointManager) {\n this.globalPartitionEndpointManager.dispose();\n }\n }\n\n private async backgroundRefreshEndpointList(\n globalEndpointManager: GlobalEndpointManager,\n refreshRate: number,\n ) {\n this.endpointRefresher = setInterval(() => {\n try {\n return withDiagnostics(\n async (diagnosticNode: DiagnosticNodeInternal) => {\n return globalEndpointManager.refreshEndpointList(diagnosticNode);\n },\n this.clientContext,\n DiagnosticNodeType.BACKGROUND_REFRESH_THREAD,\n );\n } catch (e: any) {\n console.warn(\"Failed to refresh endpoints\", e);\n }\n }, refreshRate);\n if (this.endpointRefresher.unref && typeof this.endpointRefresher.unref === \"function\") {\n this.endpointRefresher.unref();\n }\n }\n\n /**\n * Update the host framework. If provided host framework will be used to generate the defualt SDK user agent.\n * @param hostFramework - A custom string.\n * @internal\n */\n public async updateHostFramework(hostFramework: string): Promise<void> {\n this.clientContext.refreshUserAgent(hostFramework);\n }\n}\n"]}
1
+ {"version":3,"file":"CosmosClient.js","sourceRoot":"","sources":["../../src/CosmosClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAGpD,OAAO,EACL,wBAAwB,EACxB,iCAAiC,GAClC,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAE7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EA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AAC,OAAO,EAAE,CAAC;QAChD,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,6BAA6B,CACzC,qBAA4C,EAC5C,WAAmB;QAEnB,IAAI,CAAC,iBAAiB,GAAG,WAAW,CAAC,GAAG,EAAE;YACxC,IAAI,CAAC;gBACH,OAAO,eAAe,CACpB,KAAK,EAAE,cAAsC,EAAE,EAAE;oBAC/C,OAAO,qBAAqB,CAAC,mBAAmB,CAAC,cAAc,CAAC,CAAC;gBACnE,CAAC,EACD,IAAI,CAAC,aAAa,EAClB,kBAAkB,CAAC,yBAAyB,CAC7C,CAAC;YACJ,CAAC;YAAC,OAAO,CAAM,EAAE,CAAC;gBAChB,OAAO,CAAC,IAAI,CAAC,6BAA6B,EAAE,CAAC,CAAC,CAAC;YACjD,CAAC;QACH,CAAC,EAAE,WAAW,CAAC,CAAC;QAChB,IAAI,IAAI,CAAC,iBAAiB,CAAC,KAAK,IAAI,OAAO,IAAI,CAAC,iBAAiB,CAAC,KAAK,KAAK,UAAU,EAAE,CAAC;YACvF,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,CAAC;QACjC,CAAC;IACH,CAAC;IAED;;;;OAIG;IACI,KAAK,CAAC,mBAAmB,CAAC,aAAqB;QACpD,IAAI,CAAC,aAAa,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;IACrD,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport { Database, Databases } from \"./client/Database/index.js\";\nimport { Offer, Offers } from \"./client/Offer/index.js\";\nimport { ClientContext } from \"./ClientContext.js\";\nimport { parseConnectionString } from \"./common/index.js\";\nimport { Constants } from \"./common/constants.js\";\nimport { getUserAgent } from \"./common/platform.js\";\nimport type { CosmosClientOptions } from \"./CosmosClientOptions.js\";\nimport type { ClientConfigDiagnostic } from \"./CosmosDiagnostics.js\";\nimport {\n determineDiagnosticLevel,\n getDiagnosticLevelFromEnvironment,\n} from \"./diagnostics/index.js\";\nimport type { DiagnosticNodeInternal } from \"./diagnostics/DiagnosticNodeInternal.js\";\nimport { DiagnosticNodeType } from \"./diagnostics/DiagnosticNodeInternal.js\";\nimport type { DatabaseAccount } from \"./documents/index.js\";\nimport { defaultConnectionPolicy } from \"./documents/index.js\";\nimport { EncryptionManager } from \"./encryption/EncryptionManager.js\";\nimport { GlobalEndpointManager } from \"./globalEndpointManager.js\";\nimport type { RequestOptions } from \"./request/index.js\";\nimport { ResourceResponse } from \"./request/index.js\";\nimport { checkURL } from \"./utils/checkURL.js\";\nimport { getEmptyCosmosDiagnostics, withDiagnostics } from \"./utils/diagnostics.js\";\nimport { GlobalPartitionEndpointManager } from \"./globalPartitionEndpointManager.js\";\n\n/**\n * Provides a client-side logical representation of the Azure Cosmos DB database account.\n * This client is used to configure and execute requests in the Azure Cosmos DB database service.\n * @example Instantiate a client and create a new database\n * ```ts snippet:CosmosClientCreate\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 * @example Instantiate a client with custom Connection Policy\n * ```ts snippet:CosmosClientWithConnectionPolicy\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({\n * endpoint,\n * key,\n * connectionPolicy: {\n * requestTimeout: 10000,\n * },\n * });\n * ```\n */\nexport class CosmosClient {\n /**\n * Used for creating new databases, or querying/reading all databases.\n *\n * Use `.database(id)` to read, replace, or delete a specific, existing database by id.\n *\n * @example Create a new database\n * ```ts snippet:CosmosClientDatabases\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 * const { resource: databaseDefinition, database } = await client.databases.create({\n * id: \"<name here>\",\n * });\n * ```\n */\n public readonly databases: Databases;\n /**\n * Used for querying & reading all offers.\n *\n * Use `.offer(id)` to read, or replace existing offers.\n */\n public readonly offers: Offers;\n private clientContext: ClientContext;\n private endpointRefresher: NodeJS.Timeout;\n /**\n * @internal\n */\n private encryptionManager: EncryptionManager;\n /** @internal */\n private globalPartitionEndpointManager: GlobalPartitionEndpointManager;\n /**\n * Creates a new {@link CosmosClient} object from a connection string. Your database connection string can be found in the Azure Portal\n */\n constructor(connectionString: string);\n /**\n * Creates a new {@link CosmosClient} object. See {@link CosmosClientOptions} for more details on what options you can use.\n * @param options - bag of options; require at least endpoint and auth to be configured\n */\n constructor(options: CosmosClientOptions);\n constructor(optionsOrConnectionString: string | CosmosClientOptions) {\n if (typeof optionsOrConnectionString === \"string\") {\n optionsOrConnectionString = parseConnectionString(optionsOrConnectionString);\n } else if (optionsOrConnectionString.connectionString) {\n const { endpoint, key } = parseConnectionString(optionsOrConnectionString.connectionString);\n optionsOrConnectionString.endpoint = endpoint;\n optionsOrConnectionString.key = key;\n }\n\n const endpoint = checkURL(optionsOrConnectionString.endpoint);\n if (!endpoint) {\n throw new Error(\"Invalid endpoint specified\");\n }\n\n if (optionsOrConnectionString.clientEncryptionOptions) {\n if (!optionsOrConnectionString.clientEncryptionOptions.keyEncryptionKeyResolver) {\n throw new Error(\n \"KeyEncryptionKeyResolver needs to be provided to enable client-side encryption.\",\n );\n }\n if (\n optionsOrConnectionString.clientEncryptionOptions.encryptionKeyTimeToLiveInSeconds &&\n optionsOrConnectionString.clientEncryptionOptions.encryptionKeyTimeToLiveInSeconds < 60\n ) {\n throw new Error(\"EncryptionKeyTimeToLiveInSeconds needs to be >= 60 seconds.\");\n }\n this.encryptionManager = new EncryptionManager(\n optionsOrConnectionString.clientEncryptionOptions.keyEncryptionKeyResolver,\n optionsOrConnectionString.clientEncryptionOptions.encryptionKeyTimeToLiveInSeconds,\n );\n }\n\n const clientConfig: ClientConfigDiagnostic =\n this.initializeClientConfigDiagnostic(optionsOrConnectionString);\n\n optionsOrConnectionString.connectionPolicy = Object.assign(\n {},\n defaultConnectionPolicy,\n optionsOrConnectionString.connectionPolicy,\n );\n\n optionsOrConnectionString.defaultHeaders = optionsOrConnectionString.defaultHeaders || {};\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.CacheControl] = \"no-cache\";\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.Version] =\n Constants.CurrentVersion;\n if (optionsOrConnectionString.consistencyLevel !== undefined) {\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.ConsistencyLevel] =\n optionsOrConnectionString.consistencyLevel;\n }\n\n if (optionsOrConnectionString.throughputBucket !== undefined) {\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.ThroughputBucket] =\n optionsOrConnectionString.throughputBucket;\n }\n\n const userAgent = getUserAgent(optionsOrConnectionString);\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.UserAgent] = userAgent;\n optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.CustomUserAgent] = userAgent;\n\n const globalEndpointManager = new GlobalEndpointManager(\n optionsOrConnectionString,\n async (diagnosticNode: DiagnosticNodeInternal, opts: RequestOptions) =>\n this.getDatabaseAccountInternal(diagnosticNode, opts),\n );\n\n if (\n optionsOrConnectionString.connectionPolicy.enablePartitionLevelFailover ||\n optionsOrConnectionString.connectionPolicy.enablePartitionLevelCircuitBreaker\n ) {\n if (!optionsOrConnectionString.connectionPolicy.enableEndpointDiscovery) {\n throw new Error(\n \"enableEndpointDiscovery must be set to true to use partition level failover or circuit breaker.\",\n );\n }\n this.globalPartitionEndpointManager = new GlobalPartitionEndpointManager(\n optionsOrConnectionString,\n globalEndpointManager,\n );\n }\n\n this.clientContext = new ClientContext(\n optionsOrConnectionString,\n globalEndpointManager,\n clientConfig,\n determineDiagnosticLevel(\n optionsOrConnectionString.diagnosticLevel,\n getDiagnosticLevelFromEnvironment(),\n ),\n this.globalPartitionEndpointManager,\n );\n if (\n optionsOrConnectionString.connectionPolicy?.enableEndpointDiscovery &&\n optionsOrConnectionString.connectionPolicy?.enableBackgroundEndpointRefreshing\n ) {\n this.backgroundRefreshEndpointList(\n globalEndpointManager,\n optionsOrConnectionString.connectionPolicy.endpointRefreshRateInMs ||\n defaultConnectionPolicy.endpointRefreshRateInMs,\n );\n }\n\n this.databases = new Databases(this, this.clientContext, this.encryptionManager);\n this.offers = new Offers(this, this.clientContext);\n }\n\n private initializeClientConfigDiagnostic(\n optionsOrConnectionString: CosmosClientOptions,\n ): ClientConfigDiagnostic {\n return {\n endpoint: optionsOrConnectionString.endpoint,\n resourceTokensConfigured: optionsOrConnectionString.resourceTokens !== undefined,\n tokenProviderConfigured: optionsOrConnectionString.tokenProvider !== undefined,\n aadCredentialsConfigured: optionsOrConnectionString.aadCredentials !== undefined,\n connectionPolicyConfigured: optionsOrConnectionString.connectionPolicy !== undefined,\n consistencyLevel: optionsOrConnectionString.consistencyLevel,\n defaultHeaders: optionsOrConnectionString.defaultHeaders,\n agentConfigured: optionsOrConnectionString.agent !== undefined,\n userAgentSuffix: optionsOrConnectionString.userAgentSuffix,\n diagnosticLevel: optionsOrConnectionString.diagnosticLevel,\n pluginsConfigured: optionsOrConnectionString.plugins !== undefined,\n sDKVersion: Constants.SDKVersion,\n };\n }\n\n /**\n * Get information about the current {@link DatabaseAccount} (including which regions are supported, etc.)\n */\n public async getDatabaseAccount(\n options?: RequestOptions,\n ): Promise<ResourceResponse<DatabaseAccount>> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n return this.getDatabaseAccountInternal(diagnosticNode, options);\n }, this.clientContext);\n }\n\n /**\n * @hidden\n */\n public async getDatabaseAccountInternal(\n diagnosticNode: DiagnosticNodeInternal,\n options?: RequestOptions,\n ): Promise<ResourceResponse<DatabaseAccount>> {\n const response = await this.clientContext.getDatabaseAccount(diagnosticNode, options);\n return new ResourceResponse<DatabaseAccount>(\n response.result,\n response.headers,\n response.code,\n getEmptyCosmosDiagnostics(),\n response.substatus,\n );\n }\n\n /**\n * Gets the currently used write endpoint url. Useful for troubleshooting purposes.\n *\n * The url may contain a region suffix (e.g. \"-eastus\") if we're using location specific endpoints.\n */\n public async getWriteEndpoint(): Promise<string> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n return this.clientContext.getWriteEndpoint(diagnosticNode);\n }, this.clientContext);\n }\n\n /**\n * Gets the currently used read endpoint. Useful for troubleshooting purposes.\n *\n * The url may contain a region suffix (e.g. \"-eastus\") if we're using location specific endpoints.\n */\n public async getReadEndpoint(): Promise<string> {\n return withDiagnostics(async (diagnosticNode: DiagnosticNodeInternal) => {\n return this.clientContext.getReadEndpoint(diagnosticNode);\n }, this.clientContext);\n }\n\n /**\n * Gets the known write endpoints. Useful for troubleshooting purposes.\n *\n * The urls may contain a region suffix (e.g. \"-eastus\") if we're using location specific endpoints.\n */\n public getWriteEndpoints(): Promise<readonly string[]> {\n return this.clientContext.getWriteEndpoints();\n }\n\n /**\n * Gets the currently used read endpoint. Useful for troubleshooting purposes.\n *\n * The url may contain a region suffix (e.g. \"-eastus\") if we're using location specific endpoints.\n */\n public getReadEndpoints(): Promise<readonly string[]> {\n return this.clientContext.getReadEndpoints();\n }\n\n /**\n * Used for reading, updating, or deleting a existing database by id or accessing containers belonging to that database.\n *\n * This does not make a network call. Use `.read` to get info about the database after getting the {@link Database} object.\n *\n * @param id - The id of the database.\n * @example Create a new container off of an existing database\n * ```ts snippet:CosmosClientDatabaseCreateContainer\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 * const container = client.database(\"<database id>\").containers.create({\n * id: \"<name here>\",\n * });\n * ```\n *\n * @example Delete an existing database\n * ```ts snippet:CosmosClientDatabaseDelete\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 * await client.database(\"<id here>\").delete();\n * ```\n */\n public database(id: string): Database {\n return new Database(this, id, this.clientContext, this.encryptionManager);\n }\n\n /**\n * Used for reading, or updating a existing offer by id.\n * @param id - The id of the offer.\n */\n public offer(id: string): Offer {\n return new Offer(this, id, this.clientContext);\n }\n\n /**\n * Clears background endpoint refresher. Use client.dispose() when destroying the CosmosClient within another process.\n */\n public dispose(): void {\n clearTimeout(this.endpointRefresher);\n if (this.clientContext.enableEncryption) {\n clearTimeout(this.encryptionManager.encryptionKeyStoreProvider.cacheRefresher);\n clearTimeout(this.encryptionManager.protectedDataEncryptionKeyCache.cacheRefresher);\n }\n if (this.globalPartitionEndpointManager) {\n this.globalPartitionEndpointManager.dispose();\n }\n }\n\n private async backgroundRefreshEndpointList(\n globalEndpointManager: GlobalEndpointManager,\n refreshRate: number,\n ) {\n this.endpointRefresher = setInterval(() => {\n try {\n return withDiagnostics(\n async (diagnosticNode: DiagnosticNodeInternal) => {\n return globalEndpointManager.refreshEndpointList(diagnosticNode);\n },\n this.clientContext,\n DiagnosticNodeType.BACKGROUND_REFRESH_THREAD,\n );\n } catch (e: any) {\n console.warn(\"Failed to refresh endpoints\", e);\n }\n }, refreshRate);\n if (this.endpointRefresher.unref && typeof this.endpointRefresher.unref === \"function\") {\n this.endpointRefresher.unref();\n }\n }\n\n /**\n * Update the host framework. If provided host framework will be used to generate the defualt SDK user agent.\n * @param hostFramework - A custom string.\n * @internal\n */\n public async updateHostFramework(hostFramework: string): Promise<void> {\n this.clientContext.refreshUserAgent(hostFramework);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ChangeFeedForPartitionKey.d.ts","sourceRoot":"","sources":["../../../../src/client/ChangeFeed/ChangeFeedForPartitionKey.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAa,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAK5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AAM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AO,CAAC,YAAY;IACpB,OAAO,CAAC,iBAAiB;IAd3B,OAAO,CAAC,iBAAiB,CAAmC;IAC5D,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,cAAc,CAAU;IAChC,OAAO,CAAC,YAAY,CAAU;YAwBhB,mBAAmB;IAgCjC,OAAO,CAAC,qCAAqC;YAO/B,cAAc;IAK5B;;OAEG;IACH,IAAI,cAAc,IAAI,OAAO,CAE5B;IAED;;OAEG;IACW,gBAAgB,IAAI,aAAa,CAAC,0BAA0B,CAAC,KAAK,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC;IAOhG;;OAEG;IACU,QAAQ,IAAI,OAAO,CAAC,0BAA0B,CAAC,KAAK,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC;IAoBjF;;OAEG;YACW,SAAS;YAWT,eAAe;CA2E9B"}
@@ -7,6 +7,7 @@ import { convertToInternalPartitionKey } from "../../documents/index.js";
7
7
  import { getEmptyCosmosDiagnostics, withDiagnostics } from "../../utils/diagnostics.js";
8
8
  import { ChangeFeedMode } from "./ChangeFeedMode.js";
9
9
  import { decryptChangeFeedResponse } from "./changeFeedUtils.js";
10
+ import { computePartitionKeyRangeId } from "../ClientUtils.js";
10
11
  /**
11
12
  * @hidden
12
13
  * Provides iterator for change feed for one partition key.
@@ -145,6 +146,8 @@ export class ChangeFeedForPartitionKey {
145
146
  feedOptions.containerRid = this.container._rid;
146
147
  }
147
148
  try {
149
+ const isPartitionLevelFailOverEnabled = this.clientContext.isPartitionLevelFailOverEnabled();
150
+ const partitionKeyRangeId = await computePartitionKeyRangeId(diagnosticNode, convertToInternalPartitionKey(this.partitionKey), this.clientContext.partitionKeyRangeCache, isPartitionLevelFailOverEnabled, this.container);
148
151
  const response = await this.clientContext.queryFeed({
149
152
  path: this.resourceLink,
150
153
  resourceType: ResourceType.item,
@@ -154,6 +157,7 @@ export class ChangeFeedForPartitionKey {
154
157
  query: undefined,
155
158
  options: feedOptions,
156
159
  partitionKey: this.partitionKey,
160
+ partitionKeyRangeId,
157
161
  });
158
162
  return new ChangeFeedIteratorResponse(response.result, response.result ? response.result.length : 0, response.code, response.headers, getEmptyCosmosDiagnostics());
159
163
  }