1pub(crate) use crate::application::json_input::{
4 json_bool_field, json_f32_field, json_string_field, json_usize_field,
5};
6pub(crate) use crate::application::{
7 AdminUseCases, CreateDocumentInput, CreateEdgeInput, CreateEntityOutput, CreateKvInput,
8 CreateNodeEmbeddingInput, CreateNodeGraphLinkInput, CreateNodeInput, CreateNodeTableLinkInput,
9 CreateRowInput, CreateVectorInput, DeleteEntityInput, EntityUseCases, ExecuteQueryInput,
10 ExplainQueryInput, GraphCentralityInput, GraphClusteringInput, GraphCommunitiesInput,
11 GraphComponentsInput, GraphCyclesInput, GraphHitsInput, GraphNeighborhoodInput,
12 GraphPersonalizedPageRankInput, GraphShortestPathInput, GraphTopologicalSortInput,
13 GraphTraversalInput, GraphUseCases, InspectNativeArtifactInput, NativeUseCases,
14 PatchEntityInput, PatchEntityOperation, PatchEntityOperationType, SearchHybridInput,
15 SearchIvfInput, SearchMultimodalInput, SearchSimilarInput, SearchTextInput, TreeUseCases,
16};
17use std::collections::{BTreeMap, HashMap};
18use std::io::{self, Read, Write};
19use std::net::{TcpListener, TcpStream};
20use std::sync::atomic::{AtomicU64, Ordering};
21use std::thread;
22use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
23
24use std::sync::Arc;
25
26use crate::api::{RedDBError, RedDBOptions, RedDBResult};
27use crate::auth::store::AuthStore;
28use crate::catalog::{CatalogModelSnapshot, CollectionDescriptor, CollectionModel, SchemaMode};
29use crate::health::{HealthProvider, HealthReport, HealthState};
30use crate::json::{parse_json, to_vec as json_to_vec, Map, Value as JsonValue};
31use crate::runtime::{
32 RedDBRuntime, RuntimeFilter, RuntimeFilterValue, RuntimeGraphCentralityAlgorithm,
33 RuntimeGraphCentralityResult, RuntimeGraphClusteringResult, RuntimeGraphCommunityAlgorithm,
34 RuntimeGraphCommunityResult, RuntimeGraphComponentsMode, RuntimeGraphComponentsResult,
35 RuntimeGraphCyclesResult, RuntimeGraphDirection, RuntimeGraphHitsResult,
36 RuntimeGraphNeighborhoodResult, RuntimeGraphPathAlgorithm, RuntimeGraphPathResult,
37 RuntimeGraphPattern, RuntimeGraphProjection, RuntimeGraphTopologicalSortResult,
38 RuntimeGraphTraversalResult, RuntimeGraphTraversalStrategy, RuntimeIvfSearchResult,
39 RuntimeQueryWeights, RuntimeStats, ScanCursor, ScanPage,
40};
41use crate::storage::unified::devx::refs::{NodeRef, TableRef, VectorRef};
42use crate::storage::unified::dsl::{MatchComponents, QueryResult as DslQueryResult};
43use crate::storage::unified::{MetadataValue, RefTarget, SparseVector};
44use crate::storage::{CrossRef, EntityData, EntityId, EntityKind, SimilarResult, UnifiedEntity};
45use crate::transport::execution_admission::ExecutionAdmission;
46use reddb_types::Value;
47
48fn analytics_job_json(job: &crate::PhysicalAnalyticsJob) -> JsonValue {
49 crate::presentation::admin_json::analytics_job_json(job)
50}
51
52#[cfg(test)]
54pub(crate) static RED_ADMIN_TOKEN_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59 use crate::api::RedDBOptions;
60 use crate::health::HealthReport;
61 use crate::transport::{TransportListenerFailure, TransportListenerState, TransportReadiness};
62
63 #[test]
64 fn server_options_default_http_body_limit_is_32_mib() {
65 assert_eq!(ServerOptions::default().max_body_bytes, 32 * 1024 * 1024);
66 }
67
68 #[test]
69 fn health_json_reports_transport_listeners() {
70 let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
71 let mut options = ServerOptions::default();
72 options.transport_readiness = TransportReadiness {
73 active: vec![TransportListenerState {
74 transport: "grpc".to_string(),
75 bind_addr: "127.0.0.1:5000".to_string(),
76 explicit: true,
77 }],
78 failed: vec![TransportListenerFailure {
79 transport: "http".to_string(),
80 bind_addr: "127.0.0.1:5000".to_string(),
81 explicit: false,
82 reason: "http listener bind 127.0.0.1:5000: address in use".to_string(),
83 }],
84 };
85 let server = RedDBServer::with_options(runtime, options);
86
87 let payload = server.health_json_with_transport(&HealthReport::healthy());
88 let JsonValue::Object(root) = payload else {
89 panic!("health payload should be an object");
90 };
91 let Some(JsonValue::Object(listeners)) = root.get("transport_listeners") else {
92 panic!("health payload should include transport_listeners");
93 };
94 let Some(JsonValue::Array(active)) = listeners.get("active") else {
95 panic!("transport_listeners.active should be an array");
96 };
97 let Some(JsonValue::Array(failed)) = listeners.get("failed") else {
98 panic!("transport_listeners.failed should be an array");
99 };
100
101 assert_eq!(active.len(), 1);
102 assert_eq!(failed.len(), 1);
103 }
104}
105
106fn graph_projection_json(projection: &crate::PhysicalGraphProjection) -> JsonValue {
107 crate::presentation::admin_json::graph_projection_json(projection)
108}
109
110mod axum_edge;
111pub mod handlers_admin;
112mod handlers_admin_metrics;
113mod handlers_admin_status;
114mod handlers_ai;
115mod handlers_ai_model_cache;
116pub(crate) mod handlers_auth;
117mod handlers_backup;
118mod handlers_browser_auth;
119mod handlers_cache;
120mod handlers_capabilities;
121mod handlers_collection_policy;
122mod handlers_ec;
123pub(crate) mod handlers_entity;
124mod handlers_failover;
125mod handlers_geo;
126mod handlers_graph;
127mod handlers_iam_policy;
128mod handlers_keyed;
129mod handlers_log;
130mod handlers_metrics;
131mod handlers_ops;
132mod handlers_ops_policy;
133pub mod ui_bridge;
137mod ws_edge;
138pub mod ui_bundle_resolver;
142pub mod ui_auth;
145mod ui_static;
149pub mod ui_deeplink;
154pub(crate) mod handlers_query;
160mod handlers_replication;
161mod handlers_topology;
162mod handlers_vector;
163pub mod header_escape_guard;
164pub mod http_connection_limiter;
165pub mod http_handler_metrics;
166pub mod http_limits;
167pub mod http_principal_limiter;
168pub mod http_request_metrics;
169pub mod ingest_pipeline;
170pub mod output_stream;
171mod patch_support;
172mod request_body;
173mod request_context;
174mod request_identity;
175pub(crate) mod route_catalog;
176mod routes;
177pub(crate) use routes::discovered_route_catalog;
178mod routing;
179mod serverless_support;
180pub mod tls;
181mod transport;
182mod transport_surface;
183
184#[doc(hidden)]
188pub fn command_coverage_matrix() -> String {
189 route_catalog::render_command_coverage_matrix(routes::discovered_route_catalog())
190}
191
192use self::handlers_ai::*;
193use self::handlers_entity::*;
194use self::handlers_graph::*;
195use self::handlers_keyed::*;
196use self::handlers_metrics::*;
197use self::handlers_ops::*;
198use self::handlers_query::*;
199use self::http_connection_limiter::{
200 HandlerDeadline, HttpConnectionLimiter, MonotonicClock, SystemMonotonicClock,
201};
202use self::http_handler_metrics::{HttpHandlerMetrics, HttpRejectReason, HttpTransport};
203pub use self::http_limits::{
204 HttpLimitsCliInput, HttpLimitsResolved, DEFAULT_HANDLER_TIMEOUT_MS, DEFAULT_RETRY_AFTER_SECS,
205};
206use self::http_principal_limiter::PrincipalConnectionLimiter;
207use self::http_request_metrics::HttpRequestMetrics;
208use self::patch_support::*;
209pub(crate) use self::request_body::is_trivial_scalar_sql;
210use self::request_body::*;
211use self::routing::*;
212use self::serverless_support::*;
213use self::transport::*;
214
215pub(crate) fn command_catalog() -> &'static route_catalog::CommandCatalog {
216 routes::discovered_route_catalog()
217}
218
219#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum ServerSurface {
226 Public,
228 AdminOnly,
232 MetricsOnly,
236}
237
238#[derive(Debug, Clone)]
239pub struct ServerOptions {
240 pub bind_addr: String,
241 pub max_body_bytes: usize,
242 pub read_timeout_ms: u64,
243 pub write_timeout_ms: u64,
244 pub max_scan_limit: usize,
245 pub surface: ServerSurface,
249 pub transport_readiness: crate::transport::TransportReadiness,
250 pub websocket_allowed_origins: Vec<String>,
258 pub ui_dir: Option<std::path::PathBuf>,
267}
268
269pub const DEFAULT_HTTP_MAX_BODY_BYTES: usize = 32 * 1024 * 1024;
270
271impl Default for ServerOptions {
272 fn default() -> Self {
273 Self {
274 bind_addr: "127.0.0.1:5000".to_string(),
275 max_body_bytes: DEFAULT_HTTP_MAX_BODY_BYTES,
276 read_timeout_ms: 5_000,
277 write_timeout_ms: 5_000,
278 max_scan_limit: 1_000,
279 surface: ServerSurface::Public,
280 transport_readiness: crate::transport::TransportReadiness::default(),
281 websocket_allowed_origins: Vec::new(),
282 ui_dir: None,
283 }
284 }
285}
286
287pub struct ServerReplicationState {
289 pub config: crate::replication::ReplicationConfig,
290 pub primary: Option<crate::replication::primary::PrimaryReplication>,
291}
292
293#[derive(Clone)]
294pub struct RedDBServer {
295 runtime: RedDBRuntime,
296 options: ServerOptions,
297 auth_store: Option<Arc<AuthStore>>,
298 replication: Option<Arc<ServerReplicationState>>,
299 http_limiter: HttpConnectionLimiter,
304 execution_admission: ExecutionAdmission,
308 health_limiter: HttpConnectionLimiter,
314 handler_timeout: Duration,
320 handler_clock: Arc<dyn MonotonicClock>,
327 slow_inject_ms: Arc<AtomicU64>,
336 http_metrics: HttpHandlerMetrics,
342 http_request_metrics: HttpRequestMetrics,
348 retry_after_secs: u64,
352 principal_limiter: PrincipalConnectionLimiter,
360 pub(crate) stream_capacity: Arc<output_stream::StreamCapacityRegistry>,
368 pub(crate) lease_registry: Arc<output_stream::LeaseRegistry>,
373 pub(crate) cursor_registry: Arc<output_stream::CursorRegistry>,
378}
379
380const DEFAULT_HANDLER_TIMEOUT: Duration = Duration::from_millis(30_000);
382
383const HEALTH_HANDLER_CAP: usize = 4;
386
387#[derive(Debug, Clone, Copy, PartialEq, Eq)]
388enum ServerlessWarmupScope {
389 Indexes,
390 GraphProjections,
391 AnalyticsJobs,
392 NativeArtifacts,
393}
394
395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
396enum DeploymentProfile {
397 Embedded,
398 Server,
399 Serverless,
400}
401
402fn percent_decode_path_segment(input: &str) -> Result<String, String> {
403 let bytes = input.as_bytes();
404 let mut out = Vec::with_capacity(bytes.len());
405 let mut index = 0;
406 while index < bytes.len() {
407 match bytes[index] {
408 b'%' => {
409 if index + 2 >= bytes.len() {
410 return Err("truncated percent escape".to_string());
411 }
412 let high = hex_value(bytes[index + 1])
413 .ok_or_else(|| "invalid percent escape".to_string())?;
414 let low = hex_value(bytes[index + 2])
415 .ok_or_else(|| "invalid percent escape".to_string())?;
416 out.push((high << 4) | low);
417 index += 3;
418 }
419 byte => {
420 out.push(byte);
421 index += 1;
422 }
423 }
424 }
425 String::from_utf8(out).map_err(|_| "path segment is not valid UTF-8".to_string())
426}
427
428fn hex_value(byte: u8) -> Option<u8> {
429 match byte {
430 b'0'..=b'9' => Some(byte - b'0'),
431 b'a'..=b'f' => Some(byte - b'a' + 10),
432 b'A'..=b'F' => Some(byte - b'A' + 10),
433 _ => None,
434 }
435}
436
437#[derive(Debug, Clone)]
438struct ParsedQueryRequest {
439 query: String,
440 entity_types: Option<Vec<String>>,
441 capabilities: Option<Vec<String>>,
442 commit_policy: Option<crate::replication::CommitPolicy>,
443 params: Option<Vec<crate::runtime::query_request::ParamValue>>,
446}
447
448#[derive(Debug, Clone, Copy)]
449enum PatchOperationType {
450 Set,
451 Replace,
452 Unset,
453}
454
455#[derive(Debug, Clone)]
456struct PatchOperation {
457 op: PatchOperationType,
458 path: Vec<String>,
459 value: Option<JsonValue>,
460}
461
462impl RedDBServer {
463 pub fn new(runtime: RedDBRuntime) -> Self {
464 Self::with_options(runtime, ServerOptions::default())
465 }
466
467 pub fn from_database_options(
468 db_options: RedDBOptions,
469 server_options: ServerOptions,
470 ) -> RedDBResult<Self> {
471 let runtime = RedDBRuntime::with_options(db_options)?;
472 Ok(Self::with_options(runtime, server_options))
473 }
474
475 pub fn with_options(runtime: RedDBRuntime, options: ServerOptions) -> Self {
476 let http_limits = HttpLimitsResolved::builtin_defaults();
477 let execution_admission = runtime.configure_execution_admission(
478 http_limits.execution_workers,
479 http_limits
480 .max_handlers
481 .saturating_sub(http_limits.execution_workers),
482 http_limits.handler_timeout_ms,
483 );
484 Self {
485 runtime,
486 options,
487 auth_store: None,
488 replication: None,
489 http_limiter: HttpConnectionLimiter::new(http_limits.max_handlers),
490 execution_admission,
491 health_limiter: HttpConnectionLimiter::new(HEALTH_HANDLER_CAP),
492 handler_timeout: DEFAULT_HANDLER_TIMEOUT,
493 handler_clock: Arc::new(SystemMonotonicClock::new()),
494 slow_inject_ms: Arc::new(AtomicU64::new(0)),
495 http_metrics: HttpHandlerMetrics::new(),
496 http_request_metrics: HttpRequestMetrics::new(),
497 retry_after_secs: DEFAULT_RETRY_AFTER_SECS,
498 principal_limiter: PrincipalConnectionLimiter::new(
499 http_limits.max_inflight_per_principal,
500 ),
501 stream_capacity: output_stream::StreamCapacityRegistry::new(),
502 lease_registry: output_stream::LeaseRegistry::new(),
503 cursor_registry: output_stream::CursorRegistry::new(),
504 }
505 }
506
507 #[doc(hidden)]
508 pub fn stream_capacity(&self) -> &Arc<output_stream::StreamCapacityRegistry> {
509 &self.stream_capacity
510 }
511
512 #[doc(hidden)]
513 pub fn lease_registry(&self) -> &Arc<output_stream::LeaseRegistry> {
514 &self.lease_registry
515 }
516
517 #[doc(hidden)]
518 pub fn cursor_registry(&self) -> &Arc<output_stream::CursorRegistry> {
519 &self.cursor_registry
520 }
521
522 #[doc(hidden)]
523 pub fn http_metrics(&self) -> &HttpHandlerMetrics {
524 &self.http_metrics
525 }
526
527 #[doc(hidden)]
530 pub fn http_request_metrics(&self) -> &HttpRequestMetrics {
531 &self.http_request_metrics
532 }
533
534 #[doc(hidden)]
539 pub fn with_http_limiter_cap(mut self, cap: usize) -> Self {
540 self.http_limiter = HttpConnectionLimiter::new(cap);
541 let execution_workers = self.execution_admission.active_max().min(cap);
542 self.execution_admission = self.runtime.configure_execution_admission(
543 execution_workers,
544 cap.saturating_sub(execution_workers),
545 self.handler_timeout.as_millis().min(u64::MAX as u128) as u64,
546 );
547 self
548 }
549
550 pub fn with_http_limits(mut self, limits: HttpLimitsResolved) -> Self {
555 self.http_limiter = HttpConnectionLimiter::new(limits.max_handlers);
556 self.execution_admission = self.runtime.configure_execution_admission(
557 limits.execution_workers,
558 limits.max_handlers.saturating_sub(limits.execution_workers),
559 limits.handler_timeout_ms,
560 );
561 self.handler_timeout = Duration::from_millis(limits.handler_timeout_ms);
562 self.retry_after_secs = limits.retry_after_secs;
563 self.principal_limiter = PrincipalConnectionLimiter::new(limits.max_inflight_per_principal);
564 self
565 }
566
567 #[doc(hidden)]
572 pub fn with_principal_inflight_cap(mut self, cap: usize) -> Self {
573 self.principal_limiter = PrincipalConnectionLimiter::new(cap);
574 self
575 }
576
577 #[doc(hidden)]
578 pub fn principal_limiter(&self) -> &PrincipalConnectionLimiter {
579 &self.principal_limiter
580 }
581
582 #[doc(hidden)]
583 pub fn retry_after_secs(&self) -> u64 {
584 self.retry_after_secs
585 }
586
587 #[doc(hidden)]
588 pub fn http_limiter(&self) -> &HttpConnectionLimiter {
589 &self.http_limiter
590 }
591
592 pub(crate) fn execution_admission(&self) -> &ExecutionAdmission {
593 &self.execution_admission
594 }
595
596 #[doc(hidden)]
597 pub fn http_execution_active(&self) -> usize {
598 self.execution_admission.active()
599 }
600
601 #[doc(hidden)]
602 pub fn http_execution_queued(&self) -> usize {
603 self.execution_admission.queued()
604 }
605
606 #[doc(hidden)]
607 pub fn http_execution_workers(&self) -> usize {
608 self.execution_admission.active_max()
609 }
610
611 #[doc(hidden)]
613 pub fn with_http_execution_workers(mut self, workers: usize) -> Self {
614 assert!(workers > 0, "HTTP execution workers must be positive");
615 let workers = workers.min(self.http_limiter.cap());
616 self.execution_admission = self.runtime.configure_execution_admission(
617 workers,
618 self.http_limiter.cap().saturating_sub(workers),
619 self.handler_timeout.as_millis().min(u64::MAX as u128) as u64,
620 );
621 self
622 }
623
624 #[doc(hidden)]
626 pub fn health_limiter(&self) -> &HttpConnectionLimiter {
627 &self.health_limiter
628 }
629
630 #[doc(hidden)]
632 pub fn with_health_limiter_cap(mut self, cap: usize) -> Self {
633 self.health_limiter = HttpConnectionLimiter::new(cap);
634 self
635 }
636
637 #[doc(hidden)]
640 pub fn with_handler_timeout(mut self, timeout: Duration) -> Self {
641 self.handler_timeout = timeout;
642 self
643 }
644
645 #[doc(hidden)]
646 pub fn handler_timeout(&self) -> Duration {
647 self.handler_timeout
648 }
649
650 #[doc(hidden)]
655 pub fn with_handler_clock(mut self, clock: Arc<dyn MonotonicClock>) -> Self {
656 self.handler_clock = clock;
657 self
658 }
659
660 #[doc(hidden)]
665 pub fn set_test_slow_inject_ms(&self, ms: u64) {
666 self.slow_inject_ms.store(ms, Ordering::Release);
667 }
668
669 fn apply_test_slow_inject(&self) {
670 let inject_ms = self.slow_inject_ms.load(Ordering::Acquire);
671 if inject_ms == 0 {
672 return;
673 }
674 if inject_ms != u64::MAX {
675 thread::sleep(Duration::from_millis(inject_ms));
676 return;
677 }
678 while self.slow_inject_ms.load(Ordering::Acquire) == u64::MAX {
679 thread::park_timeout(Duration::from_millis(1));
680 }
681 }
682
683 fn test_slow_inject_is_blocking_gate(&self) -> bool {
684 self.slow_inject_ms.load(Ordering::Acquire) == u64::MAX
685 }
686
687 pub fn with_auth(mut self, auth_store: Arc<AuthStore>) -> Self {
691 self.runtime.set_auth_store(Arc::clone(&auth_store));
692 self.auth_store = Some(auth_store);
693 self
694 }
695
696 pub fn with_replication(mut self, state: Arc<ServerReplicationState>) -> Self {
698 self.replication = Some(state);
699 self
700 }
701
702 pub fn with_websocket_allowed_origins(mut self, origins: Vec<String>) -> Self {
707 self.options.websocket_allowed_origins = origins;
708 self
709 }
710
711 pub(crate) fn websocket_allowed_origins(&self) -> &[String] {
713 &self.options.websocket_allowed_origins
714 }
715
716 pub fn with_ui_dir(mut self, dir: std::path::PathBuf) -> Self {
722 self.options.ui_dir = Some(dir);
723 self
724 }
725
726 pub(crate) fn ui_dir(&self) -> Option<&std::path::Path> {
729 self.options.ui_dir.as_deref()
730 }
731
732 pub fn with_browser_token_authority(
739 self,
740 authority: Arc<crate::auth::browser_token::BrowserTokenAuthority>,
741 ) -> Self {
742 self.runtime.set_browser_token_authority(Some(authority));
743 self
744 }
745
746 pub fn runtime(&self) -> &RedDBRuntime {
747 &self.runtime
748 }
749
750 pub fn options(&self) -> &ServerOptions {
751 &self.options
752 }
753
754 fn admin_use_cases(&self) -> AdminUseCases<'_, RedDBRuntime> {
755 AdminUseCases::new(&self.runtime)
756 }
757
758 fn entity_use_cases(&self) -> EntityUseCases<'_, RedDBRuntime> {
759 EntityUseCases::new(&self.runtime)
760 }
761
762 fn graph_use_cases(&self) -> GraphUseCases<'_, RedDBRuntime> {
763 GraphUseCases::new(&self.runtime)
764 }
765
766 fn native_use_cases(&self) -> NativeUseCases<'_, RedDBRuntime> {
767 NativeUseCases::new(&self.runtime)
768 }
769
770 fn tree_use_cases(&self) -> TreeUseCases<'_, RedDBRuntime> {
771 TreeUseCases::new(&self.runtime)
772 }
773
774 fn transport_readiness_json(&self) -> JsonValue {
775 let active = self
776 .options
777 .transport_readiness
778 .active
779 .iter()
780 .map(|listener| {
781 let mut object = Map::new();
782 object.insert(
783 "transport".to_string(),
784 JsonValue::String(listener.transport.clone()),
785 );
786 object.insert(
787 "bind_addr".to_string(),
788 JsonValue::String(listener.bind_addr.clone()),
789 );
790 object.insert("explicit".to_string(), JsonValue::Bool(listener.explicit));
791 JsonValue::Object(object)
792 })
793 .collect();
794 let failed = self
795 .options
796 .transport_readiness
797 .failed
798 .iter()
799 .map(|listener| {
800 let mut object = Map::new();
801 object.insert(
802 "transport".to_string(),
803 JsonValue::String(listener.transport.clone()),
804 );
805 object.insert(
806 "bind_addr".to_string(),
807 JsonValue::String(listener.bind_addr.clone()),
808 );
809 object.insert("explicit".to_string(), JsonValue::Bool(listener.explicit));
810 object.insert(
811 "reason".to_string(),
812 JsonValue::String(listener.reason.clone()),
813 );
814 JsonValue::Object(object)
815 })
816 .collect();
817
818 let mut object = Map::new();
819 object.insert("active".to_string(), JsonValue::Array(active));
820 object.insert("failed".to_string(), JsonValue::Array(failed));
821 JsonValue::Object(object)
822 }
823
824 fn handle_grpc_discovery(&self) -> HttpResponse {
825 let mut methods = Map::new();
826 methods.insert(
827 "query".to_string(),
828 JsonValue::String("reddb.v1.RedDB/Query".to_string()),
829 );
830 methods.insert(
831 "batch_query".to_string(),
832 JsonValue::String("reddb.v1.RedDB/BatchQuery".to_string()),
833 );
834 methods.insert(
835 "health".to_string(),
836 JsonValue::String("reddb.v1.RedDB/Health".to_string()),
837 );
838 methods.insert(
839 "prepare".to_string(),
840 JsonValue::String("reddb.v1.RedDB/Prepare".to_string()),
841 );
842 methods.insert(
843 "execute_prepared".to_string(),
844 JsonValue::String("reddb.v1.RedDB/ExecutePrepared".to_string()),
845 );
846
847 let mut examples = Map::new();
848 examples.insert(
849 "query".to_string(),
850 JsonValue::String(
851 "grpcurl -plaintext -d '{\"query\":\"SELECT 1\"}' 127.0.0.1:5000 reddb.v1.RedDB/Query"
852 .to_string(),
853 ),
854 );
855 examples.insert(
856 "query_with_params".to_string(),
857 JsonValue::String(
858 "grpcurl -plaintext -d '{\"query\":\"SELECT $1 AS value\",\"params\":[{\"intValue\":42}]}' 127.0.0.1:5000 reddb.v1.RedDB/Query"
859 .to_string(),
860 ),
861 );
862 examples.insert(
863 "health".to_string(),
864 JsonValue::String(
865 "grpcurl -plaintext -d '{}' 127.0.0.1:5000 reddb.v1.RedDB/Health".to_string(),
866 ),
867 );
868
869 let mut object = Map::new();
870 object.insert("ok".to_string(), JsonValue::Bool(true));
871 object.insert(
872 "service".to_string(),
873 JsonValue::String("reddb.v1.RedDB".to_string()),
874 );
875 object.insert(
876 "package".to_string(),
877 JsonValue::String("reddb.v1".to_string()),
878 );
879 object.insert(
880 "proto".to_string(),
881 JsonValue::String("crates/reddb-grpc-proto/proto/reddb.proto".to_string()),
882 );
883 object.insert("methods".to_string(), JsonValue::Object(methods));
884 object.insert("examples".to_string(), JsonValue::Object(examples));
885 object.insert(
886 "transport_listeners".to_string(),
887 self.transport_readiness_json(),
888 );
889 object.insert(
890 "hint".to_string(),
891 JsonValue::String(
892 "If grpcurl cannot list services, pass the proto file with -import-path crates/reddb-grpc-proto/proto -proto reddb.proto."
893 .to_string(),
894 ),
895 );
896 json_response(200, JsonValue::Object(object))
897 }
898
899 fn handle_query_contract(&self) -> HttpResponse {
900 let mut examples = Map::new();
901 examples.insert(
902 "raw_sql".to_string(),
903 JsonValue::String("curl -sS http://127.0.0.1:5000/query -d 'SELECT 1'".to_string()),
904 );
905 examples.insert(
906 "json_query".to_string(),
907 JsonValue::String(
908 "curl -sS http://127.0.0.1:5000/query -H 'content-type: application/json' -d '{\"query\":\"SELECT 1\"}'"
909 .to_string(),
910 ),
911 );
912 examples.insert(
913 "json_query_with_params".to_string(),
914 JsonValue::String(
915 "curl -sS http://127.0.0.1:5000/query -H 'content-type: application/json' -d '{\"query\":\"SELECT $1 AS value\",\"params\":[42]}'"
916 .to_string(),
917 ),
918 );
919
920 let mut request_body = Map::new();
921 request_body.insert(
922 "query".to_string(),
923 JsonValue::String("required string".to_string()),
924 );
925 request_body.insert(
926 "params".to_string(),
927 JsonValue::String("optional array".to_string()),
928 );
929
930 let mut response_shape = Map::new();
931 response_shape.insert(
932 "columns".to_string(),
933 JsonValue::String("projected column names".to_string()),
934 );
935 response_shape.insert(
936 "records[].values".to_string(),
937 JsonValue::String("only projected values".to_string()),
938 );
939 response_shape.insert(
940 "records[].meta".to_string(),
941 JsonValue::String("internal metadata when present".to_string()),
942 );
943
944 let mut object = Map::new();
945 object.insert("ok".to_string(), JsonValue::Bool(false));
946 object.insert(
947 "code".to_string(),
948 JsonValue::String("method_not_allowed".to_string()),
949 );
950 object.insert(
951 "message".to_string(),
952 JsonValue::String("/query accepts POST requests".to_string()),
953 );
954 object.insert(
955 "hint".to_string(),
956 JsonValue::String(
957 "Send raw SQL in the body, or JSON with a string 'query' field.".to_string(),
958 ),
959 );
960 object.insert("method".to_string(), JsonValue::String("POST".to_string()));
961 object.insert("path".to_string(), JsonValue::String("/query".to_string()));
962 object.insert("request_body".to_string(), JsonValue::Object(request_body));
963 object.insert(
964 "response_shape".to_string(),
965 JsonValue::Object(response_shape),
966 );
967 object.insert("examples".to_string(), JsonValue::Object(examples));
968 object.insert(
969 "docs".to_string(),
970 JsonValue::String("https://reddb.io/docs/query".to_string()),
971 );
972
973 json_response(405, JsonValue::Object(object))
974 .with_header("Allow", http::HeaderValue::from_static("POST"))
975 }
976
977 fn handle_root_discovery(&self) -> HttpResponse {
978 let mut endpoints = Map::new();
979 endpoints.insert(
980 "health".to_string(),
981 JsonValue::String("GET /health".to_string()),
982 );
983 endpoints.insert(
984 "ready".to_string(),
985 JsonValue::String("GET /ready".to_string()),
986 );
987 endpoints.insert(
988 "query".to_string(),
989 JsonValue::String("POST /query".to_string()),
990 );
991 endpoints.insert(
992 "query_readiness".to_string(),
993 JsonValue::String("GET /ready/query".to_string()),
994 );
995 endpoints.insert(
996 "catalog".to_string(),
997 JsonValue::String("GET /catalog".to_string()),
998 );
999 endpoints.insert(
1000 "deployment_profiles".to_string(),
1001 JsonValue::String("GET /deployment/profiles".to_string()),
1002 );
1003
1004 let mut examples = Map::new();
1005 examples.insert(
1006 "http_raw_sql".to_string(),
1007 JsonValue::String("curl -sS http://127.0.0.1:5000/query -d 'SELECT 1'".to_string()),
1008 );
1009 examples.insert(
1010 "http_json_query".to_string(),
1011 JsonValue::String(
1012 "curl -sS http://127.0.0.1:5000/query -H 'content-type: application/json' -d '{\"query\":\"SELECT 1\"}'"
1013 .to_string(),
1014 ),
1015 );
1016 examples.insert(
1017 "http_json_query_with_params".to_string(),
1018 JsonValue::String(
1019 "curl -sS http://127.0.0.1:5000/query -H 'content-type: application/json' -d '{\"query\":\"SELECT $1 AS value\",\"params\":[42]}'"
1020 .to_string(),
1021 ),
1022 );
1023
1024 let mut object = Map::new();
1025 object.insert("ok".to_string(), JsonValue::Bool(true));
1026 object.insert(
1027 "service".to_string(),
1028 JsonValue::String("reddb".to_string()),
1029 );
1030 object.insert(
1031 "version".to_string(),
1032 JsonValue::String(env!("CARGO_PKG_VERSION").to_string()),
1033 );
1034 object.insert("endpoints".to_string(), JsonValue::Object(endpoints));
1035 object.insert("examples".to_string(), JsonValue::Object(examples));
1036 object.insert(
1037 "docs".to_string(),
1038 JsonValue::String("https://reddb.io/docs".to_string()),
1039 );
1040 object.insert(
1041 "transport_listeners".to_string(),
1042 self.transport_readiness_json(),
1043 );
1044 json_response(200, JsonValue::Object(object))
1045 }
1046
1047 fn health_json_with_transport(&self, report: &HealthReport) -> JsonValue {
1048 let mut value = crate::presentation::ops_json::health_json(report);
1049 if let JsonValue::Object(ref mut object) = value {
1050 object.insert(
1051 "transport_listeners".to_string(),
1052 self.transport_readiness_json(),
1053 );
1054 }
1055 value
1056 }
1057
1058 pub fn serve(&self) -> io::Result<()> {
1059 let listener = TcpListener::bind(&self.options.bind_addr)?;
1060 self.serve_on(listener)
1061 }
1062
1063 pub fn serve_on(&self, listener: TcpListener) -> io::Result<()> {
1070 let runtime = axum_edge::build_edge_runtime()?;
1071 runtime.block_on(
1072 self.clone()
1073 .serve_edge_on_std(listener, HttpTransport::Http),
1074 )
1075 }
1076
1077 pub fn serve_one_on(&self, listener: TcpListener) -> io::Result<()> {
1081 let runtime = axum_edge::build_background_edge_runtime()?;
1082 let server = self.clone();
1083 runtime.block_on(async move {
1084 listener.set_nonblocking(true)?;
1085 let listener = tokio::net::TcpListener::from_std(listener)?;
1086 let (stream, _peer) = listener.accept().await?;
1087 server.serve_edge_one(stream).await;
1088 Ok(())
1089 })
1090 }
1091
1092 pub fn serve_in_background(&self) -> thread::JoinHandle<io::Result<()>> {
1093 let server = self.clone();
1094 thread::spawn(move || server.serve())
1095 }
1096
1097 pub fn serve_in_background_on(
1098 &self,
1099 listener: TcpListener,
1100 ) -> thread::JoinHandle<io::Result<()>> {
1101 let server = self.clone();
1102 thread::spawn(move || {
1103 let runtime = axum_edge::build_background_edge_runtime()?;
1104 runtime.block_on(server.serve_edge_on_std(listener, HttpTransport::Http))
1105 })
1106 }
1107
1108 pub fn serve_tls(&self, tls_config: std::sync::Arc<rustls::ServerConfig>) -> io::Result<()> {
1112 let listener = TcpListener::bind(&self.options.bind_addr)?;
1113 self.serve_tls_on(listener, tls_config)
1114 }
1115
1116 pub fn serve_tls_on(
1117 &self,
1118 listener: TcpListener,
1119 tls_config: std::sync::Arc<rustls::ServerConfig>,
1120 ) -> io::Result<()> {
1121 let runtime = axum_edge::build_edge_runtime()?;
1122 let acceptor = axum_edge::tls_acceptor(tls_config);
1123 runtime.block_on(self.clone().serve_edge_tls_on_std(
1124 listener,
1125 acceptor,
1126 HttpTransport::Https,
1127 ))
1128 }
1129
1130 pub fn serve_tls_in_background(
1131 &self,
1132 tls_config: std::sync::Arc<rustls::ServerConfig>,
1133 ) -> thread::JoinHandle<io::Result<()>> {
1134 let server = self.clone();
1135 thread::spawn(move || server.serve_tls(tls_config))
1136 }
1137
1138 pub fn serve_tls_in_background_on(
1139 &self,
1140 listener: TcpListener,
1141 tls_config: std::sync::Arc<rustls::ServerConfig>,
1142 ) -> thread::JoinHandle<io::Result<()>> {
1143 let server = self.clone();
1144 thread::spawn(move || {
1145 let runtime = axum_edge::build_background_edge_runtime()?;
1146 let acceptor = axum_edge::tls_acceptor(tls_config);
1147 runtime.block_on(server.serve_edge_tls_on_std(listener, acceptor, HttpTransport::Https))
1148 })
1149 }
1150
1151 fn handle_connection(&self, stream: TcpStream) -> io::Result<()> {
1152 let started = Instant::now();
1153 let result = self.handle_connection_inner(stream);
1154 let elapsed = started.elapsed().as_secs_f64();
1155 self.http_metrics
1156 .record_duration(HttpTransport::Http, elapsed);
1157 result
1158 }
1159
1160 fn handle_connection_inner(&self, mut stream: TcpStream) -> io::Result<()> {
1161 stream.set_read_timeout(Some(Duration::from_millis(self.options.read_timeout_ms)))?;
1162 stream.set_write_timeout(Some(Duration::from_millis(self.options.write_timeout_ms)))?;
1163
1164 let deadline = HandlerDeadline::arm(Arc::clone(&self.handler_clock), self.handler_timeout);
1172
1173 let request = HttpRequest::read_from(&mut stream, self.options.max_body_bytes)?;
1174
1175 if deadline.expired() {
1177 self.http_metrics
1178 .record_reject(HttpTransport::Http, HttpRejectReason::HandlerTimeout);
1179 Self::write_handler_timeout_503(&mut stream);
1180 return Ok(());
1181 }
1182
1183 if self.try_route_streaming(&request, &mut stream)? {
1184 return Ok(());
1185 }
1186 let response = self.route(request);
1187
1188 self.apply_test_slow_inject();
1192
1193 if deadline.expired() {
1195 self.http_metrics
1196 .record_reject(HttpTransport::Http, HttpRejectReason::HandlerTimeout);
1197 Self::write_handler_timeout_503(&mut stream);
1198 return Ok(());
1199 }
1200
1201 response.write_to(&mut stream)?;
1202 stream.flush()?;
1203 Ok(())
1204 }
1205
1206 fn write_handler_timeout_503<S: Write>(stream: &mut S) {
1212 const RESPONSE: &[u8] = b"HTTP/1.1 503 Service Unavailable\r\n\
1213 Connection: close\r\n\
1214 Content-Length: 0\r\n\
1215 \r\n";
1216 let _ = stream.write_all(RESPONSE);
1217 let _ = stream.flush();
1218 }
1219}