Best JavaScript code snippet using best
runner-remote.ts
Source:runner-remote.ts
...77 RPC_METHODS.forEach((methodName) => this.socket.on(methodName, (this as any)[methodName].bind(this)));78 }79 // -- Socket lifecycle ----------------------------------------------------------------------80 [CONNECT]() {81 log_rpc(`socket:connect`);82 }83 [CONNECT_ERROR]() {84 log_rpc('socket:error');85 this._triggerBenchmarkError(`Unable to connect to agent "${this.uri}" (socket:connect_error)`);86 }87 [DISCONNECT]() {88 log_rpc('socket:disconnect');89 this._triggerBenchmarkError('socket:disconnect');90 }91 [ERROR]() {92 log_rpc('socket:error');93 this._triggerBenchmarkError('socket:reconnect_failed');94 }95 [RECONNECT_FAILED]() {96 log_rpc('reconnect_failed');97 this._triggerBenchmarkError('socket:reconnect_failed');98 }99 // -- Specific Best RPC Commands ------------------------------------------------------------100 [AGENT_REJECTION](reason: string) {101 log_rpc(`agent_rejection: ${AGENT_REJECTION}`);102 this._triggerBenchmarkError(reason);103 }104 [BENCHMARK_UPLOAD_REQUEST]() {105 const benchmarkConfig = this.benchmarkBuilds.shift();106 if (!benchmarkConfig) {107 return this._triggerBenchmarkError('Agent is requesting more jobs than specified');108 }109 if (this.uploadingBenchmark) {110 return this._triggerBenchmarkError('Already uploading a benchmark');111 }112 log_rpc(`${BENCHMARK_UPLOAD_REQUEST} - Sending: ${benchmarkConfig.benchmarkSignature}`);113 this.socket.emit(BEST_RPC.BENCHMARK_UPLOAD_RESPONSE, benchmarkConfig, async (benchmarkSignature: string) => {114 const { benchmarkName, benchmarkEntry, benchmarkRemoteEntry } = benchmarkConfig;115 const bundleDirname = path.dirname(benchmarkRemoteEntry || benchmarkEntry);116 const tarBundle = path.resolve(bundleDirname, `${benchmarkName}.tgz`);117 try {118 await createTarBundle(bundleDirname, benchmarkName);119 const uploader = await this._getUploaderInstance();120 uploader.upload(tarBundle);121 } catch (err) {122 return this._triggerBenchmarkError(err);123 }124 });125 }126 [BENCHMARK_RESULTS](results: BenchmarkResultsSnapshot[]) {127 this.benchmarkResults.push(...results);128 this.pendingBenchmarks -= 1;129 log_rpc(`${BENCHMARK_UPLOAD_REQUEST} - Received results, pending ${this.pendingBenchmarks}`);130 if (this.pendingBenchmarks === 0) {131 if (this.benchmarkBuilds.length === 0) {132 this._triggerBenchmarkSucess();133 } else {134 this._triggerBenchmarkError('Results missmatch: Agent has sent more jobs that benchmarks consumed...');135 }136 }137 }138 // -- Logger methods (must be side effect free) --------------------------------------------------------------------139 [BENCHMARK_START](benchmarkSignature: string) {140 this.runnerLogStream.onBenchmarkStart(benchmarkSignature);141 }142 [BENCHMARK_UPDATE](benchmarkSignature: string, state: BenchmarkResultsState, runtimeOpts: BenchmarkRuntimeConfig) {143 this.runnerLogStream.updateBenchmarkProgress(benchmarkSignature, state, runtimeOpts);144 }145 [BENCHMARK_END](benchmarkSignature: string) {146 this.runnerLogStream.onBenchmarkEnd(benchmarkSignature);147 }148 [BENCHMARK_ERROR](benchmarkSignature: string) {149 this.runnerLogStream.onBenchmarkError(benchmarkSignature);150 }151 [BENCHMARK_LOG](msg: string) {152 this.runnerLogStream.log(msg);153 }154 // -- Private --------------------------------------------------------------------155 _getUploaderInstance(): Promise<SocketIOFile> {156 if (this.uploader) {157 return Promise.resolve(this.uploader);158 }159 return new Promise((resolve, reject) => {160 const uploader = new SocketIOFile(this.socket);161 const cancelRejection = setTimeout(() => {162 reject('[RUNNER_REMOTE] uploader:error | Unable to stablish connection for upload benchmarks');163 }, 10000);164 uploader.on('start', () => {165 log_rpc('uploader:start');166 this.uploadingBenchmark = true;167 });168 uploader.on('error', (err) => {169 log_rpc('uploader:error');170 this._triggerBenchmarkError(err);171 });172 uploader.on('complete', () => {173 log_rpc('uploader:complete');174 this.uploadingBenchmark = false;175 });176 uploader.on('ready', () => {177 log_rpc('uploader:ready');178 this.uploader = uploader;179 clearTimeout(cancelRejection);180 resolve(uploader);181 });182 });183 }184 _triggerBenchmarkSucess() {185 if (this.running) {186 this.running = false;187 this.socket.disconnect();188 this._onBenchmarksRunSuccess(this.benchmarkResults);189 this._onBenchmarksRunSuccess = THROW_FUNCTION; // To catch side-effects and race conditions190 }191 }...
rpc.js
Source:rpc.js
1/*jshint esversion: 6 */2const Util = require("./common-util");3const Core = require("./commands/core");4const Admin = require("./commands/admin-rpc");5const Pinning = require("./commands/pin-rpc");6const Quota = require("./commands/quota");7const Block = require("./commands/block");8const Metadata = require("./commands/metadata");9const Channel = require("./commands/channel");10const Upload = require("./commands/upload");11const HK = require("./hk-util");12var RPC = module.exports;13const UNAUTHENTICATED_CALLS = {14 GET_FILE_SIZE: Pinning.getFileSize,15 GET_MULTIPLE_FILE_SIZE: Pinning.getMultipleFileSize,16 GET_DELETED_PADS: Pinning.getDeletedPads,17 IS_CHANNEL_PINNED: Pinning.isChannelPinned, // FIXME drop this RPC18 IS_NEW_CHANNEL: Channel.isNewChannel,19 WRITE_PRIVATE_MESSAGE: Channel.writePrivateMessage,20 GET_METADATA: Metadata.getMetadata,21};22var isUnauthenticateMessage = function (msg) {23 return msg && msg.length === 2 && typeof(UNAUTHENTICATED_CALLS[msg[0]]) === 'function';24};25var handleUnauthenticatedMessage = function (Env, msg, respond, Server, netfluxId) {26 Env.Log.silly('LOG_RPC', msg[0]);27 var method = UNAUTHENTICATED_CALLS[msg[0]];28 method(Env, msg[1], function (err, value) {29 if (err) {30 Env.WARN(err, msg[1]);31 return void respond(err);32 }33 respond(err, [null, value, null]);34 }, Server, netfluxId);35};36const AUTHENTICATED_USER_TARGETED = {37 RESET: Pinning.resetUserPins,38 PIN: Pinning.pinChannel,39 UNPIN: Pinning.unpinChannel,40 CLEAR_OWNED_CHANNEL: Channel.clearOwnedChannel,41 REMOVE_OWNED_CHANNEL: Channel.removeOwnedChannel,42 TRIM_HISTORY: Channel.trimHistory,43 UPLOAD_STATUS: Upload.status,44 UPLOAD: Upload.upload,45 UPLOAD_COMPLETE: Upload.complete,46 UPLOAD_CANCEL: Upload.cancel,47 OWNED_UPLOAD_COMPLETE: Upload.complete_owned,48 WRITE_LOGIN_BLOCK: Block.writeLoginBlock,49 REMOVE_LOGIN_BLOCK: Block.removeLoginBlock,50 ADMIN: Admin.command,51 SET_METADATA: Metadata.setMetadata,52};53const AUTHENTICATED_USER_SCOPED = {54 GET_HASH: Pinning.getHash,55 GET_TOTAL_SIZE: Pinning.getTotalSize,56 UPDATE_LIMITS: Quota.getUpdatedLimit,57 GET_LIMIT: Pinning.getLimit,58 EXPIRE_SESSION: Core.expireSessionAsync,59 REMOVE_PINS: Pinning.removePins,60 TRIM_PINS: Pinning.trimPins,61 COOKIE: Core.haveACookie,62};63var isAuthenticatedCall = function (call) {64 if (call === 'UPLOAD') { return false; }65 return typeof(AUTHENTICATED_USER_TARGETED[call] || AUTHENTICATED_USER_SCOPED[call]) === 'function';66};67var handleAuthenticatedMessage = function (Env, unsafeKey, msg, respond, Server) {68 /* If you have gotten this far, you have signed the message with the69 public key which you provided.70 */71 var safeKey = Util.escapeKeyCharacters(unsafeKey);72 var Respond = function (e, value) {73 var session = Env.Sessions[safeKey];74 var token = session? session.tokens.slice(-1)[0]: '';75 var cookie = Core.makeCookie(token).join('|');76 respond(e ? String(e): e, [cookie].concat(typeof(value) !== 'undefined' ?value: []));77 };78 msg.shift();79 // discard validated cookie from message80 if (!msg.length) {81 return void Respond('INVALID_MSG');82 }83 var TYPE = msg[0];84 Env.Log.silly('LOG_RPC', TYPE);85 if (typeof(AUTHENTICATED_USER_TARGETED[TYPE]) === 'function') {86 return void AUTHENTICATED_USER_TARGETED[TYPE](Env, safeKey, msg[1], function (e, value) {87 Env.WARN(e, value);88 return void Respond(e, value);89 }, Server);90 }91 if (typeof(AUTHENTICATED_USER_SCOPED[TYPE]) === 'function') {92 return void AUTHENTICATED_USER_SCOPED[TYPE](Env, safeKey, function (e, value) {93 if (e) {94 Env.WARN(e, safeKey);95 return void Respond(e);96 }97 Respond(e, value);98 });99 }100 return void Respond('UNSUPPORTED_RPC_CALL', msg);101};102var rpc = function (Env, Server, userId, data, respond) {103 if (!Array.isArray(data)) {104 Env.Log.debug('INVALID_ARG_FORMET', data);105 return void respond('INVALID_ARG_FORMAT');106 }107 if (!data.length) {108 return void respond("INSUFFICIENT_ARGS");109 } else if (data.length !== 1) {110 Env.Log.debug('UNEXPECTED_ARGUMENTS_LENGTH', data);111 }112 var msg = data[0].slice(0);113 if (!Array.isArray(msg)) {114 return void respond('INVALID_ARG_FORMAT');115 }116 if (isUnauthenticateMessage(msg)) {117 return handleUnauthenticatedMessage(Env, msg, respond, Server, userId);118 }119 var signature = msg.shift();120 var publicKey = msg.shift();121 // make sure a user object is initialized in the cookie jar122 var session;123 if (publicKey) {124 session = Core.getSession(Env.Sessions, publicKey);125 } else {126 Env.Log.debug("NO_PUBLIC_KEY_PROVIDED", publicKey);127 }128 var cookie = msg[0];129 if (!Core.isValidCookie(Env.Sessions, publicKey, cookie)) {130 // no cookie is fine if the RPC is to get a cookie131 if (msg[1] !== 'COOKIE') {132 return void respond('NO_COOKIE');133 }134 }135 var serialized = JSON.stringify(msg);136 if (!(serialized && typeof(publicKey) === 'string')) {137 return void respond('INVALID_MESSAGE_OR_PUBLIC_KEY');138 }139 var command = msg[1];140 if (command === 'UPLOAD') {141 // UPLOAD is a special case that skips signature validation142 // intentional fallthrough behaviour143 return void handleAuthenticatedMessage(Env, publicKey, msg, respond, Server);144 }145 if (isAuthenticatedCall(command)) {146 // check the signature on the message147 // refuse the command if it doesn't validate148 return void Env.checkSignature(serialized, signature, publicKey, function (err) {149 if (err) {150 return void respond("INVALID_SIGNATURE_OR_PUBLIC_KEY");151 }152 HK.authenticateNetfluxSession(Env, userId, publicKey);153 return void handleAuthenticatedMessage(Env, publicKey, msg, respond, Server);154 });155 }156 Env.Log.warn('INVALID_RPC_CALL', command);157 return void respond("INVALID_RPC_CALL");158};159RPC.create = function (Env, cb) {160 var Sessions = Env.Sessions;161 var updateLimitDaily = function () {162 Quota.updateCachedLimits(Env, function (e) {163 if (e) {164 Env.WARN('limitUpdate', e);165 }166 });167 };168 Quota.applyCustomLimits(Env);169 updateLimitDaily();170 Env.intervals.dailyLimitUpdate = setInterval(updateLimitDaily, 24*3600*1000);171 // expire old sessions once per minute172 Env.intervals.sessionExpirationInterval = setInterval(function () {173 Core.expireSessions(Sessions);174 }, Core.SESSION_EXPIRATION_TIME);175 cb(void 0, function (Server, userId, data, respond) {176 try {177 return rpc(Env, Server, userId, data, respond);178 } catch (e) {179 console.log("Error from RPC with data " + JSON.stringify(data));180 console.log(e.stack);181 }182 });...
Using AI Code Generation
1var log = require('./log_rpc').log;2log("Hello from test4.js");3var log = require('./log_rpc').log;4log("Hello from test5.js");5var log = require('./log_rpc').log;6log("Hello from test6.js");7var log = require('./log_rpc').log;8log("Hello from test7.js");9var log = require('./log_rpc').log;10log("Hello from test8.js");11var log = require('./log_rpc').log;12log("Hello from test9.js");13var log = require('./log_rpc').log;14log("Hello from test10.js");15var log = require('./log_rpc').log;16log("Hello from test11.js");17var log = require('./log_rpc').log;18log("Hello from test12.js");19var log = require('./log_rpc').log;20log("Hello from test13.js");21var log = require('./log_rpc').log;22log("Hello from test14.js");23var log = require('./log_rpc').log;24log("Hello from test15.js");25var log = require('./log_rpc').log;26log("Hello from test16.js");27var log = require('./log_rpc').log;28log("Hello from test17.js");
Using AI Code Generation
1var BestLog = require('bestlog');2var log = new BestLog('test4');3log.log_rpc('test4.js', 'test4.js', 'test4.js', 'test4.js');4var BestLog = require('bestlog');5var log = new BestLog('test5');6log.log_rpc('test5.js', 'test5.js', 'test5.js', 'test5.js');7var BestLog = require('bestlog');8var log = new BestLog('test6');9log.log_rpc('test6.js', 'test6.js', 'test6.js', 'test6.js');10var BestLog = require('bestlog');11var log = new BestLog('test7');12log.log_rpc('test7.js', 'test7.js', 'test7.js', 'test7.js');13var BestLog = require('bestlog');14var log = new BestLog('test8');15log.log_rpc('test8.js', 'test8.js', 'test8.js', 'test8.js');16var BestLog = require('bestlog');17var log = new BestLog('test9');18log.log_rpc('test9.js', 'test9.js', 'test9.js', 'test9.js');19var BestLog = require('bestlog');20var log = new BestLog('test10');21log.log_rpc('test10.js', 'test10.js', 'test10.js', 'test10.js');22var BestLog = require('bestlog');23var log = new BestLog('test11');24log.log_rpc('test11.js', 'test11.js', 'test11.js', 'test11.js');25var BestLog = require('bestlog');26var log = new BestLog('test
Using AI Code Generation
1var bestLog = require('./bestlog.js');2var log = new bestLog("test4");3log.log_rpc("test4.js","test4","test4", "test4");4var bestLog = require('./bestlog.js');5var log = new bestLog("test5");6log.log_rpc("test5.js","test5","test5", "test5");7var bestLog = require('./bestlog.js');8var log = new bestLog("test6");9log.log_rpc("test6.js","test6","test6", "test6");10var bestLog = require('./bestlog.js');11var log = new bestLog("test7");12log.log_rpc("test7.js","test7","test7", "test7");13var bestLog = require('./bestlog.js');14var log = new bestLog("test8");15log.log_rpc("test8.js","test8","test8", "test8");16var bestLog = require('./bestlog.js');17var log = new bestLog("test9");18log.log_rpc("test9.js","test9","test9", "test9");19var bestLog = require('./bestlog.js');20var log = new bestLog("test10");21log.log_rpc("test10.js","test10","test10", "test10");22var bestLog = require('./bestlog.js');23var log = new bestLog("test11");24log.log_rpc("test
Using AI Code Generation
1var BestRPC = require('./BestRPC.js');2var brpc = new BestRPC();3brpc.log_rpc('This is a test message from test4.js');4brpc.get_rpc(function (data) {5 console.log('Data from server: ' + data);6});7var BestRPC = function () {8 this.log_rpc = function (msg) {9 var http = require('http');10 var options = {11 };12 http.get(options, function (res) {13 }).on('error', function (e) {14 console.log("Got error: " + e.message);15 });16 };17 this.get_rpc = function (callback) {18 var http = require('http');19 var options = {20 };21 http.get(options, function (res) {22 var data = '';23 res.on('data', function (chunk) {24 data += chunk;25 });26 res.on('end', function () {27 callback(data);28 });29 }).on('error', function (e) {30 console.log("Got error: " + e.message);31 });32 };33};34module.exports = BestRPC;35var BestRPC = function () {36 this.log_rpc = function (msg) {37 var http = require('http');
Using AI Code Generation
1var BestRPC = require('BestRPC');2var rpc = new BestRPC();3rpc.log_rpc("test4.js: calling remote function");4rpc.call("test4.js: remote function", function(err, result) {5 if (err) {6 console.log("test4.js: error calling remote function");7 console.log(err);8 } else {9 console.log("test4.js: result of remote function");10 console.log(result);11 }12});
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!!