-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
linkEntity.ts
264 lines (255 loc) · 8.17 KB
/
linkEntity.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { v4 as uuid } from "uuid";
import { Constants, TokenType, defaultLock, isSasTokenProvider } from "@azure/core-amqp";
import { AccessToken } from "@azure/core-auth";
import { ConnectionContext } from "./connectionContext";
import { AwaitableSender, Receiver } from "rhea-promise";
import { logger } from "./log";
/**
* @hidden
*/
export interface LinkEntityOptions {
/**
* The unique name for the entity. If not provided then a guid will be
* assigned.
*/
name?: string;
/**
* The partitionId associated with the link entity.
*/
partitionId?: string;
/**
* The link entity address in one of the following forms:
*/
address?: string;
/**
* The link entity token audience in one of the following forms:
*/
audience?: string;
}
/**
* Describes the base class for entities like EventHub Sender, Receiver and Management link.
* @internal
*/
export class LinkEntity {
/**
* The unique name for the entity (mostly a guid).
*/
name: string;
/**
* The link entity address in one of the following forms:
*
* **Sender**
* - `"<hubName>"`
* - `"<hubName>/Partitions/<partitionId>"`.
*
* **Receiver**
* - `"<event-hub-name>/ConsumerGroups/<consumer-group-name>/Partitions/<partition-id>"`.
*
* **ManagementClient**
* -`"$management"`.
*/
address: string;
/**
* The link entity token audience in one of the following forms:
*
* **Sender**
* - `"sb://<yournamespace>.servicebus.windows.net/<hubName>"`
* - `"sb://<yournamespace>.servicebus.windows.net/<hubName>/Partitions/<partitionId>"`.
*
* **Receiver**
* - `"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/ConsumerGroups/<consumer-group-name>/Partitions/<partition-id>"`.
*
* **ManagementClient**
* - `"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/$management"`.
*/
audience: string;
/**
* The partitionId associated with the link entity.
*/
partitionId?: string;
/**
* Indicates whether the link is in the process of connecting
* (establishing) itself. Default value: `false`.
*/
isConnecting: boolean = false;
/**
* Provides relevant information about the amqp connection,
* cbs and $management sessions, token provider, sender and receivers.
*/
protected _context: ConnectionContext;
/**
* The token renewal timer that keeps track of when
* the Link Entity is due for token renewal.
*/
protected _tokenRenewalTimer?: NodeJS.Timer;
/**
* Indicates token timeout in milliseconds
*/
protected _tokenTimeoutInMs?: number;
/**
* Creates a new LinkEntity instance.
* @hidden
* @param context - The connection context.
* @param options - Options that can be provided while creating the LinkEntity.
*/
constructor(context: ConnectionContext, options?: LinkEntityOptions) {
if (!options) options = {};
this._context = context;
this.address = options.address || "";
this.audience = options.audience || "";
this.name = `${options.name}-${uuid()}`;
this.partitionId = options.partitionId;
}
/**
* Negotiates cbs claim for the LinkEntity.
* @hidden
* @param setTokenRenewal - Set the token renewal timer. Default false.
* @returns Promise<void>
*/
protected async _negotiateClaim(setTokenRenewal?: boolean): Promise<void> {
// Acquire the lock and establish a cbs session if it does not exist on the connection.
// Although node.js is single threaded, we need a locking mechanism to ensure that a
// race condition does not happen while creating a shared resource (in this case the
// cbs session, since we want to have exactly 1 cbs session per connection).
logger.verbose(
"[%s] Acquiring cbs lock: '%s' for creating the cbs session while creating the %s: " +
"'%s' with address: '%s'.",
this._context.connectionId,
this._context.cbsSession.cbsLock,
this._type,
this.name,
this.address
);
await defaultLock.acquire(this._context.cbsSession.cbsLock, () => {
return this._context.cbsSession.init();
});
let tokenObject: AccessToken;
let tokenType: TokenType;
if (isSasTokenProvider(this._context.tokenCredential)) {
tokenObject = this._context.tokenCredential.getToken(this.audience);
tokenType = TokenType.CbsTokenTypeSas;
// renew sas token in every 45 minutess
this._tokenTimeoutInMs = (3600 - 900) * 1000;
} else {
const aadToken = await this._context.tokenCredential.getToken(Constants.aadEventHubsScope);
if (!aadToken) {
throw new Error(`Failed to get token from the provided "TokenCredential" object`);
}
tokenObject = aadToken;
tokenType = TokenType.CbsTokenTypeJwt;
this._tokenTimeoutInMs = tokenObject.expiresOnTimestamp - Date.now() - 2 * 60 * 1000;
}
logger.verbose(
"[%s] %s: calling negotiateClaim for audience '%s'.",
this._context.connectionId,
this._type,
this.audience
);
// Acquire the lock to negotiate the CBS claim.
logger.verbose(
"[%s] Acquiring cbs lock: '%s' for cbs auth for %s: '%s' with address '%s'.",
this._context.connectionId,
this._context.negotiateClaimLock,
this._type,
this.name,
this.address
);
await defaultLock.acquire(this._context.negotiateClaimLock, () => {
return this._context.cbsSession.negotiateClaim(this.audience, tokenObject.token, tokenType);
});
logger.verbose(
"[%s] Negotiated claim for %s '%s' with with address: %s",
this._context.connectionId,
this._type,
this.name,
this.address
);
if (setTokenRenewal) {
await this._ensureTokenRenewal();
}
}
/**
* Ensures that the token is renewed within the predefined renewal margin.
* @hidden
*/
protected async _ensureTokenRenewal(): Promise<void> {
if (!this._tokenTimeoutInMs) {
return;
}
// Clear the existing token renewal timer.
// This scenario can happen if the connection goes down and is brought back up
// before the `nextRenewalTimeout` was reached.
if (this._tokenRenewalTimer) {
clearTimeout(this._tokenRenewalTimer);
}
this._tokenRenewalTimer = setTimeout(async () => {
try {
await this._negotiateClaim(true);
} catch (err) {
logger.verbose(
"[%s] %s '%s' with address %s, an error occurred while renewing the token: %O",
this._context.connectionId,
this._type,
this.name,
this.address,
err
);
}
}, this._tokenTimeoutInMs);
logger.verbose(
"[%s] %s '%s' with address %s, has next token renewal in %d milliseconds @(%s).",
this._context.connectionId,
this._type,
this.name,
this.address,
this._tokenTimeoutInMs,
new Date(Date.now() + this._tokenTimeoutInMs).toString()
);
}
/**
* Closes the Sender|Receiver link and it's underlying session and also removes it from the
* internal map.
* @hidden
* @param link - The Sender or Receiver link that needs to be closed and
* removed.
*/
protected async _closeLink(link?: AwaitableSender | Receiver): Promise<void> {
clearTimeout(this._tokenRenewalTimer as NodeJS.Timer);
if (link) {
try {
// Closing the link and its underlying session if the link is open. This should also
// remove them from the internal map.
await link.close();
logger.verbose(
"[%s] %s '%s' with address '%s' closed.",
this._context.connectionId,
this._type,
this.name,
this.address
);
} catch (err) {
logger.verbose(
"[%s] An error occurred while closing the %s '%s' with address '%s': %O",
this._context.connectionId,
this._type,
this.name,
this.address,
err
);
}
}
}
/**
* Provides the current type of the LinkEntity.
* @returns The entity type.
*/
private get _type(): string {
let result = "LinkEntity";
if ((this as any).constructor && (this as any).constructor.name) {
result = (this as any).constructor.name;
}
return result;
}
}