1#![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};
91pub use pb::upstream::v1::{
97 CollectionInfo, DownloadResponse, Neighbor, StatResponse, UploadRequest,
98};
99pub 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
127const CONCURRENT_REQUESTS: usize = 10;
129const 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";
134const 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
149impl 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#[derive(Debug)]
172pub struct RociaDbBuilder {
173 host: Option<String>,
174 auth: BuilderAuthConfig,
175 connect_timeout: Option<Duration>,
176}
177
178#[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 token_manager: Option<TokenManager>,
197 _token_refresh_guard: Option<Arc<TokenRefreshGuard>>,
201}
202
203#[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#[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
239pub(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
262pub(crate) fn non_empty(value: String) -> Option<String> {
264 (!value.is_empty()).then_some(value)
265}
266
267fn 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#[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#[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#[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 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#[non_exhaustive]
345#[derive(Debug, Clone)]
346pub struct DocumentQuerySort {
347 pub field: String,
348 pub direction: DocumentQuerySortDirection,
349}
350
351impl DocumentQuerySort {
352 pub fn new(field: impl Into<String>, direction: DocumentQuerySortDirection) -> Self {
354 Self {
355 field: field.into(),
356 direction,
357 }
358 }
359}
360
361#[non_exhaustive]
368#[derive(Debug, Clone, PartialEq)]
369pub struct NodeInput {
370 pub node_id: String,
371 pub value: Value,
372 pub request_id: Option<String>,
382}
383
384impl NodeInput {
385 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 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#[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 pub request_id: Option<String>,
418}
419
420impl EdgeInput {
421 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 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
449fn 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
482fn 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
520fn default_document_request_id(collection_name: &str) -> String {
529 format!("put_document:{}:{}", collection_name, Uuid::new_v4())
530}
531
532fn 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
552fn 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 pub fn new() -> Self {
585 Self::default()
586 }
587
588 pub fn host(&mut self, host: impl Into<String>) -> &mut Self {
590 self.host = Some(host.into());
591 self
592 }
593
594 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 pub fn disable_auth(&mut self) -> &mut Self {
611 self.auth = BuilderAuthConfig::Disabled;
612 self
613 }
614
615 pub fn connect_timeout(&mut self, timeout: Duration) -> &mut Self {
626 self.connect_timeout = Some(timeout);
627 self
628 }
629
630 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 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 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 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 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 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 #[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 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 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 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 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 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 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 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 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 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 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 fn assert_send_sync<T: Send + Sync>() {}
1624 assert_send_sync::<RociaDbClient>();
1625 assert_send_sync::<std::sync::Arc<RociaDbClient>>();
1626 }
1627
1628 #[test]
1636 fn put_node_requests_preserve_caller_order() {
1637 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 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 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 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 let mut builder = RociaDbBuilder::new();
1975 builder
1976 .host("http://127.0.0.1:1")
1977 .connect_timeout(Duration::ZERO);
1978 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 #[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 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 #[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; 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], 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 let client = lazy_test_client();
2091 client.invalidate_auth_token();
2092 }
2093}