cargo fmt

This commit is contained in:
tezlm 2023-08-20 19:18:19 -07:00
parent 152b9dc670
commit eeffdfd61b
Signed by: tezlm
GPG key ID: 649733FCD94AFBBA
15 changed files with 89 additions and 49 deletions

View file

@ -288,7 +288,8 @@ async fn main() -> Result<(), Error> {
if is_term && !force && std::str::from_utf8(&blob).is_err() {
return Err(StaticError(
"refusing to output binary data to tty, use `-f` to force",
).into());
)
.into());
}
std::io::stdout().write_all(&blob)?;
}

View file

@ -68,7 +68,12 @@ impl Acl {
}
for (rel_event, rel_info) in relations.values() {
trace!("check ({}, {}, {})", event_type, rel_info.rel_type, rel_event.content.get_type());
trace!(
"check ({}, {}, {})",
event_type,
rel_info.rel_type,
rel_event.content.get_type()
);
let valid_type =
rel_event.content.get_type() == to_event_type || to_event_type == "*";
let valid_rel = &rel_info.rel_type == rel_type || rel_type == "*";
@ -82,9 +87,9 @@ impl Acl {
}
pub fn is_valid(&self) -> bool {
self.users.values().all(|roles| {
roles.iter().all(|role| self.roles.contains_key(role))
})
self.users
.values()
.all(|roles| roles.iter().all(|role| self.roles.contains_key(role)))
}
}

View file

@ -1,5 +1,5 @@
use serde::{Deserialize, Serialize};
use std::collections::{HashSet, HashMap};
use std::collections::{HashMap, HashSet};
// use crate::event::EventContent;
use serde_json::Value;

View file

