Skip to main content

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