Add media cache, improve default styles

This commit is contained in:
asonix
2020-03-25 22:26:45 -05:00
parent 0a42450801
commit 9ada30626b
18 changed files with 613 additions and 65 deletions
+2
View File
@@ -28,6 +28,7 @@ pub enum UrlKind {
Inbox,
Index,
MainKey,
Media(Uuid),
NodeInfo,
Outbox,
}
@@ -136,6 +137,7 @@ impl Config {
UrlKind::Inbox => format!("{}://{}/inbox", scheme, self.hostname),
UrlKind::Index => format!("{}://{}/", scheme, self.hostname),
UrlKind::MainKey => format!("{}://{}/actor#main-key", scheme, self.hostname),
UrlKind::Media(uuid) => format!("{}://{}/media/{}", scheme, self.hostname, uuid),
UrlKind::NodeInfo => format!("{}://{}/nodeinfo/2.0.json", scheme, self.hostname),
UrlKind::Outbox => format!("{}://{}/outbox", scheme, self.hostname),
}
+60
View File
@@ -0,0 +1,60 @@
use activitystreams::primitives::XsdAnyUri;
use bytes::Bytes;
use lru::LruCache;
use std::{collections::HashMap, sync::Arc, time::Duration};
use tokio::sync::{Mutex, RwLock};
use ttl_cache::TtlCache;
use uuid::Uuid;
static MEDIA_DURATION: Duration = Duration::from_secs(60 * 60 * 24 * 2);
#[derive(Clone)]
pub struct Media {
inverse: Arc<Mutex<HashMap<XsdAnyUri, Uuid>>>,
url_cache: Arc<Mutex<LruCache<Uuid, XsdAnyUri>>>,
byte_cache: Arc<RwLock<TtlCache<Uuid, (String, Bytes)>>>,
}
impl Media {
pub fn new() -> Self {
Media {
inverse: Arc::new(Mutex::new(HashMap::new())),
url_cache: Arc::new(Mutex::new(LruCache::new(128))),
byte_cache: Arc::new(RwLock::new(TtlCache::new(128))),
}
}
pub async fn get_uuid(&self, url: &XsdAnyUri) -> Option<Uuid> {
let uuid = self.inverse.lock().await.get(url).cloned()?;
if self.url_cache.lock().await.contains(&uuid) {
return Some(uuid);
}
self.inverse.lock().await.remove(url);
None
}
pub async fn get_url(&self, uuid: Uuid) -> Option<XsdAnyUri> {
self.url_cache.lock().await.get(&uuid).cloned()
}
pub async fn get_bytes(&self, uuid: Uuid) -> Option<(String, Bytes)> {
self.byte_cache.read().await.get(&uuid).cloned()
}
pub async fn store_url(&self, url: &XsdAnyUri) -> Uuid {
let uuid = Uuid::new_v4();
self.inverse.lock().await.insert(url.clone(), uuid);
self.url_cache.lock().await.put(uuid, url.clone());
uuid
}
pub async fn store_bytes(&self, uuid: Uuid, content_type: String, bytes: Bytes) {
self.byte_cache
.write()
.await
.insert(uuid, (content_type, bytes), MEDIA_DURATION);
}
}
+3 -1
View File
@@ -1,9 +1,11 @@
mod actor;
mod media;
mod node;
mod state;
pub use self::{
actor::{Actor, ActorCache},
node::{Node, NodeCache},
media::Media,
node::{Contact, Info, Instance, Node, NodeCache},
state::State,
};
+3
View File
@@ -70,6 +70,9 @@ pub enum MyError {
#[error("Hosts don't match, {0}, {1}")]
HostMismatch(String, String),
#[error("Invalid or missing content type")]
ContentType,
#[error("Couldn't flush buffer")]
FlushBuffer,
+11 -2
View File
@@ -1,4 +1,4 @@
use crate::jobs::JobState;
use crate::{config::UrlKind, jobs::JobState};
use activitystreams::primitives::XsdAnyUri;
use anyhow::Error;
use background_jobs::{Job, Processor};
@@ -44,7 +44,14 @@ impl QueryInstance {
instance.description
};
if let Some(contact) = instance.contact {
if let Some(mut contact) = instance.contact {
if let Some(uuid) = state.media.get_uuid(&contact.avatar).await {
contact.avatar = state.config.generate_url(UrlKind::Media(uuid)).parse()?;
} else {
let uuid = state.media.store_url(&contact.avatar).await;
contact.avatar = state.config.generate_url(UrlKind::Media(uuid)).parse()?;
}
state
.node_cache
.set_contact(
@@ -57,6 +64,8 @@ impl QueryInstance {
.await?;
}
let description = ammonia::clean(&description);
state
.node_cache
.set_instance(
+36 -11
View File
@@ -9,7 +9,8 @@ pub use self::{
};
use crate::{
data::{ActorCache, NodeCache, State},
config::Config,
data::{ActorCache, Media, NodeCache, State},
db::Db,
error::MyError,
jobs::{
@@ -33,17 +34,31 @@ pub fn create_server(db: Db) -> JobServer {
JobServer::new(shared)
}
pub fn create_workers(state: State, actors: ActorCache, job_server: JobServer) {
pub fn create_workers(
state: State,
actors: ActorCache,
job_server: JobServer,
media: Media,
config: Config,
) {
let remote_handle = job_server.remote.clone();
WorkerConfig::new(move || JobState::new(state.clone(), actors.clone(), job_server.clone()))
.register(DeliverProcessor)
.register(DeliverManyProcessor)
.register(NodeinfoProcessor)
.register(InstanceProcessor)
.register(ListenersProcessor)
.set_processor_count("default", 4)
.start(remote_handle);
WorkerConfig::new(move || {
JobState::new(
state.clone(),
actors.clone(),
job_server.clone(),
media.clone(),
config.clone(),
)
})
.register(DeliverProcessor)
.register(DeliverManyProcessor)
.register(NodeinfoProcessor)
.register(InstanceProcessor)
.register(ListenersProcessor)
.set_processor_count("default", 4)
.start(remote_handle);
}
#[derive(Clone)]
@@ -51,6 +66,8 @@ pub struct JobState {
requests: Requests,
state: State,
actors: ActorCache,
config: Config,
media: Media,
node_cache: NodeCache,
job_server: JobServer,
}
@@ -61,11 +78,19 @@ pub struct JobServer {
}
impl JobState {
fn new(state: State, actors: ActorCache, job_server: JobServer) -> Self {
fn new(
state: State,
actors: ActorCache,
job_server: JobServer,
media: Media,
config: Config,
) -> Self {
JobState {
requests: state.requests(),
node_cache: state.node_cache(),
actors,
config,
media,
state,
job_server,
}
+14 -3
View File
@@ -16,7 +16,7 @@ mod routes;
use self::{
args::Args,
config::Config,
data::{ActorCache, State},
data::{ActorCache, Media, State},
db::Db,
jobs::{create_server, create_workers},
middleware::RelayResolver,
@@ -62,6 +62,7 @@ async fn main() -> Result<(), anyhow::Error> {
return Ok(());
}
let media = Media::new();
let state = State::hydrate(config.clone(), &db).await?;
let actors = ActorCache::new(db.clone());
let job_server = create_server(db.clone());
@@ -84,9 +85,11 @@ async fn main() -> Result<(), anyhow::Error> {
let state = state.clone();
let actors = actors.clone();
let job_server = job_server.clone();
let media = media.clone();
let config = config.clone();
Arbiter::new().exec_fn(move || {
create_workers(state, actors, job_server);
create_workers(state, actors, job_server, media, config);
});
}
actix_rt::signal::ctrl_c().await?;
@@ -98,7 +101,13 @@ async fn main() -> Result<(), anyhow::Error> {
let bind_address = config.bind_address();
HttpServer::new(move || {
if !no_jobs {
create_workers(state.clone(), actors.clone(), job_server.clone());
create_workers(
state.clone(),
actors.clone(),
job_server.clone(),
media.clone(),
config.clone(),
);
}
App::new()
@@ -109,7 +118,9 @@ async fn main() -> Result<(), anyhow::Error> {
.data(actors.clone())
.data(config.clone())
.data(job_server.clone())
.data(media.clone())
.service(web::resource("/").route(web::get().to(index)))
.service(web::resource("/media/{path}").route(web::get().to(routes::media)))
.service(
web::resource("/inbox")
.wrap(config.digest_middleware())
+50
View File
@@ -1,6 +1,7 @@
use crate::error::MyError;
use activitystreams::primitives::XsdAnyUri;
use actix_web::client::Client;
use bytes::Bytes;
use http_signature_normalization_actix::prelude::*;
use log::error;
use rsa::{hash::Hashes, padding::PaddingScheme, RSAPrivateKey};
@@ -63,6 +64,55 @@ impl Requests {
})
}
pub async fn fetch_bytes(&self, url: &str) -> Result<(String, Bytes), MyError> {
let mut res = self
.client
.get(url)
.header("Accept", "application/activity+json")
.header("User-Agent", self.user_agent.as_str())
.signature(&self.config, &self.key_id, |signing_string| {
self.sign(signing_string)
})?
.send()
.await
.map_err(|e| {
error!("Couldn't send request to {}, {}", url, e);
MyError::SendRequest
})?;
let content_type = if let Some(content_type) = res.headers().get("content-type") {
if let Ok(s) = content_type.to_str() {
s.to_owned()
} else {
return Err(MyError::ContentType);
}
} else {
return Err(MyError::ContentType);
};
if !res.status().is_success() {
if let Ok(bytes) = res.body().await {
if let Ok(s) = String::from_utf8(bytes.as_ref().to_vec()) {
if !s.is_empty() {
error!("Response, {}", s);
}
}
}
return Err(MyError::Status(res.status()));
}
let bytes = match res.body().limit(1024 * 1024 * 4).await {
Err(e) => {
error!("Coudn't fetch json from {}, {}", url, e);
return Err(MyError::ReceiveResponse);
}
Ok(bytes) => bytes,
};
Ok((content_type, bytes))
}
pub async fn deliver<T>(&self, inbox: XsdAnyUri, item: &T) -> Result<(), MyError>
where
T: serde::ser::Serialize,
-1
View File
@@ -8,7 +8,6 @@ pub async fn route(
config: web::Data<Config>,
) -> Result<HttpResponse, MyError> {
let nodes = state.node_cache().nodes().await;
let mut buf = BufWriter::new(Vec::new());
crate::templates::index(&mut buf, &nodes, &config)?;
+27
View File
@@ -0,0 +1,27 @@
use crate::{data::Media, error::MyError, requests::Requests};
use actix_web::{web, HttpResponse};
use uuid::Uuid;
pub async fn route(
media: web::Data<Media>,
requests: web::Data<Requests>,
uuid: web::Path<Uuid>,
) -> Result<HttpResponse, MyError> {
let uuid = uuid.into_inner();
if let Some((content_type, bytes)) = media.get_bytes(uuid).await {
return Ok(HttpResponse::Ok().content_type(content_type).body(bytes));
}
if let Some(url) = media.get_url(uuid).await {
let (content_type, bytes) = requests.fetch_bytes(url.as_str()).await?;
media
.store_bytes(uuid, content_type.clone(), bytes.clone())
.await;
return Ok(HttpResponse::Ok().content_type(content_type).body(bytes));
}
Ok(HttpResponse::NotFound().finish())
}
+2
View File
@@ -1,6 +1,7 @@
mod actor;
mod inbox;
mod index;
mod media;
mod nodeinfo;
mod statics;
@@ -8,6 +9,7 @@ pub use self::{
actor::route as actor,
inbox::route as inbox,
index::route as index,
media::route as media,
nodeinfo::{route as nodeinfo, well_known as nodeinfo_meta},
statics::route as statics,
};