ant_core/data/client/mod.rs
1//! Client operations for the Autonomi network.
2//!
3//! Provides high-level APIs for storing and retrieving data
4//! on the Autonomi decentralized network.
5
6pub mod adaptive;
7pub mod batch;
8pub mod cache;
9pub(crate) mod cached_merkle;
10pub(crate) mod cached_single;
11pub mod chunk;
12pub mod data;
13pub mod file;
14pub mod merkle;
15pub mod payment;
16pub mod quote;
17
18use crate::data::client::adaptive::{AdaptiveConfig, AdaptiveController, ChannelStart, Outcome};
19use crate::data::client::cache::ChunkCache;
20use crate::data::error::{Error, Result};
21use crate::data::network::Network;
22use crate::data::peer_cache;
23use ant_protocol::evm::Wallet;
24use ant_protocol::transport::{MultiAddr, P2PNode, PeerId};
25use ant_protocol::{XorName, CLOSE_GROUP_SIZE};
26use std::path::PathBuf;
27use std::sync::atomic::{AtomicU64, Ordering};
28use std::sync::Arc;
29use tracing::debug;
30
31/// Width of the chunk PUT-target set (initial writes plus fallback): the
32/// closest `PUT_TARGET_WIDTH` peers to the address.
33///
34/// Mirrors the node-side `K_BUCKET_SIZE` / `PAID_QUOTE_ISSUER_CLOSENESS_WIDTH`
35/// (20): a node accepts a reused payment proof only when one of the proof's
36/// closest-`CLOSE_GROUP_SIZE` quote issuers is within its own local 20-closest,
37/// so trying peers past this width is pointless.
38pub(crate) const PUT_TARGET_WIDTH: usize = 20;
39
40/// Classify a `data::error::Error` into a controller `Outcome`.
41///
42/// Capacity signals (Timeout / NetworkError) drive the controller
43/// down; application errors do not. The mapping is conservative:
44/// anything that COULD be transport-related is treated as a network
45/// signal, because under-classifying a real network failure as
46/// "application error" makes the controller blind to genuine stress.
47///
48/// Mapping policy:
49/// - `Timeout` -> `Timeout` (per-op deadline elapsed)
50/// - `Network`, `InsufficientPeers`, `Io` -> `NetworkError` (transport
51/// layer reported failure)
52/// - `Protocol`, `Storage` -> `NetworkError` (these wrap remote errors
53/// that frequently include peer disconnects mid-stream — under
54/// network stress these are how transport failures surface)
55/// - `PartialUpload` -> `NetworkError` (literal capacity signal: some
56/// chunks could not be stored)
57/// - `AlreadyStored`, `Encryption`, `Crypto`, `Payment`,
58/// `Serialization`, `InvalidData`, `NotFound`, `SignatureVerification`,
59/// `Config`, `InsufficientDiskSpace`, `CostEstimationInconclusive`,
60/// `Cancelled` -> `ApplicationError` (would happen on a perfectly
61/// healthy link; `Cancelled` is caller-initiated and must not be retried
62/// as a transport failure; `NotFound` is a definitively absent record
63/// reported over a working link, not a transport symptom)
64/// - `RemotePut` -> `ApplicationError` (the remote node responded with a
65/// structured rejection — the transport succeeded, so the node declined
66/// at the application layer; not a local capacity signal)
67/// - `CloseGroupShortfall` -> `ApplicationError` (a quorum shortfall caused
68/// by close-group dial/relay churn with no PUT-response timeouts — remote
69/// peer churn, not local backpressure; a timeout-bearing shortfall keeps
70/// `InsufficientPeers`/`NetworkError` instead, so genuine congestion still
71/// cuts the cap — V2-554)
72pub(crate) fn classify_error(err: &Error) -> Outcome {
73 match err {
74 Error::Timeout(_) => Outcome::Timeout,
75 Error::Network(_)
76 | Error::InsufficientPeers(_)
77 | Error::Io(_)
78 | Error::Protocol(_)
79 | Error::Storage(_)
80 | Error::PartialUpload { .. } => Outcome::NetworkError,
81 Error::AlreadyStored
82 | Error::Encryption(_)
83 | Error::Crypto(_)
84 | Error::Payment(_)
85 | Error::Serialization(_)
86 | Error::InvalidData(_)
87 // A definitively absent record, reported over a working link —
88 // the peers answered, there was just nothing stored there. Not a
89 // transport symptom, so it must not push the limiter down.
90 | Error::NotFound(_)
91 | Error::SignatureVerification(_)
92 | Error::Config(_)
93 | Error::InsufficientDiskSpace(_)
94 | Error::CostEstimationInconclusive(_)
95 | Error::Cancelled(_)
96 | Error::BadQuoteBinding { .. }
97 | Error::BadQuoteCommitment { .. }
98 // An external-signer merkle batch larger than one tree can hold —
99 // a caller-shape refusal raised before any network work, so it says
100 // nothing about link capacity.
101 | Error::MerkleBatchTooLarge { .. }
102 // A remote node responded with a structured rejection — the
103 // transport round-trip succeeded, so the node declined at the
104 // application layer (payment/disk/quote/pool). Not a local
105 // capacity signal; recorded but must not push the limiter down.
106 | Error::RemotePut { .. }
107 // A close-group PUT shortfall caused purely by dial/relay churn
108 // (dead/stale relayed peer addresses), with no PUT-response
109 // timeouts to signal local backpressure. Remote peer churn, not
110 // "client sending too fast" — must not push the limiter down
111 // (V2-554). A shortfall that DID time out keeps `InsufficientPeers`
112 // (`NetworkError`) so real congestion still cuts the cap.
113 | Error::CloseGroupShortfall(_) => Outcome::ApplicationError,
114 }
115}
116
117/// Compute XOR distance between a peer's ID bytes and a target address.
118///
119/// Uses the first 32 bytes of the peer ID (or fewer if shorter) XORed
120/// with the target address. The returned byte array sorts
121/// lexicographically from closest to furthest.
122pub(crate) fn peer_xor_distance(peer_id: &PeerId, target: &[u8; 32]) -> [u8; 32] {
123 let peer_bytes = peer_id.as_bytes();
124 let mut distance = [0u8; 32];
125 for (i, d) in distance.iter_mut().enumerate() {
126 let peer_byte = peer_bytes.get(i).copied().unwrap_or(0);
127 *d = peer_byte ^ target[i];
128 }
129 distance
130}
131
132/// Default timeout for lightweight network operations (quotes, DHT lookups) in seconds.
133const DEFAULT_QUOTE_TIMEOUT_SECS: u64 = 10;
134
135/// Default timeout for the per-peer chunk GET response and any other
136/// caller that explicitly reads `store_timeout_secs`, in seconds.
137///
138/// Note despite the name: this knob does **not** govern the non-merkle
139/// chunk PUT response timeout — that path uses the
140/// `STORE_RESPONSE_TIMEOUT` constant in `chunk.rs` directly. Nor does
141/// it govern the merkle batch PUT timeout — see
142/// `DEFAULT_MERKLE_STORE_TIMEOUT_SECS`.
143///
144/// 10 s matches the pre-existing `main` default and intentionally
145/// excludes residential-upload tuning, which is Mick's PR #78
146/// territory (splitting GET into its own field).
147const DEFAULT_STORE_TIMEOUT_SECS: u64 = 10;
148
149/// Default timeout for **merkle batch** chunk store operations in seconds.
150///
151/// Separate from `DEFAULT_STORE_TIMEOUT_SECS` because merkle PUTs carry
152/// an extra storer-side cost: the payment verifier runs an iterative
153/// DHT lookup (`CLOSENESS_LOOKUP_TIMEOUT` in `ant-node`, **240 s**
154/// post-PR #89) before accepting the proof.
155///
156/// This timeout MUST be >= the storer-side `CLOSENESS_LOOKUP_TIMEOUT`
157/// plus padding for the store-response round-trip and storer-local
158/// I/O. Otherwise the client gives up while the storer is still
159/// happily verifying, the storer wastes CPU/bandwidth on a chunk the
160/// client has already discarded, and the client re-targets a
161/// different close-K member — potentially double-storing the same
162/// chunk and polluting routing.
163///
164/// 270 s = 240 s (storer lookup) + 30 s padding (network RTT + LMDB
165/// put + fsync + clock skew tolerance).
166///
167/// This invariant must be re-validated if either side's timeout
168/// changes. Empirically surfaced as "every cross-region merkle chunk
169/// times out at 10 s" on a 210-node 7-region testnet run on
170/// 2026-05-12; bumping to 270 s flipped that 0/22 -> 9/9 pass rate.
171const DEFAULT_MERKLE_STORE_TIMEOUT_SECS: u64 = 270;
172
173/// Default timeout for chunk GET response operations in seconds.
174const DEFAULT_CHUNK_GET_TIMEOUT_SECS: u64 = 10;
175
176/// Default quote concurrency: high because quoting is pure network I/O
177/// (DHT lookups + small request/response messages) with no CPU-bound work.
178const DEFAULT_QUOTE_CONCURRENCY: usize = 32;
179
180/// Default store concurrency: moderate because each chunk PUT sends ~4MB
181/// to 7 close-group peers. At 8 concurrent stores, ~225MB of outbound
182/// traffic can be in flight. Users on fast connections can increase this
183/// with --store-concurrency; users on slow connections can decrease it.
184const DEFAULT_STORE_CONCURRENCY: usize = 8;
185
186/// Configuration for the Autonomi client.
187#[derive(Debug, Clone)]
188pub struct ClientConfig {
189 /// Per-op timeout for lightweight network operations (quotes,
190 /// DHT lookups), in seconds. The adaptive controller does NOT
191 /// currently size timeouts; this remains a static knob.
192 pub quote_timeout_secs: u64,
193 /// Per-op timeout, in seconds, for the chunk GET response path
194 /// (`chunk_get_from_peer`) and any other caller that reads this
195 /// field directly.
196 ///
197 /// Note despite the historical name `store_timeout_secs`: this
198 /// knob does **not** govern the non-merkle chunk PUT response
199 /// timeout (that path uses the `STORE_RESPONSE_TIMEOUT` constant
200 /// in `chunk.rs`) and does **not** govern the merkle batch PUT
201 /// timeout (see `merkle_store_timeout_secs`). Rename pending in
202 /// Mick's PR #78 which adds a dedicated `chunk_get_timeout_secs`.
203 ///
204 /// The adaptive controller does NOT currently size timeouts;
205 /// this remains a static knob.
206 pub store_timeout_secs: u64,
207 /// Per-op timeout for **merkle batch** chunk store (PUT)
208 /// operations, in seconds. Separate from `store_timeout_secs`
209 /// because merkle PUTs incur the storer-side
210 /// `CLOSENESS_LOOKUP_TIMEOUT` (240 s post-PR #89) on top of the
211 /// usual store path; the client must wait at least that long
212 /// plus padding, or the storer wastes work on a chunk the client
213 /// has already given up on. Default 270 s.
214 pub merkle_store_timeout_secs: u64,
215 /// Per-peer response timeout for chunk GET operations, in seconds.
216 /// This is intentionally independent from `store_timeout_secs`: PUTs
217 /// and GETs have different payload direction and performance profiles.
218 pub chunk_get_timeout_secs: u64,
219 /// Number of closest peers to consider for routing.
220 pub close_group_size: usize,
221 /// **Deprecated.** Pre-adaptive ceiling for quote concurrency.
222 ///
223 /// The adaptive controller now sizes quote fan-out from observed
224 /// signals. This field, when non-zero and smaller than the
225 /// controller's per-channel default, clamps the **quote channel
226 /// only** (it does NOT bleed into store or fetch). Removed in a
227 /// future release.
228 pub quote_concurrency: usize,
229 /// **Deprecated.** Pre-adaptive ceiling for store concurrency.
230 ///
231 /// The adaptive controller now sizes store fan-out from observed
232 /// signals. This field, when non-zero and smaller than the
233 /// controller's per-channel default, clamps the **store channel
234 /// only** (it does NOT bleed into quote or fetch). Removed in a
235 /// future release.
236 pub store_concurrency: usize,
237 /// Adaptive controller configuration. Defaults are tuned to match
238 /// or exceed the prior static behavior — disabling adaptation
239 /// (`adaptive.enabled = false`) reverts to the controller's
240 /// `initial` values without re-evaluation.
241 pub adaptive: AdaptiveConfig,
242 /// Allow loopback (`127.0.0.1`) connections in the saorsa-transport
243 /// layer. Set to `true` only for devnet / local testing. Production
244 /// peers on the public Autonomi network reject the QUIC handshake
245 /// variant produced when this is `true`, so the default is `false`.
246 ///
247 /// This mirrors the `--allow-loopback` flag in `ant-cli`, which already
248 /// defaults to `false` and threads through to the same
249 /// `CoreNodeConfig::builder().local(...)` call.
250 pub allow_loopback: bool,
251 /// Bind a dual-stack IPv6 socket (`true`) or an IPv4-only socket
252 /// (`false`). Defaults to `true`, matching the CLI default.
253 ///
254 /// Set to `false` only when running on hosts without a working IPv6
255 /// stack, to avoid advertising unreachable v6 addresses to the DHT
256 /// (which causes slow connects and junk DHT address records). This
257 /// mirrors the `--ipv4-only` flag in `ant-cli`.
258 pub ipv6: bool,
259}
260
261impl Default for ClientConfig {
262 fn default() -> Self {
263 Self {
264 quote_timeout_secs: DEFAULT_QUOTE_TIMEOUT_SECS,
265 store_timeout_secs: DEFAULT_STORE_TIMEOUT_SECS,
266 merkle_store_timeout_secs: DEFAULT_MERKLE_STORE_TIMEOUT_SECS,
267 chunk_get_timeout_secs: DEFAULT_CHUNK_GET_TIMEOUT_SECS,
268 close_group_size: CLOSE_GROUP_SIZE,
269 quote_concurrency: DEFAULT_QUOTE_CONCURRENCY,
270 store_concurrency: DEFAULT_STORE_CONCURRENCY,
271 adaptive: AdaptiveConfig::default(),
272 allow_loopback: false,
273 ipv6: true,
274 }
275 }
276}
277
278/// Build the adaptive controller for a `Client`. Loads any persisted
279/// snapshot, clamps cold-start values into the deprecated-flag bounds
280/// **per channel** (so a pin on `--store-concurrency` does NOT bleed
281/// into the fetch / quote channels), and returns the persistence path
282/// so callers can save back at shutdown.
283fn build_controller(config: &ClientConfig) -> (AdaptiveController, Option<PathBuf>) {
284 let mut adaptive_cfg = config.adaptive.clone();
285
286 // Per-channel ceilings: each legacy field is interpreted as a cap
287 // for ONLY its matching channel. The fetch channel has no
288 // pre-existing legacy field; it always uses the controller's
289 // default ceiling.
290 //
291 // The legacy fields are non-zero by ClientConfig::default(), but
292 // we honor them as bounds only when they would actually CONSTRAIN
293 // the controller — i.e. when smaller than the per-channel default
294 // max. A default ClientConfig must not silently lower the
295 // controller's ceilings.
296 // A value equal to the historic legacy default is treated as
297 // "not pinned by the user" — without this, every default
298 // ClientConfig would silently lower the controller's per-channel
299 // ceilings to the prior static values (32/8) and the controller
300 // could never grow above them.
301 let user_quote_max = config.quote_concurrency;
302 let user_store_max = config.store_concurrency;
303 let quote_pinned = user_quote_max > 0 && user_quote_max != DEFAULT_QUOTE_CONCURRENCY;
304 let store_pinned = user_store_max > 0 && user_store_max != DEFAULT_STORE_CONCURRENCY;
305 if quote_pinned && user_quote_max < adaptive_cfg.max.quote {
306 adaptive_cfg.max.quote = user_quote_max;
307 }
308 if store_pinned && user_store_max < adaptive_cfg.max.store {
309 adaptive_cfg.max.store = user_store_max;
310 }
311
312 // Cold-start values: matched to the prior static defaults. If the
313 // legacy field caps the channel below the cold-start, lower the
314 // start to match — never start above the channel's max.
315 let mut start = ChannelStart::default();
316 start.quote = start.quote.min(adaptive_cfg.max.quote);
317 start.store = start.store.min(adaptive_cfg.max.store);
318 start.fetch = start.fetch.min(adaptive_cfg.max.fetch);
319
320 let adaptive_enabled = adaptive_cfg.enabled;
321 let controller = AdaptiveController::new(start, adaptive_cfg);
322 // Skip disk warm-start entirely when adaptation is disabled —
323 // fixed-concurrency mode means the user wants exactly the cold
324 // start, no surprises from prior runs. (warm_start is also a
325 // no-op when disabled, but skipping the load avoids file I/O
326 // and the path-resolution side effects.)
327 let persist_path = if adaptive_enabled {
328 let p = adaptive::default_persist_path();
329 if let Some(ref path) = p {
330 if let Some(snap) = adaptive::load_snapshot(path) {
331 debug!(path = %path.display(), "adaptive: warm-start from disk");
332 controller.warm_start(snap);
333 }
334 }
335 p
336 } else {
337 // Even with adaptation off, persist_path is computed so
338 // explicit save_adaptive_snapshot() calls still work — but
339 // the controller currently never moves, so saving the cold
340 // start is harmless.
341 adaptive::default_persist_path()
342 };
343
344 // File downloads choose a stream-decrypt batch size per download
345 // from the current fetch cap and usable RAM, then pass it into
346 // self_encryption's runtime batch-size API. The adaptive controller
347 // still drives fan-out inside each batch by re-reading
348 // `controller.fetch.current()` in the decrypt callback.
349
350 (controller, persist_path)
351}
352
353/// Client for the Autonomi decentralized network.
354///
355/// Provides high-level APIs for storing and retrieving chunks
356/// and files on the network.
357pub struct Client {
358 config: ClientConfig,
359 network: Network,
360 wallet: Option<Arc<Wallet>>,
361 evm_network: Option<ant_protocol::evm::Network>,
362 chunk_cache: ChunkCache,
363 next_request_id: AtomicU64,
364 /// Adaptive concurrency controller: replaces the static
365 /// quote/store concurrency knobs. See `adaptive` module.
366 controller: AdaptiveController,
367 /// Path the controller persists its snapshot to. `None` disables
368 /// persistence (useful for tests / non-disk environments).
369 persist_path: Option<PathBuf>,
370 /// Path for the persistent client peer cache. `None` disables the cache.
371 peer_cache_path: Option<PathBuf>,
372}
373
374impl Client {
375 /// Create a client connected to the given P2P node.
376 #[must_use]
377 pub fn from_node(node: Arc<P2PNode>, config: ClientConfig) -> Self {
378 Self::from_node_with_peer_cache(node, config, None)
379 }
380
381 /// Create a client connected to the given P2P node and attach an optional
382 /// persistent peer cache path.
383 #[must_use]
384 pub fn from_node_with_peer_cache(
385 node: Arc<P2PNode>,
386 config: ClientConfig,
387 peer_cache_path: Option<PathBuf>,
388 ) -> Self {
389 let network = Network::from_node(node);
390 let (controller, persist_path) = build_controller(&config);
391 Self {
392 config,
393 network,
394 wallet: None,
395 evm_network: None,
396 chunk_cache: ChunkCache::default(),
397 next_request_id: AtomicU64::new(1),
398 controller,
399 persist_path,
400 peer_cache_path,
401 }
402 }
403
404 /// Create a client connected to bootstrap peers.
405 ///
406 /// Threads `config.allow_loopback` and `config.ipv6` through to
407 /// `Network::new`, which controls the saorsa-transport `local` and
408 /// `ipv6` flags on the underlying `CoreNodeConfig`. See
409 /// `ClientConfig::allow_loopback` and `ClientConfig::ipv6` for details.
410 ///
411 /// # Errors
412 ///
413 /// Returns an error if the P2P node cannot be created or bootstrapping fails.
414 pub async fn connect(
415 bootstrap_peers: &[std::net::SocketAddr],
416 config: ClientConfig,
417 ) -> Result<Self> {
418 debug!(
419 "Connecting to Autonomi network with {} bootstrap peers (allow_loopback={}, ipv6={})",
420 bootstrap_peers.len(),
421 config.allow_loopback,
422 config.ipv6,
423 );
424 let network = Network::new(bootstrap_peers, config.allow_loopback, config.ipv6).await?;
425 let (controller, persist_path) = build_controller(&config);
426 Ok(Self {
427 config,
428 network,
429 wallet: None,
430 evm_network: None,
431 chunk_cache: ChunkCache::default(),
432 next_request_id: AtomicU64::new(1),
433 controller,
434 persist_path,
435 peer_cache_path: None,
436 })
437 }
438
439 /// Set the wallet for payment operations.
440 ///
441 /// Also populates the EVM network from the wallet so that
442 /// token approvals work without a separate `with_evm_network` call.
443 #[must_use]
444 pub fn with_wallet(mut self, wallet: Wallet) -> Self {
445 self.evm_network = Some(wallet.network().clone());
446 self.wallet = Some(Arc::new(wallet));
447 self
448 }
449
450 /// Set the EVM network without requiring a wallet.
451 ///
452 /// This enables token approval and contract interactions
453 /// for external-signer flows where the private key lives outside Rust.
454 #[must_use]
455 pub fn with_evm_network(mut self, network: ant_protocol::evm::Network) -> Self {
456 self.evm_network = Some(network);
457 self
458 }
459
460 /// Get the EVM network, falling back to the wallet's network if available.
461 ///
462 /// # Errors
463 ///
464 /// Returns an error if neither `with_evm_network` nor `with_wallet` was called.
465 pub(crate) fn require_evm_network(&self) -> Result<&ant_protocol::evm::Network> {
466 if let Some(ref net) = self.evm_network {
467 return Ok(net);
468 }
469 if let Some(ref wallet) = self.wallet {
470 return Ok(wallet.network());
471 }
472 Err(Error::Payment(
473 "EVM network not configured — call with_evm_network() or with_wallet() first"
474 .to_string(),
475 ))
476 }
477
478 /// Get the client configuration.
479 #[must_use]
480 pub fn config(&self) -> &ClientConfig {
481 &self.config
482 }
483
484 /// Get a mutable reference to the client configuration.
485 pub fn config_mut(&mut self) -> &mut ClientConfig {
486 &mut self.config
487 }
488
489 /// Get a reference to the network layer.
490 #[must_use]
491 pub fn network(&self) -> &Network {
492 &self.network
493 }
494
495 /// Get the wallet, if configured.
496 #[must_use]
497 pub fn wallet(&self) -> Option<&Arc<Wallet>> {
498 self.wallet.as_ref()
499 }
500
501 /// Get a reference to the chunk cache.
502 #[must_use]
503 pub fn chunk_cache(&self) -> &ChunkCache {
504 &self.chunk_cache
505 }
506
507 /// Adaptive concurrency controller. Hot loops read
508 /// `controller().<channel>.current()` to size their fan-out and
509 /// call `.observe(...)` on each completion.
510 #[must_use]
511 pub fn controller(&self) -> &AdaptiveController {
512 &self.controller
513 }
514
515 /// Persist the current adaptive snapshot to disk so the next
516 /// `Client::connect` warm-starts at the learned values instead of
517 /// cold defaults. Best effort — failures log and are discarded.
518 /// Idempotent. Safe to call from a Drop impl or an explicit
519 /// shutdown hook.
520 pub fn save_adaptive_snapshot(&self) {
521 if let Some(ref path) = self.persist_path {
522 adaptive::save_snapshot(path, self.controller.snapshot());
523 }
524 }
525
526 /// Persist currently connected peers that have Direct-tagged addresses in
527 /// the DHT. Best effort; failures are logged and do not affect the client
528 /// operation that just completed.
529 pub async fn save_peer_cache(&self) {
530 if let Some(ref path) = self.peer_cache_path {
531 let node = self.network().node();
532 peer_cache::promote_connected_direct_peers(node.as_ref(), path, node.dht().k_value())
533 .await;
534 }
535 }
536
537 /// Get the next request ID for protocol messages.
538 pub(crate) fn next_request_id(&self) -> u64 {
539 self.next_request_id.fetch_add(1, Ordering::Relaxed)
540 }
541
542 /// Return the chunk PUT-target set: the closest [`PUT_TARGET_WIDTH`] peers
543 /// to the address, each paired with its known network addresses.
544 ///
545 /// Used by the merkle store path, which — unlike single-node payment — has
546 /// no witnessed put-target list to forward, so it fetches the closest-K
547 /// neighbourhood locally.
548 pub(crate) async fn put_target_peers(
549 &self,
550 target: &XorName,
551 ) -> Result<Vec<(PeerId, Vec<MultiAddr>)>> {
552 self.closest_peers(target, PUT_TARGET_WIDTH).await
553 }
554
555 /// Return the requested number of closest peers for a target address.
556 ///
557 /// Queries the DHT for peers by XOR distance. Returns each peer
558 /// paired with its known network addresses.
559 pub(crate) async fn closest_peers(
560 &self,
561 target: &XorName,
562 count: usize,
563 ) -> Result<Vec<(PeerId, Vec<MultiAddr>)>> {
564 let peers = self.network().find_closest_peers(target, count).await?;
565
566 if peers.is_empty() {
567 return Err(Error::InsufficientPeers(
568 "DHT returned no peers for target address".to_string(),
569 ));
570 }
571 Ok(peers)
572 }
573}
574
575/// Persist the adaptive snapshot when the `Client` is dropped, so any
576/// caller — CLI, daemon, library user, integration test — gets
577/// warm-start carry-over for free without remembering to call
578/// `save_adaptive_snapshot()` explicitly. Best effort, sync `std::fs`,
579/// no panic risk on a poisoned mutex (the inner helper handles it).
580///
581/// We deliberately write SYNCHRONOUSLY (not via `spawn_blocking`)
582/// because Drop runs during process shutdown / runtime teardown,
583/// when fire-and-forget background tasks can be dropped before they
584/// complete and the snapshot is silently lost. A small synchronous
585/// stall on a tokio worker (typically <1ms for a local-disk JSON
586/// write of ~50 bytes) is the right tradeoff for guaranteed
587/// persistence — BOUNDED by `DROP_SAVE_TIMEOUT` so a stalled
588/// network-mounted data dir cannot block process shutdown.
589const DROP_SAVE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500);
590
591impl Drop for Client {
592 fn drop(&mut self) {
593 let Some(path) = self.persist_path.clone() else {
594 return;
595 };
596 let snap = self.controller.snapshot();
597 adaptive::save_snapshot_with_timeout(path, snap, DROP_SAVE_TIMEOUT);
598 }
599}
600
601#[cfg(test)]
602#[allow(clippy::unwrap_used)]
603mod tests {
604 use super::*;
605
606 /// Cover EVERY variant of `data::error::Error`. Build an instance of
607 /// each, classify it, and assert the resulting `Outcome` matches the
608 /// only sensible mapping. If a future commit adds a new error variant
609 /// without updating `classify_error`, this test fails to ensure the
610 /// adaptive controller always sees correct capacity signals.
611 ///
612 /// Mapping policy (mirrors `classify_error` doc):
613 /// - `Timeout` -> `Outcome::Timeout`
614 /// - `Network`, `InsufficientPeers`, `Io`, `Protocol`, `Storage`,
615 /// `PartialUpload` -> `Outcome::NetworkError` (transport-related
616 /// or literal capacity failure)
617 /// - everything else -> `Outcome::ApplicationError` (would happen
618 /// on a perfectly healthy network)
619 #[test]
620 fn classify_error_covers_all_variants() {
621 let cases: Vec<(Error, Outcome)> = vec![
622 (Error::Timeout("t".to_string()), Outcome::Timeout),
623 (Error::Network("n".to_string()), Outcome::NetworkError),
624 (
625 Error::InsufficientPeers("p".to_string()),
626 Outcome::NetworkError,
627 ),
628 (Error::Storage("s".to_string()), Outcome::NetworkError),
629 (Error::Payment("p".to_string()), Outcome::ApplicationError),
630 (Error::Protocol("p".to_string()), Outcome::NetworkError),
631 (
632 Error::InvalidData("d".to_string()),
633 Outcome::ApplicationError,
634 ),
635 // A definitively absent record over a working link — the peers
636 // answered, nothing was stored there. Must NOT register as a
637 // capacity signal.
638 (
639 Error::NotFound("missing".to_string()),
640 Outcome::ApplicationError,
641 ),
642 (
643 Error::Serialization("s".to_string()),
644 Outcome::ApplicationError,
645 ),
646 (Error::Crypto("c".to_string()), Outcome::ApplicationError),
647 (
648 Error::Io(std::io::Error::other("io")),
649 Outcome::NetworkError,
650 ),
651 (Error::Config("c".to_string()), Outcome::ApplicationError),
652 (
653 Error::SignatureVerification("s".to_string()),
654 Outcome::ApplicationError,
655 ),
656 (
657 Error::Encryption("e".to_string()),
658 Outcome::ApplicationError,
659 ),
660 (Error::AlreadyStored, Outcome::ApplicationError),
661 (
662 Error::InsufficientDiskSpace("d".to_string()),
663 Outcome::ApplicationError,
664 ),
665 (
666 Error::CostEstimationInconclusive("c".to_string()),
667 Outcome::ApplicationError,
668 ),
669 (
670 Error::PartialUpload {
671 stored: vec![],
672 stored_count: 0,
673 failed: vec![],
674 failed_count: 0,
675 total_chunks: 0,
676 spend: Box::new(crate::data::error::PartialUploadSpend {
677 storage_cost_atto: "0".to_string(),
678 gas_cost_wei: 0,
679 }),
680 reason: "r".to_string(),
681 },
682 Outcome::NetworkError,
683 ),
684 (
685 Error::BadQuoteBinding {
686 peer_id: "peer".to_string(),
687 detail: "mismatch".to_string(),
688 },
689 Outcome::ApplicationError,
690 ),
691 // A remote application rejection: the node responded with a
692 // structured `ProtocolError`, so the transport succeeded and
693 // this must NOT register as a capacity signal (V2-468).
694 (
695 Error::RemotePut {
696 address: "abcd".to_string(),
697 source: ant_protocol::ProtocolError::PaymentFailed("stale quote".to_string()),
698 },
699 Outcome::ApplicationError,
700 ),
701 // A close-group quorum shortfall caused by dial/relay churn with
702 // no PUT-response timeouts — remote peer churn, not local
703 // backpressure, so it must NOT register as a capacity signal
704 // (V2-554). A timeout-bearing shortfall keeps `InsufficientPeers`.
705 (
706 Error::CloseGroupShortfall("Stored on 3 peers, need 4".to_string()),
707 Outcome::ApplicationError,
708 ),
709 // Refusing an oversized external-signer merkle batch happens
710 // before any network work, so it is not a capacity signal.
711 (
712 Error::MerkleBatchTooLarge {
713 addresses: 257,
714 max_leaves: 256,
715 },
716 Outcome::ApplicationError,
717 ),
718 ];
719 for (err, expected) in &cases {
720 let got = classify_error(err);
721 assert_eq!(
722 got, *expected,
723 "classify_error({err:?}) = {got:?}, expected {expected:?}",
724 );
725 }
726 }
727
728 /// C4 fix guard: pinning the legacy `quote_concurrency` /
729 /// `store_concurrency` ClientConfig fields must clamp ONLY the
730 /// matching channel's max in the resulting controller. The fetch
731 /// (download) channel must keep its full default ceiling.
732 #[test]
733 fn legacy_concurrency_pin_does_not_bleed_across_channels() {
734 let cfg = ClientConfig {
735 quote_concurrency: 4,
736 store_concurrency: 2,
737 ..ClientConfig::default()
738 };
739 let (controller, _) = build_controller(&cfg);
740 // The store/quote caps must be clamped to the user's pin.
741 assert_eq!(controller.config.max.quote, 4, "quote pin not respected");
742 assert_eq!(controller.config.max.store, 2, "store pin not respected");
743 // The fetch cap must NOT have been lowered — that's the
744 // regression C4 was about.
745 let default_fetch_max = adaptive::ChannelMax::default().fetch;
746 assert_eq!(
747 controller.config.max.fetch, default_fetch_max,
748 "fetch cap was lowered by store/quote pin (C4 regression)"
749 );
750 // Cold-start values must respect the lowered ceilings.
751 assert!(
752 controller.quote.current() <= 4,
753 "quote start exceeds its cap"
754 );
755 assert!(
756 controller.store.current() <= 2,
757 "store start exceeds its cap"
758 );
759 }
760
761 /// Default ClientConfig must NOT silently lower the controller's
762 /// per-channel ceilings — the adaptive defaults give every channel
763 /// real headroom to grow. This guards against future commits
764 /// re-introducing a global clamp.
765 #[test]
766 fn default_client_config_does_not_clamp_controller_max() {
767 let cfg = ClientConfig::default();
768 let (controller, _) = build_controller(&cfg);
769 let defaults = adaptive::ChannelMax::default();
770 // The legacy fields default to 32/8 (the prior static knobs),
771 // both of which are <= the per-channel adaptive defaults
772 // (128/64). build_controller must keep the larger, not clobber
773 // with the legacy values.
774 assert_eq!(controller.config.max.quote, defaults.quote);
775 assert_eq!(controller.config.max.store, defaults.store);
776 assert_eq!(controller.config.max.fetch, defaults.fetch);
777 // Compile-time-ish guard: if a new variant is added to Error,
778 // this match forces an update here.
779 let _ = |e: &Error| match e {
780 Error::Timeout(_)
781 | Error::Network(_)
782 | Error::InsufficientPeers(_)
783 | Error::Storage(_)
784 | Error::Payment(_)
785 | Error::Protocol(_)
786 | Error::InvalidData(_)
787 | Error::NotFound(_)
788 | Error::Serialization(_)
789 | Error::Crypto(_)
790 | Error::Io(_)
791 | Error::Config(_)
792 | Error::SignatureVerification(_)
793 | Error::Encryption(_)
794 | Error::AlreadyStored
795 | Error::InsufficientDiskSpace(_)
796 | Error::CostEstimationInconclusive(_)
797 | Error::Cancelled(_)
798 | Error::PartialUpload { .. }
799 | Error::BadQuoteBinding { .. }
800 | Error::BadQuoteCommitment { .. }
801 | Error::MerkleBatchTooLarge { .. }
802 | Error::RemotePut { .. }
803 | Error::CloseGroupShortfall(_) => (),
804 };
805 }
806}