Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Embed all external resources into a single binary #249

Merged
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
34 changes: 20 additions & 14 deletions .github/workflows/continuous-delivery.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,28 @@ on:
branches:
- main
jobs:
build-image:
build:
runs-on: ubuntu-latest
permissions:
id-token: write
env:
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
steps:
- run: sudo apt install gcc-aarch64-linux-gnu -y
- run: rustup target install aarch64-unknown-linux-gnu
- uses: actions/checkout@v4
- uses: google-github-actions/auth@v2
- uses: actions/cache@v4
with:
project_id: ${{ secrets.PROJECT_ID }}
workload_identity_provider: ${{ secrets.WORKLOAD_IDENTITY_PROVIDER }}
- uses: 'google-github-actions/setup-gcloud@v2'
- run: gcloud auth configure-docker us-central1-docker.pkg.dev
- uses: docker/setup-buildx-action@v3
- uses: docker/build-push-action@v6
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- run: npm install tailwindcss @tailwindcss/container-queries @tailwindcss/forms
- run: npx tailwindcss -i input.css -o static/app.css
- run: cargo build --release --target aarch64-unknown-linux-gnu
- uses: actions/upload-artifact@v4
with:
push: true
tags: ${{ secrets.DOCKER_IMAGE }}:latest
cache-from: type=registry,ref=${{ secrets.DOCKER_IMAGE }}:buildcache
cache-to: type=registry,ref=${{ secrets.DOCKER_IMAGE }}:buildcache,mode=max
name: simple-budget
path: target/aarch64-unknown-linux-gnu/release/simple-budget

2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ target/

.env

/static
/static/app.css
/k8s/output
27 changes: 27 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 9 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,20 @@ resolver = "2"
axum = { version = "0.7.7", features = ["ws"] }
axum-extra = { version = "0.9.4", features = ["cookie-signed", "query"] }
bson = { version = "2.13.0", features = ["serde_with-3", "chrono-0_4"] }
chrono = "0.4.38"
chrono-tz = "0.10.0"
futures-util = "0.3.31"
log = "0.4.22"
chrono = { version = "0.4.38" }
chrono-tz = { version = "0.10.0" }
futures-util = { version = "0.3.31" }
include_dir = { version = "0.7.4", features = ["glob"] }
log = { version = "0.4.22" }
mongodb = { version = "3.1.0" }
openidconnect = { version = "3.5.0", features = ["reqwest"] }
rand = "0.8.5"
serde = "1.0.210"
rand = { version = "0.8.5" }
serde = { version = "1.0.210" }
tera = { version = "1.20.0" }
tokio = { version = "1.40.0", features = ["full"] }
tower = { version = "0.5.1", features = ["util"] }
tower-http = { version = "0.6.1", features = ["fs", "trace"] }
tower-layer = "0.3.3"
tracing = "0.1.40"
tower-layer = { version = "0.3.3" }
tracing = { version = "0.1.40" }
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
validator = { version = "0.18.1", features = ["derive"] }
31 changes: 9 additions & 22 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,16 +1,4 @@
FROM rust:1.81.0 AS backend_builder
RUN mkdir -p /build
WORKDIR /build
COPY Cargo.toml /build/
RUN mkdir -p /build/src
RUN echo "fn main() {}" > /build/src/main.rs
RUN cargo build --release
COPY src /build/src
RUN touch /build/src/main.rs
RUN cargo build --release
RUN cp /build/target/release/simple-budget /build/simple-budget

