Skip to content

Commit

Permalink
improvement: Use State extension (#28)
Browse files Browse the repository at this point in the history
* feat: Use `State` extension

* chore(nix): Remove unused flake input

* chore(actions): Bump base and other actions

* fix(nix): Docker build error

* chore(action): Run actions on push
  • Loading branch information
sekunho committed Apr 2, 2023
1 parent 08de19a commit 225d56c
Show file tree
Hide file tree
Showing 10 changed files with 122 additions and 104 deletions.
9 changes: 6 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ on:
jobs:
create-release:
name: Create release
runs-on: ubuntu-20.04
runs-on: ubuntu-22.04

steps:
- name: Checkout repo
uses: actions/checkout@v2
uses: actions/checkout@v3

- name: Setup Nix
uses: cachix/install-nix-action@v15
uses: cachix/install-nix-action@v19
with:
extra_nix_config: |
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
Expand All @@ -35,6 +35,9 @@ jobs:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_PASSWORD }}

- name: Sanity check
run: nix flake check

# DOCKER IMAGE

- name: Build image
Expand Down
20 changes: 17 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,31 @@ on:
- 'src/**/*'
- 'public/purify.min.js'

push:
branches: [ main ]
paths:
- '.github/workflows/test.yml'
- 'flake.*'
- 'nix/*'
- 'Cargo.*'
- 'assets/**/*'
- 'src/**/*'
- 'public/purify.min.js'

jobs:
test:
name: Build & test
runs-on: ubuntu-20.04
runs-on: ubuntu-22.04

steps:
- name: Checkout repo
uses: actions/checkout@v2
uses: actions/checkout@v3

- name: Setup Nix
uses: cachix/install-nix-action@v15
uses: cachix/install-nix-action@v19

- name: Sanity check
run: nix flake check

- name: Build & test
run: |
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

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

64 changes: 37 additions & 27 deletions flake.lock

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

21 changes: 6 additions & 15 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,15 @@
description = "A URL shortener, except emojis";

inputs = {
nixpkgs.url = "github:NixOS/nixpkgs";
nixospkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
devenv.url = "github:cachix/devenv";

naersk = {
url = "github:nix-community/naersk";
inputs.nixpkgs.follows = "nixpkgs";
};

pre-commit-hooks = {
url = "github:cachix/pre-commit-hooks.nix";
inputs.nixpkgs.follows = "nixpkgs";
};
naersk.url = "github:nix-community/naersk";
pre-commit-hooks.url = "github:cachix/pre-commit-hooks.nix";
};

