Skip to content

Commit

Permalink
Make serving static pages optional (#22)
Browse files Browse the repository at this point in the history
* Make serving static pages optional

* Customize API configs provider

* Update Dockerfile

* Update Dockerfile

* Remove package dotenvy

* Update diesel.toml

* Update deployments/docker-compose/docker-compose.yaml

* Update .github/workflows/CI.yml

* Update README.md

* Update .github/workflows/CI.yml

* Update .github/workflows/CI.yml

* Update .github/workflows/CI.yml

* Update ./scripts/cli.sh

* Fix docker deployment
  • Loading branch information
linw1995 authored Sep 27, 2024
1 parent 8d5dafc commit f1345a2
Show file tree
Hide file tree
Showing 14 changed files with 78 additions and 43 deletions.
9 changes: 5 additions & 4 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@ on:
- .github/workflows/CI.yml
- .cargo/config.toml
- Cargo.toml
- ./**/*.rs
- ./scripts/cli.sh
- bearmark-*/**/*.rs
- scripts/cli.sh
pull_request:
branches: ["main"]
paths:
- .github/workflows/CI.yml
- .cargo/config.toml
- Cargo.toml
- ./**/*.rs
- ./scripts/cli.sh
- bearmark-*/**/*.rs
- scripts/cli.sh

env:
CARGO_TERM_COLOR: always
Expand Down Expand Up @@ -81,6 +81,7 @@ jobs:

- name: Run tests with coverage
run: |
source .envrc
./scripts/cli.sh coverage-xml
env:
CARGO_BUILD_TARGET: x86_64-unknown-linux-musl
Expand Down
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ COPY ./server /usr/local/bin/server
COPY ./static /app/static

EXPOSE 8000
ENV BM_UI_PATH=./static
ENV BM_ADDRESS=0.0.0.0

WORKDIR /app

Expand Down
15 changes: 8 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,17 @@ open http://localhost:2284

## Developments

Use nix to setup development environment.
Use nix to setup development environment,
or use `direnv` to load nix environment automatically.

```bash
nix develop
```

Or use `direnv` to load nix environment automatically.
# setup database by docker compose
# and generate .envrc file
./scripts/cli.sh setup

```bash
echo "use flake" > .envrc
# activate manually
nix develop
source .envrc
```

### Helpful Scripts
Expand Down
2 changes: 0 additions & 2 deletions bearmark-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ rand = "0.8.5"
itertools = "0.13.0"
time = { version = "0.3.36", features = ["local-offset", "macros", "serde"] }
percent-encoding = "2.3.1"
# read settings from the dotenv file
dotenvy = "0.15.7"
# logging
tracing.workspace = true
tracing-appender.workspace = true
Expand Down
4 changes: 2 additions & 2 deletions bearmark-api/src/api/bookmark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ pub fn routes() -> Vec<rocket::Route> {
#[cfg(test)]
mod test {
use super::*;
use crate::api::configs::Config;
use crate::api::configs::{self, Config};
use crate::db::bookmark::test::rand_bookmark;
use crate::utils::rand::rand_str;

Expand All @@ -213,7 +213,7 @@ mod test {
use tracing::info;

fn test_app() -> rocket::Rocket<rocket::Build> {
rocket::build()
rocket::custom(configs::config_provider())
.attach(Db::init())
.mount("/", routes())
.attach(AdHoc::config::<Config>())
Expand Down
23 changes: 21 additions & 2 deletions bearmark-api/src/api/configs.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,26 @@
use rocket::serde::{Deserialize, Serialize};
use rocket::{
figment::Figment,
serde::{Deserialize, Serialize},
};

#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(crate = "rocket::serde")]
pub struct Config {
pub ui_path: Option<String>,
pub api_key: Option<String>,
}

pub fn config_provider() -> Figment {
use rocket::figment::providers::{Env, Serialized};

rocket::figment::Figment::from(rocket::Config::default())
.merge(Serialized::defaults(Config::default()))
.merge(("databases.main", rocket_db_pools::Config::default()))
.merge(Env::prefixed("BM_").global())
}

pub fn get_database_url() -> String {
config_provider()
.extract_inner("databases.main.url")
.unwrap()
}
11 changes: 5 additions & 6 deletions bearmark-api/src/api/fairings/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use diesel_async::{
},
AsyncConnection, AsyncPgConnection,
};
use dotenvy::dotenv;
use rocket::figment::Figment;
use rocket_db_pools::{Database, Error};

Expand All @@ -21,10 +20,10 @@ impl rocket_db_pools::Pool for DBPool {

type Error = Error<InitError, GetError>;

async fn init(_figment: &Figment) -> Result<Self, Self::Error> {
dotenv().ok();

let url = std::env::var("DATABASE_URL").expect("env DATABASE_URL must be set");
async fn init(figment: &Figment) -> Result<Self, Self::Error> {
let url = figment
.extract_inner::<String>("url")
.expect("database_url must be set");
let config = AsyncDieselConnectionManager::<Connection>::new(url);
match Pool::builder(config).build() {
Ok(pool) => Ok(Self(pool)),
Expand Down Expand Up @@ -57,5 +56,5 @@ impl rocket_db_pools::Pool for DBPool {
}

#[derive(Database)]
#[database("deadpool_diesel_postgres")]
#[database("main")]
pub struct Db(DBPool);
3 changes: 2 additions & 1 deletion bearmark-api/src/api/folder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ pub fn routes() -> Vec<rocket::Route> {
#[cfg(test)]
pub(crate) mod test {
use super::*;
use crate::api::configs;
use crate::api::configs::Config;
use crate::db::bookmark::test::create_rand_bookmark;
use crate::db::connection;
Expand All @@ -122,7 +123,7 @@ pub(crate) mod test {
use tracing::info;

fn test_app() -> rocket::Rocket<rocket::Build> {
rocket::build()
rocket::custom(configs::config_provider())
.attach(Db::init())
.mount("/", routes())
.attach(AdHoc::config::<Config>())
Expand Down
6 changes: 5 additions & 1 deletion bearmark-api/src/api/guards/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ mod test {

#[test]
fn test_disable_auth() {
let client = test_client(Config { api_key: None });
let client = test_client(Config {
api_key: None,
..Default::default()
});
let response = client.get(uri!(required_auth)).dispatch();
assert_eq!(response.status(), Status::Ok);
}
Expand All @@ -82,6 +85,7 @@ mod test {
let key = rand_str(32);
let client = test_client(Config {
api_key: Some(key.clone()),
..Default::default()
});

let response = client.get(uri!(required_auth)).dispatch();
Expand Down
15 changes: 12 additions & 3 deletions bearmark-api/src/bin/serve.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[macro_use]
extern crate rocket;

use bearmark_api::api::configs::Config;
use bearmark_api::api::configs::{self, Config};
use bearmark_api::api::fairings::db::Db;
use bearmark_api::api::{bookmark, folder, tag};

Expand All @@ -15,8 +15,17 @@ async fn rocket() -> _ {
bearmark_api::utils::logging::setup_console_log();
bearmark_api::db::connection::run_migrations().await;

rocket::build()
.mount("/", FileServer::from("./static"))
let cfg_provider = configs::config_provider();
let ui_path = cfg_provider
.extract_inner::<Option<String>>("ui_path")
.unwrap();

let mut builder = rocket::custom(cfg_provider);
if let Some(ui_path) = ui_path {
// Serve the UI files if the path is provided
builder = builder.mount("/", FileServer::from(ui_path));
}
builder
.attach(Db::init())
.mount("/api/bookmarks", bookmark::routes())
.mount("/api/tags", tag::routes())
Expand Down
12 changes: 6 additions & 6 deletions bearmark-api/src/db/connection.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use diesel_async::AsyncPgConnection;
use dotenvy::dotenv;
use std::env;

use crate::api::configs;

pub async fn establish() -> AsyncPgConnection {
use diesel_async::AsyncConnection;
dotenv().ok();

let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let mut conn = AsyncPgConnection::establish(&database_url)
let url = configs::get_database_url();

let mut conn = AsyncPgConnection::establish(&url)
.await
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url));
.unwrap_or_else(|_| panic!("Error connecting database",));

if cfg!(debug_assertions) {
use diesel::connection::InstrumentationEvent;
Expand Down
5 changes: 2 additions & 3 deletions deployments/docker-compose/docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@ services:
environment:
RUST_BACKTRACE: full
RUST_LOG: ${RUST_LOG}
DATABASE_URL: postgres://${DB_USERNAME}:${DB_PASSWORD}@database:5432/${DB_DATABASE_NAME}
ROCKET_ADDRESS: 0.0.0.0
ROCKET_API_KEY: ${API_KEY}
BM_DATABASES: '{main={url="postgres://${DB_USERNAME}:${DB_PASSWORD}@database:5432/${DB_DATABASE_NAME}"}}'
BM_API_KEY: ${API_KEY}
database:
container_name: bearmark_postgres
image: postgres:12
Expand Down
2 changes: 1 addition & 1 deletion diesel.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
# see https://diesel.rs/guides/configuring-diesel-cli

[print_schema]
file = "src/db/schema.rs"
file = "bearmark-api/src/db/schema.rs"
custom_type_derives = ["diesel::query_builder::QueryId", "Clone"]
12 changes: 7 additions & 5 deletions scripts/cli.sh
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,17 @@ main() {
echo ">>> Setting up the project development environment"
docker compose up -d --wait

echo "DATABASE_URL=postgres://postgres:example@${POSTGRES_HOST-localhost}:${POSTGRES_PORT-5432}/${POSTGRES_DB-bearmark}" >.env
url=postgres://postgres:example@${POSTGRES_HOST-localhost}:${POSTGRES_PORT-5432}/${POSTGRES_DB-bearmark}
echo "use flake
export BM_DATABASES='{main={url=\"$url\"}}'" >.envrc
echo ">>> Setting up database"
./scripts/bin/diesel migration run
DATABASE_URL=$url ./scripts/bin/diesel migration run
else
echo ">>> Skip setting up the project development environment"

echo "DATABASE_URL=postgres://postgres:example@${POSTGRES_HOST-db}:${POSTGRES_PORT-5432}/${POSTGRES_DB-bearmark}" >.env
url=postgres://postgres:example@${POSTGRES_HOST-db}:${POSTGRES_PORT-5432}/${POSTGRES_DB-bearmark}
echo "export BM_DATABASES='{main={url=\"$url\"}}'" >.envrc
echo ">>> Setting up database"
diesel migration run
DATABASE_URL=$url diesel migration run
fi
echo ">>> Done"
;;
Expand Down

0 comments on commit f1345a2

Please sign in to comment.