-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlive-flow.vue
More file actions
1936 lines (1748 loc) · 87.8 KB
/
Copy pathlive-flow.vue
File metadata and controls
1936 lines (1748 loc) · 87.8 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
<script type="text/ecmascript-6">
import FailedJobModal from './live-flow/FailedJobModal.vue';
import FlowActivity from './live-flow/FlowActivity.vue';
import FlowGraph from './live-flow/FlowGraph.vue';
import FlowInspector from './live-flow/FlowInspector.vue';
import FlowKpis from './live-flow/FlowKpis.vue';
import FlowQueueTable from './live-flow/FlowQueueTable.vue';
import FlowToolbar from './live-flow/FlowToolbar.vue';
import SupervisorControls from './live-flow/SupervisorControls.vue';
import formatters from './live-flow/formatters';
import { loadViewState, saveViewState } from './live-flow/viewState';
const TIME_RANGES = ['Last 5m', 'Last 15m', 'Last 1h', 'Last 6h', 'Last 24h', 'Last 3d', 'Last 7d', 'Last 30d'];
export default {
components: { FailedJobModal, FlowActivity, FlowGraph, FlowInspector, FlowKpis, FlowQueueTable, FlowToolbar, SupervisorControls },
mixins: [formatters],
data() {
const saved = loadViewState();
return {
flow: null,
ready: false,
refreshing: false,
live: true,
filterText: typeof saved.filterText === 'string' ? saved.filterText : '',
timeRange: TIME_RANGES.includes(saved.timeRange) ? saved.timeRange : 'Last 15m',
selectedId: null,
isDark: this.sniffDark(),
retryingJobs: [],
selectedJob: null,
selectedJobDetails: null,
loadingJobDetails: false,
masters: [],
controllingHorizon: [],
lastEventTimestamp: 0,
queueJobDetails: {},
eventSpawns: [],
flowCounts: { dispatched: 0, reserved: 0, completed: 0, failed: 0 },
zoom: Number.isFinite(saved.zoom) ? Math.min(2.5, Math.max(0.35, saved.zoom)) : 1,
kpiHistory: { pending: [], processing: [], delayed: [], failed: [], flow: [], wait: [] },
queueSnapshots: {},
};
},
watch: {
selectedId(id) {
const node = this.graphNodeLookup[id];
if (!node || node.type !== 'queue') return;
const queue = this.queues.find(q => this.queueNodeId(q) === node.id || this.findQueueNode(q)?.id === node.id);
if (queue) {
this.fetchQueueJobs(queue);
this.fetchQueueSnapshots(queue);
}
},
timeRange(value) {
// Reset the events cursor so the next /events poll fetches the
// freshly-scoped window. Drop the rendered events too — they were
// tied to the prior window.
this.lastEventTimestamp = Math.max(0, Math.floor(Date.now() / 1000) - this.timeRangeSeconds());
this.mergeFlow({ events: [] });
this.refreshSummary();
this.refreshGraph();
this.refreshQueues();
saveViewState({ timeRange: value });
},
filterText(value) {
saveViewState({ filterText: value });
},
zoom(value) {
saveViewState({ zoom: value });
},
},
mounted() {
document.title = "HorizonXBrain - Live Flow";
this.refreshAll().then(() => { this.ready = true; });
this.loadSupervisorControls();
this.startPolling();
this.isDark = this.sniffDark();
this.initDarkWatcher();
// Catch up immediately when the tab becomes visible again. The
// bootstrap flag is cleared so the backlog of events fetched
// after a long hidden stretch doesn't burst as stale particles.
this._visibilityHandler = () => {
if (document.hidden || !this.live) return;
this._eventsBootstrapped = false;
this.refreshAll();
};
document.addEventListener('visibilitychange', this._visibilityHandler);
},
beforeUnmount() {
this.stopPolling();
this._darkObserver?.disconnect();
this._mq?.removeEventListener('change', this._mqUpdate);
if (this._storageHandler) window.removeEventListener('storage', this._storageHandler);
if (this._visibilityHandler) document.removeEventListener('visibilitychange', this._visibilityHandler);
},
computed: {
summary() { return this.flow?.summary ?? {}; },
meta() { return this.flow?.meta ?? {}; },
appLabel() { return this.meta.app_name ?? this.meta.horizon_name ?? 'Laravel application'; },
generatedAt() {
if (!this.flow?.generated_at) return null;
return new Date(this.flow.generated_at).toLocaleTimeString();
},
sourceClass() {
return { mock: 'mock', redis: 'redis', database: 'db', auto: 'auto' }[this.flow?.source] ?? 'mock';
},
sourceLabel() {
if (this.flow?.source === 'auto') {
return `unified · ${(this.flow?.sources ?? []).join(' + ') || 'live'}`;
}
return { mock: 'mock · demo', redis: 'redis · live', database: 'db · live' }[this.flow?.source] ?? (this.flow ? this.flow.source : 'loading');
},
isMock() { return this.flow?.source === 'mock'; },
queues() { return this.flow?.queues ?? []; },
health() { return this.flow?.health ?? []; },
healthBanner() {
const failed = this.health.filter(h => h.status === 'failed');
if (failed.length === 0) return null;
const names = failed.map(h => h.source).join(', ');
const detail = failed.map(h => h.message).filter(Boolean).join(' · ');
return detail ? `${names}: ${detail}` : `${names} unreachable`;
},
supervisors() {
return (this.masters ?? []).flatMap(master => (master.supervisors ?? []).map(supervisor => ({
...supervisor,
master: master.name,
})));
},
filteredQueues() {
const f = this.filterText.trim().toLowerCase();
if (!f) return this.queues;
return this.queues.filter(q =>
[q.name, q.connection, q.storage_connection, q.driver, q.source].filter(Boolean).some(v => String(v).toLowerCase().includes(f))
);
},
svgHeight() {
const nodeH = 52, gap = 22, topPad = 44, botPad = 32;
const queueCount = Math.max(1, this.filteredQueues.length);
const jobCount = Math.max(1, this.queueJobNodes().length);
const workerCount = Math.max(1, (this.flow?.nodes ?? []).filter(n => n.type === 'worker').slice(0, 4).length);
const resultCount = Math.max(1, (this.flow?.nodes ?? []).filter(n => n.type === 'result').slice(0, 4).length);
const maxCol = Math.max(queueCount, jobCount, workerCount, resultCount);
return Math.max(620, topPad + maxCol * (nodeH + gap) - gap + botPad);
},
graphNodes() {
const H = this.svgHeight;
const topPad = 44, botPad = 32;
const qH = 50, jH = 46, wH = 46, rH = 50, pH = 52;
const qYMin = topPad, qYMax = H - qH - botPad;
const jYMin = topPad + 2, jYMax = H - jH - botPad - 2;
const wYMin = topPad + 4, wYMax = H - wH - botPad - 4;
const rYMin = topPad, rYMax = H - rH - botPad;
const midY = H / 2;
const queues = this.filteredQueues.map((queue, i) => {
return {
id: this.queueGraphId(queue),
type: 'queue', label: queue.name, sub: this.queueSubLabel(queue),
status: this.queueStatus(queue),
x: 205, y: this.distributedY(i, this.filteredQueues.length, qYMin, qYMax),
width: 128, height: qH,
metrics: {
pending: queue.pending, delayed: queue.delayed,
wait: queue.wait_seconds, processes: queue.processes,
throughput: queue.throughput_per_minute,
current_throughput: queue.current_throughput_per_minute,
failed: queue.failed,
},
};
});
const jobSources = this.queueJobNodes();
const jobNodes = jobSources.map((job, i, all) => ({
id: job.id,
type: 'job',
label: this.shortJobName(job.name),
sub: this.jobNodeSub(job),
status: this.jobNodeStatus(job),
queueId: job.queueId,
name: job.name,
x: 395,
y: this.distributedY(i, all.length || 1, jYMin, jYMax),
width: 134,
height: jH,
metrics: job,
}));
const workerList = (this.flow?.nodes ?? []).filter(n => n.type === 'worker').slice(0, 4);
const workers = workerList.map((n, i, all) => ({
id: n.id, type: 'worker', label: n.label,
sub: `${this.formatNumber(n.metrics?.processes ?? this.summary.processing)} processes`,
status: n.status,
x: 590, y: this.distributedY(i, all.length || 1, wYMin, wYMax),
width: 128, height: wH, metrics: n.metrics ?? {},
}));
const workerNodes = workers.length ? workers : [{
id: 'workers', type: 'worker', label: 'workers',
sub: `${this.formatNumber(this.summary.processing)} active`,
status: 'healthy', x: 590, y: midY - wH / 2, width: 128, height: wH,
metrics: { processes: this.summary.processing },
}];
const resultList = (this.flow?.nodes ?? []).filter(n => n.type === 'result').slice(0, 4);
const results = resultList.map((n, i, all) => ({
id: n.id, type: 'result', label: n.label,
sub: this.resultSubLabel(n), status: n.status,
x: 790, y: this.distributedY(i, all.length || 1, rYMin, rYMax),
width: 132, height: rH, metrics: n.metrics ?? {},
}));
const prodSpread = Math.min(120, H * 0.16);
const baseNodes = [
{
id: 'producer-app', type: 'producer', label: this.appLabel,
sub: `${this.meta.environment ?? 'app'} · ${this.formatNumber(this.summary.current_throughput_per_minute ?? this.summary.throughput_per_minute)}/m`,
status: 'healthy', x: 28, y: Math.round(midY - prodSpread - pH / 2), width: 136, height: pH,
metrics: { throughput: this.summary.throughput_per_minute, current_throughput: this.summary.current_throughput_per_minute },
},
{
id: 'producer-scheduler', type: 'producer', label: 'scheduler',
sub: `${this.formatNumber(this.summary.delayed)} delayed`,
status: this.summary.delayed > 0 ? 'warning' : 'healthy',
x: 28, y: Math.round(midY + prodSpread - pH / 2), width: 136, height: pH,
metrics: { delayed: this.summary.delayed },
},
...queues, ...jobNodes, ...workerNodes, ...results,
];
return baseNodes;
},
graphNodeLookup() {
return this.graphNodes.reduce((acc, n) => { acc[n.id] = n; return acc; }, {});
},
graphEdges() {
const existing = (this.flow?.edges ?? []).filter(e => this.graphNodeLookup[e.source] && this.graphNodeLookup[e.target]);
const jobNodes = this.graphNodes.filter(n => n.type === 'job');
if (existing.length && jobNodes.length === 0) return existing;
const workers = this.graphNodes.filter(n => n.type === 'worker');
const results = this.graphNodes.filter(n => n.type === 'result');
const completed = results.find(n => n.label === 'completed') ?? results[0];
const failed = results.find(n => n.label === 'failed');
const generated = [];
this.graphNodes.filter(n => n.type === 'queue').forEach((q, i) => {
const w = workers[i % workers.length];
const producer = (q.status === 'critical' || q.status === 'warning') ? 'producer-scheduler' : 'producer-app';
const queueJobs = jobNodes.filter(j => j.queueId === q.id);
generated.push(this.edge(producer, q.id, q.status, 'dispatch', q.metrics.current_throughput ?? q.metrics.throughput));
if (queueJobs.length === 0) {
generated.push(this.edge(q.id, w.id, q.status, 'reserve', q.metrics.current_throughput ?? q.metrics.throughput));
return;
}
queueJobs.forEach(job => {
generated.push(this.edge(q.id, job.id, job.status, 'jobs', this.jobNodeFlow(job)));
generated.push(this.edge(job.id, w.id, job.status, 'reserve', this.jobNodeFlow(job)));
if (completed && Number(job.metrics.completed ?? 0) > 0) generated.push(this.edge(job.id, completed.id, 'healthy', 'done', job.metrics.completed));
if (failed && Number(job.metrics.failed ?? 0) > 0) generated.push(this.edge(job.id, failed.id, 'critical', 'failed', job.metrics.failed));
});
});
if (completed) workers.forEach(w => generated.push(this.edge(w.id, completed.id, 'healthy', 'finish', this.summary.throughput_per_minute)));
// Always keep a worker→failed edge so a brand-new failure event
// has a path to animate along, even before the next /summary
// refresh has incremented summary.failed. Edge stays "idle" when
// there are no failures (rate=0 ⇒ rendered as "idle" label).
if (failed && workers.length) {
const failedRate = Number(this.summary.failed_in_window ?? this.summary.failed ?? 0);
const status = failedRate > 0 ? 'critical' : 'healthy';
generated.push(this.edge(workers[workers.length - 1].id, failed.id, status, 'exception', failedRate));
}
return generated;
},
kpiMetrics() {
const windowed = this.summary.failed_in_window;
const failedValue = windowed !== null && windowed !== undefined ? windowed : this.summary.failed;
const failedSub = windowed !== null && windowed !== undefined
? `in ${this.timeRange.replace(/^Last /i, '').toLowerCase()}`
: 'all-time';
return [
{ key: 'pending', label: 'PENDING', value: this.metricValue(this.summary.pending), sub: this.formatNumber(this.queues.length) + ' queues', cls: 'primary' },
{ key: 'processing', label: 'PROCS', value: this.metricValue(this.summary.processing), sub: 'active', cls: '' },
{ key: 'delayed', label: 'DELAYED', value: this.metricValue(this.summary.delayed), sub: 'scheduled', cls: (this.summary.delayed ?? 0) > 0 ? 'warn' : '' },
{ key: 'failed', label: 'FAILED', value: this.metricValue(failedValue), sub: failedSub, cls: (failedValue ?? 0) > 0 ? 'danger' : '' },
{ key: 'flow', label: 'FLOW', value: this.metricValue(this.summary.current_throughput_per_minute ?? this.summary.throughput_per_minute), sub: 'jobs / min', cls: 'ok' },
{ key: 'wait', label: 'AVG WAIT', value: this.metricValue(this.summary.average_wait_seconds, 's'), sub: 'latency', cls: '' },
].map(metric => ({ ...metric, history: this.kpiHistory[metric.key] ?? [] }));
},
selectedNode() {
return this.graphNodeLookup[this.selectedId] ?? this.graphNodes.find(n => n.type === 'queue') ?? this.graphNodes[0];
},
selectedInspector() {
const node = this.selectedNode;
if (!node) return { node: { status: 'healthy' }, queue: null, jobClass: null, metrics: [], jobClasses: [], jobs: [], incoming: [], outgoing: [], action: { type: 'ok', title: 'Status', text: 'Loading…' } };
let queue = null;
let jobClass = null;
if (node.type === 'job') {
queue = this.queues.find(q => this.queueGraphId(q) === node.queueId) ?? null;
if (queue) {
jobClass = this.queueJobClasses(queue).find(c => c.name === node.name) ?? null;
}
} else {
queue = this.queues.find(q => this.queueNodeId(q) === node.id || this.findQueueNode(q)?.id === node.id) ?? null;
}
return {
node,
queue,
jobClass,
metrics: this.inspectorMetrics(node, queue, jobClass),
jobClasses: queue && !jobClass ? this.queueJobClasses(queue) : [],
jobs: queue ? this.queueJobs(queue).filter(job => !jobClass || job.name === jobClass.name) : [],
snapshots: queue ? (this.queueSnapshots[queue.name]?.snapshots ?? []) : [],
incoming: this.graphEdges.filter(e => e.target === node.id),
outgoing: this.graphEdges.filter(e => e.source === node.id),
action: this.suggestedAction(node, queue, jobClass),
};
},
},
methods: {
// The dark-mode signal is the same one Horizon's SchemeToggler controls:
// the `media` attribute on the `style[data-scheme="dark"]` stylesheet is
// empty when dark is active. We mirror its localStorage key so a manual
// theme choice is respected immediately.
sniffDark() {
try {
const stored = localStorage.getItem('horizonColorScheme');
if (stored === 'dark') return true;
if (stored === 'light') return false;
return window.matchMedia('(prefers-color-scheme: dark)').matches;
} catch { return false; }
},
initDarkWatcher() {
// Same-tab toggle: SchemeToggler mutates the stylesheet directly,
// so observe its `media` attribute for instant updates.
const el = document.querySelector('style[data-scheme="dark"]');
if (el) {
this._darkObserver = new MutationObserver(() => { this.isDark = this.sniffDark(); });
this._darkObserver.observe(el, { attributes: true, attributeFilter: ['media'] });
}
// Cross-tab toggle: storage event fires only in OTHER tabs.
this._storageHandler = (event) => {
if (event.key === 'horizonColorScheme') this.isDark = this.sniffDark();
};
window.addEventListener('storage', this._storageHandler);
// System preference change when scheme is 'system'.
this._mq = window.matchMedia('(prefers-color-scheme: dark)');
this._mqUpdate = () => { this.isDark = this.sniffDark(); };
this._mq.addEventListener('change', this._mqUpdate);
},
timeRangeSeconds() {
return {
'Last 5m': 300,
'Last 15m': 900,
'Last 1h': 3600,
'Last 6h': 21600,
'Last 24h': 86400,
'Last 3d': 259200,
'Last 7d': 604800,
'Last 30d': 2592000,
}[this.timeRange] ?? 900;
},
startPolling() {
// document.hidden guard: no point polling a tab nobody is
// looking at — refreshAll() on visibilitychange catches up.
this._intervals = [
setInterval(() => this.shouldPoll() && this.refreshSummary(), 5000),
setInterval(() => this.shouldPoll() && this.refreshGraph(), 10000),
setInterval(() => this.shouldPoll() && this.refreshQueues(), 10000),
setInterval(() => this.shouldPoll() && this.refreshEvents(), 2000),
];
},
shouldPoll() {
return this.live && !document.hidden;
},
stopPolling() {
(this._intervals ?? []).forEach(clearInterval);
this._intervals = [];
},
refreshAll() {
this.refreshing = true;
return Promise.all([
this.refreshSummary(),
this.refreshGraph(),
this.refreshQueues(),
this.refreshEvents(),
]).finally(() => { this.refreshing = false; });
},
refreshFlowPeriodically() {
return this.refreshAll();
},
mergeFlow(slice) {
this.flow = { ...(this.flow ?? {}), ...slice };
if (!this.selectedId || !this.graphNodeLookup[this.selectedId]) {
this.selectedId = this.graphNodes.find(n => n.type === 'queue')?.id ?? this.graphNodes[0]?.id;
}
},
refreshSummary() {
return this.$http.get(Horizon.basePath + '/api/flow/summary', {
params: { window: this.timeRangeSeconds() },
})
.then(response => {
this.mergeFlow({
source: response.data.source,
sources: response.data.sources,
errors: response.data.errors ?? [],
health: response.data.health ?? [],
meta: response.data.meta ?? {},
generated_at: response.data.generated_at,
summary: response.data.summary ?? {},
});
this.recordKpiHistory();
})
.catch(() => {});
},
// Ring buffers behind the KPI sparklines — one point per summary
// poll, capped so an afternoon-long session stays flat.
recordKpiHistory() {
const summary = this.flow?.summary ?? {};
const push = (key, value) => {
if (value === null || value === undefined) return;
const series = this.kpiHistory[key];
series.push(Number(value));
if (series.length > 60) series.shift();
};
push('pending', summary.pending);
push('processing', summary.processing);
push('delayed', summary.delayed);
push('failed', summary.failed_in_window ?? summary.failed);
push('flow', summary.current_throughput_per_minute ?? summary.throughput_per_minute);
push('wait', summary.average_wait_seconds);
},
refreshGraph() {
return this.$http.get(Horizon.basePath + '/api/flow/graph', {
params: { window: this.timeRangeSeconds() },
})
.then(response => this.mergeFlow({
nodes: response.data.nodes ?? [],
edges: response.data.edges ?? [],
}))
.catch(() => {});
},
refreshQueues() {
return this.$http.get(Horizon.basePath + '/api/flow/queues', {
params: { window: this.timeRangeSeconds() },
})
.then(response => {
this.mergeFlow({ queues: response.data.queues ?? [] });
const selected = this.selectedQueue();
if (selected) {
this.fetchQueueJobs(selected);
this.fetchQueueSnapshots(selected);
}
})
.catch(() => {});
},
refreshEvents() {
// Forward the active window so this hits the same cache slot as
// summary/graph/queues; otherwise the events poll lives in the
// default-window slot and forces a parallel payload rebuild.
const params = { window: this.timeRangeSeconds() };
if (this.lastEventTimestamp > 0) params.since = this.lastEventTimestamp;
return this.$http.get(Horizon.basePath + '/api/flow/events', { params }).then(response => {
const fresh = response.data.events ?? [];
if (fresh.length === 0) return;
const existing = this.flow?.events ?? [];
const seen = new Set();
const merged = [...fresh, ...existing]
.filter(event => {
const key = event.id ?? event.label ?? `${event.timestamp}-${event.queue}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
})
.slice(0, 60);
this.mergeFlow({ events: merged });
this.lastEventTimestamp = fresh.reduce(
(max, event) => Math.max(max, Number(event.timestamp ?? 0)),
this.lastEventTimestamp
);
// First poll returns historical events — skip them so the
// graph doesn't burst with N stale particles on page load.
// Subsequent polls are real-time deltas; each event maps to
// one dot traveling its edge plus a flow-count bump.
if (this._eventsBootstrapped) {
this.dispatchEventSpawns(fresh);
}
this._eventsBootstrapped = true;
}).catch(() => {});
},
dispatchEventSpawns(events) {
const ordered = [...events].sort((a, b) =>
Number(a.timestamp ?? 0) - Number(b.timestamp ?? 0)
);
const additions = ordered.map(event => {
this._spawnSequence = (this._spawnSequence ?? 0) + 1;
this.bumpFlowCount(event);
return { ...event, _spawnId: this._spawnSequence };
});
if (additions.length === 0) return;
const next = [...this.eventSpawns, ...additions];
this.eventSpawns = next.length > 200 ? next.slice(-200) : next;
},
bumpFlowCount(event) {
const map = {
completed: 'completed',
failed: 'failed',
workers: 'reserved',
queue: 'dispatched',
};
const key = map[event.result];
if (key) this.flowCounts[key]++;
},
loadSupervisorControls() {
return this.$http.get(Horizon.basePath + '/api/masters')
.then(response => { this.masters = Object.values(response.data ?? {}); })
.catch(() => { this.masters = []; });
},
isControllingHorizon(key) {
return this.controllingHorizon.includes(key);
},
controlMasters(action) {
const key = `masters:${action}`;
if (this.isControllingHorizon(key)) return;
this.controllingHorizon = [...this.controllingHorizon, key];
return this.$http.post(`${Horizon.basePath}/api/masters/${action}`)
.then(() => Promise.all([this.loadSupervisorControls(), this.refreshFlowPeriodically()]))
.finally(() => {
this.controllingHorizon = this.controllingHorizon.filter(item => item !== key);
});
},
controlSupervisor(supervisor, action) {
const key = `${supervisor.name}:${action}`;
if (this.isControllingHorizon(key)) return;
this.controllingHorizon = [...this.controllingHorizon, key];
return this.$http.post(`${Horizon.basePath}/api/supervisors/${encodeURIComponent(supervisor.name)}/${action}`)
.then(() => Promise.all([this.loadSupervisorControls(), this.refreshFlowPeriodically()]))
.finally(() => {
this.controllingHorizon = this.controllingHorizon.filter(item => item !== key);
});
},
selectNode(id) { this.selectedId = id; },
toggleLive() { this.live = !this.live; },
queueJobsKey(queue) {
if (!queue) return null;
if (Array.isArray(queue.drivers) && queue.drivers.length > 1) return queue.name;
return `${queue.driver}:${queue.connection}:${queue.name}`;
},
queueJobDetail(queue) {
const key = this.queueJobsKey(queue);
return key ? this.queueJobDetails[key] : null;
},
queueJobClasses(queue) {
const detail = this.queueJobDetail(queue);
const classes = detail?.job_classes ?? queue?.job_classes ?? [];
return classes.slice(0, 8);
},
queueJobs(queue) {
const detail = this.queueJobDetail(queue);
const jobs = detail?.jobs ?? queue?.jobs ?? [];
return jobs.slice(0, 12);
},
// Horizon's own metrics endpoint serves the snapshot series the
// scheduler's horizon:snapshot command records (~1/min, 24 kept).
// A short TTL keeps re-selections from hammering it.
fetchQueueSnapshots(queue) {
const name = queue?.name;
if (!name) return Promise.resolve();
const entry = this.queueSnapshots[name];
if (entry && Date.now() - entry.fetchedAt < 60000) return Promise.resolve();
this.queueSnapshots = {
...this.queueSnapshots,
[name]: { fetchedAt: Date.now(), snapshots: entry?.snapshots ?? [] },
};
return this.$http.get(Horizon.basePath + '/api/metrics/queues/' + encodeURIComponent(name))
.then(response => {
this.queueSnapshots = {
...this.queueSnapshots,
[name]: { fetchedAt: Date.now(), snapshots: Array.isArray(response.data) ? response.data : [] },
};
})
.catch(() => {});
},
fetchQueueJobs(queue) {
const key = this.queueJobsKey(queue);
if (!key) return Promise.resolve();
return this.$http.get(Horizon.basePath + '/api/flow/queue-jobs', { params: { key } })
.then(response => {
this.queueJobDetails = {
...this.queueJobDetails,
[key]: {
jobs: response.data.jobs ?? [],
job_classes: response.data.job_classes ?? [],
},
};
})
.catch(() => {});
},
selectedQueue() {
const node = this.selectedNode;
if (!node || node.type !== 'queue') return null;
return this.queues.find(q => this.queueNodeId(q) === node.id || this.findQueueNode(q)?.id === node.id) ?? null;
},
queueJobNodes() {
return this.filteredQueues.flatMap(queue => {
const queueId = this.queueGraphId(queue);
if (this.zoom >= 1.35) {
return (queue.jobs ?? [])
.slice(0, 8)
.map(job => ({
id: this.jobInstanceNodeId(queue, job),
queueId,
queue: queue.name,
connection: queue.connection,
name: job.name,
individual: true,
status: job.status,
attempts: job.attempts,
age_seconds: job.age_seconds,
pending: job.status === 'pending' ? 1 : 0,
reserved: job.status === 'reserved' ? 1 : 0,
completed: job.status === 'completed' ? 1 : 0,
failed: job.status === 'failed' ? 1 : 0,
latest_error: job.exception,
}));
}
return (queue.job_classes ?? [])
.slice(0, 3)
.map(jobClass => ({
...jobClass,
id: this.jobNodeId(queue, jobClass.name),
queueId,
queue: queue.name,
connection: queue.connection,
}));
});
},
jobNodeId(queue, name) {
return `job-${queue.driver}-${queue.connection}-${queue.name}-${name}`.replace(/[^a-z0-9-]+/gi, '-').toLowerCase();
},
jobInstanceNodeId(queue, job) {
return `job-${queue.driver}-${queue.connection}-${queue.name}-${job.id ?? job.name}`.replace(/[^a-z0-9-]+/gi, '-').toLowerCase();
},
jobNodeStatus(job) {
if (job.individual) return this.jobStatusClass(job.status);
if (Number(job.failed ?? 0) > 0) return 'critical';
if (Number(job.pending ?? 0) > 0 || Number(job.reserved ?? 0) > 0) return 'warning';
return 'healthy';
},
jobNodeFlow(job) {
return Number(job.pending ?? 0) + Number(job.reserved ?? 0) + Number(job.completed ?? 0) + Number(job.failed ?? 0);
},
jobNodeSub(job) {
if (job.individual) {
return `${job.status} · attempts ${this.formatNumber(job.attempts ?? 0)} · ${this.formatDuration(job.age_seconds)}`;
}
return this.jobCounts(job);
},
jobHref(job) {
if (!job?.id) return null;
if (job.inspectable === false) return null;
if (job.status === 'failed') return `${Horizon.basePath}/failed/${job.id}`;
if (job.status === 'completed') return `${Horizon.basePath}/jobs/completed/${job.id}`;
return `${Horizon.basePath}/jobs/pending/${job.id}`;
},
isRetryingJob(job) {
return this.retryingJobs.includes(job?.id);
},
retryJob(job) {
if (!job?.id || this.isRetryingJob(job)) return;
this.retryingJobs = [...this.retryingJobs, job.id];
return this.$http.post(Horizon.basePath + '/api/jobs/retry/' + job.id)
.then(() => this.refreshFlowPeriodically())
.finally(() => {
this.retryingJobs = this.retryingJobs.filter(id => id !== job.id);
});
},
openJobModal(job) {
if (!job || job.status !== 'failed') return;
this.selectedJob = job;
this.selectedJobDetails = null;
if (job.inspectable === false || !job.id) return;
this.loadingJobDetails = true;
this.$http.get(Horizon.basePath + '/api/jobs/failed/' + job.id)
.then(response => { this.selectedJobDetails = response.data; })
.finally(() => { this.loadingJobDetails = false; });
},
closeJobModal() {
this.selectedJob = null;
this.selectedJobDetails = null;
this.loadingJobDetails = false;
},
modalJobName() {
return this.selectedJobDetails?.name ?? this.selectedJob?.name ?? 'Queued job';
},
modalJobError() {
return this.selectedJobDetails?.exception ?? this.selectedJob?.exception ?? 'No exception text was captured.';
},
edge(source, target, status, label, rate) {
return { id: `${source}-${target}`, source, target, status, label, rate_per_minute: rate };
},
distributedY(index, total, min, max) {
return total <= 1 ? (min + max) / 2 : min + ((max - min) / (total - 1)) * index;
},
findQueueNode(queue) {
return (this.flow?.nodes ?? []).find(n =>
n.type === 'queue' && (n.id === this.queueNodeId(queue) || n.label === queue.name || n.id.endsWith(`-${queue.name}`))
);
},
queueNodeId(queue) {
return `queue-${queue.driver}-${queue.connection}-${queue.name}`.replace(/[^a-z0-9-]+/gi, '-').toLowerCase();
},
// The graph node id a queue actually renders under: the backend's id
// when the payload carries one, otherwise the local fallback. Job
// nodes and the inspector must resolve queues through the same id,
// or their edges never connect to the queue they belong to.
queueGraphId(queue) {
return this.findQueueNode(queue)?.id ?? this.queueNodeId(queue);
},
queueStatus(queue) {
if (this.queueFailedInWindow(queue) > 0) return 'critical';
if (queue.wait_seconds >= 30 || queue.pending >= 500) return 'critical';
if (queue.wait_seconds >= 10 || queue.pending >= 100 || queue.delayed > 0) return 'warning';
return 'healthy';
},
queueSubLabel(queue) {
const failed = this.queueFailedInWindow(queue);
if (failed > 0) return `${queue.connection} · ${this.formatNumber(failed)} failed`;
return `${queue.driver} · ${queue.connection} · ${this.formatNumber(queue.pending)} pending`;
},
// Prefer the server's windowed count — the repository computes it
// by filtering the failed_jobs index by failed_at against the
// ?window= parameter forwarded from the summary call.
queueFailedInWindow(queue) {
if (queue?.failed_in_window !== undefined && queue?.failed_in_window !== null) {
return Number(queue.failed_in_window);
}
const failed = Number(queue?.failed ?? 0);
if (failed === 0) return 0;
const lastFailedAt = this.parseTimestamp(queue?.last_failed_at);
if (lastFailedAt === null) return failed;
const cutoff = Math.floor(Date.now() / 1000) - this.timeRangeSeconds();
return lastFailedAt >= cutoff ? failed : 0;
},
parseTimestamp(value) {
if (value === null || value === undefined || value === '') return null;
if (typeof value === 'number') return value;
const parsed = Date.parse(String(value));
return Number.isFinite(parsed) ? Math.floor(parsed / 1000) : null;
},
resultSubLabel(node) {
if (node.label === 'failed') {
const nodeWindowed = node.metrics?.failed_in_window;
const summaryWindowed = this.summary.failed_in_window;
const allTime = node.metrics?.failed ?? this.summary.failed;
const windowed = nodeWindowed ?? summaryWindowed;
// When the window has no failures but historical ones exist,
// show the all-time count so the user isn't left wondering why
// a queue with failed jobs reports "0 failed".
if ((windowed === 0 || windowed === null || windowed === undefined) && Number(allTime ?? 0) > 0) {
return `${this.formatNumber(allTime)} failed (all-time)`;
}
const value = (windowed !== null && windowed !== undefined) ? windowed : allTime;
return `${this.formatNumber(value ?? 0)} failed`;
}
if (node.label === 'delayed') return `${this.formatNumber(this.summary.delayed)} delayed`;
const completedWindowed = this.summary.completed_in_window;
const completedValue = (completedWindowed !== null && completedWindowed !== undefined)
? completedWindowed
: this.summary.completed;
return `${this.formatNumber(completedValue)} completed`;
},
inspectorMetrics(node, queue, jobClass) {
if (jobClass) return [
['queue', queue?.name ?? '—'],
['class', this.shortJobName(jobClass.name)],
['full name', jobClass.name],
['pending', this.formatNumber(jobClass.pending ?? 0)],
['reserved', this.formatNumber(jobClass.reserved ?? 0)],
['completed', this.formatNumber(jobClass.completed ?? 0)],
['failed', this.formatNumber(jobClass.failed ?? 0)],
['attempts', this.formatNumber(jobClass.attempts ?? 0)],
['latest error', jobClass.latest_error ?? 'none'],
];
if (queue) {
const failedInWindow = this.queueFailedInWindow(queue);
const allTimeFailed = Number(queue.failed ?? 0);
const windowLabel = this.timeRange.replace(/^Last /i, '').toLowerCase();
const failedDisplay = failedInWindow === allTimeFailed
? this.formatNumber(allTimeFailed)
: `${this.formatNumber(failedInWindow)} in ${windowLabel} · ${this.formatNumber(allTimeFailed)} all-time`;
return [
['source', queue.source ?? queue.driver],
['connection', queue.connection],
['storage', queue.storage_connection ?? '—'],
['driver', queue.driver],
['pending', this.formatNumber(queue.pending)],
['delayed', this.formatNumber(queue.delayed)],
['oldest pending', this.formatDuration(queue.oldest_pending_seconds ?? queue.wait_seconds)],
['wait', this.metricValue(queue.wait_seconds, 's')],
['processes', this.formatNumber(queue.processes)],
['current rate', this.formatRate(queue.current_throughput_per_minute)],
['recent activity', this.formatRate(queue.recent_activity_per_minute)],
['last measured', this.formatRate(queue.throughput_per_minute)],
['drain ETA', this.formatDuration(queue.estimated_drain_seconds)],
['attempts', this.formatNumber(queue.attempts ?? 0)],
['failed', failedDisplay],
['failure rate', this.formatPercent(queue.failure_rate)],
['latest error', failedInWindow > 0 ? (queue.latest_error ?? 'none') : 'none in window'],
];
}
return Object.entries(node.metrics ?? {}).map(([k, v]) => [k.replace(/_/g, ' '), this.formatNumber(v)]);
},
suggestedAction(node, queue, jobClass) {
if (jobClass) {
if (Number(jobClass.failed ?? 0) > 0) {
return { type: 'critical', title: 'Immediate Action', text: jobClass.latest_error
? `${this.shortJobName(jobClass.name)} is failing. Latest error: ${jobClass.latest_error}`
: `${this.shortJobName(jobClass.name)} has ${this.formatNumber(jobClass.failed)} failed instance${jobClass.failed === 1 ? '' : 's'}. Inspect the failed jobs.` };
}
if (Number(jobClass.pending ?? 0) > 0 || Number(jobClass.reserved ?? 0) > 0) {
return { type: 'warn', title: 'In Flight', text: `${this.shortJobName(jobClass.name)} has ${this.formatNumber((jobClass.pending ?? 0) + (jobClass.reserved ?? 0))} job${(jobClass.pending ?? 0) + (jobClass.reserved ?? 0) === 1 ? '' : 's'} working through the queue.` };
}
return { type: 'ok', title: 'Status', text: `${this.shortJobName(jobClass.name)} is idle.` };
}
// Result nodes (completed/failed) need their own messaging:
// they have no queue context, and "backpressure" wording for a
// failed node is nonsense.
if (node.type === 'result' && node.label === 'failed') {
const inWindow = Number(node.metrics?.failed_in_window ?? this.summary.failed_in_window ?? 0);
const allTime = Number(node.metrics?.failed ?? this.summary.failed ?? 0);
const link = { to: { name: 'failed-jobs' }, text: 'View failed jobs →' };
if (inWindow > 0) {
return { type: 'critical', title: 'Immediate Action', text: `${this.formatNumber(inWindow)} job${inWindow === 1 ? '' : 's'} failed in the active window. Inspect the failures.`, link };
}
if (allTime > 0) {
return { type: 'warn', title: 'Heads Up', text: `No recent failures, but ${this.formatNumber(allTime)} historical failure${allTime === 1 ? '' : 's'} on record.`, link };
}
return { type: 'ok', title: 'Status', text: 'No failed jobs.' };
}
if (node.status === 'critical') {
const failedInWindow = queue ? this.queueFailedInWindow(queue) : 0;
if (queue && failedInWindow > 0) {
return { type: 'critical', title: 'Immediate Action', text: queue.latest_error
? `${queue.name} has ${this.formatNumber(failedInWindow)} failed jobs in window. Latest error: ${queue.latest_error}`
: `${queue.name} has ${this.formatNumber(failedInWindow)} failed jobs in window. Inspect the failures.`,
link: { to: { name: 'failed-jobs' }, text: 'View failed jobs →' } };
}
return { type: 'critical', title: 'Immediate Action', text: queue
? `Backlog is critical on ${queue.name}. Scale workers or reduce dispatch rate.`
: 'Backpressure above normal. Inspect the workload.' };
}
if (node.status === 'warning') return { type: 'warn', title: 'Suggested Action', text: queue ? `${queue.name} is showing backpressure. Consider increasing process capacity.` : 'This node is under pressure. Monitor incoming rates.' };
return { type: 'ok', title: 'Status', text: 'Node is operating normally. No action required.' };
},
},
}
</script>
<template>
<div class="lf" :class="{ 'lf-dark': isDark }">
<FlowToolbar
:flow="flow"
:source-class="sourceClass"
:source-label="sourceLabel"
:generated-at="generatedAt"
:refreshing="refreshing"
:live="live"
v-model:filterText="filterText"
v-model:timeRange="timeRange"
@refresh="refreshFlowPeriodically"
@toggle-live="toggleLive"
/>
<!-- source health -->
<div class="lf-notice lf-notice-warn" v-if="ready && healthBanner">
<svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor" style="flex-shrink:0;opacity:.8">
<path fill-rule="evenodd" d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd"/>
</svg>
{{ healthBanner }}
</div>
<!-- demo notice -->
<div class="lf-notice lf-notice-warn" v-if="ready && isMock">
<svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor" style="flex-shrink:0;opacity:.8">
<path fill-rule="evenodd" d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd"/>
</svg>
Demo data — configure a Redis or database connection to see live telemetry.
</div>
<FlowKpis :metrics="kpiMetrics" />
<!-- loading -->