-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.js
103 lines (81 loc) · 2.67 KB
/
client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
require('./prepare-environment.js');
const { default: IcWebsocket, generateRandomIdentity, createWsConfig } = require('ic-websocket-js/lib/cjs/index.js');
const { test_canister_rs } = require('../declarations/test_canister_rs/index.js');
/// IcWebsocket parameters
const gatewayAddress = process.env.WS_GATEWAY_URL;
const icUrl = process.env.IC_URL;
const canisterId = process.env.TEST_CANISTER_ID
|| process.env.CANISTER_ID_TEST_CANISTER_RS
|| process.env.CANISTER_ID_TEST_CANISTER_MO;
const messagesSentPerClient = 20;
async function connectClient(userContext, events) {
try {
const startTimestamp = Date.now();
const wsConfig = createWsConfig({
canisterId: canisterId,
canisterActor: test_canister_rs,
networkUrl: icUrl,
identity: generateRandomIdentity(),
});
const customWs = new IcWebsocket(gatewayAddress, undefined, wsConfig);
await new Promise((resolve, reject) => {
customWs.onopen = () => {
events.emit('histogram', 'open_connection_latency_s', (Date.now() - startTimestamp) / (10 ** 3));
events.emit('counter', 'connect_client_success', 1);
resolve();
};
customWs.onerror = (event) => {
reject(event.error);
}
userContext.vars.ws = customWs;
});
} catch (err) {
console.error(err);
events.emit('counter', 'connect_client_error', 1);
throw new Error(err);
}
}
async function sendMessages(userContext, events) {
const ws = userContext.vars.ws;
try {
await new Promise((resolve, reject) => {
ws.onerror = (event) => {
reject(event.error);
};
let messageCounter = 0;
ws.onmessage = (event) => {
messageCounter++;
if (messageCounter === messagesSentPerClient) {
// close the test after the last message
return resolve();
}
const message = event.data;
events.emit(
'histogram',
'receive_message_latency_ms',
Number(BigInt(Date.now()) - (BigInt(message.timestamp) / BigInt(10 ** 6)))
);
try {
const messageToSend = {
text: message.text + "-pong",
timestamp: Date.now(),
};
ws.send(messageToSend);
events.emit('counter', 'send_message_success', 1);
} catch (err) {
reject(err);
}
};
});
} catch (err) {
console.error(err);
events.emit('counter', 'send_message_error', 1);
throw new Error(err);
}
}
function disconnectClient(userContext, events, done) {
userContext.vars.ws.close();
events.emit('counter', 'disconnect_client', 1);
done();
}
module.exports = { connectClient, sendMessages, disconnectClient };