Skip to main content

reddb_server/
server.rs

1//! Minimal HTTP server for RedDB management and remote access.
2
3pub(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// Process-wide test guard for every RED_ADMIN_TOKEN mutation in server tests.
52#[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;
132/// Local `red ui` bridge: serves the UI bundle and fronts the embedded
133/// engine over RedWire-over-WebSocket for `file://` targets (issue #1042,
134/// ADR 0047/0049). Public so the `red ui` CLI command can drive it.
135pub mod ui_bridge;
136mod ws_edge;
137// `red ui` bundle resolver (issue #1043, ADR 0050): pin→URL resolution,
138// HTTPS download, SHA-256 verification, tgz extraction, and local cache
139// management for the pinned red-ui release asset.
140pub mod ui_bundle_resolver;
141// `red ui --token` credential handoff (issue #1048, ADR 0051): one-time
142// loopback nonce channel and served-UI auth-mode wiring.
143pub mod ui_auth;
144// `red server --ui` static bundle surface (issue #1047, ADR 0051): serve
145// the resolved red-ui bundle as inert static assets on the server's HTTP
146// edge so a remote browser can load it and connect back over RedWire-over-WS.
147mod ui_static;
148// `red ui <uri>` deep-link dispatch (issue #1046, ADR 0051): prefer the
149// installed desktop app via the `redui://` scheme, fall back to the served
150// browser bridge when no handler is registered. Decision + canonical
151// deep-link string live behind a testable seam.
152pub mod ui_deeplink;
153// `pub(crate)` so the RedWire input-stream path (issue #764 / S5)
154// can reuse the canonical S4 INSERT builders / identifier checks
155// (`build_insert_sql`, `is_safe_sql_identifier`) rather than fork
156// the SQL-escaping logic.
157pub(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/// Generate the command-coverage artifact: every discovered command joined
183/// against each transport's own binding table. See
184/// [`route_catalog::render_command_coverage_matrix`].
185#[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/// PLAN.md Phase 6.2 — endpoint segregation. A given HTTP listener
217/// can serve either every public surface (`Public`, default) or a
218/// restricted slice (`AdminOnly`, `MetricsOnly`). The route filter at
219/// the top of `route()` consults this so a port bound only to
220/// loopback for admin work won't accidentally hand out DML.
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub enum ServerSurface {
223    /// Everything routed normally (default — matches v0 behaviour).
224    Public,
225    /// Only `/admin/*`, `/metrics`, and `/health/*`. Other paths
226    /// return 404. Intended for `RED_ADMIN_BIND` operator listeners
227    /// which default to `127.0.0.1`.
228    AdminOnly,
229    /// Only `/metrics` and `/health/*`. Intended for
230    /// `RED_METRICS_BIND` Prometheus scrape ports that may be
231    /// exposed to non-admin networks.
232    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    /// Which subset of paths this listener serves. Defaults to
243    /// `Public`. Set to `AdminOnly` / `MetricsOnly` for dedicated
244    /// admin / scrape ports (PLAN.md Phase 6.2).
245    pub surface: ServerSurface,
246    pub transport_readiness: crate::transport::TransportReadiness,
247    /// Allowed `Origin` values for the RedWire-over-WSS browser endpoint
248    /// (issue #935, ADR 0036). WebSocket is not covered by CORS, so the
249    /// upgrade is gated on an explicit allowlist to block Cross-Site
250    /// WebSocket Hijacking. **Default-deny:** empty means the `/redwire`
251    /// route is not mounted at all — operators opt in by configuring at
252    /// least one origin. Matched exactly (scheme+host+port), e.g.
253    /// `https://app.example.com`.
254    pub websocket_allowed_origins: Vec<String>,
255    /// `red server --ui` (issue #1047, ADR 0051). When `Some`, this
256    /// listener also serves the resolved red-ui bundle from this directory
257    /// as inert static assets (`/` → `index.html`), alongside the existing
258    /// API. The assets carry no credential, so exposing them is safe by
259    /// construction — auth lives on the RedWire data endpoint, not the
260    /// asset path. Network reach is governed entirely by `bind_addr`
261    /// (default localhost), so this never widens reach on its own.
262    /// `None` (the default) leaves the listener API-only.
263    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
284/// Replication state exposed to the HTTP server.
285pub 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    /// Bounded handler-thread admission for the clear-text HTTP accept
297    /// loop (issue #570 slice 1). Cloned with the server; `Clone` of
298    /// `HttpConnectionLimiter` shares an `Arc` so every serve loop on
299    /// the same `RedDBServer` shares one cap.
300    http_limiter: HttpConnectionLimiter,
301    /// Per-handler total-time deadline (issue #570 slice 2). Each
302    /// clear-text handler thread arms a deadline at spawn and bails
303    /// with a best-effort 503 at coarse boundaries between request
304    /// parse, route dispatch, and response write. Hard-coded to 30s
305    /// here; the config knob lands in slice 5.
306    handler_timeout: Duration,
307    /// Monotonic clock the per-handler deadline (issue #621) is armed
308    /// against — the same [`MonotonicClock`] abstraction the limiter
309    /// uses. Production wires [`SystemMonotonicClock`] (real wall time);
310    /// tests inject a fake to drive timeout expiry deterministically
311    /// without `sleep()`. Shared via `Arc` so cloned server handles
312    /// (e.g. `serve_in_background`) read the same clock.
313    handler_clock: Arc<dyn MonotonicClock>,
314    /// Test-only synchronous sleep injected between route dispatch and
315    /// response write so an integration test can simulate a slow
316    /// downstream tripping the deadline. Default 0 (no-op). Shared via
317    /// `Arc` so a cloned `RedDBServer` (e.g. `serve_in_background`)
318    /// observes flips from the originating handle. Production callers
319    /// have no way to set this — the setter is `#[doc(hidden)]`.
320    slow_inject_ms: Arc<AtomicU64>,
321    /// Prometheus metrics for the HTTP handler-thread pool (issue
322    /// #573 slice 4). Records rejections (cap_exhausted /
323    /// handler_timeout) and per-handler duration histograms. Cloned
324    /// with the server via `Arc` so every serve loop on the same
325    /// `RedDBServer` writes to one set of counters.
326    http_metrics: HttpHandlerMetrics,
327    /// Issue #1239 / PRD #1237 — `reddb_http_requests_total` counters by
328    /// `method`, matched route template, and status class. Recorded once
329    /// per handled request in `route()`; read by `/metrics` and the
330    /// operational telemetry read model. Cloned with the server via `Arc`
331    /// so every serve loop on the same `RedDBServer` shares one counter set.
332    http_request_metrics: HttpRequestMetrics,
333    /// `Retry-After` value (seconds) emitted in the async edge's
334    /// capacity-reject 503 path (issue #574 slice 5). Read on the reject
335    /// path in `axum_edge`.
336    retry_after_secs: u64,
337    /// Issue #934 / PRD #930 — per-principal concurrent in-flight cap. The
338    /// global `http_limiter` bounds *total* in-flight work (async
339    /// backpressure); this bounds any *single* principal's share so one
340    /// abusive caller can't drain the whole global cap and starve the rest.
341    /// Consulted at the async edge after global admission; a principal over
342    /// its cap gets a structured 429 refusal. Shared via `Arc` (inside the
343    /// limiter) so cloned server handles enforce one set of counters.
344    principal_limiter: PrincipalConnectionLimiter,
345    /// Issue #761 / S2 — process-wide output-stream capacity registry.
346    /// Shared via `Arc` so cloned server handles (e.g.
347    /// `serve_in_background`) all enforce against one set of counters.
348    /// The HTTP NDJSON path acquires through this in
349    /// `try_route_streaming` before invoking the handler; the guard is
350    /// dropped on return so any stream-end path (success / mid-stream
351    /// error / snapshot expiry / panic unwind) releases the slot.
352    pub(crate) stream_capacity: Arc<output_stream::StreamCapacityRegistry>,
353    /// Issue #766 / S7 — resume coordinator ledger. Tracks
354    /// `(snapshot_lsn → opened_at_ms, ttl_ms)` for resume-eligibility
355    /// checks. Shared via `Arc` so cloned server handles see one
356    /// ledger.
357    pub(crate) lease_registry: Arc<output_stream::LeaseRegistry>,
358    /// Issue #807 / PRD #750 — `/query/stream` cursor registry. Holds the
359    /// opaque token → (snapshot pin, TTL, tenant, principal, query) entries
360    /// that let a client resume or reference a streamed read. Shared via
361    /// `Arc` so cloned server handles see one registry.
362    pub(crate) cursor_registry: Arc<output_stream::CursorRegistry>,
363}
364
365/// Default per-handler total-time budget (issue #571 slice 2).
366const 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    /// Optional positional `$N` bind parameters (#358), decoded into the
425    /// Request module's transport-neutral vocabulary.
426    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    /// HTTP request/error volume counters (`reddb_http_requests_total`).
499    /// Read by `/metrics` and the operational telemetry read model.
500    #[doc(hidden)]
501    pub fn http_request_metrics(&self) -> &HttpRequestMetrics {
502        &self.http_request_metrics
503    }
504
505    /// Visible for tests. Lets the integration test in
506    /// `tests/http_connection_limiter.rs` saturate the cap and observe
507    /// `503 Service Unavailable` responses without spinning up
508    /// thousands of sockets.
509    #[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    /// Stamp resolved HTTP limits onto the server (issue #574 slice 5).
516    /// Replaces the limiter cap, the per-handler deadline, and the
517    /// `Retry-After` value used by the limiter's reject path. All
518    /// values are assumed validated by [`http_limits::resolve_http_limits`].
519    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    /// Visible for tests. Override the per-principal concurrent in-flight
528    /// cap (issue #934) so the integration test can saturate one principal
529    /// and observe the structured 429 refusal without standing up hundreds
530    /// of real sockets. `0` disables the per-principal cap.
531    #[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    /// Visible for tests. Override the per-handler total-time deadline
553    /// (issue #570 slice 2). Default 30s.
554    #[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    /// Visible for tests. Override the clock the per-handler deadline
566    /// (issue #621) is armed against, so timeout expiry can be driven
567    /// deterministically without real sleeps. Default is the real
568    /// monotonic clock.
569    #[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    /// Test hook: set a synchronous sleep (in ms) inserted between
576    /// route dispatch and response write. The integration test for
577    /// slice 2 sets a value greater than `handler_timeout` to trip
578    /// the deadline, then resets to 0 to verify recovery. Shared via
579    /// `Arc<AtomicU64>` so cloned server handles see the same flip.
580    #[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    /// Attach an `AuthStore` for HTTP-layer authentication.
586    /// Also injects the store into the runtime so that `Value::Secret`
587    /// auto-encrypt/decrypt can reach the vault AES key.
588    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    /// Attach replication state for status and snapshot endpoints.
595    pub fn with_replication(mut self, state: Arc<ServerReplicationState>) -> Self {
596        self.replication = Some(state);
597        self
598    }
599
600    /// Set the `Origin` allowlist that enables the RedWire-over-WSS
601    /// browser endpoint (issue #935, ADR 0036). A non-empty list mounts
602    /// the `/redwire` upgrade route on the TLS edge; an empty list leaves
603    /// it unmounted (default-deny).
604    pub fn with_websocket_allowed_origins(mut self, origins: Vec<String>) -> Self {
605        self.options.websocket_allowed_origins = origins;
606        self
607    }
608
609    /// The configured RedWire-over-WSS `Origin` allowlist (issue #935).
610    pub(crate) fn websocket_allowed_origins(&self) -> &[String] {
611        &self.options.websocket_allowed_origins
612    }
613
614    /// Serve the resolved red-ui bundle from `dir` as inert static assets
615    /// on this listener (`red server --ui`, issue #1047, ADR 0051). The
616    /// bundle is served as a fallback after the API routing table, so it
617    /// can never shadow a real endpoint; `GET /` resolves to the bundle's
618    /// `index.html`.
619    pub fn with_ui_dir(mut self, dir: std::path::PathBuf) -> Self {
620        self.options.ui_dir = Some(dir);
621        self
622    }
623
624    /// The directory this listener serves the red-ui bundle from, if
625    /// `--ui` is active (issue #1047).
626    pub(crate) fn ui_dir(&self) -> Option<&std::path::Path> {
627        self.options.ui_dir.as_deref()
628    }
629
630    /// Enable the browser credential layer (issue #936, PRD #930) by
631    /// wiring a hybrid-token authority into the runtime. Once set, the
632    /// `/auth/browser/*` HTTP endpoints issue/rotate the access+refresh
633    /// pair and the RedWire WS handshake accepts the access JWT. Left
634    /// unset, the browser flow is inert (default-deny), matching the WS
635    /// endpoint's own opt-in posture.
636    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    /// Serve the async axum/hyper HTTP edge (issue #931) on the given
962    /// listener until it errors fatally. A dedicated multi-threaded tokio
963    /// runtime drives the I/O; the synchronous disk-backed engine is
964    /// reached via `spawn_blocking`. This replaces the retired
965    /// thread-per-connection accept loop and its `(2*num_cpus)` thread
966    /// cap — idle keep-alive connections are now cheap parked tasks.
967    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    /// Accept and serve a single connection to completion, then return.
976    /// Used by tests that want a one-shot HTTP server alongside another
977    /// transport.
978    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    /// Serve TLS-wrapped HTTPS on the configured `bind_addr`. The
1007    /// `tls_config` is shared across all connections (rustls
1008    /// `ServerConfig` is `Send + Sync`).
1009    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        // Issue #570 slice 2 / #621: arm a deadline at handler spawn and
1063        // check at coarse boundaries. Armed against the injectable
1064        // monotonic clock (#621) so timeout behaviour is deterministically
1065        // testable without real sleeps; production wires the real clock,
1066        // so this tracks wall time. No hard pre-emption — a thread blocked
1067        // inside a true syscall is still bounded only by the per-socket
1068        // read/write timeouts.
1069        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        // Boundary (a): between request parse and route dispatch.
1074        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        // Test-only injected slow downstream (issue #570 slice 2
1087        // integration test). Production builds set this to 0, so this
1088        // is a single relaxed atomic load on the hot path.
1089        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        // Boundary (b): between route dispatch and response write.
1095        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    /// Best-effort 503 emitted when the per-handler deadline expires
1108    /// at a coarse boundary. Writes are swallowed — the caller has
1109    /// already exceeded its budget, so we do not propagate write
1110    /// errors. Permit drop happens on the handler thread's normal
1111    /// exit path.
1112    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}