bee-rs 1.0.1

Rust client for the Swarm Bee API. Functional parity with bee-js / bee-go.
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
//! Upload / download options. Mirrors bee-go's `pkg/api/options.go`.
//!
//! Option fields use [`Option<bool>`] to distinguish "unset" from
//! "explicitly false" — matching bee-go's `*bool` semantics. `None`
//! omits the header; `Some(false)` sends the literal string `"false"`.

use std::fmt;
use std::sync::Arc;

use crate::swarm::{BatchId, PublicKey, Reference};

/// Per-entry signal emitted by `upload_collection` /
/// `upload_collection_entries` when an [`UploadProgress`] callback is
/// configured. Mirrors bee-js `streamDirectory` `onUploadProgress`.
#[derive(Debug, Clone, Copy)]
pub struct UploadProgress<'a> {
    /// Relative path of the entry inside the collection.
    pub path: &'a str,
    /// Size of the entry in bytes.
    pub size: u64,
    /// 0-based index of the entry within the collection.
    pub index: usize,
    /// Total number of entries in the collection.
    pub total: usize,
}

/// Boxed callback invoked once per entry when uploading a collection.
pub type OnEntryFn = Arc<dyn for<'a> Fn(UploadProgress<'a>) + Send + Sync>;

/// Data redundancy level applied at upload time. Mirrors bee-js
/// `RedundancyLevel`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum RedundancyLevel {
    /// No redundancy.
    Off = 0,
    /// Medium redundancy.
    Medium = 1,
    /// Strong redundancy.
    Strong = 2,
    /// Insane redundancy.
    Insane = 3,
    /// Paranoid redundancy.
    Paranoid = 4,
}

impl RedundancyLevel {
    /// Numeric value used as the `Swarm-Redundancy-Level` header.
    pub fn as_u8(self) -> u8 {
        self as u8
    }
}

/// Chunk-prefetch policy used when downloading erasure-coded data.
/// Mirrors bee-js `RedundancyStrategy`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum RedundancyStrategy {
    /// No prefetch.
    None = 0,
    /// Data-only prefetch.
    Data = 1,
    /// Proximity-based prefetch.
    Proximity = 2,
    /// Race strategies.
    Race = 3,
}

impl RedundancyStrategy {
    /// Numeric value used as the `Swarm-Redundancy-Strategy` header.
    pub fn as_u8(self) -> u8 {
        self as u8
    }
}

/// Base set of options accepted by every upload endpoint. Mirrors
/// bee-js / bee-go `UploadOptions`.
#[derive(Clone, Debug, Default)]
pub struct UploadOptions {
    /// When `Some(true)`, instruct Bee to wrap the upload in an Access
    /// Control Trie (ACT). The history root is returned via
    /// `Swarm-Act-History-Address`.
    pub act: Option<bool>,
    /// Existing ACT history root for re-upload under the same access
    /// policy.
    pub act_history_address: Option<Reference>,
    /// Pin the uploaded data on the local Bee node.
    pub pin: Option<bool>,
    /// Encrypt chunks; the returned reference is 64 bytes (CAC ||
    /// encryption key).
    pub encrypt: Option<bool>,
    /// Existing tag UID to attach for sync tracking. `0` omits the
    /// header (matching bee-go's `uint32(0)` zero-value semantics).
    pub tag: u32,
    /// Toggle "Bee waits for full sync" (`Some(false)`) vs
    /// "Bee accepts and syncs in background" (`Some(true)`, the Bee
    /// default).
    pub deferred: Option<bool>,
}

/// `UploadOptions` plus a redundancy level. Mirrors bee-go
/// `RedundantUploadOptions`.
#[derive(Clone, Debug, Default)]
pub struct RedundantUploadOptions {
    /// Inherited base options.
    pub base: UploadOptions,
    /// Redundancy level (`Off` omits the header).
    pub redundancy_level: Option<RedundancyLevel>,
}

/// File-specific upload options for `POST /bzz`. Mirrors bee-go
/// `FileUploadOptions`.
#[derive(Clone, Debug, Default)]
pub struct FileUploadOptions {
    /// Inherited base options.
    pub base: UploadOptions,
    /// Explicit `Content-Length` (use when uploading from a stream of
    /// unknown length).
    pub size: Option<u64>,
    /// Explicit `Content-Type`.
    pub content_type: Option<String>,
    /// Redundancy level (`Off` omits the header).
    pub redundancy_level: Option<RedundancyLevel>,
}

/// Collection upload options for tar `POST /bzz`. Mirrors bee-go
/// `CollectionUploadOptions` and bee-js `streamDirectory` opts.
#[derive(Clone, Default)]
pub struct CollectionUploadOptions {
    /// Inherited base options.
    pub base: UploadOptions,
    /// Document served when the collection root is requested.
    pub index_document: Option<String>,
    /// Document served when a path inside the collection is missing.
    pub error_document: Option<String>,
    /// Redundancy level (`Off` omits the header).
    pub redundancy_level: Option<RedundancyLevel>,
    /// Per-entry progress callback. Invoked once per entry before the
    /// collection is packed and uploaded — useful for surfacing what
    /// is about to be sent without waiting for completion.
    pub on_entry: Option<OnEntryFn>,
}

