Compare commits

...

19 Commits

Author SHA1 Message Date
9e16684ac9 Removed Field2. Bad experiment. 2025-05-08 12:07:57 -04:00
ae257f949d Making Field be more generic. 2025-05-06 17:56:21 -04:00
fd7d85edbb Updated libraries. 2025-05-06 09:07:29 -04:00
5502013b76 Patch errors if page is missing. 2025-05-04 09:55:05 -04:00
cb7526dd45 Checked json data. 2025-05-04 08:18:55 -04:00
ce3400e353 Added reply with error. 2025-05-03 18:14:47 -04:00
80124af836 Handle bad json. 2025-05-03 09:48:53 -04:00
e7c7d9f270 Prevent overwriting existing documents. 2025-05-03 08:40:51 -04:00
ea825c89eb Got content added to new pages. 2025-05-02 18:04:17 -04:00
57a09461f1 Got the new page added. 2025-05-02 08:09:05 -04:00
4fbbd30c4b Added ability to add page, but hangs in main. 2025-05-01 13:46:46 -04:00
1bfbfc5e44 Gave control to documents service. 2025-04-26 10:29:58 -04:00
55ffa538e8 Got backend using errors. 2025-04-25 14:02:40 -04:00
cb9bac9d8a Laying the ground work to add pages. 2025-04-24 12:00:17 -04:00
cb69c4d55a Corrected for cargo update. 2025-04-23 11:12:15 -04:00
ce10c73eae Added api post. 2025-04-23 10:46:33 -04:00
38af08eb14 Reattached document service. 2025-04-22 08:31:25 -04:00
0ab0b59f4c Refactored message id reset. 2025-04-22 08:00:45 -04:00
a61474f38a Clean up dead code. 2025-04-21 22:29:15 -04:00
9 changed files with 841 additions and 388 deletions

309
Cargo.lock generated
View File

