zblob 0.3.0

Resumable verified-streaming blob & directory transfer over Zenoh (BLAKE3/bao, range resume, content-addressed dedup)
Documentation
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
//! One-to-many fanout tier (optional `fanout` feature).
//!
//! The Tier-1 queryable model degrades to N independent transfers when one
//! artifact must reach many nodes at once (a config rollout, a firmware
//! push). This tier publishes the blob **once** as a sample stream on
//! `<prefix>/<id>/fanout` through a `zenoh-ext` `AdvancedPublisher`:
//!
//! - the publisher **caches** every frame, so late joiners replay history;
//! - **sample-miss detection** + heartbeat let subscribers recover losses;
//! - every slice frame is still a self-verifying bao slice, so each receiver
//!   verifies against the manifest root exactly like a Tier-1 download.
//!
//! The cache holds the entire encoded blob in publisher memory for the
//! handle's lifetime — this tier is for rollout-sized artifacts, not
//! arbitrarily large blobs.

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tokio::io::{AsyncSeekExt, AsyncWriteExt, SeekFrom};
use zenoh::qos::{CongestionControl, Priority, Reliability};
use zenoh_ext::{
    AdvancedPublisherBuilderExt, AdvancedSubscriberBuilderExt, CacheConfig, HistoryConfig,
    MissDetectionConfig, RecoveryConfig,
};

use crate::cancel::CancelToken;
use crate::chunk::TransferChunks;
use crate::client::Overwrite;
use crate::error::{BlobError, Result};
use crate::hash::Hash;
use crate::id::BlobId;
use crate::manifest::{BlobSpec, Manifest};
use crate::obs::{TransferStats, zdebug};
use crate::prefix::{QueryPrefix, ServePrefix};
use crate::progress::{Progress, ProgressSink};
use crate::verify;

/// Key the fanout stream of blob `id` is published on.
pub fn fanout_key(prefix: &str, id: &str) -> String {
    format!("{prefix}/{id}/fanout")
}

/// One sample of the fanout stream: a version-first struct, like every other
/// control message in the crate.
///
/// It used to be a bare `(u16, FanoutFrame)` tuple with no encoding tag, which
/// made this the only part of the crate breaking the crate's own wire rules —
/// and left the receiver relying on decode failure to reject foreign samples.
#[derive(Serialize, Deserialize)]
struct FanoutMessage {
    /// Wire schema version (first field; postcard is positional).
    version: u16,
    /// The frame itself.
    frame: FanoutFrame,
}

/// The payload of one fanout sample.
///
/// **postcard is positional, so this enum's variants are identified by
/// order.** Adding one anywhere but the end, or reordering, is a silent wire
/// break that no version field would catch — the decode would succeed and mean
/// something else. Append only, and bump `WIRE_VERSION` when you do.
#[derive(Serialize, Deserialize)]
enum FanoutFrame {
    /// Frame 0: the manifest.
    Manifest(Manifest),
    /// A bao slice for one transfer chunk.
    Slice {
        /// Transfer chunk index.
        index: u32,
        /// Bao slice (self-verifying against the manifest root).
        bao: Vec<u8>,
    },
}

/// Fanout tuning.
#[derive(Debug, Clone)]
pub struct FanoutConfig {
    /// Publisher heartbeat period for sample-miss detection (default 500 ms).
    pub heartbeat: Duration,
    /// Receiver-side stall timeout: give up if no *progress* is made for this
    /// long (default 30 s).
    ///
    /// Progress, not traffic. Bounding the wait for a sample instead would let
    /// a publisher streaming frames a receiver rejects — junk, replays,
    /// tampered slices — reset the timer forever, and a fanout receiver has no
    /// second responder to fall back on.
    pub stall_timeout: Duration,
    /// Receiver-side policy when `dest` already exists (default
    /// [`Overwrite::Refuse`], matching `download_to`).
    pub overwrite: Overwrite,
    /// Bytes of **unverified** pre-manifest frames a receiver will buffer
    /// while waiting for the manifest (default 16 MiB).
    ///
    /// A receiver that joins mid-stream sees slices before the manifest that
    /// would let it verify them, so it holds them. That buffer is filled by an
    /// unauthenticated publisher with data nothing has checked yet, and the
    /// manifest need never arrive — so it is the one number here that is
    /// purely a receiver-side defence, and 256 MiB (the old value) is far more
    /// than a defence should cost. Frames beyond the cap are dropped and
    /// recovered from the publisher's replay.
    pub max_early_bytes: usize,
    /// Largest blob a receiver will accept from a fanout manifest
    /// (default 1 TiB), matching `BlobClientBuilder::max_blob_size`.
    ///
    /// Was hard-coded, so a receiver could not decline an implausible one.
    pub max_blob_size: u64,
    /// Slice samples the publisher retains for late joiners (default 4096).
    ///
    /// The cache is what makes a late joiner work, so it cannot be zero — but
    /// it used to be "every slice of the blob", which pins the whole blob plus
    /// its outboard in the publisher's memory for as long as the handle lives.
    /// On the embedded producers this fleet has, that is the wrong default.
    /// A joiner that arrives after eviction re-requests what it missed.
    pub cache_samples: usize,
}

