More shuffling, store actors in db

This commit is contained in:
asonix
2020-03-23 17:17:53 -05:00
parent 9925e41673
commit e4c95a8168
23 changed files with 535 additions and 159 deletions
+262
View File
@@ -0,0 +1,262 @@
use crate::{apub::AcceptedActors, db::Db, error::MyError, requests::Requests};
use activitystreams::primitives::XsdAnyUri;
use log::error;
use std::{collections::HashSet, sync::Arc, time::Duration};
use tokio::sync::RwLock;
use ttl_cache::TtlCache;
use uuid::Uuid;
const REFETCH_DURATION: u64 = 60 * 2;
#[derive(Clone)]
pub struct ActorCache {
db: Db,
cache: Arc<RwLock<TtlCache<XsdAnyUri, Actor>>>,
following: Arc<RwLock<HashSet<XsdAnyUri>>>,
}
impl ActorCache {
pub fn new(db: Db) -> Self {
let cache = ActorCache {
db,
cache: Arc::new(RwLock::new(TtlCache::new(1024 * 8))),
following: Arc::new(RwLock::new(HashSet::new())),
};
cache.spawn_rehydrate();
cache
}
pub async fn is_following(&self, id: &XsdAnyUri) -> bool {
self.following.read().await.contains(id)
}
pub async fn get(&self, id: &XsdAnyUri, requests: &Requests) -> Result<Actor, MyError> {
if let Some(actor) = self.cache.read().await.get(id) {
return Ok(actor.clone());
}
if let Some(actor) = self.lookup(id).await? {
self.cache.write().await.insert(
id.clone(),
actor.clone(),
Duration::from_secs(REFETCH_DURATION),
);
return Ok(actor);
}
let accepted_actor = requests.fetch::<AcceptedActors>(id.as_str()).await?;
let actor_host = accepted_actor.id.as_url().host();
let inbox_host = accepted_actor.inbox().as_url().host();
if actor_host != inbox_host {
let actor_host = actor_host.map(|h| h.to_string()).unwrap_or(String::new());
let inbox_host = inbox_host.map(|h| h.to_string()).unwrap_or(String::new());
return Err(MyError::HostMismatch(actor_host, inbox_host));
}
let inbox = accepted_actor.inbox().clone();
let actor = Actor {
id: accepted_actor.id,
public_key: accepted_actor.public_key.public_key_pem,
public_key_id: accepted_actor.public_key.id,
inbox,
};
self.cache.write().await.insert(
id.clone(),
actor.clone(),
Duration::from_secs(REFETCH_DURATION),
);
self.update(id, &actor.public_key, &actor.public_key_id)
.await?;
Ok(actor)
}
pub async fn follower(&self, actor: &Actor) -> Result<(), MyError> {
self.save(actor.clone()).await
}
pub async fn cache_follower(&self, id: XsdAnyUri) {
self.following.write().await.insert(id);
}
pub async fn bust_follower(&self, id: &XsdAnyUri) {
self.following.write().await.remove(id);
}
pub async fn unfollower(&self, actor: &Actor) -> Result<Option<Uuid>, MyError> {
let conn = self.db.pool().get().await?;
let row_opt = conn
.query_opt(
"DELETE FROM actors WHERE actor_id = $1::TEXT RETURNING listener_id;",
&[&actor.id.as_str()],
)
.await?;
let row = if let Some(row) = row_opt {
row
} else {
return Ok(None);
};
let listener_id: Uuid = row.try_get(0)?;
let row_opt = conn
.query_opt(
"SELECT FROM actors WHERE listener_id = $1::UUID;",
&[&listener_id],
)
.await?;
if row_opt.is_none() {
return Ok(Some(listener_id));
}
Ok(None)
}
async fn lookup(&self, id: &XsdAnyUri) -> Result<Option<Actor>, MyError> {
let conn = self.db.pool().get().await?;
let row_opt = conn
.query_opt(
"SELECT listeners.actor_id, actors.public_key, actors.public_key_id
FROM listeners
INNER JOIN actors ON actors.listener_id = listeners.id
WHERE
actors.actor_id = $1::TEXT
AND
actors.updated_at + INTERVAL '120 seconds' < NOW()
LIMIT 1;",
&[&id.as_str()],
)
.await?;
let row = if let Some(row) = row_opt {
row
} else {
return Ok(None);
};
let inbox: String = row.try_get(0)?;
let public_key_id: String = row.try_get(2)?;
Ok(Some(Actor {
id: id.clone(),
inbox: inbox.parse()?,
public_key: row.try_get(1)?,
public_key_id: public_key_id.parse()?,
}))
}
async fn save(&self, actor: Actor) -> Result<(), MyError> {
let conn = self.db.pool().get().await?;
let row_opt = conn
.query_opt(
"SELECT id FROM listeners WHERE actor_id = $1::TEXT LIMIT 1;",
&[&actor.inbox.as_str()],
)
.await?;
let row = if let Some(row) = row_opt {
row
} else {
return Err(MyError::NotSubscribed(actor.id.as_str().to_owned()));
};
let listener_id: Uuid = row.try_get(0)?;
conn.execute(
"INSERT INTO actors (actor_id, public_key, public_key_id, listener_id, created_at, updated_at)
VALUES ($1::TEXT, $2::TEXT, $3::TEXT, $4::UUID, 'now', 'now')
ON CONFLICT (actor_id)
DO UPDATE SET public_key = $2::TEXT;",
&[&actor.id.as_str(), &actor.public_key, &actor.public_key_id.as_str(), &listener_id],
)
.await?;
Ok(())
}
async fn update(
&self,
id: &XsdAnyUri,
public_key: &str,
public_key_id: &XsdAnyUri,
) -> Result<(), MyError> {
let conn = self.db.pool().get().await?;
conn.execute(
"UPDATE actors
SET public_key = $2::TEXT, public_key_id = $3::TEXT
WHERE actor_id = $1::TEXT;",
&[&id.as_str(), &public_key, &public_key_id.as_str()],
)
.await?;
Ok(())
}
fn spawn_rehydrate(&self) {
use actix::clock::{interval_at, Instant};
let this = self.clone();
actix::spawn(async move {
let mut interval = interval_at(Instant::now(), Duration::from_secs(60 * 10));
loop {
if let Err(e) = this.rehydrate().await {
error!("Error rehydrating follows, {}", e);
}
interval.tick().await;
}
});
}
async fn rehydrate(&self) -> Result<(), MyError> {
let conn = self.db.pool().get().await?;
let rows = conn.query("SELECT actor_id FROM actors;", &[]).await?;
let actor_ids = rows
.into_iter()
.filter_map(|row| match row.try_get(0) {
Ok(s) => {
let s: String = s;
match s.parse() {
Ok(s) => Some(s),
Err(e) => {
error!("Error parsing actor id, {}", e);
None
}
}
}
Err(e) => {
error!("Error getting actor id from row, {}", e);
None
}
})
.collect();
let mut write_guard = self.following.write().await;
*write_guard = actor_ids;
Ok(())
}
}
#[derive(Clone)]
pub struct Actor {
pub id: XsdAnyUri,
pub public_key: String,
pub public_key_id: XsdAnyUri,
pub inbox: XsdAnyUri,
}
+9
View File
@@ -0,0 +1,9 @@
mod actor;
mod node;
mod state;
pub use self::{
actor::{Actor, ActorCache},
node::{Node, NodeCache},
state::State,
};
+194
View File
@@ -0,0 +1,194 @@
use activitystreams::primitives::XsdAnyUri;
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use tokio::sync::RwLock;
pub type ListenersCache = Arc<RwLock<HashSet<XsdAnyUri>>>;
#[derive(Clone)]
pub struct NodeCache {
listeners: ListenersCache,
nodes: Arc<RwLock<HashMap<XsdAnyUri, Node>>>,
}
impl NodeCache {
pub fn new(listeners: ListenersCache) -> Self {
NodeCache {
listeners,
nodes: Arc::new(RwLock::new(HashMap::new())),
}
}
pub async fn nodes(&self) -> Vec<Node> {
let listeners: HashSet<_> = self.listeners.read().await.clone();
self.nodes
.read()
.await
.iter()
.filter_map(|(k, v)| {
if listeners.contains(k) {
Some(v.clone())
} else {
None
}
})
.collect()
}
pub async fn set_info(
&self,
listener: XsdAnyUri,
software: String,
version: String,
reg: bool,
) {
if !self.listeners.read().await.contains(&listener) {
let mut nodes = self.nodes.write().await;
nodes.remove(&listener);
return;
}
let mut write_guard = self.nodes.write().await;
let node = write_guard
.entry(listener.clone())
.or_insert(Node::new(listener));
node.set_info(software, version, reg);
}
pub async fn set_instance(
&self,
listener: XsdAnyUri,
title: String,
description: String,
version: String,
reg: bool,
requires_approval: bool,
) {
if !self.listeners.read().await.contains(&listener) {
let mut nodes = self.nodes.write().await;
nodes.remove(&listener);
return;
}
let mut write_guard = self.nodes.write().await;
let node = write_guard
.entry(listener.clone())
.or_insert(Node::new(listener));
node.set_instance(title, description, version, reg, requires_approval);
}
pub async fn set_contact(
&self,
listener: XsdAnyUri,
username: String,
display_name: String,
url: XsdAnyUri,
avatar: XsdAnyUri,
) {
if !self.listeners.read().await.contains(&listener) {
let mut nodes = self.nodes.write().await;
nodes.remove(&listener);
return;
}
let mut write_guard = self.nodes.write().await;
let node = write_guard
.entry(listener.clone())
.or_insert(Node::new(listener));
node.set_contact(username, display_name, url, avatar);
}
}
#[derive(Clone, Debug)]
pub struct Node {
pub base: XsdAnyUri,
pub info: Option<Info>,
pub instance: Option<Instance>,
pub contact: Option<Contact>,
}
impl Node {
pub fn new(mut uri: XsdAnyUri) -> Self {
let url = uri.as_mut();
url.set_fragment(None);
url.set_query(None);
url.set_path("");
Node {
base: uri,
info: None,
instance: None,
contact: None,
}
}
fn set_info(&mut self, software: String, version: String, reg: bool) -> &mut Self {
self.info = Some(Info {
software,
version,
reg,
});
self
}
fn set_instance(
&mut self,
title: String,
description: String,
version: String,
reg: bool,
requires_approval: bool,
) -> &mut Self {
self.instance = Some(Instance {
title,
description,
version,
reg,
requires_approval,
});
self
}
fn set_contact(
&mut self,
username: String,
display_name: String,
url: XsdAnyUri,
avatar: XsdAnyUri,
) -> &mut Self {
self.contact = Some(Contact {
username,
display_name,
url,
avatar,
});
self
}
}
#[derive(Clone, Debug)]
pub struct Info {
pub software: String,
pub version: String,
pub reg: bool,
}
#[derive(Clone, Debug)]
pub struct Instance {
pub title: String,
pub description: String,
pub version: String,
pub reg: bool,
pub requires_approval: bool,
}
#[derive(Clone, Debug)]
pub struct Contact {
pub username: String,
pub display_name: String,
pub url: XsdAnyUri,
pub avatar: XsdAnyUri,
}
+231
View File
@@ -0,0 +1,231 @@
use crate::{
config::{Config, UrlKind},
data::NodeCache,
db::Db,
error::MyError,
requests::Requests,
};
use activitystreams::primitives::XsdAnyUri;
use actix::clock::{interval_at, Duration, Instant};
use actix_web::web;
use futures::{join, try_join};
use log::{error, info};
use lru::LruCache;
use rand::thread_rng;
use rsa::{RSAPrivateKey, RSAPublicKey};
use std::{collections::HashSet, sync::Arc};
use tokio::sync::RwLock;
#[derive(Clone)]
pub struct State {
pub public_key: RSAPublicKey,
private_key: RSAPrivateKey,
config: Config,
actor_id_cache: Arc<RwLock<LruCache<XsdAnyUri, XsdAnyUri>>>,
blocks: Arc<RwLock<HashSet<String>>>,
whitelists: Arc<RwLock<HashSet<String>>>,
listeners: Arc<RwLock<HashSet<XsdAnyUri>>>,
node_cache: NodeCache,
}
impl State {
pub fn node_cache(&self) -> NodeCache {
self.node_cache.clone()
}
pub fn requests(&self) -> Requests {
Requests::new(
self.config.generate_url(UrlKind::MainKey),
self.private_key.clone(),
format!(
"Actix Web 3.0.0-alpha.1 ({}/{}; +{})",
self.config.software_name(),
self.config.software_version(),
self.config.generate_url(UrlKind::Index),
),
)
}
pub async fn bust_whitelist(&self, whitelist: &str) {
let mut write_guard = self.whitelists.write().await;
write_guard.remove(whitelist);
}
pub async fn bust_block(&self, block: &str) {
let mut write_guard = self.blocks.write().await;
write_guard.remove(block);
}
pub async fn bust_listener(&self, inbox: &XsdAnyUri) {
let mut write_guard = self.listeners.write().await;
write_guard.remove(inbox);
}
pub async fn listeners(&self) -> Vec<XsdAnyUri> {
let read_guard = self.listeners.read().await;
read_guard.iter().cloned().collect()
}
pub async fn blocks(&self) -> Vec<String> {
let read_guard = self.blocks.read().await;
read_guard.iter().cloned().collect()
}
pub async fn listeners_without(&self, inbox: &XsdAnyUri, domain: &str) -> Vec<XsdAnyUri> {
let read_guard = self.listeners.read().await;
read_guard
.iter()
.filter_map(|listener| {
if let Some(dom) = listener.as_url().domain() {
if listener != inbox && dom != domain {
return Some(listener.clone());
}
}
None
})
.collect()
}
pub async fn is_whitelisted(&self, actor_id: &XsdAnyUri) -> bool {
if !self.config.whitelist_mode() {
return true;
}
if let Some(host) = actor_id.as_url().host() {
let read_guard = self.whitelists.read().await;
return read_guard.contains(&host.to_string());
}
false
}
pub async fn is_blocked(&self, actor_id: &XsdAnyUri) -> bool {
if let Some(host) = actor_id.as_url().host() {
let read_guard = self.blocks.read().await;
return read_guard.contains(&host.to_string());
}
true
}
pub async fn is_listener(&self, actor_id: &XsdAnyUri) -> bool {
let read_guard = self.listeners.read().await;
read_guard.contains(actor_id)
}
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 mut write_guard = self.actor_id_cache.write().await;
write_guard.put(object_id, actor_id);
}
pub async fn cache_block(&self, host: String) {
let mut write_guard = self.blocks.write().await;
write_guard.insert(host);
}
pub async fn cache_whitelist(&self, host: String) {
let mut write_guard = self.whitelists.write().await;
write_guard.insert(host);
}
pub async fn cache_listener(&self, listener: XsdAnyUri) {
let mut write_guard = self.listeners.write().await;
write_guard.insert(listener);
}
pub async fn rehydrate(&self, db: &Db) -> Result<(), MyError> {
let f1 = db.hydrate_blocks();
let f2 = db.hydrate_whitelists();
let f3 = db.hydrate_listeners();
let (blocks, whitelists, listeners) = try_join!(f1, f2, f3)?;
join!(
async move {
let mut write_guard = self.listeners.write().await;
*write_guard = listeners;
},
async move {
let mut write_guard = self.whitelists.write().await;
*write_guard = whitelists;
},
async move {
let mut write_guard = self.blocks.write().await;
*write_guard = blocks;
}
);
Ok(())
}
pub async fn hydrate(config: Config, db: &Db) -> Result<Self, MyError> {
let f1 = db.hydrate_blocks();
let f2 = db.hydrate_whitelists();
let f3 = db.hydrate_listeners();
let f4 = async move {
if let Some(key) = db.hydrate_private_key().await? {
Ok(key)
} else {
info!("Generating new keys");
let key = web::block(move || {
let mut rng = thread_rng();
RSAPrivateKey::new(&mut rng, 4096)
})
.await?;
db.update_private_key(&key).await?;
Ok(key)
}
};
let (blocks, whitelists, listeners, private_key) = try_join!(f1, f2, f3, f4)?;
let public_key = private_key.to_public_key();
let listeners = Arc::new(RwLock::new(listeners));
let state = State {
public_key,
private_key,
config,
actor_id_cache: Arc::new(RwLock::new(LruCache::new(1024 * 8))),
blocks: Arc::new(RwLock::new(blocks)),
whitelists: Arc::new(RwLock::new(whitelists)),
listeners: listeners.clone(),
node_cache: NodeCache::new(listeners),
};
state.spawn_rehydrate(db.clone());
Ok(state)
}
fn spawn_rehydrate(&self, db: Db) {
let state = self.clone();
actix::spawn(async move {
let start = Instant::now();
let duration = Duration::from_secs(60 * 10);
let mut interval = interval_at(start, duration);
loop {
interval.tick().await;
match state.rehydrate(&db).await {
Err(e) => error!("Error rehydrating, {}", e),
_ => (),
}
}
});
}
}