Skip to content

Commit

Permalink
Merge branch 'main' into riley-events
Browse files Browse the repository at this point in the history
  • Loading branch information
RileyChampion committed Dec 26, 2024
2 parents 0550cca + 93b8f0f commit 64f1d9d
Show file tree
Hide file tree
Showing 16 changed files with 175 additions and 131 deletions.
3 changes: 3 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Tell cargo to use the correct linker when cross-compiling
[target.aarch64-unknown-linux-gnu]
linker = "aarch64-linux-gnu-gcc"
8 changes: 6 additions & 2 deletions .github/workflows/deploy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,18 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-unknown-linux-gnu
- uses: Swatinem/rust-cache@v2
- name: install gcc-aarch64-linux-gnu
run: sudo apt install -y gcc-aarch64-linux-gnu
- uses: webfactory/[email protected]
with:
ssh-private-key: ${{ secrets.SSH_KEY }}
- name: ssh-keyscan
run: |
mkdir -p ~/.ssh
ssh-keyscan wlsd.foltz.io > ~/.ssh/known_hosts
ssh-keyscan wlsd.lightandsound.design > ~/.ssh/known_hosts
chmod 600 ~/.ssh/known_hosts
- name: deploy
run: scripts/deploy.sh wlsd.foltz.io
run: scripts/deploy.sh ec2-user@wlsd.lightandsound.design
29 changes: 17 additions & 12 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ jobs:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: cargo test
uses: actions-rs/cargo@v1
with:
command: test
- run: cargo test

rustfmt:
name: Format
Expand All @@ -27,11 +24,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- name: cargo fmt
uses: actions-rs/cargo@v1
with:
command: fmt
args: -- --check
- run: cargo fmt --check

clippy:
name: Lint
Expand All @@ -42,7 +35,19 @@ jobs:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: cargo clippy
uses: actions-rs/cargo@v1
- run: cargo clippy -- -D warnings

cross:
name: Cross-compile
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
command: clippy
targets: aarch64-unknown-linux-gnu
- uses: Swatinem/rust-cache@v2
- name: install gcc-aarch64-linux-gnu
run: sudo apt install -y gcc-aarch64-linux-gnu
- run: cargo build --target aarch64-unknown-linux-gnu
7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,25 @@ sqlx = { version = "0.8", features = ["sqlite", "runtime-tokio"] }
lettre = { version = "0.11", default-features = false, features = ["builder", "hostname", "pool", "smtp-transport", "tokio1", "tokio1-rustls-tls", "serde"] }
tokio = { version = "1", features = ["rt-multi-thread", "fs", "net", "sync", "macros"] }
rustls = "0.23"
rustls-acme = { version = "0.12", features = ["axum"] }

anyhow = "1"
tracing = "0.1"
tracing-subscriber = "0.3"
futures = "0.3"
serde = { version = "1", features = ["derive"] }
toml = "0.8"
rand = "0.8"
mimalloc = "*"


# Add a little optimization to debug builds
[profile.dev]
opt-level = 1
# And since they don't get recompiled often, fully optimize dependencies
[profile.dev.package."*"]
opt-level = 3

# Production build with more intense optimization
[profile.prod]
inherits = "release"
lto = true
Expand Down
11 changes: 4 additions & 7 deletions config/dev.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@
url = "https://localhost:4433"
db = "db.sqlite"

[http]
addr = "0.0.0.0:8080"
[https]
addr = "0.0.0.0:4433"
cert = "config/selfsigned.cert"
key = "config/selfsigned.key"
[net]
http_addr = "[::]:8080"
https_addr = "[::]:4433"

[mail]
[email]
addr = "smtp://localhost:1025"
from = "WLSD <[email protected]>"
19 changes: 11 additions & 8 deletions config/prod.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
[app]
url = "https://wlsd.foltz.io"
url = "https://wlsd.lightandsound.design"
db = "db.sqlite"

[http]
addr = "0.0.0.0:80"
[https]
addr = "0.0.0.0:443"
cert = "config/selfsigned.cert"
key = "config/selfsigned.key"
[net]
http_addr = "[::]:80"
https_addr = "[::]:443"

[mail]
[acme]
domain = "wlsd.lightandsound.design"
email = "[email protected]"
dir = "acme"
prod = true

