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