Database Refactor
combine service/users data w/ mod unit split sliding sync related out of service/users instrument database entry points remove increment crap from database interface de-wrap all database get() calls de-wrap all database insert() calls de-wrap all database remove() calls refactor database interface for async streaming add query key serializer for database implement Debug for result handle add query deserializer for database add deserialization trait for option handle start a stream utils suite de-wrap/asyncify/type-query count_one_time_keys() de-wrap/asyncify users count add admin query users command suite de-wrap/asyncify users exists de-wrap/partially asyncify user filter related asyncify/de-wrap users device/keys related asyncify/de-wrap user auth/misc related asyncify/de-wrap users blurhash asyncify/de-wrap account_data get; merge Data into Service partial asyncify/de-wrap uiaa; merge Data into Service partially asyncify/de-wrap transaction_ids get; merge Data into Service partially asyncify/de-wrap key_backups; merge Data into Service asyncify/de-wrap pusher service getters; merge Data into Service asyncify/de-wrap rooms alias getters/some iterators asyncify/de-wrap rooms directory getters/iterator partially asyncify/de-wrap rooms lazy-loading partially asyncify/de-wrap rooms metadata asyncify/dewrap rooms outlier asyncify/dewrap rooms pdu_metadata dewrap/partially asyncify rooms read receipt de-wrap rooms search service de-wrap/partially asyncify rooms user service partial de-wrap rooms state_compressor de-wrap rooms state_cache de-wrap room state et al de-wrap rooms timeline service additional users device/keys related de-wrap/asyncify sender asyncify services refactor database to TryFuture/TryStream refactor services for TryFuture/TryStream asyncify api handlers additional asyncification for admin module abstract stream related; support reverse streams additional stream conversions asyncify state-res related Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
parent
6001014078
commit
946ca364e0
203 changed files with 12202 additions and 10709 deletions
|
@ -1,152 +0,0 @@
|
|||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use conduit::{Error, Result};
|
||||
use database::Map;
|
||||
use ruma::{
|
||||
api::client::error::ErrorKind,
|
||||
events::{AnyGlobalAccountDataEvent, AnyRawAccountDataEvent, AnyRoomAccountDataEvent, RoomAccountDataEventType},
|
||||
serde::Raw,
|
||||
RoomId, UserId,
|
||||
};
|
||||
|
||||
use crate::{globals, Dep};
|
||||
|
||||
pub(super) struct Data {
|
||||
roomuserdataid_accountdata: Arc<Map>,
|
||||
roomusertype_roomuserdataid: Arc<Map>,
|
||||
services: Services,
|
||||
}
|
||||
|
||||
struct Services {
|
||||
globals: Dep<globals::Service>,
|
||||
}
|
||||
|
||||
impl Data {
|
||||
pub(super) fn new(args: &crate::Args<'_>) -> Self {
|
||||
let db = &args.db;
|
||||
Self {
|
||||
roomuserdataid_accountdata: db["roomuserdataid_accountdata"].clone(),
|
||||
roomusertype_roomuserdataid: db["roomusertype_roomuserdataid"].clone(),
|
||||
services: Services {
|
||||
globals: args.depend::<globals::Service>("globals"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Places one event in the account data of the user and removes the
|
||||
/// previous entry.
|
||||
pub(super) fn update(
|
||||
&self, room_id: Option<&RoomId>, user_id: &UserId, event_type: &RoomAccountDataEventType,
|
||||
data: &serde_json::Value,
|
||||
) -> Result<()> {
|
||||
let mut prefix = room_id
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_default()
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
prefix.push(0xFF);
|
||||
prefix.extend_from_slice(user_id.as_bytes());
|
||||
prefix.push(0xFF);
|
||||
|
||||
let mut roomuserdataid = prefix.clone();
|
||||
roomuserdataid.extend_from_slice(&self.services.globals.next_count()?.to_be_bytes());
|
||||
roomuserdataid.push(0xFF);
|
||||
roomuserdataid.extend_from_slice(event_type.to_string().as_bytes());
|
||||
|
||||
let mut key = prefix;
|
||||
key.extend_from_slice(event_type.to_string().as_bytes());
|
||||
|
||||
if data.get("type").is_none() || data.get("content").is_none() {
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::InvalidParam,
|
||||
"Account data doesn't have all required fields.",
|
||||
));
|
||||
}
|
||||
|
||||
self.roomuserdataid_accountdata.insert(
|
||||
&roomuserdataid,
|
||||
&serde_json::to_vec(&data).expect("to_vec always works on json values"),
|
||||
)?;
|
||||
|
||||
let prev = self.roomusertype_roomuserdataid.get(&key)?;
|
||||
|
||||
self.roomusertype_roomuserdataid
|
||||
.insert(&key, &roomuserdataid)?;
|
||||
|
||||
// Remove old entry
|
||||
if let Some(prev) = prev {
|
||||
self.roomuserdataid_accountdata.remove(&prev)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Searches the account data for a specific kind.
|
||||
pub(super) fn get(
|
||||
&self, room_id: Option<&RoomId>, user_id: &UserId, kind: &RoomAccountDataEventType,
|
||||
) -> Result<Option<Box<serde_json::value::RawValue>>> {
|
||||
let mut key = room_id
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_default()
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
key.push(0xFF);
|
||||
key.extend_from_slice(user_id.as_bytes());
|
||||
key.push(0xFF);
|
||||
key.extend_from_slice(kind.to_string().as_bytes());
|
||||
|
||||
self.roomusertype_roomuserdataid
|
||||
.get(&key)?
|
||||
.and_then(|roomuserdataid| {
|
||||
self.roomuserdataid_accountdata
|
||||
.get(&roomuserdataid)
|
||||
.transpose()
|
||||
})
|
||||
.transpose()?
|
||||
.map(|data| serde_json::from_slice(&data).map_err(|_| Error::bad_database("could not deserialize")))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Returns all changes to the account data that happened after `since`.
|
||||
pub(super) fn changes_since(
|
||||
&self, room_id: Option<&RoomId>, user_id: &UserId, since: u64,
|
||||
) -> Result<Vec<AnyRawAccountDataEvent>> {
|
||||
let mut userdata = HashMap::new();
|
||||
|
||||
let mut prefix = room_id
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_default()
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
prefix.push(0xFF);
|
||||
prefix.extend_from_slice(user_id.as_bytes());
|
||||
prefix.push(0xFF);
|
||||
|
||||
// Skip the data that's exactly at since, because we sent that last time
|
||||
let mut first_possible = prefix.clone();
|
||||
first_possible.extend_from_slice(&(since.saturating_add(1)).to_be_bytes());
|
||||
|
||||
for r in self
|
||||
.roomuserdataid_accountdata
|
||||
.iter_from(&first_possible, false)
|
||||
.take_while(move |(k, _)| k.starts_with(&prefix))
|
||||
.map(|(k, v)| {
|
||||
Ok::<_, Error>((
|
||||
k,
|
||||
match room_id {
|
||||
None => serde_json::from_slice::<Raw<AnyGlobalAccountDataEvent>>(&v)
|
||||
.map(AnyRawAccountDataEvent::Global)
|
||||
.map_err(|_| Error::bad_database("Database contains invalid account data."))?,
|
||||
Some(_) => serde_json::from_slice::<Raw<AnyRoomAccountDataEvent>>(&v)
|
||||
.map(AnyRawAccountDataEvent::Room)
|
||||
.map_err(|_| Error::bad_database("Database contains invalid account data."))?,
|
||||
},
|
||||
))
|
||||
}) {
|
||||
let (kind, data) = r?;
|
||||
userdata.insert(kind, data);
|
||||
}
|
||||
|
||||
Ok(userdata.into_values().collect())
|
||||
}
|
||||
}
|
|
@ -1,52 +1,158 @@
|
|||
mod data;
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use conduit::Result;
|
||||
use data::Data;
|
||||
use conduit::{
|
||||
implement,
|
||||
utils::{stream::TryIgnore, ReadyExt},
|
||||
Err, Error, Result,
|
||||
};
|
||||
use database::{Deserialized, Map};
|
||||
use futures::{StreamExt, TryFutureExt};
|
||||
use ruma::{
|
||||
events::{AnyRawAccountDataEvent, RoomAccountDataEventType},
|
||||
events::{AnyGlobalAccountDataEvent, AnyRawAccountDataEvent, AnyRoomAccountDataEvent, RoomAccountDataEventType},
|
||||
serde::Raw,
|
||||
RoomId, UserId,
|
||||
};
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
use crate::{globals, Dep};
|
||||
|
||||
pub struct Service {
|
||||
services: Services,
|
||||
db: Data,
|
||||
}
|
||||
|
||||
struct Data {
|
||||
roomuserdataid_accountdata: Arc<Map>,
|
||||
roomusertype_roomuserdataid: Arc<Map>,
|
||||
}
|
||||
|
||||
struct Services {
|
||||
globals: Dep<globals::Service>,
|
||||
}
|
||||
|
||||
impl crate::Service for Service {
|
||||
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||
Ok(Arc::new(Self {
|
||||
db: Data::new(&args),
|
||||
services: Services {
|
||||
globals: args.depend::<globals::Service>("globals"),
|
||||
},
|
||||
db: Data {
|
||||
roomuserdataid_accountdata: args.db["roomuserdataid_accountdata"].clone(),
|
||||
roomusertype_roomuserdataid: args.db["roomusertype_roomuserdataid"].clone(),
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
|
||||
}
|
||||
|
||||
impl Service {
|
||||
/// Places one event in the account data of the user and removes the
|
||||
/// previous entry.
|
||||
#[allow(clippy::needless_pass_by_value)]
|
||||
pub fn update(
|
||||
&self, room_id: Option<&RoomId>, user_id: &UserId, event_type: RoomAccountDataEventType,
|
||||
data: &serde_json::Value,
|
||||
) -> Result<()> {
|
||||
self.db.update(room_id, user_id, &event_type, data)
|
||||
/// Places one event in the account data of the user and removes the
|
||||
/// previous entry.
|
||||
#[allow(clippy::needless_pass_by_value)]
|
||||
#[implement(Service)]
|
||||
pub async fn update(
|
||||
&self, room_id: Option<&RoomId>, user_id: &UserId, event_type: RoomAccountDataEventType, data: &serde_json::Value,
|
||||
) -> Result<()> {
|
||||
let event_type = event_type.to_string();
|
||||
let count = self.services.globals.next_count()?;
|
||||
|
||||
let mut prefix = room_id
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_default()
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
prefix.push(0xFF);
|
||||
prefix.extend_from_slice(user_id.as_bytes());
|
||||
prefix.push(0xFF);
|
||||
|
||||
let mut roomuserdataid = prefix.clone();
|
||||
roomuserdataid.extend_from_slice(&count.to_be_bytes());
|
||||
roomuserdataid.push(0xFF);
|
||||
roomuserdataid.extend_from_slice(event_type.as_bytes());
|
||||
|
||||
let mut key = prefix;
|
||||
key.extend_from_slice(event_type.as_bytes());
|
||||
|
||||
if data.get("type").is_none() || data.get("content").is_none() {
|
||||
return Err!(Request(InvalidParam("Account data doesn't have all required fields.")));
|
||||
}
|
||||
|
||||
/// Searches the account data for a specific kind.
|
||||
#[allow(clippy::needless_pass_by_value)]
|
||||
pub fn get(
|
||||
&self, room_id: Option<&RoomId>, user_id: &UserId, event_type: RoomAccountDataEventType,
|
||||
) -> Result<Option<Box<serde_json::value::RawValue>>> {
|
||||
self.db.get(room_id, user_id, &event_type)
|
||||
self.db.roomuserdataid_accountdata.insert(
|
||||
&roomuserdataid,
|
||||
&serde_json::to_vec(&data).expect("to_vec always works on json values"),
|
||||
);
|
||||
|
||||
let prev_key = (room_id, user_id, &event_type);
|
||||
let prev = self.db.roomusertype_roomuserdataid.qry(&prev_key).await;
|
||||
|
||||
self.db
|
||||
.roomusertype_roomuserdataid
|
||||
.insert(&key, &roomuserdataid);
|
||||
|
||||
// Remove old entry
|
||||
if let Ok(prev) = prev {
|
||||
self.db.roomuserdataid_accountdata.remove(&prev);
|
||||
}
|
||||
|
||||
/// Returns all changes to the account data that happened after `since`.
|
||||
#[tracing::instrument(skip_all, name = "since", level = "debug")]
|
||||
pub fn changes_since(
|
||||
&self, room_id: Option<&RoomId>, user_id: &UserId, since: u64,
|
||||
) -> Result<Vec<AnyRawAccountDataEvent>> {
|
||||
self.db.changes_since(room_id, user_id, since)
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Searches the account data for a specific kind.
|
||||
#[implement(Service)]
|
||||
pub async fn get(
|
||||
&self, room_id: Option<&RoomId>, user_id: &UserId, kind: RoomAccountDataEventType,
|
||||
) -> Result<Box<RawValue>> {
|
||||
let key = (room_id, user_id, kind.to_string());
|
||||
self.db
|
||||
.roomusertype_roomuserdataid
|
||||
.qry(&key)
|
||||
.and_then(|roomuserdataid| self.db.roomuserdataid_accountdata.qry(&roomuserdataid))
|
||||
.await
|
||||
.deserialized_json()
|
||||
}
|
||||
|
||||
/// Returns all changes to the account data that happened after `since`.
|
||||
#[implement(Service)]
|
||||
pub async fn changes_since(
|
||||
&self, room_id: Option<&RoomId>, user_id: &UserId, since: u64,
|
||||
) -> Result<Vec<AnyRawAccountDataEvent>> {
|
||||
let mut userdata = HashMap::new();
|
||||
|
||||
let mut prefix = room_id
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_default()
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
prefix.push(0xFF);
|
||||
prefix.extend_from_slice(user_id.as_bytes());
|
||||
prefix.push(0xFF);
|
||||
|
||||
// Skip the data that's exactly at since, because we sent that last time
|
||||
let mut first_possible = prefix.clone();
|
||||
first_possible.extend_from_slice(&(since.saturating_add(1)).to_be_bytes());
|
||||
|
||||
self.db
|
||||
.roomuserdataid_accountdata
|
||||
.raw_stream_from(&first_possible)
|
||||
.ignore_err()
|
||||
.ready_take_while(move |(k, _)| k.starts_with(&prefix))
|
||||
.map(|(k, v)| {
|
||||
let v = match room_id {
|
||||
None => serde_json::from_slice::<Raw<AnyGlobalAccountDataEvent>>(v)
|
||||
.map(AnyRawAccountDataEvent::Global)
|
||||
.map_err(|_| Error::bad_database("Database contains invalid account data."))?,
|
||||
Some(_) => serde_json::from_slice::<Raw<AnyRoomAccountDataEvent>>(v)
|
||||
.map(AnyRawAccountDataEvent::Room)
|
||||
.map_err(|_| Error::bad_database("Database contains invalid account data."))?,
|
||||
};
|
||||
|
||||
Ok((k.to_owned(), v))
|
||||
})
|
||||
.ignore_err()
|
||||
.ready_for_each(|(kind, data)| {
|
||||
userdata.insert(kind, data);
|
||||
})
|
||||
.await;
|
||||
|
||||
Ok(userdata.into_values().collect())
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue