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 reddb_types::Value;
46
47fn analytics_job_json(job: &crate::PhysicalAnalyticsJob) -> JsonValue {
48 crate::presentation::admin_json::analytics_job_json(job)
49}
50
51#[cfg(test)]
53pub(crate) static RED_ADMIN_TOKEN_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58 use crate::api::RedDBOptions;
59 use crate::health::HealthReport;
60 use crate::transport::{TransportListenerFailure, TransportListenerState, TransportReadiness};
61
62 #[test]
63 fn server_options_default_http_body_limit_is_32_mib() {
64 assert_eq!(ServerOptions::default().max_body_bytes, 32 * 1024 * 1024);
65 }
66
67 #[test]
68 fn health_json_reports_transport_listeners() {
69 let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
70 let mut options = ServerOptions::default();
71 options.transport_readiness = TransportReadiness {
72 active: vec![TransportListenerState {
73 transport: "grpc".to_string(),
74 bind_addr: "127.0.0.1:5000".to_string(),
75 explicit: true,
76 }],
77 failed: vec![TransportListenerFailure {
78 transport: "http".to_string(),
79 bind_addr: "127.0.0.1:5000".to_string(),
80 explicit: false,
81 reason: "http listener bind 127.0.0.1:5000: address in use".to_string(),
82 }],
83 };
84 let server = RedDBServer::with_options(runtime, options);
85
86 let payload = server.health_json_with_transport(&HealthReport::healthy());
87 let JsonValue::Object(root) = payload else {
88 panic!("health payload should be an object");
89 };
90 let Some(JsonValue::Object(listeners)) = root.get("transport_listeners") else {
91 panic!("health payload should include transport_listeners");
92 };
93 let Some(JsonValue::Array(active)) = listeners.get("active") else {
94 panic!("transport_listeners.active should be an array");
95 };
96 let Some(JsonValue::Array(failed)) = listeners.get("failed") else {
97 panic!("transport_listeners.failed should be an array");
98 };
99
100 assert_eq!(active.len(), 1);
101 assert_eq!(failed.len(), 1);
102 }
103}
104
105fn graph_projection_json(projection: &crate::PhysicalGraphProjection) -> JsonValue {
106 crate::presentation::admin_json::graph_projection_json(projection)
107}
108
109mod axum_edge;
110pub mod handlers_admin;
111mod handlers_admin_metrics;
112mod handlers_admin_status;
113mod handlers_ai;
114mod handlers_ai_model_cache;
115pub(crate) mod handlers_auth;
116mod handlers_backup;
117mod handlers_browser_auth;
118mod handlers_cache;
119mod handlers_capabilities;
120mod handlers_collection_policy;
121mod handlers_ec;
122pub(crate) mod handlers_entity;
123mod handlers_failover;
124mod handlers_geo;
125mod handlers_graph;
126mod handlers_iam_policy;
127mod handlers_keyed;
128mod handlers_log;
129mod handlers_metrics;
130mod handlers_ops;
131mod handlers_ops_policy;
132pub mod ui_bridge;
136mod ws_edge;
137pub mod ui_bundle_resolver;
141pub mod ui_auth;
144mod ui_static;
148pub mod ui_deeplink;
153pub(crate) mod handlers_query;
158mod handlers_replication;
159mod handlers_topology;
160mod handlers_vector;
161pub mod header_escape_guard;
162pub mod http_connection_limiter;
163pub mod http_handler_metrics;
164pub mod http_limits;
165pub mod http_principal_limiter;
166pub mod http_request_metrics;
167pub mod ingest_pipeline;
168pub mod output_stream;
169mod patch_support;
170mod request_body;
171mod request_context;
172mod request_identity;
173pub(crate) mod route_catalog;
174mod routes;
175pub(crate) use routes::discovered_route_catalog;
176mod routing;
177mod serverless_support;
178pub mod tls;
179mod transport;
180mod transport_surface;
181
182#[doc(hidden)]
186pub fn command_coverage_matrix() -> String {
187 route_catalog::render_command_coverage_matrix(routes::discovered_route_catalog())
188}
189
190use self::handlers_ai::*;
191use self::handlers_entity::*;
192use self::handlers_graph::*;
193use self::handlers_keyed::*;
194use self::handlers_metrics::*;
195use self::handlers_ops::*;
196use self::handlers_query::*;
197use self::http_connection_limiter::{
198 HandlerDeadline, HttpConnectionLimiter, MonotonicClock, SystemMonotonicClock,
199};
200use self::http_handler_metrics::{HttpHandlerMetrics, HttpRejectReason, HttpTransport};
201pub use self::http_limits::{
202 HttpLimitsCliInput, HttpLimitsResolved, DEFAULT_HANDLER_TIMEOUT_MS, DEFAULT_RETRY_AFTER_SECS,
203};
204use self::http_principal_limiter::PrincipalConnectionLimiter;
205use self::http_request_metrics::HttpRequestMetrics;
206use self::patch_support::*;
207use self::request_body::*;
208use self::routing::*;
209use self::serverless_support::*;
210use self::transport::*;
211
212pub(crate) fn command_catalog() -> &'static route_catalog::CommandCatalog {
213 routes::discovered_route_catalog()
214}
215
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub enum ServerSurface {
223 Public,
225 AdminOnly,
229 MetricsOnly,
233}
234
235#[derive(Debug, Clone)]
236pub struct ServerOptions {
237 pub bind_addr: String,
238 pub max_body_bytes: usize,
239 pub read_timeout_ms: u64,
240 pub write_timeout_ms: u64,
241 pub max_scan_limit: usize,
242 pub surface: ServerSurface,
246 pub transport_readiness: crate::transport::TransportReadiness,
247 pub websocket_allowed_origins: Vec<String>,
255 pub ui_dir: Option<std::path::PathBuf>,
264}
265
266pub const DEFAULT_HTTP_MAX_BODY_BYTES: usize = 32 * 1024 * 1024;
267
268impl Default for ServerOptions {
269 fn default() -> Self {
270 Self {
271 bind_addr: "127.0.0.1:5000".to_string(),
272 max_body_bytes: DEFAULT_HTTP_MAX_BODY_BYTES,
273 read_timeout_ms: 5_000,
274 write_timeout_ms: 5_000,
275 max_scan_limit: 1_000,
276 surface: ServerSurface::Public,
277 transport_readiness: crate::transport::TransportReadiness::default(),
278 websocket_allowed_origins: Vec::new(),
279 ui_dir: None,
280 }
281 }
282}
283
284pub struct ServerReplicationState {
286 pub config: crate::replication::ReplicationConfig,
287 pub primary: Option<crate::replication::primary::PrimaryReplication>,
288}
289
290#[derive(Clone)]
291pub struct RedDBServer {
292 runtime: RedDBRuntime,
293 options: ServerOptions,
294 auth_store: Option<Arc<AuthStore>>,
295 replication: Option<Arc<ServerReplicationState>>,
296 http_limiter: HttpConnectionLimiter,
301 handler_timeout: Duration,
307 handler_clock: Arc<dyn MonotonicClock>,
314 slow_inject_ms: Arc<AtomicU64>,
321 http_metrics: HttpHandlerMetrics,
327 http_request_metrics: HttpRequestMetrics,
333 retry_after_secs: u64,
337 principal_limiter: PrincipalConnectionLimiter,
345 pub(crate) stream_capacity: Arc<output_stream::StreamCapacityRegistry>,
353 pub(crate) lease_registry: Arc<output_stream::LeaseRegistry>,
358 pub(crate) cursor_registry: Arc<output_stream::CursorRegistry>,
363}
364
365const DEFAULT_HANDLER_TIMEOUT: Duration = Duration::from_millis(30_000);
367
368#[derive(Debug, Clone, Copy, PartialEq, Eq)]
369enum ServerlessWarmupScope {
370 Indexes,
371 GraphProjections,
372 AnalyticsJobs,
373 NativeArtifacts,
374}
375
376#[derive(Debug, Clone, Copy, PartialEq, Eq)]
377enum DeploymentProfile {
378 Embedded,
379 Server,
380 Serverless,
381}
382
383fn percent_decode_path_segment(input: &str) -> Result<String, String> {
384 let bytes = input.as_bytes();
385 let mut out = Vec::with_capacity(bytes.len());
386 let mut index = 0;
387 while index < bytes.len() {
388 match bytes[index] {
389 b'%' => {
390 if index + 2 >= bytes.len() {
391 return Err("truncated percent escape".to_string());
392 }
393 let high = hex_value(bytes[index + 1])
394 .ok_or_else(|| "invalid percent escape".to_string())?;
395 let low = hex_value(bytes[index + 2])
396 .ok_or_else(|| "invalid percent escape".to_string())?;
397 out.push((high << 4) | low);
398 index += 3;
399 }
400 byte => {
401 out.push(byte);
402 index += 1;
403 }
404 }
405 }
406 String::from_utf8(out).map_err(|_| "path segment is not valid UTF-8".to_string())
407}
408
409fn hex_value(byte: u8) -> Option<u8> {
410 match byte {
411 b'0'..=b'9' => Some(byte - b'0'),
412 b'a'..=b'f' => Some(byte - b'a' + 10),
413 b'A'..=b'F' => Some(byte - b'A' + 10),
414 _ => None,
415 }
416}
417
418#[derive(Debug, Clone)]
419struct ParsedQueryRequest {
420 query: String,
421 entity_types: Option<Vec<String>>,
422 capabilities: Option<Vec<String>>,
423 commit_policy: Option<crate::replication::CommitPolicy>,
424 params: Option<Vec<crate::runtime::query_request::ParamValue>>,
427}
428
429#[derive(Debug, Clone, Copy)]
430enum PatchOperationType {
431 Set,
432 Replace,
433 Unset,
434}
435
436#[derive(Debug, Clone)]
437struct PatchOperation {
438 op: PatchOperationType,
439 path: Vec<String>,
440 value: Option<JsonValue>,
441}
442
443impl RedDBServer {
444 pub fn new(runtime: RedDBRuntime) -> Self {
445 Self::with_options(runtime, ServerOptions::default())
446 }
447
448 pub fn from_database_options(
449 db_options: RedDBOptions,
450 server_options: ServerOptions,
451 ) -> RedDBResult<Self> {
452 let runtime = RedDBRuntime::with_options(db_options)?;
453 Ok(Self::with_options(runtime, server_options))
454 }
455
456 pub fn with_options(runtime: RedDBRuntime, options: ServerOptions) -> Self {
457 Self {
458 runtime,
459 options,
460 auth_store: None,
461 replication: None,
462 http_limiter: HttpConnectionLimiter::with_default_cap(),
463 handler_timeout: DEFAULT_HANDLER_TIMEOUT,
464 handler_clock: Arc::new(SystemMonotonicClock::new()),
465 slow_inject_ms: Arc::new(AtomicU64::new(0)),
466 http_metrics: HttpHandlerMetrics::new(),
467 http_request_metrics: HttpRequestMetrics::new(),
468 retry_after_secs: DEFAULT_RETRY_AFTER_SECS,
469 principal_limiter: PrincipalConnectionLimiter::new(
470 http_limits::DEFAULT_MAX_INFLIGHT_PER_PRINCIPAL,
471 ),
472 stream_capacity: output_stream::StreamCapacityRegistry::new(),
473 lease_registry: output_stream::LeaseRegistry::new(),
474 cursor_registry: output_stream::CursorRegistry::new(),
475 }
476 }
477
478 #[doc(hidden)]
479 pub fn stream_capacity(&self) -> &Arc<output_stream::StreamCapacityRegistry> {
480 &self.stream_capacity
481 }
482
483 #[doc(hidden)]
484 pub fn lease_registry(&self) -> &Arc<output_stream::LeaseRegistry> {
485 &self.lease_registry
486 }
487
488 #[doc(hidden)]
489 pub fn cursor_registry(&self) -> &Arc<output_stream::CursorRegistry> {
490 &self.cursor_registry
491 }
492
493 #[doc(hidden)]
494 pub fn http_metrics(&self) -> &HttpHandlerMetrics {
495 &self.http_metrics
496 }
497
498 #[doc(hidden)]
501 pub fn http_request_metrics(&self) -> &HttpRequestMetrics {
502 &self.http_request_metrics
503 }
504
505 #[doc(hidden)]
510 pub fn with_http_limiter_cap(mut self, cap: usize) -> Self {
511 self.http_limiter = HttpConnectionLimiter::new(cap);
512 self
513 }
514
515 pub fn with_http_limits(mut self, limits: HttpLimitsResolved) -> Self {
520 self.http_limiter = HttpConnectionLimiter::new(limits.max_handlers);
521 self.handler_timeout = Duration::from_millis(limits.handler_timeout_ms);
522 self.retry_after_secs = limits.retry_after_secs;
523 self.principal_limiter = PrincipalConnectionLimiter::new(limits.max_inflight_per_principal);
524 self
525 }
526
527 #[doc(hidden)]
532 pub fn with_principal_inflight_cap(mut self, cap: usize) -> Self {
533 self.principal_limiter = PrincipalConnectionLimiter::new(cap);
534 self
535 }
536
537 #[doc(hidden)]
538 pub fn principal_limiter(&self) -> &PrincipalConnectionLimiter {
539 &self.principal_limiter
540 }
541
542 #[doc(hidden)]
543 pub fn retry_after_secs(&self) -> u64 {
544 self.retry_after_secs
545 }
546
547 #[doc(hidden)]
548 pub fn http_limiter(&self) -> &HttpConnectionLimiter {
549 &self.http_limiter
550 }
551
552 #[doc(hidden)]
555 pub fn with_handler_timeout(mut self, timeout: Duration) -> Self {
556 self.handler_timeout = timeout;
557 self
558 }
559
560 #[doc(hidden)]
561 pub fn handler_timeout(&self) -> Duration {
562 self.handler_timeout
563 }
564
565 #[doc(hidden)]
570 pub fn with_handler_clock(mut self, clock: Arc<dyn MonotonicClock>) -> Self {
571 self.handler_clock = clock;
572 self
573 }
574
575 #[doc(hidden)]
581 pub fn set_test_slow_inject_ms(&self, ms: u64) {
582 self.slow_inject_ms.store(ms, Ordering::Relaxed);
583 }
584
585 pub fn with_auth(mut self, auth_store: Arc<AuthStore>) -> Self {
589 self.runtime.set_auth_store(Arc::clone(&auth_store));
590 self.auth_store = Some(auth_store);
591 self
592 }
593
594 pub fn with_replication(mut self, state: Arc<ServerReplicationState>) -> Self {
596 self.replication = Some(state);
597 self
598 }
599
600 pub fn with_websocket_allowed_origins(mut self, origins: Vec<String>) -> Self {
605 self.options.websocket_allowed_origins = origins;
606 self
607 }
608
609 pub(crate) fn websocket_allowed_origins(&self) -> &[String] {
611 &self.options.websocket_allowed_origins
612 }
613
614 pub fn with_ui_dir(mut self, dir: std::path::PathBuf) -> Self {
620 self.options.ui_dir = Some(dir);
621 self
622 }
623
624 pub(crate) fn ui_dir(&self) -> Option<&std::path::Path> {
627 self.options.ui_dir.as_deref()
628 }
629
630 pub fn with_browser_token_authority(
637 self,
638 authority: Arc<crate::auth::browser_token::BrowserTokenAuthority>,
639 ) -> Self {
640 self.runtime.set_browser_token_authority(Some(authority));
641 self
642 }
643
644 pub fn runtime(&self) -> &RedDBRuntime {
645 &self.runtime
646 }
647
648 pub fn options(&self) -> &ServerOptions {
649 &self.options
650 }
651
652 fn admin_use_cases(&self) -> AdminUseCases<'_, RedDBRuntime> {
653 AdminUseCases::new(&self.runtime)
654 }
655
656 fn entity_use_cases(&self) -> EntityUseCases<'_, RedDBRuntime> {
657 EntityUseCases::new(&self.runtime)
658 }
659
660 fn graph_use_cases(&self) -> GraphUseCases<'_, RedDBRuntime> {
661 GraphUseCases::new(&self.runtime)
662 }
663
664 fn native_use_cases(&self) -> NativeUseCases<'_, RedDBRuntime> {
665 NativeUseCases::new(&self.runtime)
666 }
667
668 fn tree_use_cases(&self) -> TreeUseCases<'_, RedDBRuntime> {
669 TreeUseCases::new(&self.runtime)
670 }
671
672 fn transport_readiness_json(&self) -> JsonValue {
673 let active = self
674 .options
675 .transport_readiness
676 .active
677 .iter()
678 .map(|listener| {
679 let mut object = Map::new();
680 object.insert(
681 "transport".to_string(),
682 JsonValue::String(listener.transport.clone()),
683 );
684 object.insert(
685 "bind_addr".to_string(),
686 JsonValue::String(listener.bind_addr.clone()),
687 );
688 object.insert("explicit".to_string(), JsonValue::Bool(listener.explicit));
689 JsonValue::Object(object)
690 })
691 .collect();
692 let failed = self
693 .options
694 .transport_readiness
695 .failed
696 .iter()
697 .map(|listener| {
698 let mut object = Map::new();
699 object.insert(
700 "transport".to_string(),
701 JsonValue::String(listener.transport.clone()),
702 );
703 object.insert(
704 "bind_addr".to_string(),
705 JsonValue::String(listener.bind_addr.clone()),
706 );
707 object.insert("explicit".to_string(), JsonValue::Bool(listener.explicit));
708 object.insert(
709 "reason".to_string(),
710 JsonValue::String(listener.reason.clone()),
711 );
712 JsonValue::Object(object)
713 })
714 .collect();
715
716 let mut object = Map::new();
717 object.insert("active".to_string(), JsonValue::Array(active));
718 object.insert("failed".to_string(), JsonValue::Array(failed));
719 JsonValue::Object(object)
720 }
721
722 fn handle_grpc_discovery(&self) -> HttpResponse {
723 let mut methods = Map::new();
724 methods.insert(
725 "query".to_string(),
726 JsonValue::String("reddb.v1.RedDB/Query".to_string()),
727 );
728 methods.insert(
729 "batch_query".to_string(),
730 JsonValue::String("reddb.v1.RedDB/BatchQuery".to_string()),
731 );
732 methods.insert(
733 "health".to_string(),
734 JsonValue::String("reddb.v1.RedDB/Health".to_string()),
735 );
736 methods.insert(
737 "prepare".to_string(),
738 JsonValue::String("reddb.v1.RedDB/Prepare".to_string()),
739 );
740 methods.insert(
741 "execute_prepared".to_string(),
742 JsonValue::String("reddb.v1.RedDB/ExecutePrepared".to_string()),
743 );
744
745 let mut examples = Map::new();
746 examples.insert(
747 "query".to_string(),
748 JsonValue::String(
749 "grpcurl -plaintext -d '{\"query\":\"SELECT 1\"}' 127.0.0.1:5000 reddb.v1.RedDB/Query"
750 .to_string(),
751 ),
752 );
753 examples.insert(
754 "query_with_params".to_string(),
755 JsonValue::String(
756 "grpcurl -plaintext -d '{\"query\":\"SELECT $1 AS value\",\"params\":[{\"intValue\":42}]}' 127.0.0.1:5000 reddb.v1.RedDB/Query"
757 .to_string(),
758 ),
759 );
760 examples.insert(
761 "health".to_string(),
762 JsonValue::String(
763 "grpcurl -plaintext -d '{}' 127.0.0.1:5000 reddb.v1.RedDB/Health".to_string(),
764 ),
765 );
766
767 let mut object = Map::new();
768 object.insert("ok".to_string(), JsonValue::Bool(true));
769 object.insert(
770 "service".to_string(),
771 JsonValue::String("reddb.v1.RedDB".to_string()),
772 );
773 object.insert(
774 "package".to_string(),
775 JsonValue::String("reddb.v1".to_string()),
776 );
777 object.insert(
778 "proto".to_string(),
779 JsonValue::String("crates/reddb-grpc-proto/proto/reddb.proto".to_string()),
780 );
781 object.insert("methods".to_string(), JsonValue::Object(methods));
782 object.insert("examples".to_string(), JsonValue::Object(examples));
783 object.insert(
784 "transport_listeners".to_string(),
785 self.transport_readiness_json(),
786 );
787 object.insert(
788 "hint".to_string(),
789 JsonValue::String(
790 "If grpcurl cannot list services, pass the proto file with -import-path crates/reddb-grpc-proto/proto -proto reddb.proto."
791 .to_string(),
792 ),
793 );
794 json_response(200, JsonValue::Object(object))
795 }
796
797 fn handle_query_contract(&self) -> HttpResponse {
798 let mut examples = Map::new();
799 examples.insert(
800 "raw_sql".to_string(),
801 JsonValue::String("curl -sS http://127.0.0.1:5000/query -d 'SELECT 1'".to_string()),
802 );
803 examples.insert(
804 "json_query".to_string(),
805 JsonValue::String(
806 "curl -sS http://127.0.0.1:5000/query -H 'content-type: application/json' -d '{\"query\":\"SELECT 1\"}'"
807 .to_string(),
808 ),
809 );
810 examples.insert(
811 "json_query_with_params".to_string(),
812 JsonValue::String(
813 "curl -sS http://127.0.0.1:5000/query -H 'content-type: application/json' -d '{\"query\":\"SELECT $1 AS value\",\"params\":[42]}'"
814 .to_string(),
815 ),
816 );
817
818 let mut request_body = Map::new();
819 request_body.insert(
820 "query".to_string(),
821 JsonValue::String("required string".to_string()),
822 );
823 request_body.insert(
824 "params".to_string(),
825 JsonValue::String("optional array".to_string()),
826 );
827
828 let mut response_shape = Map::new();
829 response_shape.insert(
830 "columns".to_string(),
831 JsonValue::String("projected column names".to_string()),
832 );
833 response_shape.insert(
834 "records[].values".to_string(),
835 JsonValue::String("only projected values".to_string()),
836 );
837 response_shape.insert(
838 "records[].meta".to_string(),
839 JsonValue::String("internal metadata when present".to_string()),
840 );
841
842 let mut object = Map::new();
843 object.insert("ok".to_string(), JsonValue::Bool(false));
844 object.insert(
845 "code".to_string(),
846 JsonValue::String("method_not_allowed".to_string()),
847 );
848 object.insert(
849 "message".to_string(),
850 JsonValue::String("/query accepts POST requests".to_string()),
851 );
852 object.insert(
853 "hint".to_string(),
854 JsonValue::String(
855 "Send raw SQL in the body, or JSON with a string 'query' field.".to_string(),
856 ),
857 );
858 object.insert("method".to_string(), JsonValue::String("POST".to_string()));
859 object.insert("path".to_string(), JsonValue::String("/query".to_string()));
860 object.insert("request_body".to_string(), JsonValue::Object(request_body));
861 object.insert(
862 "response_shape".to_string(),
863 JsonValue::Object(response_shape),
864 );
865 object.insert("examples".to_string(), JsonValue::Object(examples));
866 object.insert(
867 "docs".to_string(),
868 JsonValue::String("https://reddb.io/docs/query".to_string()),
869 );
870
871 json_response(405, JsonValue::Object(object))
872 .with_header("Allow", http::HeaderValue::from_static("POST"))
873 }
874
875 fn handle_root_discovery(&self) -> HttpResponse {
876 let mut endpoints = Map::new();
877 endpoints.insert(
878 "health".to_string(),
879 JsonValue::String("GET /health".to_string()),
880 );
881 endpoints.insert(
882 "ready".to_string(),
883 JsonValue::String("GET /ready".to_string()),
884 );
885 endpoints.insert(
886 "query".to_string(),
887 JsonValue::String("POST /query".to_string()),
888 );
889 endpoints.insert(
890 "query_readiness".to_string(),
891 JsonValue::String("GET /ready/query".to_string()),
892 );
893 endpoints.insert(
894 "catalog".to_string(),
895 JsonValue::String("GET /catalog".to_string()),
896 );
897 endpoints.insert(
898 "deployment_profiles".to_string(),
899 JsonValue::String("GET /deployment/profiles".to_string()),
900 );
901
902 let mut examples = Map::new();
903 examples.insert(
904 "http_raw_sql".to_string(),
905 JsonValue::String("curl -sS http://127.0.0.1:5000/query -d 'SELECT 1'".to_string()),
906 );
907 examples.insert(
908 "http_json_query".to_string(),
909 JsonValue::String(
910 "curl -sS http://127.0.0.1:5000/query -H 'content-type: application/json' -d '{\"query\":\"SELECT 1\"}'"
911 .to_string(),
912 ),
913 );
914 examples.insert(
915 "http_json_query_with_params".to_string(),
916 JsonValue::String(
917 "curl -sS http://127.0.0.1:5000/query -H 'content-type: application/json' -d '{\"query\":\"SELECT $1 AS value\",\"params\":[42]}'"
918 .to_string(),
919 ),
920 );
921
922 let mut object = Map::new();
923 object.insert("ok".to_string(), JsonValue::Bool(true));
924 object.insert(
925 "service".to_string(),
926 JsonValue::String("reddb".to_string()),
927 );
928 object.insert(
929 "version".to_string(),
930 JsonValue::String(env!("CARGO_PKG_VERSION").to_string()),
931 );
932 object.insert("endpoints".to_string(), JsonValue::Object(endpoints));
933 object.insert("examples".to_string(), JsonValue::Object(examples));
934 object.insert(
935 "docs".to_string(),
936 JsonValue::String("https://reddb.io/docs".to_string()),
937 );
938 object.insert(
939 "transport_listeners".to_string(),
940 self.transport_readiness_json(),
941 );
942 json_response(200, JsonValue::Object(object))
943 }
944
945 fn health_json_with_transport(&self, report: &HealthReport) -> JsonValue {
946 let mut value = crate::presentation::ops_json::health_json(report);
947 if let JsonValue::Object(ref mut object) = value {
948 object.insert(
949 "transport_listeners".to_string(),
950 self.transport_readiness_json(),
951 );
952 }
953 value
954 }
955
956 pub fn serve(&self) -> io::Result<()> {
957 let listener = TcpListener::bind(&self.options.bind_addr)?;
958 self.serve_on(listener)
959 }
960
961 pub fn serve_on(&self, listener: TcpListener) -> io::Result<()> {
968 let runtime = axum_edge::build_edge_runtime()?;
969 runtime.block_on(
970 self.clone()
971 .serve_edge_on_std(listener, HttpTransport::Http),
972 )
973 }
974
975 pub fn serve_one_on(&self, listener: TcpListener) -> io::Result<()> {
979 let runtime = axum_edge::build_background_edge_runtime()?;
980 let server = self.clone();
981 runtime.block_on(async move {
982 listener.set_nonblocking(true)?;
983 let listener = tokio::net::TcpListener::from_std(listener)?;
984 let (stream, _peer) = listener.accept().await?;
985 server.serve_edge_one(stream).await;
986 Ok(())
987 })
988 }
989
990 pub fn serve_in_background(&self) -> thread::JoinHandle<io::Result<()>> {
991 let server = self.clone();
992 thread::spawn(move || server.serve())
993 }
994
995 pub fn serve_in_background_on(
996 &self,
997 listener: TcpListener,
998 ) -> thread::JoinHandle<io::Result<()>> {
999 let server = self.clone();
1000 thread::spawn(move || {
1001 let runtime = axum_edge::build_background_edge_runtime()?;
1002 runtime.block_on(server.serve_edge_on_std(listener, HttpTransport::Http))
1003 })
1004 }
1005
1006 pub fn serve_tls(&self, tls_config: std::sync::Arc<rustls::ServerConfig>) -> io::Result<()> {
1010 let listener = TcpListener::bind(&self.options.bind_addr)?;
1011 self.serve_tls_on(listener, tls_config)
1012 }
1013
1014 pub fn serve_tls_on(
1015 &self,
1016 listener: TcpListener,
1017 tls_config: std::sync::Arc<rustls::ServerConfig>,
1018 ) -> io::Result<()> {
1019 let runtime = axum_edge::build_edge_runtime()?;
1020 let acceptor = axum_edge::tls_acceptor(tls_config);
1021 runtime.block_on(self.clone().serve_edge_tls_on_std(
1022 listener,
1023 acceptor,
1024 HttpTransport::Https,
1025 ))
1026 }
1027
1028 pub fn serve_tls_in_background(
1029 &self,
1030 tls_config: std::sync::Arc<rustls::ServerConfig>,
1031 ) -> thread::JoinHandle<io::Result<()>> {
1032 let server = self.clone();
1033 thread::spawn(move || server.serve_tls(tls_config))
1034 }
1035
1036 pub fn serve_tls_in_background_on(
1037 &self,
1038 listener: TcpListener,
1039 tls_config: std::sync::Arc<rustls::ServerConfig>,
1040 ) -> thread::JoinHandle<io::Result<()>> {
1041 let server = self.clone();
1042 thread::spawn(move || {
1043 let runtime = axum_edge::build_background_edge_runtime()?;
1044 let acceptor = axum_edge::tls_acceptor(tls_config);
1045 runtime.block_on(server.serve_edge_tls_on_std(listener, acceptor, HttpTransport::Https))
1046 })
1047 }
1048
1049 fn handle_connection(&self, stream: TcpStream) -> io::Result<()> {
1050 let started = Instant::now();
1051 let result = self.handle_connection_inner(stream);
1052 let elapsed = started.elapsed().as_secs_f64();
1053 self.http_metrics
1054 .record_duration(HttpTransport::Http, elapsed);
1055 result
1056 }
1057
1058 fn handle_connection_inner(&self, mut stream: TcpStream) -> io::Result<()> {
1059 stream.set_read_timeout(Some(Duration::from_millis(self.options.read_timeout_ms)))?;
1060 stream.set_write_timeout(Some(Duration::from_millis(self.options.write_timeout_ms)))?;
1061
1062 let deadline = HandlerDeadline::arm(Arc::clone(&self.handler_clock), self.handler_timeout);
1070
1071 let request = HttpRequest::read_from(&mut stream, self.options.max_body_bytes)?;
1072
1073 if deadline.expired() {
1075 self.http_metrics
1076 .record_reject(HttpTransport::Http, HttpRejectReason::HandlerTimeout);
1077 Self::write_handler_timeout_503(&mut stream);
1078 return Ok(());
1079 }
1080
1081 if self.try_route_streaming(&request, &mut stream)? {
1082 return Ok(());
1083 }
1084 let response = self.route(request);
1085
1086 let inject_ms = self.slow_inject_ms.load(Ordering::Relaxed);
1090 if inject_ms > 0 {
1091 thread::sleep(Duration::from_millis(inject_ms));
1092 }
1093
1094 if deadline.expired() {
1096 self.http_metrics
1097 .record_reject(HttpTransport::Http, HttpRejectReason::HandlerTimeout);
1098 Self::write_handler_timeout_503(&mut stream);
1099 return Ok(());
1100 }
1101
1102 stream.write_all(&response.to_http_bytes())?;
1103 stream.flush()?;
1104 Ok(())
1105 }
1106
1107 fn write_handler_timeout_503<S: Write>(stream: &mut S) {
1113 const RESPONSE: &[u8] = b"HTTP/1.1 503 Service Unavailable\r\n\
1114 Connection: close\r\n\
1115 Content-Length: 0\r\n\
1116 \r\n";
1117 let _ = stream.write_all(RESPONSE);
1118 let _ = stream.flush();
1119 }
1120}