Best JavaScript code snippet using devicefarmer-stf
transport.ts
Source:transport.ts
1import { Result, VoidResult, ok, fail, failed, error, errorCode } from './result';2import { StompitError } from './error';3import { Chunk } from './stream/chunk';4import { Reader } from './stream/reader';5import { ReadLimits, readFrame } from './frame/input';6import { WriteLimits, writeFrame } from './frame/output';7import { Frame, ProtocolVersion } from './frame/protocol';8import { FrameHeaders } from './frame/header';9import { RECEIPT_NOT_REQUESTED } from './client/receipt';10type Milliseconds = number;11/**12 * The transport interface for a STOMP session.13 *14 * Support for the Heart-beating feature is the responsibility of the transport implementation. If the feature is15 * unsupported the transport must omit the `heart-beat` header or specify a value of `0,0`.16 */17export interface Transport {18 /**19 * Returns the suggested timeout value for a receipt. This function is only useful for client sessions.20 *21 * Possible values:22 * * Milliseconds as positive integer,23 * * {@link RECEIPT_NO_TIMEOUT},24 * * {@link RECEIPT_NOT_REQUESTED}25 *26 * If a transport returns {@link RECEIPT_DEFAULT_TIMEOUT} then the client session translate this value to {@link RECEIPT_NOT_REQUESTED}27 */28 getReceiptTimeout(frame: Frame): Milliseconds;29 /**30 * Receive the next incoming frame. The return value may resolve before the frame is fully deserialized. The transport31 * may only read as far as the end of the frame header to then let the caller control reading the frame body.32 *33 * The STOMP session implementation must not call this function before the previous frame's body has been fully read.34 */35 readFrame(protocolVersion: ProtocolVersion): Promise<Result<Frame, StompitError>>;36 /**37 * Send the next outgoing frame. The return value resolves once the frame has been fully serialised and sent for38 * transmission.39 */40 writeFrame(frame: Frame, protocolVersion: ProtocolVersion): Promise<StompitError | undefined>;41 /**42 * Close the connection.43 */44 close(): Promise<void>;45}46/**47 * A base class for a transport's configuration class. This is useful for transport implementations that use the48 * {@link readFrame} and {@link writeFrame} functions.49 */50export interface TransportLimits {51 operationTimeout: Milliseconds;52 /**53 * The desired minimum rate of incoming data from the connection peer. The actual expected rate is negotiated with54 * the connection peer as the session is establishing. If no data is received during the interval then the connection55 * is dead.56 */57 desiredReadRate: Milliseconds;58 /**59 * The desired minimum rate of outgoing data to the connection peer. See {@link desiredReadRate} for intended behaviour,60 * but applies to outgoing data.61 */62 desiredWriteRate: Milliseconds;63 /**64 * The delay tolerance value adds time to the unresponsive state threshold.65 */66 delayTolerance: Milliseconds;67 /**68 * Read frame size limits69 */70 readLimits: ReadLimits;71 /**72 * Write frame size limits73 */74 writeLimits: WriteLimits;75}76export const limitDefaults: TransportLimits = {77 operationTimeout: 3000,78 desiredReadRate: 3000,79 desiredWriteRate: 0,80 delayTolerance: 3000,81 readLimits: {82 maxHeaderLines: 128,83 maxLineLength: 8000,84 maxBodyLength: Infinity,85 maxBodyChunkLength: 1638486 },87 writeLimits: {88 bufferSize: 1638489 }90};91/**92 * Used by the transport to perform byte-level communication with the peer93 */94export interface TransportStream extends AsyncIterable<Chunk> {95 /**96 * The running total amount of bytes received97 */98 readonly bytesRead: number;99 /**100 * The running total amount of bytes sent101 */102 readonly bytesWritten: number;103 /**104 * Send data105 *106 * @param chunk Byte array107 */108 write(chunk: Chunk): Promise<VoidResult>;109 /**110 * Signal the end of writing operations111 */112 writeEnd(): Promise<VoidResult>;113 /**114 * Close the stream and release the associated resources115 */116 close(): void;117}118const ERROR_SESSION_TIMEOUT = 'session timeout';119/**120 * A transport implementation that serialises frames in the standard format and observes the standard protocol.121 */122export class StandardTransport implements Transport {123 private stream: TransportStream;124 private streamError: StompitError | undefined;125 private reader: Reader;126 private writing: boolean;127 private limits: TransportLimits;128 private readRateTimer: NodeJS.Timeout | undefined;129 private writeRateTimer: NodeJS.Timeout | undefined;130 private sessionStarted: boolean;131 private sessionClosed: boolean;132 /**133 * @param stream The underlying stream used to transmit frames134 * @param limits Time and size limits to place on the transport135 * @param sessionStarted Pass true value if the session is already established136 */137 public constructor(stream: TransportStream, limits: TransportLimits, sessionStarted = false) {138 this.stream = stream;139 this.limits = limits;140 this.reader = new Reader(stream[Symbol.asyncIterator]());141 this.writing = false;142 this.sessionStarted = sessionStarted;143 this.sessionClosed = false;144 }145 /**146 * @inheritdoc147 */148 public getReceiptTimeout(frame: Frame) {149 if ('DISCONNECT' === frame.command || 'UNSUBSCRIBE' === frame.command) {150 return this.limits.operationTimeout;151 }152 return RECEIPT_NOT_REQUESTED;153 }154 /**155 * @inheritdoc156 */157 public async readFrame(protocolVersion: ProtocolVersion) {158 if (this.sessionClosed) {159 return errorCode('TransportFailure', 'session closed');160 }161 const params = {162 ...this.limits.readLimits,163 protocolVersion,164 ignoreLeadingEmptyLines: this.sessionStarted165 };166 const result = await readFrame(this.reader, params);167 if (failed(result)) {168 return this.failStream(error(result));169 }170 if (!this.sessionStarted) {171 const frame = result.value;172 if ('CONNECTED' === frame.command) {173 this.sessionStarted = true;174 const heartbeat = this.startHeartBeat(frame.headers);175 if (failed(heartbeat)) {176 return this.failStream(error(heartbeat));177 }178 }179 }180 return result;181 }182 /**183 * @inheritdoc184 */185 public async writeFrame(frame: Frame, protocolVersion: ProtocolVersion) {186 if (this.sessionClosed) {187 return new StompitError('TransportFailure', 'session closed');188 }189 const params = {190 ...this.limits.writeLimits,191 protocolVersion192 };193 switch (frame.command) {194 case 'CONNECT': {195 if (this.sessionStarted) {196 return this.failStream(new StompitError('ProtocolViolation', 'client sent multiple CONNECT frames')).error;197 }198 if (frame.headers.has('heart-beat')) {199 frame.headers = frame.headers.filter(([name, _value]) => 'heart-beat' === name);200 }201 const writeRate = this.limits.desiredWriteRate;202 const readRate = this.limits.desiredReadRate;203 if (writeRate > 0 || readRate > 0) {204 frame.headers = FrameHeaders.merge(frame.headers, new FrameHeaders([205 ['heart-beat', [206 Math.max(0, writeRate).toFixed(),207 Math.max(0, readRate).toFixed()208 ].join(',')]209 ]));210 }211 break;212 }213 case 'CONNECTED': {214 if (this.sessionStarted) {215 return this.failStream(new StompitError('ProtocolViolation', 'server sent multiple CONNECTED frames')).error;216 }217 this.sessionStarted = true;218 const heartbeat = this.startHeartBeat(frame.headers, false);219 if (failed(heartbeat)) {220 return this.failStream(error(heartbeat)).error;221 }222 const [sendRate, recvRate] = heartbeat.value;223 frame.headers = FrameHeaders.merge(frame.headers, new FrameHeaders([224 ['heart-beat', `${sendRate},${recvRate}`]225 ]));226 break;227 }228 }229 this.writing = true;230 const result = await writeFrame(frame, this.stream, params);231 this.writing = false;232 if ('CONNECTED' === frame.command) {233 this.startHeartBeat(frame.headers, true);234 }235 return result;236 }237 private failStream(error: StompitError) {238 if (this.streamError) {239 return fail(this.streamError);240 }241 this.streamError = error;242 this.close();243 return fail(error);244 }245 /**246 * @inheritdoc247 */248 public close() {249 if (this.sessionClosed) {250 return Promise.resolve();251 }252 this.sessionClosed = true;253 if (this.readRateTimer) {254 clearInterval(this.readRateTimer);255 this.readRateTimer = undefined;256 }257 if (this.writeRateTimer) {258 clearInterval(this.writeRateTimer);259 this.writeRateTimer = undefined;260 }261 return (async () => {262 if (!this.streamError) {263 const error = await this.stream.writeEnd();264 if (error) {265 this.streamError = error;266 }267 }268 this.stream.close();269 })();270 }271 private startHeartBeat(headers: FrameHeaders, monitor = true): Result<[number, number], StompitError> {272 const heartBeatString = headers.get('heart-beat');273 if (undefined === heartBeatString) {274 return ok([0, 0]);275 }276 const heartBeatTokens = heartBeatString.match(/^(\d+),(\d+)$/);277 if (null === heartBeatTokens) {278 return errorCode('ProtocolViolation', 'invalid heart-beat header');279 }280 const remoteWriteRate = parseInt(heartBeatTokens[1], 10);281 const remoteReadRate = parseInt(heartBeatTokens[2], 10);282 const localWriteRate = this.limits.desiredWriteRate;283 const localReadRate = this.limits.desiredReadRate;284 const enableWriteRate = 0 !== remoteReadRate && 0 !== localWriteRate;285 const writeRate = enableWriteRate ? Math.max(localWriteRate, remoteReadRate) : 0;286 if (writeRate > 0 && monitor) {287 this.monitorWriteRate(writeRate);288 }289 const enableReadRate = 0 !== remoteWriteRate && 0 !== localReadRate;290 const readRate = enableReadRate ? Math.max(localReadRate, remoteWriteRate) : 0;291 if (readRate > 0 && monitor) {292 this.monitorReadRate(readRate + this.limits.delayTolerance);293 }294 return ok([writeRate, readRate]);295 }296 private monitorReadRate(milliseconds: number) {297 let lastBytesRead = this.stream.bytesRead;298 this.readRateTimer = setInterval(() => {299 const bytesRead = this.stream.bytesRead;300 if (bytesRead === lastBytesRead) {301 this.failStream(new StompitError('TransportFailure', ERROR_SESSION_TIMEOUT));302 return;303 }304 lastBytesRead = bytesRead;305 }, milliseconds);306 }307 private monitorWriteRate(milliseconds: number) {308 let lastBytesWritten = this.stream.bytesWritten;309 const LF = Buffer.from('\n', 'ascii');310 this.writeRateTimer = setInterval(() => {311 let bytesWritten = this.stream.bytesWritten;312 if (bytesWritten === lastBytesWritten && !this.writing) {313 this.stream.write(LF);314 bytesWritten += 1;315 }316 lastBytesWritten = bytesWritten;317 }, milliseconds);318 }...
limits.ts
Source:limits.ts
...12import { createFailError, ToolingLog, CiStatsMetric } from '@kbn/dev-utils';13import { OptimizerConfig, Limits } from './optimizer';14const DEFAULT_BUDGET = 15000;15const diff = <T>(a: T[], b: T[]): T[] => a.filter((item) => !b.includes(item));16export function readLimits(path: string): Limits {17 let yaml;18 try {19 yaml = Fs.readFileSync(path, 'utf8');20 } catch (error) {21 if (error.code !== 'ENOENT') {22 throw error;23 }24 }25 return yaml ? Yaml.safeLoad(yaml) : {};26}27export function validateLimitsForAllBundles(28 log: ToolingLog,29 config: OptimizerConfig,30 limitsPath: string31) {32 const limitBundleIds = Object.keys(readLimits(limitsPath).pageLoadAssetSize || {});33 const configBundleIds = config.bundles.map((b) => b.id);34 const missingBundleIds = diff(configBundleIds, limitBundleIds);35 const extraBundleIds = diff(limitBundleIds, configBundleIds);36 const issues = [];37 if (missingBundleIds.length) {38 issues.push(`missing: ${missingBundleIds.join(', ')}`);39 }40 if (extraBundleIds.length) {41 issues.push(`extra: ${extraBundleIds.join(', ')}`);42 }43 if (issues.length) {44 throw createFailError(45 dedent`46 The limits defined in packages/kbn-optimizer/limits.yml are outdated. Please update47 this file with a limit (in bytes) for every production bundle.48 ${issues.join('\n ')}49 To automatically update the limits file locally run:50 node scripts/build_kibana_platform_plugins.js --update-limits51 To validate your changes locally run:52 node scripts/build_kibana_platform_plugins.js --validate-limits53 ` + '\n'54 );55 }56 log.success('limits.yml file valid');57}58interface UpdateBundleLimitsOptions {59 log: ToolingLog;60 config: OptimizerConfig;61 dropMissing: boolean;62 limitsPath: string;63}64export function updateBundleLimits({65 log,66 config,67 dropMissing,68 limitsPath,69}: UpdateBundleLimitsOptions) {70 const limits = readLimits(limitsPath);71 const metrics: CiStatsMetric[] = config.filteredBundles72 .map((bundle) =>73 JSON.parse(Fs.readFileSync(Path.resolve(bundle.outputDir, 'metrics.json'), 'utf-8'))74 )75 .flat()76 .sort((a, b) => a.id.localeCompare(b.id));77 const pageLoadAssetSize: NonNullable<Limits['pageLoadAssetSize']> = dropMissing78 ? {}79 : limits.pageLoadAssetSize ?? {};80 for (const metric of metrics) {81 if (metric.group === 'page load bundle size') {82 const existingLimit = limits.pageLoadAssetSize?.[metric.id];83 pageLoadAssetSize[metric.id] =84 existingLimit != null && existingLimit >= metric.value...
Using AI Code Generation
1var DeviceLimits = require('devicefarmer-stf-device-limits');2var deviceLimits = new DeviceLimits();3deviceLimits.readLimits(function(err, limits) {4 if (err) {5 console.log('Error: ' + err);6 } else {7 console.log('limits: ' + JSON.stringify(limits));8 }9});10var DeviceLimits = require('devicefarmer-stf-device-limits');11var deviceLimits = new DeviceLimits();12deviceLimits.readLimits(function(err, limits) {13 if (err) {14 console.log('Error: ' + err);15 } else {16 console.log('limits: ' + JSON.stringify(limits));17 }18});19var DeviceLimits = require('devicefarmer-stf-device-limits');20var deviceLimits = new DeviceLimits();21deviceLimits.readLimits(function(err, limits) {22 if (err) {23 console.log('Error: ' + err);24 } else {25 console.log('limits: ' + JSON.stringify(limits));26 }27});28var DeviceLimits = require('devicefarmer-stf-device-limits');29var deviceLimits = new DeviceLimits();30deviceLimits.readLimits(function(err, limits) {31 if (err) {32 console.log('Error: ' + err);33 } else {34 console.log('limits: ' + JSON.stringify(limits));35 }36});37var DeviceLimits = require('devicefarmer-stf-device-limits');38var deviceLimits = new DeviceLimits();39deviceLimits.readLimits(function(err, limits) {40 if (err) {41 console.log('Error: ' + err);42 } else {43 console.log('limits: ' + JSON.stringify(limits));44 }45});46var DeviceLimits = require('devicefarmer-stf-device-limits');47var deviceLimits = new DeviceLimits();48deviceLimits.readLimits(function(err, limits) {
Using AI Code Generation
1var deviceLimits = require('devicefarmer-stf-device-limits');2var limits = deviceLimits.readLimits();3console.log(limits);4var deviceLimits = require('devicefarmer-stf-device-limits');5var limits = deviceLimits.readLimitsSync();6console.log(limits);
Using AI Code Generation
1var limits = require('devicefarmer-stf-limits');2limits.readLimits(function(err, limits){3 console.log(limits);4});5var limits = require('devicefarmer-stf-limits');6limits.readLimits(function(err, limits){7 console.log(limits);8});9var limits = require('devicefarmer-stf-limits');10limits.readLimits(function(err, limits){11 console.log(limits);12});13var limits = require('devicefarmer-stf-limits');14limits.readLimits(function(err, limits){15 console.log(limits);16});17var limits = require('devicefarmer-stf-limits');18limits.readLimits(function(err, limits){19 console.log(limits);20});21var limits = require('devicefarmer-stf-limits');22limits.readLimits(function(err, limits){23 console.log(limits);24});25var limits = require('devicefarmer-stf-limits');26limits.readLimits(function(err, limits){27 console.log(limits);28});29var limits = require('devicefarmer-stf-limits');30limits.readLimits(function(err, limits){31 console.log(limits);32});33var limits = require('devicefarmer-stf-limits');34limits.readLimits(function(err, limits){35 console.log(limits);36});37var limits = require('devicefarmer-stf-limits');38limits.readLimits(function(err, limits){39 console.log(limits);40});
Using AI Code Generation
1var limits = require('devicefarmer-stf-limits');2var readLimits = limits.readLimits;3var limits = readLimits('/path/to/limits.json');4console.log(limits);5{6 "limits": {7 "cpu": {8 },9 "memory": {10 }11 }12}13readLimits(filePath)
Using AI Code Generation
1var device = require('devicefarmer-stf-device');2device.readLimits(function(err, data) {3 console.log('err: ' + err);4 console.log('data: ' + JSON.stringify(data));5});6var device = require('devicefarmer-stf-device');7device.readLimits(function(err, data) {8 console.log('err: ' + err);9 console.log('data: ' + JSON.stringify(data));10});11var device = require('devicefarmer-stf-device');12device.readLimits(function(err, data) {13 console.log('err: ' + err);14 console.log('data: ' + JSON.stringify(data));15});16var device = require('devicefarmer-stf-device');17device.readLimits(function(err, data) {18 console.log('err: ' + err);19 console.log('data: ' + JSON.stringify(data));20});21var device = require('devicefarmer-stf-device');22device.readLimits(function(err, data) {23 console.log('err: ' + err);24 console.log('data: ' + JSON.stringify(data));25});26var device = require('devicefarmer-stf-device');27device.readLimits(function(err, data) {28 console.log('err: ' + err);29 console.log('data: ' + JSON.stringify(data));30});31var device = require('devicefarmer-stf-device');32device.readLimits(function(err, data) {33 console.log('err: ' + err);34 console.log('data: ' + JSON.stringify(data));35});36var device = require('devicefarmer-stf-device');37device.readLimits(function(err, data) {38 console.log('err: ' + err);
Using AI Code Generation
1const devicefarmer = require('devicefarmer-stf-device');2device.readLimits().then(function (limits) {3 console.log('limits are', limits);4}).catch(function (err) {5 console.log('error is', err);6});7const devicefarmer = require('devicefarmer-stf-device');8device.readLimits().then(function (limits) {9 console.log('limits are', limits);10}).catch(function (err) {11 console.log('error is', err);12});13const devicefarmer = require('devicefarmer-stf-device');14device.setLimits({cpu: '10', memory: '100'}).then(function (limits) {15 console.log('limits are', limits);16}).catch(function (err) {17 console.log('error is', err);18});19const devicefarmer = require('devicefarmer-stf-device');20device.setLimits({cpu: '10', memory: '100'}).then(function (limits) {21 console.log('limits are', limits);22}).catch(function (err) {23 console.log('error is', err);24});25const devicefarmer = require('devicefarmer-stf-device');26device.setLimits({cpu: '10', memory: '100'}).then(function (limits) {27 console.log('limits are', limits);28}).catch(function (err) {29 console.log('error is', err);30});31const devicefarmer = require('devicefarmer-stf-device');
Using AI Code Generation
1var readLimits = require('devicefarmer-stf').readLimits;2var device = {3};4readLimits(device, function (err, limits) {5 if (err) {6 console.log('Error in reading limits', err);7 } else {8 console.log('Limits are', limits);9 }10});11var setLimits = require('devicefarmer-stf').setLimits;12var device = {13};14var limits = {15};16setLimits(device, limits, function (err, limits) {17 if (err) {18 console.log('Error in setting limits', err);19 } else {20 console.log('Limits are', limits);21 }22});23var getLimits = require('devicefarmer-stf').getLimits;24var device = {25};26getLimits(device, function (err, limits) {27 if (err) {28 console.log('Error in getting limits', err);29 } else {30 console.log('Limits are', limits);31 }32});33var clearLimits = require('devicefarmer-stf').clearLimits;34var device = {35};36clearLimits(device, function (err, limits) {37 if (err) {38 console.log('Error in clearing limits', err);39 } else {40 console.log('Limits are', limits);41 }42});43var getLog = require('devicefarmer-stf').getLog;44var device = {45};46getLog(device, function (
Using AI Code Generation
1var limits = require('devicefarmer-stf-limits');2var limit = limits.readLimits();3console.log(limit);4{ 5}6var limits = require('devicefarmer-stf-limits');7limits.setLimits(30, 50, 50, 50);8var limits = require('devicefarmer-stf-limits');9limits.setLimits(30, 50, 50, 50, function(err, result){10 if(err){11 console.log(err);12 }13 else{14 console.log(result);15 }16});17{ 18}19var limits = require('devicefarmer-stf-limits');20limits.setLimits(30, 50, 50, 50, function(err, result){21 if(err){22 console.log(err);23 }24 else{25 console.log(result);26 }27});28{ 29}30var limits = require('devicefarmer-stf-limits');31limits.setLimits(30, 50, 50, 50, function(err, result){32 if(err){33 console.log(err);34 }35 else{36 console.log(result);37 }38});39{ 40}41var limits = require('devicefarmer-stf-limits');42limits.setLimits(30, 50, 50, 50
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!!