This commit is contained in:
Philip (a-0) 2024-01-07 22:28:09 +01:00
parent 3c67388fae
commit 4f8d6ec3d0
16 changed files with 61 additions and 60 deletions

View file

@ -1,9 +1,8 @@
use reqwest::Method; use reqwest::Method;
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
use super::UbisyncRequest; use super::UbisyncRequest;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct AppRegisterRequest { pub struct AppRegisterRequest {
pub name: String, pub name: String,
@ -25,4 +24,4 @@ impl UbisyncRequest for AppRegisterRequest {
fn path(&self, _: Self::PathParameters) -> String { fn path(&self, _: Self::PathParameters) -> String {
"/app/register".to_string() "/app/register".to_string()
} }
} }

View file

@ -1,11 +1,10 @@
use reqwest::Method; use reqwest::Method;
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
use crate::types::{ElementContent, ElementId, Element}; use crate::types::{Element, ElementContent, ElementId};
use super::UbisyncRequest; use super::UbisyncRequest;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct ElementCreateRequest { pub struct ElementCreateRequest {
pub content: ElementContent, pub content: ElementContent,
@ -28,7 +27,6 @@ impl UbisyncRequest for ElementCreateRequest {
} }
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct ElementGetRequest; pub struct ElementGetRequest;
@ -78,11 +76,11 @@ pub struct ElementRemoveResponse;
impl UbisyncRequest for ElementRemoveRequest { impl UbisyncRequest for ElementRemoveRequest {
type PathParameters = ElementId; type PathParameters = ElementId;
type Response = ElementRemoveResponse; type Response = ElementRemoveResponse;
fn method(&self) -> Method { fn method(&self) -> Method {
Method::DELETE Method::DELETE
} }
fn path(&self, params: Self::PathParameters) -> String { fn path(&self, params: Self::PathParameters) -> String {
format!("/element/{}", serde_json::to_string(&params).unwrap()) format!("/element/{}", serde_json::to_string(&params).unwrap())
} }
} }

View file

@ -3,7 +3,6 @@ pub mod messages;
pub mod peer; pub mod peer;
pub mod types; pub mod types;
#[macro_export] #[macro_export]
macro_rules! tracing_setup { macro_rules! tracing_setup {
($level:expr) => { ($level:expr) => {

View file

@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::types::{MessageId, ElementId, ElementContent}; use crate::types::{ElementContent, ElementId, MessageId};
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Message { pub struct Message {
@ -9,8 +9,6 @@ pub struct Message {
content: MessageContent, content: MessageContent,
} }
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
pub struct MessageRelations { pub struct MessageRelations {
pub parents: Vec<MessageId>, pub parents: Vec<MessageId>,

View file

@ -1,7 +1,5 @@
use std::fmt::Display; use std::fmt::Display;
#[derive(Debug)] #[derive(Debug)]
pub enum UbisyncError { pub enum UbisyncError {
InvalidNodeReply(String), InvalidNodeReply(String),
@ -12,9 +10,11 @@ impl Display for UbisyncError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Self::InvalidNodeReply(msg) => write!(f, "Invalid reply from ubisync node: {}", msg), Self::InvalidNodeReply(msg) => write!(f, "Invalid reply from ubisync node: {}", msg),
Self::AppRegistrationFailed => write!(f, "Registrating this app at the ubisync node failed."), Self::AppRegistrationFailed => {
write!(f, "Registrating this app at the ubisync node failed.")
}
} }
} }
} }
impl std::error::Error for UbisyncError {} impl std::error::Error for UbisyncError {}

View file

@ -1,4 +1,9 @@
use axum::{Router, routing::get, response::{Response, IntoResponse}, http::StatusCode, Json}; use axum::{
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
Json, Router,
};
use tokio::{net::TcpListener, task::JoinHandle}; use tokio::{net::TcpListener, task::JoinHandle};
use crate::{config::ApiConfig, state::ApiState}; use crate::{config::ApiConfig, state::ApiState};
@ -45,7 +50,7 @@ impl ApiBuilder {
pub async fn build(&self, state: ApiState) -> Api { pub async fn build(&self, state: ApiState) -> Api {
let mut app: Router = Router::new(); let mut app: Router = Router::new();
app = app.route("/versions", get(list_available_versions)); app = app.route("/versions", get(list_available_versions));
match &self.version { match &self.version {
Some(v) if v == "v0" => app = app.nest(&format!("/{}", v), v0::get_router(state)), Some(v) if v == "v0" => app = app.nest(&format!("/{}", v), v0::get_router(state)),
_ => app = app.nest("/v0", v0::get_router(state)), _ => app = app.nest("/v0", v0::get_router(state)),
@ -75,7 +80,6 @@ impl ApiBuilder {
} }
} }
async fn list_available_versions() -> Response { async fn list_available_versions() -> Response {
(StatusCode::OK, Json {0: vec!["v0"]}).into_response() (StatusCode::OK, Json { 0: vec!["v0"] }).into_response()
} }

View file

@ -11,8 +11,8 @@ use tracing::debug;
use crate::state::ApiState; use crate::state::ApiState;
use ubisync_lib::{ use ubisync_lib::{
api::element::{ api::element::{
ElementCreateRequest, ElementCreateResponse, ElementGetResponse, ElementSetRequest, ElementCreateRequest, ElementCreateResponse, ElementGetResponse, ElementRemoveResponse,
ElementSetResponse, ElementRemoveResponse, ElementSetRequest, ElementSetResponse,
}, },
types::ElementId, types::ElementId,
}; };
@ -27,9 +27,7 @@ pub(super) async fn get(Path(id): Path<ElementId>, s: Extension<Arc<ApiState>>)
}, },
) )
.into_response(), .into_response(),
Err(_) => { Err(_) => StatusCode::NOT_FOUND.into_response(),
StatusCode::NOT_FOUND.into_response()
}
} }
} }
@ -72,7 +70,13 @@ pub(super) async fn set(
pub(super) async fn remove(Path(id): Path<ElementId>, s: Extension<Arc<ApiState>>) -> Response { pub(super) async fn remove(Path(id): Path<ElementId>, s: Extension<Arc<ApiState>>) -> Response {
let res = s.remove_element(&id); let res = s.remove_element(&id);
match res { match res {
Ok(_) => (StatusCode::OK, Json { 0: ElementRemoveResponse }).into_response(), Ok(_) => (
StatusCode::OK,
Json {
0: ElementRemoveResponse,
},
)
.into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
} }
} }

View file

@ -17,7 +17,6 @@ use tokio::task::JoinHandle;
use crate::state::CommState; use crate::state::CommState;
use crate::Config; use crate::Config;
pub struct CommHandle { pub struct CommHandle {
state: Arc<CommState>, state: Arc<CommState>,
i2p_server: Arc<I2pListener>, i2p_server: Arc<I2pListener>,
@ -196,7 +195,8 @@ impl CommHandle {
} }
#[cfg(test)] #[cfg(test)]
mod tests {use i2p::net::I2pListener; mod tests {
use i2p::net::I2pListener;
use i2p::sam::StreamForward; use i2p::sam::StreamForward;
use i2p::sam_options::SAMOptions; use i2p::sam_options::SAMOptions;
use i2p::Session; use i2p::Session;

View file

@ -5,11 +5,9 @@ use api::{Api, ApiBuilder};
use comm::CommHandle; use comm::CommHandle;
use config::Config; use config::Config;
use i2p::net::I2pSocketAddr; use i2p::net::I2pSocketAddr;
use state::{State, CommState, ApiState}; use state::{ApiState, CommState, State};
use ubisync_lib::{peer::Peer, types::PeerId}; use ubisync_lib::{peer::Peer, types::PeerId};
pub mod api; pub mod api;
pub mod comm; pub mod comm;
pub mod config; pub mod config;
@ -64,4 +62,4 @@ impl Ubisync {
pub fn get_destination(&self) -> anyhow::Result<I2pSocketAddr> { pub fn get_destination(&self) -> anyhow::Result<I2pSocketAddr> {
self.comm_handle.i2p_address() self.comm_handle.i2p_address()
} }
} }

View file

@ -1,9 +1,6 @@
use ubisync::{Ubisync, config::Config}; use ubisync::{config::Config, Ubisync};
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let _node = Ubisync::new(&Config::default()).await.unwrap(); let _node = Ubisync::new(&Config::default()).await.unwrap();
} }

View file

@ -4,7 +4,10 @@ use chrono::Utc;
use cozo::DbInstance; use cozo::DbInstance;
use jsonwebtoken::{DecodingKey, EncodingKey, Validation}; use jsonwebtoken::{DecodingKey, EncodingKey, Validation};
use tracing::debug; use tracing::debug;
use ubisync_lib::{types::{ElementContent, ElementId, Element}, messages::MessageContent}; use ubisync_lib::{
messages::MessageContent,
types::{Element, ElementContent, ElementId},
};
use crate::{api::v0::app::AppId, state::queries}; use crate::{api::v0::app::AppId, state::queries};
@ -32,13 +35,7 @@ impl ApiState {
pub fn add_app(&self, name: &str, description: &str) -> anyhow::Result<AppId> { pub fn add_app(&self, name: &str, description: &str) -> anyhow::Result<AppId> {
let id = AppId::new(); let id = AppId::new();
let last_access = Utc::now(); let last_access = Utc::now();
queries::apps::add( queries::apps::add(self.db(), &id, &last_access, name, description)?;
self.db(),
&id,
&last_access,
name,
description,
)?;
debug!("Successfully added app"); debug!("Successfully added app");
Ok(id) Ok(id)
@ -103,7 +100,7 @@ impl ApiState {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use tracing::Level; use tracing::Level;
use ubisync_lib::{types::ElementContent, tracing_setup}; use ubisync_lib::{tracing_setup, types::ElementContent};
use crate::state::State; use crate::state::State;
@ -113,7 +110,7 @@ mod tests {
#[serial_test::serial] #[serial_test::serial]
async fn test_element_create() { async fn test_element_create() {
tracing_setup!(Level::DEBUG); tracing_setup!(Level::DEBUG);
let state = ApiState::new( let state = ApiState::new(
State::new("mem").await.unwrap(), State::new("mem").await.unwrap(),
"abcdabcdabcdabcdabcdabcdabcdabcd", "abcdabcdabcdabcdabcdabcdabcdabcd",

View file

@ -3,7 +3,10 @@ use std::sync::Arc;
use cozo::DbInstance; use cozo::DbInstance;
use tracing::debug; use tracing::debug;
use ubisync_lib::{types::{Element, ElementContent, ElementId, MessageId, PeerId}, peer::Peer}; use ubisync_lib::{
peer::Peer,
types::{Element, ElementContent, ElementId, MessageId, PeerId},
};
use crate::state::queries; use crate::state::queries;
@ -83,15 +86,18 @@ mod tests {
use crate::state::State; use crate::state::State;
use super::CommState; use super::CommState;
use tracing::Level; use tracing::Level;
use ubisync_lib::{types::{ElementContent, ElementId, MessageId}, tracing_setup}; use ubisync_lib::{
tracing_setup,
types::{ElementContent, ElementId, MessageId},
};
#[tokio::test] #[tokio::test]
#[serial_test::serial] #[serial_test::serial]
async fn test_element_add() { async fn test_element_add() {
tracing_setup!(Level::DEBUG); tracing_setup!(Level::DEBUG);
let state = CommState::new(State::new("mem").await.unwrap()); let state = CommState::new(State::new("mem").await.unwrap());
let id = ElementId::new(); let id = ElementId::new();
state state

View file

@ -4,7 +4,6 @@ use anyhow::Error;
use cozo::DbInstance; use cozo::DbInstance;
use tracing::{debug, error}; use tracing::{debug, error};
mod api_state; mod api_state;
mod comm_state; mod comm_state;
mod queries; mod queries;
@ -12,7 +11,11 @@ mod schema;
pub use api_state::ApiState; pub use api_state::ApiState;
pub use comm_state::CommState; pub use comm_state::CommState;
use ubisync_lib::{types::{ElementId, ElementContent, Element, Tag}, messages::{Message, MessageContent}, peer::Peer}; use ubisync_lib::{
messages::{Message, MessageContent},
peer::Peer,
types::{Element, ElementContent, ElementId, Tag},
};
use crate::comm::CommHandle; use crate::comm::CommHandle;

View file

@ -7,9 +7,7 @@ use tracing::{debug, error};
use crate::{ use crate::{
run_query, run_query,
state::{ state::{Element, ElementContent, ElementId},
Element, ElementContent, ElementId,
},
}; };
use ubisync_lib::types::{MessageId, Tag}; use ubisync_lib::types::{MessageId, Tag};

View file

@ -1,6 +1,6 @@
use anyhow::Error; use anyhow::Error;
use cozo::{DataValue, DbInstance, ScriptMutability}; use cozo::{DataValue, DbInstance, ScriptMutability};
use ubisync_lib::{types::PeerId, peer::Peer}; use ubisync_lib::{peer::Peer, types::PeerId};
use crate::run_query; use crate::run_query;

View file

@ -4,11 +4,11 @@ use tracing::{debug, warn, Level};
use ubisync::{config::Config, Ubisync}; use ubisync::{config::Config, Ubisync};
use ubisync_lib::{ use ubisync_lib::{
api::element::{ElementCreateRequest, ElementGetRequest}, api::element::{ElementCreateRequest, ElementGetRequest},
types::{Element, ElementContent}, tracing_setup, tracing_setup,
types::{Element, ElementContent},
}; };
use ubisync_sdk::UbisyncClient; use ubisync_sdk::UbisyncClient;
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn two_nodes_element_creation() { async fn two_nodes_element_creation() {
tracing_setup!(Level::DEBUG); tracing_setup!(Level::DEBUG);