Skip to main content

rociadb_sdk/
lib.rs

1//! Rocia DB SDK client for gRPC upstream services.
2//!
3//! The client speaks to a RociaDB server over gRPC and covers four service
4//! areas: documents, graph nodes and edges, file transfer, and tenants.
5//! Every call goes through a single [`RociaDbClient`], built by
6//! [`RociaDbBuilder`], which owns the connection and the auth token refresh.
7//!
8//! # Quick example
9//!
10//! ```rust,no_run
11//! use rociadb_sdk::RociaDbBuilder;
12//! use serde_json::json;
13//!
14//! # #[tokio::main]
15//! # async fn main() -> rociadb_sdk::Result<()> {
16//! let client = RociaDbBuilder::new()
17//!     .host("http://127.0.0.1:50051")
18//!     .auth_client_credentials(
19//!         "https://example.com/token",
20//!         "client-id",
21//!         "client-secret",
22//!     )
23//!     .build()
24//!     .await?;
25//!
26//! client
27//!     .create_document(
28//!         "tenant-1",
29//!         "products",
30//!         "sku-123",
31//!         json!({"sku": "sku-123"}),
32//!         Some("product".to_string()),
33//!         Some("products".to_string()),
34//!     )
35//!     .await?;
36//! # Ok(())
37//! # }
38//! ```
39//!
40//! # Building
41//!
42//! The build script compiles the `.proto` files bundled with this crate, so
43//! **`protoc` must be available** on any machine that compiles it, including
44//! CI: either on `PATH`, or at the location given by the `PROTOC` environment
45//! variable. Nothing else is needed from the system — the Google well-known
46//! types the API uses ship inside the crate.
47//!
48//! # Example project
49//!
50//! [`example-rust-project`](https://github.com/RociaDB/example-rust-project)
51//! wires this SDK into a runnable program, end to end.
52//!
53//! # Where things live
54//!
55//! Document, graph, file and tenant calls are all inherent methods on
56//! [`RociaDbClient`], so the module list is short:
57//!
58//! - [`auth`] — token acquisition and refresh, and the interceptors that
59//!   attach credentials to outgoing calls. Useful when you drive
60//!   authentication yourself rather than through the builder.
61//! - [`mod@file`] — the option types for uploads ([`FileUploadOptions`],
62//!   [`FileStreamUploadOptions`]) and the chunking rules the wire contract
63//!   imposes.
64//! - [`graph`] — the page and node types returned by neighbor traversal
65//!   ([`NeighborPage`], [`NeighborNode`]).
66//!
67//! # Stability
68//!
69//! The public API follows semantic versioning from 1.0.0 onward, with one
70//! documented exception: the internal `pb` module holds code generated from
71//! the `.proto` files by prost and tonic, and is not covered by that promise.
72//! A routine prost or
73//! tonic upgrade can reshape those generated types without this SDK's own API
74//! changing. Five of them — [`CollectionInfo`], [`StatResponse`],
75//! [`Neighbor`], [`UploadRequest`] and [`DownloadResponse`] — appear in public
76//! signatures and are re-exported at the crate root for that reason; depend on
77//! the re-exports: the `pb` module itself is private.
78#![allow(clippy::doc_lazy_continuation)]
79
80pub mod auth;
81mod document;
82mod error;
83pub mod file;
84pub mod graph;
85pub(crate) mod pb;
86mod tenant;
87
88pub use error::{Result, RociaDbError};
89pub use file::{FileStreamUploadOptions, FileUploadOptions};
90pub use graph::{NeighborNode, NeighborPage};
91/// Generated protobuf types that appear directly in a public method signature,
92/// re-exported here so callers can name them without depending on the crate's
93/// private `pb` module. The stability caveat in the crate documentation applies
94/// to them: a prost or tonic upgrade can reshape these types without the SDK's
95/// own API changing.
96pub use pb::upstream::v1::{
97    CollectionInfo, DownloadResponse, Neighbor, StatResponse, UploadRequest,
98};
99/// Re-exported so callers do not need `tonic` as a direct dependency just to
100/// name the return type of [`RociaDbClient::download_file_stream`]. The same
101/// stability caveat applies: a major tonic upgrade can reshape this type
102/// without the SDK's own API changing.
103pub use tonic::codec::Streaming;
104
105use crate::error::{AuthResultExt, ConnectionResultExt, JsonResultExt, StatusResultExt};
106use crate::pb::upstream::v1::document_service_client::DocumentServiceClient;
107use crate::pb::upstream::v1::file_service_client::FileServiceClient;
108use crate::pb::upstream::v1::graph_service_client::GraphServiceClient;
109use crate::pb::upstream::v1::tenant_service_client::TenantServiceClient;
110use crate::pb::upstream::v1::{
111    AddEdgeRequest, FindByFieldRequest, GetDocRequest, GetNodeRequest, ListCollectionsRequest,
112    ListDocRequest, PageRequest, PutDocRequest, PutNodeRequest, QueryDocRequest, QueryFilter,
113    QueryOperator, QuerySort, SortDirection,
114};
115use auth::{BearerInterceptor, TokenManager, TokenRefreshGuard};
116use futures::{TryStreamExt, stream};
117use serde::{Serialize, de::DeserializeOwned};
118use serde_json::{Value, json};
119use std::env;
120use std::sync::Arc;
121use std::time::Duration;
122use tonic::codegen::InterceptedService;
123use tonic::transport::{Channel, ClientTlsConfig, Endpoint};
124use tracing::{debug, error, info, warn};
125use uuid::Uuid;
126
127/// Max concurrent in-flight requests for batch operations.
128const CONCURRENT_REQUESTS: usize = 10;
129/// Page size used when the caller does not provide one.
130const DEFAULT_PAGE_SIZE: u32 = 20;
131const AUTH_TOKEN_URL_ENV: &str = "AUTH_TOKEN_URL";
132const AUTH_CLIENT_ID_ENV: &str = "AUTH_CLIENT_ID";
133const AUTH_CLIENT_SECRET_ENV: &str = "AUTH_CLIENT_SECRET";
134/// Connect timeout applied in [`RociaDbBuilder::build`] when
135/// [`RociaDbBuilder::connect_timeout`] was never called, so a host that
136/// never answers cannot hang `build()` forever.
137const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
138
139#[derive(Clone)]
140enum BuilderAuthConfig {
141    Enabled {
142        token_url: Option<String>,
143        client_id: Option<String>,
144        client_secret: Option<String>,
145    },
146    Disabled,
147}
148
149// Manual `Debug` impl instead of `#[derive(Debug)]`: a derived impl would
150// print `client_secret` in clear text, so any `format!("{:?}", ..)` or
151// debug-level log of a `RociaDbBuilder` would leak the OAuth2 secret.
152impl std::fmt::Debug for BuilderAuthConfig {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        match self {
155            Self::Enabled {
156                token_url,
157                client_id,
158                client_secret: _,
159            } => f
160                .debug_struct("Enabled")
161                .field("token_url", token_url)
162                .field("client_id", client_id)
163                .field("client_secret", &"[redacted]")
164                .finish(),
165            Self::Disabled => f.write_str("Disabled"),
166        }
167    }
168}
169
170/// Builder for RociaDbClient.
171#[derive(Debug)]
172pub struct RociaDbBuilder {
173    host: Option<String>,
174    auth: BuilderAuthConfig,
175    connect_timeout: Option<Duration>,
176}
177
178/// gRPC client for document, graph, file, and tenant services.
179///
180/// `Clone` is cheap: clones share the same underlying channel, token
181/// manager, and background token-refresh task (the refresh task keeps
182/// running until every clone has been dropped). Every method takes `&self`
183/// (not `&mut self`): each call clones the cheap, `Arc`-backed inner
184/// service client before issuing its RPC, the same way the batch helpers
185/// ([`RociaDbClient::put_nodes`], [`RociaDbClient::add_edges`]) always
186/// have. A shared `RociaDbClient` behind an `Arc` therefore needs no
187/// `Mutex` to be usable concurrently.
188#[derive(Clone)]
189pub struct RociaDbClient {
190    upstream_document: DocumentServiceClient<InterceptedService<Channel, BearerInterceptor>>,
191    upstream_graph: GraphServiceClient<InterceptedService<Channel, BearerInterceptor>>,
192    upstream_file: FileServiceClient<InterceptedService<Channel, BearerInterceptor>>,
193    upstream_tenant: TenantServiceClient<InterceptedService<Channel, BearerInterceptor>>,
194    /// `None` when auth is disabled. Used to service
195    /// [`RociaDbClient::refresh_auth_token`].
196    token_manager: Option<TokenManager>,
197    /// Keeps the background token-refresh task alive for as long as this
198    /// client (or any of its clones) exists. Never read directly, hence the
199    /// leading underscore; it exists purely for its `Drop`.
200    _token_refresh_guard: Option<Arc<TokenRefreshGuard>>,
201}
202
203/// One page of listed items with the cursor for the next page.
204///
205/// `next_cursor` is `None` once the server has no further page. The cursor
206/// is opaque and must be passed back unchanged.
207#[non_exhaustive]
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub struct Page<T> {
210    pub items: Vec<T>,
211    pub next_cursor: Option<String>,
212}
213
214/// One page of document results, together with the total number of
215/// documents matching the request (before pagination). `items` and
216/// `next_cursor` follow the same contract as [`Page<T>`].
217///
218/// The cost of `total_count` is **not** the same across the three methods
219/// that produce it, because the server computes it differently for each:
220/// - [`RociaDbClient::list_documents`] (`ListDoc`): free — the server keeps
221///   a running per-collection counter updated on every write, so reading it
222///   costs nothing beyond the listing itself.
223/// - [`RociaDbClient::search_documents`] (`FindByField`): a count over the
224///   matching field-index entries.
225/// - [`RociaDbClient::query_documents`] (`QueryDoc`): expensive — the server
226///   only knows the total once it has filtered the *complete* candidate set
227///   for the query, so the cost scales with the number of candidates on
228///   every single call. Do not call this in a loop expecting a cheap
229///   number; fetch it once and cache it if the same query is issued
230///   repeatedly.
231#[non_exhaustive]
232#[derive(Debug, Clone, PartialEq, Eq)]
233pub struct DocumentPage<T> {
234    pub items: Vec<T>,
235    pub next_cursor: Option<String>,
236    pub total_count: u64,
237}
238
239/// Build a `PageRequest` applying the SDK default page size.
240///
241/// The server rejects `limit == 0` with `INVALID_ARGUMENT`; this is
242/// rejected here too so the caller gets an immediate, clear error instead
243/// of a round trip to the server. The server's own page-size ceiling
244/// (`limits.max_page_size`, 200 by default) is intentionally not
245/// duplicated here — it is configurable server-side, so any positive limit
246/// is forwarded unchanged and the server has the final say.
247pub(crate) fn page_request(
248    limit: Option<u32>,
249    cursor: Option<&str>,
250) -> Result<Option<PageRequest>> {
251    if limit == Some(0) {
252        return Err(RociaDbError::validation(
253            "page limit must be greater than zero",
254        ));
255    }
256    Ok(Some(PageRequest {
257        limit: limit.unwrap_or(DEFAULT_PAGE_SIZE),
258        cursor: cursor.unwrap_or_default().to_string(),
259    }))
260}
261
262/// Map the protobuf empty-string cursor to `None`.
263pub(crate) fn non_empty(value: String) -> Option<String> {
264    (!value.is_empty()).then_some(value)
265}
266
267/// Validate that `node_label` and `node_graph` are either both set or both
268/// absent, before any network call. Pulled out of
269/// [`RociaDbClient::create_document`] as a pure function so the rule is
270/// unit-testable without a live client.
271fn validate_node_binding(node_label: &Option<String>, node_graph: &Option<String>) -> Result<()> {
272    if node_label.is_some() != node_graph.is_some() {
273        return Err(RociaDbError::validation(format!(
274            "node_label and node_graph must be provided together (got node_label={:?}, node_graph={:?})",
275            node_label, node_graph
276        )));
277    }
278    Ok(())
279}
280
281/// Supported document query operators exposed by the SDK.
282#[non_exhaustive]
283#[derive(Debug, Clone, Copy)]
284pub enum DocumentQueryOperator {
285    Eq,
286    In,
287    Contains,
288}
289
290impl DocumentQueryOperator {
291    fn as_proto(self) -> i32 {
292        match self {
293            Self::Eq => QueryOperator::Eq as i32,
294            Self::In => QueryOperator::In as i32,
295            Self::Contains => QueryOperator::Contains as i32,
296        }
297    }
298}
299
300/// Supported document sort directions exposed by the SDK.
301#[non_exhaustive]
302#[derive(Debug, Clone, Copy)]
303pub enum DocumentQuerySortDirection {
304    Asc,
305    Desc,
306}
307
308impl DocumentQuerySortDirection {
309    fn as_proto(self) -> i32 {
310        match self {
311            Self::Asc => SortDirection::Asc as i32,
312            Self::Desc => SortDirection::Desc as i32,
313        }
314    }
315}
316
317/// Filter definition for `QueryDoc`.
318#[non_exhaustive]
319#[derive(Debug, Clone)]
320pub struct DocumentQueryFilter {
321    pub field: String,
322    pub operator: DocumentQueryOperator,
323    pub values: Vec<Value>,
324}
325
326impl DocumentQueryFilter {
327    /// Build a filter on `field`, comparing it against `values` with
328    /// `operator`. How many values an operator expects is the server's
329    /// contract, not the SDK's: `Eq` takes one, `In` takes the set to match.
330    pub fn new(
331        field: impl Into<String>,
332        operator: DocumentQueryOperator,
333        values: Vec<Value>,
334    ) -> Self {
335        Self {
336            field: field.into(),
337            operator,
338            values,
339        }
340    }
341}
342
343/// Sort definition for `QueryDoc`.
344#[non_exhaustive]
345#[derive(Debug, Clone)]
346pub struct DocumentQuerySort {
347    pub field: String,
348    pub direction: DocumentQuerySortDirection,
349}
350
351impl DocumentQuerySort {
352    /// Sort on `field` in `direction`.
353    pub fn new(field: impl Into<String>, direction: DocumentQuerySortDirection) -> Self {
354        Self {
355            field: field.into(),
356            direction,
357        }
358    }
359}
360
361/// One node to upsert, used by [`RociaDbClient::put_nodes`].
362///
363/// `node_id` is the **complete** node id (for example `"product:sku-1"`),
364/// not a `(label, id)` pair for the SDK to reassemble: `label:id` remains a
365/// usage convention, not something the server enforces or the SDK
366/// recomposes.
367#[non_exhaustive]
368#[derive(Debug, Clone, PartialEq)]
369pub struct NodeInput {
370    pub node_id: String,
371    pub value: Value,
372    /// Idempotency key for this item's `PutNode` call. When `None`, one is
373    /// generated automatically (`put_node:<uuid>` — the same prefix
374    /// [`RociaDbClient::put_node`] uses for a single-item write, so a
375    /// `PutNode` call always carries the same default prefix regardless of
376    /// which path produced it). Provide it explicitly — and reuse the same
377    /// value on a retry — so a batch replayed after a timeout resumes
378    /// safely: the server deduplicates on `(tenant, operation,
379    /// request_id)`, so a repeated `request_id` is recognized as the same
380    /// write rather than a new one.
381    pub request_id: Option<String>,
382}
383
384impl NodeInput {
385    /// Upsert `value` at `node_id`, letting the SDK generate the
386    /// idempotency key. Chain [`NodeInput::with_request_id`] to supply your
387    /// own — which is what makes a retried batch safe to replay.
388    pub fn new(node_id: impl Into<String>, value: Value) -> Self {
389        Self {
390            node_id: node_id.into(),
391            value,
392            request_id: None,
393        }
394    }
395
396    /// Set the idempotency key for this item; see [`NodeInput::request_id`].
397    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
398        self.request_id = Some(request_id.into());
399        self
400    }
401}
402
403/// One edge to upsert, used by [`RociaDbClient::add_edges`].
404///
405/// `edge_id` is raw and must not be prefixed with `label`.
406#[non_exhaustive]
407#[derive(Debug, Clone, PartialEq)]
408pub struct EdgeInput {
409    pub edge_id: String,
410    pub from: String,
411    pub to: String,
412    pub label: String,
413    pub value: Value,
414    /// Idempotency key for this item's `AddEdge` call. When `None`, one is
415    /// generated automatically (a bare UUID, with no prefix). See
416    /// [`NodeInput::request_id`] for why reusing it on a retry matters.
417    pub request_id: Option<String>,
418}
419
420impl EdgeInput {
421    /// Upsert an edge `label` carrying `value`, running `from` -> `to`,
422    /// letting the SDK generate the idempotency key. Chain
423    /// [`EdgeInput::with_request_id`] to supply your own. `edge_id` is raw:
424    /// do not prefix it with `label`.
425    pub fn new(
426        edge_id: impl Into<String>,
427        from: impl Into<String>,
428        to: impl Into<String>,
429        label: impl Into<String>,
430        value: Value,
431    ) -> Self {
432        Self {
433            edge_id: edge_id.into(),
434            from: from.into(),
435            to: to.into(),
436            label: label.into(),
437            value,
438            request_id: None,
439        }
440    }
441
442    /// Set the idempotency key for this item; see [`EdgeInput::request_id`].
443    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
444        self.request_id = Some(request_id.into());
445        self
446    }
447}
448
449/// Build the ordered `PutNodeRequest` batch for [`RociaDbClient::put_nodes`].
450/// Pulled out as a pure, network-free function — the same way
451/// [`crate::file::chunk_upload_requests`] is for uploads — so the batch's
452/// wire shape is unit-testable without a live client: item order is
453/// preserved (`nodes` is consumed via `into_iter` in the order given),
454/// duplicate `node_id`s are not merged (each `NodeInput` becomes exactly
455/// one `PutNodeRequest`), and `request_id` is passed through unchanged or
456/// defaulted to `put_node:<uuid>` when absent — the same default prefix
457/// [`RociaDbClient::put_node`] uses for a single-item write, so every
458/// `PutNode` call defaults consistently regardless of whether it went
459/// through the batch or single-item path.
460fn build_put_node_requests(
461    tenant_id: &str,
462    graph_name: &str,
463    nodes: Vec<NodeInput>,
464) -> Result<Vec<PutNodeRequest>> {
465    nodes
466        .into_iter()
467        .map(|node| {
468            let json = serde_json::to_vec(&node.value).encode_context("node json")?;
469            Ok(PutNodeRequest {
470                tenant_id: tenant_id.to_string(),
471                graph: graph_name.to_string(),
472                node_id: node.node_id,
473                json,
474                request_id: node
475                    .request_id
476                    .unwrap_or_else(|| format!("put_node:{}", Uuid::new_v4())),
477            })
478        })
479        .collect()
480}
481
482/// Build the ordered `AddEdgeRequest` batch for [`RociaDbClient::add_edges`].
483/// Same rationale and guarantees as [`build_put_node_requests`]: order
484/// preserved, duplicate `edge_id`s not merged, `request_id` passed through
485/// unchanged or defaulted to a bare UUID (no prefix) when absent.
486fn build_add_edge_requests(
487    tenant_id: &str,
488    graph_name: &str,
489    edges: Vec<EdgeInput>,
490) -> Result<Vec<AddEdgeRequest>> {
491    edges
492        .into_iter()
493        .map(|edge| {
494            let json = serde_json::to_vec(&edge.value).encode_context("edge json")?;
495            debug!(
496                tenant_id = tenant_id,
497                graph = graph_name,
498                edge_id = edge.edge_id,
499                from = edge.from,
500                to = edge.to,
501                label = edge.label,
502                "prepared graph edge upsert"
503            );
504            Ok(AddEdgeRequest {
505                tenant_id: tenant_id.to_string(),
506                graph: graph_name.to_string(),
507                edge_id: edge.edge_id,
508                from: edge.from,
509                to: edge.to,
510                label: edge.label,
511                json,
512                request_id: edge
513                    .request_id
514                    .unwrap_or_else(|| Uuid::new_v4().to_string()),
515            })
516        })
517        .collect()
518}
519
520/// Default idempotency key for the `PutDoc` write issued by
521/// [`RociaDbClient::create_document`] when the caller does not use
522/// [`RociaDbClient::create_document_with_request_id`] directly. Pulled out
523/// as a pure, network-free function — the same reason
524/// [`build_put_node_requests`] and [`build_add_edge_requests`] exist — so
525/// the exact default prefix (`put_document:{collection}:<uuid>`, matching
526/// [`RociaDbClient::put_document`]'s own default) is unit-testable without
527/// a live client or a network call.
528fn default_document_request_id(collection_name: &str) -> String {
529    format!("put_document:{}:{}", collection_name, Uuid::new_v4())
530}
531
532/// Reject a `host` URL whose path is neither empty nor `"/"`, before any
533/// connection attempt: a mistyped host carrying a leftover path (for
534/// example `http://127.0.0.1:50051/v1` pasted from somewhere else) would
535/// otherwise be silently accepted by tonic, which simply ignores the path
536/// component when dialing.
537///
538/// `http::Uri::path()` already returns `"/"` for a URI with no explicit
539/// path component (verified against `http` 1.x), so this rejects strictly
540/// more than "path is exactly absent".
541fn validate_host_path(host: &str) -> Result<()> {
542    let uri: http::Uri = host.parse().connection_context("invalid upstream host")?;
543    let path = uri.path();
544    if !path.is_empty() && path != "/" {
545        return Err(RociaDbError::connection(format!(
546            "RociaDB host must contain only a hostname and port, got path {path:?}"
547        )));
548    }
549    Ok(())
550}
551
552/// Resolve the connect timeout [`RociaDbBuilder::build`] applies: `explicit`
553/// when [`RociaDbBuilder::connect_timeout`] was called, or
554/// [`DEFAULT_CONNECT_TIMEOUT`] otherwise — rejecting a zero timeout either
555/// way. Extracted as a pure, network-free function (mirrors
556/// [`validate_host_path`]) so both the default value and the zero-timeout
557/// rejection are unit-testable without ever dialing an upstream.
558fn resolve_connect_timeout(explicit: Option<Duration>) -> Result<Duration> {
559    let connect_timeout = explicit.unwrap_or(DEFAULT_CONNECT_TIMEOUT);
560    if connect_timeout.is_zero() {
561        return Err(RociaDbError::validation(
562            "connect timeout must be greater than zero",
563        ));
564    }
565    Ok(connect_timeout)
566}
567
568impl Default for RociaDbBuilder {
569    fn default() -> Self {
570        Self {
571            host: Some("http://127.0.0.1:50051".to_string()),
572            auth: BuilderAuthConfig::Enabled {
573                token_url: None,
574                client_id: None,
575                client_secret: None,
576            },
577            connect_timeout: None,
578        }
579    }
580}
581
582impl RociaDbBuilder {
583    /// Create a builder with default settings.
584    pub fn new() -> Self {
585        Self::default()
586    }
587
588    /// Set the upstream host (ex: http://127.0.0.1:50051).
589    pub fn host(&mut self, host: impl Into<String>) -> &mut Self {
590        self.host = Some(host.into());
591        self
592    }
593
594    /// Configure OAuth2 client credentials for upstream auth.
595    pub fn auth_client_credentials(
596        &mut self,
597        token_url: impl Into<String>,
598        client_id: impl Into<String>,
599        client_secret: impl Into<String>,
600    ) -> &mut Self {
601        self.auth = BuilderAuthConfig::Enabled {
602            token_url: Some(token_url.into()),
603            client_id: Some(client_id.into()),
604            client_secret: Some(client_secret.into()),
605        };
606        self
607    }
608
609    /// Disable auth headers on outgoing requests.
610    pub fn disable_auth(&mut self) -> &mut Self {
611        self.auth = BuilderAuthConfig::Disabled;
612        self
613    }
614
615    /// Set the deadline used while connecting to the upstream host.
616    ///
617    /// The value is stored as-is here (no validation), the same way
618    /// [`RociaDbBuilder::host`] and
619    /// [`RociaDbBuilder::auth_client_credentials`] never validate before
620    /// [`RociaDbBuilder::build`] — validation (rejecting a zero timeout)
621    /// happens there instead. When this is never called, `build()` applies
622    /// a 10-second default unconditionally: without any timeout at all,
623    /// `.connect().await` could hang forever against a host with slow
624    /// DNS/TCP, which is a robustness gap rather than a mere convenience.
625    pub fn connect_timeout(&mut self, timeout: Duration) -> &mut Self {
626        self.connect_timeout = Some(timeout);
627        self
628    }
629
630    /// Build a client connected to the upstream.
631    ///
632    /// When auth is enabled, this fetches the first token and starts a
633    /// background task that refreshes it before it expires (the IdP's
634    /// tokens are short-lived — 600 seconds today) for as long as the
635    /// returned `RociaDbClient` or any of its clones is kept alive. Call
636    /// [`RociaDbClient::refresh_auth_token`] after an `UNAUTHENTICATED`
637    /// error to force an out-of-band refresh.
638    pub async fn build(&self) -> Result<RociaDbClient> {
639        let host = self
640            .host
641            .as_ref()
642            .ok_or_else(|| RociaDbError::connection("missing upstream host"))?;
643        info!(host = %host, "building rocia db client");
644        validate_host_path(host)?;
645        let connect_timeout = resolve_connect_timeout(self.connect_timeout)?;
646        let endpoint = Endpoint::from_shared(host.clone())
647            .connection_context("invalid upstream host")?
648            .tls_config(ClientTlsConfig::new().with_native_roots())
649            .connection_context("failed to configure TLS")?
650            .connect_timeout(connect_timeout);
651        let channel = endpoint
652            .connect()
653            .await
654            .connection_context("failed to connect to upstream")?;
655        let (interceptor, token_manager, token_refresh_guard) = match &self.auth {
656            BuilderAuthConfig::Disabled => {
657                warn!(host = %host, "building rocia db client with auth disabled");
658                (BearerInterceptor::disabled(), None, None)
659            }
660            BuilderAuthConfig::Enabled {
661                token_url,
662                client_id,
663                client_secret,
664            } => {
665                let token_url = token_url
666                    .clone()
667                    .or_else(|| env::var(AUTH_TOKEN_URL_ENV).ok())
668                    .ok_or_else(|| {
669                        RociaDbError::connection("missing auth token url (set AUTH_TOKEN_URL)")
670                    })?;
671                let client_id = client_id
672                    .clone()
673                    .or_else(|| env::var(AUTH_CLIENT_ID_ENV).ok())
674                    .ok_or_else(|| {
675                        RociaDbError::connection("missing auth client id (set AUTH_CLIENT_ID)")
676                    })?;
677                let client_secret = client_secret
678                    .clone()
679                    .or_else(|| env::var(AUTH_CLIENT_SECRET_ENV).ok())
680                    .ok_or_else(|| {
681                        RociaDbError::connection(
682                            "missing auth client secret (set AUTH_CLIENT_SECRET)",
683                        )
684                    })?;
685
686                // `token_url`/`client_id` are deliberately not logged here:
687                // they expose the auth infrastructure (IdP endpoint, OAuth2
688                // client identity) in any log pipeline configured at debug
689                // level.
690                debug!(host = %host, "initializing upstream token manager");
691                let token_manager =
692                    TokenManager::new(reqwest::Client::new(), token_url, client_id, client_secret)
693                        .await
694                        .auth_context("failed to initialize token manager")?;
695                let interceptor = token_manager.interceptor();
696                // Without a background refresh, the IdP token would simply
697                // expire after its `expires_in` (600s here). Start it now
698                // and keep the guard alive inside the client for as long as
699                // it (or any clone of it) exists.
700                let refresh_interval = token_manager.refresh_interval();
701                info!(
702                    host = %host,
703                    refresh_interval_secs = refresh_interval.as_secs(),
704                    "starting background token refresh"
705                );
706                let guard = token_manager.spawn_refresh(refresh_interval);
707                (interceptor, Some(token_manager), Some(Arc::new(guard)))
708            }
709        };
710        let upstream_document =
711            DocumentServiceClient::with_interceptor(channel.clone(), interceptor.clone());
712        let upstream_graph =
713            GraphServiceClient::with_interceptor(channel.clone(), interceptor.clone());
714        let upstream_file =
715            FileServiceClient::with_interceptor(channel.clone(), interceptor.clone());
716        let upstream_tenant = TenantServiceClient::with_interceptor(channel, interceptor);
717        info!(host = %host, "rocia db client ready");
718        Ok(RociaDbClient {
719            upstream_document,
720            upstream_graph,
721            upstream_file,
722            upstream_tenant,
723            token_manager,
724            _token_refresh_guard: token_refresh_guard,
725        })
726    }
727}
728
729impl RociaDbClient {
730    /// Force an immediate refresh of the upstream auth token.
731    ///
732    /// Call this after an RPC fails with `UNAUTHENTICATED` — the server
733    /// treats that status as the signal to renew the token, as opposed to
734    /// `PERMISSION_DENIED`, which means the token is valid but lacks the
735    /// required scope and retrying after a refresh will not help. A no-op
736    /// returning `Ok(())` when the client was built with
737    /// [`RociaDbBuilder::disable_auth`].
738    pub async fn refresh_auth_token(&self) -> Result<()> {
739        match &self.token_manager {
740            Some(manager) => manager.refresh_now().await,
741            None => Ok(()),
742        }
743    }
744
745    /// Signal that the cached upstream auth token should no longer be
746    /// trusted, without waiting for a fresh one.
747    ///
748    /// This is the lazy counterpart to
749    /// [`RociaDbClient::refresh_auth_token`]: it is **synchronous** and
750    /// returns immediately — it only wakes the background refresh task
751    /// (started by [`RociaDbBuilder::build`]) so it refreshes at the next
752    /// opportunity, instead of making the caller pay for the network round
753    /// trip. Prefer this over [`RociaDbClient::refresh_auth_token`] when
754    /// you just want to mark the token stale (for example, from a
755    /// fire-and-forget error handler) rather than block until a new one is
756    /// in hand before retrying. A no-op when the client was built with
757    /// [`RociaDbBuilder::disable_auth`].
758    pub fn invalidate_auth_token(&self) {
759        if let Some(manager) = &self.token_manager {
760            manager.request_refresh();
761        }
762    }
763}
764
765impl RociaDbClient {
766    /// Create or update a document, and optionally a graph node reference.
767    ///
768    /// `node_label` and `node_graph` must be provided together: if only one
769    /// of them is set, this returns an error before any network call.
770    ///
771    /// This call is **not atomic**: the document is written first, and the
772    /// graph node binding (when requested) is written second. If the node
773    /// write fails, the document is left in place without its node
774    /// binding — callers that need both or neither must handle that
775    /// themselves (for example by retrying the node write, or by treating
776    /// a document without its expected node as needing repair).
777    pub async fn create_document(
778        &self,
779        tenant_id: &str,
780        collection_name: &str,
781        document_id: &str,
782        value: Value,
783        node_label: Option<String>,
784        node_graph: Option<String>,
785    ) -> Result<()> {
786        let request_id = default_document_request_id(collection_name);
787        self.create_document_with_request_id(
788            tenant_id,
789            collection_name,
790            document_id,
791            &value,
792            node_label,
793            node_graph,
794            request_id,
795        )
796        .await
797    }
798
799    /// Same as [`RociaDbClient::create_document`], with a caller-provided
800    /// idempotency key for the document write (the `PutDoc` call only — the
801    /// graph node binding, when requested, keeps generating its own key,
802    /// exactly as it already does in [`RociaDbClient::create_document`]).
803    /// Reuse the same `request_id` on a retry so the server recognizes a
804    /// repeated write instead of applying it twice.
805    ///
806    /// Unlike [`RociaDbClient::create_document`], `value` is generic over
807    /// any `Serialize` type — consistent with
808    /// [`RociaDbClient::put_document_with_request_id`],
809    /// [`RociaDbClient::put_node_with_request_id`], and
810    /// [`RociaDbClient::add_edge_with_request_id`] — rather than requiring
811    /// the caller to pre-serialize into `serde_json::Value` first.
812    #[allow(clippy::too_many_arguments)]
813    pub async fn create_document_with_request_id<T: Serialize + ?Sized>(
814        &self,
815        tenant_id: &str,
816        collection_name: &str,
817        document_id: &str,
818        value: &T,
819        node_label: Option<String>,
820        node_graph: Option<String>,
821        request_id: impl Into<String>,
822    ) -> Result<()> {
823        validate_node_binding(&node_label, &node_graph)?;
824        debug!(
825            tenant_id = tenant_id,
826            collection = collection_name,
827            document_id = document_id,
828            has_node_binding = node_label.is_some() && node_graph.is_some(),
829            "upserting document"
830        );
831        let json = serde_json::to_vec(value)
832            .inspect_err(|error| {
833                error!(
834                    tenant_id = tenant_id,
835                    collection = collection_name,
836                    document_id = document_id,
837                    error = %error,
838                    "failed to encode document json"
839                );
840            })
841            .encode_context("document json")?;
842        let doc = PutDocRequest {
843            tenant_id: tenant_id.to_string(),
844            collection: collection_name.to_string(),
845            id: document_id.to_string(),
846            json,
847            request_id: request_id.into(),
848        };
849        let mut upstream_document = self.upstream_document.clone();
850        upstream_document
851            .put_doc(doc)
852            .await
853            .inspect_err(|error| {
854                error!(
855                    tenant_id = tenant_id,
856                    collection = collection_name,
857                    document_id = document_id,
858                    error = %error,
859                    "failed to upsert document"
860                );
861            })
862            .status_context("failed to upsert document")?;
863        info!(
864            tenant_id = tenant_id,
865            collection = collection_name,
866            document_id = document_id,
867            "document upserted"
868        );
869        if let (Some(label), Some(graph)) = (node_label, node_graph) {
870            debug!(
871                tenant_id = tenant_id,
872                collection = collection_name,
873                document_id = document_id,
874                graph = %graph,
875                label = %label,
876                "upserting graph node binding for document"
877            );
878            let json = serde_json::to_vec(&json!({
879                "collection": collection_name,
880                "id": document_id,
881            }))
882            .inspect_err(|error| {
883                error!(
884                    tenant_id = tenant_id,
885                    collection = collection_name,
886                    document_id = document_id,
887                    graph = %graph,
888                    label = %label,
889                    error = %error,
890                    "failed to encode node json"
891                );
892            })
893            .encode_context("node json")?;
894            let req = PutNodeRequest {
895                tenant_id: tenant_id.to_string(),
896                graph: graph.clone(),
897                node_id: format!("{}:{}", label, document_id),
898                json,
899                request_id: format!("put_node:{}", Uuid::new_v4()),
900            };
901            let mut upstream_graph = self.upstream_graph.clone();
902            upstream_graph
903                .put_node(req)
904                .await
905                .inspect_err(|error| {
906                    error!(
907                        tenant_id = tenant_id,
908                        collection = collection_name,
909                        document_id = document_id,
910                        graph = %graph,
911                        label = %label,
912                        error = %error,
913                        "failed to upsert graph node binding"
914                    );
915                })
916                .status_context("failed to upsert graph node binding")?;
917            info!(
918                tenant_id = tenant_id,
919                collection = collection_name,
920                document_id = document_id,
921                graph = %graph,
922                label = %label,
923                "graph node binding upserted"
924            );
925        }
926        Ok(())
927    }
928
929    /// Find documents whose `search_field` equals `value` (`FindByField`).
930    ///
931    /// `total_count` on the returned [`DocumentPage`] is a count over the
932    /// matching field-index entries — see [`DocumentPage`] for how this
933    /// compares to [`RociaDbClient::list_documents`] and
934    /// [`RociaDbClient::query_documents`].
935    pub async fn search_documents<T>(
936        &self,
937        tenant_id: &str,
938        collection_name: &str,
939        search_field: &str,
940        value: &impl Serialize,
941        limit: Option<u32>,
942        cursor: Option<&str>,
943    ) -> Result<DocumentPage<T>>
944    where
945        T: DeserializeOwned,
946    {
947        debug!(
948            tenant_id = tenant_id,
949            collection = collection_name,
950            search_field = search_field,
951            limit = limit.unwrap_or(DEFAULT_PAGE_SIZE),
952            cursor = cursor.unwrap_or(""),
953            "searching documents by field"
954        );
955        let page = page_request(limit, cursor)?;
956
957        let value_json = serde_json::to_vec(value)
958            .inspect_err(|error| {
959                error!(
960                    tenant_id = tenant_id,
961                    collection = collection_name,
962                    search_field = search_field,
963                    error = %error,
964                    "failed to encode search value"
965                );
966            })
967            .encode_context("search value")?;
968
969        let mut upstream_document = self.upstream_document.clone();
970        let result = upstream_document
971            .find_by_field(FindByFieldRequest {
972                tenant_id: tenant_id.to_string(),
973                collection: collection_name.to_string(),
974                field: search_field.to_string(),
975                value_json,
976                page,
977            })
978            .await
979            .inspect_err(|error| {
980                error!(
981                    tenant_id = tenant_id,
982                    collection = collection_name,
983                    search_field = search_field,
984                    error = %error,
985                    "failed to search documents"
986                );
987            })
988            .status_context("failed to search documents")?
989            .into_inner();
990
991        let resp = result
992            .json
993            .into_iter()
994            .map(|data| serde_json::from_slice::<T>(&data))
995            .collect::<std::result::Result<Vec<T>, serde_json::Error>>()
996            .inspect_err(|error| {
997                error!(
998                    tenant_id = tenant_id,
999                    collection = collection_name,
1000                    search_field = search_field,
1001                    error = %error,
1002                    "failed to decode search results"
1003                );
1004            })
1005            .decode_context("search results")?;
1006
1007        let next_cursor = result
1008            .page
1009            .and_then(|page| (!page.next_cursor.is_empty()).then_some(page.next_cursor));
1010        debug!(
1011            tenant_id = tenant_id,
1012            collection = collection_name,
1013            search_field = search_field,
1014            result_count = resp.len(),
1015            total_count = result.total_count,
1016            next_cursor = next_cursor.as_deref().unwrap_or(""),
1017            "document search completed"
1018        );
1019
1020        Ok(DocumentPage {
1021            items: resp,
1022            next_cursor,
1023            total_count: result.total_count,
1024        })
1025    }
1026
1027    /// Return one paginated page of every document in `collection_name`
1028    /// (`ListDoc`).
1029    ///
1030    /// `total_count` on the returned [`DocumentPage`] is **free**: the
1031    /// server keeps a running per-collection counter updated on every
1032    /// write, so reading it costs nothing beyond the listing itself — see
1033    /// [`DocumentPage`] for how this compares to
1034    /// [`RociaDbClient::search_documents`] and
1035    /// [`RociaDbClient::query_documents`].
1036    pub async fn list_documents<T>(
1037        &self,
1038        tenant_id: &str,
1039        collection_name: &str,
1040        limit: Option<u32>,
1041        cursor: Option<&str>,
1042    ) -> Result<DocumentPage<T>>
1043    where
1044        T: DeserializeOwned,
1045    {
1046        debug!(
1047            tenant_id = tenant_id,
1048            collection = collection_name,
1049            limit = limit.unwrap_or(DEFAULT_PAGE_SIZE),
1050            cursor = cursor.unwrap_or(""),
1051            "listing documents"
1052        );
1053        let page = page_request(limit, cursor)?;
1054        let mut upstream_document = self.upstream_document.clone();
1055        let result = upstream_document
1056            .list_doc(ListDocRequest {
1057                tenant_id: tenant_id.to_string(),
1058                collection: collection_name.to_string(),
1059                page,
1060            })
1061            .await
1062            .inspect_err(|error| {
1063                error!(
1064                    tenant_id = tenant_id,
1065                    collection = collection_name,
1066                    error = %error,
1067                    "failed to list documents"
1068                );
1069            })
1070            .status_context("failed to list documents")?
1071            .into_inner();
1072
1073        let resp = result
1074            .json
1075            .into_iter()
1076            .map(|data| serde_json::from_slice::<T>(&data))
1077            .collect::<std::result::Result<Vec<T>, serde_json::Error>>()
1078            .inspect_err(|error| {
1079                error!(
1080                    tenant_id = tenant_id,
1081                    collection = collection_name,
1082                    error = %error,
1083                    "failed to decode listed documents"
1084                );
1085            })
1086            .decode_context("listed documents")?;
1087
1088        let next_cursor = result
1089            .page
1090            .and_then(|page| (!page.next_cursor.is_empty()).then_some(page.next_cursor));
1091        debug!(
1092            tenant_id = tenant_id,
1093            collection = collection_name,
1094            result_count = resp.len(),
1095            total_count = result.total_count,
1096            next_cursor = next_cursor.as_deref().unwrap_or(""),
1097            "document listing completed"
1098        );
1099
1100        Ok(DocumentPage {
1101            items: resp,
1102            next_cursor,
1103            total_count: result.total_count,
1104        })
1105    }
1106
1107    /// List the document collections holding at least one document. Each
1108    /// `CollectionInfo` carries its document count.
1109    pub async fn list_collections(
1110        &self,
1111        tenant_id: &str,
1112        limit: Option<u32>,
1113        cursor: Option<&str>,
1114    ) -> Result<Page<CollectionInfo>> {
1115        debug!(
1116            tenant_id = tenant_id,
1117            limit = limit.unwrap_or(DEFAULT_PAGE_SIZE),
1118            cursor = cursor.unwrap_or(""),
1119            "listing collections"
1120        );
1121        let mut upstream_document = self.upstream_document.clone();
1122        let result = upstream_document
1123            .list_collections(ListCollectionsRequest {
1124                tenant_id: tenant_id.to_string(),
1125                page: page_request(limit, cursor)?,
1126            })
1127            .await
1128            .inspect_err(|error| {
1129                error!(
1130                    tenant_id = tenant_id,
1131                    error = %error,
1132                    "failed to list collections"
1133                );
1134            })
1135            .status_context("failed to list collections")?
1136            .into_inner();
1137
1138        Ok(Page {
1139            items: result.collections,
1140            next_cursor: result.page.and_then(|page| non_empty(page.next_cursor)),
1141        })
1142    }
1143
1144    /// Execute a paginated multi-filter document query.
1145    ///
1146    /// The underlying server applies filters with logical AND and uses the
1147    /// provided sort list in order. The returned `next_cursor` is an opaque
1148    /// server cursor that should be fed back unchanged.
1149    ///
1150    /// `total_count` on the returned [`DocumentPage`] is **expensive**: the
1151    /// server only knows it after filtering the complete candidate set for
1152    /// the query, so the cost scales with the number of candidates on every
1153    /// call — never call this in a loop just to get a count; see
1154    /// [`DocumentPage`] for the full comparison with
1155    /// [`RociaDbClient::list_documents`] and
1156    /// [`RociaDbClient::search_documents`].
1157    pub async fn query_documents<T>(
1158        &self,
1159        tenant_id: &str,
1160        collection_name: &str,
1161        filters: &[DocumentQueryFilter],
1162        sort: &[DocumentQuerySort],
1163        limit: Option<u32>,
1164        cursor: Option<&str>,
1165    ) -> Result<DocumentPage<T>>
1166    where
1167        T: DeserializeOwned,
1168    {
1169        debug!(
1170            tenant_id = tenant_id,
1171            collection = collection_name,
1172            filter_count = filters.len(),
1173            sort_count = sort.len(),
1174            limit = limit.unwrap_or(DEFAULT_PAGE_SIZE),
1175            cursor = cursor.unwrap_or(""),
1176            "querying documents"
1177        );
1178
1179        let page = page_request(limit, cursor)?;
1180
1181        let proto_filters = filters
1182            .iter()
1183            .map(|filter| -> Result<QueryFilter> {
1184                Ok(QueryFilter {
1185                    field: filter.field.clone(),
1186                    operator: filter.operator.as_proto(),
1187                    values_json: filter
1188                        .values
1189                        .iter()
1190                        .map(serde_json::to_vec)
1191                        .collect::<std::result::Result<Vec<_>, _>>()
1192                        .inspect_err(|error| {
1193                            error!(
1194                                tenant_id = tenant_id,
1195                                collection = collection_name,
1196                                field = %filter.field,
1197                                error = %error,
1198                                "failed to encode query filter value"
1199                            );
1200                        })
1201                        .encode_context("query filter value")?,
1202                })
1203            })
1204            .collect::<Result<Vec<_>>>()?;
1205
1206        let proto_sort = sort
1207            .iter()
1208            .map(|sort| QuerySort {
1209                field: sort.field.clone(),
1210                direction: sort.direction.as_proto(),
1211            })
1212            .collect::<Vec<_>>();
1213
1214        let mut upstream_document = self.upstream_document.clone();
1215        let result = upstream_document
1216            .query_doc(QueryDocRequest {
1217                tenant_id: tenant_id.to_string(),
1218                collection: collection_name.to_string(),
1219                filters: proto_filters,
1220                sort: proto_sort,
1221                page,
1222            })
1223            .await
1224            .inspect_err(|error| {
1225                error!(
1226                    tenant_id = tenant_id,
1227                    collection = collection_name,
1228                    error = %error,
1229                    "failed to query documents"
1230                );
1231            })
1232            .status_context("failed to query documents")?
1233            .into_inner();
1234
1235        let resp = result
1236            .json
1237            .into_iter()
1238            .map(|data| serde_json::from_slice::<T>(&data))
1239            .collect::<std::result::Result<Vec<T>, serde_json::Error>>()
1240            .inspect_err(|error| {
1241                error!(
1242                    tenant_id = tenant_id,
1243                    collection = collection_name,
1244                    error = %error,
1245                    "failed to decode queried documents"
1246                );
1247            })
1248            .decode_context("queried documents")?;
1249
1250        let next_cursor = result
1251            .page
1252            .and_then(|page| (!page.next_cursor.is_empty()).then_some(page.next_cursor));
1253        debug!(
1254            tenant_id = tenant_id,
1255            collection = collection_name,
1256            result_count = resp.len(),
1257            total_count = result.total_count,
1258            next_cursor = next_cursor.as_deref().unwrap_or(""),
1259            "document query completed"
1260        );
1261
1262        Ok(DocumentPage {
1263            items: resp,
1264            next_cursor,
1265            total_count: result.total_count,
1266        })
1267    }
1268
1269    /// Fetch a single document by id and decode its JSON payload into `T`
1270    /// (`GetDoc`).
1271    ///
1272    /// Unlike [`search_documents`](Self::search_documents),
1273    /// [`list_documents`](Self::list_documents) and
1274    /// [`query_documents`](Self::query_documents), this returns the value
1275    /// directly rather than a [`DocumentPage`]: there is nothing to paginate
1276    /// when fetching by id.
1277    pub async fn get_document<T>(
1278        &self,
1279        tenant_id: &str,
1280        collection_name: &str,
1281        document_id: &str,
1282    ) -> Result<T>
1283    where
1284        T: DeserializeOwned,
1285    {
1286        debug!(
1287            tenant_id = tenant_id,
1288            collection = collection_name,
1289            document_id = document_id,
1290            "loading document"
1291        );
1292        let mut upstream_document = self.upstream_document.clone();
1293        let result = upstream_document
1294            .get_doc(GetDocRequest {
1295                tenant_id: tenant_id.to_string(),
1296                collection: collection_name.to_string(),
1297                id: document_id.to_string(),
1298            })
1299            .await
1300            .inspect_err(|error| {
1301                error!(
1302                    tenant_id = tenant_id,
1303                    collection = collection_name,
1304                    document_id = document_id,
1305                    error = %error,
1306                    "failed to load document"
1307                );
1308            })
1309            .status_context("failed to load document")?
1310            .into_inner();
1311
1312        let resp = serde_json::from_slice::<T>(&result.json)
1313            .inspect_err(|error| {
1314                error!(
1315                    tenant_id = tenant_id,
1316                    collection = collection_name,
1317                    document_id = document_id,
1318                    error = %error,
1319                    "failed to decode document"
1320                );
1321            })
1322            .decode_context("document")?;
1323        debug!(
1324            tenant_id = tenant_id,
1325            collection = collection_name,
1326            document_id = document_id,
1327            "document loaded"
1328        );
1329
1330        Ok(resp)
1331    }
1332
1333    /// Upsert a batch of nodes in a graph with bounded concurrency (at most
1334    /// 10 `PutNode` calls in flight at once). `nodes` is consumed in the
1335    /// order the caller provides — duplicate `node_id`s are **not** merged,
1336    /// both are sent, in order.
1337    ///
1338    /// **This batch is not atomic and stops at the first error**: on
1339    /// failure, in-flight requests are cancelled and the error does not say
1340    /// which items had already succeeded. To resume after a failure, replay
1341    /// the same `nodes` sequence with the same [`NodeInput::request_id`]
1342    /// values you used the first time — the server deduplicates on
1343    /// `(tenant, operation, request_id)`, so already-applied writes are
1344    /// recognized and skipped rather than reapplied, and only the writes
1345    /// that never landed actually happen.
1346    pub async fn put_nodes(
1347        &self,
1348        tenant_id: &str,
1349        graph_name: &str,
1350        nodes: impl IntoIterator<Item = NodeInput>,
1351    ) -> Result<()> {
1352        let nodes: Vec<NodeInput> = nodes.into_iter().collect();
1353        debug!(
1354            tenant_id = tenant_id,
1355            graph = graph_name,
1356            node_count = nodes.len(),
1357            "upserting graph nodes batch"
1358        );
1359        let requests = build_put_node_requests(tenant_id, graph_name, nodes)?;
1360        stream::iter(requests.into_iter().map(Ok::<_, RociaDbError>))
1361            .try_for_each_concurrent(CONCURRENT_REQUESTS, |node| {
1362                let mut upstream = self.upstream_graph.clone();
1363                async move {
1364                    let graph = node.graph.clone();
1365                    let node_id = node.node_id.clone();
1366                    upstream
1367                        .put_node(node)
1368                        .await
1369                        .status_context("failed to upsert node")
1370                        .map_err(|error| {
1371                            error!(
1372                                graph = graph,
1373                                node_id = node_id,
1374                                error = %error,
1375                                "failed to upsert graph node"
1376                            );
1377                            error
1378                        })?;
1379                    Ok(())
1380                }
1381            })
1382            .await?;
1383        info!(
1384            tenant_id = tenant_id,
1385            graph = graph_name,
1386            "graph nodes batch upserted"
1387        );
1388        Ok(())
1389    }
1390
1391    /// Fetch a node and decode its JSON payload. `node_id` uses the
1392    /// `label:id` format.
1393    pub async fn get_node(
1394        &self,
1395        tenant_id: &str,
1396        graph_name: &str,
1397        node_id: &str,
1398    ) -> Result<Value> {
1399        debug!(
1400            tenant_id = tenant_id,
1401            graph = graph_name,
1402            node_id = node_id,
1403            "loading graph node"
1404        );
1405        let mut upstream_graph = self.upstream_graph.clone();
1406        let resp = upstream_graph
1407            .get_node(GetNodeRequest {
1408                tenant_id: tenant_id.to_string(),
1409                graph: graph_name.to_string(),
1410                node_id: node_id.to_string(),
1411            })
1412            .await
1413            .inspect_err(|error| {
1414                error!(
1415                    tenant_id = tenant_id,
1416                    graph = graph_name,
1417                    node_id = node_id,
1418                    error = %error,
1419                    "failed to load graph node"
1420                );
1421            })
1422            .status_context("failed to load graph node")?
1423            .into_inner();
1424        let value = serde_json::from_slice(&resp.json)
1425            .inspect_err(|error| {
1426                error!(
1427                    tenant_id = tenant_id,
1428                    graph = graph_name,
1429                    node_id = node_id,
1430                    error = %error,
1431                    "failed to decode node json"
1432                );
1433            })
1434            .decode_context("node json")?;
1435        debug!(
1436            tenant_id = tenant_id,
1437            graph = graph_name,
1438            node_id = node_id,
1439            "graph node loaded"
1440        );
1441        Ok(value)
1442    }
1443
1444    /// Upsert a batch of edges with bounded concurrency (at most 10
1445    /// `AddEdge` calls in flight at once). `edges` is consumed in the order
1446    /// the caller provides — duplicate `edge_id`s are **not** merged, both
1447    /// are sent, in order.
1448    ///
1449    /// The server returns `NOT_FOUND` for any edge whose `from` or `to`
1450    /// node does not already exist in `graph_name`: create both endpoint
1451    /// nodes before adding an edge between them.
1452    ///
1453    /// **This batch is not atomic and stops at the first error**: on
1454    /// failure, in-flight requests are cancelled and the error does not say
1455    /// which items had already succeeded. To resume after a failure, replay
1456    /// the same `edges` sequence with the same [`EdgeInput::request_id`]
1457    /// values you used the first time — the server deduplicates on
1458    /// `(tenant, operation, request_id)`, so already-applied writes are
1459    /// recognized and skipped rather than reapplied, and only the writes
1460    /// that never landed actually happen.
1461    pub async fn add_edges(
1462        &self,
1463        tenant_id: &str,
1464        graph_name: &str,
1465        edges: impl IntoIterator<Item = EdgeInput>,
1466    ) -> Result<()> {
1467        let edges: Vec<EdgeInput> = edges.into_iter().collect();
1468        debug!(
1469            tenant_id = tenant_id,
1470            graph = graph_name,
1471            edge_count = edges.len(),
1472            "upserting graph edges batch"
1473        );
1474        let requests = build_add_edge_requests(tenant_id, graph_name, edges)?;
1475        stream::iter(requests.into_iter().map(Ok::<_, RociaDbError>))
1476            .try_for_each_concurrent(CONCURRENT_REQUESTS, |edge| {
1477                let mut upstream = self.upstream_graph.clone();
1478                async move {
1479                    let graph = edge.graph.clone();
1480                    let edge_id = edge.edge_id.clone();
1481                    let from = edge.from.clone();
1482                    let to = edge.to.clone();
1483                    let label = edge.label.clone();
1484                    upstream
1485                        .add_edge(edge)
1486                        .await
1487                        .status_context("failed to add edge")
1488                        .map_err(|error| {
1489                            error!(
1490                                graph = graph,
1491                                edge_id = edge_id,
1492                                from = from,
1493                                to = to,
1494                                label = label,
1495                                error = %error,
1496                                "failed to upsert graph edge"
1497                            );
1498                            error
1499                        })?;
1500                    Ok(())
1501                }
1502            })
1503            .await?;
1504        info!(
1505            tenant_id = tenant_id,
1506            graph = graph_name,
1507            "graph edges batch upserted"
1508        );
1509
1510        Ok(())
1511    }
1512
1513    /// Delete an edge by id.
1514    pub async fn delete_edge(
1515        &self,
1516        tenant_id: &str,
1517        graph_name: &str,
1518        edge_id: &str,
1519    ) -> Result<()> {
1520        debug!(
1521            tenant_id = tenant_id,
1522            graph = graph_name,
1523            edge_id = edge_id,
1524            "deleting graph edge"
1525        );
1526        self.delete_edge_with_request_id(
1527            tenant_id,
1528            graph_name,
1529            edge_id,
1530            format!("delete_edge:{}", Uuid::new_v4()),
1531        )
1532        .await?;
1533        info!(
1534            tenant_id = tenant_id,
1535            graph = graph_name,
1536            edge_id = edge_id,
1537            "graph edge deleted"
1538        );
1539        Ok(())
1540    }
1541}
1542
1543#[cfg(test)]
1544mod tests {
1545    use super::{
1546        BearerInterceptor, DEFAULT_CONNECT_TIMEOUT, DocumentPage, DocumentServiceClient, EdgeInput,
1547        FileServiceClient, GraphServiceClient, NodeInput, RociaDbBuilder, RociaDbClient,
1548        TenantServiceClient, build_add_edge_requests, build_put_node_requests,
1549        default_document_request_id, resolve_connect_timeout, validate_host_path,
1550        validate_node_binding,
1551    };
1552    use crate::{FileStreamUploadOptions, RociaDbError};
1553    use futures::stream;
1554    use std::time::Duration;
1555    use tonic::transport::Endpoint;
1556
1557    /// A `RociaDbClient` wired to a channel that never actually dials
1558    /// (`Endpoint::connect_lazy` performs no I/O — it only builds a
1559    /// connector that would try to connect on the *first real RPC*). Used
1560    /// to test the client-side gating that must reject a request before
1561    /// ever reaching the network — if such a test regressed and the
1562    /// gating ran too late, it would hang or fail against the unreachable
1563    /// `127.0.0.1:1` host instead of returning promptly.
1564    fn lazy_test_client() -> RociaDbClient {
1565        let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy();
1566        let interceptor = BearerInterceptor::disabled();
1567        RociaDbClient {
1568            upstream_document: DocumentServiceClient::with_interceptor(
1569                channel.clone(),
1570                interceptor.clone(),
1571            ),
1572            upstream_graph: GraphServiceClient::with_interceptor(
1573                channel.clone(),
1574                interceptor.clone(),
1575            ),
1576            upstream_file: FileServiceClient::with_interceptor(
1577                channel.clone(),
1578                interceptor.clone(),
1579            ),
1580            upstream_tenant: TenantServiceClient::with_interceptor(channel, interceptor),
1581            token_manager: None,
1582            _token_refresh_guard: None,
1583        }
1584    }
1585
1586    #[test]
1587    fn node_binding_accepts_both_absent() {
1588        validate_node_binding(&None, &None).expect("both absent must be accepted");
1589    }
1590
1591    #[test]
1592    fn node_binding_accepts_both_present() {
1593        validate_node_binding(&Some("product".to_string()), &Some("products".to_string()))
1594            .expect("both present must be accepted");
1595    }
1596
1597    #[test]
1598    fn node_binding_rejects_label_without_graph() {
1599        let error = validate_node_binding(&Some("product".to_string()), &None)
1600            .expect_err("node_label without node_graph must be rejected");
1601        assert!(matches!(error, RociaDbError::Validation(_)));
1602        assert!(error.to_string().contains("must be provided together"));
1603        assert!(error.to_string().contains("node_label=Some(\"product\")"));
1604    }
1605
1606    #[test]
1607    fn node_binding_rejects_graph_without_label() {
1608        let error = validate_node_binding(&None, &Some("products".to_string()))
1609            .expect_err("node_graph without node_label must be rejected");
1610        assert!(matches!(error, RociaDbError::Validation(_)));
1611        assert!(error.to_string().contains("must be provided together"));
1612        assert!(error.to_string().contains("node_graph=Some(\"products\")"));
1613    }
1614
1615    #[test]
1616    fn client_is_send_sync_so_an_arc_needs_no_mutex() {
1617        // `RociaDbClient` methods take `&self`, not `&mut self` (each call
1618        // clones the cheap, Arc-backed inner service client before issuing
1619        // its RPC). This is only sound to share across tasks if the type is
1620        // both `Send` and `Sync`: a plain compile-time trait assertion, not
1621        // a runtime check, but it locks in the intent so a future field
1622        // that breaks it fails the build instead of shipping silently.
1623        fn assert_send_sync<T: Send + Sync>() {}
1624        assert_send_sync::<RociaDbClient>();
1625        assert_send_sync::<std::sync::Arc<RociaDbClient>>();
1626    }
1627
1628    // `build_put_node_requests` / `build_add_edge_requests` are the pure,
1629    // network-free cores of `RociaDbClient::put_nodes` /
1630    // `RociaDbClient::add_edges` (see their doc comments). These tests lock
1631    // in the three properties an ordered `Vec<NodeInput>` / `Vec<EdgeInput>`
1632    // batch input must have: caller order is preserved, duplicate keys are
1633    // not merged, and each item gets its own idempotency key.
1634
1635    #[test]
1636    fn put_node_requests_preserve_caller_order() {
1637        // A `HashMap`-keyed batch input could not guarantee this —
1638        // iteration order over a hash map is unspecified, so it could
1639        // silently reorder `PutNode` calls relative to what the caller
1640        // wrote.
1641        let nodes = vec![
1642            NodeInput {
1643                node_id: "product:3".to_string(),
1644                value: serde_json::json!({"n": 3}),
1645                request_id: None,
1646            },
1647            NodeInput {
1648                node_id: "product:1".to_string(),
1649                value: serde_json::json!({"n": 1}),
1650                request_id: None,
1651            },
1652            NodeInput {
1653                node_id: "product:2".to_string(),
1654                value: serde_json::json!({"n": 2}),
1655                request_id: None,
1656            },
1657        ];
1658        let requests =
1659            build_put_node_requests("tenant", "catalog", nodes).expect("build must succeed");
1660        let ids: Vec<&str> = requests.iter().map(|r| r.node_id.as_str()).collect();
1661        assert_eq!(ids, vec!["product:3", "product:1", "product:2"]);
1662    }
1663
1664    #[test]
1665    fn put_node_requests_do_not_merge_duplicate_node_ids() {
1666        let nodes = vec![
1667            NodeInput {
1668                node_id: "product:1".to_string(),
1669                value: serde_json::json!({"n": 1}),
1670                request_id: None,
1671            },
1672            NodeInput {
1673                node_id: "product:1".to_string(),
1674                value: serde_json::json!({"n": 2}),
1675                request_id: None,
1676            },
1677        ];
1678        let requests =
1679            build_put_node_requests("tenant", "catalog", nodes).expect("build must succeed");
1680        assert_eq!(
1681            requests.len(),
1682            2,
1683            "a HashMap keyed by node_id would have collapsed this to one request"
1684        );
1685        assert_eq!(requests[0].node_id, "product:1");
1686        assert_eq!(requests[1].node_id, "product:1");
1687        assert_ne!(
1688            requests[0].json, requests[1].json,
1689            "each duplicate keeps its own payload"
1690        );
1691    }
1692
1693    #[test]
1694    fn put_node_requests_use_node_id_verbatim_with_no_label_recomposition() {
1695        let nodes = vec![NodeInput {
1696            node_id: "product:sku-1".to_string(),
1697            value: serde_json::json!({}),
1698            request_id: None,
1699        }];
1700        let requests =
1701            build_put_node_requests("tenant", "catalog", nodes).expect("build must succeed");
1702        assert_eq!(requests[0].node_id, "product:sku-1");
1703    }
1704
1705    #[test]
1706    fn put_node_requests_pass_through_caller_supplied_request_id() {
1707        let nodes = vec![NodeInput {
1708            node_id: "product:1".to_string(),
1709            value: serde_json::json!({}),
1710            request_id: Some("caller-chosen-id".to_string()),
1711        }];
1712        let requests =
1713            build_put_node_requests("tenant", "catalog", nodes).expect("build must succeed");
1714        assert_eq!(requests[0].request_id, "caller-chosen-id");
1715    }
1716
1717    #[test]
1718    fn put_node_requests_default_request_id_matches_the_single_item_put_node_prefix() {
1719        // `put_nodes` (batch) and `put_node` (single-item) both issue
1720        // `PutNode` calls, so an absent id must default to the exact same
1721        // prefix on both paths: `put_node:<uuid>`.
1722        let nodes = vec![
1723            NodeInput {
1724                node_id: "product:1".to_string(),
1725                value: serde_json::json!({}),
1726                request_id: None,
1727            },
1728            NodeInput {
1729                node_id: "product:2".to_string(),
1730                value: serde_json::json!({}),
1731                request_id: None,
1732            },
1733        ];
1734        let requests =
1735            build_put_node_requests("tenant", "catalog", nodes).expect("build must succeed");
1736        for request in &requests {
1737            let uuid_part = request
1738                .request_id
1739                .strip_prefix("put_node:")
1740                .expect("default request_id must use the put_node: prefix");
1741            uuid::Uuid::parse_str(uuid_part).expect("suffix after the prefix must be a uuid");
1742        }
1743        assert_ne!(
1744            requests[0].request_id, requests[1].request_id,
1745            "each item without an explicit request_id must get its own generated id"
1746        );
1747    }
1748
1749    #[test]
1750    fn add_edge_requests_preserve_caller_order() {
1751        let edges = vec![
1752            EdgeInput {
1753                edge_id: "e3".to_string(),
1754                from: "a".to_string(),
1755                to: "b".to_string(),
1756                label: "knows".to_string(),
1757                value: serde_json::json!({}),
1758                request_id: None,
1759            },
1760            EdgeInput {
1761                edge_id: "e1".to_string(),
1762                from: "b".to_string(),
1763                to: "c".to_string(),
1764                label: "knows".to_string(),
1765                value: serde_json::json!({}),
1766                request_id: None,
1767            },
1768            EdgeInput {
1769                edge_id: "e2".to_string(),
1770                from: "c".to_string(),
1771                to: "d".to_string(),
1772                label: "knows".to_string(),
1773                value: serde_json::json!({}),
1774                request_id: None,
1775            },
1776        ];
1777        let requests =
1778            build_add_edge_requests("tenant", "catalog", edges).expect("build must succeed");
1779        let ids: Vec<&str> = requests.iter().map(|r| r.edge_id.as_str()).collect();
1780        assert_eq!(ids, vec!["e3", "e1", "e2"]);
1781    }
1782
1783    #[test]
1784    fn add_edge_requests_do_not_merge_duplicate_edge_ids() {
1785        let edges = vec![
1786            EdgeInput {
1787                edge_id: "e1".to_string(),
1788                from: "a".to_string(),
1789                to: "b".to_string(),
1790                label: "knows".to_string(),
1791                value: serde_json::json!({"v": 1}),
1792                request_id: None,
1793            },
1794            EdgeInput {
1795                edge_id: "e1".to_string(),
1796                from: "a".to_string(),
1797                to: "b".to_string(),
1798                label: "knows".to_string(),
1799                value: serde_json::json!({"v": 2}),
1800                request_id: None,
1801            },
1802        ];
1803        let requests =
1804            build_add_edge_requests("tenant", "catalog", edges).expect("build must succeed");
1805        assert_eq!(
1806            requests.len(),
1807            2,
1808            "a HashMap keyed by edge_id would have collapsed this to one request"
1809        );
1810        assert_ne!(
1811            requests[0].json, requests[1].json,
1812            "each duplicate keeps its own payload"
1813        );
1814    }
1815
1816    #[test]
1817    fn add_edge_requests_pass_through_caller_supplied_request_id() {
1818        let edges = vec![EdgeInput {
1819            edge_id: "e1".to_string(),
1820            from: "a".to_string(),
1821            to: "b".to_string(),
1822            label: "knows".to_string(),
1823            value: serde_json::json!({}),
1824            request_id: Some("caller-chosen-id".to_string()),
1825        }];
1826        let requests =
1827            build_add_edge_requests("tenant", "catalog", edges).expect("build must succeed");
1828        assert_eq!(requests[0].request_id, "caller-chosen-id");
1829    }
1830
1831    #[test]
1832    fn add_edge_requests_default_request_id_stays_a_bare_uuid() {
1833        // Unlike nodes, edges default to no prefix at all (a bare
1834        // `Uuid::new_v4().to_string()`).
1835        let edges = vec![
1836            EdgeInput {
1837                edge_id: "e1".to_string(),
1838                from: "a".to_string(),
1839                to: "b".to_string(),
1840                label: "knows".to_string(),
1841                value: serde_json::json!({}),
1842                request_id: None,
1843            },
1844            EdgeInput {
1845                edge_id: "e2".to_string(),
1846                from: "b".to_string(),
1847                to: "c".to_string(),
1848                label: "knows".to_string(),
1849                value: serde_json::json!({}),
1850                request_id: None,
1851            },
1852        ];
1853        let requests =
1854            build_add_edge_requests("tenant", "catalog", edges).expect("build must succeed");
1855        for request in &requests {
1856            uuid::Uuid::parse_str(&request.request_id)
1857                .expect("default request_id must be a bare uuid with no prefix");
1858        }
1859        assert_ne!(
1860            requests[0].request_id, requests[1].request_id,
1861            "each item without an explicit request_id must get its own generated id"
1862        );
1863    }
1864
1865    #[test]
1866    fn document_page_exposes_items_next_cursor_and_total_count() {
1867        let page = DocumentPage {
1868            items: vec!["a", "b"],
1869            next_cursor: Some("cursor-2".to_string()),
1870            total_count: 42,
1871        };
1872        assert_eq!(page.items, vec!["a", "b"]);
1873        assert_eq!(page.next_cursor.as_deref(), Some("cursor-2"));
1874        assert_eq!(page.total_count, 42);
1875    }
1876
1877    #[test]
1878    fn document_page_has_no_next_cursor_on_the_last_page() {
1879        let page: DocumentPage<i32> = DocumentPage {
1880            items: vec![1, 2, 3],
1881            next_cursor: None,
1882            total_count: 3,
1883        };
1884        assert!(page.next_cursor.is_none());
1885        assert_eq!(page.items, vec![1, 2, 3]);
1886        assert_eq!(page.total_count, 3);
1887    }
1888
1889    #[test]
1890    fn document_page_derives_clone_and_equality() {
1891        let page = DocumentPage {
1892            items: vec![1],
1893            next_cursor: None,
1894            total_count: 1,
1895        };
1896        assert_eq!(page.clone(), page);
1897        let different = DocumentPage {
1898            items: vec![1],
1899            next_cursor: None,
1900            total_count: 2,
1901        };
1902        assert_ne!(page, different);
1903    }
1904
1905    #[test]
1906    fn host_path_validation_accepts_a_host_with_no_path_component() {
1907        validate_host_path("http://127.0.0.1:50051").expect("an absent path must be accepted");
1908    }
1909
1910    #[test]
1911    fn host_path_validation_accepts_a_bare_root_path() {
1912        validate_host_path("http://127.0.0.1:50051/").expect("a bare \"/\" must be accepted");
1913    }
1914
1915    #[test]
1916    fn host_path_validation_rejects_a_host_carrying_a_leftover_path() {
1917        let error = validate_host_path("http://127.0.0.1:50051/v1")
1918            .expect_err("a host with a non-root path must be rejected");
1919        assert!(matches!(error, RociaDbError::Connection { .. }));
1920        assert!(
1921            error.to_string().contains("/v1"),
1922            "the error should name the offending path, got: {error}"
1923        );
1924    }
1925
1926    #[test]
1927    fn default_connect_timeout_matches_the_typescript_sdk_default() {
1928        assert_eq!(DEFAULT_CONNECT_TIMEOUT, Duration::from_secs(10));
1929    }
1930
1931    #[test]
1932    fn resolve_connect_timeout_falls_back_to_the_default_when_unset() {
1933        let timeout =
1934            resolve_connect_timeout(None).expect("the default timeout must always be accepted");
1935        assert_eq!(timeout, DEFAULT_CONNECT_TIMEOUT);
1936    }
1937
1938    #[test]
1939    fn resolve_connect_timeout_accepts_a_caller_supplied_positive_value() {
1940        let timeout = resolve_connect_timeout(Some(Duration::from_secs(3)))
1941            .expect("a positive explicit timeout must be accepted");
1942        assert_eq!(timeout, Duration::from_secs(3));
1943    }
1944
1945    #[test]
1946    fn resolve_connect_timeout_rejects_zero() {
1947        let error = resolve_connect_timeout(Some(Duration::ZERO))
1948            .expect_err("a zero connect timeout must be rejected");
1949        assert!(matches!(error, RociaDbError::Validation(_)));
1950        assert!(error.to_string().contains("greater than zero"));
1951    }
1952
1953    #[test]
1954    fn builder_connect_timeout_setter_stores_the_value_unvalidated() {
1955        // Mirrors `RociaDbBuilder::host` / `auth_client_credentials`: the
1956        // setter never validates, only `build()` does (via
1957        // `resolve_connect_timeout`, tested above) — so even a nonsensical
1958        // zero duration must be stored as-is here.
1959        let mut builder = RociaDbBuilder::new();
1960        builder.connect_timeout(Duration::ZERO);
1961        assert_eq!(builder.connect_timeout, Some(Duration::ZERO));
1962
1963        let mut builder = RociaDbBuilder::new();
1964        builder.connect_timeout(Duration::from_secs(42));
1965        assert_eq!(builder.connect_timeout, Some(Duration::from_secs(42)));
1966    }
1967
1968    #[tokio::test]
1969    async fn build_rejects_a_zero_connect_timeout_before_any_network_call() {
1970        // `validate_host_path` and the connect-timeout check both run
1971        // before `Endpoint::connect()`, so this must return promptly with
1972        // `Validation` instead of hanging or failing against the
1973        // (deliberately unreachable) host.
1974        let mut builder = RociaDbBuilder::new();
1975        builder
1976            .host("http://127.0.0.1:1")
1977            .connect_timeout(Duration::ZERO);
1978        // `RociaDbClient` intentionally does not derive `Debug` (it would
1979        // expose channel/interceptor internals), so `expect_err` cannot be
1980        // used here — match instead.
1981        let error = match builder.build().await {
1982            Ok(_) => panic!("a zero connect timeout must fail build()"),
1983            Err(error) => error,
1984        };
1985        assert!(matches!(error, RociaDbError::Validation(_)));
1986    }
1987
1988    #[tokio::test]
1989    async fn build_rejects_a_host_with_a_leftover_path_before_any_network_call() {
1990        let mut builder = RociaDbBuilder::new();
1991        builder.host("http://127.0.0.1:1/v1");
1992        let error = match builder.build().await {
1993            Ok(_) => panic!("a host carrying a path must fail build()"),
1994            Err(error) => error,
1995        };
1996        assert!(matches!(error, RociaDbError::Connection { .. }));
1997    }
1998
1999    // `BuilderAuthConfig`'s manual `Debug` impl must redact `client_secret`
2000    // — a derived `Debug` would print it in clear text.
2001    #[test]
2002    fn builder_debug_output_redacts_the_client_secret() {
2003        let mut builder = RociaDbBuilder::new();
2004        builder.auth_client_credentials(
2005            "https://idp.example.com/token",
2006            "client-123",
2007            "super-secret-value",
2008        );
2009        let debug_output = format!("{builder:?}");
2010        assert!(
2011            !debug_output.contains("super-secret-value"),
2012            "the raw client_secret must never appear in Debug output, got: {debug_output}"
2013        );
2014        assert!(
2015            debug_output.contains("[redacted]"),
2016            "the redaction placeholder must appear, got: {debug_output}"
2017        );
2018        // Non-sensitive fields must stay visible: only the secret is
2019        // redacted, not the whole auth config (still useful for
2020        // diagnostics).
2021        assert!(debug_output.contains("https://idp.example.com/token"));
2022        assert!(debug_output.contains("client-123"));
2023    }
2024
2025    #[test]
2026    fn default_document_request_id_uses_the_put_document_prefix_with_a_fresh_uuid_each_time() {
2027        let first = default_document_request_id("catalog");
2028        let second = default_document_request_id("catalog");
2029        let uuid_part = first
2030            .strip_prefix("put_document:catalog:")
2031            .expect("default request_id must use the put_document:{collection}: prefix");
2032        uuid::Uuid::parse_str(uuid_part).expect("suffix after the prefix must be a uuid");
2033        assert_ne!(
2034            first, second,
2035            "each call without an explicit request_id must get its own generated id"
2036        );
2037    }
2038
2039    // `upload_file_chunked`'s pre-flight validation (file size, checksum
2040    // length) must run — and fail — before the method ever touches the
2041    // network, so these tests run against a client wired to an unreachable
2042    // host and must still return promptly.
2043
2044    #[tokio::test]
2045    async fn upload_file_chunked_rejects_an_oversized_file_before_any_network_call() {
2046        let client = lazy_test_client();
2047        let oversized = 5u64 * 1024 * 1024 * 1024 + 1; // 5 GiB + 1 byte
2048        let result = client
2049            .upload_file_chunked(
2050                "tenant",
2051                "bucket",
2052                "file",
2053                oversized,
2054                vec![0u8; 32],
2055                stream::empty::<Vec<u8>>(),
2056                FileStreamUploadOptions::default(),
2057            )
2058            .await;
2059        let error = result.expect_err("a file over the 5 GiB limit must be rejected");
2060        assert!(matches!(error, RociaDbError::Validation(_)));
2061        assert!(error.to_string().contains("5 GiB"));
2062    }
2063
2064    #[tokio::test]
2065    async fn upload_file_chunked_rejects_a_wrong_length_checksum_before_any_network_call() {
2066        let client = lazy_test_client();
2067        let result = client
2068            .upload_file_chunked(
2069                "tenant",
2070                "bucket",
2071                "file",
2072                0,
2073                vec![0u8; 10], // must be exactly 32 bytes (sha256)
2074                stream::empty::<Vec<u8>>(),
2075                FileStreamUploadOptions::default(),
2076            )
2077            .await;
2078        let error = result.expect_err("a checksum that is not 32 bytes must be rejected");
2079        assert!(matches!(error, RociaDbError::Validation(_)));
2080        assert!(error.to_string().contains("32 bytes"));
2081    }
2082
2083    #[tokio::test]
2084    async fn invalidate_auth_token_is_a_harmless_no_op_when_auth_is_disabled() {
2085        // `lazy_test_client()` itself needs a tokio runtime just to build
2086        // its (never-dialed) channel — but `invalidate_auth_token` is
2087        // called here with no `.await`, which is the point: it is
2088        // synchronous by design and must never need to wait on a network
2089        // round trip, unlike `refresh_auth_token`.
2090        let client = lazy_test_client();
2091        client.invalidate_auth_token();
2092    }
2093}