-
Notifications
You must be signed in to change notification settings - Fork 825
/
ZoneContextManager.ts
262 lines (237 loc) · 7.66 KB
/
ZoneContextManager.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
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
Context,
ContextManager,
ROOT_CONTEXT,
} from '@opentelemetry/context-base';
import { Func, TargetWithEvents } from './types';
import { isListenerObject } from './util';
/* Key name to be used to save a context reference in Zone */
const ZONE_CONTEXT_KEY = 'OT_ZONE_CONTEXT';
/**
* ZoneContextManager
* This module provides an easy functionality for tracing action between asynchronous operations in web.
* It was not possible with standard [StackContextManager]{@link https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-web/src/StackContextManager.ts}.
* It heavily depends on [zone.js]{@link https://www.npmjs.com/package/zone.js}.
* It stores the information about context in zone. Each Context will have always new Zone;
* It also supports binding a certain Span to a target that has "addEventListener" and "removeEventListener".
* When this happens a new zone is being created and the provided Span is being assigned to this zone.
*/
export class ZoneContextManager implements ContextManager {
/**
* whether the context manager is enabled or not
*/
private _enabled = false;
/**
* Helps to create a unique name for the zones - part of zone name
*/
private _zoneCounter = 0;
/**
* Returns the active context from certain zone name
* @param activeZone
*/
private _activeContextFromZone(activeZone: Zone | undefined): Context {
return (activeZone && activeZone.get(ZONE_CONTEXT_KEY)) || ROOT_CONTEXT;
}
/**
* @param target Function to be executed within the context
* @param context A context (span) to be executed within target function
*/
private _bindFunction<T extends Function>(target: T, context: Context): T {
const manager = this;
const contextWrapper = function (this: any, ...args: unknown[]) {
return manager.with(context, () => target.apply(this, args));
};
Object.defineProperty(contextWrapper, 'length', {
enumerable: false,
configurable: true,
writable: false,
value: target.length,
});
return (contextWrapper as unknown) as T;
}
/**
* @param obj target object on which the listeners will be patched
* @param context A context (span) to be bind to target
*/
private _bindListener<T>(obj: T, context: Context): T {
const target = (obj as unknown) as TargetWithEvents;
if (target.__ot_listeners !== undefined) {
return obj;
}
target.__ot_listeners = {};
if (typeof target.addEventListener === 'function') {
target.addEventListener = this._patchAddEventListener(
target,
target.addEventListener,
context
);
}
if (typeof target.removeEventListener === 'function') {
target.removeEventListener = this._patchRemoveEventListener(
target,
target.removeEventListener
);
}
return obj;
}
/**
* Creates a new unique zone name
*/
private _createZoneName() {
this._zoneCounter++;
const random = Math.random();
return `${this._zoneCounter}-${random}`;
}
/**
* Creates a new zone
* @param zoneName zone name
* @param context A context (span) to be bind with Zone
*/
private _createZone(zoneName: string, context: unknown): Zone {
return Zone.current.fork({
name: zoneName,
properties: {
[ZONE_CONTEXT_KEY]: context,
},
});
}
/**
* Returns the active zone
*/
private _getActiveZone(): Zone | undefined {
return Zone.current;
}
/**
* Patches addEventListener method
* @param target any target that has "addEventListener" method
* @param original reference to the patched method
* @param [context] context to be bind to the listener
*/
private _patchAddEventListener(
target: TargetWithEvents,
original: Function,
context: Context
) {
const contextManager = this;
return function (
this: {},
event: string,
listener: Func<void>,
opts?: any
) {
if (target.__ot_listeners === undefined) {
target.__ot_listeners = {};
}
let listeners = target.__ot_listeners[event];
if (listeners === undefined) {
listeners = new WeakMap();
target.__ot_listeners[event] = listeners;
}
const patchedListener = contextManager.bind(listener, context);
// store a weak reference of the user listener to ours
listeners.set(listener, patchedListener);
return original.call(this, event, patchedListener, opts);
};
}
/**
* Patches removeEventListener method
* @param target any target that has "removeEventListener" method
* @param original reference to the patched method
*/
private _patchRemoveEventListener(
target: TargetWithEvents,
original: Function
) {
return function (this: {}, event: string, listener: Func<void>) {
if (
target.__ot_listeners === undefined ||
target.__ot_listeners[event] === undefined
) {
return original.call(this, event, listener);
}
const events = target.__ot_listeners[event];
const patchedListener = events.get(listener);
events.delete(listener);
return original.call(this, event, patchedListener || listener);
};
}
/**
* Returns the active context
*/
active(): Context {
if (!this._enabled) {
return ROOT_CONTEXT;
}
const activeZone = this._getActiveZone();
const active = this._activeContextFromZone(activeZone);
if (active) {
return active;
}
return ROOT_CONTEXT;
}
/**
* Binds a the certain context or the active one to the target function and then returns the target
* @param target
* @param context A context (span) to be bind to target
*/
bind<T>(target: T | TargetWithEvents, context: Context): T {
// if no specific context to propagate is given, we use the current one
if (context === undefined) {
context = this.active();
}
if (typeof target === 'function') {
return this._bindFunction(target, context);
} else if (isListenerObject(target)) {
this._bindListener(target, context);
}
return (target as unknown) as T;
}
/**
* Disable the context manager (clears all the contexts)
*/
disable(): this {
this._enabled = false;
return this;
}
/**
* Enables the context manager and creates a default(root) context
*/
enable(): this {
this._enabled = true;
return this;
}
/**
* Calls the callback function [fn] with the provided [context].
* If [context] is undefined then it will use the active context.
* The context will be set as active
* @param context A context (span) to be called with provided callback
* @param fn Callback function
* @param thisArg optional receiver to be used for calling fn
* @param args optional arguments forwarded to fn
*/
with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(
context: Context | null,
fn: F,
thisArg?: ThisParameterType<F>,
...args: A
): ReturnType<F> {
const zoneName = this._createZoneName();
const newZone = this._createZone(zoneName, context);
return newZone.run(fn, thisArg, args);
}
}