@aidra/pmx-io 9.24.0 → 9.26.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/lib/standalone/transport.js +336 -50
- package/lib/transport/ws.js +10 -2
- package/package.json +1 -1
- package/preload.cjs +7 -1
- package/preload.mjs +6 -5
|
@@ -29,6 +29,17 @@ const LOG_BATCH_MAX = 4 * 1024 * 1024
|
|
|
29
29
|
const LOG_LINES_PER_SECOND = 2000
|
|
30
30
|
const LOG_DROP_REPORT_MS = 60000
|
|
31
31
|
const NOT_QUEUED = ['status', 'logs', 'trace-span', 'trace-spans']
|
|
32
|
+
// prodman 28 §6 (80 NIO-300…303): protocol 2 offered; verifyPM2 repeated every 60 s while
|
|
33
|
+
// connected; waits after the server's close codes
|
|
34
|
+
const PROTOCOL_VERSION = 2
|
|
35
|
+
const REPOLL_MS = 60000
|
|
36
|
+
const REPLACED_MS = 5 * 60000 // after a 4000, doubled per further one, at most 12× (1 h)
|
|
37
|
+
const REFUSED_MS = 60000 // after 4001…4004, 4402, 4403, doubled, at most 10× (10 min)
|
|
38
|
+
const REFUSED_RESET = 60000 // a connection open this long resets the refusal count
|
|
39
|
+
const REPLACED_RESET = 2 * 3600000 // … and this long the 4000 count (longer than the longest wait)
|
|
40
|
+
const SELF_REPLACE_WINDOW = 30000 // a 4000 this soon after our own move is not another process
|
|
41
|
+
const MAX_SPREAD_MS = 600000
|
|
42
|
+
const REFUSAL_CODES = [4001, 4002, 4003, 4004, 4402, 4403]
|
|
32
43
|
const REFUSAL = '%s is not available: %s runs without PM2 (@pm2/io standalone)'
|
|
33
44
|
|
|
34
45
|
// -- configuration (NIO-262) ----------------------------------------------------------------------
|
|
@@ -239,6 +250,70 @@ function backoff (baseMs, attempt) {
|
|
|
239
250
|
return Math.round(ms * (0.8 + Math.random() * 0.4))
|
|
240
251
|
}
|
|
241
252
|
|
|
253
|
+
/** A duration in ms from the environment (tests shorten the waits), else `dflt`. */
|
|
254
|
+
function timing (name, dflt) {
|
|
255
|
+
const v = Number(process.env[name])
|
|
256
|
+
return Number.isFinite(v) && v > 0 ? v : dflt
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function jittered (ms) {
|
|
260
|
+
return Math.round(ms * (0.8 + Math.random() * 0.4))
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** `spread=<seconds>` in a 1012 close reason, in ms (≤ 10 min); null when absent. */
|
|
264
|
+
function restartSpread (reason) {
|
|
265
|
+
const m = /spread=([0-9.]+)/.exec(String(reason || ''))
|
|
266
|
+
const s = m ? Number(m[1]) : NaN
|
|
267
|
+
return Number.isFinite(s) && s > 0 ? Math.min(s * 1000, MAX_SPREAD_MS) : null
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** SPL-080: the version the server echoed in its 101 answer; none = 1, never above ours. */
|
|
271
|
+
function agreedProtocol (headers) {
|
|
272
|
+
const v = Number(headers && headers['x-protocol-version'])
|
|
273
|
+
return Number.isInteger(v) && v >= 1 ? Math.min(v, PROTOCOL_VERSION) : 1
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Whether version `a` is older than `b` (dotted numbers; `-pre` before the release). */
|
|
277
|
+
function olderVersion (a, b) {
|
|
278
|
+
const parse = (v) => {
|
|
279
|
+
const m = /^v?([0-9]+(?:\.[0-9]+)*)(-[^+]*)?(\+.*)?$/.exec(String(v).trim())
|
|
280
|
+
return m ? { n: m[1].split('.').map(Number), pre: Boolean(m[2]) } : null
|
|
281
|
+
}
|
|
282
|
+
const x = parse(a)
|
|
283
|
+
const y = parse(b)
|
|
284
|
+
if (!x || !y) return false
|
|
285
|
+
for (let i = 0; i < Math.max(x.n.length, y.n.length); i++) {
|
|
286
|
+
const d = (x.n[i] || 0) - (y.n[i] || 0)
|
|
287
|
+
if (d) return d < 0
|
|
288
|
+
}
|
|
289
|
+
return x.pre && !y.pre
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function upgradeMessage (doc) {
|
|
293
|
+
const min = typeof doc.min_agent_version === 'string' ? doc.min_agent_version : 'a newer version'
|
|
294
|
+
const msg = typeof doc.msg === 'string' && doc.msg ? ': ' + doc.msg : ''
|
|
295
|
+
return `prodman requires @aidra/pmx-io ${min} or later (this is ${VERSION})${msg}`
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* SPL-083: `endpoints.root` when it differs from `current`: https always, http only when the
|
|
300
|
+
* current URL is http itself (never off TLS).
|
|
301
|
+
*/
|
|
302
|
+
function rootChange (doc, current) {
|
|
303
|
+
const raw = doc && doc.endpoints && typeof doc.endpoints.root === 'string' ? doc.endpoints.root.trim() : ''
|
|
304
|
+
if (!raw) return null
|
|
305
|
+
let u
|
|
306
|
+
try {
|
|
307
|
+
u = new URL(raw)
|
|
308
|
+
} catch (_) {
|
|
309
|
+
return null
|
|
310
|
+
}
|
|
311
|
+
const ok = u.protocol === 'https:' || (u.protocol === 'http:' && /^http:\/\//i.test(String(current)))
|
|
312
|
+
if (!ok || !u.hostname) return null
|
|
313
|
+
const next = raw.replace(/\/+$/, '')
|
|
314
|
+
return next !== String(current).replace(/\/+$/, '') ? next : null
|
|
315
|
+
}
|
|
316
|
+
|
|
242
317
|
function countLines (text) {
|
|
243
318
|
const n = text.split('\n').length - (text.endsWith('\n') ? 1 : 0)
|
|
244
319
|
return n || 1
|
|
@@ -264,9 +339,19 @@ class ProdmanTransport {
|
|
|
264
339
|
this._connecting = false
|
|
265
340
|
this._stopping = false
|
|
266
341
|
this._closed = false
|
|
267
|
-
this._timers = { status: null, ping: null, retry: null, logs: null }
|
|
342
|
+
this._timers = { status: null, ping: null, retry: null, logs: null, repoll: null }
|
|
268
343
|
this._hsAttempt = 0
|
|
269
344
|
this._wsAttempt = 0
|
|
345
|
+
// 80 NIO-300…303
|
|
346
|
+
this.protocol = 1
|
|
347
|
+
this._endpoint = null
|
|
348
|
+
this._repolling = false
|
|
349
|
+
this._moving = false
|
|
350
|
+
this._replacedStrikes = 0
|
|
351
|
+
this._refusedStrikes = 0
|
|
352
|
+
this._closeDelay = null
|
|
353
|
+
this._droppedOwnAt = 0
|
|
354
|
+
this._advice = null
|
|
270
355
|
this._lastRefusal = null
|
|
271
356
|
this.collectLogs = false
|
|
272
357
|
this._batchSupported = false
|
|
@@ -383,7 +468,7 @@ class ProdmanTransport {
|
|
|
383
468
|
} catch (err) {
|
|
384
469
|
this._connecting = false
|
|
385
470
|
debug('connection failed: %s', err && err.message)
|
|
386
|
-
this._schedule(() => this._run(), backoff(5000, this._wsAttempt++))
|
|
471
|
+
this._schedule(() => this._run(), backoff(timing('PMX_IO_RECONNECT_MS', 5000), this._wsAttempt++))
|
|
387
472
|
}
|
|
388
473
|
}
|
|
389
474
|
|
|
@@ -404,12 +489,16 @@ class ProdmanTransport {
|
|
|
404
489
|
IO_VERSION,
|
|
405
490
|
MEMORY: Math.floor(limits.memoryBytes / 1048576),
|
|
406
491
|
HOSTNAME: container.hostname(),
|
|
407
|
-
CPUS: cpus
|
|
492
|
+
CPUS: cpus,
|
|
493
|
+
// prodman 28 SPL-080/081: what this client is, for a server that checks a minimum version
|
|
494
|
+
AGENT_VERSION: VERSION,
|
|
495
|
+
PROTOCOL_VERSION
|
|
408
496
|
}
|
|
409
497
|
}
|
|
410
498
|
}
|
|
411
499
|
|
|
412
|
-
|
|
500
|
+
/** POST verifyPM2; resolves the JSON document (rejects on a network error or a non-JSON body). */
|
|
501
|
+
async _verify () {
|
|
413
502
|
const { httpRequest } = require('../transport/ws')
|
|
414
503
|
const body = JSON.stringify(this.handshakeBody())
|
|
415
504
|
const res = await httpRequest('POST', this.cfg.url + '/api/node/verifyPM2', body, {
|
|
@@ -417,92 +506,288 @@ class ProdmanTransport {
|
|
|
417
506
|
'User-Agent': '@pmx/io/' + VERSION,
|
|
418
507
|
Accept: 'application/json'
|
|
419
508
|
}, { timeout: 15000, proxy: this.cfg.proxy || undefined })
|
|
420
|
-
let doc
|
|
421
509
|
try {
|
|
422
|
-
|
|
510
|
+
return JSON.parse(res.body.toString('utf8'))
|
|
423
511
|
} catch (_) {
|
|
424
512
|
throw new Error(`handshake: HTTP ${res.status}, not JSON`)
|
|
425
513
|
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
async _handshake () {
|
|
517
|
+
const doc = await this._verify()
|
|
518
|
+
this._versionAdvice(doc)
|
|
426
519
|
const ws = doc && doc.endpoints && typeof doc.endpoints.ws === 'string' ? doc.endpoints.ws : null
|
|
520
|
+
if (doc && doc.upgrade_required === true) {
|
|
521
|
+
const e = new Error(upgradeMessage(doc))
|
|
522
|
+
e.refused = true
|
|
523
|
+
throw e
|
|
524
|
+
}
|
|
427
525
|
if (!doc || doc.active !== true || !ws) {
|
|
428
526
|
const e = new Error((doc && typeof doc.msg === 'string' && doc.msg) || 'bucket not active')
|
|
429
527
|
e.refused = true
|
|
430
528
|
throw e
|
|
431
529
|
}
|
|
530
|
+
this._moveRoot(doc)
|
|
432
531
|
const p = doc.prodman && typeof doc.prodman === 'object' ? doc.prodman : {}
|
|
433
532
|
return { endpoint: ws, collectLogs: p.collect_logs === true, traceSpansBatch: p.trace_spans_batch === true, tracing: p.tracing }
|
|
434
533
|
}
|
|
435
534
|
|
|
535
|
+
/** SPL-081 (80 NIO-301): `min_agent_version` above this version → one warning per value. */
|
|
536
|
+
_versionAdvice (doc) {
|
|
537
|
+
const min = doc && typeof doc.min_agent_version === 'string' ? doc.min_agent_version : null
|
|
538
|
+
const msg = min && doc.upgrade_required !== true && olderVersion(VERSION, min)
|
|
539
|
+
? `prodman recommends @aidra/pmx-io ${min} or later (this is ${VERSION})`
|
|
540
|
+
: null
|
|
541
|
+
if (msg && msg !== this._advice) {
|
|
542
|
+
try {
|
|
543
|
+
process.stderr.write(`[@pm2/io] ${msg}\n`)
|
|
544
|
+
} catch (_) {}
|
|
545
|
+
}
|
|
546
|
+
this._advice = msg
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** SPL-083 (80 NIO-302): `endpoints.root` replaces the configured URL for the next handshakes. */
|
|
550
|
+
_moveRoot (doc) {
|
|
551
|
+
const root = rootChange(doc, this.cfg.url)
|
|
552
|
+
if (!root) return
|
|
553
|
+
debug('prodman moved the root URL: %s -> %s', redact(this.cfg.url), redact(root))
|
|
554
|
+
this.cfg = Object.assign({}, this.cfg, { url: root })
|
|
555
|
+
}
|
|
556
|
+
|
|
436
557
|
_pongTimeout () {
|
|
437
558
|
const v = Number(process.env.PRODMAN_WS_TIMEOUT)
|
|
438
559
|
return Number.isFinite(v) && v > 0 ? v : PONG_TIMEOUT
|
|
439
560
|
}
|
|
440
561
|
|
|
562
|
+
_wsHeaders () {
|
|
563
|
+
return {
|
|
564
|
+
'X-KM-PUBLIC': this.cfg.publicKey,
|
|
565
|
+
'X-KM-SECRET': this.cfg.secretKey,
|
|
566
|
+
'X-KM-SERVER': this.server,
|
|
567
|
+
'X-PM2-VERSION': IO_VERSION,
|
|
568
|
+
'X-PROTOCOL-VERSION': String(PROTOCOL_VERSION),
|
|
569
|
+
'User-Agent': '@pmx/io/' + VERSION
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
441
573
|
_connect (endpoint) {
|
|
442
574
|
if (this._stopping) {
|
|
443
575
|
this._connecting = false
|
|
444
576
|
return
|
|
445
577
|
}
|
|
446
578
|
const { WebSocketClient } = require('../transport/ws')
|
|
447
|
-
const ws = new WebSocketClient(endpoint, {
|
|
448
|
-
'X-KM-PUBLIC': this.cfg.publicKey,
|
|
449
|
-
'X-KM-SECRET': this.cfg.secretKey,
|
|
450
|
-
'X-KM-SERVER': this.server,
|
|
451
|
-
'X-PM2-VERSION': IO_VERSION,
|
|
452
|
-
'X-PROTOCOL-VERSION': '1',
|
|
453
|
-
'User-Agent': '@pmx/io/' + VERSION
|
|
454
|
-
}, { proxy: this.cfg.proxy || undefined })
|
|
455
|
-
let lastSeen = Date.now()
|
|
579
|
+
const ws = new WebSocketClient(endpoint, this._wsHeaders(), { proxy: this.cfg.proxy || undefined })
|
|
456
580
|
let opened = false
|
|
457
581
|
ws.on('open', () => {
|
|
458
582
|
opened = true
|
|
459
|
-
this._ws = ws
|
|
460
583
|
this._connecting = false
|
|
461
584
|
this._wsAttempt = 0
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
this.
|
|
473
|
-
this.
|
|
474
|
-
|
|
475
|
-
this.
|
|
476
|
-
if (Date.now() - lastSeen > this._pongTimeout()) return ws.terminate()
|
|
477
|
-
ws.ping()
|
|
478
|
-
}, PING_INTERVAL)
|
|
479
|
-
if (this._timers.ping.unref) this._timers.ping.unref()
|
|
480
|
-
this._timers.logs = setInterval(() => this._flushLogs(false), LOG_BATCH_MS)
|
|
481
|
-
if (this._timers.logs.unref) this._timers.logs.unref()
|
|
585
|
+
this._install(ws, endpoint)
|
|
586
|
+
})
|
|
587
|
+
this._wire(ws)
|
|
588
|
+
ws.on('close', (code, reason) => {
|
|
589
|
+
if (!opened) this._connecting = false
|
|
590
|
+
if (ws._superseded) return
|
|
591
|
+
const current = this._ws === ws
|
|
592
|
+
if (current) this._disconnected()
|
|
593
|
+
if (this._stopping) return
|
|
594
|
+
// a move in progress takes over (or fails and reconnects)
|
|
595
|
+
if (this._moving) return
|
|
596
|
+
const delay = current ? this._afterClose(code, reason, Date.now() - ws._openedAt) : backoff(timing('PMX_IO_RECONNECT_MS', 5000), this._wsAttempt++)
|
|
597
|
+
debug('connection closed (%s), reconnecting in %d ms', code, delay)
|
|
598
|
+
this._schedule(() => this._run(), delay)
|
|
482
599
|
})
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/** Listeners every socket has: liveness and inbound frames (from the current socket only). */
|
|
603
|
+
_wire (ws) {
|
|
604
|
+
ws._lastSeen = Date.now()
|
|
605
|
+
ws.on('drain', () => {
|
|
606
|
+
if (this._ws === ws) this._drain()
|
|
607
|
+
})
|
|
608
|
+
ws.on('pong', () => { ws._lastSeen = Date.now() })
|
|
609
|
+
ws.on('ping', () => { ws._lastSeen = Date.now() })
|
|
486
610
|
ws.on('message', (text) => {
|
|
487
|
-
|
|
488
|
-
this._onText(text)
|
|
611
|
+
ws._lastSeen = Date.now()
|
|
612
|
+
if (this._ws === ws) this._onText(text)
|
|
489
613
|
})
|
|
490
614
|
ws.on('error', (err) => debug('socket error: %s', err && err.message))
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** `ws` (open) becomes the connection: status first, then the queue; timers and re-poll. */
|
|
618
|
+
_install (ws, endpoint) {
|
|
619
|
+
this._disconnectTimers()
|
|
620
|
+
this._ws = ws
|
|
621
|
+
this._endpoint = endpoint
|
|
622
|
+
ws._openedAt = Date.now()
|
|
623
|
+
ws._lastSeen = Date.now()
|
|
624
|
+
this.protocol = agreedProtocol(ws.responseHeaders)
|
|
625
|
+
debug('connected to %s (protocol %d)', redact(endpoint), this.protocol)
|
|
626
|
+
try {
|
|
627
|
+
const addr = ws._socket && ws._socket.localAddress
|
|
628
|
+
if (typeof addr === 'string' && addr.includes('.') && !addr.startsWith('127.')) this._ip = addr
|
|
629
|
+
} catch (_) {}
|
|
630
|
+
this._sendStatus(true)
|
|
631
|
+
if (this._shutdownPayload && this._shutdownSentOn !== ws) {
|
|
632
|
+
// CTR-022: re-sent on a new connection while the shutdown is in progress
|
|
633
|
+
this._pending.unshift(['agent:shutdown', JSON.stringify({ channel: 'agent:shutdown', payload: this._shutdownPayload }), null])
|
|
634
|
+
}
|
|
635
|
+
this._drain()
|
|
636
|
+
this._timers.status = setInterval(() => this._sendStatus(false), STATUS_INTERVAL)
|
|
637
|
+
if (this._timers.status.unref) this._timers.status.unref()
|
|
638
|
+
this._timers.ping = setInterval(() => {
|
|
639
|
+
if (Date.now() - ws._lastSeen > this._pongTimeout()) return ws.terminate()
|
|
640
|
+
ws.ping()
|
|
641
|
+
}, PING_INTERVAL)
|
|
642
|
+
if (this._timers.ping.unref) this._timers.ping.unref()
|
|
643
|
+
this._timers.logs = setInterval(() => this._flushLogs(false), LOG_BATCH_MS)
|
|
644
|
+
if (this._timers.logs.unref) this._timers.logs.unref()
|
|
645
|
+
// 80 NIO-300: the handshake is repeated while connected, as the pmx agent does (AG-305)
|
|
646
|
+
this._timers.repoll = setInterval(() => this._repoll(), timing('PMX_IO_REPOLL_MS', REPOLL_MS))
|
|
647
|
+
if (this._timers.repoll.unref) this._timers.repoll.unref()
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* 80 NIO-300 (AG-305): while connected, verifyPM2 again. Settings are applied; refused keys or
|
|
652
|
+
* `upgrade_required` close the socket and go back to the handshake loop; a changed
|
|
653
|
+
* `endpoints.ws` moves the connection (NIO-300 move: the new socket opens before the old one
|
|
654
|
+
* closes, so nothing queued or batched is lost); errors are ignored until the next poll.
|
|
655
|
+
*/
|
|
656
|
+
async _repoll () {
|
|
657
|
+
if (this._repolling || this._stopping || !this._connected()) return
|
|
658
|
+
this._repolling = true
|
|
659
|
+
let doc
|
|
660
|
+
try {
|
|
661
|
+
doc = await this._verify()
|
|
662
|
+
} catch (err) {
|
|
663
|
+
debug('re-poll failed: %s', err && err.message)
|
|
664
|
+
return
|
|
665
|
+
} finally {
|
|
666
|
+
this._repolling = false
|
|
667
|
+
}
|
|
668
|
+
if (this._stopping || !this._connected() || !doc || typeof doc !== 'object') return
|
|
669
|
+
this._versionAdvice(doc)
|
|
670
|
+
const p = doc.prodman && typeof doc.prodman === 'object' ? doc.prodman : null
|
|
671
|
+
if ((doc.active === false && doc.error === true) || doc.upgrade_required === true) {
|
|
672
|
+
const msg = doc.upgrade_required === true ? upgradeMessage(doc) : (typeof doc.msg === 'string' ? doc.msg : 'refused')
|
|
673
|
+
if (msg !== this._lastRefusal) {
|
|
674
|
+
this._lastRefusal = msg
|
|
675
|
+
try {
|
|
676
|
+
process.stderr.write(`[@pm2/io] prodman refused the connection: ${msg}\n`)
|
|
677
|
+
} catch (_) {}
|
|
678
|
+
}
|
|
679
|
+
this._refusedStrikes++
|
|
680
|
+
this._closeDelay = this._refusedDelay()
|
|
681
|
+
this._ws.close(1000, 'Disconnecting')
|
|
682
|
+
return
|
|
683
|
+
}
|
|
684
|
+
const ws = doc.endpoints && typeof doc.endpoints.ws === 'string' && doc.endpoints.ws ? doc.endpoints.ws : null
|
|
685
|
+
if (doc.active !== true || !ws || doc.disabled === true || doc.pending === true) return
|
|
686
|
+
if (p) {
|
|
687
|
+
if (typeof p.collect_logs === 'boolean') this.collectLogs = p.collect_logs
|
|
688
|
+
this._batchSupported = p.trace_spans_batch === true
|
|
689
|
+
this._applyTracing(p.tracing)
|
|
690
|
+
}
|
|
691
|
+
this._moveRoot(doc)
|
|
692
|
+
if (ws !== this._endpoint) this._move(ws)
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/** Make before break: open `endpoint`; once open it becomes the connection and the old one closes. */
|
|
696
|
+
_move (endpoint) {
|
|
697
|
+
if (this._moving || this._stopping) return
|
|
698
|
+
const old = this._ws
|
|
699
|
+
debug('endpoint changed: moving to %s', redact(endpoint))
|
|
700
|
+
this._moving = true
|
|
701
|
+
const { WebSocketClient } = require('../transport/ws')
|
|
702
|
+
const ws = new WebSocketClient(endpoint, this._wsHeaders(), { proxy: this.cfg.proxy || undefined })
|
|
703
|
+
let opened = false
|
|
704
|
+
this._wire(ws)
|
|
705
|
+
ws.on('open', () => {
|
|
706
|
+
opened = true
|
|
707
|
+
this._moving = false
|
|
708
|
+
if (this._stopping) return ws.close(1000, 'Shutting down')
|
|
709
|
+
// the old socket is ours: its 4000 (the server replacing it by this one) is expected
|
|
710
|
+
this._droppedOwnAt = Date.now()
|
|
711
|
+
if (old && this._ws === old) {
|
|
712
|
+
old._superseded = true
|
|
713
|
+
this._install(ws, endpoint)
|
|
714
|
+
this._retire(old)
|
|
715
|
+
} else if (!this._ws) {
|
|
716
|
+
this._install(ws, endpoint)
|
|
717
|
+
} else {
|
|
718
|
+
ws.close(1000, 'Disconnecting')
|
|
719
|
+
}
|
|
720
|
+
})
|
|
721
|
+
ws.on('close', (code, reason) => {
|
|
722
|
+
if (!opened) {
|
|
723
|
+
this._moving = false
|
|
724
|
+
debug('move to %s failed (%s): staying', redact(endpoint), code)
|
|
725
|
+
if (!this._ws && !this._stopping) this._schedule(() => this._run(), backoff(timing('PMX_IO_RECONNECT_MS', 5000), this._wsAttempt++))
|
|
726
|
+
return
|
|
727
|
+
}
|
|
728
|
+
if (ws._superseded || this._ws !== ws) return
|
|
729
|
+
this._disconnected()
|
|
494
730
|
if (this._stopping) return
|
|
495
|
-
const delay =
|
|
496
|
-
debug('connection closed, reconnecting in %d ms', delay)
|
|
731
|
+
const delay = this._afterClose(code, reason, Date.now() - ws._openedAt)
|
|
497
732
|
this._schedule(() => this._run(), delay)
|
|
498
733
|
})
|
|
499
734
|
}
|
|
500
735
|
|
|
736
|
+
/** Closes a superseded socket with 1000 once what it holds is written (at most 5 s). */
|
|
737
|
+
_retire (old) {
|
|
738
|
+
const deadline = Date.now() + 5000
|
|
739
|
+
const check = () => {
|
|
740
|
+
if (old.readyState !== 1) return
|
|
741
|
+
if (old.bufferedAmount() === 0 || Date.now() >= deadline) return old.close(1000, 'Moving to a new endpoint')
|
|
742
|
+
const t = setTimeout(check, 20)
|
|
743
|
+
if (t.unref) t.unref()
|
|
744
|
+
}
|
|
745
|
+
check()
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* 80 NIO-303 (prodman 28 SPL-082): the delay before the next handshake after the server closed
|
|
750
|
+
* the current socket with `code`. `lived` = how long it was open.
|
|
751
|
+
*/
|
|
752
|
+
_afterClose (code, reason, lived) {
|
|
753
|
+
if (this._closeDelay !== null) {
|
|
754
|
+
const d = this._closeDelay
|
|
755
|
+
this._closeDelay = null
|
|
756
|
+
return d
|
|
757
|
+
}
|
|
758
|
+
if (lived >= REFUSED_RESET) this._refusedStrikes = 0
|
|
759
|
+
if (lived >= REPLACED_RESET) this._replacedStrikes = 0
|
|
760
|
+
if (code === 4000) {
|
|
761
|
+
if (this._droppedOwnAt && Date.now() - this._droppedOwnAt < SELF_REPLACE_WINDOW) return backoff(timing('PMX_IO_RECONNECT_MS', 5000), this._wsAttempt++)
|
|
762
|
+
this._replacedStrikes++
|
|
763
|
+
const base = timing('PMX_IO_REPLACED_MS', REPLACED_MS)
|
|
764
|
+
const d = jittered(Math.min(base * Math.pow(2, this._replacedStrikes - 1), base * 12))
|
|
765
|
+
try {
|
|
766
|
+
process.stderr.write(`[@pm2/io] prodman closed the connection: another process reports as "${this.server}" (4000 ${reason || 'replaced'}); retrying in ${Math.round(d / 1000)} s\n`)
|
|
767
|
+
} catch (_) {}
|
|
768
|
+
return d
|
|
769
|
+
}
|
|
770
|
+
if (REFUSAL_CODES.includes(code)) {
|
|
771
|
+
this._refusedStrikes++
|
|
772
|
+
debug('prodman refused the connection (%d %s)', code, reason)
|
|
773
|
+
return this._refusedDelay()
|
|
774
|
+
}
|
|
775
|
+
if (code === 1012) {
|
|
776
|
+
this._wsAttempt = 0
|
|
777
|
+
const spread = restartSpread(reason)
|
|
778
|
+
return spread !== null ? Math.round(Math.random() * spread) : backoff(timing('PMX_IO_RECONNECT_MS', 5000), this._wsAttempt++)
|
|
779
|
+
}
|
|
780
|
+
return backoff(timing('PMX_IO_RECONNECT_MS', 5000), this._wsAttempt++)
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
_refusedDelay () {
|
|
784
|
+
const base = timing('PMX_IO_REFUSED_MS', REFUSED_MS)
|
|
785
|
+
return jittered(Math.min(base * Math.pow(2, Math.max(0, this._refusedStrikes - 1)), base * 10))
|
|
786
|
+
}
|
|
787
|
+
|
|
501
788
|
_disconnected () {
|
|
502
789
|
this._ws = null
|
|
503
|
-
|
|
504
|
-
clearInterval(this._timers.ping)
|
|
505
|
-
clearInterval(this._timers.logs)
|
|
790
|
+
this._disconnectTimers()
|
|
506
791
|
this._trimOffline()
|
|
507
792
|
this._batch = { out: [], err: [] }
|
|
508
793
|
this._batchBytes = 0
|
|
@@ -1006,6 +1291,7 @@ class ProdmanTransport {
|
|
|
1006
1291
|
clearInterval(this._timers.status)
|
|
1007
1292
|
clearInterval(this._timers.ping)
|
|
1008
1293
|
clearInterval(this._timers.logs)
|
|
1294
|
+
clearInterval(this._timers.repoll)
|
|
1009
1295
|
}
|
|
1010
1296
|
|
|
1011
1297
|
destroyAll () {
|
|
@@ -1037,4 +1323,4 @@ function safeCwd () {
|
|
|
1037
1323
|
}
|
|
1038
1324
|
}
|
|
1039
1325
|
|
|
1040
|
-
module.exports = { ProdmanTransport, resolveConfig, resolveUrl, serverName, matchesFilter, Footprint, IO_VERSION, REFUSAL, NOT_QUEUED }
|
|
1326
|
+
module.exports = { ProdmanTransport, resolveConfig, resolveUrl, serverName, matchesFilter, Footprint, IO_VERSION, REFUSAL, NOT_QUEUED, PROTOCOL_VERSION, restartSpread, agreedProtocol, olderVersion, rootChange }
|
package/lib/transport/ws.js
CHANGED
|
@@ -272,6 +272,10 @@ class WebSocketClient extends EventEmitter {
|
|
|
272
272
|
this._socket = null
|
|
273
273
|
this._closeTimer = null
|
|
274
274
|
this.closeCode = null
|
|
275
|
+
// the server's close reason (prodman 28 SPL-082: a 1012 may carry `spread=<s>`)
|
|
276
|
+
this.closeReason = ''
|
|
277
|
+
// the 101 answer's headers (SPL-080: `x-protocol-version`)
|
|
278
|
+
this.responseHeaders = null
|
|
275
279
|
process.nextTick(() => this._connect())
|
|
276
280
|
}
|
|
277
281
|
|
|
@@ -319,7 +323,7 @@ class WebSocketClient extends EventEmitter {
|
|
|
319
323
|
this.readyState = 3
|
|
320
324
|
clearTimeout(this._closeTimer)
|
|
321
325
|
clearTimeout(this._upgradeTimer)
|
|
322
|
-
this.emit('close', this.closeCode)
|
|
326
|
+
this.emit('close', this.closeCode, this.closeReason)
|
|
323
327
|
}
|
|
324
328
|
|
|
325
329
|
_onData (chunk) {
|
|
@@ -343,6 +347,7 @@ class WebSocketClient extends EventEmitter {
|
|
|
343
347
|
else if (h.headers['sec-websocket-extensions'] !== undefined) why = 'unrequested extension'
|
|
344
348
|
else if (h.headers['sec-websocket-protocol'] !== undefined) why = 'unrequested subprotocol'
|
|
345
349
|
if (why) return this._abort(new Error(why))
|
|
350
|
+
this.responseHeaders = h.headers
|
|
346
351
|
this.readyState = 1
|
|
347
352
|
this.emit('open')
|
|
348
353
|
}
|
|
@@ -414,7 +419,10 @@ class WebSocketClient extends EventEmitter {
|
|
|
414
419
|
if (payload.length === 1) return this._protocolError(1002)
|
|
415
420
|
if (payload.length > 2 && validUtf8(payload.slice(2)) === null) return this._protocolError(1007)
|
|
416
421
|
const code = payload.length >= 2 ? payload.readUInt16BE(0) : 1005
|
|
417
|
-
if (this.closeCode === null)
|
|
422
|
+
if (this.closeCode === null) {
|
|
423
|
+
this.closeCode = code
|
|
424
|
+
this.closeReason = payload.length > 2 ? payload.slice(2).toString('utf8') : ''
|
|
425
|
+
}
|
|
418
426
|
if (this.readyState === 1) {
|
|
419
427
|
this._writeFrame(0x8, payload.length >= 2 ? payload.slice(0, 2) : Buffer.alloc(0))
|
|
420
428
|
this.readyState = 2
|
package/package.json
CHANGED
package/preload.cjs
CHANGED
|
@@ -17,7 +17,13 @@ try {
|
|
|
17
17
|
// the root under the daemon (NIO-020), or a descendant / worker thread of one (NIO-291/293)
|
|
18
18
|
if ((env.PMX_IO === '1' || (!env.PMX_IO && env.PMX_IO_HUB && env.PMX_IO_STANDALONE !== '1')) &&
|
|
19
19
|
env.pmx !== 'false' && env.automation !== 'false') {
|
|
20
|
-
require('./lib/activate.js')
|
|
20
|
+
const activation = require('./lib/activate.js')
|
|
21
|
+
activation.activate()
|
|
22
|
+
// NIO-085 / 83 CMP-003: the module hooks for the call map (on by default) or tracing are
|
|
23
|
+
// registered here, not through an `--import` of preload.mjs on every app: `--import` makes
|
|
24
|
+
// Node load a CommonJS entry through the ES-module loader (T-INT-041). registerEsmHooks
|
|
25
|
+
// does nothing when both are off, once registered, or on Bun (no Node module hooks).
|
|
26
|
+
if (!process.versions.bun) activation.registerEsmHooks()
|
|
21
27
|
}
|
|
22
28
|
} catch (err) {
|
|
23
29
|
try {
|
package/preload.mjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// Copyright (c) 2026 Mike Warriner. All rights reserved. Proprietary — see LICENSE.
|
|
2
2
|
|
|
3
|
-
// ES module preload, injected with `--import` only when
|
|
4
|
-
//
|
|
5
|
-
// activates on its own when used alone, and
|
|
6
|
-
// ES-module libraries when tracing or the call
|
|
7
|
-
//
|
|
3
|
+
// ES module preload, injected with `--import` only when tracing is enabled (02 D-05, 80
|
|
4
|
+
// INJ-010). It shares state with preload.cjs (which Node runs first and which already registers
|
|
5
|
+
// the module hooks for tracing or the call map), activates on its own when used alone, and
|
|
6
|
+
// registers the module customization hooks that wrap ES-module libraries when tracing or the call
|
|
7
|
+
// map is on and they are not registered yet (NIO-085, NIO-210, 83 CMP-003). It never registers a
|
|
8
|
+
// hook otherwise.
|
|
8
9
|
|
|
9
10
|
import { createRequire } from 'node:module'
|
|
10
11
|
|