Repository navigation
Expand file tree
/
Copy pathaggregate.js
More file actions
1757 lines (1651 loc) · 78.4 KB
/
Copy pathaggregate.js
File metadata and controls
1757 lines (1651 loc) · 78.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Cluster aggregation: fold N nodes' admin payloads into one cluster answer, at read time.
*
* WHY THE CONSOLE DOES THIS AND NOT THE PLUGIN. Almost everything interesting in a prerender
* deployment is node-local by construction — `hdb_analytics` rows are written per node, the
* backlog snapshot and the queue keeper cover only the residency-pinned keys THAT node owns, the
* lease table is a node-local shared buffer, and the unrouted tally is per worker. A plugin-side "cluster"
* endpoint would have to fan out to its peers, which means every prerender node becomes a
* client of every other prerender node on a path that also serves crawler traffic. The console
* is already the one component that holds every node's session and talks to all of them, and it
* runs off the serve path. So the fan-out lives here, and the plugin stays a set of honest
* per-node endpoints.
*
* THREE MERGE CLASSES, and picking the wrong one is how a dashboard lies:
*
* MERGED — node-local numbers that genuinely add up (analytics, the backlog snapshot, the
* unrouted tally). Summed here. This is the only class that produces a number no
* single node can report: the true cluster backlog, the true serve rate.
* SHARED — replicated tables every node can answer for identically (pages, sitemaps,
* invalidations, the crawl sketches, the static metric catalog). Fanning these out
* would multiply load to produce four copies of one answer, so ONE node answers and
* the payload says which.
* COMPARED — config. Identical by intent, so the interesting content is any DISAGREEMENT: a
* component deploy that silently skipped a node shows up here and nowhere else.
*
* PARTIAL ANSWERS ARE LABELLED, NEVER SILENTLY SHORT. A sum missing a node is not a smaller
* number, it is a WRONG number, and it looks exactly like a real decline. Every merged payload
* carries `sources` — who answered, who didn't, and why — and the UI refuses to present an
* incomplete sum without saying so.
*
* Everything here is pure: `(results) => payload`. No I/O, no Harper globals, so the merge math
* is unit-tested directly.
*/
/** The scope sentinel the UI sends in place of a node origin. Never a hostname. */
export const CLUSTER = 'cluster';
/**
* Routes whose numbers are node-local and additive. Everything else in PROXIED_GET reads a
* replicated table (or is static), so it is answered by ONE node — see SHARED_NOTE.
*/
export const MERGED_GET = Object.freeze([
'overview',
'analytics',
'unrouted',
'config',
// Neither of these ADDS the way analytics does — a probe pass and a purge pass are run one node
// at a time over the keys that node owns, so what the merge produces is every node's own slice
// side by side plus the running tally. They are here rather than in SHARED_NOTE because the
// alternative is worse in the one way this classification exists to prevent: one node's
// "deleted 240,118" answered under a cluster label reads as done when three quarters of the
// keyspace has not been touched.
'change-probe',
'discovery-purge',
// Each node's queue keeper holds only the rows that node owns, so the cluster's queue is the sum —
// and a node that cannot vouch for its numbers answers 503 with the reason. See mergeQueueState.
'queue-state',
]);
/**
* Why a route is answered by a single node under cluster scope, keyed by route. Shown in the
* UI so "cluster" never implies a fan-out that didn't happen.
*/
export const SHARED_NOTE = Object.freeze({
'pages': 'page_cache replicates — any node holds the whole corpus',
'page-content': 'page_cache replicates — any node holds the whole corpus',
'sitemaps': 'the sitemaps database replicates',
'invalidations': 'the invalidation database replicates',
'crawl-breadth': 'crawl sketches replicate; a read already merges every node’s shard',
'metrics': 'the metric catalog is static, compiled into the plugin',
});
/**
* POST routes that act on ONE node's own state and therefore cannot be sent to an arbitrary
* node. Under cluster scope these are refused with an instruction to pick a node, rather than
* quietly landing on whichever node happened to be first — "Run repair sweep" hitting one of
* four nodes while the console says "all nodes" is the kind of thing an operator discovers
* three incidents later.
*
* `queue` is absent on purpose: a control write is replicated intent, and its own `scope` field
* already says which node(s) it applies to.
*/
export const NODE_LOCAL_POST = Object.freeze({
'reconcile': 'The repair sweep runs over the keys ONE node owns. Pick a node to sweep it.',
// Node-scoped for a second reason on top of residency: the in-flight check reads THIS node's
// lease buffer, so asked of a non-owner it cannot tell an orphan from a key mid-render — and
// this sweep deletes.
'sweep-orphans': 'The orphan sweep deletes among the keys ONE node owns. Pick a node to sweep it.',
'backlog': 'A backlog snapshot covers the keys ONE node owns. Pick a node to recompute it.',
// A probe pass walks the registry rows THIS node owns and writes their baselines, and the
// canary probes the cohort built from that same slice. Fanned out it would be N passes at N
// times the agreed origin rate, which is the one thing changeProbe.ratePerSecond exists to
// stop — the rate is a promise made to whoever runs the origin, per node.
'change-probe':
'A probe pass covers the URLs ONE node owns, at that node’s agreed probe rate. Pick a node to run it.',
// Deletes, owner-scoped, and paced per node — the sweep-orphans argument exactly.
'discovery-purge':
'A purge deletes among the keys ONE node owns. Pick a node to run it, and run every node to cover the keyspace.',
// `schedule` reads RenderSchedule node-locally (replicateFrom: false, because the table is
// residency-pinned and a cross-node read has no timeout). Asked of a node that does not own
// the key it truthfully answers "no row" — which reads as "this URL will never render". The
// UI never calls it (it is the peer endpoint `explain` uses, and `explain` already proxies
// to the owner itself); a caller reaching it directly has to name the node they mean.
'schedule':
'A schedule row is only readable on the node that owns the key. Pick a node — or use explain, which finds the owner for you.',
});
/**
* POST routes whose cluster-scoped answer carries a provenance envelope, and the reason one node
* is the whole write. The read side's SHARED_NOTE, pointed the other way.
*
* This is NOT the inverse of NODE_LOCAL_POST. Every route absent from that map already lands on a
* single node (see `writeNode`); membership here only adds the envelope naming which node took it
* and why that is cluster-wide.
*
* `config-override` is here and an invalidation is not, because of what reads the answer next. A
* config write is followed, seconds later, by the one panel that treats nodes disagreeing as a
* DEPLOY FAILURE — and until the write replicates the nodes do disagree. The response has to have
* already said "one node took this, the rows replicate, the others converge", or the console's own
* write path reads as the alarm it exists to raise. Nothing reads an invalidation's answer that
* way, so those keep their byte-exact pass-through.
*/
export const REPLICATED_POST_NOTE = Object.freeze({
'config-override': 'stored config overrides replicate — one node takes the write and every node converges',
});
// ---------------------------------------------------------------- small helpers
const num = (v) => (Number.isFinite(v) ? v : null);
const finite = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : NaN);
/** Sum of a field over results, or null when no result carried a finite value. */
function sumOf(items, read) {
let total = 0;
let seen = false;
for (const item of items) {
const value = finite(read(item));
if (Number.isFinite(value)) {
total += value;
seen = true;
}
}
return seen ? total : null;
}
const maxOf = (items, read) => {
let best = null;
for (const item of items) {
const value = finite(read(item));
if (Number.isFinite(value) && (best === null || value > best)) best = value;
}
return best;
};
const minOf = (items, read) => {
let best = null;
for (const item of items) {
const value = finite(read(item));
if (Number.isFinite(value) && (best === null || value < best)) best = value;
}
return best;
};
/** Element-wise sum of equal-length numeric arrays; shorter arrays contribute what they have. */
function sumArrays(arrays, length) {
const out = new Array(length).fill(0);
for (const arr of arrays) {
if (!Array.isArray(arr)) continue;
for (let i = 0; i < length && i < arr.length; i++) {
const value = finite(arr[i]);
if (Number.isFinite(value)) out[i] += value;
}
}
return out;
}
/**
* The result whose `read` timestamp is newest. Used wherever every node holds a replicated copy
* of the same row: they should agree, and when they don't the freshest copy is the one to show.
*/
function freshest(items, read) {
let best = null;
let bestAt = -Infinity;
for (const item of items) {
const at = finite(read(item));
if (Number.isFinite(at) && at > bestAt) {
bestAt = at;
best = item;
}
}
return best ?? items[0] ?? null;
}
const msOf = (value) => {
if (value === null || value === undefined) return NaN;
const n = typeof value === 'number' ? value : Date.parse(value);
return Number.isFinite(n) ? n : NaN;
};
const isoOrNull = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
// ---------------------------------------------------------------- the envelope
/**
* The provenance block every cluster-scoped response carries. This is the honesty contract:
* a merged number is only as trustworthy as `complete`, and `nodes[]` says exactly which node
* failed and how, so a dip in a chart can always be told apart from a node that stopped
* answering.
*/
export function sourcesOf(results, { mode, scope = 'cluster', extra = null } = {}) {
const nodes = results.map((r) => ({
origin: r.origin,
hostname: r.hostname,
ok: !!r.ok,
status: r.status ?? 0,
error: r.error ?? null,
ms: Number.isFinite(r.ms) ? r.ms : null,
// How long ago the console's read cache fetched this node's answer; null when it was read now.
ageMs: Number.isFinite(r.ageMs) ? r.ageMs : null,
}));
const answered = nodes.filter((n) => n.ok).length;
return {
mode,
scope,
answered,
configured: nodes.length,
complete: answered === nodes.length && answered > 0,
nodes,
...(extra ?? {}),
};
}
/** Everything that answered with a usable body. */
const okBodies = (results) => results.filter((r) => r.ok && r.body && typeof r.body === 'object');
/**
* The response when nothing answered. A 502 rather than an empty aggregate: zero serves across
* a cluster that is actually up is the single most dangerous number this console could print.
*/
const allFailed = (results, mode) => ({
status: 502,
body: {
error: 'No prerender node answered.',
sources: sourcesOf(results, { mode }),
},
});
// ---------------------------------------------------------------- analytics
const comboKey = (s) => `${s.metric} ${s.path ?? ''} ${s.method ?? ''} ${s.type ?? ''}`;
/**
* Merge per-node analytics windows into one cluster window.
*
* BUCKETS ALIGN BY INDEX, NOT BY TIMESTAMP. Every node derives `bucketMs` deterministically
* from the same requested range, so bucket *i* means the same elapsed offset everywhere; the
* nodes' window starts differ only by the few milliseconds between the fan-out's requests
* (reported as `skewMs`, and always far under a ≥60s bucket). A node that clamped the range
* differently — a peer running an older plugin, or a smaller `management.analytics.maxRange` —
* produces a DIFFERENT bucket width, and index alignment would then silently smear two
* timebases together. Those nodes are dropped from the merge and reported as failed sources
* with the reason, which is the one outcome an operator can act on.
*
* DISTRIBUTIONS ARE COUNT-WEIGHTED AND APPROXIMATE, twice over: once inside each node (merging
* Harper's per-combo aggregates) and again here. The weight available in the payload is the
* bucket's `count`, which slightly over-weights buckets containing rows that carried no stats;
* for value metrics — where a row without a mean is vanishing — the error is negligible. The UI
* writes "≈" on every merged percentile for exactly this reason. A merged p95 is a trend line,
* never an SLO.
*/
/**
* Which series get PER-NODE BUCKETS in the merged analytics payload: bot serves (by source and
* verdict) and render outcomes. That is what the traffic-by-instance and renders-by-node charts
* draw, and nothing else needs a per-node time axis.
*
* Collapsed over the remaining slot (the bot name on `bot_serve`) before shipping, which keeps it to
* a dozen or so arrays per node instead of one per (bot × verdict × source) — the per-instance view
* compares nodes, and a bot filter cannot narrow it (the tag on its card says so).
*/
const PER_NODE_BUCKETED = (s) => s.metric === 'bot_serve' || (s.metric === 'render' && s.path === 'outcome');
function perNodeBuckets(series, bucketCount) {
const out = new Map();
for (const s of series ?? []) {
if (!PER_NODE_BUCKETED(s)) continue;
const key = `${s.metric}\u0000${s.path ?? ''}\u0000${s.method ?? ''}`;
let acc = out.get(key);
if (!acc) {
acc = {
metric: s.metric,
path: s.path ?? null,
method: s.method ?? null,
count: 0,
counts: new Array(bucketCount).fill(0),
};
out.set(key, acc);
}
acc.count += finite(s.count) || 0;
const counts = Array.isArray(s.counts) ? s.counts : [];
for (let i = 0; i < bucketCount && i < counts.length; i++) {
const c = finite(counts[i]);
if (Number.isFinite(c)) acc.counts[i] += c;
}
}
return [...out.values()];
}
export function mergeAnalytics(results) {
const usable = okBodies(results).filter((r) => r.body.available !== false);
if (!usable.length) {
// Every node answered "analytics unavailable" (or none answered at all). Pass the first
// node's explanation through rather than inventing an empty window.
const explained = okBodies(results)[0];
if (explained) {
return {
status: 200,
body: { ...explained.body, sources: sourcesOf(results, { mode: 'merged' }) },
};
}
return allFailed(results, 'merged');
}
// DOUBLE-COUNT GUARD. When a deployment sets `analytics_replicate: true`, every node's
// hdb_analytics already holds every node's rows — the plugin says so with `scope: 'cluster'`.
// Summing would then multiply the whole cluster by N. One node answers instead.
const replicated = usable.find((r) => r.body.scope === 'cluster');
if (replicated) {
return {
status: 200,
body: {
...replicated.body,
sources: sourcesOf(results, {
mode: 'shared',
extra: {
servedBy: replicated.hostname,
note: 'analytics_replicate is on — each node’s table already holds the whole cluster, so summing would multiply it.',
},
}),
},
};
}
// Group by bucket width; the largest group wins and the rest are reported as mismatched.
const byWidth = new Map();
for (const r of usable) {
const width = finite(r.body.bucketMs);
const key = Number.isFinite(width) ? width : 'invalid';
byWidth.set(key, [...(byWidth.get(key) ?? []), r]);
}
let merged = usable;
let mismatched = [];
if (byWidth.size > 1) {
const groups = [...byWidth.entries()].sort((a, b) => b[1].length - a[1].length);
merged = groups[0][1];
mismatched = groups.slice(1).flatMap(([, group]) => group);
}
const canonical = merged[0].body;
const bucketMs = canonical.bucketMs;
const bucketCount = Math.max(...merged.map((r) => finite(r.body.bucketCount) || 0), 1);
// One accumulator per (metric, path, method, type) combo.
const combos = new Map();
for (const r of merged) {
for (const s of r.body.series ?? []) {
const key = comboKey(s);
let acc = combos.get(key);
if (!acc) {
acc = {
metric: s.metric,
path: s.path ?? null,
method: s.method ?? null,
type: s.type ?? null,
count: 0,
total: 0,
counts: new Array(bucketCount).fill(0),
value: false,
meanSum: 0,
medianSum: 0,
p95Sum: 0,
statWeight: 0,
meanSums: new Array(bucketCount).fill(0),
medianSums: new Array(bucketCount).fill(0),
p95Sums: new Array(bucketCount).fill(0),
statWeights: new Array(bucketCount).fill(0),
};
combos.set(key, acc);
}
const count = finite(s.count) || 0;
acc.count += count;
acc.total += finite(s.total) || 0;
const counts = Array.isArray(s.counts) ? s.counts : [];
for (let i = 0; i < bucketCount && i < counts.length; i++) {
const c = finite(counts[i]);
if (Number.isFinite(c)) acc.counts[i] += c;
}
// A series is a distribution if the node sent one. Weight by the node's own count.
const mean = finite(s.mean);
if (Number.isFinite(mean) && count > 0) {
acc.value = true;
acc.meanSum += mean * count;
acc.statWeight += count;
const median = finite(s.median);
if (Number.isFinite(median)) acc.medianSum += median * count;
const p95 = finite(s.p95);
if (Number.isFinite(p95)) acc.p95Sum += p95 * count;
}
if (Array.isArray(s.means)) {
acc.value = true;
for (let i = 0; i < bucketCount && i < s.means.length; i++) {
const weight = finite(counts[i]);
const m = finite(s.means[i]);
if (Number.isFinite(m) && Number.isFinite(weight) && weight > 0) {
acc.meanSums[i] += m * weight;
acc.statWeights[i] += weight;
// Carried through the cluster merge as well, or the typical-case line exists on one
// node and vanishes the moment an operator switches to cluster scope — which is the
// default view, so it would effectively not exist at all.
const med = finite(s.medians?.[i]);
if (Number.isFinite(med)) acc.medianSums[i] += med * weight;
const p = finite(s.p95s?.[i]);
if (Number.isFinite(p)) acc.p95Sums[i] += p * weight;
}
}
}
}
}
const series = [...combos.values()].map((acc) => {
const out = {
metric: acc.metric,
path: acc.path,
method: acc.method,
type: acc.type,
count: acc.count,
total: acc.total,
counts: acc.counts,
};
if (acc.value && acc.statWeight > 0) {
out.mean = acc.meanSum / acc.statWeight;
out.median = acc.medianSum / acc.statWeight;
out.p95 = acc.p95Sum / acc.statWeight;
out.means = acc.statWeights.map((w, i) => (w > 0 ? acc.meanSums[i] / w : null));
out.medians = acc.statWeights.map((w, i) => (w > 0 ? acc.medianSums[i] / w : null));
out.p95s = acc.statWeights.map((w, i) => (w > 0 ? acc.p95Sums[i] / w : null));
}
return out;
});
series.sort((a, b) => b.count - a.count || a.metric.localeCompare(b.metric));
// Per-node totals WITHOUT buckets: enough for the node table's throughput column (which
// otherwise has to print "—" for every node but one) at a few hundred bytes per node,
// instead of shipping four full bucketed payloads.
const byNode = merged.map((r) => ({
origin: r.origin,
hostname: r.hostname,
// The node's OWN `server.hostname`, which is the key QueueStatus rows use. `hostname`
// above is the configured origin's host and carries the port, so it does not join
// against the node table — this is the field that does.
node: r.body.node ?? null,
rangeMs: r.body.rangeMs ?? null,
truncated: !!r.body.truncated,
scan: r.body.scan ?? null,
totals: (r.body.series ?? []).map((s) => ({
metric: s.metric,
path: s.path ?? null,
method: s.method ?? null,
type: s.type ?? null,
count: finite(s.count) || 0,
})),
buckets: perNodeBuckets(r.body.series, bucketCount),
// Harper's own per-minute resource rows for that node (plugin v0.92.0+): CPU, memory, event loop,
// disk. Passed through per node, never summed — see `hosts` on the overview merge.
system: r.body.system ?? null,
}));
// Config that should be identical across nodes; a disagreement changes what the reference
// bands on the charts mean, so it is flagged rather than quietly taken from node one.
const intervalsJson = merged.map((r) => JSON.stringify(r.body.intervals ?? null));
const intervalsDiverge = new Set(intervalsJson).size > 1;
const truncated = merged.some((r) => r.body.truncated);
const startMs = minOf(merged, (r) => r.body.startMs);
const skewMs = (maxOf(merged, (r) => r.body.startMs) ?? 0) - (startMs ?? 0);
const failedForMerge = [
...results.filter((r) => !r.ok),
...mismatched.map((r) => ({
...r,
ok: false,
error: `bucket width ${r.body.bucketMs}ms ≠ ${bucketMs}ms (different analytics range clamp) — excluded from the merge`,
})),
];
const sourceRows = [...merged.map((r) => ({ ...r, ok: true })), ...failedForMerge];
return {
status: 200,
body: {
available: true,
scope: 'cluster',
node: null,
workerIndex: null,
rangeMs: canonical.rangeMs,
startMs,
endMs: maxOf(merged, (r) => r.body.endMs),
bucketMs,
bucketCount,
// The COVERED window is the intersection, not the union: a number summed across
// nodes is only honest over the span every contributing node actually reached.
coveredFromMs: truncated ? maxOf(merged, (r) => r.body.coveredFromMs) : startMs,
coveredToMs: truncated ? minOf(merged, (r) => r.body.coveredToMs) : maxOf(merged, (r) => r.body.endMs),
truncated,
skewMs,
intervals: canonical.intervals ?? null,
intervalsDiverge,
scan: {
scans: merged.length,
ms: maxOf(merged, (r) => r.body.scan?.ms) ?? 0,
scanned: sumOf(merged, (r) => r.body.scan?.scanned) ?? 0,
kept: sumOf(merged, (r) => r.body.scan?.kept) ?? 0,
cap: sumOf(merged, (r) => r.body.scan?.cap) ?? 0,
},
// The stalest cache in the merge bounds how fresh the whole window is.
cacheAgeMs: maxOf(merged, (r) => r.body.cacheAgeMs),
series,
byNode,
sources: sourcesOf(sourceRows, { mode: 'merged' }),
},
};
}
// ---------------------------------------------------------------- overview
/**
* Merge per-node overviews.
*
* The headline is `backlog`: each node's snapshot covers only the RenderSchedule keys it owns
* (the table is residency-pinned, and a node cannot read another node's rows without an
* unbounded replication fetch), so summing the per-node snapshots is the ONLY way to see the
* cluster's real render backlog. No single node can report it, and until now the console
* couldn't either — an operator had to open four consoles and add up the tiles.
*
* The table COUNTS are the opposite case and must not be summed: `Target`, `PrerenderedPage`
* and `Sitemap` all replicate, so every node counts the same corpus. They are taken from the
* freshest snapshot and checked for disagreement — which is itself a finding, since a
* persistent spread between nodes means replication has a gap.
*/
export function mergeOverview(results) {
const usable = okBodies(results);
if (!usable.length) return allFailed(results, 'merged');
const bodies = usable.map((r) => ({ ...r, b: r.body }));
// ---- nodes: QueueStatus replicates, so every node holds a copy of every node's row. That
// makes this the one place a fan-out sees the SAME row through four different eyes, and the
// two things worth knowing here both come out of that, without any node writing anything.
//
// LIVENESS IS NOT IN THE ROW. `statusChangedTime` is when the status last moved, and a busy
// node holding `queued` legitimately never moves — so no age threshold over it can separate
// "healthy and steady" from "dead". But the console just asked every node for this payload,
// so it knows exactly which ones answered, as of now. That is the honest liveness signal and
// it costs nothing. (Under node scope there is no fan-out and therefore no claim: the field
// is left null rather than guessed.)
//
// DISAGREEMENT IS THE OTHER SIGNAL, and it is the one nothing else can see. All four copies
// of a row should be identical once replication has caught up, so a persistent spread means
// replication is not delivering that node's writes. Measured in the field: one node's own
// copy of its row was 3 hours newer than every peer's, because its outbound replication for
// that database had been dead since morning while every other database on the same link
// flowed. Taking the freshest copy — which is what this merge used to do, silently — hides
// precisely that.
// Both keys, lowercased and port-stripped: a QueueStatus row is keyed by the node's OWN
// `server.hostname`, while a failed result only ever carries the configured origin's host —
// so neither alone joins every case. Same two-sided join, for the same reason, as the
// per-node throughput column.
const asked = new Map(); // hostname -> did it answer
const hostKey = (value) => String(value).toLowerCase().split(':')[0];
for (const r of results) {
for (const key of [r.body?.node, r.hostname]) {
if (!key) continue;
asked.set(hostKey(key), (asked.get(hostKey(key)) ?? false) || !!r.ok);
}
}
const copies = new Map(); // hostname -> [{ reporter, at, status }]
for (const { hostname: reporter, b } of bodies) {
for (const node of b.nodes ?? []) {
if (!copies.has(node.hostname)) copies.set(node.hostname, []);
copies.get(node.hostname).push({ reporter, at: msOf(node.statusChangedTime), row: node });
}
}
const nodes = [...copies.entries()]
.map(([hostname, seen]) => {
// Newest copy for the displayed status: it is the one that has actually heard from
// the node most recently. The spread beside it is what says whether to trust that.
const newest = seen.reduce((best, c) => (!best || !(best.at >= c.at) ? c : best), null);
const times = seen.map((c) => c.at).filter(Number.isFinite);
const spreadMs = times.length > 1 ? Math.max(...times) - Math.min(...times) : 0;
const answered = asked.get(hostKey(hostname));
return {
...newest.row,
// `isThisNode` is meaningless in a cluster view — there is no "this node".
isThisNode: false,
// null = not one of the configured nodes, so it was never asked and no claim is made.
responding: answered === undefined ? null : answered,
copies: seen.length,
spreadMs,
// Which reporters hold a copy older than the newest, and by how far. This is the
// replication-gap detail — named reporters, so it points at a link, not a node.
behind: seen
.filter((c) => Number.isFinite(c.at) && Number.isFinite(newest.at) && newest.at - c.at > 0)
.map((c) => ({ reporter: c.reporter, byMs: newest.at - c.at }))
.sort((a, b) => b.byMs - a.byMs),
};
})
.sort((a, b) => String(a.hostname).localeCompare(String(b.hostname)));
// ---- table counts: replicated, so compare rather than add.
const freshestCounts = freshest(bodies, (r) => msOf(r.b.countsAsOf));
const counts = mergeCounts(bodies, freshestCounts?.b?.counts ?? null);
// ---- backlog: node-local slices of one cluster-wide queue. SUM.
const runs = bodies.map((r) => r.b.backlog?.lastRun).filter(Boolean);
const bucketLength = Math.max(0, ...runs.map((run) => (Array.isArray(run.buckets) ? run.buckets.length : 0)));
const summedBuckets = sumArrays(
runs.map((run) => (run.buckets ?? []).map((bucket) => bucket.count)),
bucketLength
).map((count, hour) => ({ hour, count }));
// Since plugin v0.93.0 a snapshot's queue half comes from the node's queue keeper, and a node
// whose keeper was not live at snapshot time reports `queueUnavailable` with a null `overdue`.
// `sumOf` skips a null, so that node would silently drop out of "due now" — named instead, the
// same way as a node with no snapshot at all.
const unavailable = bodies
.filter((r) => r.b.backlog?.lastRun && !r.b.backlog.lastRun.error && !Number.isFinite(r.b.backlog.lastRun.overdue))
.map((r) => r.hostname);
const backlogRun = runs.length
? {
overdue: sumOf(runs, (run) => run.overdue),
inFlight: sumOf(runs, (run) => run.inFlight),
buckets: summedBuckets,
scanned: sumOf(runs, (run) => run.scanned),
truncated: runs.some((run) => run.truncated),
horizonMs: runs[0]?.horizonMs ?? null,
source: runs.find((run) => run.source)?.source ?? null,
// A sum is only as fresh as its STALEST input — and only as complete as its
// narrowest, so a node with no snapshot yet is named rather than counted as zero.
finishedAt: minOf(runs, (run) => msOf(run.finishedAt)),
startedAt: minOf(runs, (run) => msOf(run.startedAt)),
counts,
error: runs.find((run) => run.error)?.error ?? null,
nodes: runs.length,
missing: bodies.filter((r) => !r.b.backlog?.lastRun).map((r) => r.hostname),
unavailable,
}
: null;
// ---- leases: live, per node. In flight ADDS across nodes — it is the cluster's render
// concurrency — but slot pressure is per node (each node has its own lease table, and a full one
// refuses grants there however empty the others are), so the worst node is kept beside the sum.
const leaseRows = bodies
.filter((r) => r.b.leases && typeof r.b.leases === 'object')
.map((r) => ({
hostname: r.hostname,
occupancy: num(finite(r.b.leases.occupancy)),
maxLeases: num(finite(r.b.leases.maxLeases)),
oldestLeaseAgeMs: num(finite(r.b.leases.oldestLeaseAgeMs)),
oldestLeaseExpiresAt: num(finite(r.b.leases.oldestLeaseExpiresAt)),
}));
const slotShare = (row) =>
row.maxLeases > 0 && Number.isFinite(row.occupancy) ? row.occupancy / row.maxLeases : NaN;
let fullest = null;
for (const row of leaseRows) {
const share = slotShare(row);
if (Number.isFinite(share) && (fullest === null || share > slotShare(fullest))) fullest = row;
}
const leases = leaseRows.length
? {
occupancy: sumOf(leaseRows, (row) => row.occupancy),
maxLeases: sumOf(leaseRows, (row) => row.maxLeases),
oldestLeaseAgeMs: maxOf(leaseRows, (row) => row.oldestLeaseAgeMs),
oldestLeaseExpiresAt: minOf(leaseRows, (row) => row.oldestLeaseExpiresAt),
fullestNode: fullest?.hostname ?? null,
fullestShare: fullest ? slotShare(fullest) : null,
// A node that answered without the block (an older plugin) is named, not counted as idle.
missing: bodies.filter((r) => !(r.b.leases && typeof r.b.leases === 'object')).map((r) => r.hostname),
byNode: leaseRows,
}
: null;
// ---- reconcile: per-node sweeps over each node's own keys. Sum the work, and name any
// node where the sweep is OFF — one node with reconcile disabled is a silent hole in the
// corpus, and a cluster view that reported "enabled" because three nodes were would hide it.
const reconciles = bodies.map((r) => ({ hostname: r.hostname, ...(r.b.reconcile ?? {}) }));
const sweeps = reconciles.map((r) => r.lastRun).filter(Boolean);
const reconcile = {
enabled: reconciles.every((r) => r.enabled !== false),
disabledOn: reconciles.filter((r) => r.enabled === false).map((r) => r.hostname),
interval: reconciles.find((r) => Number.isFinite(r.interval))?.interval ?? null,
running: reconciles.some((r) => r.running),
lastRun: sweeps.length
? {
examined: sumOf(sweeps, (s) => s.examined),
owned: sumOf(sweeps, (s) => s.owned),
restored: sumOf(sweeps, (s) => s.restored),
truncated: sweeps.some((s) => s.truncated),
finishedAt: minOf(sweeps, (s) => msOf(s.finishedAt)),
error: sweeps.find((s) => s.error)?.error ?? null,
nodes: sweeps.length,
}
: null,
};
// ---- orphan sweep: same node scope as reconcile, so the same sum — but MANUAL, which
// changes what the merge has to say. There is no cadence to report and no "disabled on"
// hole to name; the interesting shortfall is the opposite one, a node nobody has swept.
// `sweptNodes` vs the answering node count is what says so, since a node that has never run
// it contributes zero to every total here and that is indistinguishable from a clean node.
const orphanRuns = bodies.map((r) => ({ hostname: r.hostname, ...(r.b.orphanSweep ?? {}) }));
const orphanSweeps = orphanRuns.map((r) => r.lastRun).filter(Boolean);
const orphanSweep = {
maxDeletes: orphanRuns.find((r) => Number.isFinite(r.maxDeletes))?.maxDeletes ?? null,
dryRunDefault: orphanRuns.some((r) => r.dryRunDefault),
running: orphanRuns.some((r) => r.running),
sweptNodes: orphanSweeps.length,
unsweptNodes: orphanRuns.filter((r) => !r.lastRun).map((r) => r.hostname),
lastRun: orphanSweeps.length
? {
examined: sumOf(orphanSweeps, (s) => s.examined),
owned: sumOf(orphanSweeps, (s) => s.owned),
orphaned: sumOf(orphanSweeps, (s) => s.orphaned),
deleted: sumOf(orphanSweeps, (s) => s.deleted),
leaseSkipped: sumOf(orphanSweeps, (s) => s.leaseSkipped),
truncated: orphanSweeps.some((s) => s.truncated),
// A cluster figure counts as a dry run only if EVERY node's was: one node that
// actually deleted makes "nothing was deleted" false.
dryRun: orphanSweeps.every((s) => s.dryRun),
finishedAt: minOf(orphanSweeps, (s) => msOf(s.finishedAt)),
error: orphanSweeps.find((s) => s.error)?.error ?? null,
nodes: orphanSweeps.length,
}
: null,
};
const controlRows = bodies.map((r) => r.b.control?.cluster).filter(Boolean);
const intervalsJson = bodies.map((r) => JSON.stringify(r.b.intervals ?? null));
return {
status: 200,
body: {
// The aggregate is as of its oldest constituent, not its newest.
generatedAt: minOf(bodies, (r) => r.b.generatedAt),
node: null,
workerIndex: null,
scope: 'cluster',
localQueueStatus: null,
queueStatusByNode: Object.fromEntries(bodies.map((r) => [r.hostname, r.b.localQueueStatus ?? null])),
// Point-in-time host vitals (plugin v0.92.0+), one entry per node that answered and NEVER merged:
// a CPU, memory or uptime figure means something only for the node that reported it, and an
// average of four would hide exactly the node that is in trouble. `host` is null for a plugin
// that predates it.
hosts: bodies.map((r) => ({
origin: r.origin,
hostname: r.hostname,
node: r.b.node ?? null,
host: r.b.host ?? null,
})),
control: {
cluster: freshest(controlRows, (row) => msOf(row.updatedTime)) ?? null,
knownScopes: [...new Set(bodies.flatMap((r) => r.b.control?.knownScopes ?? []))],
},
nodes,
counts,
countsAsOf: freshestCounts?.b?.countsAsOf ?? null,
backlog: {
enabled: bodies.some((r) => r.b.backlog?.enabled),
disabledOn: bodies.filter((r) => r.b.backlog?.enabled === false).map((r) => r.hostname),
interval: bodies.find((r) => Number.isFinite(r.b.backlog?.interval))?.b.backlog.interval ?? null,
running: bodies.some((r) => r.b.backlog?.running),
lastRun: backlogRun,
},
intervals: bodies[0].b.intervals ?? null,
intervalsDiverge: new Set(intervalsJson).size > 1,
leases,
reconcile,
orphanSweep,
sources: sourcesOf(results, { mode: 'merged' }),
},
};
}
/**
* Table counts across nodes. Every counted table replicates, so the nodes should agree;
* `divergent` marks the ones that don't. A count is an estimate on a large table, so the
* threshold is generous — this is looking for a replication GAP, not for jitter.
*/
const DIVERGENCE_THRESHOLD = 0.02;
function mergeCounts(bodies, representative) {
if (!representative) return null;
const out = {};
for (const [table, value] of Object.entries(representative)) {
const observed = bodies
.map((r) => ({ hostname: r.hostname, count: finite(r.b.counts?.[table]?.recordCount) }))
.filter((o) => Number.isFinite(o.count));
const high = Math.max(...observed.map((o) => o.count), 0);
const low = observed.length ? Math.min(...observed.map((o) => o.count)) : 0;
const divergent = observed.length > 1 && high > 0 && (high - low) / high > DIVERGENCE_THRESHOLD;
out[table] = {
...value,
divergent,
...(divergent ? { spread: { low, high, byNode: observed } } : {}),
};
}
return out;
}
// ---------------------------------------------------------------- unrouted
/**
* The unrouted tally, summed across nodes.
*
* It stays labelled `perWorker` because it still is: each node answers from ONE worker's
* in-process counters, so the cluster sum is a sum of N single-worker slices, not the cluster's
* traffic. That understatement is why the panel exists at all (it answers "is anything hitting
* a route we don't classify", not "how much"), and the payload keeps saying so.
*/
export function mergeUnrouted(results) {
const usable = okBodies(results);
if (!usable.length) return allFailed(results, 'merged');
const classes = new Set();
for (const r of usable) {
for (const key of Object.keys(r.body.report ?? {})) {
if (Array.isArray(r.body.report[key])) classes.add(key);
}
}
const report = { overflowed: usable.some((r) => r.body.report?.overflowed) };
for (const routeClass of classes) {
const merged = new Map();
for (const r of usable) {
for (const row of r.body.report?.[routeClass] ?? []) {
const existing = merged.get(row.bucket);
if (existing) existing.count += finite(row.count) || 0;
else merged.set(row.bucket, { bucket: row.bucket, count: finite(row.count) || 0, samplePath: row.samplePath });
}
}
report[routeClass] = [...merged.values()].sort((a, b) => b.count - a.count);
}
return {
status: 200,
body: {
node: null,
workerIndex: null,
scope: 'cluster',
perWorker: true,
workers: usable.length,
interval: usable[0].body.interval ?? null,
report,
sources: sourcesOf(results, { mode: 'merged' }),
},
};
}
// ---------------------------------------------------------------- config
/** Bound on the reported divergence list — a truly divergent pair would otherwise be huge. */
const MAX_DIVERGENCES = 60;
/**
* Flatten an object to dotted leaf paths. Arrays are leaves (order matters and an element-wise
* diff of, say, a route list is noise, not a finding).
*/
function flatten(value, prefix = '', out = new Map()) {
if (value && typeof value === 'object' && !Array.isArray(value)) {
for (const [key, child] of Object.entries(value)) flatten(child, prefix ? `${prefix}.${key}` : key, out);
} else {
out.set(prefix, JSON.stringify(value ?? null));
}
return out;
}
/**
* Every option path some node reports a stored override for.
*
* TWO SOURCES, and both are load-bearing, because they disagree in exactly the window this
* function exists to explain. `overrides.rows` is the replicated TABLE as that node last read it;
* `layers[].overridden` is the layer that node has actually APPLIED. A set still in flight is a
* row nobody has applied yet (table only); a CLEAR still in flight is a node running an override
* no row backs any more (applied layer only). Reading either alone misfiles one of the two as a
* deploy failure — see the classification below.
*/
function overriddenPaths(usable) {
const paths = new Set();
for (const r of usable) {
for (const row of r.body.overrides?.rows ?? []) {
if (typeof row?.path === 'string' && row.path) paths.add(row.path);
}
for (const layer of r.body.layers ?? []) {
if (layer?.overridden && typeof layer.path === 'string' && layer.path) paths.add(layer.path);
}
}
return paths;
}
/**
* The override layer, cluster-wide.
*
* The ROWS replicate, so they are the union and `missingOn` names any node a row has not reached —
* the direct readout of "the edit is still landing" that keeps an operator from reading the
* divergence list as a broken deploy.
*
* The WATCH STATE does not replicate and is per node and per worker: whether that node's
* subscription is live, when its backstop last re-read, and whether either is erroring. It is
* therefore reported per node and the scalar `watch` is deliberately ABSENT from the cluster
* answer — a single watch object here would be node one's, and a node whose override watch has
* died is precisely the node that silently stops honouring every edit made from this console.
* `degraded` rolls up as ANY, for the same reason.
*
* Returns null for a plugin that predates the override layer, so the reference body passes
* through untouched rather than growing an empty section.
*/
function mergeOverrides(usable) {
if (!usable.some((r) => r.body.overrides && typeof r.body.overrides === 'object')) return null;
const hostnames = usable.map((r) => r.hostname);
const rows = new Map();
for (const r of usable) {
for (const row of r.body.overrides?.rows ?? []) {
if (typeof row?.path !== 'string' || !row.path) continue;
let entry = rows.get(row.path);
if (!entry) rows.set(row.path, (entry = { row, presentOn: [] }));
entry.presentOn.push(r.hostname);
}
}
return {
// True only if EVERY node honours the layer: the kill switch is a file option, so a node
// where it is off is running the deployed config while the console lists rows it obeys.
// (That difference is also a real config divergence, and shows up as one.)
enabled: usable.every((r) => r.body.overrides?.enabled !== false),
rows: [...rows.values()].map(({ row, presentOn }) => ({
...row,
missingOn: hostnames.filter((hostname) => !presentOn.includes(hostname)),
})),
degraded: usable.some((r) => r.body.overrides?.degraded === true),
truncated: usable.some((r) => r.body.overrides?.truncated === true),
error: usable.map((r) => r.body.overrides?.error).find((error) => error) ?? null,
nodes: usable.map((r) => ({
hostname: r.hostname,
enabled: r.body.overrides?.enabled ?? null,
degraded: r.body.overrides?.degraded ?? null,
truncated: r.body.overrides?.truncated ?? null,
error: r.body.overrides?.error ?? null,
rowCount: (r.body.overrides?.rows ?? []).length,
watch: r.body.overrides?.watch ?? null,
})),
};
}
/**
* Compare each node's effective config against the first node's.
*
* THIS IS THE ONE PLACE A HALF-APPLIED DEPLOY IS VISIBLE. A component deploy that restarts
* three nodes and silently skips the fourth leaves a cluster running two versions of its own
* configuration, and every other panel keeps looking healthy — the skipped node serves traffic,
* reports queue status, and answers this API. The only symptom is that its options differ.
*
* SINCE THE OVERRIDE LAYER, DISAGREEMENT HAS A SECOND CAUSE, and it is a benign one. An override
* written from this console commits on one node and reaches the rest by replication, so between
* the write and every node re-reading the table the cluster genuinely disagrees about that path —
* a state that ends by itself in about a second, or by `management.overrides.syncInterval` if a
* node's subscription never established. Left unclassified, every config edit an operator makes
* here raises the alarm that means "a deploy skipped a node", and an alarm that fires on its own
* console's normal operation stops being read at all. So each divergence carries `overridden`:
* true means some node has an override in play at that path and this is the layer converging (or,
* if it persists, an override one node is refusing — the `override-rejected` state, visible in
* that node's `layers`); false is the original finding, unchanged and still a deploy failure.
*/
export function mergeConfig(results) {
const usable = okBodies(results);
if (!usable.length) return allFailed(results, 'compared');
const reference = usable[0];
const referenceFlat = flatten(reference.body.config ?? {});
const overridden = overriddenPaths(usable);
const divergences = [];
let truncated = false;
for (const r of usable.slice(1)) {
const flat = flatten(r.body.config ?? {});
const paths = new Set([...referenceFlat.keys(), ...flat.keys()]);
for (const path of paths) {
if (referenceFlat.get(path) === flat.get(path)) continue;
if (divergences.length >= MAX_DIVERGENCES) {