toolkit_contract/wiring.rs
1//! `ClientWiring` — typed config schema consumed by `#[toolkit::provides]`.
2//!
3//! Lives outside the feature-gated `runtime` module so the deserialization
4//! itself is always available: any module loaded into the host must be able
5//! to parse its wiring config regardless of which transport features its
6//! provider SDK compiled in. The actual conversion to a runtime
7//! [`ClientConfig`](crate::runtime::config::ClientConfig) is gated on
8//! `runtime-client`.
9
10use std::time::Duration;
11
12use serde::Deserialize;
13
14/// Fine-tuning knobs forwarded to the transport client when a remote
15/// transport is selected. All fields are optional — missing values fall
16/// back to the SDK defaults baked into
17/// [`ClientConfig`](crate::runtime::config::ClientConfig).
18#[derive(Clone, Debug, Default, Deserialize)]
19pub struct ClientTuning {
20 /// Per-call request deadline (e.g., `"5s"`, `"500ms"`).
21 #[serde(default, with = "toolkit_utils::humantime_serde::option")]
22 pub timeout: Option<Duration>,
23
24 /// Override for the retry policy applied to `#[retryable]` methods.
25 #[serde(default)]
26 pub retry: Option<RetrySettings>,
27
28 /// Override for the stream reconnect policy, of any framing.
29 ///
30 /// `alias = "sse_reconnect"` keeps already-deployed config files working:
31 /// this struct has no `rename_all`, so the Rust field name *is* the JSON
32 /// key, and the field was called `sse_reconnect` before the policy covered
33 /// framings other than SSE.
34 ///
35 /// Supplying **both** `stream_reconnect` and `sse_reconnect` is rejected as
36 /// a duplicate field — the two name the same field — so a config that adds
37 /// the new key without removing the legacy one fails loudly at parse time
38 /// rather than silently honouring one and dropping the other. This holds
39 /// even though the field is `#[serde(flatten)]`-ed into [`ClientWiring`].
40 #[serde(default, alias = "sse_reconnect")]
41 pub stream_reconnect: Option<ReconnectSettings>,
42
43 /// Reject plaintext `http://` endpoints.
44 ///
45 /// Defaults to `false` (the in-mesh convention), or `true` when
46 /// `toolkit-http/fips` is enabled; there `require_tls: false` is the
47 /// explicit opt-in to plaintext and logs a warning. Without this knob a
48 /// discovery-resolved client always got the default, so a consumer talking
49 /// to an endpoint outside a trusted boundary had no way to demand TLS —
50 /// while forwarding a tenant bearer token over it.
51 #[serde(default)]
52 pub require_tls: Option<bool>,
53
54 /// Circuit breaker for each endpoint this client calls. Missing keeps the
55 /// defaults (on: opens when at least half of at least 10 calls in 30s
56 /// failed at the transport level, open for 10s, then one probe);
57 /// `{ enabled: false }` turns it off. Unknown keys and invalid values are
58 /// rejected at parse time.
59 #[cfg(feature = "runtime-client")]
60 #[serde(default)]
61 pub circuit_breaker: Option<toolkit_resilience::circuit_breaker::CircuitBreakerConfig>,
62
63 /// Max idle keep-alive connections per upstream host. Raise this to at least
64 /// the expected per-upstream request concurrency so HTTP/1.1 connections are
65 /// reused instead of churned under load. Missing keeps the SDK default
66 /// ([`ClientConfig::pool_max_idle_per_host`](crate::runtime::config::ClientConfig::pool_max_idle_per_host)).
67 ///
68 /// **REST transport only.** A gRPC client accepts this key but it has no
69 /// effect (a warning is logged when such a client is wired).
70 #[serde(default)]
71 pub pool_max_idle_per_host: Option<usize>,
72
73 /// How long idle keep-alive connections are retained (e.g. `"90s"`, `"2m"`)
74 /// before being closed and reopened on the next request. Companion of
75 /// `pool_max_idle_per_host`; raise it above the gap between successive bursts
76 /// to a given upstream to keep connections warm. Missing keeps the SDK
77 /// default ([`ClientConfig::pool_idle_timeout`](crate::runtime::config::ClientConfig::pool_idle_timeout)).
78 ///
79 /// **REST transport only** (see `pool_max_idle_per_host`).
80 #[serde(default, with = "toolkit_utils::humantime_serde::option")]
81 pub pool_idle_timeout: Option<Duration>,
82
83 /// Max concurrent in-flight requests through this client at once. Requests
84 /// beyond the cap are shed immediately (`HttpError::Overloaded`). Keep it at
85 /// or above `pool_max_idle_per_host` so the pool can be fully reused. Missing
86 /// keeps the SDK default
87 /// ([`ClientConfig::max_concurrent_requests`](crate::runtime::config::ClientConfig::max_concurrent_requests)).
88 ///
89 /// **REST transport only** (see `pool_max_idle_per_host`).
90 #[serde(default)]
91 pub max_concurrent_requests: Option<usize>,
92
93 /// Platform-plane credential source forwarded onto the built
94 /// [`ClientConfig`](crate::runtime::config::ClientConfig). Injected by the
95 /// runtime's proxy-wiring phase, never from config (`#[serde(skip)]`); gated
96 /// on `runtime-client` since the type lives there.
97 #[cfg(feature = "runtime-client")]
98 #[serde(skip)]
99 pub internal_token_provider: Option<crate::runtime::config::InternalTokenProvider>,
100}
101
102impl ClientTuning {
103 /// Every key a [`ClientTuning`] reads. It is flattened into
104 /// [`ConsumerWiring`] and [`ClientWiring`], so serde cannot reject unknown
105 /// keys there; the config reader checks against this list instead.
106 pub const KEYS: &'static [&'static str] = &[
107 "timeout",
108 "retry",
109 "stream_reconnect",
110 "sse_reconnect",
111 "require_tls",
112 "circuit_breaker",
113 "pool_max_idle_per_host",
114 "pool_idle_timeout",
115 "max_concurrent_requests",
116 ];
117
118 /// The knobs set on this tuning that a gRPC client does not apply.
119 ///
120 /// Used to warn when a gRPC client is wired: it reads the endpoint,
121 /// `timeout`, `retry`, `require_tls` and `circuit_breaker`. The pool and
122 /// concurrency knobs are REST-only, and gRPC streams do not reconnect yet,
123 /// so `stream_reconnect` (or `sse_reconnect`) is not applied either.
124 /// Returns their names (empty when none are set).
125 #[must_use]
126 pub fn grpc_ignored_knobs(&self) -> Vec<&'static str> {
127 let mut set = Vec::new();
128 if self.stream_reconnect.is_some() {
129 set.push("stream_reconnect");
130 }
131 if self.pool_max_idle_per_host.is_some() {
132 set.push("pool_max_idle_per_host");
133 }
134 if self.pool_idle_timeout.is_some() {
135 set.push("pool_idle_timeout");
136 }
137 if self.max_concurrent_requests.is_some() {
138 set.push("max_concurrent_requests");
139 }
140 set
141 }
142}
143
144/// Deserializable mirror of
145/// [`RetryConfig`](crate::runtime::config::RetryConfig). All fields optional;
146/// missing values keep the runtime default.
147#[derive(Clone, Debug, Default, Deserialize)]
148#[serde(deny_unknown_fields)]
149pub struct RetrySettings {
150 pub max_attempts: Option<u32>,
151 #[serde(default, with = "toolkit_utils::humantime_serde::option")]
152 pub base_delay: Option<Duration>,
153 #[serde(default, with = "toolkit_utils::humantime_serde::option")]
154 pub max_delay: Option<Duration>,
155 pub multiplier: Option<f64>,
156}
157
158/// Deserializable mirror of
159/// [`ReconnectConfig`](crate::runtime::config::ReconnectConfig).
160#[derive(Clone, Debug, Default, Deserialize)]
161#[serde(deny_unknown_fields)]
162pub struct ReconnectSettings {
163 pub max_attempts: Option<u32>,
164 #[serde(default, with = "toolkit_utils::humantime_serde::option")]
165 pub base_delay: Option<Duration>,
166 #[serde(default, with = "toolkit_utils::humantime_serde::option")]
167 pub max_delay: Option<Duration>,
168}
169
170/// Transport choice + endpoint + tuning for one provided contract.
171///
172/// Read by `#[toolkit::provides]` from
173/// `gears.<gear>.clients.provides.<contract_snake>`, with
174/// `gears.<gear>.clients.defaults` merged under it. If the key is absent the
175/// wiring defaults to [`ClientWiring::Local`].
176#[derive(Clone, Debug, Default, Deserialize)]
177#[serde(rename_all = "lowercase", tag = "transport")]
178pub enum ClientWiring {
179 /// In-process. The provider gear's local factory is invoked.
180 #[default]
181 Local,
182 /// Generated REST client points at `endpoint`.
183 Rest {
184 endpoint: String,
185 #[serde(default, flatten)]
186 tuning: ClientTuning,
187 },
188 /// Generated gRPC client connects to `endpoint`.
189 Grpc {
190 endpoint: String,
191 #[serde(default, flatten)]
192 tuning: ClientTuning,
193 },
194}
195
196/// Whether `s` is an absolute URI (scheme + authority) — the shape a usable
197/// static endpoint override must have. A bare host, relative path or empty string
198/// would otherwise be marked resolved with no probe (`/readyz` 200 while every
199/// call fails). Enforced at parse time by [`ConsumerWiring`]'s `endpoint` deserializer.
200#[must_use]
201fn is_absolute_endpoint(s: &str) -> bool {
202 s.parse::<http::Uri>()
203 .is_ok_and(|uri| uri.scheme().is_some() && uri.authority().is_some())
204}
205
206/// `deserialize_with` for [`ConsumerWiring::endpoint`]: keeps the field a plain
207/// `Option<String>` while rejecting a present, non-absolute value at parse time
208/// (see [`is_absolute_endpoint`]).
209fn deserialize_optional_endpoint<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
210where
211 D: serde::Deserializer<'de>,
212{
213 let endpoint = Option::<String>::deserialize(deserializer)?;
214 if let Some(ref s) = endpoint
215 && !is_absolute_endpoint(s)
216 {
217 return Err(serde::de::Error::custom(format!(
218 "`{s}` is not an absolute URI (needs scheme + host, e.g. `http://host:port`)"
219 )));
220 }
221 Ok(endpoint)
222}
223
224/// Consumer-side wiring for one dependency, read from
225/// `gears.<owner>.clients.consumes.<dep>` (with `gears.<owner>.clients.defaults`
226/// merged under it) by the runtime's proxy-wiring phase and applied to the
227/// directory-resolving client that `#[toolkit::consumes]` registers.
228///
229/// An object with an optional `endpoint` (omit to keep discovery) plus a
230/// flattened [`ClientTuning`]:
231///
232/// ```yaml
233/// clients:
234/// consumes:
235/// api-contracts:
236/// timeout: "5s"
237/// max_concurrent_requests: 256
238/// # endpoint: "http://..." # optional; omit to keep discovery
239/// # grpc_endpoint: "http://..." # optional; for gRPC clients of this dep
240/// ```
241///
242/// Unlike [`ClientWiring`] there is **no** `transport` tag: the transport is
243/// chosen in code (`#[toolkit::consumes(.., transport = grpc)]`). A gRPC client
244/// uses `grpc_endpoint` when set, else `endpoint`; it ignores the REST-only
245/// pool and concurrency knobs and `stream_reconnect` (see
246/// [`ClientTuning::grpc_ignored_knobs`]).
247///
248/// Must be an object; a bare `<dep>: "http://host"` string (the old shape) is
249/// rejected at parse time — use the `endpoint` field.
250#[derive(Clone, Debug, Default, Deserialize)]
251pub struct ConsumerWiring {
252 /// Static-endpoint override (ADR-0004 dev/test escape hatch): when set, the
253 /// dep is wired to this fixed endpoint instead of being discovered. Rejected
254 /// at parse time unless it is an absolute URI (see [`is_absolute_endpoint`]).
255 #[serde(default, deserialize_with = "deserialize_optional_endpoint")]
256 pub endpoint: Option<String>,
257 /// Static-endpoint override for gRPC clients of this dep, when they must
258 /// not use `endpoint` (a gear that consumes the dep over both REST and
259 /// gRPC). Validated like `endpoint`.
260 #[serde(default, deserialize_with = "deserialize_optional_endpoint")]
261 pub grpc_endpoint: Option<String>,
262 /// Client tuning, flattened into the same map as `endpoint`.
263 #[serde(default, flatten)]
264 pub tuning: ClientTuning,
265}
266
267impl ConsumerWiring {
268 /// Split the wiring into its static-endpoint override (if any) and the
269 /// [`ClientTuning`] to apply.
270 #[must_use]
271 pub fn into_parts(self) -> (Option<String>, ClientTuning) {
272 (self.endpoint, self.tuning)
273 }
274}
275
276#[cfg(feature = "runtime-client")]
277impl ClientTuning {
278 /// `require_tls` with the default applied: an unset value is `false`, or
279 /// `true` when `toolkit-http/fips` is on. Use this instead of reading the
280 /// `Option` directly; [`Self::apply_to`] resolves it the same way.
281 #[must_use]
282 pub fn effective_require_tls(&self) -> bool {
283 self.require_tls
284 .unwrap_or_else(crate::runtime::config::default_require_tls)
285 }
286
287 /// Apply tuning overrides onto a fresh [`ClientConfig`] built from `endpoint`.
288 #[must_use]
289 pub fn apply_to(&self, endpoint: impl Into<String>) -> crate::runtime::config::ClientConfig {
290 use crate::runtime::config::{ClientConfig, ReconnectConfig, RetryConfig};
291
292 let mut cfg = ClientConfig::new(endpoint);
293 if let Some(timeout) = self.timeout {
294 cfg = cfg.with_timeout(timeout);
295 }
296 if let Some(ref r) = self.retry {
297 let base = cfg.retry.clone();
298 cfg = cfg.with_retry(RetryConfig {
299 max_attempts: r.max_attempts.unwrap_or(base.max_attempts),
300 base_delay: r.base_delay.unwrap_or(base.base_delay),
301 max_delay: r.max_delay.unwrap_or(base.max_delay),
302 multiplier: r.multiplier.unwrap_or(base.multiplier),
303 });
304 }
305 if let Some(ref s) = self.stream_reconnect {
306 let base = cfg.stream_reconnect.clone();
307 cfg = cfg.with_stream_reconnect(ReconnectConfig {
308 max_attempts: s.max_attempts.unwrap_or(base.max_attempts),
309 base_delay: s.base_delay.unwrap_or(base.base_delay),
310 max_delay: s.max_delay.unwrap_or(base.max_delay),
311 // Not exposed as wiring keys yet; inherit the base policy.
312 min_healthy_uptime: base.min_healthy_uptime,
313 max_total_reopens: base.max_total_reopens,
314 });
315 }
316 if let Some(require_tls) = self.require_tls {
317 cfg = cfg.with_require_tls(require_tls);
318 }
319 if let Some(max) = self.pool_max_idle_per_host {
320 cfg = cfg.with_pool_max_idle_per_host(max);
321 }
322 if let Some(timeout) = self.pool_idle_timeout {
323 cfg = cfg.with_pool_idle_timeout(Some(timeout));
324 }
325 if let Some(max) = self.max_concurrent_requests {
326 cfg = cfg.with_max_concurrent_requests(Some(max));
327 }
328 cfg = cfg.with_internal_token_provider(self.internal_token_provider.clone());
329 cfg
330 }
331
332 /// The circuit breaker this tuning asks for, named `name` in logs and
333 /// rejections; `None` when it is turned off.
334 #[must_use]
335 pub fn circuit_breaker_for(
336 &self,
337 name: &str,
338 ) -> Option<std::sync::Arc<toolkit_resilience::circuit_breaker::CircuitBreaker>> {
339 use toolkit_resilience::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig};
340
341 let config = self.circuit_breaker.clone().unwrap_or_default();
342 if !config.enabled() {
343 return None;
344 }
345 // Parsed configs are validated already; a hand-built invalid one runs
346 // with the defaults rather than without a breaker.
347 let breaker = CircuitBreaker::new(config).or_else(|err| {
348 tracing::warn!(breaker = name, error = %err, "invalid circuit breaker config; using defaults");
349 CircuitBreaker::new(CircuitBreakerConfig::default())
350 });
351 breaker.ok().map(|b| std::sync::Arc::new(b.with_name(name)))
352 }
353
354 /// Attach the platform-plane credential source forwarded onto the built
355 /// [`ClientConfig`](crate::runtime::config::ClientConfig). Used by the
356 /// proxy-wiring phase to thread the process credential into a
357 /// directory-resolving (`#[toolkit::consumes]`) client.
358 #[must_use]
359 pub fn with_internal_token_provider(
360 mut self,
361 provider: Option<crate::runtime::config::InternalTokenProvider>,
362 ) -> Self {
363 self.internal_token_provider = provider;
364 self
365 }
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371
372 /// A static override is only usable if it is an absolute URI. An empty string,
373 /// a bare host, or a relative path would otherwise reach the wiring code, take
374 /// the static branch, and mark the dep resolved with no probe — 200 on
375 /// `/readyz` while every call fails.
376 #[test]
377 fn is_absolute_endpoint_accepts_only_scheme_plus_authority() {
378 assert!(is_absolute_endpoint("http://host:8081"));
379 assert!(is_absolute_endpoint("https://billing.svc/base"));
380 assert!(!is_absolute_endpoint(""));
381 assert!(!is_absolute_endpoint("billing"));
382 assert!(!is_absolute_endpoint("/path/only"));
383 assert!(!is_absolute_endpoint("not a uri"));
384 }
385
386 /// `ConsumerWiring` validates the endpoint at parse time: a present-but-invalid
387 /// value fails to deserialize (rather than yielding an unchecked string), the
388 /// valid value survives verbatim, and an omitted `endpoint` keeps discovery
389 /// while still parsing the tuning.
390 #[test]
391 fn consumer_wiring_validates_endpoint_on_deserialize() {
392 let ok: ConsumerWiring = serde_json::from_value(serde_json::json!({
393 "endpoint": "http://billing:8080",
394 "max_concurrent_requests": 256
395 }))
396 .expect("valid absolute endpoint must parse");
397 let (endpoint, tuning) = ok.into_parts();
398 assert_eq!(endpoint.as_deref(), Some("http://billing:8080"));
399 assert_eq!(tuning.max_concurrent_requests, Some(256));
400
401 assert!(
402 serde_json::from_value::<ConsumerWiring>(serde_json::json!({ "endpoint": "" }))
403 .is_err(),
404 "an empty endpoint must be rejected at deserialize time"
405 );
406 assert!(
407 serde_json::from_value::<ConsumerWiring>(serde_json::json!({ "endpoint": "billing" }))
408 .is_err(),
409 "a bare host must be rejected at deserialize time"
410 );
411
412 let no_endpoint: ConsumerWiring =
413 serde_json::from_value(serde_json::json!({ "max_concurrent_requests": 1 }))
414 .expect("omitted endpoint keeps discovery");
415 assert_eq!(no_endpoint.endpoint, None);
416 assert_eq!(no_endpoint.tuning.max_concurrent_requests, Some(1));
417 }
418}