outputs = { self, nixpkgs, nixospkgs, devenv, naersk, pre-commit-hooks } @ inputs: (
outputs = { self, nixpkgs, devenv, naersk, pre-commit-hooks } @ inputs: (
let system = "x86_64-linux";
pkgs = nixospkgs.legacyPackages.${system};
pkgs = nixpkgs.legacyPackages.${system};

naersk-lib = naersk.lib.${system}.override {
cargo = pkgs.cargo;
Expand Down Expand Up @@ -89,7 +80,7 @@
program = "${self.packages.${system}.emojied}/bin/emojied";
};

nixosModule = import ./nix/modules/services/emojied.nix;
nixosModules.default = import ./nix/modules/services/emojied.nix;

devShells.${system}.default = devenv.lib.mkShell {
inherit inputs pkgs;
Expand Down
72 changes: 29 additions & 43 deletions src/controllers.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use axum::extract::{Extension, Form, Path, Query};
use axum::extract::{Form, Path, Query, State};
use axum::http::StatusCode;
use axum::response::Json;
use hyper::{
Expand All @@ -11,10 +11,10 @@ use std::collections::HashMap;
use std::fs;
use std::sync::Arc;

use crate::config::AppConfig;
use crate::state::AppState;
use crate::url::CreateUrl;
use crate::views::url::{AutogeneratedUrl, CustomUrl, RootData};
use crate::{db, emoji, leaderboard, url, views};
use crate::{emoji, leaderboard, url, views};

// TODO: Move stuff to their own modules
// TODO: Implement SSE for URL stats page
Expand All @@ -29,13 +29,13 @@ pub async fn root(Query(params): Query<HashMap<String, String>>) -> Markup {
}

pub async fn insert_url(
Extension(handle): Extension<Arc<db::Handle>>,
State(app_state): State<Arc<AppState>>,
Query(params): Query<HashMap<String, String>>,
Form(form_data): Form<CreateUrl>,
) -> (StatusCode, Markup) {
let custom_url = params.get(&String::from("custom_url")).is_some();

match url::insert_url(&*handle, form_data).await {
match url::insert_url(&(*app_state).db_handle, form_data).await {
Ok(i) => {
let root_data = if custom_url {
RootData::Custom(CustomUrl::HasIdentifier(i))
Expand All @@ -62,10 +62,10 @@ pub async fn insert_url(
}

pub async fn rpc_insert_url(
Extension(handle): Extension<Arc<db::Handle>>,
State(app_state): State<Arc<AppState>>,
Json(data): Json<CreateUrl>,
) -> (StatusCode, Json<Value>) {
match url::insert_url(&*handle, data).await {
match url::insert_url(&(*app_state).db_handle, data).await {
Ok(identifier) => (
StatusCode::CREATED,
Json(json!({ "identifier": identifier })),
Expand All @@ -75,10 +75,10 @@ pub async fn rpc_insert_url(
}

pub async fn url_stats(
Extension(handle): Extension<Arc<db::Handle>>,
State(app_state): State<Arc<AppState>>,
Path(identifier): Path<String>,
) -> (StatusCode, Markup) {
match url::url_stats(&*handle, identifier).await {
match url::url_stats(&(*app_state).db_handle, identifier).await {
Ok(url_stat) => (StatusCode::OK, views::url::view_stats(&url_stat)),
Err(_e) => {
// TODO: Give back 50x when it's a problem with the DB
Expand All @@ -88,13 +88,13 @@ pub async fn url_stats(
}

pub async fn fetch_url(
Extension(handle): Extension<Arc<db::Handle>>,
State(app_state): State<Arc<AppState>>,
Path(identifier): Path<String>,
) -> (StatusCode, HeaderMap, Markup) {
let mut headers = HeaderMap::new();

if emoji::is_valid(&identifier) {
match url::fetch_url(&*handle, identifier).await {
match url::fetch_url(&(*app_state).db_handle, identifier).await {
Ok(u) => {
headers.insert(LOCATION, u.parse().unwrap());

Expand All @@ -109,19 +109,17 @@ pub async fn fetch_url(
}
}

pub async fn leaderboard(Extension(handle): Extension<Arc<db::Handle>>) -> (StatusCode, Markup) {
match leaderboard::fetch(&*handle).await {
pub async fn leaderboard(State(app_state): State<Arc<AppState>>) -> (StatusCode, Markup) {
match leaderboard::fetch(&(*app_state).db_handle).await {
Ok(entries) => (StatusCode::OK, views::leaderboard::render(entries)),
Err(_e) => (StatusCode::INTERNAL_SERVER_ERROR, maud::html! {}),
}
}

// TODO: Static assets controller
pub async fn js(
Extension(config): Extension<Arc<AppConfig>>
) -> (StatusCode, HeaderMap, String) {
pub async fn js(State(app_state): State<Arc<AppState>>) -> (StatusCode, HeaderMap, String) {
let mut headers = HeaderMap::new();
let mut static_assets_path = config.static_assets_path.clone();
let mut static_assets_path = (*app_state).config.static_assets_path.clone();

static_assets_path.push("app.js");

Expand All @@ -139,11 +137,9 @@ pub async fn js(
}
}

pub async fn purifyjs(
Extension(config): Extension<Arc<AppConfig>>
) -> (StatusCode, HeaderMap, String) {
pub async fn purifyjs(State(app_state): State<Arc<AppState>>) -> (StatusCode, HeaderMap, String) {
let mut headers = HeaderMap::new();
let mut static_assets_path = config.static_assets_path.clone();
let mut static_assets_path = (*app_state).config.static_assets_path.clone();

static_assets_path.push("purify.min.js");

Expand All @@ -161,11 +157,9 @@ pub async fn purifyjs(
}
}

pub async fn stylesheet(
Extension(config): Extension<Arc<AppConfig>>
) -> (StatusCode, HeaderMap, String) {
pub async fn stylesheet(State(app_state): State<Arc<AppState>>) -> (StatusCode, HeaderMap, String) {
let mut headers = HeaderMap::new();
let mut static_assets_path = config.static_assets_path.clone();
let mut static_assets_path = (*app_state).config.static_assets_path.clone();

static_assets_path.push("app.css");

Expand Down Expand Up @@ -226,33 +220,25 @@ fn parse_url_error(e: url::Error) -> (StatusCode, Json<Value>) {
),
url::Error::MissingScheme => (
StatusCode::BAD_REQUEST,
Json(
json!({
"message": "URL must have a scheme. Valid schemes are: https, or http.\ne.g https://example.com",
"type": "E008"
}),
),
Json(json!({
"message": "URL must have a scheme. Valid schemes are: https, or http.\ne.g https://example.com",
"type": "E008"
})),
),
url::Error::UnsupportedScheme => (
StatusCode::BAD_REQUEST,
Json(
json!({
"message": "Unsupported scheme. Acceptable schemes are: https, or http.\ne.g https://example.com",
"type": "E009"
}),
),
Json(json!({
"message": "Unsupported scheme. Acceptable schemes are: https, or http.\ne.g https://example.com",
"type": "E009"
})),
),
url::Error::MissingHost => (
StatusCode::BAD_REQUEST,
Json(
json!({"message": "URL host does not exist, or is invalid.", "type": "E010"}),
),
Json(json!({"message": "URL host does not exist, or is invalid.", "type": "E010"})),
),
url::Error::MissingPath => (
StatusCode::BAD_REQUEST,
Json(
json!({"message": "URL path does not exist, or is invalid.", "type": "E011"}),
),
Json(json!({"message": "URL path does not exist, or is invalid.", "type": "E011"})),
),
}
}
1 change: 1 addition & 0 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use postgres_native_tls::MakeTlsConnector;
use std::{fmt, io};
use tokio_postgres::NoTls;

#[derive(Clone)]
pub struct Handle {
pub pool: Pool,
}
Expand Down
Loading

0 comments on commit 225d56c

Please sign in to comment.