@opentap/runner-client
Version:
This is the web client for the OpenTAP Runner.
422 lines (421 loc) • 22.9 kB
JavaScript
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RunnerClient = void 0;
var nats_ws_1 = require("nats.ws");
var DTOs_1 = require("./DTOs");
var BaseClient_1 = require("./BaseClient");
var utils_1 = require("./utils");
var RunnerClient = /** @class */ (function (_super) {
__extends(RunnerClient, _super);
function RunnerClient(baseSubject, options) {
var _this = _super.call(this, baseSubject, options) || this;
// Contains the endpoints for Defaults in the runner plugin.
_this.default = {
/* Create a Session based on the dependencies of a TestPlan. Returned
Session will have referenced TestPlan pre-loaded. The Session will be
created with the base image and base settings. */
startSession: function (testPlanRepositoryReference, timeout) {
return _this.request('StartDefaultSession', testPlanRepositoryReference !== null && testPlanRepositoryReference !== void 0 ? testPlanRepositoryReference : null, { timeout: timeout })
.then(function (sessionJs) { return DTOs_1.Session.fromJS(sessionJs); })
.then(_this.success())
.catch(_this.error());
},
/* Create a Session based on the dependencies of a TestPlan, but with
an image which packages overrides the default and testplan dependencies.
Returned Session will have referenced TestPlan pre-loaded. The Session
will be created with the base image and base settings.
*/
startSessionWithOverriddenImage: function (testPlanReference, imageOverride, timeout) {
var defaultSessionRequest = {
testPlanReference: testPlanReference !== null && testPlanReference !== void 0 ? testPlanReference : null,
imageOverride: imageOverride !== null && imageOverride !== void 0 ? imageOverride : null,
};
return _this.request('StartDefaultSessionOverrideImage', defaultSessionRequest, { timeout: timeout })
.then(function (sessionJs) { return DTOs_1.Session.fromJS(sessionJs); })
.then(_this.success())
.catch(_this.error());
},
/* Gets the base image. The base image is always included in the image
creation process */
getImage: function () {
return _this.request('GetDefaultImage')
.then(function (imageJs) { return DTOs_1.Image.fromJS(imageJs); })
.then(_this.success())
.catch(_this.error());
},
/* Sets the base image. The specified image is resolved and set as the
base image */
setImage: function (image) {
return _this.request('SetDefaultImage', image)
.then(function (imageJs) { return DTOs_1.Image.fromJS(imageJs); })
.then(_this.success())
.catch(_this.error());
},
/* Gets the base settings package. The base settings is always included
in the image creation process and loaded into the created session */
getSettings: function () {
return _this.request('GetDefaultSettings')
.then(function (repositoryPackageReferenceJs) {
return repositoryPackageReferenceJs ? DTOs_1.RepositoryPackageReference.fromJS(repositoryPackageReferenceJs) : undefined;
})
.then(_this.success())
.catch(_this.error());
},
/* Sets the base settings package. The base settings is always included
in the image creation process and loaded into the created session */
setSettings: function (repositoryPackageReference) {
return _this.request('SetDefaultSettings', repositoryPackageReference).then(_this.success()).catch(_this.error());
},
/* Saves the default settings in the repository. */
saveDefaultSettings: function (defaultSettings) {
return _this.request('SaveDefaultSettingsInRepository', defaultSettings).then(_this.success()).catch(_this.error());
},
};
_this.runnerId = (0, utils_1.getSubjectParts)(baseSubject).runnerId;
return _this;
}
/**
* Get the logs zip file from the server.
* @returns {{Promise<Uint8Array>}}
* @description The logs zip file contains the logs from the server.
*/
RunnerClient.prototype.getLogsZip = function () {
return this.request('LogsZip', undefined, { rawResponse: true }).then(this.success()).catch(this.error());
};
/**
* Get the created image with the specified ID.
* @param imageId
* @returns {{Promise<Image>}}
*/
RunnerClient.prototype.getImage = function (imageId) {
return (imageId === null || imageId === void 0 ? void 0 : imageId.length) > 0
? this.request('GetImage', imageId)
.then(function (imageJs) { return DTOs_1.Image.fromJS(imageJs); })
.then(this.success())
.catch(this.error())
: Promise.reject('imageId is not defined');
};
/**
* Get all created images
* @returns {{Promise<Image[]>}}
*/
RunnerClient.prototype.getImages = function () {
return this.request('GetImages')
.then(function (imageArrayJs) { return imageArrayJs.map(function (imageJs) { return DTOs_1.Image.fromJS(imageJs); }); })
.then(this.success())
.catch(this.error());
};
/**
* Get all sessions
* @returns {{Promise<Session[]>}}
*/
RunnerClient.prototype.getSessions = function () {
return this.request('GetSessions')
.then(function (sessionArrayJs) { return sessionArrayJs.map(function (sessionJs) { return DTOs_1.Session.fromJS(sessionJs); }); })
.then(this.success())
.catch(this.error());
};
RunnerClient.prototype.setSession = function (session) {
return this.request('SetSession', session)
.then(function (sessionJs) { return DTOs_1.Session.fromJS(sessionJs); })
.then(this.success())
.catch(this.error());
};
/**
* Create a OpenTAP package configuration image from a list image inputs consisting of user specified packages and repositories.
* @param {Image[]} images List of images
* @param {number} timeout Optional timeout in milliseconds
* @returns {{Promise<Image>}}
*/
RunnerClient.prototype.resolveImage = function (images, timeout) {
return (images === null || images === void 0 ? void 0 : images.length) > 0
? this.request('ResolveImage', images, { timeout: timeout })
.then(function (imageJs) { return DTOs_1.Image.fromJS(imageJs); })
.then(this.success())
.catch(this.error())
: Promise.reject('images list is not defined or is empty');
};
/**
* Dry runs to resolve an image from a list of images. Dry run means that no packages will be downloaded.
* @param {Image[]} images List of images
* @param {number} timeout Optional timeout in milliseconds
* @returns {{Promise<Image>}}
*/
RunnerClient.prototype.resolveImageDryRun = function (images, timeout) {
return (images === null || images === void 0 ? void 0 : images.length) > 0
? this.request('ResolveImageDryRun', images, { timeout: timeout })
.then(function (imageJs) { return DTOs_1.Image.fromJS(imageJs); })
.then(this.success())
.catch(this.error())
: Promise.reject('images list is not defined or is empty');
};
/**
* Shut down a session
* @param sessionId the ID of the session to shut down
* @returns {{Promise<void>}}
*/
RunnerClient.prototype.shutdownSession = function (sessionId) {
return (sessionId === null || sessionId === void 0 ? void 0 : sessionId.length) > 0
? this.request('ShutdownSession', sessionId).then(this.success()).catch(this.error())
: Promise.reject('sessionId is not defined');
};
/**
* Start a session
* @returns {{Promise<Session>}}
*/
RunnerClient.prototype.startSession = function () {
return this.request('StartSession')
.then(function (sessionJs) { return DTOs_1.Session.fromJS(sessionJs); })
.then(this.success())
.catch(this.error());
};
/**
* Get the session manager image.
* @returns {{Promise<Image>}}
*/
RunnerClient.prototype.getSessionManagerImage = function () {
return this.request('GetSessionManagerImage')
.then(function (imageJs) { return DTOs_1.Image.fromJS(imageJs); })
.then(this.success())
.catch(this.error());
};
/**
* Start a session based on an image.
* @param imageId
* @returns {{Promise<Session>}}
*/
RunnerClient.prototype.startImageSession = function (image) {
return image
? this.request('StartImageSession', image)
.then(function (sessionJs) { return DTOs_1.Session.fromJS(sessionJs); })
.then(this.success())
.catch(this.error())
: Promise.reject('image is not defined');
};
/**
* Update the `Runner` plugin to the given version
* @param runnerUpdateRequest
* @returns {{Promise<void>}}
*/
RunnerClient.prototype.updateRunner = function (runnerUpdateRequest) {
return this.request('UpdateRunner', runnerUpdateRequest).then(this.success()).catch(this.error());
};
/**
* Subscribe to the MetadataUpdated event
* @param {(event:MetadataUpdatedEvent|undefined,err:NatsError|Error|null)=>void} handler
* @param {SubscriptionOptions} options?
* @returns Subscription
*/
RunnerClient.prototype.connectMetadataUpdatedEvents = function (handler, options) {
return this.subscribe('Events.MetadataUpdated', __assign(__assign({}, options), { callback: function (error, encodedMessage) {
if (error) {
handler(undefined, error);
return;
}
try {
var jsonCodec = (0, nats_ws_1.JSONCodec)();
var metadataEventJson = jsonCodec.decode(encodedMessage === null || encodedMessage === void 0 ? void 0 : encodedMessage.data);
var metadataEvent = DTOs_1.MetadataUpdatedEvent.fromJS(metadataEventJson);
handler(metadataEvent, error);
}
catch (error) {
handler(undefined, error);
}
} }));
};
/**
* Connect to metrics published for the given SessionMetricInfo from the idle session
* @param {ISessionMetricInfo} metricInfo
* @param {(result:MetricValue|undefined,err:NatsError|Error|null)=>void} handler
* @param {SubscriptionOptions} options?
* @returns Subscription
*/
RunnerClient.prototype.connectMetric = function (metricInfo, inactiveThresholdMilliseconds, maxBatchSize, handler) {
var _this = this;
return this.createJetStreamConsumer('Metrics', "M.".concat(metricInfo.subjectPostfix), {
domain: this.runnerId,
}, { inactive_threshold: (0, nats_ws_1.nanos)(inactiveThresholdMilliseconds) }).then(function (consumer) {
var isCloseInitiated = false;
var deleteConsumer = consumer.delete.bind(consumer);
consumer.delete = function () {
isCloseInitiated = true;
return deleteConsumer();
};
// Async function here so the loop starts without blocking returning a consumer
(function () { return __awaiter(_this, void 0, void 0, function () {
var consumerInfo, numberPending, _loop_1, state_1;
var _this = this;
var _a, e_1, _b, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0: return [4 /*yield*/, consumer.info()];
case 1:
consumerInfo = _d.sent();
numberPending = consumerInfo.num_pending;
_loop_1 = function () {
var arraySize, metricData_1, messages, index, _e, messages_1, messages_1_1, message, e_1_1, _f;
return __generator(this, function (_g) {
switch (_g.label) {
case 0:
_g.trys.push([0, 14, , 15]);
arraySize = Math.max(Math.min(maxBatchSize, numberPending), 1);
metricData_1 = {
encodedMetrics: new Array(arraySize),
timestamps: new Array(arraySize),
};
return [4 /*yield*/, consumer.fetch({ max_messages: arraySize })];
case 1:
messages = _g.sent();
index = 0;
_g.label = 2;
case 2:
_g.trys.push([2, 7, 8, 13]);
_e = true, messages_1 = (e_1 = void 0, __asyncValues(messages));
_g.label = 3;
case 3: return [4 /*yield*/, messages_1.next()];
case 4:
if (!(messages_1_1 = _g.sent(), _a = messages_1_1.done, !_a)) return [3 /*break*/, 6];
_c = messages_1_1.value;
_e = false;
message = _c;
// Store the message data and timestamp
metricData_1.encodedMetrics[index] = message.data;
metricData_1.timestamps[index] = message.info.timestampNanos;
numberPending = message.info.pending;
// If we are at the last message or there are no more pending messages, call the handler
if (index === arraySize - 1 || message.info.pending === 0) {
return [3 /*break*/, 6];
}
// Increment the index
index++;
_g.label = 5;
case 5:
_e = true;
return [3 /*break*/, 3];
case 6: return [3 /*break*/, 13];
case 7:
e_1_1 = _g.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 13];
case 8:
_g.trys.push([8, , 11, 12]);
if (!(!_e && !_a && (_b = messages_1.return))) return [3 /*break*/, 10];
return [4 /*yield*/, _b.call(messages_1)];
case 9:
_g.sent();
_g.label = 10;
case 10: return [3 /*break*/, 12];
case 11:
if (e_1) throw e_1.error;
return [7 /*endfinally*/];
case 12: return [7 /*endfinally*/];
case 13:
(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, handler(metricData_1)];
}); }); })();
return [3 /*break*/, 15];
case 14:
_f = _g.sent();
return [2 /*return*/, "break"];
case 15: return [2 /*return*/];
}
});
};
_d.label = 2;
case 2:
if (!!isCloseInitiated) return [3 /*break*/, 4];
return [5 /*yield**/, _loop_1()];
case 3:
state_1 = _d.sent();
if (state_1 === "break")
return [3 /*break*/, 4];
return [3 /*break*/, 2];
case 4: return [2 /*return*/];
}
});
}); })();
return consumer;
});
};
/**
* Gets the runner status
* @return Promise
*/
RunnerClient.prototype.getStatus = function () {
return this.request('Status')
.then(function (status) { return DTOs_1.RunnerStatus.fromJS(status); })
.then(this.success())
.catch(this.error());
};
return RunnerClient;
}(BaseClient_1.BaseClient));
exports.RunnerClient = RunnerClient;