1pub(crate) use crate::application::json_input::{
2 json_bool_field, json_f32_field, json_string_field, json_usize_field,
3};
4pub(crate) use crate::application::{
5 AdminUseCases, CreateEdgeInput, CreateEntityOutput, CreateNodeGraphLinkInput, CreateNodeInput,
6 CreateNodeTableLinkInput, CreateRowInput, CreateVectorInput, DeleteEntityInput, EntityUseCases,
7 ExplainQueryInput, GraphCentralityInput, GraphClusteringInput, GraphCommunitiesInput,
8 GraphComponentsInput, GraphCyclesInput, GraphHitsInput, GraphNeighborhoodInput,
9 GraphPersonalizedPageRankInput, GraphShortestPathInput, GraphTopologicalSortInput,
10 GraphTraversalInput, GraphUseCases, InspectNativeArtifactInput, NativeUseCases,
11 PatchEntityInput, SearchHybridInput, SearchIvfInput, SearchSimilarInput, SearchTextInput,
12};
13use std::collections::BTreeMap;
14use std::pin::Pin;
15use std::sync::Arc;
16use std::time::{SystemTime, UNIX_EPOCH};
17
18use crate::api::{RedDBOptions, RedDBResult};
19use crate::auth::middleware::{check_permission, AuthResult, AuthSource};
20use crate::auth::store::AuthStore;
21use crate::auth::Role;
22use crate::health::{HealthProvider, HealthState};
23use crate::json::{
24 from_str as json_from_str, to_string as json_to_string, Map, Value as JsonValue,
25};
26use crate::runtime::query_request::{
27 ParamValue, PreparedId, PreparedRegistry, QueryRequest as RuntimeQueryRequest,
28 QueryRequestExecutor,
29};
30use crate::runtime::{
31 RedDBRuntime, RuntimeFilter, RuntimeFilterValue, RuntimeGraphCentralityAlgorithm,
32 RuntimeGraphCentralityResult, RuntimeGraphClusteringResult, RuntimeGraphCommunityAlgorithm,
33 RuntimeGraphCommunityResult, RuntimeGraphComponentsMode, RuntimeGraphComponentsResult,
34 RuntimeGraphCyclesResult, RuntimeGraphDirection, RuntimeGraphHitsResult,
35 RuntimeGraphNeighborhoodResult, RuntimeGraphPathAlgorithm, RuntimeGraphPathResult,
36 RuntimeGraphPattern, RuntimeGraphProjection, RuntimeGraphTopologicalSortResult,
37 RuntimeGraphTraversalResult, RuntimeGraphTraversalStrategy, RuntimeIvfSearchResult,
38 RuntimeQueryResult, RuntimeQueryWeights, RuntimeStats, ScanPage,
39};
40use crate::storage::unified::devx::refs::{NodeRef, TableRef};
41use crate::storage::unified::{Metadata, MetadataValue};
42use crate::storage::{EntityData, EntityId, UnifiedEntity};
43use reddb_types::Value;
44use tokio_stream::wrappers::TcpListenerStream;
45use tonic::metadata::MetadataMap;
46use tonic::{Request, Response, Status};
47
48pub use reddb_grpc_proto as proto;
54
55use proto::red_db_server::{RedDb, RedDbServer};
56use proto::{
57 ask_stream_event, AskAnswerToken, AskReply, AskRequest, AskSources, AskStreamEvent,
58 BatchInsertChunk, BatchInsertReply, BatchQueryReply, BatchQueryRequest, BulkEntityReply,
59 Citation, CollectionRequest, CollectionsReply, DeleteEntityRequest, DeploymentProfileRequest,
60 Empty, EntityReply, ExecutePreparedRequest, ExportRequest, GraphProjectionUpsertRequest,
61 HealthReply, IndexNameRequest, IndexToggleRequest, JsonBulkCreateRequest, JsonCreateRequest,
62 JsonPayloadRequest, KvWatchEvent, KvWatchRequest, ManifestRequest, OperationReply,
63 PayloadReply, PrepareQueryReply, PrepareQueryRequest, QueryReply, QueryRequest, QueryValue,
64 ScanEntity, ScanReply, ScanRequest, StatsReply, TopologyReply, TopologyRequest,
65 UpdateEntityRequest, Validation, ValidationItem,
66};
67
68pub(crate) mod catalog_dispatch;
69pub(crate) mod control_support;
70mod entity_ops;
71mod input_support;
72pub(crate) mod scan_json;
73
74use self::catalog_dispatch::*;
75use self::control_support::*;
76use self::entity_ops::*;
77use self::input_support::*;
78use self::scan_json::*;
79
80#[derive(Debug, Clone)]
81pub struct GrpcServerOptions {
82 pub bind_addr: String,
83 pub tls: Option<GrpcTlsOptions>,
88}
89
90#[derive(Debug, Clone)]
96pub struct GrpcTlsOptions {
97 pub cert_pem: Vec<u8>,
99 pub key_pem: Vec<u8>,
101 pub client_ca_pem: Option<Vec<u8>>,
106}
107
108impl GrpcTlsOptions {
109 pub fn to_tonic_config(
113 &self,
114 ) -> Result<tonic::transport::ServerTlsConfig, Box<dyn std::error::Error>> {
115 let identity = tonic::transport::Identity::from_pem(&self.cert_pem, &self.key_pem);
116 let mut cfg = tonic::transport::ServerTlsConfig::new().identity(identity);
117 if let Some(ca_pem) = &self.client_ca_pem {
118 cfg = cfg.client_ca_root(tonic::transport::Certificate::from_pem(ca_pem));
119 }
120 Ok(cfg)
121 }
122}
123
124const GRPC_MAX_CONCURRENT_STREAMS: u32 = 256;
127
128const GRPC_CONCURRENCY_LIMIT_PER_CONNECTION: usize = 256;
131
132const GRPC_KEEPALIVE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
135const GRPC_KEEPALIVE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
136
137fn configured_transport_builder() -> tonic::transport::Server {
143 tonic::transport::Server::builder()
144 .max_concurrent_streams(Some(GRPC_MAX_CONCURRENT_STREAMS))
145 .concurrency_limit_per_connection(GRPC_CONCURRENCY_LIMIT_PER_CONNECTION)
146 .http2_keepalive_interval(Some(GRPC_KEEPALIVE_INTERVAL))
147 .http2_keepalive_timeout(Some(GRPC_KEEPALIVE_TIMEOUT))
148}
149
150impl Default for GrpcServerOptions {
151 fn default() -> Self {
152 Self {
153 bind_addr: "127.0.0.1:55055".to_string(),
154 tls: None,
155 }
156 }
157}
158
159#[derive(Clone)]
160pub struct RedDBGrpcServer {
161 runtime: RedDBRuntime,
162 options: GrpcServerOptions,
163 auth_store: Arc<AuthStore>,
164 prepared_registry: Arc<PreparedRegistry>,
165 oauth_validator: Option<Arc<crate::auth::OAuthValidator>>,
171}
172
173impl RedDBGrpcServer {
174 pub fn new(runtime: RedDBRuntime) -> Self {
175 let auth_config = crate::auth::AuthConfig::default();
176 let auth_store = Arc::new(AuthStore::new(auth_config));
177 Self::with_options(runtime, GrpcServerOptions::default(), auth_store)
178 }
179
180 pub fn from_database_options(
181 db_options: RedDBOptions,
182 options: GrpcServerOptions,
183 ) -> RedDBResult<Self> {
184 let runtime = RedDBRuntime::with_options(db_options.clone())?;
186
187 let auth_store = if db_options.auth.vault_enabled {
188 let pager = runtime.db().store().pager().cloned().ok_or_else(|| {
192 crate::api::RedDBError::Internal(
193 "vault requires a paged database (persistent mode)".into(),
194 )
195 })?;
196 let store = AuthStore::with_vault(db_options.auth.clone(), pager)
197 .map_err(|e| crate::api::RedDBError::Internal(e.to_string()))?;
198 Arc::new(store)
199 } else {
200 Arc::new(AuthStore::new(db_options.auth.clone()))
201 };
202 auth_store.bootstrap_from_env();
203 Ok(Self::with_options(runtime, options, auth_store))
204 }
205
206 pub fn with_options(
207 runtime: RedDBRuntime,
208 options: GrpcServerOptions,
209 auth_store: Arc<AuthStore>,
210 ) -> Self {
211 runtime.set_auth_store(Arc::clone(&auth_store));
214 Self {
215 runtime,
216 options,
217 auth_store,
218 prepared_registry: Arc::new(PreparedRegistry::new()),
219 oauth_validator: None,
220 }
221 }
222
223 pub fn with_oauth_validator(mut self, validator: Arc<crate::auth::OAuthValidator>) -> Self {
229 self.oauth_validator = Some(validator);
230 self
231 }
232
233 pub fn oauth_validator(&self) -> Option<&Arc<crate::auth::OAuthValidator>> {
235 self.oauth_validator.as_ref()
236 }
237
238 pub fn runtime(&self) -> &RedDBRuntime {
239 &self.runtime
240 }
241
242 pub fn options(&self) -> &GrpcServerOptions {
243 &self.options
244 }
245
246 pub fn auth_store(&self) -> &Arc<AuthStore> {
247 &self.auth_store
248 }
249
250 pub(crate) fn with_listener_options(mut self, options: GrpcServerOptions) -> Self {
251 self.options = options;
252 self
253 }
254
255 fn grpc_runtime(&self) -> GrpcRuntime {
256 GrpcRuntime {
257 runtime: self.runtime.clone(),
258 auth_store: self.auth_store.clone(),
259 prepared_registry: Arc::clone(&self.prepared_registry),
260 oauth_validator: self.oauth_validator.clone(),
261 }
262 }
263
264 pub async fn serve(&self) -> Result<(), Box<dyn std::error::Error>> {
265 let addr = self.options.bind_addr.parse()?;
266 let mut builder = configured_transport_builder();
267 if let Some(tls) = &self.options.tls {
268 log_grpc_tls_identity(tls);
271 builder = builder.tls_config(tls.to_tonic_config()?)?;
272 }
273 builder
274 .add_service(Self::configured_service(self.grpc_runtime()))
275 .serve(addr)
276 .await?;
277 Ok(())
278 }
279
280 pub async fn serve_on(
281 &self,
282 listener: std::net::TcpListener,
283 ) -> Result<(), Box<dyn std::error::Error>> {
284 listener.set_nonblocking(true)?;
285 let listener = tokio::net::TcpListener::from_std(listener)?;
286 let incoming = TcpListenerStream::new(listener);
287 let mut builder = configured_transport_builder();
288 if let Some(tls) = &self.options.tls {
289 log_grpc_tls_identity(tls);
290 builder = builder.tls_config(tls.to_tonic_config()?)?;
291 }
292 builder
293 .add_service(Self::configured_service(self.grpc_runtime()))
294 .serve_with_incoming(incoming)
295 .await?;
296 Ok(())
297 }
298
299 pub(crate) async fn serve_router_demux(
306 &self,
307 rx: tokio::sync::mpsc::Receiver<tokio::net::TcpStream>,
308 ) -> Result<(), Box<dyn std::error::Error>> {
309 use tokio_stream::StreamExt;
310 let incoming = tokio_stream::wrappers::ReceiverStream::new(rx).map(Ok::<_, std::io::Error>);
311 let mut builder = configured_transport_builder();
312 if let Some(tls) = &self.options.tls {
313 log_grpc_tls_identity(tls);
314 builder = builder.tls_config(tls.to_tonic_config()?)?;
315 }
316 builder
317 .add_service(Self::configured_service(self.grpc_runtime()))
318 .serve_with_incoming(incoming)
319 .await?;
320 Ok(())
321 }
322
323 fn max_message_bytes() -> usize {
329 const DEFAULT: usize = 32 * 1024 * 1024;
330 std::env::var("REDDB_GRPC_MAX_MESSAGE_BYTES")
331 .ok()
332 .and_then(|raw| raw.trim().parse::<usize>().ok())
333 .filter(|value| *value > 0)
334 .unwrap_or(DEFAULT)
335 }
336
337 fn configured_service(runtime: GrpcRuntime) -> GrpcCatalogService {
338 use tonic::codec::CompressionEncoding;
342 let max_message = Self::max_message_bytes();
343 let service = RedDbServer::new(runtime.clone())
344 .max_decoding_message_size(max_message)
345 .max_encoding_message_size(max_message)
346 .accept_compressed(CompressionEncoding::Zstd)
347 .accept_compressed(CompressionEncoding::Gzip)
348 .send_compressed(CompressionEncoding::Zstd);
349 GrpcCatalogService::new(service, runtime)
350 }
351}
352
353#[derive(Clone)]
354struct GrpcRuntime {
355 runtime: RedDBRuntime,
356 auth_store: Arc<AuthStore>,
357 prepared_registry: Arc<PreparedRegistry>,
358 oauth_validator: Option<Arc<crate::auth::OAuthValidator>>,
362}
363
364impl GrpcRuntime {
365 fn admin_use_cases(&self) -> AdminUseCases<'_, RedDBRuntime> {
366 AdminUseCases::new(&self.runtime)
367 }
368
369 fn entity_use_cases(&self) -> EntityUseCases<'_, RedDBRuntime> {
370 EntityUseCases::new(&self.runtime)
371 }
372
373 fn graph_use_cases(&self) -> GraphUseCases<'_, RedDBRuntime> {
374 GraphUseCases::new(&self.runtime)
375 }
376
377 fn native_use_cases(&self) -> NativeUseCases<'_, RedDBRuntime> {
378 NativeUseCases::new(&self.runtime)
379 }
380}
381
382fn grpc_query_value_to_param_value(value: QueryValue) -> Result<ParamValue, Status> {
383 use proto::query_value::Kind;
384
385 match value
386 .kind
387 .ok_or_else(|| Status::invalid_argument("missing query param value"))?
388 {
389 Kind::NullValue(_) => Ok(ParamValue::Null),
390 Kind::BoolValue(value) => Ok(ParamValue::Bool(value)),
391 Kind::IntValue(value) => Ok(ParamValue::Int64(value)),
392 Kind::FloatValue(value) => Ok(ParamValue::Float64(value)),
393 Kind::TextValue(value) => Ok(ParamValue::Text(value)),
394 Kind::BytesValue(value) => Ok(ParamValue::Bytes(value)),
395 Kind::VectorValue(value) => Ok(ParamValue::Vector(value.values)),
396 Kind::JsonValue(value) => {
397 let parsed = json_from_str::<JsonValue>(&value)
398 .map_err(|e| Status::invalid_argument(format!("json param parse error: {e}")))?;
399 let encoded = json_to_string(&parsed)
400 .map_err(|e| Status::invalid_argument(format!("json param encode error: {e}")))?;
401 Ok(ParamValue::Json(encoded.into_bytes()))
402 }
403 Kind::TimestampValue(value) => Ok(ParamValue::Timestamp(value)),
404 Kind::UuidValue(value) => {
405 let bytes: [u8; 16] = value.try_into().map_err(|value: Vec<u8>| {
406 Status::invalid_argument(format!(
407 "uuid param must be 16 bytes, got {}",
408 value.len()
409 ))
410 })?;
411 Ok(ParamValue::Uuid(bytes))
412 }
413 }
414}
415
416struct GrpcIdentityGuard {
422 previous_identity: Option<(String, crate::auth::Role)>,
423 previous_tenant: Option<String>,
424}
425
426impl GrpcIdentityGuard {
427 fn install(identity: Option<(crate::auth::UserId, crate::auth::Role)>) -> Self {
428 use crate::runtime::execution_context as ctx;
429 let previous_identity = ctx::current_auth_identity_for_audit();
430 let previous_tenant = ctx::current_tenant();
431 match identity {
432 Some((id, role)) => {
433 match id.tenant {
434 Some(tenant) => ctx::set_current_tenant(tenant),
435 None => ctx::clear_current_tenant(),
436 }
437 ctx::set_current_auth_identity(id.username, role);
438 }
439 None => {
440 ctx::clear_current_auth_identity();
441 ctx::clear_current_tenant();
442 }
443 }
444 Self {
445 previous_identity,
446 previous_tenant,
447 }
448 }
449}
450
451impl Drop for GrpcIdentityGuard {
452 fn drop(&mut self) {
453 use crate::runtime::execution_context as ctx;
454 match self.previous_identity.take() {
455 Some((username, role)) => ctx::set_current_auth_identity(username, role),
456 None => ctx::clear_current_auth_identity(),
457 }
458 match self.previous_tenant.take() {
459 Some(tenant) => ctx::set_current_tenant(tenant),
460 None => ctx::clear_current_tenant(),
461 }
462 }
463}
464
465fn grpc_request_identity<T>(
469 runtime: &GrpcRuntime,
470 request: &Request<T>,
471) -> Option<(crate::auth::UserId, crate::auth::Role)> {
472 let principal = request
473 .extensions()
474 .get::<catalog_dispatch::GrpcDispatchContext>()
475 .and_then(|context| context.principal.clone())?;
476 let role = match runtime.resolve_auth(request.metadata()) {
477 crate::auth::middleware::AuthResult::Authenticated { role, .. } => role,
478 _ => return None,
479 };
480 let (tenant, username) = principal
481 .split_once('/')
482 .map_or((None, principal.as_str()), |(tenant, username)| {
483 (Some(tenant), username)
484 });
485 Some((crate::auth::UserId::from_parts(tenant, username), role))
486}
487
488fn execute_grpc_query_request(
489 runtime: &RedDBRuntime,
490 prepared: &PreparedRegistry,
491 identity: Option<(crate::auth::UserId, crate::auth::Role)>,
492 query: String,
493 params: Vec<QueryValue>,
494 commit_policy: Option<crate::replication::CommitPolicy>,
495) -> Result<RuntimeQueryResult, Status> {
496 if query.trim().is_empty() {
497 return Err(Status::invalid_argument("query field cannot be empty"));
498 }
499 let _identity = GrpcIdentityGuard::install(identity);
500
501 let params = params
502 .into_iter()
503 .map(grpc_query_value_to_param_value)
504 .collect::<Result<Vec<_>, _>>()?;
505 let mut request = RuntimeQueryRequest::sql(query, params);
506 if let Some(commit_policy) = commit_policy {
507 request = request.with_commit_policy(commit_policy);
508 }
509 QueryRequestExecutor::new(runtime, prepared)
510 .execute(request)
511 .map_err(grpc_query_request_error)
512}
513
514fn grpc_commit_policy_from_metadata(
515 metadata: &MetadataMap,
516) -> Result<Option<crate::replication::CommitPolicy>, Status> {
517 let Some(value) = metadata.get("x-reddb-commit-policy") else {
518 return Ok(None);
519 };
520 let value = value
521 .to_str()
522 .map_err(|_| Status::invalid_argument("x-reddb-commit-policy must be ascii"))?;
523 crate::replication::CommitPolicy::parse_strict(value)
524 .map(Some)
525 .ok_or_else(|| Status::invalid_argument(format!("invalid commit policy '{value}'")))
526}
527
528fn grpc_json_bind_to_param_value(value: &str) -> Result<ParamValue, Status> {
529 let value = json_from_str::<JsonValue>(value)
530 .map_err(|error| Status::invalid_argument(format!("bind parse error: {error}")))?;
531 Ok(match value {
532 JsonValue::Null => ParamValue::Null,
533 JsonValue::Bool(value) => ParamValue::Bool(value),
534 JsonValue::Integer(value) => ParamValue::Int64(value),
535 JsonValue::Number(value) if value.fract() == 0.0 && value.abs() < i64::MAX as f64 => {
536 ParamValue::Int64(value as i64)
537 }
538 JsonValue::Number(value) => ParamValue::Float64(value),
539 JsonValue::String(value) => ParamValue::Text(value),
540 other => ParamValue::Text(json_to_string(&other).unwrap_or_default()),
541 })
542}
543
544fn grpc_query_request_error(error: crate::api::RedDBError) -> Status {
545 let message = error.to_string();
546 if message.contains("commit policy timed out") {
547 return Status::deadline_exceeded(message);
548 }
549 match error {
550 crate::api::RedDBError::Query(message) if message.contains("not found or expired") => {
551 Status::not_found(message)
552 }
553 crate::api::RedDBError::Query(message)
554 if message == "prepared_needs_replan" || message == "prepared statements disabled" =>
555 {
556 Status::failed_precondition(message)
557 }
558 crate::api::RedDBError::Query(message)
561 if message.contains("prepared bind failed")
562 || message.contains("weaker than resolved floor") =>
563 {
564 Status::invalid_argument(message)
565 }
566 crate::api::RedDBError::Validation { message, .. } => Status::invalid_argument(message),
567 other => to_status(other),
571 }
572}
573
574#[cfg(test)]
575mod grpc_query_value_tests {
576 use super::*;
577 use proto::query_value::Kind;
578
579 #[test]
580 fn grpc_query_value_maps_to_request_param_variants() {
581 let cases = vec![
582 (
583 QueryValue {
584 kind: Some(Kind::NullValue(proto::QueryNull {})),
585 },
586 ParamValue::Null,
587 ),
588 (
589 QueryValue {
590 kind: Some(Kind::BoolValue(true)),
591 },
592 ParamValue::Bool(true),
593 ),
594 (
595 QueryValue {
596 kind: Some(Kind::IntValue(42)),
597 },
598 ParamValue::Int64(42),
599 ),
600 (
601 QueryValue {
602 kind: Some(Kind::FloatValue(1.5)),
603 },
604 ParamValue::Float64(1.5),
605 ),
606 (
607 QueryValue {
608 kind: Some(Kind::BytesValue(vec![0, 1, 2])),
609 },
610 ParamValue::Bytes(vec![0, 1, 2]),
611 ),
612 (
613 QueryValue {
614 kind: Some(Kind::VectorValue(proto::QueryVector {
615 values: vec![0.25, 0.5],
616 })),
617 },
618 ParamValue::Vector(vec![0.25, 0.5]),
619 ),
620 (
621 QueryValue {
622 kind: Some(Kind::TimestampValue(1_779_999_000)),
623 },
624 ParamValue::Timestamp(1_779_999_000),
625 ),
626 (
627 QueryValue {
628 kind: Some(Kind::UuidValue(vec![0x11; 16])),
629 },
630 ParamValue::Uuid([0x11; 16]),
631 ),
632 ];
633
634 for (input, expected) in cases {
635 assert_eq!(grpc_query_value_to_param_value(input).unwrap(), expected);
636 }
637
638 assert_eq!(
639 grpc_query_value_to_param_value(QueryValue {
640 kind: Some(Kind::TextValue("alice".into())),
641 })
642 .unwrap(),
643 ParamValue::Text("alice".to_string())
644 );
645 assert_eq!(
646 grpc_query_value_to_param_value(QueryValue {
647 kind: Some(Kind::JsonValue("{\"role\":\"admin\"}".into())),
648 })
649 .unwrap(),
650 ParamValue::Json(b"{\"role\":\"admin\"}".to_vec())
651 );
652 }
653
654 #[test]
655 fn grpc_query_value_rejects_missing_kind_and_bad_uuid() {
656 assert!(grpc_query_value_to_param_value(QueryValue { kind: None }).is_err());
657 assert!(grpc_query_value_to_param_value(QueryValue {
658 kind: Some(Kind::UuidValue(vec![0; 15])),
659 })
660 .is_err());
661 }
662
663 #[test]
664 fn grpc_query_rejects_empty_query_before_runtime_parse() {
665 let runtime =
666 RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
667 let prepared = PreparedRegistry::new();
668 let err = execute_grpc_query_request(
669 &runtime,
670 &prepared,
671 None,
672 " ".to_string(),
673 Vec::new(),
674 None,
675 )
676 .expect_err("empty query should fail");
677
678 assert_eq!(err.code(), tonic::Code::InvalidArgument);
679 assert_eq!(err.message(), "query field cannot be empty");
680 }
681
682 #[test]
683 fn grpc_query_params_are_bound_before_execution() {
684 let runtime =
685 RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
686 seed_grpc_param_table(&runtime);
687 let prepared = PreparedRegistry::new();
688
689 let result = execute_grpc_query_request(
690 &runtime,
691 &prepared,
692 None,
693 "SELECT id, name FROM p WHERE id = $1 AND name = $2".to_string(),
694 grpc_param_values(),
695 None,
696 )
697 .expect("parameterized query");
698
699 assert_eq!(result.result.records.len(), 1);
700 }
701
702 #[test]
703 fn grpc_query_enforces_ack_n_commit_policy_fail_closed() {
704 let _env_lock = env_lock().lock().expect("env lock");
705 let _env = EnvGuard::set(&[
706 ("RED_PRIMARY_COMMIT_POLICY", "ack_n=1"),
707 ("RED_REPLICATION_ACK_TIMEOUT_MS", "20"),
708 ("RED_COMMIT_FAIL_ON_TIMEOUT", "true"),
709 ]);
710 let data_path = temp_data_path("grpc_ack_n_timeout");
711 cleanup(&data_path);
712
713 let runtime = RedDBRuntime::with_options(
714 crate::api::RedDBOptions::persistent(&data_path)
715 .with_replication(crate::replication::ReplicationConfig::primary()),
716 )
717 .expect("runtime");
718 let prepared = PreparedRegistry::new();
719
720 let err = execute_grpc_query_request(
721 &runtime,
722 &prepared,
723 None,
724 "INSERT INTO grpc_ack_items (id, name) VALUES (1, 'alpha')".to_string(),
725 Vec::new(),
726 None,
727 )
728 .expect_err("ack_n without replica ack must fail closed");
729
730 assert_eq!(err.code(), tonic::Code::DeadlineExceeded);
731 assert!(
732 err.message().contains("commit policy timed out")
733 && err.message().contains("RED_COMMIT_FAIL_ON_TIMEOUT"),
734 "error should identify commit policy timeout, got {err:?}"
735 );
736 assert!(
737 runtime.cdc_current_lsn() > 0,
738 "local mutation should advance CDC before gRPC response fails"
739 );
740
741 cleanup(&data_path);
742 }
743
744 #[tokio::test]
745 async fn grpc_query_rpc_binds_query_request_params() {
746 let runtime =
747 RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
748 seed_grpc_param_table(&runtime);
749 let service = GrpcRuntime {
750 runtime,
751 auth_store: Arc::new(AuthStore::new(crate::auth::AuthConfig::default())),
752 prepared_registry: Arc::new(PreparedRegistry::new()),
753 oauth_validator: None,
754 };
755
756 let reply = RedDb::query(
757 &service,
758 Request::new(QueryRequest {
759 query: "SELECT id, name FROM p WHERE id = $1 AND name = $2".to_string(),
760 entity_types: Vec::new(),
761 capabilities: Vec::new(),
762 params: grpc_param_values(),
763 }),
764 )
765 .await
766 .expect("query rpc")
767 .into_inner();
768
769 assert_eq!(reply.record_count, 1);
770 assert!(reply.result_json.contains("Alice"), "{}", reply.result_json);
771 assert!(!reply.result_json.contains("Bob"), "{}", reply.result_json);
772 }
773
774 #[tokio::test]
775 async fn grpc_prepared_id_is_shared_by_connection_listeners_only() {
776 let runtime =
777 RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
778 let server = RedDBGrpcServer::new(runtime.clone());
779 let plain_listener = server.grpc_runtime();
780 let tls_listener = server.grpc_runtime();
781 let second_connection = RedDBGrpcServer::new(runtime).grpc_runtime();
782
783 let prepared = RedDb::prepare_query(
784 &plain_listener,
785 Request::new(PrepareQueryRequest {
786 query: "SELECT 7 AS value".to_string(),
787 }),
788 )
789 .await
790 .expect("prepare on plaintext listener")
791 .into_inner();
792
793 let reply = RedDb::execute_prepared(
794 &tls_listener,
795 Request::new(ExecutePreparedRequest {
796 prepared_id: prepared.prepared_id,
797 bind_json: vec!["42".to_string()],
798 }),
799 )
800 .await
801 .expect("execute on TLS listener of the same connection")
802 .into_inner();
803 assert!(reply.result_json.contains("42"), "{}", reply.result_json);
804
805 let error = RedDb::execute_prepared(
806 &second_connection,
807 Request::new(ExecutePreparedRequest {
808 prepared_id: prepared.prepared_id,
809 bind_json: vec!["42".to_string()],
810 }),
811 )
812 .await
813 .expect_err("another connection must not resolve the prepared ID");
814 assert_eq!(error.code(), tonic::Code::NotFound);
815 }
816
817 #[tokio::test]
818 async fn grpc_execute_prepared_rejects_a_stale_ddl_epoch() {
819 let runtime =
820 RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
821 let service = RedDBGrpcServer::new(runtime.clone()).grpc_runtime();
822 let prepared = RedDb::prepare_query(
823 &service,
824 Request::new(PrepareQueryRequest {
825 query: "SELECT 7 AS value".to_string(),
826 }),
827 )
828 .await
829 .expect("prepare query")
830 .into_inner();
831
832 runtime
833 .execute_query("CREATE TABLE grpc_prepared_epoch (id INTEGER)")
834 .expect("execute DDL");
835
836 let error = RedDb::execute_prepared(
837 &service,
838 Request::new(ExecutePreparedRequest {
839 prepared_id: prepared.prepared_id,
840 bind_json: vec!["42".to_string()],
841 }),
842 )
843 .await
844 .expect_err("DDL must invalidate the gRPC prepared shape");
845 assert_eq!(error.code(), tonic::Code::FailedPrecondition);
846 assert_eq!(error.message(), "prepared_needs_replan");
847 }
848
849 #[tokio::test]
850 async fn grpc_prepared_kill_switch_rejects_prepare_and_execute() {
851 let runtime =
852 RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
853 let service = RedDBGrpcServer::new(runtime).grpc_runtime();
854 let prepared = RedDb::prepare_query(
855 &service,
856 Request::new(PrepareQueryRequest {
857 query: "SELECT 7 AS value".to_string(),
858 }),
859 )
860 .await
861 .expect("prepare before kill switch")
862 .into_inner();
863
864 service.prepared_registry.disable();
865
866 let prepare_error = RedDb::prepare_query(
867 &service,
868 Request::new(PrepareQueryRequest {
869 query: "SELECT 1".to_string(),
870 }),
871 )
872 .await
873 .expect_err("kill switch must reject prepare");
874 assert_eq!(prepare_error.code(), tonic::Code::FailedPrecondition);
875 assert_eq!(prepare_error.message(), "prepared statements disabled");
876
877 let execute_error = RedDb::execute_prepared(
878 &service,
879 Request::new(ExecutePreparedRequest {
880 prepared_id: prepared.prepared_id,
881 bind_json: vec!["42".to_string()],
882 }),
883 )
884 .await
885 .expect_err("kill switch must reject execute");
886 assert_eq!(execute_error.code(), tonic::Code::FailedPrecondition);
887 assert_eq!(execute_error.message(), "prepared statements disabled");
888 }
889
890 #[tokio::test]
891 async fn grpc_query_honors_per_request_commit_policy() {
892 let _env_lock = env_lock().lock().expect("env lock");
893 let _env = EnvGuard::set(&[("RED_PRIMARY_COMMIT_POLICY", "ack_n=1")]);
894 let runtime =
895 RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
896 runtime
897 .execute_query("CREATE TABLE grpc_request_policy (id INTEGER)")
898 .expect("create table");
899 let service = RedDBGrpcServer::new(runtime.clone()).grpc_runtime();
900 let mut request = Request::new(QueryRequest {
901 query: "INSERT INTO grpc_request_policy (id) VALUES (1)".to_string(),
902 entity_types: Vec::new(),
903 capabilities: Vec::new(),
904 params: Vec::new(),
905 });
906 request
907 .metadata_mut()
908 .insert("x-reddb-commit-policy", "local".parse().expect("metadata"));
909
910 let error = RedDb::query(&service, request)
911 .await
912 .expect_err("weaker per-request policy must fail before mutation");
913 assert_eq!(error.code(), tonic::Code::InvalidArgument);
914 assert!(error.message().contains("weaker than resolved floor"));
915
916 let rows = runtime
917 .execute_query("SELECT id FROM grpc_request_policy")
918 .expect("read rows");
919 assert!(rows.result.records.is_empty());
920 }
921
922 #[tokio::test]
923 async fn pull_wal_records_rejects_stale_term_on_grpc_path() {
924 let runtime = RedDBRuntime::with_options(
925 crate::api::RedDBOptions::in_memory()
926 .with_replication(crate::replication::ReplicationConfig::primary().with_term(6)),
927 )
928 .expect("runtime");
929 let auth_store = Arc::new(AuthStore::new(crate::auth::AuthConfig {
930 enabled: true,
931 require_auth: true,
932 ..crate::auth::AuthConfig::default()
933 }));
934 let bootstrap = auth_store
935 .bootstrap("replica", "secret")
936 .expect("bootstrap");
937 let policy = crate::auth::policies::Policy::from_json_str(
938 r#"{
939 "id": "replication-stream",
940 "version": 1,
941 "statements": [{
942 "effect": "allow",
943 "actions": ["cluster:replication:stream"],
944 "resources": ["cluster:replication"]
945 }]
946 }"#,
947 )
948 .expect("policy");
949 auth_store.put_policy(policy).expect("install policy");
950 auth_store
951 .attach_policy(
952 crate::auth::store::PrincipalRef::User(crate::auth::UserId::platform("replica")),
953 "replication-stream",
954 )
955 .expect("attach policy");
956 let service = GrpcRuntime {
957 runtime,
958 auth_store,
959 prepared_registry: Arc::new(PreparedRegistry::new()),
960 oauth_validator: None,
961 };
962
963 let open = reddb_wire::replication::WalStreamOpen {
964 since_lsn: 0,
965 max_count: 1,
966 replica_id: Some("replica-a".to_string()),
967 term: 5,
968 await_data: false,
969 await_timeout_ms: 1,
970 };
971 let mut request = Request::new(JsonPayloadRequest {
972 payload_json: String::from_utf8(open.encode_json()).expect("json"),
973 });
974 request.metadata_mut().insert(
975 "authorization",
976 format!("Bearer {}", bootstrap.api_key.key)
977 .parse()
978 .expect("metadata"),
979 );
980
981 let err = RedDb::pull_wal_records(&service, request)
982 .await
983 .expect_err("stale term should be fenced");
984
985 assert_eq!(err.code(), tonic::Code::FailedPrecondition);
986 assert!(
987 err.message().contains("stale")
988 || err.message().contains("fenced")
989 || err.message().contains("current term"),
990 "unexpected stale-term error: {err:?}"
991 );
992 }
993
994 fn seed_grpc_param_table(runtime: &RedDBRuntime) {
995 runtime
996 .execute_query("CREATE TABLE p (id INTEGER, name TEXT)")
997 .expect("create table");
998 runtime
999 .execute_query("INSERT INTO p (id, name) VALUES (1, 'Alice')")
1000 .expect("insert alice");
1001 runtime
1002 .execute_query("INSERT INTO p (id, name) VALUES (2, 'Bob')")
1003 .expect("insert bob");
1004 }
1005
1006 fn grpc_param_values() -> Vec<QueryValue> {
1007 vec![
1008 QueryValue {
1009 kind: Some(Kind::IntValue(1)),
1010 },
1011 QueryValue {
1012 kind: Some(Kind::TextValue("Alice".to_string())),
1013 },
1014 ]
1015 }
1016
1017 fn env_lock() -> &'static std::sync::Mutex<()> {
1018 static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
1019 LOCK.get_or_init(|| std::sync::Mutex::new(()))
1020 }
1021
1022 struct EnvGuard {
1023 previous: Vec<(&'static str, Option<String>)>,
1024 }
1025
1026 impl EnvGuard {
1027 fn set(vars: &[(&'static str, &'static str)]) -> Self {
1028 let previous = vars
1029 .iter()
1030 .map(|(key, _)| (*key, std::env::var(key).ok()))
1031 .collect();
1032 for (key, value) in vars {
1033 std::env::set_var(key, value);
1034 }
1035 Self { previous }
1036 }
1037 }
1038
1039 impl Drop for EnvGuard {
1040 fn drop(&mut self) {
1041 for (key, value) in self.previous.iter().rev() {
1042 match value {
1043 Some(value) => std::env::set_var(key, value),
1044 None => std::env::remove_var(key),
1045 }
1046 }
1047 }
1048 }
1049
1050 fn temp_data_path(name: &str) -> std::path::PathBuf {
1051 let suffix = SystemTime::now()
1052 .duration_since(UNIX_EPOCH)
1053 .unwrap()
1054 .as_nanos();
1055 std::env::temp_dir().join(format!("reddb_{name}_{suffix}.rdb"))
1056 }
1057
1058 fn cleanup(data_path: &std::path::Path) {
1059 let _ = std::fs::remove_file(data_path);
1060 let _ = std::fs::remove_file(
1061 crate::replication::primary::PrimaryReplication::slot_path_for(data_path),
1062 );
1063 let _ = std::fs::remove_file(crate::replication::primary::LogicalWalSpool::path_for(
1064 data_path,
1065 ));
1066 let _ = std::fs::remove_dir_all(
1067 crate::replication::primary::PrimaryReplication::primary_replica_root_for(data_path),
1068 );
1069 reddb_file::cleanup_rebootstrap_artifacts(data_path);
1070 }
1071}
1072
1073#[cfg(test)]
1074mod grpc_ask_query_reply_tests {
1075 use super::*;
1076 use crate::storage::query::unified::{UnifiedRecord, UnifiedResult};
1077 use reddb_rql::modes::QueryMode;
1078 use reddb_types::Value as SchemaValue;
1079
1080 fn ask_runtime_result() -> RuntimeQueryResult {
1081 let mut result = UnifiedResult::with_columns(vec![
1082 "answer".into(),
1083 "provider".into(),
1084 "model".into(),
1085 "mode".into(),
1086 "retry_count".into(),
1087 "prompt_tokens".into(),
1088 "completion_tokens".into(),
1089 "sources_flat".into(),
1090 "citations".into(),
1091 "validation".into(),
1092 ]);
1093 let mut record = UnifiedRecord::new();
1094 record.set("answer", SchemaValue::text("Deploy failed [^1]."));
1095 record.set("provider", SchemaValue::text("openai"));
1096 record.set("model", SchemaValue::text("gpt-4o-mini"));
1097 record.set("mode", SchemaValue::text("strict"));
1098 record.set("retry_count", SchemaValue::Integer(0));
1099 record.set("prompt_tokens", SchemaValue::Integer(11));
1100 record.set("completion_tokens", SchemaValue::Integer(7));
1101 record.set(
1102 "sources_flat",
1103 SchemaValue::Json(
1104 br#"[{"urn":"urn:reddb:row:deployments:1","kind":"row","collection":"deployments","id":"1"}]"#.to_vec(),
1105 ),
1106 );
1107 record.set(
1108 "citations",
1109 SchemaValue::Json(br#"[{"marker":1,"urn":"urn:reddb:row:deployments:1"}]"#.to_vec()),
1110 );
1111 record.set(
1112 "validation",
1113 SchemaValue::Json(br#"{"ok":true,"warnings":[],"errors":[]}"#.to_vec()),
1114 );
1115 result.push(record);
1116
1117 RuntimeQueryResult {
1118 query: "ASK 'why did deploy fail?'".to_string(),
1119 mode: QueryMode::Sql,
1120 statement: "ask",
1121 engine: "runtime-ai",
1122 result,
1123 affected_rows: 0,
1124 statement_type: "select",
1125 bookmark: None,
1126 notice: None,
1127 }
1128 }
1129
1130 #[test]
1131 fn query_reply_ask_result_json_uses_full_canonical_schema() {
1132 let reply = query_reply(ask_runtime_result(), &None, &None);
1133 let json: crate::json::Value =
1134 crate::json::from_str(&reply.result_json).expect("valid ask json");
1135
1136 assert_eq!(
1137 json.get("answer").and_then(crate::json::Value::as_str),
1138 Some("Deploy failed [^1].")
1139 );
1140 assert_eq!(
1141 json.get("cache_hit").and_then(crate::json::Value::as_bool),
1142 Some(false)
1143 );
1144 assert_eq!(
1145 json.get("cost_usd").and_then(crate::json::Value::as_f64),
1146 Some(0.0)
1147 );
1148 assert_eq!(
1149 json.get("mode").and_then(crate::json::Value::as_str),
1150 Some("strict")
1151 );
1152 assert_eq!(
1153 json.get("retry_count").and_then(crate::json::Value::as_u64),
1154 Some(0)
1155 );
1156 assert!(
1157 json.get("records").is_none(),
1158 "ASK must not be row-wrapped: {}",
1159 reply.result_json
1160 );
1161 assert!(
1162 json.get("sources_flat")
1163 .and_then(crate::json::Value::as_array)
1164 .is_some_and(|sources| sources.len() == 1
1165 && sources[0]
1166 .get("payload")
1167 .and_then(crate::json::Value::as_str)
1168 .is_some()),
1169 "sources_flat must be parsed with payload fallback: {}",
1170 reply.result_json
1171 );
1172 assert!(
1173 json.get("citations")
1174 .and_then(crate::json::Value::as_array)
1175 .is_some_and(|citations| citations.len() == 1),
1176 "citations must be parsed: {}",
1177 reply.result_json
1178 );
1179 assert_eq!(
1180 json.get("validation")
1181 .and_then(|v| v.get("ok"))
1182 .and_then(crate::json::Value::as_bool),
1183 Some(true)
1184 );
1185 }
1186
1187 #[test]
1188 fn query_reply_non_ask_answer_column_keeps_row_shape() {
1189 let mut result = UnifiedResult::with_columns(vec!["answer".into()]);
1190 let mut record = UnifiedRecord::new();
1191 record.set("answer", SchemaValue::text("plain select"));
1192 result.push(record);
1193
1194 let reply = query_reply(
1195 RuntimeQueryResult {
1196 query: "SELECT 'plain select' AS answer".to_string(),
1197 mode: QueryMode::Sql,
1198 statement: "select",
1199 engine: "runtime-sql",
1200 result,
1201 affected_rows: 0,
1202 statement_type: "select",
1203 bookmark: None,
1204 notice: None,
1205 },
1206 &None,
1207 &None,
1208 );
1209 let json: crate::json::Value =
1210 crate::json::from_str(&reply.result_json).expect("valid query json");
1211
1212 assert!(
1213 json.get("records").is_some(),
1214 "non-ASK must stay row-wrapped"
1215 );
1216 assert!(
1217 json.get("answer").is_none(),
1218 "non-ASK must not use ASK envelope"
1219 );
1220 }
1221
1222 #[test]
1223 fn query_reply_non_ask_json_column_preserves_object() {
1224 let mut result = UnifiedResult::with_columns(vec!["value".into()]);
1225 let mut record = UnifiedRecord::new();
1226 record.set(
1227 "value",
1228 SchemaValue::Json(br#"{"alpha":"A","nested":{"leaf":12}}"#.to_vec()),
1229 );
1230 result.push(record);
1231
1232 let reply = query_reply(
1233 RuntimeQueryResult {
1234 query: "LIST KV proj AS JSON".to_string(),
1235 mode: QueryMode::Sql,
1236 statement: "kv_list_json",
1237 engine: "kv",
1238 result,
1239 affected_rows: 0,
1240 statement_type: "select",
1241 bookmark: None,
1242 notice: None,
1243 },
1244 &None,
1245 &None,
1246 );
1247 let json: crate::json::Value =
1248 crate::json::from_str(&reply.result_json).expect("valid query json");
1249 let value = json
1250 .get("records")
1251 .and_then(crate::json::Value::as_array)
1252 .and_then(|records| records.first())
1253 .and_then(|record| record.get("value"))
1254 .expect("value column");
1255
1256 assert_eq!(
1257 value.get("alpha").and_then(crate::json::Value::as_str),
1258 Some("A")
1259 );
1260 assert_eq!(
1261 value
1262 .get("nested")
1263 .and_then(|nested| nested.get("leaf"))
1264 .and_then(crate::json::Value::as_f64),
1265 Some(12.0)
1266 );
1267 }
1268}
1269
1270fn log_grpc_tls_identity(tls: &GrpcTlsOptions) {
1273 use sha2::{Digest, Sha256};
1274 let cert_fp = {
1275 let mut h = Sha256::new();
1276 h.update(&tls.cert_pem);
1277 let digest = h.finalize();
1278 let mut buf = String::with_capacity(64);
1281 for b in digest.iter() {
1282 buf.push_str(&format!("{b:02x}"));
1283 }
1284 buf
1285 };
1286 tracing::info!(
1287 target: "reddb::security",
1288 transport = "grpc",
1289 cert_sha256 = %cert_fp,
1290 mtls = tls.client_ca_pem.is_some(),
1291 "gRPC TLS identity loaded"
1292 );
1293}
1294
1295include!("grpc/service_impl.rs");