forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflow.ts
More file actions
1335 lines (1214 loc) · 36.5 KB
/
Copy pathflow.ts
File metadata and controls
1335 lines (1214 loc) · 36.5 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
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type {
DashboardFlowGraph,
DashboardFlowLink,
DashboardFlowNode,
FlowBuildOptions,
FlowFilterOptions,
FlowLinkSelection,
FlowMetric,
FlowNodeFilter,
FlowNodeKind,
FlowOverflowMode,
FlowQuotaDataItem,
FlowRole,
FlowSummary,
ProcessedFlowData,
} from '@/features/dashboard/types'
import { getDashboardChartColors } from './charts'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type VChartSpec = Record<string, any>
type FlowMetrics = {
quota: number
tokens: number
requests: number
}
type FlowSankeyLabels = {
quota: string
tokens: string
requests: string
share: string
}
type FlowPathNode = {
id: string
label: string
kind: FlowNodeKind
}
type PreparedFlowPath = {
path: FlowPathNode[]
metrics: FlowMetrics
}
type FlowNodeRank = {
node: FlowPathNode
value: number
}
type FlowPathContext = {
deletedTokenLabel?: (tokenId: number) => string
}
type FlowGraphOptions = {
topNodeLimit?: number
overflowMode?: FlowOverflowMode
otherNodeLabel?: (kind: FlowNodeKind) => string
activeNode?: FlowNodeFilter
activeLink?: FlowLinkSelection
maskSensitive?: boolean
}
type FlowHighlightSets = {
nodes: Set<string>
links: Set<string>
}
const EMPTY_FLOW_PATH_CONTEXT: FlowPathContext = {}
const DEFAULT_FLOW_ROLE: FlowRole = 'user'
const DEFAULT_FLOW_OVERFLOW_MODE: FlowOverflowMode = 'aggregate'
const DEFAULT_FLOW_SANKEY_LABELS: FlowSankeyLabels = {
quota: 'Quota',
tokens: 'Tokens',
requests: 'Requests',
share: 'Share',
}
const DEFAULT_FLOW_CHART_COLOR = '#1664FF'
const FLOW_NODE_KINDS: readonly FlowNodeKind[] = [
'user',
'node',
'token',
'group',
'model',
'channel',
]
const FLOW_NODE_KIND_SET = new Set<FlowNodeKind>(FLOW_NODE_KINDS)
const OTHER_FLOW_NODE_IDS: Record<FlowNodeKind, string> = {
user: 'user:__other__',
node: 'node:__other__',
token: 'token:__other__',
group: 'group:__other__',
model: 'model:__other__',
channel: 'channel:__other__',
}
const DEFAULT_OTHER_FLOW_NODE_LABELS: Record<FlowNodeKind, string> = {
user: 'Other users',
node: 'Other nodes',
token: 'Other tokens',
group: 'Other groups',
model: 'Other models',
channel: 'Other channels',
}
// Kinds whose labels can leak identity (people, keys, infra, business setup).
// Model names are public, so they stay visible even when masking is on.
const SENSITIVE_FLOW_KINDS = new Set<FlowNodeKind>([
'user',
'node',
'token',
'group',
'channel',
])
const OTHER_FLOW_NODE_ID_SET = new Set<string>(
Object.values(OTHER_FLOW_NODE_IDS)
)
function numberValue(value: unknown): number {
const n = Number(value)
return Number.isFinite(n) ? n : 0
}
function isFlowNodeKind(value: unknown): value is FlowNodeKind {
return (
typeof value === 'string' && FLOW_NODE_KIND_SET.has(value as FlowNodeKind)
)
}
function rowMetrics(row: FlowQuotaDataItem): FlowMetrics {
return {
quota: numberValue(row.quota),
tokens: numberValue(row.token_used),
requests: numberValue(row.count),
}
}
function metricValue(metrics: FlowMetrics, metric: FlowMetric): number {
if (metric === 'requests') return metrics.requests
if (metric === 'tokens') return metrics.tokens
return metrics.quota
}
function userNode(row: FlowQuotaDataItem): FlowPathNode {
const userID = numberValue(row.user_id)
return {
id: userID > 0 ? `user:${userID}` : `user:${row.username || 'unknown'}`,
label: row.username || (userID > 0 ? `user-${userID}` : 'Unknown User'),
kind: 'user',
}
}
function nodeNameNode(row: FlowQuotaDataItem): FlowPathNode {
const nodeName = row.node_name || 'default-node'
return {
id: `node:${nodeName}`,
label: nodeName,
kind: 'node',
}
}
function tokenNode(row: FlowQuotaDataItem, ctx: FlowPathContext): FlowPathNode {
const tokenID = numberValue(row.token_id)
return {
id:
tokenID > 0 ? `token:${tokenID}` : `token:${row.token_name || 'unknown'}`,
label: row.token_name || deletedTokenLabel(tokenID, ctx),
kind: 'token',
}
}
function deletedTokenLabel(tokenID: number, ctx: FlowPathContext): string {
if (tokenID <= 0) return 'Unknown Token'
return ctx.deletedTokenLabel?.(tokenID) ?? `token-${tokenID}`
}
function groupNode(row: FlowQuotaDataItem): FlowPathNode {
const useGroup = row.use_group || 'unknown'
return {
id: `group:${useGroup}`,
label: useGroup,
kind: 'group',
}
}
function modelNode(row: FlowQuotaDataItem): FlowPathNode {
const model = row.model_name || 'unknown'
return {
id: `model:${model}`,
label: row.model_name || 'Unknown Model',
kind: 'model',
}
}
function channelNode(row: FlowQuotaDataItem): FlowPathNode {
const channelID = numberValue(row.channel_id)
return {
id:
channelID > 0
? `channel:${channelID}`
: `channel:${row.channel_name || 'unknown'}`,
label:
row.channel_name || (channelID > 0 ? `channel-${channelID}` : 'Unknown'),
kind: 'channel',
}
}
const NODE_BUILDERS: Record<
FlowNodeKind,
(row: FlowQuotaDataItem, ctx: FlowPathContext) => FlowPathNode
> = {
user: userNode,
node: nodeNameNode,
token: tokenNode,
group: groupNode,
model: modelNode,
channel: channelNode,
}
const ROLE_FLOW_STAGES: Record<FlowRole, FlowNodeKind[]> = {
root: ['user', 'node', 'token', 'group', 'model', 'channel'],
admin: ['user', 'group', 'model', 'channel'],
user: ['token', 'group', 'model'],
}
// A Sankey needs at least two columns to draw any link, so hiding stages can
// never collapse the path below this many columns.
const MIN_FLOW_STAGES = 2
export function getFlowStages(role: FlowRole): FlowNodeKind[] {
return ROLE_FLOW_STAGES[role] ?? ROLE_FLOW_STAGES.user
}
function resolveVisibleStages(
role: FlowRole,
visibleStages?: FlowNodeKind[]
): FlowNodeKind[] {
const stages = getFlowStages(role)
if (!visibleStages) return stages
const visible = new Set(visibleStages)
const filtered = stages.filter((stage) => visible.has(stage))
return filtered.length >= MIN_FLOW_STAGES ? filtered : stages
}
function flowPathForStages(
row: FlowQuotaDataItem,
stages: FlowNodeKind[],
ctx: FlowPathContext = EMPTY_FLOW_PATH_CONTEXT
): FlowPathNode[] {
return stages.map((stage) => NODE_BUILDERS[stage](row, ctx))
}
function colorAt(index: number, palette?: readonly string[]): string {
const colors =
palette && palette.length > 0 ? palette : getDashboardChartColors(index + 1)
if (colors.length === 0) return DEFAULT_FLOW_CHART_COLOR
return colors[index % colors.length] ?? DEFAULT_FLOW_CHART_COLOR
}
function colorPalette(
colorCount: number,
palette?: readonly string[]
): readonly string[] {
if (palette && palette.length > 0) return palette
const colors = getDashboardChartColors(colorCount)
return colors.length > 0 ? colors : [DEFAULT_FLOW_CHART_COLOR]
}
function alphaColor(
color: string,
alpha: number
): { color: string; alpha: number } {
const normalized = color.trim()
const hex = normalized.startsWith('#') ? normalized.slice(1) : normalized
if (!/^[0-9a-f]{6}$/i.test(hex)) {
return { color: normalized, alpha }
}
const value = Number.parseInt(hex, 16)
const red = (value >> 16) & 255
const green = (value >> 8) & 255
const blue = value & 255
return {
color: `rgba(${red}, ${green}, ${blue}, ${alpha.toFixed(2)})`,
alpha: 1,
}
}
function stableColorMap(
keys: string[],
palette?: readonly string[]
): Map<string, string> {
const map = new Map<string, string>()
const uniqueKeys = [...new Set(keys)]
const colors = colorPalette(uniqueKeys.length, palette)
uniqueKeys.forEach((key, index) => {
map.set(key, colorAt(index, colors))
})
return map
}
function filterRows(
rows: FlowQuotaDataItem[],
options: FlowBuildOptions = {}
): FlowQuotaDataItem[] {
const selectedUsers = new Set(options.selectedUsers ?? [])
if (selectedUsers.size === 0) return rows
return rows.filter((row) => selectedUsers.has(userNode(row).id))
}
function nodeFilterKey(filter: FlowNodeFilter): string {
return `${filter.kind}\u0000${filter.id}`
}
function normalizeSelectedNodeFilters(
selectedNodes: readonly FlowNodeFilter[] | undefined,
stages: readonly FlowNodeKind[]
): Map<FlowNodeKind, Set<string>> {
const visibleKinds = new Set(stages)
const filters = new Map<FlowNodeKind, Set<string>>()
for (const filter of selectedNodes ?? []) {
if (!visibleKinds.has(filter.kind)) continue
const selected = filters.get(filter.kind) ?? new Set<string>()
selected.add(filter.id)
filters.set(filter.kind, selected)
}
return filters
}
function pathMatchesNodeFilters(
path: FlowPathNode[],
filters: Map<FlowNodeKind, Set<string>>
): boolean {
if (filters.size === 0) return true
const pathNodesByKind = new Map<FlowNodeKind, Set<string>>()
for (const node of path) {
const ids = pathNodesByKind.get(node.kind) ?? new Set<string>()
ids.add(node.id)
pathNodesByKind.set(node.kind, ids)
}
for (const [kind, selectedIds] of filters) {
const pathIds = pathNodesByKind.get(kind)
if (!pathIds) return false
let hasSelectedNode = false
for (const id of selectedIds) {
if (pathIds.has(id)) {
hasSelectedNode = true
break
}
}
if (!hasSelectedNode) return false
}
return true
}
function filterRowsByNodes(
rows: FlowQuotaDataItem[],
selectedNodes: readonly FlowNodeFilter[] | undefined,
stages: FlowNodeKind[],
ctx: FlowPathContext
): FlowQuotaDataItem[] {
const filters = normalizeSelectedNodeFilters(selectedNodes, stages)
if (filters.size === 0) return rows
return rows.filter((row) =>
pathMatchesNodeFilters(flowPathForStages(row, stages, ctx), filters)
)
}
function selectedNodeFiltersExceptKind(
selectedNodes: readonly FlowNodeFilter[] | undefined,
kind: FlowNodeKind
): FlowNodeFilter[] | undefined {
const filtered = (selectedNodes ?? []).filter(
(filter) => filter.kind !== kind
)
return filtered.length > 0 ? filtered : undefined
}
function addNode(
map: Map<string, DashboardFlowNode>,
pathNode: FlowPathNode,
metrics: FlowMetrics,
metric: FlowMetric,
color: string,
colorKey: string
): void {
const previous = map.get(pathNode.id) ?? {
id: pathNode.id,
label: pathNode.label,
kind: pathNode.kind,
value: 0,
requests: 0,
quota: 0,
tokens: 0,
color,
colorKey,
}
previous.value += metricValue(metrics, metric)
previous.requests += metrics.requests
previous.quota += metrics.quota
previous.tokens += metrics.tokens
map.set(pathNode.id, previous)
}
function addLink(
map: Map<string, DashboardFlowLink>,
source: FlowPathNode,
target: FlowPathNode,
metrics: FlowMetrics,
metric: FlowMetric,
color: string,
colorKey: string
): void {
const key = `${source.id}\u0000${target.id}`
const previous = map.get(key) ?? {
source: source.id,
target: target.id,
value: 0,
requests: 0,
quota: 0,
tokens: 0,
sourceLabel: source.label,
targetLabel: target.label,
color,
linkColor: color,
linkAlpha: 1,
hoverColor: color,
colorKey,
share: 0,
}
previous.value += metricValue(metrics, metric)
previous.requests += metrics.requests
previous.quota += metrics.quota
previous.tokens += metrics.tokens
map.set(key, previous)
}
function assignLinkDisplayColors(links: DashboardFlowLink[]): void {
const linksBySource = new Map<string, DashboardFlowLink[]>()
for (const link of links) {
const sourceLinks = linksBySource.get(link.source) ?? []
sourceLinks.push(link)
linksBySource.set(link.source, sourceLinks)
}
for (const sourceLinks of linksBySource.values()) {
const sortedLinks = [...sourceLinks].sort(
(a, b) =>
b.value - a.value || linkStableKey(a).localeCompare(linkStableKey(b))
)
const denominator = Math.max(sortedLinks.length - 1, 1)
sortedLinks.forEach((link, index) => {
const alpha =
sortedLinks.length === 1 ? 0.34 : 0.24 + (index / denominator) * 0.2
const displayColor = alphaColor(link.color, alpha)
link.linkColor = displayColor.color
link.linkAlpha = displayColor.alpha
link.hoverColor = link.color
})
}
}
function byValueThenLabel<T extends { value: number; label: string }>(
a: T,
b: T
): number {
return b.value - a.value || a.label.localeCompare(b.label)
}
function linkStableKey(link: Pick<DashboardFlowLink, 'source' | 'target'>) {
return `${link.source}\u0000${link.target}`
}
function pathLinkKey(source: FlowPathNode, target: FlowPathNode): string {
return `${source.id}\u0000${target.id}`
}
function byLinkDrawPriority(
a: DashboardFlowLink,
b: DashboardFlowLink
): number {
return (
Number(a.dimmed) - Number(b.dimmed) ||
Number(b.highlighted) - Number(a.highlighted) ||
b.value - a.value ||
linkStableKey(a).localeCompare(linkStableKey(b))
)
}
function buildSummary(rows: FlowQuotaDataItem[]): FlowSummary {
return rows.reduce<FlowSummary>(
(summary, row) => {
const metrics = rowMetrics(row)
summary.quota += metrics.quota
summary.tokens += metrics.tokens
summary.requests += metrics.requests
return summary
},
{
quota: 0,
tokens: 0,
requests: 0,
}
)
}
function normalizeTopNodeLimit(limit?: number): number | undefined {
if (limit === undefined) return undefined
const parsed = Math.floor(limit)
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined
}
function otherFlowNode(
kind: FlowNodeKind,
labeler?: (kind: FlowNodeKind) => string
): FlowPathNode {
return {
id: OTHER_FLOW_NODE_IDS[kind],
label: labeler?.(kind) ?? DEFAULT_OTHER_FLOW_NODE_LABELS[kind],
kind,
}
}
function buildTopNodeSets(
rows: FlowQuotaDataItem[],
metric: FlowMetric,
stages: FlowNodeKind[],
limit: number | undefined,
ctx: FlowPathContext
): Map<FlowNodeKind, Set<string>> | undefined {
if (!limit) return undefined
const totals = new Map<FlowNodeKind, Map<string, FlowNodeRank>>()
for (const stage of stages) {
totals.set(stage, new Map())
}
for (const row of rows) {
const metrics = rowMetrics(row)
const value = metricValue(metrics, metric)
const path = flowPathForStages(row, stages, ctx)
for (const node of path) {
const stageTotals = totals.get(node.kind)
if (!stageTotals) continue
const current = stageTotals.get(node.id) ?? { node, value: 0 }
current.value += value
stageTotals.set(node.id, current)
}
}
const topSets = new Map<FlowNodeKind, Set<string>>()
for (const [kind, stageTotals] of totals) {
const topIds = [...stageTotals.values()]
.sort(
(a, b) =>
b.value - a.value ||
a.node.label.localeCompare(b.node.label) ||
a.node.id.localeCompare(b.node.id)
)
.slice(0, limit)
.map((rank) => rank.node.id)
topSets.set(kind, new Set(topIds))
}
return topSets
}
function isTopFlowNode(
node: FlowPathNode,
topNodeSets?: Map<FlowNodeKind, Set<string>>
): boolean {
const topNodes = topNodeSets?.get(node.kind)
return !topNodes || topNodes.has(node.id)
}
function applyTopNodeLimit(
path: FlowPathNode[],
topNodeSets: Map<FlowNodeKind, Set<string>> | undefined,
mode: FlowOverflowMode,
labeler?: (kind: FlowNodeKind) => string
): FlowPathNode[] | undefined {
if (!topNodeSets) return path
const containsOverflowNode = path.some(
(node) => !isTopFlowNode(node, topNodeSets)
)
if (!containsOverflowNode) return path
if (mode === 'hide') return undefined
return path.map((node) =>
isTopFlowNode(node, topNodeSets) ? node : otherFlowNode(node.kind, labeler)
)
}
function pathContainsFlowNode(
path: FlowPathNode[],
filter: FlowNodeFilter
): boolean {
return path.some((node) => node.kind === filter.kind && node.id === filter.id)
}
function pathContainsFlowLink(
path: FlowPathNode[],
link: FlowLinkSelection
): boolean {
for (let i = 0; i < path.length - 1; i++) {
if (path[i]?.id === link.source && path[i + 1]?.id === link.target) {
return true
}
}
return false
}
function buildFlowHighlightSets(
preparedPaths: PreparedFlowPath[],
activeNode: FlowNodeFilter | undefined,
activeLink: FlowLinkSelection | undefined,
stages: FlowNodeKind[]
): FlowHighlightSets | undefined {
const nodeActive = Boolean(activeNode && stages.includes(activeNode.kind))
if (!nodeActive && !activeLink) return undefined
// A link selection highlights paths that traverse that exact edge; otherwise
// fall back to highlighting paths that pass through the active node.
const matchesPath = (path: FlowPathNode[]): boolean => {
if (activeLink) return pathContainsFlowLink(path, activeLink)
return activeNode ? pathContainsFlowNode(path, activeNode) : false
}
const highlightedNodes = new Set<string>()
const highlightedLinks = new Set<string>()
for (const prepared of preparedPaths) {
const { path } = prepared
if (!matchesPath(path)) continue
for (const node of path) {
highlightedNodes.add(node.id)
}
for (let i = 0; i < path.length - 1; i++) {
const source = path[i]
const target = path[i + 1]
if (!source || !target) continue
highlightedLinks.add(pathLinkKey(source, target))
}
}
if (highlightedNodes.size === 0) return undefined
return {
nodes: highlightedNodes,
links: highlightedLinks,
}
}
// Fully masks a label. Nodes stay distinct because the Sankey identifies them
// by `key` (the node id), not by this display text, so identical masked labels
// never merge.
const FLOW_MASK_TEXT = '\u2022\u2022\u2022\u2022'
function maskFlowLabel(label: string): string {
if (label.length === 0) return label
return FLOW_MASK_TEXT
}
// Masks sensitive node/link labels in place. Node identity (`id`) is untouched,
// so links, highlighting, and layout stay exactly the same; only the rendered
// text changes.
function maskFlowGraphLabels(
nodes: Map<string, DashboardFlowNode>,
links: Map<string, DashboardFlowLink>
): void {
const maskedById = new Map<string, string>()
for (const node of nodes.values()) {
if (!SENSITIVE_FLOW_KINDS.has(node.kind)) continue
if (OTHER_FLOW_NODE_ID_SET.has(node.id)) continue
const masked = maskFlowLabel(node.label)
node.label = masked
maskedById.set(node.id, masked)
}
if (maskedById.size === 0) return
for (const link of links.values()) {
const sourceMasked = maskedById.get(link.source)
if (sourceMasked !== undefined) link.sourceLabel = sourceMasked
const targetMasked = maskedById.get(link.target)
if (targetMasked !== undefined) link.targetLabel = targetMasked
}
}
function applyFlowHighlights(
nodes: Iterable<DashboardFlowNode>,
links: Iterable<DashboardFlowLink>,
highlightSets: FlowHighlightSets | undefined
): void {
if (!highlightSets) return
for (const node of nodes) {
node.highlighted = highlightSets.nodes.has(node.id)
node.dimmed = !node.highlighted
}
for (const link of links) {
const highlighted = highlightSets.links.has(linkStableKey(link))
link.highlighted = highlighted
link.dimmed = !highlighted
}
}
function buildFlowGraph(
rows: FlowQuotaDataItem[],
metric: FlowMetric,
role: FlowRole,
palette?: readonly string[],
visibleStages?: FlowNodeKind[],
ctx: FlowPathContext = EMPTY_FLOW_PATH_CONTEXT,
options: FlowGraphOptions = {}
): DashboardFlowGraph {
const stages = resolveVisibleStages(role, visibleStages)
const topNodeSets = buildTopNodeSets(
rows,
metric,
stages,
normalizeTopNodeLimit(options.topNodeLimit),
ctx
)
const overflowMode = options.overflowMode ?? DEFAULT_FLOW_OVERFLOW_MODE
const preparedPaths: PreparedFlowPath[] = []
for (const row of rows) {
const path = applyTopNodeLimit(
flowPathForStages(row, stages, ctx),
topNodeSets,
overflowMode,
options.otherNodeLabel
)
if (!path) continue
preparedPaths.push({ path, metrics: rowMetrics(row) })
}
const nodes = new Map<string, DashboardFlowNode>()
const links = new Map<string, DashboardFlowLink>()
const colors = stableColorMap(
preparedPaths
.map((prepared) => prepared.path[0]?.id)
.filter((id): id is string => Boolean(id))
.sort((a, b) => a.localeCompare(b)),
palette
)
for (const prepared of preparedPaths) {
const { path, metrics } = prepared
const root = path[0]
if (!root) continue
const color = colors.get(root.id) ?? colorAt(0, palette)
for (const node of path) {
addNode(nodes, node, metrics, metric, color, root.id)
}
for (let i = 0; i < path.length - 1; i++) {
const source = path[i]
const target = path[i + 1]
if (!source || !target) continue
addLink(links, source, target, metrics, metric, color, root.id)
}
}
if (options.maskSensitive) {
maskFlowGraphLabels(nodes, links)
}
applyFlowHighlights(
nodes.values(),
links.values(),
buildFlowHighlightSets(
preparedPaths,
options.activeNode,
options.activeLink,
stages
)
)
const flowLinks = [...links.values()].sort(
(a, b) =>
a.source.localeCompare(b.source) || a.target.localeCompare(b.target)
)
const firstStepSources = new Set(
preparedPaths
.map((prepared) => prepared.path[0]?.id)
.filter((id): id is string => Boolean(id))
)
const total = flowLinks
.filter((link) => firstStepSources.has(link.source))
.reduce((sum, link) => sum + link.value, 0)
for (const link of flowLinks) {
link.share = total > 0 ? link.value / total : 0
}
assignLinkDisplayColors(flowLinks)
return {
nodes: [...nodes.values()].sort(byValueThenLabel),
links: flowLinks,
}
}
function formatNumber(value: number): string {
return Intl.NumberFormat(undefined, { maximumFractionDigits: 0 }).format(
value
)
}
function buildUserFilterOptions(
rows: FlowQuotaDataItem[],
metric: FlowMetric = 'quota',
palette?: readonly string[]
): FlowFilterOptions['users'] {
const users = new Map<
string,
{
label: string
value: number
color: string
}
>()
const colors = stableColorMap(
rows.map((row) => userNode(row).id).sort((a, b) => a.localeCompare(b)),
palette
)
for (const row of rows) {
const user = userNode(row)
if (!row.user_id && !row.username) continue
const metrics = rowMetrics(row)
const value = metricValue(metrics, metric)
const current = users.get(user.id) ?? {
label: user.label,
value: 0,
color: colors.get(user.id) ?? colorAt(0, palette),
}
current.value += value
users.set(user.id, current)
}
return [...users.entries()]
.map(([value, user]) => ({
value,
label: user.label,
valueLabel: formatNumber(user.value),
valueRaw: user.value,
color: user.color,
}))
.sort((a, b) => b.valueRaw - a.valueRaw || a.label.localeCompare(b.label))
}
function buildNodeFilterOptions(
rows: FlowQuotaDataItem[],
metric: FlowMetric,
role: FlowRole,
visibleStages: FlowNodeKind[] | undefined,
palette: readonly string[] | undefined,
ctx: FlowPathContext,
selectedNodes?: readonly FlowNodeFilter[]
): FlowFilterOptions['nodes'] {
const stages = resolveVisibleStages(role, visibleStages)
const stageOrder = new Map(stages.map((stage, index) => [stage, index]))
const colorIds = new Set<string>()
for (const row of rows) {
for (const node of flowPathForStages(row, stages, ctx)) {
colorIds.add(node.id)
}
}
const colors = stableColorMap(
[...colorIds].sort((a, b) => a.localeCompare(b)),
palette
)
const options: FlowFilterOptions['nodes'] = []
for (const stage of stages) {
const totals = new Map<
string,
{
node: FlowPathNode
value: number
}
>()
const candidateRows = filterRowsByNodes(
rows,
selectedNodeFiltersExceptKind(selectedNodes, stage),
stages,
ctx
)
for (const row of candidateRows) {
const metrics = rowMetrics(row)
const value = metricValue(metrics, metric)
const node = NODE_BUILDERS[stage](row, ctx)
const key = nodeFilterKey({ kind: node.kind, id: node.id })
const current = totals.get(key) ?? { node, value: 0 }
current.value += value
totals.set(key, current)
}
for (const rank of totals.values()) {
options.push({
kind: rank.node.kind,
value: rank.node.id,
label: rank.node.label,
valueLabel: formatNumber(rank.value),
valueRaw: rank.value,
color: colors.get(rank.node.id) ?? colorAt(0, palette),
})
}
}
return options.sort(
(a, b) =>
(stageOrder.get(a.kind) ?? 0) - (stageOrder.get(b.kind) ?? 0) ||
b.valueRaw - a.valueRaw ||
a.label.localeCompare(b.label) ||
a.value.localeCompare(b.value)
)
}
export function buildFlowFilterOptions(
rows: FlowQuotaDataItem[],
metric: FlowMetric = 'quota',
palette?: readonly string[],
role: FlowRole = DEFAULT_FLOW_ROLE,
visibleStages?: FlowNodeKind[],
selectedNodes?: readonly FlowNodeFilter[]
): FlowFilterOptions {
return {
users: buildUserFilterOptions(rows, metric, palette),
nodes: buildNodeFilterOptions(
rows,
metric,
role,
visibleStages,
palette,
EMPTY_FLOW_PATH_CONTEXT,
selectedNodes
),
}
}
export function buildDashboardFlowData(
rows: FlowQuotaDataItem[],
metric: FlowMetric = 'quota',
options: FlowBuildOptions = {}
): ProcessedFlowData {
const role = options.role ?? DEFAULT_FLOW_ROLE
const palette = options.colorPalette
const ctx = {
deletedTokenLabel: options.deletedTokenLabel,
}
const stages = resolveVisibleStages(role, options.visibleStages)
const userFilteredRows = filterRows(rows, options)
const filteredRows = filterRowsByNodes(
userFilteredRows,
options.selectedNodes,
stages,
ctx
)
return {
summary: buildSummary(filteredRows),
flow: buildFlowGraph(
filteredRows,
metric,
role,
palette,
options.visibleStages,
ctx,
{