forked from thinhhoangpham/tcp_analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfolder_integration.js
More file actions
1599 lines (1356 loc) · 60.7 KB
/
folder_integration.js
File metadata and controls
1599 lines (1356 loc) · 60.7 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
/**
* Integration module for folder-based loading with existing visualization
* Bridges the DataSource (with DuckDB support) with the ip_bar_diagram visualization
* Now supports CSV-based multi-resolution loading from resolutions/ folder
*/
import { folderLoader } from './folder_loader.js';
// Lazy load optional modules that may fail (DuckDB, etc.)
let dataSource = null;
let resolutionManager = null;
let csvResolutionManager = null;
let RESOLUTION = null;
async function loadOptionalModules() {
try {
const dataSourceModule = await import('./src/data/data-source.js');
dataSource = dataSourceModule.dataSource;
} catch (err) {
console.warn('[FolderIntegration] data-source.js not available (DuckDB disabled):', err.message);
}
try {
const resModule = await import('./src/data/resolution-manager.js');
resolutionManager = resModule.resolutionManager;
} catch (err) {
console.warn('[FolderIntegration] resolution-manager.js not available:', err.message);
}
try {
const csvResModule = await import('./src/data/csv-resolution-manager.js');
csvResolutionManager = csvResModule.csvResolutionManager;
RESOLUTION = csvResModule.RESOLUTION;
} catch (err) {
console.warn('[FolderIntegration] csv-resolution-manager.js not available:', err.message);
}
}
// Store current state
let currentMode = 'csv'; // 'csv' or 'folder'
let selectedIPs = [];
let currentFlowsIndex = [];
let useMultiResolution = false;
let useCsvMultiRes = false; // True when using CSV-based resolution files
let chunkedFlowState = null; // State for chunked_flows format (on-demand loading)
/**
* Initialize folder integration
*/
export function initFolderIntegration() {
console.log('Initializing folder integration...');
// Wire up data source radio buttons (if they exist)
const csvRadio = document.getElementById('dataSourceCSV');
const folderRadio = document.getElementById('dataSourceFolder');
const csvSection = document.getElementById('csvSourceSection');
const folderSection = document.getElementById('folderSourceSection');
if (csvRadio && folderRadio && csvSection && folderSection) {
csvRadio.addEventListener('change', () => {
if (csvRadio.checked) {
currentMode = 'csv';
csvSection.style.display = 'block';
folderSection.style.display = 'none';
}
});
folderRadio.addEventListener('change', () => {
if (folderRadio.checked) {
currentMode = 'folder';
csvSection.style.display = 'none';
folderSection.style.display = 'block';
}
});
} else {
console.log('Data source controls not found - likely auto-loading from TimeArcs');
}
// Wire up separate packet/flow folder buttons
const openPacketsFolderBtn = document.getElementById('openPacketsFolderBtn');
const openFlowsFolderBtn = document.getElementById('openFlowsFolderBtn');
if (openPacketsFolderBtn) {
openPacketsFolderBtn.addEventListener('click', () => handleOpenFolder('packets'));
}
if (openFlowsFolderBtn) {
openFlowsFolderBtn.addEventListener('click', () => handleOpenFolder('flows'));
}
console.log('Folder integration initialized');
}
/**
* Handle opening a folder - validates format matches the requested mode
* @param {string} mode - 'packets' or 'flows'
*/
async function handleOpenFolder(mode = 'packets') {
try {
showProgress(`Opening ${mode} folder...`, 0);
const result = await folderLoader.openFolder();
if (!result.success) {
hideProgress();
if (!result.cancelled) {
alert('Failed to open folder. Please try again.');
}
return;
}
hideProgress();
const folderHandle = folderLoader.folderHandle;
const manifest = result.manifest;
const hasCsvResolutions = await checkCsvResolutionsAvailable(folderHandle);
// Validate folder format matches requested mode
const isFlowFormat = manifest?.format === 'multires_flows' || manifest?.format === 'chunked_flows' || manifest?.format === 'chunked' || manifest?.format === 'chunked_flows_by_ip_pair';
const isPacketFormat = manifest?.format === 'multires_packets' || (!isFlowFormat && hasCsvResolutions);
if (mode === 'flows' && !isFlowFormat) {
alert(`This folder contains packet data, not flow data.\n\nExpected format: multires_flows, chunked_flows, or chunked\nFound format: ${manifest?.format || 'unknown'}\n\nPlease use "Load Packets" button instead.`);
return;
}
if (mode === 'packets' && isFlowFormat) {
alert(`This folder contains flow data, not packet data.\n\nExpected format: multires_packets\nFound format: ${manifest?.format}\n\nPlease use "Load Flows" button instead.`);
return;
}
// Determine format type for display
let formatType = mode === 'flows' ? 'Multi-Resolution Flows' : 'Multi-Resolution Packets';
// Update UI with folder info (if element exists)
const folderInfo = document.getElementById('folderInfo');
if (folderInfo) {
const countLabel = mode === 'flows' ? 'Flows' : 'Packets';
const totalCount = mode === 'flows'
? result.manifest?.total_flows?.toLocaleString()
: result.manifest?.total_packets?.toLocaleString();
folderInfo.innerHTML = `
<strong>Folder:</strong> ${result.folderName}<br>
<strong>Format:</strong> ${formatType}<br>
<strong>${countLabel}:</strong> ${totalCount || 'N/A'}<br>
<strong>IPs:</strong> ${result.manifest?.unique_ips || 'N/A'}
<div style="margin-top: 8px;">
<button id="loadDataBtn" style="padding: 6px 12px; background: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer;">
▶ Load ${mode === 'flows' ? 'Flows' : 'Packets'}
</button>
</div>
`;
// Wire up load data button with the correct mode
document.getElementById('loadDataBtn').addEventListener('click', () => {
if (mode === 'flows') {
// Choose handler based on format
if (manifest?.format === 'chunked_flows' || manifest?.format === 'chunked' || manifest?.format === 'chunked_flows_by_ip_pair') {
handleChunkedFlowsFolder(result);
} else {
handleFlowMultiResFolder(result);
}
} else {
handleCsvMultiResFolder(result);
}
});
}
console.log(`[FolderIntegration] Folder opened: ${result.folderName}, mode: ${mode}, format: ${manifest?.format}`);
} catch (err) {
hideProgress();
console.error('Error opening folder:', err);
alert(`Error opening folder: ${err.message}`);
}
}
/**
* Load data from the opened folder
*/
async function loadFolderData(hasCsvResolutions, result) {
try {
if (hasCsvResolutions) {
const manifest = result.manifest;
// Check for flow-based format (from tcp_flow_detector_multires.py)
if (manifest?.format === 'multires_flows') {
console.log('[FolderIntegration] Flow-based multi-resolution format detected!');
await handleFlowMultiResFolder(result);
return;
}
// Packet-based multi-resolution format
console.log('[FolderIntegration] Packet-based multi-resolution format detected!');
await handleCsvMultiResFolder(result);
return;
}
// Standard folder format - load packets.csv if available
const folderHandle = folderLoader.folderHandle;
let hasPacketsCsv = false;
try {
await folderHandle.getFileHandle('packets.csv');
hasPacketsCsv = true;
} catch { /* no packets.csv */ }
if (!hasPacketsCsv) {
// Try to load flows index directly without packets.csv
console.log('[FolderIntegration] No packets.csv found, loading flows index only...');
showProgress('Loading flows index...', 20);
try {
const flowsIndex = await folderLoader.loadFlowsIndex();
currentFlowsIndex = flowsIndex;
// Load statistics
showProgress('Loading statistics...', 60);
let ipStats = {};
let flagStats = {};
try {
ipStats = await folderLoader.loadIPStats();
} catch (e) {
console.warn('[FolderIntegration] IP stats not available:', e.message);
}
try {
flagStats = await folderLoader.loadFlagStats();
} catch (e) {
console.warn('[FolderIntegration] Flag stats not available:', e.message);
}
hideProgress();
// Trigger visualization with flows data (no packets)
console.log('[FolderIntegration] Triggering visualization with flows-only data...');
triggerVisualizationFromFolder([], flowsIndex, ipStats, flagStats, result.manifest);
return;
} catch (flowErr) {
hideProgress();
alert(`No packets.csv or flows_index.json found in folder. Please select a valid data folder.`);
return;
}
}
// Load packets for visualization
showProgress('Loading packets...', 10);
const packets = await folderLoader.loadPackets((progress, current, total) => {
showProgress(`Loading packets: ${current.toLocaleString()} / ${total.toLocaleString()}`, 10 + (progress * 0.6));
});
// Load flows index
showProgress('Loading flows index...', 70);
const flowsIndex = await folderLoader.loadFlowsIndex();
currentFlowsIndex = flowsIndex;
// Load statistics
showProgress('Loading statistics...', 80);
const ipStats = await folderLoader.loadIPStats();
const flagStats = await folderLoader.loadFlagStats();
hideProgress();
// Trigger visualization with loaded data
console.log('Triggering visualization with folder data...');
triggerVisualizationFromFolder(packets, flowsIndex, ipStats, flagStats, result.manifest);
} catch (err) {
hideProgress();
console.error('Error loading data:', err);
alert(`Error loading data: ${err.message}`);
}
}
/**
* Check if folder contains CSV-based multi-resolution format
*/
async function checkCsvResolutionsAvailable(folderHandle) {
try {
const resDir = await folderHandle.getDirectoryHandle('resolutions');
// Check for seconds index
const secondsDir = await resDir.getDirectoryHandle('seconds');
await secondsDir.getFileHandle('index.json');
return true;
} catch {
return false;
}
}
/**
* Handle CSV-based multi-resolution folder loading
*/
async function handleCsvMultiResFolder(result) {
useCsvMultiRes = true;
useMultiResolution = true;
// Ensure optional modules are loaded
await loadOptionalModules();
if (!csvResolutionManager) {
throw new Error('CSV Resolution Manager not available. Check browser console for module loading errors.');
}
try {
// Update UI with folder info (if element exists)
const folderInfo = document.getElementById('folderInfo');
if (folderInfo) {
folderInfo.innerHTML = `
<strong>Folder:</strong> ${result.folderName}<br>
<strong>Format:</strong> Multi-Resolution CSV<br>
<strong>Packets:</strong> ${result.manifest?.total_packets?.toLocaleString() || 'Loading...'}<br>
<strong>IPs:</strong> ${result.manifest?.unique_ips || 'Loading...'}
`;
}
// Initialize CSV resolution manager - use folderLoader.folderHandle
showProgress('Loading resolution index...', 10);
const secondsData = await csvResolutionManager.init(folderLoader.folderHandle);
console.log(`[FolderIntegration] Loaded ${secondsData.length} second-level bins`);
// Update folder info with loaded data (if element exists)
if (folderInfo) {
folderInfo.innerHTML = `
<strong>Folder:</strong> ${result.folderName}<br>
<strong>Format:</strong> Multi-Resolution CSV<br>
<strong>Second bins:</strong> ${secondsData.length.toLocaleString()}<br>
<strong>Time range:</strong> ${formatTimeRange(csvResolutionManager.timeExtent)}
`;
}
// Extract unique IPs from seconds data
showProgress('Extracting IP addresses...', 50);
const uniqueIPs = extractUniqueIPsFromBins(secondsData);
console.log(`[FolderIntegration] Found ${uniqueIPs.length} unique IPs`);
hideProgress();
// Trigger visualization with seconds data (aggregated view)
console.log('[FolderIntegration] Triggering visualization with multi-resolution data...');
triggerMultiResVisualization(secondsData, uniqueIPs, result.manifest);
} catch (err) {
hideProgress();
console.error('[FolderIntegration] Error loading multi-resolution data:', err);
alert(`Error loading multi-resolution data: ${err.message}`);
}
}
// Store for on-demand flow loading
let flowResolutionState = null;
/**
* Handle flow-based multi-resolution folder (from tcp_flow_detector_multires.py)
* Only loads overview (seconds) data initially - flows are loaded on-demand
*/
async function handleFlowMultiResFolder(result) {
showProgress('Loading overview data...', 10);
const folderHandle = folderLoader.folderHandle;
const resDir = await folderHandle.getDirectoryHandle('resolutions');
// Load seconds data for timeline overview
const secDir = await resDir.getDirectoryHandle('seconds');
const dataFile = await secDir.getFileHandle('data.csv');
const secondsCSV = await (await dataFile.getFile()).text();
const secondsBins = parseFlowSecondsCSV(secondsCSV);
showProgress('Loading flow index...', 50);
// Load raw flow index (metadata only, not actual flows)
const rawDir = await resDir.getDirectoryHandle('raw');
const indexFile = await rawDir.getFileHandle('index.json');
const rawIndex = JSON.parse(await (await indexFile.getFile()).text());
// Store state for on-demand loading
flowResolutionState = {
folderHandle,
resDir,
rawDir,
rawIndex,
manifest: result.manifest,
flowCache: new Map(), // Cache loaded chunks
timeExtent: [rawIndex.time_range.start, rawIndex.time_range.end]
};
showProgress('Extracting IPs from manifest...', 80);
// Get unique IP count from manifest (don't load all flows just for IPs)
const uniqueIPCount = result.manifest?.unique_ips || 0;
hideProgress();
// Dispatch a separate event for flow data that doesn't reset visualization
// This preserves current IP selection and packet data
const event = new CustomEvent('flowDataLoaded', {
detail: {
overviewBins: secondsBins,
manifest: result.manifest,
flowResolutionState: flowResolutionState,
loadFlowsForTimeRange: loadFlowsForTimeRange,
totalFlows: rawIndex.total_count,
timeExtent: flowResolutionState.timeExtent
}
});
document.dispatchEvent(event);
console.log(`[FolderIntegration] Flow data loaded: ${secondsBins.length} overview bins, ${rawIndex.total_count} flows available on-demand`);
}
/**
* Handle chunked flows folder (from tcp_data_loader_streaming.py v2.1)
* Loads flows from flows/flows_index.json and flows/chunk_*.json
*/
async function handleChunkedFlowsFolder(result) {
showProgress('Loading flows index...', 10);
const folderHandle = folderLoader.folderHandle;
// Check if folder handle is still valid
if (!folderHandle) {
hideProgress();
alert('Folder handle is no longer valid. Please select the folder again.');
return;
}
try {
// Verify/request permission to read the folder
let permission = 'prompt';
try {
permission = await folderHandle.queryPermission({ mode: 'read' });
} catch (e) {
console.warn('[FolderIntegration] queryPermission failed:', e.message);
}
console.log(`[FolderIntegration] Current permission: ${permission}`);
if (permission !== 'granted') {
try {
permission = await folderHandle.requestPermission({ mode: 'read' });
} catch (e) {
console.warn('[FolderIntegration] requestPermission failed:', e.message);
}
if (permission !== 'granted') {
throw new Error('Permission to read folder was denied. Please try again and grant access.');
}
}
// Load flows directory
let flowsDir;
try {
flowsDir = await folderHandle.getDirectoryHandle('flows');
console.log('[FolderIntegration] Got flows/ directory handle');
} catch (dirErr) {
console.error('[FolderIntegration] Cannot access flows/ directory:', dirErr);
throw new Error(`Cannot access 'flows/' directory. Make sure this folder was created by tcp_data_loader_streaming.py and contains a 'flows/' subdirectory.\n\nError: ${dirErr.message}`);
}
// Load chunks metadata (small file with time ranges and category counts per chunk)
showProgress('Loading chunks metadata...', 30);
let chunksMeta = [];
let isV3Format = false; // v3 uses pairs_meta.json with flows organized by IP pair
// Check for v3 format (chunked_flows_by_ip_pair) first
const manifestFormat = result.manifest?.format;
if (manifestFormat === 'chunked_flows_by_ip_pair') {
try {
const pairsMetaFile = await flowsDir.getFileHandle('pairs_meta.json');
const pairsMetaContent = await (await pairsMetaFile.getFile()).text();
const pairsMeta = JSON.parse(pairsMetaContent);
isV3Format = true;
// Flatten pairs_meta into chunksMeta format for unified handling
// Each pair has: pair_folder, ips, chunks (array with file, start, end, count, etc.)
for (const pair of pairsMeta) {
for (const chunk of (pair.chunks || [])) {
chunksMeta.push({
file: `by_pair/${pair.pair_folder}/${chunk.file}`,
start: chunk.start,
end: chunk.end,
count: chunk.count,
graceful: chunk.graceful || 0,
abortive: chunk.abortive || 0,
invalid: chunk.invalid || 0,
ongoing: chunk.ongoing || 0,
ips: pair.ips,
ipPair: pair.pair_folder
});
}
}
console.log(`[FolderIntegration] v3 format: Loaded ${pairsMeta.length} IP pairs, ${chunksMeta.length} total chunks`);
} catch (v3Err) {
console.warn('[FolderIntegration] pairs_meta.json not found:', v3Err.message);
}
}
// If not v3 or v3 failed, try v2 format (chunks_meta.json)
if (!isV3Format || chunksMeta.length === 0) {
try {
const metaFile = await flowsDir.getFileHandle('chunks_meta.json');
const metaContent = await (await metaFile.getFile()).text();
chunksMeta = JSON.parse(metaContent);
console.log(`[FolderIntegration] v2 format: Loaded metadata for ${chunksMeta.length} chunks`);
} catch (metaErr) {
console.warn('[FolderIntegration] chunks_meta.json not found, will scan chunks:', metaErr.message);
// Fallback: scan chunk files (slower, for old data)
try {
for await (const entry of flowsDir.values()) {
if (entry.kind === 'file' && entry.name.startsWith('chunk_') && entry.name.endsWith('.json')) {
chunksMeta.push({ file: entry.name });
}
}
chunksMeta.sort((a, b) => a.file.localeCompare(b.file));
} catch (listErr) {
throw new Error(`Cannot access flows/ directory: ${listErr.message}`);
}
}
}
if (chunksMeta.length === 0) {
throw new Error('No flow chunks found in flows/ directory.');
}
// Store state for on-demand chunk loading
chunkedFlowState = {
folderHandle,
flowsDir,
chunksMeta,
manifest: result.manifest,
chunkCache: new Map(), // Cache for loaded chunks
isV3Format: isV3Format
};
// Calculate totals from metadata
let totalFlows = 0;
let minTime = Infinity, maxTime = -Infinity;
for (const chunk of chunksMeta) {
totalFlows += chunk.count || 0;
if (chunk.start && chunk.start < minTime) minTime = chunk.start;
if (chunk.end && chunk.end > maxTime) maxTime = chunk.end;
}
const timeExtent = [minTime, maxTime];
console.log(`[FolderIntegration] Loaded metadata for ${chunksMeta.length} chunks, ${totalFlows} total flows, v3=${isV3Format}`);
hideProgress();
// Dispatch flowDataLoaded event with chunk metadata (not all flows)
// The overview chart will bin from this metadata
// Actual flows are loaded on-demand when user clicks
const actualFormat = isV3Format ? 'chunked_flows_by_ip_pair' : 'chunked_flows';
const event = new CustomEvent('flowDataLoaded', {
detail: {
chunksMeta: chunksMeta,
manifest: result.manifest,
totalFlows: totalFlows,
timeExtent: timeExtent,
format: actualFormat,
loadChunksForTimeRange: loadChunksForTimeRange // On-demand loader
}
});
document.dispatchEvent(event);
console.log(`[FolderIntegration] Flow metadata loaded: ${chunksMeta.length} chunks, ${totalFlows} flows, time: ${timeExtent[0]} - ${timeExtent[1]}`);
} catch (err) {
hideProgress();
console.error('[FolderIntegration] Error loading chunked flows:', err);
alert(`Error loading chunked flows: ${err.message}`);
}
}
/**
* Load flows from chunks that overlap with a time range (on-demand)
* @param {number} startTime - Start timestamp in microseconds
* @param {number} endTime - End timestamp in microseconds
* @param {Array<string>} selectedIPs - Optional array of selected IPs to filter by
* @returns {Promise<Array>} Array of flow objects
*/
async function loadChunksForTimeRange(startTime, endTime, selectedIPs = null) {
if (!chunkedFlowState) {
console.warn('No chunked flow state available');
return [];
}
const { flowsDir, chunksMeta, chunkCache } = chunkedFlowState;
const selectedIPSet = selectedIPs ? new Set(selectedIPs) : null;
// Find chunks that overlap with the time range
const relevantChunks = chunksMeta.filter(chunk =>
chunk.end >= startTime && chunk.start <= endTime
);
if (relevantChunks.length === 0) {
return [];
}
const allFlows = [];
for (const chunk of relevantChunks) {
// Check cache first
if (chunkCache.has(chunk.file)) {
const cachedFlows = chunkCache.get(chunk.file);
const filtered = cachedFlows.filter(f => {
// Filter by time range (match overview chart binning: by startTime only)
if (f.startTime < startTime || f.startTime >= endTime) {
return false;
}
// Filter by selected IPs if provided (both initiator AND responder must be in selected IPs)
if (selectedIPSet && (!selectedIPSet.has(f.initiator) || !selectedIPSet.has(f.responder))) {
return false;
}
return true;
});
allFlows.push(...filtered);
continue;
}
// Load chunk from disk
try {
// Handle nested paths for v3 format (e.g., by_pair/172-28-4-7__192-168-1-1/chunk_00000.json)
let fileHandle;
if (chunk.file.includes('/')) {
const pathParts = chunk.file.split('/');
let currentDir = flowsDir;
for (let i = 0; i < pathParts.length - 1; i++) {
currentDir = await currentDir.getDirectoryHandle(pathParts[i]);
}
fileHandle = await currentDir.getFileHandle(pathParts[pathParts.length - 1]);
} else {
fileHandle = await flowsDir.getFileHandle(chunk.file);
}
const file = await fileHandle.getFile();
const content = await file.text();
const flows = JSON.parse(content).map(convertChunkedFlow);
// Cache the chunk
chunkCache.set(chunk.file, flows);
// Filter to time range AND selected IPs
const filtered = flows.filter(f => {
// Filter by time range (match overview chart binning: by startTime only)
if (f.startTime < startTime || f.startTime >= endTime) {
return false;
}
// Filter by selected IPs if provided (both initiator AND responder must be in selected IPs)
if (selectedIPSet && (!selectedIPSet.has(f.initiator) || !selectedIPSet.has(f.responder))) {
return false;
}
return true;
});
allFlows.push(...filtered);
} catch (err) {
console.error(`Failed to load chunk ${chunk.file}:`, err);
}
}
return allFlows;
}
/**
* Convert a flow from tcp_data_loader_streaming.py format to visualization format
*/
function convertChunkedFlow(flow) {
// The flow objects from tcp_data_loader_streaming.py already have camelCase names
// and the structure we need, so we just ensure all required fields exist
return {
// Identity
id: flow.id,
key: flow.key,
// Endpoints
initiator: flow.initiator,
responder: flow.responder,
initiatorPort: flow.initiatorPort,
responderPort: flow.responderPort,
// Timing
startTime: flow.startTime,
endTime: flow.endTime,
// State
state: flow.state,
closeType: flow.closeType,
invalidReason: flow.invalidReason,
// Flags
establishmentComplete: flow.establishmentComplete || false,
dataTransferStarted: flow.dataTransferStarted || false,
closingStarted: flow.closingStarted || false,
ongoing: flow.ongoing || false,
// Stats
totalPackets: flow.totalPackets || 0,
totalBytes: flow.totalBytes || 0,
// Phases (for packet counts in UI)
phases: flow.phases || {
establishment: [],
dataTransfer: [],
closing: []
},
// Full packets if available
packets: flow.packets || []
};
}
/**
* Load flows for a specific time range (on-demand)
* @param {number} startTime - Start timestamp in microseconds
* @param {number} endTime - End timestamp in microseconds
* @returns {Promise<Array>} Array of flow objects
*/
async function loadFlowsForTimeRange(startTime, endTime) {
if (!flowResolutionState) {
console.warn('[FlowLoader] No flow resolution state available');
return [];
}
const { rawDir, rawIndex, flowCache } = flowResolutionState;
// Find chunks that overlap with the time range
const relevantChunks = rawIndex.chunks.filter(chunk =>
chunk.end >= startTime && chunk.start <= endTime
);
if (relevantChunks.length === 0) {
console.log(`[FlowLoader] No chunks found for time range`);
return [];
}
console.log(`[FlowLoader] Loading ${relevantChunks.length} chunks for time range`);
const allFlows = [];
for (const chunk of relevantChunks) {
// Check cache first
if (flowCache.has(chunk.file)) {
const cachedFlows = flowCache.get(chunk.file);
const filtered = cachedFlows.filter(f =>
f.startTime <= endTime && f.endTime >= startTime
);
allFlows.push(...filtered);
continue;
}
// Load chunk
try {
const file = await rawDir.getFileHandle(chunk.file);
const csvText = await (await file.getFile()).text();
const flows = parseFlowCSV(csvText);
// Cache the chunk
flowCache.set(chunk.file, flows);
// Filter to time range
const filtered = flows.filter(f =>
f.startTime <= endTime && f.endTime >= startTime
);
allFlows.push(...filtered);
console.log(`[FlowLoader] Loaded ${chunk.file}: ${flows.length} flows, ${filtered.length} in range`);
} catch (err) {
console.error(`[FlowLoader] Failed to load ${chunk.file}:`, err);
}
}
console.log(`[FlowLoader] Total flows for time range: ${allFlows.length}`);
return allFlows;
}
/**
* Get flow resolution state (for external access)
*/
function getFlowResolutionState() {
return flowResolutionState;
}
/**
* Get chunked flow state (for external access)
*/
function getChunkedFlowState() {
return chunkedFlowState;
}
/**
* Load a flow's full detail with embedded packets from flow folder
* @param {Object} flowSummary - Flow summary object with id, startTime, endTime
* @returns {Promise<Object>} Flow object with full packet data in phases
*/
async function loadFlowDetailWithPackets(flowSummary) {
console.log('[FlowDetail] loadFlowDetailWithPackets called with:', flowSummary);
console.log('[FlowDetail] chunkedFlowState:', chunkedFlowState ? 'exists' : 'null');
if (!chunkedFlowState) {
console.warn('[FlowDetail] No chunked flow state available - flow folder may not be loaded');
return null;
}
const { flowsDir, chunksMeta, chunkCache } = chunkedFlowState;
console.log('[FlowDetail] flowsDir:', flowsDir ? 'exists' : 'null');
console.log('[FlowDetail] chunksMeta length:', chunksMeta ? chunksMeta.length : 0);
const flowId = flowSummary.id;
const flowStartTime = flowSummary.startTime;
console.log(`[FlowDetail] Loading detail for flow ${flowId}, startTime: ${flowStartTime}`);
// Find ALL chunks that could contain this flow based on time range AND IPs
// Note: Chunks can have overlapping time ranges, so we need to search multiple chunks
const { initiator, responder, initiatorPort, responderPort } = flowSummary;
console.log(`[FlowDetail] Searching for chunk containing flow with startTime ${flowStartTime}`);
console.log(`[FlowDetail] Connection: ${initiator}:${initiatorPort} ↔ ${responder}:${responderPort}`);
console.log(`[FlowDetail] First few chunk time ranges:`, chunksMeta.slice(0, 5).map(c => ({file: c.file, start: c.start, end: c.end})));
// Collect all candidate chunks (matching time range and IPs)
const candidateChunks = [];
for (const chunk of chunksMeta) {
if (chunk.start <= flowStartTime && flowStartTime <= chunk.end) {
// Also check if chunk contains both initiator and responder IPs
const chunkIPs = chunk.ips || [];
const hasInitiator = chunkIPs.includes(initiator);
const hasResponder = chunkIPs.includes(responder);
if (hasInitiator && hasResponder) {
candidateChunks.push(chunk);
}
}
}
console.log(`[FlowDetail] Found ${candidateChunks.length} candidate chunks`);
if (candidateChunks.length === 0) {
console.error(`[FlowDetail] No chunks match flow ${flowId} (${initiator} ↔ ${responder} @ ${flowStartTime})`);
return null;
}
// Search through all candidate chunks until we find the flow
for (const chunk of candidateChunks) {
console.log(`[FlowDetail] Searching chunk ${chunk.file}...`);
const flows = await loadChunkFromCache(chunk.file, flowsDir, chunkCache);
// Try to find by ID first
let flow = flows.find(f => f.id === flowId);
// If not found by ID, try matching by connection tuple + startTime
if (!flow) {
flow = flows.find(f =>
f.initiator === initiator &&
f.responder === responder &&
f.initiatorPort === initiatorPort &&
f.responderPort === responderPort &&
Math.abs(f.startTime - flowStartTime) < 1000 // Within 1ms
);
}
if (flow) {
console.log(`[FlowDetail] ✅ Found flow ${flowId} in ${chunk.file} with ${countFlowPackets(flow)} packets`);
return flow;
}
console.log(`[FlowDetail] Flow not in ${chunk.file}, continuing search...`);
}
console.error(`[FlowDetail] ❌ Flow ${flowId} not found in any of ${candidateChunks.length} candidate chunks`);
return null;
}
/**
* Load chunk from cache or disk
* Note: Returns raw flows with full packet data in phases
*/
async function loadChunkFromCache(chunkFile, flowsDir, chunkCache) {
// Check if chunk is already cached
// Note: loadChunksForTimeRange may have cached converted flows - we need raw flows
// Use a different cache key for raw flows
const rawCacheKey = `raw:${chunkFile}`;
if (chunkCache.has(rawCacheKey)) {
console.log(`[FlowDetail] Using cached raw flows from ${chunkFile}`);
return chunkCache.get(rawCacheKey);
}
try {
console.log(`[FlowDetail] Loading chunk from disk: ${chunkFile}`);
const fileHandle = await flowsDir.getFileHandle(chunkFile);
const file = await fileHandle.getFile();
const content = await file.text();
const flows = JSON.parse(content);
// Cache raw flows separately from converted flows
chunkCache.set(rawCacheKey, flows);
console.log(`[FlowDetail] Loaded ${flows.length} raw flows from ${chunkFile}`);
if (flows.length > 0) {
const sample = flows[0];
console.log(`[FlowDetail] Sample flow structure:`, {
id: sample.id,
hasPhases: !!sample.phases,
establishmentCount: sample.phases?.establishment?.length || 0,
dataTransferCount: sample.phases?.dataTransfer?.length || 0,
closingCount: sample.phases?.closing?.length || 0
});
}
return flows;
} catch (err) {
console.error(`[FlowDetail] Failed to load ${chunkFile}:`, err);
return [];
}
}
/**
* Count total packets in a flow's phases
*/
function countFlowPackets(flow) {
if (!flow || !flow.phases) return 0;
const est = flow.phases.establishment?.length || 0;
const data = flow.phases.dataTransfer?.length || 0;
const close = flow.phases.closing?.length || 0;
return est + data + close;
}
/**
* Extract all packets from a flow's phases into a flat array
* @param {Object} flow - Flow object with phases containing packets
* @returns {Array} Array of packet objects with phase info
*/
function extractPacketsFromFlow(flow) {
if (!flow || !flow.phases) return [];
const packets = [];
const phases = ['establishment', 'dataTransfer', 'closing'];
for (const phaseName of phases) {
const phasePackets = flow.phases[phaseName] || [];
for (const entry of phasePackets) {
if (entry.packet) {
packets.push({
...entry.packet,
phase: phaseName,
phaseStep: entry.phase || entry.description || phaseName
});
}
}
}
// Sort by timestamp
packets.sort((a, b) => a.timestamp - b.timestamp);
console.log(`[FlowDetail] Extracted ${packets.length} packets from flow`);
return packets;
}
/**
* Load flows from multires_flows format (tcp_flow_detector output)
*/
async function loadFlowsFromMultiRes(folderHandle, onProgress) {
const resDir = await folderHandle.getDirectoryHandle('resolutions');
const rawDir = await resDir.getDirectoryHandle('raw');
// Load index
const indexFile = await rawDir.getFileHandle('index.json');
const index = JSON.parse(await (await indexFile.getFile()).text());
const allFlows = [];
const totalChunks = index.chunks.length;
// Load all raw chunks
for (let i = 0; i < totalChunks; i++) {
const chunk = index.chunks[i];
const file = await rawDir.getFileHandle(chunk.file);
const csvText = await (await file.getFile()).text();
const flows = parseFlowCSV(csvText);
allFlows.push(...flows);
if (onProgress) {
onProgress(((i + 1) / totalChunks) * 100, allFlows.length, index.total_count);
}
}
console.log(`[FlowLoader] Loaded ${allFlows.length} flows from ${totalChunks} chunks`);
return allFlows;
}
/**
* Parse flow CSV and convert to visualization format
*/
function parseFlowCSV(csvText) {
const lines = csvText.split('\n').filter(l => l.trim());
if (lines.length < 2) return [];
const headers = lines[0].split(',').map(h => h.trim());
const flows = [];
for (let i = 1; i < lines.length; i++) {
const values = lines[i].split(',');