@ -1,10 +1,10 @@
use hex::FromHex;
use serde::{Deserialize, Serialize};
use std::{
fmt::{Debug, Display},
str::FromStr,
};
use thiserror::Error;
use hex::FromHex;
// TODO: convert to base64?
@ -51,8 +51,7 @@ impl TryFrom<&str> for ItemRef {
if split.next().is_some() {
return Err(ItemRefParseError::ExtraData);
}
let bytes = Vec::from_hex(hash)
.map_err(|_| ItemRefParseError::InvalidHashChar)?;
let bytes = Vec::from_hex(hash).map_err(|_| ItemRefParseError::InvalidHashChar)?;
if bytes.len() != hash_type.get_len() as usize {
return Err(ItemRefParseError::InvalidHashLength);
}

View file

@ -18,7 +18,7 @@ pub struct Query {
/// after filtering, relations are fetched
#[serde(skip_serializing_if = "HashSet::is_empty", default)]
pub relations: HashSet<QueryRelation>,
// TODO: specify (forward) relations to fetch?
// #[serde(skip_serializing_if = "HashSet::is_empty", default)]
// pub fetch: HashSet<QueryRelation>,
@ -38,7 +38,7 @@ pub struct QueryBuilder {
pub enum QueryRelation {
/// (source_type, rel_type)
FromRel(String, String),
/// (source_type, rel_type, target_type)
FromRelTo(String, String, String),
}
@ -60,7 +60,7 @@ impl Query {
pub fn builder() -> QueryBuilder {
QueryBuilder::new()
}
pub fn matches_relationless(&self, event: &Event, allow_redaction: bool) -> bool {
let bad_ref = self.refs.as_ref().is_some_and(|s| !s.contains(&event.id));
let bad_sender = self
@ -75,7 +75,9 @@ impl Query {
.tags
.as_ref()
.is_some_and(|s| s.is_disjoint(&event.derived.tags));
let bad_redact = !allow_redaction && !self.with_redacts && matches!(event.content, EventContent::Redacted(_));
let bad_redact = !allow_redaction
&& !self.with_redacts
&& matches!(event.content, EventContent::Redacted(_));
!(bad_ref || bad_sender || bad_type || bad_tags || bad_redact)
}
@ -126,7 +128,11 @@ impl QueryRelation {
Self::FromRel(source_type.into(), rel_type.into())
}
pub fn from_rel_to(source_type: impl Into<String>, rel_type: impl Into<String>, target_type: impl Into<String>) -> Self {
pub fn from_rel_to(
source_type: impl Into<String>,
rel_type: impl Into<String>,
target_type: impl Into<String>,
) -> Self {
Self::FromRelTo(source_type.into(), rel_type.into(), target_type.into())
}
}
@ -162,7 +168,7 @@ impl QueryBuilder {
}
self
}
pub fn with_relation(mut self, relation: &QueryRelation) -> Self {
self.query.relations.insert(relation.clone());
self

View file

@ -1,4 +1,8 @@
use crate::{Error, routes::util::{P2PAuth, NodeAuth}, consts::{HEADER_GRANT, HEADER_NODE}};
use crate::{
consts::{HEADER_GRANT, HEADER_NODE},
routes::util::{NodeAuth, P2PAuth},
Error,
};
use axum::http::StatusCode;
use bytes::Bytes;
use sha2::Digest;
@ -94,7 +98,13 @@ impl Client {
Ok(Some(Item::from_bytes(bytes)?))
}
pub async fn get_via(&self, item_ref: &ItemRef, via: &str, node_auth: &NodeAuth, grant: Option<&P2PAuth>) -> Result<Option<Item>, Error> {
pub async fn get_via(
&self,
item_ref: &ItemRef,
via: &str,
node_auth: &NodeAuth,
grant: Option<&P2PAuth>,
) -> Result<Option<Item>, Error> {
debug!("get blob through server {}", via);
let url = format!("http://{}/things/{}", via, item_ref);
trace!("auth: {:?}", node_auth);

View file

@ -1,7 +1,7 @@
use clap::{Parser, Subcommand};
use ufh::actor::ActorId;
use crate::peer::Contact;
use serde::{Serialize, Deserialize};
use clap::{Parser, Subcommand};
use serde::{Deserialize, Serialize};
use ufh::actor::ActorId;
#[derive(Debug, Parser, Serialize, Deserialize)]
#[command(

View file

@ -4,11 +4,20 @@
use serde::{Deserialize, Serialize};
use sha2::Digest;
use std::{fmt::{Display, Debug}, str::FromStr};
use tracing::{trace, debug};
use ufh::{item::ItemRef, actor::ActorId};
use std::{
fmt::{Debug, Display},
str::FromStr,
};
use tracing::{debug, trace};
use ufh::{actor::ActorId, item::ItemRef};
use crate::{routes::{util::{NodeAuth, P2PAuth}, actors::Error}, consts::{HEADER_NODE, HEADER_GRANT}};
use crate::{
consts::{HEADER_GRANT, HEADER_NODE},
routes::{
actors::Error,
util::{NodeAuth, P2PAuth},
},
};
/// the length of each key
const KEY_LEN: usize = 20;
@ -98,7 +107,7 @@ impl NodeId {
pub fn new_from_ref(item_ref: &ItemRef) -> Self {
NodeId::new_from_str(&item_ref.to_string())
}
pub fn new_from_actor(actor: &ActorId) -> Self {
NodeId::new_from_str(&actor.to_string())
}
@ -204,7 +213,7 @@ impl Contact {
.json()
.await
}
pub async fn send_auth(
&self,
sender: &Self,

View file

@ -3,10 +3,11 @@
use std::collections::VecDeque;
use crate::{
consts::ALWAYS_VIEWABLE,
items::events::get_relations,
routes::things::Error,
state::db::{sqlite::Sqlite, Database, DbItem, Location},
Relations, consts::ALWAYS_VIEWABLE,
Relations,
};
use tracing::trace;
use ufh::{

View file

@ -1,5 +1,5 @@
use crate::error::Error;
use crate::routes::util::{get_blob, Authenticate, perms};
use crate::routes::util::{get_blob, perms, Authenticate};
use crate::state::db::{Database, DbItem};
use crate::ServerState;
use axum::extract::{Path, State};
@ -25,7 +25,7 @@ pub async fn route(
) -> Response<(StatusCode, HeaderMap, Vec<u8>)> {
tracing::Span::current().record("item_ref", &item_ref.to_string());
debug!("fetch blob");
let grant = if let Some(user) = &auth.user {
let grants = state.grants.read().await;
grants.get(user).cloned()
@ -100,7 +100,8 @@ pub async fn route(
let mut chunks = Vec::with_capacity(file.chunks.len());
for item_ref in &intersection {
let Some(Item::Blob(blob)) = state.items.get(item_ref, grant.as_ref()).await? else {
let Some(Item::Blob(blob)) = state.items.get(item_ref, grant.as_ref()).await?
else {
// should i remove this constraint - allow x.file events to exist without having all blobs?
unreachable!("file didn't reference a blob");
};
@ -124,7 +125,8 @@ pub async fn route(
let mut chunks = Vec::with_capacity(file.chunks.len());
for item_ref in &intersection {
let Some(Item::Blob(blob)) = state.items.get(item_ref, grant.as_ref()).await? else {
let Some(Item::Blob(blob)) = state.items.get(item_ref, grant.as_ref()).await?
else {
unreachable!("file didn't reference a blob");
};
chunks.push(blob);

View file

@ -6,15 +6,16 @@ use axum::{
use bytes::Bytes;
use reqwest::StatusCode;
use std::sync::Arc;
use tracing::{trace, debug};
use tracing::{debug, trace};
use ufh::item::ItemRef;
use super::{Error, Response};
use crate::{
consts::ALWAYS_VIEWABLE,
items::Item,
perms::can_view_event,
routes::util::{perms, Authenticate},
ServerState, consts::ALWAYS_VIEWABLE,
ServerState,
};
#[tracing::instrument(skip_all, fields(item_ref))]

View file

@ -1,5 +1,5 @@
use super::{Error, Response};
use crate::routes::util::{get_blob, Authenticate, perms};
use crate::routes::util::{get_blob, perms, Authenticate};
use crate::state::db::{Database, Thumbnail};
use crate::ServerState;
use axum::extract::{Path, Query, State};

View file

@ -1,7 +1,7 @@
#![allow(unused)]
use crate::items::Create;
use crate::items::events::get_relations;
use crate::items::Create;
use crate::perms::can_view_event;
use crate::routes::util::{perms, Authenticate};
use crate::Error;
@ -116,7 +116,9 @@ async fn sync(state: Arc<ServerState>, ws: &mut WebSocket) -> Result<(), Error>
}
},
},
Msg::Server(Create { event, relations, .. }) => {
Msg::Server(Create {
event, relations, ..
}) => {
let Some(user) = &user else {
continue;
};

View file

@ -347,27 +347,25 @@ impl Database for Sqlite {
FromRelTo(&'a str, &'a str, &'a str),
}
let matchable = match relation {
QueryRelation::FromRel(from_type, rel_type) => Query::FromRel(from_type.as_str(), rel_type.as_str()),
QueryRelation::FromRelTo(from_type, rel_type, to_type) => Query::FromRelTo(from_type.as_str(), rel_type.as_str(), to_type.as_str()),
QueryRelation::FromRel(from_type, rel_type) => {
Query::FromRel(from_type.as_str(), rel_type.as_str())
}
QueryRelation::FromRelTo(from_type, rel_type, to_type) => {
Query::FromRelTo(from_type.as_str(), rel_type.as_str(), to_type.as_str())
}
};
match matchable {
Query::FromRel("*", "*") | Query::FromRelTo("*", "*", "*") => {
builder.push(" OR 1 = 1 ");
}
Query::FromRel("*", rel_type) | Query::FromRelTo("*", rel_type, "*") => {
builder
.push(" OR graph.rel_type = ")
.push_bind(rel_type);
builder.push(" OR graph.rel_type = ").push_bind(rel_type);
}
Query::FromRel(from_type, "*") | Query::FromRelTo(from_type, "*", "*") => {
builder
.push(" OR events_from.type = ")
.push_bind(from_type);
builder.push(" OR events_from.type = ").push_bind(from_type);
}
Query::FromRelTo("*", "*", to_type) => {
builder
.push(" OR events_to.type = ")
.push_bind(to_type);
builder.push(" OR events_to.type = ").push_bind(to_type);
}
Query::FromRelTo(from_type, "*", to_type) => {
builder
@ -385,7 +383,8 @@ impl Database for Sqlite {
.push_bind(to_type)
.push(")");
}
Query::FromRel(from_type, rel_type) | Query::FromRelTo(from_type, rel_type, "*") => {
Query::FromRel(from_type, rel_type)
| Query::FromRelTo(from_type, rel_type, "*") => {
builder
.push(" OR (events_from.type = ")
.push_bind(from_type)

View file

@ -32,7 +32,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)
.with_state(Arc::new(state));
// TODO: real cli (or better yet, config file)
let port = std::env::args().nth(1).as_deref().unwrap_or("3219").parse().expect("invalid number");
let port = std::env::args()
.nth(1)
.as_deref()
.unwrap_or("3219")
.parse()
.expect("invalid number");
let addr = SocketAddr::V4(SocketAddrV4::new("0.0.0.0".parse().unwrap(), port));
axum::Server::bind(&addr)
.serve(router.into_make_service())