impl CollectionUploadOptions {
    /// Set the per-entry progress callback. Builder convenience for
    /// callers that don't want to construct the [`OnEntryFn`] type
    /// themselves.
    pub fn with_on_entry<F>(mut self, f: F) -> Self
    where
        F: for<'a> Fn(UploadProgress<'a>) + Send + Sync + 'static,
    {
        self.on_entry = Some(Arc::new(f));
        self
    }
}

impl fmt::Debug for CollectionUploadOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CollectionUploadOptions")
            .field("base", &self.base)
            .field("index_document", &self.index_document)
            .field("error_document", &self.error_document)
            .field("redundancy_level", &self.redundancy_level)
            .field("on_entry", &self.on_entry.as_ref().map(|_| "<callback>"))
            .finish()
    }
}

/// Download options. All fields are optional; `Default::default()`
/// keeps Bee defaults. Mirrors bee-go `DownloadOptions`.
#[derive(Clone, Debug, Default)]
pub struct DownloadOptions {
    /// Erasure-coded prefetch policy.
    pub redundancy_strategy: Option<RedundancyStrategy>,
    /// Allow strategy fallback. Bee default is `true`.
    pub fallback: Option<bool>,
    /// Per-chunk retrieval timeout in milliseconds.
    pub timeout_ms: Option<u64>,
    /// ACT publisher public key.
    pub act_publisher: Option<PublicKey>,
    /// ACT history root for permission resolution.
    pub act_history_address: Option<Reference>,
    /// Unix timestamp at which to evaluate ACT permissions.
    pub act_timestamp: Option<i64>,
}

/// Postage stamp creation options. Mirrors bee-js / bee-go
/// `PostageBatchOptions`.
#[derive(Clone, Debug, Default)]
pub struct PostageBatchOptions {
    /// Human-readable label.
    pub label: Option<String>,
    /// Whether the batch is immutable.
    pub immutable: Option<bool>,
    /// Override the gas price (decimal string).
    pub gas_price: Option<String>,
    /// Override the gas limit (decimal string).
    pub gas_limit: Option<String>,
}

// ---- header preparation -------------------------------------------------

/// Header pairs: name + value. Used to push headers into a request
/// builder in the order they were added.
pub type HeaderPairs = Vec<(&'static str, String)>;

fn bool_str(b: bool) -> &'static str {
    if b { "true" } else { "false" }
}

fn push_upload_options(out: &mut HeaderPairs, opts: &UploadOptions) {
    if let Some(v) = opts.pin {
        out.push(("Swarm-Pin", bool_str(v).to_string()));
    }
    if let Some(v) = opts.encrypt {
        out.push(("Swarm-Encrypt", bool_str(v).to_string()));
    }
    if opts.tag > 0 {
        out.push(("Swarm-Tag", opts.tag.to_string()));
    }
    if let Some(v) = opts.deferred {
        out.push(("Swarm-Deferred-Upload", bool_str(v).to_string()));
    }
    if let Some(v) = opts.act {
        out.push(("Swarm-Act", bool_str(v).to_string()));
    }
    if let Some(ref r) = opts.act_history_address {
        out.push(("Swarm-Act-History-Address", r.to_hex()));
    }
}

/// Build the header set for a base upload. The batch is required.
pub fn prepare_upload_headers(batch_id: &BatchId, opts: Option<&UploadOptions>) -> HeaderPairs {
    let mut out = vec![("Swarm-Postage-Batch-Id", batch_id.to_hex())];
    if let Some(o) = opts {
        push_upload_options(&mut out, o);
    }
    out
}

/// Build the header set for a redundant upload.
pub fn prepare_redundant_upload_headers(
    batch_id: &BatchId,
    opts: Option<&RedundantUploadOptions>,
) -> HeaderPairs {
    match opts {
        None => prepare_upload_headers(batch_id, None),
        Some(o) => {
            let mut out = prepare_upload_headers(batch_id, Some(&o.base));
            if let Some(level) = o.redundancy_level {
                if !matches!(level, RedundancyLevel::Off) {
                    out.push(("Swarm-Redundancy-Level", level.as_u8().to_string()));
                }
            }
            out
        }
    }
}

/// Build the header set for a `POST /bzz` file upload.
pub fn prepare_file_upload_headers(
    batch_id: &BatchId,
    opts: Option<&FileUploadOptions>,
) -> HeaderPairs {
    match opts {
        None => prepare_upload_headers(batch_id, None),
        Some(o) => {
            let mut out = prepare_upload_headers(batch_id, Some(&o.base));
            if let Some(size) = o.size {
                out.push(("Content-Length", size.to_string()));
            }
            if let Some(ref ct) = o.content_type {
                out.push(("Content-Type", ct.clone()));
            }
            if let Some(level) = o.redundancy_level {
                if !matches!(level, RedundancyLevel::Off) {
                    out.push(("Swarm-Redundancy-Level", level.as_u8().to_string()));
                }
            }
            out
        }
    }
}

