aegis-server 0.2.6

API server for Aegis database
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! Aegis Server Binary
//!
//! API server for Aegis database with REST endpoints for the dashboard.
//! Supports both HTTP and HTTPS (TLS) connections.
//!
//! @version 0.1.0
//! @author AutomataNexus Development Team

use aegis_server::backup::BackupManager;
use aegis_server::secrets::{self, SecretsProvider};
use aegis_server::{create_router, AppState, ClusterTlsConfig, ServerConfig};
use axum_server::tls_rustls::RustlsConfig;
use clap::Parser;
use std::net::SocketAddr;
use std::path::PathBuf;
use tokio::signal;

#[derive(Parser)]
#[command(name = "aegis-server")]
#[command(about = "Aegis Database API Server")]
struct Args {
    /// Host to bind to
    #[arg(short = 'H', long, default_value = "127.0.0.1")]
    host: String,

    /// Port to listen on
    #[arg(short, long, default_value = "9090")]
    port: u16,

    /// Data directory for persistence (enables disk storage)
    #[arg(short, long)]
    data_dir: Option<String>,

    /// Unique node ID (auto-generated if not provided)
    #[arg(long)]
    node_id: Option<String>,

    /// Node name for display (e.g., "AxonML", "NexusScribe")
    #[arg(long)]
    node_name: Option<String>,

    /// Comma-separated list of peer addresses to join (e.g., "127.0.0.1:9090,127.0.0.1:9091")
    #[arg(long)]
    peers: Option<String>,

    /// Cluster name
    #[arg(long, default_value = "aegis-cluster")]
    cluster: String,

    /// Enable TLS/HTTPS
    #[arg(long)]
    tls: bool,

    /// TLS certificate file path (PEM format)
    #[arg(long)]
    tls_cert: Option<String>,

    /// TLS private key file path (PEM format)
    #[arg(long)]
    tls_key: Option<String>,

    /// Enable TLS for cluster communication (uses same certs as server TLS by default)
    #[arg(long)]
    cluster_tls: bool,

    /// CA certificate for verifying cluster peer certificates (PEM format)
    #[arg(long)]
    cluster_ca_cert: Option<String>,

    /// Client certificate for cluster mTLS (PEM format, optional)
    #[arg(long)]
    cluster_client_cert: Option<String>,

    /// Client private key for cluster mTLS (PEM format, optional)
    #[arg(long)]
    cluster_client_key: Option<String>,

    /// Skip certificate verification for cluster TLS (INSECURE - only for testing)
    #[arg(long)]
    cluster_tls_insecure: bool,
}

#[tokio::main]
async fn main() {
    // Initialize tracing
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive(tracing::Level::INFO.into()),
        )
        .init();

    let args = Args::parse();

    // Production mode TLS requirement check
    // In production, TLS must be enabled unless explicitly overridden
    let is_production = std::env::var("AEGIS_PRODUCTION")
        .map(|v| v.eq_ignore_ascii_case("true") || v == "1")
        .unwrap_or(false);
    let allow_insecure = std::env::var("AEGIS_ALLOW_INSECURE")
        .map(|v| v.eq_ignore_ascii_case("true") || v == "1")
        .unwrap_or(false);

    if is_production && !args.tls && !allow_insecure {
        eprintln!();
        eprintln!("╔══════════════════════════════════════════════════════════════════════╗");
        eprintln!("║                    PRODUCTION SECURITY ERROR                         ║");
        eprintln!("╠══════════════════════════════════════════════════════════════════════╣");
        eprintln!("║  TLS is required in production mode but is not enabled.              ║");
        eprintln!("║                                                                      ║");
        eprintln!("║  To fix this, enable TLS with:                                       ║");
        eprintln!("║    --tls --tls-cert /path/to/cert.pem --tls-key /path/to/key.pem     ║");
        eprintln!("║                                                                      ║");
        eprintln!("║  Or set environment variables:                                       ║");
        eprintln!("║    AEGIS_TLS_CERT=/path/to/cert.pem                                  ║");
        eprintln!("║    AEGIS_TLS_KEY=/path/to/key.pem                                    ║");
        eprintln!("║                                                                      ║");
        eprintln!("║  To bypass this check (NOT RECOMMENDED), set:                        ║");
        eprintln!("║    AEGIS_ALLOW_INSECURE=true                                         ║");
        eprintln!("╚══════════════════════════════════════════════════════════════════════╝");
        eprintln!();
        std::process::exit(1);
    }

    if is_production && allow_insecure && !args.tls {
        tracing::warn!("╔══════════════════════════════════════════════════════════════════════╗");
        tracing::warn!("║  WARNING: Running production mode WITHOUT TLS (AEGIS_ALLOW_INSECURE) ║");
        tracing::warn!("║  This is a security risk! Enable TLS for production deployments.     ║");
        tracing::warn!("╚══════════════════════════════════════════════════════════════════════╝");
    }

    // Initialize built-in vault
    let vault_data_dir = args
        .data_dir
        .as_ref()
        .map(|d| std::path::PathBuf::from(d).join("vault"));
    let built_in_vault = std::sync::Arc::new(aegis_vault::AegisVault::new_auto(vault_data_dir));
    tracing::info!(
        "Built-in vault initialized (sealed: {})",
        built_in_vault.is_sealed()
    );

    // Initialize secrets manager (built-in vault → external Vault → env vars)
    let secrets_manager = secrets::init_secrets_manager(Some(built_in_vault)).await;

    // Parse peer addresses
    let peers: Vec<String> = args
        .peers
        .map(|p| {
            p.split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect()
        })
        .unwrap_or_default();

    // Build cluster TLS configuration if enabled
    let cluster_tls_config = if args.cluster_tls || args.tls {
        // If cluster_tls is explicitly enabled, or if server TLS is enabled (inherit by default)
        let enabled = args.cluster_tls || args.tls;
        Some(ClusterTlsConfig {
            enabled,
            ca_cert_path: args.cluster_ca_cert.clone(),
            client_cert_path: args
                .cluster_client_cert
                .clone()
                .or_else(|| args.tls_cert.clone()),
            client_key_path: args
                .cluster_client_key
                .clone()
                .or_else(|| args.tls_key.clone()),
            danger_accept_invalid_certs: args.cluster_tls_insecure,
        })
    } else {
        None
    };

    // Build server configuration
    let config = ServerConfig::new(&args.host, args.port)
        .with_data_dir(args.data_dir.clone())
        .with_node_id(args.node_id.clone())
        .with_node_name(args.node_name.clone())
        .with_cluster_name(args.cluster.clone())
        .with_peers(peers.clone())
        .with_cluster_tls(cluster_tls_config);

    let addr: SocketAddr = config.socket_addr();

    if let Some(ref data_dir) = args.data_dir {
        tracing::info!("Persistence enabled, data directory: {}", data_dir);
    } else {
        tracing::warn!(
            "No data directory specified, running in-memory only (data will be lost on restart)"
        );
    }

    if !peers.is_empty() {
        tracing::info!("Cluster mode enabled, peers: {:?}", peers);
        if config.cluster_tls_enabled() {
            tracing::info!("Cluster TLS enabled for inter-node communication");
            if let Some(ref cluster_tls) = config.cluster_tls {
                if cluster_tls.danger_accept_invalid_certs {
                    tracing::warn!("Cluster TLS certificate verification DISABLED (insecure)");
                }
                if cluster_tls.ca_cert_path.is_some() {
                    tracing::info!("  Using custom CA certificate for peer verification");
                }
                if cluster_tls.client_cert_path.is_some() {
                    tracing::info!("  mTLS enabled with client certificate");
                }
            }
        } else {
            tracing::warn!("Cluster TLS disabled - inter-node communication is unencrypted");
        }
    }

    tracing::info!("Starting Aegis Server on {}", addr);
    tracing::info!("Node ID: {}", config.node_id);
    if let Some(ref name) = config.node_name {
        tracing::info!("Node Name: {}", name);
    }

    let state = AppState::with_secrets(config, Some(&secrets_manager));

    // Warn loudly at startup if no admin user is configured
    if state.auth.list_users().is_empty() {
        tracing::warn!("==========================================================");
        tracing::warn!("SECURITY WARNING: No admin user configured!");
        tracing::warn!("All API endpoints are accessible without authentication.");
        tracing::warn!("Store credentials in the vault or set AEGIS_ADMIN_USERNAME");
        tracing::warn!("and AEGIS_ADMIN_PASSWORD environment variables.");
        tracing::warn!("==========================================================");
    }

    let state_for_shutdown = state.clone();
    let app = create_router(state.clone());

    // Start periodic save task if persistence is enabled
    let state_for_save = state_for_shutdown.clone();
    if args.data_dir.is_some() {
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(30));
            loop {
                interval.tick().await;
                if let Err(e) = state_for_save.save_to_disk() {
                    tracing::error!("Failed to save data: {}", e);
                }
            }
        });
    }

    // Start automatic backup scheduler if persistence is enabled
    if args.data_dir.is_some() {
        let state_for_backup = state_for_shutdown.clone();
        tokio::spawn(async move {
            // Wait 60 seconds before first check
            tokio::time::sleep(tokio::time::Duration::from_secs(60)).await;

            // Check every hour if auto-backups are enabled
            let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(3600));

            loop {
                interval.tick().await;

                let settings = state_for_backup.settings.read().await;
                if !settings.auto_backups_enabled {
                    continue;
                }
                let retention_days = settings.retention_days;
                drop(settings);

                // Flush all in-memory state to disk for a consistent backup checkpoint
                tracing::info!("Creating backup checkpoint...");
                if let Err(e) = state_for_backup.save_to_disk() {
                    tracing::warn!("Pre-backup save failed: {}", e);
                    continue; // Skip backup if save fails
                }

                if let Some(ref dir) = state_for_backup.config.data_dir {
                    let data_dir = std::path::PathBuf::from(dir);
                    let manager = BackupManager::new(data_dir);

                    match manager.create_backup(true, Some("auto-scheduler"), false, None) {
                        Ok(info) => {
                            tracing::info!(
                                "Auto-backup created: {} ({} files)",
                                info.id,
                                info.files_count
                            );

                            // Clean up old backups beyond retention count
                            if let Ok(mut backups) = manager.list_backups() {
                                // Keep only the newest N backups (retention_days worth of hourly backups)
                                let max_backups = (retention_days as usize) * 24;
                                if backups.len() > max_backups {
                                    // Sort by timestamp descending
                                    backups.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
                                    for old in &backups[max_backups..] {
                                        if let Err(e) = manager.delete_backup(&old.id) {
                                            tracing::warn!(
                                                "Failed to delete old backup {}: {}",
                                                old.id,
                                                e
                                            );
                                        } else {
                                            tracing::info!("Deleted expired backup: {}", old.id);
                                        }
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            tracing::error!("Auto-backup failed: {}", e);
                        }
                    }
                }
            }
        });
    }

    // Start peer discovery and heartbeat task
    let state_for_cluster = state_for_shutdown.clone();
    let peers_for_task = peers.clone();
    if !peers_for_task.is_empty() {
        tokio::spawn(async move {
            // Initial delay to let server start
            tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;

            // Join peers on startup
            for peer_addr in &peers_for_task {
                join_peer(&state_for_cluster, peer_addr).await;
            }

            // Periodic heartbeat loop
            let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(5));
            loop {
                interval.tick().await;
                send_heartbeats(&state_for_cluster).await;
            }
        });
    }

    // Determine TLS configuration
    let tls_config = if args.tls {
        // Try command line args first, then environment/Vault
        let cert_path = match args
            .tls_cert
            .or_else(|| secrets_manager.get(secrets::keys::TLS_CERT_PATH))
        {
            Some(p) => p,
            None => {
                tracing::error!("TLS enabled but no certificate path provided. Use --tls-cert or set AEGIS_TLS_CERT");
                std::process::exit(1);
            }
        };

        let key_path = match args
            .tls_key
            .or_else(|| secrets_manager.get(secrets::keys::TLS_KEY_PATH))
        {
            Some(p) => p,
            None => {
                tracing::error!(
                    "TLS enabled but no key path provided. Use --tls-key or set AEGIS_TLS_KEY"
                );
                std::process::exit(1);
            }
        };

        // Verify files exist
        if !PathBuf::from(&cert_path).exists() {
            tracing::error!("TLS certificate file not found: {}", cert_path);
            std::process::exit(1);
        }
        if !PathBuf::from(&key_path).exists() {
            tracing::error!("TLS key file not found: {}", key_path);
            std::process::exit(1);
        }

        Some((cert_path, key_path))
    } else {
        None
    };

    // Run server with or without TLS
    if let Some((cert_path, key_path)) = tls_config {
        // TLS/HTTPS mode
        tracing::info!("TLS enabled, loading certificates...");
        tracing::info!("  Certificate: {}", cert_path);
        tracing::info!("  Private key: {}", key_path);

        let rustls_config = RustlsConfig::from_pem_file(&cert_path, &key_path)
            .await
            .expect("Failed to load TLS configuration");

        tracing::info!("Aegis Server listening on https://{}", addr);
        tracing::info!("Dashboard API ready at https://{}/api/v1", addr);

        let handle = axum_server::Handle::new();
        let handle_for_shutdown = handle.clone();

        // Spawn shutdown handler
        tokio::spawn(async move {
            shutdown_signal(state_for_shutdown).await;
            handle_for_shutdown.graceful_shutdown(Some(std::time::Duration::from_secs(30)));
        });

        axum_server::bind_rustls(addr, rustls_config)
            .handle(handle)
            .serve(app.into_make_service())
            .await
            .expect("Server error");
    } else {
        // HTTP mode
        let listener = tokio::net::TcpListener::bind(addr)
            .await
            .expect("Failed to bind to address");

        tracing::info!("Aegis Server listening on http://{}", addr);
        tracing::info!("Dashboard API ready at http://{}/api/v1", addr);

        axum::serve(listener, app)
            .with_graceful_shutdown(shutdown_signal(state_for_shutdown))
            .await
            .expect("Server error");
    }
}

/// Build a reqwest client configured for cluster communication.
/// Supports TLS with optional CA certificate and client certificates for mTLS.
fn build_cluster_client(config: &ClusterTlsConfig) -> Result<reqwest::Client, reqwest::Error> {
    let mut builder = reqwest::Client::builder();

    // Handle certificate verification
    if config.danger_accept_invalid_certs {
        builder = builder.danger_accept_invalid_certs(true);
    }

    // Add custom CA certificate if provided
    if let Some(ref ca_path) = config.ca_cert_path {
        if let Ok(ca_cert_pem) = std::fs::read(ca_path) {
            if let Ok(ca_cert) = reqwest::Certificate::from_pem(&ca_cert_pem) {
                builder = builder.add_root_certificate(ca_cert);
                tracing::debug!("Added custom CA certificate from {}", ca_path);
            } else {
                tracing::warn!("Failed to parse CA certificate from {}", ca_path);
            }
        } else {
            tracing::warn!("Failed to read CA certificate file: {}", ca_path);
        }
    }

    // Add client certificate for mTLS if provided
    if let (Some(ref cert_path), Some(ref key_path)) =
        (&config.client_cert_path, &config.client_key_path)
    {
        if let (Ok(cert_pem), Ok(key_pem)) = (std::fs::read(cert_path), std::fs::read(key_path)) {
            // Combine cert and key into a single PEM for reqwest Identity
            let mut combined_pem = cert_pem;
            combined_pem.extend_from_slice(b"\n");
            combined_pem.extend_from_slice(&key_pem);

            if let Ok(identity) = reqwest::Identity::from_pem(&combined_pem) {
                builder = builder.identity(identity);
                tracing::debug!("Added client certificate for mTLS");
            } else {
                tracing::warn!("Failed to parse client certificate/key for mTLS");
            }
        } else {
            tracing::warn!("Failed to read client certificate or key files");
        }
    }

    builder.build()
}

/// Get the URL scheme (http or https) based on cluster TLS configuration.
fn get_cluster_scheme(config: &aegis_server::ServerConfig) -> &'static str {
    if config.cluster_tls_enabled() {
        "https"
    } else {
        "http"
    }
}

/// Join a peer node in the cluster.
async fn join_peer(state: &AppState, peer_addr: &str) {
    let self_info = state.admin.get_self_info();
    let scheme = get_cluster_scheme(&state.config);
    let url = format!("{}://{}/api/v1/cluster/join", scheme, peer_addr);

    // Build the appropriate client based on TLS configuration
    let client = if let Some(ref cluster_tls) = state.config.cluster_tls {
        if cluster_tls.enabled {
            match build_cluster_client(cluster_tls) {
                Ok(c) => c,
                Err(e) => {
                    tracing::error!(
                        "Failed to build TLS client for cluster communication: {}",
                        e
                    );
                    return;
                }
            }
        } else {
            reqwest::Client::new()
        }
    } else {
        reqwest::Client::new()
    };

    let body = serde_json::json!({
        "node_id": self_info.id,
        "node_name": self_info.name,
        "address": self_info.address,
    });

    match client
        .post(&url)
        .json(&body)
        .timeout(std::time::Duration::from_secs(5))
        .send()
        .await
    {
        Ok(response) => {
            if response.status().is_success() {
                if let Ok(data) = response.json::<serde_json::Value>().await {
                    tracing::info!("Successfully joined peer at {} ({})", peer_addr, scheme);
                    // Register any peers returned by the join response
                    if let Some(peers) = data.get("peers").and_then(|p| p.as_array()) {
                        for peer in peers {
                            if let (Some(id), Some(addr)) = (
                                peer.get("id").and_then(|v| v.as_str()),
                                peer.get("address").and_then(|v| v.as_str()),
                            ) {
                                if addr != self_info.address {
                                    let name = peer
                                        .get("name")
                                        .and_then(|v| v.as_str())
                                        .map(|s| s.to_string());
                                    state.admin.register_peer(aegis_server::admin::PeerNode {
                                        id: id.to_string(),
                                        name,
                                        address: addr.to_string(),
                                        status: aegis_server::admin::NodeStatus::Online,
                                        role: aegis_server::admin::NodeRole::Follower,
                                        last_seen: std::time::SystemTime::now()
                                            .duration_since(std::time::UNIX_EPOCH)
                                            .unwrap_or_default()
                                            .as_millis()
                                            as u64,
                                        version: env!("CARGO_PKG_VERSION").to_string(),
                                        uptime_seconds: 0,
                                        metrics: None,
                                    });
                                    state.admin.add_peer_address(addr.to_string());
                                }
                            }
                        }
                    }
                }
            } else {
                tracing::warn!(
                    "Failed to join peer at {}: HTTP {}",
                    peer_addr,
                    response.status()
                );
            }
        }
        Err(e) => {
            tracing::warn!("Failed to connect to peer at {}: {}", peer_addr, e);
        }
    }
}