impl Default for FanoutConfig {
    fn default() -> Self {
        FanoutConfig {
            heartbeat: Duration::from_millis(500),
            stall_timeout: Duration::from_secs(30),
            overwrite: Overwrite::default(),
            max_early_bytes: 16 * 1024 * 1024,
            max_blob_size: 1 << 40,
            cache_samples: 4096,
        }
    }
}

/// How many pre-manifest slice frames a receiver will buffer while waiting for
/// the manifest frame; the byte cap is
/// [`FanoutConfig::max_early_bytes`]. Frames beyond either cap are dropped;
/// heartbeat recovery re-delivers samples the *transport* missed but not ones
/// the application discarded, so a receiver that joins mid-stream may need the
/// publisher's cache replay (which the initial history query performs) to fill
/// what it dropped here.
const EARLY_SLICE_MAX_FRAMES: usize = 512;

/// Keeps a fanout publication (and its replay cache) alive.
#[derive(Debug)]
pub struct FanoutHandle {
    stop: Arc<tokio::sync::Notify>,
    join: tokio::task::JoinHandle<Result<()>>,
}

impl FanoutHandle {
    /// Stop serving the cache and release its memory.
    pub async fn shutdown(self) -> Result<()> {
        self.stop.notify_one();
        self.join.await.map_err(BlobError::Task)?
    }
}

/// Fan out the file at `path` under `spec`: hash it, publish the manifest and
/// every bao slice once (cached for late joiners), and keep serving until the
/// returned handle is shut down. Returns the manifest — distribute
/// `(id, root)` so receivers can pin.
pub async fn fanout_file(
    session: &zenoh::Session,
    prefix: &ServePrefix,
    spec: BlobSpec,
    path: impl Into<PathBuf>,
    cfg: FanoutConfig,
) -> Result<(Manifest, FanoutHandle)> {
    let path = path.into();
    let hash_path = path.clone();
    let (outboard, total_len) =
        tokio::task::spawn_blocking(move || -> std::io::Result<(verify::MemOutboard, u64)> {
            let file = std::fs::File::open(&hash_path)?;
            let total_len = file.metadata()?.len();
            Ok((verify::compute_outboard(file)?, total_len))
        })
        .await??;
    let outboard = Arc::new(outboard);
    let chunks = TransferChunks::new(spec.chunk_size, total_len)?;
    let count = chunks.count();
    let manifest = Manifest {
        version: crate::wire::WIRE_VERSION,
        id: BlobId::new(spec.id.clone())?,
        filename: spec.filename,
        total_len,
        chunk_size: spec.chunk_size,
        root: Hash::from(outboard.root),
        created_ms: spec.created_ms,
        // A publisher has no per-query limits to advertise: fanout is a
        // publication, not a query surface.
        ext: crate::wire::Ext::new(),
    };
    manifest.validate(u64::MAX)?;

    let stop = Arc::new(tokio::sync::Notify::new());
    let stop2 = stop.clone();
    let key = fanout_key(prefix.as_str(), &manifest.id);
    let task_manifest = manifest.clone();
    let session = session.clone();
    let join = tokio::spawn(async move {
        let publisher = session
            .declare_publisher(key)
            // Publications default to CongestionControl::Drop — for bulk
            // fanout that would shed slices under local backpressure and
            // leave subscribers to limp along on recovery. Block instead
            // (reliable delivery is the point of this tier).
            .congestion_control(CongestionControl::Block)
            .reliability(Reliability::Reliable)
            // Bulk rollout yields to telemetry on shared links (see
            // `BlobClientBuilder::priority`).
            .priority(Priority::DataLow)
            // Bounded: retaining every slice would pin the whole blob in the
            // publisher's memory for the handle's lifetime.
            .cache(
                CacheConfig::default()
                    .max_samples(cfg.cache_samples.max(1).min(count as usize + 1)),
            )
            .sample_miss_detection(MissDetectionConfig::default().heartbeat(cfg.heartbeat))
            // Liveliness token: lets subscribers' `detect_late_publishers`
            // notice this publisher (re)appearing and re-query its history.
            .publisher_detection()
            .await
            .map_err(BlobError::zenoh)?;

        publisher
            .put(crate::wire::encode(&FanoutMessage {
                version: crate::wire::WIRE_VERSION,
                frame: FanoutFrame::Manifest(task_manifest.clone()),
            })?)
            .encoding(&crate::wire::ENC_FANOUT)
            .await
            .map_err(BlobError::zenoh)?;

        let mut reader = tokio::task::spawn_blocking(move || std::fs::File::open(&path)).await??;
        for index in 0..count {
            let ob = outboard.clone();
            let byte_range = chunks.byte_range(index);
            let (r, slice) = tokio::task::spawn_blocking(
                move || -> (std::fs::File, std::io::Result<Vec<u8>>) {
                    let slice =
                        verify::encode_slice(&reader, &*ob, verify::chunk_range(byte_range));
                    (reader, slice)
                },
            )
            .await?;
            reader = r;
            publisher
                .put(crate::wire::encode(&FanoutMessage {
                    version: crate::wire::WIRE_VERSION,
                    frame: FanoutFrame::Slice { index, bao: slice? },
                })?)
                .encoding(&crate::wire::ENC_FANOUT)
                .await
                .map_err(BlobError::zenoh)?;
        }
        zdebug!(id = %task_manifest.id, chunks = count, "fanout published; serving cache");

        // All frames are in the cache; keep the publisher (and thus replay +
        // heartbeat) alive until shutdown.
        stop2.notified().await;
        Ok(())
    });

    Ok((manifest, FanoutHandle { stop, join }))
}