[email]
addr = "smtp://localhost:1080"
from = "WLSD <[email protected]>"
4 changes: 2 additions & 2 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
max_width = 110
chain_width = 100
fn_call_width = 100
chain_width = 80
fn_call_width = 80
struct_lit_width = 75
single_line_if_else_max_width = 80
19 changes: 9 additions & 10 deletions scripts/bootstrap.sh
Original file line number Diff line number Diff line change
@@ -1,29 +1,28 @@
#!/bin/bash
set -euxo pipefail
if [ $# -ne 1 ]; then
echo "Usage: scripts/deploy.sh <hostname>"
echo "Usage: scripts/deploy.sh <user>@<hostname>"
exit 1
fi

ssh root@$1 <<'EOS'
ssh $1 <<'EOS'
# update
apt update
apt upgrade -y
apt install -y rsync
sudo yum update -y
# create a user
if ! id wlsd &>/dev/null; then
adduser --disabled-password --gecos "" wlsd
sudo adduser wlsd
fi
# add ssh keys
cat > .ssh/authorized_keys <<EOF
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILd0t8vieD+N6tL23X7NAS3bIm69dcq27eOoqjHT8ae5 foltz
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHYLLX74GD4EJy2yZyn63AA7XXGoS1AHDrpxh+1lYgO4JeMqUk34S+eiyJ7WpENVKrePUeKhfqfgbqY1f05k37o= foltz@navi
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBK0kzT3O4qZcnwHQEhocVu7c8ksX1UMgnupSP4tA0CFvapjexRbYBTO4EwZuLJk/Arx/CNB4IVpB8w9tpkXkbFY= [email protected]/foltz/wlsd
EOF
# setup service
cat > /etc/systemd/system/wlsd.service <<EOF
sudo tee /etc/systemd/system/wlsd.service <<EOF >/dev/null
[Unit]
Description=WLSD
After=network.target
Expand All @@ -38,7 +37,7 @@ Restart=always
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable wlsd
#systemctl restart wlsd
sudo systemctl daemon-reload
sudo systemctl enable wlsd
sudo systemctl restart wlsd
EOS
16 changes: 8 additions & 8 deletions scripts/deploy.sh
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
#!/bin/bash
set -euxo pipefail
if [ $# -ne 1 ]; then
echo "Usage: scripts/deploy.sh <hostname>"
echo "Usage: scripts/deploy.sh <user>@<hostname>"
exit 1
fi

cargo build --profile prod
cargo build --profile prod --target aarch64-unknown-linux-gnu

rsync -Pavzr --delete assets templates config target/prod/wlsd root@$1:/home/wlsd/
ssh root@$1 <<'EOS'
apt-get update
apt-get upgrade -y
setcap 'cap_net_bind_service=+ep' /home/wlsd/wlsd
systemctl restart wlsd
ls -l target/aarch64-unknown-linux-gnu/
ls -l target/aarch64-unknown-linux-gnu/*
rsync --rsync-path="sudo rsync" -Pavzr --delete assets templates config target/aarch64-unknown-linux-gnu/prod/wlsd $1:/home/wlsd/
ssh $1 <<'EOS'
sudo setcap 'cap_net_bind_service=+ep' /home/wlsd/wlsd
sudo systemctl restart wlsd
EOS
12 changes: 7 additions & 5 deletions src/app.rs → src/app/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use std::{sync::Arc, time::Duration};

use crate::*;
use crate::utils::{config::*, db::Db, email::Email};
use tera::Tera;

use anyhow::Result;
use axum::{
extract::{MatchedPath, Path, Query, Request, State},
http::{header, StatusCode},
response::{Html, IntoResponse, Response},
response::{Html, IntoResponse, Redirect, Response},
routing::{get, post},
Form, Router,
};
Expand All @@ -20,15 +22,15 @@ struct AppState {
config: Config,
templates: Tera,
db: Db,
mail: Mail,
mail: Email,
}

pub async fn build(config: Config) -> Result<Router> {
let state = app::AppState {
let state = AppState {
config: config.clone(),
templates: Tera::new("templates/*")?,
db: Db::connect(&config.app.db).await?,
mail: Mail::connect(config.mail).await?,
mail: Email::connect(config.email).await?,
};

let router = Router::new()
Expand Down
40 changes: 0 additions & 40 deletions src/config.rs

This file was deleted.

65 changes: 45 additions & 20 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,63 @@
use anyhow::{Context, Result};
use axum::{handler::HandlerWithoutStateExt as _, response::Redirect};
use axum_server::tls_rustls::RustlsConfig;
use mimalloc::MiMalloc;
use tera::Tera;

mod app;
mod config;
mod db;
mod mail;

use config::*;
use db::Db;
use mail::Mail;
mod utils;

#[global_allocator]
static ALLOC: MiMalloc = MiMalloc;
use axum::{handler::HandlerWithoutStateExt, response::Redirect};
use axum_server::tls_rustls::RustlsConfig;
use futures::StreamExt;
use utils::config::*;

#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt().init();
let file = std::env::args().nth(1).context("usage: wlsd <config.yaml>")?;
let config = config::load(&file).await.with_context(|| format!("loading config={file}"))?;

// Load the server config
let file = std::env::args().nth(1).context("usage: wlsd <config.toml>")?;
let config = Config::load(&file).await?;

let app = app::build(config.clone()).await?.into_make_service();
tracing::info!("Live at {}", &config.app.url);

// Redirect HTTP to HTTPS
// Spawn an auxillary HTTP server which just redirects to HTTPS
tokio::spawn(async move {
let redirect = move || async move { Redirect::permanent(&config.app.url) };
axum_server::bind(config.http.addr).serve(redirect.into_make_service()).await
axum_server::bind(config.net.http_addr)
.serve(redirect.into_make_service())
.await
});

// Bind HTTPS
let rustls = RustlsConfig::from_pem_file(config.https.cert, config.https.key).await?;
axum_server::bind_rustls(config.https.addr, rustls).serve(app).await?;
// Spawn the main HTTPS server
match config.acme {
// If ACME is configured, request a TLS certificate from Let's Encrypt
Some(acme) => {
let mut acme = rustls_acme::AcmeConfig::new([&acme.domain])
.contact_push(format!("mailto:{}", &acme.email))
.cache(rustls_acme::caches::DirCache::new(acme.dir.clone()))
.directory_lets_encrypt(acme.prod)
.state();

let acceptor = acme.axum_acceptor(acme.default_rustls_config());

tokio::spawn(async move {
loop {
match acme.next().await.unwrap() {
Ok(ok) => tracing::info!("acme: {:?}", ok),
Err(err) => tracing::error!("acme: {}", err),
}
}
});

axum_server::bind(config.net.https_addr).acceptor(acceptor).serve(app).await?;
}
// Otherwise, use the bundled self-signed TLS cert
None => {
let cert = include_bytes!("../config/selfsigned.cert");
let key = include_bytes!("../config/selfsigned.key");
let rustls = RustlsConfig::from_pem(cert.into(), key.into()).await?;
axum_server::bind_rustls(config.net.https_addr, rustls).serve(app).await?;
}
}

Ok(())
}
Loading

0 comments on commit 64f1d9d

Please sign in to comment.