Skip to content

Commit

Permalink
demo app
Browse files Browse the repository at this point in the history
  • Loading branch information
levkk committed Oct 29, 2024
1 parent 03ed3fc commit 055f591
Show file tree
Hide file tree
Showing 15 changed files with 141 additions and 33 deletions.
9 changes: 9 additions & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ members = [
"rwf-cli",
"rwf-macros",
"rwf-tests",
"examples/django",
"examples/django", "examples/request-tracking",
]
11 changes: 11 additions & 0 deletions examples/request-tracking/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "request-tracking"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rwf = { path = "../../rwf" }
tokio = { version = "1", features = ["full"] }
rand = "0.8"
Empty file.
6 changes: 6 additions & 0 deletions examples/request-tracking/rwf.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[general]
track_requests = true
log_queries = true

[database]
name = "rwf_request_tracking"
1 change: 1 addition & 0 deletions examples/request-tracking/src/controllers/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

37 changes: 37 additions & 0 deletions examples/request-tracking/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
mod controllers;
mod models;

use rand::Rng;
use rwf::{http, prelude::*, Server};

#[derive(Default)]
struct Index;

#[async_trait]
impl Controller for Index {
async fn handle(&self, request: &Request) -> Result<Response, Error> {
let ok = rand::thread_rng().gen::<bool>();

if ok {
// This is tracked.
Ok(Response::new().html("
<h2>All requests are tracked</h2>
<p>To view requests, connect to the <code>rwf_request_tracking</code> database and run:</p>
<code>SELECT * FROM rwf_requests ORDER BY id</code>
"))
} else {
// This is tracked also.
Err(Error::HttpError(Box::new(http::Error::MissingParameter)))
}
}
}

#[tokio::main]
async fn main() -> Result<(), http::Error> {
Logger::init();
Migrations::migrate().await?;

Server::new(vec![route!("/" => Index)])
.launch("0.0.0.0:8000")
.await
}
1 change: 1 addition & 0 deletions examples/request-tracking/src/models/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Empty file.
18 changes: 18 additions & 0 deletions rwf-cli/src/setup.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::path::Path;
use tokio::fs::{create_dir_all, read_to_string, File};
use tokio::process::Command;

use crate::logging::created;
use rwf::colors::MaybeColorize;
Expand Down Expand Up @@ -62,4 +63,21 @@ pub async fn setup() {
break;
}
}

// Add rwf dependencies
Command::new("cargo")
.arg("add")
.arg("tokio@1")
.arg("--features")
.arg("full")
.status()
.await
.unwrap();

Command::new("cargo")
.arg("add")
.arg("rwf")
.status()
.await
.unwrap();
}
9 changes: 9 additions & 0 deletions rwf/src/controller/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,15 @@ impl SessionId {
}
}

impl std::fmt::Display for SessionId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SessionId::Authenticated(id) => write!(f, "{}", id),
SessionId::Guest(id) => write!(f, "{}", id),
}
}
}

