+ Clearer logging from the json api

* Renamed db helper function to be (debatably) more clear in its intentions
	That function and everything in that module is quickly become awful however

+ Adding some notes for later db-lib development
This commit is contained in:
shockrah 2021-03-24 01:43:52 -07:00
parent a1f86fdf6e
commit 52fab01119
5 changed files with 42 additions and 11 deletions

1
json-api/Cargo.lock generated
View File

@ -353,6 +353,7 @@ name = "db"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"mysql_async", "mysql_async",
"rand 0.8.3",
"serde", "serde",
"tokio 1.4.0", "tokio 1.4.0",
] ]

View File

@ -45,6 +45,7 @@ pub struct Message {
pub channel_id: UBigInt pub channel_id: UBigInt
} }
// Same EXCEPT for the fact that this has the name tacked on to it
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
pub struct UserMessage { pub struct UserMessage {
pub id: UBigInt, pub id: UBigInt,

View File

@ -21,7 +21,29 @@ const MAX_MESSAGES: u64 = 1000;
impl Message { impl Message {
fn send_verify_error(res: Result<QueryResult<Conn, BinaryProtocol>, SqlError> ) -> Result<Response<Self>, SqlError> { fn new(id: u64, time: i64, content: &str, content_type: &str, uid: u64, cid: u64) -> Self {
// Here for convenience pretty straight forward, copying at the last second
Message {
id,
time,
content: content.into(),
content_type: content_type.into(),
author_id: uid,
channel_id: cid
}
}
fn message_passthrough_no_err(res: Result<QueryResult<Conn, BinaryProtocol>, SqlError>, passthrough: Self)
-> Result<Response<Self>, SqlError> {
/* You shouldn't have cum here.webm
* Basically sending messages with mysql is kinda painful so we
* do some special error checking by hand to see if
* a message was sent to an existing channel.
* The whole point of this is to avoid sending back a 500 to user clients
* which may cause confusing error handling in userland. This means we have
* confusing error handling on the server side but one of the parties has to
* do this stupid check so fuck it at least its mostly pointers anyway
*/
if let Err(e) = res { if let Err(e) = res {
return match e { return match e {
SqlError::Server(err) => { SqlError::Server(err) => {
@ -38,7 +60,7 @@ impl Message {
} }
// all good response // all good response
else { else {
return Ok(Response::Empty); return Ok(Response::Row(passthrough));
} }
} }
@ -70,10 +92,18 @@ impl Message {
"author" => uid, "author" => uid,
"channel" => cid "channel" => cid
}).await; }).await;
Self::send_verify_error(res) let msg = Message::new(id, now, content, content_type, uid, cid);
Self::message_passthrough_no_err(res, msg)
} }
}, },
_ => { _ => {
/*
* Amazing hardcoded limit on binary content_length
* TODO: make this not hardcoded
* This really should be configurable by someone somewhere
* The best way of doing this honestly it probably through some kind of lazy static
* we can set an env var from the cli frontend for that lz_static to read
*/
if content.len() > 10_000_000 { if content.len() > 10_000_000 {
Ok(Response::RestrictedInput("Large data not allowed".into())) Ok(Response::RestrictedInput("Large data not allowed".into()))
} else { } else {
@ -95,7 +125,8 @@ impl Message {
"author" => uid, "author" => uid,
"channel" => cid "channel" => cid
}).await; }).await;
if let Ok(ret) = Self::send_verify_error(res) { let msg = Message::new(id, now, content, content_type, uid, cid);
if let Ok(ret) = Self::message_passthrough_no_err(res, msg) {
// now save the data to disk // now save the data to disk
match fs::File::create(content_ref).await { match fs::File::create(content_ref).await {
Ok(mut file) => { Ok(mut file) => {

View File

@ -63,7 +63,7 @@ async fn route_dispatcher(
const GET: &Method = &Method::GET; const GET: &Method = &Method::GET;
const POST: &Method = &Method::POST; const POST: &Method = &Method::POST;
const DELETE: &Method = &Method::DELETE; const DELETE: &Method = &Method::DELETE;
println!("{}: {}", meth, path); println!("[INFO] {}: {}", meth, path);
match (meth, path) { match (meth, path) {
/* INVITES */ /* INVITES */
(POST, routes::INVITE_CREATE) => invites::create(pool, resp, params).await, (POST, routes::INVITE_CREATE) => invites::create(pool, resp, params).await,
@ -88,7 +88,7 @@ async fn route_dispatcher(
/* META ROUTE */ /* META ROUTE */
(GET, routes::META) => meta::server_meta(resp).await, (GET, routes::META) => meta::server_meta(resp).await,
_ => { _ => {
println!("\tNOT FOUND: {}: {}", meth, path); println!("[INFO]\tNOT FOUND: {}: {}", meth, path);
*resp.status_mut() = StatusCode::NOT_FOUND *resp.status_mut() = StatusCode::NOT_FOUND
} }
} }
@ -116,11 +116,10 @@ async fn main_responder(request: Request<Body>) -> Result<Response<Body>, hyper:
route_dispatcher(&DB_POOL, &mut response, &method, path, body, params, headers).await; route_dispatcher(&DB_POOL, &mut response, &method, path, body, params, headers).await;
}, },
LoginValid => { LoginValid => {
println!("LoginValid");
auth::login_get_jwt(&DB_POOL, &mut response, params).await; auth::login_get_jwt(&DB_POOL, &mut response, params).await;
}, },
NoKey | BadKey => { NoKey | BadKey => {
println!("NoKey | BadKey"); println!("[DEBUG] NoKey | BadKey");
*response.status_mut() = StatusCode::UNAUTHORIZED; *response.status_mut() = StatusCode::UNAUTHORIZED;
}, },
ServerIssue(msg) => { ServerIssue(msg) => {
@ -130,7 +129,7 @@ async fn main_responder(request: Request<Body>) -> Result<Response<Body>, hyper:
} }
} }
else { else {
println!("\tPARSER: Parameter parsing failed"); println!("[INFO] PARSER: Parameter parsing failed");
*response.status_mut() = StatusCode::BAD_REQUEST; *response.status_mut() = StatusCode::BAD_REQUEST;
} }
Ok(response) Ok(response)
@ -143,7 +142,7 @@ async fn shutdown_signal() {
} }
async fn start_server(ecode: u16, port: u16) -> u16 { async fn start_server(ecode: u16, port: u16) -> u16 {
println!("Servering on localhost:{}", port); println!("[INFO] HTTP listening on localhost:{}", port);
let addr = SocketAddr::from(([127,0,0,1], port)); let addr = SocketAddr::from(([127,0,0,1], port));
let service = make_service_fn(|_conn| async { let service = make_service_fn(|_conn| async {
Ok::<_, Infallible>(service_fn(main_responder)) Ok::<_, Infallible>(service_fn(main_responder))

View File

@ -68,7 +68,6 @@ pub async fn send_message(pool: &Pool, response: &mut Response<Body>, body: Body
let uid = qs_param!(params, "id", u64).unwrap(); let uid = qs_param!(params, "id", u64).unwrap();
let ctype: Option<&str> = match headers.get("Content-Type") { let ctype: Option<&str> = match headers.get("Content-Type") {
Some(hval) => { Some(hval) => {
println!("{:?}", hval);
match hval.to_str() { match hval.to_str() {
Ok(s) => Some(s), Ok(s) => Some(s),
_ => None _ => None