dbrest-core 0.8.6

Database-agnostic core for the dbrest REST API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! HTTP server setup and lifecycle
//!
//! Creates the main API server and the admin server, wires up graceful
//! shutdown, and starts the NOTIFY listener.
//!
//! # Startup Sequence
//!
//! 1. Create database backend (connect, query version).
//! 2. Create `AppState`.
//! 3. Load schema cache.
//! 4. Start admin server (separate port).
//! 5. Start NOTIFY listener (background task).
//! 6. Start main API server.
//!
//! # Graceful Shutdown
//!
//! Listens for `SIGTERM` and `Ctrl+C`. On receipt, stops accepting new
//! connections and drains in-flight requests before exiting.

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;

use hyper_util::rt::{TokioExecutor, TokioIo};
use hyper_util::server::conn::auto::Builder;
use hyper_util::service::TowerToHyperService;
use tokio::net::TcpListener;

use crate::backend::{DatabaseBackend, DbVersion, SqlDialect};
use crate::config::AppConfig;
use crate::error::Error;

use super::admin::create_admin_router;
use super::router::create_router;
use super::state::AppState;

/// Start the dbrest server with a pre-constructed backend and dialect.
///
/// This is the main entry point for the application. It initializes all
/// components and starts serving HTTP requests.
pub async fn start_server(_config: AppConfig) -> Result<(), Error> {
    // This function is kept as a convenience that will be called from the
    // binary crate after constructing the backend. Since dbrest-core cannot
    // create PgBackend directly (it lives in dbrest-postgres), the binary
    // crate should use `start_server_with_backend` instead.
    //
    // For backwards compatibility during migration, this returns an error
    // guiding callers to use the correct function.
    Err(Error::Internal(
        "start_server() cannot create a database backend from dbrest-core. \
         Use start_server_with_backend() instead."
            .to_string(),
    ))
}

/// Start the dbrest server with an already-connected backend.
///
/// The caller (typically the root binary crate) is responsible for creating
/// the database backend and querying its version.
pub async fn start_server_with_backend(
    db: Arc<dyn DatabaseBackend>,
    dialect: Arc<dyn SqlDialect>,
    db_version: DbVersion,
    config: AppConfig,
) -> Result<(), Error> {
    let state = AppState::new_with_backend(db.clone(), dialect, config.clone(), db_version);

    // 4. Load schema cache
    tracing::info!("Loading schema cache…");
    state.reload_schema_cache().await?;

    // 5. Build routers
    let main_router = create_router(state.clone());
    let admin_router = create_admin_router(state.clone());

    // 6. Cancellation channel for background tasks
    let (cancel_tx, cancel_rx) = tokio::sync::watch::channel(false);

    // 7. Start NOTIFY listener
    if config.db_channel_enabled {
        let listener_state = state.clone();
        let listener_db = db.clone();
        let channel = config.db_channel.clone();
        tokio::spawn(async move {
            start_notify_listener(listener_db, listener_state, &channel, cancel_rx).await;
        });
    }

    // 8. Start admin server (if configured)
    if let Some(admin_port) = config.admin_server_port {
        let admin_ip = parse_address(&config.admin_server_host)?;
        let admin_addr = SocketAddr::new(admin_ip, admin_port);
        let admin_listener = TcpListener::bind(admin_addr)
            .await
            .map_err(|e| Error::Internal(format!("Failed to bind admin server: {}", e)))?;

        tracing::info!(addr = %admin_addr, "Admin server listening");

        tokio::spawn(async move {
            loop {
                let (stream, _addr) = match admin_listener.accept().await {
                    Ok(v) => v,
                    Err(e) => {
                        tracing::warn!(error = %e, "Admin TCP accept error");
                        continue;
                    }
                };

                let svc = admin_router.clone();
                tokio::spawn(async move {
                    let io = TokioIo::new(stream);
                    let hyper_svc = TowerToHyperService::new(svc);
                    let conn = Builder::new(TokioExecutor::new());
                    if let Err(e) = conn.serve_connection_with_upgrades(io, hyper_svc).await {
                        tracing::debug!(error = %e, "Admin connection error");
                    }
                });
            }
        });
    }

    // 9. Start main server — Unix socket or TCP
    #[cfg(unix)]
    if let Some(ref socket_path) = config.server_unix_socket {
        serve_unix_socket(main_router, socket_path, config.server_unix_socket_mode).await?;
    } else {
        serve_tcp(main_router, &config).await?;
    }

    #[cfg(not(unix))]
    {
        if config.server_unix_socket.is_some() {
            return Err(Error::InvalidConfig {
                message: "Unix sockets are not supported on this platform".to_string(),
            });
        }
        serve_tcp(main_router, &config).await?;
    }

    // 10. Cleanup
    tracing::info!("Shutting down…");
    let _ = cancel_tx.send(true);

    Ok(())
}

