UNPKG

@opentap/runner-client

Version:

This is the web client for the OpenTAP Runner.

316 lines (315 loc) 15.4 kB
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 __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); } }; import { JSONCodec, nanos } from 'nats.ws'; import { Image, MetadataUpdatedEvent, RepositoryPackageReference, RunnerStatus, Session, } from './DTOs'; import { BaseClient } from './BaseClient'; import { getSubjectParts } from './utils'; export class RunnerClient extends BaseClient { constructor(baseSubject, options) { super(baseSubject, options); // 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: (testPlanRepositoryReference, timeout) => { return this.request('StartDefaultSession', testPlanRepositoryReference !== null && testPlanRepositoryReference !== void 0 ? testPlanRepositoryReference : null, { timeout }) .then(sessionJs => 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: (testPlanReference, imageOverride, timeout) => { const defaultSessionRequest = { testPlanReference: testPlanReference !== null && testPlanReference !== void 0 ? testPlanReference : null, imageOverride: imageOverride !== null && imageOverride !== void 0 ? imageOverride : null, }; return this.request('StartDefaultSessionOverrideImage', defaultSessionRequest, { timeout }) .then(sessionJs => 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: () => { return this.request('GetDefaultImage') .then(imageJs => 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: (image) => { return this.request('SetDefaultImage', image) .then(imageJs => 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: () => { return this.request('GetDefaultSettings') .then(repositoryPackageReferenceJs => repositoryPackageReferenceJs ? 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: (repositoryPackageReference) => { return this.request('SetDefaultSettings', repositoryPackageReference).then(this.success()).catch(this.error()); }, /* Saves the default settings in the repository. */ saveDefaultSettings: (defaultSettings) => { return this.request('SaveDefaultSettingsInRepository', defaultSettings).then(this.success()).catch(this.error()); }, }; this.runnerId = getSubjectParts(baseSubject).runnerId; } /** * Get the logs zip file from the server. * @returns {{Promise<Uint8Array>}} * @description The logs zip file contains the logs from the server. */ getLogsZip() { 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>}} */ getImage(imageId) { return (imageId === null || imageId === void 0 ? void 0 : imageId.length) > 0 ? this.request('GetImage', imageId) .then(imageJs => Image.fromJS(imageJs)) .then(this.success()) .catch(this.error()) : Promise.reject('imageId is not defined'); } /** * Get all created images * @returns {{Promise<Image[]>}} */ getImages() { return this.request('GetImages') .then(imageArrayJs => imageArrayJs.map(imageJs => Image.fromJS(imageJs))) .then(this.success()) .catch(this.error()); } /** * Get all sessions * @returns {{Promise<Session[]>}} */ getSessions() { return this.request('GetSessions') .then(sessionArrayJs => sessionArrayJs.map(sessionJs => Session.fromJS(sessionJs))) .then(this.success()) .catch(this.error()); } setSession(session) { return this.request('SetSession', session) .then(sessionJs => 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>}} */ resolveImage(images, timeout) { return (images === null || images === void 0 ? void 0 : images.length) > 0 ? this.request('ResolveImage', images, { timeout }) .then(imageJs => 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>}} */ resolveImageDryRun(images, timeout) { return (images === null || images === void 0 ? void 0 : images.length) > 0 ? this.request('ResolveImageDryRun', images, { timeout: timeout }) .then(imageJs => 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>}} */ shutdownSession(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>}} */ startSession() { return this.request('StartSession') .then(sessionJs => Session.fromJS(sessionJs)) .then(this.success()) .catch(this.error()); } /** * Get the session manager image. * @returns {{Promise<Image>}} */ getSessionManagerImage() { return this.request('GetSessionManagerImage') .then(imageJs => Image.fromJS(imageJs)) .then(this.success()) .catch(this.error()); } /** * Start a session based on an image. * @param imageId * @returns {{Promise<Session>}} */ startImageSession(image) { return image ? this.request('StartImageSession', image) .then(sessionJs => 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>}} */ updateRunner(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 */ connectMetadataUpdatedEvents(handler, options) { return this.subscribe('Events.MetadataUpdated', Object.assign(Object.assign({}, options), { callback(error, encodedMessage) { if (error) { handler(undefined, error); return; } try { const jsonCodec = JSONCodec(); const metadataEventJson = jsonCodec.decode(encodedMessage === null || encodedMessage === void 0 ? void 0 : encodedMessage.data); const metadataEvent = 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 */ connectMetric(metricInfo, inactiveThresholdMilliseconds, maxBatchSize, handler) { return this.createJetStreamConsumer('Metrics', `M.${metricInfo.subjectPostfix}`, { domain: this.runnerId, }, { inactive_threshold: nanos(inactiveThresholdMilliseconds) }).then(consumer => { let isCloseInitiated = false; const deleteConsumer = consumer.delete.bind(consumer); consumer.delete = () => { isCloseInitiated = true; return deleteConsumer(); }; // Async function here so the loop starts without blocking returning a consumer (() => __awaiter(this, void 0, void 0, function* () { var _a, e_1, _b, _c; // Get the consumer info to determine the number of pending messages const consumerInfo = yield consumer.info(); let numberPending = consumerInfo.num_pending; while (!isCloseInitiated) { try { // We want to define the batch size based on how many message we will consume in the next fetch const arraySize = Math.max(Math.min(maxBatchSize, numberPending), 1); // Create the object with preallocated arrays for better performance const metricData = { encodedMetrics: new Array(arraySize), timestamps: new Array(arraySize), }; // Fetch the messages const messages = yield consumer.fetch({ max_messages: arraySize }); // for await of doesn't return the index, so we need to keep track of it let index = 0; try { for (var _d = true, messages_1 = (e_1 = void 0, __asyncValues(messages)), messages_1_1; messages_1_1 = yield messages_1.next(), _a = messages_1_1.done, !_a; _d = true) { _c = messages_1_1.value; _d = false; const message = _c; // Store the message data and timestamp metricData.encodedMetrics[index] = message.data; metricData.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) { break; } // Increment the index index++; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = messages_1.return)) yield _b.call(messages_1); } finally { if (e_1) throw e_1.error; } } (() => __awaiter(this, void 0, void 0, function* () { return handler(metricData); }))(); } catch (_e) { break; } } }))(); return consumer; }); } /** * Gets the runner status * @return Promise */ getStatus() { return this.request('Status') .then(status => RunnerStatus.fromJS(status)) .then(this.success()) .catch(this.error()); } }