ic_agent/agent/
builder.rs

1use crate::{
2    agent::{agent_config::AgentConfig, Agent},
3    AgentError, Identity, NonceFactory, NonceGenerator,
4};
5use std::sync::Arc;
6
7use super::{route_provider::RouteProvider, HttpService};
8
9/// A builder for an [`Agent`].
10#[derive(Default)]
11pub struct AgentBuilder {
12    config: AgentConfig,
13}
14
15impl AgentBuilder {
16    /// Create an instance of [Agent] with the information from this builder.
17    pub fn build(self) -> Result<Agent, AgentError> {
18        Agent::new(self.config)
19    }
20
21    /// Set the dynamic transport layer for the [`Agent`], performing continuous discovery of the API boundary nodes
22    /// and routing traffic via them based on latency. Cannot be set together with `with_route_provider`.
23    ///
24    /// See [`DynamicRouteProvider`](super::route_provider::DynamicRouteProvider) if more customization is needed such as polling intervals.
25    pub fn with_background_dynamic_routing(mut self) -> Self {
26        assert!(
27            self.config.route_provider.is_none(),
28            "with_background_dynamic_routing cannot be called with with_route_provider"
29        );
30        self.config.background_dynamic_routing = true;
31        self
32    }
33
34    /// Set the URL of the [`Agent`]. Either this or `with_route_provider` must be called (but not both).
35    pub fn with_url<S: Into<String>>(mut self, url: S) -> Self {
36        assert!(
37            self.config.route_provider.is_none(),
38            "with_url cannot be called with with_route_provider"
39        );
40        self.config.url = Some(url.into().parse().unwrap());
41        self
42    }
43
44    /// Add a `NonceFactory` to this Agent. By default, no nonce is produced.
45    pub fn with_nonce_factory(self, nonce_factory: NonceFactory) -> AgentBuilder {
46        self.with_nonce_generator(nonce_factory)
47    }
48
49    /// Same as [`Self::with_nonce_factory`], but for any `NonceGenerator` type
50    pub fn with_nonce_generator<N: 'static + NonceGenerator>(
51        self,
52        nonce_factory: N,
53    ) -> AgentBuilder {
54        self.with_arc_nonce_generator(Arc::new(nonce_factory))
55    }
56
57    /// Same as [`Self::with_nonce_generator`], but reuses an existing `Arc`.
58    pub fn with_arc_nonce_generator(
59        mut self,
60        nonce_factory: Arc<dyn NonceGenerator>,
61    ) -> AgentBuilder {
62        self.config.nonce_factory = Arc::new(nonce_factory);
63        self
64    }
65
66    /// Add an identity provider for signing messages. This is required.
67    pub fn with_identity<I>(self, identity: I) -> Self
68    where
69        I: 'static + Identity,
70    {
71        self.with_arc_identity(Arc::new(identity))
72    }
73
74    /// Same as [`Self::with_identity`], but reuses an existing box
75    pub fn with_boxed_identity(self, identity: Box<dyn Identity>) -> Self {
76        self.with_arc_identity(Arc::from(identity))
77    }
78
79    /// Same as [`Self::with_identity`], but reuses an existing `Arc`
80    pub fn with_arc_identity(mut self, identity: Arc<dyn Identity>) -> Self {
81        self.config.identity = identity;
82        self
83    }
84
85    /// Provides a _default_ ingress expiry. This is the delta that will be applied
86    /// at the time an update or query is made. The default expiry cannot be a
87    /// fixed system time. This is also used when checking certificate timestamps.
88    ///
89    /// The timestamp corresponding to this duration may be rounded in order to reduce
90    /// cache misses. The current implementation rounds to the nearest minute if the
91    /// expiry is more than a minute, but this is not guaranteed.
92    pub fn with_ingress_expiry(mut self, ingress_expiry: std::time::Duration) -> Self {
93        self.config.ingress_expiry = ingress_expiry;
94        self
95    }
96
97    /// Allows disabling query signature verification. Query signatures improve resilience but require
98    /// a separate read-state call to fetch node keys.
99    pub fn with_verify_query_signatures(mut self, verify_query_signatures: bool) -> Self {
100        self.config.verify_query_signatures = verify_query_signatures;
101        self
102    }
103
104    /// Sets the maximum number of requests that the agent will make concurrently. The replica is configured
105    /// to only permit 50 concurrent requests per client. Set this value lower if you have multiple agents,
106    /// to avoid the slowdown of retrying any 429 errors.
107    pub fn with_max_concurrent_requests(mut self, max_concurrent_requests: usize) -> Self {
108        self.config.max_concurrent_requests = max_concurrent_requests;
109        self
110    }
111
112    /// Add a `RouteProvider` to this agent, to provide the URLs of boundary nodes.
113    pub fn with_route_provider(self, provider: impl RouteProvider + 'static) -> Self {
114        self.with_arc_route_provider(Arc::new(provider))
115    }
116
117    /// Same as [`Self::with_route_provider`], but reuses an existing `Arc`.
118    pub fn with_arc_route_provider(mut self, provider: Arc<dyn RouteProvider>) -> Self {
119        assert!(
120            !self.config.background_dynamic_routing,
121            "with_background_dynamic_routing cannot be called with with_route_provider"
122        );
123        assert!(
124            self.config.url.is_none(),
125            "with_url cannot be called with with_route_provider"
126        );
127        self.config.route_provider = Some(provider);
128        self
129    }
130
131    /// Provide a pre-configured HTTP client to use. Use this to set e.g. HTTP timeouts or proxy configuration.
132    pub fn with_http_client(mut self, client: reqwest::Client) -> Self {
133        assert!(
134            self.config.http_service.is_none(),
135            "with_arc_http_middleware cannot be called with with_http_client"
136        );
137        self.config.client = Some(client);
138        self
139    }
140
141    /// Provide a custom `reqwest`-compatible HTTP service, e.g. to add per-request headers for custom boundary nodes.
142    /// Most users will not need this and should use `with_http_client`. Cannot be called with `with_http_client`.
143    ///
144    /// The trait is automatically implemented for any `tower::Service` impl matching the one `reqwest::Client` uses,
145    /// including `reqwest-middleware`. This is a low-level interface, and direct implementations must provide all automatic retry logic.
146    pub fn with_arc_http_middleware(mut self, service: Arc<dyn HttpService>) -> Self {
147        assert!(
148            self.config.client.is_none(),
149            "with_arc_http_middleware cannot be called with with_http_client"
150        );
151        self.config.http_service = Some(service);
152        self
153    }
154
155    /// Retry up to the specified number of times upon encountering underlying TCP errors.
156    pub fn with_max_tcp_error_retries(mut self, retries: usize) -> Self {
157        self.config.max_tcp_error_retries = retries;
158        self
159    }
160
161    /// Don't accept HTTP bodies any larger than `max_size` bytes.
162    pub fn with_max_response_body_size(mut self, max_size: usize) -> Self {
163        self.config.max_response_body_size = Some(max_size);
164        self
165    }
166    /// Set the maximum time to wait for a response from the replica.
167    pub fn with_max_polling_time(mut self, max_polling_time: std::time::Duration) -> Self {
168        self.config.max_polling_time = max_polling_time;
169        self
170    }
171}