feat: add base app

Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
2024-04-12 09:05:04 +02:00
commit 3ceb52c378
16 changed files with 2542 additions and 0 deletions

1
crates/contractor/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target

View File

@@ -0,0 +1,19 @@
[package]
name = "contractor"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
clap.workspace = true
dotenv.workspace = true
axum.workspace = true
serde = { version = "1.0.197", features = ["derive"] }
sqlx = { version = "0.7.3", features = ["runtime-tokio", "tls-rustls", "postgres", "uuid", "time"] }
uuid = { version = "1.7.0", features = ["v4"] }
tower-http = { version = "0.5.2", features = ["cors", "trace"] }
futures = "0.3.30"

View File

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

View File

@@ -0,0 +1,40 @@
use std::net::SocketAddr;
use axum::{extract::MatchedPath, http::Request, routing::get, Router};
use tower_http::trace::TraceLayer;
use crate::SharedState;
pub async fn serve_axum(state: &SharedState, host: &SocketAddr) -> Result<(), anyhow::Error> {
tracing::info!("running webhook server");
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?;
Ok(())
}
async fn root() -> &'static str {
"Hello, contractor!"
}

View File

@@ -0,0 +1,62 @@
use std::{net::SocketAddr, sync::Arc};
use clap::{Parser, Subcommand};
use futures::{stream::FuturesUnordered, StreamExt};
use tokio::task;
#[derive(Parser)]
#[command(author, version, about, long_about = None, subcommand_required = true)]
struct Command {
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Subcommand)]
enum Commands {
Serve {
#[arg(env = "SERVICE_HOST", long, default_value = "127.0.0.1:3000")]
host: SocketAddr,
},
}
mod api;
mod schedule;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
dotenv::dotenv().ok();
tracing_subscriber::fmt::init();
let cli = Command::parse();
if let Some(Commands::Serve { host }) = cli.command {
tracing::info!("Starting service");
let state = SharedState::from(Arc::new(State::new().await?));
let mut tasks = FuturesUnordered::new();
tasks.push({
let state = state.clone();
task::spawn(async move {
serve_axum(&state, &host).await?;
Ok::<(), anyhow::Error>(())
})
});
tasks.push(task::spawn(async move {
serve_cron_jobs(&state).await?;
Ok::<(), anyhow::Error>(())
}));
while let Some(result) = tasks.next().await {
result??
}
}
Ok(())
}
mod state;
pub use crate::state::{SharedState, State};
use crate::{api::serve_axum, schedule::serve_cron_jobs};

View File

@@ -0,0 +1,14 @@
use crate::SharedState;
pub async fn serve_cron_jobs(_state: &SharedState) -> Result<(), anyhow::Error> {
tokio::spawn(async move {
loop {
tracing::info!("running cronjobs");
tokio::time::sleep(std::time::Duration::from_secs(10_000)).await;
}
Ok::<(), anyhow::Error>(())
})
.await??;
Ok(())
}

View File

@@ -0,0 +1,41 @@
use std::{ops::Deref, sync::Arc};
#[derive(Clone)]
pub struct SharedState(Arc<State>);
impl From<Arc<State>> for SharedState {
fn from(value: Arc<State>) -> Self {
Self(value)
}
}
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 })
Ok(Self {})
}
}