Skip to content

Commit

Permalink
feat: shutdown handler route
Browse files Browse the repository at this point in the history
  • Loading branch information
frectonz committed Aug 7, 2024
1 parent ef53010 commit 7087474
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 10 deletions.
41 changes: 34 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use async_trait::async_trait;
use clap::{Parser, Subcommand};
use tokio::sync::mpsc;
use warp::Filter;

const ROWS_PER_PAGE: i32 = 50;
Expand Down Expand Up @@ -136,7 +137,9 @@ async fn main() -> color_eyre::Result<()> {
.allow_methods(vec!["GET", "POST", "DELETE"])
.allow_headers(vec!["Content-Length", "Content-Type"]);

let api = warp::path("api").and(handlers::routes(db));
let (shutdown_tx, mut shutdown_rx) = mpsc::channel(1);

let api = warp::path("api").and(handlers::routes(db, shutdown_tx));
let homepage = statics::homepage(index_html.clone());
let statics = statics::routes();

Expand All @@ -153,13 +156,17 @@ async fn main() -> color_eyre::Result<()> {

let address = args.address.parse::<std::net::SocketAddr>()?;
let (_, fut) = warp::serve(routes).bind_with_graceful_shutdown(address, async move {
tokio::signal::ctrl_c()
.await
.expect("failed to listen to shutdown signal");
tokio::select! {
_ = tokio::signal::ctrl_c() => {
println!();
}
_ = shutdown_rx.recv() => {
tracing::info!("received shutdown signal")
}
}
});

fut.await;
println!();
tracing::info!("shutting down...");

Ok(())
Expand Down Expand Up @@ -2932,6 +2939,7 @@ mod responses {

mod handlers {
use serde::Deserialize;
use tokio::sync::mpsc;
use warp::Filter;

use crate::{rejections, responses::Version, Database};
Expand All @@ -2945,6 +2953,7 @@ mod handlers {

pub fn routes(
db: impl Database,
shutdown_signal: mpsc::Sender<()>,
) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {
let overview = warp::path::end()
.and(warp::get())
Expand All @@ -2969,8 +2978,18 @@ mod handlers {
.and(warp::body::json::<QueryBody>())
.and_then(query);
let version = warp::get().and(warp::path!("version")).and_then(version);

overview.or(tables).or(table).or(query).or(data).or(version)
let shutdown = warp::post()
.and(warp::path!("shutdown"))
.and(with_state(&shutdown_signal))
.and_then(shutdown);

overview
.or(tables)
.or(table)
.or(query)
.or(data)
.or(version)
.or(shutdown)
}

#[derive(Deserialize)]
Expand Down Expand Up @@ -3040,6 +3059,14 @@ mod handlers {

Ok(warp::reply::json(&version))
}

async fn shutdown(
shutdown_signal: mpsc::Sender<()>,
) -> Result<impl warp::Reply, warp::Rejection> {
let res = shutdown_signal.send(()).await;
tracing::info!("sent shutdown signal: {res:?}");
Ok("")
}
}

mod rejections {
Expand Down
3 changes: 3 additions & 0 deletions ui/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,6 @@ export const fetchQuery = (value: string) =>
body: JSON.stringify({ query: value }),
});
export const fetchVersion = () => $fetch(version, `${BASE_URL}/version`);

export const sendShutdown = () =>
fetch(`${BASE_URL}/shutdown`, { method: "POST" });
5 changes: 2 additions & 3 deletions ui/src/routes/__root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useQuery } from "@tanstack/react-query";
import { Link, Outlet, createRootRoute } from "@tanstack/react-router";

import { cn } from "@/lib/utils";
import { fetchVersion } from "@/api";
import { fetchVersion, sendShutdown } from "@/api";
import { setTheme, useTheme } from "@/provider/theme.provider";

import {
Expand All @@ -26,7 +26,6 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";

const TanStackRouterDevtools = import.meta.env.PROD
? () => null // Render nothing in production
Expand Down Expand Up @@ -156,7 +155,7 @@ function Shutdown() {
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
console.log("shutdown");
sendShutdown();
}}
>
Shutdown
Expand Down

0 comments on commit 7087474

Please sign in to comment.