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 /// Max idle keep-alive connections per upstream host. Raise this to at least
55 /// the expected per-upstream request concurrency so HTTP/1.1 connections are
56 /// reused instead of churned under load. Missing keeps the SDK default
57 /// ([`ClientConfig::pool_max_idle_per_host`](crate::runtime::config::ClientConfig::pool_max_idle_per_host)).
58 ///
59 /// **REST transport only.** A `transport: grpc` wiring accepts this key but
60 /// it has no effect — the gRPC client reads only `endpoint`, `timeout` and
61 /// `require_tls` (a warning is logged at gRPC client construction).
62 #[serde(default)]
63 pub pool_max_idle_per_host: Option<usize>,
64
65 /// How long idle keep-alive connections are retained (e.g. `"90s"`, `"2m"`)
66 /// before being closed and reopened on the next request. Companion of
67 /// `pool_max_idle_per_host`; raise it above the gap between successive bursts
68 /// to a given upstream to keep connections warm. Missing keeps the SDK
69 /// default ([`ClientConfig::pool_idle_timeout`](crate::runtime::config::ClientConfig::pool_idle_timeout)).
70 ///
71 /// **REST transport only** (see `pool_max_idle_per_host`).
72 #[serde(default, with = "toolkit_utils::humantime_serde::option")]
73 pub pool_idle_timeout: Option<Duration>,
74
75 /// Max concurrent in-flight requests through this client at once. Requests
76 /// beyond the cap are shed immediately (`HttpError::Overloaded`). Keep it at
77 /// or above `pool_max_idle_per_host` so the pool can be fully reused. Missing
78 /// keeps the SDK default
79 /// ([`ClientConfig::max_concurrent_requests`](crate::runtime::config::ClientConfig::max_concurrent_requests)).
80 ///
81 /// **REST transport only** (see `pool_max_idle_per_host`).
82 #[serde(default)]
83 pub max_concurrent_requests: Option<usize>,
84
85 /// Platform-plane credential source forwarded onto the built
86 /// [`ClientConfig`](crate::runtime::config::ClientConfig). Injected by the
87 /// runtime's proxy-wiring phase, never from config (`#[serde(skip)]`); gated
88 /// on `runtime-client` since the type lives there.
89 #[cfg(feature = "runtime-client")]
90 #[serde(skip)]
91 pub internal_token_provider: Option<crate::runtime::config::InternalTokenProvider>,
92}
93
94impl ClientTuning {
95 /// Every key a [`ClientTuning`] reads. It is flattened into
96 /// [`ConsumerWiring`] and [`ClientWiring`], so serde cannot reject unknown
97 /// keys there; the config reader checks against this list instead.
98 pub const KEYS: &'static [&'static str] = &[
99 "timeout",
100 "retry",
101 "stream_reconnect",
102 "sse_reconnect",
103 "require_tls",
104 "pool_max_idle_per_host",
105 "pool_idle_timeout",
106 "max_concurrent_requests",
107 ];
108
109 /// REST-only transport knobs that were explicitly set on this tuning.
110 ///
111 /// Used to warn when a non-REST transport is selected: the gRPC client reads
112 /// only `endpoint`, `timeout` and `require_tls`, so
113 /// `pool_max_idle_per_host`, `pool_idle_timeout` and
114 /// `max_concurrent_requests` on a `transport: grpc` wiring silently go
115 /// nowhere. Returns their names (empty when none are set).
116 #[must_use]
117 pub fn rest_only_knobs_set(&self) -> Vec<&'static str> {
118 let mut set = Vec::new();
119 if self.pool_max_idle_per_host.is_some() {
120 set.push("pool_max_idle_per_host");
121 }
122 if self.pool_idle_timeout.is_some() {
123 set.push("pool_idle_timeout");
124 }
125 if self.max_concurrent_requests.is_some() {
126 set.push("max_concurrent_requests");
127 }
128 set
129 }
130}
131
132/// Deserializable mirror of
133/// [`RetryConfig`](crate::runtime::config::RetryConfig). All fields optional;
134/// missing values keep the runtime default.
135#[derive(Clone, Debug, Default, Deserialize)]
136#[serde(deny_unknown_fields)]
137pub struct RetrySettings {
138 pub max_attempts: Option<u32>,
139 #[serde(default, with = "toolkit_utils::humantime_serde::option")]
140 pub base_delay: Option<Duration>,
141 #[serde(default, with = "toolkit_utils::humantime_serde::option")]
142 pub max_delay: Option<Duration>,
143 pub multiplier: Option<f64>,
144}
145
146/// Deserializable mirror of
147/// [`ReconnectConfig`](crate::runtime::config::ReconnectConfig).
148#[derive(Clone, Debug, Default, Deserialize)]
149#[serde(deny_unknown_fields)]
150pub struct ReconnectSettings {
151 pub max_attempts: Option<u32>,
152 #[serde(default, with = "toolkit_utils::humantime_serde::option")]
153 pub base_delay: Option<Duration>,
154 #[serde(default, with = "toolkit_utils::humantime_serde::option")]
155 pub max_delay: Option<Duration>,
156}
157
158/// Transport choice + endpoint + tuning for one provided contract.
159///
160/// Read by `#[toolkit::provides]` from
161/// `gears.<gear>.clients.provides.<contract_snake>`, with
162/// `gears.<gear>.clients.defaults` merged under it. If the key is absent the
163/// wiring defaults to [`ClientWiring::Local`].
164#[derive(Clone, Debug, Default, Deserialize)]
165#[serde(rename_all = "lowercase", tag = "transport")]
166pub enum ClientWiring {
167 /// In-process. The provider gear's local factory is invoked.
168 #[default]
169 Local,
170 /// Generated REST client points at `endpoint`.
171 Rest {
172 endpoint: String,
173 #[serde(default, flatten)]
174 tuning: ClientTuning,
175 },
176 /// Generated gRPC client connects to `endpoint`.
177 Grpc {
178 endpoint: String,
179 #[serde(default, flatten)]
180 tuning: ClientTuning,
181 },
182}
183
184/// Whether `s` is an absolute URI (scheme + authority) — the shape a usable
185/// static endpoint override must have. A bare host, relative path or empty string
186/// would otherwise be marked resolved with no probe (`/readyz` 200 while every
187/// call fails). Enforced at parse time by [`ConsumerWiring`]'s `endpoint` deserializer.
188#[must_use]
189fn is_absolute_endpoint(s: &str) -> bool {
190 s.parse::<http::Uri>()
191 .is_ok_and(|uri| uri.scheme().is_some() && uri.authority().is_some())
192}
193
194/// `deserialize_with` for [`ConsumerWiring::endpoint`]: keeps the field a plain
195/// `Option<String>` while rejecting a present, non-absolute value at parse time
196/// (see [`is_absolute_endpoint`]).
197fn deserialize_optional_endpoint<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
198where
199 D: serde::Deserializer<'de>,
200{
201 let endpoint = Option::<String>::deserialize(deserializer)?;
202 if let Some(ref s) = endpoint
203 && !is_absolute_endpoint(s)
204 {
205 return Err(serde::de::Error::custom(format!(
206 "`{s}` is not an absolute URI (needs scheme + host, e.g. `http://host:port`)"
207 )));
208 }
209 Ok(endpoint)
210}
211
212/// Consumer-side wiring for one dependency, read from
213/// `gears.<owner>.clients.consumes.<dep>` (with `gears.<owner>.clients.defaults`
214/// merged under it) by the runtime's proxy-wiring phase and applied to the
215/// directory-resolving REST client that `#[toolkit::consumes]` registers.
216///
217/// An object with an optional `endpoint` (omit to keep discovery) plus a
218/// flattened [`ClientTuning`]:
219///
220/// ```yaml
221/// clients:
222/// consumes:
223/// api-contracts:
224/// timeout: "5s"
225/// max_concurrent_requests: 256
226/// # endpoint: "http://..." # optional; omit to keep discovery
227/// ```
228///
229/// Unlike [`ClientWiring`] there is **no** `transport` tag: the
230/// `#[toolkit::consumes]` path is REST-only, so every tuning knob applies. (A
231/// hand-written [`ConsumerRegistration`](crate::runtime) may bind a non-REST
232/// transport, which reads only the knobs it understands.)
233///
234/// Must be an object; a bare `<dep>: "http://host"` string (the old shape) is
235/// rejected at parse time — use the `endpoint` field.
236#[derive(Clone, Debug, Default, Deserialize)]
237pub struct ConsumerWiring {
238 /// Static-endpoint override (ADR-0004 dev/test escape hatch): when set, the
239 /// dep is wired to this fixed endpoint instead of being discovered. Rejected
240 /// at parse time unless it is an absolute URI (see [`is_absolute_endpoint`]).
241 #[serde(default, deserialize_with = "deserialize_optional_endpoint")]
242 pub endpoint: Option<String>,
243 /// REST client tuning, flattened into the same map as `endpoint`.
244 #[serde(default, flatten)]
245 pub tuning: ClientTuning,
246}
247
248impl ConsumerWiring {
249 /// Split the wiring into its static-endpoint override (if any) and the
250 /// [`ClientTuning`] to apply.
251 #[must_use]
252 pub fn into_parts(self) -> (Option<String>, ClientTuning) {
253 (self.endpoint, self.tuning)
254 }
255}
256
257#[cfg(feature = "runtime-client")]
258impl ClientTuning {
259 /// `require_tls` with the default applied: an unset value is `false`, or
260 /// `true` when `toolkit-http/fips` is on. Use this instead of reading the
261 /// `Option` directly; [`Self::apply_to`] resolves it the same way.
262 #[must_use]
263 pub fn effective_require_tls(&self) -> bool {
264 self.require_tls
265 .unwrap_or_else(crate::runtime::config::default_require_tls)
266 }
267
268 /// Apply tuning overrides onto a fresh [`ClientConfig`] built from `endpoint`.
269 #[must_use]
270 pub fn apply_to(&self, endpoint: impl Into<String>) -> crate::runtime::config::ClientConfig {
271 use crate::runtime::config::{ClientConfig, ReconnectConfig, RetryConfig};
272
273 let mut cfg = ClientConfig::new(endpoint);
274 if let Some(timeout) = self.timeout {
275 cfg = cfg.with_timeout(timeout);
276 }
277 if let Some(ref r) = self.retry {
278 let base = cfg.retry.clone();
279 cfg = cfg.with_retry(RetryConfig {
280 max_attempts: r.max_attempts.unwrap_or(base.max_attempts),
281 base_delay: r.base_delay.unwrap_or(base.base_delay),
282 max_delay: r.max_delay.unwrap_or(base.max_delay),
283 multiplier: r.multiplier.unwrap_or(base.multiplier),
284 });
285 }
286 if let Some(ref s) = self.stream_reconnect {
287 let base = cfg.stream_reconnect.clone();
288 cfg = cfg.with_stream_reconnect(ReconnectConfig {
289 max_attempts: s.max_attempts.unwrap_or(base.max_attempts),
290 base_delay: s.base_delay.unwrap_or(base.base_delay),
291 max_delay: s.max_delay.unwrap_or(base.max_delay),
292 // Not exposed as wiring keys yet; inherit the base policy.
293 min_healthy_uptime: base.min_healthy_uptime,
294 max_total_reopens: base.max_total_reopens,
295 });
296 }
297 if let Some(require_tls) = self.require_tls {
298 cfg = cfg.with_require_tls(require_tls);
299 }
300 if let Some(max) = self.pool_max_idle_per_host {
301 cfg = cfg.with_pool_max_idle_per_host(max);
302 }
303 if let Some(timeout) = self.pool_idle_timeout {
304 cfg = cfg.with_pool_idle_timeout(Some(timeout));
305 }
306 if let Some(max) = self.max_concurrent_requests {
307 cfg = cfg.with_max_concurrent_requests(Some(max));
308 }
309 cfg = cfg.with_internal_token_provider(self.internal_token_provider.clone());
310 cfg
311 }
312
313 /// Attach the platform-plane credential source forwarded onto the built
314 /// [`ClientConfig`](crate::runtime::config::ClientConfig). Used by the
315 /// proxy-wiring phase to thread the process credential into a
316 /// directory-resolving (`#[toolkit::consumes]`) client.
317 #[must_use]
318 pub fn with_internal_token_provider(
319 mut self,
320 provider: Option<crate::runtime::config::InternalTokenProvider>,
321 ) -> Self {
322 self.internal_token_provider = provider;
323 self
324 }
325}
326
327#[cfg(test)]
328mod tests {
329 use super::*;
330
331 /// A static override is only usable if it is an absolute URI. An empty string,
332 /// a bare host, or a relative path would otherwise reach the wiring code, take
333 /// the static branch, and mark the dep resolved with no probe — 200 on
334 /// `/readyz` while every call fails.
335 #[test]
336 fn is_absolute_endpoint_accepts_only_scheme_plus_authority() {
337 assert!(is_absolute_endpoint("http://host:8081"));
338 assert!(is_absolute_endpoint("https://billing.svc/base"));
339 assert!(!is_absolute_endpoint(""));
340 assert!(!is_absolute_endpoint("billing"));
341 assert!(!is_absolute_endpoint("/path/only"));
342 assert!(!is_absolute_endpoint("not a uri"));
343 }
344
345 /// `ConsumerWiring` validates the endpoint at parse time: a present-but-invalid
346 /// value fails to deserialize (rather than yielding an unchecked string), the
347 /// valid value survives verbatim, and an omitted `endpoint` keeps discovery
348 /// while still parsing the tuning.
349 #[test]
350 fn consumer_wiring_validates_endpoint_on_deserialize() {
351 let ok: ConsumerWiring = serde_json::from_value(serde_json::json!({
352 "endpoint": "http://billing:8080",
353 "max_concurrent_requests": 256
354 }))
355 .expect("valid absolute endpoint must parse");
356 let (endpoint, tuning) = ok.into_parts();
357 assert_eq!(endpoint.as_deref(), Some("http://billing:8080"));
358 assert_eq!(tuning.max_concurrent_requests, Some(256));
359
360 assert!(
361 serde_json::from_value::<ConsumerWiring>(serde_json::json!({ "endpoint": "" }))
362 .is_err(),
363 "an empty endpoint must be rejected at deserialize time"
364 );
365 assert!(
366 serde_json::from_value::<ConsumerWiring>(serde_json::json!({ "endpoint": "billing" }))
367 .is_err(),
368 "a bare host must be rejected at deserialize time"
369 );
370
371 let no_endpoint: ConsumerWiring =
372 serde_json::from_value(serde_json::json!({ "max_concurrent_requests": 1 }))
373 .expect("omitted endpoint keeps discovery");
374 assert_eq!(no_endpoint.endpoint, None);
375 assert_eq!(no_endpoint.tuning.max_concurrent_requests, Some(1));
376 }
377}