-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
79 lines (65 loc) · 2.14 KB
/
index.js
File metadata and controls
79 lines (65 loc) · 2.14 KB
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
#!/usr/bin/env node
const ScaledroneWS = require('scaledrone-node');
const ScaledroneREST = require('scaledrone-node-push');
const crypto = require('crypto');
const CHANNEL_ID = process.env.CHANNEL_ID || 'rAs7cOdHUbHWXlpv';
const SECRET = process.env.CHANNEL_SECRET || 'NicsuJZlEp0EbLCjhppyUeOt8k8e0lQj';
const ROOM = 'ping';
const INTERVAL_MS = 1000;
if (!CHANNEL_ID || !SECRET) {
console.error('Set CHANNEL_ID and CHANNEL_SECRET');
process.exit(1);
}
const rest = new ScaledroneREST({ channelId: CHANNEL_ID, secretKey: SECRET });
const ws = new ScaledroneWS(CHANNEL_ID);
const room = ws.subscribe(ROOM);
const inflight = new Map(); // id -> t0 (ns)
function nowNs() { return process.hrtime.bigint(); }
function toMs(ns) { return Number(ns) / 1e6; }
function id() { return crypto.randomBytes(8).toString('hex'); }
let timer = null;
function sendOnce() {
const msgId = id();
inflight.set(msgId, nowNs());
const msg = JSON.stringify({ id: msgId });
// console.log('Publishing', msgId);
rest.publish(ROOM, msg, (err) => {
if (err) {
console.error('REST publish error:', err.message || err);
} else {
// console.log('Published', { id: msgId });
}
});
}
room.on('open', (err) => {
if (err) {
console.error('Room open error:', err.message || err);
process.exit(2);
}
console.log(`channel=${CHANNEL_ID} room=${ROOM} interval=${INTERVAL_MS}ms`);
timer = setInterval(sendOnce, INTERVAL_MS);
});
room.on('message', (m) => {
// console.log('GOT DATA:', m);
let data = m && m.data;
if (!data) return;
if (typeof data === 'string') {
try { data = JSON.parse(data); } catch (_) {}
}
const msgId = data && data.id;
const t0 = msgId && inflight.get(msgId);
if (!t0) return;
inflight.delete(msgId);
const rttMs = toMs(nowNs() - t0);
console.log(`${new Date().toISOString()} id=${msgId} rtt=${rttMs.toFixed(2)}ms`);
});
ws.on('error', (e) => console.error('WS error:', e.message || e));
ws.on('close', () => {
if (timer) clearInterval(timer);
console.warn('WS closed');
});
process.on('SIGINT', () => {
if (timer) clearInterval(timer);
try { ws.close && ws.close(); } catch (_) {}
process.exit(0);
});