UNPKG

34.6 kBJavaScriptView Raw
1import { _ as __assign } from './tslib.es6-f952ba6f.js';
2import { U as Utils, E as ErrorCodes } from './Utils-38a0872e.js';
3
4var ServerClient = /** @class */ (function () {
5 function ServerClient() {
6 var _this = this;
7 this.apiVersionUrlParam = "?api-version=2016-12-12";
8 this.oldTsmTsqApiVersion = "?api-version=2018-11-01-preview";
9 this.tsmTsqApiVersion = "?api-version=2020-07-31";
10 this.referenceDataAPIVersion = "?api-version=2017-11-15";
11 this.maxRetryCount = 3;
12 this.sessionId = Utils.guid();
13 this.retriableStatusCodes = [408, 429, 500, 503];
14 this.onAjaxError = function (logObject) { };
15 this.onAjaxRetry = function (logObject) { };
16 this.onFallbackToOldApiVersion = function (logObject) { };
17 this.retryBasedOnStatus = function (xhr) { return _this.retriableStatusCodes.indexOf(xhr.status) !== -1; };
18 this.fallBackToOldApiVersion = function (xhr) { return xhr.status === 400 && xhr.response.indexOf('UnsupportedTSXVersionTSX01') !== -1; };
19 this.setStandardHeaders = function (xhr, token) {
20 var clientRequestId = Utils.guid();
21 xhr.setRequestHeader('Authorization', 'Bearer ' + token);
22 xhr.setRequestHeader('x-ms-client-request-id', clientRequestId);
23 xhr.setRequestHeader('x-ms-client-session-id', _this.sessionId);
24 return clientRequestId;
25 };
26 this.mergeTsqEventsResults = function (tsqEvents) {
27 var events = { properties: [], timestamps: [] };
28 tsqEvents.forEach(function (tsqe) {
29 var currentPropertiesValueLength = events.timestamps.length;
30 if (tsqe.properties && tsqe.properties.length) {
31 tsqe.properties.forEach(function (prop) {
32 var foundProperty = events.properties.filter(function (p) { return p.name === prop.name && p.type === prop.type; });
33 var existingProperty;
34 if (foundProperty.length === 1) {
35 var indexOfExistingProperty = events.properties.indexOf(foundProperty[0]);
36 existingProperty = events.properties[indexOfExistingProperty];
37 }
38 else {
39 existingProperty = { name: prop.name, type: prop.type, values: [] };
40 events.properties.push(existingProperty);
41 }
42 while (existingProperty.values.length < currentPropertiesValueLength) {
43 existingProperty.values.push(null);
44 }
45 existingProperty.values = existingProperty.values.concat(prop.values);
46 });
47 }
48 events.timestamps = events.timestamps.concat(tsqe.timestamps);
49 });
50 return events;
51 };
52 this.getQueryApiResult = function (token, results, contentObject, index, uri, resolve, messageProperty, onProgressChange, mergeAccumulatedResults, xhr) {
53 if (onProgressChange === void 0) { onProgressChange = function (percentComplete) { }; }
54 if (mergeAccumulatedResults === void 0) { mergeAccumulatedResults = false; }
55 if (xhr === void 0) { xhr = null; }
56 if (xhr === null) {
57 xhr = new XMLHttpRequest();
58 }
59 var onreadystatechange;
60 var retryCount = 0;
61 var retryTimeout;
62 var continuationToken;
63 var accumulator = [];
64 var clientRequestId;
65 onreadystatechange = function () {
66 if (xhr.readyState != 4)
67 return;
68 var fallBackToOldApiVersion = _this.fallBackToOldApiVersion(xhr);
69 if (xhr.status == 200) {
70 var message = JSON.parse(xhr.responseText);
71 if (!message.continuationToken) {
72 if (mergeAccumulatedResults && accumulator.length) {
73 accumulator.push(message);
74 results[index] = _this.mergeTsqEventsResults(accumulator);
75 }
76 else {
77 results[index] = messageProperty(message);
78 delete results[index].progress;
79 }
80 var eventCount = (results[index] && results[index].timestamps && results[index].timestamps.length) ? results[index].timestamps.length : 0;
81 var take = (contentObject && contentObject.getEvents && contentObject.getEvents.take) ? contentObject.getEvents.take : 0;
82 if (eventCount && take && eventCount === take) {
83 results['moreEventsAvailable'] = true;
84 }
85 if (results.map(function (ar) { return !('progress' in ar); }).reduce(function (p, c) { p = c && p; return p; }, true))
86 resolve(results);
87 }
88 else {
89 accumulator.push(message);
90 var progressFromMessage = message && message.progress ? message.progress : 0;
91 results[index].progress = mergeAccumulatedResults ? Math.max(progressFromMessage, accumulator.reduce(function (p, c) { return p + (c.timestamps && c.timestamps.length ? c.timestamps.length : 0); }, 0) / contentObject.getEvents.take * 100) : progressFromMessage;
92 xhr = new XMLHttpRequest();
93 xhr.onreadystatechange = onreadystatechange;
94 xhr.open('POST', uri);
95 _this.setStandardHeaders(xhr, token);
96 xhr.setRequestHeader('Content-Type', 'application/json');
97 continuationToken = message.continuationToken;
98 xhr.setRequestHeader('x-ms-continuation', continuationToken);
99 xhr.send(JSON.stringify(contentObject));
100 }
101 }
102 else if ((_this.retryBasedOnStatus(xhr) && retryCount < _this.maxRetryCount) || fallBackToOldApiVersion) {
103 retryCount += fallBackToOldApiVersion ? 0 : 1;
104 retryTimeout = _this.retryWithDelay(retryCount, function () {
105 if (fallBackToOldApiVersion) {
106 uri = uri.split(_this.tsmTsqApiVersion).join(_this.oldTsmTsqApiVersion);
107 _this.onFallbackToOldApiVersion({ uri: uri, payload: JSON.stringify(contentObject), clientRequestId: clientRequestId, sessionId: _this.sessionId, statusCode: xhr.status });
108 }
109 xhr.open('POST', uri);
110 clientRequestId = _this.setStandardHeaders(xhr, token);
111 xhr.setRequestHeader('Content-Type', 'application/json');
112 if (continuationToken)
113 xhr.setRequestHeader('x-ms-continuation', continuationToken);
114 xhr.send(JSON.stringify(contentObject));
115 _this.onAjaxRetry({ uri: uri, payload: JSON.stringify(contentObject), clientRequestId: clientRequestId, sessionId: _this.sessionId, statusCode: xhr.status });
116 });
117 }
118 else if (xhr.status !== 0) {
119 results[index] = { __tsiError__: JSON.parse(xhr.responseText) };
120 if (results.map(function (ar) { return !('progress' in ar); }).reduce(function (p, c) { p = c && p; return p; }, true)) {
121 resolve(results);
122 _this.onAjaxError({ uri: uri, payload: JSON.stringify(contentObject), clientRequestId: clientRequestId, sessionId: _this.sessionId });
123 }
124 }
125 var percentComplete = Math.max(results.map(function (r) { return 'progress' in r ? r.progress : 100; }).reduce(function (p, c) { return p + c; }, 0) / results.length, 1);
126 onProgressChange(percentComplete);
127 };
128 xhr.onreadystatechange = onreadystatechange;
129 xhr.onabort = function () {
130 resolve('__CANCELLED__');
131 clearTimeout(retryTimeout);
132 };
133 xhr.open('POST', uri);
134 clientRequestId = _this.setStandardHeaders(xhr, token);
135 xhr.setRequestHeader('Content-Type', 'application/json');
136 xhr.send(JSON.stringify(contentObject));
137 };
138 // this function returns a promise which resolve empty object after request is done and
139 // keeps track of the items and changes the values in the passed parameters
140 // based on the response if it is erroneous
141 this.sendBatchDataPostRequestPromise = function (requestParams, batchParams) {
142 var url = requestParams.url, token = requestParams.token, method = requestParams.method, onProgressChange = requestParams.onProgressChange, batch = requestParams.batch;
143 return new Promise(function (resolve) {
144 var batchObject = {};
145 batchObject[method] = batch;
146 var xhr = new XMLHttpRequest();
147 xhr.onreadystatechange = function () {
148 if (xhr.readyState !== 4) {
149 return;
150 }
151 if (xhr.status === 200 || xhr.status === 202) {
152 var result = JSON.parse(xhr.responseText);
153 if (result === null || result === void 0 ? void 0 : result.error) {
154 batchParams.erroneousDataCount += batch.length;
155 batchParams.resultErrorMessage += result.error.message ? ' Item ' + batchParams.dataIndex + "-" + (batchParams.dataIndex + batch.length) + ": " + result.error.message : '';
156 batchParams.dataIndex += batch.length;
157 return;
158 }
159 else {
160 result[method].forEach(function (i) {
161 var _a;
162 batchParams.dataIndex++;
163 if ((i === null || i === void 0 ? void 0 : i.error) || (i === null || i === void 0 ? void 0 : i.code) === ErrorCodes.InvalidInput) {
164 batchParams.erroneousDataCount++;
165 batchParams.resultErrorMessage += "\n>Item-" + batchParams.dataIndex + ": " + (((_a = i === null || i === void 0 ? void 0 : i.error) === null || _a === void 0 ? void 0 : _a.message) || (i === null || i === void 0 ? void 0 : i.message));
166 }
167 });
168 }
169 }
170 else {
171 batchParams.erroneousDataCount += batch.length;
172 batchParams.resultErrorMessage += ' Item ' + batchParams.dataIndex + "-" + (batchParams.dataIndex + batch.length) + ": Server error!";
173 batchParams.dataIndex += batch.length;
174 }
175 batchParams.completedDataCount += batch.length;
176 var percentComplete = batchParams.completedDataCount * 100 / batchParams.totalItemCount;
177 onProgressChange(percentComplete);
178 resolve({});
179 };
180 xhr.open('POST', url);
181 _this.setStandardHeaders(xhr, token);
182 xhr.setRequestHeader('Content-Type', 'application/json');
183 xhr.send(JSON.stringify(batchObject));
184 });
185 };
186 this.createPostBatchPromise = function (url, data, token, method, responseTextFormat, onProgressChange, batchSize, maxByteSize) {
187 var batchParams = {
188 dataIndex: 0,
189 erroneousDataCount: 0,
190 completedDataCount: 0,
191 totalItemCount: data.length,
192 resultErrorMessage: ''
193 };
194 var batches = [];
195 while (data.length) {
196 var batch = [];
197 while (batch.length < batchSize && Utils.memorySizeOf(batch.concat(data[0])) < maxByteSize) { // create the batch of data to send based on limits provided
198 batch = batch.concat(data.splice(0, 1));
199 if (data.length === 0) {
200 break;
201 }
202 }
203 if (batch.length) {
204 batches.push(batch);
205 }
206 }
207 //returns a promise with result object which waits for inner promises to make batch requests and resolve
208 return batches.reduce(function (p, batch) {
209 return p.then(function () { return _this.sendBatchDataPostRequestPromise({ url: url, token: token, method: method, onProgressChange: onProgressChange, batch: batch }, batchParams); }); // send batches in sequential order
210 }, Promise.resolve())
211 .then(function () {
212 var result = {};
213 if (batchParams.erroneousDataCount === 0) {
214 result[method] = [{}];
215 }
216 else {
217 result[method] = [{ error: { code: ErrorCodes.PartialSuccess, message: "Error in " + batchParams.erroneousDataCount + "/" + batchParams.totalItemCount + (" items. " + batchParams.resultErrorMessage) } }];
218 }
219 return responseTextFormat(JSON.stringify(result));
220 });
221 };
222 this.createPromiseFromXhrForBatchData = function (url, payload, token, responseTextFormat, onProgressChange, batchSize, maxByteSize) {
223 if (onProgressChange === void 0) { onProgressChange = function (percentComplete) { }; }
224 if (batchSize === void 0) { batchSize = 1000; }
225 if (maxByteSize === void 0) { maxByteSize = 8000000; }
226 var payloadObj = JSON.parse(payload);
227 if (payloadObj.put || payloadObj.update) {
228 var method = payloadObj.put ? "put" : "update";
229 var data = payloadObj[method];
230 return _this.createPostBatchPromise(url, data, token, method, responseTextFormat, onProgressChange, batchSize, maxByteSize);
231 }
232 else {
233 return _this.createPromiseFromXhr(url, 'POST', payload, token, function (responseText) { return JSON.parse(responseText); });
234 }
235 };
236 }
237 ServerClient.prototype.Server = function () {
238 };
239 ServerClient.prototype.createPromiseFromXhr = function (uri, httpMethod, payload, token, responseTextFormat, continuationToken) {
240 var _this = this;
241 if (continuationToken === void 0) { continuationToken = null; }
242 return new Promise(function (resolve, reject) {
243 var sendRequest;
244 var retryCount = 0;
245 var clientRequestId;
246 sendRequest = function () {
247 var xhr = new XMLHttpRequest();
248 xhr.onreadystatechange = function () {
249 if (xhr.readyState != 4)
250 return;
251 if (xhr.status >= 200 && xhr.status < 300) {
252 if (xhr.responseText.length == 0)
253 resolve({});
254 else {
255 resolve(responseTextFormat(xhr.responseText));
256 }
257 }
258 else if (_this.retryBasedOnStatus(xhr) && retryCount < _this.maxRetryCount) {
259 retryCount++;
260 _this.retryWithDelay(retryCount, sendRequest);
261 _this.onAjaxRetry({ uri: uri, method: httpMethod, payload: JSON.stringify(payload), clientRequestId: clientRequestId, sessionId: _this.sessionId, statusCode: xhr.status });
262 }
263 else {
264 reject(xhr);
265 _this.onAjaxError({ uri: uri, method: httpMethod, payload: JSON.stringify(payload), clientRequestId: clientRequestId, sessionId: _this.sessionId });
266 }
267 };
268 xhr.open(httpMethod, uri);
269 clientRequestId = _this.setStandardHeaders(xhr, token);
270 if (httpMethod == 'POST' || httpMethod == 'PUT')
271 xhr.setRequestHeader('Content-Type', 'application/json');
272 if (continuationToken)
273 xhr.setRequestHeader('x-ms-continuation', continuationToken);
274 xhr.send(payload);
275 };
276 sendRequest();
277 });
278 };
279 ServerClient.prototype.getCancellableTsqResults = function (token, uri, tsqArray, onProgressChange, mergeAccumulatedResults, storeType) {
280 if (onProgressChange === void 0) { onProgressChange = function (p) { }; }
281 if (mergeAccumulatedResults === void 0) { mergeAccumulatedResults = false; }
282 if (storeType === void 0) { storeType = null; }
283 // getTsqResults() returns either a promise or an array containing a promise + cancel trigger
284 // depending on whether we set the hasCancelTrigger flag. Here we need to set the type of what
285 // we get back to 'unknown'. This lets TypeScript know that we have enough information to
286 // confidently cast the return value as an Array<Promise<any> | Function>.
287 var promiseAndTrigger = this.getTsqResults(token, uri, tsqArray, onProgressChange, mergeAccumulatedResults, storeType, true);
288 return promiseAndTrigger;
289 };
290 ServerClient.prototype.getTsqResults = function (token, uri, tsqArray, onProgressChange, mergeAccumulatedResults, storeType, hasCancelTrigger) {
291 var _this = this;
292 if (onProgressChange === void 0) { onProgressChange = function (p) { }; }
293 if (mergeAccumulatedResults === void 0) { mergeAccumulatedResults = false; }
294 if (storeType === void 0) { storeType = null; }
295 if (hasCancelTrigger === void 0) { hasCancelTrigger = false; }
296 var tsqResults = [];
297 tsqArray.forEach(function (tsq) {
298 tsqResults.push({ progress: 0 });
299 });
300 var xhrs = tsqArray.map(function (tsq) {
301 return new XMLHttpRequest();
302 });
303 var storeTypeString = storeType ? '&storeType=' + storeType : '';
304 var promise = new Promise(function (resolve, reject) {
305 tsqArray.map(function (tsq, i) {
306 return _this.getQueryApiResult(token, tsqResults, tsq, i, "https://" + uri + "/timeseries/query" + _this.tsmTsqApiVersion + storeTypeString, resolve, function (message) { return message; }, onProgressChange, mergeAccumulatedResults, xhrs[i]);
307 });
308 });
309 if (hasCancelTrigger) {
310 var cancelTrigger = function () {
311 xhrs.forEach(function (xhr) {
312 xhr.abort();
313 });
314 };
315 return [promise, cancelTrigger];
316 }
317 return promise;
318 };
319 ServerClient.prototype.getAggregates = function (token, uri, tsxArray, onProgressChange) {
320 var _this = this;
321 if (onProgressChange === void 0) { onProgressChange = function (p) { }; }
322 var aggregateResults = [];
323 tsxArray.forEach(function (ae) {
324 aggregateResults.push({ progress: 0 });
325 });
326 return new Promise(function (resolve, reject) {
327 tsxArray.forEach(function (tsx, i) {
328 _this.getQueryApiResult(token, aggregateResults, tsx, i, "https://" + uri + "/aggregates" + _this.apiVersionUrlParam, resolve, function (message) { return message.aggregates[0]; }, onProgressChange);
329 });
330 });
331 };
332 ServerClient.prototype.getTimeseriesInstances = function (token, environmentFqdn, limit, timeSeriesIds) {
333 var _this = this;
334 if (limit === void 0) { limit = 10000; }
335 if (timeSeriesIds === void 0) { timeSeriesIds = null; }
336 if (!timeSeriesIds || timeSeriesIds.length === 0) {
337 return new Promise(function (resolve, reject) {
338 _this.getDataWithContinuationBatch(token, resolve, reject, [], 'https://' + environmentFqdn + '/timeseries/instances/' + _this.tsmTsqApiVersion, 'GET', 'instances', null, limit);
339 });
340 }
341 else {
342 return this.createPromiseFromXhr('https://' + environmentFqdn + '/timeseries/instances/$batch' + this.tsmTsqApiVersion, "POST", JSON.stringify({ get: timeSeriesIds }), token, function (responseText) { return JSON.parse(responseText); });
343 }
344 };
345 ServerClient.prototype.getTimeseriesTypes = function (token, environmentFqdn, typeIds) {
346 if (typeIds === void 0) { typeIds = null; }
347 if (!typeIds || typeIds.length === 0) {
348 var uri = 'https://' + environmentFqdn + '/timeseries/types/' + this.tsmTsqApiVersion;
349 return this.createPromiseFromXhr(uri, "GET", {}, token, function (responseText) { return JSON.parse(responseText); });
350 }
351 else {
352 return this.createPromiseFromXhr('https://' + environmentFqdn + '/timeseries/types/$batch' + this.tsmTsqApiVersion, "POST", JSON.stringify({ get: { typeIds: typeIds, names: null } }), token, function (responseText) { return JSON.parse(responseText); });
353 }
354 };
355 ServerClient.prototype.postTimeSeriesTypes = function (token, environmentFqdn, payload, useOldApiVersion) {
356 if (useOldApiVersion === void 0) { useOldApiVersion = false; }
357 var uri = 'https://' + environmentFqdn + '/timeseries/types/$batch' + (useOldApiVersion ? this.oldTsmTsqApiVersion : this.tsmTsqApiVersion);
358 return this.createPromiseFromXhr(uri, "POST", payload, token, function (responseText) { return JSON.parse(responseText); });
359 };
360 ServerClient.prototype.updateSavedQuery = function (token, timeSeriesQuery, endpoint) {
361 if (endpoint === void 0) { endpoint = 'https://api.timeseries.azure.com'; }
362 var uri = endpoint + "/artifacts/" + timeSeriesQuery.id + this.tsmTsqApiVersion;
363 var payload = JSON.stringify(timeSeriesQuery);
364 return this.createPromiseFromXhr(uri, "MERGE", payload, token, function (responseText) { return JSON.parse(responseText); });
365 };
366 ServerClient.prototype.getTimeseriesHierarchies = function (token, environmentFqdn) {
367 var uri = 'https://' + environmentFqdn + '/timeseries/hierarchies/' + this.tsmTsqApiVersion;
368 return this.createPromiseFromXhr(uri, "GET", {}, token, function (responseText) { return JSON.parse(responseText); });
369 };
370 ServerClient.prototype.getTimeseriesModel = function (token, environmentFqdn) {
371 var uri = 'https://' + environmentFqdn + '/timeseries/modelSettings/' + this.tsmTsqApiVersion;
372 return this.createPromiseFromXhr(uri, "GET", {}, token, function (responseText) { return JSON.parse(responseText); });
373 };
374 ServerClient.prototype.getTimeseriesInstancesPathSearch = function (token, environmentFqdn, payload, instancesContinuationToken, hierarchiesContinuationToken) {
375 if (instancesContinuationToken === void 0) { instancesContinuationToken = null; }
376 if (hierarchiesContinuationToken === void 0) { hierarchiesContinuationToken = null; }
377 var uri = 'https://' + environmentFqdn + '/timeseries/instances/search' + this.tsmTsqApiVersion;
378 var requestPayload = __assign({}, payload);
379 if (requestPayload.path.length == 0) {
380 requestPayload.path = null;
381 }
382 return this.createPromiseFromXhr(uri, "POST", JSON.stringify(requestPayload), token, function (responseText) { return JSON.parse(responseText); }, instancesContinuationToken || hierarchiesContinuationToken);
383 };
384 ServerClient.prototype.getTimeseriesInstancesSuggestions = function (token, environmentFqdn, searchString, take) {
385 if (take === void 0) { take = 10; }
386 var uri = 'https://' + environmentFqdn + '/timeseries/instances/suggest' + this.tsmTsqApiVersion;
387 return this.createPromiseFromXhr(uri, "POST", JSON.stringify({ searchString: searchString, take: take }), token, function (responseText) { return JSON.parse(responseText); });
388 };
389 ServerClient.prototype.getTimeseriesInstancesSearch = function (token, environmentFqdn, searchString, continuationToken) {
390 if (continuationToken === void 0) { continuationToken = null; }
391 var uri = 'https://' + environmentFqdn + '/timeseries/instances/search' + this.tsmTsqApiVersion;
392 return this.createPromiseFromXhr(uri, "POST", JSON.stringify({ searchString: searchString }), token, function (responseText) { return JSON.parse(responseText); }, continuationToken);
393 };
394 ServerClient.prototype.getReferenceDatasetRows = function (token, environmentFqdn, datasetId) {
395 var _this = this;
396 return new Promise(function (resolve, reject) {
397 _this.getDataWithContinuationBatch(token, resolve, reject, [], "https://" + environmentFqdn + "/referencedatasets/" + datasetId + "/items" + _this.apiVersionUrlParam + "&format=stream", 'POST', 'items');
398 });
399 };
400 ServerClient.prototype.postReferenceDatasetRows = function (token, environmentFqdn, datasetName, rows, onProgressChange) {
401 if (onProgressChange === void 0) { onProgressChange = function (p) { }; }
402 var uri = "https://" + environmentFqdn + "/referencedatasets/" + datasetName + "/$batch" + this.apiVersionUrlParam;
403 return this.createPromiseFromXhrForBatchData(uri, JSON.stringify({ put: rows }), token, function (responseText) { return JSON.parse(responseText); }, onProgressChange);
404 };
405 ServerClient.prototype.getReferenceDatasets = function (token, resourceId, endpoint) {
406 if (endpoint === void 0) { endpoint = "https://management.azure.com"; }
407 var uri = endpoint + resourceId + "/referencedatasets" + this.referenceDataAPIVersion;
408 return this.createPromiseFromXhr(uri, "GET", {}, token, function (responseText) { return JSON.parse(responseText); });
409 };
410 ServerClient.prototype.deleteReferenceDataSet = function (token, resourceId, datasetName, endpoint) {
411 if (endpoint === void 0) { endpoint = "https://management.azure.com"; }
412 var uri = endpoint + resourceId + "/referencedatasets/" + datasetName + this.referenceDataAPIVersion;
413 return this.createPromiseFromXhr(uri, "DELETE", {}, token, function (responseText) { return JSON.parse(responseText); });
414 };
415 ServerClient.prototype.putReferenceDataSet = function (token, resourceId, datasetName, dataSet, endpoint) {
416 if (endpoint === void 0) { endpoint = "https://management.azure.com"; }
417 var uri = endpoint + resourceId + "/referencedatasets/" + datasetName + this.referenceDataAPIVersion;
418 return this.createPromiseFromXhr(uri, "PUT", JSON.stringify(dataSet), token, function (responseText) { return JSON.parse(responseText); });
419 };
420 ServerClient.prototype.getGen1Environment = function (token, resourceId, endpoint) {
421 if (endpoint === void 0) { endpoint = "https://management.azure.com"; }
422 var uri = endpoint + resourceId + this.referenceDataAPIVersion;
423 return this.createPromiseFromXhr(uri, "GET", {}, token, function (responseText) { return JSON.parse(responseText); });
424 };
425 ServerClient.prototype.getEnvironments = function (token, endpoint) {
426 if (endpoint === void 0) { endpoint = 'https://api.timeseries.azure.com'; }
427 var uri = endpoint + '/environments' + this.apiVersionUrlParam;
428 return this.createPromiseFromXhr(uri, "GET", {}, token, function (responseText) { return JSON.parse(responseText); });
429 };
430 ServerClient.prototype.getSampleEnvironments = function (token, endpoint) {
431 if (endpoint === void 0) { endpoint = 'https://api.timeseries.azure.com'; }
432 var uri = endpoint + '/sampleenvironments' + this.apiVersionUrlParam;
433 return this.createPromiseFromXhr(uri, "GET", {}, token, function (responseText) { return JSON.parse(responseText); });
434 };
435 ServerClient.prototype.getMetadata = function (token, environmentFqdn, minMillis, maxMillis) {
436 var uri = 'https://' + environmentFqdn + '/metadata' + this.apiVersionUrlParam;
437 var searchSpan = { searchSpan: { from: new Date(minMillis).toISOString(), to: new Date(maxMillis).toISOString() } };
438 var payload = JSON.stringify(searchSpan);
439 return this.createPromiseFromXhr(uri, "POST", payload, token, function (responseText) { return JSON.parse(responseText).properties; });
440 };
441 ServerClient.prototype.getEventSchema = function (token, environmentFqdn, minMillis, maxMillis) {
442 var uri = 'https://' + environmentFqdn + '/eventSchema' + this.tsmTsqApiVersion;
443 var searchSpan = { searchSpan: { from: new Date(minMillis).toISOString(), to: new Date(maxMillis).toISOString() } };
444 var payload = JSON.stringify(searchSpan);
445 return this.createPromiseFromXhr(uri, "POST", payload, token, function (responseText) { return JSON.parse(responseText).properties; });
446 };
447 ServerClient.prototype.getAvailability = function (token, environmentFqdn, apiVersion, hasWarm) {
448 var _this = this;
449 if (apiVersion === void 0) { apiVersion = this.apiVersionUrlParam; }
450 if (hasWarm === void 0) { hasWarm = false; }
451 var uriBase = 'https://' + environmentFqdn + '/availability';
452 var coldUri = uriBase + apiVersion + (hasWarm ? '&storeType=ColdStore' : '');
453 return new Promise(function (resolve, reject) {
454 _this.createPromiseFromXhr(coldUri, "GET", {}, token, function (responseText) { return JSON.parse(responseText); }).then(function (coldResponse) {
455 if (hasWarm) {
456 var warmUri = uriBase + apiVersion + '&storeType=WarmStore';
457 _this.createPromiseFromXhr(warmUri, "GET", {}, token, function (responseText) { return JSON.parse(responseText); }).then(function (warmResponse) {
458 var availability = warmResponse ? warmResponse.availability : null;
459 if (coldResponse.availability) {
460 availability = Utils.mergeAvailabilities(warmResponse.availability, coldResponse.availability, warmResponse.retention);
461 }
462 resolve({ availability: availability });
463 })
464 .catch(function () { resolve(coldResponse); });
465 }
466 else {
467 resolve(coldResponse);
468 }
469 })
470 .catch(function (xhr) {
471 reject(xhr);
472 });
473 });
474 };
475 ServerClient.prototype.getEvents = function (token, environmentFqdn, predicateObject, options, minMillis, maxMillis) {
476 var uri = 'https://' + environmentFqdn + '/events' + this.apiVersionUrlParam;
477 var take = 10000;
478 var searchSpan = { from: new Date(minMillis).toISOString(), to: new Date(maxMillis).toISOString() };
479 var topObject = { sort: [{ input: { builtInProperty: '$ts' }, order: 'Asc' }], count: take };
480 var messageObject = { predicate: predicateObject, top: topObject, searchSpan: searchSpan };
481 var payload = JSON.stringify(messageObject);
482 return this.createPromiseFromXhr(uri, "POST", payload, token, function (responseText) { return JSON.parse(responseText).events; });
483 };
484 ServerClient.prototype.getDataWithContinuationBatch = function (token, resolve, reject, rows, url, verb, propName, continuationToken, maxResults) {
485 var _this = this;
486 if (continuationToken === void 0) { continuationToken = null; }
487 if (maxResults === void 0) { maxResults = Number.MAX_VALUE; }
488 var continuationToken, sendRequest, clientRequestId, retryCount = 0;
489 var xhr = new XMLHttpRequest();
490 xhr.onreadystatechange = function () {
491 if (xhr.readyState != 4)
492 return;
493 if (xhr.status == 200) {
494 var message = JSON.parse(xhr.responseText);
495 if (message[propName])
496 rows = rows.concat(message[propName]);
497 // HACK because /instances doesn't match /items
498 continuationToken = verb == 'GET' ? message.continuationToken : xhr.getResponseHeader('x-ms-continuation');
499 if (!continuationToken || rows.length >= maxResults)
500 resolve(rows);
501 else
502 _this.getDataWithContinuationBatch(token, resolve, reject, rows, url, verb, propName, continuationToken, maxResults);
503 }
504 else if (_this.retryBasedOnStatus(xhr) && retryCount < _this.maxRetryCount) {
505 retryCount++;
506 _this.retryWithDelay(retryCount, sendRequest);
507 _this.onAjaxRetry({ uri: url, method: verb, clientRequestId: clientRequestId, sessionId: _this.sessionId, statusCode: xhr.status });
508 }
509 else {
510 reject(xhr);
511 _this.onAjaxError({ uri: url, method: verb, clientRequestId: clientRequestId, sessionId: _this.sessionId });
512 }
513 };
514 sendRequest = function () {
515 xhr.open(verb, url);
516 clientRequestId = _this.setStandardHeaders(xhr, token);
517 if (verb === 'POST')
518 xhr.setRequestHeader('Content-Type', 'application/json');
519 if (continuationToken)
520 xhr.setRequestHeader('x-ms-continuation', continuationToken);
521 xhr.send(JSON.stringify({ take: 100000 }));
522 };
523 sendRequest();
524 };
525 ServerClient.prototype.retryWithDelay = function (retryNumber, method) {
526 var retryDelay = (Math.exp(retryNumber - 1) + Math.random() * 2) * 1000;
527 return setTimeout(method, retryDelay);
528 };
529 return ServerClient;
530}());
531
532export { ServerClient as S };