Skip to main content

radicle_artifact_core/
protocol.rs

1//! Wire protocol for the rad-artifact node control socket.
2//!
3//! One request per Unix-socket connection, each command a single line of
4//! JSON terminated by `\n`. Most commands are one-shot: the client writes
5//! one [`Command`] and reads one [`CommandResult<T>`]. The streaming
6//! commands ([`Command::Fetch`], [`Command::Download`], [`Command::Export`])
7//! instead emit a sequence of [`StreamEvent`] frames — zero or more
8//! `progress`, then one
9//! terminal `okay`/`error` whose tags match [`CommandResult`].
10//!
11//! The schema is additive-friendly on the wire (an unknown command tag
12//! is an error; unknown struct fields are ignored, new variants are new
13//! tags), but the Rust types are plain —
14//! the node crate constructs and exhaustively matches them, and all
15//! crates in this workspace version in lockstep.
16
17use std::path::PathBuf;
18
19use radicle::git::Oid;
20use radicle::identity::RepoId;
21use serde::{Deserialize, Serialize};
22use url::Url;
23
24use crate::cid::{ArtifactKind, Cid};
25use crate::keys::EndpointId;
26
27/// How imported bytes are placed in the store.
28///
29/// A serde-friendly, project-stable representation suitable for the wire
30/// protocol; the node maps it onto `iroh_blobs::api::blobs::ImportMode`.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "camelCase")]
33pub enum ImportMode {
34    /// Copy bytes into the store. The source file can be moved or
35    /// deleted afterwards without breaking seeding. Default for the
36    /// node.
37    Copy,
38    /// Reference the source file in place. No bytes are copied. The
39    /// caller is responsible for keeping the source path stable for as
40    /// long as they want to seed the artifact; if the file is moved or
41    /// deleted, fetches will fail.
42    Reference,
43}
44
45/// A control-socket request.
46///
47/// Serialized as JSON with an internal `"command"` tag, camelCase
48/// variant names. Unit variants (`Status`, `Shutdown`) serialize to
49/// `{"command":"status"}`.
50#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
51#[serde(tag = "command", rename_all = "camelCase")]
52pub enum Command {
53    /// Cheap liveness probe: the node replies `{"okay":null}` and does no
54    /// work. Used to tell a live owner from a stale socket file. Distinct
55    /// from any network-level reachability check against a peer endpoint.
56    Alive,
57    /// Report node status.
58    Status,
59    /// Import bytes from `path`, verify against `cid`, register the
60    /// `seeded/{rid}/{release}/{cid}` tag.
61    Seed {
62        /// Repository the artifact belongs to.
63        rid: RepoId,
64        /// Release the seeded tag is scoped to. Lets a CID shared by several
65        /// releases be unseeded per release without dropping the others.
66        release: Oid,
67        /// Expected content identifier.
68        cid: Cid,
69        /// Path to the artifact on disk (file for blobs, directory for collections).
70        path: PathBuf,
71        /// Whether the artifact is a single blob or a collection.
72        kind: ArtifactKind,
73        /// Copy bytes into the store or reference them in place.
74        mode: ImportMode,
75    },
76    /// Remove seeded tags for `cid`. Idempotent. `release: Some(id)` drops
77    /// just that release's tag; `None` stops seeding the CID across every
78    /// release of `rid`.
79    Unseed {
80        /// Repository the artifact belongs to.
81        rid: RepoId,
82        /// Release to stop seeding, or `None` for all releases of `rid`.
83        #[serde(default, skip_serializing_if = "Option::is_none")]
84        release: Option<Oid>,
85        /// Content identifier to stop seeding.
86        cid: Cid,
87    },
88    /// Whether `(rid, cid)` is currently seeded under any release.
89    IsSeeding {
90        /// Repository the artifact belongs to.
91        rid: RepoId,
92        /// Content identifier to check.
93        cid: Cid,
94    },
95    /// List CIDs seeded under `rid`.
96    ListSeeded {
97        /// Repository to enumerate.
98        rid: RepoId,
99    },
100    /// Cheap predicate: is this CID's content present/complete in the
101    /// store? No network. One-shot, returns [`HasResult`]. Hash-keyed and
102    /// repo-agnostic.
103    Has {
104        /// Content identifier to look up.
105        cid: Cid,
106    },
107    /// Export already-local bytes to `dest`. No network. Streaming —
108    /// emits `exporting` progress, then [`ExportReceipt`]. Errors with
109    /// [`ErrorCode::NotLocal`] if the content isn't complete in the store.
110    Export {
111        /// Content identifier to export.
112        cid: Cid,
113        /// Destination path (file for blobs, directory for collections).
114        dest: PathBuf,
115    },
116    /// Fetch an artifact into the store: no-op if already complete locally,
117    /// else download from `locations`, optionally tag as seeded. Does not
118    /// write to disk — use [`Command::Download`] for that. Streaming —
119    /// emits progress, then [`FetchReceipt`].
120    Fetch {
121        /// Repository the artifact belongs to (for the seeded tag).
122        rid: RepoId,
123        /// Expected content identifier; the blob kind is derived from it.
124        cid: Cid,
125        /// Resolved providers/URLs to try. Iroh providers are batched into
126        /// one multi-provider download; URLs are tried in sequence.
127        locations: Vec<FetchLocation>,
128        /// Release to seed under once the fetch completes, tagged
129        /// `seeded/{rid}/{release}/{cid}` so the node serves it. `None`
130        /// fetches without seeding; pairing seed intent with its release
131        /// keeps an unscoped seed unrepresentable.
132        #[serde(default, skip_serializing_if = "Option::is_none")]
133        seed: Option<Oid>,
134    },
135    /// Download an artifact to disk: [`Command::Fetch`] into the store, then
136    /// export to `dest`. Fast-path export if already local. Optionally tags
137    /// as seeded. Streaming — emits progress, then [`DownloadReceipt`].
138    Download {
139        /// Repository the artifact belongs to (for the seeded tag).
140        rid: RepoId,
141        /// Expected content identifier; the blob kind is derived from it.
142        cid: Cid,
143        /// Resolved providers/URLs to try. Iroh providers are batched into
144        /// one multi-provider download; URLs are tried in sequence.
145        locations: Vec<FetchLocation>,
146        /// Destination path (file for blobs, directory for collections).
147        dest: PathBuf,
148        /// Release to seed under once the download completes, tagged
149        /// `seeded/{rid}/{release}/{cid}` so the node serves it. `None`
150        /// downloads without seeding; pairing seed intent with its release
151        /// keeps an unscoped seed unrepresentable.
152        #[serde(default, skip_serializing_if = "Option::is_none")]
153        seed: Option<Oid>,
154    },
155    /// Ask the node to shut down gracefully.
156    Shutdown,
157}
158
159/// A resolved place to fetch an artifact from.
160///
161/// Owned and serde-friendly, unlike the borrowed COB form (`(&Url, &Did)`).
162/// The caller resolves COB locations (including DID-derived bare
163/// `radiroh://` entries) into this concrete form; the node does no
164/// identity resolution of its own.
165#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
166#[serde(rename_all = "camelCase")]
167pub enum FetchLocation {
168    /// An HTTP(S) (or other-scheme) URL, serialized as the URL string.
169    Url(Url),
170    /// An iroh provider, serialized as the canonical `radiroh://<base32>` URL.
171    Iroh(EndpointId),
172}
173
174/// Top-level response envelope.
175///
176/// Externally tagged so the wire reads `{"okay": <T>}` or
177/// `{"error": <CommandError>}`. Type-stable across commands by parameter.
178#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
179#[serde(rename_all = "camelCase")]
180pub enum CommandResult<T> {
181    /// Success with command-specific payload.
182    Okay(T),
183    /// Failure with structured error.
184    Error(CommandError),
185}
186
187/// Frame of a streaming response ([`Command::Fetch`], [`Command::Download`],
188/// [`Command::Export`]).
189///
190/// Externally tagged: `{"progress": …}` (repeatable, non-terminal) then
191/// exactly one terminal `{"okay": <T>}` / `{"error": <CommandError>}`. The
192/// terminal tags deliberately match [`CommandResult`] so a generic reader
193/// recognizes them; `progress` is the new, non-terminal frame.
194#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
195#[serde(rename_all = "camelCase")]
196pub enum StreamEvent<T> {
197    /// Non-terminal progress update.
198    Progress(FetchProgress),
199    /// Terminal success with command-specific payload.
200    Okay(T),
201    /// Terminal failure.
202    Error(CommandError),
203}
204
205/// One progress frame for a streaming command.
206///
207/// An enum, not a struct, so Location-level events (which carry no byte
208/// offset) and byte-movement events are modeled distinctly. The variants
209/// map onto the iroh `DownloadProgressItem` kinds the download loop
210/// already produces. `Export` only ever emits [`FetchProgress::Exporting`].
211#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
212#[serde(
213    rename_all = "camelCase",
214    rename_all_fields = "camelCase",
215    tag = "kind"
216)]
217pub enum FetchProgress {
218    /// Endpoint/relay setup, before any Location is tried.
219    Connecting,
220    /// Now attempting this Location.
221    TryingLocation {
222        /// Endpoint being tried.
223        endpoint_id: EndpointId,
224    },
225    /// This Location failed; moving on to the next.
226    LocationFailed {
227        /// Endpoint that failed.
228        endpoint_id: EndpointId,
229    },
230    /// Byte movement during download.
231    Downloading {
232        /// Bytes downloaded so far.
233        offset: u64,
234        /// Total size, if known.
235        total: Option<u64>,
236    },
237    /// Byte movement while writing the store out to disk.
238    Exporting {
239        /// Bytes exported so far.
240        offset: u64,
241        /// Total size, if known.
242        total: Option<u64>,
243        /// Collection member being exported; `None` for a single blob.
244        entry: Option<String>,
245    },
246}
247
248/// Structured failure: an [`ErrorCode`] plus a human-readable message.
249#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
250#[serde(rename_all = "camelCase")]
251pub struct CommandError {
252    /// Machine-readable category.
253    pub code: ErrorCode,
254    /// Free-form detail; not for parsing.
255    pub message: String,
256}
257
258/// Classifier for [`CommandError`]. `#[non_exhaustive]` so new codes are
259/// additive.
260#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
261#[serde(rename_all = "camelCase")]
262pub enum ErrorCode {
263    /// Content hash from `path` did not match the requested `cid`.
264    CidMismatch,
265    /// `path` does not exist or is not readable.
266    PathNotFound,
267    /// Tried to operate on a `(rid, cid)` that is not seeded.
268    NotSeeding,
269    /// Local I/O failure.
270    Io,
271    /// Iroh networking or store failure.
272    Iroh,
273    /// Wire-level decode failure: the command line was not valid JSON,
274    /// or a typed field (rid, cid, …) failed to parse. The accompanying
275    /// `message` surfaces the underlying serde error.
276    InvalidRequest,
277    /// `Export` (or a fetch fast path) needed local bytes that the store
278    /// does not hold completely.
279    NotLocal,
280    /// A `Fetch`/`Download` was given no usable locations to try.
281    NoLocations,
282    /// Every provider/URL a `Fetch`/`Download` tried failed; `message`
283    /// lists them.
284    AllFailed,
285    /// Bug or unhandled state inside the node.
286    Internal,
287}
288
289/// Successful result of [`Command::Seed`].
290#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
291#[serde(rename_all = "camelCase")]
292pub struct SeedReceipt {
293    /// Echo of the requested repository.
294    pub rid: RepoId,
295    /// Echo of the requested CID.
296    pub cid: Cid,
297    /// Endpoint id the node is serving on, as a canonical `radiroh://<base32>` URL.
298    pub endpoint_id: EndpointId,
299    /// Logical size of the imported artifact in bytes.
300    pub bytes: u64,
301    /// `true` if this call newly tagged the pair; `false` if it was
302    /// already tagged before the call.
303    pub was_new: bool,
304}
305
306/// Successful result of [`Command::Unseed`].
307#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
308#[serde(rename_all = "camelCase")]
309pub struct UnseedReceipt {
310    /// Echo of the requested repository.
311    pub rid: RepoId,
312    /// Echo of the requested CID.
313    pub cid: Cid,
314    /// `true` if a tag was removed; `false` if no tag existed.
315    pub was_removed: bool,
316}
317
318/// One entry returned by [`Command::ListSeeded`].
319#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
320#[serde(rename_all = "camelCase")]
321pub struct SeededEntry {
322    /// Content identifier currently tagged under the requested rid.
323    pub cid: Cid,
324    /// Logical artifact size in bytes. Best-effort — zero if the iroh
325    /// status call temporarily fails.
326    pub bytes: u64,
327    /// Whether the store actually holds every byte. A seeded tag records
328    /// intent, so it can outlive the bytes it points at (a wiped store, a
329    /// restored backup); this reports what is on disk. `None` means the
330    /// lookup failed, or the node predates the field — treat it as
331    /// unknown, never as missing.
332    #[serde(default)]
333    pub complete: Option<bool>,
334    /// Releases that seed this CID. One CID can belong to several releases
335    /// of the repository. Empty when the node predates the field.
336    #[serde(default)]
337    pub releases: Vec<Oid>,
338}
339
340/// Result of [`Command::Has`].
341#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
342#[serde(rename_all = "camelCase")]
343pub struct HasResult {
344    /// Some bytes for this CID are in the store.
345    pub present: bool,
346    /// The content is fully downloaded.
347    pub complete: bool,
348    /// Logical size known so far, in bytes.
349    pub bytes: u64,
350}
351
352/// Terminal result of [`Command::Export`].
353#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
354#[serde(rename_all = "camelCase")]
355pub struct ExportReceipt {
356    /// Echo of the exported CID.
357    pub cid: Cid,
358    /// Where the bytes were written.
359    pub dest: PathBuf,
360    /// Logical size exported, in bytes.
361    pub bytes: u64,
362}
363
364/// Terminal result of [`Command::Fetch`].
365#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
366#[serde(rename_all = "camelCase")]
367pub struct FetchReceipt {
368    /// Echo of the requested repository.
369    pub rid: RepoId,
370    /// Echo of the fetched CID.
371    pub cid: Cid,
372    /// Logical size now complete in the store, in bytes.
373    pub bytes: u64,
374    /// `true` if the bytes were already local; no network was used.
375    pub from_cache: bool,
376    /// `true` if a `seeded/{rid}/{release}/{cid}` tag is now set.
377    pub seeded: bool,
378    /// Endpoint id the node serves on, as a canonical `radiroh://<base32>`
379    /// URL. Present so the caller can write the `add_location` COB after a
380    /// seeding fetch. Mirrors [`SeedReceipt::endpoint_id`].
381    pub endpoint_id: EndpointId,
382}
383
384/// Terminal result of [`Command::Download`].
385#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
386#[serde(rename_all = "camelCase")]
387pub struct DownloadReceipt {
388    /// Echo of the requested repository.
389    pub rid: RepoId,
390    /// Echo of the downloaded CID.
391    pub cid: Cid,
392    /// Where the bytes were written.
393    pub dest: PathBuf,
394    /// Logical size exported, in bytes.
395    pub bytes: u64,
396    /// `true` if the bytes were already local; no network was used.
397    pub from_cache: bool,
398    /// `true` if a `seeded/{rid}/{release}/{cid}` tag is now set.
399    pub seeded: bool,
400    /// Endpoint id the node serves on, as a canonical `radiroh://<base32>`
401    /// URL. Present so the caller can write the `add_location` COB after a
402    /// seeding download. Mirrors [`SeedReceipt::endpoint_id`].
403    pub endpoint_id: EndpointId,
404}
405
406/// Successful result of [`Command::Status`]. See the design doc for the
407/// per-field source recipes; in v1 only the obvious fields are wired and
408/// the rest default to zero.
409#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
410#[serde(rename_all = "camelCase")]
411pub struct Status {
412    /// Endpoint id the node is serving on, as a canonical `radiroh://<base32>` URL.
413    pub endpoint_id: EndpointId,
414    /// Unix timestamp (seconds) when the node bound its socket.
415    pub started_at_unix: i64,
416    /// Aggregated tag-level stats.
417    pub seeded: SeededStats,
418    /// Connection counters derived from iroh's metrics.
419    pub connections: ConnectionStats,
420    /// Bytes-on-the-wire counters from iroh's socket metrics.
421    pub traffic: TrafficStats,
422    /// Home-relay connectivity and measured latency.
423    pub relay: RelayStats,
424    /// Pkarr key and the pkarr relays the node publishes to. `None` when the
425    /// node predates the field.
426    #[serde(default)]
427    pub pkarr: Option<PkarrStats>,
428    /// Soft warnings rendered as advice to the user.
429    pub warnings: Warnings,
430}
431
432/// Aggregated `seeded/{rid}/{release}/{cid}` tag stats across all repos.
433#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
434#[serde(rename_all = "camelCase")]
435pub struct SeededStats {
436    /// Number of distinct seeded blobs. A blob tagged in several releases
437    /// counts once.
438    pub count: usize,
439    /// Sum of logical sizes across distinct seeded blobs.
440    pub bytes_logical: u64,
441}
442
443/// QUIC connection counters from iroh's socket metrics.
444#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
445#[serde(rename_all = "camelCase")]
446pub struct ConnectionStats {
447    /// Currently open connections (`opened_total - closed_total`).
448    pub active: u32,
449    /// Lifetime opened-handshaked count (excludes 0-RTT).
450    pub opened_total: u64,
451    /// Lifetime closed count.
452    pub closed_total: u64,
453    /// Lifetime count of direct (non-relayed) connections.
454    pub direct_total: u64,
455    /// Lifetime count of holepunch attempts (client-side increments only).
456    pub holepunch_attempts: u64,
457    /// Path counter: direct.
458    pub paths_direct: u64,
459    /// Path counter: relayed.
460    pub paths_relayed: u64,
461}
462
463/// Bytes-on-the-wire counters from iroh's socket metrics. See the design
464/// doc for the disco-vs-data semantics — `out_bytes` includes disco
465/// frames, `in_bytes` excludes them.
466#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
467#[serde(rename_all = "camelCase")]
468pub struct TrafficStats {
469    /// Bytes sent across ipv4/ipv6/relay (includes disco).
470    pub out_bytes: u64,
471    /// Bytes received across ipv4/ipv6/relay/custom (data only).
472    pub in_bytes: u64,
473}
474
475/// Home-relay connectivity. The relay is how peers that can't holepunch a
476/// direct path reach this node, so a disconnected relay means reduced
477/// reachability even while the local socket is bound.
478#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
479#[serde(rename_all = "camelCase")]
480pub struct RelayStats {
481    /// Per-home-relay status. Empty before a relay is selected, or when
482    /// relays are disabled.
483    pub relays: Vec<RelayHealth>,
484    /// URL of the lowest-latency relay net_report would prefer, if a report
485    /// has landed yet.
486    pub preferred: Option<String>,
487    /// A QAD (UDP) round trip completed over IPv4 — i.e. direct UDP works.
488    pub udp_v4: bool,
489    /// A QAD (UDP) round trip completed over IPv6.
490    pub udp_v6: bool,
491}
492
493/// Connection status and measured latency of a single home relay.
494#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
495#[serde(rename_all = "camelCase")]
496pub struct RelayHealth {
497    /// Relay URL.
498    pub url: String,
499    /// `true` when the endpoint currently holds a connection to the relay.
500    pub connected: bool,
501    /// Lowest round-trip latency measured by net_report, in milliseconds.
502    /// `None` until a probe lands.
503    pub latency_ms: Option<u64>,
504    /// Most recent connection error when disconnected; `None` when connected
505    /// or before any failure was observed.
506    pub last_error: Option<String>,
507}
508
509/// Pkarr identity of the node. Peers resolve the node's home relay through
510/// these pkarr relays.
511#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
512#[serde(rename_all = "camelCase")]
513pub struct PkarrStats {
514    /// The node's key as a `pk:<z32>` URI.
515    pub uri: String,
516    /// Pkarr relays (HTTP servers, not iroh relays) the node publishes to
517    /// and resolves from.
518    pub relays: Vec<Url>,
519}
520
521/// Soft warnings surfaced in `Status`, rendered as advice to the user.
522#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
523#[serde(rename_all = "camelCase")]
524pub struct Warnings {
525    /// Set when no home relay is connected; peers that can't holepunch may
526    /// be unable to reach this node.
527    pub relay_unreachable: bool,
528}
529
530#[cfg(test)]
531mod tests {
532    use std::path::PathBuf;
533    use std::str::FromStr;
534
535    use serde_json::json;
536
537    use super::*;
538
539    /// Real RepoId used as a wire-snapshot fixture.
540    const SAMPLE_RID: &str = "rad:z2u2CP3ZJzB7ZqE8jHrau19yjpdip";
541
542    fn sample_rid() -> RepoId {
543        RepoId::from_str(SAMPLE_RID).unwrap()
544    }
545
546    /// Release Oid (a COB ObjectId's git hash) used as a wire-snapshot fixture.
547    const SAMPLE_RELEASE: &str = "0123456789abcdef0123456789abcdef01234567";
548
549    fn sample_release() -> Oid {
550        Oid::from_str(SAMPLE_RELEASE).unwrap()
551    }
552
553    /// Real Blake3/raw Cid for wire snapshots — built from a pinned
554    /// preimage so the multibase string stays stable across runs.
555    fn sample_cid() -> Cid {
556        let digest = blake3::hash(b"protocol-cid-sample");
557        let mh =
558            cid::multihash::Multihash::<64>::wrap(crate::cid::HASH_CODE_BLAKE3, digest.as_bytes())
559                .unwrap();
560        Cid::from(cid::Cid::new_v1(crate::cid::RAW_CODEC, mh))
561    }
562
563    /// Catch-all check that every top-level type round-trips through
564    /// JSON and the encoding stays bit-for-bit stable. If you add a
565    /// field or change a tag, expect to update the literals here.
566    #[test]
567    fn wire_snapshot_command_status() {
568        let cmd = Command::Status;
569        let s = serde_json::to_string(&cmd).unwrap();
570        assert_eq!(s, r#"{"command":"status"}"#);
571        let back: Command = serde_json::from_str(&s).unwrap();
572        assert_eq!(back, cmd);
573    }
574
575    #[test]
576    fn wire_snapshot_command_alive() {
577        let cmd = Command::Alive;
578        let s = serde_json::to_string(&cmd).unwrap();
579        assert_eq!(s, r#"{"command":"alive"}"#);
580        let back: Command = serde_json::from_str(&s).unwrap();
581        assert_eq!(back, cmd);
582    }
583
584    #[test]
585    fn wire_snapshot_command_seed() {
586        let cid = sample_cid();
587        let cmd = Command::Seed {
588            rid: sample_rid(),
589            release: sample_release(),
590            cid,
591            path: PathBuf::from("/tmp/a"),
592            kind: ArtifactKind::Blob,
593            mode: ImportMode::Copy,
594        };
595        let s = serde_json::to_value(&cmd).unwrap();
596        assert_eq!(
597            s,
598            json!({
599                "command": "seed",
600                "rid": SAMPLE_RID,
601                "release": SAMPLE_RELEASE,
602                "cid": cid.to_string(),
603                "path": "/tmp/a",
604                "kind": "blob",
605                "mode": "copy",
606            })
607        );
608    }
609
610    #[test]
611    fn wire_snapshot_command_unseed_and_lookups() {
612        let cid = sample_cid();
613        // `release: None` (stop seeding the CID everywhere) omits the field.
614        let unseed = Command::Unseed {
615            rid: sample_rid(),
616            release: None,
617            cid,
618        };
619        assert_eq!(
620            serde_json::to_value(&unseed).unwrap(),
621            json!({"command":"unseed", "rid": SAMPLE_RID, "cid": cid.to_string()})
622        );
623
624        // `release: Some(..)` (one release) carries the id.
625        let unseed_one = Command::Unseed {
626            rid: sample_rid(),
627            release: Some(sample_release()),
628            cid,
629        };
630        assert_eq!(
631            serde_json::to_value(&unseed_one).unwrap(),
632            json!({"command":"unseed", "rid": SAMPLE_RID, "release": SAMPLE_RELEASE, "cid": cid.to_string()})
633        );
634
635        let is_seeding = Command::IsSeeding {
636            rid: sample_rid(),
637            cid,
638        };
639        assert_eq!(
640            serde_json::to_value(&is_seeding).unwrap(),
641            json!({"command":"isSeeding", "rid": SAMPLE_RID, "cid": cid.to_string()})
642        );
643
644        let list = Command::ListSeeded { rid: sample_rid() };
645        assert_eq!(
646            serde_json::to_value(&list).unwrap(),
647            json!({"command":"listSeeded", "rid": SAMPLE_RID})
648        );
649
650        let shutdown = Command::Shutdown;
651        assert_eq!(
652            serde_json::to_value(&shutdown).unwrap(),
653            json!({"command":"shutdown"})
654        );
655    }
656
657    #[test]
658    fn wire_snapshot_command_result_ok_and_err() {
659        let ok: CommandResult<u32> = CommandResult::Okay(7);
660        assert_eq!(serde_json::to_value(&ok).unwrap(), json!({"okay": 7}));
661
662        let err: CommandResult<u32> = CommandResult::Error(CommandError {
663            code: ErrorCode::CidMismatch,
664            message: "expected != actual".into(),
665        });
666        assert_eq!(
667            serde_json::to_value(&err).unwrap(),
668            json!({"error": {"code": "cidMismatch", "message": "expected != actual"}})
669        );
670    }
671
672    #[test]
673    fn wire_snapshot_receipts() {
674        let endpoint_id = sample_endpoint_id();
675        let cid = sample_cid();
676        let seed = SeedReceipt {
677            rid: sample_rid(),
678            cid,
679            endpoint_id,
680            bytes: 42,
681            was_new: true,
682        };
683        assert_eq!(
684            serde_json::to_value(&seed).unwrap(),
685            json!({
686                "rid": SAMPLE_RID,
687                "cid": cid.to_string(),
688                // Serialized as the canonical radiroh:// URL form.
689                "endpointId": endpoint_id.to_string(),
690                "bytes": 42,
691                "wasNew": true,
692            })
693        );
694        // Round-trips back to the same typed value.
695        let back: SeedReceipt =
696            serde_json::from_value(serde_json::to_value(&seed).unwrap()).unwrap();
697        assert_eq!(back, seed);
698
699        let unseed = UnseedReceipt {
700            rid: sample_rid(),
701            cid,
702            was_removed: false,
703        };
704        assert_eq!(
705            serde_json::to_value(&unseed).unwrap(),
706            json!({"rid": SAMPLE_RID, "cid": cid.to_string(), "wasRemoved": false})
707        );
708
709        let entry = SeededEntry {
710            cid,
711            bytes: 1024,
712            complete: Some(true),
713            releases: vec![sample_release()],
714        };
715        assert_eq!(
716            serde_json::to_value(&entry).unwrap(),
717            json!({
718                "cid": cid.to_string(),
719                "bytes": 1024,
720                "complete": true,
721                "releases": [SAMPLE_RELEASE],
722            })
723        );
724
725        // An older node omits `releases`; it decodes as empty.
726        let old: SeededEntry = serde_json::from_value(
727            json!({"cid": cid.to_string(), "bytes": 1024, "complete": true}),
728        )
729        .unwrap();
730        assert!(old.releases.is_empty());
731    }
732
733    /// Fixed endpoint id for wire snapshots; derived from a pinned secret.
734    fn sample_endpoint_id() -> EndpointId {
735        iroh_base::SecretKey::from_bytes(&[7u8; 32]).public().into()
736    }
737
738    #[test]
739    fn wire_snapshot_status_zeroed() {
740        let endpoint_id = sample_endpoint_id();
741        let st = Status {
742            endpoint_id,
743            started_at_unix: 0,
744            seeded: SeededStats::default(),
745            connections: ConnectionStats::default(),
746            traffic: TrafficStats::default(),
747            relay: RelayStats::default(),
748            pkarr: Some(PkarrStats {
749                uri: endpoint_id.to_pkarr_uri(),
750                relays: vec![Url::parse("https://dns.example.org/pkarr").unwrap()],
751            }),
752            warnings: Warnings::default(),
753        };
754        assert_eq!(
755            serde_json::to_value(&st).unwrap(),
756            json!({
757                "endpointId": endpoint_id.to_string(),
758                "startedAtUnix": 0,
759                "seeded": {"count": 0, "bytesLogical": 0},
760                "connections": {
761                    "active": 0,
762                    "openedTotal": 0,
763                    "closedTotal": 0,
764                    "directTotal": 0,
765                    "holepunchAttempts": 0,
766                    "pathsDirect": 0,
767                    "pathsRelayed": 0,
768                },
769                "traffic": {"outBytes": 0, "inBytes": 0},
770                "relay": {
771                    "relays": [],
772                    "preferred": null,
773                    "udpV4": false,
774                    "udpV6": false,
775                },
776                "pkarr": {
777                    "uri": endpoint_id.to_pkarr_uri(),
778                    "relays": ["https://dns.example.org/pkarr"],
779                },
780                "warnings": {"relayUnreachable": false},
781            })
782        );
783    }
784
785    #[test]
786    fn status_without_pkarr_decodes() {
787        // A node that predates the `pkarr` field must still decode.
788        let endpoint_id = sample_endpoint_id();
789        let st: Status = serde_json::from_value(json!({
790            "endpointId": endpoint_id.to_string(),
791            "startedAtUnix": 0,
792            "seeded": {"count": 0, "bytesLogical": 0},
793            "connections": {
794                "active": 0,
795                "openedTotal": 0,
796                "closedTotal": 0,
797                "directTotal": 0,
798                "holepunchAttempts": 0,
799                "pathsDirect": 0,
800                "pathsRelayed": 0,
801            },
802            "traffic": {"outBytes": 0, "inBytes": 0},
803            "relay": {"relays": [], "preferred": null, "udpV4": false, "udpV6": false},
804            "warnings": {"relayUnreachable": false},
805        }))
806        .unwrap();
807        assert_eq!(st.pkarr, None);
808    }
809
810    #[test]
811    fn wire_snapshot_command_has_export_fetch_download() {
812        let cid = sample_cid();
813        let endpoint_id = sample_endpoint_id();
814
815        let has = Command::Has { cid };
816        assert_eq!(
817            serde_json::to_value(&has).unwrap(),
818            json!({"command": "has", "cid": cid.to_string()})
819        );
820
821        let export = Command::Export {
822            cid,
823            dest: PathBuf::from("/tmp/out"),
824        };
825        assert_eq!(
826            serde_json::to_value(&export).unwrap(),
827            json!({"command": "export", "cid": cid.to_string(), "dest": "/tmp/out"})
828        );
829
830        // Fetch is store-only: no `dest` field on the wire. `seed: Some(..)`
831        // carries the release to seed under.
832        let fetch = Command::Fetch {
833            rid: sample_rid(),
834            cid,
835            locations: vec![
836                FetchLocation::Iroh(endpoint_id),
837                FetchLocation::Url(Url::parse("https://e.x/f").unwrap()),
838            ],
839            seed: Some(sample_release()),
840        };
841        assert_eq!(
842            serde_json::to_value(&fetch).unwrap(),
843            json!({
844                "command": "fetch",
845                "rid": SAMPLE_RID,
846                "cid": cid.to_string(),
847                "locations": [
848                    {"iroh": endpoint_id.to_string()},
849                    {"url": "https://e.x/f"},
850                ],
851                "seed": SAMPLE_RELEASE,
852            })
853        );
854        let back: Command = serde_json::from_value(serde_json::to_value(&fetch).unwrap()).unwrap();
855        assert_eq!(back, fetch);
856
857        // Download adds `dest`; `seed: None` omits the field entirely.
858        let download = Command::Download {
859            rid: sample_rid(),
860            cid,
861            locations: vec![FetchLocation::Iroh(endpoint_id)],
862            dest: PathBuf::from("/tmp/out"),
863            seed: None,
864        };
865        assert_eq!(
866            serde_json::to_value(&download).unwrap(),
867            json!({
868                "command": "download",
869                "rid": SAMPLE_RID,
870                "cid": cid.to_string(),
871                "locations": [{"iroh": endpoint_id.to_string()}],
872                "dest": "/tmp/out",
873            })
874        );
875        let back: Command =
876            serde_json::from_value(serde_json::to_value(&download).unwrap()).unwrap();
877        assert_eq!(back, download);
878    }
879
880    #[test]
881    fn wire_snapshot_stream_event() {
882        // Terminal tags match CommandResult; `progress` is the new frame.
883        let progress: StreamEvent<u32> = StreamEvent::Progress(FetchProgress::Connecting);
884        assert_eq!(
885            serde_json::to_value(&progress).unwrap(),
886            json!({"progress": {"kind": "connecting"}})
887        );
888
889        let ok: StreamEvent<u32> = StreamEvent::Okay(7);
890        assert_eq!(serde_json::to_value(&ok).unwrap(), json!({"okay": 7}));
891
892        let err: StreamEvent<u32> = StreamEvent::Error(CommandError {
893            code: ErrorCode::AllFailed,
894            message: "no locations".into(),
895        });
896        assert_eq!(
897            serde_json::to_value(&err).unwrap(),
898            json!({"error": {"code": "allFailed", "message": "no locations"}})
899        );
900    }
901
902    #[test]
903    fn wire_snapshot_fetch_progress() {
904        let endpoint_id = sample_endpoint_id();
905        let cases = [
906            (FetchProgress::Connecting, json!({"kind": "connecting"})),
907            (
908                FetchProgress::TryingLocation { endpoint_id },
909                json!({"kind": "tryingLocation", "endpointId": endpoint_id.to_string()}),
910            ),
911            (
912                FetchProgress::LocationFailed { endpoint_id },
913                json!({"kind": "locationFailed", "endpointId": endpoint_id.to_string()}),
914            ),
915            (
916                FetchProgress::Downloading {
917                    offset: 65536,
918                    total: Some(1048576),
919                },
920                json!({"kind": "downloading", "offset": 65536, "total": 1048576}),
921            ),
922            (
923                FetchProgress::Exporting {
924                    offset: 10,
925                    total: None,
926                    entry: Some("a/b.txt".into()),
927                },
928                json!({"kind": "exporting", "offset": 10, "total": null, "entry": "a/b.txt"}),
929            ),
930        ];
931        for (value, expected) in cases {
932            assert_eq!(serde_json::to_value(&value).unwrap(), expected);
933            let back: FetchProgress =
934                serde_json::from_value(serde_json::to_value(&value).unwrap()).unwrap();
935            assert_eq!(back, value);
936        }
937    }
938
939    #[test]
940    fn wire_snapshot_fetch_results() {
941        let cid = sample_cid();
942        let endpoint_id = sample_endpoint_id();
943
944        let has = HasResult {
945            present: true,
946            complete: false,
947            bytes: 1024,
948        };
949        assert_eq!(
950            serde_json::to_value(&has).unwrap(),
951            json!({"present": true, "complete": false, "bytes": 1024})
952        );
953
954        let export = ExportReceipt {
955            cid,
956            dest: PathBuf::from("/tmp/out"),
957            bytes: 2048,
958        };
959        assert_eq!(
960            serde_json::to_value(&export).unwrap(),
961            json!({"cid": cid.to_string(), "dest": "/tmp/out", "bytes": 2048})
962        );
963
964        // Fetch receipt has no `dest`; `bytes` is the logical store size.
965        let fetch = FetchReceipt {
966            rid: sample_rid(),
967            cid,
968            bytes: 4096,
969            from_cache: false,
970            seeded: true,
971            endpoint_id,
972        };
973        assert_eq!(
974            serde_json::to_value(&fetch).unwrap(),
975            json!({
976                "rid": SAMPLE_RID,
977                "cid": cid.to_string(),
978                "bytes": 4096,
979                "fromCache": false,
980                "seeded": true,
981                "endpointId": endpoint_id.to_string(),
982            })
983        );
984        let back: FetchReceipt =
985            serde_json::from_value(serde_json::to_value(&fetch).unwrap()).unwrap();
986        assert_eq!(back, fetch);
987
988        // Download receipt adds `dest`.
989        let download = DownloadReceipt {
990            rid: sample_rid(),
991            cid,
992            dest: PathBuf::from("/tmp/out"),
993            bytes: 4096,
994            from_cache: true,
995            seeded: false,
996            endpoint_id,
997        };
998        assert_eq!(
999            serde_json::to_value(&download).unwrap(),
1000            json!({
1001                "rid": SAMPLE_RID,
1002                "cid": cid.to_string(),
1003                "dest": "/tmp/out",
1004                "bytes": 4096,
1005                "fromCache": true,
1006                "seeded": false,
1007                "endpointId": endpoint_id.to_string(),
1008            })
1009        );
1010        let back: DownloadReceipt =
1011            serde_json::from_value(serde_json::to_value(&download).unwrap()).unwrap();
1012        assert_eq!(back, download);
1013    }
1014}