impl Default for SessionId {
fn default() -> Self {
use rand::{distributions::Alphanumeric, thread_rng, Rng};
Expand Down
36 changes: 29 additions & 7 deletions rwf/src/controller/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use crate::config::get_config;

use tokio::select;
use tokio::time::{interval, timeout};
use tracing::{debug, info};
use tracing::{debug, error, info};

use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -86,8 +86,6 @@ pub trait Controller: Sync + Send {
return auth.auth().denied(&request).await;
}

let no_session = request.session().is_none();

let outcome = self.middleware().handle_request(request).await?;
let response = match outcome {
(Outcome::Forward(request), executed) => match self.handle(&request).await {
Expand All @@ -96,7 +94,29 @@ pub trait Controller: Sync + Send {
.handle_response(&request, response.from_request(&request)?, executed)
.await?
}
Err(err) => return Err(err),
Err(err) => {
error!("{}", err);

let response = match err {
Error::HttpError(err) => match err.code() {
400 => Response::bad_request(),
403 => Response::forbidden(),
_ => Response::internal_error(err),
},

Error::ViewError(err) => Response::internal_error_pretty(
"Template error",
err.to_string().as_str(),
),

err => Response::internal_error(err),
};

// Run the middleware chain on the response anyway.
self.middleware()
.handle_response(&request, response, executed)
.await?
}
},
(Outcome::Stop(request, response), executed) => {
self.middleware()
Expand Down Expand Up @@ -447,7 +467,7 @@ pub trait WebsocketController: Controller {
loop {
select! {
_ = check.tick() => {
debug!("{} check session \"{:?}\"", "websocket".purple(), session_id);
debug!("{} check session \"{}\"", "websocket".purple(), session_id);

let closed = match timeout(
config.websocket.ping_timeout.unsigned_abs(),
Expand All @@ -467,7 +487,9 @@ pub trait WebsocketController: Controller {
message = receiver.recv() => {
match message {
Ok(message) => {
debug!("sending {:?} to {:?}", message, receiver.session_id());
debug!("{} sending {:?} to session \"{}\"",
"websocket".purple(),
message, receiver.session_id());
message.send(&mut stream).await?;
}

Expand All @@ -485,7 +507,7 @@ pub trait WebsocketController: Controller {
let frame = frame?;

if frame.is_pong() {
debug!("{} session \"{:?}\" is alive", "websocket".purple(), session_id);
debug!("{} session \"{}\" is alive", "websocket".purple(), session_id);
lost_pings -= 1;

// Protect against weird clients.
Expand Down
18 changes: 1 addition & 17 deletions rwf/src/http/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
//!
//! The server is using Tokio, so it can support millions of concurrent clients.
use super::{Error, Handler, Request, Response, Router};
use crate::controller::Error as ControllerError;

use crate::colors::MaybeColorize;

Expand Down Expand Up @@ -125,22 +124,7 @@ impl Server {
Ok(response) => response,
Err(err) => {
error!("{}", err);
match err {
ControllerError::HttpError(err) => match err.code() {
400 => Response::bad_request(),
403 => Response::forbidden(),
_ => Response::internal_error(err),
},

ControllerError::ViewError(err) => {
Response::internal_error_pretty(
"Template error",
err.to_string().as_str(),
)
}

err => Response::internal_error(err),
}
Response::internal_error(err)
}
};

Expand Down
15 changes: 12 additions & 3 deletions rwf/src/model/migrations/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,18 @@ impl Migrations {
while let Some(dir_entry) = dir_entries.next_entry().await? {
let metadata = dir_entry.metadata().await?;
if metadata.is_file() {
let file = MigrationFile::parse(
dir_entry.file_name().to_str().expect("migration OsString"),
)?;
let file_name = dir_entry
.file_name()
.to_str()
.expect("migration OsString")
.to_string();

// Skip hidden files
if file_name.starts_with(".") {
continue;
}

let file = MigrationFile::parse(&file_name)?;
let entry = checks
.entry(file.name.clone())
.or_insert_with(Check::default);
Expand Down
11 changes: 6 additions & 5 deletions rwf/src/model/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ impl<T: Model> Query<T> {
let result = match result {
Ok(result) => result,
Err(err) => {
self.log_error();
self.log_error(&err);
return Err(err);
}
};
Expand All @@ -542,7 +542,7 @@ impl<T: Model> Query<T> {
match result {
Ok(rows) => Ok(rows),
Err(err) => {
self.log_error();
self.log_error(&err);
Err(err)
}
}
Expand Down Expand Up @@ -659,12 +659,13 @@ impl<T: Model> Query<T> {
);
}

fn log_error(&self) {
fn log_error(&self, err: &Error) {
error!(
"{} {} {}",
"{} {} {} {}",
Self::type_name().green(),
self.action().purple(),
self.to_sql()
self.to_sql(),
err,
)
}
}
Expand Down

0 comments on commit 055f591

Please sign in to comment.