@decentnetwork/beagle 0.1.138 → 0.1.143
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/carrier-node.d.ts +21 -0
- package/dist/carrier-node.js +17 -1
- package/dist/desktop/app.js +303 -86
- package/dist/embedded-host.d.ts +13 -0
- package/dist/embedded-host.js +301 -36
- package/dist/file-route.d.ts +43 -0
- package/dist/file-route.js +55 -0
- package/dist/message-store.d.ts +7 -2
- package/dist/message-store.js +25 -3
- package/package.json +3 -3
package/dist/embedded-host.js
CHANGED
|
@@ -13,6 +13,7 @@ import { EventEmitter } from "node:events";
|
|
|
13
13
|
import { existsSync } from "node:fs";
|
|
14
14
|
import { mkdir, readFile, writeFile, unlink } from "node:fs/promises";
|
|
15
15
|
import { basename, resolve } from "node:path";
|
|
16
|
+
import { createHash } from "node:crypto";
|
|
16
17
|
import { CarrierNode } from "./carrier-node.js";
|
|
17
18
|
import { MessageStore } from "./message-store.js";
|
|
18
19
|
import { parseGroupFile, storedGroupFiles, withoutFileData } from "./group-file.js";
|
|
@@ -20,13 +21,29 @@ import { FriendMetaStore } from "./friend-meta.js";
|
|
|
20
21
|
import { Logger } from "./logger.js";
|
|
21
22
|
import { acquireIdentityLock } from "./identity-lock.js";
|
|
22
23
|
import { refreshPendingAvatars, requesterAvatar } from "./pending-requests.js";
|
|
23
|
-
|
|
24
|
-
* on disk until they reconnect, and an unbounded queue is how you fill a
|
|
25
|
-
* user's disk by accident. Live transfers have no such limit. */
|
|
26
|
-
const OUTBOX_MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
24
|
+
import { OFFER_WINDOW_MS, routeFileSend } from "./file-route.js";
|
|
27
25
|
/** Inline envelope ceiling for a JS peer: base64 (~1.34x) inside a 16MB
|
|
28
26
|
* bulkmsg cap. */
|
|
29
27
|
const INLINE_MAX_BYTES = 11 * 1024 * 1024;
|
|
28
|
+
/** Re-offer backoff for a queued file whose live delivery the SDK gave up on
|
|
29
|
+
* (#liveDeliveryGaveUp): 15 s, 30 s, 1 min… capped at 5 min. */
|
|
30
|
+
const LIVE_RETRY_BASE_MS = 15_000;
|
|
31
|
+
const LIVE_RETRY_MAX_MS = 5 * 60_000;
|
|
32
|
+
/** What a sending-side `file-cancel` means (peer's `onFileCancel` reasons):
|
|
33
|
+
* none = the friend's KILL, they declined it → "cancelled"; "local" = our own
|
|
34
|
+
* cancelSend, the caller sets the row; anything else ("no-response",
|
|
35
|
+
* "timeout", "peer-offline", or a reason a later peer adds) = the SDK gave up
|
|
36
|
+
* on the path → the file is still owed (#liveDeliveryGaveUp). */
|
|
37
|
+
export function liveCancelMeaning(reason) {
|
|
38
|
+
if (!reason)
|
|
39
|
+
return "declined";
|
|
40
|
+
if (reason === "local")
|
|
41
|
+
return "ours";
|
|
42
|
+
return "gave-up";
|
|
43
|
+
}
|
|
44
|
+
/** A live send with no progress event for this long counts as a give-up
|
|
45
|
+
* (#giveUpStalledSends) — same rule as lan 0.1.325 (LIVE_STALL_MS). */
|
|
46
|
+
const LIVE_STALL_MS = 90_000;
|
|
30
47
|
/** Native (iOS/Android) peers get NO inline shortcut at any size — they
|
|
31
48
|
* stream via sendFile → DNFT1 (peer >= 0.1.141) like everyone else, because
|
|
32
49
|
* the inline envelope has no usable confirmation against a native peer:
|
|
@@ -54,7 +71,7 @@ function sanitizeFileName(name) {
|
|
|
54
71
|
export class EmbeddedHost {
|
|
55
72
|
kind = "embedded";
|
|
56
73
|
hasVirtualLan = false;
|
|
57
|
-
#node
|
|
74
|
+
#node;
|
|
58
75
|
#messages;
|
|
59
76
|
#meta;
|
|
60
77
|
#logger = new Logger({ prefix: "Beagle" });
|
|
@@ -83,11 +100,25 @@ export class EmbeddedHost {
|
|
|
83
100
|
#callWaiters = [];
|
|
84
101
|
/** fileId -> which chat message it belongs to, so progress can patch it. */
|
|
85
102
|
#activeSends = new Map();
|
|
103
|
+
/** Checks live sends for LIVE_STALL_MS without progress (#giveUpStalledSends). */
|
|
104
|
+
#stallTimer = null;
|
|
105
|
+
/** fileId -> the offer-window timer of a live send that may still fall back
|
|
106
|
+
* to Express (iOS `offerWindow`, file-route.ts). Cleared on the first sign
|
|
107
|
+
* the friend accepted (an ack = file-progress), on complete and on cancel. */
|
|
108
|
+
#offerWindows = new Map();
|
|
109
|
+
/** `<peer>:<sha256>` of inbound files being saved right now, so two
|
|
110
|
+
* deliveries of the same bytes arriving together still make one row. */
|
|
111
|
+
#savingInbound = new Set();
|
|
112
|
+
/** msgId -> when a queued file whose live delivery the SDK gave up on may be
|
|
113
|
+
* offered again (#liveDeliveryGaveUp). Backs off per file; the friend
|
|
114
|
+
* reconnecting clears it. In memory: a restart retries at once. */
|
|
115
|
+
#retryBackoff = new Map();
|
|
86
116
|
#autoAccept;
|
|
87
117
|
/** Released when this peer stops, so the daemon may take the identity. */
|
|
88
118
|
#releaseIdentity = null;
|
|
89
119
|
constructor(opts) {
|
|
90
120
|
this.#opts = opts;
|
|
121
|
+
this.#node = opts.node ?? new CarrierNode();
|
|
91
122
|
this.#autoAccept = opts.autoAcceptFriends;
|
|
92
123
|
this.#messages = new MessageStore(resolve(opts.configDir, "messages.json"));
|
|
93
124
|
this.#meta = new FriendMetaStore(resolve(opts.configDir, "friends-meta.json"));
|
|
@@ -180,6 +211,9 @@ export class EmbeddedHost {
|
|
|
180
211
|
})();
|
|
181
212
|
}, 8000);
|
|
182
213
|
this.#sweepTimer.unref?.();
|
|
214
|
+
const stallMs = this.#opts.liveStallMs ?? LIVE_STALL_MS;
|
|
215
|
+
this.#stallTimer = setInterval(() => this.#giveUpStalledSends(Date.now()), Math.min(8000, Math.max(20, stallMs / 4)));
|
|
216
|
+
this.#stallTimer.unref?.();
|
|
183
217
|
}
|
|
184
218
|
#sweeping = false;
|
|
185
219
|
/** A session that can actually carry traffic right now. */
|
|
@@ -255,8 +289,13 @@ export class EmbeddedHost {
|
|
|
255
289
|
// sat visibly stuck despite the peer being online. One delayed retry
|
|
256
290
|
// covers that gap; the per-send chain and later reconnects cover the
|
|
257
291
|
// rest.
|
|
258
|
-
if (e.status === "connected")
|
|
259
|
-
|
|
292
|
+
if (e.status === "connected") {
|
|
293
|
+
// A fresh session is a fresh chance: offer backed-off files now.
|
|
294
|
+
for (const b of this.#retryBackoff.values())
|
|
295
|
+
if (b.peer === e.pubkey)
|
|
296
|
+
b.notBefore = 0;
|
|
297
|
+
void this.#chainFlush(e.pubkey);
|
|
298
|
+
} // fast path
|
|
260
299
|
});
|
|
261
300
|
this.#node.on("call-signal", (evt) => {
|
|
262
301
|
this.#callLog.push({
|
|
@@ -271,9 +310,11 @@ export class EmbeddedHost {
|
|
|
271
310
|
for (const w of waiters)
|
|
272
311
|
w();
|
|
273
312
|
});
|
|
274
|
-
// Inline files
|
|
313
|
+
// Inline files: the path native iOS/Android peers use online, and (peer
|
|
314
|
+
// >= 0.1.176) an offline file message pulled from Express — `via`
|
|
315
|
+
// "offline", `fileId` = SHA-256 of the bytes. Stored once per bytes.
|
|
275
316
|
this.#node.on("inline-file", (f) => {
|
|
276
|
-
void this.#saveIncoming(f.pubkey, f.name, Buffer.from(f.data));
|
|
317
|
+
void this.#saveIncoming(f.pubkey, f.name, Buffer.from(f.data), { via: f.via, sha256: f.fileId });
|
|
277
318
|
});
|
|
278
319
|
// toxcore file transfer. The daemon logs an incoming file once, on
|
|
279
320
|
// completion — no "receiving" chip — and MessageStore's status enum has no
|
|
@@ -292,17 +333,23 @@ export class EmbeddedHost {
|
|
|
292
333
|
// `sending` is authoritative for direction — no map scanning needed.
|
|
293
334
|
if (!p.sending)
|
|
294
335
|
return;
|
|
336
|
+
// An ack means the friend accepted: no Express fallback for this one.
|
|
337
|
+
this.#endOfferWindow(p.fileId);
|
|
295
338
|
const s = this.#activeSends.get(p.fileId);
|
|
296
|
-
if (s)
|
|
297
|
-
|
|
339
|
+
if (!s)
|
|
340
|
+
return;
|
|
341
|
+
s.lastMs = Date.now();
|
|
342
|
+
this.#messages.patchFile(s.peer, s.msgId, { sent: p.received });
|
|
298
343
|
});
|
|
299
344
|
this.#node.on("file-complete", (p) => {
|
|
300
345
|
if (p.sending) {
|
|
346
|
+
this.#endOfferWindow(p.fileId);
|
|
301
347
|
const s = this.#activeSends.get(p.fileId);
|
|
302
348
|
if (!s)
|
|
303
349
|
return;
|
|
304
350
|
this.#messages.patchFile(s.peer, s.msgId, { status: "sent", sent: p.size });
|
|
305
351
|
this.#activeSends.delete(p.fileId);
|
|
352
|
+
this.#retryBackoff.delete(s.msgId);
|
|
306
353
|
void unlink(resolve(this.outboxDir, s.msgId)).catch(() => undefined);
|
|
307
354
|
this.#events.emit("event", { type: "chat", userid: s.peer, dir: "out" });
|
|
308
355
|
return;
|
|
@@ -314,11 +361,30 @@ export class EmbeddedHost {
|
|
|
314
361
|
this.#node.on("file-cancel", (p) => {
|
|
315
362
|
if (!p.sending)
|
|
316
363
|
return;
|
|
364
|
+
this.#endOfferWindow(p.fileId);
|
|
317
365
|
const s = this.#activeSends.get(p.fileId);
|
|
318
366
|
if (!s)
|
|
319
367
|
return;
|
|
320
|
-
|
|
368
|
+
const meaning = liveCancelMeaning(p.reason);
|
|
369
|
+
// Our own cancelSend: whoever called it sets the row (they forget the
|
|
370
|
+
// send first, so this is only a stray). Left tracked, so the 90 s
|
|
371
|
+
// no-progress backstop still settles it.
|
|
372
|
+
if (meaning === "ours")
|
|
373
|
+
return;
|
|
321
374
|
this.#activeSends.delete(p.fileId);
|
|
375
|
+
// The SDK ending a send itself — no answer to the offer ("no-response"),
|
|
376
|
+
// no ack progress ("timeout"), the friend's session gone
|
|
377
|
+
// ("peer-offline", peer >= 0.1.178), or any reason it adds later — is the
|
|
378
|
+
// PATH failing, not anyone cancelling. The file is still owed: Express
|
|
379
|
+
// if it fits, else back to the outbox and offered again when they are
|
|
380
|
+
// back. Never "cancelled".
|
|
381
|
+
if (meaning === "gave-up") {
|
|
382
|
+
void this.#liveDeliveryGaveUp(s.peer, s.msgId, p.reason);
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
// No reason: the friend's KILL — they declined it.
|
|
386
|
+
this.#messages.patchFile(s.peer, s.msgId, { status: "cancelled" });
|
|
387
|
+
this.#events.emit("event", { type: "chat", userid: s.peer, dir: "out" });
|
|
322
388
|
});
|
|
323
389
|
}
|
|
324
390
|
/** A group file that came with its bytes: downloads/<name> (a different
|
|
@@ -343,17 +409,22 @@ export class EmbeddedHost {
|
|
|
343
409
|
/** downloads/<name> ← a group file's bytes; a different file of the same
|
|
344
410
|
* name gets "-2", "-3"… Returns the name used. */
|
|
345
411
|
async #writeGroupDownload(f) {
|
|
412
|
+
return this.#writeDownload(f.name, f.data);
|
|
413
|
+
}
|
|
414
|
+
/** downloads/<name> ← bytes, never over a DIFFERENT file of the same name:
|
|
415
|
+
* that one keeps its name and these get "-2", "-3"… Returns the name used. */
|
|
416
|
+
async #writeDownload(fileName, data) {
|
|
346
417
|
await mkdir(this.downloadsDir, { recursive: true });
|
|
347
|
-
const safe = sanitizeFileName(
|
|
418
|
+
const safe = sanitizeFileName(fileName);
|
|
348
419
|
const dot = safe.lastIndexOf(".");
|
|
349
420
|
let name = safe;
|
|
350
421
|
for (let i = 2; i < 1000; i++) {
|
|
351
422
|
const existing = await readFile(resolve(this.downloadsDir, name)).catch(() => undefined);
|
|
352
|
-
if (!existing || existing.equals(
|
|
423
|
+
if (!existing || existing.equals(data))
|
|
353
424
|
break;
|
|
354
425
|
name = dot > 0 ? `${safe.slice(0, dot)}-${i}${safe.slice(dot)}` : `${safe}-${i}`;
|
|
355
426
|
}
|
|
356
|
-
await writeFile(resolve(this.downloadsDir, name),
|
|
427
|
+
await writeFile(resolve(this.downloadsDir, name), data);
|
|
357
428
|
return name;
|
|
358
429
|
}
|
|
359
430
|
/** On start: group files a host older than beagle 0.1.131 stored as CGP1
|
|
@@ -386,20 +457,33 @@ export class EmbeddedHost {
|
|
|
386
457
|
if (saved || dropped)
|
|
387
458
|
this.#logger.info(`stored group files: ${saved} saved as files, ${dropped} duplicates dropped`);
|
|
388
459
|
}
|
|
389
|
-
/** Persist a received file under downloads/ and log it in the thread.
|
|
390
|
-
|
|
391
|
-
|
|
460
|
+
/** Persist a received file under downloads/ and log it in the thread.
|
|
461
|
+
*
|
|
462
|
+
* Once per bytes (iOS OFFLINE-FILE-MESSAGE.md, "Identity and dedup": the
|
|
463
|
+
* row id is `ft-` + SHA-256): Express re-delivering an offline file on
|
|
464
|
+
* reconnect, or a file that came live AND through the 10 s Express
|
|
465
|
+
* fallback, makes one row. Received rows carry `sha256` from now on. */
|
|
466
|
+
async #saveIncoming(pubkey, name, data, opts = {}) {
|
|
467
|
+
const sha256 = (opts.sha256 || createHash("sha256").update(data).digest("hex")).toLowerCase();
|
|
468
|
+
const key = `${pubkey}:${sha256}`;
|
|
469
|
+
if (this.#savingInbound.has(key) || this.#messages.hasFileSha(pubkey, sha256, "in")) {
|
|
470
|
+
this.#logger.info(`"${name}" from ${pubkey.slice(0, 8)} already received (ft-${sha256.slice(0, 16)}) — not stored twice`);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
this.#savingInbound.add(key);
|
|
392
474
|
try {
|
|
393
|
-
await
|
|
394
|
-
|
|
395
|
-
this.#messages.appendFile(pubkey, "in", { name: safe, size: data.length });
|
|
475
|
+
const saved = await this.#writeDownload(name, data);
|
|
476
|
+
this.#messages.appendFile(pubkey, "in", { name: saved, size: data.length, sha256 }, Date.now(), { via: opts.via });
|
|
396
477
|
this.#meta.ensure(pubkey);
|
|
397
478
|
this.#events.emit("event", { type: "chat", userid: pubkey, dir: "in" });
|
|
398
|
-
this.#logger.info(`saved "${
|
|
479
|
+
this.#logger.info(`saved "${saved}" (${data.length}B) from ${pubkey.slice(0, 8)}${opts.via === "offline" ? " (offline, via Express)" : ""}`);
|
|
399
480
|
}
|
|
400
481
|
catch (e) {
|
|
401
482
|
this.#logger.warn(`could not save incoming file: ${e.message}`);
|
|
402
483
|
}
|
|
484
|
+
finally {
|
|
485
|
+
this.#savingInbound.delete(key);
|
|
486
|
+
}
|
|
403
487
|
}
|
|
404
488
|
/** Deliver anything queued while this friend was offline. */
|
|
405
489
|
async #flushOutbox(pubkey) {
|
|
@@ -424,15 +508,29 @@ export class EmbeddedHost {
|
|
|
424
508
|
continue;
|
|
425
509
|
}
|
|
426
510
|
const path = resolve(this.outboxDir, msg.id);
|
|
427
|
-
if (!existsSync(path))
|
|
511
|
+
if (!existsSync(path)) {
|
|
512
|
+
// Nothing left to deliver: say so instead of "waits here" forever.
|
|
513
|
+
this.#messages.patchFile(pubkey, msg.id, { status: "failed" });
|
|
514
|
+
this.#events.emit("event", { type: "chat", userid: pubkey, dir: "out" });
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
const backoff = this.#retryBackoff.get(msg.id);
|
|
518
|
+
if (backoff && backoff.notBefore > Date.now())
|
|
428
519
|
continue;
|
|
429
520
|
try {
|
|
430
521
|
const data = await readFile(path);
|
|
431
522
|
const fileId = this.#node.sendFile(pubkey, new Uint8Array(data), msg.file.name);
|
|
432
523
|
if (fileId) {
|
|
433
524
|
this.#messages.patchFile(pubkey, msg.id, { status: "sending", sent: 0 });
|
|
434
|
-
this.#activeSends.set(fileId, { peer: pubkey, msgId: msg.id });
|
|
435
|
-
|
|
525
|
+
this.#activeSends.set(fileId, { peer: pubkey, msgId: msg.id, lastMs: Date.now() });
|
|
526
|
+
// Same rule as a fresh send: a file that fits Express falls back
|
|
527
|
+
// there if the friend does not accept within the offer window.
|
|
528
|
+
const route = routeFileSend({ online: true, name: msg.file.name, size: data.length, expressAvailable: this.#node.canSendFileViaExpress() });
|
|
529
|
+
if (route.kind === "live" && route.offerWindow)
|
|
530
|
+
this.#startOfferWindow(fileId, pubkey, msg.id, msg.file.name);
|
|
531
|
+
this.#events.emit("event", { type: "chat", userid: pubkey, dir: "out" });
|
|
532
|
+
this.#logger.info(`delivering queued "${msg.file.name}" to ${pubkey.slice(0, 8)}` +
|
|
533
|
+
(backoff ? ` (attempt ${backoff.attempts + 1})` : ""));
|
|
436
534
|
}
|
|
437
535
|
}
|
|
438
536
|
catch (e) {
|
|
@@ -460,6 +558,17 @@ export class EmbeddedHost {
|
|
|
460
558
|
clearInterval(this.#sweepTimer);
|
|
461
559
|
this.#sweepTimer = null;
|
|
462
560
|
}
|
|
561
|
+
if (this.#stallTimer) {
|
|
562
|
+
clearInterval(this.#stallTimer);
|
|
563
|
+
this.#stallTimer = null;
|
|
564
|
+
}
|
|
565
|
+
for (const t of this.#offerWindows.values())
|
|
566
|
+
clearTimeout(t);
|
|
567
|
+
this.#offerWindows.clear();
|
|
568
|
+
this.#retryBackoff.clear();
|
|
569
|
+
// The store writes on a 1 s debounce; a stop inside that window lost the
|
|
570
|
+
// last change (a file's "sending" row, a just-sent message).
|
|
571
|
+
this.#messages.flush();
|
|
463
572
|
// Stop the peer FIRST, then release the lock. The reverse order would open
|
|
464
573
|
// a window where a daemon could start while our peer is still live.
|
|
465
574
|
await this.#node.stop();
|
|
@@ -752,6 +861,7 @@ export class EmbeddedHost {
|
|
|
752
861
|
for (const [fileId, s] of this.#activeSends) {
|
|
753
862
|
if (s.msgId !== id)
|
|
754
863
|
continue;
|
|
864
|
+
this.#endOfferWindow(fileId);
|
|
755
865
|
if (this.#node.cancelSend(s.peer, fileId))
|
|
756
866
|
cancelled++;
|
|
757
867
|
this.#activeSends.delete(fileId);
|
|
@@ -767,9 +877,12 @@ export class EmbeddedHost {
|
|
|
767
877
|
if (!existsSync(path))
|
|
768
878
|
continue;
|
|
769
879
|
const data = await readFile(path);
|
|
770
|
-
|
|
880
|
+
// The row's own name — the friend should not receive "retry-<id>".
|
|
881
|
+
const row = (this.#messages.history(req.peer)[req.peer] ?? []).find((m) => m.id === id);
|
|
882
|
+
const fileId = this.#node.sendFile(req.peer, new Uint8Array(data), row?.file?.name ?? `retry-${id}`);
|
|
771
883
|
if (fileId) {
|
|
772
|
-
this.#activeSends.set(fileId, { peer: req.peer, msgId: id });
|
|
884
|
+
this.#activeSends.set(fileId, { peer: req.peer, msgId: id, lastMs: Date.now() });
|
|
885
|
+
this.#retryBackoff.delete(id);
|
|
773
886
|
this.#messages.patchFile(req.peer, id, { status: "sending", sent: 0 });
|
|
774
887
|
retried++;
|
|
775
888
|
}
|
|
@@ -838,29 +951,56 @@ export class EmbeddedHost {
|
|
|
838
951
|
}
|
|
839
952
|
})();
|
|
840
953
|
}
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
954
|
+
// The row carries the SHA-256 of the bytes: iOS keys a file row as
|
|
955
|
+
// `ft-` + its first 16 hex chars, and so does Express re-delivery.
|
|
956
|
+
const sha256 = createHash("sha256").update(data).digest("hex");
|
|
957
|
+
const route = routeFileSend({
|
|
958
|
+
online: this.#node.isFriendOnline(userid),
|
|
959
|
+
name: safe,
|
|
960
|
+
size: data.length,
|
|
961
|
+
expressAvailable: this.#node.canSendFileViaExpress(),
|
|
962
|
+
});
|
|
963
|
+
if (route.kind === "refuse")
|
|
964
|
+
throw new Error(route.reason);
|
|
965
|
+
if (route.kind === "express" || route.kind === "outbox") {
|
|
966
|
+
// Offline friend. Either way the bytes are kept in outbox/<id> first:
|
|
967
|
+
// for Express until the post succeeded (a failed post leaves the row
|
|
968
|
+
// queued here), for the outbox until the friend is online.
|
|
969
|
+
const express = route.kind === "express";
|
|
970
|
+
const msg = this.#messages.appendFile(userid, "out", {
|
|
971
|
+
name: safe, size: data.length, status: express ? "sending" : "queued", sent: 0, sha256,
|
|
972
|
+
});
|
|
847
973
|
if (!msg)
|
|
848
974
|
throw new Error("Could not queue file");
|
|
849
975
|
await mkdir(this.outboxDir, { recursive: true });
|
|
850
976
|
await writeFile(resolve(this.outboxDir, msg.id), data);
|
|
851
977
|
this.#meta.ensure(userid);
|
|
852
978
|
this.#events.emit("event", { type: "chat", userid, dir: "out" });
|
|
853
|
-
|
|
979
|
+
if (!express) {
|
|
980
|
+
this.#logger.info(`"${safe}" (${data.length}B) waits in the outbox until ${userid.slice(0, 8)} is online`);
|
|
981
|
+
return { queued: true, name: safe, size: data.length };
|
|
982
|
+
}
|
|
983
|
+
// Non-blocking, like every send: the post is up to 5 MiB to Express.
|
|
984
|
+
void this.#parkOnExpress(userid, msg.id, data, safe, "friend offline");
|
|
985
|
+
return { offline: true, pending: true, name: safe, size: data.length };
|
|
854
986
|
}
|
|
855
987
|
// Everyone streams — a native friend's packets ride DNFT1 frames inside
|
|
856
988
|
// friend messages (see the note on the deleted native inline gate above).
|
|
857
989
|
const native = this.#node.isNativeFriend(userid);
|
|
858
|
-
const msg = this.#messages.appendFile(userid, "out", { name: safe, size: data.length, status: "sending", sent: 0 });
|
|
990
|
+
const msg = this.#messages.appendFile(userid, "out", { name: safe, size: data.length, status: "sending", sent: 0, sha256 });
|
|
859
991
|
if (!msg)
|
|
860
992
|
throw new Error("Could not create file message");
|
|
861
993
|
await mkdir(this.outboxDir, { recursive: true });
|
|
862
994
|
await writeFile(resolve(this.outboxDir, msg.id), data);
|
|
863
995
|
const fileId = this.#node.sendFile(userid, new Uint8Array(data), safe);
|
|
996
|
+
if (!fileId && route.offerWindow) {
|
|
997
|
+
// No transfer slot, but it fits Express: park it there, as the offer
|
|
998
|
+
// window would after 10 s anyway.
|
|
999
|
+
this.#meta.ensure(userid);
|
|
1000
|
+
this.#events.emit("event", { type: "chat", userid, dir: "out" });
|
|
1001
|
+
void this.#parkOnExpress(userid, msg.id, data, safe, "no free transfer slot");
|
|
1002
|
+
return { offline: true, pending: true, name: safe, size: data.length };
|
|
1003
|
+
}
|
|
864
1004
|
if (!fileId) {
|
|
865
1005
|
// No transfer slot. The inline fallback only helps a JS friend (their
|
|
866
1006
|
// text-ack makes it confirmable); to a native it is unconfirmable by
|
|
@@ -899,10 +1039,135 @@ export class EmbeddedHost {
|
|
|
899
1039
|
})();
|
|
900
1040
|
return { inline: true, name: safe, size: data.length, pending: true };
|
|
901
1041
|
}
|
|
902
|
-
this.#activeSends.set(fileId, { peer: userid, msgId: msg.id });
|
|
1042
|
+
this.#activeSends.set(fileId, { peer: userid, msgId: msg.id, lastMs: Date.now() });
|
|
1043
|
+
if (route.offerWindow)
|
|
1044
|
+
this.#startOfferWindow(fileId, userid, msg.id, safe);
|
|
903
1045
|
this.#meta.ensure(userid);
|
|
904
1046
|
this.#events.emit("event", { type: "chat", userid, dir: "out" });
|
|
905
1047
|
return { fileId, name: safe, size: data.length };
|
|
906
1048
|
}
|
|
1049
|
+
/** The SDK gave up on a live send: no answer to the offer, or no ack
|
|
1050
|
+
* progress, for 60 s (a half-open session: we see the friend online but
|
|
1051
|
+
* nothing gets through). Never a total-time limit — a slow transfer that
|
|
1052
|
+
* keeps acking runs as long as it needs. The bytes are still in
|
|
1053
|
+
* outbox/<id>: a file that fits Express goes there, anything else waits
|
|
1054
|
+
* "queued" and is offered again, backing off 15 s, 30 s, 1 min… up to
|
|
1055
|
+
* 5 min, and at once when the friend reconnects. The receiver resumes
|
|
1056
|
+
* from what it already holds (same fileId = same bytes). */
|
|
1057
|
+
async #liveDeliveryGaveUp(peer, msgId, reason) {
|
|
1058
|
+
const data = await readFile(resolve(this.outboxDir, msgId)).catch(() => undefined);
|
|
1059
|
+
const msg = (this.#messages.history(peer)[peer] ?? []).find((m) => m.id === msgId);
|
|
1060
|
+
const name = msg?.file?.name ?? msgId;
|
|
1061
|
+
const why = reason === "no-response" ? "no answer to the offer for 60 s" :
|
|
1062
|
+
reason === "timeout" ? "no progress for 60 s" :
|
|
1063
|
+
reason === "peer-offline" ? "their session went away" :
|
|
1064
|
+
reason === "stalled" ? `no progress for ${Math.round((this.#opts.liveStallMs ?? LIVE_STALL_MS) / 1000)} s` :
|
|
1065
|
+
`ended by the SDK: ${reason}`;
|
|
1066
|
+
if (!data) {
|
|
1067
|
+
this.#messages.patchFile(peer, msgId, { status: "failed" });
|
|
1068
|
+
this.#events.emit("event", { type: "chat", userid: peer, dir: "out" });
|
|
1069
|
+
this.#logger.warn(`live delivery of "${name}" to ${peer.slice(0, 8)} gave up (${why}) and its bytes are gone`);
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
const route = routeFileSend({ online: false, name, size: data.length, expressAvailable: this.#node.canSendFileViaExpress() });
|
|
1073
|
+
if (route.kind === "express") {
|
|
1074
|
+
this.#messages.patchFile(peer, msgId, { status: "sending", sent: 0 });
|
|
1075
|
+
this.#events.emit("event", { type: "chat", userid: peer, dir: "out" });
|
|
1076
|
+
if (await this.#parkOnExpress(peer, msgId, data, name, `live delivery gave up: ${why}`))
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
const prev = this.#retryBackoff.get(msgId);
|
|
1080
|
+
const attempts = (prev?.attempts ?? 0) + 1;
|
|
1081
|
+
const delay = Math.min(LIVE_RETRY_MAX_MS, (this.#opts.liveRetryBaseMs ?? LIVE_RETRY_BASE_MS) * 2 ** (attempts - 1));
|
|
1082
|
+
this.#retryBackoff.set(msgId, { peer, attempts, notBefore: Date.now() + delay });
|
|
1083
|
+
this.#messages.patchFile(peer, msgId, { status: "queued", sent: 0 });
|
|
1084
|
+
this.#events.emit("event", { type: "chat", userid: peer, dir: "out" });
|
|
1085
|
+
this.#logger.warn(`live delivery of "${name}" to ${peer.slice(0, 8)} gave up (${why}) — queued, next try in ${Math.round(delay / 1000)} s`);
|
|
1086
|
+
}
|
|
1087
|
+
/** Live sends with no progress for LIVE_STALL_MS: withdrawn and handled as a
|
|
1088
|
+
* give-up (#liveDeliveryGaveUp). Backstop for peer's own no-progress
|
|
1089
|
+
* give-up ("timeout"), which never fires in peer 0.1.176 — every stall
|
|
1090
|
+
* resets its clock — so a receiver frozen mid-transfer left the row
|
|
1091
|
+
* "sending" forever. 90 s, so peer's 60 s timer wins once it is fixed
|
|
1092
|
+
* (0.1.177). The offer phase counts from the offer; peer's working 60 s
|
|
1093
|
+
* "no-response" give-up normally ends it first. The receiver keeps its
|
|
1094
|
+
* .part (a KILL does not delete it), so the next offer resumes. */
|
|
1095
|
+
#giveUpStalledSends(now) {
|
|
1096
|
+
const stallMs = this.#opts.liveStallMs ?? LIVE_STALL_MS;
|
|
1097
|
+
for (const [fileId, s] of [...this.#activeSends]) {
|
|
1098
|
+
if (now - s.lastMs < stallMs)
|
|
1099
|
+
continue;
|
|
1100
|
+
// Forget it first, so our own KILL is not read as anything else.
|
|
1101
|
+
this.#activeSends.delete(fileId);
|
|
1102
|
+
this.#endOfferWindow(fileId);
|
|
1103
|
+
try {
|
|
1104
|
+
this.#node.cancelSend(s.peer, fileId);
|
|
1105
|
+
}
|
|
1106
|
+
catch { /* already gone */ }
|
|
1107
|
+
void this.#liveDeliveryGaveUp(s.peer, s.msgId, "stalled");
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
/** Post one offline file message to Express (peer >= 0.1.176). The row goes
|
|
1111
|
+
* "sent" + via "offline": stored on Express, theirs when they come online.
|
|
1112
|
+
* If Express refuses or cannot be reached, the bytes stay in outbox/<id>
|
|
1113
|
+
* and the row goes "queued": delivered live when the friend is next online
|
|
1114
|
+
* (#flushOutbox). Never re-flushes from here — a friend who is "online"
|
|
1115
|
+
* but not accepting would otherwise bounce between the two forever. */
|
|
1116
|
+
async #parkOnExpress(userid, msgId, data, name, why) {
|
|
1117
|
+
try {
|
|
1118
|
+
const { fileId } = await this.#node.sendFileViaExpress(userid, new Uint8Array(data), name);
|
|
1119
|
+
this.#messages.patchFile(userid, msgId, { status: "sent", sent: data.length });
|
|
1120
|
+
this.#messages.setFileVia(userid, msgId, "offline");
|
|
1121
|
+
void unlink(resolve(this.outboxDir, msgId)).catch(() => undefined);
|
|
1122
|
+
this.#logger.info(`"${name}" (${data.length}B) parked on Express for ${userid.slice(0, 8)} (${why}; ft-${fileId.slice(0, 16)})`);
|
|
1123
|
+
this.#events.emit("event", { type: "chat", userid, dir: "out" });
|
|
1124
|
+
return true;
|
|
1125
|
+
}
|
|
1126
|
+
catch (e) {
|
|
1127
|
+
this.#messages.patchFile(userid, msgId, { status: "queued", sent: 0 });
|
|
1128
|
+
this.#messages.setFileVia(userid, msgId, undefined);
|
|
1129
|
+
this.#logger.warn(`"${name}" could not go to Express (${e.message}) — it waits here until ${userid.slice(0, 8)} is online`);
|
|
1130
|
+
this.#events.emit("event", { type: "chat", userid, dir: "out" });
|
|
1131
|
+
return false;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
/** iOS `offerWindow`: a live offer of a file that fits Express gets
|
|
1135
|
+
* OFFER_WINDOW_MS to be accepted. */
|
|
1136
|
+
#startOfferWindow(fileId, peer, msgId, name) {
|
|
1137
|
+
this.#endOfferWindow(fileId);
|
|
1138
|
+
const t = setTimeout(() => void this.#offerWindowExpired(fileId, peer, msgId, name), this.#opts.offerWindowMs ?? OFFER_WINDOW_MS);
|
|
1139
|
+
t.unref?.();
|
|
1140
|
+
this.#offerWindows.set(fileId, t);
|
|
1141
|
+
}
|
|
1142
|
+
#endOfferWindow(fileId) {
|
|
1143
|
+
const t = this.#offerWindows.get(fileId);
|
|
1144
|
+
if (t)
|
|
1145
|
+
clearTimeout(t);
|
|
1146
|
+
this.#offerWindows.delete(fileId);
|
|
1147
|
+
}
|
|
1148
|
+
/** Not accepted in time: withdraw the offer (KILL) and park the file on
|
|
1149
|
+
* Express. The receiver keys both by the bytes' SHA-256, so a late ACCEPT
|
|
1150
|
+
* racing this still ends in one row on their side. */
|
|
1151
|
+
async #offerWindowExpired(fileId, peer, msgId, name) {
|
|
1152
|
+
this.#offerWindows.delete(fileId);
|
|
1153
|
+
if (!this.#activeSends.has(fileId))
|
|
1154
|
+
return; // finished or cancelled meanwhile
|
|
1155
|
+
// Forget it BEFORE cancelling, so our own KILL is not read as the user
|
|
1156
|
+
// cancelling the transfer.
|
|
1157
|
+
this.#activeSends.delete(fileId);
|
|
1158
|
+
try {
|
|
1159
|
+
this.#node.cancelSend(peer, fileId);
|
|
1160
|
+
}
|
|
1161
|
+
catch { /* already gone */ }
|
|
1162
|
+
const data = await readFile(resolve(this.outboxDir, msgId)).catch(() => undefined);
|
|
1163
|
+
if (!data) {
|
|
1164
|
+
this.#messages.patchFile(peer, msgId, { status: "failed" });
|
|
1165
|
+
this.#events.emit("event", { type: "chat", userid: peer, dir: "out" });
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
this.#logger.info(`"${name}" not accepted by ${peer.slice(0, 8)} within ${(this.#opts.offerWindowMs ?? OFFER_WINDOW_MS) / 1000} s — offer withdrawn, sending through Express`);
|
|
1169
|
+
this.#messages.patchFile(peer, msgId, { status: "sending", sent: 0 });
|
|
1170
|
+
await this.#parkOnExpress(peer, msgId, data, name, "offer not accepted in time");
|
|
1171
|
+
}
|
|
907
1172
|
}
|
|
908
1173
|
_a = EmbeddedHost;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** Files bigger than this are not queued for an offline friend — the bytes sit
|
|
2
|
+
* on disk until they reconnect, and an unbounded queue is how you fill a
|
|
3
|
+
* user's disk by accident. Live transfers have no such limit. */
|
|
4
|
+
export declare const OUTBOX_MAX_FILE_BYTES: number;
|
|
5
|
+
/** iOS `offerWindow`: how long a live offer may go unaccepted before a file
|
|
6
|
+
* that fits Express is withdrawn and parked there instead. */
|
|
7
|
+
export declare const OFFER_WINDOW_MS = 10000;
|
|
8
|
+
/** The exact size of the offline file message sendFileViaExpress would post
|
|
9
|
+
* for this name and size (the meta JSON is built the same way). */
|
|
10
|
+
export declare function expressMessageBytes(name: string, size: number): {
|
|
11
|
+
total: number;
|
|
12
|
+
meta: number;
|
|
13
|
+
};
|
|
14
|
+
/** True when one offline file message on Express can carry this file. */
|
|
15
|
+
export declare function fitsExpress(name: string, size: number): boolean;
|
|
16
|
+
export type FileRoute =
|
|
17
|
+
/** Live transfer; `offerWindow` = fall back to Express if not accepted in time. */
|
|
18
|
+
{
|
|
19
|
+
kind: "live";
|
|
20
|
+
offerWindow: boolean;
|
|
21
|
+
}
|
|
22
|
+
/** One offline file message on Express. */
|
|
23
|
+
| {
|
|
24
|
+
kind: "express";
|
|
25
|
+
}
|
|
26
|
+
/** Kept in the local outbox until the friend is online. */
|
|
27
|
+
| {
|
|
28
|
+
kind: "outbox";
|
|
29
|
+
}
|
|
30
|
+
/** Offline and over the outbox cap: refused up front. */
|
|
31
|
+
| {
|
|
32
|
+
kind: "refuse";
|
|
33
|
+
reason: string;
|
|
34
|
+
};
|
|
35
|
+
/** The routing table above. `expressAvailable` is false on a peer SDK without
|
|
36
|
+
* sendFileViaExpress or with no Express node: then an offline file of any
|
|
37
|
+
* size waits in the outbox, as it did before. */
|
|
38
|
+
export declare function routeFileSend(opts: {
|
|
39
|
+
online: boolean;
|
|
40
|
+
name: string;
|
|
41
|
+
size: number;
|
|
42
|
+
expressAvailable: boolean;
|
|
43
|
+
}): FileRoute;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Where an outgoing file goes: live, Express, or this computer's outbox.
|
|
2
|
+
//
|
|
3
|
+
// decent-hq TASK-2026-11-13-desktop-multifile-and-offline-files, part C.2,
|
|
4
|
+
// following iOS (1.8.37+, Elastos.NET.WebRTC.Swift.SDK docs/OFFLINE-FILE-MESSAGE.md,
|
|
5
|
+
// "Sender rules"):
|
|
6
|
+
//
|
|
7
|
+
// friend offline, fits Express → ONE offline file message on Express
|
|
8
|
+
// (peer >= 0.1.176 sendFileViaExpress); the
|
|
9
|
+
// row reads "offline" — stored, not yet theirs.
|
|
10
|
+
// friend offline, too big → the local outbox (25 MB cap, as before); the
|
|
11
|
+
// row says it waits on this computer until the
|
|
12
|
+
// friend is online. Over 25 MB: refused.
|
|
13
|
+
// friend online → live transfer. When it fits Express and the
|
|
14
|
+
// friend has not accepted within OFFER_WINDOW_MS
|
|
15
|
+
// (iOS `offerWindow`), the offer is withdrawn
|
|
16
|
+
// and the file goes to Express instead.
|
|
17
|
+
//
|
|
18
|
+
// "Fits Express" is the whole message: [u32 metaLen][meta JSON][bytes] ≤
|
|
19
|
+
// 5 242 880 bytes (Carrier's legacy bulk-message cap), meta ≤ 4096.
|
|
20
|
+
import { OFFLINE_FILE_MAX_MESSAGE_BYTES, OFFLINE_FILE_MAX_META_BYTES, contentTypeForFileName } from "@decentnetwork/peer";
|
|
21
|
+
/** Files bigger than this are not queued for an offline friend — the bytes sit
|
|
22
|
+
* on disk until they reconnect, and an unbounded queue is how you fill a
|
|
23
|
+
* user's disk by accident. Live transfers have no such limit. */
|
|
24
|
+
export const OUTBOX_MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
25
|
+
/** iOS `offerWindow`: how long a live offer may go unaccepted before a file
|
|
26
|
+
* that fits Express is withdrawn and parked there instead. */
|
|
27
|
+
export const OFFER_WINDOW_MS = 10_000;
|
|
28
|
+
/** The exact size of the offline file message sendFileViaExpress would post
|
|
29
|
+
* for this name and size (the meta JSON is built the same way). */
|
|
30
|
+
export function expressMessageBytes(name, size) {
|
|
31
|
+
const meta = Buffer.byteLength(JSON.stringify({ type: "file", filename: name, contentType: contentTypeForFileName(name), size }), "utf-8");
|
|
32
|
+
return { total: 4 + meta + size, meta };
|
|
33
|
+
}
|
|
34
|
+
/** True when one offline file message on Express can carry this file. */
|
|
35
|
+
export function fitsExpress(name, size) {
|
|
36
|
+
const { total, meta } = expressMessageBytes(name, size);
|
|
37
|
+
return total <= OFFLINE_FILE_MAX_MESSAGE_BYTES && meta <= OFFLINE_FILE_MAX_META_BYTES;
|
|
38
|
+
}
|
|
39
|
+
/** The routing table above. `expressAvailable` is false on a peer SDK without
|
|
40
|
+
* sendFileViaExpress or with no Express node: then an offline file of any
|
|
41
|
+
* size waits in the outbox, as it did before. */
|
|
42
|
+
export function routeFileSend(opts) {
|
|
43
|
+
const fits = opts.expressAvailable && fitsExpress(opts.name, opts.size);
|
|
44
|
+
if (opts.online)
|
|
45
|
+
return { kind: "live", offerWindow: fits };
|
|
46
|
+
if (fits)
|
|
47
|
+
return { kind: "express" };
|
|
48
|
+
if (opts.size <= OUTBOX_MAX_FILE_BYTES)
|
|
49
|
+
return { kind: "outbox" };
|
|
50
|
+
return {
|
|
51
|
+
kind: "refuse",
|
|
52
|
+
reason: `Peer is offline — queued files are limited to ${(OUTBOX_MAX_FILE_BYTES / 1024 / 1024) | 0} MB ` +
|
|
53
|
+
`(this is ${(opts.size / 1024 / 1024).toFixed(1)} MB). Send it once they're online.`,
|
|
54
|
+
};
|
|
55
|
+
}
|
package/dist/message-store.d.ts
CHANGED
|
@@ -80,6 +80,9 @@ export declare class MessageStore {
|
|
|
80
80
|
/** Record how an outgoing text travelled: "online" over a live session,
|
|
81
81
|
* "offline" posted to the express relay for the peer to collect. */
|
|
82
82
|
setVia(peer: string, id: string, via: "online" | "offline"): boolean;
|
|
83
|
+
/** The same for a FILE row: "offline" = parked on Express, "online" = a
|
|
84
|
+
* live transfer, undefined = not on the wire yet (waiting in the outbox). */
|
|
85
|
+
setFileVia(peer: string, id: string, via: "online" | "offline" | undefined): boolean;
|
|
83
86
|
/** Has this peer ever sent us anything? Used as proof-of-friendship for
|
|
84
87
|
* records that predate the SDK's acceptedAt bookkeeping — a message can
|
|
85
88
|
* only arrive over an established session. */
|
|
@@ -111,8 +114,10 @@ export declare class MessageStore {
|
|
|
111
114
|
}, origin?: ChatMessage["origin"]): ChatMessage | undefined;
|
|
112
115
|
/** Every message in a peer's thread (oldest first). Read-only use. */
|
|
113
116
|
thread(peer: string): readonly ChatMessage[];
|
|
114
|
-
/** True when this peer's thread already holds a file with these bytes
|
|
115
|
-
|
|
117
|
+
/** True when this peer's thread already holds a file with these bytes —
|
|
118
|
+
* in `dir` only, when given (a received file must not be dropped because
|
|
119
|
+
* we once SENT the same bytes). */
|
|
120
|
+
hasFileSha(peer: string, sha256: string, dir?: "in" | "out"): boolean;
|
|
116
121
|
/** Patch an existing file message's transfer fields (status / sent bytes).
|
|
117
122
|
* No-op if the id isn't found. Returns true if it patched. */
|
|
118
123
|
patchFile(peer: string, id: string, patch: {
|