How to use socksEnd method in Playwright Internal

Best JavaScript code snippet using playwright-internal

app.js

Source:app.js Github

copy

Full Screen

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...

Full Screen

Full Screen

client.js

Source:client.js Github

copy

Full Screen

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}...

Full Screen

Full Screen

statsd.spec.js

Source:statsd.spec.js Github

copy

Full Screen

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 });...

Full Screen

Full Screen

MusicManager.js

Source:MusicManager.js Github

copy

Full Screen

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 }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

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 }...

Full Screen

Full Screen

socksend_8tcl.js

Source:socksend_8tcl.js Github

copy

Full Screen

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 ]...

Full Screen

Full Screen

heartCheck.js

Source:heartCheck.js Github

copy

Full Screen

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}...

Full Screen

Full Screen

52699ae0232bb6ff51e3ddb41ff507ef072e55e4_0_1.js

Source:52699ae0232bb6ff51e3ddb41ff507ef072e55e4_0_1.js Github

copy

Full Screen

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 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

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();

Full Screen

Using AI Code Generation

copy

Full Screen

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

Full Screen

Using AI Code Generation

copy

Full Screen

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 });

Full Screen

Using AI Code Generation

copy

Full Screen

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();

Full Screen

Using AI Code Generation

copy

Full Screen

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, '

Full Screen

Using AI Code Generation

copy

Full Screen

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: {

Full Screen

Using AI Code Generation

copy

Full Screen

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 };

Full Screen

Using AI Code Generation

copy

Full Screen

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, '

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful