|
| 1 | +# Graceful Shutdown |
| 2 | + |
| 3 | +Graceful shutdown allows your API to stop accepting new connections and finish processing active requests before terminating. This is crucial for avoiding data loss and ensuring a smooth deployment process. |
| 4 | + |
| 5 | +## Problem |
| 6 | + |
| 7 | +When you stop a server (e.g., via `CTRL+C` or `SIGTERM`), you want to ensure that: |
| 8 | +1. The server stops listening on the port. |
| 9 | +2. Ongoing requests are allowed to complete. |
| 10 | +3. Resources (database connections, background jobs) are cleaned up properly. |
| 11 | + |
| 12 | +## Solution |
| 13 | + |
| 14 | +RustAPI provides the `run_with_shutdown` method, which accepts a `Future`. When this future completes, the server initiates the shutdown process. |
| 15 | + |
| 16 | +### Basic Example (CTRL+C) |
| 17 | + |
| 18 | +```rust |
| 19 | +use rustapi_rs::prelude::*; |
| 20 | +use tokio::signal; |
| 21 | + |
| 22 | +#[tokio::main] |
| 23 | +async fn main() -> Result<()> { |
| 24 | + // 1. Define your application |
| 25 | + let app = RustApi::new().route("/", get(hello)); |
| 26 | + |
| 27 | + // 2. Define the shutdown signal |
| 28 | + let shutdown_signal = async { |
| 29 | + signal::ctrl_c() |
| 30 | + .await |
| 31 | + .expect("failed to install CTRL+C handler"); |
| 32 | + }; |
| 33 | + |
| 34 | + // 3. Run with shutdown |
| 35 | + println!("Server running... Press CTRL+C to stop."); |
| 36 | + app.run_with_shutdown("127.0.0.1:3000", shutdown_signal).await?; |
| 37 | + |
| 38 | + println!("Server stopped gracefully."); |
| 39 | + Ok(()) |
| 40 | +} |
| 41 | + |
| 42 | +async fn hello() -> &'static str { |
| 43 | + // Simulate some work |
| 44 | + tokio::time::sleep(std::time::Duration::from_secs(2)).await; |
| 45 | + "Hello, World!" |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +### Production Example (Unix Signals) |
| 50 | + |
| 51 | +In a production environment (like Kubernetes or Docker), you need to handle `SIGTERM` as well as `SIGINT`. |
| 52 | + |
| 53 | +```rust |
| 54 | +use rustapi_rs::prelude::*; |
| 55 | +use tokio::signal; |
| 56 | + |
| 57 | +#[tokio::main] |
| 58 | +async fn main() -> Result<()> { |
| 59 | + let app = RustApi::new().route("/", get(hello)); |
| 60 | + |
| 61 | + app.run_with_shutdown("0.0.0.0:3000", shutdown_signal()).await?; |
| 62 | + |
| 63 | + Ok(()) |
| 64 | +} |
| 65 | + |
| 66 | +async fn shutdown_signal() { |
| 67 | + let ctrl_c = async { |
| 68 | + signal::ctrl_c() |
| 69 | + .await |
| 70 | + .expect("failed to install Ctrl+C handler"); |
| 71 | + }; |
| 72 | + |
| 73 | + #[cfg(unix)] |
| 74 | + let terminate = async { |
| 75 | + signal::unix::signal(signal::unix::SignalKind::terminate()) |
| 76 | + .expect("failed to install signal handler") |
| 77 | + .recv() |
| 78 | + .await; |
| 79 | + }; |
| 80 | + |
| 81 | + #[cfg(not(unix))] |
| 82 | + let terminate = std::future::pending::<()>(); |
| 83 | + |
| 84 | + tokio::select! { |
| 85 | + _ = ctrl_c => println!("Received Ctrl+C"), |
| 86 | + _ = terminate => println!("Received SIGTERM"), |
| 87 | + } |
| 88 | +} |
| 89 | +``` |
| 90 | + |
| 91 | +## Discussion |
| 92 | + |
| 93 | +- **Active Requests**: RustAPI (via Hyper) will wait for active requests to complete. |
| 94 | +- **Timeout**: You might want to wrap the server execution in a timeout if you want to force shutdown after a certain period (though Hyper usually handles connection draining well). |
| 95 | +- **Background Tasks**: If you have spawned background tasks using `tokio::spawn`, they are detached and will be aborted when the runtime shuts down. For critical background work, consider using a dedicated job queue (like `rustapi-jobs`) or a `CancellationToken` to coordinate shutdown. |
0 commit comments