Compare commits
10 Commits
4fbbd30c4b
...
9e16684ac9
| Author | SHA1 | Date | |
|---|---|---|---|
| 9e16684ac9 | |||
| ae257f949d | |||
| fd7d85edbb | |||
| 5502013b76 | |||
| cb7526dd45 | |||
| ce3400e353 | |||
| 80124af836 | |||
| e7c7d9f270 | |||
| ea825c89eb | |||
| 57a09461f1 |
26
Cargo.lock
generated
26
Cargo.lock
generated
@ -90,9 +90,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "axum"
|
name = "axum"
|
||||||
version = "0.8.3"
|
version = "0.8.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "de45108900e1f9b9242f7f2e254aa3e2c029c921c258fe9e6b4217eeebd54288"
|
checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum-core",
|
"axum-core",
|
||||||
"bytes",
|
"bytes",
|
||||||
@ -177,9 +177,9 @@ checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cc"
|
name = "cc"
|
||||||
version = "1.2.19"
|
version = "1.2.21"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8e3a13707ac958681c13b39b458c073d0d9bc8a22cb1b2f4c8e55eb72c13f362"
|
checksum = "8691782945451c1c383942c4874dbe63814f61cb57ef773cda2972682b7bb3c0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"shlex",
|
"shlex",
|
||||||
]
|
]
|
||||||
@ -192,9 +192,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "chrono"
|
name = "chrono"
|
||||||
version = "0.4.40"
|
version = "0.4.41"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1a7964611d71df112cb1730f2ee67324fcf4d0fc6606acbbe9bfe06df124637c"
|
checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"android-tzdata",
|
"android-tzdata",
|
||||||
"iana-time-zone",
|
"iana-time-zone",
|
||||||
@ -555,6 +555,8 @@ dependencies = [
|
|||||||
"axum",
|
"axum",
|
||||||
"chrono",
|
"chrono",
|
||||||
"clap",
|
"clap",
|
||||||
|
"http-body-util",
|
||||||
|
"serde_json",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-cookies",
|
"tower-cookies",
|
||||||
@ -664,9 +666,9 @@ checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "redox_syscall"
|
name = "redox_syscall"
|
||||||
version = "0.5.11"
|
version = "0.5.12"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d2f103c6d277498fbceb16e84d317e2a400f160f46904d5f5410848c829511a3"
|
checksum = "928fca9cf2aa042393a8325b9ead81d2f0df4cb12e1e24cef072922ccd99c5af"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags",
|
"bitflags",
|
||||||
]
|
]
|
||||||
@ -797,9 +799,9 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "2.0.100"
|
version = "2.0.101"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0"
|
checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@ -845,9 +847,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tokio"
|
name = "tokio"
|
||||||
version = "1.44.2"
|
version = "1.45.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48"
|
checksum = "2513ca694ef9ede0fb23fe71a4ee4107cb102b9dc1930f6d0fd77aae068ae165"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"backtrace",
|
"backtrace",
|
||||||
"bytes",
|
"bytes",
|
||||||
|
|||||||
@ -9,9 +9,11 @@ edition = "2021"
|
|||||||
axum = ">=0.8.0"
|
axum = ">=0.8.0"
|
||||||
chrono = { version = ">=0.4.40", features = ["now"] }
|
chrono = { version = ">=0.4.40", features = ["now"] }
|
||||||
clap = { version = ">=4.5.1", features = ["derive"] }
|
clap = { version = ">=4.5.1", features = ["derive"] }
|
||||||
|
serde_json = ">=1.0.140"
|
||||||
tokio = { version = ">=1.36.0", features = ["full"] }
|
tokio = { version = ">=1.36.0", features = ["full"] }
|
||||||
tower-cookies = ">=0.11.0"
|
tower-cookies = ">=0.11.0"
|
||||||
uuid = { version = ">=1.8.0", features = ["v4"] }
|
uuid = { version = ">=1.8.0", features = ["v4"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
http-body-util = ">=0.1.3"
|
||||||
tower = { version = ">=0.5.2", features = ["util"] }
|
tower = { version = ">=0.5.2", features = ["util"] }
|
||||||
|
|||||||
@ -9,7 +9,12 @@ use std::{
|
|||||||
};
|
};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
const RESPONS_TO: [MsgType; 4] = [MsgType::ActionOk, MsgType::Document, MsgType::Error, MsgType::SessionValidated];
|
const RESPONS_TO: [MsgType; 4] = [
|
||||||
|
MsgType::ActionOk,
|
||||||
|
MsgType::Document,
|
||||||
|
MsgType::Error,
|
||||||
|
MsgType::SessionValidated,
|
||||||
|
];
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ClientChannel {
|
pub struct ClientChannel {
|
||||||
|
|||||||
176
src/document.rs
176
src/document.rs
@ -2,6 +2,7 @@ use crate::{
|
|||||||
queue::{Message, MsgType, Queue},
|
queue::{Message, MsgType, Queue},
|
||||||
ActionType, ErrorType,
|
ActionType, ErrorType,
|
||||||
};
|
};
|
||||||
|
use serde_json::Value;
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
sync::mpsc::{channel, Receiver},
|
sync::mpsc::{channel, Receiver},
|
||||||
@ -40,20 +41,59 @@ impl Document {
|
|||||||
loop {
|
loop {
|
||||||
let msg = self.rx.recv().unwrap();
|
let msg = self.rx.recv().unwrap();
|
||||||
match msg.get_data("action") {
|
match msg.get_data("action") {
|
||||||
Some(action) => match action.to_action().unwrap() {
|
Some(action_field) => {
|
||||||
ActionType::Add => self.add(msg),
|
let action = action_field.to_action().unwrap();
|
||||||
|
match action {
|
||||||
|
ActionType::Add | ActionType::Update => self.add(action, msg),
|
||||||
_ => self.get(msg),
|
_ => self.get(msg),
|
||||||
},
|
}
|
||||||
|
}
|
||||||
None => self.get(msg),
|
None => self.get(msg),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add(&mut self, msg: Message) {
|
fn add(&mut self, action: ActionType, msg: Message) {
|
||||||
let name = msg.get_data("name").unwrap().to_string();
|
let name = msg.get_data("name").unwrap().to_string();
|
||||||
let doc = msg.get_data("doc").unwrap().to_string();
|
match self.data.get(&name) {
|
||||||
self.data.insert(name, doc);
|
Some(_) => match action {
|
||||||
self.queue.send(msg.reply(MsgType::ActionOk)).unwrap();
|
ActionType::Add => {
|
||||||
|
self.queue
|
||||||
|
.send(msg.reply_with_error(ErrorType::DocumentAlreadyExists))
|
||||||
|
.unwrap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ActionType::Update => {}
|
||||||
|
_ => unreachable!("listen should prevent anything else"),
|
||||||
|
},
|
||||||
|
None => match action {
|
||||||
|
ActionType::Add => {}
|
||||||
|
ActionType::Update => {
|
||||||
|
self.queue
|
||||||
|
.send(msg.reply_with_error(ErrorType::DocumentNotFound))
|
||||||
|
.unwrap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_ => unreachable!("listen should prevent anything else"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
let doc: Value = match serde_json::from_str(&msg.get_data("doc").unwrap().to_string()) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(_) => {
|
||||||
|
self.queue
|
||||||
|
.send(msg.reply_with_error(ErrorType::DocumentInvalidRequest))
|
||||||
|
.unwrap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let reply = match doc["template"].as_str() {
|
||||||
|
Some(content) => {
|
||||||
|
self.data.insert(name, content.to_string());
|
||||||
|
msg.reply(MsgType::ActionOk)
|
||||||
|
}
|
||||||
|
None => msg.reply_with_error(ErrorType::DocumentInvalidRequest),
|
||||||
|
};
|
||||||
|
self.queue.send(reply).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get(&self, msg: Message) {
|
fn get(&self, msg: Message) {
|
||||||
@ -61,17 +101,13 @@ impl Document {
|
|||||||
Some(doc) => doc.to_string(),
|
Some(doc) => doc.to_string(),
|
||||||
None => "root".to_string(),
|
None => "root".to_string(),
|
||||||
};
|
};
|
||||||
let mut reply = match self.data.get(&name) {
|
let reply = match self.data.get(&name) {
|
||||||
Some(data) => {
|
Some(data) => {
|
||||||
let mut holder = msg.reply(MsgType::Document);
|
let mut holder = msg.reply(MsgType::Document);
|
||||||
holder.add_data("doc", data.clone());
|
holder.add_data("doc", data.clone());
|
||||||
holder
|
holder
|
||||||
},
|
|
||||||
None => {
|
|
||||||
let mut holder = msg.reply(MsgType::Error);
|
|
||||||
holder.add_data("error_type", ErrorType::DocumentNotFound);
|
|
||||||
holder
|
|
||||||
}
|
}
|
||||||
|
None => msg.reply_with_error(ErrorType::DocumentNotFound),
|
||||||
};
|
};
|
||||||
self.queue.send(reply).unwrap();
|
self.queue.send(reply).unwrap();
|
||||||
}
|
}
|
||||||
@ -80,6 +116,7 @@ impl Document {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub mod documents {
|
pub mod documents {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
@ -88,7 +125,10 @@ pub mod documents {
|
|||||||
fn setup_document() -> (Queue, Receiver<Message>) {
|
fn setup_document() -> (Queue, Receiver<Message>) {
|
||||||
let queue = Queue::new();
|
let queue = Queue::new();
|
||||||
let (tx, rx) = channel();
|
let (tx, rx) = channel();
|
||||||
queue.add(tx, [MsgType::ActionOk, MsgType::Document, MsgType::Error].to_vec());
|
queue.add(
|
||||||
|
tx,
|
||||||
|
[MsgType::ActionOk, MsgType::Document, MsgType::Error].to_vec(),
|
||||||
|
);
|
||||||
Document::start(queue.clone());
|
Document::start(queue.clone());
|
||||||
(queue, rx)
|
(queue, rx)
|
||||||
}
|
}
|
||||||
@ -134,10 +174,9 @@ pub mod documents {
|
|||||||
#[test]
|
#[test]
|
||||||
fn root_always_exists() {
|
fn root_always_exists() {
|
||||||
let (queue, rx) = setup_document();
|
let (queue, rx) = setup_document();
|
||||||
let name = format!("name-{}", Uuid::new_v4());
|
|
||||||
let mut msg = Message::new(MsgType::DocumentRequest);
|
let mut msg = Message::new(MsgType::DocumentRequest);
|
||||||
msg.add_data("name", "root");
|
msg.add_data("name", "root");
|
||||||
queue.send(msg);
|
queue.send(msg).unwrap();
|
||||||
let reply = rx.recv_timeout(TIMEOUT).unwrap();
|
let reply = rx.recv_timeout(TIMEOUT).unwrap();
|
||||||
match reply.get_msg_type() {
|
match reply.get_msg_type() {
|
||||||
MsgType::Document => {}
|
MsgType::Document => {}
|
||||||
@ -153,10 +192,13 @@ pub mod documents {
|
|||||||
let (queue, rx) = setup_document();
|
let (queue, rx) = setup_document();
|
||||||
let name = format!("name-{}", Uuid::new_v4());
|
let name = format!("name-{}", Uuid::new_v4());
|
||||||
let content = format!("content-{}", Uuid::new_v4());
|
let content = format!("content-{}", Uuid::new_v4());
|
||||||
|
let input = json!({
|
||||||
|
"template": content.clone()
|
||||||
|
});
|
||||||
let mut msg1 = Message::new(MsgType::DocumentRequest);
|
let mut msg1 = Message::new(MsgType::DocumentRequest);
|
||||||
msg1.add_data("name", name.clone());
|
msg1.add_data("name", name.clone());
|
||||||
msg1.add_data("action", ActionType::Add);
|
msg1.add_data("action", ActionType::Add);
|
||||||
msg1.add_data("doc", content.clone());
|
msg1.add_data("doc", input.to_string());
|
||||||
queue.send(msg1.clone()).unwrap();
|
queue.send(msg1.clone()).unwrap();
|
||||||
let reply1 = rx.recv_timeout(TIMEOUT).unwrap();
|
let reply1 = rx.recv_timeout(TIMEOUT).unwrap();
|
||||||
assert_eq!(reply1.get_id(), msg1.get_id());
|
assert_eq!(reply1.get_id(), msg1.get_id());
|
||||||
@ -182,4 +224,104 @@ pub mod documents {
|
|||||||
}
|
}
|
||||||
assert_eq!(reply2.get_data("doc").unwrap().to_string(), content);
|
assert_eq!(reply2.get_data("doc").unwrap().to_string(), content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_does_not_overwrite_existing() {
|
||||||
|
let (queue, rx) = setup_document();
|
||||||
|
let mut holder = Message::new(MsgType::DocumentRequest);
|
||||||
|
holder.add_data("name", "root");
|
||||||
|
holder.add_data("action", ActionType::Get);
|
||||||
|
queue.send(holder.clone()).unwrap();
|
||||||
|
let binding = rx.recv_timeout(TIMEOUT).unwrap();
|
||||||
|
let expected = binding.get_data("doc").unwrap();
|
||||||
|
let input = json!({
|
||||||
|
"template": format!("content-{}", Uuid::new_v4())
|
||||||
|
});
|
||||||
|
let mut msg = Message::new(MsgType::DocumentRequest);
|
||||||
|
msg.add_data("name", "root");
|
||||||
|
msg.add_data("action", ActionType::Add);
|
||||||
|
msg.add_data("doc", input.to_string());
|
||||||
|
queue.send(msg.clone()).unwrap();
|
||||||
|
let reply = rx.recv_timeout(TIMEOUT).unwrap();
|
||||||
|
assert_eq!(reply.get_id(), msg.get_id());
|
||||||
|
match reply.get_msg_type() {
|
||||||
|
MsgType::Error => {}
|
||||||
|
_ => unreachable!(
|
||||||
|
"got '{:?}': should have received document",
|
||||||
|
reply.get_msg_type()
|
||||||
|
),
|
||||||
|
}
|
||||||
|
match reply.get_data("error_type") {
|
||||||
|
Some(err) => match err.to_error_type().unwrap() {
|
||||||
|
ErrorType::DocumentAlreadyExists => {}
|
||||||
|
_ => unreachable!("got {:?}: should have been document not found'", err),
|
||||||
|
},
|
||||||
|
None => unreachable!("should contain error type"),
|
||||||
|
}
|
||||||
|
queue.send(holder).unwrap();
|
||||||
|
let binding = rx.recv_timeout(TIMEOUT).unwrap();
|
||||||
|
let result = binding.get_data("doc").unwrap();
|
||||||
|
assert_eq!(result.to_string(), expected.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_json() {
|
||||||
|
let inputs = ["Invalid json request.", "{}"];
|
||||||
|
let (queue, rx) = setup_document();
|
||||||
|
for input in inputs.into_iter() {
|
||||||
|
let mut msg = Message::new(MsgType::DocumentRequest);
|
||||||
|
msg.add_data("action", ActionType::Add);
|
||||||
|
msg.add_data("name", "doc");
|
||||||
|
msg.add_data("doc", input);
|
||||||
|
queue.send(msg.clone()).unwrap();
|
||||||
|
let reply = match rx.recv_timeout(TIMEOUT) {
|
||||||
|
Ok(data) => data,
|
||||||
|
Err(err) => {
|
||||||
|
assert!(false, "got '{}' with the following json: '{}'", err, input);
|
||||||
|
Message::new(MsgType::Error)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
assert_eq!(reply.get_id(), msg.get_id());
|
||||||
|
match reply.get_msg_type() {
|
||||||
|
MsgType::Error => {}
|
||||||
|
_ => unreachable!(
|
||||||
|
"got '{:?}': should have received document",
|
||||||
|
reply.get_msg_type()
|
||||||
|
),
|
||||||
|
}
|
||||||
|
match reply.get_data("error_type") {
|
||||||
|
Some(err) => match err.to_error_type().unwrap() {
|
||||||
|
ErrorType::DocumentInvalidRequest => {}
|
||||||
|
_ => unreachable!("got {:?}: should have been bad request'", err),
|
||||||
|
},
|
||||||
|
None => unreachable!("should contain error type"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn patch_nonexistant_page() {
|
||||||
|
let (queue, rx) = setup_document();
|
||||||
|
let input = json!({
|
||||||
|
"template": "Sothing here"
|
||||||
|
});
|
||||||
|
let mut msg = Message::new(MsgType::DocumentRequest);
|
||||||
|
msg.add_data("action", ActionType::Update);
|
||||||
|
msg.add_data("name", "something");
|
||||||
|
msg.add_data("doc", input.to_string());
|
||||||
|
queue.send(msg.clone()).unwrap();
|
||||||
|
let reply = rx.recv_timeout(TIMEOUT).unwrap();
|
||||||
|
assert_eq!(reply.get_id(), msg.get_id());
|
||||||
|
match reply.get_msg_type() {
|
||||||
|
MsgType::Error => {}
|
||||||
|
_ => unreachable!("got {:?}: shoud have been error", reply.get_msg_type()),
|
||||||
|
}
|
||||||
|
match reply.get_data("error_type") {
|
||||||
|
Some(err) => match err.to_error_type().unwrap() {
|
||||||
|
ErrorType::DocumentNotFound => {}
|
||||||
|
_ => unreachable!("got {:?}: should have been document not found'", err),
|
||||||
|
},
|
||||||
|
None => unreachable!("should contain error type"),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
17
src/field.rs
17
src/field.rs
@ -3,6 +3,15 @@ use chrono::prelude::*;
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
enum FieldType {
|
||||||
|
Action,
|
||||||
|
DateTime,
|
||||||
|
Error,
|
||||||
|
StaticString,
|
||||||
|
Uuid,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub enum Field {
|
pub enum Field {
|
||||||
Action(ActionType),
|
Action(ActionType),
|
||||||
@ -233,7 +242,8 @@ mod fields {
|
|||||||
let field: Field = err.into();
|
let field: Field = err.into();
|
||||||
match field {
|
match field {
|
||||||
Field::ErrorType(data) => match data {
|
Field::ErrorType(data) => match data {
|
||||||
ErrorType::DocumentNotFound => {} //_ => unreachable!("got {:?}: should have been Document not found", data),
|
ErrorType::DocumentNotFound => {}
|
||||||
|
_ => unreachable!("got {:?}: should have been Document not found", data),
|
||||||
},
|
},
|
||||||
_ => unreachable!("should have been an error type"),
|
_ => unreachable!("should have been an error type"),
|
||||||
}
|
}
|
||||||
@ -251,7 +261,8 @@ mod fields {
|
|||||||
let field: Field = err.into();
|
let field: Field = err.into();
|
||||||
let result = field.to_error_type().unwrap();
|
let result = field.to_error_type().unwrap();
|
||||||
match result {
|
match result {
|
||||||
ErrorType::DocumentNotFound => {} //_ => unreachable!("got {:?}: should have been document not found", result),
|
ErrorType::DocumentNotFound => {}
|
||||||
|
_ => unreachable!("got {:?}: should have been document not found", result),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -282,7 +293,7 @@ mod fields {
|
|||||||
let field: Field = Uuid::new_v4().into();
|
let field: Field = Uuid::new_v4().into();
|
||||||
match field.to_action() {
|
match field.to_action() {
|
||||||
Ok(_) => unreachable!("should have returned an error"),
|
Ok(_) => unreachable!("should have returned an error"),
|
||||||
Err(_) => {},
|
Err(_) => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
21
src/lib.rs
21
src/lib.rs
@ -13,15 +13,17 @@ use queue::{Message, MsgType, Queue};
|
|||||||
use session::Session;
|
use session::Session;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub enum ActionType {
|
pub enum ActionType {
|
||||||
Get,
|
Get,
|
||||||
Add,
|
Add,
|
||||||
Update,
|
Update,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub enum ErrorType {
|
pub enum ErrorType {
|
||||||
|
DocumentAlreadyExists,
|
||||||
|
DocumentInvalidRequest,
|
||||||
DocumentNotFound,
|
DocumentNotFound,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -75,6 +77,7 @@ mod mtt_replies {
|
|||||||
match reply.get_error() {
|
match reply.get_error() {
|
||||||
Some(err) => match err {
|
Some(err) => match err {
|
||||||
ErrorType::DocumentNotFound => {}
|
ErrorType::DocumentNotFound => {}
|
||||||
|
_ => unreachable!("got {:?}: should have been document not found", err),
|
||||||
},
|
},
|
||||||
None => unreachable!("should return an error type"),
|
None => unreachable!("should return an error type"),
|
||||||
}
|
}
|
||||||
@ -96,6 +99,7 @@ mod mtt_replies {
|
|||||||
match reply.get_error() {
|
match reply.get_error() {
|
||||||
Some(err) => match err {
|
Some(err) => match err {
|
||||||
ErrorType::DocumentNotFound => {}
|
ErrorType::DocumentNotFound => {}
|
||||||
|
_ => unreachable!("got {:?}: should have been document not found", err),
|
||||||
},
|
},
|
||||||
None => unreachable!("should return an error type"),
|
None => unreachable!("should return an error type"),
|
||||||
}
|
}
|
||||||
@ -132,7 +136,13 @@ impl MoreThanText {
|
|||||||
reply.get_data("sess_id").unwrap().to_uuid().unwrap()
|
reply.get_data("sess_id").unwrap().to_uuid().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_document<S>(&self, sess_id: Uuid, action: ActionType, doc_name: S) -> MTTReply
|
pub fn get_document<S>(
|
||||||
|
&self,
|
||||||
|
sess_id: Uuid,
|
||||||
|
action: ActionType,
|
||||||
|
doc_name: S,
|
||||||
|
data: String,
|
||||||
|
) -> MTTReply
|
||||||
where
|
where
|
||||||
S: Into<String>,
|
S: Into<String>,
|
||||||
{
|
{
|
||||||
@ -140,6 +150,7 @@ impl MoreThanText {
|
|||||||
msg.add_data("sess_id", sess_id);
|
msg.add_data("sess_id", sess_id);
|
||||||
msg.add_data("action", action);
|
msg.add_data("action", action);
|
||||||
msg.add_data("name", doc_name.into());
|
msg.add_data("name", doc_name.into());
|
||||||
|
msg.add_data("doc", data);
|
||||||
let rx = self.client_channel.send(msg);
|
let rx = self.client_channel.send(msg);
|
||||||
let reply = rx.recv().unwrap();
|
let reply = rx.recv().unwrap();
|
||||||
MTTReply::new(reply)
|
MTTReply::new(reply)
|
||||||
@ -175,7 +186,7 @@ mod mtt {
|
|||||||
fn get_root_document_with_str() {
|
fn get_root_document_with_str() {
|
||||||
let mut mtt = MoreThanText::new();
|
let mut mtt = MoreThanText::new();
|
||||||
let id = mtt.validate_session(Some(Uuid::new_v4()));
|
let id = mtt.validate_session(Some(Uuid::new_v4()));
|
||||||
let output = mtt.get_document(id, ActionType::Get, "root");
|
let output = mtt.get_document(id, ActionType::Get, "root", "".to_string());
|
||||||
assert!(output.get_error().is_none());
|
assert!(output.get_error().is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -183,7 +194,7 @@ mod mtt {
|
|||||||
fn get_root_document_with_string() {
|
fn get_root_document_with_string() {
|
||||||
let mut mtt = MoreThanText::new();
|
let mut mtt = MoreThanText::new();
|
||||||
let id = mtt.validate_session(Some(Uuid::new_v4()));
|
let id = mtt.validate_session(Some(Uuid::new_v4()));
|
||||||
let output = mtt.get_document(id, ActionType::Get, "root".to_string());
|
let output = mtt.get_document(id, ActionType::Get, "root".to_string(), "".to_string());
|
||||||
assert!(output.get_error().is_none());
|
assert!(output.get_error().is_none());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
160
src/main.rs
160
src/main.rs
@ -6,7 +6,7 @@ use axum::{
|
|||||||
RequestPartsExt, Router,
|
RequestPartsExt, Router,
|
||||||
};
|
};
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use morethantext::{ActionType, MoreThanText};
|
use morethantext::{ActionType, ErrorType, MoreThanText};
|
||||||
use std::{collections::HashMap, convert::Infallible};
|
use std::{collections::HashMap, convert::Infallible};
|
||||||
use tokio::{spawn, sync::mpsc::channel};
|
use tokio::{spawn, sync::mpsc::channel};
|
||||||
use tower_cookies::{Cookie, CookieManagerLayer, Cookies};
|
use tower_cookies::{Cookie, CookieManagerLayer, Cookies};
|
||||||
@ -45,7 +45,7 @@ async fn create_app(state: MoreThanText) -> Router {
|
|||||||
Router::new()
|
Router::new()
|
||||||
.route("/", get(mtt_conn))
|
.route("/", get(mtt_conn))
|
||||||
.route("/{document}", get(mtt_conn))
|
.route("/{document}", get(mtt_conn))
|
||||||
.route("/api/{document}", post(mtt_conn))
|
.route("/api/{document}", post(mtt_conn).patch(mtt_conn))
|
||||||
.layer(CookieManagerLayer::new())
|
.layer(CookieManagerLayer::new())
|
||||||
.layer(Extension(state.clone()))
|
.layer(Extension(state.clone()))
|
||||||
.with_state(state)
|
.with_state(state)
|
||||||
@ -85,11 +85,13 @@ async fn mtt_conn(
|
|||||||
method: Method,
|
method: Method,
|
||||||
path: Path<HashMap<String, String>>,
|
path: Path<HashMap<String, String>>,
|
||||||
state: State<MoreThanText>,
|
state: State<MoreThanText>,
|
||||||
|
body: String,
|
||||||
) -> impl IntoResponse {
|
) -> impl IntoResponse {
|
||||||
let (tx, mut rx) = channel(1);
|
let (tx, mut rx) = channel(1);
|
||||||
let action = match method {
|
let action = match method {
|
||||||
Method::GET => ActionType::Get,
|
Method::GET => ActionType::Get,
|
||||||
Method::POST => ActionType::Add,
|
Method::POST => ActionType::Add,
|
||||||
|
Method::PATCH => ActionType::Update,
|
||||||
_ => unreachable!("reouter should prevent this"),
|
_ => unreachable!("reouter should prevent this"),
|
||||||
};
|
};
|
||||||
let doc = match path.get("document") {
|
let doc = match path.get("document") {
|
||||||
@ -97,13 +99,18 @@ async fn mtt_conn(
|
|||||||
None => "root".to_string(),
|
None => "root".to_string(),
|
||||||
};
|
};
|
||||||
spawn(async move {
|
spawn(async move {
|
||||||
tx.send(state.get_document(sess_id.0, action, doc))
|
tx.send(state.get_document(sess_id.0, action, doc, body))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
});
|
});
|
||||||
let reply = rx.recv().await.unwrap();
|
let reply = rx.recv().await.unwrap();
|
||||||
let status = match reply.get_error() {
|
let status = match reply.get_error() {
|
||||||
Some(_) => StatusCode::NOT_FOUND,
|
Some(err) => match err {
|
||||||
|
ErrorType::DocumentAlreadyExists => StatusCode::CONFLICT,
|
||||||
|
ErrorType::DocumentInvalidRequest => StatusCode::BAD_REQUEST,
|
||||||
|
ErrorType::DocumentNotFound => StatusCode::NOT_FOUND,
|
||||||
|
// _ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
},
|
||||||
None => StatusCode::OK,
|
None => StatusCode::OK,
|
||||||
};
|
};
|
||||||
(status, reply.get_document())
|
(status, reply.get_document())
|
||||||
@ -112,7 +119,6 @@ async fn mtt_conn(
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod servers {
|
mod servers {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::time::Duration;
|
|
||||||
use axum::{
|
use axum::{
|
||||||
body::Body,
|
body::Body,
|
||||||
http::{
|
http::{
|
||||||
@ -120,6 +126,8 @@ mod servers {
|
|||||||
Method, Request,
|
Method, Request,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
use http_body_util::BodyExt;
|
||||||
|
use serde_json::json;
|
||||||
use tower::ServiceExt;
|
use tower::ServiceExt;
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@ -193,10 +201,14 @@ mod servers {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
//#[tokio::test]
|
#[tokio::test]
|
||||||
async fn add_new_page() {
|
async fn add_new_page() {
|
||||||
let base = "/something".to_string();
|
let base = "/something".to_string();
|
||||||
let api = format!("/api{}", &base);
|
let api = format!("/api{}", &base);
|
||||||
|
let content = format!("content-{}", Uuid::new_v4());
|
||||||
|
let document = json!({
|
||||||
|
"template": content.clone()
|
||||||
|
});
|
||||||
let app = create_app(MoreThanText::new()).await;
|
let app = create_app(MoreThanText::new()).await;
|
||||||
let response = app
|
let response = app
|
||||||
.clone()
|
.clone()
|
||||||
@ -204,7 +216,7 @@ mod servers {
|
|||||||
Request::builder()
|
Request::builder()
|
||||||
.method(Method::POST)
|
.method(Method::POST)
|
||||||
.uri(&api)
|
.uri(&api)
|
||||||
.body(Body::empty())
|
.body(document.to_string())
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
@ -225,5 +237,139 @@ mod servers {
|
|||||||
"failed to get ro {:?}",
|
"failed to get ro {:?}",
|
||||||
base
|
base
|
||||||
);
|
);
|
||||||
|
let body = response.into_body().collect().await.unwrap().to_bytes();
|
||||||
|
assert_eq!(body, content);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn cannot_add_duplicate_document_names() {
|
||||||
|
let app = create_app(MoreThanText::new()).await;
|
||||||
|
let document = json!({
|
||||||
|
"template": "something completely different."
|
||||||
|
});
|
||||||
|
let response = app
|
||||||
|
.clone()
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/api/root")
|
||||||
|
.body(document.to_string())
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
response.status(),
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
"do not allow post to existing documents"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn invalid_json() {
|
||||||
|
let app = create_app(MoreThanText::new()).await;
|
||||||
|
let response = app
|
||||||
|
.clone()
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/api/something")
|
||||||
|
.body("Some invalid json.".to_string())
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
response.status(),
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"do not allow post to existing documents"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn post_with_missing_document() {
|
||||||
|
let app = create_app(MoreThanText::new()).await;
|
||||||
|
let response = app
|
||||||
|
.clone()
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/api/something")
|
||||||
|
.body("{}".to_string())
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
response.status(),
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"do not allow post to existing documents"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn patch_root() {
|
||||||
|
let content = format!("content-{}", Uuid::new_v4());
|
||||||
|
let document = json!({
|
||||||
|
"template": content.clone()
|
||||||
|
});
|
||||||
|
let app = create_app(MoreThanText::new()).await;
|
||||||
|
let response = app
|
||||||
|
.clone()
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method(Method::PATCH)
|
||||||
|
.uri("/api/root".to_string())
|
||||||
|
.body(document.to_string())
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
response.status(),
|
||||||
|
StatusCode::OK,
|
||||||
|
"failed to patch /api/root",
|
||||||
|
);
|
||||||
|
let response = app
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.uri("/".to_string())
|
||||||
|
.body(Body::empty())
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
response.status(),
|
||||||
|
StatusCode::OK,
|
||||||
|
"failed to get to home page",
|
||||||
|
);
|
||||||
|
let body = response.into_body().collect().await.unwrap().to_bytes();
|
||||||
|
assert_eq!(body, content);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn patch_missing_page() {
|
||||||
|
let content = format!("content-{}", Uuid::new_v4());
|
||||||
|
let document = json!({
|
||||||
|
"template": content.clone()
|
||||||
|
});
|
||||||
|
let app = create_app(MoreThanText::new()).await;
|
||||||
|
let response = app
|
||||||
|
.clone()
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method(Method::PATCH)
|
||||||
|
.uri("/api/something".to_string())
|
||||||
|
.body(document.to_string())
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
response.status(),
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
"failed to patch /api/somethingt",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
36
src/queue.rs
36
src/queue.rs
@ -1,4 +1,4 @@
|
|||||||
use crate::field::Field;
|
use crate::{field::Field, ErrorType};
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
sync::{mpsc::Sender, Arc, RwLock},
|
sync::{mpsc::Sender, Arc, RwLock},
|
||||||
@ -48,6 +48,12 @@ impl Message {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn reply_with_error(&self, error: ErrorType) -> Self {
|
||||||
|
let mut reply = self.reply(MsgType::Error);
|
||||||
|
reply.add_data("error_type", error);
|
||||||
|
reply
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_msg_type(&self) -> &MsgType {
|
pub fn get_msg_type(&self) -> &MsgType {
|
||||||
&self.msg_type
|
&self.msg_type
|
||||||
}
|
}
|
||||||
@ -181,6 +187,34 @@ mod messages {
|
|||||||
msg.reset_id();
|
msg.reset_id();
|
||||||
assert_ne!(msg.get_id(), id);
|
assert_ne!(msg.get_id(), id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn error_reply() {
|
||||||
|
let msg = Message::new(MsgType::Time);
|
||||||
|
let errors = [
|
||||||
|
ErrorType::DocumentAlreadyExists,
|
||||||
|
ErrorType::DocumentInvalidRequest,
|
||||||
|
];
|
||||||
|
for error in errors.into_iter() {
|
||||||
|
let reply = msg.reply_with_error(error.clone());
|
||||||
|
assert_eq!(reply.get_id(), msg.get_id());
|
||||||
|
assert_eq!(
|
||||||
|
format!("{:?}", reply.get_msg_type()),
|
||||||
|
format!("{:?}", MsgType::Error)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
format!(
|
||||||
|
"{:?}",
|
||||||
|
reply
|
||||||
|
.get_data("error_type")
|
||||||
|
.unwrap()
|
||||||
|
.to_error_type()
|
||||||
|
.unwrap()
|
||||||
|
),
|
||||||
|
format!("{:?}", error)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user