-
Notifications
You must be signed in to change notification settings - Fork 2
/
lib.rs
176 lines (160 loc) · 5.31 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
//! These docs are focused on technical details. For tutorials check out [prest.blog](https://prest.blog)
#![doc(html_favicon_url = "https://prest.blog/favicon.ico")]
// for macro-generated code inside prest itself
pub(crate) use crate as prest;
pub use serde;
pub use serde_derive::{Deserialize, Serialize};
pub use anyhow::{anyhow, bail, Result as AnyhowResult};
pub use async_trait::async_trait;
pub use axum::{
self,
body::{Body, HttpBody},
error_handling::{HandleError, HandleErrorLayer},
extract::{
self, Extension, Form, FromRequest, FromRequestParts, Host, MatchedPath, NestedPath,
OriginalUri, Path, Query, Request,
},
http::{self, header, HeaderMap, HeaderValue, Method, StatusCode, Uri},
middleware::{from_extractor, from_extractor_with_state, from_fn, from_fn_with_state, Next},
response::{
AppendHeaders, ErrorResponse, Html, IntoResponse, IntoResponseParts, Json, Redirect,
Response, ResponseParts,
},
routing::{any, delete, get, patch, post, put},
Router,
};
pub use axum_htmx::{
HxBoosted, HxCurrentUrl, HxEvent, HxHistoryRestoreRequest, HxLocation, HxPrompt, HxPushUrl,
HxRedirect, HxRefresh, HxReplaceUrl, HxRequest, HxReselect, HxResponseTrigger, HxReswap,
HxRetarget, HxTarget, HxTrigger, HxTriggerName, SwapOption,
};
pub use axum_valid::*;
pub use futures::{
executor::block_on as await_fut,
stream::{self, Stream, StreamExt, TryStreamExt},
};
pub use serde_json::{from_str as from_json_str, json, to_string as to_json_string};
pub use std::sync::LazyLock as Lazy;
pub use std::{convert::Infallible, env, sync::Arc};
pub use toml::{Table as TomlTable, Value as TomlValue};
pub use tower::{self, BoxError, Layer, Service, ServiceBuilder};
pub use tracing::{debug, error, info, trace, warn};
pub use uuid::Uuid;
mod config;
pub use config::*;
#[cfg(feature = "db")]
mod db;
#[cfg(feature = "db")]
pub use db::*;
#[cfg(feature = "embed")]
mod embed;
#[cfg(feature = "embed")]
pub use embed::*;
#[cfg(feature = "html")]
mod html;
#[cfg(feature = "html")]
pub use html::*;
#[cfg(feature = "html")]
/// Default doctype for HTML
pub const DOCTYPE: PreEscaped<&'static str> = PreEscaped("<!DOCTYPE html>");
/// Default favicon
pub static FAVICON: &[u8] = include_bytes!("favicon.ico");
#[cfg(host)]
mod host;
#[cfg(host)]
pub use host::*;
#[cfg(sw)]
mod service_worker;
#[cfg(sw)]
pub use service_worker::*;
// --- GENERAL UTILS ---
/// Starting point for prest apps that performs basic setup
#[macro_export]
macro_rules! init {
($(tables $($table:ident),+)?) => {
{
let manifest = include_str!("../Cargo.toml");
#[cfg(not(target_arch = "wasm32"))]
let ___ = prest::dotenv();
prest::init_tracing_subscriber();
let config = APP_CONFIG.init(manifest, env!("CARGO_MANIFEST_DIR"));
prest::DB.init();
$(
$( $table::prepare_table(); )+
)?
let _ = *prest::RT;
prest::info!("Initialized {} v{}", config.name, config.version);
}
};
}
/// A little helper to init router and route in a single call to improve formatting
pub fn route<S: Clone + Send + Sync + 'static>(
path: &str,
method_router: axum::routing::method_routing::MethodRouter<S>,
) -> Router<S> {
Router::<S>::new().route(path, method_router)
}
/// Default javascript code that registers a service worker from `/sw.js`
pub const REGISTER_SW_SNIPPET: &str =
"if ('serviceWorker' in navigator) navigator.serviceWorker.register('sw.js', {type: 'module'});";
/// Returns whether PWA will be built with current configs
pub fn is_pwa() -> bool {
#[cfg(sw)]
return true;
#[cfg(host)]
match cfg!(debug) {
true => std::env::var("PWA").map_or(false, |v| v == "debug"),
false => std::env::var("PWA").map_or(true, |v| v == "release"),
}
}
#[macro_export]
macro_rules! include_html {
($path: tt) => {
PreEscaped(include_str!($path))
};
}
/// Basic Result alias with [`enum@prest::Error`]`
pub type Result<T = (), E = Error> = std::result::Result<T, E>;
use thiserror::Error;
/// Error type used across prest codebase
#[derive(Error, Debug)]
pub enum Error {
#[error("Internal")]
Internal,
#[error("Unauthorized")]
Unauthorized,
#[error("Not found")]
NotFound,
#[error(transparent)]
Env(#[from] std::env::VarError),
#[cfg(all(host, feature = "auth"))]
#[error(transparent)]
Session(#[from] tower_sessions::session_store::Error),
#[cfg(all(host, feature = "auth"))]
#[error(transparent)]
Auth(#[from] AuthError),
#[cfg(all(host, feature = "auth"))]
#[error(transparent)]
OAuth(#[from] openidconnect::ClaimsVerificationError),
#[cfg(feature = "db")]
#[error(transparent)]
GlueSQL(#[from] gluesql::core::error::Error),
#[error(transparent)]
IO(#[from] std::io::Error),
#[error(transparent)]
Anyhow(#[from] anyhow::Error),
#[error(transparent)]
FormRejection(#[from] axum::extract::rejection::FormRejection),
#[cfg(host)]
#[error(transparent)]
RuSSH(#[from] russh::Error),
#[cfg(host)]
#[error(transparent)]
RuSFTP(#[from] russh_sftp::client::error::Error),
}
impl IntoResponse for Error {
fn into_response(self) -> Response {
error!("{self}");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
}
}