Skip to content

Commit

Permalink
add app w/ brotli support
Browse files Browse the repository at this point in the history
  • Loading branch information
stackdump committed Mar 8, 2024
1 parent b8f7401 commit 8c1ea00
Show file tree
Hide file tree
Showing 27 changed files with 452 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ use std::sync::Mutex;
use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::{IntoResponse, Redirect, Response},
response::{Html, IntoResponse, Redirect, Response},
Router,
routing::get,
};
use clap::Parser;
use include_dir::{Dir, include_dir};
use pflow_metamodel::compression::unzip_encoded;
use pflow_metamodel::oid;
use pflow_metamodel::petri_net::PetriNet;
Expand Down Expand Up @@ -160,13 +161,30 @@ async fn index_handler(
return index_response(zblob.ipfs_cid, zblob.base64_zipped).into_response();
}

const STATIC_DIR: Dir = include_dir!("static");
async fn serve_static(filepath: Path<String>) -> impl IntoResponse {
let filepath = if filepath.as_str().is_empty() {
"index.html".to_string()
} else {
(*filepath).clone()
};

tracing::info!("Serving static file: {:?}", filepath);

match STATIC_DIR.get_file(&filepath) {
Some(file) => Html::<axum::body::Body>(file.contents_utf8().unwrap().into()),
None => Html::<axum::body::Body>("404 Not Found".into()),
}
}

pub fn app() -> Router {
let store = Storage::new("pflow.db").unwrap();
store.create_tables().unwrap();
let state: Arc<Mutex<Storage>> = Arc::new(Mutex::new(store));

// Build route service
Router::new()
.route("/p/:filepath", get(serve_static)) // serve static files
.route("/img/:ipfs_cid.svg", get(img_handler))
.route("/src/:ipfs_cid.json", get(src_handler))
.route("/p/:ipfs_cid/", get(model_handler))
Expand Down
121 changes: 121 additions & 0 deletions src/server.rs_
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
use std::{
collections::HashMap,
net::{Ipv4Addr, SocketAddr},
sync::{Arc, RwLock},
time::Duration,
};

use axum::{
body::Bytes,
extract::{Path, State},
http::{header, HeaderValue, StatusCode},
response::{Html, IntoResponse, Redirect},
Router,
routing::get,
};
use axum::routing::post;
use clap::Parser;
use include_dir::{Dir, include_dir};
use tokio::net::TcpListener;
use tower::ServiceBuilder;
use tower_http::{
LatencyUnit,
ServiceBuilderExt,
timeout::TimeoutLayer, trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer},
};

/// Simple key/value store with an HTTP API
#[derive(Debug, Parser)]
struct Config {
/// The port to listen on
#[clap(short = 'p', long, default_value = "3000")]
port: u16,
}

#[derive(Clone, Debug)]
struct AppState {
db: Arc<RwLock<HashMap<String, Bytes>>>,
}

#[tokio::main]
async fn main() {
// Setup tracing
tracing_subscriber::fmt::init();

// Parse command line arguments
let config = Config::parse();

// Run our service
let addr = SocketAddr::from((Ipv4Addr::UNSPECIFIED, config.port));
tracing::info!("Listening on {}", addr);
axum::serve(
TcpListener::bind(addr).await.expect("bind error"),
app().into_make_service(),
)
.await
.expect("server error");
}

const STATIC_DIR: Dir = include_dir!("static");

async fn serve_static(filepath: Path<String>) -> impl IntoResponse {
let filepath = if filepath.as_str().is_empty() {
"index.html".to_string()
} else {
(*filepath).clone()
};

tracing::info!("Serving static file: {:?}", filepath);

match STATIC_DIR.get_file(&filepath) {
Some(file) => Html::<axum::body::Body>(file.contents_utf8().unwrap().into()),
None => Html::<axum::body::Body>("404 Not Found".into()),
}
}

