Best JavaScript code snippet using playwright-internal
app.js
Source:app.js
1const net = require('net');2const util = require('util');3const fs = require('fs');4const Redis = require('ioredis');5let opts = {6 hosts: [ // sentinels7 { host: '192.168.112.2', port: 26379 },8 { host: '192.168.112.3', port: 26379 },9 { host: '192.168.112.4', port: 26379 }10 ],11 quorum_num: 2, // number of nodes to consider quorum12 quorum_event_window: 5000, // in ms13 precheck: true, // retrieve & update master before main run14 precheck_masters: ['mred1'], // master names15 notify: {16 socket: '/run/haproxy.sock', // writable haproxy socket17 map_file: '/etc/haproxy/maps/redmaster', // map file18 map_command: (master, ip) => {19 return `${opts.notify.map_file} ${master} ${ip}`;20 },21 show_command: () => {22 return `show map ${opts.notify.map_file}\n`;23 },24 kill_command: (master, ip) => {25 return `shutdown sessions server b:${master}:${ip}/s:${master}:${ip}\n`;26 }27 },28 redis_opts: {29 connectTimeout: 2000,30 retryStrategy: (times) => { // fixed conn retry interval, in ms31 return 5000;32 },33 maxRetriesPerRequest: null, // retry indefinitely34 },35};36// ---------------------------------------------------------------------------37class Deferred {38 constructor() {39 this.promise = new Promise((resolve, reject) => {40 this.reject = reject41 this.resolve = resolve42 })43 this.then = this.promise.then.bind(this.promise);44 this.catch = this.promise.catch.bind(this.promise);45 }46}47class Serial {48 constructor() {49 this.tasks = null;50 }51 singularity (fn) {52 let deferral = new Deferred();53 let done = (data) => {54 if (this.tasks.length === 0)55 this.tasks = null;56 deferral.resolve(data);57 if (!!this.tasks && this.tasks.length > 0) {58 this.tasks.shift()();59 }60 }61 if (!this.tasks) {62 this.tasks = []63 fn().then(done);64 } else {65 this.tasks.push(() => { fn().then(done) });66 }67 return deferral.promise;68 }69}70// ---------------------------------------------------------------------------71const serlock = new Serial();72let quorum_data = {};73let pclients;74function socksend(cmd) {75 return new Promise((resolve, reject) => {76 let sock = net.connect(opts.notify.socket, () => {77 console.log(`>>>> sending to ${opts.notify.socket}: ${cmd}`.trim());78 sock.write(cmd);79 });80 sock.on('data', (data) => {81 // sock.end();82 const reply = data.toString().trim();83 console.log(`<<<< reply: "${reply}"`);84 resolve(reply);85 });86 sock.on('error', err => {87 reject(err);88 })89 });90}91function update_haproxy_map(master, newip, newport) {92 const map_cmd = opts.notify.map_command(master, newip);93 return socksend(`set map ${map_cmd}\n`)94 .then(reply => {95 if (reply.match('entry not found'))96 return socksend(`add map ${map_cmd}\n`)97 else98 return reply99 })100 .then(reply => {101 if (reply.match('^$'))102 return newip103 else104 return new Error('didnt get proper reply');105 });106}107function kill_haproxy_sessions(master, oldip) {108 const cmd = opts.notify.kill_command(master, oldip);109 return socksend(cmd)110 .then(reply => {111 if (reply.match('^$'))112 return true113 else114 throw new Error("ERR didn't get proper reply when killing sessions");115 });116}117function save_haproxy_map() {118 return new Promise((resolve, reject) => {119 return socksend(opts.notify.show_command())120 .then((data) => {121 let mapdata = data.trim().replace(/^\w+?\s(\w+)\s(\w+)\b/mg, '$1 $2');122 fs.writeFile(opts.notify.map_file, mapdata, (err) => {123 if (err) return reject(err);124 console.log(`Map file ${opts.notify.map_file} updated.`);125 resolve();126 });127 });128 });129}130function quorum_cb (master, oldip, oldport, newip, newport) {131 console.log(`>>>> quorum cb called for ${master} > ${newip}`);132 return serlock.singularity(() => {133 return update_haproxy_map(master, newip, newport)134 .then(() => {135 const saveit = () =>136 save_haproxy_map()137 .catch(err => {138 console.log(`ERR saving maps to file: ${err}`);139 return err;140 });141 if (oldip) // this is a master transition142 return kill_haproxy_sessions(master, oldip).then(saveit)143 else // this is a preliminary master check144 return saveit();145 })146 .then(() => newip)147 .catch(err => {148 console.log(`ERR sending master update via haproxy socket: ${err}`);149 return err;150 });151 });152}153function init_red_instance(red_args) {154 const host = red_args['host'];155 const redis = new Redis(Object.assign(red_args, opts.redis_opts));156 redis.subscribe('+switch-master', (err, count) => {157 if (err)158 console.log("ERROR subscribing: " + err)159 else160 console.log(`[${host}] subscribed to ${count} channel`);161 });162 redis.on('message', (chan, msg) => {163 // switch-master <master name> <oldip> <oldport> <newip> <newport>164 let [master, oldip, oldport, newip, newport] = msg.split(" ");165 console.log(`[${host}] said master ${master} moved ${oldip}:${oldport} >>> ${newip}:${newport}`);166 let qdata = (quorum_data[master] = quorum_data[master] || {'voters': new Set()});167 // console.log('qdata: ' + util.inspect(qdata, {depth: 1, colors: true}));168 let voting_cleanup = () => {169 clearTimeout(qdata['timer']);170 delete qdata['timer'];171 qdata['voters'] = new Set();172 if (qdata['elected'])173 console.log(`<${master}> ------- Successfully closing election window for ${qdata['ip']} -------------\n`);174 else175 console.log(`<${master}> ---------- NO quorum inside election window for ${qdata['ip']} -------------\n`);176 delete qdata['elected'];177 }178 let check_vote = () => {179 if (qdata['voters'].add(host).size === opts.quorum_num) {180 qdata['last_elected'] = newip;181 qdata['elected'] = true;182 console.log(`<${master}> ------------------------- Elected ${qdata['ip']} --------------------------`);183 return quorum_cb(master, oldip, oldport, newip, newport);184 }185 }186 if (qdata['last_elected'] === newip)187 return console.log(`[${host}]<${master}> ignoring vote for already elected master **${newip}**`);188 if (!qdata['timer']) { // first event189 console.log(`[${host}]<${master}> First event: electing ${newip} ------------------------`);190 qdata['ip'] = newip;191 qdata['timer'] = setTimeout(voting_cleanup, opts.quorum_event_window);192 } else { // inside quorum window193 console.log(`[${host}]<${master}> Followup event electing **${newip}**`);194 if (qdata['ip'] !== newip)195 return console.log(`[${host}]<${master}> ALERT: wanted to elect a different master **${newip}**, ignoring...`);196 }197 check_vote();198 });199 redis.on('ready', () => {200 console.log(`[${redis.stream.remoteAddress}:${redis.stream.remotePort}] READY`);201 });202 redis.on('close', () => {203 if (redis.stream.remoteAddress) // not a reconnect event204 console.log(`[${redis.stream.remoteAddress}:${redis.stream.remotePort}] conn CLOSED`);205 });206 redis.on('error', (err, data) => {207 let pref = redis.stream.remoteAddress ? `${redis.stream.remoteAddress}:${redis.stream.remotePort}` : `(${host})NOTCONN`;208 console.log(`[${pref}] ERR: ${err}`);209 });210 return redis;211}212//213function main() {214 if (pclients) return;215 pclients = opts.hosts.map(init_red_instance);216 process.on('SIGINT', function() {217 console.log("Caught interrupt signal, exiting.");218 for (const master in quorum_data){219 if (quorum_data[master]['timer'])220 clearTimeout(quorum_data[master]['timer']);221 }222 pclients.map((r) => { r.disconnect() });223 });224}225//226function get_current_master() {227 console.log('Preliminary master retrieval starting...')228 const preclient = new Redis(Object.assign({enableOfflineQueue: false, connectTimeout: 5000, reconnectOnError: false, retryStrategy: false}, opts.hosts[0]));229 preclient.on('ready', () => {230 Promise.all(opts.precheck_masters.map((master) => {231 return preclient.sendCommand(new Redis.Command('sentinel', ['master', master], {replyEncoding: 'utf8'}))232 .then((data) => {233 let res = data.reduce((acc, cur, i) => {if (i % 2) acc[data[i-1]] = data[i]; return acc;}, {}) // array to object234 console.log(`<${master}> got master IP: ${res.ip}`);235 return quorum_cb(master, null, null, res.ip, res.port);236 })237 .catch((err) => {238 console.log(`<${master}> error getting master: ${err}`);239 return err;240 });241 })).then((res) => {242 console.log('Completed preliminary master resolution.', 'The outcome was:' + util.inspect(res));243 preclient.disconnect();244 main();245 });246 })247 preclient.on('error', (err) => {248 console.log(`Got an error when trying to retrieve master info, proceeding nevertheless. ${err}`);249 main()250 })251}252//253if (opts.precheck)254 get_current_master()255else...
client.js
Source:client.js
1const ws = require("ws");2const HeartCheck = require('./heartCheck');3const SockSend = require('./sockSend');4const Watch = require('./watch');5const cmdAPIModule = require('./cmd'); // é»è®¤çcmd6const path = 'ws://127.0.0.1:10001'; // æ¬æº7class ClientSocket{8 // åå§åçcmdAPI ä¸éè¦æ¯æ¬¡å®ä¾åé½å¼å
¥cmdAPI9 static cmdAPIInit = {};10 constructor(config = {}) {11 const {12 url = path, // æå¡ç«¯å°å13 restartMax = 3, // é»è®¤æå¤éå¯æ¬¡æ°ä¸º314 reconnectTime = 2 * 1000, // é»è®¤2séè¿ä¸æ¬¡15 cmdAPI = {}, // æ¥å£æ件16 wsConfig = {}, // websocketé
ç½®17 heartTimeout = 10 * 1000, // å¿è·³æ£æµæ¶é´ 10s18 } = config;19 this.url = url;20 this.cmdAPI = {21 ...cmdAPIModule,22 ...ClientSocket.cmdAPIInit,23 ...cmdAPI24 };25 // nodeç¯å¢26 if(typeof(WebSocket) === "undefined") {27 this.wsConfig = {28 handshakeTimeout: 3000, // è¿æ¥è¶
æ¶29 ...wsConfig30 };31 }else{32 //æµè§å¨ç¯å¢33 this.wsConfig = typeof(wsConfig) !== "string" ? null : wsConfig;34 }35 this.heartTimeout = heartTimeout;36 this.reconnectTime = reconnectTime;37 this.restartMax = restartMax;38 this.lockReconnect = false; // æ¯å¦æ£å¨éè¿39 this.timeout = null; // éè¿å®æ¶å¨40 this.sockSend = new SockSend(this.cmdAPI); // 订é
å½¢å¼ä¼ è¾æ¶æ¯41 this.socket = {};42 this.restartNum = 0; // å½åéå¯æ¬¡æ°43 this.socketIsClose = false; // æ¯å¦å·²ç»å®å
¨å
³é44 // æä¸ä¸ªå±æ§Socket.readyStateï¼45 this.socketReadyState = {46 0: 'websocketè¿æ¥å°æªå»ºç«, æ æ³è¿æ¥å°æå¡ç«¯',47 1: 'websocketè¿æ¥å·²å»ºç«ï¼å¯ä»¥è¿è¡éä¿¡',48 2: 'websocketè¿æ¥æ£å¨è¿è¡å
³é',49 3: 'websocketè¿æ¥å·²ç»å
³éæè
è¿æ¥ä¸è½æå¼'50 }51 }52 /**53 * çå¾
wsçå¯å¨ é»è®¤çå¾
3次54 * @params {number} restartMaxNow 该次请æ±æå¤éå¯æ¬¡æ°55 * ä¼ é该å¼çæ
åµä¸º56 * 1.å·²ç»å®ä¾å并è¿è¡è¿createSocket57 * 2.readyState ä¸ä¸º1ï¼wsä¸å¨è¿è¡ä¸ï¼58 * 3.éçå¾
éå¯æå¤restartMaxNow次59 * **/60 waitCreate(restartMaxNow = 3) {61 // å¦æä¼ érestartMax ä¸ç¨å¨æthis.restartMax62 return new Promise((rs)=>{63 // å¦æå·²ç»å¯å¨æå64 if(this.socket.readyState === 1) {65 return rs(this.socket.readyState);66 }else if(this.socketIsClose) {67 // wså·²ç»å®å
¨å
³éæ æ³éå¯ å°è¯éå¯68 this.socketIsClose = false;69 this.websocketStart();70 }71 // å½åéå¯æ¬¡æ°72 let restartNum = 0;73 let watchRestartNum = new Watch(this, 'restartNum');74 watchRestartNum.init((newsValue, oldValue)=>{75 if(newsValue - 1 === oldValue) {76 restartNum++;77 console.log('çå¾
éå¯' + restartNum);78 // çå¾
restartMaxNow 次åè¿æªå¯å¨æå79 if(restartNum >= restartMaxNow) {80 rs(this.socket.readyState);81 watchRestartNum.clear();82 }83 }else{84 // å¯å¨æåå restartNum ä¼å为085 rs(this.socket.readyState);86 watchRestartNum.clear();87 }88 })89 })90 }91 createSocket() {92 return new Promise((rs)=>{93 // æåå¯å¨wsåè°ç¨è¯¥åè°å½æ°æè¶
è¿è¿æ¥æ¬¡æ°åè¿åSocketç¶æ94 this.waitSocketState = (readyState) =>{95 rs(readyState);96 }97 this.websocketStart();98 });99 }100 // å¯å¨websocket101 websocketStart() {102 try {103 // nodeç¯å¢104 if(typeof(WebSocket) === "undefined"){105 this.socket = new ws(this.url, this.wsConfig);106 }else{107 // æµè§å¨ç¯å¢108 this.socket = new WebSocket(this.url, this.wsConfig);109 }110 this.websocketInit();111 } catch (e) {112 console.log('catch', e);113 this.websocketReconnect();114 }115 }116 // 对wséè¿117 websocketReconnect() {118 // æ¯å¦æ£å¨æ§è¡éè¿ æè
å·²ç»å®å
¨å
³éåä¸åéå¯119 if (this.lockReconnect || this.socketIsClose) {120 return;121 }else if(this.restartNum >= this.restartMax && this.restartMax > 0) {122 // æå¤éå¯restartMax次(å¦ærestartMax <= 0ä¸ç¨èèéå¯æ¬¡æ°)123 this.socketIsClose = true;124 this.waitSocketState(this.socket.readyState);125 return;126 }127 this.restartNum++;128 console.log('éå¯', this.restartNum);129 this.lockReconnect = true;130 //没è¿æ¥ä¸ä¼ä¸ç´éè¿ï¼è®¾ç½®å»¶è¿é¿å
请æ±è¿å¤131 this.timeout && clearTimeout(this.timeout);132 this.timeout = setTimeout(() => {133 this.websocketStart();134 this.lockReconnect = false;135 }, this.reconnectTime);136 }137 // 对socketçäºä»¶è¿è¡æ³¨å138 websocketInit () {139 const onOpen = () => {140 // console.log("sock connect success !!!!--------------------------------");141 // æ´æ°ä¼ è¾ä¿¡æ¯éçsocket142 this.sockSend.changeSocket(this.socket);143 // å¿è·³æ£æµ144 this.heartCheck = new HeartCheck(this.sockSend, this.heartTimeout);145 // å¯å¨æååéå¯æ¬¡æ°å½é¶146 this.restartNum = 0;147 // 继ç»è¿è¡è¿æªå®æçäºä»¶148 this.sockSend.restartEmit();149 // å建åå¼å§å¿è·³æ£æµ150 this.heartCheck.startHeart();151 // å¯å¨websocketæå152 this.waitSocketState && this.waitSocketState(this.socket.readyState);153 }154 const onError = (err) => {155 console.log("error--- ", err);156 }157 const onClose = (e) => {158 this.heartCheck && this.heartCheck.stopHeart();159 console.log("close---", this.socket.readyState);160 this.websocketReconnect(); // éè¿161 }162 const onEnd = (e) => {163 console.log("end");164 }165 // node ç¯å¢æ¥æ¶ä¿¡æ¯166 const onMessageNode = (data) => {167 //æ¿å°ä»»ä½æ¶æ¯é½è¯´æå½åè¿æ¥æ¯æ£å¸¸ç éæ°å¼å§å¿è·³æ£æµ168 this.heartCheck.startHeart();169 const messageData = JSON.parse(data.toString());170 this.sockSend.emit(messageData);171 }172 // web ç¯å¢æ¥æ¶ä¿¡æ¯173 const onMessageWeb = (res) => {174 // 读åblob æ¯æ¬¡é½æ°å»º é¿å
ç¸äºå½±å175 const fileReader = new FileReader();176 //æ¿å°ä»»ä½æ¶æ¯é½è¯´æå½åè¿æ¥æ¯æ£å¸¸ç éæ°å¼å§å¿è·³æ£æµ177 this.heartCheck.startHeart();178 //å°Blob 对象转æ¢æå符串179 fileReader.readAsText(res.data, 'utf-8');180 fileReader.onload = (e) => {181 const messageData = JSON.parse(fileReader.result.toString());182 this.sockSend.emit(messageData);183 }184 }185 // nodeç¯å¢186 if(typeof(WebSocket) === "undefined") {187 this.socket.on("open",onOpen);188 this.socket.on("error", onError);189 this.socket.on("close", onClose);190 this.socket.on("end", onEnd);191 this.socket.on("message", onMessageNode);192 }else{193 // æµè§å¨ç¯å¢194 this.socket.onopen = onOpen;195 this.socket.onerror = onError;196 this.socket.onclose = onClose;197 this.socket.onmessage = onMessageWeb;198 }199 }200 // éæ¯socket201 clearSocket() {202 // ä¸åéå¯203 this.socketIsClose = true;204 // æå¼ws205 this.socket.close(1000);206 // éæ¯è®¢é
207 this.sockSend.emitter.off();208 }209}...
statsd.spec.js
Source:statsd.spec.js
1"use strict";2const lolex = require("@sinonjs/fake-timers");3jest.mock("dgram");4const dgram = require("dgram");5const sockSend = jest.fn((data, from, to, port, host, cb) => cb());6const sockClose = jest.fn();7dgram.createSocket = jest.fn(() => ({8 send: sockSend,9 close: sockClose10}));11const StatsDReporter = require("../../../../src/metrics/reporters/statsd");12const ServiceBroker = require("../../../../src/service-broker");13const MetricRegistry = require("../../../../src/metrics/registry");14describe("Test StatsDReporter class", () => {15 describe("Test Constructor", () => {16 it("should create with default options", () => {17 const reporter = new StatsDReporter();18 expect(reporter.opts).toEqual({19 includes: null,20 excludes: null,21 metricNamePrefix: null,22 metricNameSuffix: null,23 metricNameFormatter: null,24 labelNameFormatter: null,25 host: "localhost",26 port: 8125,27 maxPayloadSize: 130028 });29 });30 it("should create with custom options", () => {31 const reporter = new StatsDReporter({32 metricNamePrefix: "mol-",33 metricNameSuffix: ".data",34 includes: "moleculer.**",35 excludes: ["moleculer.circuit-breaker.**", "moleculer.custom.**"],36 metricNameFormatter: () => {},37 labelNameFormatter: () => {},38 host: "localhost",39 port: 8888,40 maxPayloadSize: 60041 });42 expect(reporter.opts).toEqual({43 metricNamePrefix: "mol-",44 metricNameSuffix: ".data",45 includes: ["moleculer.**"],46 excludes: ["moleculer.circuit-breaker.**", "moleculer.custom.**"],47 metricNameFormatter: expect.any(Function),48 labelNameFormatter: expect.any(Function),49 host: "localhost",50 port: 8888,51 maxPayloadSize: 60052 });53 });54 });55 describe("Test init method", () => {56 let clock;57 beforeAll(() => (clock = lolex.install()));58 afterAll(() => clock.uninstall());59 it("should start timer & create directory", () => {60 const fakeBroker = {61 nodeID: "node-123",62 namespace: "test-ns"63 };64 const fakeRegistry = { broker: fakeBroker };65 const reporter = new StatsDReporter({ interval: 2000, folder: "/metrics" });66 reporter.flush = jest.fn();67 reporter.init(fakeRegistry);68 expect(reporter.flush).toBeCalledTimes(1);69 });70 });71 describe("Test labelsToTags method", () => {72 const broker = new ServiceBroker({ logger: false, nodeID: "node-123" });73 const registry = new MetricRegistry(broker);74 const reporter = new StatsDReporter({});75 reporter.init(registry);76 it("should convert labels to filename compatible string", () => {77 expect(reporter.labelsToTags()).toBe("");78 expect(reporter.labelsToTags({})).toBe("");79 expect(80 reporter.labelsToTags({81 a: 5,82 b: "John",83 c: true,84 d: null,85 e: '"Hello \' Mol:ec?uler"'86 })87 ).toBe('a:5,b:John,c:true,d:null,e:\\"Hello \' Mol:ec?uler\\"');88 });89 });90 describe("Test flush method", () => {91 const fakeBroker = {92 nodeID: "node-123",93 namespace: "test-ns"94 };95 const fakeRegistry = { broker: fakeBroker };96 const reporter = new StatsDReporter({});97 reporter.sendChunks = jest.fn();98 reporter.generateStatsDSeries = jest.fn(() => []);99 reporter.init(fakeRegistry);100 it("should call generateStatsDSeries", () => {101 reporter.generateStatsDSeries.mockClear();102 reporter.sendChunks.mockClear();103 reporter.flush();104 expect(reporter.generateStatsDSeries).toBeCalledTimes(1);105 expect(reporter.sendChunks).toBeCalledTimes(0);106 });107 it("should call generateStatsDSeries & sendChunks", () => {108 reporter.generateStatsDSeries = jest.fn(() => [1, 2]);109 reporter.sendChunks.mockClear();110 reporter.flush();111 expect(reporter.generateStatsDSeries).toBeCalledTimes(1);112 expect(reporter.sendChunks).toBeCalledTimes(1);113 expect(reporter.sendChunks).toBeCalledWith([1, 2]);114 });115 });116 describe("Test sendChunks method with maxPayloadSize", () => {117 let clock;118 beforeAll(() => (clock = lolex.install()));119 afterAll(() => clock.uninstall());120 const fakeBroker = {121 nodeID: "node-123",122 namespace: "test-ns"123 };124 const fakeRegistry = { broker: fakeBroker };125 const reporter = new StatsDReporter({ maxPayloadSize: 200 });126 reporter.send = jest.fn();127 const series = [128 "12345678901234567890123456789012345678901234567890",129 "23456789012345678901234567890123456789012345678901",130 "34567890123456789012345678901234567890123456789012",131 "45678901234567890123456789012345678901234567890123",132 "56789012345678901234567890123456789012345678901234",133 "67890123456789012345678901234567890123456789012345"134 ];135 it("should call send with chunks", () => {136 reporter.send.mockClear();137 reporter.sendChunks(Array.from(series));138 expect(reporter.send).toBeCalledTimes(1);139 expect(reporter.send).toBeCalledWith(Buffer.from(series.slice(0, 4).join("\n")));140 });141 it("should call send with the rest", () => {142 reporter.send.mockClear();143 clock.tick(150);144 expect(reporter.send).toBeCalledTimes(1);145 expect(reporter.send).toBeCalledWith(Buffer.from(series.slice(4, 6).join("\n")));146 });147 it("should not call send", () => {148 reporter.send.mockClear();149 clock.tick(150);150 expect(reporter.send).toBeCalledTimes(0);151 });152 });153 describe("Test sendChunks method without maxPayloadSize", () => {154 let clock;155 beforeAll(() => (clock = lolex.install()));156 afterAll(() => clock.uninstall());157 const fakeBroker = {158 nodeID: "node-123",159 namespace: "test-ns"160 };161 const fakeRegistry = { broker: fakeBroker };162 const reporter = new StatsDReporter({ maxPayloadSize: 0 });163 reporter.send = jest.fn();164 const series = [165 "12345678901234567890123456789012345678901234567890",166 "23456789012345678901234567890123456789012345678901",167 "34567890123456789012345678901234567890123456789012",168 "45678901234567890123456789012345678901234567890123",169 "56789012345678901234567890123456789012345678901234",170 "67890123456789012345678901234567890123456789012345"171 ];172 it("should call send with all chunks", () => {173 reporter.send.mockClear();174 reporter.sendChunks(Array.from(series));175 expect(reporter.send).toBeCalledTimes(1);176 expect(reporter.send).toBeCalledWith(Buffer.from(series.slice(0, 6).join("\n")));177 });178 it("should not call send", () => {179 reporter.send.mockClear();180 clock.tick(150);181 expect(reporter.send).toBeCalledTimes(0);182 });183 });184 describe("Test send method", () => {185 const broker = new ServiceBroker({ logger: false, metrics: true });186 const registry = broker.metrics;187 const reporter = new StatsDReporter({ maxPayloadSize: 0 });188 reporter.init(registry);189 it("should send data via udp4", () => {190 dgram.createSocket.mockClear();191 sockSend.mockClear();192 sockClose.mockClear();193 const buf = Buffer.from("Moleculer Metrics Data");194 reporter.send(buf);195 expect(dgram.createSocket).toBeCalledTimes(1);196 expect(dgram.createSocket).toBeCalledWith("udp4");197 expect(sockSend).toBeCalledTimes(1);198 expect(sockSend).toBeCalledWith(buf, 0, 22, 8125, "localhost", expect.any(Function));199 expect(sockClose).toBeCalledTimes(1);200 });201 });202 describe("Test generateStatsDSeries & generateStatDLine method", () => {203 const broker = new ServiceBroker({ logger: false, metrics: true });204 const registry = broker.metrics;205 const reporter = new StatsDReporter({206 includes: "test.**"207 });208 reporter.init(registry);209 it("should call generateStatDLine", () => {210 registry.register({ name: "os.datetime.utc", type: "gauge" }).set(123456);211 registry212 .register({ name: "test.info", type: "info", description: "Test Info Metric" })213 .set("Test Value");214 registry.register({215 name: "test.counter",216 type: "counter",217 labelNames: ["action"],218 description: "Test Counter Metric"219 });220 registry.increment("test.counter", null, 5);221 registry.increment("test.counter", { action: "posts\\comments" }, 8);222 registry.register({223 name: "test.gauge-total",224 type: "gauge",225 labelNames: ["action"],226 description: "Test Gauge Metric"227 });228 registry.decrement("test.gauge-total", { action: 'users-"John"' }, 8);229 registry.set("test.gauge-total", { action: "posts" }, null);230 registry.register({231 name: "test.histogram",232 type: "histogram",233 labelNames: ["action"],234 buckets: true,235 quantiles: true,236 unit: "byte"237 });238 registry.observe("test.histogram", 8, null);239 registry.observe("test.histogram", 2, null);240 registry.observe("test.histogram", 6, null);241 registry.observe("test.histogram", 2, null);242 registry.observe("test.histogram", 1, { action: "auth" });243 registry.observe("test.histogram", 3, { action: "auth" });244 registry.observe("test.histogram", 7, { action: "auth" });245 const res = reporter.generateStatsDSeries();246 expect(res).toEqual([247 'test.info:"Test Value"|s',248 "test.counter:5|c|#",249 "test.counter:8|c|#action:posts\\\\comments",250 'test.gauge-total:-8|g|#action:users-\\"John\\"',251 "test.gauge-total:[object Object]|g|#"252 ]);253 });254 });255 describe("Test metricChanged method", () => {256 const broker = new ServiceBroker({257 logger: false,258 metrics: {259 reporter: "StatsD"260 }261 });262 const registry = broker.metrics;263 const reporter = registry.reporter[0];264 it("should call generateStatDLine", () => {265 registry.register({266 name: "test.histogram",267 type: "histogram",268 labelNames: ["action"],269 buckets: true,270 quantiles: true,271 unit: "byte"272 });273 reporter.send = jest.fn();274 registry.observe("test.histogram", 7, { action: "auth" });275 expect(reporter.send).toBeCalledTimes(1);276 expect(reporter.send).toBeCalledWith(Buffer.from("test.histogram:7|ms|#action:auth"));277 });278 });...
MusicManager.js
Source:MusicManager.js
1const { Client: Lavaqueue } = require("lavaqueue");2const config = require("../../config.json");3const { MessageEmbed } = require("discord.js");4const { Queue } = require("lavaqueue");5const NODE = config.lavalink;6const REDIS = config.redis;7function send(guildID, packet) {8 if (this.client.guilds.cache) {9 const guild = this.client.guilds.cache.get(guildID);10 if (guild) {11 return guild.shard.send(packet);12 }13 } else {14 const guild = this.client.guilds.get(guildID);15 if (guild) {16 const sockSend = this.client.ws.send;17 const shardSend = guild.shard.send;18 const socket = typeof sockSend === "function";19 return socket ? sockSend(packet) : shardSend(packet);20 }21 }22}23function packetHandler(packet) {24 switch (packet.t) {25 case "VOICE_SERVER_UPDATE":26 this.voiceServerUpdate(packet.d);27 break;28 case "VOICE_STATE_UPDATE":29 this.voiceStateUpdate(packet.d);30 break;31 default:32 // noop33 }34}35async function eventHandler(inbound) {36 if (inbound.type === "TrackStartEvent") {37 this.decode(inbound.track).then((track) => {38 const embed = new MessageEmbed()39 .setTitle("Now playing...")40 .setDescription(41 `[${track.author} | ${track.title}](${track.uri})`42 );43 this.queues.get(inbound.guildId)44 .player.infoChannel.send(embed);45 });46 }47 const finished = ["STOPPED", "FINISHED"].includes(inbound.reason);48 if (inbound.type === "TrackEndEvent" && finished) {49 const embed = new MessageEmbed()50 .setTitle("Queue finished...");51 this.queues.get(inbound.guildId)52 .player.infoChannel.send(embed);53 }54}55module.exports = class MusicManager extends Lavaqueue {56 constructor(client) {57 super({58 userID: client.user.id,59 password: NODE.password,60 hosts: {61 rest: `http${NODE.ssl}://${NODE.host}:${NODE.port}`,62 ws: `ws${NODE.ssl}://${NODE.host}:${NODE.port}`,63 redis: REDIS64 },65 send: send66 });67 this.client = client;68 /* packetHandler updates voice states69 eventHandler listens on rotating queue */70 client.on("raw", packetHandler.bind(this));71 this.on("event", eventHandler.bind(this));72 }73 get(key) {74 let queue;75 queue = super.get(key);76 if (!queue) {77 queue = new Queue(this, key);78 this.set(key, queue)79 }80 return queue;81 }82 async fetchTracks(query) {83 let finder;84 try {85 finder = new URL(query);86 } catch (err) {87 if (err instanceof TypeError) {88 finder = `ytsearch:${query}`;89 }90 }91 return this.load(finder);92 }...
index.js
Source:index.js
1const ClientSocket = require('../index')2const clientSocket = new ClientSocket({3 url: 'ws://127.0.0.1:10001', // æå¡ç«¯å°å4 restartMax: 3, // é»è®¤æå¤éå¯æ¬¡æ°ä¸º35 reconnectTime: 2 * 1000, // é»è®¤2séè¿ä¸æ¬¡6 cmdAPI: {}, // æ¥å£æ件7 wsConfig: {8 handshakeTimeout: 3000, // è¿æ¥è¶
æ¶æ¶é¿9 }, // websocketé
ç½®10 heartTimeout: 10 * 1000, // å¿è·³æ£æµæ¶é´ 10s11});12let aJsUuid; // a.jséçuuid13// è¿æªå建wsè¿æ¥å°±å¯ä»¥å¼å§è®¢é
14// 订é
æ¹å¼ serve -> client15// åªè¦æå¡ç«¯æ¨é该å½ä»¤å°±ä¼è§¦å16clientSocket.sockSend.emitter.on('applySite', ({resData})=>{17 console.log('订é
æ¹å¼', resData.content.name);18 if(resData.uuid === aJsUuid) {19 console.log('æå¨b.jsé订é
', aJsUuid, resData);20 }21});22(async ()=>{23 const wsReadyState = await clientSocket.createSocket();24 if(wsReadyState === 1) {25 // åè°æ¹å¼ client -> serve -> client26 // å
é¨çæuuid èªå¨ç»å®27 clientSocket.sockSend.send('test', {name: '1'},28 ({reqData, resData, onmessage, socket})=>{29 console.log('åè°æ¹å¼', resData.content.name);30 });31 clientSocket.sockSend.send('test', {name: '2'}, ({resData})=>{32 console.log('åè°æ¹å¼', resData.content.name);33 });34 // æç§ä½¿ç¨åºæ¯ a.jséè¿è¡éä¿¡ b.js订é
35 // sendä¼è¿åuuid36 aJsUuid = clientSocket.sockSend.send('test', {name: '3'});37 }...
socksend_8tcl.js
Source:socksend_8tcl.js
1var socksend_8tcl =2[3 [ "GetUniqueSocketId", "socksend_8tcl.html#aa3fead282e0c215160bcc825defd89ba", null ],4 [ "processData", "socksend_8tcl.html#a98a9e8c5bbdf7d84c1aee82b96d993ad", null ],5 [ "sockappsetup", "socksend_8tcl.html#ae9580a1d54de9bd0b19723a1d362616d", null ],6 [ "sockconnect", "socksend_8tcl.html#a356651f667b705ff6218ff56df221e5d", null ],7 [ "sockreceive", "socksend_8tcl.html#a69c76c4fbdb57f37d00e755f430d08a1", null ],8 [ "socksend", "socksend_8tcl.html#a23c620b18975ad491f7ec2df7f5ac6b5", null ],9 [ "socksendDebug", "socksend_8tcl.html#ae6962e883c4749aec9a13ef61ba4b24a", null ],10 [ "socksendopen", "socksend_8tcl.html#aa996cbe2133122c22455549642de9134", null ],11 [ "socksendsetup", "socksend_8tcl.html#ad376776eaef4f9a085e83df605a0d3ee", null ],12 [ "tkerror", "socksend_8tcl.html#a473afe5b9bf329ddbf291aad966a5bd3", null ],13 [ "tkrsend", "socksend_8tcl.html#a4404ed8ef40d5d869ff6aee797fc1e19", null ]...
heartCheck.js
Source:heartCheck.js
1class HeartCheck {2 constructor(sockSend, heartTimeout) {3 this.timeoutSize = heartTimeout;4 this.timeoutFun = null;5 this.sockSend = sockSend;6 }7 // å¼å§å¿è·³æ£æµ8 startHeart(){9 this.stopHeart();10 this.timeoutFun = setTimeout(()=>{11 this.sockSend.send('heart');12 }, this.timeoutSize);13 }14 // åæ¢å¿è·³15 stopHeart() {16 this.timeoutFun && clearTimeout(this.timeoutFun);17 }18}...
52699ae0232bb6ff51e3ddb41ff507ef072e55e4_0_1.js
Source:52699ae0232bb6ff51e3ddb41ff507ef072e55e4_0_1.js
1function (event) {2 var msg = JSON.parse(event.data);3 parentSend("Worker received command: " + msg.command);4 if (msg.command == "start_download") {5 var t_id = msg.content.torrent_id;6 parentSend("Worker got torrent_id: " + t_id);7 if (SOCKOPEN) {8 sockSend(t_id);9 } else {10 setTimeout(sockSend, 1000, t_id);11 }12 }...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch({4 proxy: {5 },6 });7 const context = await browser.newContext();8 const page = await context.newPage();9 await page.screenshot({ path: `example.png` });10 await browser.close();11})();12const playwright = require('playwright');13(async () => {14 const browser = await playwright.chromium.launch({15 proxy: {16 },17 });18 const context = await browser.newContext();19 const page = await context.newPage();20 await page.screenshot({ path: `example.png` });21 await browser.close();22})();23const playwright = require('playwright');24(async () => {25 const browser = await playwright.chromium.launch({26 proxy: {27 },28 });29 const context = await browser.newContext();30 const page = await context.newPage();31 await page.screenshot({ path: `example.png` });32 await browser.close();33})();34const playwright = require('playwright');35(async () => {36 const browser = await playwright.chromium.launch({37 proxy: {38 },39 });40 const context = await browser.newContext();41 const page = await context.newPage();42 await page.screenshot({ path: `example.png` });43 await browser.close();44})();45const playwright = require('playwright');46(async () => {47 const browser = await playwright.chromium.launch({48 proxy: {49 },50 });51 const context = await browser.newContext();52 const page = await context.newPage();
Using AI Code Generation
1const {socksEnd} = require('playwright/lib/utils/socks');2const {socksStart} = require('playwright/lib/utils/socks');3const {socksConnect} = require('playwright/lib/utils/socks');4const {socksConnectOverHttp} = require('playwright/lib/utils/socks');5const {socksConnectOverHttps} = require('playwright/lib/utils/socks');6const {socksConnectOverHttp2} = require('playwright/lib/utils/socks');7const {socksConnectOverWebSocket} = require('playwright/lib/utils/socks');8const {socksConnectOverWebSocketOverHttp} = require('playwright/lib/utils/socks');9const {socksConnectOverWebSocketOverHttps} = require('playwright/lib/utils/socks');10const {socksConnectOverWebSocketOverHttp2} = require('playwright/lib/utils/socks');11const {socksConnectOverHttpOverHttp2} = require('playwright/lib/utils/socks');12const {socksConnectOverHttpsOverHttp2} = require('playwright/lib/utils/socks');13const {socksConnectOverHttpOverHttp2OverWebSocket} = require('playwright/lib/utils/socks');14const {socksConnectOverHttpsOverHttp2OverWebSocket} = require('playwright/lib/utils/socks');15const {socksConnectOverHttpOverHttp2OverWebSocketOverHttps} = require('playwright/lib/utils/socks');16const {socksConnectOverHttpsOver
Using AI Code Generation
1const playwright = require('playwright');2const socks = require('socksv5');3const socksServer = socks.createServer((info, accept, deny) => {4 accept();5});6socksServer.listen(1080);7(async () => {8 const browser = await playwright.chromium.launch({ headless: false });
Using AI Code Generation
1const socksEnd = require('playwright/lib/server/socksServer').socksEnd;2socksEnd();3const socksStart = require('playwright/lib/server/socksServer').socksStart;4socksStart();5const socksReset = require('playwright/lib/server/socksServer').socksReset;6socksReset();7const socksRewrite = require('playwright/lib/server/socksServer').socksRewrite;8socksRewrite();9const socksRewrite = require('playwright/lib/server/socksServer').socksRewrite;10socksRewrite();11const socksRewrite = require('playwright/lib/server/socksServer').socksRewrite;12socksRewrite();13const socksRewrite = require('playwright/lib/server/socksServer').socksRewrite;14socksRewrite();15const socksRewrite = require('playwright/lib/server/socksServer').socksRewrite;16socksRewrite();17const socksRewrite = require('playwright/lib/server/socksServer').socksRewrite;18socksRewrite();19const socksRewrite = require('playwright/lib/server/socksServer').socksRewrite;20socksRewrite();21const socksRewrite = require('playwright/lib/server/socksServer').socksRewrite;22socksRewrite();23const socksRewrite = require('playwright/lib/server/socksServer').socksRewrite;24socksRewrite();
Using AI Code Generation
1const {socksEnd} = require('playwright/lib/server/browserContext');2const {socksStart} = require('playwright/lib/server/browserContext');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext({recordHar: {path: 'test.har'}});6 const page = await context.newPage();7 await socksStart(context, '
Using AI Code Generation
1const playwright = require('playwright');2const { createServer } = require('http');3const { createProxyServer } = require('http-proxy');4const proxy = createProxyServer({});5(async () => {6 const browser = await playwright.chromium.launch({7 proxy: {
Using AI Code Generation
1const socks = require('playwright-socks');2const socksOptions = { socksPort: 8080 };3const socksServer = await socks.createSocksServer(socksOptions);4const browser = await socksServer.launchBrowser();5const page = await browser.newPage();6await socksServer.close();7const socks = require('playwright-socks');8const socksOptions = { socksPort: 8080 };9const socksServer = await socks.createSocksServer(socksOptions);10const browser = await socksServer.launchBrowser();11const page = await browser.newPage();12await socksServer.close();13const socks = require('playwright-socks');14const socksOptions = { socksPort: 8080 };15const socksServer = await socks.createSocksServer(socksOptions);16const browser = await socksServer.launchBrowser();17const page = await browser.newPage();18await socksServer.close();19const socks = require('playwright-socks');20const socksOptions = { socksPort: 8080 };21const socksServer = await socks.createSocksServer(socksOptions);22const browser = await socksServer.launchBrowser();23const page = await browser.newPage();24await socksServer.close();25const socks = require('playwright-socks');26const socksOptions = { socksPort: 8080 };27const socksServer = await socks.createSocksServer(socksOptions);28const browser = await socksServer.launchBrowser();29const page = await browser.newPage();30await socksServer.close();31const socks = require('playwright-socks');32const socksOptions = { socksPort: 8080 };33const socksServer = await socks.createSocksServer(socksOptions);34const browser = await socksServer.launchBrowser();35const page = await browser.newPage();36await socksServer.close();37const socks = require('playwright-socks');38const socksOptions = { socksPort: 8080 };
Using AI Code Generation
1const socks = require('socksv5');2const net = require('net');3const http = require('http');4const { SocksProxyAgent } = require('socks-proxy-agent');5const server = socks.createServer(function(info, accept, deny) {6 var socket;7 if ((socket = accept(true))) {8 console.log('SOCKS connection from ' +9 socket.remoteAddress + ':' + socket.remotePort);10 socket.on('data', function(data) {11 console.log('SOCKS data from ' +12 socket.remoteAddress + ':' + socket.remotePort + ': ' + data);13 });14 socket.on('end', function() {15 console.log('SOCKS connection from ' +16 socket.remoteAddress + ':' + socket.remotePort + ' ended');17 });18 socket.on('close', function(had_error) {19 console.log('SOCKS connection from ' +20 socket.remoteAddress + ':' + socket.remotePort + ' closed');21 });22 socket.on('error', function(error) {23 console.log('SOCKS connection from ' +24 socket.remoteAddress + ':' + socket.remotePort + ' errored: ' + error);25 });26 }27});28server.listen(1080, '
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!