/// Receive a fanned-out blob into `dest` (via `<dest>.part`, atomically
/// renamed on completion, honoring [`FanoutConfig::overwrite`]), verifying
/// every slice against the manifest root — pin it by passing `expected_root`.
/// Works for subscribers that join *after* publication (history replay) and
/// across losses (recovery + heartbeat). Slices arriving before the manifest
/// frame are buffered (bounded); unacceptable manifest frames from hostile
/// co-publishers are skipped, not fatal.
///
/// Unlike `download_to` there is **no resume**: on error or cancellation the
/// partial is removed and a retry starts over (the publisher's cache replay
/// makes that cheap).
#[allow(clippy::too_many_arguments)] // transfer surface mirrors download_to
pub async fn receive_fanout(
    session: &zenoh::Session,
    prefix: &QueryPrefix,
    id: &str,
    expected_root: Option<Hash>,
    dest: &Path,
    sink: &dyn ProgressSink,
    cancel: &CancelToken,
    cfg: FanoutConfig,
) -> Result<TransferStats> {
    let started_at = tokio::time::Instant::now();

    // Refuse before receiving anything, as `download_to` does. Checking after
    // the stream had been consumed spent the whole transfer on a request that
    // was then refused — and, worse, the error path below deletes the `.part`,
    // which contradicts what `Overwrite::Refuse` promises ("nothing is lost").
    if cfg.overwrite == Overwrite::Refuse && tokio::fs::try_exists(dest).await? {
        return Err(BlobError::DestinationExists(dest.to_path_buf()));
    }

    let subscriber = session
        .declare_subscriber(fanout_key(prefix.as_str(), id))
        // The declare-time history query replays the publisher's whole cache
        // (no depth limit) — this is what makes late joiners work; the
        // default 10 s query timeout is too tight for a large replay.
        .history(HistoryConfig::default().detect_late_publishers())
        .recovery(RecoveryConfig::default().heartbeat())
        .query_timeout(cfg.stall_timeout)
        .await
        .map_err(BlobError::zenoh)?;

    // Phase A: acquire an acceptable manifest, buffering early slices.
    let mut early: Vec<(u32, Vec<u8>)> = Vec::new();
    let mut early_bytes = 0usize;
    let mut deferred_reject: Option<BlobError> = None;
    // `stall_timeout` bounds the wait for *progress*, not the wait for a
    // sample. Applying it only to `recv` let a publisher that streamed junk
    // reset the timer on every frame and hold a receiver open indefinitely —
    // and this is the one tier with no other exit, since there is no second
    // responder to fall back on. Found by the adversarial test below, which
    // hung rather than failing.
    let last_progress = tokio::time::Instant::now();
    let (m, chunks, root) = loop {
        if last_progress.elapsed() > cfg.stall_timeout {
            return Err(deferred_reject.unwrap_or(BlobError::Incomplete {
                received: 0,
                total: 0,
            }));
        }
        if cancel.is_cancelled() {
            sink.emit(Progress::Cancelled {
                received: 0,
                total: 0,
            });
            return Err(BlobError::Cancelled {
                received: 0,
                total: 0,
            });
        }
        // Watch the token *while* waiting: a cancel must not have to outlast
        // `stall_timeout` (see `cancel.rs`).
        let waited = cancel
            .until_cancelled(tokio::time::timeout(
                cfg.stall_timeout,
                subscriber.recv_async(),
            ))
            .await;
        let sample = match waited {
            Some(Ok(Ok(sample))) => sample,
            None => {
                sink.emit(Progress::Cancelled {
                    received: 0,
                    total: 0,
                });
                return Err(BlobError::Cancelled {
                    received: 0,
                    total: 0,
                });
            }
            _ => {
                return Err(deferred_reject.unwrap_or(BlobError::Incomplete {
                    received: 0,
                    total: 0,
                }));
            }
        };
        // Filter on the encoding tag *before* decoding, like every other
        // receive path in the crate. Relying on decode failure to reject a
        // foreign sample is the "opaque error deep in a transfer" failure mode
        // v2 removed everywhere else — and this was the one place it survived.
        if !crate::wire::ENC_FANOUT.matches(sample.encoding()) {
            continue;
        }
        let Ok(msg) = crate::wire::decode::<FanoutMessage>(&sample.payload().to_bytes()) else {
            continue;
        };
        if msg.version != crate::wire::WIRE_VERSION {
            continue;
        }
        match msg.frame {
            FanoutFrame::Manifest(m) => {
                let verdict = m
                    .validate(cfg.max_blob_size)
                    .and_then(|()| {
                        if m.id != id {
                            return Err(BlobError::MalformedMessage(format!(
                                "fanout manifest id {:?} does not match {id:?}",
                                m.id
                            )));
                        }
                        if let Some(expected) = expected_root
                            && m.root != expected
                        {
                            return Err(BlobError::RootMismatch {
                                expected,
                                actual: m.root,
                            });
                        }
                        // An empty blob carries no slices, so nothing later
                        // proves the root; check it here or a publisher could
                        // serve "verified" emptiness under any claimed root.
                        if m.total_len == 0 && m.root != Hash::of(b"") {
                            return Err(BlobError::RootMismatch {
                                expected: Hash::of(b""),
                                actual: m.root,
                            });
                        }
                        Ok(())
                    })
                    .and_then(|()| m.chunks());
                match verdict {
                    Ok(chunks) => {
                        let root: blake3::Hash = m.root.into();
                        break (m, chunks, root);
                    }
                    Err(e) => {
                        deferred_reject.get_or_insert(e);
                        continue; // a hostile co-publisher must not be fatal
                    }
                }
            }
            FanoutFrame::Slice { index, bao } => {
                if early.len() < EARLY_SLICE_MAX_FRAMES
                    && early_bytes + bao.len() <= cfg.max_early_bytes
                {
                    early_bytes += bao.len();
                    early.push((index, bao));
                }
            }
        }
    };

    let count = chunks.count();
    sink.emit(Progress::Started {
        total_len: m.total_len,
        chunk_count: count,
    });
    if let Some(parent) = dest.parent()
        && !parent.as_os_str().is_empty()
    {
        tokio::fs::create_dir_all(parent).await?;
    }
    let part = {
        let mut p = dest.as_os_str().to_os_string();
        p.push(".part");
        PathBuf::from(p)
    };
    {
        let f = tokio::fs::File::create(&part).await?;
        f.set_len(m.total_len).await?;
    }
    let mut file = tokio::fs::OpenOptions::new()
        .write(true)
        .open(&part)
        .await?;
    let mut present: Vec<bool> = vec![false; count as usize];
    let mut received = 0u32;
    let mut stats = TransferStats::default();

    // Phase B: drain the early buffer, then the live/replayed stream. Any
    // error or cancellation removes the partial (fanout has no resume).
    let result: Result<()> = async {
        for (index, bao) in early.drain(..) {
            apply_slice(
                &m,
                &chunks,
                &root,
                &mut file,
                &mut present,
                &mut received,
                &mut stats,
                sink,
                index,
                &bao,
            )
            .await?;
        }
        let mut last_progress = tokio::time::Instant::now();
        let mut progressed = received;
        while received < count {
            if received > progressed {
                progressed = received;
                last_progress = tokio::time::Instant::now();
            } else if last_progress.elapsed() > cfg.stall_timeout {
                // No *progress* within the budget — see phase A.
                return Err(BlobError::Incomplete {
                    received,
                    total: count,
                });
            }
            if cancel.is_cancelled() {
                sink.emit(Progress::Cancelled {
                    received,
                    total: count,
                });
                return Err(BlobError::Cancelled {
                    received,
                    total: count,
                });
            }
            let waited = cancel
                .until_cancelled(tokio::time::timeout(
                    cfg.stall_timeout,
                    subscriber.recv_async(),
                ))
                .await;
            let sample = match waited {
                Some(Ok(Ok(sample))) => sample,
                None => {
                    sink.emit(Progress::Cancelled {
                        received,
                        total: count,
                    });
                    return Err(BlobError::Cancelled {
                        received,
                        total: count,
                    });
                }
                _ => {
                    return Err(BlobError::Incomplete {
                        received,
                        total: count,
                    });
                }
            };
            // Same rule as phase A: filter on the encoding tag *before*
            // decoding. Phase B used to skip this, so a co-publisher whose
            // frames the front door would reject could inject them once the
            // manifest was through — the bao proof still protected the bytes,
            // but a foreign sample must be rejected for what it is.
            if !crate::wire::ENC_FANOUT.matches(sample.encoding()) {
                continue;
            }
            let Ok(msg) = crate::wire::decode::<FanoutMessage>(&sample.payload().to_bytes()) else {
                continue;
            };
            if msg.version != crate::wire::WIRE_VERSION {
                continue;
            }
            if let FanoutFrame::Slice { index, bao } = msg.frame {
                apply_slice(
                    &m,
                    &chunks,
                    &root,
                    &mut file,
                    &mut present,
                    &mut received,
                    &mut stats,
                    sink,
                    index,
                    &bao,
                )
                .await?;
            }
        }
        file.sync_data().await?;
        Ok(())
    }
    .await;
    drop(file);
    if let Err(e) = result {
        let _ = tokio::fs::remove_file(&part).await;
        return Err(e);
    }
    // A destination that appeared while we were receiving: the TOCTOU
    // backstop for the check at the top. Returning here — after the removal
    // above, not through it — *keeps* the finished `.part`, which is exactly
    // what `Overwrite::Refuse` documents ("nothing is lost").
    if cfg.overwrite == Overwrite::Refuse && tokio::fs::try_exists(dest).await? {
        return Err(BlobError::DestinationExists(dest.to_path_buf()));
    }
    tokio::fs::rename(&part, dest).await?;
    sink.emit(Progress::Completed {
        path: dest.to_path_buf(),
    });
    stats.elapsed = started_at.elapsed();
    Ok(stats)
}