pub(crate) fn app() -> Router {
// Build our database for holding the key/value pairs
let state = AppState {
db: Arc::new(RwLock::new(HashMap::new())),
};

let sensitive_headers: Arc<[_]> = vec![header::AUTHORIZATION, header::COOKIE].into();

// Build our middleware stack
let middleware = ServiceBuilder::new()
.layer(
TraceLayer::new_for_http()
.on_body_chunk(|chunk: &Bytes, latency: Duration, _: &tracing::Span| {
tracing::trace!(size_bytes = chunk.len(), latency = ?latency, "sending body chunk")
})
.make_span_with(DefaultMakeSpan::new().include_headers(true))
.on_response(DefaultOnResponse::new().include_headers(true).latency_unit(LatencyUnit::Micros)),
)
.layer(TimeoutLayer::new(Duration::from_secs(10)));

// Build route service
Router::new()
.route("/get/:key", get(get_key))
.route("/set/:key", post(set_key))
.route("/p/:filepath", get(serve_static)) // serve static files
.route("/p/", get(|| serve_static(Path("index.html".to_string())))) // serve static files with default path
.route("/p", get(|| async { Redirect::to("/p/") })) // redirect /p to /p/
.route("/", get(|| async { Redirect::to("/p/") })) // redirect / to /p/
.layer(middleware)
.with_state(state)
}

async fn get_key(path: Path<String>, state: State<AppState>) -> impl IntoResponse {
let state = state.db.read().unwrap();

if let Some(value) = state.get(&*path).cloned() {
Ok(value)
} else {
Err(StatusCode::NOT_FOUND)
}
}

async fn set_key(Path(path): Path<String>, state: State<AppState>, value: Bytes) {
let mut state = state.db.write().unwrap();
state.insert(path, value);
}
24 changes: 24 additions & 0 deletions static/UNLICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <https://unlicense.org>
Binary file added static/android-chrome-192x192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/android-chrome-256x256.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/apple-touch-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 14 additions & 0 deletions static/asset-manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"files": {
"main.css": "/p/static/css/main.31cba778.css",
"main.js": "/p/static/js/main.08efb24d.js",
"static/media/brotli_wasm_bg.wasm": "/p/static/media/brotli_wasm_bg.0679dcc7b534fcfcac29.wasm",
"index.html": "/p/index.html",
"main.31cba778.css.map": "/p/static/css/main.31cba778.css.map",
"main.08efb24d.js.map": "/p/static/js/main.08efb24d.js.map"
},
"entrypoints": [
"static/css/main.31cba778.css",
"static/js/main.08efb24d.js"
]
}
9 changes: 9 additions & 0 deletions static/browserconfig.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square150x150logo src="/mstile-150x150.png"/>
<TileColor>#da532c</TileColor>
</tile>
</msapplication>
</browserconfig>
Binary file added static/favicon-16x16.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/favicon-32x32.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/favicon.ico
Binary file not shown.
1 change: 1 addition & 0 deletions static/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<!doctype html><html lang="en"><head><title>pflow | metamodel explorer</title><meta charset="utf-8"/><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="icon" href="/p/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><link rel="apple-touch-icon" href="/p/logo192.png"/><link rel="manifest" href="/p/manifest.json"/><script defer="defer" src="/p/static/js/main.08efb24d.js"></script><link href="/p/static/css/main.31cba778.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>
1 change: 1 addition & 0 deletions static/logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/logo192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/logo512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions static/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"short_name": "pflow.xyz",
"name": "pflow.xyz",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
Binary file added static/mstile-150x150.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions static/robots.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
40 changes: 40 additions & 0 deletions static/safari-pinned-tab.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions static/share.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"cid": "QmeV1kwh3333bsnT6YRfdCRrSgUPngKmAhhTa4RrqYPbKT"
}
19 changes: 19 additions & 0 deletions static/site.webmanifest
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "",
"short_name": "",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-256x256.png",
"sizes": "256x256",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}
Loading

0 comments on commit 8c1ea00

Please sign in to comment.