/// Send heartbeats to all known peers.
async fn send_heartbeats(state: &AppState) {
    let self_info = state.admin.get_self_info();
    let peers = state.admin.get_peers();
    let scheme = get_cluster_scheme(&state.config);

    // Build the appropriate client based on TLS configuration
    let client = if let Some(ref cluster_tls) = state.config.cluster_tls {
        if cluster_tls.enabled {
            match build_cluster_client(cluster_tls) {
                Ok(c) => c,
                Err(e) => {
                    tracing::error!("Failed to build TLS client for heartbeats: {}", e);
                    return;
                }
            }
        } else {
            reqwest::Client::new()
        }
    } else {
        reqwest::Client::new()
    };

    for peer in peers {
        let url = format!("{}://{}/api/v1/cluster/heartbeat", scheme, peer.address);
        let body = serde_json::json!({
            "node_id": self_info.id,
            "node_name": self_info.name,
            "address": self_info.address,
            "uptime_seconds": self_info.uptime_seconds,
            "metrics": self_info.metrics,
        });

        match client
            .post(&url)
            .json(&body)
            .timeout(std::time::Duration::from_secs(3))
            .send()
            .await
        {
            Ok(response) => {
                if !response.status().is_success() {
                    tracing::debug!(
                        "Heartbeat to {} failed: HTTP {}",
                        peer.address,
                        response.status()
                    );
                    state.admin.mark_peer_offline(&peer.id);
                }
            }
            Err(_) => {
                tracing::debug!("Heartbeat to {} failed: connection error", peer.address);
                state.admin.mark_peer_offline(&peer.id);
            }
        }
    }

    // Also try to discover new peers from configured addresses
    for addr in state.admin.peer_addresses() {
        let existing = state.admin.get_peers();
        if !existing.iter().any(|p| p.address == addr) {
            join_peer(state, &addr).await;
        }
    }
}

async fn shutdown_signal(state: AppState) {
    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("Failed to install Ctrl+C handler");
    };

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

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

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

    tracing::info!("Shutdown signal received, saving data...");
    if let Err(e) = state.save_to_disk() {
        tracing::error!("Failed to save data on shutdown: {}", e);
    } else {
        tracing::info!("Data saved successfully");
    }
}