FROM node:alpine AS frontend_builder
FROM node AS frontend_builder
RUN mkdir /build
COPY src/templates /build/src/templates
COPY src/input.css /build/src/input.css
Expand All @@ -22,18 +10,17 @@ RUN npx tailwindcss -i src/input.css -o app.css
COPY controllers /build/controllers
RUN gzip -k app.css controllers/*.js

FROM scratch
COPY --from=backend_builder /build/simple-budget /simple-budget
COPY src/templates /src/templates
# Avoid doing anything in these steps outside of COPY
FROM rust:1.82.0-alpine
COPY --from=frontend_builder /build/controllers /static/controllers
COPY src/favicon.png /static/favicon.png
COPY etc_passwd /etc/passwd
COPY --from=frontend_builder /build/app.css /static/app.css
COPY --from=frontend_builder /build/app.css.gz /static/app.css.gz
COPY --from=frontend_builder /build/src/google.css /static/google.css
COPY --from=backend_builder /lib/x86_64-linux-gnu/libgcc_s.so.1 /lib/x86_64-linux-gnu/libgcc_s.so.1
COPY --from=backend_builder /lib/x86_64-linux-gnu/libm.so.6 /lib/x86_64-linux-gnu/libm.so.6
COPY --from=backend_builder /lib/x86_64-linux-gnu/libc.so.6 /lib/x86_64-linux-gnu/libc.so.6
COPY --from=backend_builder /lib64/ld-linux-x86-64.so.2 /lib64/ld-linux-x86-64.so.2
COPY src/favicon.png /static/favicon.png
COPY etc_passwd /etc/passwd
COPY src/templates /src/templates

COPY simple-budget /simple-budget

USER 65534
CMD ["/simple-budget"]
File renamed without changes.
2 changes: 1 addition & 1 deletion src/authenticated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use serde::{Deserialize, Serialize};
use std::env;
use tokio::{spawn, sync::watch};
use tracing::debug;
mod accounts;
pub mod accounts;
mod dashboard;
mod envelopes;
mod goals;
Expand Down
6 changes: 3 additions & 3 deletions src/authenticated/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ mod update;
#[derive(Debug, Validate, Deserialize)]
pub struct AccountForm {
#[validate(length(min = 5))]
name: String,
pub name: String,
#[validate(range(min = 0.0))]
amount: f64,
debt: Option<bool>,
pub amount: f64,
pub debt: Option<bool>,
}

async fn initialize_context(
Expand Down
14 changes: 4 additions & 10 deletions src/authenticated/accounts/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ use axum::{
response::{Html, IntoResponse, Redirect, Response},
Extension, Form,
};
use mongodb::{bson::oid::ObjectId, Collection};
use std::str::FromStr;
use mongodb::bson::oid::ObjectId;
use tera::Context;
use validator::Validate;

Expand Down Expand Up @@ -62,16 +61,10 @@ pub async fn page(
name: form.name.to_owned(),
amount: form.amount.to_owned(),
debt: form.debt.unwrap_or(false),
user_id: ObjectId::from_str(&user.id).unwrap().to_string(),
user_id: ObjectId::parse_str(&user.id)?.to_string(),
};

let accounts: Collection<Account> = shared_state
.mongo
.default_database()
.unwrap()
.collection("accounts");

let _ = accounts.insert_one(account_record).await?;
account_record.create(&shared_state.mongo).await?;

Ok(Redirect::to("/accounts").into_response())
}
Expand All @@ -87,6 +80,7 @@ mod tests {
use axum::Router;

use bson::doc;
use mongodb::Collection;
use std::str::from_utf8;
use tower::ServiceExt;

Expand Down
2 changes: 0 additions & 2 deletions src/authenticated/accounts/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ pub async fn modal(
.collection("accounts");

let filter = doc! {"_id": ObjectId::from_str(&id).unwrap(), "user_id": ObjectId::from_str(&user.id).unwrap()};

let account = accounts.find_one(filter.clone()).await?;

let Some(_) = account else {
return Err(FormError {
message: "could not find account".to_string(),
Expand Down
30 changes: 8 additions & 22 deletions src/authenticated/accounts/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ use axum::{
response::{Html, IntoResponse, Redirect, Response},
Extension, Form,
};
use mongodb::bson::{doc, oid::ObjectId};
use std::str::FromStr;
use mongodb::bson::oid::ObjectId;
use tera::Context;
use validator::Validate;

Expand Down Expand Up @@ -59,28 +58,15 @@ pub async fn action(
}
}

let accounts: mongodb::Collection<Account> = shared_state
.mongo
.default_database()
.unwrap()
.collection("accounts");

let filter = doc! {"_id": ObjectId::from_str(&id).unwrap(), "user_id": ObjectId::from_str(&user.id).unwrap()};

let account = accounts.find_one(filter.clone()).await?;

let Some(mut account) = account else {
return Err(FormError {
message: "could not find account".to_string(),
status_code: Some(StatusCode::NOT_FOUND),
});
let account = Account {
_id: ObjectId::parse_str(id)?.to_string(),
user_id: ObjectId::parse_str(&user.id)?.to_string(),
name: form.name.to_owned(),
amount: form.amount.to_owned(),
debt: form.debt.unwrap_or(false),
};

account.name = form.name.clone();
account.amount = form.amount;
account.debt = form.debt.unwrap_or(false);

let _ = accounts.replace_one(filter, account).await?;
account.update(&shared_state.mongo).await?;

Ok(Redirect::to("/accounts").into_response())
}
Expand Down
4 changes: 2 additions & 2 deletions src/authenticated/dashboard.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::UserExtension;
use crate::models::account::accounts_total_for;
use crate::models::account::Account;
use crate::models::envelope::envelopes_total_for;
use crate::utilities::dates::{TimeProvider, TimeUtilities};
use crate::{errors::FormError, models::user::User, Section, SharedState};
Expand Down Expand Up @@ -78,7 +78,7 @@ pub async fn generate_dashboard_context_for(user: &User, client: &Client) -> Con
.unwrap_or(0.0);

let envelopes_total = envelopes_total_for(&user_id, client).await;
let accounts_total = accounts_total_for(&user_id, client).await;
let accounts_total = Account::accounts_total_for(&user_id, client).await;

let remaining_total = accounts_total - envelopes_total - goals_total;

Expand Down
35 changes: 35 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,54 @@ impl From<mongodb::error::Error> for FormError {
}
}

impl From<ModelError> for FormError {
fn from(value: ModelError) -> Self {
log::error!("{:#?}", value);

FormError {
message: value.to_string(),
status_code: None,
}
}
}

#[derive(Debug)]
pub enum ModelError {
MissingDefaultDatabase,

#[allow(dead_code)]
OidError(bson::oid::Error),

#[allow(dead_code)]
OidParsingError(bson::oid::Error),

#[allow(dead_code)]
DatabaseError(mongodb::error::Error),
}

impl From<bson::oid::Error> for ModelError {
fn from(err: bson::oid::Error) -> ModelError {
ModelError::OidError(err)
}
}
impl From<mongodb::error::Error> for ModelError {
fn from(err: mongodb::error::Error) -> ModelError {
ModelError::DatabaseError(err)
}
}

impl std::fmt::Display for ModelError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::MissingDefaultDatabase => {
write!(
f,
"default database not configured, check the connection string"
)
}
Self::OidError(bson_error) => write!(f, "{}", bson_error),
Self::OidParsingError(bson_error) => write!(f, "{}", bson_error),
Self::DatabaseError(mongo_error) => write!(f, "{}", mongo_error),
}
}
}
Loading