iosignal 9.12.0 → 9.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/esm/io.js +5 -5
- package/dist/browser/esm/io.js.map +1 -1
- package/dist/browser/iife/io.js +5 -5
- package/dist/browser/iife/io.js.map +1 -1
- package/dist/node/iosignal.cjs +1340 -126
- package/dist/node/iosignal.d.cts +278 -1
- package/dist/node/iosignal.d.ts +278 -1
- package/dist/node/iosignal.js +1342 -129
- package/dist/types/common/payload.d.ts +9 -0
- package/package.json +1 -1
package/dist/node/iosignal.cjs
CHANGED
|
@@ -16,9 +16,14 @@ var node_net = require('node:net');
|
|
|
16
16
|
var os = require('os');
|
|
17
17
|
var fs = require('fs');
|
|
18
18
|
var process$1 = require('process');
|
|
19
|
+
var promises = require('node:fs/promises');
|
|
20
|
+
var node_crypto = require('node:crypto');
|
|
21
|
+
var node_fs = require('node:fs');
|
|
22
|
+
var node_os = require('node:os');
|
|
19
23
|
var path = require('path');
|
|
20
24
|
|
|
21
|
-
var
|
|
25
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
26
|
+
var version$1 = "9.14.0";
|
|
22
27
|
var pkg = {
|
|
23
28
|
version: version$1};
|
|
24
29
|
|
|
@@ -596,12 +601,12 @@ const STATUS$1 = {
|
|
|
596
601
|
ERROR: 255
|
|
597
602
|
};
|
|
598
603
|
|
|
599
|
-
const encoder$
|
|
604
|
+
const encoder$3 = new TextEncoder();
|
|
600
605
|
|
|
601
606
|
|
|
602
607
|
function getSignalPack(tag, ...args) {
|
|
603
608
|
if (typeof tag !== 'string') throw TypeError('tag should be string.')
|
|
604
|
-
let tagEncoded = encoder$
|
|
609
|
+
let tagEncoded = encoder$3.encode(tag);
|
|
605
610
|
if (tagEncoded.byteLength > SIZE_LIMIT.TAG_LEN1) throw TypeError('tag UTF-8 byte length exceeds 255')
|
|
606
611
|
let payload = parsePayload(args);
|
|
607
612
|
|
|
@@ -643,7 +648,7 @@ function parsePayload(args) {
|
|
|
643
648
|
} else if (args.length == 1) {
|
|
644
649
|
if (typeof args[0] === 'string' || typeof args[0] === 'number') {
|
|
645
650
|
type = PAYLOAD_TYPE.TEXT;
|
|
646
|
-
pack = encoder$
|
|
651
|
+
pack = encoder$3.encode(args[0] + "."); // add null byte area.
|
|
647
652
|
pack[pack.byteLength - 1] = 0; // set byte-zero : '\0' in C/C++
|
|
648
653
|
|
|
649
654
|
} else if (ArrayBuffer.isView(args[0]) || args[0] instanceof ArrayBuffer) {
|
|
@@ -651,7 +656,7 @@ function parsePayload(args) {
|
|
|
651
656
|
pack = $$1.B8(args[0]);
|
|
652
657
|
} else if (typeof args[0] === 'object') {
|
|
653
658
|
type = PAYLOAD_TYPE.OBJECT;
|
|
654
|
-
pack = encoder$
|
|
659
|
+
pack = encoder$3.encode(JSON.stringify(args[0]));
|
|
655
660
|
} else {
|
|
656
661
|
throw new Error('unknown payload arguments')
|
|
657
662
|
}
|
|
@@ -665,7 +670,7 @@ function parsePayload(args) {
|
|
|
665
670
|
type = PAYLOAD_TYPE.MBA;
|
|
666
671
|
} else {
|
|
667
672
|
type = PAYLOAD_TYPE.MJSON;
|
|
668
|
-
pack = encoder$
|
|
673
|
+
pack = encoder$3.encode(JSON.stringify(args));
|
|
669
674
|
}
|
|
670
675
|
|
|
671
676
|
}
|
|
@@ -677,6 +682,42 @@ function getPayloadFromSignalPack(signalPack) {
|
|
|
677
682
|
let tagLen = signalPack.readUint8(1);
|
|
678
683
|
return signalPack.subarray(3 + tagLen)
|
|
679
684
|
}
|
|
685
|
+
const decoder$5 = new TextDecoder();
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Arguments of a SIGNAL payload, as IO emits them after the tag: EMPTY [], TEXT [string] (the
|
|
689
|
+
* trailing NUL that C/C++ senders add is removed), BINARY [the buffer itself], OBJECT [value],
|
|
690
|
+
* MJSON [...values], MBA [...args]. null for an unknown payload type. Throws on malformed JSON/MBA.
|
|
691
|
+
* @param {number} payloadType
|
|
692
|
+
* @param {Uint8Array} payloadBuffer
|
|
693
|
+
* @returns {any[] | null}
|
|
694
|
+
*/
|
|
695
|
+
function decodeSignalArgs(payloadType, payloadBuffer) {
|
|
696
|
+
switch (payloadType) {
|
|
697
|
+
case PAYLOAD_TYPE.EMPTY:
|
|
698
|
+
return []
|
|
699
|
+
case PAYLOAD_TYPE.TEXT: {
|
|
700
|
+
const end = payloadBuffer[payloadBuffer.byteLength - 1] === 0 ? payloadBuffer.byteLength - 1 : payloadBuffer.byteLength;
|
|
701
|
+
return [decoder$5.decode(payloadBuffer.subarray(0, end))]
|
|
702
|
+
}
|
|
703
|
+
case PAYLOAD_TYPE.BINARY:
|
|
704
|
+
return [payloadBuffer]
|
|
705
|
+
case PAYLOAD_TYPE.OBJECT:
|
|
706
|
+
return [JSON.parse(decoder$5.decode(payloadBuffer))]
|
|
707
|
+
case PAYLOAD_TYPE.MJSON: {
|
|
708
|
+
const values = JSON.parse(decoder$5.decode(payloadBuffer));
|
|
709
|
+
if (!Array.isArray(values)) throw new TypeError('MJSON payload is not an array')
|
|
710
|
+
return values
|
|
711
|
+
}
|
|
712
|
+
case PAYLOAD_TYPE.MBA: {
|
|
713
|
+
const mba = $$1.unpack(payloadBuffer);
|
|
714
|
+
if (!mba) throw new TypeError('malformed MBA payload')
|
|
715
|
+
return mba.args
|
|
716
|
+
}
|
|
717
|
+
default:
|
|
718
|
+
return null
|
|
719
|
+
}
|
|
720
|
+
}
|
|
680
721
|
|
|
681
722
|
const t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function e(e,r,n,i,o){let f,s,u,h,a,c,l,p,y,g,d,b,w;for(;o>=64;){for(f=r[0],s=r[1],u=r[2],h=r[3],a=r[4],c=r[5],l=r[6],p=r[7],g=0;g<16;g++)d=i+4*g,e[g]=(255&n[d])<<24|(255&n[d+1])<<16|(255&n[d+2])<<8|255&n[d+3];for(g=16;g<64;g++)y=e[g-2],b=(y>>>17|y<<15)^(y>>>19|y<<13)^y>>>10,y=e[g-15],w=(y>>>7|y<<25)^(y>>>18|y<<14)^y>>>3,e[g]=(b+e[g-7]|0)+(w+e[g-16]|0);for(g=0;g<64;g++)b=(((a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7))+(a&c^~a&l)|0)+(p+(t[g]+e[g]|0)|0)|0,w=((f>>>2|f<<30)^(f>>>13|f<<19)^(f>>>22|f<<10))+(f&s^f&u^s&u)|0,p=l,l=c,c=a,a=h+b|0,h=u,u=s,s=f,f=b+w|0;r[0]+=f,r[1]+=s,r[2]+=u,r[3]+=h,r[4]+=a,r[5]+=c,r[6]+=l,r[7]+=p,i+=64,o-=64;}return i}const r=function(){function t(){this.digestLength=32,this.blockSize=64,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=false,this.reset();}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=false,this},t.prototype.clean=function(){for(var t=0;t<this.buffer.length;t++)this.buffer[t]=0;for(t=0;t<this.temp.length;t++)this.temp[t]=0;this.reset();},t.prototype.update=function(t,r){if(void 0===r&&(r=t.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");let n=0;if(this.bytesHashed+=r,this.bufferLength>0){for(;this.bufferLength<64&&r>0;)this.buffer[this.bufferLength++]=t[n++],r--;64===this.bufferLength&&(e(this.temp,this.state,this.buffer,0,64),this.bufferLength=0);}for(r>=64&&(n=e(this.temp,this.state,t,n,r),r%=64);r>0;)this.buffer[this.bufferLength++]=t[n++],r--;return this},t.prototype.finish=function(t){if(!this.finished){const t=this.bytesHashed,n=this.bufferLength,i=t/536870912|0,o=t<<3,f=t%64<56?64:128;this.buffer[n]=128;for(var r=n+1;r<f-8;r++)this.buffer[r]=0;this.buffer[f-8]=i>>>24&255,this.buffer[f-7]=i>>>16&255,this.buffer[f-6]=i>>>8&255,this.buffer[f-5]=i>>>0&255,this.buffer[f-4]=o>>>24&255,this.buffer[f-3]=o>>>16&255,this.buffer[f-2]=o>>>8&255,this.buffer[f-1]=o>>>0&255,e(this.temp,this.state,this.buffer,0,f),this.finished=true;}for(r=0;r<8;r++)t[4*r+0]=this.state[r]>>>24&255,t[4*r+1]=this.state[r]>>>16&255,t[4*r+2]=this.state[r]>>>8&255,t[4*r+3]=this.state[r]>>>0&255;return this},t.prototype.digest=function(){const t=new Uint8Array(this.digestLength);return this.finish(t),t},t.prototype._saveState=function(t){for(let e=0;e<this.state.length;e++)t[e]=this.state[e];},t.prototype._restoreState=function(t,e){for(let e=0;e<this.state.length;e++)this.state[e]=t[e];this.bytesHashed=e,this.finished=false,this.bufferLength=0;},t}(),n=function(){function t(t){this.inner=new r,this.outer=new r,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;const e=new Uint8Array(this.blockSize);if(t.length>this.blockSize)(new r).update(t).finish(e).clean();else for(var n=0;n<t.length;n++)e[n]=t[n];for(n=0;n<e.length;n++)e[n]^=54;this.inner.update(e);for(n=0;n<e.length;n++)e[n]^=106;this.outer.update(e),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(n=0;n<e.length;n++)e[n]=0;}return t.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},t.prototype.clean=function(){for(let t=0;t<this.istate.length;t++)this.ostate[t]=this.istate[t]=0;this.inner.clean(),this.outer.clean();},t.prototype.update=function(t){return this.inner.update(t),this},t.prototype.finish=function(t){return this.outer.finished?this.outer.finish(t):(this.inner.finish(t),this.outer.update(t,this.digestLength).finish(t)),this},t.prototype.digest=function(){const t=new Uint8Array(this.digestLength);return this.finish(t),t},t}();function i(t){const e=(new r).update(t),n=e.digest();return e.clean(),n}var o,f,s,u={},h={},a={};
|
|
682
723
|
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */function c(){return f||(f=1,a.read=function(t,e,r,n,i){var o,f,s=8*i-n-1,u=(1<<s)-1,h=u>>1,a=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-a)-1,p>>=-a,a+=s;a>0;o=256*o+t[e+c],c+=l,a-=8);for(f=o&(1<<-a)-1,o>>=-a,a+=n;a>0;f=256*f+t[e+c],c+=l,a-=8);if(0===o)o=1-h;else {if(o===u)return f?NaN:1/0*(p?-1:1);f+=Math.pow(2,n),o-=h;}return (p?-1:1)*f*Math.pow(2,o-n)},a.write=function(t,e,r,n,i,o){var f,s,u,h=8*o-i-1,a=(1<<h)-1,c=a>>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,y=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,f=a):(f=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-f))<1&&(f--,u*=2),(e+=f+c>=1?l/u:l*Math.pow(2,1-c))*u>=2&&(f++,u/=2),f+c>=a?(s=0,f=a):f+c>=1?(s=(e*u-1)*Math.pow(2,i),f+=c):(s=e*Math.pow(2,c-1)*Math.pow(2,i),f=0));i>=8;t[r+p]=255&s,p+=y,s/=256,i-=8);for(f=f<<i|s,h+=i;h>0;t[r+p]=255&f,p+=y,f/=256,h-=8);t[r+p-y]|=128*g;}),a}
|
|
@@ -705,13 +746,13 @@ const t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1
|
|
|
705
746
|
*/
|
|
706
747
|
|
|
707
748
|
const Buffer$1 = $$1.Buffer;
|
|
708
|
-
const encoder$
|
|
749
|
+
const encoder$2 = new TextEncoder();
|
|
709
750
|
const decoder$4 = new TextDecoder();
|
|
710
751
|
|
|
711
752
|
// Wire tag lengths use one byte, regardless of JavaScript string length.
|
|
712
753
|
function encodeTag(tag, allowEmpty = true) {
|
|
713
754
|
if (typeof tag !== 'string') throw TypeError('tag should be string.')
|
|
714
|
-
const encoded = encoder$
|
|
755
|
+
const encoded = encoder$2.encode(tag);
|
|
715
756
|
if ((!allowEmpty && encoded.byteLength === 0) || encoded.byteLength > SIZE_LIMIT.TAG_LEN1) {
|
|
716
757
|
throw TypeError('tag UTF-8 byte length must be ' + (allowEmpty ? '0' : '1') + '~255')
|
|
717
758
|
}
|
|
@@ -1291,83 +1332,15 @@ class IOCore extends EventEmitter {
|
|
|
1291
1332
|
> cid_sub message: tag includes cid and @ both : 'cid@*'
|
|
1292
1333
|
> ch_sub message: else.
|
|
1293
1334
|
*/
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
if (tag
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
this.emit('message', tag);
|
|
1304
|
-
}
|
|
1305
|
-
break;
|
|
1306
|
-
|
|
1307
|
-
case PAYLOAD_TYPE.TEXT:
|
|
1308
|
-
// !! Must remove null char before decode in JS.
|
|
1309
|
-
// string payload contains null char for the c/cpp devices.
|
|
1310
|
-
let payloadStringWithoutNull = payloadBuffer;
|
|
1311
|
-
if (payloadBuffer[payloadBuffer.byteLength - 1] === 0) {
|
|
1312
|
-
payloadStringWithoutNull = payloadBuffer.subarray(0, payloadBuffer.byteLength - 1);
|
|
1313
|
-
}
|
|
1314
|
-
let oneString = decoder$4.decode(payloadStringWithoutNull);
|
|
1315
|
-
if (tag.indexOf('@') === 0) {
|
|
1316
|
-
this.emit('@', tag, oneString);
|
|
1317
|
-
if (tag !== '@') this.emit(tag, tag, oneString);
|
|
1318
|
-
} else {
|
|
1319
|
-
this.emit(tag, tag, oneString);
|
|
1320
|
-
this.emit('message', tag, oneString);
|
|
1321
|
-
}
|
|
1322
|
-
break;
|
|
1323
|
-
|
|
1324
|
-
case PAYLOAD_TYPE.BINARY:
|
|
1325
|
-
if (tag.indexOf('@') === 0) {
|
|
1326
|
-
this.emit('@', tag, payloadBuffer);
|
|
1327
|
-
if (tag !== '@') this.emit(tag, tag, payloadBuffer);
|
|
1328
|
-
} else {
|
|
1329
|
-
this.emit(tag, tag, payloadBuffer);
|
|
1330
|
-
this.emit('message', tag, payloadBuffer);
|
|
1331
|
-
}
|
|
1332
|
-
break;
|
|
1333
|
-
|
|
1334
|
-
case PAYLOAD_TYPE.OBJECT:
|
|
1335
|
-
let oneObjectBuffer = decoder$4.decode(payloadBuffer);
|
|
1336
|
-
let oneJSONObject = JSON.parse(oneObjectBuffer);
|
|
1337
|
-
if (tag.indexOf('@') === 0) {
|
|
1338
|
-
this.emit('@', tag, oneJSONObject);
|
|
1339
|
-
if (tag !== '@') this.emit(tag, tag, oneJSONObject);
|
|
1340
|
-
} else {
|
|
1341
|
-
this.emit(tag, tag, oneJSONObject);
|
|
1342
|
-
this.emit('message', tag, oneJSONObject);
|
|
1343
|
-
}
|
|
1344
|
-
break;
|
|
1345
|
-
|
|
1346
|
-
case PAYLOAD_TYPE.MJSON:
|
|
1347
|
-
let mjsonBuffer = decoder$4.decode(payloadBuffer);
|
|
1348
|
-
let mjson = JSON.parse(mjsonBuffer);
|
|
1349
|
-
if (tag.indexOf('@') === 0) {
|
|
1350
|
-
this.emit('@', tag, ...mjson);
|
|
1351
|
-
if (tag !== '@') this.emit(tag, tag, ...mjson);
|
|
1352
|
-
} else {
|
|
1353
|
-
this.emit(tag, tag, ...mjson);
|
|
1354
|
-
this.emit('message', tag, ...mjson);
|
|
1355
|
-
}
|
|
1356
|
-
break;
|
|
1357
|
-
|
|
1358
|
-
case PAYLOAD_TYPE.MBA:
|
|
1359
|
-
let mbaObject = $$1.unpack(payloadBuffer);
|
|
1360
|
-
if (tag.indexOf('@') === 0) {
|
|
1361
|
-
this.emit('@', tag, ...mbaObject.args);
|
|
1362
|
-
if (tag !== '@') this.emit(tag, tag, ...mbaObject.args);
|
|
1363
|
-
} else {
|
|
1364
|
-
this.emit(tag, tag, ...mbaObject.args);
|
|
1365
|
-
this.emit('message', tag, ...mbaObject.args);
|
|
1366
|
-
}
|
|
1367
|
-
break;
|
|
1368
|
-
|
|
1369
|
-
default:
|
|
1370
|
-
// console.log('## Unkown payloadtype', payloadType)
|
|
1335
|
+
const args = decodeSignalArgs(payloadType, payloadBuffer);
|
|
1336
|
+
if (args) {
|
|
1337
|
+
if (tag.indexOf('@') === 0) {
|
|
1338
|
+
this.emit('@', tag, ...args);
|
|
1339
|
+
if (tag !== '@') this.emit(tag, tag, ...args);
|
|
1340
|
+
} else {
|
|
1341
|
+
this.emit(tag, tag, ...args);
|
|
1342
|
+
this.emit('message', tag, ...args);
|
|
1343
|
+
}
|
|
1371
1344
|
}
|
|
1372
1345
|
|
|
1373
1346
|
} catch (err) {
|
|
@@ -8745,6 +8718,385 @@ function deliveryAllowed(target, sender) {
|
|
|
8745
8718
|
return policy.defaultAllow
|
|
8746
8719
|
}
|
|
8747
8720
|
|
|
8721
|
+
const encoder$1 = new TextEncoder();
|
|
8722
|
+
const NAME = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
8723
|
+
|
|
8724
|
+
/**
|
|
8725
|
+
* Validates one tag pattern of a host. A trailing '*' makes it a prefix; '*' is allowed nowhere else.
|
|
8726
|
+
* Channel patterns (inbound, and own without '@'): global channel tags, so no '@' and no leading
|
|
8727
|
+
* '#' (home channels belong to one network) or '$'. Unicast patterns (own, leading '@'): the topic
|
|
8728
|
+
* of '<cid>@topic' messages.
|
|
8729
|
+
* @returns {{ pattern: string, text: string, prefix: boolean, unicast: boolean }}
|
|
8730
|
+
*/
|
|
8731
|
+
function parsePattern(pattern, allowUnicast) {
|
|
8732
|
+
if (typeof pattern !== 'string' || pattern.length === 0) throw new TypeError('host tag must be a non-empty string')
|
|
8733
|
+
const prefix = pattern.endsWith('*');
|
|
8734
|
+
const text = prefix ? pattern.slice(0, -1) : pattern;
|
|
8735
|
+
if (text.includes('*')) throw new TypeError(`host tag ${pattern}: '*' is allowed only at the end`)
|
|
8736
|
+
if (text.includes(',')) throw new TypeError(`host tag ${pattern}: ',' separates tags`)
|
|
8737
|
+
if (encoder$1.encode(text).byteLength > SIZE_LIMIT.TAG_LEN1) throw new TypeError(`host tag ${pattern} exceeds 255 UTF-8 bytes`)
|
|
8738
|
+
const unicast = text.startsWith('@');
|
|
8739
|
+
if (unicast) {
|
|
8740
|
+
if (!allowUnicast) throw new TypeError(`host tag ${pattern}: inbound tags are channel tags (no '@')`)
|
|
8741
|
+
if (text.indexOf('@', 1) !== -1) throw new TypeError(`host tag ${pattern}: a unicast topic has one '@'`)
|
|
8742
|
+
if (text.length === 1) throw new TypeError(`host tag ${pattern}: empty topic`)
|
|
8743
|
+
} else {
|
|
8744
|
+
if (text.includes('@')) throw new TypeError(`host tag ${pattern}: channel tags have no '@'`)
|
|
8745
|
+
if (text.startsWith('#')) throw new TypeError(`host tag ${pattern}: home channel tags ('#...') cannot be hosted`)
|
|
8746
|
+
if (text.startsWith('$')) throw new TypeError(`host tag ${pattern}: '$' prefix is reserved`)
|
|
8747
|
+
if (text.length === 0) throw new TypeError(`host tag ${pattern}: empty tag`)
|
|
8748
|
+
}
|
|
8749
|
+
return { pattern, text, prefix, unicast }
|
|
8750
|
+
}
|
|
8751
|
+
|
|
8752
|
+
function overlaps(a, b) {
|
|
8753
|
+
if (a.prefix && b.text.startsWith(a.text)) return true
|
|
8754
|
+
if (b.prefix && a.text.startsWith(b.text)) return true
|
|
8755
|
+
return a.text === b.text
|
|
8756
|
+
}
|
|
8757
|
+
|
|
8758
|
+
/**
|
|
8759
|
+
* The tags all hosts of one server have claimed. Patterns never overlap, so a tag matches at most one.
|
|
8760
|
+
*/
|
|
8761
|
+
class HostTable {
|
|
8762
|
+
constructor() {
|
|
8763
|
+
this.exact = new Map(); // text -> entry
|
|
8764
|
+
this.prefixes = []; // entries
|
|
8765
|
+
this.hosts = new Map(); // name -> Host
|
|
8766
|
+
}
|
|
8767
|
+
|
|
8768
|
+
get size() {
|
|
8769
|
+
return this.hosts.size
|
|
8770
|
+
}
|
|
8771
|
+
|
|
8772
|
+
add(host, entries) {
|
|
8773
|
+
if (this.hosts.has(host.name)) throw new Error(`host ${host.name} already exists`)
|
|
8774
|
+
const all = [...this.exact.values(), ...this.prefixes];
|
|
8775
|
+
entries.forEach((entry, i) => {
|
|
8776
|
+
for (const other of [...all, ...entries.slice(0, i)]) {
|
|
8777
|
+
if (overlaps(entry, other)) {
|
|
8778
|
+
throw new Error(`host tag ${entry.pattern} overlaps ${other.pattern}` +
|
|
8779
|
+
(other.host === host ? '' : ` of host ${other.host.name}`))
|
|
8780
|
+
}
|
|
8781
|
+
}
|
|
8782
|
+
});
|
|
8783
|
+
for (const entry of entries) {
|
|
8784
|
+
if (entry.prefix) this.prefixes.push(entry);
|
|
8785
|
+
else this.exact.set(entry.text, entry);
|
|
8786
|
+
}
|
|
8787
|
+
this.hosts.set(host.name, host);
|
|
8788
|
+
}
|
|
8789
|
+
|
|
8790
|
+
remove(host) {
|
|
8791
|
+
if (this.hosts.get(host.name) !== host) return
|
|
8792
|
+
this.hosts.delete(host.name);
|
|
8793
|
+
for (const [text, entry] of this.exact) if (entry.host === host) this.exact.delete(text);
|
|
8794
|
+
this.prefixes = this.prefixes.filter(entry => entry.host !== host);
|
|
8795
|
+
}
|
|
8796
|
+
|
|
8797
|
+
// tag: a client channel tag, or '@topic' of a unicast. Returns the entry or undefined.
|
|
8798
|
+
match(tag) {
|
|
8799
|
+
const entry = this.exact.get(tag);
|
|
8800
|
+
if (entry) return entry
|
|
8801
|
+
for (const p of this.prefixes) if (tag.startsWith(p.text)) return p
|
|
8802
|
+
return undefined
|
|
8803
|
+
}
|
|
8804
|
+
|
|
8805
|
+
// A connection closed. ownsCid: it still owned its CID (no newer connection took it over).
|
|
8806
|
+
remoteClosed(remote, ownsCid) {
|
|
8807
|
+
if (!ownsCid || !remote.cid) return
|
|
8808
|
+
for (const host of this.hosts.values()) host._remoteClosed(remote);
|
|
8809
|
+
}
|
|
8810
|
+
}
|
|
8811
|
+
|
|
8812
|
+
/**
|
|
8813
|
+
* Game logic (or any server-side logic) inside the server process. Created by server.host().
|
|
8814
|
+
*
|
|
8815
|
+
* Events:
|
|
8816
|
+
* 'message' (from, tag, ...args) a client signal to one of the inbound tags. from is the
|
|
8817
|
+
* server's view of the sender (never anything in the payload).
|
|
8818
|
+
* 'leave' (from, reason) a participant's connection closed (it no longer has its CID)
|
|
8819
|
+
* 'error' (error) a 'message' or 'leave' handler threw
|
|
8820
|
+
* 'close' () the host was closed
|
|
8821
|
+
*/
|
|
8822
|
+
class Host extends require$$0$3 {
|
|
8823
|
+
|
|
8824
|
+
constructor(manager, name, options = {}) {
|
|
8825
|
+
super();
|
|
8826
|
+
if (typeof name !== 'string' || !NAME.test(name)) {
|
|
8827
|
+
throw new TypeError('host name: 1-64 characters of A-Z a-z 0-9 _ . -')
|
|
8828
|
+
}
|
|
8829
|
+
if (options === null || typeof options !== 'object') throw new TypeError('host options must be an object')
|
|
8830
|
+
for (const key of Object.keys(options)) {
|
|
8831
|
+
if (!['inbound', 'own', 'fanout', 'retain'].includes(key)) throw new TypeError(`unknown host option: ${key}`)
|
|
8832
|
+
}
|
|
8833
|
+
const list = (key) => {
|
|
8834
|
+
const value = options[key] ?? [];
|
|
8835
|
+
if (!Array.isArray(value)) throw new TypeError(`host option ${key} must be an array of tags`)
|
|
8836
|
+
return value
|
|
8837
|
+
};
|
|
8838
|
+
/** @type {Host} */
|
|
8839
|
+
const host = this;
|
|
8840
|
+
const inbound = list('inbound').map(p => ({ ...parsePattern(p, false), kind: 'inbound', host }));
|
|
8841
|
+
const own = list('own').map(p => ({ ...parsePattern(p, true), kind: 'own', host }));
|
|
8842
|
+
if (inbound.length === 0) throw new TypeError('host needs at least one inbound tag')
|
|
8843
|
+
|
|
8844
|
+
const fanout = options.fanout ?? null;
|
|
8845
|
+
if (fanout !== null && !(Number.isSafeInteger(fanout) && fanout > 0)) {
|
|
8846
|
+
throw new RangeError('host fanout must be null or a positive integer')
|
|
8847
|
+
}
|
|
8848
|
+
const retain = options.retain ?? {};
|
|
8849
|
+
for (const key of ['tags', 'bytes']) {
|
|
8850
|
+
if (retain[key] !== undefined && !(Number.isSafeInteger(retain[key]) && retain[key] > 0)) {
|
|
8851
|
+
throw new RangeError(`host retain.${key} must be a positive integer`)
|
|
8852
|
+
}
|
|
8853
|
+
}
|
|
8854
|
+
|
|
8855
|
+
this.name = name;
|
|
8856
|
+
this.manager = manager;
|
|
8857
|
+
this.fanout = fanout;
|
|
8858
|
+
this.retainTags = retain.tags ?? null; // null: the server's retain.tagsPerOwner
|
|
8859
|
+
this.retainBytes = retain.bytes ?? null; // null: the server's retain.bytesPerOwner
|
|
8860
|
+
this.retainOwnerKey = 'host:' + name;
|
|
8861
|
+
this.ownChannels = own.filter(e => !e.unicast);
|
|
8862
|
+
this.closed = false;
|
|
8863
|
+
/** @type {Map<string, Readonly<object>>} cid -> from, connections that sent to this host */
|
|
8864
|
+
this._participants = new Map();
|
|
8865
|
+
/** cid -> { inputs, firstAt, lastAt }: activity of each participant, for the dashboard */
|
|
8866
|
+
this._activity = new Map();
|
|
8867
|
+
// Cumulative since the host opened; readers compute rates from deltas (see Dashboard).
|
|
8868
|
+
this.counters = {
|
|
8869
|
+
inbound: 0, // inputs handed to 'message'
|
|
8870
|
+
rejected: 0, // inputs to an inbound tag that were not handed over (E2E, unreadable payload)
|
|
8871
|
+
denied: 0, // client messages to a tag this host owns, dropped
|
|
8872
|
+
published: 0, delivered: 0, // publish() calls and the connections they reached
|
|
8873
|
+
sent: 0, // to() messages sent
|
|
8874
|
+
joins: 0, leaves: 0, errors: 0,
|
|
8875
|
+
handlerMs: 0, // time spent in 'message' and 'leave' handlers
|
|
8876
|
+
};
|
|
8877
|
+
this.handlerMaxMs = 0;
|
|
8878
|
+
this.reported = {}; // last host.report() values
|
|
8879
|
+
this._journal = []; // recent notable events (join, leave, denied, error), oldest first
|
|
8880
|
+
this._journalSeq = 0;
|
|
8881
|
+
this._loops = new Set();
|
|
8882
|
+
|
|
8883
|
+
manager.hosts.add(this, [...inbound, ...own]);
|
|
8884
|
+
// Values a client retained on these tags before the host claimed them are not the host's.
|
|
8885
|
+
for (const tag of [...manager.retain_messages.keys()]) {
|
|
8886
|
+
if (!tag.startsWith(manager.CHANNEL_PREFIX)) continue
|
|
8887
|
+
const entry = manager.hosts.match(tag.slice(manager.CHANNEL_PREFIX.length));
|
|
8888
|
+
if (entry?.host === this) manager.dropChannelRetain(tag);
|
|
8889
|
+
}
|
|
8890
|
+
}
|
|
8891
|
+
|
|
8892
|
+
/** Connections that have sent to this host and are still online: cid -> from. */
|
|
8893
|
+
get participants() {
|
|
8894
|
+
return this._participants
|
|
8895
|
+
}
|
|
8896
|
+
|
|
8897
|
+
/** Stop tracking a participant; no 'leave' is emitted for it (until it sends again). */
|
|
8898
|
+
forget(cid) {
|
|
8899
|
+
this._activity.delete(cid);
|
|
8900
|
+
return this._participants.delete(cid)
|
|
8901
|
+
}
|
|
8902
|
+
|
|
8903
|
+
/**
|
|
8904
|
+
* Publish to one of the host's own channel tags. A tag with '$' is also retained, owned by the
|
|
8905
|
+
* host. Returns the number of connections it was delivered to.
|
|
8906
|
+
*/
|
|
8907
|
+
publish(tag, ...args) {
|
|
8908
|
+
this._open();
|
|
8909
|
+
if (typeof tag !== 'string') throw new TypeError('tag should be string.')
|
|
8910
|
+
const entry = this.manager.hosts.match(tag);
|
|
8911
|
+
if (tag.startsWith('@') || entry?.host !== this || entry.kind !== 'own') {
|
|
8912
|
+
throw new Error(`host ${this.name} does not own channel tag ${tag}`)
|
|
8913
|
+
}
|
|
8914
|
+
const message = getSignalPack(tag, ...args);
|
|
8915
|
+
const n = this.manager.hostPublish(this, this.manager.CHANNEL_PREFIX + tag, message);
|
|
8916
|
+
this.counters.published++;
|
|
8917
|
+
this.counters.delivered += n;
|
|
8918
|
+
return n
|
|
8919
|
+
}
|
|
8920
|
+
|
|
8921
|
+
/**
|
|
8922
|
+
* Send to one connection. It receives '@' + topic. Returns false when the CID is not online
|
|
8923
|
+
* or its receive buffer is too small for the message.
|
|
8924
|
+
*/
|
|
8925
|
+
to(cid, topic, ...args) {
|
|
8926
|
+
this._open();
|
|
8927
|
+
if (typeof topic !== 'string' || topic.length === 0 || topic.includes('@')) {
|
|
8928
|
+
throw new TypeError('topic must be a non-empty string without @')
|
|
8929
|
+
}
|
|
8930
|
+
const remote = this.manager.cid2remote.get(cid);
|
|
8931
|
+
const message = getSignalPack('@' + topic, ...args);
|
|
8932
|
+
if (!remote || remote._closing) return false
|
|
8933
|
+
const skipped = remote.peerRxLimitSkipped;
|
|
8934
|
+
remote.send_enc_mode(message);
|
|
8935
|
+
if (remote.peerRxLimitSkipped !== skipped) return false
|
|
8936
|
+
this.counters.sent++;
|
|
8937
|
+
return true
|
|
8938
|
+
}
|
|
8939
|
+
|
|
8940
|
+
/**
|
|
8941
|
+
* Values to show on the server dashboard ("game" panel), e.g. { round: 3, players: 8 }.
|
|
8942
|
+
* Merged into the last report; a key set to null is removed. Numbers, short strings and booleans,
|
|
8943
|
+
* at most 20 keys.
|
|
8944
|
+
*/
|
|
8945
|
+
report(values) {
|
|
8946
|
+
if (values === null || typeof values !== 'object') throw new TypeError('report() takes an object')
|
|
8947
|
+
for (const [key, value] of Object.entries(values)) {
|
|
8948
|
+
if (value === null || value === undefined) { delete this.reported[key]; continue }
|
|
8949
|
+
if (!['number', 'string', 'boolean'].includes(typeof value)) throw new TypeError(`report value ${key} must be a number, string or boolean`)
|
|
8950
|
+
if (!(key in this.reported) && Object.keys(this.reported).length >= 20) continue
|
|
8951
|
+
this.reported[String(key).slice(0, 32)] = typeof value === 'string' ? value.slice(0, 64) : value;
|
|
8952
|
+
}
|
|
8953
|
+
return this
|
|
8954
|
+
}
|
|
8955
|
+
|
|
8956
|
+
/**
|
|
8957
|
+
* Run fn(now) every intervalMs, like setInterval, and measure it for the dashboard: the gap between
|
|
8958
|
+
* ticks and how long each tick took. A throwing tick is reported as an 'error' and the loop goes on.
|
|
8959
|
+
* Returns a stop function; close() stops every loop.
|
|
8960
|
+
*/
|
|
8961
|
+
loop(intervalMs, fn) {
|
|
8962
|
+
this._open();
|
|
8963
|
+
if (!(Number.isFinite(intervalMs) && intervalMs >= 1)) throw new RangeError('loop interval must be at least 1 ms')
|
|
8964
|
+
if (typeof fn !== 'function') throw new TypeError('loop needs a function')
|
|
8965
|
+
const stats = { intervalMs, ticks: 0, gaps: [], steps: [], last: 0 };
|
|
8966
|
+
const timer = setInterval(() => {
|
|
8967
|
+
const t0 = node_perf_hooks.performance.now();
|
|
8968
|
+
if (stats.last) { stats.gaps.push(t0 - stats.last); if (stats.gaps.length > 200) stats.gaps.shift(); }
|
|
8969
|
+
stats.last = t0;
|
|
8970
|
+
try { fn(Date.now()); } catch (error) { this._failed(error); }
|
|
8971
|
+
stats.steps.push(node_perf_hooks.performance.now() - t0); if (stats.steps.length > 200) stats.steps.shift();
|
|
8972
|
+
stats.ticks++;
|
|
8973
|
+
}, intervalMs);
|
|
8974
|
+
const entry = { timer, stats };
|
|
8975
|
+
this._loops.add(entry);
|
|
8976
|
+
return () => { clearInterval(timer); this._loops.delete(entry); }
|
|
8977
|
+
}
|
|
8978
|
+
|
|
8979
|
+
/** Timing of the loops started with loop(): target, ticks, gap p50/p99 and step average/max (ms). */
|
|
8980
|
+
loopStats() {
|
|
8981
|
+
const pct = (a, p) => { if (!a.length) return 0; const s = [...a].sort((x, y) => x - y); return s[Math.min(s.length - 1, Math.floor(p / 100 * s.length))] };
|
|
8982
|
+
return [...this._loops].map(({ stats: s }) => ({
|
|
8983
|
+
intervalMs: s.intervalMs, ticks: s.ticks,
|
|
8984
|
+
gapP50: pct(s.gaps, 50), gapP99: pct(s.gaps, 99), gapMax: s.gaps.length ? Math.max(...s.gaps) : 0,
|
|
8985
|
+
stepAvg: s.steps.length ? s.steps.reduce((a, b) => a + b, 0) / s.steps.length : 0,
|
|
8986
|
+
stepMax: s.steps.length ? Math.max(...s.steps) : 0,
|
|
8987
|
+
}))
|
|
8988
|
+
}
|
|
8989
|
+
|
|
8990
|
+
/** Participants with their activity: [{ from, inputs, firstAt, lastAt }]. */
|
|
8991
|
+
activity() {
|
|
8992
|
+
return [...this._participants.values()].map((from) => ({ from, ...(this._activity.get(from.cid) ?? { inputs: 0, firstAt: 0, lastAt: 0 }) }))
|
|
8993
|
+
}
|
|
8994
|
+
|
|
8995
|
+
/** Notable events after sequence `after`: [{ seq, at, kind: 'join'|'leave'|'denied'|'error', ... }]. */
|
|
8996
|
+
journal(after = 0) {
|
|
8997
|
+
return this._journal.filter((e) => e.seq > after)
|
|
8998
|
+
}
|
|
8999
|
+
|
|
9000
|
+
_note(kind, data) {
|
|
9001
|
+
this._journal.push({ seq: ++this._journalSeq, at: Date.now(), kind, ...data });
|
|
9002
|
+
if (this._journal.length > 200) this._journal.shift();
|
|
9003
|
+
}
|
|
9004
|
+
|
|
9005
|
+
// A client sent to a tag this host owns (Manager.sender dropped it).
|
|
9006
|
+
_denied(remote, tag) {
|
|
9007
|
+
this.counters.denied++;
|
|
9008
|
+
this._note('denied', { cid: remote.cid, tag });
|
|
9009
|
+
}
|
|
9010
|
+
|
|
9011
|
+
_failed(error) {
|
|
9012
|
+
this.counters.errors++;
|
|
9013
|
+
this._note('error', { message: String(error?.message ?? error).slice(0, 200) });
|
|
9014
|
+
if (this.listenerCount('error')) this.emit('error', error);
|
|
9015
|
+
else console.error(`host ${this.name} error:`, error);
|
|
9016
|
+
}
|
|
9017
|
+
|
|
9018
|
+
/** Release the tags (they become ordinary channels again) and the host's retained values. */
|
|
9019
|
+
close() {
|
|
9020
|
+
if (this.closed) return
|
|
9021
|
+
this.closed = true;
|
|
9022
|
+
for (const { timer } of this._loops) clearInterval(timer);
|
|
9023
|
+
this._loops.clear();
|
|
9024
|
+
this.manager.hosts.remove(this);
|
|
9025
|
+
const owner = this.manager.retainOwners.get(this.retainOwnerKey);
|
|
9026
|
+
if (owner) for (const tag of [...owner.tags]) this.manager.dropChannelRetain(tag);
|
|
9027
|
+
this._participants.clear();
|
|
9028
|
+
this._activity.clear();
|
|
9029
|
+
this.emit('close');
|
|
9030
|
+
}
|
|
9031
|
+
|
|
9032
|
+
_open() {
|
|
9033
|
+
if (this.closed) throw new Error(`host ${this.name} is closed`)
|
|
9034
|
+
}
|
|
9035
|
+
|
|
9036
|
+
// The server's view of a sender; reused while nothing in it changes.
|
|
9037
|
+
static from(remote) {
|
|
9038
|
+
const authorized = remote.boho?.isAuthorized === true;
|
|
9039
|
+
const f = remote._hostFrom;
|
|
9040
|
+
if (f && f.cid === remote.cid && f.uid === remote.uid && f.role === remote.role &&
|
|
9041
|
+
f.nick === remote.nick && f.authorized === authorized) return f
|
|
9042
|
+
return remote._hostFrom = Object.freeze({
|
|
9043
|
+
cid: remote.cid, uid: remote.uid || null, role: remote.role, authorized,
|
|
9044
|
+
nick: remote.nick || '', ssid: remote.ssid
|
|
9045
|
+
})
|
|
9046
|
+
}
|
|
9047
|
+
|
|
9048
|
+
// A SIGNAL from a client to one of the inbound tags. Returns false if it was not delivered.
|
|
9049
|
+
_receive(remote, tag, message) {
|
|
9050
|
+
if (message[0] !== IOMsg.SIGNAL || !remote.cid) return false
|
|
9051
|
+
const tagLen = message[1];
|
|
9052
|
+
if (message.byteLength < tagLen + 3) return false
|
|
9053
|
+
let args;
|
|
9054
|
+
try {
|
|
9055
|
+
args = decodeSignalArgs(message[2 + tagLen], message.subarray(3 + tagLen));
|
|
9056
|
+
} catch {
|
|
9057
|
+
return false
|
|
9058
|
+
}
|
|
9059
|
+
if (!args) return false
|
|
9060
|
+
const from = Host.from(remote);
|
|
9061
|
+
const now = Date.now();
|
|
9062
|
+
let act = this._activity.get(from.cid);
|
|
9063
|
+
if (!act) {
|
|
9064
|
+
act = { inputs: 0, firstAt: now, lastAt: now };
|
|
9065
|
+
this._activity.set(from.cid, act);
|
|
9066
|
+
this.counters.joins++;
|
|
9067
|
+
this._note('join', { cid: from.cid, nick: from.nick, authorized: from.authorized });
|
|
9068
|
+
}
|
|
9069
|
+
act.inputs++;
|
|
9070
|
+
act.lastAt = now;
|
|
9071
|
+
this._participants.set(from.cid, from);
|
|
9072
|
+
this.counters.inbound++;
|
|
9073
|
+
this._emitSafely('message', from, tag, ...args);
|
|
9074
|
+
return true
|
|
9075
|
+
}
|
|
9076
|
+
|
|
9077
|
+
_remoteClosed(remote) {
|
|
9078
|
+
const from = this._participants.get(remote.cid);
|
|
9079
|
+
if (!from) return
|
|
9080
|
+
this._participants.delete(remote.cid);
|
|
9081
|
+
this._activity.delete(remote.cid);
|
|
9082
|
+
this.counters.leaves++;
|
|
9083
|
+
this._note('leave', { cid: remote.cid, reason: remote.closeReason ?? 'close' });
|
|
9084
|
+
this._emitSafely('leave', Host.from(remote), remote.closeReason ?? 'close');
|
|
9085
|
+
}
|
|
9086
|
+
|
|
9087
|
+
_emitSafely(name, ...args) {
|
|
9088
|
+
const t0 = node_perf_hooks.performance.now();
|
|
9089
|
+
try {
|
|
9090
|
+
this.emit(name, ...args);
|
|
9091
|
+
} catch (error) {
|
|
9092
|
+
this._failed(error);
|
|
9093
|
+
}
|
|
9094
|
+
const ms = node_perf_hooks.performance.now() - t0;
|
|
9095
|
+
this.counters.handlerMs += ms;
|
|
9096
|
+
if (ms > this.handlerMaxMs) this.handlerMaxMs = ms;
|
|
9097
|
+
}
|
|
9098
|
+
}
|
|
9099
|
+
|
|
8748
9100
|
// Characters of an anonymous CID after its '?': lowercase Crockford base32, easy to read aloud and type.
|
|
8749
9101
|
const ANONYMOUS_CID_ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz';
|
|
8750
9102
|
|
|
@@ -8766,7 +9118,10 @@ class Manager {
|
|
|
8766
9118
|
this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
|
|
8767
9119
|
publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
|
|
8768
9120
|
peerRxLimitSkipped: 0, // messages not sent: larger than the peer's advertised RX buffer
|
|
8769
|
-
policyDenied: 0
|
|
9121
|
+
policyDenied: 0, // unicasts and CID publications a device's delivery policy kept back
|
|
9122
|
+
hostInbound: 0, // client signals handed to a host (server.host)
|
|
9123
|
+
hostRejected: 0, // signals to a host tag that were not handed over (E2E, malformed payload)
|
|
9124
|
+
hostDenied: 0 }; // client signals to a tag a host owns, dropped
|
|
8770
9125
|
|
|
8771
9126
|
this.authManager = authManager;
|
|
8772
9127
|
|
|
@@ -8791,6 +9146,7 @@ class Manager {
|
|
|
8791
9146
|
this.retainExpiry = new Map(); // key: channel retain tag in a grace pool -> expiry time
|
|
8792
9147
|
this.retainBytes = 0; // all retained messages, channel and CID
|
|
8793
9148
|
this.channel_map = new Map(); // key: channelName -> value: < remote : Set >
|
|
9149
|
+
this.hosts = new HostTable(); // tags claimed by server.host() hosts
|
|
8794
9150
|
this.CHANNEL_PREFIX = 'CH:';
|
|
8795
9151
|
this.CID_PREFIX = 'CID:';
|
|
8796
9152
|
this.metrics = new Metrics(this);
|
|
@@ -8936,10 +9292,12 @@ class Manager {
|
|
|
8936
9292
|
if (this.connectionLogger) this.connectionLogger.log(remoteInfo);
|
|
8937
9293
|
// A replaced duplicate login no longer owns its CID; the new connection is still online.
|
|
8938
9294
|
const cidOwner = this.cid2remote.get(remote.cid);
|
|
8939
|
-
|
|
9295
|
+
const ownsCid = !remote.cid || !cidOwner || cidOwner === remote;
|
|
9296
|
+
if (ownsCid) {
|
|
8940
9297
|
this.deligateSignal(remote, '@state', 'close');
|
|
8941
9298
|
this.deligateSignal(remote, '@$state', 'close');
|
|
8942
9299
|
}
|
|
9300
|
+
if (this.hosts.size) this.hosts.remoteClosed(remote, ownsCid);
|
|
8943
9301
|
|
|
8944
9302
|
// remove subscriber
|
|
8945
9303
|
for (let ch of remote.channels.keys()) {
|
|
@@ -9062,6 +9420,28 @@ class Manager {
|
|
|
9062
9420
|
if (tag.indexOf('$') == 0) return ['err', 'prefix $ is reserved for userSet tag.']
|
|
9063
9421
|
|
|
9064
9422
|
let cidIndex = tag.indexOf('@');
|
|
9423
|
+
|
|
9424
|
+
// Hosts (server.host): a signal to an inbound tag goes to the host only, with its sender; a
|
|
9425
|
+
// client may not send to a tag a host owns. CID publications ('@topic') name their sender and
|
|
9426
|
+
// are never hosted.
|
|
9427
|
+
if (this.hosts.size && cidIndex !== 0) {
|
|
9428
|
+
const entry = this.hosts.match(cidIndex > 0 ? tag.slice(cidIndex) : tag);
|
|
9429
|
+
if (entry?.kind === 'inbound') {
|
|
9430
|
+
if (entry.host._receive(remote, tag, message)) {
|
|
9431
|
+
this.counters.hostInbound++;
|
|
9432
|
+
return ['ok', 1]
|
|
9433
|
+
}
|
|
9434
|
+
this.counters.hostRejected++;
|
|
9435
|
+
entry.host.counters.rejected++;
|
|
9436
|
+
return ['err', 'Not accepted by the host']
|
|
9437
|
+
}
|
|
9438
|
+
if (entry) {
|
|
9439
|
+
this.counters.hostDenied++;
|
|
9440
|
+
entry.host._denied(remote, tag);
|
|
9441
|
+
if (this.server?.listenerCount?.('host:denied')) this.server.emit('host:denied', remote, tag, entry.host.name);
|
|
9442
|
+
return ['err', 'Tag is reserved by a host']
|
|
9443
|
+
}
|
|
9444
|
+
}
|
|
9065
9445
|
// A device whose policy also covers its publications: each subscriber is checked (see deliveryPolicy.js).
|
|
9066
9446
|
const publisher = cidIndex === 0 && remote.rxPolicy?.filterPublish ? remote : null;
|
|
9067
9447
|
if (cidIndex === 0) {
|
|
@@ -9126,36 +9506,39 @@ class Manager {
|
|
|
9126
9506
|
}
|
|
9127
9507
|
|
|
9128
9508
|
this.counters.publishes++;
|
|
9509
|
+
const sent = this.deliver(tag, message, remote.quota.fanout, publisher);
|
|
9510
|
+
if (sent === null) return ['err', 'No subscriber.']
|
|
9511
|
+
return ['ok', sent]
|
|
9512
|
+
}
|
|
9513
|
+
|
|
9514
|
+
// Sends a SIGNAL to the subscribers of a full channel key ('CH:…', 'CID:…', home channel), at
|
|
9515
|
+
// most fanout (null: all). publisher: a device whose delivery policy filters its publications.
|
|
9516
|
+
// Returns the number sent, or null when the channel has no subscribers.
|
|
9517
|
+
deliver(tag, message, fanout, publisher = null) {
|
|
9518
|
+
const remotes = this.channel_map.get(tag);
|
|
9519
|
+
if (!remotes || remotes.size === 0) return null
|
|
9520
|
+
const limit = fanout === null ? remotes.size : Math.min(fanout, remotes.size);
|
|
9521
|
+
this.counters.quotaExcluded += remotes.size - limit;
|
|
9129
9522
|
let sentCounter = 0;
|
|
9130
|
-
|
|
9131
|
-
|
|
9132
|
-
|
|
9133
|
-
|
|
9134
|
-
|
|
9135
|
-
const limit = fanout === null ? remotes.size : Math.min(fanout, remotes.size);
|
|
9136
|
-
this.counters.quotaExcluded += remotes.size - limit;
|
|
9137
|
-
let peers = remotes.values();
|
|
9138
|
-
while (sentCounter < limit) {
|
|
9139
|
-
let c = peers.next().value;
|
|
9140
|
-
if (!c) {
|
|
9141
|
-
// console.log('## null remote' )
|
|
9142
|
-
break;
|
|
9143
|
-
}
|
|
9144
|
-
if (publisher && !deliveryAllowed(publisher, c)) {
|
|
9145
|
-
this.deliveryDenied(publisher, c, 'publish');
|
|
9146
|
-
continue
|
|
9147
|
-
}
|
|
9148
|
-
// change: from v4.x allow receiveSelfMessages.
|
|
9149
|
-
c.send_enc_mode(message);
|
|
9150
|
-
sentCounter++;
|
|
9151
|
-
}
|
|
9152
|
-
|
|
9153
|
-
this.counters.deliveryAttempts += sentCounter;
|
|
9154
|
-
return ['ok', sentCounter]
|
|
9523
|
+
for (const c of remotes) {
|
|
9524
|
+
if (sentCounter >= limit) break;
|
|
9525
|
+
if (publisher && !deliveryAllowed(publisher, c)) {
|
|
9526
|
+
this.deliveryDenied(publisher, c, 'publish');
|
|
9527
|
+
continue
|
|
9155
9528
|
}
|
|
9529
|
+
// change: from v4.x allow receiveSelfMessages.
|
|
9530
|
+
c.send_enc_mode(message);
|
|
9531
|
+
sentCounter++;
|
|
9156
9532
|
}
|
|
9157
|
-
|
|
9158
|
-
return
|
|
9533
|
+
this.counters.deliveryAttempts += sentCounter;
|
|
9534
|
+
return sentCounter
|
|
9535
|
+
}
|
|
9536
|
+
|
|
9537
|
+
// A host's publication (Host.publish): full channel key, already packed.
|
|
9538
|
+
hostPublish(host, tag, message) {
|
|
9539
|
+
if (tag.includes('$') && this.retainOptions.enabled) this.storeChannelRetain(tag, message, null, host);
|
|
9540
|
+
this.counters.publishes++;
|
|
9541
|
+
return this.deliver(tag, message, host.fanout) ?? 0
|
|
9159
9542
|
}
|
|
9160
9543
|
|
|
9161
9544
|
|
|
@@ -9203,14 +9586,18 @@ class Manager {
|
|
|
9203
9586
|
return owner
|
|
9204
9587
|
}
|
|
9205
9588
|
|
|
9206
|
-
|
|
9207
|
-
|
|
9589
|
+
// host: a Host (server.host) writing its own tag, with its own budget; remote is then null.
|
|
9590
|
+
storeChannelRetain(tag, message, remote, host = null) {
|
|
9591
|
+
const owner = this.retainOwner(host ? host.retainOwnerKey
|
|
9592
|
+
: remote.boho.isAuthorized ? 'cid:' + remote.cid : 'conn:' + remote.ssid);
|
|
9593
|
+
const tagsPerOwner = host?.retainTags ?? this.retainOptions.tagsPerOwner;
|
|
9594
|
+
const bytesPerOwner = host?.retainBytes ?? this.retainOptions.bytesPerOwner;
|
|
9208
9595
|
const old = this.retain_messages.get(tag);
|
|
9209
9596
|
const freed = old?.byteLength ?? 0;
|
|
9210
9597
|
const room = old || (this.retain_messages.size < this.retainOptions.limitCounter &&
|
|
9211
|
-
owner.tags.size <
|
|
9598
|
+
owner.tags.size < tagsPerOwner);
|
|
9212
9599
|
const ownerBytes = owner.bytes - (this.retain_owner.get(tag) === owner ? freed : 0);
|
|
9213
|
-
if (room && this.retainFits(message, freed, ownerBytes,
|
|
9600
|
+
if (room && this.retainFits(message, freed, ownerBytes, bytesPerOwner)) {
|
|
9214
9601
|
if (old) this.releaseChannelRetain(tag, freed);
|
|
9215
9602
|
this.retain_messages.set(tag, this.retainCopy(message));
|
|
9216
9603
|
owner.bytes += message.byteLength;
|
|
@@ -9425,12 +9812,81 @@ class Manager {
|
|
|
9425
9812
|
}
|
|
9426
9813
|
}
|
|
9427
9814
|
|
|
9428
|
-
|
|
9429
|
-
|
|
9430
|
-
|
|
9431
|
-
|
|
9432
|
-
|
|
9433
|
-
|
|
9815
|
+
// Live server telemetry, sampled once a second and shared by every reader (the dashboard, the
|
|
9816
|
+
// monitor service): CPU, event-loop delay and utilisation, memory, connections by transport and
|
|
9817
|
+
// state, send queues of slow peers, and per-second rates of the manager's counters.
|
|
9818
|
+
// `value` holds the latest sample. dispose() stops the timer.
|
|
9819
|
+
class ServerStats {
|
|
9820
|
+
// onSample(value): called after each sample (the dashboard keeps its history from it).
|
|
9821
|
+
constructor(server, { onSample = null } = {}) {
|
|
9822
|
+
this.server = server;
|
|
9823
|
+
this.onSample = onSample;
|
|
9824
|
+
// Traffic counters come from the manager's cumulative counters, counted since this service started.
|
|
9825
|
+
this.base = { ...server.manager.counters };
|
|
9826
|
+
this.counters = { opened: 0, closed: 0, authFailed: 0,
|
|
9827
|
+
...Object.fromEntries(Object.keys(this.base).map(key => [key, 0])) };
|
|
9828
|
+
this.onState = (_peer, _previous) => {
|
|
9829
|
+
if (_peer.state === STATE.OPEN) this.counters.opened++;
|
|
9830
|
+
if (_peer.state === STATE.CLOSED) this.counters.closed++;
|
|
9831
|
+
if (_peer.state === STATE.AUTH_FAIL) this.counters.authFailed++;
|
|
9832
|
+
};
|
|
9833
|
+
server.on('remote:state', this.onState);
|
|
9834
|
+
this.delay = node_perf_hooks.monitorEventLoopDelay({ resolution: 20 }); this.delay.enable();
|
|
9835
|
+
this.cpu = process.cpuUsage(); this.elu = node_perf_hooks.performance.eventLoopUtilization();
|
|
9836
|
+
this.previousAt = node_perf_hooks.performance.now(); this.previous = { ...this.counters };
|
|
9837
|
+
this.sample();
|
|
9838
|
+
this.timer = setInterval(() => this.sample(), 1000); this.timer.unref();
|
|
9839
|
+
}
|
|
9840
|
+
sample() {
|
|
9841
|
+
const now = node_perf_hooks.performance.now(), elapsed = Math.max(1, now - this.previousAt);
|
|
9842
|
+
for (const key in this.base) this.counters[key] = this.server.manager.counters[key] - this.base[key];
|
|
9843
|
+
let authenticated = 0, websocket = 0, queuedBytes = 0, maxQueuedBytes = 0;
|
|
9844
|
+
let txQueuePeakBytes = 0, txWriteFalseCount = 0, txDrainMaxMs = 0;
|
|
9845
|
+
let txBlockedConnections = 0, txBlockedMaxMs = 0;
|
|
9846
|
+
const states = {};
|
|
9847
|
+
const transports = { websocket: { total: 0, authenticated: 0 }, tcp: { total: 0, authenticated: 0 } };
|
|
9848
|
+
for (const peer of this.server.manager.remotes) {
|
|
9849
|
+
const transport = transports[peer.socketType === 'websocket' ? 'websocket' : 'tcp']; transport.total++;
|
|
9850
|
+
if (peer.boho.isAuthorized) { authenticated++; transport.authenticated++; }
|
|
9851
|
+
if (peer.socketType === 'websocket') websocket++;
|
|
9852
|
+
const queued = peer.socket.bufferedAmount ?? peer.socket.writableLength ?? 0;
|
|
9853
|
+
queuedBytes += queued; maxQueuedBytes = Math.max(maxQueuedBytes, queued);
|
|
9854
|
+
txQueuePeakBytes = Math.max(txQueuePeakBytes, peer.txQueuePeakBytes ?? 0);
|
|
9855
|
+
txWriteFalseCount += peer.txWriteFalseCount ?? 0;
|
|
9856
|
+
txDrainMaxMs = Math.max(txDrainMaxMs, peer.txDrainMaxMs ?? 0);
|
|
9857
|
+
if (peer.txBlockedSince != null) {
|
|
9858
|
+
txBlockedConnections++;
|
|
9859
|
+
txBlockedMaxMs = Math.max(txBlockedMaxMs, now - peer.txBlockedSince);
|
|
9860
|
+
}
|
|
9861
|
+
const name = peer.getStateName(); states[name] = (states[name] || 0) + 1;
|
|
9862
|
+
}
|
|
9863
|
+
const rates = Object.fromEntries(Object.entries(this.counters).map(([key, value]) => [key, (value - this.previous[key]) * 1000 / elapsed]));
|
|
9864
|
+
const cpu = process.cpuUsage(), elu = node_perf_hooks.performance.eventLoopUtilization();
|
|
9865
|
+
const delta = node_perf_hooks.performance.eventLoopUtilization(elu, this.elu);
|
|
9866
|
+
const mem = process.memoryUsage(), total = this.server.manager.remotes.size;
|
|
9867
|
+
let hostAvailableBytes = null;
|
|
9868
|
+
if (process.platform === 'linux') {
|
|
9869
|
+
try { const match = node_fs.readFileSync('/proc/meminfo', 'utf8').match(/^MemAvailable:\s+(\d+) kB/m); if (match) hostAvailableBytes = Number(match[1]) * 1024; }
|
|
9870
|
+
catch { /* Optional host telemetry must not interrupt service. */ }
|
|
9871
|
+
}
|
|
9872
|
+
this.value = { at: Date.now(), total, authenticated, anonymous: total - authenticated, websocket,
|
|
9873
|
+
transports, hostAvailableBytes, hostTotalBytes: node_os.totalmem(), channels: this.server.manager.channel_map.size, states, queuedBytes, maxQueuedBytes,
|
|
9874
|
+
txQueuePeakBytes, txWriteFalseCount, txDrainMaxMs, txBlockedConnections, txBlockedMaxMs,
|
|
9875
|
+
counters: { ...this.counters }, rates, rss: mem.rss, heapUsed: mem.heapUsed,
|
|
9876
|
+
cpuPercent: ((cpu.user - this.cpu.user) + (cpu.system - this.cpu.system)) / (elapsed * 10),
|
|
9877
|
+
eventLoopUtilization: delta.utilization,
|
|
9878
|
+
eventLoopP99Ms: this.delay.percentile(99) / 1e6,
|
|
9879
|
+
// anonymous: profile name of unauthenticated connections; profiles: the server's quotas now.
|
|
9880
|
+
quota: { anonymous: this.server.anonymousQuota, profiles: structuredClone(this.server.quotas) } };
|
|
9881
|
+
this.previousAt = now; this.previous = { ...this.counters }; this.cpu = cpu; this.elu = elu; this.delay.reset();
|
|
9882
|
+
if (this.onSample) {
|
|
9883
|
+
try { this.onSample(this.value); } catch (error) { console.error('server stats reader error:', error); }
|
|
9884
|
+
}
|
|
9885
|
+
}
|
|
9886
|
+
dispose() {
|
|
9887
|
+
clearInterval(this.timer); this.delay.disable(); this.server.off('remote:state', this.onState);
|
|
9888
|
+
}
|
|
9889
|
+
}
|
|
9434
9890
|
|
|
9435
9891
|
const decoder = new TextDecoder();
|
|
9436
9892
|
const DUPLICATE_LOGIN_POLICIES = ['keepOld', 'keepNew'];
|
|
@@ -9735,6 +10191,718 @@ class BohoAuth {
|
|
|
9735
10191
|
|
|
9736
10192
|
}
|
|
9737
10193
|
|
|
10194
|
+
// The dashboard web page, kept as a string so it ships inside the package (no CDN, works offline).
|
|
10195
|
+
// No backticks or template placeholders inside: the page is plain HTML, CSS and ES5-ish JavaScript.
|
|
10196
|
+
const PAGE = String.raw`<!doctype html>
|
|
10197
|
+
<html lang="ko">
|
|
10198
|
+
<head>
|
|
10199
|
+
<meta charset="utf-8">
|
|
10200
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
10201
|
+
<title>IOSignal Dashboard</title>
|
|
10202
|
+
<style>
|
|
10203
|
+
:root {
|
|
10204
|
+
--bg: #f3f5fa; --panel: #ffffff; --ink: #172036; --muted: #5f6a85; --line: #dde3ef; --grid: #e9edf5;
|
|
10205
|
+
--a: #0ea5a0; --b: #4f6bed; --c: #f59e0b; --d: #e5484d; --e: #8b5cf6; --ok: #22b573;
|
|
10206
|
+
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
|
10207
|
+
--sans: system-ui, -apple-system, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif;
|
|
10208
|
+
color-scheme: light;
|
|
10209
|
+
}
|
|
10210
|
+
@media (prefers-color-scheme: dark) {
|
|
10211
|
+
:root { --bg: #0d1220; --panel: #151c30; --ink: #e6ebf7; --muted: #8e99b8; --line: #263050; --grid: #1d2640;
|
|
10212
|
+
--a: #2dd4bf; --b: #7c93ff; --c: #fbbf24; --d: #ff6b6b; --e: #a78bfa; --ok: #34d399; color-scheme: dark; }
|
|
10213
|
+
}
|
|
10214
|
+
* { box-sizing: border-box; }
|
|
10215
|
+
body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.5 var(--sans); }
|
|
10216
|
+
header { position: sticky; top: 0; z-index: 5; display: flex; flex-wrap: wrap; gap: 10px 16px; align-items: center;
|
|
10217
|
+
padding: 10px max(16px, env(safe-area-inset-left)); background: color-mix(in srgb, var(--bg) 88%, transparent);
|
|
10218
|
+
backdrop-filter: blur(8px); border-bottom: 1px solid var(--line); }
|
|
10219
|
+
h1 { font-size: 16px; margin: 0; letter-spacing: .01em; }
|
|
10220
|
+
h1 b { color: var(--a); }
|
|
10221
|
+
.pill { font: 600 12px var(--mono); padding: 3px 10px; border-radius: 99px; background: var(--grid); color: var(--muted); }
|
|
10222
|
+
.pill.live { background: color-mix(in srgb, var(--ok) 18%, transparent); color: var(--ok); }
|
|
10223
|
+
.pill.live::before { content: ""; display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--ok); margin-right: 6px; animation: blink 1.2s infinite; }
|
|
10224
|
+
.pill.bad { background: color-mix(in srgb, var(--d) 18%, transparent); color: var(--d); }
|
|
10225
|
+
@keyframes blink { 50% { opacity: .25; } }
|
|
10226
|
+
.meta { font: 12px var(--mono); color: var(--muted); }
|
|
10227
|
+
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin-left: auto; }
|
|
10228
|
+
.chip { font: 600 12px var(--sans); border: 1px solid var(--line); background: var(--panel); color: var(--muted); border-radius: 99px; padding: 4px 11px; cursor: pointer; }
|
|
10229
|
+
.chip[aria-pressed="true"] { background: var(--ink); color: var(--panel); border-color: var(--ink); }
|
|
10230
|
+
.chip:focus-visible, button:focus-visible, input:focus-visible { outline: 2px solid var(--a); outline-offset: 2px; }
|
|
10231
|
+
main { padding: 16px max(16px, env(safe-area-inset-left)) 40px; display: grid; gap: 14px; grid-template-columns: repeat(12, minmax(0, 1fr)); }
|
|
10232
|
+
section.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px; min-width: 0; display: grid; gap: 10px; align-content: start; }
|
|
10233
|
+
section.panel h2 { font-size: 13px; margin: 0; color: var(--muted); font-weight: 700; letter-spacing: .06em; text-transform: uppercase; display: flex; gap: 8px; align-items: baseline; }
|
|
10234
|
+
section.panel h2 small { text-transform: none; letter-spacing: 0; font-weight: 500; font-family: var(--mono); }
|
|
10235
|
+
.w12 { grid-column: span 12; } .w8 { grid-column: span 8; } .w6 { grid-column: span 6; } .w4 { grid-column: span 4; }
|
|
10236
|
+
@media (max-width: 1100px) { .w8, .w4 { grid-column: span 12; } .w6 { grid-column: span 12; } }
|
|
10237
|
+
.gauges { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; }
|
|
10238
|
+
@media (max-width: 640px) { .gauges { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
|
10239
|
+
.gauge { display: grid; justify-items: center; gap: 2px; }
|
|
10240
|
+
.gauge canvas { width: 100%; max-width: 150px; aspect-ratio: 1.45; }
|
|
10241
|
+
.gauge span { font-size: 12px; color: var(--muted); }
|
|
10242
|
+
canvas.chart { width: 100%; height: 150px; display: block; }
|
|
10243
|
+
canvas.chart.tall { height: 190px; }
|
|
10244
|
+
.legend { display: flex; flex-wrap: wrap; gap: 12px; font: 12px var(--mono); color: var(--muted); }
|
|
10245
|
+
.legend i { display: inline-block; width: 10px; height: 3px; border-radius: 2px; margin-right: 5px; vertical-align: middle; }
|
|
10246
|
+
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(118px, 1fr)); gap: 8px; }
|
|
10247
|
+
.stat { border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px; display: grid; gap: 2px; }
|
|
10248
|
+
.stat b { font: 700 20px var(--mono); font-variant-numeric: tabular-nums; }
|
|
10249
|
+
.stat span { font-size: 12px; color: var(--muted); }
|
|
10250
|
+
.stat.flash { animation: flash .8s ease-out; }
|
|
10251
|
+
@keyframes flash { from { background: color-mix(in srgb, var(--d) 30%, transparent); } }
|
|
10252
|
+
.hosts { display: grid; grid-template-columns: repeat(auto-fit, minmax(270px, 1fr)); gap: 12px; }
|
|
10253
|
+
.host { border: 1px solid var(--line); border-radius: 12px; padding: 12px; display: grid; gap: 8px; position: relative; overflow: hidden; }
|
|
10254
|
+
.host header { all: unset; display: flex; align-items: center; gap: 8px; }
|
|
10255
|
+
.host h3 { margin: 0; font: 700 15px var(--mono); }
|
|
10256
|
+
.pulse { width: 12px; height: 12px; border-radius: 50%; background: var(--a); box-shadow: 0 0 0 0 color-mix(in srgb, var(--a) 60%, transparent); }
|
|
10257
|
+
.host .big { font: 800 30px var(--mono); line-height: 1; font-variant-numeric: tabular-nums; }
|
|
10258
|
+
.host .row { display: flex; flex-wrap: wrap; gap: 4px 14px; font: 12px var(--mono); color: var(--muted); }
|
|
10259
|
+
.host .row b { color: var(--ink); font-weight: 600; }
|
|
10260
|
+
.host canvas { width: 100%; height: 56px; display: block; }
|
|
10261
|
+
.shield { position: absolute; right: 10px; top: 10px; font: 700 11px var(--mono); color: var(--d); opacity: 0; transition: opacity .3s; }
|
|
10262
|
+
.shield.on { opacity: 1; }
|
|
10263
|
+
.loop { display: grid; gap: 6px; }
|
|
10264
|
+
.bar { height: 10px; border-radius: 6px; background: var(--grid); position: relative; overflow: hidden; }
|
|
10265
|
+
.bar > i { position: absolute; inset: 0 auto 0 0; border-radius: 6px; background: var(--a); transition: width .4s; }
|
|
10266
|
+
.bar > em { position: absolute; top: -2px; bottom: -2px; width: 2px; background: var(--ink); opacity: .6; }
|
|
10267
|
+
.kv { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 6px; }
|
|
10268
|
+
.kv div { background: var(--grid); border-radius: 8px; padding: 6px 9px; display: grid; }
|
|
10269
|
+
.kv span { font-size: 11px; color: var(--muted); } .kv b { font: 700 16px var(--mono); overflow-wrap: anywhere; }
|
|
10270
|
+
.table { overflow-x: auto; }
|
|
10271
|
+
table { border-collapse: collapse; width: 100%; font: 12.5px var(--mono); }
|
|
10272
|
+
th, td { padding: 6px 8px; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; }
|
|
10273
|
+
th { color: var(--muted); font-weight: 600; font-family: var(--sans); }
|
|
10274
|
+
.act { display: inline-block; height: 8px; border-radius: 4px; background: var(--b); vertical-align: middle; min-width: 2px; }
|
|
10275
|
+
.badge { font-size: 11px; padding: 1px 6px; border-radius: 6px; background: var(--grid); color: var(--muted); }
|
|
10276
|
+
.badge.auth { background: color-mix(in srgb, var(--ok) 20%, transparent); color: var(--ok); }
|
|
10277
|
+
.events { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; max-height: 340px; overflow: auto; font: 12.5px var(--mono); }
|
|
10278
|
+
.events li { display: flex; gap: 8px; align-items: baseline; padding: 4px 6px; border-radius: 6px; animation: slide .5s ease-out; }
|
|
10279
|
+
@keyframes slide { from { background: color-mix(in srgb, var(--a) 22%, transparent); transform: translateX(-6px); } }
|
|
10280
|
+
.events time { color: var(--muted); }
|
|
10281
|
+
.k { font: 700 11px var(--sans); padding: 1px 7px; border-radius: 6px; }
|
|
10282
|
+
.k.join { background: color-mix(in srgb, var(--ok) 22%, transparent); color: var(--ok); }
|
|
10283
|
+
.k.leave { background: var(--grid); color: var(--muted); }
|
|
10284
|
+
.k.denied { background: color-mix(in srgb, var(--d) 22%, transparent); color: var(--d); }
|
|
10285
|
+
.k.error { background: color-mix(in srgb, var(--c) 25%, transparent); color: var(--c); }
|
|
10286
|
+
.empty { color: var(--muted); font-size: 13px; padding: 6px 0; }
|
|
10287
|
+
.overlay { position: fixed; inset: 0; z-index: 10; display: grid; place-items: center; background: color-mix(in srgb, var(--bg) 80%, transparent); backdrop-filter: blur(6px); padding: 16px; }
|
|
10288
|
+
.overlay form { background: var(--panel); border: 1px solid var(--line); border-radius: 16px; padding: 20px; width: min(360px, 100%); display: grid; gap: 10px; box-shadow: 0 20px 50px rgba(0,0,0,.2); }
|
|
10289
|
+
.overlay h2 { margin: 0; font-size: 18px; }
|
|
10290
|
+
.overlay input { padding: 9px 11px; border-radius: 9px; border: 1px solid var(--line); background: var(--bg); color: var(--ink); font: 14px var(--mono); }
|
|
10291
|
+
.overlay button { padding: 10px; border: 0; border-radius: 10px; background: var(--a); color: #fff; font-weight: 700; cursor: pointer; }
|
|
10292
|
+
.overlay p { margin: 0; color: var(--muted); font-size: 13px; }
|
|
10293
|
+
.overlay .err { color: var(--d); }
|
|
10294
|
+
[hidden] { display: none !important; }
|
|
10295
|
+
@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }
|
|
10296
|
+
</style>
|
|
10297
|
+
</head>
|
|
10298
|
+
<body>
|
|
10299
|
+
<header>
|
|
10300
|
+
<h1><b>IOSignal</b> Dashboard</h1>
|
|
10301
|
+
<span id="status" class="pill">연결 중</span>
|
|
10302
|
+
<span id="meta" class="meta"></span>
|
|
10303
|
+
<nav class="chips" id="chips" aria-label="패널"></nav>
|
|
10304
|
+
</header>
|
|
10305
|
+
<main id="main">
|
|
10306
|
+
<section class="panel w12" data-panel="server">
|
|
10307
|
+
<h2>서버 <small id="uptime"></small></h2>
|
|
10308
|
+
<div class="gauges">
|
|
10309
|
+
<div class="gauge"><canvas id="gCpu"></canvas><span>CPU</span></div>
|
|
10310
|
+
<div class="gauge"><canvas id="gEld"></canvas><span>이벤트 루프 지연 p99</span></div>
|
|
10311
|
+
<div class="gauge"><canvas id="gElu"></canvas><span>이벤트 루프 사용률</span></div>
|
|
10312
|
+
<div class="gauge"><canvas id="gMem"></canvas><span>메모리 (RSS)</span></div>
|
|
10313
|
+
</div>
|
|
10314
|
+
<canvas class="chart" id="cLoad"></canvas>
|
|
10315
|
+
<div class="legend"><span><i style="background:var(--a)"></i>CPU %</span><span><i style="background:var(--c)"></i>지연 p99 ms</span><span><i style="background:var(--e)"></i>연결 수</span></div>
|
|
10316
|
+
<div class="stats" id="sConn"></div>
|
|
10317
|
+
</section>
|
|
10318
|
+
<section class="panel w8" data-panel="traffic">
|
|
10319
|
+
<h2>트래픽 <small>초당</small></h2>
|
|
10320
|
+
<canvas class="chart tall" id="cMsg"></canvas>
|
|
10321
|
+
<div class="legend"><span><i style="background:var(--b)"></i>받은 메시지</span><span><i style="background:var(--a)"></i>보낸 메시지</span><span><i style="background:var(--d)"></i>버린 메시지(쿼터)</span></div>
|
|
10322
|
+
<canvas class="chart" id="cBytes"></canvas>
|
|
10323
|
+
<div class="legend"><span><i style="background:var(--b)"></i>받은 바이트</span><span><i style="background:var(--a)"></i>보낸 바이트</span></div>
|
|
10324
|
+
</section>
|
|
10325
|
+
<section class="panel w4" data-panel="traffic">
|
|
10326
|
+
<h2>전송 상태</h2>
|
|
10327
|
+
<div class="stats" id="sTraffic"></div>
|
|
10328
|
+
</section>
|
|
10329
|
+
<section class="panel w12" data-panel="hosts">
|
|
10330
|
+
<h2>호스트 <small id="hostCount"></small></h2>
|
|
10331
|
+
<div class="hosts" id="hosts"></div>
|
|
10332
|
+
</section>
|
|
10333
|
+
<section class="panel w6" data-panel="game">
|
|
10334
|
+
<h2>게임 루프</h2>
|
|
10335
|
+
<div id="game" class="loop"></div>
|
|
10336
|
+
</section>
|
|
10337
|
+
<section class="panel w6" data-panel="events">
|
|
10338
|
+
<h2>이벤트 <small>입장 · 퇴장 · 위조 차단 · 오류</small></h2>
|
|
10339
|
+
<ul class="events" id="events"></ul>
|
|
10340
|
+
</section>
|
|
10341
|
+
<section class="panel w12" data-panel="participants">
|
|
10342
|
+
<h2>참가자</h2>
|
|
10343
|
+
<div class="table" id="players"></div>
|
|
10344
|
+
</section>
|
|
10345
|
+
</main>
|
|
10346
|
+
|
|
10347
|
+
<div class="overlay" id="gate" hidden>
|
|
10348
|
+
<form id="gateForm">
|
|
10349
|
+
<h2 id="gateTitle">대시보드 로그인</h2>
|
|
10350
|
+
<p id="gateHelp"></p>
|
|
10351
|
+
<input id="gateId" placeholder="ID" autocomplete="username">
|
|
10352
|
+
<input id="gateKey" type="password" placeholder="키" autocomplete="current-password">
|
|
10353
|
+
<p id="gateErr" class="err" hidden></p>
|
|
10354
|
+
<button type="submit">보기</button>
|
|
10355
|
+
</form>
|
|
10356
|
+
</div>
|
|
10357
|
+
|
|
10358
|
+
<script>var CONFIG = __CONFIG__;</script>
|
|
10359
|
+
<script src="__IO__"></script>
|
|
10360
|
+
<script>
|
|
10361
|
+
(function () {
|
|
10362
|
+
"use strict";
|
|
10363
|
+
var $ = function (id) { return document.getElementById(id); };
|
|
10364
|
+
var css = function (name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); };
|
|
10365
|
+
var store = { get: function (k) { try { return localStorage.getItem(k); } catch (e) { return null; } },
|
|
10366
|
+
set: function (k, v) { try { localStorage.setItem(k, v); } catch (e) {} },
|
|
10367
|
+
sget: function (k) { try { return sessionStorage.getItem(k); } catch (e) { return null; } },
|
|
10368
|
+
sset: function (k, v) { try { sessionStorage.setItem(k, v); } catch (e) {} } };
|
|
10369
|
+
var esc = function (s) { return String(s == null ? "" : s).replace(/[&<>"]/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """ }[c]; }); };
|
|
10370
|
+
var fmtB = function (n) { n = n || 0; return n >= 1048576 ? (n / 1048576).toFixed(1) + " MB" : n >= 1024 ? (n / 1024).toFixed(1) + " KB" : Math.round(n) + " B"; };
|
|
10371
|
+
var fmtN = function (n) { n = n || 0; return n >= 10000 ? (n / 1000).toFixed(1) + "k" : n >= 100 ? Math.round(n) + "" : (Math.round(n * 10) / 10) + ""; };
|
|
10372
|
+
var fmtT = function (ms) { var s = Math.floor(ms / 1000), h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60); return (h ? h + "시간 " : "") + m + "분 " + (s % 60) + "초"; };
|
|
10373
|
+
|
|
10374
|
+
// ------------------------------------------------ panels the viewer turns on and off
|
|
10375
|
+
var NAMES = { server: "서버", traffic: "트래픽", hosts: "호스트", game: "게임 루프", participants: "참가자", events: "이벤트" };
|
|
10376
|
+
var saved = store.get("iosignal.dashboard.panels");
|
|
10377
|
+
var shown = saved ? saved.split(",") : CONFIG.panels.slice();
|
|
10378
|
+
function applyPanels() {
|
|
10379
|
+
var nodes = document.querySelectorAll("[data-panel]");
|
|
10380
|
+
for (var i = 0; i < nodes.length; i++) nodes[i].hidden = shown.indexOf(nodes[i].getAttribute("data-panel")) < 0;
|
|
10381
|
+
var chips = $("chips").children;
|
|
10382
|
+
for (var j = 0; j < chips.length; j++) chips[j].setAttribute("aria-pressed", String(shown.indexOf(chips[j].getAttribute("data-p")) >= 0));
|
|
10383
|
+
store.set("iosignal.dashboard.panels", shown.join(","));
|
|
10384
|
+
draw();
|
|
10385
|
+
}
|
|
10386
|
+
Object.keys(NAMES).forEach(function (p) {
|
|
10387
|
+
var b = document.createElement("button");
|
|
10388
|
+
b.className = "chip"; b.type = "button"; b.textContent = NAMES[p]; b.setAttribute("data-p", p);
|
|
10389
|
+
b.onclick = function () { var i = shown.indexOf(p); if (i >= 0) shown.splice(i, 1); else shown.push(p); applyPanels(); };
|
|
10390
|
+
$("chips").appendChild(b);
|
|
10391
|
+
});
|
|
10392
|
+
|
|
10393
|
+
// ------------------------------------------------ state
|
|
10394
|
+
var series = [], latest = null, hosts = [], events = [], info = null, startedAt = 0, hostHist = {};
|
|
10395
|
+
var pulses = {};
|
|
10396
|
+
|
|
10397
|
+
// ------------------------------------------------ canvas helpers
|
|
10398
|
+
function fit(cv) {
|
|
10399
|
+
var r = cv.getBoundingClientRect(), d = Math.min(2, window.devicePixelRatio || 1);
|
|
10400
|
+
var w = Math.max(10, Math.round(r.width * d)), h = Math.max(10, Math.round(r.height * d));
|
|
10401
|
+
if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; }
|
|
10402
|
+
var c = cv.getContext("2d"); c.setTransform(d, 0, 0, d, 0, 0);
|
|
10403
|
+
return { c: c, w: r.width, h: r.height };
|
|
10404
|
+
}
|
|
10405
|
+
// Lines over time with a soft area under the first one. lines: [{ values, color, scale? }]
|
|
10406
|
+
function chart(cv, lines, opts) {
|
|
10407
|
+
if (!cv.offsetParent) return;
|
|
10408
|
+
var f = fit(cv), c = f.c, w = f.w, h = f.h, pad = { l: 58, r: 12, t: 8, b: 18 };
|
|
10409
|
+
c.clearRect(0, 0, w, h);
|
|
10410
|
+
var max = (opts && opts.max) || 1;
|
|
10411
|
+
lines.forEach(function (l) { if (!l.own) l.values.forEach(function (v) { if (v > max) max = v; }); });
|
|
10412
|
+
max = niceMax(max);
|
|
10413
|
+
var n = Math.max(2, CONFIG.history), x0 = pad.l, x1 = w - pad.r, y0 = h - pad.b, y1 = pad.t;
|
|
10414
|
+
c.strokeStyle = css("--grid"); c.lineWidth = 1; c.fillStyle = css("--muted"); c.font = "11px " + css("--mono"); c.textAlign = "right";
|
|
10415
|
+
for (var g = 0; g <= 3; g++) {
|
|
10416
|
+
var y = y0 - (y0 - y1) * g / 3;
|
|
10417
|
+
c.beginPath(); c.moveTo(x0, y); c.lineTo(x1, y); c.stroke();
|
|
10418
|
+
c.fillText((opts && opts.fmt ? opts.fmt(max * g / 3) : fmtN(max * g / 3)), x0 - 6, y + 4);
|
|
10419
|
+
}
|
|
10420
|
+
c.textAlign = "left"; c.fillText("-" + Math.round(n / 60) + "분", x0, h - 3); c.textAlign = "right"; c.fillText("지금", x1, h - 3);
|
|
10421
|
+
lines.forEach(function (l, li) {
|
|
10422
|
+
var v = l.values, m = l.own ? niceMax(Math.max.apply(null, v.concat([1]))) : max;
|
|
10423
|
+
if (!v.length) return;
|
|
10424
|
+
var X = function (i) { return x1 - (v.length - 1 - i) * (x1 - x0) / (n - 1); };
|
|
10425
|
+
var Y = function (val) { return y0 - (y0 - y1) * Math.min(1, (val || 0) / m); };
|
|
10426
|
+
c.beginPath();
|
|
10427
|
+
for (var i = 0; i < v.length; i++) { var px = X(i), py = Y(v[i]); if (i) c.lineTo(px, py); else c.moveTo(px, py); }
|
|
10428
|
+
c.strokeStyle = css(l.color); c.lineWidth = 2; c.lineJoin = "round"; c.stroke();
|
|
10429
|
+
if (li === 0) {
|
|
10430
|
+
c.lineTo(X(v.length - 1), y0); c.lineTo(X(0), y0); c.closePath();
|
|
10431
|
+
var grad = c.createLinearGradient(0, y1, 0, y0);
|
|
10432
|
+
grad.addColorStop(0, hexA(css(l.color), 0.28)); grad.addColorStop(1, hexA(css(l.color), 0));
|
|
10433
|
+
c.fillStyle = grad; c.fill();
|
|
10434
|
+
}
|
|
10435
|
+
var lx = X(v.length - 1), ly = Y(v[v.length - 1]);
|
|
10436
|
+
c.fillStyle = css(l.color); c.beginPath(); c.arc(lx, ly, 3.5, 0, 6.3); c.fill();
|
|
10437
|
+
});
|
|
10438
|
+
}
|
|
10439
|
+
function niceMax(v) { var p = Math.pow(10, Math.floor(Math.log10(Math.max(v, 1e-9)))); var m = v / p; return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p; }
|
|
10440
|
+
function hexA(col, a) {
|
|
10441
|
+
if (col.charAt(0) === "#") { var n = parseInt(col.slice(1), 16); return "rgba(" + (n >> 16) + "," + ((n >> 8) & 255) + "," + (n & 255) + "," + a + ")"; }
|
|
10442
|
+
return col;
|
|
10443
|
+
}
|
|
10444
|
+
// Half-ring gauge with an animated needle value.
|
|
10445
|
+
var gaugeNow = {};
|
|
10446
|
+
function gauge(id, value, max, label, color) {
|
|
10447
|
+
var cv = $(id); if (!cv.offsetParent) return;
|
|
10448
|
+
var cur = gaugeNow[id] == null ? value : gaugeNow[id] + (value - gaugeNow[id]) * 0.18;
|
|
10449
|
+
gaugeNow[id] = cur;
|
|
10450
|
+
var f = fit(cv), c = f.c, w = f.w, h = f.h, r = Math.min(w / 2, h) * 0.86, cx = w / 2, cy = h * 0.9;
|
|
10451
|
+
c.clearRect(0, 0, w, h);
|
|
10452
|
+
c.lineCap = "round"; c.lineWidth = r * 0.17;
|
|
10453
|
+
c.strokeStyle = css("--grid"); c.beginPath(); c.arc(cx, cy, r, Math.PI, 2 * Math.PI); c.stroke();
|
|
10454
|
+
var frac = Math.max(0, Math.min(1, cur / max));
|
|
10455
|
+
var col = frac > 0.85 ? css("--d") : frac > 0.6 ? css("--c") : css(color);
|
|
10456
|
+
c.strokeStyle = col; c.beginPath(); c.arc(cx, cy, r, Math.PI, Math.PI + Math.PI * Math.max(0.01, frac)); c.stroke();
|
|
10457
|
+
c.fillStyle = css("--ink"); c.textAlign = "center"; c.font = "700 " + Math.round(r * 0.36) + "px " + css("--mono");
|
|
10458
|
+
c.fillText(label(cur), cx, cy - r * 0.2);
|
|
10459
|
+
}
|
|
10460
|
+
function spark(cv, values, color) {
|
|
10461
|
+
if (!cv.offsetParent) return;
|
|
10462
|
+
var f = fit(cv), c = f.c, w = f.w, h = f.h; c.clearRect(0, 0, w, h);
|
|
10463
|
+
if (!values.length) return;
|
|
10464
|
+
var m = niceMax(Math.max.apply(null, values.concat([1]))), n = 60;
|
|
10465
|
+
c.beginPath();
|
|
10466
|
+
for (var i = 0; i < values.length; i++) {
|
|
10467
|
+
var x = w - (values.length - 1 - i) * w / (n - 1), y = h - 3 - (h - 6) * values[i] / m;
|
|
10468
|
+
if (i) c.lineTo(x, y); else c.moveTo(x, y);
|
|
10469
|
+
}
|
|
10470
|
+
c.strokeStyle = css(color); c.lineWidth = 1.8; c.stroke();
|
|
10471
|
+
c.lineTo(w, h); c.lineTo(w - (values.length - 1) * w / (n - 1), h); c.closePath();
|
|
10472
|
+
c.fillStyle = hexA(css(color), 0.18); c.fill();
|
|
10473
|
+
}
|
|
10474
|
+
|
|
10475
|
+
// ------------------------------------------------ render
|
|
10476
|
+
function stat(label, value, flash) { return '<div class="stat' + (flash ? " flash" : "") + '"><b>' + value + "</b><span>" + label + "</span></div>"; }
|
|
10477
|
+
var prevDropped = 0, prevDenied = {};
|
|
10478
|
+
function render() {
|
|
10479
|
+
if (!latest) return;
|
|
10480
|
+
var p = latest.point, s = latest.server;
|
|
10481
|
+
$("uptime").textContent = "가동 " + fmtT(s.uptime);
|
|
10482
|
+
$("meta").textContent = "시청 " + s.own.viewers + "명" + (info ? " · Node " + info.node : "");
|
|
10483
|
+
$("sConn").innerHTML = stat("연결", p.conns) + stat("WebSocket", p.ws) + stat("TCP (보드)", p.tcp) + stat("로그인", p.auth) + stat("채널", s.channels);
|
|
10484
|
+
var dropped = s.counters.rateLimited + s.counters.oversizeRejected;
|
|
10485
|
+
$("sTraffic").innerHTML = stat("버린 메시지 (누적)", fmtN(dropped), dropped > prevDropped) +
|
|
10486
|
+
stat("느린 연결", s.txBlockedConnections) + stat("밀린 송신", fmtB(s.queuedBytes)) +
|
|
10487
|
+
stat("가장 많이 밀린 연결", fmtB(s.maxQueuedBytes)) + stat("수신 버퍼 초과로 안 보냄", fmtN(s.counters.peerRxLimitSkipped));
|
|
10488
|
+
prevDropped = dropped;
|
|
10489
|
+
renderHosts();
|
|
10490
|
+
renderGame();
|
|
10491
|
+
renderPlayers();
|
|
10492
|
+
}
|
|
10493
|
+
function renderHosts() {
|
|
10494
|
+
$("hostCount").textContent = hosts.length ? hosts.length + "개" : "";
|
|
10495
|
+
if (!hosts.length) { $("hosts").innerHTML = '<p class="empty">등록된 호스트가 없습니다. server.host()로 게임을 올리면 여기에 나옵니다.</p>'; return; }
|
|
10496
|
+
var box = $("hosts");
|
|
10497
|
+
hosts.forEach(function (h) {
|
|
10498
|
+
var el = box.querySelector('[data-host="' + CSS.escape(h.name) + '"]');
|
|
10499
|
+
if (!el) {
|
|
10500
|
+
el = document.createElement("div"); el.className = "host"; el.setAttribute("data-host", h.name);
|
|
10501
|
+
el.innerHTML = '<header><span class="pulse"></span><h3></h3></header><span class="shield">위조 차단!</span>' +
|
|
10502
|
+
'<div><span class="big"></span> <span class="meta">참가자</span></div><canvas></canvas><div class="row"></div>';
|
|
10503
|
+
el.querySelector("h3").textContent = h.name;
|
|
10504
|
+
box.appendChild(el);
|
|
10505
|
+
}
|
|
10506
|
+
el.querySelector(".big").textContent = h.participants;
|
|
10507
|
+
var r = h.rates;
|
|
10508
|
+
el.querySelector(".row").innerHTML = "<span>입력 <b>" + fmtN(r.inbound) + "/s</b></span><span>방송 <b>" + fmtN(r.published) + "/s</b></span>" +
|
|
10509
|
+
"<span>1:1 <b>" + fmtN(r.sent) + "/s</b></span><span>처리 <b>" + h.handlerAvgMs.toFixed(2) + "ms</b> (최대 " + h.handlerMaxMs.toFixed(1) + ")</span>" +
|
|
10510
|
+
"<span>차단 <b>" + h.totals.denied + "</b></span><span>오류 <b>" + h.totals.errors + "</b></span>";
|
|
10511
|
+
var shield = el.querySelector(".shield");
|
|
10512
|
+
if ((prevDenied[h.name] || 0) < h.totals.denied) { shield.classList.add("on"); setTimeout(function () { shield.classList.remove("on"); }, 1500); }
|
|
10513
|
+
prevDenied[h.name] = h.totals.denied;
|
|
10514
|
+
pulses[h.name] = r.inbound;
|
|
10515
|
+
spark(el.querySelector("canvas"), (hostHist[h.name] || []).map(function (x) { return x.in || 0; }), "--a");
|
|
10516
|
+
});
|
|
10517
|
+
Array.prototype.slice.call(box.children).forEach(function (el) {
|
|
10518
|
+
if (!hosts.some(function (h) { return h.name === el.getAttribute("data-host"); })) el.remove();
|
|
10519
|
+
});
|
|
10520
|
+
}
|
|
10521
|
+
function renderGame() {
|
|
10522
|
+
if (!hosts.length) { $("game").innerHTML = '<p class="empty">호스트가 없습니다.</p>'; return; }
|
|
10523
|
+
var html = "";
|
|
10524
|
+
hosts.forEach(function (h) {
|
|
10525
|
+
html += '<div><b style="font-family:var(--mono)">' + esc(h.name) + "</b></div>";
|
|
10526
|
+
if (!h.loops.length) html += '<p class="empty">host.loop(ms, fn)를 쓰면 틱 간격과 처리 시간이 여기에 나옵니다.</p>';
|
|
10527
|
+
h.loops.forEach(function (l) {
|
|
10528
|
+
var scale = l.intervalMs * 2, gap = Math.min(1, l.gapP99 / scale), target = l.intervalMs / scale;
|
|
10529
|
+
html += '<div class="row" style="display:flex;gap:12px;font:12px var(--mono);color:var(--muted)"><span>목표 <b style="color:var(--ink)">' + l.intervalMs + 'ms</b></span><span>틱 간격 p50 <b style="color:var(--ink)">' + l.gapP50.toFixed(1) + '</b> · p99 <b style="color:var(--ink)">' + l.gapP99.toFixed(1) + '</b></span><span>처리 평균 <b style="color:var(--ink)">' + l.stepAvg.toFixed(2) + 'ms</b> · 최대 ' + l.stepMax.toFixed(1) + '</span><span>' + l.ticks + '틱</span></div>' +
|
|
10530
|
+
'<div class="bar" title="틱 간격 p99 (선: 목표)"><i style="width:' + (gap * 100).toFixed(1) + '%;background:' + (l.gapP99 > l.intervalMs * 1.5 ? "var(--d)" : l.gapP99 > l.intervalMs * 1.15 ? "var(--c)" : "var(--a)") + '"></i><em style="left:' + (target * 100).toFixed(1) + '%"></em></div>' +
|
|
10531
|
+
'<div class="bar" title="처리 시간 / 목표"><i style="width:' + Math.min(100, l.stepAvg / l.intervalMs * 100).toFixed(1) + '%;background:var(--b)"></i></div>';
|
|
10532
|
+
});
|
|
10533
|
+
var keys = Object.keys(h.report || {});
|
|
10534
|
+
if (keys.length) {
|
|
10535
|
+
html += '<div class="kv">' + keys.map(function (k) { return "<div><span>" + esc(k) + "</span><b>" + esc(h.report[k]) + "</b></div>"; }).join("") + "</div>";
|
|
10536
|
+
} else html += '<p class="empty">host.report({ ... })로 보낸 값이 여기에 나옵니다.</p>';
|
|
10537
|
+
});
|
|
10538
|
+
$("game").innerHTML = html;
|
|
10539
|
+
}
|
|
10540
|
+
function renderPlayers() {
|
|
10541
|
+
var rows = [];
|
|
10542
|
+
hosts.forEach(function (h) { (h.players || []).forEach(function (p) { rows.push([h.name, p]); }); });
|
|
10543
|
+
if (!rows.length) { $("players").innerHTML = '<p class="empty">아직 입력을 보낸 참가자가 없습니다.</p>'; return; }
|
|
10544
|
+
var max = Math.max.apply(null, rows.map(function (r) { return r[1].inputs; }).concat([1]));
|
|
10545
|
+
$("players").innerHTML = "<table><thead><tr><th>호스트</th><th>CID</th><th>이름</th><th>로그인</th><th>입력</th><th>참가</th><th>마지막 입력</th></tr></thead><tbody>" +
|
|
10546
|
+
rows.map(function (r) {
|
|
10547
|
+
var p = r[1];
|
|
10548
|
+
return "<tr><td>" + esc(r[0]) + "</td><td>" + esc(p.cid) + "</td><td>" + esc(p.nick || "-") + "</td><td>" +
|
|
10549
|
+
(p.authorized ? '<span class="badge auth">로그인</span>' : '<span class="badge">익명</span>') + '</td><td><span class="act" style="width:' + Math.round(80 * p.inputs / max) + 'px"></span> ' + p.inputs +
|
|
10550
|
+
"</td><td>" + fmtT(p.since) + "</td><td>" + (p.idle < 1000 ? "방금" : Math.round(p.idle / 1000) + "초 전") + "</td></tr>";
|
|
10551
|
+
}).join("") + "</tbody></table>";
|
|
10552
|
+
}
|
|
10553
|
+
var KIND = { join: "입장", leave: "퇴장", denied: "위조 차단", error: "오류" };
|
|
10554
|
+
function addEvents(list, initial) {
|
|
10555
|
+
if (!list || !list.length) return;
|
|
10556
|
+
var ul = $("events");
|
|
10557
|
+
list.forEach(function (e) {
|
|
10558
|
+
events.push(e);
|
|
10559
|
+
var li = document.createElement("li");
|
|
10560
|
+
var t = new Date(e.at);
|
|
10561
|
+
var detail = e.kind === "denied" ? (e.cid || "") + " → " + (e.tag || "") : e.kind === "error" ? (e.message || "") : (e.cid || "") + (e.reason ? " (" + e.reason + ")" : "");
|
|
10562
|
+
li.innerHTML = "<time>" + t.toLocaleTimeString() + '</time><span class="k ' + e.kind + '">' + (KIND[e.kind] || e.kind) + "</span><span>" + esc(e.host) + "</span><span>" + esc(detail) + "</span>";
|
|
10563
|
+
if (initial) li.style.animation = "none";
|
|
10564
|
+
ul.insertBefore(li, ul.firstChild);
|
|
10565
|
+
});
|
|
10566
|
+
while (ul.children.length > 120) ul.removeChild(ul.lastChild);
|
|
10567
|
+
if (!ul.children.length) ul.innerHTML = '<li class="empty">아직 이벤트가 없습니다.</li>';
|
|
10568
|
+
}
|
|
10569
|
+
|
|
10570
|
+
function draw() {
|
|
10571
|
+
var pick = function (k) { return series.map(function (p) { return p[k] || 0; }); };
|
|
10572
|
+
chart($("cLoad"), [{ values: pick("cpu"), color: "--a" }, { values: pick("eld"), color: "--c" }, { values: pick("conns"), color: "--e", own: true }], { max: 10 });
|
|
10573
|
+
chart($("cMsg"), [{ values: pick("rxMsg"), color: "--b" }, { values: pick("txMsg"), color: "--a" }, { values: pick("dropped"), color: "--d" }], { max: 10 });
|
|
10574
|
+
chart($("cBytes"), [{ values: pick("rxB"), color: "--b" }, { values: pick("txB"), color: "--a" }], { max: 1024, fmt: fmtB });
|
|
10575
|
+
}
|
|
10576
|
+
// Gauges and host pulses move every frame; charts redraw on each sample.
|
|
10577
|
+
function frame(t) {
|
|
10578
|
+
if (latest) {
|
|
10579
|
+
var p = latest.point, total = latest.server.hostTotalBytes || 1;
|
|
10580
|
+
gauge("gCpu", p.cpu, 100, function (v) { return Math.round(v) + "%"; }, "--a");
|
|
10581
|
+
gauge("gEld", p.eld, 100, function (v) { return v.toFixed(1) + "ms"; }, "--c");
|
|
10582
|
+
gauge("gElu", p.elu * 100, 100, function (v) { return Math.round(v) + "%"; }, "--b");
|
|
10583
|
+
gauge("gMem", p.rss / 1048576, Math.max(256, Math.min(total / 1048576, 2048)), function (v) { return Math.round(v) + "MB"; }, "--e");
|
|
10584
|
+
}
|
|
10585
|
+
var dots = document.querySelectorAll(".host");
|
|
10586
|
+
for (var i = 0; i < dots.length; i++) {
|
|
10587
|
+
var rate = pulses[dots[i].getAttribute("data-host")] || 0;
|
|
10588
|
+
var speed = Math.min(8, 0.6 + rate / 8);
|
|
10589
|
+
var k = (Math.sin(t / 1000 * speed * Math.PI) + 1) / 2;
|
|
10590
|
+
var dot = dots[i].querySelector(".pulse");
|
|
10591
|
+
dot.style.boxShadow = rate > 0 ? "0 0 0 " + (k * 7).toFixed(1) + "px " + hexA(css("--a"), 0.35 * (1 - k)) : "none";
|
|
10592
|
+
dot.style.background = rate > 0 ? css("--a") : css("--muted");
|
|
10593
|
+
}
|
|
10594
|
+
requestAnimationFrame(frame);
|
|
10595
|
+
}
|
|
10596
|
+
requestAnimationFrame(frame);
|
|
10597
|
+
addEventListener("resize", draw);
|
|
10598
|
+
|
|
10599
|
+
// ------------------------------------------------ IOSignal connection
|
|
10600
|
+
var io = null, helloTimer = 0, cred = {};
|
|
10601
|
+
function status(text, cls) { var el = $("status"); el.textContent = text; el.className = "pill" + (cls ? " " + cls : ""); }
|
|
10602
|
+
function connect() {
|
|
10603
|
+
if (io) { try { io.destroy(); } catch (e) {} }
|
|
10604
|
+
io = new IO();
|
|
10605
|
+
if (CONFIG.access === "login" && cred.id) io.auth(cred.id, cred.key);
|
|
10606
|
+
io.on("change", function () {
|
|
10607
|
+
if (io.stateName !== "ready") status(io.stateName === "closed" ? "연결 끊김" : "연결 중", io.stateName === "closed" ? "bad" : "");
|
|
10608
|
+
});
|
|
10609
|
+
io.on("ready", function () { hello(); });
|
|
10610
|
+
io.on(CONFIG.topic, function (tag, msg) { onMessage(msg); });
|
|
10611
|
+
io.open((location.protocol === "https:" ? "wss://" : "ws://") + location.host + CONFIG.ws);
|
|
10612
|
+
clearInterval(helloTimer);
|
|
10613
|
+
helloTimer = setInterval(hello, 5000);
|
|
10614
|
+
}
|
|
10615
|
+
function hello() { if (io && io.stateName === "ready") io.signal(CONFIG.tag, { op: "hello", token: cred.token }); }
|
|
10616
|
+
function onMessage(m) {
|
|
10617
|
+
if (!m || !m.type) return;
|
|
10618
|
+
if (m.type === "denied") { status("권한 없음", "bad"); askAccess(true); return; }
|
|
10619
|
+
if (m.type === "full") { status("시청자가 가득 찼습니다", "bad"); return; }
|
|
10620
|
+
if (m.type === "init") {
|
|
10621
|
+
$("gate").hidden = true;
|
|
10622
|
+
status("실시간", "live");
|
|
10623
|
+
info = m.server; startedAt = m.startedAt; series = m.series.slice();
|
|
10624
|
+
hostHist = {};
|
|
10625
|
+
series.forEach(function (p) { Object.keys(p.hosts || {}).forEach(function (n) { (hostHist[n] = hostHist[n] || []).push(p.hosts[n]); }); });
|
|
10626
|
+
$("events").innerHTML = "";
|
|
10627
|
+
addEvents(m.events, true);
|
|
10628
|
+
if (!saved) { shown = m.panels.slice(); applyPanels(); }
|
|
10629
|
+
return;
|
|
10630
|
+
}
|
|
10631
|
+
if (m.type === "tick") {
|
|
10632
|
+
latest = m; hosts = m.hosts;
|
|
10633
|
+
series.push(m.point); if (series.length > CONFIG.history) series.shift();
|
|
10634
|
+
Object.keys(m.point.hosts || {}).forEach(function (n) { var a = (hostHist[n] = hostHist[n] || []); a.push(m.point.hosts[n]); if (a.length > 60) a.shift(); });
|
|
10635
|
+
addEvents(m.events, false);
|
|
10636
|
+
render(); draw();
|
|
10637
|
+
}
|
|
10638
|
+
}
|
|
10639
|
+
function askAccess(failed) {
|
|
10640
|
+
var gate = $("gate");
|
|
10641
|
+
$("gateErr").hidden = !failed; $("gateErr").textContent = failed ? "확인하지 못했습니다. 다시 입력해 주세요." : "";
|
|
10642
|
+
if (CONFIG.access === "token") {
|
|
10643
|
+
$("gateTitle").textContent = "대시보드 토큰"; $("gateHelp").textContent = "서버 설정의 dashboard.access.token 값을 입력하세요.";
|
|
10644
|
+
$("gateId").hidden = true; $("gateKey").placeholder = "토큰";
|
|
10645
|
+
} else {
|
|
10646
|
+
$("gateTitle").textContent = "대시보드 로그인"; $("gateHelp").textContent = "이 서버에 로그인할 수 있는 ID와 키를 입력하세요(허용된 역할 또는 CID).";
|
|
10647
|
+
}
|
|
10648
|
+
gate.hidden = false;
|
|
10649
|
+
(CONFIG.access === "token" ? $("gateKey") : $("gateId")).focus();
|
|
10650
|
+
}
|
|
10651
|
+
$("gateForm").addEventListener("submit", function (e) {
|
|
10652
|
+
e.preventDefault();
|
|
10653
|
+
if (CONFIG.access === "token") { cred = { token: $("gateKey").value }; store.sset("iosignal.dashboard.token", cred.token); hello(); }
|
|
10654
|
+
else { cred = { id: $("gateId").value.trim(), key: $("gateKey").value }; connect(); }
|
|
10655
|
+
});
|
|
10656
|
+
addEventListener("pagehide", function () { if (io && io.stateName === "ready") io.signal(CONFIG.tag, { op: "bye" }); });
|
|
10657
|
+
|
|
10658
|
+
applyPanels();
|
|
10659
|
+
addEvents([], true);
|
|
10660
|
+
if (CONFIG.access === "token") { var t = store.sget("iosignal.dashboard.token") || new URLSearchParams(location.search).get("key"); if (t) cred = { token: t }; }
|
|
10661
|
+
connect();
|
|
10662
|
+
if (CONFIG.access === "login" || (CONFIG.access === "token" && !cred.token)) askAccess(false);
|
|
10663
|
+
})();
|
|
10664
|
+
</script>
|
|
10665
|
+
</body>
|
|
10666
|
+
</html>`;
|
|
10667
|
+
|
|
10668
|
+
/** The page with its settings: { io, ws, access, panels, history, tag, topic }. */
|
|
10669
|
+
function dashboardPage(config) {
|
|
10670
|
+
const json = JSON.stringify(config).replace(/</g, '\\u003c');
|
|
10671
|
+
return PAGE.replace('__CONFIG__', json).replace('__IO__', config.io.replace(/"/g, ''))
|
|
10672
|
+
}
|
|
10673
|
+
|
|
10674
|
+
/** Tags of the dashboard's own host. Viewers send to IN; the host sends to one viewer as '@' + TOPIC. */
|
|
10675
|
+
const DASHBOARD = { HOST: 'iosignal.dashboard', IN: 'iosignal.dashboard#in', TOPIC: 'iosignal.dashboard' };
|
|
10676
|
+
const DASHBOARD_PANELS = ['server', 'traffic', 'hosts', 'game', 'participants', 'events'];
|
|
10677
|
+
|
|
10678
|
+
const IO_BUNDLE = new URL('../../dist/browser/iife/io.js', (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('iosignal.cjs', document.baseURI).href)));
|
|
10679
|
+
const VIEWER_TTL_MS = 15000;
|
|
10680
|
+
const PARTICIPANT_LIMIT = 60;
|
|
10681
|
+
const sha = (s) => node_crypto.createHash('sha256').update(String(s)).digest();
|
|
10682
|
+
|
|
10683
|
+
/**
|
|
10684
|
+
* The server dashboard: a web page (options.path) that shows the server and its hosts live.
|
|
10685
|
+
* It talks to the page through IOSignal itself: viewers send 'hello' to DASHBOARD.IN, a host checks
|
|
10686
|
+
* access, and every second it sends the latest sample to each viewer with host.to().
|
|
10687
|
+
*
|
|
10688
|
+
* options (all optional):
|
|
10689
|
+
* path: '/dashboard'
|
|
10690
|
+
* access: 'open' | { token: '...' } | { login: { roles: ['admin'], cids: [] } }
|
|
10691
|
+
* panels: panels shown first (DASHBOARD_PANELS); viewers can switch them
|
|
10692
|
+
* history: seconds kept for the charts (default 300, 10-3600)
|
|
10693
|
+
* maxViewers: default 20
|
|
10694
|
+
* showIdentities: show participant CIDs and names (default: true unless access is 'open')
|
|
10695
|
+
*/
|
|
10696
|
+
class Dashboard {
|
|
10697
|
+
constructor(server, options = {}) {
|
|
10698
|
+
if (options === true) options = {};
|
|
10699
|
+
if (options === null || typeof options !== 'object') throw new TypeError('dashboard options must be an object or true')
|
|
10700
|
+
for (const key of Object.keys(options)) {
|
|
10701
|
+
if (!['path', 'access', 'panels', 'history', 'maxViewers', 'showIdentities'].includes(key)) {
|
|
10702
|
+
throw new TypeError(`unknown dashboard option: ${key}`)
|
|
10703
|
+
}
|
|
10704
|
+
}
|
|
10705
|
+
const path = options.path ?? '/dashboard';
|
|
10706
|
+
if (typeof path !== 'string' || !/^\/[A-Za-z0-9._~\-/]*$/.test(path) || path.length > 64) {
|
|
10707
|
+
throw new TypeError("dashboard path must start with '/' and use URL-safe characters")
|
|
10708
|
+
}
|
|
10709
|
+
this.path = path.length > 1 ? path.replace(/\/+$/, '') : path;
|
|
10710
|
+
this.access = this.#access(options.access ?? 'open');
|
|
10711
|
+
const panels = options.panels ?? DASHBOARD_PANELS;
|
|
10712
|
+
if (!Array.isArray(panels) || panels.some((p) => !DASHBOARD_PANELS.includes(p))) {
|
|
10713
|
+
throw new TypeError(`dashboard panels must be some of: ${DASHBOARD_PANELS.join(', ')}`)
|
|
10714
|
+
}
|
|
10715
|
+
this.panels = [...new Set(panels)];
|
|
10716
|
+
this.history = Number.isInteger(options.history) && options.history >= 10 && options.history <= 3600 ? options.history : 300;
|
|
10717
|
+
if (options.history !== undefined && this.history !== options.history) throw new RangeError('dashboard history: 10-3600 seconds')
|
|
10718
|
+
this.maxViewers = options.maxViewers ?? 20;
|
|
10719
|
+
if (!Number.isInteger(this.maxViewers) || this.maxViewers < 1 || this.maxViewers > 200) throw new RangeError('dashboard maxViewers: 1-200')
|
|
10720
|
+
this.showIdentities = options.showIdentities ?? this.access.mode !== 'open';
|
|
10721
|
+
|
|
10722
|
+
this.server = server;
|
|
10723
|
+
this.startedAt = Date.now();
|
|
10724
|
+
this.viewers = new Map(); // cid -> { lastAt }
|
|
10725
|
+
this.series = []; // [{ at, ... }] one point a second, at most `history`
|
|
10726
|
+
this.lastHostCounters = new Map();
|
|
10727
|
+
this.lastJournal = new Map(); // host name -> last journal seq sent
|
|
10728
|
+
this.events = []; // recent events for a viewer that just arrived
|
|
10729
|
+
|
|
10730
|
+
this.host = server.host(DASHBOARD.HOST, { inbound: [DASHBOARD.IN], own: ['@' + DASHBOARD.TOPIC] });
|
|
10731
|
+
this.host.on('message', (from, tag, msg) => this.#onViewer(from, msg));
|
|
10732
|
+
this.host.on('leave', (from) => this.viewers.delete(from.cid));
|
|
10733
|
+
this.host.on('error', (error) => console.error('dashboard error:', error));
|
|
10734
|
+
this.stats = new ServerStats(server, { onSample: (value) => this.#onSample(value) });
|
|
10735
|
+
}
|
|
10736
|
+
|
|
10737
|
+
#access(access) {
|
|
10738
|
+
if (access === 'open') return { mode: 'open' }
|
|
10739
|
+
if (access && typeof access === 'object' && typeof access.token === 'string') {
|
|
10740
|
+
if (access.token.length < 8) throw new RangeError('dashboard token: at least 8 characters')
|
|
10741
|
+
return { mode: 'token', hash: sha(access.token) }
|
|
10742
|
+
}
|
|
10743
|
+
if (access && typeof access === 'object' && access.login && typeof access.login === 'object') {
|
|
10744
|
+
const roles = access.login.roles ?? ['admin'];
|
|
10745
|
+
const cids = access.login.cids ?? [];
|
|
10746
|
+
if (!Array.isArray(roles) || !Array.isArray(cids)) throw new TypeError('dashboard login: roles and cids are arrays')
|
|
10747
|
+
for (const role of roles) if (!ROLES.includes(role)) throw new RangeError(`dashboard login role must be one of: ${ROLES.join(', ')}`)
|
|
10748
|
+
return { mode: 'login', roles, cids: new Set(cids) }
|
|
10749
|
+
}
|
|
10750
|
+
throw new TypeError("dashboard access must be 'open', { token } or { login: { roles, cids } }")
|
|
10751
|
+
}
|
|
10752
|
+
|
|
10753
|
+
/** Whether this viewer (the server's view of it) may watch. */
|
|
10754
|
+
allowed(from, msg) {
|
|
10755
|
+
const a = this.access;
|
|
10756
|
+
if (a.mode === 'open') return true
|
|
10757
|
+
if (a.mode === 'token') return typeof msg?.token === 'string' && node_crypto.timingSafeEqual(sha(msg.token), a.hash)
|
|
10758
|
+
if (!from.authorized) return false
|
|
10759
|
+
return a.cids.has(from.cid) || a.roles.some((role) => hasRole({ role: from.role, boho: { isAuthorized: true } }, role))
|
|
10760
|
+
}
|
|
10761
|
+
|
|
10762
|
+
#onViewer(from, msg) {
|
|
10763
|
+
if (msg?.op === 'bye') { this.viewers.delete(from.cid); return }
|
|
10764
|
+
if (msg?.op !== 'hello') return
|
|
10765
|
+
const known = this.viewers.get(from.cid);
|
|
10766
|
+
if (!this.allowed(from, msg)) { this.host.to(from.cid, DASHBOARD.TOPIC, { type: 'denied', mode: this.access.mode }); return }
|
|
10767
|
+
if (!known && this.viewers.size >= this.maxViewers) { this.host.to(from.cid, DASHBOARD.TOPIC, { type: 'full' }); return }
|
|
10768
|
+
this.viewers.set(from.cid, { lastAt: Date.now() });
|
|
10769
|
+
if (!known) this.host.to(from.cid, DASHBOARD.TOPIC, this.#init());
|
|
10770
|
+
}
|
|
10771
|
+
|
|
10772
|
+
#init() {
|
|
10773
|
+
return {
|
|
10774
|
+
type: 'init', at: Date.now(), startedAt: this.startedAt, panels: this.panels, history: this.history,
|
|
10775
|
+
showIdentities: this.showIdentities, server: this.#serverInfo(), series: this.series, events: this.events.slice(-60),
|
|
10776
|
+
}
|
|
10777
|
+
}
|
|
10778
|
+
|
|
10779
|
+
#serverInfo() {
|
|
10780
|
+
const s = this.server;
|
|
10781
|
+
return {
|
|
10782
|
+
ws: s.port ?? null, tcp: s.congPort ?? null, membersOnly: s.membersOnly, anonymousQuota: s.anonymousQuota,
|
|
10783
|
+
quota: s.quotas?.[s.anonymousQuota] ?? null, node: process.version,
|
|
10784
|
+
}
|
|
10785
|
+
}
|
|
10786
|
+
|
|
10787
|
+
#mask(cid) {
|
|
10788
|
+
if (this.showIdentities) return cid
|
|
10789
|
+
const s = String(cid ?? '');
|
|
10790
|
+
return s.length <= 2 ? '••' : s.slice(0, 2) + '•'.repeat(Math.min(4, s.length - 2))
|
|
10791
|
+
}
|
|
10792
|
+
|
|
10793
|
+
#hosts(now) {
|
|
10794
|
+
const out = [];
|
|
10795
|
+
for (const host of this.server.hosts) {
|
|
10796
|
+
if (host === this.host || host.closed) continue
|
|
10797
|
+
const c = host.counters;
|
|
10798
|
+
const prev = this.lastHostCounters.get(host) ?? { ...c, at: now - 1000 };
|
|
10799
|
+
const sec = Math.max(0.001, (now - prev.at) / 1000);
|
|
10800
|
+
const rate = (k) => (c[k] - prev[k]) / sec;
|
|
10801
|
+
const handled = (c.inbound - prev.inbound) + (c.leaves - prev.leaves);
|
|
10802
|
+
this.lastHostCounters.set(host, { ...c, at: now });
|
|
10803
|
+
const item = {
|
|
10804
|
+
name: host.name, participants: host.participants.size,
|
|
10805
|
+
rates: { inbound: rate('inbound'), denied: rate('denied'), rejected: rate('rejected'), published: rate('published'), delivered: rate('delivered'), sent: rate('sent'), errors: rate('errors') },
|
|
10806
|
+
totals: { inbound: c.inbound, denied: c.denied, rejected: c.rejected, joins: c.joins, leaves: c.leaves, errors: c.errors },
|
|
10807
|
+
handlerAvgMs: handled > 0 ? (c.handlerMs - prev.handlerMs) / handled : 0,
|
|
10808
|
+
handlerMaxMs: host.handlerMaxMs,
|
|
10809
|
+
loops: host.loopStats(), report: host.reported,
|
|
10810
|
+
};
|
|
10811
|
+
{
|
|
10812
|
+
item.players = host.activity()
|
|
10813
|
+
.sort((a, b) => b.lastAt - a.lastAt).slice(0, PARTICIPANT_LIMIT)
|
|
10814
|
+
.map(({ from, inputs, firstAt, lastAt }) => ({
|
|
10815
|
+
cid: this.#mask(from.cid), nick: this.showIdentities ? from.nick : '', authorized: from.authorized,
|
|
10816
|
+
inputs, since: now - firstAt, idle: now - lastAt,
|
|
10817
|
+
}));
|
|
10818
|
+
}
|
|
10819
|
+
const after = this.lastJournal.get(host.name) ?? 0;
|
|
10820
|
+
const fresh = host.journal(after);
|
|
10821
|
+
if (fresh.length) this.lastJournal.set(host.name, fresh.at(-1).seq);
|
|
10822
|
+
for (const e of fresh) {
|
|
10823
|
+
this.events.push({ host: host.name, at: e.at, kind: e.kind, cid: e.cid ? this.#mask(e.cid) : undefined, tag: e.tag, reason: e.reason, message: e.message });
|
|
10824
|
+
}
|
|
10825
|
+
out.push(item);
|
|
10826
|
+
}
|
|
10827
|
+
if (this.events.length > 200) this.events.splice(0, this.events.length - 200);
|
|
10828
|
+
return out
|
|
10829
|
+
}
|
|
10830
|
+
|
|
10831
|
+
#onSample(v) {
|
|
10832
|
+
const now = v.at;
|
|
10833
|
+
for (const [cid, viewer] of this.viewers) if (now - viewer.lastAt > VIEWER_TTL_MS) this.viewers.delete(cid);
|
|
10834
|
+
const eventsBefore = this.events.length;
|
|
10835
|
+
const hosts = this.#hosts(now);
|
|
10836
|
+
// The dashboard's own traffic, so it can be told apart from the game's.
|
|
10837
|
+
const own = { viewers: this.viewers.size };
|
|
10838
|
+
const point = {
|
|
10839
|
+
at: now, cpu: v.cpuPercent, elu: v.eventLoopUtilization, eld: v.eventLoopP99Ms, rss: v.rss, heap: v.heapUsed,
|
|
10840
|
+
conns: v.total, ws: v.websocket, tcp: v.total - v.websocket, auth: v.authenticated,
|
|
10841
|
+
rxMsg: v.rates.rxMessages ?? 0, txMsg: v.rates.txMessages ?? 0, rxB: v.rates.rxBytes ?? 0, txB: v.rates.txBytes ?? 0,
|
|
10842
|
+
dropped: (v.rates.rateLimited ?? 0) + (v.rates.oversizeRejected ?? 0),
|
|
10843
|
+
hosts: Object.fromEntries(hosts.map((h) => [h.name, { in: h.rates.inbound, denied: h.rates.denied, players: h.participants, step: h.loops[0]?.stepAvg ?? null, gap: h.loops[0]?.gapP99 ?? null }])),
|
|
10844
|
+
};
|
|
10845
|
+
this.series.push(point);
|
|
10846
|
+
if (this.series.length > this.history) this.series.shift();
|
|
10847
|
+
if (!this.viewers.size) return
|
|
10848
|
+
const frame = {
|
|
10849
|
+
type: 'tick', point,
|
|
10850
|
+
server: {
|
|
10851
|
+
uptime: now - this.startedAt, states: v.states, queuedBytes: v.queuedBytes, maxQueuedBytes: v.maxQueuedBytes,
|
|
10852
|
+
txBlockedConnections: v.txBlockedConnections, channels: v.channels, hostTotalBytes: v.hostTotalBytes,
|
|
10853
|
+
counters: { rateLimited: v.counters.rateLimited, oversizeRejected: v.counters.oversizeRejected, peerRxLimitSkipped: v.counters.peerRxLimitSkipped },
|
|
10854
|
+
own,
|
|
10855
|
+
},
|
|
10856
|
+
hosts, events: this.events.slice(eventsBefore),
|
|
10857
|
+
};
|
|
10858
|
+
for (const cid of this.viewers.keys()) this.host.to(cid, DASHBOARD.TOPIC, frame);
|
|
10859
|
+
}
|
|
10860
|
+
|
|
10861
|
+
/**
|
|
10862
|
+
* Serves the page (GET path) and the browser client (path + '/io.js'). Returns true when it
|
|
10863
|
+
* answered. A Server with `port` calls it itself; with your own httpServer call it first in
|
|
10864
|
+
* your request handler: if (server.dashboard.handle(req, res)) return
|
|
10865
|
+
*/
|
|
10866
|
+
handle(req, res) {
|
|
10867
|
+
let pathname;
|
|
10868
|
+
try { pathname = new URL(req.url || '/', 'http://localhost').pathname; } catch { return false }
|
|
10869
|
+
const root = this.path === '/' ? '' : this.path;
|
|
10870
|
+
if (pathname !== this.path && pathname !== root + '/' && pathname !== root + '/io.js') return false
|
|
10871
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { Allow: 'GET, HEAD' }); res.end(); return true }
|
|
10872
|
+
const headers = { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' };
|
|
10873
|
+
if (pathname === root + '/io.js') {
|
|
10874
|
+
promises.readFile(IO_BUNDLE).then((js) => {
|
|
10875
|
+
res.writeHead(200, { ...headers, 'Content-Type': 'text/javascript; charset=utf-8' });
|
|
10876
|
+
res.end(req.method === 'HEAD' ? undefined : js);
|
|
10877
|
+
}, () => { res.writeHead(500); res.end('IOSignal browser bundle not found (build dist first)'); });
|
|
10878
|
+
return true
|
|
10879
|
+
}
|
|
10880
|
+
const config = {
|
|
10881
|
+
io: root + '/io.js', ws: this.server.wsPath || '/', access: this.access.mode, panels: this.panels,
|
|
10882
|
+
history: this.history, tag: DASHBOARD.IN, topic: '@' + DASHBOARD.TOPIC,
|
|
10883
|
+
};
|
|
10884
|
+
res.writeHead(200, {
|
|
10885
|
+
...headers, 'Content-Type': 'text/html; charset=utf-8',
|
|
10886
|
+
'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:; img-src 'self' data:",
|
|
10887
|
+
});
|
|
10888
|
+
res.end(req.method === 'HEAD' ? undefined : dashboardPage(config));
|
|
10889
|
+
return true
|
|
10890
|
+
}
|
|
10891
|
+
|
|
10892
|
+
close() {
|
|
10893
|
+
this.stats.dispose();
|
|
10894
|
+
this.host.close();
|
|
10895
|
+
this.viewers.clear();
|
|
10896
|
+
}
|
|
10897
|
+
}
|
|
10898
|
+
|
|
10899
|
+
const STATUS = {
|
|
10900
|
+
OK: 0,
|
|
10901
|
+
//0~127: success
|
|
10902
|
+
//128~255: fail
|
|
10903
|
+
ERROR: 255
|
|
10904
|
+
};
|
|
10905
|
+
|
|
9738
10906
|
/**
|
|
9739
10907
|
* LocalKeyProvider.js
|
|
9740
10908
|
*
|
|
@@ -9907,6 +11075,9 @@ class Server extends require$$0$3 {
|
|
|
9907
11075
|
* options.anonymousQuota: profile of a connection that has not authenticated (default 'anonymous').
|
|
9908
11076
|
* options.duplicateLogin: 'keepOld' | 'keepNew' for this Server's connections; overrides the auth
|
|
9909
11077
|
* manager's own policy without changing it, so an auth manager can be shared between servers.
|
|
11078
|
+
* options.dashboard: true or { path, access, panels, history, maxViewers, showIdentities } shows a live
|
|
11079
|
+
* status page of the server and its hosts (see Dashboard.js); off by default. With `port` the Server
|
|
11080
|
+
* serves it itself; with your own httpServer call server.dashboard.handle(req, res) in its handler.
|
|
9910
11081
|
* A failed listen (e.g. EADDRINUSE) is emitted as 'error'.
|
|
9911
11082
|
* @param {any} [authManager] Optional authentication manager.
|
|
9912
11083
|
*/
|
|
@@ -9945,6 +11116,7 @@ class Server extends require$$0$3 {
|
|
|
9945
11116
|
this.membersOnly = boolean('membersOnly', options.membersOnly ?? serverOption.membersOnly);
|
|
9946
11117
|
this.serviceNames = new Set();
|
|
9947
11118
|
this.services = new Map(); // name -> service module (for lifecycle hooks)
|
|
11119
|
+
this.hosts = new Set(); // open hosts (server.host)
|
|
9948
11120
|
// Stays null for a CongSocket-only server, so close() does not wait on a WebSocket server.
|
|
9949
11121
|
this.wss = null;
|
|
9950
11122
|
this.port = null;
|
|
@@ -9978,6 +11150,16 @@ class Server extends require$$0$3 {
|
|
|
9978
11150
|
}
|
|
9979
11151
|
|
|
9980
11152
|
this.manager = new Manager(this, authManager);
|
|
11153
|
+
// The status page; null when off.
|
|
11154
|
+
this.dashboard = null;
|
|
11155
|
+
if (options.dashboard) {
|
|
11156
|
+
try {
|
|
11157
|
+
this.dashboard = new Dashboard(this, options.dashboard);
|
|
11158
|
+
} catch (error) {
|
|
11159
|
+
this.manager.close(); // a bad dashboard option must not leave the heartbeat timer running
|
|
11160
|
+
throw error
|
|
11161
|
+
}
|
|
11162
|
+
}
|
|
9981
11163
|
|
|
9982
11164
|
this.serverCountToListen = 0;
|
|
9983
11165
|
this.listeningServerCount = 0;
|
|
@@ -9996,7 +11178,15 @@ class Server extends require$$0$3 {
|
|
|
9996
11178
|
|
|
9997
11179
|
startWSServer() {
|
|
9998
11180
|
// console.log('optoins', options )
|
|
9999
|
-
if (this.port || this.port == 0) {
|
|
11181
|
+
if ((this.port || this.port == 0) && this.dashboard) {
|
|
11182
|
+
// The WebSocket server alone answers plain HTTP with 426; the dashboard needs pages too.
|
|
11183
|
+
this.ownHttp = require$$2$1.createServer((req, res) => {
|
|
11184
|
+
if (!this.dashboard.handle(req, res)) { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not found'); }
|
|
11185
|
+
});
|
|
11186
|
+
this.ownHttp.on('error', (err) => this.onListenerError('ws', err));
|
|
11187
|
+
this.wss = new WebSocketServer({ server: this.ownHttp, path: this.wsPath, maxPayload: this.maxPayload });
|
|
11188
|
+
this.ownHttp.listen(this.port);
|
|
11189
|
+
} else if (this.port || this.port == 0) {
|
|
10000
11190
|
this.wss = new WebSocketServer({ port: this.port , path: this.wsPath, maxPayload: this.maxPayload });
|
|
10001
11191
|
} else if (this.httpServer ) {
|
|
10002
11192
|
this.wss = new WebSocketServer({ server: this.httpServer, path: this.wsPath, maxPayload: this.maxPayload });
|
|
@@ -10070,6 +11260,25 @@ class Server extends require$$0$3 {
|
|
|
10070
11260
|
return this.manager.metrics.snapshot()
|
|
10071
11261
|
}
|
|
10072
11262
|
|
|
11263
|
+
/**
|
|
11264
|
+
* Server-side logic (a game, a room) in this process. Signals clients send to the inbound tags go
|
|
11265
|
+
* to the host only, with the server's view of the sender; clients cannot send to the tags it owns.
|
|
11266
|
+
* @param {string} name 1-64 characters of A-Z a-z 0-9 _ . -
|
|
11267
|
+
* @param {{ inbound: string[], own?: string[], fanout?: number|null,
|
|
11268
|
+
* retain?: { tags?: number, bytes?: number } }} options
|
|
11269
|
+
* inbound: channel tags clients send to the host (a trailing '*' is a prefix). Not relayed.
|
|
11270
|
+
* own: channel tags only the host publishes, and '@topic' unicast topics only the host sends.
|
|
11271
|
+
* fanout: most subscribers one publish reaches (default null: all).
|
|
11272
|
+
* retain: budget of the host's retained ('$') values (default: retain.tagsPerOwner/bytesPerOwner).
|
|
11273
|
+
* @returns {Host}
|
|
11274
|
+
*/
|
|
11275
|
+
host(name, options) {
|
|
11276
|
+
const host = new Host(this.manager, name, options);
|
|
11277
|
+
host.once('close', () => this.hosts.delete(host));
|
|
11278
|
+
this.hosts.add(host);
|
|
11279
|
+
return host
|
|
11280
|
+
}
|
|
11281
|
+
|
|
10073
11282
|
/**
|
|
10074
11283
|
* RPC service register.
|
|
10075
11284
|
* service: service_name <string>
|
|
@@ -10129,6 +11338,8 @@ class Server extends require$$0$3 {
|
|
|
10129
11338
|
*/
|
|
10130
11339
|
close(callback) {
|
|
10131
11340
|
console.log('closing iosignal server...');
|
|
11341
|
+
if (this.dashboard) this.dashboard.close();
|
|
11342
|
+
for (const host of [...this.hosts]) host.close();
|
|
10132
11343
|
if (this.manager) {
|
|
10133
11344
|
this.manager.close();
|
|
10134
11345
|
}
|
|
@@ -10158,7 +11369,10 @@ class Server extends require$$0$3 {
|
|
|
10158
11369
|
if (this.wss) {
|
|
10159
11370
|
this.wss.close(() => {
|
|
10160
11371
|
// console.log('wss server closed.')
|
|
10161
|
-
onClosed()
|
|
11372
|
+
if (!this.ownHttp) return onClosed()
|
|
11373
|
+
// The HTTP server this Server made for the dashboard closes with it.
|
|
11374
|
+
this.ownHttp.close(() => onClosed());
|
|
11375
|
+
this.ownHttp.closeAllConnections?.();
|
|
10162
11376
|
});
|
|
10163
11377
|
}
|
|
10164
11378
|
|