Skip to main content

udb_client/
client.rs

1//! The data-plane client.
2//!
3//! Every method routes through [`UdbClient::request`], which is the single point
4//! that applies connection metadata. That is deliberate: if applying tenant scope
5//! were the caller's job, forgetting it once would be a cross-tenant read, and
6//! nothing in the type system would object.
7
8use tonic::transport::{Channel, Endpoint};
9use tonic::{Code, Request, Status};
10
11use crate::auth::TokenManager;
12use crate::error::{CallPolicy, UdbError};
13use crate::metadata::Metadata;
14use crate::proto::udb::entity::v1 as entity;
15use crate::proto::udb::services::v1::data_broker_client::DataBrokerClient;
16use crate::record::{DecodeError, Records};
17
18/// A connected UDB data-plane client bound to one identity.
19#[derive(Clone, Debug)]
20pub struct UdbClient {
21    inner: DataBrokerClient<Channel>,
22    meta: Metadata,
23    /// Overrides the per-RPC default when set. Reads default to a retrying
24    /// policy and mutations to a single attempt, so an override is only needed
25    /// to tighten a deadline or to opt a mutation into retries the CALLER knows
26    /// are safe (an idempotency key, say).
27    policy: Option<CallPolicy>,
28    /// The owner of the bearer every call carries, when the client was built
29    /// with [`UdbClient::with_token_manager`]. `None` sends `meta`'s bearer.
30    tokens: Option<TokenManager>,
31}
32
33/// Calls whose UNAUTHENTICATED is about the credential in the request, never
34/// the bearer: they are not repeated after a renewal.
35const AUTHN_SERVICE_PREFIX: &str = "/udb.core.authn.services.v1.AuthnService/";
36
37/// Generate an RPC wrapper with identical retry and deadline handling.
38///
39/// A macro rather than a generic helper because the closure would have to hand a
40/// `&mut` client into an async block per attempt, and the lifetime dance costs
41/// more clarity than the repetition saves. `$default` is the policy used when the
42/// client carries no override.
43macro_rules! rpc {
44    ($(#[$m:meta])* $name:ident, $rpc:ident, $req:ty, $resp:ty, $path:expr) => {
45        $(#[$m])*
46        pub async fn $name(&mut self, req: $req) -> Result<$resp, UdbError> {
47            let policy = self.policy.unwrap_or_else(|| CallPolicy::from_contract($path));
48            let mut attempt: u32 = 1;
49            let mut renewed = false;
50            loop {
51                let (mut request, sent) = self.prepare(req.clone()).await?;
52                if let Some(deadline) = policy.deadline {
53                    request.set_timeout(deadline);
54                }
55                match self.inner.$rpc(request).await {
56                    Ok(response) => return Ok(response.into_inner()),
57                    Err(status) => {
58                        let err = UdbError::from_status(status);
59                        if !renewed && self.renew_refused(&sent, &err, $path).await {
60                            // The broker refused the owned bearer this call
61                            // carried (a restarted broker, a revoked session).
62                            // It refuses authentication before any handler
63                            // runs, so the call is made exactly once more,
64                            // with the renewed bearer.
65                            renewed = true;
66                            continue;
67                        }
68                        if policy.should_retry(attempt, &err) {
69                            tokio::time::sleep(policy.backoff_for(attempt, &err)).await;
70                            attempt += 1;
71                            continue;
72                        }
73                        return Err(err);
74                    }
75                }
76            }
77        }
78    };
79}
80
81impl UdbClient {
82    /// Connect to a broker's data-plane listener (`:50051` by default).
83    ///
84    /// Note the port: UDB runs SEPARATE listeners with different authorization
85    /// models — the data plane authorizes through Casbin, while the native
86    /// service listener uses scope-based endpoint security. A credential accepted
87    /// by one is not automatically accepted by the other, and the mismatch
88    /// presents as a permissions error rather than a wrong-address error.
89    pub async fn connect(
90        endpoint: impl Into<String>,
91        meta: Metadata,
92    ) -> Result<Self, tonic::transport::Error> {
93        let channel = Endpoint::from_shared(endpoint.into())?.connect().await?;
94        Ok(Self::with_channel(channel, meta))
95    }
96
97    /// Wrap an already-configured channel — use this for TLS, custom timeouts,
98    /// load balancing, or interceptors.
99    pub fn with_channel(channel: Channel, meta: Metadata) -> Self {
100        Self {
101            inner: DataBrokerClient::new(channel),
102            meta,
103            policy: None,
104            tokens: None,
105        }
106    }
107
108    /// A copy of this client whose calls carry the access token `tokens` owns,
109    /// renewed when stale, instead of the metadata's static bearer.
110    ///
111    /// When the broker refuses that token before its local expiry (a restarted
112    /// broker that lost the session, a revoked session), the client marks it,
113    /// renews it (refresh, else sign in again) and repeats the refused call
114    /// exactly once; the broker refuses authentication before any handler runs,
115    /// so a repeat cannot apply a write twice. A token renewed moments ago that
116    /// is refused again fails the call UNAUTHENTICATED. See [`crate::auth`].
117    pub fn with_token_manager(&self, tokens: TokenManager) -> Self {
118        Self {
119            inner: self.inner.clone(),
120            meta: self.meta.clone(),
121            policy: self.policy,
122            tokens: Some(tokens),
123        }
124    }
125
126    /// The request for one attempt, and the access token it carries when the
127    /// client owns its bearer (empty otherwise).
128    async fn prepare<T>(&self, message: T) -> Result<(Request<T>, String), Status> {
129        let Some(tokens) = &self.tokens else {
130            return Ok((self.request(message)?, String::new()));
131        };
132        let bearer = tokens.access_token().await?;
133        let mut request = Request::new(message);
134        self.meta
135            .clone()
136            .with_bearer_token(bearer.clone())
137            .apply(&mut request)?;
138        Ok((request, bearer))
139    }
140
141    /// Whether a failed call should be made once more because the broker
142    /// refused the owned bearer `sent` and the owner has marked it for renewal.
143    async fn renew_refused(&self, sent: &str, err: &UdbError, path: &str) -> bool {
144        match &self.tokens {
145            Some(tokens)
146                if !sent.is_empty()
147                    && err.code() == Code::Unauthenticated
148                    && !path.starts_with(AUTHN_SERVICE_PREFIX) =>
149            {
150                tokens.reject(sent).await
151            }
152            _ => false,
153        }
154    }
155
156    /// The connection's metadata.
157    pub fn metadata(&self) -> &Metadata {
158        &self.meta
159    }
160
161    /// A copy of this client carrying request-scoped audit fields.
162    ///
163    /// Identity is intentionally not settable here; see [`Metadata`].
164    pub fn with_audit(
165        &self,
166        purpose: impl Into<String>,
167        correlation_id: impl Into<String>,
168    ) -> Self {
169        Self {
170            inner: self.inner.clone(),
171            meta: self.meta.clone().with_audit(purpose, correlation_id),
172            policy: self.policy,
173            tokens: self.tokens.clone(),
174        }
175    }
176
177    /// Replace the bearer credential, e.g. after a token refresh.
178    ///
179    /// The copy carries exactly this bearer: a [`TokenManager`] attached with
180    /// [`UdbClient::with_token_manager`] is dropped, and a refusal of a bearer
181    /// the client does not own is never renewed or repeated.
182    pub fn with_bearer_token(&self, token: impl Into<String>) -> Self {
183        Self {
184            inner: self.inner.clone(),
185            meta: self.meta.clone().with_bearer_token(token),
186            policy: self.policy,
187            tokens: None,
188        }
189    }
190
191    /// Wrap a message in a request carrying this connection's metadata.
192    ///
193    /// Public so callers can reach an RPC this wrapper does not expose yet
194    /// without hand-rolling — and without hand-rolling the headers. It carries
195    /// the metadata's static bearer, not one a [`TokenManager`] owns.
196    pub fn request<T>(&self, message: T) -> Result<Request<T>, Status> {
197        let mut req = Request::new(message);
198        self.meta.apply(&mut req)?;
199        Ok(req)
200    }
201
202    /// The raw generated client, for RPCs this wrapper does not cover.
203    ///
204    /// Pair it with [`UdbClient::request`] so metadata is still applied.
205    pub fn raw(&mut self) -> &mut DataBrokerClient<Channel> {
206        &mut self.inner
207    }
208
209    /// Apply a deadline/retry policy to every call this client makes.
210    pub fn with_policy(&self, policy: CallPolicy) -> Self {
211        Self {
212            inner: self.inner.clone(),
213            meta: self.meta.clone(),
214            policy: Some(policy),
215            tokens: self.tokens.clone(),
216        }
217    }
218
219    rpc!(
220        /// Broker capabilities: a cheap authenticated read, also a warm-up and
221        /// reachability probe.
222        get_capabilities,
223        get_capabilities,
224        entity::CapabilitiesRequest,
225        entity::CapabilitiesResponse,
226        "/udb.services.v1.DataBroker/GetCapabilities"
227    );
228
229    rpc!(
230        /// Read. Retry policy comes from the contract, not this wrapper.
231        select,
232        select,
233        entity::SelectRequest,
234        entity::RecordSet,
235        "/udb.services.v1.DataBroker/Select"
236    );
237    rpc!(
238        /// Write. The contract declares it replayable, so it retries.
239        upsert,
240        upsert,
241        entity::UpsertRequest,
242        entity::MutationResponse,
243        "/udb.services.v1.DataBroker/Upsert"
244    );
245    rpc!(
246        /// Write. Contract-declared replayable.
247        update,
248        update,
249        entity::UpdateRequest,
250        entity::MutationResponse,
251        "/udb.services.v1.DataBroker/Update"
252    );
253    rpc!(
254        /// Write. Contract-declared replayable.
255        delete,
256        delete,
257        entity::DeleteRequest,
258        entity::MutationResponse,
259        "/udb.services.v1.DataBroker/Delete"
260    );
261    rpc!(
262        /// Compare-and-swap. The contract does NOT declare it replayable: a CAS
263        /// that timed out may have committed, and a repeat would compare against
264        /// state its own first attempt wrote.
265        bulk_cas,
266        bulk_cas,
267        entity::BulkCasRequest,
268        entity::BulkCasResponse,
269        "/udb.services.v1.DataBroker/BulkCas"
270    );
271    rpc!(
272        /// Read.
273        vector_search,
274        vector_search,
275        entity::VectorSearchRequest,
276        entity::VectorSet,
277        "/udb.services.v1.DataBroker/VectorSearch"
278    );
279    rpc!(
280        /// Write. Not contract-declared replayable.
281        vector_upsert,
282        vector_upsert,
283        entity::VectorUpsertRequest,
284        entity::MutationResponse,
285        "/udb.services.v1.DataBroker/VectorUpsert"
286    );
287
288    /// Select and decode in one step.
289    ///
290    /// Prefer this over [`UdbClient::select`] plus hand-decoding. The raw
291    /// `RecordSet` carries the records in `records_json` and sends the
292    /// `rows` field EMPTY for wire compatibility, and nothing in the generated
293    /// struct says which is which — so the natural-looking `set.rows[i].fields`
294    /// yields the right record COUNT with no data in it, and reports a populated
295    /// table as a page of empty entities. See [`crate::record`].
296    pub async fn select_records(
297        &mut self,
298        req: entity::SelectRequest,
299    ) -> Result<Records, SelectError> {
300        let set = self.select(req).await?;
301        Ok(Records::decode(&set)?)
302    }
303}
304
305/// A failed [`UdbClient::select_records`]: the call itself, or the decode of what
306/// came back.
307///
308/// Kept as two variants rather than flattened into [`UdbError`] so a caller can
309/// tell "the broker refused" from "the broker answered with something this client
310/// could not trust" — they need different responses, and only the first is worth
311/// retrying.
312// `UdbError` carries the typed error detail (reason, constraint, column, fix
313// hint, missing); boxing it would change this public enum for a cold path.
314#[allow(clippy::large_enum_variant)]
315#[derive(Debug)]
316pub enum SelectError {
317    /// The RPC failed.
318    Call(UdbError),
319    /// The RPC succeeded and the response was not structurally decodable.
320    Decode(DecodeError),
321}
322
323impl From<UdbError> for SelectError {
324    fn from(err: UdbError) -> Self {
325        Self::Call(err)
326    }
327}
328
329impl From<DecodeError> for SelectError {
330    fn from(err: DecodeError) -> Self {
331        Self::Decode(err)
332    }
333}
334
335impl std::fmt::Display for SelectError {
336    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
337        match self {
338            Self::Call(err) => write!(f, "select failed: {err}"),
339            Self::Decode(err) => write!(f, "select returned an undecodable record set: {err}"),
340        }
341    }
342}
343
344impl std::error::Error for SelectError {
345    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
346        match self {
347            Self::Call(err) => Some(err),
348            Self::Decode(err) => Some(err),
349        }
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356    use crate::metadata::headers;
357
358    // `connect_lazy` registers with the Tokio reactor even though it dials
359    // nothing, so these must run inside a runtime. They exercise metadata
360    // assembly, not transport: nothing needs to be listening.
361    fn client() -> UdbClient {
362        let channel = Endpoint::from_static("http://127.0.0.1:50051").connect_lazy();
363        UdbClient::with_channel(
364            channel,
365            Metadata::new("tenant-1")
366                .with_project("proj-9")
367                .with_bearer_token("tok"),
368        )
369    }
370
371    #[tokio::test]
372    async fn request_carries_connection_identity() {
373        let c = client();
374        let req = c.request(()).expect("metadata applies");
375        let md = req.metadata();
376        assert_eq!(md.get(headers::TENANT_ID).unwrap(), "tenant-1");
377        assert_eq!(md.get(headers::PROJECT_ID).unwrap(), "proj-9");
378        assert_eq!(md.get(headers::AUTHORIZATION).unwrap(), "Bearer tok");
379    }
380
381    #[tokio::test]
382    async fn with_audit_keeps_identity_and_adds_audit() {
383        let c = client().with_audit("billing", "corr-7");
384        let req = c.request(()).expect("metadata applies");
385        let md = req.metadata();
386        assert_eq!(md.get(headers::TENANT_ID).unwrap(), "tenant-1");
387        assert_eq!(md.get(headers::PURPOSE).unwrap(), "billing");
388        assert_eq!(md.get(headers::CORRELATION_ID).unwrap(), "corr-7");
389    }
390
391    #[test]
392    fn wrapped_rpc_paths_exist_in_the_registry() {
393        // A typo in a path literal would make `from_contract` fall through to the
394        // conservative default and silently stop retrying that RPC — a change
395        // nothing else would catch.
396        for path in [
397            "/udb.services.v1.DataBroker/GetCapabilities",
398            "/udb.services.v1.DataBroker/Select",
399            "/udb.services.v1.DataBroker/Upsert",
400            "/udb.services.v1.DataBroker/Update",
401            "/udb.services.v1.DataBroker/Delete",
402            "/udb.services.v1.DataBroker/BulkCas",
403            "/udb.services.v1.DataBroker/VectorSearch",
404            "/udb.services.v1.DataBroker/VectorUpsert",
405        ] {
406            assert!(
407                crate::generated_rpcs::spec_for_path(path).is_some(),
408                "{path} is not in the generated registry"
409            );
410        }
411    }
412
413    #[test]
414    fn contract_drives_retry_and_disagrees_with_naive_naming() {
415        use crate::generated_rpcs::is_retry_safe;
416        // Reads: obviously repeatable.
417        assert!(is_retry_safe("/udb.services.v1.DataBroker/Select"));
418        // Mutations the CONTRACT declares replayable. A name-based guess would
419        // refuse these, which is exactly the mistake this replaced.
420        assert!(is_retry_safe("/udb.services.v1.DataBroker/Upsert"));
421        assert!(is_retry_safe("/udb.services.v1.DataBroker/Delete"));
422        // And ones it does not.
423        assert!(!is_retry_safe("/udb.services.v1.DataBroker/BulkCas"));
424        assert!(!is_retry_safe("/udb.services.v1.DataBroker/VectorUpsert"));
425    }
426
427    #[tokio::test]
428    async fn a_static_bearer_drops_the_token_manager() {
429        let channel = Endpoint::from_static("http://127.0.0.1:50061").connect_lazy();
430        let tokens = TokenManager::new(channel, Metadata::new("tenant-1"));
431        let owned = client().with_token_manager(tokens);
432        assert!(owned.tokens.is_some());
433        assert!(owned.with_audit("billing", "corr-7").tokens.is_some());
434        assert!(owned.with_policy(CallPolicy::once()).tokens.is_some());
435        // Negative: a bearer the client does not own is never renewed.
436        assert!(owned.with_bearer_token("caller-owned").tokens.is_none());
437    }
438
439    #[tokio::test]
440    async fn an_unowned_or_authn_refusal_is_never_repeated() {
441        let refused = UdbError::from_status(Status::unauthenticated("invalid credential"));
442        let path = "/udb.services.v1.DataBroker/Select";
443        // No token manager: the bearer is the caller's.
444        assert!(!client().renew_refused("tok", &refused, path).await);
445
446        let channel = Endpoint::from_static("http://127.0.0.1:50061").connect_lazy();
447        let owned = client().with_token_manager(TokenManager::new(channel, Metadata::new("t")));
448        // A call that carried no owned bearer, an AuthnService call, and a
449        // failure other than UNAUTHENTICATED are never repeated.
450        assert!(!owned.renew_refused("", &refused, path).await);
451        assert!(
452            !owned
453                .renew_refused(
454                    "tok",
455                    &refused,
456                    "/udb.core.authn.services.v1.AuthnService/Login"
457                )
458                .await
459        );
460        let denied = UdbError::from_status(Status::permission_denied("no"));
461        assert!(!owned.renew_refused("tok", &denied, path).await);
462        // The manager holds no token, so "tok" is not its bearer either.
463        assert!(!owned.renew_refused("tok", &refused, path).await);
464    }
465
466    #[tokio::test]
467    async fn with_bearer_token_replaces_only_the_credential() {
468        let c = client().with_bearer_token("rotated");
469        assert_eq!(c.metadata().tenant_id, "tenant-1");
470        let req = c.request(()).expect("metadata applies");
471        assert_eq!(
472            req.metadata().get(headers::AUTHORIZATION).unwrap(),
473            "Bearer rotated"
474        );
475    }
476}