Skip to content
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
2 changes: 1 addition & 1 deletion .github/workflows/deploy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ jobs:
steps:
- uses: actions/checkout@v6
- uses: Swatinem/rust-cache@v2
- run: cargo install wasm-bindgen-cli
- run: cargo install wasm-bindgen-cli --version 0.2.120
- run: rustup target add wasm32-unknown-unknown
- run: cargo run -p definy-build
- run: cargo build -p definy-server --release
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/pull_request.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
- run: cargo fmt --check
- uses: browser-actions/setup-chrome@v2
- uses: nanasess/setup-chromedriver@v2
- run: cargo install wasm-bindgen-cli
- run: cargo install wasm-bindgen-cli --version 0.2.120
- run: rustup target add wasm32-unknown-unknown
- run: cargo run -p definy-build
- run: cargo test
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ https://github.com/narumincho/definy/tree/prev2023
- [wasm-bindgen-cli](https://wasm-bindgen.github.io/wasm-bindgen/)

```sh
cargo install wasm-bindgen-cli
cargo install wasm-bindgen-cli --version 0.2.120
```

- [PostgreSQL 17](https://www.postgresql.org/download/)
Expand Down
69 changes: 29 additions & 40 deletions definy-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ mod event;

use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;

use http_body_util::Full;
use hyper::body::Bytes;
Expand All @@ -27,42 +26,6 @@ async fn main() -> Result<(), anyhow::Error> {
pool: Arc::new(RwLock::new(None)),
};

let state_for_retry = state.clone();
tokio::spawn(async move {
loop {
let current_pool = state_for_retry.pool.read().await.clone();

match current_pool {
Some(pool) => {
if let Err(error) = sqlx::query("select 1").execute(&pool).await {
eprintln!(
"Database health check failed. Switching to reconnect mode... {:?}",
error
);
let mut guard = state_for_retry.pool.write().await;
*guard = None;
}
}
None => match db::init_db().await {
Ok(pool) => {
{
let mut guard = state_for_retry.pool.write().await;
*guard = Some(pool);
}
println!("Database is available. API requests will use the database.");
}
Err(error) => {
eprintln!(
"Failed to connect to database. Retrying in 5 seconds... {:?}",
error
);
}
},
}
tokio::time::sleep(Duration::from_secs(5)).await;
}
});

let addr = SocketAddr::from((
std::net::IpAddr::V6(match std::env::var("FLY_APP_NAME") {
Ok(_) => std::net::Ipv6Addr::UNSPECIFIED,
Expand Down Expand Up @@ -141,7 +104,7 @@ async fn handler(
let language_resolution =
definy_ui::language::resolve_language(uri.query(), accept_language);
let language_fallback_notice = language_resolution.fallback_notice();
let pool = state.pool.read().await.clone();
let pool = ensure_pool(&state).await;
return match pool {
Some(pool) => {
handle_html(
Expand Down Expand Up @@ -170,7 +133,7 @@ async fn handler(
.header("Cache-Control", "public, max-age=31536000, immutable")
.body(Full::new(Bytes::from_static(ICON_CONTENT))),
"events" => {
let pool = state.pool.read().await.clone();
let pool = ensure_pool(&state).await;
match pool {
Some(pool) => event::handle_events(request, address, &pool).await,
None => db_unavailable_response(false),
Expand All @@ -179,7 +142,7 @@ async fn handler(
path => {
if let Some(event_binary_hash_hex) = path.strip_prefix("events/") {
let event_binary_hash_hex = event_binary_hash_hex.to_string();
let pool = state.pool.read().await.clone();
let pool = ensure_pool(&state).await;
match pool {
Some(pool) => {
event::handle_event_get(request, pool, &event_binary_hash_hex).await
Expand All @@ -196,6 +159,32 @@ async fn handler(
}
}

async fn ensure_pool(state: &AppState) -> Option<sqlx::postgres::PgPool> {
if let Some(pool) = state.pool.read().await.clone() {
return Some(pool);
}

match db::init_db().await {
Ok(pool) => {
let mut guard = state.pool.write().await;
if let Some(existing_pool) = guard.clone() {
return Some(existing_pool);
}
*guard = Some(pool.clone());
drop(guard);
println!("Database is available. API requests will use the database.");
Some(pool)
}
Err(error) => {
eprintln!(
"Failed to connect to database while handling request: {:?}",
error
);
None
}
}
}

fn db_unavailable_response(wants_html: bool) -> Result<Response<Full<Bytes>>, hyper::http::Error> {
if wants_html {
return Response::builder()
Expand Down
2 changes: 1 addition & 1 deletion definy-ui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ pub fn render(
Title::new()
.children([text(page_title::document_title_text(state))])
.into_node(),
Meta::new("viewport", "width=device-width,initial-scale=1.0"),
Meta::node("viewport", "width=device-width,initial-scale=1.0"),
Link::new()
.rel("icon")
.href(include_str!("../../web-distribution/icon.png.sha256"))
Expand Down
2 changes: 1 addition & 1 deletion narumincho-vdom/src/meta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub struct Meta {

impl Meta {
/// https://developer.mozilla.org/ja/docs/Web/HTML/Reference/Elements/meta
pub fn new<State>(name: &str, content: &str) -> node::Node<State> {
pub fn node<State>(name: &str, content: &str) -> node::Node<State> {
node::Node::Element(node::Element {
element_name: "meta".to_string(),
styles: crate::style::Style::new(),
Expand Down