-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathborgHUIstreamMgr.js
More file actions
1852 lines (1601 loc) · 57.3 KB
/
Copy pathborgHUIstreamMgr.js
File metadata and controls
1852 lines (1601 loc) · 57.3 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
const crypto = require("crypto");
const fs = require("fs");
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
const shardSize = 256 * 1024;
const MAX_FAIL_REQ = 8;
function sleep(ms){
return new Promise(resolve=>{
setTimeout(resolve,ms)
});
}
class Mutex {
constructor() {
this._locked = false;
this._waiters = [];
}
async lock() {
if (!this._locked) {
this._locked = true;
console.log(`lock():: locking`);
return;
}
return new Promise( (resolve) => {
this._waiters.push(resolve);
console.log(`lock():: n waiting =`, this._waiters.length);
});
}
unlock() {
if (this._waiters.length > 0) {
const next = this._waiters.shift();
console.log(`lock():: n exiting =`, this._waiters.length);
next();
} else {
this._locked = false;
console.log(`lock():: unlocked `, this._waiters.length);
}
}
}
class BorgHUIstreamMgr {
constructor(net) {
this.net = net;
this.cell = null;
this.streams = new Map(); // streamId → streamMeta / conversation
this.dstreams = new Map();
this.memFiles = new Map(); // streamId → Buffer ( in memory file system);
this.sentShardListener(); // start listening for sendBinShard results.
this.shardPortals = new Map();
this.initializeShardPortals();
console.log(`BorgHUIstreamMgr:: shardPortals`,this.shardPortals);
}
initializeShardPortals() {
const portals = this.net.portal.getPortalsAll('shardTreeCell');
this.shardPortals = portals; // keep original if needed
this.shardPortalsMap = new Map();
for (const node of portals.nodes) {
this.shardPortalsMap.set(node.ip, {
ip: node.ip,
port: portals.port,
pKey: node.pKey,
errors: node.errors || 0,
lastSuccess: node.date || 0,
lastFailure: 0,
bannedUntil: 0
});
}
this.portalIndex = 0; // round‑robin index
}
attachCell(cell){
this.cell = cell;
//console.log('hello');
}
prepareTempFile(filepath, fileSize) {
const file = filepath;
// Check if cache file already exists
let cacheExists = false;
let cacheSize = 0;
try {
if (fs.existsSync(file)) {
const stats = fs.statSync(file);
cacheSize = stats.size;
cacheExists = true;
//console.log(`prepareTempFile():: cache file exists: ${file} (${cacheSize} bytes)`);
}
} catch (err) {
console.error("Failed to check cache file:", err);
}
// If cache exists and matches expected size, keep it
if (cacheExists && cacheSize === fileSize) {
//console.log(`prepareTempFile():: using existing cache file (${fileSize} bytes)`);
return file;
}
// Otherwise, create new file or truncate existing
// Remove old file if it exists and size doesn't match
if (cacheExists) {
try {
fs.unlinkSync(file);
console.log(`prepareTempFile():: removed stale cache file (size mismatch: ${cacheSize} vs ${fileSize})`);
} catch (err) {
console.error("Failed to remove old temp file:", err);
}
}
// Pre-allocate the file to full size
const fd = fs.openSync(file, 'w');
fs.ftruncateSync(fd, fileSize);
fs.closeSync(fd);
//console.log(`prepareTempFile():: created new file (${fileSize} bytes)`);
return file;
}
prepareBlobMemFile(streamId, fileSize) {
// Remove any stale buffer
if (this.memFiles.has(streamId)) {
this.memFiles.delete(streamId);
}
// Allocate full-size buffer in RAM
const buffer = Buffer.alloc(fileSize);
// Store it in the memFile map
this.memFiles.set(streamId, buffer);
return buffer;
}
sha256(buf) {
return crypto.createHash('sha256').update(buf).digest('hex');
}
async writeShardToFile(stream,shard) {
const shardSize = stream.shardSize;
const fileSize = stream.totalSize;
const index = shard.shardIdx;
const offset = index * shardSize;
const expectedShardId = shard.shardId;
const remaining = fileSize - offset;
const isFinal = (index === stream.count - 1);
// 1. Size validation
if (!isFinal) {
// Non-final shard must match shardSize exactly
if (shard.shard.length !== shardSize) {
console.log(`writeShardToFile():: BAD_SIZE `,shard.shard.length,shardSize);
return { ok: false, reason: "BAD_SIZE", index };
}
} else {
// Final shard must be <= remaining bytes
if (shard.shard.length > remaining) {
console.log(`writeShardToFile():: BAD_SIZE_FINAL `,shard.shard.length,remaining);
return { ok: false, reason: "BAD_SIZE_FINAL", index };
}
}
// 2. Validate shard hash
const actualHash = this.sha256(shard.shard);
if (actualHash !== expectedShardId) {
console.log(`writeShardToFile():: BAD_HASH `,actualHash,expectedShardId);
return { ok: false, reason: "BAD_HASH", index };
}
// 3. Random-access write
if (stream.type === 'memFile' || stream.type === 'dsBuffer') {
shard.shard.copy(stream.buffer, offset);
}
else {
const fh = await fs.promises.open(stream.tempFilePath, 'r+');
try {
await fh.write(shard.shard, 0, shard.shard.length, offset);
} finally {
await fh.close();
}
}
return { ok: true, index };
}
// ---------------------------------------------------------
// Create a stream descriptor for outgoing messages
// ---------------------------------------------------------
async createStreamMsg(service,msg,type,winSize,nCopys=3,blob=null) {
const filename = msg.filename;
let streamId;
let shards;
let isMemoryFile = false;
if (type === 'memoryfile'){
type = 'file';
isMemoryFile = true;
}
// CASE 1: File-based stream (deterministic)
if (type === 'file') {
streamId = await this.getHash(msg.filename);
shards = await this.getShardMap(msg.filename);
}
// CASE 2: Blob-based stream (content-addressed)
else if (blob) {
streamId = this.sha256(blob); // deterministic for memFile/dsBuffer
shards = this.getBlobShardMap(blob);
}
// CASE 3: Memory stream without blob (rare)
else {
streamId = await this.getHash(msg.filename); // small file direct to memory buffer
shards = await this.getShardMap(msg.filename);
}
const fmap = {
service,
streamId,
filename,
isMemFile : isMemoryFile,
requestMutex: new Mutex(),
reqId : msg.reqId,
shardSize : shards.shardSize,
shardHashes : shards.shardHashes,
count : shards.count,
totalSize : shards.totalSize,
type : type,
winSize : winSize,
nCopys : nCopys,
// State machine
status : "metaDataSent", // metaDataSent → metaDataACK → transferring → completed
acked : false,
completed : false,
// Progress
shardsSent : 0,
pendingShards : new Set([...Array(shards.count).keys()]),
inFlight : new Set(),
blastPorts : new Map(),
blastIdx : 0,
shardsSentOK : new Map(),
inProgress : false,
// Diagnostics
sentAt : Date.now()
};
if (blob) {
fmap.buffer = streamId;
this.memFiles.set(streamId,blob);
}
this.streams.set(streamId, fmap);
return {
streamId,
shardSize: fmap.shardSize,
shardHashes : fmap.shardHashes,
count : fmap.count,
totalSize : fmap.totalSize,
type : type,
winSize : winSize,
filename
};
}
// ---------------------------------------------------------
// Send a normal PeerTree message that includes a stream descriptor
// ---------------------------------------------------------
async streamRepoFileFrom(service,repo,httpRes){
return await this.doOpenStream(repo,service,httpRes);
}
async streamFrom(service,fmap){
// FOR TESTING ONLY!
console.log('fig',fmap);
fmap.pendingShards = new Set([...Array(j.stream.count).keys()]);
fmap.inFlight = new Set(); // shardIdx values currently requested but not yet received
fmap.inProgress = true;
// Diagnostics
fmap.startAt = Date.now();
fmap.timeElapsed = 0;
// Storage
if (fmap.type === 'memFile' || fmap.type === 'dsBuffer') {
fmap.buffer = this.prepareBlobMemFile(fmap.streamId, fmap.totalSize);
}
else {
fmap.tempFilePath = await this.prepareTempFile(`./downloads/${fmap.streamId}.tmp`, fmap.totalSize);
}
// Start requesting shards
this.gatherShards(fmap);
// Kick off the first batch of shard requests
this.requestShardBatch(fmap.streamId,service);
}
streamTo(service,type = 'file',winSize = 12,nCopys=3,blob=null) {
return new Promise(async (resolve) => {
// Get all available portals
const portals = Array.from(this.shardPortalsMap.values());
if (portals.length === 0) {
resolve({ result: 'noPortalsAvailable' });
return;
}
const reqId = crypto.randomUUID();
const msg = {
req : 'openBinStream',
filename : service.filename
}
msg.reqId = reqId;
// Create stream descriptor
const stream = await this.createStreamMsg(service,msg,type,winSize,nCopys,blob);
msg.stream = stream;
const fullStream = this.streams.get(stream.streamId);
let startBlast = false;
let nResponses = 0;
const nPortals = portals.length;
let timer;
let failListener, replyListener, sendOKListener;
//console.log(`sendMsg():: `,msg,toIp);
// DELIVERED PATH
const toIp = service.host;
// FAILURE PATH
this.net.on('xhrFail', failListener = (j) => {
console.log('streamTo():: xhrFail ',j);
if (j.toHost === toIp && j.req === msg.req) {
nResponses++;
if (nResponses >= nPortals) {
this.net.removeListener('xhrFail', failListener);
this.net.removeListener('xhrPostOK', sendOKListener);
clearTimeout(timer);
}
}
});
// SUCCESS PATH
this.net.on('xhrPostOK', sendOKListener = async (j) => {
if (j.reqId === reqId) {
console.log(`streamTo():: heard from `,j.toHost);
nResponses++;
if (j.res.result === 'STREAM_META_ACK'){
fullStream.blastPorts.set(j.toHost,{ip:j.toHost,bannedUntil:0});
if (startBlast === false){
startBlast = true;
this.setStatus(stream.streamId, j.status);
await this.doBlastShardBatch(service,stream.streamId);
resolve(j);
}
}
if (nResponses >= nPortals) {
this.net.removeListener('xhrFail', failListener);
this.net.removeListener('xhrPostOK', sendOKListener);
clearTimeout(timer);
if (startBlast === false) {
console.error(`DStreamMgrObj.sendMsg():: failed to open remote stream`);
this.removeStream(stream.streamId);
resolve({ result: 'noPortalsResponded' });
return;
}
}
console.log(`BlastPorts Are`,fullStream.blastPorts);
}
});
// Timeout for first ACK
const TIMEOUT_MS = 5000;
timer = setTimeout(() => {
console.log('streamTo():: timeout waiting for first ACK');
this.net.removeListener('xhrFail', failListener);
this.net.removeListener('xhrPostOK', sendOKListener);
if (startBlast === false) {
console.error(`DStreamMgrObj.sendMsg():: startBlast Timeout - removing stream`);
this.removeStream(stream.streamId);
resolve({ result: 'noPortalsResponded' });
return;
}
}, TIMEOUT_MS);
service.endPoint = '/netREQ/';
portals.forEach((portal) => {
service.host = portal.ip;
console.log(`streamTo():: sending msg`,service,msg);
this.sendMsgCX(JSON.parse(JSON.stringify(service)), JSON.parse(JSON.stringify(msg)));
});
});
}
setStatus(sId,status){
const stream = this.streams.get(sId);
stream.status = status;
return;
}
async doBlastShardBatch(service, streamId) {
const stream = this.streams.get(streamId);
if (!stream) {
console.log(`Stream not found.`,streamId);
return;
}
// Nothing to do if stream is already complete
if (stream.completed) return;
// Fill the window
console.log(`doBlastShardBatch():: pending ${stream.pendingShards.size} inFlight: ${stream.inFlight.size}`);
while (
stream.inFlight.size < stream.winSize &&
stream.pendingShards.size > 0
){
const mutex = stream.requestMutex;
await mutex.lock();
try {
const shardIdx = stream.pendingShards.values().next().value;
stream.pendingShards.delete(shardIdx);
const shard = stream.shardHashes[shardIdx];
const shardId = shard.hash;
let shardHID = this.net.wallet.calculateHash(`${shardId}-${this.net.wallet.ownMUID}-${Date.now()}`);
if (stream.isMemFile){
shardHID = this.net.wallet.calculateHash(`${shardId}-${this.net.wallet.ownMUID}`);
console.log(`shardHID = this.net.wallet.calculateHash(${shardId}-${this.net.wallet.ownMUID}`,shardHID);
}
const shardSig = this.net.wallet.signToken(shardHID);
shard.hashHID = shardHID;
console.log(`stream shardHashes`,stream.shardHashes[shardIdx]);
// Mark as in-flight
stream.inFlight.add(shardIdx);
console.log(`hashing:: ${shardId}-${this.net.wallet.ownMUID}-${Date.now()}`);
console.log(`doBlastShardBatch():: shard.hashID `,`${shard.hashHID}:${shardHID}`);
console.log(`doBlastShardBatch():: service is `,service);
const portal = this.getNextBlastPort(stream);
if (portal) {
service.host = portal.ip;
}
// Dispatch the shard
console.log(`doBlastShardBatch():: `,service, stream.streamId, shardIdx, shardId,shardHID,shardSig);
this.sendStreamShard(service, stream.streamId, shardIdx, shardId,shardHID,shardSig);
// Optional: status update
this.setStatus(stream.streamId, `sending:${shardIdx}`);
} finally {
mutex.unlock();
}
}
}
getNextBlastPort(stream) {
const now = Date.now();
const portals = Array.from(stream.blastPorts.values());
if (portals.length === 0) return null;
for (let i = 0; i < portals.length; i++) {
const portal = portals[stream.blastIdx % portals.length];
stream.blastIdx = (stream.blastIdx + 1) % portals.length;
// Skip banned portals
if (portal.bannedUntil && portal.bannedUntil > now) {
continue;
}
return portal;
}
// If all portals are banned, pick the least-banned one
return portals.reduce((a, b) =>
(a.bannedUntil || 0) < (b.bannedUntil || 0) ? a : b
);
}
// ---------------------------------------------------------
// Send a shard to a remote host
// ---------------------------------------------------------
async sendStreamShard(service, streamId, shardIdx,shardId,shardHID,shardSig) {
const stream = this.streams.get(streamId);
if (!service ) service = stream.service;
const shard = await this.getShardData(streamId, shardIdx);
const msg = {
streamId : streamId,
shardId : shardId,
shardIdx : shardIdx,
reqTime : Date.now(),
shard : shard,
// Required by /storeShard/ endpoint
hash : shardId, // canonical shard hash
hashID : shardHID, // shart Identity pointer
hashSig : shardSig,
opKey : this.net.wallet.publicKey,
encrypt : stream.encrypt || 0,
expires : stream.expires || 0,
nCopys : stream.nCopys || 3,
pass : stream.pass || 0,
fptr : shardIdx*stream.shardSize,
index : shardIdx,
from : this.net.wallet.ownMUID
}
// Then send raw binary shard
service.endPoint = '/storeShard/'
console.log(`sendStreamShard()::`,msg);
this.sendBinaryShardCX(service, msg);
this.setStatus(streamId,'transfering:'+shardId);
}
// ---------------------------------------------------------
// Remove stream metadata
// ---------------------------------------------------------
removeStream(streamId) {
this.memFiles.delete(streamId);
this.streams.delete(streamId);
}
closeOutgoingStream(stream){
this.removeStream(stream.streamId);
}
getHash(filePath) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash("sha256");
const stream = fs.createReadStream(filePath);
stream.on("data", chunk => hash.update(chunk));
stream.on("end", () => resolve(hash.digest("hex")));
stream.on("error", reject);
});
}
getBlobShardMap(blob, shardSize = 256 * 1024) {
const shardHashes = [];
const totalSize = blob.length;
let offset = 0;
while (offset < totalSize) {
const end = Math.min(offset + shardSize, totalSize);
const shard = blob.slice(offset, end);
const hash = crypto.createHash("sha256")
.update(shard)
.digest("hex");
shardHashes.push(hash);
offset = end;
}
return {
shardSize,
shardHashes,
count: shardHashes.length,
totalSize
};
}
getShardMap(filePath, shardSize = 256 * 1024) {
return new Promise((resolve, reject) => {
const shardHashes = [];
let shardBuffer = Buffer.alloc(0);
let totalSize = 0;
const stream = fs.createReadStream(filePath);
stream.on("data", chunk => {
totalSize += chunk.length;
// Append chunk to current shard buffer
shardBuffer = Buffer.concat([shardBuffer, chunk]);
// Process full shards
while (shardBuffer.length >= shardSize) {
const shard = shardBuffer.slice(0, shardSize);
const hash = crypto.createHash("sha256")
.update(shard)
.digest("hex");
shardHashes.push({hash:hash,hashHID:null});
shardBuffer = shardBuffer.slice(shardSize);
}
});
stream.on("end", () => {
// Process final partial shard
if (shardBuffer.length > 0) {
const hash = crypto.createHash("sha256")
.update(shardBuffer)
.digest("hex");
shardHashes.push({hash:hash,hashHID:null});
}
resolve({
shardSize,
shardHashes,
count: shardHashes.length,
totalSize
});
});
stream.on("error", reject);
});
}
getShardData(streamId, shardIdx) {
return new Promise(async (resolve, reject) => {
const stream = this.streams.get(streamId);
if (!stream) return reject(new Error("Unknown streamId"));
const start = shardIdx * stream.shardSize;
const end = Math.min(start + stream.shardSize, stream.totalSize);
// CASE 1: memFile / dsBuffer (RAM)
//console.log(`getShardData::() stream is `,stream);
if (stream.hasOwnProperty('buffer') && stream.buffer !== null && (stream.type === 'memFile' || stream.type === 'dsBuffer')) {
try {
const slice = stream.buffer.slice(start, end);
return resolve(slice);
} catch (err) {
return reject(err);
}
}
// CASE 2: file (disk)
const chunks = [];
const fstream = fs.createReadStream(stream.filename, {
start,
end: end - 1 // inclusive
});
fstream.on("data", chunk => chunks.push(chunk));
fstream.on("end", () => resolve(Buffer.concat(chunks)));
fstream.on("error", reject);
});
}
gatherShards(stream) {
const handler = async (data) => {
if (data.streamId !== stream.streamId) return;
try {
await this.onShardReceived({
streamId: stream.streamId,
shard: {
portal : data.toHost,
shardId : data.hash,
shardIdx : data.index,
error : data.error,
shard : data.data
}
});
} catch (err) {
// If shard processing fails, close the stream
this.closeIncomingStream(stream);
}
};
this.net.on('requestBinShardOk', handler);
stream._shardHandler = handler;
}
closeIncomingStream(stream, withError = false) {
// Remove shard event listener
if (stream._shardHandler) {
this.net.removeListener('binShard', stream._shardHandler);
stream._shardHandler = null;
}
// Mark stream as completed
stream.inProgress = false;
stream.completed = true;
stream.status = "completed";
// Diagnostics
stream.timeElapsed = Date.now() - stream.startAt;
// Remove from active streams
console.log(`Stream ${stream.streamId} completed in ${stream.timeElapsed}ms`);
let httpRes = stream.httpRes;
let filePath = stream.tempFilePath;
let mimeType = stream.mimeType;
console.log(`closeIncomingStream():: mimeType`, mimeType);
if (mimeType.startsWith("video/")) {
console.log(`closeIncomingStream():: is video true`);
// Only end clients if they still exist and stream wasn't already closed
if (stream.videoClients && stream.videoClients.length > 0) {
for (const client of stream.videoClients) {
try {
console.log(`closeIncomingStream():: ending video client stream`);
client.end();
} catch (err) {
console.warn("Video client already ended", err);
}
}
}
//this.dstreams.delete(stream.streamId);
return;
}
if (withError) {
console.error("getFileFromRepo():: File read error: MAX_TRIES");
if (httpRes && !httpRes.headersSent) {
httpRes.writeHead(500);
httpRes.end("File read error");
}
this.dstreams.delete(stream.streamId);
return;
}
if (stream.mimeType.startsWith("text") && stream.mode !== 'download') {
const fileContent = fs.readFileSync(stream.tempFilePath, 'utf8');
const jreply = {
callback : 'handlerTextSpot',
res : 'textSpot',
html : fileContent,
ftype : stream.mimeType
}
const reply = JSON.stringify(jreply);
const headers = {
"Content-Type": "application/json", // Changed from stream.mimeType
"Content-Length": Buffer.byteLength(reply), // Changed from stream.totalSize
};
headers["ETag"] = `"${stream.streamId}"`;
headers["Content-Disposition"] = `inline; filename="${stream.origName}"`;
// Send headers
httpRes.writeHead(200, headers);
httpRes.end(reply);
return true;
}
// For non-video files, deliver file
if (httpRes && !httpRes.headersSent) {
const headers = {
"Content-Type": stream.mimeType,
"Content-Length": stream.totalSize,
"Accept-Ranges": "bytes"
};
headers["ETag"] = `"${stream.streamId}"`;
headers["Content-Disposition"] = `inline; filename="${stream.origName}"`;
// Send headers
httpRes.writeHead(200, headers);
// Create a read stream and pipe it out
const fileStream = fs.createReadStream(filePath);
fileStream.on("error", err => {
console.error("getFileFromRepo():: File read error:", err);
if (!httpRes.headersSent) {
httpRes.writeHead(500);
httpRes.end("File read error");
}
});
// Pipe file to client
fileStream.pipe(httpRes);
}
// remove stream
this.dstreams.delete(stream.streamId);
}
async doOpenStream(repo, service, httpRes, winSize = 12) {
let j = repo.file;
console.log(`doOpenStream():: repo.file`,j);
let shards = [];
j.shards.forEach((shard) => shards.push({ hash: shard.shardID, shardHID: shard.shardHID }));
const input = j.filename;
const origName = input.split('/').pop();
const fmap = {
httpRes: httpRes,
requestMutex: new Mutex(),
videoClients: [],
videoShardBuffer: new Map(),
inRetry: new Map(),
nextToSend: 0,
service: service,
streamId: j.fileInfo.checkSum,
filename: service.filename,
mode : service?.mode,
origName: origName,
mimeType: j.fileInfo.fileType,
reqId: crypto.randomUUID(),
response: 'na',
request: 'sendShard',
shardSize: j.fileInfo.shardSize,
shardHashes: shards,
count: shards.length,
totalSize: j.fileInfo.fileSize,
type: 'file',
// State machine
status: "readyForShards",
acked: true,
completed: false,
// Progress
shardsReceived: 0,
pendingShards: new Set([...Array(shards.length).keys()]),
inFlight: new Set(),
windowSize: winSize,
inProgress: true,
// Diagnostics
startAt: Date.now(),
timeElapsed: 0,
_backgroundDownloadStarted: false
};
// Storage
if (fmap.type === 'memFile' || fmap.type === 'dsBuffer') {
fmap.buffer = this.prepareBlobMemFile(fmap.streamId, fmap.totalSize);
} else {
fmap.tempFilePath = await this.prepareTempFile(fmap.filename, fmap.totalSize);
}
this.dstreams.set(fmap.streamId, fmap);
// 🔥 NEW: Try to stream from cache first (with range support)
const streamedFromCache = await this.streamFromCacheFast(fmap);
if (streamedFromCache) {
console.log(`doOpenStream():: streamed from cache for ${fmap.streamId}`);
return fmap;
}
// If not fully cached, handle video streaming with range support
if (fmap.mimeType.startsWith("video/")) {
console.log(`doOpenStream():: is video: handling range request`);
await this.handleRangeRequest(fmap.streamId, httpRes);
return fmap;
}
// For non-video files, use normal shard retrieval
this.dstreams.set(fmap.streamId, fmap);
// Start requesting shards
this.gatherShards(fmap);
// Kick off the first batch of shard requests
this.requestShardBatch(fmap.streamId, service);
return fmap;
}
getNextPortal() {
const now = Date.now();
const portals = Array.from(this.shardPortalsMap.values());
if (portals.length === 0) return null;
for (let i = 0; i < portals.length; i++) {
const portal = portals[this.portalIndex % portals.length];
this.portalIndex = (this.portalIndex + 1) % portals.length;
// Skip banned portals
if (portal.bannedUntil && portal.bannedUntil > now) {
continue;
}
return portal;
}
// If all portals are banned, pick the least-banned one
return portals.reduce((a, b) =>
(a.bannedUntil || 0) < (b.bannedUntil || 0) ? a : b
);
}
async requestShardBatch(streamId,service) {
//console.log(`requestShardBatch():: `);
const stream = this.dstreams.get(streamId);
if (!stream) {
console.log(`requestShardBatch():: stream NOT OPEN.`);
return;
}
// If nothing left, close stream
if (stream.pendingShards.size === 0 && stream.inFlight.size === 0) {
return;
}
const mutex = stream.requestMutex;
await mutex.lock();
try {
// Fill the window
console.log(`requestShardBatch():: pending ${stream.pendingShards.size} inFlight: ${stream.inFlight.size} winSize${stream.windowSize} `);
let portal = {host:'localhost',port:80,endpoint:'/'};
while (
stream.inFlight.size < stream.windowSize &&
stream.pendingShards.size > 0
) {
const shardIdx = this.getLowestPendingShard(stream.pendingShards);
if (shardIdx === null) return;
// Check if shard exists locally FIRST (acts as a cache)
const foundLocal = await this.checkLocalShard(streamId, shardIdx,portal);
if (foundLocal) {
// The shard was found locally and the event has been emitted
// The onShardReceived handler will process it
// Continue to the next shard without making a network request
console.log(`requestShardBatch():: shard ${shardIdx} found in local cache, skipping network request`);
continue;
}
// If not found locally, proceed with network request
// Move shard from pending → inFlight
stream.pendingShards.delete(shardIdx);
stream.inFlight.add(shardIdx);
let shard = stream.shardHashes[shardIdx];
// 🔥 ROTATE PORTAL NODE HERE
portal = this.getNextPortal();
if (portal) {
service.host = portal.ip;
service.port = this.shardPortals.port; // shared port
}
const msg = {
req : "requestShard",
sIndex : shardIdx,
shard : {
streamId : streamId,
ownerID : this.net.wallet.ownMUID,
hash : shard.hash,
hashID : shard.shardHID,
encrypted : 0,
shardSize : stream.shardSize
}
};
console.log(`requestShardBatch():: sending `,shardIdx,stream.shardHashes[shardIdx].hash,portal.ip);
console.log(` `);
this.sendMsgCX(service, msg);
}
} finally {
mutex.unlock();
}
}
async checkLocalShard(streamId, shardIdx,portal) {
const stream = this.dstreams.get(streamId);
if (!stream) {
console.log(`checkLocalShard():: stream not found ${streamId}`);
return false;
}
// Check if we have a local file or buffer that already contains this shard
const shard = stream.shardHashes[shardIdx];
if (!shard) {
console.log(`checkLocalShard():: shard ${shardIdx} not found in shardHashes`);
return false;
}
let shardData = null;
// CASE 1: Check if we have a buffer (memFile or dsBuffer)
if (stream.hasOwnProperty('buffer') && stream.buffer !== null &&
(stream.type === 'memFile' || stream.type === 'dsBuffer')) {
const start = shardIdx * stream.shardSize;
const end = Math.min(start + stream.shardSize, stream.totalSize);
try {
shardData = stream.buffer.slice(start, end);
} catch (err) {
console.log(`checkLocalShard():: error reading from buffer: ${err}`);
return false;
}
}
// CASE 2: Check if we have a temporary file on disk
else if (stream.tempFilePath) {
try {
const start = shardIdx * stream.shardSize;
const end = Math.min(start + stream.shardSize, stream.totalSize);
// Check if file exists
if (!fs.existsSync(stream.tempFilePath)) {
console.log(`checkLocalShard():: temp file not found ${stream.tempFilePath}`);
return false;
}
// Read the shard from the file
const fd = fs.openSync(stream.tempFilePath, 'r');
const buffer = Buffer.alloc(end - start);
const readBytes = fs.readSync(fd, buffer, 0, buffer.length, start);
fs.closeSync(fd);
if (readBytes === 0) {
console.log(`checkLocalShard():: no data read from file for shard ${shardIdx}`);
return false;
}