/// Background NOTIFY listener using the database backend.
///
/// Public variant for use by [`crate::app::builder::DbrestRouters::start_listener`].
pub async fn start_notify_listener_public(
    db: Arc<dyn DatabaseBackend>,
    state: AppState,
    channel: &str,
    cancel: tokio::sync::watch::Receiver<bool>,
) {
    start_notify_listener(db, state, channel, cancel).await;
}

/// Background NOTIFY listener (internal).
async fn start_notify_listener(
    db: Arc<dyn DatabaseBackend>,
    state: AppState,
    channel: &str,
    cancel: tokio::sync::watch::Receiver<bool>,
) {
    tracing::info!(channel = %channel, "Starting NOTIFY listener");

    loop {
        if *cancel.borrow() {
            tracing::info!("NOTIFY listener shutting down");
            return;
        }

        let state_clone = state.clone();
        let on_event: std::sync::Arc<dyn Fn(String) + Send + Sync> =
            std::sync::Arc::new(move |payload: String| {
                let state = state_clone.clone();
                tokio::spawn(async move {
                    if (payload.contains("schema") || payload.contains("reload"))
                        && let Err(e) = state.reload_schema_cache().await
                    {
                        tracing::error!(error = %e, "Failed to reload schema cache");
                    }
                    if payload.contains("config")
                        && let Err(e) = state.reload_config().await
                    {
                        tracing::error!(error = %e, "Failed to reload config");
                    }
                });
            });

        match db.start_listener(channel, cancel.clone(), on_event).await {
            Ok(()) => {
                tracing::info!("NOTIFY listener exiting normally");
                return;
            }
            Err(e) => {
                tracing::warn!(error = %e, "NOTIFY listener disconnected, reconnecting in 5s");
                tokio::time::sleep(std::time::Duration::from_secs(5)).await;
            }
        }
    }
}

/// Start the main server on a TCP socket with HTTP/1.1 and HTTP/2 support.
///
/// Uses `hyper_util::server::conn::auto::Builder` to auto-negotiate the
/// protocol. Browsers connecting over cleartext will use HTTP/1.1 with
/// upgrade to h2c; behind a TLS-terminating proxy the ALPN negotiation
/// selects HTTP/2 transparently.
async fn serve_tcp(router: axum::Router, config: &AppConfig) -> Result<(), Error> {
    let server_ip = parse_address(&config.server_host)?;
    let server_addr = SocketAddr::new(server_ip, config.server_port);
    let listener = TcpListener::bind(server_addr)
        .await
        .map_err(|e| Error::Internal(format!("Failed to bind main server: {}", e)))?;

    tracing::info!(addr = %server_addr, "dbrest server listening (HTTP/1.1 + h2c)");

    let shutdown = shutdown_signal();
    tokio::pin!(shutdown);

    loop {
        tokio::select! {
            result = listener.accept() => {
                let (stream, _addr) = match result {
                    Ok(v) => v,
                    Err(e) => {
                        tracing::warn!(error = %e, "TCP accept error");
                        continue;
                    }
                };

                let svc = router.clone();
                tokio::spawn(async move {
                    let io = TokioIo::new(stream);
                    let hyper_svc = TowerToHyperService::new(svc);
                    let conn = Builder::new(TokioExecutor::new());
                    if let Err(e) = conn.serve_connection_with_upgrades(io, hyper_svc).await {
                        tracing::debug!(error = %e, "Connection error");
                    }
                });
            }
            _ = &mut shutdown => {
                tracing::info!("Shutting down TCP server");
                break;
            }
        }
    }

    Ok(())
}

