@azure/core-amqp 4.4.0 → 4.4.1-alpha.20250721.2
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/ConnectionContextBase.js +3 -4
- package/dist/browser/ConnectionContextBase.js.map +1 -1
- package/dist/browser/amqpAnnotatedMessage.js +11 -4
- package/dist/browser/amqpAnnotatedMessage.js.map +1 -1
- package/dist/browser/auth/tokenProvider.js +4 -0
- package/dist/browser/auth/tokenProvider.js.map +1 -1
- package/dist/browser/cbs.js +30 -18
- package/dist/browser/cbs.js.map +1 -1
- package/dist/browser/connectionConfig/connectionConfig.js +11 -3
- package/dist/browser/connectionConfig/connectionConfig.js.map +1 -1
- package/dist/browser/errors.js +37 -9
- package/dist/browser/errors.js.map +1 -1
- package/dist/browser/requestResponseLink.js +13 -11
- package/dist/browser/requestResponseLink.js.map +1 -1
- package/dist/browser/retry.js +2 -2
- package/dist/browser/retry.js.map +1 -1
- package/dist/browser/util/lock.js +4 -7
- package/dist/browser/util/lock.js.map +1 -1
- package/dist/browser/util/utils.js +1 -0
- package/dist/browser/util/utils.js.map +1 -1
- package/dist/commonjs/ConnectionContextBase.js +3 -4
- package/dist/commonjs/ConnectionContextBase.js.map +1 -1
- package/dist/commonjs/amqpAnnotatedMessage.js +11 -4
- package/dist/commonjs/amqpAnnotatedMessage.js.map +1 -1
- package/dist/commonjs/auth/tokenProvider.js +4 -0
- package/dist/commonjs/auth/tokenProvider.js.map +1 -1
- package/dist/commonjs/cbs.js +30 -18
- package/dist/commonjs/cbs.js.map +1 -1
- package/dist/commonjs/connectionConfig/connectionConfig.js +11 -3
- package/dist/commonjs/connectionConfig/connectionConfig.js.map +1 -1
- package/dist/commonjs/errors.js +37 -9
- package/dist/commonjs/errors.js.map +1 -1
- package/dist/commonjs/requestResponseLink.js +13 -11
- package/dist/commonjs/requestResponseLink.js.map +1 -1
- package/dist/commonjs/retry.js +2 -2
- package/dist/commonjs/retry.js.map +1 -1
- package/dist/commonjs/tsdoc-metadata.json +11 -11
- package/dist/commonjs/util/lock.js +4 -7
- package/dist/commonjs/util/lock.js.map +1 -1
- package/dist/commonjs/util/runtimeInfo.js +2 -2
- package/dist/commonjs/util/runtimeInfo.js.map +1 -1
- package/dist/commonjs/util/utils.js +1 -0
- package/dist/commonjs/util/utils.js.map +1 -1
- package/dist/esm/ConnectionContextBase.js +3 -4
- package/dist/esm/ConnectionContextBase.js.map +1 -1
- package/dist/esm/amqpAnnotatedMessage.js +11 -4
- package/dist/esm/amqpAnnotatedMessage.js.map +1 -1
- package/dist/esm/auth/tokenProvider.js +4 -0
- package/dist/esm/auth/tokenProvider.js.map +1 -1
- package/dist/esm/cbs.js +30 -18
- package/dist/esm/cbs.js.map +1 -1
- package/dist/esm/connectionConfig/connectionConfig.js +11 -3
- package/dist/esm/connectionConfig/connectionConfig.js.map +1 -1
- package/dist/esm/errors.js +37 -9
- package/dist/esm/errors.js.map +1 -1
- package/dist/esm/requestResponseLink.js +13 -11
- package/dist/esm/requestResponseLink.js.map +1 -1
- package/dist/esm/retry.js +2 -2
- package/dist/esm/retry.js.map +1 -1
- package/dist/esm/util/lock.js +4 -7
- package/dist/esm/util/lock.js.map +1 -1
- package/dist/esm/util/runtimeInfo.js +1 -1
- package/dist/esm/util/runtimeInfo.js.map +1 -1
- package/dist/esm/util/utils.js +1 -0
- package/dist/esm/util/utils.js.map +1 -1
- package/dist/react-native/ConnectionContextBase.js +3 -4
- package/dist/react-native/ConnectionContextBase.js.map +1 -1
- package/dist/react-native/amqpAnnotatedMessage.js +11 -4
- package/dist/react-native/amqpAnnotatedMessage.js.map +1 -1
- package/dist/react-native/auth/tokenProvider.js +4 -0
- package/dist/react-native/auth/tokenProvider.js.map +1 -1
- package/dist/react-native/cbs.js +30 -18
- package/dist/react-native/cbs.js.map +1 -1
- package/dist/react-native/connectionConfig/connectionConfig.js +11 -3
- package/dist/react-native/connectionConfig/connectionConfig.js.map +1 -1
- package/dist/react-native/errors.js +37 -9
- package/dist/react-native/errors.js.map +1 -1
- package/dist/react-native/requestResponseLink.js +13 -11
- package/dist/react-native/requestResponseLink.js.map +1 -1
- package/dist/react-native/retry.js +2 -2
- package/dist/react-native/retry.js.map +1 -1
- package/dist/react-native/util/lock.js +4 -7
- package/dist/react-native/util/lock.js.map +1 -1
- package/dist/react-native/util/runtimeInfo-react-native.mjs.map +1 -1
- package/dist/react-native/util/runtimeInfo.js +1 -2
- package/dist/react-native/util/utils.js +1 -0
- package/dist/react-native/util/utils.js.map +1 -1
- package/package.json +5 -5
|
@@ -57,7 +57,6 @@ export const ConnectionContextBase = {
|
|
|
57
57
|
* the base connection context.
|
|
58
58
|
*/
|
|
59
59
|
create(parameters) {
|
|
60
|
-
var _a, _b, _c;
|
|
61
60
|
ConnectionConfig.validate(parameters.config, {
|
|
62
61
|
isEntityPathRequired: parameters.isEntityPathRequired || false,
|
|
63
62
|
});
|
|
@@ -69,9 +68,9 @@ export const ConnectionContextBase = {
|
|
|
69
68
|
const connectionOptions = {
|
|
70
69
|
transport: (parameters.config.useDevelopmentEmulator ? Constants.TCP : Constants.TLS),
|
|
71
70
|
host: parameters.config.host,
|
|
72
|
-
hostname:
|
|
71
|
+
hostname: parameters.config.amqpHostname ?? parameters.config.host,
|
|
73
72
|
username: parameters.config.sharedAccessKeyName,
|
|
74
|
-
port:
|
|
73
|
+
port: parameters.config.port ?? (parameters.config.useDevelopmentEmulator ? 5672 : 5671),
|
|
75
74
|
reconnect: false,
|
|
76
75
|
properties: {
|
|
77
76
|
product: parameters.connectionProperties.product,
|
|
@@ -91,7 +90,7 @@ export const ConnectionContextBase = {
|
|
|
91
90
|
const host = parameters.config.host;
|
|
92
91
|
const endpoint = parameters.config.webSocketEndpointPath || "";
|
|
93
92
|
const socketOptions = parameters.config.webSocketConstructorOptions || {};
|
|
94
|
-
const port =
|
|
93
|
+
const port = parameters.config.port ?? 443;
|
|
95
94
|
connectionOptions.webSocketOptions = {
|
|
96
95
|
webSocket: socket,
|
|
97
96
|
url: `wss://${host}:${port}/${endpoint}`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConnectionContextBase.js","sourceRoot":"","sources":["../../src/ConnectionContextBase.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EACL,UAAU,EAKV,aAAa,GACd,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AA8F9C,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAE9B,MAAM,kBAAmB,SAAQ,UAAU;IACzC;;;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,OAA6B;QAC9C,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QACjD,MAAM,CAAC,eAAe,CAAC,gBAAgB,CAAC,CAAC;QACzC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,KAAK,CAAC,qBAAqB,CAAC,OAAsC;QAChE,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC;QAC1D,MAAM,CAAC,eAAe,CAAC,gBAAgB,CAAC,CAAC;QACzC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,cAAc,CAAC,OAA+B;QAClD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;QACrD,QAAQ,CAAC,eAAe,CAAC,gBAAgB,CAAC,CAAC;QAC3C,OAAO,QAAQ,CAAC;IAClB,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UAAU,EAAE,UAAU;YACtB,YAAY,EAAE,UAAU,CAAC,EAAE;YAC3B,UAAU,EAAE,IAAI,SAAS,CAAC,UAAU,EAAE,cAAc,CAAC;YACrD,MAAM,EAAE,UAAU,CAAC,MAAM;YACzB,iBAAiB;gBACf,MAAM,aAAa,GAAG,IAAI,kBAAkB,CAAC,iBAAiB,CAAC,CAAC;gBAChE,MAAM,iBAAiB,GAAG,GAAG,SAAS,CAAC,mBAAmB,IAAI,aAAa,EAAE,EAAE,CAAC;gBAChF,IAAI,CAAC,wBAAwB,GAAG,KAAK,CAAC;gBACtC,IAAI,CAAC,cAAc,GAAG,iBAAiB,CAAC;gBACxC,IAAI,CAAC,kBAAkB,GAAG,GAAG,SAAS,CAAC,cAAc,MAAM,aAAa,EAAE,EAAE,CAAC;gBAC7E,IAAI,CAAC,UAAU,GAAG,aAAa,CAAC;gBAChC,IAAI,CAAC,YAAY,GAAG,aAAa,CAAC,EAAE,CAAC;gBACrC,IAAI,CAAC,UAAU,GAAG,IAAI,SAAS,CAAC,aAAa,EAAE,iBAAiB,CAAC,CAAC;YACpE,CAAC;SACF,CAAC;QAEF,OAAO,qBAAqB,CAAC;IAC/B,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AwaitableSender, Receiver, Sender } from \"rhea-promise\";\nimport {\n Connection,\n type ConnectionOptions,\n type CreateAwaitableSenderOptions,\n type CreateReceiverOptions,\n type CreateSenderOptions,\n generate_uuid,\n} from \"rhea-promise\";\nimport { getFrameworkInfo, getPlatformInfo } from \"./util/runtimeInfo.js\";\nimport { CbsClient } from \"./cbs.js\";\nimport { ConnectionConfig } from \"./connectionConfig/connectionConfig.js\";\nimport { Constants } from \"./util/constants.js\";\nimport { isNodeLike } from \"@azure/core-util\";\n\n/**\n * Provides contextual information like the underlying amqp connection, cbs session, tokenProvider,\n * Connection config, data transformer, etc.\n */\nexport interface ConnectionContextBase {\n /**\n * The EventHub connection config that is created after\n * parsing the connection string.\n */\n readonly config: ConnectionConfig;\n /**\n * The unique lock name per connection that is used to\n * acquire the lock for establishing an amqp connection per client if one does not exist.\n */\n connectionLock: string;\n /**\n * The unique lock name per connection that is used to\n * acquire the lock for negotiating cbs claim by an entity on that connection.\n */\n negotiateClaimLock: string;\n /**\n * The underlying AMQP connection.\n */\n connection: Connection;\n /**\n * The amqp connection id that uniquely identifies the\n * connection within a process.\n */\n connectionId: string;\n /**\n * Indicates whether the close() method was\n * called on the connection object.\n */\n wasConnectionCloseCalled: boolean;\n /**\n * A reference to the cbs session ($cbs endpoint) on the\n * underlying AMQP connection for the EventHub Client.\n */\n cbsSession: CbsClient;\n /**\n * Updates the context to use a new underlying AMQP connection and new cbs session.\n */\n refreshConnection: () => void;\n}\n\n/**\n * Defines the properties that need to be set while establishing the AMQP connection.\n */\nexport interface ConnectionProperties {\n /**\n * The name of the product that will be populated as the AMQP\n * connection property. Example: \"MSJSClient\".\n */\n product: string;\n /**\n * The version of the package/sdk that is making the AMQP connection.\n */\n version: string;\n /**\n * The userAgent that needs to be set as the AMQP connection\n * property. Example: `\"/js-service-bus\"` or `\"/js-event-hubs,/js-event-processor-host=1.0.0\"`.\n */\n userAgent: string;\n}\n\n/**\n * Describes the parameters that can be provided to create the base connection context.\n */\nexport interface CreateConnectionContextBaseParameters {\n /**\n * The connection config that is created by parsing the\n * connection string.\n */\n config: ConnectionConfig;\n /**\n * Properties to be provided while creating\n * the AMQP connection.\n */\n connectionProperties: ConnectionProperties;\n /**\n * Determines whether entity path should be a part of\n * the connection config. If `true` it must be present, `false` otherwise. Default value false.\n */\n isEntityPathRequired?: boolean;\n /**\n * The duration in which the promise should\n * complete (resolve/reject). If it is not completed, then the Promise will be rejected after\n * timeout occurs. Default: `60000 milliseconds`.\n */\n operationTimeoutInMs?: number;\n}\n\nconst maxListenerLimit = 1000;\n\nclass CoreAmqpConnection extends Connection {\n /**\n * Creates an amqp sender link. Max listener limit on the sender is set to 1000 because the\n * default value of 10 in NodeJS is too low.\n * @param options - Optional parameters to create a sender link.\n * @returns Promise<Sender>.\n */\n async createSender(options?: CreateSenderOptions): Promise<Sender> {\n const sender = await super.createSender(options);\n sender.setMaxListeners(maxListenerLimit);\n return sender;\n }\n\n /**\n * Creates an awaitable amqp sender. Max listener limit on the sender is set to 1000 because the\n * default value of 10 in NodeJS is too low.\n * @param options - Optional parameters to create an awaitable sender link.\n * - If `onError` and `onSessionError` handlers are not provided then the `AwaitableSender` will\n * clear the timer and reject the Promise for all the entries of inflight send operation in its\n * `deliveryDispositionMap`.\n * - If the user is handling the reconnection of sender link or the underlying connection in it's\n * app, then the `onError` and `onSessionError` handlers must be provided by the user and (s)he\n * shall be responsible of clearing the `deliveryDispositionMap` of inflight `send()` operation.\n *\n * @returns Promise<AwaitableSender>.\n */\n async createAwaitableSender(options?: CreateAwaitableSenderOptions): Promise<AwaitableSender> {\n const sender = await super.createAwaitableSender(options);\n sender.setMaxListeners(maxListenerLimit);\n return sender;\n }\n\n /**\n * Creates an amqp receiver link. Max listener limit on the sender is set to 1000 because the\n * default value of 10 in NodeJS is too low.\n * @param options - Optional parameters to create a receiver link.\n * @returns Promise<Receiver>.\n */\n async createReceiver(options?: CreateReceiverOptions): Promise<Receiver> {\n const receiver = await super.createReceiver(options);\n receiver.setMaxListeners(maxListenerLimit);\n return receiver;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- renaming constant would be a breaking change.\nexport const ConnectionContextBase = {\n /**\n * Creates the base connection context.\n * @param parameters - Parameters to be provided to create\n * the base connection context.\n */\n create(parameters: CreateConnectionContextBaseParameters): ConnectionContextBase {\n ConnectionConfig.validate(parameters.config, {\n isEntityPathRequired: parameters.isEntityPathRequired || false,\n });\n const userAgent = parameters.connectionProperties.userAgent;\n if (userAgent.length > Constants.maxUserAgentLength) {\n throw new Error(\n `The user-agent string cannot be more than ${Constants.maxUserAgentLength} characters in length.` +\n `The given user-agent string is: ${userAgent} with length: ${userAgent.length}`,\n );\n }\n\n const connectionOptions: ConnectionOptions = {\n transport: (parameters.config.useDevelopmentEmulator ? Constants.TCP : Constants.TLS) as any,\n host: parameters.config.host,\n hostname: parameters.config.amqpHostname ?? parameters.config.host,\n username: parameters.config.sharedAccessKeyName,\n port: parameters.config.port ?? (parameters.config.useDevelopmentEmulator ? 5672 : 5671),\n reconnect: false,\n properties: {\n product: parameters.connectionProperties.product,\n version: parameters.connectionProperties.version,\n \"user-agent\": userAgent,\n platform: getPlatformInfo(),\n framework: getFrameworkInfo(),\n },\n idle_time_out: Constants.defaultConnectionIdleTimeoutInMs,\n operationTimeoutInSeconds: parameters.operationTimeoutInMs\n ? parameters.operationTimeoutInMs / 1000\n : undefined,\n };\n\n if (\n parameters.config.webSocket ||\n (!isNodeLike && typeof self !== \"undefined\" && (self as any).WebSocket)\n ) {\n const socket = parameters.config.webSocket || (self as any).WebSocket;\n const host = parameters.config.host;\n const endpoint = parameters.config.webSocketEndpointPath || \"\";\n const socketOptions = parameters.config.webSocketConstructorOptions || {};\n const port = parameters.config.port ?? 443;\n\n connectionOptions.webSocketOptions = {\n webSocket: socket,\n url: `wss://${host}:${port}/${endpoint}`,\n protocol: [\"AMQPWSB10\"],\n options: socketOptions,\n };\n }\n\n const connection = new CoreAmqpConnection(connectionOptions);\n const connectionLock = `${Constants.establishConnection}-${generate_uuid()}`;\n const connectionContextBase: ConnectionContextBase = {\n wasConnectionCloseCalled: false,\n connectionLock: connectionLock,\n negotiateClaimLock: `${Constants.negotiateClaim}-${generate_uuid()}`,\n connection: connection,\n connectionId: connection.id,\n cbsSession: new CbsClient(connection, connectionLock),\n config: parameters.config,\n refreshConnection() {\n const newConnection = new CoreAmqpConnection(connectionOptions);\n const newConnectionLock = `${Constants.establishConnection}-${generate_uuid()}`;\n this.wasConnectionCloseCalled = false;\n this.connectionLock = newConnectionLock;\n this.negotiateClaimLock = `${Constants.negotiateClaim} - ${generate_uuid()}`;\n this.connection = newConnection;\n this.connectionId = newConnection.id;\n this.cbsSession = new CbsClient(newConnection, newConnectionLock);\n },\n };\n\n return connectionContextBase;\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"ConnectionContextBase.js","sourceRoot":"","sources":["../../src/ConnectionContextBase.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EACL,UAAU,EAKV,aAAa,GACd,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AA8F9C,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAE9B,MAAM,kBAAmB,SAAQ,UAAU;IACzC;;;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,OAA6B;QAC9C,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QACjD,MAAM,CAAC,eAAe,CAAC,gBAAgB,CAAC,CAAC;QACzC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,KAAK,CAAC,qBAAqB,CAAC,OAAsC;QAChE,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC;QAC1D,MAAM,CAAC,eAAe,CAAC,gBAAgB,CAAC,CAAC;QACzC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,cAAc,CAAC,OAA+B;QAClD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;QACrD,QAAQ,CAAC,eAAe,CAAC,gBAAgB,CAAC,CAAC;QAC3C,OAAO,QAAQ,CAAC;IAClB,C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YAAY,EAAE,UAAU,CAAC,EAAE;YAC3B,UAAU,EAAE,IAAI,SAAS,CAAC,UAAU,EAAE,cAAc,CAAC;YACrD,MAAM,EAAE,UAAU,CAAC,MAAM;YACzB,iBAAiB;gBACf,MAAM,aAAa,GAAG,IAAI,kBAAkB,CAAC,iBAAiB,CAAC,CAAC;gBAChE,MAAM,iBAAiB,GAAG,GAAG,SAAS,CAAC,mBAAmB,IAAI,aAAa,EAAE,EAAE,CAAC;gBAChF,IAAI,CAAC,wBAAwB,GAAG,KAAK,CAAC;gBACtC,IAAI,CAAC,cAAc,GAAG,iBAAiB,CAAC;gBACxC,IAAI,CAAC,kBAAkB,GAAG,GAAG,SAAS,CAAC,cAAc,MAAM,aAAa,EAAE,EAAE,CAAC;gBAC7E,IAAI,CAAC,UAAU,GAAG,aAAa,CAAC;gBAChC,IAAI,CAAC,YAAY,GAAG,aAAa,CAAC,EAAE,CAAC;gBACrC,IAAI,CAAC,UAAU,GAAG,IAAI,SAAS,CAAC,aAAa,EAAE,iBAAiB,CAAC,CAAC;YACpE,CAAC;SACF,CAAC;QAEF,OAAO,qBAAqB,CAAC;IAC/B,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AwaitableSender, Receiver, Sender } from \"rhea-promise\";\nimport {\n Connection,\n type ConnectionOptions,\n type CreateAwaitableSenderOptions,\n type CreateReceiverOptions,\n type CreateSenderOptions,\n generate_uuid,\n} from \"rhea-promise\";\nimport { getFrameworkInfo, getPlatformInfo } from \"./util/runtimeInfo.js\";\nimport { CbsClient } from \"./cbs.js\";\nimport { ConnectionConfig } from \"./connectionConfig/connectionConfig.js\";\nimport { Constants } from \"./util/constants.js\";\nimport { isNodeLike } from \"@azure/core-util\";\n\n/**\n * Provides contextual information like the underlying amqp connection, cbs session, tokenProvider,\n * Connection config, data transformer, etc.\n */\nexport interface ConnectionContextBase {\n /**\n * The EventHub connection config that is created after\n * parsing the connection string.\n */\n readonly config: ConnectionConfig;\n /**\n * The unique lock name per connection that is used to\n * acquire the lock for establishing an amqp connection per client if one does not exist.\n */\n connectionLock: string;\n /**\n * The unique lock name per connection that is used to\n * acquire the lock for negotiating cbs claim by an entity on that connection.\n */\n negotiateClaimLock: string;\n /**\n * The underlying AMQP connection.\n */\n connection: Connection;\n /**\n * The amqp connection id that uniquely identifies the\n * connection within a process.\n */\n connectionId: string;\n /**\n * Indicates whether the close() method was\n * called on the connection object.\n */\n wasConnectionCloseCalled: boolean;\n /**\n * A reference to the cbs session ($cbs endpoint) on the\n * underlying AMQP connection for the EventHub Client.\n */\n cbsSession: CbsClient;\n /**\n * Updates the context to use a new underlying AMQP connection and new cbs session.\n */\n refreshConnection: () => void;\n}\n\n/**\n * Defines the properties that need to be set while establishing the AMQP connection.\n */\nexport interface ConnectionProperties {\n /**\n * The name of the product that will be populated as the AMQP\n * connection property. Example: \"MSJSClient\".\n */\n product: string;\n /**\n * The version of the package/sdk that is making the AMQP connection.\n */\n version: string;\n /**\n * The userAgent that needs to be set as the AMQP connection\n * property. Example: `\"/js-service-bus\"` or `\"/js-event-hubs,/js-event-processor-host=1.0.0\"`.\n */\n userAgent: string;\n}\n\n/**\n * Describes the parameters that can be provided to create the base connection context.\n */\nexport interface CreateConnectionContextBaseParameters {\n /**\n * The connection config that is created by parsing the\n * connection string.\n */\n config: ConnectionConfig;\n /**\n * Properties to be provided while creating\n * the AMQP connection.\n */\n connectionProperties: ConnectionProperties;\n /**\n * Determines whether entity path should be a part of\n * the connection config. If `true` it must be present, `false` otherwise. Default value false.\n */\n isEntityPathRequired?: boolean;\n /**\n * The duration in which the promise should\n * complete (resolve/reject). If it is not completed, then the Promise will be rejected after\n * timeout occurs. Default: `60000 milliseconds`.\n */\n operationTimeoutInMs?: number;\n}\n\nconst maxListenerLimit = 1000;\n\nclass CoreAmqpConnection extends Connection {\n /**\n * Creates an amqp sender link. Max listener limit on the sender is set to 1000 because the\n * default value of 10 in NodeJS is too low.\n * @param options - Optional parameters to create a sender link.\n * @returns Promise<Sender>.\n */\n async createSender(options?: CreateSenderOptions): Promise<Sender> {\n const sender = await super.createSender(options);\n sender.setMaxListeners(maxListenerLimit);\n return sender;\n }\n\n /**\n * Creates an awaitable amqp sender. Max listener limit on the sender is set to 1000 because the\n * default value of 10 in NodeJS is too low.\n * @param options - Optional parameters to create an awaitable sender link.\n * - If `onError` and `onSessionError` handlers are not provided then the `AwaitableSender` will\n * clear the timer and reject the Promise for all the entries of inflight send operation in its\n * `deliveryDispositionMap`.\n * - If the user is handling the reconnection of sender link or the underlying connection in it's\n * app, then the `onError` and `onSessionError` handlers must be provided by the user and (s)he\n * shall be responsible of clearing the `deliveryDispositionMap` of inflight `send()` operation.\n *\n * @returns Promise<AwaitableSender>.\n */\n async createAwaitableSender(options?: CreateAwaitableSenderOptions): Promise<AwaitableSender> {\n const sender = await super.createAwaitableSender(options);\n sender.setMaxListeners(maxListenerLimit);\n return sender;\n }\n\n /**\n * Creates an amqp receiver link. Max listener limit on the sender is set to 1000 because the\n * default value of 10 in NodeJS is too low.\n * @param options - Optional parameters to create a receiver link.\n * @returns Promise<Receiver>.\n */\n async createReceiver(options?: CreateReceiverOptions): Promise<Receiver> {\n const receiver = await super.createReceiver(options);\n receiver.setMaxListeners(maxListenerLimit);\n return receiver;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- renaming constant would be a breaking change.\nexport const ConnectionContextBase = {\n /**\n * Creates the base connection context.\n * @param parameters - Parameters to be provided to create\n * the base connection context.\n */\n create(parameters: CreateConnectionContextBaseParameters): ConnectionContextBase {\n ConnectionConfig.validate(parameters.config, {\n isEntityPathRequired: parameters.isEntityPathRequired || false,\n });\n const userAgent = parameters.connectionProperties.userAgent;\n if (userAgent.length > Constants.maxUserAgentLength) {\n throw new Error(\n `The user-agent string cannot be more than ${Constants.maxUserAgentLength} characters in length.` +\n `The given user-agent string is: ${userAgent} with length: ${userAgent.length}`,\n );\n }\n\n const connectionOptions: ConnectionOptions = {\n transport: (parameters.config.useDevelopmentEmulator ? Constants.TCP : Constants.TLS) as any,\n host: parameters.config.host,\n hostname: parameters.config.amqpHostname ?? parameters.config.host,\n username: parameters.config.sharedAccessKeyName,\n port: parameters.config.port ?? (parameters.config.useDevelopmentEmulator ? 5672 : 5671),\n reconnect: false,\n properties: {\n product: parameters.connectionProperties.product,\n version: parameters.connectionProperties.version,\n \"user-agent\": userAgent,\n platform: getPlatformInfo(),\n framework: getFrameworkInfo(),\n },\n idle_time_out: Constants.defaultConnectionIdleTimeoutInMs,\n operationTimeoutInSeconds: parameters.operationTimeoutInMs\n ? parameters.operationTimeoutInMs / 1000\n : undefined,\n };\n\n if (\n parameters.config.webSocket ||\n (!isNodeLike && typeof self !== \"undefined\" && (self as any).WebSocket)\n ) {\n const socket = parameters.config.webSocket || (self as any).WebSocket;\n const host = parameters.config.host;\n const endpoint = parameters.config.webSocketEndpointPath || \"\";\n const socketOptions = parameters.config.webSocketConstructorOptions || {};\n const port = parameters.config.port ?? 443;\n\n connectionOptions.webSocketOptions = {\n webSocket: socket,\n url: `wss://${host}:${port}/${endpoint}`,\n protocol: [\"AMQPWSB10\"],\n options: socketOptions,\n };\n }\n\n const connection = new CoreAmqpConnection(connectionOptions);\n const connectionLock = `${Constants.establishConnection}-${generate_uuid()}`;\n const connectionContextBase: ConnectionContextBase = {\n wasConnectionCloseCalled: false,\n connectionLock: connectionLock,\n negotiateClaimLock: `${Constants.negotiateClaim}-${generate_uuid()}`,\n connection: connection,\n connectionId: connection.id,\n cbsSession: new CbsClient(connection, connectionLock),\n config: parameters.config,\n refreshConnection() {\n const newConnection = new CoreAmqpConnection(connectionOptions);\n const newConnectionLock = `${Constants.establishConnection}-${generate_uuid()}`;\n this.wasConnectionCloseCalled = false;\n this.connectionLock = newConnectionLock;\n this.negotiateClaimLock = `${Constants.negotiateClaim} - ${generate_uuid()}`;\n this.connection = newConnection;\n this.connectionId = newConnection.id;\n this.cbsSession = new CbsClient(newConnection, newConnectionLock);\n },\n };\n\n return connectionContextBase;\n },\n};\n"]}
|
|
@@ -40,15 +40,22 @@ export const AmqpAnnotatedMessage = {
|
|
|
40
40
|
* Takes AmqpAnnotatedMessage and returns it in the RheaMessage(`Message` type from "rhea") format.
|
|
41
41
|
*/
|
|
42
42
|
toRheaMessage(msg) {
|
|
43
|
-
|
|
44
|
-
|
|
43
|
+
const rhMsg = {
|
|
44
|
+
...AmqpMessageProperties.toRheaMessageProperties(msg.properties || {}),
|
|
45
|
+
...AmqpMessageHeader.toRheaMessageHeader(msg.header || {}),
|
|
46
|
+
body: msg.body,
|
|
47
|
+
message_annotations: msg.messageAnnotations,
|
|
48
|
+
delivery_annotations: msg.deliveryAnnotations,
|
|
49
|
+
application_properties: msg.applicationProperties,
|
|
50
|
+
footer: msg.footer,
|
|
51
|
+
};
|
|
45
52
|
// There is a loss of fidelity in the TTL header if larger than uint32 max value. As a workaround
|
|
46
53
|
// we set the absolute_expiry_time and creation_time on the message based on the TTL. These
|
|
47
54
|
// values are then used to reconstruct the accurate TTL for received messages.
|
|
48
|
-
if (
|
|
55
|
+
if (msg.header?.timeToLive) {
|
|
49
56
|
const ttl = msg.header.timeToLive;
|
|
50
57
|
rhMsg.ttl = Math.min(ttl, Constants.maxUint32Value);
|
|
51
|
-
rhMsg.creation_time =
|
|
58
|
+
rhMsg.creation_time = rhMsg.creation_time ?? new Date();
|
|
52
59
|
rhMsg.absolute_expiry_time = new Date(Math.min(rhMsg.creation_time.getTime() + ttl, Constants.maxAbsoluteExpiryTime));
|
|
53
60
|
}
|
|
54
61
|
return rhMsg;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"amqpAnnotatedMessage.js","sourceRoot":"","sources":["../../src/amqpAnnotatedMessage.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;A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U,IAAI,EAAE,CAAC;YACtE,GAAG,iBAAiB,CAAC,mBAAmB,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC;YAC1D,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,mBAAmB,EAAE,GAAG,CAAC,kBAAkB;YAC3C,oBAAoB,EAAE,GAAG,CAAC,mBAAmB;YAC7C,sBAAsB,EAAE,GAAG,CAAC,qBAAqB;YACjD,MAAM,EAAE,GAAG,CAAC,MAAM;SACnB,CAAC;QAEF,iGAAiG;QACjG,2FAA2F;QAC3F,8EAA8E;QAC9E,IAAI,GAAG,CAAC,MAAM,EAAE,UAAU,EAAE,CAAC;YAC3B,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC;YAClC,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,SAAS,CAAC,cAAc,CAAC,CAAC;YACpD,KAAK,CAAC,aAAa,GAAG,KAAK,CAAC,aAAa,IAAI,IAAI,IAAI,EAAE,CAAC;YACxD,KAAK,CAAC,oBAAoB,GAAG,IAAI,IAAI,CACnC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,aAAa,CAAC,OAAO,EAAE,GAAG,GAAG,EAAE,SAAS,CAAC,qBAAqB,CAAC,CAC/E,CAAC;QACJ,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport { AmqpMessageHeader } from \"./messageHeader.js\";\nimport { AmqpMessageProperties } from \"./messageProperties.js\";\nimport type { Message as RheaMessage } from \"rhea-promise\";\nimport { Constants } from \"./util/constants.js\";\n\n/**\n * Describes the AmqpAnnotatedMessage, part of the ServiceBusReceivedMessage(as `amqpAnnotatedMessage` property).\n */\nexport interface AmqpAnnotatedMessage {\n /**\n * Describes the defined set of standard header properties of the message.\n */\n header?: AmqpMessageHeader;\n /**\n * Describes set of footer properties of the message.\n */\n footer?: { [key: string]: any };\n /**\n * A dictionary containing message attributes that will be held in the message header\n */\n messageAnnotations?: { [key: string]: any };\n /**\n * A dictionary used for delivery-specific\n * non-standard properties at the head of the message.\n */\n deliveryAnnotations?: { [key: string]: any };\n /**\n * A dictionary containing application specific message properties.\n */\n applicationProperties?: { [key: string]: any };\n /**\n * Describes the defined set of standard properties of the message.\n */\n properties?: AmqpMessageProperties;\n /**\n * The message body.\n */\n body: any;\n /**\n * The AMQP section where the data was decoded from.\n */\n bodyType?: \"data\" | \"sequence\" | \"value\";\n}\n\n/**\n * Describes the operations that can be performed on(or to get) the AmqpAnnotatedMessage.\n */\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- renaming constant would be a breaking change.\nexport const AmqpAnnotatedMessage = {\n /**\n * Takes RheaMessage(`Message` type from \"rhea\") and returns it in the AmqpAnnotatedMessage format.\n */\n fromRheaMessage(msg: RheaMessage): AmqpAnnotatedMessage {\n const amqpMsg = {\n header: AmqpMessageHeader.fromRheaMessageHeader(msg),\n footer: (msg as any).footer,\n messageAnnotations: msg.message_annotations,\n deliveryAnnotations: msg.delivery_annotations,\n applicationProperties: msg.application_properties,\n properties: AmqpMessageProperties.fromRheaMessageProperties(msg),\n body: msg.body,\n };\n if (msg.absolute_expiry_time) {\n const absoluteExpiryTime = msg.absolute_expiry_time.getTime();\n amqpMsg.properties.absoluteExpiryTime = Math.min(\n absoluteExpiryTime,\n Constants.maxAbsoluteExpiryTime,\n );\n\n // The TTL from the header can be at most approximately 49 days (uint32\n // max value milliseconds) due to the AMQP spec. In order to allow for\n // larger TTLs set by the user, we take the difference of the\n // absolute_expiry_time and the creation_time (if both are set). If either of\n // those properties is not set, we fall back to the TTL from the header.\n if (msg.creation_time) {\n amqpMsg.header.timeToLive =\n amqpMsg.properties.absoluteExpiryTime - msg.creation_time.getTime();\n }\n }\n\n return amqpMsg;\n },\n /**\n * Takes AmqpAnnotatedMessage and returns it in the RheaMessage(`Message` type from \"rhea\") format.\n */\n toRheaMessage(msg: AmqpAnnotatedMessage): RheaMessage {\n const rhMsg = {\n ...AmqpMessageProperties.toRheaMessageProperties(msg.properties || {}),\n ...AmqpMessageHeader.toRheaMessageHeader(msg.header || {}),\n body: msg.body,\n message_annotations: msg.messageAnnotations,\n delivery_annotations: msg.deliveryAnnotations,\n application_properties: msg.applicationProperties,\n footer: msg.footer,\n };\n\n // There is a loss of fidelity in the TTL header if larger than uint32 max value. As a workaround\n // we set the absolute_expiry_time and creation_time on the message based on the TTL. These\n // values are then used to reconstruct the accurate TTL for received messages.\n if (msg.header?.timeToLive) {\n const ttl = msg.header.timeToLive;\n rhMsg.ttl = Math.min(ttl, Constants.maxUint32Value);\n rhMsg.creation_time = rhMsg.creation_time ?? new Date();\n rhMsg.absolute_expiry_time = new Date(\n Math.min(rhMsg.creation_time.getTime() + ttl, Constants.maxAbsoluteExpiryTime),\n );\n }\n\n return rhMsg;\n },\n};\n"]}
|
|
@@ -31,6 +31,10 @@ export class SasTokenProviderImpl {
|
|
|
31
31
|
get isSasTokenProvider() {
|
|
32
32
|
return true;
|
|
33
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* The SASCredential containing the key name and secret key value.
|
|
36
|
+
*/
|
|
37
|
+
_credential;
|
|
34
38
|
/**
|
|
35
39
|
* Initializes a new instance of SasTokenProvider
|
|
36
40
|
* @param credential - The source `NamedKeyCredential` or `SASCredential`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokenProvider.js","sourceRoot":"","sources":["../../../src/auth/tokenProvider.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACzE,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAqBnD;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CACpC,IAIiB;IAEjB,IAAI,oBAAoB,CAAC,IAAI,CAAC,IAAI,eAAe,CAAC,IAAI,CAAC,E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Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, NamedKeyCredential, SASCredential } from \"@azure/core-auth\";\nimport { isNamedKeyCredential, isSASCredential } from \"@azure/core-auth\";\nimport { signString } from \"../util/hmacSha256.js\";\n\n/**\n * A SasTokenProvider provides an alternative to TokenCredential for providing an `AccessToken`.\n * @hidden\n */\nexport interface SasTokenProvider {\n /**\n * Property used to distinguish SasTokenProvider from TokenCredential.\n */\n isSasTokenProvider: true;\n /**\n * Gets the token provided by this provider.\n *\n * This method is called automatically by Azure SDK client libraries.\n *\n * @param audience - The audience for which the token is desired.\n */\n getToken(audience: string): Promise<AccessToken>;\n}\n\n/**\n * Creates a token provider from the provided shared access data.\n * @param data - The sharedAccessKeyName/sharedAccessKey pair or the sharedAccessSignature.\n * @hidden\n */\nexport function createSasTokenProvider(\n data:\n | { sharedAccessKeyName: string; sharedAccessKey: string }\n | { sharedAccessSignature: string }\n | NamedKeyCredential\n | SASCredential,\n): SasTokenProvider {\n if (isNamedKeyCredential(data) || isSASCredential(data)) {\n return new SasTokenProviderImpl(data);\n } else if (\"sharedAccessKeyName\" in data && \"sharedAccessKey\" in data) {\n return new SasTokenProviderImpl({ name: data.sharedAccessKeyName, key: data.sharedAccessKey });\n } else {\n return new SasTokenProviderImpl({ signature: data.sharedAccessSignature });\n }\n}\n\n/**\n * A TokenProvider that generates a Sas token:\n * `SharedAccessSignature sr=<resource>&sig=<signature>&se=<expiry>&skn=<keyname>`\n *\n * @internal\n */\nexport class SasTokenProviderImpl implements SasTokenProvider {\n /**\n * Property used to distinguish TokenProvider from TokenCredential.\n */\n get isSasTokenProvider(): true {\n return true;\n }\n\n /**\n * The SASCredential containing the key name and secret key value.\n */\n private _credential: SASCredential | NamedKeyCredential;\n\n /**\n * Initializes a new instance of SasTokenProvider\n * @param credential - The source `NamedKeyCredential` or `SASCredential`.\n */\n constructor(credential: SASCredential | NamedKeyCredential) {\n this._credential = credential;\n }\n\n /**\n * Gets the sas token for the specified audience\n * @param audience - The audience for which the token is desired.\n */\n async getToken(audience: string): Promise<AccessToken> {\n if (isNamedKeyCredential(this._credential)) {\n return createToken(\n this._credential.name,\n this._credential.key,\n Math.floor(Date.now() / 1000) + 3600,\n audience,\n );\n } else {\n return {\n token: this._credential.signature,\n expiresOnTimestamp: 0,\n };\n }\n }\n}\n\n/**\n * Creates the sas token based on the provided information.\n * @param keyName - The shared access key name.\n * @param key - The shared access key.\n * @param expiry - The time period in unix time after which the token will expire.\n * @param audience - The audience for which the token is desired.\n * @internal\n */\nasync function createToken(\n keyName: string,\n key: string,\n expiry: number,\n audience: string,\n): Promise<AccessToken> {\n audience = encodeURIComponent(audience);\n keyName = encodeURIComponent(keyName);\n const stringToSign = audience + \"\\n\" + expiry;\n\n const sig = await signString(key, stringToSign);\n return {\n token: `SharedAccessSignature sr=${audience}&sig=${sig}&se=${expiry}&skn=${keyName}`,\n expiresOnTimestamp: expiry,\n };\n}\n"]}
|
package/dist/browser/cbs.js
CHANGED
|
@@ -13,24 +13,37 @@ import { translate } from "./errors.js";
|
|
|
13
13
|
* Describes the EventHub/ServiceBus Cbs client that talks to the $cbs endpoint over AMQP connection.
|
|
14
14
|
*/
|
|
15
15
|
export class CbsClient {
|
|
16
|
+
/**
|
|
17
|
+
* CBS endpoint - "$cbs"
|
|
18
|
+
*/
|
|
19
|
+
endpoint = Constants.cbsEndpoint;
|
|
20
|
+
/**
|
|
21
|
+
* CBS replyTo - The receiver link name that the service should reply to.
|
|
22
|
+
*/
|
|
23
|
+
replyTo = `${Constants.cbsReplyTo}-${generate_uuid()}`;
|
|
24
|
+
/**
|
|
25
|
+
* The unique lock name per $cbs session per connection that is used to
|
|
26
|
+
* acquire the lock for establishing a cbs session if one does not exist for an amqp connection.
|
|
27
|
+
*/
|
|
28
|
+
cbsLock = `${Constants.negotiateCbsKey}-${generate_uuid()}`;
|
|
29
|
+
/**
|
|
30
|
+
* The unique lock name per connection that is used to
|
|
31
|
+
* acquire the lock for establishing an amqp connection if one does not exist.
|
|
32
|
+
*/
|
|
33
|
+
connectionLock;
|
|
34
|
+
/**
|
|
35
|
+
* The AMQP connection.
|
|
36
|
+
*/
|
|
37
|
+
connection;
|
|
38
|
+
/**
|
|
39
|
+
* CBS sender, receiver on the same session.
|
|
40
|
+
*/
|
|
41
|
+
_cbsSenderReceiverLink;
|
|
16
42
|
/**
|
|
17
43
|
* @param connection - The AMQP connection.
|
|
18
44
|
* @param connectionLock - A unique string (usually a guid) per connection.
|
|
19
45
|
*/
|
|
20
46
|
constructor(connection, connectionLock) {
|
|
21
|
-
/**
|
|
22
|
-
* CBS endpoint - "$cbs"
|
|
23
|
-
*/
|
|
24
|
-
this.endpoint = Constants.cbsEndpoint;
|
|
25
|
-
/**
|
|
26
|
-
* CBS replyTo - The receiver link name that the service should reply to.
|
|
27
|
-
*/
|
|
28
|
-
this.replyTo = `${Constants.cbsReplyTo}-${generate_uuid()}`;
|
|
29
|
-
/**
|
|
30
|
-
* The unique lock name per $cbs session per connection that is used to
|
|
31
|
-
* acquire the lock for establishing a cbs session if one does not exist for an amqp connection.
|
|
32
|
-
*/
|
|
33
|
-
this.cbsLock = `${Constants.negotiateCbsKey}-${generate_uuid()}`;
|
|
34
47
|
this.connection = connection;
|
|
35
48
|
this.connectionLock = connectionLock;
|
|
36
49
|
}
|
|
@@ -44,7 +57,7 @@ export class CbsClient {
|
|
|
44
57
|
async init(options = {}) {
|
|
45
58
|
const { abortSignal, timeoutInMs } = options;
|
|
46
59
|
try {
|
|
47
|
-
if (abortSignal
|
|
60
|
+
if (abortSignal?.aborted) {
|
|
48
61
|
throw new AbortError(StandardAbortMessage);
|
|
49
62
|
}
|
|
50
63
|
// Acquire the lock and establish an amqp connection if it does not exist.
|
|
@@ -89,7 +102,7 @@ export class CbsClient {
|
|
|
89
102
|
}
|
|
90
103
|
catch (err) {
|
|
91
104
|
const translatedError = translate(err);
|
|
92
|
-
logger.warning("[%s] An error occurred while establishing the cbs links: %s", this.connection.id, `${translatedError
|
|
105
|
+
logger.warning("[%s] An error occurred while establishing the cbs links: %s", this.connection.id, `${translatedError?.name}: ${translatedError?.message}`);
|
|
93
106
|
logErrorStackTrace(translatedError);
|
|
94
107
|
throw translatedError;
|
|
95
108
|
}
|
|
@@ -132,7 +145,7 @@ export class CbsClient {
|
|
|
132
145
|
async negotiateClaim(audience, token, tokenType, options = {}) {
|
|
133
146
|
const { abortSignal, timeoutInMs } = options;
|
|
134
147
|
try {
|
|
135
|
-
if (abortSignal
|
|
148
|
+
if (abortSignal?.aborted) {
|
|
136
149
|
throw new AbortError(StandardAbortMessage);
|
|
137
150
|
}
|
|
138
151
|
if (!this._cbsSenderReceiverLink) {
|
|
@@ -207,8 +220,7 @@ export class CbsClient {
|
|
|
207
220
|
* @returns `true` open, `false` closed.
|
|
208
221
|
*/
|
|
209
222
|
isOpen() {
|
|
210
|
-
|
|
211
|
-
return Boolean((_a = this._cbsSenderReceiverLink) === null || _a === void 0 ? void 0 : _a.isOpen());
|
|
223
|
+
return Boolean(this._cbsSenderReceiverLink?.isOpen());
|
|
212
224
|
}
|
|
213
225
|
_fromRheaMessageResponse(msg) {
|
|
214
226
|
const cbsResponse = {
|
package/dist/browser/cbs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cbs.js","sourceRoot":"","sources":["../../src/cbs.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAQrD,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAE3D,OAAO,EAAE,sB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CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAC5D,GAAG,CAAC;YACJ,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;YACnD,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;IAED;;;OAGG;IACI,MAAM;;QACX,OAAO,OAAO,CAAC,MAAA,IAAI,CAAC,sBAAsB,0CAAE,MAAM,EAAE,CAAC,CAAC;IACxD,CAAC;IAEO,wBAAwB,CAAC,GAAgB;QAC/C,MAAM,WAAW,GAAG;YAClB,aAAa,EAAE,GAAG,CAAC,cAAyB;YAC5C,UAAU,EAAE,GAAG,CAAC,sBAAsB,CAAC,CAAC,CAAC,GAAG,CAAC,sBAAsB,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,EAAE;YACvF,iBAAiB,EAAE,GAAG,CAAC,sBAAsB;gBAC3C,CAAC,CAAC,GAAG,CAAC,sBAAsB,CAAC,oBAAoB,CAAC;gBAClD,CAAC,CAAC,EAAE;SACP,CAAC;QACF,MAAM,CAAC,OAAO,CAAC,2CAA2C,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC;QAC7F,OAAO,WAAW,CAAC;IACrB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AbortError } from \"@azure/abort-controller\";\nimport type {\n Connection,\n EventContext,\n ReceiverOptions,\n Message as RheaMessage,\n SenderOptions,\n} from \"rhea-promise\";\nimport { ReceiverEvents, SenderEvents, generate_uuid } from \"rhea-promise\";\nimport { logErrorStackTrace, logger } from \"./log.js\";\nimport { Constants } from \"./util/constants.js\";\nimport { RequestResponseLink } from \"./requestResponseLink.js\";\nimport { StandardAbortMessage } from \"./util/constants.js\";\nimport type { TokenType } from \"./auth/token.js\";\nimport { defaultCancellableLock } from \"./util/utils.js\";\nimport { isError } from \"@azure/core-util\";\nimport { translate } from \"./errors.js\";\n\n/**\n * Describes the CBS Response.\n */\nexport interface CbsResponse {\n correlationId: string;\n statusCode: string;\n statusDescription: string;\n}\n\n/**\n * Describes the EventHub/ServiceBus Cbs client that talks to the $cbs endpoint over AMQP connection.\n */\nexport class CbsClient {\n /**\n * CBS endpoint - \"$cbs\"\n */\n readonly endpoint: string = Constants.cbsEndpoint;\n /**\n * CBS replyTo - The receiver link name that the service should reply to.\n */\n readonly replyTo: string = `${Constants.cbsReplyTo}-${generate_uuid()}`;\n /**\n * The unique lock name per $cbs session per connection that is used to\n * acquire the lock for establishing a cbs session if one does not exist for an amqp connection.\n */\n readonly cbsLock: string = `${Constants.negotiateCbsKey}-${generate_uuid()}`;\n /**\n * The unique lock name per connection that is used to\n * acquire the lock for establishing an amqp connection if one does not exist.\n */\n readonly connectionLock: string;\n /**\n * The AMQP connection.\n */\n connection: Connection;\n\n /**\n * CBS sender, receiver on the same session.\n */\n private _cbsSenderReceiverLink?: RequestResponseLink;\n\n /**\n * @param connection - The AMQP connection.\n * @param connectionLock - A unique string (usually a guid) per connection.\n */\n constructor(connection: Connection, connectionLock: string) {\n this.connection = connection;\n this.connectionLock = connectionLock;\n }\n\n /**\n * Creates a singleton instance of the CBS session if it hasn't been initialized previously on\n * the given connection.\n * @param options - Optional parameters that can be used to affect this method's behavior.\n * For example, `abortSignal` can be passed to allow cancelling an in-progress `init` invocation.\n * @returns Promise<void>.\n */\n async init(options: { abortSignal?: AbortSignalLike; timeoutInMs?: number } = {}): Promise<void> {\n const { abortSignal, timeoutInMs } = options;\n\n try {\n if (abortSignal?.aborted) {\n throw new AbortError(StandardAbortMessage);\n }\n\n // Acquire the lock and establish an amqp connection if it does not exist.\n if (!this.connection.isOpen()) {\n logger.verbose(\"The CBS client is trying to establish an AMQP connection.\");\n await defaultCancellableLock.acquire(\n this.connectionLock,\n () => {\n return this.connection.open({ abortSignal });\n },\n { abortSignal: abortSignal, timeoutInMs: timeoutInMs },\n );\n }\n\n if (!this.isOpen()) {\n const rxOpt: ReceiverOptions = {\n source: {\n address: this.endpoint,\n },\n name: this.replyTo,\n onSessionError: (context: EventContext) => {\n const id = context.connection.options.id;\n const ehError = translate(context.session!.error!);\n logger.verbose(\n \"[%s] An error occurred on the session for request/response links \" + \"for $cbs: %O\",\n id,\n ehError,\n );\n },\n };\n const srOpt: SenderOptions = { target: { address: this.endpoint } };\n logger.verbose(\n \"[%s] Creating sender/receiver links on a session for $cbs endpoint.\",\n this.connection.id,\n );\n this._cbsSenderReceiverLink = await RequestResponseLink.create(\n this.connection,\n srOpt,\n rxOpt,\n { abortSignal },\n );\n this._cbsSenderReceiverLink.sender.on(SenderEvents.senderError, (context: EventContext) => {\n const id = context.connection.options.id;\n const ehError = translate(context.sender!.error!);\n logger.verbose(\"[%s] An error occurred on the cbs sender link.. %O\", id, ehError);\n });\n this._cbsSenderReceiverLink.receiver.on(\n ReceiverEvents.receiverError,\n (context: EventContext) => {\n const id = context.connection.options.id;\n const ehError = translate(context.receiver!.error!);\n logger.verbose(\"[%s] An error occurred on the cbs receiver link.. %O\", id, ehError);\n },\n );\n logger.verbose(\n \"[%s] Successfully created the cbs sender '%s' and receiver '%s' \" +\n \"links over cbs session.\",\n this.connection.id,\n this._cbsSenderReceiverLink.sender.name,\n this._cbsSenderReceiverLink.receiver.name,\n );\n } else {\n logger.verbose(\n \"[%s] CBS session is already present. Reusing the cbs sender '%s' \" +\n \"and receiver '%s' links over cbs session.\",\n this.connection.id,\n this._cbsSenderReceiverLink!.sender.name,\n this._cbsSenderReceiverLink!.receiver.name,\n );\n }\n } catch (err) {\n const translatedError = translate(err);\n logger.warning(\n \"[%s] An error occurred while establishing the cbs links: %s\",\n this.connection.id,\n `${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }\n\n /**\n * Negotiates the CBS claim with the EventHub/ServiceBus Service.\n * @param audience - The entity token audience for which the token is requested in one\n * of the following forms:\n *\n * - **ServiceBus**\n * - **Sender**\n * - `\"sb://<yournamespace>.servicebus.windows.net/<queue-name>\"`\n * - `\"sb://<yournamespace>.servicebus.windows.net/<topic-name>\"`\n *\n * - **Receiver**\n * - `\"sb://<yournamespace>.servicebus.windows.net/<queue-name>\"`\n * - `\"sb://<yournamespace>.servicebus.windows.net/<topic-name>\"`\n *\n * - **ManagementClient**\n * - `\"sb://<your-namespace>.servicebus.windows.net/<queue-name>/$management\"`.\n * - `\"sb://<your-namespace>.servicebus.windows.net/<topic-name>/$management\"`.\n *\n * - **EventHubs**\n * - **Sender**\n * - `\"sb://<yournamespace>.servicebus.windows.net/<hubName>\"`\n * - `\"sb://<yournamespace>.servicebus.windows.net/<hubName>/Partitions/<partitionId>\"`.\n *\n * - **Receiver**\n * - `\"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/ConsumerGroups/<consumer-group-name>/Partitions/<partition-id>\"`.\n *\n * - **ManagementClient**\n * - `\"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/$management\"`.\n * @param token - The token that needs to be sent in the put-token request.\n * @param tokenType - The type of token being used. For example, 'jwt' or 'servicebus.windows.net:sastoken'.\n * @param options - Optional parameters that can be used to affect this method's behavior.\n * For example, `abortSignal` can be passed to allow cancelling an in-progress `negotiateClaim` invocation.\n * @returns A Promise that resolves when $cbs authentication is successful\n * and rejects when an error occurs during $cbs authentication.\n */\n async negotiateClaim(\n audience: string,\n token: string,\n tokenType: TokenType,\n options: { abortSignal?: AbortSignalLike; timeoutInMs?: number } = {},\n ): Promise<CbsResponse> {\n const { abortSignal, timeoutInMs } = options;\n try {\n if (abortSignal?.aborted) {\n throw new AbortError(StandardAbortMessage);\n }\n\n if (!this._cbsSenderReceiverLink) {\n throw new Error(\"Attempted to negotiate a claim but the CBS link does not exist.\");\n }\n\n const request: RheaMessage = {\n body: token,\n message_id: generate_uuid(),\n reply_to: this.replyTo,\n to: this.endpoint,\n application_properties: {\n operation: Constants.operationPutToken,\n name: audience,\n type: tokenType,\n },\n };\n const responseMessage = await this._cbsSenderReceiverLink.sendRequest(request, {\n abortSignal,\n timeoutInMs,\n requestName: \"negotiateClaim\",\n });\n logger.verbose(\"[%s] The CBS response is: %O\", this.connection.id, responseMessage);\n return this._fromRheaMessageResponse(responseMessage);\n } catch (err) {\n logger.warning(\n \"[%s] An error occurred while negotiating the cbs claim: %s\",\n this.connection.id,\n isError(err) ? `${err.name}: ${err.message}` : String(err),\n );\n logErrorStackTrace(err);\n throw err;\n }\n }\n\n /**\n * Closes the AMQP cbs session to the EventHub/ServiceBus for this client,\n * returning a promise that will be resolved when disconnection is completed.\n * @returns\n */\n async close(): Promise<void> {\n try {\n if (this.isOpen()) {\n const cbsLink = this._cbsSenderReceiverLink;\n this._cbsSenderReceiverLink = undefined;\n await cbsLink!.close();\n logger.verbose(\"[%s] Successfully closed the cbs session.\", this.connection.id);\n }\n } catch (err) {\n const msg = `An error occurred while closing the cbs link: ${\n isError(err) && err.stack ? err.stack : JSON.stringify(err)\n }.`;\n logger.verbose(\"[%s] %s\", this.connection.id, msg);\n throw new Error(msg);\n }\n }\n\n /**\n * Removes the AMQP cbs session to the EventHub/ServiceBus for this client,\n * @returns void\n */\n remove(): void {\n try {\n if (this._cbsSenderReceiverLink) {\n const cbsLink = this._cbsSenderReceiverLink;\n this._cbsSenderReceiverLink = undefined;\n cbsLink!.remove();\n logger.verbose(\"[%s] Successfully removed the cbs session.\", this.connection.id);\n }\n } catch (err) {\n const msg = `An error occurred while removing the cbs link: ${\n isError(err) && err.stack ? err.stack : JSON.stringify(err)\n }.`;\n logger.verbose(\"[%s] %s\", this.connection.id, msg);\n throw new Error(msg);\n }\n }\n\n /**\n * Indicates whether the cbs sender receiver link is open or closed.\n * @returns `true` open, `false` closed.\n */\n public isOpen(): boolean {\n return Boolean(this._cbsSenderReceiverLink?.isOpen());\n }\n\n private _fromRheaMessageResponse(msg: RheaMessage): CbsResponse {\n const cbsResponse = {\n correlationId: msg.correlation_id! as string,\n statusCode: msg.application_properties ? msg.application_properties[\"status-code\"] : \"\",\n statusDescription: msg.application_properties\n ? msg.application_properties[\"status-description\"]\n : \"\",\n };\n logger.verbose(\"[%s] The deserialized CBS response is: %o\", this.connection.id, cbsResponse);\n return cbsResponse;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cbs.js","sourceRoot":"","sources":["../../src/cbs.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAQrD,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAE3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAWxC;;GAEG;AACH,MAAM,OAAO,SAAS;IACpB;;OAEG;IACM,QAAQ,GAAW,SAAS,CAAC,WAAW,CAAC;IAClD;;OAEG;IACM,OAAO,GAAW,GAAG,SAAS,CAAC,UAAU,IAAI,aAAa,EAAE,EAAE,CAAC;IACxE;;;OAGG;IACM,OAAO,GAAW,GAAG,SAAS,CAAC,eAAe,IAAI,aAAa,EAAE,EAAE,CAAC;IAC7E;;;OAGG;IACM,cAAc,CAAS;IAChC;;OAEG;IACH,UAAU,CAAa;IAEvB;;OAEG;IACK,sBAAsB,CAAuB;IAErD;;;OAGG;IACH,YAAY,UAAsB,EAA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AC,aAAa,CAAC,CAAC,CAAC,CAAC,EAAE;YACvF,iBAAiB,EAAE,GAAG,CAAC,sBAAsB;gBAC3C,CAAC,CAAC,GAAG,CAAC,sBAAsB,CAAC,oBAAoB,CAAC;gBAClD,CAAC,CAAC,EAAE;SACP,CAAC;QACF,MAAM,CAAC,OAAO,CAAC,2CAA2C,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC;QAC7F,OAAO,WAAW,CAAC;IACrB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AbortError } from \"@azure/abort-controller\";\nimport type {\n Connection,\n EventContext,\n ReceiverOptions,\n Message as RheaMessage,\n SenderOptions,\n} from \"rhea-promise\";\nimport { ReceiverEvents, SenderEvents, generate_uuid } from \"rhea-promise\";\nimport { logErrorStackTrace, logger } from \"./log.js\";\nimport { Constants } from \"./util/constants.js\";\nimport { RequestResponseLink } from \"./requestResponseLink.js\";\nimport { StandardAbortMessage } from \"./util/constants.js\";\nimport type { TokenType } from \"./auth/token.js\";\nimport { defaultCancellableLock } from \"./util/utils.js\";\nimport { isError } from \"@azure/core-util\";\nimport { translate } from \"./errors.js\";\n\n/**\n * Describes the CBS Response.\n */\nexport interface CbsResponse {\n correlationId: string;\n statusCode: string;\n statusDescription: string;\n}\n\n/**\n * Describes the EventHub/ServiceBus Cbs client that talks to the $cbs endpoint over AMQP connection.\n */\nexport class CbsClient {\n /**\n * CBS endpoint - \"$cbs\"\n */\n readonly endpoint: string = Constants.cbsEndpoint;\n /**\n * CBS replyTo - The receiver link name that the service should reply to.\n */\n readonly replyTo: string = `${Constants.cbsReplyTo}-${generate_uuid()}`;\n /**\n * The unique lock name per $cbs session per connection that is used to\n * acquire the lock for establishing a cbs session if one does not exist for an amqp connection.\n */\n readonly cbsLock: string = `${Constants.negotiateCbsKey}-${generate_uuid()}`;\n /**\n * The unique lock name per connection that is used to\n * acquire the lock for establishing an amqp connection if one does not exist.\n */\n readonly connectionLock: string;\n /**\n * The AMQP connection.\n */\n connection: Connection;\n\n /**\n * CBS sender, receiver on the same session.\n */\n private _cbsSenderReceiverLink?: RequestResponseLink;\n\n /**\n * @param connection - The AMQP connection.\n * @param connectionLock - A unique string (usually a guid) per connection.\n */\n constructor(connection: Connection, connectionLock: string) {\n this.connection = connection;\n this.connectionLock = connectionLock;\n }\n\n /**\n * Creates a singleton instance of the CBS session if it hasn't been initialized previously on\n * the given connection.\n * @param options - Optional parameters that can be used to affect this method's behavior.\n * For example, `abortSignal` can be passed to allow cancelling an in-progress `init` invocation.\n * @returns Promise<void>.\n */\n async init(options: { abortSignal?: AbortSignalLike; timeoutInMs?: number } = {}): Promise<void> {\n const { abortSignal, timeoutInMs } = options;\n\n try {\n if (abortSignal?.aborted) {\n throw new AbortError(StandardAbortMessage);\n }\n\n // Acquire the lock and establish an amqp connection if it does not exist.\n if (!this.connection.isOpen()) {\n logger.verbose(\"The CBS client is trying to establish an AMQP connection.\");\n await defaultCancellableLock.acquire(\n this.connectionLock,\n () => {\n return this.connection.open({ abortSignal });\n },\n { abortSignal: abortSignal, timeoutInMs: timeoutInMs },\n );\n }\n\n if (!this.isOpen()) {\n const rxOpt: ReceiverOptions = {\n source: {\n address: this.endpoint,\n },\n name: this.replyTo,\n onSessionError: (context: EventContext) => {\n const id = context.connection.options.id;\n const ehError = translate(context.session!.error!);\n logger.verbose(\n \"[%s] An error occurred on the session for request/response links \" + \"for $cbs: %O\",\n id,\n ehError,\n );\n },\n };\n const srOpt: SenderOptions = { target: { address: this.endpoint } };\n logger.verbose(\n \"[%s] Creating sender/receiver links on a session for $cbs endpoint.\",\n this.connection.id,\n );\n this._cbsSenderReceiverLink = await RequestResponseLink.create(\n this.connection,\n srOpt,\n rxOpt,\n { abortSignal },\n );\n this._cbsSenderReceiverLink.sender.on(SenderEvents.senderError, (context: EventContext) => {\n const id = context.connection.options.id;\n const ehError = translate(context.sender!.error!);\n logger.verbose(\"[%s] An error occurred on the cbs sender link.. %O\", id, ehError);\n });\n this._cbsSenderReceiverLink.receiver.on(\n ReceiverEvents.receiverError,\n (context: EventContext) => {\n const id = context.connection.options.id;\n const ehError = translate(context.receiver!.error!);\n logger.verbose(\"[%s] An error occurred on the cbs receiver link.. %O\", id, ehError);\n },\n );\n logger.verbose(\n \"[%s] Successfully created the cbs sender '%s' and receiver '%s' \" +\n \"links over cbs session.\",\n this.connection.id,\n this._cbsSenderReceiverLink.sender.name,\n this._cbsSenderReceiverLink.receiver.name,\n );\n } else {\n logger.verbose(\n \"[%s] CBS session is already present. Reusing the cbs sender '%s' \" +\n \"and receiver '%s' links over cbs session.\",\n this.connection.id,\n this._cbsSenderReceiverLink!.sender.name,\n this._cbsSenderReceiverLink!.receiver.name,\n );\n }\n } catch (err) {\n const translatedError = translate(err);\n logger.warning(\n \"[%s] An error occurred while establishing the cbs links: %s\",\n this.connection.id,\n `${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }\n\n /**\n * Negotiates the CBS claim with the EventHub/ServiceBus Service.\n * @param audience - The entity token audience for which the token is requested in one\n * of the following forms:\n *\n * - **ServiceBus**\n * - **Sender**\n * - `\"sb://<yournamespace>.servicebus.windows.net/<queue-name>\"`\n * - `\"sb://<yournamespace>.servicebus.windows.net/<topic-name>\"`\n *\n * - **Receiver**\n * - `\"sb://<yournamespace>.servicebus.windows.net/<queue-name>\"`\n * - `\"sb://<yournamespace>.servicebus.windows.net/<topic-name>\"`\n *\n * - **ManagementClient**\n * - `\"sb://<your-namespace>.servicebus.windows.net/<queue-name>/$management\"`.\n * - `\"sb://<your-namespace>.servicebus.windows.net/<topic-name>/$management\"`.\n *\n * - **EventHubs**\n * - **Sender**\n * - `\"sb://<yournamespace>.servicebus.windows.net/<hubName>\"`\n * - `\"sb://<yournamespace>.servicebus.windows.net/<hubName>/Partitions/<partitionId>\"`.\n *\n * - **Receiver**\n * - `\"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/ConsumerGroups/<consumer-group-name>/Partitions/<partition-id>\"`.\n *\n * - **ManagementClient**\n * - `\"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/$management\"`.\n * @param token - The token that needs to be sent in the put-token request.\n * @param tokenType - The type of token being used. For example, 'jwt' or 'servicebus.windows.net:sastoken'.\n * @param options - Optional parameters that can be used to affect this method's behavior.\n * For example, `abortSignal` can be passed to allow cancelling an in-progress `negotiateClaim` invocation.\n * @returns A Promise that resolves when $cbs authentication is successful\n * and rejects when an error occurs during $cbs authentication.\n */\n async negotiateClaim(\n audience: string,\n token: string,\n tokenType: TokenType,\n options: { abortSignal?: AbortSignalLike; timeoutInMs?: number } = {},\n ): Promise<CbsResponse> {\n const { abortSignal, timeoutInMs } = options;\n try {\n if (abortSignal?.aborted) {\n throw new AbortError(StandardAbortMessage);\n }\n\n if (!this._cbsSenderReceiverLink) {\n throw new Error(\"Attempted to negotiate a claim but the CBS link does not exist.\");\n }\n\n const request: RheaMessage = {\n body: token,\n message_id: generate_uuid(),\n reply_to: this.replyTo,\n to: this.endpoint,\n application_properties: {\n operation: Constants.operationPutToken,\n name: audience,\n type: tokenType,\n },\n };\n const responseMessage = await this._cbsSenderReceiverLink.sendRequest(request, {\n abortSignal,\n timeoutInMs,\n requestName: \"negotiateClaim\",\n });\n logger.verbose(\"[%s] The CBS response is: %O\", this.connection.id, responseMessage);\n return this._fromRheaMessageResponse(responseMessage);\n } catch (err) {\n logger.warning(\n \"[%s] An error occurred while negotiating the cbs claim: %s\",\n this.connection.id,\n isError(err) ? `${err.name}: ${err.message}` : String(err),\n );\n logErrorStackTrace(err);\n throw err;\n }\n }\n\n /**\n * Closes the AMQP cbs session to the EventHub/ServiceBus for this client,\n * returning a promise that will be resolved when disconnection is completed.\n * @returns\n */\n async close(): Promise<void> {\n try {\n if (this.isOpen()) {\n const cbsLink = this._cbsSenderReceiverLink;\n this._cbsSenderReceiverLink = undefined;\n await cbsLink!.close();\n logger.verbose(\"[%s] Successfully closed the cbs session.\", this.connection.id);\n }\n } catch (err) {\n const msg = `An error occurred while closing the cbs link: ${\n isError(err) && err.stack ? err.stack : JSON.stringify(err)\n }.`;\n logger.verbose(\"[%s] %s\", this.connection.id, msg);\n throw new Error(msg);\n }\n }\n\n /**\n * Removes the AMQP cbs session to the EventHub/ServiceBus for this client,\n * @returns void\n */\n remove(): void {\n try {\n if (this._cbsSenderReceiverLink) {\n const cbsLink = this._cbsSenderReceiverLink;\n this._cbsSenderReceiverLink = undefined;\n cbsLink!.remove();\n logger.verbose(\"[%s] Successfully removed the cbs session.\", this.connection.id);\n }\n } catch (err) {\n const msg = `An error occurred while removing the cbs link: ${\n isError(err) && err.stack ? err.stack : JSON.stringify(err)\n }.`;\n logger.verbose(\"[%s] %s\", this.connection.id, msg);\n throw new Error(msg);\n }\n }\n\n /**\n * Indicates whether the cbs sender receiver link is open or closed.\n * @returns `true` open, `false` closed.\n */\n public isOpen(): boolean {\n return Boolean(this._cbsSenderReceiverLink?.isOpen());\n }\n\n private _fromRheaMessageResponse(msg: RheaMessage): CbsResponse {\n const cbsResponse = {\n correlationId: msg.correlation_id! as string,\n statusCode: msg.application_properties ? msg.application_properties[\"status-code\"] : \"\",\n statusDescription: msg.application_properties\n ? msg.application_properties[\"status-description\"]\n : \"\",\n };\n logger.verbose(\"[%s] The deserialized CBS response is: %o\", this.connection.id, cbsResponse);\n return cbsResponse;\n }\n}\n"]}
|
|
@@ -10,12 +10,12 @@ function getHost(endpoint) {
|
|
|
10
10
|
}
|
|
11
11
|
}
|
|
12
12
|
const matches = /.*:\/\/([^/:]*)/.exec(endpoint);
|
|
13
|
-
const match = matches
|
|
13
|
+
const match = matches?.[1];
|
|
14
14
|
return !match ? endpoint : match;
|
|
15
15
|
}
|
|
16
16
|
function extractPort(ep) {
|
|
17
17
|
const matches = /.*:(\d*)/.exec(ep);
|
|
18
|
-
const match = matches
|
|
18
|
+
const match = matches?.[1];
|
|
19
19
|
return match ? parseInt(match, 10) : undefined;
|
|
20
20
|
}
|
|
21
21
|
function getPort(endpoint) {
|
|
@@ -52,7 +52,15 @@ export const ConnectionConfig = {
|
|
|
52
52
|
if (parsedCS.Endpoint.includes(":")) {
|
|
53
53
|
port = getPort(parsedCS.Endpoint);
|
|
54
54
|
}
|
|
55
|
-
const result =
|
|
55
|
+
const result = {
|
|
56
|
+
connectionString: connectionString,
|
|
57
|
+
endpoint: parsedCS.Endpoint,
|
|
58
|
+
host: getHost(parsedCS.Endpoint),
|
|
59
|
+
sharedAccessKeyName: parsedCS.SharedAccessKeyName,
|
|
60
|
+
sharedAccessKey: parsedCS.SharedAccessKey,
|
|
61
|
+
useDevelopmentEmulator: parsedCS.UseDevelopmentEmulator === "true",
|
|
62
|
+
...(port !== undefined ? { port } : undefined),
|
|
63
|
+
};
|
|
56
64
|
if (path || parsedCS.EntityPath) {
|
|
57
65
|
result.entityPath = path || parsedCS.EntityPath;
|
|
58
66
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connectionConfig.js","sourceRoot":"","sources":["../../../src/connectionConfig/connectionConfig.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAkFzD,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,iBAAiB,CAAC,CAAC;AAEnD,SAAS,OAAO,CAAC,QAAgB;IAC/B,KAAK,MAAM,EAAE,IAAI,eAAe,EAAE,CAAC;QACjC,IAAI,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC;YAC1B,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;IAED,MAAM,OAAO,GAAG,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACjD,MAAM,KAAK,GAAG,OAAO,aAAP,OAAO,uBA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{ WebSocketImpl } from \"rhea-promise\";\nimport { isDefined } from \"@azure/core-util\";\nimport { parseConnectionString } from \"../util/utils.js\";\n\n/**\n * Describes the options that can be provided while creating a connection config.\n */\nexport interface ConnectionConfigOptions {\n /**\n * Indicates whether the entity path is required in the\n * connection config.\n */\n isEntityPathRequired?: boolean;\n}\n\n/**\n * Describes the connection config object that is created after parsing an EventHub or ServiceBus\n * connection string.\n */\nexport interface ConnectionConfig {\n /**\n * The service bus endpoint\n * \"sb://<yournamespace>.servicebus.windows.net/\".\n */\n endpoint: string;\n /**\n * The DNS hostname or IP address of the service.\n * Typically of the form \"<yournamespace>.servicebus.windows.net\" unless connecting\n * to the service through an intermediary.\n */\n host: string;\n /**\n * The fully qualified name of the host to connect to.\n * This field can be used by AMQP proxies to determine the correct back-end service to\n * connect the client to.\n * Typically of the form \"<yournamespace>.servicebus.windows.net\".\n */\n amqpHostname?: string;\n /**\n * The port number.\n */\n port?: number;\n /**\n * The connection string.\n */\n connectionString: string;\n /**\n * The name/path of the entity (hub/queue/topic name) to which the\n * connection needs to happen.\n */\n entityPath?: string;\n /**\n * The name of the access key.\n */\n sharedAccessKeyName: string;\n /**\n * The secret value of the access key.\n */\n sharedAccessKey: string;\n\n /**\n * The WebSocket constructor used to create an AMQP connection\n * over a WebSocket. In browsers, the built-in WebSocket will be used by default. In Node, a\n * TCP socket will be used if a WebSocket constructor is not provided.\n */\n webSocket?: WebSocketImpl;\n\n /**\n * The path for the endpoint that accepts an AMQP\n * connection over WebSockets.\n */\n webSocketEndpointPath?: string;\n\n /**\n * Options to be passed to the WebSocket constructor\n */\n webSocketConstructorOptions?: any;\n /**\n * This should be true only if the connection string contains the slug \";UseDevelopmentEmulator=true\"\n * and the endpoint is a loopback address.\n */\n useDevelopmentEmulator?: boolean;\n}\n\nconst specialLocalIPs = [\"::1\", \"0:0:0:0:0:0:0:1\"];\n\nfunction getHost(endpoint: string): string {\n for (const ip of specialLocalIPs) {\n if (endpoint.includes(ip)) {\n return ip;\n }\n }\n\n const matches = /.*:\\/\\/([^/:]*)/.exec(endpoint);\n const match = matches?.[1];\n return !match ? endpoint : match;\n}\n\nfunction extractPort(ep: string): number | undefined {\n const matches = /.*:(\\d*)/.exec(ep);\n const match = matches?.[1];\n return match ? parseInt(match, 10) : undefined;\n}\n\nfunction getPort(endpoint: string): number | undefined {\n for (const ip of specialLocalIPs) {\n if (endpoint.includes(ip)) {\n return extractPort(endpoint.replace(ip, \"\"));\n }\n }\n\n return extractPort(endpoint);\n}\n\n/**\n * Describes the ConnectionConfig module\n */\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- renaming constant would be a breaking change.\nexport const ConnectionConfig = {\n /**\n * Creates the connection config.\n * @param connectionString - The connection string for a given service like\n * EventHub/ServiceBus.\n * @param path - The name/path of the entity (hub name) to which the\n * connection needs to happen. This will override the EntityPath in the connectionString\n * if present.\n * @returns ConnectionConfig\n */\n create(connectionString: string, path?: string): ConnectionConfig {\n connectionString = String(connectionString);\n\n const parsedCS = parseConnectionString<{\n Endpoint: string;\n SharedAccessKeyName: string;\n SharedAccessKey: string;\n EntityPath?: string;\n UseDevelopmentEmulator?: string;\n }>(connectionString);\n if (!parsedCS.Endpoint) {\n throw new TypeError(\"Missing Endpoint in Connection String.\");\n }\n\n if (!parsedCS.Endpoint.endsWith(\"/\")) parsedCS.Endpoint += \"/\";\n\n let port: number | undefined;\n if (parsedCS.Endpoint.includes(\":\")) {\n port = getPort(parsedCS.Endpoint);\n }\n\n const result: ConnectionConfig = {\n connectionString: connectionString,\n endpoint: parsedCS.Endpoint,\n host: getHost(parsedCS.Endpoint),\n sharedAccessKeyName: parsedCS.SharedAccessKeyName,\n sharedAccessKey: parsedCS.SharedAccessKey,\n useDevelopmentEmulator: parsedCS.UseDevelopmentEmulator === \"true\",\n ...(port !== undefined ? { port } : undefined),\n };\n\n if (path || parsedCS.EntityPath) {\n result.entityPath = path || parsedCS.EntityPath;\n }\n return result;\n },\n\n /**\n * Validates the properties of connection config.\n * @param config - The connection config to be validated.\n * @returns void\n */\n validate(config: ConnectionConfig, options?: ConnectionConfigOptions): void {\n if (!options) options = {};\n\n if (!config) {\n throw new TypeError(\"Missing configuration\");\n }\n\n if (!config.endpoint) {\n throw new TypeError(\"Missing 'endpoint' in configuration\");\n }\n config.endpoint = String(config.endpoint);\n\n if (!config.host) {\n throw new TypeError(\"Missing 'host' in configuration\");\n }\n config.host = String(config.host);\n\n if (config.port !== undefined && !(config.port >= 0 && config.port <= 65535)) {\n throw new TypeError(`Invalid 'port' of ${config.port} in configuration`);\n }\n\n if (options.isEntityPathRequired && !config.entityPath) {\n throw new TypeError(\"Missing 'entityPath' in configuration\");\n }\n if (isDefined(config.entityPath)) {\n config.entityPath = String(config.entityPath);\n }\n\n if (!isSharedAccessSignature(config.connectionString)) {\n if (!config.sharedAccessKeyName) {\n throw new TypeError(\"Missing 'sharedAccessKeyName' in configuration\");\n }\n config.sharedAccessKeyName = String(config.sharedAccessKeyName);\n\n if (!config.sharedAccessKey) {\n throw new TypeError(\"Missing 'sharedAccessKey' in configuration\");\n }\n config.sharedAccessKey = String(config.sharedAccessKey);\n }\n },\n};\n\n/**\n * @internal\n */\nexport function isSharedAccessSignature(connectionString: string): boolean {\n return connectionString.match(/;{0,1}SharedAccessSignature=SharedAccessSignature /) != null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"connectionConfig.js","sourceRoot":"","sources":["../../../src/connectionConfig/connectionConfig.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAkFzD,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,iBAAiB,CAAC,CAAC;AAEnD,SAAS,OAAO,CAAC,QAAgB;IAC/B,KAAK,MAAM,EAAE,IAAI,eAAe,EAAE,CAAC;QACjC,IAAI,QAAQ,CAAC,QAAQ,CAAC,EAAE,CA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C,gBAAwB;IAC9D,OAAO,gBAAgB,CAAC,KAAK,CAAC,oDAAoD,CAAC,IAAI,IAAI,CAAC;AAC9F,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { WebSocketImpl } from \"rhea-promise\";\nimport { isDefined } from \"@azure/core-util\";\nimport { parseConnectionString } from \"../util/utils.js\";\n\n/**\n * Describes the options that can be provided while creating a connection config.\n */\nexport interface ConnectionConfigOptions {\n /**\n * Indicates whether the entity path is required in the\n * connection config.\n */\n isEntityPathRequired?: boolean;\n}\n\n/**\n * Describes the connection config object that is created after parsing an EventHub or ServiceBus\n * connection string.\n */\nexport interface ConnectionConfig {\n /**\n * The service bus endpoint\n * \"sb://<yournamespace>.servicebus.windows.net/\".\n */\n endpoint: string;\n /**\n * The DNS hostname or IP address of the service.\n * Typically of the form \"<yournamespace>.servicebus.windows.net\" unless connecting\n * to the service through an intermediary.\n */\n host: string;\n /**\n * The fully qualified name of the host to connect to.\n * This field can be used by AMQP proxies to determine the correct back-end service to\n * connect the client to.\n * Typically of the form \"<yournamespace>.servicebus.windows.net\".\n */\n amqpHostname?: string;\n /**\n * The port number.\n */\n port?: number;\n /**\n * The connection string.\n */\n connectionString: string;\n /**\n * The name/path of the entity (hub/queue/topic name) to which the\n * connection needs to happen.\n */\n entityPath?: string;\n /**\n * The name of the access key.\n */\n sharedAccessKeyName: string;\n /**\n * The secret value of the access key.\n */\n sharedAccessKey: string;\n\n /**\n * The WebSocket constructor used to create an AMQP connection\n * over a WebSocket. In browsers, the built-in WebSocket will be used by default. In Node, a\n * TCP socket will be used if a WebSocket constructor is not provided.\n */\n webSocket?: WebSocketImpl;\n\n /**\n * The path for the endpoint that accepts an AMQP\n * connection over WebSockets.\n */\n webSocketEndpointPath?: string;\n\n /**\n * Options to be passed to the WebSocket constructor\n */\n webSocketConstructorOptions?: any;\n /**\n * This should be true only if the connection string contains the slug \";UseDevelopmentEmulator=true\"\n * and the endpoint is a loopback address.\n */\n useDevelopmentEmulator?: boolean;\n}\n\nconst specialLocalIPs = [\"::1\", \"0:0:0:0:0:0:0:1\"];\n\nfunction getHost(endpoint: string): string {\n for (const ip of specialLocalIPs) {\n if (endpoint.includes(ip)) {\n return ip;\n }\n }\n\n const matches = /.*:\\/\\/([^/:]*)/.exec(endpoint);\n const match = matches?.[1];\n return !match ? endpoint : match;\n}\n\nfunction extractPort(ep: string): number | undefined {\n const matches = /.*:(\\d*)/.exec(ep);\n const match = matches?.[1];\n return match ? parseInt(match, 10) : undefined;\n}\n\nfunction getPort(endpoint: string): number | undefined {\n for (const ip of specialLocalIPs) {\n if (endpoint.includes(ip)) {\n return extractPort(endpoint.replace(ip, \"\"));\n }\n }\n\n return extractPort(endpoint);\n}\n\n/**\n * Describes the ConnectionConfig module\n */\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- renaming constant would be a breaking change.\nexport const ConnectionConfig = {\n /**\n * Creates the connection config.\n * @param connectionString - The connection string for a given service like\n * EventHub/ServiceBus.\n * @param path - The name/path of the entity (hub name) to which the\n * connection needs to happen. This will override the EntityPath in the connectionString\n * if present.\n * @returns ConnectionConfig\n */\n create(connectionString: string, path?: string): ConnectionConfig {\n connectionString = String(connectionString);\n\n const parsedCS = parseConnectionString<{\n Endpoint: string;\n SharedAccessKeyName: string;\n SharedAccessKey: string;\n EntityPath?: string;\n UseDevelopmentEmulator?: string;\n }>(connectionString);\n if (!parsedCS.Endpoint) {\n throw new TypeError(\"Missing Endpoint in Connection String.\");\n }\n\n if (!parsedCS.Endpoint.endsWith(\"/\")) parsedCS.Endpoint += \"/\";\n\n let port: number | undefined;\n if (parsedCS.Endpoint.includes(\":\")) {\n port = getPort(parsedCS.Endpoint);\n }\n\n const result: ConnectionConfig = {\n connectionString: connectionString,\n endpoint: parsedCS.Endpoint,\n host: getHost(parsedCS.Endpoint),\n sharedAccessKeyName: parsedCS.SharedAccessKeyName,\n sharedAccessKey: parsedCS.SharedAccessKey,\n useDevelopmentEmulator: parsedCS.UseDevelopmentEmulator === \"true\",\n ...(port !== undefined ? { port } : undefined),\n };\n\n if (path || parsedCS.EntityPath) {\n result.entityPath = path || parsedCS.EntityPath;\n }\n return result;\n },\n\n /**\n * Validates the properties of connection config.\n * @param config - The connection config to be validated.\n * @returns void\n */\n validate(config: ConnectionConfig, options?: ConnectionConfigOptions): void {\n if (!options) options = {};\n\n if (!config) {\n throw new TypeError(\"Missing configuration\");\n }\n\n if (!config.endpoint) {\n throw new TypeError(\"Missing 'endpoint' in configuration\");\n }\n config.endpoint = String(config.endpoint);\n\n if (!config.host) {\n throw new TypeError(\"Missing 'host' in configuration\");\n }\n config.host = String(config.host);\n\n if (config.port !== undefined && !(config.port >= 0 && config.port <= 65535)) {\n throw new TypeError(`Invalid 'port' of ${config.port} in configuration`);\n }\n\n if (options.isEntityPathRequired && !config.entityPath) {\n throw new TypeError(\"Missing 'entityPath' in configuration\");\n }\n if (isDefined(config.entityPath)) {\n config.entityPath = String(config.entityPath);\n }\n\n if (!isSharedAccessSignature(config.connectionString)) {\n if (!config.sharedAccessKeyName) {\n throw new TypeError(\"Missing 'sharedAccessKeyName' in configuration\");\n }\n config.sharedAccessKeyName = String(config.sharedAccessKeyName);\n\n if (!config.sharedAccessKey) {\n throw new TypeError(\"Missing 'sharedAccessKey' in configuration\");\n }\n config.sharedAccessKey = String(config.sharedAccessKey);\n }\n },\n};\n\n/**\n * @internal\n */\nexport function isSharedAccessSignature(connectionString: string): boolean {\n return connectionString.match(/;{0,1}SharedAccessSignature=SharedAccessSignature /) != null;\n}\n"]}
|
package/dist/browser/errors.js
CHANGED
|
@@ -467,6 +467,43 @@ export function isMessagingError(error) {
|
|
|
467
467
|
* Describes the base class for Messaging Error.
|
|
468
468
|
*/
|
|
469
469
|
export class MessagingError extends Error {
|
|
470
|
+
/**
|
|
471
|
+
* Address to which the network connection failed.
|
|
472
|
+
* Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.
|
|
473
|
+
*/
|
|
474
|
+
address;
|
|
475
|
+
/**
|
|
476
|
+
* A string label that identifies the error.
|
|
477
|
+
*/
|
|
478
|
+
code;
|
|
479
|
+
/**
|
|
480
|
+
* System-provided error number.
|
|
481
|
+
* Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.
|
|
482
|
+
*/
|
|
483
|
+
errno;
|
|
484
|
+
/**
|
|
485
|
+
* The error name. Default value: "MessagingError".
|
|
486
|
+
*/
|
|
487
|
+
name = "MessagingError";
|
|
488
|
+
/**
|
|
489
|
+
* The unavailable network connection port.
|
|
490
|
+
* Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.
|
|
491
|
+
*/
|
|
492
|
+
port;
|
|
493
|
+
/**
|
|
494
|
+
* Name of the system call that triggered the error.
|
|
495
|
+
* Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.
|
|
496
|
+
*/
|
|
497
|
+
syscall;
|
|
498
|
+
/**
|
|
499
|
+
*
|
|
500
|
+
* Describes whether the error is retryable. Default: true.
|
|
501
|
+
*/
|
|
502
|
+
retryable = true;
|
|
503
|
+
/**
|
|
504
|
+
* Extra details about the error.
|
|
505
|
+
*/
|
|
506
|
+
info;
|
|
470
507
|
/**
|
|
471
508
|
* @param message - The error message that provides more information about the error.
|
|
472
509
|
* @param originalError - An error whose properties will be copied to the MessagingError if the
|
|
@@ -474,15 +511,6 @@ export class MessagingError extends Error {
|
|
|
474
511
|
*/
|
|
475
512
|
constructor(message, originalError) {
|
|
476
513
|
super(message);
|
|
477
|
-
/**
|
|
478
|
-
* The error name. Default value: "MessagingError".
|
|
479
|
-
*/
|
|
480
|
-
this.name = "MessagingError";
|
|
481
|
-
/**
|
|
482
|
-
*
|
|
483
|
-
* Describes whether the error is retryable. Default: true.
|
|
484
|
-
*/
|
|
485
|
-
this.retryable = true;
|
|
486
514
|
if (!originalError) {
|
|
487
515
|
return;
|
|
488
516
|
}
|