Best JavaScript code snippet using best
runner-stream.ts
Source:runner-stream.ts
1/*2 * Copyright (c) 2019, salesforce.com, inc.3 * All rights reserved.4 * SPDX-License-Identifier: MIT5 * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT6*/7import path from "path";8import { isInteractive as globaIsInteractive } from "@best/utils";9import chalk from "chalk";10import trimPath from "./utils/trim-path";11import countEOL from "./utils/count-eod";12import { ProxiedStream, proxyStream } from "./utils/proxy-stream";13import {14 BenchmarkRuntimeConfig,15 RunnerStream,16 BenchmarksBundle,17 BenchmarkUpdateState,18} from "@best/types";19enum State {20 QUEUED = 'QUEUED',21 RUNNING = 'RUNNING',22 DONE = 'DONE',23 ERROR = 'ERROR',24}25interface BenchmarkStatus { state: State; displayPath: string; projectName: string, progress?: BenchmarkProgress }26type AllBencharkRunnerState = Map<string, BenchmarkStatus>27interface BenchmarkProgress {28 executedIterations: number,29 estimated: number,30 runtime: number,31 avgIteration: number,32}33const STATE_ANSI = {34 RUNNING: chalk.reset.inverse.yellow.bold(` ${State.RUNNING} `),35 QUEUED: chalk.reset.inverse.gray.bold(` ${State.QUEUED} `),36 ERROR: chalk.reset.inverse.redBright.bold(` ${State.ERROR} `),37 DONE: chalk.reset.inverse.green.bold(` ${State.DONE} `),38};39const INIT_MSG = '\n Running benchmarks... \n\n';40const PROGRESS_TEXT = chalk.dim('Progress running: ');41const PROGRESS_BAR_WIDTH = 40;42const DEFAULT_TIMEOUT = 60;43function printState(state: State) {44 return STATE_ANSI[state];45}46function printDisplayName(displayPath: string, overflow: number) {47 const dirname = overflow ? trimPath(path.dirname(displayPath), overflow) : path.dirname(displayPath);48 const basename = path.basename(displayPath);49 return chalk.dim(dirname + path.sep) + chalk.bold(basename);50}51function printProjectName(projectName: string) {52 return ' ' + chalk.reset.cyan.dim(`(${projectName})`);53}54function calculateBenchmarkProgress(progress: BenchmarkUpdateState, { iterations, maxDuration, minSampleCount }: BenchmarkRuntimeConfig): BenchmarkProgress {55 const { executedIterations, executedTime } = progress;56 const avgIteration = executedTime / executedIterations;57 const runtime = parseInt((executedTime / 1000) + '', 10);58 let estimated: number;59 if (iterations) {60 estimated = Math.round(iterations * avgIteration / 1000) + 1;61 } else if (avgIteration * minSampleCount > maxDuration) {62 estimated = Math.round(minSampleCount * avgIteration / 1000) + 1;63 } else {64 estimated = maxDuration / 1000;65 }66 return {67 executedIterations,68 estimated,69 runtime,70 avgIteration,71 };72}73function printProgressBar(runTime: number, estimatedTime: number, width: number) {74 // If we are more than one second over the estimated time, highlight it.75 const renderedTime = estimatedTime && runTime >= estimatedTime + 1 ? chalk.bold.yellow(runTime + 's') : runTime + 's';76 let time = chalk.bold(`Time:`) + ` ${renderedTime}`;77 if (runTime < estimatedTime) {78 time += `, estimated ${estimatedTime}s`;79 }80 // Only show a progress bar if the test run is actually going to take some time81 if (estimatedTime > 2 && runTime < estimatedTime && width) {82 const availableWidth = Math.min(PROGRESS_BAR_WIDTH, width);83 const length = Math.min(Math.floor(runTime / estimatedTime * availableWidth), availableWidth);84 if (availableWidth >= 2) {85 time += '\n' + chalk.green('â').repeat(length) + chalk.white('â').repeat(availableWidth - length);86 }87 }88 return time;89}90export default class RunnerOutputStream implements RunnerStream {91 stdoutColumns: number;92 stdoutWrite: Function;93 isInteractive: boolean;94 _streamBuffer: string = '';95 _state: AllBencharkRunnerState;96 _innerLog: string = '';97 _scheduled: NodeJS.Timeout | null = null;98 _proxyStream: ProxiedStream;99 constructor(buildConfig: BenchmarksBundle[], stream: NodeJS.WriteStream, isInteractive?: boolean) {100 this.stdoutColumns = stream.columns || 80;101 this.stdoutWrite = stream.write.bind(stream);102 this.isInteractive = isInteractive !== undefined ? isInteractive : globaIsInteractive;103 this._state = this.initState(buildConfig);104 this._proxyStream = proxyStream(stream, this.isInteractive);105 }106 initState(buildConfigs: BenchmarksBundle[]): AllBencharkRunnerState {107 return buildConfigs.reduce((state: AllBencharkRunnerState, benchmarkBundle: BenchmarksBundle): AllBencharkRunnerState => {108 benchmarkBundle.benchmarkBuilds.forEach(({ benchmarkEntry, benchmarkSignature, projectConfig: { projectName }}) => {109 state.set(benchmarkSignature, {110 projectName,111 state: State.QUEUED,112 displayPath: benchmarkEntry,113 });114 });115 return state;116 }, new Map());117 }118 clearBufferStream() {119 let buffer = this._streamBuffer;120 const lines = countEOL(buffer);121 if (lines) {122 buffer = '\r\x1B[K\r\x1B[1A'.repeat(lines);123 }124 if (this.isInteractive) {125 // clear last line126 this.stdoutWrite('\x1b[999D\x1b[K');127 }128 this.stdoutWrite(buffer);129 this._streamBuffer = '';130 }131 writeBufferStream(str: string) {132 this._streamBuffer += str;133 this.stdoutWrite(str);134 }135 updateRunnerState(benchmarkSignature: string, state: State) {136 const stateConfig = this._state.get(benchmarkSignature);137 if (!stateConfig) {138 throw new Error(`Unknown benchmark build started (${benchmarkSignature})`);139 }140 if (stateConfig.state !== State.ERROR) {141 stateConfig.state = state;142 }143 }144 scheduleUpdate(time?: number, fn?: Function) {145 if (!this._scheduled) {146 this._scheduled = setTimeout(() => {147 fn ? fn() : this.updateStream();148 this._scheduled = null;149 }, time || DEFAULT_TIMEOUT);150 }151 }152 printBenchmarkState({ state, projectName, displayPath }: { state: State, projectName: string, displayPath: string }) {153 const columns = this.stdoutColumns;154 const overflow = columns - (state.length + projectName.length + displayPath.length + /* for padding */ 14);155 const hasOverflow = overflow < 0;156 const ansiState = printState(state);157 const ansiProjectName = printProjectName(projectName);158 const ansiDisplayname = printDisplayName(displayPath, hasOverflow ? Math.abs(overflow): 0);159 return `${ansiState} ${ansiProjectName} ${ansiDisplayname}\n`;160 }161 printProgress(progress: BenchmarkProgress, { displayPath }: BenchmarkStatus): string {162 const benchmarkName = chalk.bold.black(path.basename(displayPath));163 return [164 `\n${PROGRESS_TEXT} ${benchmarkName}`,165 chalk.bold.black('Avg iteration: ') + progress.avgIteration.toFixed(2) + 'ms',166 chalk.bold.black('Completed iterations: ') + progress.executedIterations,167 printProgressBar(progress.runtime, progress.estimated, 40)168 ].join('\n') + '\n\n';169 }170 updateStream() {171 let buffer = INIT_MSG;172 let progressStr: string = '';173 for (const benchmarkState of this._state.values()) {174 const { state, displayPath, projectName, progress } = benchmarkState;175 buffer += this.printBenchmarkState({ state, displayPath, projectName });176 if (state === State.RUNNING && progress) {177 progressStr += this.printProgress(progress, benchmarkState);178 }179 }180 const streamProxyBuffer = this._proxyStream.readBuffer();181 streamProxyBuffer ? `Buffered console logs:\n ${streamProxyBuffer}` : '';182 this.clearBufferStream();183 this.writeBufferStream(buffer + progressStr + streamProxyBuffer);184 }185 log(message: string) {186 this._innerLog = message;187 if (this.isInteractive) {188 this.scheduleUpdate();189 } else {190 this.stdoutWrite(` :: ${message}\n`);191 }192 }193 _clearTimeout() {194 if (this._scheduled) {195 clearTimeout(this._scheduled);196 this._scheduled = null;197 }198 }199 // -- Lifecycle200 onBenchmarkStart(benchmarkSignature: string) {201 this.updateRunnerState(benchmarkSignature, State.RUNNING);202 if (this.isInteractive) {203 this.scheduleUpdate();204 } else {205 const benchmarkState = this._state.get(benchmarkSignature);206 if (benchmarkState) {207 this.stdoutWrite(this.printBenchmarkState(benchmarkState));208 }209 }210 }211 onBenchmarkEnd(benchmarkSignature: string) {212 this.updateRunnerState(benchmarkSignature, State.DONE);213 this._innerLog = '';214 const benchmarkState = this._state.get(benchmarkSignature);215 if (benchmarkState) {216 if (this.isInteractive) {217 if (benchmarkState.state === State.ERROR) {218 this.updateStream();219 this.stdoutWrite('\n');220 } else {221 this.scheduleUpdate();222 }223 } else {224 this._clearTimeout();225 this.stdoutWrite(this.printBenchmarkState(benchmarkState) + '\n');226 }227 }228 }229 onBenchmarkError(benchmarkSignature: string) {230 this.updateRunnerState(benchmarkSignature, State.ERROR);231 }232 updateBenchmarkProgress(benchmarkSignature: string, updatedBenchmarkState: BenchmarkUpdateState, runtimeOpts: BenchmarkRuntimeConfig) {233 const progress = calculateBenchmarkProgress(updatedBenchmarkState, runtimeOpts);234 const benchmarkState = this._state.get(benchmarkSignature);235 benchmarkState!.progress = progress;236 const { executedIterations, avgIteration, estimated, runtime } = progress;237 const runIter = executedIterations.toString().padEnd(5, " ");238 const avgIter = `${avgIteration.toFixed(2)}ms`.padEnd(10, " ");239 const remaining = estimated - runtime;240 if (this.isInteractive) {241 this.scheduleUpdate();242 } else {243 this.scheduleUpdate(2500, () => {244 this.stdoutWrite(245 ` :: ${benchmarkState!.displayPath} > ran: ${runIter} | avg: ${avgIter} | remainingTime: ${remaining}s \n`246 );247 });248 }249 }250 init() {251 if (this.isInteractive) {252 this.updateStream();253 } else {254 this.stdoutWrite(INIT_MSG);255 }256 }257 finish() {258 this._clearTimeout();259 this._proxyStream.unproxyStream();260 if (this.isInteractive) {261 this.updateStream();262 } else {263 this.stdoutWrite('\n');264 }265 }...
remote-client.ts
Source:remote-client.ts
1/*2 * Copyright (c) 2019, salesforce.com, inc.3 * All rights reserved.4 * SPDX-License-Identifier: MIT5 * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT6 */7import { EventEmitter } from 'events';8import path from 'path';9import { Socket as ServerSocket } from 'socket.io';10import SocketIOFile from 'socket.io-file';11import { BEST_RPC } from '@best/shared';12import {13 BrowserSpec,14 BuildConfig,15 RunnerStream,16 BenchmarkRuntimeConfig,17 BenchmarkUpdateState,18 AgentState,19} from '@best/types';20import { RemoteClientConfig } from '@best/types';21import { getUploaderInstance, extractBenchmarkTarFile } from './utils/benchmark-loader';22enum RemoteClientState {23 IDLE = 'IDLE',24 REQUESTING_JOB_INFO = 'REQUESTING_JOB_INFO',25 REQUESTING_JOB_PAYLOAD = 'REQUESTING_JOB_PAYLOAD',26}27const { DISCONNECT, CONNECT_ERROR, ERROR, RECONNECT_FAILED, BENCHMARK_UPLOAD_RESPONSE } = BEST_RPC;28const RPC_METHODS = [DISCONNECT, CONNECT_ERROR, ERROR, RECONNECT_FAILED, BENCHMARK_UPLOAD_RESPONSE];29export default class RemoteClient extends EventEmitter implements RunnerStream {30 private socket: ServerSocket;31 private uploader?: SocketIOFile;32 private specs?: BrowserSpec;33 public connected: boolean;34 private pendingBenchmarksToUpload: number;35 private pendingResultsToSend: number = 0;36 private state: RemoteClientState = RemoteClientState.IDLE;37 private _requestJobSuccess: Function = function () {};38 private _requestJobError: Function = function (err: any) {39 throw new Error(err);40 };41 private debounce?: any;42 constructor(socket: ServerSocket, { specs, jobs }: RemoteClientConfig) {43 super();44 this.socket = socket;45 this.connected = this.socket.connected;46 this.specs = specs;47 this.pendingBenchmarksToUpload = jobs;48 RPC_METHODS.forEach((methodName) => this.socket.on(methodName, (this as any)[methodName].bind(this)));49 }50 // -- Socket lifecycle ------------------------------------------------------------51 [CONNECT_ERROR](reason: string) {52 console.log(`${this.getId()} - socket:connect_error`, reason);53 this.disconnectClient(reason);54 }55 [DISCONNECT](reason: string) {56 if (this.connected) {57 console.log(`${this.getId()} - socket:disconnect`, reason);58 this.disconnectClient(reason);59 }60 }61 [ERROR](reason: string) {62 console.log(`${this.getId()} - socket:error`, reason);63 this.disconnectClient(reason);64 }65 [RECONNECT_FAILED](reason: string) {66 console.log(`${this.getId()} - socket:reconnect_failed`, reason);67 this.disconnectClient(reason);68 }69 // -- Specific Best RPC Commands ------------------------------------------------------------70 async [BENCHMARK_UPLOAD_RESPONSE](benchmarkConfig: BuildConfig, emitContinuationForUpload: Function) {71 if (this.state !== RemoteClientState.REQUESTING_JOB_INFO) {72 this.disconnectClient('Client should not send jobs at this point.');73 this._requestJobError('Unexpected upload response');74 }75 console.log(76 `[AGENT_REMOTE_CLIENT] Receiving benchmark ${benchmarkConfig.benchmarkSignature} from socket ${this.socket.id}`,77 );78 const { benchmarkEntry, benchmarkName, benchmarkSignature } = benchmarkConfig;79 const uploader = this.getUploader();80 this.state = RemoteClientState.REQUESTING_JOB_PAYLOAD;81 emitContinuationForUpload(benchmarkSignature); // This is an ACK, telling the client that is ok to send the file now82 try {83 // Retrieve an uncompress the benchmark bundle84 const tarFile = await uploader.load(benchmarkEntry);85 await extractBenchmarkTarFile(tarFile);86 // Modify the benchmark bundle to point to the new files87 const uploadDir = path.dirname(tarFile);88 benchmarkConfig.benchmarkRemoteEntry = path.join(uploadDir, `${benchmarkName}.html`);89 benchmarkConfig.benchmarkRemoteFolder = uploadDir;90 console.log(91 `[AGENT_REMOTE_CLIENT] Completed upload for benchmark ${benchmarkConfig.benchmarkSignature} from socket ${this.socket.id}`,92 );93 this.state = RemoteClientState.IDLE;94 this.pendingBenchmarksToUpload -= 1;95 this.pendingResultsToSend += 1;96 this._requestJobSuccess(benchmarkConfig);97 // Notify upload updates98 this.emit(BEST_RPC.REMOTE_CLIENT_UPLOAD_COMPLETED);99 } catch (err) {100 this.disconnectClient(err as any);101 this._requestJobError(err);102 } finally {103 this.state = RemoteClientState.IDLE;104 }105 }106 // -- Private107 getUploader(): any {108 if (!this.uploader) {109 const uploader = getUploaderInstance(this.socket);110 uploader.on('stream', ({ wrote, size }: any) => {111 console.log(` :: [ARC-${this.socket.id}] loading benchmark (${wrote} / ${size})`);112 });113 this.uploader = uploader;114 }115 return this.uploader;116 }117 // -- RunnerStream methods ----------------------------------------------------------118 finish() {119 console.log(`[AGENT_REMOTE_CLIENT] finishingRunner`);120 }121 init() {122 console.log(`[AGENT_REMOTE_CLIENT] startingRunner`);123 }124 log(message: string) {125 if (this.socket.connected) {126 this.socket.emit(BEST_RPC.BENCHMARK_LOG, message);127 }128 }129 onBenchmarkEnd(benchmarkSignature: string) {130 console.log(`[AGENT_REMOTE_CLIENT] benchmarkEnd(${benchmarkSignature})`);131 if (this.socket.connected) {132 this.socket.emit(BEST_RPC.BENCHMARK_END, benchmarkSignature);133 this.emit(BEST_RPC.BENCHMARK_END, benchmarkSignature);134 clearTimeout(this.debounce);135 this.debounce = undefined;136 }137 }138 onBenchmarkError(benchmarkSignature: string) {139 if (this.socket.connected) {140 this.socket.emit(BEST_RPC.BENCHMARK_ERROR, benchmarkSignature);141 this.emit(BEST_RPC.BENCHMARK_ERROR, benchmarkSignature);142 }143 }144 onBenchmarkStart(benchmarkSignature: string) {145 if (this.socket.connected) {146 console.log(`[AGENT_REMOTE_CLIENT] benchmarkStart(${benchmarkSignature})`);147 this.socket.emit(BEST_RPC.BENCHMARK_START, benchmarkSignature);148 this.emit(BEST_RPC.BENCHMARK_START, benchmarkSignature);149 }150 }151 updateBenchmarkProgress(benchmarkSignature: string, state: BenchmarkUpdateState, opts: BenchmarkRuntimeConfig) {152 if (!this.debounce && this.socket.connected) {153 this.debounce = setTimeout(() => {154 this.debounce = undefined;155 if (this.socket.connected) {156 console.log(157 `[AGENT_REMOTE_CLIENT] benchmarkProgress(${benchmarkSignature}) | iterations: ${state.executedIterations}`,158 );159 this.socket.emit(BEST_RPC.BENCHMARK_UPDATE, benchmarkSignature, state, opts);160 this.emit(BEST_RPC.BENCHMARK_UPDATE, benchmarkSignature, state, opts);161 }162 }, 1000);163 }164 }165 // -- Imperative methods ------------------------------------------------------------166 disconnectClient(reason?: string) {167 if (this.connected) {168 this.connected = false;169 this.pendingBenchmarksToUpload = -1;170 this.socket.emit(BEST_RPC.AGENT_REJECTION, reason);171 this.socket.disconnect(true);172 this.emit(BEST_RPC.DISCONNECT, reason);173 }174 }175 getId() {176 return `REMOTE_CLIENT_${this.socket.id}`;177 }178 getPendingBenchmarks() {179 return this.pendingBenchmarksToUpload;180 }181 getSpecs() {182 return this.specs;183 }184 getState() {185 return {186 clientId: this.toString(),187 specs: this.specs,188 jobs: this.getPendingBenchmarks(),189 state: this.isIdle() ? AgentState.IDLE : AgentState.BUSY,190 };191 }192 getStatusInfo() {193 return `remining jobs: ${this.pendingBenchmarksToUpload} | specs: ${this.specs} | state: ${this.state}`;194 }195 isBusy() {196 return !this.isIdle();197 }198 isIdle() {199 return this.state === RemoteClientState.IDLE;200 }201 requestJob(): Promise<BuildConfig> {202 if (this.isIdle()) {203 return new Promise((resolve, reject) => {204 this.state = RemoteClientState.REQUESTING_JOB_INFO;205 this.socket.emit(BEST_RPC.BENCHMARK_UPLOAD_REQUEST);206 this._requestJobSuccess = resolve;207 this._requestJobError = reject;208 });209 } else {210 return Promise.reject(`RemoteClient is busy`);211 }212 }213 sendResults(results: any) {214 this.pendingResultsToSend -= 1;215 console.log(`[AGENT_REMOTE_CLIENT] Sending Results | pending: ${this.pendingResultsToSend}`);216 this.socket.emit(BEST_RPC.BENCHMARK_RESULTS, results);217 if (this.pendingBenchmarksToUpload === 0 && this.pendingResultsToSend === 0) {218 this.emit(BEST_RPC.REMOTE_CLIENT_EMPTY_QUEUE);219 }220 }221 toString() {222 return this.getId();223 }...
index.ts
Source:index.ts
1/*2 * Copyright (c) 2019, salesforce.com, inc.3 * All rights reserved.4 * SPDX-License-Identifier: MIT5 * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT6*/7import { FrozenGlobalConfig, FrozenProjectConfig, BuildConfig, BenchmarkRuntimeConfig, BenchmarkResults, BenchmarkResultsState, BenchmarkResultsSnapshot, Interruption } from '@best/types';8import AbstractRunner from '@best/runner-abstract';9import HeadlessBrowser from "./headless";10import { RunnerStream } from "@best/types";11declare var BEST: any;12const UPDATE_INTERVAL = 300;13export default class Runner extends AbstractRunner {14 async run(benchmarkBuilds: BuildConfig[], projectConfig: FrozenProjectConfig, globalConfig: FrozenGlobalConfig, runnerLogStream: RunnerStream, interruption?: Interruption): Promise<BenchmarkResultsSnapshot[]> {15 const snapshotResults: BenchmarkResultsSnapshot[] = [];16 for (const benchmarkInfo of benchmarkBuilds) {17 const { benchmarkEntry, benchmarkRemoteEntry, benchmarkSignature } = benchmarkInfo;18 const runtimeOptions = this.getRuntimeOptions(projectConfig);19 const state = this.initializeBenchmarkState();20 const { url, terminate } = await this.initializeServer(benchmarkRemoteEntry || benchmarkEntry, projectConfig);21 const browser = new HeadlessBrowser(url, projectConfig);22 try {23 await browser.initialize();24 runnerLogStream.onBenchmarkStart(benchmarkSignature);25 const { results } = await this.runIterations(benchmarkSignature, browser, state, runtimeOptions, runnerLogStream, interruption);26 const version = await browser.version();27 const environment = await this.getEnvironment({ version }, projectConfig, globalConfig);28 snapshotResults.push({ results, environment, benchmarkInfo, projectConfig });29 } catch (e) {30 runnerLogStream.onBenchmarkError(benchmarkSignature);31 throw e;32 } finally {33 runnerLogStream.onBenchmarkEnd(benchmarkSignature);34 await browser.close();35 terminate();36 }37 }38 return snapshotResults;39 }40 initializeBenchmarkState(): BenchmarkResultsState {41 return { executedTime: 0, executedIterations: 0, results: [] };42 }43 async runIterations(benchmarkSignature: string, browser: HeadlessBrowser, state: BenchmarkResultsState, runtimeOptions: BenchmarkRuntimeConfig, runnnerLogStream: RunnerStream, interruption?: Interruption): Promise<BenchmarkResultsState> {44 return runtimeOptions.iterateOnClient45 ? this.runClientIterations(benchmarkSignature, browser, state, runtimeOptions, runnnerLogStream)46 : this.runServerIterations(benchmarkSignature, browser, state, runtimeOptions, runnnerLogStream, interruption);47 }48 async runClientIterations(benchmarkSignature: string, browser: HeadlessBrowser, state: BenchmarkResultsState, runtimeOptions: BenchmarkRuntimeConfig, runnerLogStream: RunnerStream): Promise<BenchmarkResultsState> {49 // Run an iteration to estimate the time it will take50 const testResult = await this.runIteration(browser, { iterations: 1 });51 const estimatedIterationTime = testResult.aggregate;52 const start = Date.now();53 // eslint-disable-next-line lwc/no-set-interval54 const intervalId = setInterval(() => {55 const executing = Date.now() - start;56 state.executedTime = executing;57 state.executedIterations = Math.round(executing / estimatedIterationTime);58 const updatedState = { executedIterations: state.executedIterations, executedTime: state.executedTime };59 runnerLogStream.updateBenchmarkProgress(benchmarkSignature, updatedState, runtimeOptions);60 }, UPDATE_INTERVAL);61 await browser.reloadPage();62 const { results: [root,] } = await this.runIteration(browser, runtimeOptions);63 state.results.push(root);64 clearInterval(intervalId);65 return state;66 }67 async runServerIterations(benchmarkSignature: string, browser: HeadlessBrowser, state: BenchmarkResultsState, runtimeOptions: BenchmarkRuntimeConfig, runnnerLogStream: RunnerStream, interruption?: Interruption): Promise<BenchmarkResultsState> {68 if (interruption && interruption.requestedInterruption) {69 throw new Error(`Halted execution: interruption`);70 }71 if (state.executedTime < runtimeOptions.maxDuration || state.executedIterations < runtimeOptions.minSampleCount) {72 const start = Date.now();73 const benchmarkResults = await this.runIteration(browser, runtimeOptions);74 const { results: [root,] } = benchmarkResults;75 await browser.reloadPage();76 state.executedTime += Date.now() - start;77 state.executedIterations += 1;78 if (root) {79 state.results.push(root);80 }81 const updatedState = { executedIterations: state.executedIterations, executedTime: state.executedTime };82 runnnerLogStream.updateBenchmarkProgress(benchmarkSignature, updatedState, runtimeOptions);83 return this.runIterations(benchmarkSignature, browser, state, runtimeOptions, runnnerLogStream, interruption);84 }85 return state;86 }87 runIteration(browser: HeadlessBrowser, payload: any): Promise<BenchmarkResults> {88 return browser.evaluate((o: any) => BEST.runBenchmark(o), payload);89 }90 static async getBrowserSpecs() {91 return HeadlessBrowser.getSpecs();92 }...
Using AI Code Generation
1var BestSigner = require('bestsigner');2var bestSigner = new BestSigner();3bestSigner.benchmarkSignature(function(err, result) {4 if (err) {5 console.log(err);6 } else {7 console.log(result);8 }9});10var BestSigner = require('bestsigner');11var bestSigner = new BestSigner();12bestSigner.benchmarkSignature(function(err, result) {13 if (err) {14 console.log(err);15 } else {16 console.log(result);17 }18});19var BestSigner = require('bestsigner');20var bestSigner = new BestSigner();21bestSigner.benchmarkSignature(function(err, result) {22 if (err) {23 console.log(err);24 } else {25 console.log(result);26 }27});28var BestSigner = require('bestsigner');29var bestSigner = new BestSigner();30bestSigner.benchmarkSignature(function(err, result) {31 if (err) {32 console.log(err);33 } else {34 console.log(result);35 }36});37var BestSigner = require('bestsigner');38var bestSigner = new BestSigner();39bestSigner.benchmarkSignature(function(err, result) {40 if (err) {41 console.log(err);42 } else {43 console.log(result);44 }45});46var BestSigner = require('bestsigner');47var bestSigner = new BestSigner();48bestSigner.benchmarkSignature(function(err, result) {49 if (err) {50 console.log(err);51 } else {52 console.log(result);53 }54});55var BestSigner = require('bestsigner');56var bestSigner = new BestSigner();57bestSigner.benchmarkSignature(function(err, result) {58 if (err) {59 console.log(err);60 }
Using AI Code Generation
1var BestSigner = require('bestsigner');2var fs = require('fs');3var bestsigner = new BestSigner();4var message = 'Hello World!';5var algorithm = 'sha1';6var privateKey = fs.readFileSync('private.pem');7var publicKey = fs.readFileSync('public.pem');8var signature = bestsigner.sign(message, algorithm, privateKey);9var verified = bestsigner.verify(message, algorithm, signature, publicKey);10console.log('Signature: ' + signature);11console.log('Verified: ' + verified);12var benchmark = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey);13console.log('Benchmark: ' + benchmark);14var benchmark2 = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey);15console.log('Benchmark: ' + benchmark2);16var benchmark3 = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey);17console.log('Benchmark: ' + benchmark3);18var benchmark4 = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey);19console.log('Benchmark: ' + benchmark4);20var benchmark5 = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey);21console.log('Benchmark: ' + benchmark5);22var benchmark6 = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey);23console.log('Benchmark: ' + benchmark6);24var benchmark7 = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey);25console.log('Benchmark: ' + benchmark7);26var benchmark8 = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey);27console.log('Benchmark: ' + benchmark8);28var benchmark9 = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey);29console.log('Benchmark: ' + benchmark9);30var benchmark10 = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey);31console.log('Benchmark: ' + benchmark10);32var benchmark11 = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey);33console.log('Benchmark: ' + benchmark11);34var benchmark12 = bestsigner.benchmarkSignature('sha1', 1000, privateKey, publicKey
Using AI Code Generation
1var BestSigner = require('bestsigner');2var signer = new BestSigner();3signer.benchmarkSignature('test.txt', function (err, result) {4 if (err) {5 console.log(err);6 } else {7 console.log(result);8 }9});10var BestSigner = require('bestsigner');11var signer = new BestSigner();12signer.benchmarkSignature('test.txt', function (err, result) {13 if (err) {14 console.log(err);15 } else {16 console.log(result);17 }18});19var BestSigner = require('bestsigner');20var signer = new BestSigner();21signer.benchmarkVerification('test.txt', function (err, result) {22 if (err) {23 console.log(err);24 } else {25 console.log(result);26 }27});28var BestSigner = require('bestsigner');29var signer = new BestSigner();30signer.benchmarkVerification('test.txt', function (err, result) {31 if (err) {32 console.log(err);33 } else {34 console.log(result);35 }36});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!