feat: with basic server
All checks were successful
continuous-integration/drone/push Build is passing

Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
2024-05-11 15:50:24 +02:00
parent 7d268e73f0
commit 6a147ba0d2
15 changed files with 280 additions and 125 deletions

View File

@@ -0,0 +1,28 @@
[package]
name = "hyperlog-server"
version = "0.1.0"
edition = "2021"
[dependencies]
hyperlog-core.workspace = true
anyhow.workspace = true
tokio.workspace = true
tracing.workspace = true
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
uuid.workspace = true
tower-http = { version = "0.5.2", features = ["cors", "trace"] }
sqlx = { version = "0.7.4", features = [
"runtime-tokio",
"tls-rustls",
"postgres",
"uuid",
"time",
] }
[dev-dependencies]
similar-asserts = "1.5.0"
tempfile = "3.10.1"

View File

@@ -0,0 +1 @@
-- Add migration script here

View File

@@ -0,0 +1,40 @@
use std::{net::SocketAddr, sync::Arc};
use axum::{extract::MatchedPath, http::Request, routing::get, Router};
use tower_http::trace::TraceLayer;
use crate::state::{SharedState, State};
async fn root() -> &'static str {
"Hello, hyperlog!"
}
pub async fn serve(state: &SharedState, host: &SocketAddr) -> anyhow::Result<()> {
let app = Router::new()
.route("/", get(root))
.with_state(state.clone())
.layer(
TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {
// Log the matched route's path (with placeholders not filled in).
// Use request.uri() or OriginalUri if you want the real path.
let matched_path = request
.extensions()
.get::<MatchedPath>()
.map(MatchedPath::as_str);
tracing::info_span!(
"http_request",
method = ?request.method(),
matched_path,
some_other_field = tracing::field::Empty,
)
}), // ...
);
tracing::info!("listening on {}", host);
let listener = tokio::net::TcpListener::bind(host).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
Ok(())
}

View File

@@ -0,0 +1,40 @@
use std::{net::SocketAddr, sync::Arc};
use axum::{extract::MatchedPath, http::Request, routing::get, Router};
use tower_http::trace::TraceLayer;
use crate::state::{SharedState, State};
async fn root() -> &'static str {
"Hello, hyperlog!"
}
pub async fn serve(state: &SharedState, host: &SocketAddr) -> anyhow::Result<()> {
let app = Router::new()
.route("/", get(root))
.with_state(state.clone())
.layer(
TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {
// Log the matched route's path (with placeholders not filled in).
// Use request.uri() or OriginalUri if you want the real path.
let matched_path = request
.extensions()
.get::<MatchedPath>()
.map(MatchedPath::as_str);
tracing::info_span!(
"http_request",
method = ?request.method(),
matched_path,
some_other_field = tracing::field::Empty,
)
}), // ...
);
tracing::info!("listening on {}", host);
let listener = tokio::net::TcpListener::bind(host).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
Ok(())
}

View File

@@ -0,0 +1,36 @@
use std::{net::SocketAddr, sync::Arc};
use crate::state::{SharedState, State};
mod external_http;
mod internal_http;
mod state;
#[derive(Clone)]
pub struct ServeOptions {
pub external_http: SocketAddr,
pub internal_http: SocketAddr,
}
pub async fn serve(opts: ServeOptions) -> anyhow::Result<()> {
let ctrl_c = async {
tokio::signal::ctrl_c().await.unwrap();
tracing::info!("kill signal received, shutting down");
};
tracing::debug!("setting up dependencies");
let state = SharedState(Arc::new(State::new().await?));
tracing::debug!("serve starting");
tokio::select!(
res = external_http::serve(&state, &opts.external_http) => {
res?
},
res = internal_http::serve(&state, &opts.internal_http) => {
res?
},
() = ctrl_c => {}
);
tracing::debug!("serve finalized");
Ok(())
}

View File

@@ -0,0 +1,37 @@
use std::{ops::Deref, sync::Arc};
use anyhow::Context;
use sqlx::{Pool, Postgres};
#[derive(Clone)]
pub struct SharedState(pub Arc<State>);
impl Deref for SharedState {
type Target = Arc<State>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub struct State {
pub _db: Pool<Postgres>,
}
impl State {
pub async fn new() -> anyhow::Result<Self> {
let db = sqlx::PgPool::connect(
&std::env::var("DATABASE_URL").context("DATABASE_URL is not set")?,
)
.await?;
sqlx::migrate!("migrations/crdb")
.set_locking(false)
.run(&db)
.await?;
let _ = sqlx::query("SELECT 1;").fetch_one(&db).await?;
Ok(Self { _db: db })
}
}