Use existing caches
This commit is contained in:
-100
@@ -1,100 +0,0 @@
|
||||
use std::collections::{BTreeMap, HashMap, LinkedList};
|
||||
|
||||
pub struct WeightedCache<K, V>
|
||||
where
|
||||
K: std::hash::Hash + Eq + Clone,
|
||||
{
|
||||
size: usize,
|
||||
capacity: usize,
|
||||
forward: HashMap<K, (V, Count)>,
|
||||
backward: BTreeMap<Count, LinkedList<K>>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct Count(usize);
|
||||
|
||||
impl<K, V> WeightedCache<K, V>
|
||||
where
|
||||
K: std::hash::Hash + Eq + Clone,
|
||||
{
|
||||
/// Create a new Weighted Cache
|
||||
///
|
||||
/// panics if capacity is 0
|
||||
pub fn new(capacity: usize) -> Self {
|
||||
if capacity == 0 {
|
||||
panic!("Cache Capacity must be > 0");
|
||||
}
|
||||
|
||||
WeightedCache {
|
||||
size: 0,
|
||||
capacity,
|
||||
forward: HashMap::new(),
|
||||
backward: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets a value from the weighted cache
|
||||
pub fn get(&mut self, key: K) -> Option<&V> {
|
||||
let (value, count) = self.forward.get_mut(&key)?;
|
||||
|
||||
if let Some(v) = self.backward.get_mut(count) {
|
||||
v.drain_filter(|item| item == &key);
|
||||
}
|
||||
|
||||
count.0 += 1;
|
||||
|
||||
let entry = self.backward.entry(*count).or_insert(LinkedList::new());
|
||||
entry.push_back(key);
|
||||
|
||||
Some(&*value)
|
||||
}
|
||||
|
||||
/// set a value in the weighted cache
|
||||
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
|
||||
if self.forward.contains_key(&key) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let ret = if self.size >= self.capacity {
|
||||
self.remove_least()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let count = Count(1);
|
||||
self.forward.insert(key.clone(), (value, count));
|
||||
let entry = self.backward.entry(count).or_insert(LinkedList::new());
|
||||
|
||||
entry.push_back(key);
|
||||
self.size += 1;
|
||||
|
||||
ret
|
||||
}
|
||||
|
||||
fn remove_least(&mut self) -> Option<V> {
|
||||
let items = self.backward.values_mut().next()?;
|
||||
|
||||
let oldest = items.pop_front()?;
|
||||
let length = items.len();
|
||||
drop(items);
|
||||
|
||||
let (item, count) = self.forward.remove(&oldest)?;
|
||||
|
||||
if length == 0 {
|
||||
self.backward.remove(&count);
|
||||
self.backward = self
|
||||
.backward
|
||||
.clone()
|
||||
.into_iter()
|
||||
.map(|(mut k, v)| {
|
||||
k.0 -= count.0;
|
||||
(k, v)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
self.size -= 1;
|
||||
|
||||
Some(item)
|
||||
}
|
||||
}
|
||||
+16
-6
@@ -2,7 +2,6 @@ use activitystreams::primitives::XsdAnyUri;
|
||||
use actix::Addr;
|
||||
use actix_web::{client::Client, web, Responder};
|
||||
use log::info;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
apub::{AcceptedActors, AcceptedObjects, ValidTypes},
|
||||
@@ -20,11 +19,10 @@ pub async fn inbox(
|
||||
client: web::Data<Client>,
|
||||
input: web::Json<AcceptedObjects>,
|
||||
) -> Result<impl Responder, MyError> {
|
||||
let _state = state.into_inner();
|
||||
let input = input.into_inner();
|
||||
|
||||
info!("Relaying {} for {}", input.object.id(), input.actor);
|
||||
let actor = fetch_actor(client.into_inner(), &input.actor).await?;
|
||||
let actor = fetch_actor(state, client, &input.actor).await?;
|
||||
info!("Actor, {:#?}", actor);
|
||||
|
||||
match input.kind {
|
||||
@@ -38,8 +36,16 @@ pub async fn inbox(
|
||||
Ok("{}")
|
||||
}
|
||||
|
||||
async fn fetch_actor(client: Arc<Client>, actor_id: &XsdAnyUri) -> Result<AcceptedActors, MyError> {
|
||||
client
|
||||
async fn fetch_actor(
|
||||
state: web::Data<State>,
|
||||
client: web::Data<Client>,
|
||||
actor_id: &XsdAnyUri,
|
||||
) -> Result<AcceptedActors, MyError> {
|
||||
if let Some(actor) = state.get_actor(actor_id).await {
|
||||
return Ok(actor);
|
||||
}
|
||||
|
||||
let actor: AcceptedActors = client
|
||||
.get(actor_id.as_ref())
|
||||
.header("Accept", "application/activity+json")
|
||||
.send()
|
||||
@@ -47,7 +53,11 @@ async fn fetch_actor(client: Arc<Client>, actor_id: &XsdAnyUri) -> Result<Accept
|
||||
.map_err(|_| MyError)?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|_| MyError)
|
||||
.map_err(|_| MyError)?;
|
||||
|
||||
state.cache_actor(actor_id.to_owned(), actor.clone()).await;
|
||||
|
||||
Ok(actor)
|
||||
}
|
||||
|
||||
impl actix_web::error::ResponseError for MyError {}
|
||||
|
||||
+4
-2
@@ -15,8 +15,10 @@ impl ArbiterLabelFactory {
|
||||
}
|
||||
|
||||
pub fn set_label(&self) {
|
||||
let id = self.0.fetch_add(1, Ordering::SeqCst);
|
||||
actix::Arbiter::set_item(ArbiterLabel(id));
|
||||
if !actix::Arbiter::contains_item::<ArbiterLabel>() {
|
||||
let id = self.0.fetch_add(1, Ordering::SeqCst);
|
||||
actix::Arbiter::set_item(ArbiterLabel(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ use actix_web::{client::Client, web, App, HttpServer, Responder};
|
||||
use bb8_postgres::tokio_postgres;
|
||||
|
||||
mod apub;
|
||||
mod cache;
|
||||
mod db_actor;
|
||||
mod inbox;
|
||||
mod label;
|
||||
|
||||
+29
-11
@@ -2,32 +2,49 @@ use activitystreams::primitives::XsdAnyUri;
|
||||
use anyhow::Error;
|
||||
use bb8_postgres::tokio_postgres::{row::Row, Client};
|
||||
use futures::try_join;
|
||||
use lru::LruCache;
|
||||
use std::{collections::HashSet, sync::Arc};
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use tokio::sync::RwLock;
|
||||
use ttl_cache::TtlCache;
|
||||
|
||||
use crate::{cache::WeightedCache, db_actor::Pool};
|
||||
use crate::{apub::AcceptedActors, db_actor::Pool};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct State {
|
||||
cache: Arc<Mutex<WeightedCache<XsdAnyUri, XsdAnyUri>>>,
|
||||
actor_cache: Arc<RwLock<TtlCache<XsdAnyUri, AcceptedActors>>>,
|
||||
actor_id_cache: Arc<RwLock<LruCache<XsdAnyUri, XsdAnyUri>>>,
|
||||
blocks: Arc<RwLock<HashSet<XsdAnyUri>>>,
|
||||
whitelists: Arc<RwLock<HashSet<XsdAnyUri>>>,
|
||||
listeners: Arc<RwLock<HashSet<XsdAnyUri>>>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub async fn is_cached(&self, object_id: XsdAnyUri) -> bool {
|
||||
let cache = self.cache.clone();
|
||||
pub async fn get_actor(&self, actor_id: &XsdAnyUri) -> Option<AcceptedActors> {
|
||||
let cache = self.actor_cache.clone();
|
||||
|
||||
let mut lock = cache.lock().await;
|
||||
lock.get(object_id).is_some()
|
||||
let read_guard = cache.read().await;
|
||||
read_guard.get(actor_id).cloned()
|
||||
}
|
||||
|
||||
pub async fn cache_actor(&self, actor_id: XsdAnyUri, actor: AcceptedActors) {
|
||||
let cache = self.actor_cache.clone();
|
||||
|
||||
let mut write_guard = cache.write().await;
|
||||
write_guard.insert(actor_id, actor, std::time::Duration::from_secs(3600));
|
||||
}
|
||||
|
||||
pub async fn is_cached(&self, object_id: &XsdAnyUri) -> bool {
|
||||
let cache = self.actor_id_cache.clone();
|
||||
|
||||
let read_guard = cache.read().await;
|
||||
read_guard.contains(object_id)
|
||||
}
|
||||
|
||||
pub async fn cache(&self, object_id: XsdAnyUri, actor_id: XsdAnyUri) {
|
||||
let cache = self.cache.clone();
|
||||
let cache = self.actor_id_cache.clone();
|
||||
|
||||
let mut lock = cache.lock().await;
|
||||
lock.insert(object_id, actor_id);
|
||||
let mut write_guard = cache.write().await;
|
||||
write_guard.put(object_id, actor_id);
|
||||
}
|
||||
|
||||
pub async fn add_block(&self, client: &Client, block: XsdAnyUri) -> Result<(), Error> {
|
||||
@@ -103,7 +120,8 @@ impl State {
|
||||
let (blocks, whitelists, listeners) = try_join!(f1, f2, f3)?;
|
||||
|
||||
Ok(State {
|
||||
cache: Arc::new(Mutex::new(WeightedCache::new(1024 * 8))),
|
||||
actor_cache: Arc::new(RwLock::new(TtlCache::new(1024 * 8))),
|
||||
actor_id_cache: Arc::new(RwLock::new(LruCache::new(1024 * 8))),
|
||||
blocks: Arc::new(RwLock::new(blocks)),
|
||||
whitelists: Arc::new(RwLock::new(whitelists)),
|
||||
listeners: Arc::new(RwLock::new(listeners)),
|
||||
|
||||
Reference in New Issue
Block a user