/// Verify one slice frame against the root and write its leaves; duplicates
/// and out-of-range indices are ignored, tampered frames counted + dropped.
#[allow(clippy::too_many_arguments)]
async fn apply_slice(
    m: &Manifest,
    chunks: &TransferChunks,
    root: &blake3::Hash,
    file: &mut tokio::fs::File,
    present: &mut [bool],
    received: &mut u32,
    stats: &mut TransferStats,
    sink: &dyn ProgressSink,
    index: u32,
    bao: &[u8],
) -> Result<()> {
    let count = chunks.count();
    if index >= count || present[index as usize] {
        return Ok(());
    }
    let mut leaves: Vec<(u64, Vec<u8>)> = Vec::new();
    let decoded = verify::decode_slice(
        root,
        m.total_len,
        verify::chunk_range(chunks.byte_range(index)),
        bao,
        |off, data| {
            leaves.push((off, data.to_vec()));
            Ok(())
        },
    );
    if decoded.is_err() {
        stats.rejected += 1;
        return Ok(());
    }
    for (off, data) in leaves {
        file.seek(SeekFrom::Start(off)).await?;
        file.write_all(&data).await?;
    }
    present[index as usize] = true;
    *received += 1;
    stats.chunks_fetched += 1;
    stats.bytes_fetched += chunks.len_of(index) as u64;
    sink.emit(Progress::Chunk {
        index,
        received: *received,
        total: count,
        bytes_received: stats.bytes_fetched,
    });
    Ok(())
}