/// Build the header set for a tar `POST /bzz` collection upload.
pub fn prepare_collection_upload_headers(
    batch_id: &BatchId,
    opts: Option<&CollectionUploadOptions>,
) -> HeaderPairs {
    match opts {
        None => prepare_upload_headers(batch_id, None),
        Some(o) => {
            let mut out = prepare_upload_headers(batch_id, Some(&o.base));
            if let Some(ref idx) = o.index_document {
                out.push(("Swarm-Index-Document", idx.clone()));
            }
            if let Some(ref err) = o.error_document {
                out.push(("Swarm-Error-Document", err.clone()));
            }
            if let Some(level) = o.redundancy_level {
                if !matches!(level, RedundancyLevel::Off) {
                    out.push(("Swarm-Redundancy-Level", level.as_u8().to_string()));
                }
            }
            out
        }
    }
}

/// Build the header set for a download. Setting any of `act_publisher`
/// / `act_history_address` / `act_timestamp` implicitly turns
/// `Swarm-Act` on.
pub fn prepare_download_headers(opts: Option<&DownloadOptions>) -> HeaderPairs {
    let mut out = HeaderPairs::new();
    let Some(o) = opts else { return out };

    if let Some(s) = o.redundancy_strategy {
        out.push(("Swarm-Redundancy-Strategy", s.as_u8().to_string()));
    }
    if let Some(v) = o.fallback {
        out.push(("Swarm-Redundancy-Fallback-Mode", bool_str(v).to_string()));
    }
    if let Some(ms) = o.timeout_ms {
        if ms > 0 {
            out.push(("Swarm-Chunk-Retrieval-Timeout", ms.to_string()));
        }
    }
    let mut act = false;
    if let Some(ref pk) = o.act_publisher {
        if let Ok(hex) = pk.compressed_hex() {
            out.push(("Swarm-Act-Publisher", hex));
            act = true;
        }
    }
    if let Some(ref r) = o.act_history_address {
        out.push(("Swarm-Act-History-Address", r.to_hex()));
        act = true;
    }
    if let Some(ts) = o.act_timestamp {
        if ts > 0 {
            out.push(("Swarm-Act-Timestamp", ts.to_string()));
            act = true;
        }
    }
    if act {
        out.push(("Swarm-Act", "true".to_string()));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn batch() -> BatchId {
        BatchId::new(&[0xab; 32]).unwrap()
    }

    fn header<'a>(h: &'a [(&'static str, String)], name: &str) -> Option<&'a str> {
        h.iter().find(|(k, _)| *k == name).map(|(_, v)| v.as_str())
    }

    #[test]
    fn upload_headers_omit_unset_fields() {
        let h = prepare_upload_headers(&batch(), None);
        assert_eq!(
            header(&h, "Swarm-Postage-Batch-Id"),
            Some("ab".repeat(32).as_str())
        );
        assert!(header(&h, "Swarm-Pin").is_none());
        assert!(header(&h, "Swarm-Encrypt").is_none());
    }

    #[test]
    fn upload_headers_distinguish_none_from_some_false() {
        let opts = UploadOptions {
            pin: Some(false),
            ..Default::default()
        };
        let h = prepare_upload_headers(&batch(), Some(&opts));
        assert_eq!(header(&h, "Swarm-Pin"), Some("false"));
    }

    #[test]
    fn redundancy_level_off_is_omitted() {
        let opts = RedundantUploadOptions {
            redundancy_level: Some(RedundancyLevel::Off),
            ..Default::default()
        };
        let h = prepare_redundant_upload_headers(&batch(), Some(&opts));
        assert!(header(&h, "Swarm-Redundancy-Level").is_none());
    }

    #[test]
    fn redundancy_level_medium_emits_header() {
        let opts = RedundantUploadOptions {
            redundancy_level: Some(RedundancyLevel::Medium),
            ..Default::default()
        };
        let h = prepare_redundant_upload_headers(&batch(), Some(&opts));
        assert_eq!(header(&h, "Swarm-Redundancy-Level"), Some("1"));
    }

    #[test]
    fn collection_upload_uses_swarm_index_document_header() {
        let opts = CollectionUploadOptions {
            index_document: Some("index.html".into()),
            ..Default::default()
        };
        let h = prepare_collection_upload_headers(&batch(), Some(&opts));
        assert_eq!(header(&h, "Swarm-Index-Document"), Some("index.html"));
    }

    #[test]
    fn download_act_implies_swarm_act_true() {
        let opts = DownloadOptions {
            act_history_address: Some(Reference::from_hex(&"00".repeat(32)).unwrap()),
            ..Default::default()
        };
        let h = prepare_download_headers(Some(&opts));
        assert_eq!(header(&h, "Swarm-Act"), Some("true"));
    }

    #[test]
    fn download_no_options_no_headers() {
        assert!(prepare_download_headers(None).is_empty());
        assert!(prepare_download_headers(Some(&DownloadOptions::default())).is_empty());
    }
}