@azure/event-hubs 6.0.1-alpha.20250618.1 → 6.0.1-alpha.20250730.1
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.
- package/dist/browser/batchingPartitionChannel.js +23 -17
- package/dist/browser/batchingPartitionChannel.js.map +1 -1
- package/dist/browser/connectionContext.js +18 -32
- package/dist/browser/connectionContext.js.map +1 -1
- package/dist/browser/diagnostics/instrumentEventData.js +6 -7
- package/dist/browser/diagnostics/instrumentEventData.js.map +1 -1
- package/dist/browser/eventData.js +6 -4
- package/dist/browser/eventData.js.map +1 -1
- package/dist/browser/eventDataAdapter.js +5 -2
- package/dist/browser/eventDataAdapter.js.map +1 -1
- package/dist/browser/eventDataBatch.js +61 -9
- package/dist/browser/eventDataBatch.js.map +1 -1
- package/dist/browser/eventHubBufferedProducerClient.js +65 -50
- package/dist/browser/eventHubBufferedProducerClient.js.map +1 -1
- package/dist/browser/eventHubConsumerClient.js +70 -24
- package/dist/browser/eventHubConsumerClient.js.map +1 -1
- package/dist/browser/eventHubProducerClient.js +58 -15
- package/dist/browser/eventHubProducerClient.js.map +1 -1
- package/dist/browser/eventHubSender.js +118 -35
- package/dist/browser/eventHubSender.js.map +1 -1
- package/dist/browser/eventProcessor.js +27 -5
- package/dist/browser/eventProcessor.js.map +1 -1
- package/dist/browser/impl/awaitableQueue.js +6 -2
- package/dist/browser/impl/awaitableQueue.js.map +1 -1
- package/dist/browser/impl/partitionAssigner.js +2 -4
- package/dist/browser/impl/partitionAssigner.js.map +1 -1
- package/dist/browser/impl/partitionGate.js +1 -3
- package/dist/browser/impl/partitionGate.js.map +1 -1
- package/dist/browser/inMemoryCheckpointStore.js +10 -8
- package/dist/browser/inMemoryCheckpointStore.js.map +1 -1
- package/dist/browser/loadBalancerStrategies/balancedStrategy.js +1 -0
- package/dist/browser/loadBalancerStrategies/balancedStrategy.js.map +1 -1
- package/dist/browser/loadBalancerStrategies/greedyStrategy.js +1 -0
- package/dist/browser/loadBalancerStrategies/greedyStrategy.js.map +1 -1
- package/dist/browser/managementClient.js +53 -19
- package/dist/browser/managementClient.js.map +1 -1
- package/dist/browser/partitionProcessor.js +5 -2
- package/dist/browser/partitionProcessor.js.map +1 -1
- package/dist/browser/partitionPump.js +15 -6
- package/dist/browser/partitionPump.js.map +1 -1
- package/dist/browser/partitionReceiver.js +30 -25
- package/dist/browser/partitionReceiver.js.map +1 -1
- package/dist/browser/pumpManager.js +3 -1
- package/dist/browser/pumpManager.js.map +1 -1
- package/dist/browser/util/delayWithoutThrow.js +1 -1
- package/dist/browser/util/delayWithoutThrow.js.map +1 -1
- package/dist/commonjs/batchingPartitionChannel.js +23 -17
- package/dist/commonjs/batchingPartitionChannel.js.map +1 -1
- package/dist/commonjs/connectionContext.js +18 -32
- package/dist/commonjs/connectionContext.js.map +1 -1
- package/dist/commonjs/diagnostics/instrumentEventData.js +6 -7
- package/dist/commonjs/diagnostics/instrumentEventData.js.map +1 -1
- package/dist/commonjs/eventData.js +6 -4
- package/dist/commonjs/eventData.js.map +1 -1
- package/dist/commonjs/eventDataAdapter.js +5 -2
- package/dist/commonjs/eventDataAdapter.js.map +1 -1
- package/dist/commonjs/eventDataBatch.js +61 -9
- package/dist/commonjs/eventDataBatch.js.map +1 -1
- package/dist/commonjs/eventHubBufferedProducerClient.js +65 -50
- package/dist/commonjs/eventHubBufferedProducerClient.js.map +1 -1
- package/dist/commonjs/eventHubConsumerClient.js +70 -24
- package/dist/commonjs/eventHubConsumerClient.js.map +1 -1
- package/dist/commonjs/eventHubProducerClient.js +58 -15
- package/dist/commonjs/eventHubProducerClient.js.map +1 -1
- package/dist/commonjs/eventHubSender.js +118 -35
- package/dist/commonjs/eventHubSender.js.map +1 -1
- package/dist/commonjs/eventProcessor.js +27 -5
- package/dist/commonjs/eventProcessor.js.map +1 -1
- package/dist/commonjs/impl/awaitableQueue.js +6 -2
- package/dist/commonjs/impl/awaitableQueue.js.map +1 -1
- package/dist/commonjs/impl/partitionAssigner.js +2 -4
- package/dist/commonjs/impl/partitionAssigner.js.map +1 -1
- package/dist/commonjs/impl/partitionGate.js +1 -3
- package/dist/commonjs/impl/partitionGate.js.map +1 -1
- package/dist/commonjs/inMemoryCheckpointStore.js +10 -8
- package/dist/commonjs/inMemoryCheckpointStore.js.map +1 -1
- package/dist/commonjs/loadBalancerStrategies/balancedStrategy.js +1 -0
- package/dist/commonjs/loadBalancerStrategies/balancedStrategy.js.map +1 -1
- package/dist/commonjs/loadBalancerStrategies/greedyStrategy.js +1 -0
- package/dist/commonjs/loadBalancerStrategies/greedyStrategy.js.map +1 -1
- package/dist/commonjs/managementClient.js +53 -19
- package/dist/commonjs/managementClient.js.map +1 -1
- package/dist/commonjs/partitionProcessor.js +5 -2
- package/dist/commonjs/partitionProcessor.js.map +1 -1
- package/dist/commonjs/partitionPump.js +15 -6
- package/dist/commonjs/partitionPump.js.map +1 -1
- package/dist/commonjs/partitionReceiver.js +30 -25
- package/dist/commonjs/partitionReceiver.js.map +1 -1
- package/dist/commonjs/pumpManager.js +3 -1
- package/dist/commonjs/pumpManager.js.map +1 -1
- package/dist/commonjs/tsdoc-metadata.json +11 -11
- package/dist/commonjs/util/delayWithoutThrow.js +1 -1
- package/dist/commonjs/util/delayWithoutThrow.js.map +1 -1
- package/dist/esm/batchingPartitionChannel.js +23 -17
- package/dist/esm/batchingPartitionChannel.js.map +1 -1
- package/dist/esm/connectionContext.js +18 -32
- package/dist/esm/connectionContext.js.map +1 -1
- package/dist/esm/diagnostics/instrumentEventData.js +6 -7
- package/dist/esm/diagnostics/instrumentEventData.js.map +1 -1
- package/dist/esm/eventData.js +6 -4
- package/dist/esm/eventData.js.map +1 -1
- package/dist/esm/eventDataAdapter.js +5 -2
- package/dist/esm/eventDataAdapter.js.map +1 -1
- package/dist/esm/eventDataBatch.js +61 -9
- package/dist/esm/eventDataBatch.js.map +1 -1
- package/dist/esm/eventHubBufferedProducerClient.js +65 -50
- package/dist/esm/eventHubBufferedProducerClient.js.map +1 -1
- package/dist/esm/eventHubConsumerClient.js +70 -24
- package/dist/esm/eventHubConsumerClient.js.map +1 -1
- package/dist/esm/eventHubProducerClient.js +58 -15
- package/dist/esm/eventHubProducerClient.js.map +1 -1
- package/dist/esm/eventHubSender.js +118 -35
- package/dist/esm/eventHubSender.js.map +1 -1
- package/dist/esm/eventProcessor.js +27 -5
- package/dist/esm/eventProcessor.js.map +1 -1
- package/dist/esm/impl/awaitableQueue.js +6 -2
- package/dist/esm/impl/awaitableQueue.js.map +1 -1
- package/dist/esm/impl/partitionAssigner.js +2 -4
- package/dist/esm/impl/partitionAssigner.js.map +1 -1
- package/dist/esm/impl/partitionGate.js +1 -3
- package/dist/esm/impl/partitionGate.js.map +1 -1
- package/dist/esm/inMemoryCheckpointStore.js +10 -8
- package/dist/esm/inMemoryCheckpointStore.js.map +1 -1
- package/dist/esm/loadBalancerStrategies/balancedStrategy.js +1 -0
- package/dist/esm/loadBalancerStrategies/balancedStrategy.js.map +1 -1
- package/dist/esm/loadBalancerStrategies/greedyStrategy.js +1 -0
- package/dist/esm/loadBalancerStrategies/greedyStrategy.js.map +1 -1
- package/dist/esm/managementClient.js +53 -19
- package/dist/esm/managementClient.js.map +1 -1
- package/dist/esm/partitionProcessor.js +5 -2
- package/dist/esm/partitionProcessor.js.map +1 -1
- package/dist/esm/partitionPump.js +15 -6
- package/dist/esm/partitionPump.js.map +1 -1
- package/dist/esm/partitionReceiver.js +30 -25
- package/dist/esm/partitionReceiver.js.map +1 -1
- package/dist/esm/pumpManager.js +3 -1
- package/dist/esm/pumpManager.js.map +1 -1
- package/dist/esm/util/delayWithoutThrow.js +1 -1
- package/dist/esm/util/delayWithoutThrow.js.map +1 -1
- package/package.json +1 -1
|
@@ -14,10 +14,8 @@ import { getRandomName } from "./util/utils.js";
|
|
|
14
14
|
* @internal
|
|
15
15
|
*/
|
|
16
16
|
export class InMemoryCheckpointStore {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
this._committedCheckpoints = new Map();
|
|
20
|
-
}
|
|
17
|
+
_partitionOwnershipMap = new Map();
|
|
18
|
+
_committedCheckpoints = new Map();
|
|
21
19
|
/**
|
|
22
20
|
* Get the list of all existing partition ownership from the underlying data store. Could return empty
|
|
23
21
|
* results if there are is no existing ownership information.
|
|
@@ -31,7 +29,7 @@ export class InMemoryCheckpointStore {
|
|
|
31
29
|
async listOwnership(_fullyQualifiedNamespace, _eventHubName, _consumerGroup) {
|
|
32
30
|
const ownerships = [];
|
|
33
31
|
for (const value of this._partitionOwnershipMap.values()) {
|
|
34
|
-
ownerships.push(
|
|
32
|
+
ownerships.push({ ...value });
|
|
35
33
|
}
|
|
36
34
|
return ownerships;
|
|
37
35
|
}
|
|
@@ -48,7 +46,11 @@ export class InMemoryCheckpointStore {
|
|
|
48
46
|
if (!this._partitionOwnershipMap.has(ownership.partitionId) ||
|
|
49
47
|
this._partitionOwnershipMap.get(ownership.partitionId).etag === ownership.etag) {
|
|
50
48
|
const date = new Date();
|
|
51
|
-
const newOwnership =
|
|
49
|
+
const newOwnership = {
|
|
50
|
+
...ownership,
|
|
51
|
+
etag: getRandomName(),
|
|
52
|
+
lastModifiedTimeInMs: date.getTime(),
|
|
53
|
+
};
|
|
52
54
|
this._partitionOwnershipMap.set(newOwnership.partitionId, newOwnership);
|
|
53
55
|
claimedOwnerships.push(newOwnership);
|
|
54
56
|
}
|
|
@@ -63,7 +65,7 @@ export class InMemoryCheckpointStore {
|
|
|
63
65
|
async updateCheckpoint(checkpoint) {
|
|
64
66
|
throwTypeErrorIfParameterMissing("", "updateCheckpoint", "sequenceNumber", checkpoint.sequenceNumber);
|
|
65
67
|
throwTypeErrorIfParameterMissing("", "updateCheckpoint", "offset", checkpoint.offset);
|
|
66
|
-
checkpoint =
|
|
68
|
+
checkpoint = { ...checkpoint };
|
|
67
69
|
const partitionOwnership = this._partitionOwnershipMap.get(checkpoint.partitionId);
|
|
68
70
|
if (partitionOwnership) {
|
|
69
71
|
partitionOwnership.etag = getRandomName();
|
|
@@ -84,7 +86,7 @@ export class InMemoryCheckpointStore {
|
|
|
84
86
|
}
|
|
85
87
|
const checkpoints = [];
|
|
86
88
|
for (const value of partitionMap.values()) {
|
|
87
|
-
checkpoints.push(
|
|
89
|
+
checkpoints.push({ ...value });
|
|
88
90
|
}
|
|
89
91
|
return checkpoints;
|
|
90
92
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inMemoryCheckpointStore.js","sourceRoot":"","sources":["../../src/inMemoryCheckpointStore.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,gCAAgC,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD;;;;;;;;;;GAUG;AACH,MAAM,OAAO,uBAAuB;
|
|
1
|
+
{"version":3,"file":"inMemoryCheckpointStore.js","sourceRoot":"","sources":["../../src/inMemoryCheckpointStore.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,gCAAgC,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD;;;;;;;;;;GAUG;AACH,MAAM,OAAO,uBAAuB;IAC1B,sBAAsB,GAAoC,IAAI,GAAG,EAAE,CAAC;IACpE,qBAAqB,GAAyC,IAAI,GAAG,EAAE,CAAC;IAEhF;;;;;;;;;OASG;IACH,KAAK,CAAC,aAAa,CACjB,wBAAgC,EAChC,aAAqB,EACrB,cAAsB;QAEtB,MAAM,UAAU,GAAG,EAAE,CAAC;QAEtB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,sBAAsB,CAAC,MAAM,EAAE,EAAE,CAAC;YACzD,UAAU,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;QAChC,CAAC;QAED,OAAO,UAAU,CAAC;IACpB,CAAC;IAED;;;;;;OAMG;IACH,KA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,CAAC,YAAY,IAAI,UAAU,CAAC,aAAa,EAAE,CAAC;YAC3G,IAAI,YAAY,GAAG,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YAEvD,IAAI,YAAY,IAAI,IAAI,EAAE,CAAC;gBACzB,YAAY,GAAG,IAAI,GAAG,EAAE,CAAC;gBACzB,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC;YACpD,CAAC;YAED,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;IAED,KAAK,CAAC,eAAe,CACnB,uBAA+B,EAC/B,YAAoB,EACpB,aAAqB;QAErB,MAAM,GAAG,GAAG,GAAG,uBAAuB,IAAI,YAAY,IAAI,aAAa,EAAE,CAAC;QAE1E,MAAM,YAAY,GAAG,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAEzD,IAAI,YAAY,IAAI,IAAI,EAAE,CAAC;YACzB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,WAAW,GAAG,EAAE,CAAC;QAEvB,KAAK,MAAM,KAAK,IAAI,YAAY,CAAC,MAAM,EAAE,EAAE,CAAC;YAC1C,WAAW,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;QACjC,CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { CheckpointStore, PartitionOwnership } from \"./eventProcessor.js\";\nimport type { Checkpoint } from \"./partitionProcessor.js\";\nimport { throwTypeErrorIfParameterMissing } from \"./util/error.js\";\nimport { getRandomName } from \"./util/utils.js\";\n\n/**\n * The `EventProcessor` relies on a `CheckpointStore` to store checkpoints and handle partition\n * ownerships. `InMemoryCheckpointStore` is simple partition manager that stores checkpoints and\n * partition ownerships in memory of your program.\n *\n * You can use the `InMemoryCheckpointStore` to get started with using the `EventProcessor`.\n * But in production, you should choose an implementation of the `CheckpointStore` interface that will\n * store the checkpoints and partition ownerships to a durable store instead.\n *\n * @internal\n */\nexport class InMemoryCheckpointStore implements CheckpointStore {\n private _partitionOwnershipMap: Map<string, PartitionOwnership> = new Map();\n private _committedCheckpoints: Map<string, Map<string, Checkpoint>> = new Map();\n\n /**\n * Get the list of all existing partition ownership from the underlying data store. Could return empty\n * results if there are is no existing ownership information.\n *\n * @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net.\n * @param eventHubName - The event hub name.\n * @param consumerGroup - The consumer group name.\n * @returns Partition ownership details of all the partitions that have/had an owner..\n */\n async listOwnership(\n _fullyQualifiedNamespace: string,\n _eventHubName: string,\n _consumerGroup: string,\n ): Promise<PartitionOwnership[]> {\n const ownerships = [];\n\n for (const value of this._partitionOwnershipMap.values()) {\n ownerships.push({ ...value });\n }\n\n return ownerships;\n }\n\n /**\n * Claim ownership of a list of partitions. This will return the list of partitions that were owned\n * successfully.\n *\n * @param partitionOwnership - The list of partition ownership this instance is claiming to own.\n * @returns A list partitions this instance successfully claimed ownership.\n */\n async claimOwnership(partitionOwnership: PartitionOwnership[]): Promise<PartitionOwnership[]> {\n const claimedOwnerships = [];\n\n for (const ownership of partitionOwnership) {\n if (\n !this._partitionOwnershipMap.has(ownership.partitionId) ||\n this._partitionOwnershipMap.get(ownership.partitionId)!.etag === ownership.etag\n ) {\n const date = new Date();\n\n const newOwnership = {\n ...ownership,\n etag: getRandomName(),\n lastModifiedTimeInMs: date.getTime(),\n };\n\n this._partitionOwnershipMap.set(newOwnership.partitionId, newOwnership);\n claimedOwnerships.push(newOwnership);\n }\n }\n return claimedOwnerships;\n }\n\n /**\n * Updates the checkpoint in the data store for a partition.\n *\n * @param checkpoint - The checkpoint.\n */\n async updateCheckpoint(checkpoint: Checkpoint): Promise<void> {\n throwTypeErrorIfParameterMissing(\n \"\",\n \"updateCheckpoint\",\n \"sequenceNumber\",\n checkpoint.sequenceNumber,\n );\n throwTypeErrorIfParameterMissing(\"\", \"updateCheckpoint\", \"offset\", checkpoint.offset);\n\n checkpoint = { ...checkpoint };\n\n const partitionOwnership = this._partitionOwnershipMap.get(checkpoint.partitionId);\n if (partitionOwnership) {\n partitionOwnership.etag = getRandomName();\n\n const key = `${checkpoint.fullyQualifiedNamespace}:${checkpoint.eventHubName}:${checkpoint.consumerGroup}`;\n let partitionMap = this._committedCheckpoints.get(key);\n\n if (partitionMap == null) {\n partitionMap = new Map();\n this._committedCheckpoints.set(key, partitionMap);\n }\n\n partitionMap.set(checkpoint.partitionId, checkpoint);\n }\n }\n\n async listCheckpoints(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n consumerGroup: string,\n ): Promise<Checkpoint[]> {\n const key = `${fullyQualifiedNamespace}:${eventHubName}:${consumerGroup}`;\n\n const partitionMap = this._committedCheckpoints.get(key);\n\n if (partitionMap == null) {\n return [];\n }\n\n const checkpoints = [];\n\n for (const value of partitionMap.values()) {\n checkpoints.push({ ...value });\n }\n\n return checkpoints;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"balancedStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/balancedStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAGrE;;;;;;;;GAQG;AACH,MAAM,OAAO,6BAA6B;
|
|
1
|
+
{"version":3,"file":"balancedStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/balancedStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAGrE;;;;;;;;GAQG;AACH,MAAM,OAAO,6BAA6B;IAMX;IAL7B;;;;OAIG;IACH,YAA6B,yCAAiD;QAAjD,8CAAyC,GAAzC,yCAAyC,CAAQ;IAAG,CAAC;IAElF;;;;;;;OAOG;IACI,oBAAoB,CACzB,UAAkB,EAClB,4BAA6D,EAC7D,YAAsB;QAEtB,MAAM,mBAAmB,GAAG,uBAAuB,CACjD,UAAU,EACV,4BAA4B,EAC5B,YAAY,EACZ,IAAI,CAAC,yCAAyC,CAC/C,CAAC;QAEF,IAAI,CAAC,mBAAmB,CAAC,MAAM,EAAE,CAAC;YAChC,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;QAC3E,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC,CAAC;IAC5C,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { LoadBalancingStrategy } from \"./loadBalancingStrategy.js\";\nimport { listAvailablePartitions } from \"./loadBalancingStrategy.js\";\nimport type { PartitionOwnership } from \"../eventProcessor.js\";\n\n/**\n * The BalancedLoadBalancerStrategy is meant to be used when the user\n * wants to reach a load balanced state with less partition 'thrashing'.\n *\n * Partition thrashing - where a partition changes owners - is minimized\n * by only returning a single partition to claim at a time.\n * This minimizes the number of times a partition should need to be stolen.\n * @internal\n */\nexport class BalancedLoadBalancingStrategy implements LoadBalancingStrategy {\n /**\n * Creates an instance of BalancedLoadBalancingStrategy.\n *\n * @param _partitionOwnershipExpirationIntervalInMs - The length of time a partition claim is valid.\n */\n constructor(private readonly _partitionOwnershipExpirationIntervalInMs: number) {}\n\n /**\n * Implements load balancing by taking into account current ownership and\n * the full set of partitions in the Event Hub.\n * @param ourOwnerId - The id we should assume is _our_ id when checking for ownership.\n * @param claimedPartitionOwnershipMap - The current claimed ownerships for partitions.\n * @param partitionIds - Partitions to assign owners to.\n * @returns Partition ids to claim.\n */\n public getPartitionsToClaim(\n ourOwnerId: string,\n claimedPartitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIds: string[],\n ): string[] {\n const claimablePartitions = listAvailablePartitions(\n ourOwnerId,\n claimedPartitionOwnershipMap,\n partitionIds,\n this._partitionOwnershipExpirationIntervalInMs,\n );\n\n if (!claimablePartitions.length) {\n return [];\n }\n\n const randomIndex = Math.floor(Math.random() * claimablePartitions.length);\n return [claimablePartitions[randomIndex]];\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"greedyStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/greedyStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAGrE;;GAEG;AACH,MAAM,OAAO,2BAA2B;
|
|
1
|
+
{"version":3,"file":"greedyStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/greedyStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAGrE;;GAEG;AACH,MAAM,OAAO,2BAA2B;IAMT;IAL7B;;;;OAIG;IACH,YAA6B,yCAAiD;QAAjD,8CAAyC,GAAzC,yCAAyC,CAAQ;IAAG,CAAC;IAElF;;;;;;;OAOG;IACI,oBAAoB,CACzB,UAAkB,EAClB,4BAA6D,EAC7D,YAAsB;QAEtB,OAAO,uBAAuB,CAC5B,UAAU,EACV,4BAA4B,EAC5B,YAAY,EACZ,IAAI,CAAC,yCAAyC,CAC/C,CAAC;IACJ,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { LoadBalancingStrategy } from \"./loadBalancingStrategy.js\";\nimport { listAvailablePartitions } from \"./loadBalancingStrategy.js\";\nimport type { PartitionOwnership } from \"../eventProcessor.js\";\n\n/**\n * @internal\n */\nexport class GreedyLoadBalancingStrategy implements LoadBalancingStrategy {\n /**\n * Creates an instance of GreedyLoadBalancingStrategy.\n *\n * @param _partitionOwnershipExpirationIntervalInMs - The length of time a partition claim is valid.\n */\n constructor(private readonly _partitionOwnershipExpirationIntervalInMs: number) {}\n\n /**\n * Implements load balancing by taking into account current ownership and\n * the new set of partitions to add.\n * @param ourOwnerId - The id we should assume is _our_ id when checking for ownership.\n * @param claimedPartitionOwnershipMap - The current claimed ownerships for partitions.\n * @param partitionIds - Partitions to assign owners to.\n * @returns Partition ids to claim.\n */\n public getPartitionsToClaim(\n ourOwnerId: string,\n claimedPartitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIds: string[],\n ): string[] {\n return listAvailablePartitions(\n ourOwnerId,\n claimedPartitionOwnershipMap,\n partitionIds,\n this._partitionOwnershipExpirationIntervalInMs,\n );\n }\n}\n"]}
|
|
@@ -14,6 +14,40 @@ import { getRandomName } from "./util/utils.js";
|
|
|
14
14
|
* to the $management endpoint over AMQP connection.
|
|
15
15
|
*/
|
|
16
16
|
export class ManagementClient {
|
|
17
|
+
managementLock = getRandomName(Constants.managementRequestKey);
|
|
18
|
+
/**
|
|
19
|
+
* The name/path of the entity (hub name) for which the management
|
|
20
|
+
* request needs to be made.
|
|
21
|
+
*/
|
|
22
|
+
entityPath;
|
|
23
|
+
/**
|
|
24
|
+
* The reply to Guid for the management client.
|
|
25
|
+
*/
|
|
26
|
+
replyTo = getRandomName();
|
|
27
|
+
/**
|
|
28
|
+
* $management sender, receiver on the same session.
|
|
29
|
+
*/
|
|
30
|
+
_mgmtReqResLink;
|
|
31
|
+
/**
|
|
32
|
+
* The address in the following form:
|
|
33
|
+
* `"$management"`.
|
|
34
|
+
*/
|
|
35
|
+
address;
|
|
36
|
+
/**
|
|
37
|
+
* The token audience in the following form:
|
|
38
|
+
* `"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/$management"`.
|
|
39
|
+
*/
|
|
40
|
+
audience;
|
|
41
|
+
/**
|
|
42
|
+
* Provides relevant information about the amqp connection,
|
|
43
|
+
* cbs and $management sessions, token provider, sender and receivers.
|
|
44
|
+
*/
|
|
45
|
+
_context;
|
|
46
|
+
/**
|
|
47
|
+
* The authentication loop that keeps the token refreshed.
|
|
48
|
+
*/
|
|
49
|
+
authLoop;
|
|
50
|
+
logger;
|
|
17
51
|
/**
|
|
18
52
|
* Instantiates the management client.
|
|
19
53
|
* @param context - The connection context.
|
|
@@ -21,13 +55,8 @@ export class ManagementClient {
|
|
|
21
55
|
* `/messages/events/$management`.
|
|
22
56
|
*/
|
|
23
57
|
constructor(context, { address, audience } = {}) {
|
|
24
|
-
this.
|
|
25
|
-
|
|
26
|
-
* The reply to Guid for the management client.
|
|
27
|
-
*/
|
|
28
|
-
this.replyTo = getRandomName();
|
|
29
|
-
this.address = address !== null && address !== void 0 ? address : Constants.management;
|
|
30
|
-
this.audience = audience !== null && audience !== void 0 ? audience : context.config.getManagementAudience();
|
|
58
|
+
this.address = address ?? Constants.management;
|
|
59
|
+
this.audience = audience ?? context.config.getManagementAudience();
|
|
31
60
|
this._context = context;
|
|
32
61
|
const logPrefix = createManagementLogPrefix(this._context.connectionId);
|
|
33
62
|
this.logger = createSimpleLogger(logger, logPrefix);
|
|
@@ -68,10 +97,13 @@ export class ManagementClient {
|
|
|
68
97
|
operation: Constants.readOperation,
|
|
69
98
|
name: this.entityPath,
|
|
70
99
|
type: `${Constants.vendorString}:${Constants.eventHub}`,
|
|
71
|
-
security_token: securityToken
|
|
100
|
+
security_token: securityToken?.token,
|
|
72
101
|
},
|
|
73
102
|
};
|
|
74
|
-
const info = await this._makeManagementRequest(request,
|
|
103
|
+
const info = await this._makeManagementRequest(request, {
|
|
104
|
+
...updatedOptions,
|
|
105
|
+
requestName: "getHubRuntimeInformation",
|
|
106
|
+
});
|
|
75
107
|
const runtimeInfo = {
|
|
76
108
|
name: info.name,
|
|
77
109
|
createdOn: new Date(info.created_at),
|
|
@@ -82,7 +114,7 @@ export class ManagementClient {
|
|
|
82
114
|
return runtimeInfo;
|
|
83
115
|
}
|
|
84
116
|
catch (error) {
|
|
85
|
-
logger.warning(`an error occurred while getting the hub runtime information: ${error
|
|
117
|
+
logger.warning(`an error occurred while getting the hub runtime information: ${error?.name}: ${error?.message}`);
|
|
86
118
|
logErrorStackTrace(error);
|
|
87
119
|
throw error;
|
|
88
120
|
}
|
|
@@ -108,10 +140,13 @@ export class ManagementClient {
|
|
|
108
140
|
name: this.entityPath,
|
|
109
141
|
type: `${Constants.vendorString}:${Constants.partition}`,
|
|
110
142
|
partition: `${partitionId}`,
|
|
111
|
-
security_token: securityToken
|
|
143
|
+
security_token: securityToken?.token,
|
|
112
144
|
},
|
|
113
145
|
};
|
|
114
|
-
const info = await this._makeManagementRequest(request,
|
|
146
|
+
const info = await this._makeManagementRequest(request, {
|
|
147
|
+
...updatedOptions,
|
|
148
|
+
requestName: "getPartitionInformation",
|
|
149
|
+
});
|
|
115
150
|
const partitionInfo = {
|
|
116
151
|
beginningSequenceNumber: info.begin_sequence_number,
|
|
117
152
|
eventHubName: info.name,
|
|
@@ -125,7 +160,7 @@ export class ManagementClient {
|
|
|
125
160
|
return partitionInfo;
|
|
126
161
|
}
|
|
127
162
|
catch (error) {
|
|
128
|
-
logger.warning(`an error occurred while getting the partition information: ${error
|
|
163
|
+
logger.warning(`an error occurred while getting the partition information: ${error?.name}: ${error?.message}`);
|
|
129
164
|
logErrorStackTrace(error);
|
|
130
165
|
throw error;
|
|
131
166
|
}
|
|
@@ -136,10 +171,9 @@ export class ManagementClient {
|
|
|
136
171
|
* returning a promise that will be resolved when disconnection is completed.
|
|
137
172
|
*/
|
|
138
173
|
async close() {
|
|
139
|
-
var _a;
|
|
140
174
|
try {
|
|
141
175
|
// Always stop the auth loop when closing the management link.
|
|
142
|
-
|
|
176
|
+
this.authLoop?.stop();
|
|
143
177
|
if (this._isMgmtRequestResponseLinkOpen()) {
|
|
144
178
|
const mgmtLink = this._mgmtReqResLink;
|
|
145
179
|
this._mgmtReqResLink = undefined;
|
|
@@ -148,7 +182,7 @@ export class ManagementClient {
|
|
|
148
182
|
}
|
|
149
183
|
}
|
|
150
184
|
catch (err) {
|
|
151
|
-
const msg = `an error occurred while closing the management session: ${err
|
|
185
|
+
const msg = `an error occurred while closing the management session: ${err?.name}: ${err?.message}`;
|
|
152
186
|
logger.warning(msg);
|
|
153
187
|
logErrorStackTrace(err);
|
|
154
188
|
throw new Error(msg);
|
|
@@ -189,7 +223,7 @@ export class ManagementClient {
|
|
|
189
223
|
}
|
|
190
224
|
catch (err) {
|
|
191
225
|
const translatedError = translate(err);
|
|
192
|
-
logger.warning(`an error occurred while establishing the links: ${translatedError
|
|
226
|
+
logger.warning(`an error occurred while establishing the links: ${translatedError?.name}: ${translatedError?.message}`);
|
|
193
227
|
logErrorStackTrace(translatedError);
|
|
194
228
|
throw translatedError;
|
|
195
229
|
}
|
|
@@ -219,7 +253,7 @@ export class ManagementClient {
|
|
|
219
253
|
}
|
|
220
254
|
catch (err) {
|
|
221
255
|
const translatedError = translate(err);
|
|
222
|
-
logger.warning("an error occurred while creating the link: %s", `${translatedError
|
|
256
|
+
logger.warning("an error occurred while creating the link: %s", `${translatedError?.name}: ${translatedError?.message}`);
|
|
223
257
|
logErrorStackTrace(translatedError);
|
|
224
258
|
throw translatedError;
|
|
225
259
|
}
|
|
@@ -259,7 +293,7 @@ export class ManagementClient {
|
|
|
259
293
|
}
|
|
260
294
|
catch (err) {
|
|
261
295
|
const translatedError = translate(err);
|
|
262
|
-
logger.warning("an error occurred during send on management request-response link with address: %s", `${translatedError
|
|
296
|
+
logger.warning("an error occurred during send on management request-response link with address: %s", `${translatedError?.name}: ${translatedError?.message}`);
|
|
263
297
|
logErrorStackTrace(translatedError);
|
|
264
298
|
throw translatedError;
|
|
265
299
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"managementClient.js","sourceRoot":"","sources":["../../src/managementClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,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corporation.\n// Licensed under the MIT License.\n\nimport type { RetryConfig, RetryOptions, SendRequestOptions } from \"@azure/core-amqp\";\nimport {\n Constants,\n RequestResponseLink,\n RetryOperationType,\n defaultCancellableLock,\n isSasTokenProvider,\n retry,\n translate,\n} from \"@azure/core-amqp\";\nimport type { EventContext, Message, ReceiverOptions, SenderOptions } from \"rhea-promise\";\nimport { ReceiverEvents, SenderEvents } from \"rhea-promise\";\nimport type { SimpleLogger } from \"./logger.js\";\nimport {\n logErrorStackTrace,\n createSimpleLogger,\n logger,\n createManagementLogPrefix,\n} from \"./logger.js\";\nimport { throwErrorIfConnectionClosed, throwTypeErrorIfParameterMissing } from \"./util/error.js\";\nimport type { AbortSignalLike } from \"@azure/abort-controller\";\nimport type { AccessToken } from \"@azure/core-auth\";\nimport type { ConnectionContext } from \"./connectionContext.js\";\nimport type { OperationOptions } from \"./util/operationOptions.js\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing.js\";\nimport { getRetryAttemptTimeoutInMs } from \"./util/retries.js\";\nimport type { TimerLoop } from \"./util/timerLoop.js\";\nimport { withAuth } from \"./withAuth.js\";\nimport { getRandomName } from \"./util/utils.js\";\n\n/**\n * Describes the runtime information of an Event Hub.\n */\nexport interface EventHubProperties {\n /**\n * The name of the event hub.\n */\n name: string;\n /**\n * The date and time the hub was created in UTC.\n */\n createdOn: Date;\n /**\n * The slice of string partition identifiers.\n */\n partitionIds: string[];\n /**\n * Whether the hub has geographical disaster recovery enabled.\n */\n isGeoDrEnabled: boolean;\n}\n\n/**\n * Describes the runtime information of an EventHub Partition.\n */\nexport interface PartitionProperties {\n /**\n * The name of the Event Hub.\n */\n eventHubName: string;\n /**\n * Identifier of the partition within the Event Hub.\n */\n partitionId: string;\n /**\n * The starting sequence number of the partition's message log.\n */\n beginningSequenceNumber: number;\n /**\n * The last sequence number of the partition's message log.\n */\n lastEnqueuedSequenceNumber: number;\n /**\n * The offset of the last enqueued message in the partition's message log.\n */\n lastEnqueuedOffset: string;\n /**\n * The time of the last enqueued message in the partition's message log in UTC.\n */\n lastEnqueuedOnUtc: Date;\n /**\n * Indicates whether the partition is empty.\n */\n isEmpty: boolean;\n}\n\n/**\n * @internal\n */\nexport interface ManagementClientOptions {\n address?: string;\n audience?: string;\n}\n\n/**\n * @internal\n * Describes the EventHubs Management Client that talks\n * to the $management endpoint over AMQP connection.\n */\nexport class ManagementClient {\n readonly managementLock: string = getRandomName(Constants.managementRequestKey);\n /**\n * The name/path of the entity (hub name) for which the management\n * request needs to be made.\n */\n private readonly entityPath: string;\n /**\n * The reply to Guid for the management client.\n */\n private readonly replyTo: string = getRandomName();\n /**\n * $management sender, receiver on the same session.\n */\n private _mgmtReqResLink?: RequestResponseLink;\n /**\n * The address in the following form:\n * `\"$management\"`.\n */\n private readonly address: string;\n /**\n * The token audience in the following form:\n * `\"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/$management\"`.\n */\n private readonly audience: string;\n /**\n * Provides relevant information about the amqp connection,\n * cbs and $management sessions, token provider, sender and receivers.\n */\n private readonly _context: ConnectionContext;\n /**\n * The authentication loop that keeps the token refreshed.\n */\n private authLoop?: TimerLoop;\n private readonly logger: SimpleLogger;\n\n /**\n * Instantiates the management client.\n * @param context - The connection context.\n * @param address - The address for the management endpoint. For IotHub it will be\n * `/messages/events/$management`.\n */\n constructor(context: ConnectionContext, { address, audience }: ManagementClientOptions = {}) {\n this.address = address ?? Constants.management;\n this.audience = audience ?? context.config.getManagementAudience();\n this._context = context;\n const logPrefix = createManagementLogPrefix(this._context.connectionId);\n this.logger = createSimpleLogger(logger, logPrefix);\n this.entityPath = context.config.entityPath as string;\n }\n\n /**\n * Gets the security token for the management application properties.\n * @internal\n */\n async getSecurityToken(): Promise<AccessToken | null> {\n if (isSasTokenProvider(this._context.tokenCredential)) {\n // the security_token has the $management address removed from the end of the audience\n // expected audience: sb://fully.qualified.namespace/event-hub-name/$management\n const audienceParts = this.audience.split(\"/\");\n // for management links, address should be '$management'\n if (audienceParts[audienceParts.length - 1] === this.address) {\n audienceParts.pop();\n }\n const audience = audienceParts.join(\"/\");\n return this._context.tokenCredential.getToken(audience);\n }\n\n // aad credentials use the aad scope\n return this._context.tokenCredential.getToken(Constants.aadEventHubsScope);\n }\n\n /**\n * Provides the eventhub runtime information.\n */\n async getEventHubProperties(\n options: OperationOptions & { retryOptions?: RetryOptions } = {},\n ): Promise<EventHubProperties> {\n throwErrorIfConnectionClosed(this._context);\n return tracingClient.withSpan(\n \"ManagementClient.getEventHubProperties\",\n options,\n async (updatedOptions) => {\n try {\n const securityToken = await this.getSecurityToken();\n\n const request: Message = {\n body: Buffer.from(JSON.stringify([])),\n message_id: getRandomName(),\n reply_to: this.replyTo,\n application_properties: {\n operation: Constants.readOperation,\n name: this.entityPath as string,\n type: `${Constants.vendorString}:${Constants.eventHub}`,\n security_token: securityToken?.token,\n },\n };\n\n const info: any = await this._makeManagementRequest(request, {\n ...updatedOptions,\n requestName: \"getHubRuntimeInformation\",\n });\n const runtimeInfo: EventHubProperties = {\n name: info.name,\n createdOn: new Date(info.created_at),\n partitionIds: info.partition_ids,\n isGeoDrEnabled: info.georeplication_factor > 1,\n };\n logger.verbose(\"the hub runtime info is: %O\", runtimeInfo);\n\n return runtimeInfo;\n } catch (error: any) {\n logger.warning(\n `an error occurred while getting the hub runtime information: ${error?.name}: ${error?.message}`,\n );\n logErrorStackTrace(error);\n throw error;\n }\n },\n toSpanOptions(this._context.config),\n );\n }\n\n /**\n * Provides information about the specified partition.\n * @param partitionId - Partition ID for which partition information is required.\n */\n async getPartitionProperties(\n partitionId: string,\n options: OperationOptions & { retryOptions?: RetryOptions } = {},\n ): Promise<PartitionProperties> {\n throwErrorIfConnectionClosed(this._context);\n throwTypeErrorIfParameterMissing(\n this._context.connectionId,\n \"getPartitionProperties\",\n \"partitionId\",\n partitionId,\n );\n partitionId = String(partitionId);\n\n return tracingClient.withSpan(\n \"ManagementClient.getPartitionProperties\",\n options,\n async (updatedOptions) => {\n try {\n const securityToken = await this.getSecurityToken();\n const request: Message = {\n body: Buffer.from(JSON.stringify([])),\n message_id: getRandomName(),\n reply_to: this.replyTo,\n application_properties: {\n operation: Constants.readOperation,\n name: this.entityPath as string,\n type: `${Constants.vendorString}:${Constants.partition}`,\n partition: `${partitionId}`,\n security_token: securityToken?.token,\n },\n };\n\n const info: any = await this._makeManagementRequest(request, {\n ...updatedOptions,\n requestName: \"getPartitionInformation\",\n });\n\n const partitionInfo: PartitionProperties = {\n beginningSequenceNumber: info.begin_sequence_number,\n eventHubName: info.name,\n lastEnqueuedOffset: info.last_enqueued_offset,\n lastEnqueuedOnUtc: new Date(info.last_enqueued_time_utc),\n lastEnqueuedSequenceNumber: info.last_enqueued_sequence_number,\n partitionId: info.partition,\n isEmpty: info.is_partition_empty,\n };\n logger.verbose(\"the partition info is: %O.\", partitionInfo);\n return partitionInfo;\n } catch (error: any) {\n logger.warning(\n `an error occurred while getting the partition information: ${error?.name}: ${error?.message}`,\n );\n logErrorStackTrace(error);\n throw error;\n }\n },\n toSpanOptions(this._context.config),\n );\n }\n\n /**\n * Closes the AMQP management session to the Event Hub for this client,\n * returning a promise that will be resolved when disconnection is completed.\n */\n async close(): Promise<void> {\n try {\n // Always stop the auth loop when closing the management link.\n this.authLoop?.stop();\n if (this._isMgmtRequestResponseLinkOpen()) {\n const mgmtLink = this._mgmtReqResLink;\n this._mgmtReqResLink = undefined;\n await mgmtLink!.close();\n logger.info(\"successfully closed the management session.\");\n }\n } catch (err: any) {\n const msg = `an error occurred while closing the management session: ${err?.name}: ${err?.message}`;\n logger.warning(msg);\n logErrorStackTrace(err);\n throw new Error(msg);\n }\n }\n\n private async _init({\n abortSignal,\n timeoutInMs,\n }: {\n abortSignal: AbortSignalLike | undefined;\n timeoutInMs: number;\n }): Promise<void> {\n const createLink = async () => {\n const rxopt: ReceiverOptions = {\n source: { address: this.address },\n name: this.replyTo,\n target: { address: this.replyTo },\n onSessionError: (context: EventContext) => {\n const ehError = translate(context.session!.error!);\n logger.verbose(\n \"an error occurred on the session for request/response links for \" + \"$management: %O\",\n ehError,\n );\n },\n };\n const sropt: SenderOptions = {\n target: { address: this.address },\n };\n logger.verbose(\n \"creating sender/receiver links with \" + \"srOpts: %o, receiverOpts: %O.\",\n sropt,\n rxopt,\n );\n this._mgmtReqResLink = await RequestResponseLink.create(\n this._context.connection,\n sropt,\n rxopt,\n { abortSignal },\n );\n this._mgmtReqResLink.sender.on(SenderEvents.senderError, (context: EventContext) => {\n const ehError = translate(context.sender!.error!);\n logger.verbose(\"an error occurred on the $management sender link.. %O\", ehError);\n });\n this._mgmtReqResLink.receiver.on(ReceiverEvents.receiverError, (context: EventContext) => {\n const ehError = translate(context.receiver!.error!);\n logger.verbose(\"an error occurred on the $management receiver link.. %O\", ehError);\n });\n logger.verbose(\n \"created sender '%s' and receiver '%s' links\",\n this._mgmtReqResLink.sender.name,\n this._mgmtReqResLink.receiver.name,\n );\n };\n try {\n if (!this._isMgmtRequestResponseLinkOpen()) {\n // Wait for the connectionContext to be ready to open the link.\n await this._context.readyToOpenLink();\n this.authLoop = await withAuth(\n createLink,\n this._context,\n this.audience,\n timeoutInMs,\n this.logger,\n { abortSignal },\n );\n }\n } catch (err) {\n const translatedError = translate(err);\n logger.warning(\n `an error occurred while establishing the links: ${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }\n\n /**\n * Helper method to make the management request\n * @param request - The AMQP message to send\n * @param options - The options to use when sending a request over a $management link\n */\n private async _makeManagementRequest(\n request: Message,\n options: {\n retryOptions?: RetryOptions;\n abortSignal?: AbortSignalLike;\n requestName?: string;\n } = {},\n ): Promise<any> {\n const retryOptions = options.retryOptions || {};\n try {\n const abortSignal: AbortSignalLike | undefined = options && options.abortSignal;\n\n const sendOperationPromise = async (): Promise<Message> => {\n let count = 0;\n\n const retryTimeoutInMs = getRetryAttemptTimeoutInMs(options.retryOptions);\n let timeTakenByInit = 0;\n\n if (!this._isMgmtRequestResponseLinkOpen()) {\n logger.verbose(\"acquiring lock to get the management req res link.\");\n\n const initOperationStartTime = Date.now();\n try {\n await defaultCancellableLock.acquire(\n this.managementLock,\n () => {\n const acquireLockEndTime = Date.now();\n const timeoutInMs =\n retryTimeoutInMs - (acquireLockEndTime - initOperationStartTime);\n return this._init({ abortSignal, timeoutInMs });\n },\n { abortSignal, timeoutInMs: retryTimeoutInMs },\n );\n } catch (err) {\n const translatedError = translate(err);\n logger.warning(\n \"an error occurred while creating the link: %s\",\n `${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n timeTakenByInit = Date.now() - initOperationStartTime;\n }\n\n const remainingOperationTimeoutInMs = retryTimeoutInMs - timeTakenByInit;\n\n const sendRequestOptions: SendRequestOptions = {\n abortSignal: options.abortSignal,\n requestName: options.requestName,\n timeoutInMs: remainingOperationTimeoutInMs,\n };\n\n count++;\n if (count !== 1) {\n // Generate a new message_id every time after the first attempt\n request.message_id = getRandomName();\n } else if (!request.message_id) {\n // Set the message_id in the first attempt only if it is not set\n request.message_id = getRandomName();\n }\n\n return this._mgmtReqResLink!.sendRequest(request, sendRequestOptions);\n };\n\n const config: RetryConfig<Message> = Object.defineProperties(\n {\n operation: sendOperationPromise,\n operationType: RetryOperationType.management,\n abortSignal: abortSignal,\n retryOptions: retryOptions,\n },\n {\n connectionId: {\n enumerable: true,\n get: () => {\n return this._context.connectionId;\n },\n },\n },\n ) as RetryConfig<Message>;\n return (await retry<Message>(config)).body;\n } catch (err) {\n const translatedError = translate(err);\n logger.warning(\n \"an error occurred during send on management request-response link with address: %s\",\n `${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }\n\n private _isMgmtRequestResponseLinkOpen(): boolean {\n return this._mgmtReqResLink! && this._mgmtReqResLink!.isOpen();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"managementClient.js","sourceRoot":"","sources":["../../src/managementClient.ts"],"names":[],"mappings":"AAAA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AE,CAAC;gBACvC,CAAC;qBAAM,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;oBAC/B,gEAAgE;oBAChE,OAAO,CAAC,UAAU,GAAG,aAAa,EAAE,CAAC;gBACvC,CAAC;gBAED,OAAO,IAAI,CAAC,eAAgB,CAAC,WAAW,CAAC,OAAO,EAAE,kBAAkB,CAAC,CAAC;YACxE,CAAC,CAAC;YAEF,MAAM,MAAM,GAAyB,MAAM,CAAC,gBAAgB,CAC1D;gBACE,SAAS,EAAE,oBAAoB;gBAC/B,aAAa,EAAE,kBAAkB,CAAC,UAAU;gBAC5C,WAAW,EAAE,WAAW;gBACxB,YAAY,EAAE,YAAY;aAC3B,EACD;gBACE,YAAY,EAAE;oBACZ,UAAU,EAAE,IAAI;oBAChB,GAAG,EAAE,GAAG,EAAE;wBACR,OAAO,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC;oBACpC,CAAC;iBACF;aACF,CACsB,CAAC;YAC1B,OAAO,CAAC,MAAM,KAAK,CAAU,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;QAC7C,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,eAAe,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;YACvC,MAAM,CAAC,OAAO,CACZ,oFAAoF,EACpF,GAAG,eAAe,EAAE,IAAI,KAAK,eAAe,EAAE,OAAO,EAAE,CACxD,CAAC;YACF,kBAAkB,CAAC,eAAe,CAAC,CAAC;YACpC,MAAM,eAAe,CAAC;QACxB,CAAC;IACH,CAAC;IAEO,8BAA8B;QACpC,OAAO,IAAI,CAAC,eAAgB,IAAI,IAAI,CAAC,eAAgB,CAAC,MAAM,EAAE,CAAC;IACjE,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { RetryConfig, RetryOptions, SendRequestOptions } from \"@azure/core-amqp\";\nimport {\n Constants,\n RequestResponseLink,\n RetryOperationType,\n defaultCancellableLock,\n isSasTokenProvider,\n retry,\n translate,\n} from \"@azure/core-amqp\";\nimport type { EventContext, Message, ReceiverOptions, SenderOptions } from \"rhea-promise\";\nimport { ReceiverEvents, SenderEvents } from \"rhea-promise\";\nimport type { SimpleLogger } from \"./logger.js\";\nimport {\n logErrorStackTrace,\n createSimpleLogger,\n logger,\n createManagementLogPrefix,\n} from \"./logger.js\";\nimport { throwErrorIfConnectionClosed, throwTypeErrorIfParameterMissing } from \"./util/error.js\";\nimport type { AbortSignalLike } from \"@azure/abort-controller\";\nimport type { AccessToken } from \"@azure/core-auth\";\nimport type { ConnectionContext } from \"./connectionContext.js\";\nimport type { OperationOptions } from \"./util/operationOptions.js\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing.js\";\nimport { getRetryAttemptTimeoutInMs } from \"./util/retries.js\";\nimport type { TimerLoop } from \"./util/timerLoop.js\";\nimport { withAuth } from \"./withAuth.js\";\nimport { getRandomName } from \"./util/utils.js\";\n\n/**\n * Describes the runtime information of an Event Hub.\n */\nexport interface EventHubProperties {\n /**\n * The name of the event hub.\n */\n name: string;\n /**\n * The date and time the hub was created in UTC.\n */\n createdOn: Date;\n /**\n * The slice of string partition identifiers.\n */\n partitionIds: string[];\n /**\n * Whether the hub has geographical disaster recovery enabled.\n */\n isGeoDrEnabled: boolean;\n}\n\n/**\n * Describes the runtime information of an EventHub Partition.\n */\nexport interface PartitionProperties {\n /**\n * The name of the Event Hub.\n */\n eventHubName: string;\n /**\n * Identifier of the partition within the Event Hub.\n */\n partitionId: string;\n /**\n * The starting sequence number of the partition's message log.\n */\n beginningSequenceNumber: number;\n /**\n * The last sequence number of the partition's message log.\n */\n lastEnqueuedSequenceNumber: number;\n /**\n * The offset of the last enqueued message in the partition's message log.\n */\n lastEnqueuedOffset: string;\n /**\n * The time of the last enqueued message in the partition's message log in UTC.\n */\n lastEnqueuedOnUtc: Date;\n /**\n * Indicates whether the partition is empty.\n */\n isEmpty: boolean;\n}\n\n/**\n * @internal\n */\nexport interface ManagementClientOptions {\n address?: string;\n audience?: string;\n}\n\n/**\n * @internal\n * Describes the EventHubs Management Client that talks\n * to the $management endpoint over AMQP connection.\n */\nexport class ManagementClient {\n readonly managementLock: string = getRandomName(Constants.managementRequestKey);\n /**\n * The name/path of the entity (hub name) for which the management\n * request needs to be made.\n */\n private readonly entityPath: string;\n /**\n * The reply to Guid for the management client.\n */\n private readonly replyTo: string = getRandomName();\n /**\n * $management sender, receiver on the same session.\n */\n private _mgmtReqResLink?: RequestResponseLink;\n /**\n * The address in the following form:\n * `\"$management\"`.\n */\n private readonly address: string;\n /**\n * The token audience in the following form:\n * `\"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/$management\"`.\n */\n private readonly audience: string;\n /**\n * Provides relevant information about the amqp connection,\n * cbs and $management sessions, token provider, sender and receivers.\n */\n private readonly _context: ConnectionContext;\n /**\n * The authentication loop that keeps the token refreshed.\n */\n private authLoop?: TimerLoop;\n private readonly logger: SimpleLogger;\n\n /**\n * Instantiates the management client.\n * @param context - The connection context.\n * @param address - The address for the management endpoint. For IotHub it will be\n * `/messages/events/$management`.\n */\n constructor(context: ConnectionContext, { address, audience }: ManagementClientOptions = {}) {\n this.address = address ?? Constants.management;\n this.audience = audience ?? context.config.getManagementAudience();\n this._context = context;\n const logPrefix = createManagementLogPrefix(this._context.connectionId);\n this.logger = createSimpleLogger(logger, logPrefix);\n this.entityPath = context.config.entityPath as string;\n }\n\n /**\n * Gets the security token for the management application properties.\n * @internal\n */\n async getSecurityToken(): Promise<AccessToken | null> {\n if (isSasTokenProvider(this._context.tokenCredential)) {\n // the security_token has the $management address removed from the end of the audience\n // expected audience: sb://fully.qualified.namespace/event-hub-name/$management\n const audienceParts = this.audience.split(\"/\");\n // for management links, address should be '$management'\n if (audienceParts[audienceParts.length - 1] === this.address) {\n audienceParts.pop();\n }\n const audience = audienceParts.join(\"/\");\n return this._context.tokenCredential.getToken(audience);\n }\n\n // aad credentials use the aad scope\n return this._context.tokenCredential.getToken(Constants.aadEventHubsScope);\n }\n\n /**\n * Provides the eventhub runtime information.\n */\n async getEventHubProperties(\n options: OperationOptions & { retryOptions?: RetryOptions } = {},\n ): Promise<EventHubProperties> {\n throwErrorIfConnectionClosed(this._context);\n return tracingClient.withSpan(\n \"ManagementClient.getEventHubProperties\",\n options,\n async (updatedOptions) => {\n try {\n const securityToken = await this.getSecurityToken();\n\n const request: Message = {\n body: Buffer.from(JSON.stringify([])),\n message_id: getRandomName(),\n reply_to: this.replyTo,\n application_properties: {\n operation: Constants.readOperation,\n name: this.entityPath as string,\n type: `${Constants.vendorString}:${Constants.eventHub}`,\n security_token: securityToken?.token,\n },\n };\n\n const info: any = await this._makeManagementRequest(request, {\n ...updatedOptions,\n requestName: \"getHubRuntimeInformation\",\n });\n const runtimeInfo: EventHubProperties = {\n name: info.name,\n createdOn: new Date(info.created_at),\n partitionIds: info.partition_ids,\n isGeoDrEnabled: info.georeplication_factor > 1,\n };\n logger.verbose(\"the hub runtime info is: %O\", runtimeInfo);\n\n return runtimeInfo;\n } catch (error: any) {\n logger.warning(\n `an error occurred while getting the hub runtime information: ${error?.name}: ${error?.message}`,\n );\n logErrorStackTrace(error);\n throw error;\n }\n },\n toSpanOptions(this._context.config),\n );\n }\n\n /**\n * Provides information about the specified partition.\n * @param partitionId - Partition ID for which partition information is required.\n */\n async getPartitionProperties(\n partitionId: string,\n options: OperationOptions & { retryOptions?: RetryOptions } = {},\n ): Promise<PartitionProperties> {\n throwErrorIfConnectionClosed(this._context);\n throwTypeErrorIfParameterMissing(\n this._context.connectionId,\n \"getPartitionProperties\",\n \"partitionId\",\n partitionId,\n );\n partitionId = String(partitionId);\n\n return tracingClient.withSpan(\n \"ManagementClient.getPartitionProperties\",\n options,\n async (updatedOptions) => {\n try {\n const securityToken = await this.getSecurityToken();\n const request: Message = {\n body: Buffer.from(JSON.stringify([])),\n message_id: getRandomName(),\n reply_to: this.replyTo,\n application_properties: {\n operation: Constants.readOperation,\n name: this.entityPath as string,\n type: `${Constants.vendorString}:${Constants.partition}`,\n partition: `${partitionId}`,\n security_token: securityToken?.token,\n },\n };\n\n const info: any = await this._makeManagementRequest(request, {\n ...updatedOptions,\n requestName: \"getPartitionInformation\",\n });\n\n const partitionInfo: PartitionProperties = {\n beginningSequenceNumber: info.begin_sequence_number,\n eventHubName: info.name,\n lastEnqueuedOffset: info.last_enqueued_offset,\n lastEnqueuedOnUtc: new Date(info.last_enqueued_time_utc),\n lastEnqueuedSequenceNumber: info.last_enqueued_sequence_number,\n partitionId: info.partition,\n isEmpty: info.is_partition_empty,\n };\n logger.verbose(\"the partition info is: %O.\", partitionInfo);\n return partitionInfo;\n } catch (error: any) {\n logger.warning(\n `an error occurred while getting the partition information: ${error?.name}: ${error?.message}`,\n );\n logErrorStackTrace(error);\n throw error;\n }\n },\n toSpanOptions(this._context.config),\n );\n }\n\n /**\n * Closes the AMQP management session to the Event Hub for this client,\n * returning a promise that will be resolved when disconnection is completed.\n */\n async close(): Promise<void> {\n try {\n // Always stop the auth loop when closing the management link.\n this.authLoop?.stop();\n if (this._isMgmtRequestResponseLinkOpen()) {\n const mgmtLink = this._mgmtReqResLink;\n this._mgmtReqResLink = undefined;\n await mgmtLink!.close();\n logger.info(\"successfully closed the management session.\");\n }\n } catch (err: any) {\n const msg = `an error occurred while closing the management session: ${err?.name}: ${err?.message}`;\n logger.warning(msg);\n logErrorStackTrace(err);\n throw new Error(msg);\n }\n }\n\n private async _init({\n abortSignal,\n timeoutInMs,\n }: {\n abortSignal: AbortSignalLike | undefined;\n timeoutInMs: number;\n }): Promise<void> {\n const createLink = async () => {\n const rxopt: ReceiverOptions = {\n source: { address: this.address },\n name: this.replyTo,\n target: { address: this.replyTo },\n onSessionError: (context: EventContext) => {\n const ehError = translate(context.session!.error!);\n logger.verbose(\n \"an error occurred on the session for request/response links for \" + \"$management: %O\",\n ehError,\n );\n },\n };\n const sropt: SenderOptions = {\n target: { address: this.address },\n };\n logger.verbose(\n \"creating sender/receiver links with \" + \"srOpts: %o, receiverOpts: %O.\",\n sropt,\n rxopt,\n );\n this._mgmtReqResLink = await RequestResponseLink.create(\n this._context.connection,\n sropt,\n rxopt,\n { abortSignal },\n );\n this._mgmtReqResLink.sender.on(SenderEvents.senderError, (context: EventContext) => {\n const ehError = translate(context.sender!.error!);\n logger.verbose(\"an error occurred on the $management sender link.. %O\", ehError);\n });\n this._mgmtReqResLink.receiver.on(ReceiverEvents.receiverError, (context: EventContext) => {\n const ehError = translate(context.receiver!.error!);\n logger.verbose(\"an error occurred on the $management receiver link.. %O\", ehError);\n });\n logger.verbose(\n \"created sender '%s' and receiver '%s' links\",\n this._mgmtReqResLink.sender.name,\n this._mgmtReqResLink.receiver.name,\n );\n };\n try {\n if (!this._isMgmtRequestResponseLinkOpen()) {\n // Wait for the connectionContext to be ready to open the link.\n await this._context.readyToOpenLink();\n this.authLoop = await withAuth(\n createLink,\n this._context,\n this.audience,\n timeoutInMs,\n this.logger,\n { abortSignal },\n );\n }\n } catch (err) {\n const translatedError = translate(err);\n logger.warning(\n `an error occurred while establishing the links: ${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }\n\n /**\n * Helper method to make the management request\n * @param request - The AMQP message to send\n * @param options - The options to use when sending a request over a $management link\n */\n private async _makeManagementRequest(\n request: Message,\n options: {\n retryOptions?: RetryOptions;\n abortSignal?: AbortSignalLike;\n requestName?: string;\n } = {},\n ): Promise<any> {\n const retryOptions = options.retryOptions || {};\n try {\n const abortSignal: AbortSignalLike | undefined = options && options.abortSignal;\n\n const sendOperationPromise = async (): Promise<Message> => {\n let count = 0;\n\n const retryTimeoutInMs = getRetryAttemptTimeoutInMs(options.retryOptions);\n let timeTakenByInit = 0;\n\n if (!this._isMgmtRequestResponseLinkOpen()) {\n logger.verbose(\"acquiring lock to get the management req res link.\");\n\n const initOperationStartTime = Date.now();\n try {\n await defaultCancellableLock.acquire(\n this.managementLock,\n () => {\n const acquireLockEndTime = Date.now();\n const timeoutInMs =\n retryTimeoutInMs - (acquireLockEndTime - initOperationStartTime);\n return this._init({ abortSignal, timeoutInMs });\n },\n { abortSignal, timeoutInMs: retryTimeoutInMs },\n );\n } catch (err) {\n const translatedError = translate(err);\n logger.warning(\n \"an error occurred while creating the link: %s\",\n `${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n timeTakenByInit = Date.now() - initOperationStartTime;\n }\n\n const remainingOperationTimeoutInMs = retryTimeoutInMs - timeTakenByInit;\n\n const sendRequestOptions: SendRequestOptions = {\n abortSignal: options.abortSignal,\n requestName: options.requestName,\n timeoutInMs: remainingOperationTimeoutInMs,\n };\n\n count++;\n if (count !== 1) {\n // Generate a new message_id every time after the first attempt\n request.message_id = getRandomName();\n } else if (!request.message_id) {\n // Set the message_id in the first attempt only if it is not set\n request.message_id = getRandomName();\n }\n\n return this._mgmtReqResLink!.sendRequest(request, sendRequestOptions);\n };\n\n const config: RetryConfig<Message> = Object.defineProperties(\n {\n operation: sendOperationPromise,\n operationType: RetryOperationType.management,\n abortSignal: abortSignal,\n retryOptions: retryOptions,\n },\n {\n connectionId: {\n enumerable: true,\n get: () => {\n return this._context.connectionId;\n },\n },\n },\n ) as RetryConfig<Message>;\n return (await retry<Message>(config)).body;\n } catch (err) {\n const translatedError = translate(err);\n logger.warning(\n \"an error occurred during send on management request-response link with address: %s\",\n `${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }\n\n private _isMgmtRequestResponseLinkOpen(): boolean {\n return this._mgmtReqResLink! && this._mgmtReqResLink!.isOpen();\n }\n}\n"]}
|
|
@@ -12,6 +12,10 @@ import { logger } from "./logger.js";
|
|
|
12
12
|
* @internal
|
|
13
13
|
*/
|
|
14
14
|
export class PartitionProcessor {
|
|
15
|
+
_eventHandlers;
|
|
16
|
+
_checkpointStore;
|
|
17
|
+
_context;
|
|
18
|
+
_lastEnqueuedEventProperties;
|
|
15
19
|
constructor(_eventHandlers, _checkpointStore, _context) {
|
|
16
20
|
this._eventHandlers = _eventHandlers;
|
|
17
21
|
this._checkpointStore = _checkpointStore;
|
|
@@ -73,8 +77,7 @@ export class PartitionProcessor {
|
|
|
73
77
|
* events are received.
|
|
74
78
|
*/
|
|
75
79
|
async initialize() {
|
|
76
|
-
|
|
77
|
-
return (_b = (_a = this._eventHandlers).processInitialize) === null || _b === void 0 ? void 0 : _b.call(_a, this);
|
|
80
|
+
return this._eventHandlers.processInitialize?.(this);
|
|
78
81
|
}
|
|
79
82
|
/**
|
|
80
83
|
* This method is called before the partition processor is closed by the EventProcessor.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"partitionProcessor.js","sourceRoot":"","sources":["../../src/partitionProcessor.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAWlC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAyCrC;;;;;;;;;GASG;AACH,MAAM,OAAO,kBAAkB;
|
|
1
|
+
{"version":3,"file":"partitionProcessor.js","sourceRoot":"","sources":["../../src/partitionProcessor.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAWlC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAyCrC;;;;;;;;;GASG;AACH,MAAM,OAAO,kBAAkB;IAInB;IACA;IACA;IALF,4BAA4B,CAA+B;IAEnE,YACU,cAAyC,EACzC,gBAAiC,EACjC,QAEP;QAJO,mBAAc,GAAd,cAAc,CAA2B;QACzC,qBAAgB,GAAhB,gBAAgB,CAAiB;QACjC,aAAQ,GAAR,QAAQ,CAEf;IACA,CAAC;IAEJ;;;;;OAKG;IACH,IAAW,2BAA2B;QACpC,OAAO,IAAI,CAAC,4BAA6B,CAAC;IAC5C,CAAC;IAED;;;;OAIG;IACH,IAAW,2BAA2B,CAAC,UAAuC;QAC5E,IAAI,CAAC,4BAA4B,GAAG,UAAU,CAAC;IACjD,CAAC;IAED;;;OAGG;IACH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AC3E,CAAC;QACH,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACI,KAAK,CAAC,gBAAgB,CAAC,SAA4B;QACxD,MAAM,UAAU,GAAe;YAC7B,uBAAuB,EAAE,IAAI,CAAC,QAAQ,CAAC,uBAAuB;YAC9D,YAAY,EAAE,IAAI,CAAC,QAAQ,CAAC,YAAY;YACxC,aAAa,EAAE,IAAI,CAAC,QAAQ,CAAC,aAAa;YAC1C,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,WAAW;YACtC,cAAc,EAAE,SAAS,CAAC,cAAc;YACxC,MAAM,EAAE,SAAS,CAAC,MAAM;SACzB,CAAC;QAEF,MAAM,IAAI,CAAC,gBAAiB,CAAC,gBAAgB,CAAC,UAAU,CAAC,CAAC;IAC5D,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n BasicPartitionProperties,\n PartitionContext,\n SubscriptionEventHandlers,\n} from \"./eventHubConsumerClientModels.js\";\nimport type { CheckpointStore } from \"./eventProcessor.js\";\nimport type { CloseReason } from \"./models/public.js\";\nimport type { LastEnqueuedEventProperties } from \"./partitionReceiver.js\";\nimport type { ReceivedEventData } from \"./eventData.js\";\nimport { logger } from \"./logger.js\";\n\n/**\n * A checkpoint is meant to represent the last successfully processed event by the user from a particular\n * partition of a consumer group in an Event Hub instance.\n *\n * When the `updateCheckpoint()` method on the `PartitionProcessor` class is called by the user, a\n * `Checkpoint` is created internally. It is then stored in the storage solution implemented by the\n * `CheckpointManager` chosen by the user when creating an `EventProcessor`.\n *\n * Users are never expected to interact with `Checkpoint` directly. This interface exists to support the\n * internal workings of `EventProcessor` and `CheckpointManager`.\n **/\nexport interface Checkpoint {\n /**\n * The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net\n */\n fullyQualifiedNamespace: string;\n /**\n * The event hub name\n */\n eventHubName: string;\n /**\n * The consumer group name\n */\n consumerGroup: string;\n /**\n * The identifier of the Event Hub partition\n */\n partitionId: string;\n /**\n * The sequence number of the event\n */\n sequenceNumber: number;\n /**\n * The offset of the event.\n */\n offset: string;\n}\n\n/**\n * The `PartitionProcessor` is responsible for processing events received from Event Hubs when using `EventProcessor`\n *\n * The EventProcessor creates a new instance of the PartitionProcessor for each partition of the event hub it starts processing. When you extend the `PartitionProcessor` in order to customize it as you see fit,\n * - Override the `processEvents()` method to add the code to process the received events. This is also a good place to update the checkpoints using the `updateCheckpoint()` method\n * - Optionally override the `processError()` method to handle any error that might have occurred when processing the events.\n * - Optionally override the `initialize()` method to implement any set up related tasks you would want to carry out before starting to receive events from the partition\n * - Optionally override the `close()` method to implement any tear down or clean up tasks you would want to carry out.\n * @internal\n */\nexport class PartitionProcessor implements PartitionContext {\n private _lastEnqueuedEventProperties?: LastEnqueuedEventProperties;\n\n constructor(\n private _eventHandlers: SubscriptionEventHandlers,\n private _checkpointStore: CheckpointStore,\n private _context: BasicPartitionProperties & {\n eventProcessorId: string;\n },\n ) {}\n\n /**\n * Information on the last enqueued event in the partition that is being processed.\n * This property is updated by the `EventProcessor` if the `trackLastEnqueuedEventProperties` option is set to true\n * when creating an instance of EventProcessor\n * @readonly\n */\n public get lastEnqueuedEventProperties(): LastEnqueuedEventProperties {\n return this._lastEnqueuedEventProperties!;\n }\n\n /**\n * Information on the last enqueued event in the partition that is being processed.\n * This property is updated by the `EventProcessor` if the `trackLastEnqueuedEventProperties` option is set to true\n * when creating an instance of EventProcessor\n */\n public set lastEnqueuedEventProperties(properties: LastEnqueuedEventProperties) {\n this._lastEnqueuedEventProperties = properties;\n }\n\n /**\n * The fully qualified namespace from where the current partition is being processed. It is set by the `EventProcessor`\n * @readonly\n */\n public get fullyQualifiedNamespace(): string {\n return this._context.fullyQualifiedNamespace;\n }\n\n /**\n * The name of the consumer group from where the current partition is being processed. It is set by the `EventProcessor`\n * @readonly\n */\n public get consumerGroup(): string {\n return this._context.consumerGroup!;\n }\n\n /**\n * The name of the event hub to which the current partition belongs. It is set by the `EventProcessor`\n * @readonly\n */\n public get eventHubName(): string {\n return this._context.eventHubName;\n }\n\n /**\n * The identifier of the Event Hub partition that is being processed. It is set by the `EventProcessor`\n * @readonly\n */\n public get partitionId(): string {\n return this._context.partitionId;\n }\n\n /**\n * The unique identifier of the `EventProcessor` that has spawned the current instance of `PartitionProcessor`. This is set by the `EventProcessor`\n */\n public get eventProcessorId(): string {\n return this._context.eventProcessorId;\n }\n\n /**\n * This method is called when the `EventProcessor` takes ownership of a new partition and before any\n * events are received.\n */\n async initialize(): Promise<void> {\n return this._eventHandlers.processInitialize?.(this);\n }\n\n /**\n * This method is called before the partition processor is closed by the EventProcessor.\n *\n * @param reason - The reason for closing this partition processor.\n */\n async close(reason: CloseReason): Promise<void> {\n if (this._eventHandlers.processClose) {\n await this._eventHandlers.processClose(reason, this);\n }\n }\n\n /**\n * This method is called when new events are received.\n *\n * This is also a good place to update checkpoints as appropriate.\n *\n * @param event - The received events to be processed.\n */\n async processEvents(events: ReceivedEventData[]): Promise<void> {\n await this._eventHandlers.processEvents(events, this);\n }\n\n /**\n * This method is called when an error occurs while receiving events from Event Hubs.\n *\n * @param error - The error to be processed.\n */\n async processError(error: Error): Promise<void> {\n if (this._eventHandlers.processError) {\n try {\n await this._eventHandlers.processError(error, this);\n } catch (err: any) {\n logger.verbose(`Error thrown from user's processError handler : ${err}`);\n }\n }\n }\n\n /**\n * Updates the checkpoint using the event data.\n *\n * A checkpoint is meant to represent the last successfully processed event by the user from a particular\n * partition of a consumer group in an Event Hub instance.\n *\n * @param eventData - The event that you want to update the checkpoint with.\n */\n public async updateCheckpoint(eventData: ReceivedEventData): Promise<void> {\n const checkpoint: Checkpoint = {\n fullyQualifiedNamespace: this._context.fullyQualifiedNamespace,\n eventHubName: this._context.eventHubName,\n consumerGroup: this._context.consumerGroup,\n partitionId: this._context.partitionId,\n sequenceNumber: eventData.sequenceNumber,\n offset: eventData.offset,\n };\n\n await this._checkpointStore!.updateCheckpoint(checkpoint);\n }\n}\n"]}
|
|
@@ -9,11 +9,17 @@ import { extractSpanContextFromEventData } from "./diagnostics/instrumentEventDa
|
|
|
9
9
|
* @internal
|
|
10
10
|
*/
|
|
11
11
|
export class PartitionPump {
|
|
12
|
+
_context;
|
|
13
|
+
_startPosition;
|
|
14
|
+
_partitionProcessor;
|
|
15
|
+
_processorOptions;
|
|
16
|
+
_receiver;
|
|
17
|
+
_isReceiving = false;
|
|
18
|
+
_isStopped = false;
|
|
19
|
+
_abortController;
|
|
12
20
|
constructor(_context, partitionProcessor, _startPosition, options) {
|
|
13
21
|
this._context = _context;
|
|
14
22
|
this._startPosition = _startPosition;
|
|
15
|
-
this._isReceiving = false;
|
|
16
|
-
this._isStopped = false;
|
|
17
23
|
this._partitionProcessor = partitionProcessor;
|
|
18
24
|
this._processorOptions = options;
|
|
19
25
|
this._abortController = new AbortController();
|
|
@@ -123,7 +129,6 @@ export class PartitionPump {
|
|
|
123
129
|
}
|
|
124
130
|
}
|
|
125
131
|
async stop(reason) {
|
|
126
|
-
var _a;
|
|
127
132
|
if (this._isStopped) {
|
|
128
133
|
return;
|
|
129
134
|
}
|
|
@@ -134,11 +139,11 @@ export class PartitionPump {
|
|
|
134
139
|
// otherwise the receiver will remove the listener on the abortSignal
|
|
135
140
|
// before it has a chance to be emitted.
|
|
136
141
|
this._abortController.abort();
|
|
137
|
-
await
|
|
142
|
+
await this._receiver?.close();
|
|
138
143
|
await this._partitionProcessor.close(reason);
|
|
139
144
|
}
|
|
140
145
|
catch (err) {
|
|
141
|
-
logger.warning(`An error occurred while closing the receiver: ${err
|
|
146
|
+
logger.warning(`An error occurred while closing the receiver: ${err?.name}: ${err?.message}`);
|
|
142
147
|
logErrorStackTrace(err);
|
|
143
148
|
this._partitionProcessor.processError(err);
|
|
144
149
|
throw err;
|
|
@@ -161,6 +166,10 @@ export function toProcessingSpanOptions(receivedEvents, eventHubProperties) {
|
|
|
161
166
|
});
|
|
162
167
|
}
|
|
163
168
|
}
|
|
164
|
-
return
|
|
169
|
+
return {
|
|
170
|
+
spanLinks,
|
|
171
|
+
spanKind: "consumer",
|
|
172
|
+
...toSpanOptions(eventHubProperties, "process"),
|
|
173
|
+
};
|
|
165
174
|
}
|
|
166
175
|
//# sourceMappingURL=partitionPump.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"partitionPump.js","sourceRoot":"","sources":["../../src/partitionPump.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAKjD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAKxD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACxE,OAAO,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AAEvF;;GAEG;AACH,MAAM,OAAO,aAAa;IAOxB,YACU,QAA2B,EACnC,kBAAsC,EACrB,cAA6B,EAC9C,OAAoC;QAH5B,aAAQ,GAAR,QAAQ,CAAmB;QAElB,mBAAc,GAAd,cAAc,CAAe;QANxC,iBAAY,GAAY,KAAK,CAAC;QAC9B,eAAU,GAAY,KAAK,CAAC;QAQlC,IAAI,CAAC,mBAAmB,GAAG,kBAAkB,CAAC;QAC9C,IAAI,CAAC,iBAAiB,GAAG,OAAO,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,IAAI,eAAe,EAAE,CAAC;IAChD,CAAC;IAED,IAAW,WAAW;QACpB,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;IAED,KAAK,CAAC,KAAK;QACT,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QACzB,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,mBAAmB,CAAC,UAAU,EAAE,CAAC;QAC9C,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,+CAA+C;YAC/C,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MAAM,CAAA,MAAA,IAAI,CAAC,SAAS,0CAAE,KAAK,EAAE,CAAA,CAAC;YAC9B,MAAM,IAAI,CAAC,mBAAmB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC/C,CAAC;QAAC,OAAO,GAAQ,EAAE,CAAC;YAClB,MAAM,CAAC,OAAO,CAAC,iDAAiD,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,IAAI,KAAK,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,EAAE,CAAC,CAAC;YAC9F,kBAAkB,CAAC,GAAG,CAAC,CAAC;YACxB,IAAI,CAAC,mBAAmB,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC;YAC3C,MAAM,GAAG,CAAC;QACZ,CAAC;IACH,CAAC;CACF;AAED;;GAEG;AACH,MAAM,UAAU,uBAAuB,CACrC,cAAmC,EACnC,kBAAyE;IAEzE,MAAM,SAAS,GAAsB,EAAE,CAAC;IACxC,KAAK,MAAM,aAAa,IAAI,cAAc,EAAE,CAAC;QAC3C,MAAM,cAAc,GAAG,+BAA+B,CAAC,aAAa,CAAC,CAAC;QACtE,IAAI,cAAc,EAAE,CAAC;YACnB,SAAS,CAAC,IAAI,CAAC;gBACb,cAAc;gBACd,UAAU,EAAE;oBACV,YAAY,EAAE,aAAa,CAAC,eAAe,CAAC,OAAO,EAAE;iBACtD;aACF,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,uBACE,SAAS,EACT,QAAQ,EAAE,UAAU,IACjB,aAAa,CAAC,kBAAkB,EAAE,SAAS,CAAC,EAC/C;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { TracingSpanOptions, TracingSpanLink } from \"@azure/core-tracing\";\nimport { logErrorStackTrace, logger } from \"./logger.js\";\nimport { CloseReason } from \"./models/public.js\";\nimport type { CommonEventProcessorOptions } from \"./models/private.js\";\nimport type { ConnectionContext } from \"./connectionContext.js\";\nimport type { EventHubConnectionConfig } from \"./eventhubConnectionConfig.js\";\nimport type { PartitionReceiver } from \"./partitionReceiver.js\";\nimport { createReceiver } from \"./partitionReceiver.js\";\nimport type { EventPosition } from \"./eventPosition.js\";\nimport type { MessagingError } from \"@azure/core-amqp\";\nimport type { PartitionProcessor } from \"./partitionProcessor.js\";\nimport type { ReceivedEventData } from \"./eventData.js\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing.js\";\nimport { extractSpanContextFromEventData } from \"./diagnostics/instrumentEventData.js\";\n\n/**\n * @internal\n */\nexport class PartitionPump {\n private _partitionProcessor: PartitionProcessor;\n private _processorOptions: CommonEventProcessorOptions;\n private _receiver: PartitionReceiver | undefined;\n private _isReceiving: boolean = false;\n private _isStopped: boolean = false;\n private _abortController: AbortController;\n constructor(\n private _context: ConnectionContext,\n partitionProcessor: PartitionProcessor,\n private readonly _startPosition: EventPosition,\n options: CommonEventProcessorOptions,\n ) {\n this._partitionProcessor = partitionProcessor;\n this._processorOptions = options;\n this._abortController = new AbortController();\n }\n\n public get isReceiving(): boolean {\n return this._isReceiving;\n }\n\n async start(): Promise<void> {\n this._isReceiving = true;\n try {\n await this._partitionProcessor.initialize();\n } catch (err) {\n // swallow the error from the user-defined code\n this._partitionProcessor.processError(err as Error);\n }\n\n // this is intentionally not await'd - the _receiveEvents loop will continue to\n // execute and can be stopped by calling .stop()\n this._receiveEvents(this._partitionProcessor.partitionId);\n logger.info(\n `Successfully started the receiver for partition \"${this._partitionProcessor.partitionId}\".`,\n );\n }\n\n /**\n * Creates a new `PartitionReceiver` and replaces any existing receiver.\n * @param partitionId - The partition the receiver should read messages from.\n * @param lastSeenSequenceNumber - The sequence number to begin receiving messages from (exclusive).\n * If `-1`, then the PartitionPump's startPosition will be used instead.\n */\n private _setOrReplaceReceiver(\n partitionId: string,\n lastSeenSequenceNumber: number,\n ): PartitionReceiver {\n // Determine what the new EventPosition should be.\n // If this PartitionPump has received events, we'll start from the last\n // seen sequenceNumber (exclusive).\n // Otherwise, use the `_startPosition`.\n const currentEventPosition: EventPosition =\n lastSeenSequenceNumber >= 0\n ? {\n sequenceNumber: lastSeenSequenceNumber,\n isInclusive: false,\n }\n : this._startPosition;\n\n // Set or replace the PartitionPump's receiver.\n this._receiver = createReceiver(\n this._context,\n this._partitionProcessor.consumerGroup,\n this._partitionProcessor.eventProcessorId,\n partitionId,\n currentEventPosition,\n {\n ownerLevel: this._processorOptions.ownerLevel,\n trackLastEnqueuedEventProperties: this._processorOptions.trackLastEnqueuedEventProperties,\n retryOptions: this._processorOptions.retryOptions,\n skipParsingBodyAsJson: this._processorOptions.skipParsingBodyAsJson,\n prefetchCount: this._processorOptions.prefetchCount,\n },\n );\n\n return this._receiver;\n }\n\n private async _receiveEvents(partitionId: string): Promise<void> {\n let lastSeenSequenceNumber = -1;\n let receiver = this._setOrReplaceReceiver(partitionId, lastSeenSequenceNumber);\n\n while (this._isReceiving) {\n try {\n // Check if the receiver was closed so we can recreate it.\n if (receiver.isClosed) {\n receiver = this._setOrReplaceReceiver(partitionId, lastSeenSequenceNumber);\n }\n\n const receivedEvents = await receiver.receiveBatch(\n this._processorOptions.maxBatchSize,\n this._processorOptions.maxWaitTimeInSeconds,\n this._abortController.signal,\n );\n\n if (\n this._processorOptions.trackLastEnqueuedEventProperties &&\n receiver.lastEnqueuedEventProperties\n ) {\n this._partitionProcessor.lastEnqueuedEventProperties =\n receiver.lastEnqueuedEventProperties;\n }\n // avoid calling user's processEvents handler if the pump was stopped while receiving events\n if (!this._isReceiving) {\n return;\n }\n\n if (receivedEvents.length) {\n lastSeenSequenceNumber = receivedEvents[receivedEvents.length - 1].sequenceNumber;\n }\n\n await tracingClient.withSpan(\n \"PartitionPump.process\",\n {},\n () => this._partitionProcessor.processEvents(receivedEvents),\n toProcessingSpanOptions(receivedEvents, this._context.config),\n );\n } catch (err: any) {\n // check if this pump is still receiving\n // it may not be if the EventProcessor was stopped during processEvents\n if (!this._isReceiving) {\n // no longer receiving, so close was called from somewhere else\n return;\n }\n\n logger.warning(\n `An error was thrown while receiving or processing events on partition \"${this._partitionProcessor.partitionId}\"`,\n );\n logErrorStackTrace(err);\n // forward error to user's processError and swallow errors they may throw\n try {\n await this._partitionProcessor.processError(err as Error);\n } catch (errorFromUser) {\n // Using verbose over warning because this error is swallowed.\n logger.verbose(\"An error was thrown by user's processError method: \", errorFromUser);\n }\n\n // close the partition processor if a non-retryable error was encountered\n if (typeof err !== \"object\" || !(err as MessagingError).retryable) {\n try {\n // If the exception indicates that the partition was stolen (i.e some other consumer with same ownerlevel\n // started consuming the partition), update the closeReason\n if (err.code === \"ReceiverDisconnectedError\") {\n return await this.stop(CloseReason.OwnershipLost);\n }\n // this will close the pump and will break us out of the while loop\n return await this.stop(CloseReason.Shutdown);\n } catch (errorFromStop) {\n // Using verbose over warning because this error is swallowed.\n logger.verbose(\n `An error occurred while closing the receiver with reason ${CloseReason.Shutdown}: `,\n errorFromStop,\n );\n }\n }\n }\n }\n }\n\n async stop(reason: CloseReason): Promise<void> {\n if (this._isStopped) {\n return;\n }\n this._isStopped = true;\n this._isReceiving = false;\n try {\n // Trigger the cancellation before closing the receiver,\n // otherwise the receiver will remove the listener on the abortSignal\n // before it has a chance to be emitted.\n this._abortController.abort();\n await this._receiver?.close();\n await this._partitionProcessor.close(reason);\n } catch (err: any) {\n logger.warning(`An error occurred while closing the receiver: ${err?.name}: ${err?.message}`);\n logErrorStackTrace(err);\n this._partitionProcessor.processError(err);\n throw err;\n }\n }\n}\n\n/**\n * @internal\n */\nexport function toProcessingSpanOptions(\n receivedEvents: ReceivedEventData[],\n eventHubProperties: Pick<EventHubConnectionConfig, \"entityPath\" | \"host\">,\n): TracingSpanOptions {\n const spanLinks: TracingSpanLink[] = [];\n for (const receivedEvent of receivedEvents) {\n const tracingContext = extractSpanContextFromEventData(receivedEvent);\n if (tracingContext) {\n spanLinks.push({\n tracingContext,\n attributes: {\n enqueuedTime: receivedEvent.enqueuedTimeUtc.getTime(),\n },\n });\n }\n }\n return {\n spanLinks,\n spanKind: \"consumer\",\n ...toSpanOptions(eventHubProperties, \"process\"),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"partitionPump.js","sourceRoot":"","sources":["../../src/partitionPump.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAKjD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAKxD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACxE,OAAO,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AAEvF;;GAEG;AACH,MAAM,OAAO,aAAa;IAQd;IAES;IATX,mBAAmB,CAAqB;IACxC,iBAAiB,CAA8B;IAC/C,SAAS,CAAgC;IACzC,YAAY,GAAY,KAAK,CAAC;IAC9B,UAAU,GAAY,KAAK,CAAC;IAC5B,gBAAgB,CAAkB;IAC1C,YACU,QAA2B,EACnC,kBAAsC,EACrB,cAA6B,EAC9C,OAAoC;QAH5B,aAAQ,GAAR,QAAQ,CAAmB;QAElB,mBAAc,GAAd,cAAc,CAAe;QAG9C,IAAI,CAAC,mBAAmB,GAAG,kBAAkB,CAAC;QAC9C,IAAI,CAAC,iBAAiB,GAAG,OAAO,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,IAAI,eAAe,EAAE,CAAC;IAChD,CAAC;IAED,IAAW,WAAW;QACpB,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;IAED,KAAK,CAAC,KAAK;QACT,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QACzB,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,mBAAmB,CAAC,UAAU,EAAE,CAAC;QAC9C,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,+CAA+C;YAC/C,IAAI,CAAC,mBAAmB,CAAC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AE,KAAK,EAAE,CAAC;YAC9B,MAAM,IAAI,CAAC,mBAAmB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC/C,CAAC;QAAC,OAAO,GAAQ,EAAE,CAAC;YAClB,MAAM,CAAC,OAAO,CAAC,iDAAiD,GAAG,EAAE,IAAI,KAAK,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC;YAC9F,kBAAkB,CAAC,GAAG,CAAC,CAAC;YACxB,IAAI,CAAC,mBAAmB,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC;YAC3C,MAAM,GAAG,CAAC;QACZ,CAAC;IACH,CAAC;CACF;AAED;;GAEG;AACH,MAAM,UAAU,uBAAuB,CACrC,cAAmC,EACnC,kBAAyE;IAEzE,MAAM,SAAS,GAAsB,EAAE,CAAC;IACxC,KAAK,MAAM,aAAa,IAAI,cAAc,EAAE,CAAC;QAC3C,MAAM,cAAc,GAAG,+BAA+B,CAAC,aAAa,CAAC,CAAC;QACtE,IAAI,cAAc,EAAE,CAAC;YACnB,SAAS,CAAC,IAAI,CAAC;gBACb,cAAc;gBACd,UAAU,EAAE;oBACV,YAAY,EAAE,aAAa,CAAC,eAAe,CAAC,OAAO,EAAE;iBACtD;aACF,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO;QACL,SAAS;QACT,QAAQ,EAAE,UAAU;QACpB,GAAG,aAAa,CAAC,kBAAkB,EAAE,SAAS,CAAC;KAChD,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { TracingSpanOptions, TracingSpanLink } from \"@azure/core-tracing\";\nimport { logErrorStackTrace, logger } from \"./logger.js\";\nimport { CloseReason } from \"./models/public.js\";\nimport type { CommonEventProcessorOptions } from \"./models/private.js\";\nimport type { ConnectionContext } from \"./connectionContext.js\";\nimport type { EventHubConnectionConfig } from \"./eventhubConnectionConfig.js\";\nimport type { PartitionReceiver } from \"./partitionReceiver.js\";\nimport { createReceiver } from \"./partitionReceiver.js\";\nimport type { EventPosition } from \"./eventPosition.js\";\nimport type { MessagingError } from \"@azure/core-amqp\";\nimport type { PartitionProcessor } from \"./partitionProcessor.js\";\nimport type { ReceivedEventData } from \"./eventData.js\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing.js\";\nimport { extractSpanContextFromEventData } from \"./diagnostics/instrumentEventData.js\";\n\n/**\n * @internal\n */\nexport class PartitionPump {\n private _partitionProcessor: PartitionProcessor;\n private _processorOptions: CommonEventProcessorOptions;\n private _receiver: PartitionReceiver | undefined;\n private _isReceiving: boolean = false;\n private _isStopped: boolean = false;\n private _abortController: AbortController;\n constructor(\n private _context: ConnectionContext,\n partitionProcessor: PartitionProcessor,\n private readonly _startPosition: EventPosition,\n options: CommonEventProcessorOptions,\n ) {\n this._partitionProcessor = partitionProcessor;\n this._processorOptions = options;\n this._abortController = new AbortController();\n }\n\n public get isReceiving(): boolean {\n return this._isReceiving;\n }\n\n async start(): Promise<void> {\n this._isReceiving = true;\n try {\n await this._partitionProcessor.initialize();\n } catch (err) {\n // swallow the error from the user-defined code\n this._partitionProcessor.processError(err as Error);\n }\n\n // this is intentionally not await'd - the _receiveEvents loop will continue to\n // execute and can be stopped by calling .stop()\n this._receiveEvents(this._partitionProcessor.partitionId);\n logger.info(\n `Successfully started the receiver for partition \"${this._partitionProcessor.partitionId}\".`,\n );\n }\n\n /**\n * Creates a new `PartitionReceiver` and replaces any existing receiver.\n * @param partitionId - The partition the receiver should read messages from.\n * @param lastSeenSequenceNumber - The sequence number to begin receiving messages from (exclusive).\n * If `-1`, then the PartitionPump's startPosition will be used instead.\n */\n private _setOrReplaceReceiver(\n partitionId: string,\n lastSeenSequenceNumber: number,\n ): PartitionReceiver {\n // Determine what the new EventPosition should be.\n // If this PartitionPump has received events, we'll start from the last\n // seen sequenceNumber (exclusive).\n // Otherwise, use the `_startPosition`.\n const currentEventPosition: EventPosition =\n lastSeenSequenceNumber >= 0\n ? {\n sequenceNumber: lastSeenSequenceNumber,\n isInclusive: false,\n }\n : this._startPosition;\n\n // Set or replace the PartitionPump's receiver.\n this._receiver = createReceiver(\n this._context,\n this._partitionProcessor.consumerGroup,\n this._partitionProcessor.eventProcessorId,\n partitionId,\n currentEventPosition,\n {\n ownerLevel: this._processorOptions.ownerLevel,\n trackLastEnqueuedEventProperties: this._processorOptions.trackLastEnqueuedEventProperties,\n retryOptions: this._processorOptions.retryOptions,\n skipParsingBodyAsJson: this._processorOptions.skipParsingBodyAsJson,\n prefetchCount: this._processorOptions.prefetchCount,\n },\n );\n\n return this._receiver;\n }\n\n private async _receiveEvents(partitionId: string): Promise<void> {\n let lastSeenSequenceNumber = -1;\n let receiver = this._setOrReplaceReceiver(partitionId, lastSeenSequenceNumber);\n\n while (this._isReceiving) {\n try {\n // Check if the receiver was closed so we can recreate it.\n if (receiver.isClosed) {\n receiver = this._setOrReplaceReceiver(partitionId, lastSeenSequenceNumber);\n }\n\n const receivedEvents = await receiver.receiveBatch(\n this._processorOptions.maxBatchSize,\n this._processorOptions.maxWaitTimeInSeconds,\n this._abortController.signal,\n );\n\n if (\n this._processorOptions.trackLastEnqueuedEventProperties &&\n receiver.lastEnqueuedEventProperties\n ) {\n this._partitionProcessor.lastEnqueuedEventProperties =\n receiver.lastEnqueuedEventProperties;\n }\n // avoid calling user's processEvents handler if the pump was stopped while receiving events\n if (!this._isReceiving) {\n return;\n }\n\n if (receivedEvents.length) {\n lastSeenSequenceNumber = receivedEvents[receivedEvents.length - 1].sequenceNumber;\n }\n\n await tracingClient.withSpan(\n \"PartitionPump.process\",\n {},\n () => this._partitionProcessor.processEvents(receivedEvents),\n toProcessingSpanOptions(receivedEvents, this._context.config),\n );\n } catch (err: any) {\n // check if this pump is still receiving\n // it may not be if the EventProcessor was stopped during processEvents\n if (!this._isReceiving) {\n // no longer receiving, so close was called from somewhere else\n return;\n }\n\n logger.warning(\n `An error was thrown while receiving or processing events on partition \"${this._partitionProcessor.partitionId}\"`,\n );\n logErrorStackTrace(err);\n // forward error to user's processError and swallow errors they may throw\n try {\n await this._partitionProcessor.processError(err as Error);\n } catch (errorFromUser) {\n // Using verbose over warning because this error is swallowed.\n logger.verbose(\"An error was thrown by user's processError method: \", errorFromUser);\n }\n\n // close the partition processor if a non-retryable error was encountered\n if (typeof err !== \"object\" || !(err as MessagingError).retryable) {\n try {\n // If the exception indicates that the partition was stolen (i.e some other consumer with same ownerlevel\n // started consuming the partition), update the closeReason\n if (err.code === \"ReceiverDisconnectedError\") {\n return await this.stop(CloseReason.OwnershipLost);\n }\n // this will close the pump and will break us out of the while loop\n return await this.stop(CloseReason.Shutdown);\n } catch (errorFromStop) {\n // Using verbose over warning because this error is swallowed.\n logger.verbose(\n `An error occurred while closing the receiver with reason ${CloseReason.Shutdown}: `,\n errorFromStop,\n );\n }\n }\n }\n }\n }\n\n async stop(reason: CloseReason): Promise<void> {\n if (this._isStopped) {\n return;\n }\n this._isStopped = true;\n this._isReceiving = false;\n try {\n // Trigger the cancellation before closing the receiver,\n // otherwise the receiver will remove the listener on the abortSignal\n // before it has a chance to be emitted.\n this._abortController.abort();\n await this._receiver?.close();\n await this._partitionProcessor.close(reason);\n } catch (err: any) {\n logger.warning(`An error occurred while closing the receiver: ${err?.name}: ${err?.message}`);\n logErrorStackTrace(err);\n this._partitionProcessor.processError(err);\n throw err;\n }\n }\n}\n\n/**\n * @internal\n */\nexport function toProcessingSpanOptions(\n receivedEvents: ReceivedEventData[],\n eventHubProperties: Pick<EventHubConnectionConfig, \"entityPath\" | \"host\">,\n): TracingSpanOptions {\n const spanLinks: TracingSpanLink[] = [];\n for (const receivedEvent of receivedEvents) {\n const tracingContext = extractSpanContextFromEventData(receivedEvent);\n if (tracingContext) {\n spanLinks.push({\n tracingContext,\n attributes: {\n enqueuedTime: receivedEvent.enqueuedTimeUtc.getTime(),\n },\n });\n }\n }\n return {\n spanLinks,\n spanKind: \"consumer\",\n ...toSpanOptions(eventHubProperties, \"process\"),\n };\n}\n"]}
|