@ -82,17 +82,6 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "async-trait"
version = "0.1.88"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e539d3fca749fcee5236ab05e93a52867dd549cc157c8cb7f99595f3cedffdb5"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "autocfg"
version = "1.4.0"
@ -101,13 +90,13 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "axum"
version = "0.7.9"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f"
checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5"
dependencies = [
"async-trait",
"axum-core 0.4.5",
"axum-core",
"bytes",
"form_urlencoded",
"futures-util",
"http",
"http-body",
@ -133,27 +122,6 @@ dependencies = [
"tracing",
]
[[package]]
name = "axum-core"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199"
dependencies = [
"async-trait",
"bytes",
"futures-util",
"http",
"http-body",
"http-body-util",
"mime",
"pin-project-lite",
"rustversion",
"sync_wrapper",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "axum-core"
version = "0.5.2"
@ -171,30 +139,7 @@ dependencies = [
"sync_wrapper",
"tower-layer",
"tower-service",
]
[[package]]
name = "axum-extra"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c794b30c904f0a1c2fb7740f7df7f7972dfaa14ef6f57cb6178dc63e5dca2f04"
dependencies = [
"axum",
"axum-core 0.4.5",
"bytes",
"cookie",
"fastrand",
"futures-util",
"http",
"http-body",
"http-body-util",
"mime",
"multer",
"pin-project-lite",
"serde",
"tower",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
@ -212,27 +157,12 @@ dependencies = [
"windows-targets",
]
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bitflags"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "bumpalo"
version = "3.17.0"
@ -247,9 +177,9 @@ checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
[[package]]
name = "cc"
version = "1.2.19"
version = "1.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e3a13707ac958681c13b39b458c073d0d9bc8a22cb1b2f4c8e55eb72c13f362"
checksum = "8691782945451c1c383942c4874dbe63814f61cb57ef773cda2972682b7bb3c0"
dependencies = [
"shlex",
]
@ -262,9 +192,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
version = "0.4.40"
version = "0.4.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a7964611d71df112cb1730f2ee67324fcf4d0fc6606acbbe9bfe06df124637c"
checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d"
dependencies = [
"android-tzdata",
"iana-time-zone",
@ -276,9 +206,9 @@ dependencies = [
[[package]]
name = "clap"
version = "4.5.36"
version = "4.5.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2df961d8c8a0d08aa9945718ccf584145eee3f3aa06cddbeac12933781102e04"
checksum = "eccb054f56cbd38340b380d4a8e69ef1f02f1af43db2f0cc817a4774d80ae071"
dependencies = [
"clap_builder",
"clap_derive",
@ -286,9 +216,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.5.36"
version = "4.5.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "132dbda40fb6753878316a489d5a1242a8ef2f0d9e47ba01c951ea8aa7d013a5"
checksum = "efd9466fac8543255d3b1fcad4762c5e116ffe808c8a3043d4263cd4fd4862a2"
dependencies = [
"anstream",
"anstyle",
@ -326,12 +256,7 @@ version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
dependencies = [
"base64",
"hmac",
"percent-encoding",
"rand",
"sha2",
"subtle",
"time",
"version_check",
]
@ -342,25 +267,6 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "deranged"
version = "0.4.0"
@ -370,32 +276,6 @@ dependencies = [
"powerfmt",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
name = "encoding_rs"
version = "0.8.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
dependencies = [
"cfg-if",
]
[[package]]
name = "fastrand"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "fnv"
version = "1.0.7"
@ -457,27 +337,6 @@ dependencies = [
"slab",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
dependencies = [
"cfg-if",
"libc",
"wasi 0.11.0+wasi-snapshot-preview1",
]
[[package]]
name = "getrandom"
version = "0.3.2"
@ -502,15 +361,6 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "http"
version = "1.3.1"
@ -662,9 +512,9 @@ checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
[[package]]
name = "matchit"
version = "0.7.3"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "memchr"
@ -703,33 +553,16 @@ name = "morethantext"
version = "0.1.0"
dependencies = [
"axum",
"axum-extra",
"chrono",
"clap",
"rand",
"http-body-util",
"serde_json",
"tokio",
"tower",
"tower-cookies",
"uuid",
]
[[package]]
name = "multer"
version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b"
dependencies = [
"bytes",
"encoding_rs",
"futures-util",
"http",
"httparse",
"memchr",
"mime",
"spin",
"version_check",
]
[[package]]
name = "num-conv"
version = "0.1.0"
@ -807,15 +640,6 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.95"
@ -840,41 +664,11 @@ version = "5.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5"
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom 0.2.15",
]
[[package]]
name = "redox_syscall"
version = "0.5.11"
version = "0.5.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f103c6d277498fbceb16e84d317e2a400f160f46904d5f5410848c829511a3"
checksum = "928fca9cf2aa042393a8325b9ead81d2f0df4cb12e1e24cef072922ccd99c5af"
dependencies = [
"bitflags",
]
@ -957,17 +751,6 @@ dependencies = [
"serde",
]
[[package]]
name = "sha2"
version = "0.10.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "shlex"
version = "1.3.0"
@ -976,9 +759,9 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "signal-hook-registry"
version = "1.4.2"
version = "1.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"
checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410"
dependencies = [
"libc",
]
@ -1008,29 +791,17 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.100"
version = "2.0.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0"
checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf"
dependencies = [
"proc-macro2",
"quote",
@ -1076,9 +847,9 @@ dependencies = [
[[package]]
name = "tokio"
version = "1.44.2"
version = "1.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48"
checksum = "2513ca694ef9ede0fb23fe71a4ee4107cb102b9dc1930f6d0fd77aae068ae165"
dependencies = [
"backtrace",
"bytes",
@ -1125,7 +896,7 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "151b5a3e3c45df17466454bb74e9ecedecc955269bdedbf4d150dfa393b55a36"
dependencies = [
"axum-core 0.5.2",
"axum-core",
"cookie",
"futures-util",
"http",
@ -1167,12 +938,6 @@ dependencies = [
"once_cell",
]
[[package]]
name = "typenum"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f"
[[package]]
name = "unicode-ident"
version = "1.0.18"
@ -1191,7 +956,7 @@ version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9"
dependencies = [
"getrandom 0.3.2",
"getrandom",
]
[[package]]
@ -1422,23 +1187,3 @@ checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
dependencies = [
"bitflags",
]
[[package]]
name = "zerocopy"
version = "0.8.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2586fea28e186957ef732a5f8b3be2da217d65c5969d4b1e17f973ebbe876879"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a996a8f63c5c4448cd959ac1bab0aaa3306ccfd060472f85943ee0750f0169be"
dependencies = [
"proc-macro2",
"quote",
"syn",
]

View File

@ -6,14 +6,14 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
axum = "0.7.4"
axum-extra = { version = "0.9.2", features = ["cookie-signed"] }
chrono = { version = "0.4.40", features = ["now"] }
clap = { version = "4.5.1", features = ["derive"] }
rand = "0.8.5"
tokio = { version = "1.36.0", features = ["full"] }
tower-cookies = "0.11.0"
uuid = { version = "1.8.0", features = ["v4"] }
axum = ">=0.8.0"
chrono = { version = ">=0.4.40", features = ["now"] }
clap = { version = ">=4.5.1", features = ["derive"] }
serde_json = ">=1.0.140"
tokio = { version = ">=1.36.0", features = ["full"] }
tower-cookies = ">=0.11.0"
uuid = { version = ">=1.8.0", features = ["v4"] }
[dev-dependencies]
tower = { version = "0.5.2", features = ["util"] }
http-body-util = ">=0.1.3"
tower = { version = ">=0.5.2", features = ["util"] }

View File

@ -1,8 +1,4 @@
use crate::{
field::Field,
queue::{Message, MsgType, Queue},
utils::GenID,
};
use crate::queue::{Message, MsgType, Queue};
use std::{
collections::HashMap,
sync::{
@ -13,7 +9,12 @@ use std::{
};
use uuid::Uuid;
const RESPONS_TO: [MsgType; 2] = [MsgType::Document, MsgType::SessionValidated];
const RESPONS_TO: [MsgType; 4] = [
MsgType::ActionOk,
MsgType::Document,
MsgType::Error,
MsgType::SessionValidated,
];
#[derive(Clone)]
pub struct ClientChannel {
@ -31,16 +32,12 @@ impl ClientChannel {
pub fn send(&self, mut msg: Message) -> Receiver<Message> {
let mut reg = self.registry.lock().unwrap();
if reg.contains_key(&msg.get_id()) {
let mut id = Uuid::new_v4();
while reg.contains_key(&id) {
id = Uuid::new_v4();
}
msg.reset_id(id);
while reg.contains_key(&msg.get_id()) {
msg.reset_id();
}
let (tx, rx) = channel();
reg.insert(msg.get_id(), tx);
self.queue.send(msg);
self.queue.send(msg).unwrap();
rx
}
@ -60,17 +57,6 @@ mod client_channels {
static TIMEOUT: Duration = Duration::from_millis(500);
#[test]
fn request_new_message() {
let queue = Queue::new();
let chan = ClientChannel::new(queue);
let msg_types = [MsgType::Document, MsgType::Time];
for msg_type in msg_types.iter() {
let msg = Message::new(msg_type.clone());
assert_eq!(msg.get_msg_type(), msg_type);
}
}
#[test]
fn fowards_message() {
let msg_type = MsgType::Document;
@ -122,15 +108,13 @@ mod client_channels {
pub struct Client {
channel: ClientChannel,
queue: Queue,
rx: Receiver<Message>,
}
impl Client {
fn new(chan: ClientChannel, queue: Queue, rx: Receiver<Message>) -> Self {
fn new(chan: ClientChannel, rx: Receiver<Message>) -> Self {
Self {
channel: chan,
queue: queue,
rx: rx,
}
}
@ -139,7 +123,7 @@ impl Client {
let (tx, rx) = channel();
queue.add(tx.clone(), RESPONS_TO.to_vec());
let chan = ClientChannel::new(queue.clone());
let client = Client::new(chan.clone(), queue, rx);
let client = Client::new(chan.clone(), rx);
spawn(move || {
client.listen();
});
@ -171,7 +155,22 @@ mod clients {
let chan_rx = chan.send(Message::new(MsgType::SessionValidate));
let msg = queue_rx.recv_timeout(TIMEOUT).unwrap();
let expected = create_validated_reply(msg);
queue.send(expected.clone());
queue.send(expected.clone()).unwrap();
let result = chan_rx.recv_timeout(TIMEOUT).unwrap();
assert_eq!(result.get_id(), expected.get_id());
assert_eq!(result.get_msg_type(), expected.get_msg_type());
}
#[test]
fn document_return() {
let queue = Queue::new();
let (queue_tx, queue_rx) = channel();
queue.add(queue_tx, [MsgType::DocumentRequest].to_vec());
let chan = Client::start(queue.clone());
let chan_rx = chan.send(Message::new(MsgType::DocumentRequest));
let msg = queue_rx.recv_timeout(TIMEOUT).unwrap();
let expected = msg.reply(MsgType::Document);
queue.send(expected.clone()).unwrap();
let result = chan_rx.recv_timeout(TIMEOUT).unwrap();
assert_eq!(result.get_id(), expected.get_id());
assert_eq!(result.get_msg_type(), expected.get_msg_type());

View File

@ -1,5 +1,10 @@
use crate::queue::{Message, MsgType, Queue};
use crate::{
queue::{Message, MsgType, Queue},
ActionType, ErrorType,
};
use serde_json::Value;
use std::{
collections::HashMap,
sync::mpsc::{channel, Receiver},
thread::spawn,
};
@ -7,13 +12,17 @@ use std::{
const RESPONDS_TO: [MsgType; 1] = [MsgType::DocumentRequest];
pub struct Document {
data: HashMap<String, String>,
queue: Queue,
rx: Receiver<Message>,
}
impl Document {
fn new(queue: Queue, rx: Receiver<Message>) -> Self {
let mut data = HashMap::new();
data.insert("root".to_string(), "Something goes here.".to_string());
Self {
data: data,
queue: queue,
rx: rx,
}
@ -31,40 +40,102 @@ impl Document {
fn listen(&mut self) {
loop {
let msg = self.rx.recv().unwrap();
let mut reply = msg.reply(MsgType::Document);
reply.add_data(
"sess_id",
msg.get_data("sess_id").unwrap().to_uuid().unwrap(),
);
reply.add_data("doc", "Something goes hwew");
match msg.get_data("action") {
Some(action_field) => {
let action = action_field.to_action().unwrap();
match action {
ActionType::Add | ActionType::Update => self.add(action, msg),
_ => self.get(msg),
}
}
None => self.get(msg),
}
}
}
fn add(&mut self, action: ActionType, msg: Message) {
let name = msg.get_data("name").unwrap().to_string();
match self.data.get(&name) {
Some(_) => match action {
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) {
let name = match msg.get_data("name") {
Some(doc) => doc.to_string(),
None => "root".to_string(),
};
let reply = match self.data.get(&name) {
Some(data) => {
let mut holder = msg.reply(MsgType::Document);
holder.add_data("doc", data.clone());
holder
}
None => msg.reply_with_error(ErrorType::DocumentNotFound),
};
self.queue.send(reply).unwrap();
}
}
#[cfg(test)]
pub mod documents {
use super::*;
use serde_json::json;
use std::time::Duration;
use uuid::Uuid;
const TIMEOUT: Duration = Duration::from_millis(500);
pub fn get_root_document() -> Message {
Message::new(MsgType::DocumentRequest)
}
fn setup_document(listen_for: Vec<MsgType>) -> (Queue, Receiver<Message>) {
fn setup_document() -> (Queue, Receiver<Message>) {
let queue = Queue::new();
let (tx, rx) = channel();
queue.add(tx, listen_for);
queue.add(
tx,
[MsgType::ActionOk, MsgType::Document, MsgType::Error].to_vec(),
);
Document::start(queue.clone());
(queue, rx)
}
#[test]
fn start_service() {
let (queue, rx) = setup_document([MsgType::Document].to_vec());
let (queue, rx) = setup_document();
let id = Uuid::new_v4();
let mut msg = Message::new(MsgType::DocumentRequest);
msg.add_data("sess_id", id.clone());
@ -75,7 +146,182 @@ pub mod documents {
MsgType::Document => {}
_ => unreachable!("got {:?} should have gotten document", msg.get_msg_type()),
}
assert_eq!(reply.get_data("sess_id").unwrap().to_uuid().unwrap(), id);
assert!(reply.get_data("doc").is_some());
}
#[test]
fn no_existing_document() {
let (queue, rx) = setup_document();
let name = format!("name-{}", Uuid::new_v4());
let mut msg = Message::new(MsgType::DocumentRequest);
msg.add_data("name", name.clone());
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"),
}
}
#[test]
fn root_always_exists() {
let (queue, rx) = setup_document();
let mut msg = Message::new(MsgType::DocumentRequest);
msg.add_data("name", "root");
queue.send(msg).unwrap();
let reply = rx.recv_timeout(TIMEOUT).unwrap();
match reply.get_msg_type() {
MsgType::Document => {}
_ => unreachable!(
"Got '{:?}': should have been a document",
reply.get_msg_type()
),
}
}
#[test]
fn add_new_document() {
let (queue, rx) = setup_document();
let name = format!("name-{}", Uuid::new_v4());
let content = format!("content-{}", Uuid::new_v4());
let input = json!({
"template": content.clone()
});
let mut msg1 = Message::new(MsgType::DocumentRequest);
msg1.add_data("name", name.clone());
msg1.add_data("action", ActionType::Add);
msg1.add_data("doc", input.to_string());
queue.send(msg1.clone()).unwrap();
let reply1 = rx.recv_timeout(TIMEOUT).unwrap();
assert_eq!(reply1.get_id(), msg1.get_id());
match reply1.get_msg_type() {
MsgType::ActionOk => {}
_ => unreachable!(
"got {:?}: should have received action ok",
reply1.get_msg_type()
),
}
let mut msg2 = Message::new(MsgType::DocumentRequest);
msg2.add_data("name", name.clone());
msg2.add_data("action", ActionType::Get);
queue.send(msg2.clone()).unwrap();
let reply2 = rx.recv_timeout(TIMEOUT).unwrap();
assert_eq!(reply2.get_id(), msg2.get_id());
match reply2.get_msg_type() {
MsgType::Document => {}
_ => unreachable!(
"got {:?}: should have received document",
reply2.get_msg_type()
),
}
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"),
}
}
}

View File

@ -1,15 +1,34 @@
use crate::{ActionType, ErrorType};
use chrono::prelude::*;
use std::fmt;
use uuid::Uuid;
#[derive(Clone, Debug, PartialEq)]
enum FieldType {
Action,
DateTime,
Error,
StaticString,
Uuid,
}
#[derive(Clone, Debug)]
pub enum Field {
Action(ActionType),
DateTime(DateTime<Utc>),
ErrorType(ErrorType),
Static(String),
Uuid(Uuid),
DateTime(DateTime<Utc>),
}
impl Field {
pub fn to_action(&self) -> Result<ActionType, String> {
match self {
Field::Action(data) => Ok(data.clone()),
_ => Err("not an action".to_string()),
}
}
pub fn to_uuid(&self) -> Result<Uuid, String> {
match self {
Field::Uuid(data) => Ok(data.clone()),
@ -23,6 +42,13 @@ impl Field {
_ => Err("not a datetime".to_string()),
}
}
pub fn to_error_type(&self) -> Result<ErrorType, String> {
match self {
Field::ErrorType(data) => Ok(data.clone()),
_ => Err("not an error type".to_string()),
}
}
}
impl From<String> for Field {
@ -45,6 +71,12 @@ impl From<&str> for Field {
}
}
impl From<ActionType> for Field {
fn from(value: ActionType) -> Self {
Field::Action(value)
}
}
impl From<Uuid> for Field {
fn from(value: Uuid) -> Self {
Field::Uuid(value)
@ -57,12 +89,19 @@ impl From<DateTime<Utc>> for Field {
}
}
impl From<ErrorType> for Field {
fn from(value: ErrorType) -> Self {
Field::ErrorType(value)
}
}
impl fmt::Display for Field {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Field::Uuid(data) => write!(f, "{}", data),
Field::Static(data) => write!(f, "{}", data),
Field::DateTime(data) => write!(f, "{}", data),
Field::Static(data) => write!(f, "{}", data),
Field::Uuid(data) => write!(f, "{}", data),
_ => write!(f, ""),
}
}
}
@ -196,4 +235,65 @@ mod fields {
let field: Field = txt.into();
assert!(field.to_datetime().is_err(), "should not return a value");
}
#[test]
fn from_error_to_field() {
let err = ErrorType::DocumentNotFound;
let field: Field = err.into();
match field {
Field::ErrorType(data) => match data {
ErrorType::DocumentNotFound => {}
_ => unreachable!("got {:?}: should have been Document not found", data),
},
_ => unreachable!("should have been an error type"),
}
}
#[test]
fn from_field_to_error_type_error() {
let field: Field = Uuid::new_v4().into();
assert!(field.to_error_type().is_err(), "should generate an error");
}
#[test]
fn from_field_to_error_type() {
let err = ErrorType::DocumentNotFound;
let field: Field = err.into();
let result = field.to_error_type().unwrap();
match result {
ErrorType::DocumentNotFound => {}
_ => unreachable!("got {:?}: should have been document not found", result),
}
}
#[test]
fn from_action_to_field() {
let actions = [ActionType::Add, ActionType::Get, ActionType::Update];
for action in actions.into_iter() {
let result: Field = action.clone().into();
match result {
Field::Action(data) => assert_eq!(format!("{:?}", data), format!("{:?}", action)),
_ => unreachable!("should have been an action"),
}
}
}
#[test]
fn from_field_to_action() {
let actions = [ActionType::Add, ActionType::Get, ActionType::Update];
for action in actions.into_iter() {
let field: Field = action.clone().into();
let result = field.to_action().unwrap();
assert_eq!(format!("{:?}", result), format!("{:?}", action));
}
}
#[test]
fn from_uuid_to_action() {
let field: Field = Uuid::new_v4().into();
match field.to_action() {
Ok(_) => unreachable!("should have returned an error"),
Err(_) => {}
}
}
}

View File

@ -4,7 +4,6 @@ mod document;
mod field;
mod queue;
mod session;
mod utils;
use client::{Client, ClientChannel};
use clock::Clock;
@ -14,6 +13,99 @@ use queue::{Message, MsgType, Queue};
use session::Session;
use uuid::Uuid;
#[derive(Clone, Debug, PartialEq)]
pub enum ActionType {
Get,
Add,
Update,
}
#[derive(Clone, Debug, PartialEq)]
pub enum ErrorType {
DocumentAlreadyExists,
DocumentInvalidRequest,
DocumentNotFound,
}
pub struct MTTReply {
document: String,
error_type: Option<ErrorType>,
}
impl MTTReply {
fn new(msg: Message) -> Self {
Self {
document: match msg.get_data("doc") {
Some(doc) => doc.to_string(),
None => "".to_string(),
},
error_type: match msg.get_data("error_type") {
Some(err) => Some(err.to_error_type().unwrap()),
None => None,
},
}
}
pub fn get_document(&self) -> String {
self.document.clone()
}
pub fn get_error(&self) -> Option<ErrorType> {
self.error_type.clone()
}
}
#[cfg(test)]
mod mtt_replies {
use super::*;
#[test]
fn create_reply_with_no_error() {
let mut msg = Message::new(MsgType::Document);
let content = format!("content-{}", Uuid::new_v4());
msg.add_data("doc", content.to_string());
let reply = MTTReply::new(msg);
assert!(reply.get_error().is_none());
assert_eq!(reply.get_document(), content);
}
#[test]
fn create_reply_with_error() {
let mut msg = Message::new(MsgType::Error);
msg.add_data("error_type", ErrorType::DocumentNotFound);
let reply = MTTReply::new(msg);
match reply.get_error() {
Some(err) => match err {
ErrorType::DocumentNotFound => {}
_ => unreachable!("got {:?}: should have been document not found", err),
},
None => unreachable!("should return an error type"),
}
assert_eq!(reply.get_document(), "");
}
#[test]
fn no_error() {
let msg = Message::new(MsgType::Document);
let reply = MTTReply::new(msg);
assert!(reply.get_error().is_none());
}
#[test]
fn some_error() {
let mut msg = Message::new(MsgType::Error);
msg.add_data("error_type", ErrorType::DocumentNotFound);
let reply = MTTReply::new(msg);
match reply.get_error() {
Some(err) => match err {
ErrorType::DocumentNotFound => {}
_ => unreachable!("got {:?}: should have been document not found", err),
},
None => unreachable!("should return an error type"),
}
}
}
#[derive(Clone)]
pub struct MoreThanText {
client_channel: ClientChannel,
@ -44,16 +136,65 @@ impl MoreThanText {
reply.get_data("sess_id").unwrap().to_uuid().unwrap()
}
pub fn request<F>(&mut self, session: Option<F>) -> Message
pub fn get_document<S>(
&self,
sess_id: Uuid,
action: ActionType,
doc_name: S,
data: String,
) -> MTTReply
where
F: Into<Field>,
S: Into<String>,
{
let sess = match session {
Some(id) => Some(id.into()),
None => None,
};
let req = Message::new(MsgType::DocumentRequest);
let rx = self.client_channel.send(req.into());
rx.recv().unwrap()
let mut msg = Message::new(MsgType::DocumentRequest);
msg.add_data("sess_id", sess_id);
msg.add_data("action", action);
msg.add_data("name", doc_name.into());
msg.add_data("doc", data);
let rx = self.client_channel.send(msg);
let reply = rx.recv().unwrap();
MTTReply::new(reply)
}
}
#[cfg(test)]
mod mtt {
use super::*;
#[test]
fn session_id_is_unique() {
let mut mtt = MoreThanText::new();
let input: Option<String> = None;
let mut ids: Vec<Uuid> = Vec::new();
for _ in 0..10 {
let id = mtt.validate_session(input.clone());
assert!(!ids.contains(&id));
ids.push(id);
}
}
#[test]
fn reuse_existing_session() {
let mut mtt = MoreThanText::new();
let initial: Option<String> = None;
let id = mtt.validate_session(initial);
let output = mtt.validate_session(Some(id.clone()));
assert_eq!(output, id);
}
#[test]
fn get_root_document_with_str() {
let mut mtt = MoreThanText::new();
let id = mtt.validate_session(Some(Uuid::new_v4()));
let output = mtt.get_document(id, ActionType::Get, "root", "".to_string());
assert!(output.get_error().is_none());
}
#[test]
fn get_root_document_with_string() {
let mut mtt = MoreThanText::new();
let id = mtt.validate_session(Some(Uuid::new_v4()));
let output = mtt.get_document(id, ActionType::Get, "root".to_string(), "".to_string());
assert!(output.get_error().is_none());
}
}

View File

@ -1,14 +1,13 @@
use axum::{
async_trait,
extract::{Extension, FromRequestParts, State},
http::request::Parts,
extract::{Extension, FromRequestParts, Path, State},
http::{request::Parts, Method, StatusCode},
response::IntoResponse,
routing::get,
routing::{get, post},
RequestPartsExt, Router,
};
use clap::Parser;
use morethantext::MoreThanText;
use std::convert::Infallible;
use morethantext::{ActionType, ErrorType, MoreThanText};
use std::{collections::HashMap, convert::Infallible};
use tokio::{spawn, sync::mpsc::channel};
use tower_cookies::{Cookie, CookieManagerLayer, Cookies};
use uuid::Uuid;
@ -45,6 +44,8 @@ async fn main() {
async fn create_app(state: MoreThanText) -> Router {
Router::new()
.route("/", get(mtt_conn))
.route("/{document}", get(mtt_conn))
.route("/api/{document}", post(mtt_conn).patch(mtt_conn))
.layer(CookieManagerLayer::new())
.layer(Extension(state.clone()))
.with_state(state)
@ -53,14 +54,13 @@ async fn create_app(state: MoreThanText) -> Router {
#[derive(Clone)]
struct SessionID(Uuid);
#[async_trait]
impl<S> FromRequestParts<S> for SessionID
where
S: Send + Sync,
{
type Rejection = Infallible;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let Extension(cookies) = parts.extract::<Extension<Cookies>>().await.unwrap();
let Extension(mut state) = parts.extract::<Extension<MoreThanText>>().await.unwrap();
let req_id = match cookies.get(SESSION_KEY) {
@ -82,9 +82,38 @@ where
async fn mtt_conn(
sess_id: SessionID,
method: Method,
path: Path<HashMap<String, String>>,
state: State<MoreThanText>,
body: String,
) -> impl IntoResponse {
("something".to_string(),)
let (tx, mut rx) = channel(1);
let action = match method {
Method::GET => ActionType::Get,
Method::POST => ActionType::Add,
Method::PATCH => ActionType::Update,
_ => unreachable!("reouter should prevent this"),
};
let doc = match path.get("document") {
Some(result) => result.clone(),
None => "root".to_string(),
};
spawn(async move {
tx.send(state.get_document(sess_id.0, action, doc, body))
.await
.unwrap();
});
let reply = rx.recv().await.unwrap();
let status = match reply.get_error() {
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,
};
(status, reply.get_document())
}
#[cfg(test)]
@ -94,9 +123,11 @@ mod servers {
body::Body,
http::{
header::{COOKIE, SET_COOKIE},
Request, StatusCode,
Method, Request,
},
};
use http_body_util::BodyExt;
use serde_json::json;
use tower::ServiceExt;
#[tokio::test]
@ -141,7 +172,7 @@ mod servers {
.unwrap();
assert_eq!(initial.status(), StatusCode::OK);
let sessid = initial.headers().get(SET_COOKIE).unwrap();
let mut request = Request::builder()
let request = Request::builder()
.uri("/")
.header(COOKIE, sessid.clone())
.body(Body::empty())
@ -156,16 +187,189 @@ mod servers {
#[tokio::test]
async fn receive_file_not_found() {
let uri = "/something";
let app = create_app(MoreThanText::new()).await;
let response = app
.oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(
response.status(),
StatusCode::NOT_FOUND,
"'{}' should not exist",
uri
);
}
#[tokio::test]
async fn add_new_page() {
let base = "/something".to_string();
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 response = app
.clone()
.oneshot(
Request::builder()
.method(Method::POST)
.uri(&api)
.body(document.to_string())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
response.status(),
StatusCode::OK,
"failed to post ro {:?}",
api
);
let response = app
.oneshot(Request::builder().uri(&base).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(
response.status(),
StatusCode::OK,
"failed to get ro {:?}",
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("/isomething")
.uri("/".to_string())
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
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",
);
}
}

View File

@ -1,4 +1,4 @@
use crate::field::Field;
use crate::{field::Field, ErrorType};
use std::{
collections::HashMap,
sync::{mpsc::Sender, Arc, RwLock},
@ -7,9 +7,10 @@ use uuid::Uuid;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum MsgType {
ClientRequest,
ActionOk,
Document,
DocumentRequest,
Error,
SessionValidate,
SessionValidated,
Time,
@ -47,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 {
&self.msg_type
}
@ -71,15 +78,14 @@ impl Message {
self.id.clone()
}
pub fn reset_id(&mut self, id: Uuid) {
self.id = id;
pub fn reset_id(&mut self) {
self.id = Uuid::new_v4();
}
}
#[cfg(test)]
mod messages {
use super::*;
use crate::document::documents::get_root_document;
#[test]
fn new_message() {
@ -108,11 +114,11 @@ mod messages {
let mut msg = Message::new(MsgType::SessionValidate);
msg.id = id.clone();
msg.add_data("test", "test");
let data = MsgType::ClientRequest;
let data = MsgType::SessionValidate;
let result = msg.reply(data);
assert_eq!(result.id, id);
match result.msg_type {
MsgType::ClientRequest => {}
MsgType::SessionValidate => {}
_ => unreachable!("should have been a registration request"),
}
assert!(result.data.is_empty());
@ -177,8 +183,37 @@ mod messages {
#[test]
fn reset_msg_id() {
let mut msg = Message::new(MsgType::Time);
msg.reset_id(Uuid::nil());
assert_eq!(msg.get_id(), Uuid::nil());
let id = msg.get_id();
msg.reset_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)
);
}
}
}

View File

@ -1,17 +0,0 @@
use uuid::Uuid;
pub struct GenID;
impl GenID {
pub fn new() -> Self {
GenID {}
}
}
impl Iterator for GenID {
type Item = Uuid;
fn next(&mut self) -> Option<Self::Item> {
Some(Uuid::new_v4())
}
}