Skip to content

Commit

Permalink
feat: Run regular PRAGMA optimize calls
Browse files Browse the repository at this point in the history
This is recommended to be run regularly to improve query performance.

See https://www.sqlite.org/pragma.html#pragma_optimize for more details.
  • Loading branch information
jorgenpt committed Sep 3, 2024
1 parent c68e49e commit e72b80d
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions src/bin/rugs_metadata_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use axum::{
};
use base64::prelude::*;
use clap::Parser;
use futures::pin_mut;
use sqlx::SqlitePool;
use tokio::sync::RwLock;
use tower::ServiceBuilder;
Expand All @@ -20,6 +21,9 @@ use rugs::handlers::*;
#[cfg(debug_assertions)]
use rugs::middleware::print_request_response;

// Run `PRAGMA optimize` every 12 hours (https://www.sqlite.org/pragma.html#pragma_optimize)
const OPTIMIZE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60 * 60 * 12);

/// A simple authenticated metadata server for UGS
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
Expand Down Expand Up @@ -126,14 +130,35 @@ async fn main() -> Result<()> {
.await
.with_context(|| format!("Could not open database at {}", args.database))?;

let optimize_pool = pool.clone();
// Per the sqlite docs, this is recommended to be run on startup (https://www.sqlite.org/pragma.html#pragma_optimize)
sqlx::query("PRAGMA optimize=0x10002")
.execute(&optimize_pool)
.await?;

let addr = SocketAddr::from(([0, 0, 0, 0], config.http_port));
info!("listening on {}", addr);
axum::Server::bind(&addr)

let server_future = axum::Server::bind(&addr)
.serve(app(config, pool).into_make_service())
.with_graceful_shutdown(async {
exit_rx.await.ok();
})
.await?;
});

pin_mut!(server_future);
loop {
let delay_result = tokio::time::timeout(OPTIMIZE_INTERVAL, &mut server_future).await;
match delay_result {
Err(_) => {
info!("running regular `PRAGMA optimize`");
// Per the sqlite docs, this is recommended to be run regularly for long-running apps (https://www.sqlite.org/pragma.html#pragma_optimize)
sqlx::query("PRAGMA optimize")
.execute(&optimize_pool)
.await?;
}
Ok(server_result) => break server_result?,
}
}

Ok(())
}
Expand Down

0 comments on commit e72b80d

Please sign in to comment.