/// Start the main server on a Unix domain socket.
#[cfg(unix)]
async fn serve_unix_socket(
    router: axum::Router,
    socket_path: &std::path::Path,
    mode: u32,
) -> Result<(), Error> {
    use std::os::unix::fs::PermissionsExt;

    let _ = std::fs::remove_file(socket_path);

    let uds = tokio::net::UnixListener::bind(socket_path).map_err(|e| {
        Error::Internal(format!(
            "Failed to bind Unix socket '{}': {}",
            socket_path.display(),
            e
        ))
    })?;

    std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(mode)).map_err(|e| {
        Error::Internal(format!(
            "Failed to set socket permissions on '{}': {}",
            socket_path.display(),
            e
        ))
    })?;

    tracing::info!(path = %socket_path.display(), "dbrest server listening (Unix socket)");

    let shutdown = shutdown_signal();
    tokio::pin!(shutdown);

    loop {
        tokio::select! {
            result = uds.accept() => {
                let (stream, _addr) = match result {
                    Ok(v) => v,
                    Err(e) => {
                        tracing::warn!(error = %e, "Unix socket accept error");
                        continue;
                    }
                };

                let svc = router.clone();
                tokio::spawn(async move {
                    let io = TokioIo::new(stream);
                    let hyper_svc = TowerToHyperService::new(svc);
                    let conn = Builder::new(TokioExecutor::new());
                    if let Err(e) = conn.serve_connection_with_upgrades(io, hyper_svc).await {
                        tracing::debug!(error = %e, "Connection error");
                    }
                });
            }
            _ = &mut shutdown => {
                tracing::info!("Shutting down Unix socket server");
                break;
            }
        }
    }

    let _ = std::fs::remove_file(socket_path);
    Ok(())
}

/// Parse a host string into an `IpAddr`.
pub fn parse_address(host: &str) -> Result<IpAddr, Error> {
    match host {
        "!4" | "*" | "*4" => Ok(IpAddr::V4(Ipv4Addr::UNSPECIFIED)),
        "!6" | "*6" => Ok(IpAddr::V6(Ipv6Addr::UNSPECIFIED)),
        "localhost" => Ok(IpAddr::V4(Ipv4Addr::LOCALHOST)),
        other => other.parse::<IpAddr>().map_err(|_| Error::InvalidConfig {
            message: format!("Invalid server host: '{other}'"),
        }),
    }
}

/// Wait for a shutdown signal (SIGTERM or Ctrl+C).
async fn shutdown_signal() {
    let ctrl_c = async {
        tokio::signal::ctrl_c()
            .await
            .expect("Failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
            .expect("Failed to install SIGTERM handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_address_ipv4_any() {
        assert_eq!(
            parse_address("!4").unwrap(),
            IpAddr::V4(Ipv4Addr::UNSPECIFIED)
        );
    }

    #[test]
    fn test_parse_address_ipv6_any() {
        assert_eq!(
            parse_address("!6").unwrap(),
            IpAddr::V6(Ipv6Addr::UNSPECIFIED)
        );
    }

    #[test]
    fn test_parse_address_star() {
        assert_eq!(
            parse_address("*").unwrap(),
            IpAddr::V4(Ipv4Addr::UNSPECIFIED)
        );
    }

    #[test]
    fn test_parse_address_star4() {
        assert_eq!(
            parse_address("*4").unwrap(),
            IpAddr::V4(Ipv4Addr::UNSPECIFIED)
        );
    }

    #[test]
    fn test_parse_address_star6() {
        assert_eq!(
            parse_address("*6").unwrap(),
            IpAddr::V6(Ipv6Addr::UNSPECIFIED)
        );
    }

    #[test]
    fn test_parse_address_localhost() {
        assert_eq!(
            parse_address("localhost").unwrap(),
            IpAddr::V4(Ipv4Addr::LOCALHOST)
        );
    }

    #[test]
    fn test_parse_address_literal_ipv4() {
        let addr = parse_address("192.168.1.1").unwrap();
        assert_eq!(addr, IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)));
    }

    #[test]
    fn test_parse_address_literal_ipv6() {
        let addr = parse_address("::1").unwrap();
        assert_eq!(addr, IpAddr::V6(Ipv6Addr::LOCALHOST));
    }

    #[test]
    fn test_parse_address_invalid() {
        let err = parse_address("not-an-ip");
        assert!(err.is_err());
    }

    #[test]
    fn test_parse_address_loopback() {
        assert_eq!(
            parse_address("127.0.0.1").unwrap(),
            IpAddr::V4(Ipv4Addr::LOCALHOST)
        );
    }
}