-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathCorrelationIdManager.ts
executable file
·182 lines (161 loc) · 7.71 KB
/
CorrelationIdManager.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
import Util = require("./Util");
import Config = require("./Config");
import Logging = require("./Logging");
class CorrelationIdManager {
private static TAG = "CorrelationIdManager";
private static _handle: NodeJS.Timer;
public static correlationIdPrefix = "cid-v1:";
public static w3cEnabled = true;
// To avoid extraneous HTTP requests, we maintain a queue of callbacks waiting on a particular appId lookup,
// as well as a cache of completed lookups so future requests can be resolved immediately.
private static pendingLookups: { [key: string]: Function[] } = {};
private static completedLookups: { [key: string]: string } = {};
private static requestIdMaxLength = 1024;
private static currentRootId = Util.randomu32();
public static queryCorrelationId(config: Config, callback: (correlationId: string) => void) {
// GET request to `${this.endpointBase}/api/profiles/${this.instrumentationKey}/appId`
// If it 404s, the iKey is bad and we should give up
// If it fails otherwise, try again later
const appIdUrlString = `${config.profileQueryEndpoint}/api/profiles/${config.instrumentationKey}/appId`;
if (CorrelationIdManager.completedLookups.hasOwnProperty(appIdUrlString)) {
callback(CorrelationIdManager.completedLookups[appIdUrlString]);
return;
} else if (CorrelationIdManager.pendingLookups[appIdUrlString]) {
CorrelationIdManager.pendingLookups[appIdUrlString].push(callback);
return;
}
CorrelationIdManager.pendingLookups[appIdUrlString] = [callback];
const fetchAppId = () => {
if (!CorrelationIdManager.pendingLookups[appIdUrlString]) {
// This query has been cancelled.
return;
}
const requestOptions = {
method: "GET",
// Ensure this request is not captured by auto-collection.
// Note: we don't refer to the property in HttpDependencyParser because that would cause a cyclical dependency
disableAppInsightsAutoCollection: true
};
Logging.info(CorrelationIdManager.TAG, requestOptions);
const req = Util.makeRequest(config, appIdUrlString, requestOptions, (res) => {
if (res.statusCode === 200) {
// Success; extract the appId from the body
let appId = "";
res.setEncoding("utf-8");
res.on("data", (data: any) => {
appId += data;
});
res.on("end", () => {
Logging.info(CorrelationIdManager.TAG, appId);
const result = CorrelationIdManager.correlationIdPrefix + appId;
CorrelationIdManager.completedLookups[appIdUrlString] = result;
if (CorrelationIdManager.pendingLookups[appIdUrlString]) {
CorrelationIdManager.pendingLookups[appIdUrlString].forEach((cb) => cb(result));
}
delete CorrelationIdManager.pendingLookups[appIdUrlString];
});
} else if (res.statusCode >= 400 && res.statusCode < 500) {
// Not found, probably a bad key. Do not try again.
CorrelationIdManager.completedLookups[appIdUrlString] = undefined;
delete CorrelationIdManager.pendingLookups[appIdUrlString];
}
else {
// Keep retrying
return;
}
// Do not retry
if (CorrelationIdManager._handle) {
clearTimeout(CorrelationIdManager._handle);
CorrelationIdManager._handle = undefined;
}
}, true, false);
if (req) {
req.on("error", (error: Error) => {
// Unable to contact endpoint.
// Do nothing for now.
Logging.warn(CorrelationIdManager.TAG, error);
if (this._handle) {
clearTimeout(CorrelationIdManager._handle);
CorrelationIdManager._handle = undefined;
}
});
req.end();
}
};
if (!CorrelationIdManager._handle) {
CorrelationIdManager._handle = <any>setTimeout(fetchAppId, config.correlationIdRetryIntervalMs);
CorrelationIdManager._handle.unref(); // Don't block apps from terminating
}
// Initial fetch
setImmediate(fetchAppId);
}
public static cancelCorrelationIdQuery(config: Config, callback: (correlationId: string) => void) {
const appIdUrlString = `${config.profileQueryEndpoint}/api/profiles/${config.instrumentationKey}/appId`;
const pendingLookups = CorrelationIdManager.pendingLookups[appIdUrlString];
if (pendingLookups) {
CorrelationIdManager.pendingLookups[appIdUrlString] = pendingLookups.filter((cb) => cb != callback);
if (CorrelationIdManager.pendingLookups[appIdUrlString].length == 0) {
delete CorrelationIdManager.pendingLookups[appIdUrlString];
}
}
}
/**
* Generate a request Id according to https://github.com/lmolkova/correlation/blob/master/hierarchical_request_id.md
* @param parentId
*/
public static generateRequestId(parentId: string): string {
if (parentId) {
parentId = parentId[0] == "|" ? parentId : "|" + parentId;
if (parentId[parentId.length - 1] !== ".") {
parentId += ".";
}
const suffix = (CorrelationIdManager.currentRootId++).toString(16);
return CorrelationIdManager.appendSuffix(parentId, suffix, "_")
} else {
return CorrelationIdManager.generateRootId();
}
}
/**
* Given a hierarchical identifier of the form |X.*
* return the root identifier X
* @param id
*/
public static getRootId(id: string): string {
let endIndex = id.indexOf(".");
if (endIndex < 0) {
endIndex = id.length;
}
const startIndex = id[0] === "|" ? 1 : 0;
return id.substring(startIndex, endIndex);
}
private static generateRootId(): string {
return "|" + Util.w3cTraceId() + ".";
}
private static appendSuffix(parentId: string, suffix: string, delimiter: string): string {
if (parentId.length + suffix.length < CorrelationIdManager.requestIdMaxLength) {
return parentId + suffix + delimiter;
}
// Combined identifier would be too long, so we must truncate it.
// We need 9 characters of space: 8 for the overflow ID, 1 for the
// overflow delimiter '#'
let trimPosition = CorrelationIdManager.requestIdMaxLength - 9;
if (parentId.length > trimPosition) {
for (; trimPosition > 1; --trimPosition) {
const c = parentId[trimPosition - 1];
if (c === "." || c === "_") {
break;
}
}
}
if (trimPosition <= 1) {
// parentId is not a valid ID
return CorrelationIdManager.generateRootId();
}
suffix = Util.randomu32().toString(16);
while (suffix.length < 8) {
suffix = "0" + suffix;
}
return parentId.substring(0, trimPosition) + suffix + "#";
}
}
export = CorrelationIdManager;