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}
335
336/// Result of [`Command::Has`].
337#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
338#[serde(rename_all = "camelCase")]
339pub struct HasResult {
340 /// Some bytes for this CID are in the store.
341 pub present: bool,
342 /// The content is fully downloaded.
343 pub complete: bool,
344 /// Logical size known so far, in bytes.
345 pub bytes: u64,
346}
347
348/// Terminal result of [`Command::Export`].
349#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
350#[serde(rename_all = "camelCase")]
351pub struct ExportReceipt {
352 /// Echo of the exported CID.
353 pub cid: Cid,
354 /// Where the bytes were written.
355 pub dest: PathBuf,
356 /// Logical size exported, in bytes.
357 pub bytes: u64,
358}
359
360/// Terminal result of [`Command::Fetch`].
361#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
362#[serde(rename_all = "camelCase")]
363pub struct FetchReceipt {
364 /// Echo of the requested repository.
365 pub rid: RepoId,
366 /// Echo of the fetched CID.
367 pub cid: Cid,
368 /// Logical size now complete in the store, in bytes.
369 pub bytes: u64,
370 /// `true` if the bytes were already local; no network was used.
371 pub from_cache: bool,
372 /// `true` if a `seeded/{rid}/{cid}` tag is now set.
373 pub seeded: bool,
374 /// Endpoint id the node serves on, as a canonical `radiroh://<base32>`
375 /// URL. Present so the caller can write the `add_location` COB after a
376 /// seeding fetch. Mirrors [`SeedReceipt::endpoint_id`].
377 pub endpoint_id: EndpointId,
378}
379
380/// Terminal result of [`Command::Download`].
381#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
382#[serde(rename_all = "camelCase")]
383pub struct DownloadReceipt {
384 /// Echo of the requested repository.
385 pub rid: RepoId,
386 /// Echo of the downloaded CID.
387 pub cid: Cid,
388 /// Where the bytes were written.
389 pub dest: PathBuf,
390 /// Logical size exported, in bytes.
391 pub bytes: u64,
392 /// `true` if the bytes were already local; no network was used.
393 pub from_cache: bool,
394 /// `true` if a `seeded/{rid}/{cid}` tag is now set.
395 pub seeded: bool,
396 /// Endpoint id the node serves on, as a canonical `radiroh://<base32>`
397 /// URL. Present so the caller can write the `add_location` COB after a
398 /// seeding download. Mirrors [`SeedReceipt::endpoint_id`].
399 pub endpoint_id: EndpointId,
400}
401
402/// Successful result of [`Command::Status`]. See the design doc for the
403/// per-field source recipes; in v1 only the obvious fields are wired and
404/// the rest default to zero.
405#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
406#[serde(rename_all = "camelCase")]
407pub struct Status {
408 /// Endpoint id the node is serving on, as a canonical `radiroh://<base32>` URL.
409 pub endpoint_id: EndpointId,
410 /// Unix timestamp (seconds) when the node bound its socket.
411 pub started_at_unix: i64,
412 /// Aggregated tag-level stats.
413 pub seeded: SeededStats,
414 /// Connection counters derived from iroh's metrics.
415 pub connections: ConnectionStats,
416 /// Bytes-on-the-wire counters from iroh's socket metrics.
417 pub traffic: TrafficStats,
418 /// Home-relay connectivity and measured latency.
419 pub relay: RelayStats,
420 /// Soft warnings rendered as advice to the user.
421 pub warnings: Warnings,
422}
423
424/// Aggregated `seeded/{rid}/{cid}` tag stats across all repos.
425#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
426#[serde(rename_all = "camelCase")]
427pub struct SeededStats {
428 /// Number of tagged `(rid, cid)` pairs.
429 pub count: usize,
430 /// Sum of logical artifact sizes across all tags.
431 pub bytes_logical: u64,
432}
433
434/// QUIC connection counters from iroh's socket metrics.
435#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
436#[serde(rename_all = "camelCase")]
437pub struct ConnectionStats {
438 /// Currently open connections (`opened_total - closed_total`).
439 pub active: u32,
440 /// Lifetime opened-handshaked count (excludes 0-RTT).
441 pub opened_total: u64,
442 /// Lifetime closed count.
443 pub closed_total: u64,
444 /// Lifetime count of direct (non-relayed) connections.
445 pub direct_total: u64,
446 /// Lifetime count of holepunch attempts (client-side increments only).
447 pub holepunch_attempts: u64,
448 /// Path counter: direct.
449 pub paths_direct: u64,
450 /// Path counter: relayed.
451 pub paths_relayed: u64,
452}
453
454/// Bytes-on-the-wire counters from iroh's socket metrics. See the design
455/// doc for the disco-vs-data semantics — `out_bytes` includes disco
456/// frames, `in_bytes` excludes them.
457#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
458#[serde(rename_all = "camelCase")]
459pub struct TrafficStats {
460 /// Bytes sent across ipv4/ipv6/relay (includes disco).
461 pub out_bytes: u64,
462 /// Bytes received across ipv4/ipv6/relay/custom (data only).
463 pub in_bytes: u64,
464}
465
466/// Home-relay connectivity. The relay is how peers that can't holepunch a
467/// direct path reach this node, so a disconnected relay means reduced
468/// reachability even while the local socket is bound.
469#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
470#[serde(rename_all = "camelCase")]
471pub struct RelayStats {
472 /// Per-home-relay status. Empty before a relay is selected, or when
473 /// relays are disabled.
474 pub relays: Vec<RelayHealth>,
475 /// URL of the lowest-latency relay net_report would prefer, if a report
476 /// has landed yet.
477 pub preferred: Option<String>,
478 /// A QAD (UDP) round trip completed over IPv4 — i.e. direct UDP works.
479 pub udp_v4: bool,
480 /// A QAD (UDP) round trip completed over IPv6.
481 pub udp_v6: bool,
482}
483
484/// Connection status and measured latency of a single home relay.
485#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
486#[serde(rename_all = "camelCase")]
487pub struct RelayHealth {
488 /// Relay URL.
489 pub url: String,
490 /// `true` when the endpoint currently holds a connection to the relay.
491 pub connected: bool,
492 /// Lowest round-trip latency measured by net_report, in milliseconds.
493 /// `None` until a probe lands.
494 pub latency_ms: Option<u64>,
495 /// Most recent connection error when disconnected; `None` when connected
496 /// or before any failure was observed.
497 pub last_error: Option<String>,
498}
499
500/// Soft warnings surfaced in `Status`, rendered as advice to the user.
501#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
502#[serde(rename_all = "camelCase")]
503pub struct Warnings {
504 /// Set when no home relay is connected; peers that can't holepunch may
505 /// be unable to reach this node.
506 pub relay_unreachable: bool,
507}
508
509#[cfg(test)]
510mod tests {
511 use std::path::PathBuf;
512 use std::str::FromStr;
513
514 use serde_json::json;
515
516 use super::*;
517
518 /// Real RepoId used as a wire-snapshot fixture.
519 const SAMPLE_RID: &str = "rad:z2u2CP3ZJzB7ZqE8jHrau19yjpdip";
520
521 fn sample_rid() -> RepoId {
522 RepoId::from_str(SAMPLE_RID).unwrap()
523 }
524
525 /// Release Oid (a COB ObjectId's git hash) used as a wire-snapshot fixture.
526 const SAMPLE_RELEASE: &str = "0123456789abcdef0123456789abcdef01234567";
527
528 fn sample_release() -> Oid {
529 Oid::from_str(SAMPLE_RELEASE).unwrap()
530 }
531
532 /// Real Blake3/raw Cid for wire snapshots — built from a pinned
533 /// preimage so the multibase string stays stable across runs.
534 fn sample_cid() -> Cid {
535 let digest = blake3::hash(b"protocol-cid-sample");
536 let mh =
537 cid::multihash::Multihash::<64>::wrap(crate::cid::HASH_CODE_BLAKE3, digest.as_bytes())
538 .unwrap();
539 Cid::from(cid::Cid::new_v1(crate::cid::RAW_CODEC, mh))
540 }
541
542 /// Catch-all check that every top-level type round-trips through
543 /// JSON and the encoding stays bit-for-bit stable. If you add a
544 /// field or change a tag, expect to update the literals here.
545 #[test]
546 fn wire_snapshot_command_status() {
547 let cmd = Command::Status;
548 let s = serde_json::to_string(&cmd).unwrap();
549 assert_eq!(s, r#"{"command":"status"}"#);
550 let back: Command = serde_json::from_str(&s).unwrap();
551 assert_eq!(back, cmd);
552 }
553
554 #[test]
555 fn wire_snapshot_command_alive() {
556 let cmd = Command::Alive;
557 let s = serde_json::to_string(&cmd).unwrap();
558 assert_eq!(s, r#"{"command":"alive"}"#);
559 let back: Command = serde_json::from_str(&s).unwrap();
560 assert_eq!(back, cmd);
561 }
562
563 #[test]
564 fn wire_snapshot_command_seed() {
565 let cid = sample_cid();
566 let cmd = Command::Seed {
567 rid: sample_rid(),
568 release: sample_release(),
569 cid,
570 path: PathBuf::from("/tmp/a"),
571 kind: ArtifactKind::Blob,
572 mode: ImportMode::Copy,
573 };
574 let s = serde_json::to_value(&cmd).unwrap();
575 assert_eq!(
576 s,
577 json!({
578 "command": "seed",
579 "rid": SAMPLE_RID,
580 "release": SAMPLE_RELEASE,
581 "cid": cid.to_string(),
582 "path": "/tmp/a",
583 "kind": "blob",
584 "mode": "copy",
585 })
586 );
587 }
588
589 #[test]
590 fn wire_snapshot_command_unseed_and_lookups() {
591 let cid = sample_cid();
592 // `release: None` (stop seeding the CID everywhere) omits the field.
593 let unseed = Command::Unseed {
594 rid: sample_rid(),
595 release: None,
596 cid,
597 };
598 assert_eq!(
599 serde_json::to_value(&unseed).unwrap(),
600 json!({"command":"unseed", "rid": SAMPLE_RID, "cid": cid.to_string()})
601 );
602
603 // `release: Some(..)` (one release) carries the id.
604 let unseed_one = Command::Unseed {
605 rid: sample_rid(),
606 release: Some(sample_release()),
607 cid,
608 };
609 assert_eq!(
610 serde_json::to_value(&unseed_one).unwrap(),
611 json!({"command":"unseed", "rid": SAMPLE_RID, "release": SAMPLE_RELEASE, "cid": cid.to_string()})
612 );
613
614 let is_seeding = Command::IsSeeding {
615 rid: sample_rid(),
616 cid,
617 };
618 assert_eq!(
619 serde_json::to_value(&is_seeding).unwrap(),
620 json!({"command":"isSeeding", "rid": SAMPLE_RID, "cid": cid.to_string()})
621 );
622
623 let list = Command::ListSeeded { rid: sample_rid() };
624 assert_eq!(
625 serde_json::to_value(&list).unwrap(),
626 json!({"command":"listSeeded", "rid": SAMPLE_RID})
627 );
628
629 let shutdown = Command::Shutdown;
630 assert_eq!(
631 serde_json::to_value(&shutdown).unwrap(),
632 json!({"command":"shutdown"})
633 );
634 }
635
636 #[test]
637 fn wire_snapshot_command_result_ok_and_err() {
638 let ok: CommandResult<u32> = CommandResult::Okay(7);
639 assert_eq!(serde_json::to_value(&ok).unwrap(), json!({"okay": 7}));
640
641 let err: CommandResult<u32> = CommandResult::Error(CommandError {
642 code: ErrorCode::CidMismatch,
643 message: "expected != actual".into(),
644 });
645 assert_eq!(
646 serde_json::to_value(&err).unwrap(),
647 json!({"error": {"code": "cidMismatch", "message": "expected != actual"}})
648 );
649 }
650
651 #[test]
652 fn wire_snapshot_receipts() {
653 let endpoint_id = sample_endpoint_id();
654 let cid = sample_cid();
655 let seed = SeedReceipt {
656 rid: sample_rid(),
657 cid,
658 endpoint_id,
659 bytes: 42,
660 was_new: true,
661 };
662 assert_eq!(
663 serde_json::to_value(&seed).unwrap(),
664 json!({
665 "rid": SAMPLE_RID,
666 "cid": cid.to_string(),
667 // Serialized as the canonical radiroh:// URL form.
668 "endpointId": endpoint_id.to_string(),
669 "bytes": 42,
670 "wasNew": true,
671 })
672 );
673 // Round-trips back to the same typed value.
674 let back: SeedReceipt =
675 serde_json::from_value(serde_json::to_value(&seed).unwrap()).unwrap();
676 assert_eq!(back, seed);
677
678 let unseed = UnseedReceipt {
679 rid: sample_rid(),
680 cid,
681 was_removed: false,
682 };
683 assert_eq!(
684 serde_json::to_value(&unseed).unwrap(),
685 json!({"rid": SAMPLE_RID, "cid": cid.to_string(), "wasRemoved": false})
686 );
687
688 let entry = SeededEntry {
689 cid,
690 bytes: 1024,
691 complete: Some(true),
692 };
693 assert_eq!(
694 serde_json::to_value(&entry).unwrap(),
695 json!({"cid": cid.to_string(), "bytes": 1024, "complete": true})
696 );
697 }
698
699 /// Fixed endpoint id for wire snapshots; derived from a pinned secret.
700 fn sample_endpoint_id() -> EndpointId {
701 iroh_base::SecretKey::from_bytes(&[7u8; 32]).public().into()
702 }
703
704 #[test]
705 fn wire_snapshot_status_zeroed() {
706 let endpoint_id = sample_endpoint_id();
707 let st = Status {
708 endpoint_id,
709 started_at_unix: 0,
710 seeded: SeededStats::default(),
711 connections: ConnectionStats::default(),
712 traffic: TrafficStats::default(),
713 relay: RelayStats::default(),
714 warnings: Warnings::default(),
715 };
716 assert_eq!(
717 serde_json::to_value(&st).unwrap(),
718 json!({
719 "endpointId": endpoint_id.to_string(),
720 "startedAtUnix": 0,
721 "seeded": {"count": 0, "bytesLogical": 0},
722 "connections": {
723 "active": 0,
724 "openedTotal": 0,
725 "closedTotal": 0,
726 "directTotal": 0,
727 "holepunchAttempts": 0,
728 "pathsDirect": 0,
729 "pathsRelayed": 0,
730 },
731 "traffic": {"outBytes": 0, "inBytes": 0},
732 "relay": {
733 "relays": [],
734 "preferred": null,
735 "udpV4": false,
736 "udpV6": false,
737 },
738 "warnings": {"relayUnreachable": false},
739 })
740 );
741 }
742
743 #[test]
744 fn wire_snapshot_command_has_export_fetch_download() {
745 let cid = sample_cid();
746 let endpoint_id = sample_endpoint_id();
747
748 let has = Command::Has { cid };
749 assert_eq!(
750 serde_json::to_value(&has).unwrap(),
751 json!({"command": "has", "cid": cid.to_string()})
752 );
753
754 let export = Command::Export {
755 cid,
756 dest: PathBuf::from("/tmp/out"),
757 };
758 assert_eq!(
759 serde_json::to_value(&export).unwrap(),
760 json!({"command": "export", "cid": cid.to_string(), "dest": "/tmp/out"})
761 );
762
763 // Fetch is store-only: no `dest` field on the wire. `seed: Some(..)`
764 // carries the release to seed under.
765 let fetch = Command::Fetch {
766 rid: sample_rid(),
767 cid,
768 locations: vec![
769 FetchLocation::Iroh(endpoint_id),
770 FetchLocation::Url(Url::parse("https://e.x/f").unwrap()),
771 ],
772 seed: Some(sample_release()),
773 };
774 assert_eq!(
775 serde_json::to_value(&fetch).unwrap(),
776 json!({
777 "command": "fetch",
778 "rid": SAMPLE_RID,
779 "cid": cid.to_string(),
780 "locations": [
781 {"iroh": endpoint_id.to_string()},
782 {"url": "https://e.x/f"},
783 ],
784 "seed": SAMPLE_RELEASE,
785 })
786 );
787 let back: Command = serde_json::from_value(serde_json::to_value(&fetch).unwrap()).unwrap();
788 assert_eq!(back, fetch);
789
790 // Download adds `dest`; `seed: None` omits the field entirely.
791 let download = Command::Download {
792 rid: sample_rid(),
793 cid,
794 locations: vec![FetchLocation::Iroh(endpoint_id)],
795 dest: PathBuf::from("/tmp/out"),
796 seed: None,
797 };
798 assert_eq!(
799 serde_json::to_value(&download).unwrap(),
800 json!({
801 "command": "download",
802 "rid": SAMPLE_RID,
803 "cid": cid.to_string(),
804 "locations": [{"iroh": endpoint_id.to_string()}],
805 "dest": "/tmp/out",
806 })
807 );
808 let back: Command =
809 serde_json::from_value(serde_json::to_value(&download).unwrap()).unwrap();
810 assert_eq!(back, download);
811 }
812
813 #[test]
814 fn wire_snapshot_stream_event() {
815 // Terminal tags match CommandResult; `progress` is the new frame.
816 let progress: StreamEvent<u32> = StreamEvent::Progress(FetchProgress::Connecting);
817 assert_eq!(
818 serde_json::to_value(&progress).unwrap(),
819 json!({"progress": {"kind": "connecting"}})
820 );
821
822 let ok: StreamEvent<u32> = StreamEvent::Okay(7);
823 assert_eq!(serde_json::to_value(&ok).unwrap(), json!({"okay": 7}));
824
825 let err: StreamEvent<u32> = StreamEvent::Error(CommandError {
826 code: ErrorCode::AllFailed,
827 message: "no locations".into(),
828 });
829 assert_eq!(
830 serde_json::to_value(&err).unwrap(),
831 json!({"error": {"code": "allFailed", "message": "no locations"}})
832 );
833 }
834
835 #[test]
836 fn wire_snapshot_fetch_progress() {
837 let endpoint_id = sample_endpoint_id();
838 let cases = [
839 (FetchProgress::Connecting, json!({"kind": "connecting"})),
840 (
841 FetchProgress::TryingLocation { endpoint_id },
842 json!({"kind": "tryingLocation", "endpointId": endpoint_id.to_string()}),
843 ),
844 (
845 FetchProgress::LocationFailed { endpoint_id },
846 json!({"kind": "locationFailed", "endpointId": endpoint_id.to_string()}),
847 ),
848 (
849 FetchProgress::Downloading {
850 offset: 65536,
851 total: Some(1048576),
852 },
853 json!({"kind": "downloading", "offset": 65536, "total": 1048576}),
854 ),
855 (
856 FetchProgress::Exporting {
857 offset: 10,
858 total: None,
859 entry: Some("a/b.txt".into()),
860 },
861 json!({"kind": "exporting", "offset": 10, "total": null, "entry": "a/b.txt"}),
862 ),
863 ];
864 for (value, expected) in cases {
865 assert_eq!(serde_json::to_value(&value).unwrap(), expected);
866 let back: FetchProgress =
867 serde_json::from_value(serde_json::to_value(&value).unwrap()).unwrap();
868 assert_eq!(back, value);
869 }
870 }
871
872 #[test]
873 fn wire_snapshot_fetch_results() {
874 let cid = sample_cid();
875 let endpoint_id = sample_endpoint_id();
876
877 let has = HasResult {
878 present: true,
879 complete: false,
880 bytes: 1024,
881 };
882 assert_eq!(
883 serde_json::to_value(&has).unwrap(),
884 json!({"present": true, "complete": false, "bytes": 1024})
885 );
886
887 let export = ExportReceipt {
888 cid,
889 dest: PathBuf::from("/tmp/out"),
890 bytes: 2048,
891 };
892 assert_eq!(
893 serde_json::to_value(&export).unwrap(),
894 json!({"cid": cid.to_string(), "dest": "/tmp/out", "bytes": 2048})
895 );
896
897 // Fetch receipt has no `dest`; `bytes` is the logical store size.
898 let fetch = FetchReceipt {
899 rid: sample_rid(),
900 cid,
901 bytes: 4096,
902 from_cache: false,
903 seeded: true,
904 endpoint_id,
905 };
906 assert_eq!(
907 serde_json::to_value(&fetch).unwrap(),
908 json!({
909 "rid": SAMPLE_RID,
910 "cid": cid.to_string(),
911 "bytes": 4096,
912 "fromCache": false,
913 "seeded": true,
914 "endpointId": endpoint_id.to_string(),
915 })
916 );
917 let back: FetchReceipt =
918 serde_json::from_value(serde_json::to_value(&fetch).unwrap()).unwrap();
919 assert_eq!(back, fetch);
920
921 // Download receipt adds `dest`.
922 let download = DownloadReceipt {
923 rid: sample_rid(),
924 cid,
925 dest: PathBuf::from("/tmp/out"),
926 bytes: 4096,
927 from_cache: true,
928 seeded: false,
929 endpoint_id,
930 };
931 assert_eq!(
932 serde_json::to_value(&download).unwrap(),
933 json!({
934 "rid": SAMPLE_RID,
935 "cid": cid.to_string(),
936 "dest": "/tmp/out",
937 "bytes": 4096,
938 "fromCache": true,
939 "seeded": false,
940 "endpointId": endpoint_id.to_string(),
941 })
942 );
943 let back: DownloadReceipt =
944 serde_json::from_value(serde_json::to_value(&download).unwrap()).unwrap();
945 assert_eq!(back, download);
946 }
947}