Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Graceful Shutdown #233

Merged
merged 2 commits into from
Aug 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ Then your project directory has `wrangler.toml`, `package.json` and a Rust libra

See README of the [template](https://github.com/ohkami-rs/ohkami-templates/tree/main/worker) for details.

### `"graceful"`:Graceful Shutdown

Automatically catch Ctrl-C ( SIGINT ) and perform graceful shutdown.\
Currently, only supported on `rt_tokio`.

### `"sse"`:Server-Sent Events

Ohkami responds with HTTP/1.1 `Transfer-Encoding: chunked`.\
Expand Down
2 changes: 2 additions & 0 deletions Taskfile.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ tasks:
cmds:
- cargo test --lib --features rt_tokio,DEBUG,{{.MAYBE_NIGHTLY}}
- cargo test --lib --features rt_tokio,DEBUG,sse,ws,{{.MAYBE_NIGHTLY}}
- cargo test --lib --features rt_tokio,DEBUG,graceful,{{.MAYBE_NIGHTLY}}

test_rt_async-std:
vars:
Expand Down Expand Up @@ -101,6 +102,7 @@ tasks:
- cargo check --lib --features rt_tokio,{{.MAYBE_NIGHTLY}}
- cargo check --lib --features rt_tokio,sse,{{.MAYBE_NIGHTLY}}
- cargo check --lib --features rt_tokio,sse,ws,{{.MAYBE_NIGHTLY}}
- cargo check --lib --features rt_tokio,graceful,{{.MAYBE_NIGHTLY}}

check_rt_async-std:
vars:
Expand Down
1 change: 1 addition & 0 deletions ohkami/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ nightly = []
testing = []
sse = ["ohkami_lib/stream"]
ws = ["dep:sha1"]
graceful = ["rt_tokio", "tokio/signal", "tokio/macros"]

##### DEBUG #####
DEBUG = [
Expand Down
17 changes: 12 additions & 5 deletions ohkami/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,23 @@
all(feature="rt_tokio", feature="rt_async-std"),
all(feature="rt_async-std", feature="rt_worker"),
all(feature="rt_worker", feature="rt_tokio"),
))] compile_error!("
Can't activate multiple `rt_*` features!
");
))] compile_error! {"
Can't activate multiple `rt_*` features at once!
"}

#[cfg(any(
all(feature="graceful", not(feature="rt_tokio")),
))] compile_error! {"
In current versoin, `graceful` feature is only supported on `rt_tokio`.
Please wait for future development for other runtimes...
"}

#[cfg(not(feature="DEBUG"))] const _: () = {
#[cfg(all(feature="rt_worker", not(target_arch="wasm32")))]
compile_error!("
compile_error! {"
`rt_worker` must be activated on `wasm32` target!
(We recommend to touch `.cargo/config.toml`: `[build] target = \"wasm32-unknown-unknown\"`)
");
"}
};


Expand Down
35 changes: 34 additions & 1 deletion ohkami/src/ohkami/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,40 @@ impl Ohkami {
Err(e) => panic!("Failed to bind TCP listener: {e}"),
};

#[cfg(feature="rt_tokio")] {
#[cfg(all(feature="rt_tokio", feature="graceful"))] {
let ctrl_c = tokio::signal::ctrl_c();
let (ctrl_c_tx, ctrl_c_rx) = tokio::sync::watch::channel(());
__rt__::task::spawn(async move {
ctrl_c.await.expect("something was unexpected around Ctrl-C");
drop(ctrl_c_rx);
});

let (close_tx, close_rx) = tokio::sync::watch::channel(());
loop {
tokio::select! {
accept = listener.accept() => {
crate::DEBUG!("Accepted {accept:#?}");
let Ok((connection, _)) = accept else {continue};
let session = Session::new(router.clone(), connection);
let close_rx = close_rx.clone();
__rt__::task::spawn(async {
session.manage().await;
drop(close_rx)
});
},
_ = ctrl_c_tx.closed() => {
crate::DEBUG!("Recieved Ctrl-C, trying graceful shutdown");

crate::DEBUG!("Waiting {} session(s) to finish...", close_tx.receiver_count());
drop(close_rx);
close_tx.closed().await;

break
}
}
}
}
#[cfg(all(feature="rt_tokio", not(feature="graceful")))] {
loop {
let Ok((connection, _)) = listener.accept().await else {continue};

Expand Down
15 changes: 1 addition & 14 deletions ohkami/src/ohkami/router/radix.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::request::Path;
use crate::{Method, Request, Response};
use crate::fangs::{FangProcCaller, BoxedFPC, Handler};
use crate::fangs::{FangProcCaller, BoxedFPC};
use ohkami_lib::Slice;
use std::fmt::Write as _;

Expand Down Expand Up @@ -30,21 +30,8 @@ pub(super) struct Node {
}
}

enum HandlerMarker { None, Some }
impl From<Option<&Handler>> for HandlerMarker {
fn from(h: Option<&Handler>) -> Self {
match h {Some(_) => Self::Some, None => Self::None}
}
}
impl std::fmt::Debug for HandlerMarker {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {Self::Some => f.write_char('@'), Self::None => f.write_str("None")}
}
}

f.debug_struct("")
.field("patterns", &PatternsMarker(self.patterns))
// .field("proc", &HandlerMarker::from(self.handler.as_ref()))
.field("children", &self.children)
.finish()
}
Expand Down
16 changes: 0 additions & 16 deletions ohkami_lib/src/serde_urlencoded/_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,29 +16,13 @@ enum Gender {
Other,
}

#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum Difficulty {
Low,
Middle,
High,
Ultimate,
}


#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct User<'s> {
name: Cow<'s, str>,
age: Option<Age>,
gender: Option<Gender>,
}

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Problem<'s> {
title: Cow<'s, str>,
content: String,
difficulty: Option<Difficulty>,
}

#[derive(Deserialize, PartialEq, Debug)]
struct URLRequest<'req> {
url: Cow<'req, str>,
Expand Down
Loading