Upgrade Ruma again

This commit is contained in:
Jonas Platte 2022-06-03 11:29:51 +02:00
parent 6454ff2c3d
commit 86d5bbd27b
No known key found for this signature in database
GPG key ID: CC154DE0E30B7C67
24 changed files with 408 additions and 344 deletions

501
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -21,7 +21,7 @@ tower-http = { version = "0.2.1", features = ["add-extension", "cors", "compress
# Used for matrix spec type definitions and helpers
#ruma = { version = "0.4.0", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
ruma = { git = "https://github.com/ruma/ruma", rev = "3ec82181581b6411d2fa96c196bc96052236d3a5", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-pre-spec", "unstable-exhaustive-types"] }
ruma = { git = "https://github.com/ruma/ruma", rev = "a8e7c47bbe00047adcd10b2e5e860fd4d8cbf9fe", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-pre-spec", "unstable-exhaustive-types"] }
#ruma = { git = "https://github.com/timokoesters/ruma", rev = "50c1db7e0a3a21fc794b0cce3b64285a4c750c71", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
#ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }

View file

@ -347,7 +347,7 @@ pub async fn whoami_route(
body: Ruma<whoami::v3::Request>,
) -> Result<whoami::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let device_id = body.sender_device.as_ref().cloned();
let device_id = body.sender_device.clone();
Ok(whoami::v3::Response {
user_id: sender_user.clone(),

View file

@ -14,7 +14,7 @@ use ruma::{
federation,
},
serde::Raw,
DeviceId, DeviceKeyAlgorithm, UserId,
DeviceKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
};
use serde_json::json;
use std::collections::{BTreeMap, HashMap, HashSet};
@ -257,7 +257,7 @@ pub async fn get_key_changes_route(
device_list_updates.extend(
db.users
.keys_changed(
&room_id.to_string(),
room_id.as_str(),
body.from.parse().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`.")
})?,
@ -276,7 +276,7 @@ pub async fn get_key_changes_route(
pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
sender_user: Option<&UserId>,
device_keys_input: &BTreeMap<Box<UserId>, Vec<Box<DeviceId>>>,
device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>,
allowed_signatures: F,
db: &Database,
) -> Result<get_keys::v3::Response> {
@ -416,7 +416,7 @@ fn add_unsigned_device_display_name(
}
pub(crate) async fn claim_keys_helper(
one_time_keys_input: &BTreeMap<Box<UserId>, BTreeMap<Box<DeviceId>, DeviceKeyAlgorithm>>,
one_time_keys_input: &BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeyAlgorithm>>,
db: &Database,
) -> Result<claim_keys::v3::Response> {
let mut one_time_keys = BTreeMap::new();

View file

@ -25,7 +25,7 @@ use ruma::{
},
serde::{to_canonical_value, Base64, CanonicalJsonObject, CanonicalJsonValue},
state_res::{self, RoomVersion},
uint, EventId, RoomId, RoomVersionId, ServerName, UserId,
uint, EventId, OwnedEventId, OwnedRoomId, OwnedServerName, RoomId, RoomVersionId, UserId,
};
use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use std::{
@ -89,7 +89,7 @@ pub async fn join_room_by_id_or_alias_route(
let sender_user = body.sender_user.as_deref().expect("user is authenticated");
let body = body.body;
let (servers, room_id) = match Box::<RoomId>::try_from(body.room_id_or_alias) {
let (servers, room_id) = match OwnedRoomId::try_from(body.room_id_or_alias) {
Ok(room_id) => {
let mut servers: HashSet<_> = db
.rooms
@ -179,7 +179,7 @@ pub async fn kick_user_route(
.room_state_get(
&body.room_id,
&StateEventType::RoomMember,
&body.user_id.to_string(),
body.user_id.as_str(),
)?
.ok_or(Error::BadRequest(
ErrorKind::BadState,
@ -240,7 +240,7 @@ pub async fn ban_user_route(
.room_state_get(
&body.room_id,
&StateEventType::RoomMember,
&body.user_id.to_string(),
body.user_id.as_str(),
)?
.map_or(
Ok(RoomMemberEventContent {
@ -308,7 +308,7 @@ pub async fn unban_user_route(
.room_state_get(
&body.room_id,
&StateEventType::RoomMember,
&body.user_id.to_string(),
body.user_id.as_str(),
)?
.ok_or(Error::BadRequest(
ErrorKind::BadState,
@ -462,7 +462,7 @@ async fn join_room_by_id_helper(
db: &Database,
sender_user: Option<&UserId>,
room_id: &RoomId,
servers: &HashSet<Box<ServerName>>,
servers: &HashSet<OwnedServerName>,
_third_party_signed: Option<&IncomingThirdPartySigned>,
) -> Result<join_room_by_id::v3::Response> {
let sender_user = sender_user.expect("user is authenticated");
@ -726,7 +726,7 @@ fn validate_and_add_event_id(
room_version: &RoomVersionId,
pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
db: &Database,
) -> Result<(Box<EventId>, CanonicalJsonObject)> {
) -> Result<(OwnedEventId, CanonicalJsonObject)> {
let mut value: CanonicalJsonObject = serde_json::from_str(pdu.get()).map_err(|e| {
error!("Invalid PDU in server response: {:?}: {:?}", pdu, e);
Error::BadServerResponse("Invalid PDU in server response")
@ -990,7 +990,7 @@ pub(crate) async fn invite_helper<'a>(
warn!("Server {} changed invite event, that's not allowed in the spec: ours: {:?}, theirs: {:?}", user_id.server_name(), pdu_json, value);
}
let origin: Box<ServerName> = serde_json::from_value(
let origin: OwnedServerName = serde_json::from_value(
serde_json::to_value(value.get("origin").ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Event needs an origin field.",

View file

@ -39,7 +39,7 @@ pub async fn redact_event_route(
.expect("event is valid, we just created it"),
unsigned: None,
state_key: None,
redacts: Some(body.event_id.into()),
redacts: Some((&*body.event_id).into()),
},
sender_user,
&body.room_id,

View file

@ -23,7 +23,7 @@ use ruma::{
},
int,
serde::{CanonicalJsonObject, JsonObject},
RoomAliasId, RoomId,
OwnedRoomAliasId, RoomAliasId, RoomId,
};
use serde_json::{json, value::to_raw_value};
use std::{cmp::max, collections::BTreeMap, sync::Arc};
@ -77,7 +77,7 @@ pub async fn create_room_route(
));
}
let alias: Option<Box<RoomAliasId>> =
let alias: Option<OwnedRoomAliasId> =
body.room_alias_name
.as_ref()
.map_or(Ok(None), |localpart| {

View file

@ -10,7 +10,7 @@ use ruma::{
RoomEventType, StateEventType,
},
serde::Raw,
DeviceId, RoomId, UserId,
OwnedDeviceId, OwnedUserId, RoomId, UserId,
};
use std::{
collections::{hash_map::Entry, BTreeMap, HashMap, HashSet},
@ -128,8 +128,8 @@ pub async fn sync_events_route(
async fn sync_helper_wrapper(
db: Arc<DatabaseGuard>,
sender_user: Box<UserId>,
sender_device: Box<DeviceId>,
sender_user: OwnedUserId,
sender_device: OwnedDeviceId,
body: sync_events::v3::IncomingRequest,
tx: Sender<Option<Result<sync_events::v3::Response>>>,
) {
@ -170,8 +170,8 @@ async fn sync_helper_wrapper(
async fn sync_helper(
db: Arc<DatabaseGuard>,
sender_user: Box<UserId>,
sender_device: Box<DeviceId>,
sender_user: OwnedUserId,
sender_device: OwnedDeviceId,
body: sync_events::v3::IncomingRequest,
// bool = caching allowed
) -> Result<(sync_events::v3::Response, bool), Error> {
@ -222,7 +222,7 @@ async fn sync_helper(
// Look for device list updates of this account
device_list_updates.extend(
db.users
.keys_changed(&sender_user.to_string(), since, None)
.keys_changed(sender_user.as_str(), since, None)
.filter_map(|r| r.ok()),
);
@ -407,7 +407,7 @@ async fn sync_helper(
};
// This check is in case a bad user ID made it into the database
if let Ok(uid) = UserId::parse(state_key.as_ref()) {
if let Ok(uid) = UserId::parse(state_key) {
lazy_loaded.insert(uid);
}
state_events.push(pdu);
@ -614,7 +614,7 @@ async fn sync_helper(
// Look for device list updates in this room
device_list_updates.extend(
db.users
.keys_changed(&room_id.to_string(), since, None)
.keys_changed(room_id.as_str(), since, None)
.filter_map(|r| r.ok()),
);

View file

@ -4,7 +4,7 @@ use std::{
net::{IpAddr, Ipv4Addr},
};
use ruma::{RoomVersionId, ServerName};
use ruma::{OwnedServerName, RoomVersionId};
use serde::{de::IgnoredAny, Deserialize};
use tracing::warn;
@ -20,7 +20,7 @@ pub struct Config {
pub port: u16,
pub tls: Option<TlsConfig>,
pub server_name: Box<ServerName>,
pub server_name: OwnedServerName,
#[serde(default = "default_database_backend")]
pub database_backend: String,
pub database_path: String,
@ -58,7 +58,7 @@ pub struct Config {
pub proxy: ProxyConfig,
pub jwt_secret: Option<String>,
#[serde(default = "Vec::new")]
pub trusted_servers: Vec<Box<ServerName>>,
pub trusted_servers: Vec<OwnedServerName>,
#[serde(default = "default_log")]
pub log: String,
#[serde(default)]

View file

@ -25,7 +25,7 @@ use ruma::{
GlobalAccountDataEvent, GlobalAccountDataEventType,
},
push::Ruleset,
DeviceId, EventId, RoomId, UserId,
DeviceId, EventId, OwnedRoomId, RoomId, UserId,
};
use std::{
collections::{BTreeMap, HashMap, HashSet},
@ -453,7 +453,7 @@ impl Database {
if db.globals.database_version()? < 7 {
// Upgrade state store
let mut last_roomstates: HashMap<Box<RoomId>, u64> = HashMap::new();
let mut last_roomstates: HashMap<OwnedRoomId, u64> = HashMap::new();
let mut current_sstatehash: Option<u64> = None;
let mut current_room = None;
let mut current_state = HashSet::new();

View file

@ -30,7 +30,7 @@ use ruma::{
},
RoomEventType,
},
EventId, RoomAliasId, RoomId, RoomName, RoomVersionId, ServerName, UserId,
EventId, OwnedEventId, OwnedRoomAliasId, RoomId, RoomVersionId, ServerName, UserId,
};
use serde_json::value::to_raw_value;
use tokio::sync::{mpsc, MutexGuard, RwLock, RwLockReadGuard};
@ -234,7 +234,7 @@ enum AdminCommand {
/// Get the auth_chain of a PDU
GetAuthChain {
/// An event ID (the $ character followed by the base64 reference hash)
event_id: Box<EventId>,
event_id: OwnedEventId,
},
#[clap(verbatim_doc_comment)]
@ -252,7 +252,7 @@ enum AdminCommand {
/// Retrieve and print a PDU by ID from the Conduit database
GetPdu {
/// An event ID (a $ followed by the base64 reference hash)
event_id: Box<EventId>,
event_id: OwnedEventId,
},
/// Print database memory usage statistics
@ -335,7 +335,7 @@ fn process_admin_command(
Err(e) => RoomMessageEventContent::text_plain(e.to_string()),
},
AdminCommand::GetAuthChain { event_id } => {
let event_id = Arc::<EventId>::from(event_id);
let event_id = Arc::from(&*event_id);
if let Some(event) = db.rooms.get_pdu_json(&event_id)? {
let room_id_str = event
.get("room_id")
@ -704,8 +704,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
)?;
// 5. Events implied by name and topic
let room_name = RoomName::parse(format!("{} Admin Room", db.globals.server_name()))
.expect("Room name is valid");
let room_name = format!("{} Admin Room", db.globals.server_name());
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: RoomEventType::RoomName,
@ -739,7 +738,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
)?;
// 6. Room alias
let alias: Box<RoomAliasId> = format!("#admins:{}", db.globals.server_name())
let alias: OwnedRoomAliasId = format!("#admins:{}", db.globals.server_name())
.try_into()
.expect("#admins:server_name is a valid alias name");
@ -774,7 +773,7 @@ pub(crate) async fn make_user_admin(
user_id: &UserId,
displayname: String,
) -> Result<()> {
let admin_room_alias: Box<RoomAliasId> = format!("#admins:{}", db.globals.server_name())
let admin_room_alias: OwnedRoomAliasId = format!("#admins:{}", db.globals.server_name())
.try_into()
.expect("#admins:server_name is a valid alias name");
let room_id = db

View file

@ -4,8 +4,8 @@ use ruma::{
client::sync::sync_events,
federation::discovery::{ServerSigningKeys, VerifyKey},
},
DeviceId, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, ServerName,
ServerSigningKeyId, UserId,
MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedServerName,
OwnedServerSigningKeyId, OwnedUserId, RoomVersionId, ServerName,
};
use std::{
collections::{BTreeMap, HashMap},
@ -24,7 +24,7 @@ use super::abstraction::Tree;
pub const COUNTER: &[u8] = b"c";
type WellKnownMap = HashMap<Box<ServerName>, (FedDest, String)>;
type WellKnownMap = HashMap<OwnedServerName, (FedDest, String)>;
type TlsNameMap = HashMap<String, (Vec<IpAddr>, u16)>;
type RateLimitState = (Instant, u32); // Time if last failed try, number of failed tries
type SyncHandle = (
@ -45,13 +45,13 @@ pub struct Globals {
pub stable_room_versions: Vec<RoomVersionId>,
pub unstable_room_versions: Vec<RoomVersionId>,
pub(super) server_signingkeys: Arc<dyn Tree>,
pub bad_event_ratelimiter: Arc<RwLock<HashMap<Box<EventId>, RateLimitState>>>,
pub bad_event_ratelimiter: Arc<RwLock<HashMap<OwnedEventId, RateLimitState>>>,
pub bad_signature_ratelimiter: Arc<RwLock<HashMap<Vec<String>, RateLimitState>>>,
pub servername_ratelimiter: Arc<RwLock<HashMap<Box<ServerName>, Arc<Semaphore>>>>,
pub sync_receivers: RwLock<HashMap<(Box<UserId>, Box<DeviceId>), SyncHandle>>,
pub roomid_mutex_insert: RwLock<HashMap<Box<RoomId>, Arc<Mutex<()>>>>,
pub roomid_mutex_state: RwLock<HashMap<Box<RoomId>, Arc<TokioMutex<()>>>>,
pub roomid_mutex_federation: RwLock<HashMap<Box<RoomId>, Arc<TokioMutex<()>>>>, // this lock will be held longer
pub servername_ratelimiter: Arc<RwLock<HashMap<OwnedServerName, Arc<Semaphore>>>>,
pub sync_receivers: RwLock<HashMap<(OwnedUserId, OwnedDeviceId), SyncHandle>>,
pub roomid_mutex_insert: RwLock<HashMap<OwnedRoomId, Arc<Mutex<()>>>>,
pub roomid_mutex_state: RwLock<HashMap<OwnedRoomId, Arc<TokioMutex<()>>>>,
pub roomid_mutex_federation: RwLock<HashMap<OwnedRoomId, Arc<TokioMutex<()>>>>, // this lock will be held longer
pub rotate: RotationHandler,
}
@ -263,7 +263,7 @@ impl Globals {
self.config.default_room_version.clone()
}
pub fn trusted_servers(&self) -> &[Box<ServerName>] {
pub fn trusted_servers(&self) -> &[OwnedServerName] {
&self.config.trusted_servers
}
@ -316,7 +316,7 @@ impl Globals {
&self,
origin: &ServerName,
new_keys: ServerSigningKeys,
) -> Result<BTreeMap<Box<ServerSigningKeyId>, VerifyKey>> {
) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
// Not atomic, but this is not critical
let signingkeys = self.server_signingkeys.get(origin.as_bytes())?;
@ -355,7 +355,7 @@ impl Globals {
pub fn signing_keys_for(
&self,
origin: &ServerName,
) -> Result<BTreeMap<Box<ServerSigningKeyId>, VerifyKey>> {
) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
let signingkeys = self
.server_signingkeys
.get(origin.as_bytes())?

View file

@ -5,7 +5,7 @@ use ruma::{
error::ErrorKind,
},
serde::Raw,
RoomId, UserId,
OwnedRoomId, RoomId, UserId,
};
use std::{collections::BTreeMap, sync::Arc};
@ -211,13 +211,13 @@ impl KeyBackups {
&self,
user_id: &UserId,
version: &str,
) -> Result<BTreeMap<Box<RoomId>, RoomKeyBackup>> {
) -> Result<BTreeMap<OwnedRoomId, RoomKeyBackup>> {
let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff);
prefix.extend_from_slice(version.as_bytes());
prefix.push(0xff);
let mut rooms = BTreeMap::<Box<RoomId>, RoomKeyBackup>::new();
let mut rooms = BTreeMap::<OwnedRoomId, RoomKeyBackup>::new();
for result in self
.backupkeyid_backup

View file

@ -234,6 +234,7 @@ pub fn get_actions<'a>(
db: &Database,
) -> Result<&'a [Action]> {
let ctx = PushConditionRoomCtx {
user_id: user.to_owned(),
room_id: room_id.to_owned(),
member_count: 10_u32.into(), // TODO: get member count efficiently
user_display_name: db

View file

@ -27,7 +27,8 @@ use ruma::{
push::{Action, Ruleset, Tweak},
serde::{CanonicalJsonObject, CanonicalJsonValue, Raw},
state_res::{self, RoomVersion, StateMap},
uint, DeviceId, EventId, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId,
uint, DeviceId, EventId, OwnedDeviceId, OwnedEventId, OwnedRoomAliasId, OwnedRoomId,
OwnedServerName, OwnedUserId, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId,
};
use serde::Deserialize;
use serde_json::value::to_raw_value;
@ -108,16 +109,16 @@ pub struct Rooms {
/// RoomId + EventId -> Parent PDU EventId.
pub(super) referencedevents: Arc<dyn Tree>,
pub(super) pdu_cache: Mutex<LruCache<Box<EventId>, Arc<PduEvent>>>,
pub(super) pdu_cache: Mutex<LruCache<OwnedEventId, Arc<PduEvent>>>,
pub(super) shorteventid_cache: Mutex<LruCache<u64, Arc<EventId>>>,
pub(super) auth_chain_cache: Mutex<LruCache<Vec<u64>, Arc<HashSet<u64>>>>,
pub(super) eventidshort_cache: Mutex<LruCache<Box<EventId>, u64>>,
pub(super) eventidshort_cache: Mutex<LruCache<OwnedEventId, u64>>,
pub(super) statekeyshort_cache: Mutex<LruCache<(StateEventType, String), u64>>,
pub(super) shortstatekey_cache: Mutex<LruCache<u64, (StateEventType, String)>>,
pub(super) our_real_users_cache: RwLock<HashMap<Box<RoomId>, Arc<HashSet<Box<UserId>>>>>,
pub(super) appservice_in_room_cache: RwLock<HashMap<Box<RoomId>, HashMap<String, bool>>>,
pub(super) our_real_users_cache: RwLock<HashMap<OwnedRoomId, Arc<HashSet<OwnedUserId>>>>,
pub(super) appservice_in_room_cache: RwLock<HashMap<OwnedRoomId, HashMap<String, bool>>>,
pub(super) lazy_load_waiting:
Mutex<HashMap<(Box<UserId>, Box<DeviceId>, Box<RoomId>, u64), HashSet<Box<UserId>>>>,
Mutex<HashMap<(OwnedUserId, OwnedDeviceId, OwnedRoomId, u64), HashSet<OwnedUserId>>>,
pub(super) stateinfo_cache: Mutex<
LruCache<
u64,
@ -129,7 +130,7 @@ pub struct Rooms {
)>,
>,
>,
pub(super) lasttimelinecount_cache: Mutex<HashMap<Box<RoomId>, u64>>,
pub(super) lasttimelinecount_cache: Mutex<HashMap<OwnedRoomId, u64>>,
}
impl Rooms {
@ -1992,7 +1993,7 @@ impl Rooms {
// where events in the current room state do not exist
self.set_room_state(room_id, statehashid)?;
let mut servers: HashSet<Box<ServerName>> =
let mut servers: HashSet<OwnedServerName> =
self.room_servers(room_id).filter_map(|r| r.ok()).collect();
// In case we are kicking or banning a user, we need to inform their server of the change
@ -2002,7 +2003,7 @@ impl Rooms {
.as_ref()
.and_then(|state_key| UserId::parse(state_key.as_str()).ok())
{
servers.insert(Box::from(state_key_uid.server_name()));
servers.insert(state_key_uid.server_name().to_owned());
}
}
@ -2498,7 +2499,7 @@ impl Rooms {
&self,
room_id: &RoomId,
db: &Database,
) -> Result<Arc<HashSet<Box<UserId>>>> {
) -> Result<Arc<HashSet<OwnedUserId>>> {
let maybe = self
.our_real_users_cache
.read()
@ -2814,7 +2815,7 @@ impl Rooms {
}
#[tracing::instrument(skip(self))]
pub fn id_from_alias(&self, alias: &RoomAliasId) -> Result<Option<Box<RoomId>>> {
pub fn id_from_alias(&self, alias: &RoomAliasId) -> Result<Option<OwnedRoomId>> {
self.alias_roomid
.get(alias.alias().as_bytes())?
.map(|bytes| {
@ -2830,7 +2831,7 @@ impl Rooms {
pub fn room_aliases<'a>(
&'a self,
room_id: &RoomId,
) -> impl Iterator<Item = Result<Box<RoomAliasId>>> + 'a {
) -> impl Iterator<Item = Result<OwnedRoomAliasId>> + 'a {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
@ -2859,7 +2860,7 @@ impl Rooms {
}
#[tracing::instrument(skip(self))]
pub fn public_rooms(&self) -> impl Iterator<Item = Result<Box<RoomId>>> + '_ {
pub fn public_rooms(&self) -> impl Iterator<Item = Result<OwnedRoomId>> + '_ {
self.publicroomids.iter().map(|(bytes, _)| {
RoomId::parse(
utils::string_from_bytes(&bytes).map_err(|_| {
@ -2922,8 +2923,8 @@ impl Rooms {
#[tracing::instrument(skip(self))]
pub fn get_shared_rooms<'a>(
&'a self,
users: Vec<Box<UserId>>,
) -> Result<impl Iterator<Item = Result<Box<RoomId>>> + 'a> {
users: Vec<OwnedUserId>,
) -> Result<impl Iterator<Item = Result<OwnedRoomId>> + 'a> {
let iterators = users.into_iter().map(move |user_id| {
let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff);
@ -2962,7 +2963,7 @@ impl Rooms {
pub fn room_servers<'a>(
&'a self,
room_id: &RoomId,
) -> impl Iterator<Item = Result<Box<ServerName>>> + 'a {
) -> impl Iterator<Item = Result<OwnedServerName>> + 'a {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
@ -2995,7 +2996,7 @@ impl Rooms {
pub fn server_rooms<'a>(
&'a self,
server: &ServerName,
) -> impl Iterator<Item = Result<Box<RoomId>>> + 'a {
) -> impl Iterator<Item = Result<OwnedRoomId>> + 'a {
let mut prefix = server.as_bytes().to_vec();
prefix.push(0xff);
@ -3017,7 +3018,7 @@ impl Rooms {
pub fn room_members<'a>(
&'a self,
room_id: &RoomId,
) -> impl Iterator<Item = Result<Box<UserId>>> + 'a {
) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
@ -3063,7 +3064,7 @@ impl Rooms {
pub fn room_useroncejoined<'a>(
&'a self,
room_id: &RoomId,
) -> impl Iterator<Item = Result<Box<UserId>>> + 'a {
) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
@ -3089,7 +3090,7 @@ impl Rooms {
pub fn room_members_invited<'a>(
&'a self,
room_id: &RoomId,
) -> impl Iterator<Item = Result<Box<UserId>>> + 'a {
) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
@ -3145,7 +3146,7 @@ impl Rooms {
pub fn rooms_joined<'a>(
&'a self,
user_id: &UserId,
) -> impl Iterator<Item = Result<Box<RoomId>>> + 'a {
) -> impl Iterator<Item = Result<OwnedRoomId>> + 'a {
self.userroomid_joined
.scan_prefix(user_id.as_bytes().to_vec())
.map(|(key, _)| {
@ -3168,7 +3169,7 @@ impl Rooms {
pub fn rooms_invited<'a>(
&'a self,
user_id: &UserId,
) -> impl Iterator<Item = Result<(Box<RoomId>, Vec<Raw<AnyStrippedStateEvent>>)>> + 'a {
) -> impl Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnyStrippedStateEvent>>)>> + 'a {
let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff);
@ -3241,7 +3242,7 @@ impl Rooms {
pub fn rooms_left<'a>(
&'a self,
user_id: &UserId,
) -> impl Iterator<Item = Result<(Box<RoomId>, Vec<Raw<AnySyncStateEvent>>)>> + 'a {
) -> impl Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnySyncStateEvent>>)>> + 'a {
let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff);
@ -3385,7 +3386,7 @@ impl Rooms {
user_id: &UserId,
device_id: &DeviceId,
room_id: &RoomId,
lazy_load: HashSet<Box<UserId>>,
lazy_load: HashSet<OwnedUserId>,
count: u64,
) {
self.lazy_load_waiting.lock().unwrap().insert(

View file

@ -8,7 +8,7 @@ use ruma::{
presence::PresenceState,
serde::Raw,
signatures::CanonicalJsonObject,
RoomId, UInt, UserId,
OwnedUserId, RoomId, UInt, UserId,
};
use std::{
collections::{HashMap, HashSet},
@ -78,7 +78,7 @@ impl RoomEdus {
since: u64,
) -> impl Iterator<
Item = Result<(
Box<UserId>,
OwnedUserId,
u64,
Raw<ruma::events::AnySyncEphemeralRoomEvent>,
)>,
@ -450,7 +450,7 @@ impl RoomEdus {
{
// Send new presence events to set the user offline
let count = globals.next_count()?.to_be_bytes();
let user_id: Box<_> = utils::string_from_bytes(&user_id_bytes)
let user_id: OwnedUserId = utils::string_from_bytes(&user_id_bytes)
.map_err(|_| {
Error::bad_database("Invalid UserId bytes in userid_lastpresenceupdate.")
})?
@ -499,7 +499,7 @@ impl RoomEdus {
since: u64,
_rooms: &super::Rooms,
_globals: &super::super::globals::Globals,
) -> Result<HashMap<Box<UserId>, PresenceEvent>> {
) -> Result<HashMap<OwnedUserId, PresenceEvent>> {
//self.presence_maintain(rooms, globals)?;
let mut prefix = room_id.as_bytes().to_vec();

View file

@ -26,7 +26,7 @@ use ruma::{
events::{push_rules::PushRulesEvent, AnySyncEphemeralRoomEvent, GlobalAccountDataEventType},
push,
receipt::ReceiptType,
uint, MilliSecondsSinceUnixEpoch, ServerName, UInt, UserId,
uint, MilliSecondsSinceUnixEpoch, OwnedServerName, ServerName, UInt, UserId,
};
use tokio::{
select,
@ -40,7 +40,7 @@ use super::abstraction::Tree;
pub enum OutgoingKind {
Appservice(String),
Push(Vec<u8>, Vec<u8>), // user and pushkey
Normal(Box<ServerName>),
Normal(OwnedServerName),
}
impl OutgoingKind {
@ -323,7 +323,7 @@ impl Sending {
// Look for device list updates in this room
device_list_changes.extend(
db.users
.keys_changed(&room_id.to_string(), since, None)
.keys_changed(room_id.as_str(), since, None)
.filter_map(|r| r.ok())
.filter(|user_id| user_id.server_name() == db.globals.server_name()),
);
@ -420,7 +420,7 @@ impl Sending {
}
#[tracing::instrument(skip(self, servers, pdu_id))]
pub fn send_pdu<I: Iterator<Item = Box<ServerName>>>(
pub fn send_pdu<I: Iterator<Item = OwnedServerName>>(
&self,
servers: I,
pdu_id: &[u8],

View file

@ -13,7 +13,7 @@ use ruma::{
},
},
signatures::CanonicalJsonValue,
DeviceId, UserId,
DeviceId, OwnedDeviceId, OwnedUserId, UserId,
};
use tracing::error;
@ -22,7 +22,7 @@ use super::abstraction::Tree;
pub struct Uiaa {
pub(super) userdevicesessionid_uiaainfo: Arc<dyn Tree>, // User-interactive authentication
pub(super) userdevicesessionid_uiaarequest:
RwLock<BTreeMap<(Box<UserId>, Box<DeviceId>, String), CanonicalJsonValue>>,
RwLock<BTreeMap<(OwnedUserId, OwnedDeviceId, String), CanonicalJsonValue>>,
}
impl Uiaa {

View file

@ -4,8 +4,8 @@ use ruma::{
encryption::{CrossSigningKey, DeviceKeys, OneTimeKey},
events::{AnyToDeviceEvent, StateEventType},
serde::Raw,
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, MxcUri, RoomAliasId,
UInt, UserId,
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, OwnedDeviceId,
OwnedDeviceKeyId, OwnedMxcUri, OwnedUserId, RoomAliasId, UInt, UserId,
};
use std::{collections::BTreeMap, mem, sync::Arc};
use tracing::warn;
@ -85,7 +85,7 @@ impl Users {
/// Find out which user an access token belongs to.
#[tracing::instrument(skip(self, token))]
pub fn find_from_token(&self, token: &str) -> Result<Option<(Box<UserId>, String)>> {
pub fn find_from_token(&self, token: &str) -> Result<Option<(OwnedUserId, String)>> {
self.token_userdeviceid
.get(token.as_bytes())?
.map_or(Ok(None), |bytes| {
@ -113,7 +113,7 @@ impl Users {
/// Returns an iterator over all users on this homeserver.
#[tracing::instrument(skip(self))]
pub fn iter(&self) -> impl Iterator<Item = Result<Box<UserId>>> + '_ {
pub fn iter(&self) -> impl Iterator<Item = Result<OwnedUserId>> + '_ {
self.userid_password.iter().map(|(bytes, _)| {
UserId::parse(utils::string_from_bytes(&bytes).map_err(|_| {
Error::bad_database("User ID in userid_password is invalid unicode.")
@ -217,7 +217,7 @@ impl Users {
/// Get the avatar_url of a user.
#[tracing::instrument(skip(self, user_id))]
pub fn avatar_url(&self, user_id: &UserId) -> Result<Option<Box<MxcUri>>> {
pub fn avatar_url(&self, user_id: &UserId) -> Result<Option<OwnedMxcUri>> {
self.userid_avatarurl
.get(user_id.as_bytes())?
.map(|bytes| {
@ -231,7 +231,7 @@ impl Users {
/// Sets a new avatar_url or removes it if avatar_url is None.
#[tracing::instrument(skip(self, user_id, avatar_url))]
pub fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option<Box<MxcUri>>) -> Result<()> {
pub fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option<OwnedMxcUri>) -> Result<()> {
if let Some(avatar_url) = avatar_url {
self.userid_avatarurl
.insert(user_id.as_bytes(), avatar_url.to_string().as_bytes())?;
@ -340,7 +340,7 @@ impl Users {
pub fn all_device_ids<'a>(
&'a self,
user_id: &UserId,
) -> impl Iterator<Item = Result<Box<DeviceId>>> + 'a {
) -> impl Iterator<Item = Result<OwnedDeviceId>> + 'a {
let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff);
// All devices have metadata
@ -446,7 +446,7 @@ impl Users {
device_id: &DeviceId,
key_algorithm: &DeviceKeyAlgorithm,
globals: &super::globals::Globals,
) -> Result<Option<(Box<DeviceKeyId>, Raw<OneTimeKey>)>> {
) -> Result<Option<(OwnedDeviceKeyId, Raw<OneTimeKey>)>> {
let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff);
prefix.extend_from_slice(device_id.as_bytes());
@ -496,7 +496,7 @@ impl Users {
.scan_prefix(userdeviceid)
.map(|(bytes, _)| {
Ok::<_, Error>(
serde_json::from_slice::<Box<DeviceKeyId>>(
serde_json::from_slice::<OwnedDeviceKeyId>(
&*bytes.rsplit(|&b| b == 0xff).next().ok_or_else(|| {
Error::bad_database("OneTimeKey ID in db is invalid.")
})?,
@ -684,7 +684,7 @@ impl Users {
.ok_or_else(|| Error::bad_database("key in keyid_key has no signatures field."))?
.as_object_mut()
.ok_or_else(|| Error::bad_database("key in keyid_key has invalid signatures field."))?
.entry(sender_id.to_owned())
.entry(sender_id.to_string())
.or_insert_with(|| serde_json::Map::new().into());
signatures
@ -709,7 +709,7 @@ impl Users {
user_or_room_id: &str,
from: u64,
to: Option<u64>,
) -> impl Iterator<Item = Result<Box<UserId>>> + 'a {
) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
let mut prefix = user_or_room_id.as_bytes().to_vec();
prefix.push(0xff);

View file

@ -6,7 +6,7 @@ use ruma::{
error::{Error as RumaError, ErrorKind},
uiaa::{UiaaInfo, UiaaResponse},
},
ServerName,
OwnedServerName,
};
use thiserror::Error;
use tracing::{error, warn};
@ -55,7 +55,7 @@ pub enum Error {
source: reqwest::Error,
},
#[error("{0}")]
FederationError(Box<ServerName>, RumaError),
FederationError(OwnedServerName, RumaError),
#[error("Could not do this io: {source}")]
IoError {
#[from]

View file

@ -5,7 +5,8 @@ use ruma::{
AnyStrippedStateEvent, AnySyncRoomEvent, AnySyncStateEvent, RoomEventType, StateEvent,
},
serde::{CanonicalJsonObject, CanonicalJsonValue, Raw},
state_res, EventId, MilliSecondsSinceUnixEpoch, RoomId, UInt, UserId,
state_res, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId,
UInt, UserId,
};
use serde::{Deserialize, Serialize};
use serde_json::{
@ -25,8 +26,8 @@ pub struct EventHash {
#[derive(Clone, Deserialize, Serialize, Debug)]
pub struct PduEvent {
pub event_id: Arc<EventId>,
pub room_id: Box<RoomId>,
pub sender: Box<UserId>,
pub room_id: OwnedRoomId,
pub sender: OwnedUserId,
pub origin_server_ts: UInt,
#[serde(rename = "type")]
pub kind: RoomEventType,
@ -42,7 +43,7 @@ pub struct PduEvent {
pub unsigned: Option<Box<RawJsonValue>>,
pub hashes: EventHash,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signatures: Option<Box<RawJsonValue>>, // BTreeMap<Box<ServerName>, BTreeMap<ServerSigningKeyId, String>>
pub signatures: Option<Box<RawJsonValue>>, // BTreeMap<OwnedServerName, BTreeMap<ServerSigningKeyId, String>>
}
impl PduEvent {
@ -333,7 +334,7 @@ impl Ord for PduEvent {
pub(crate) fn gen_event_id_canonical_json(
pdu: &RawJsonValue,
db: &Database,
) -> crate::Result<(Box<EventId>, CanonicalJsonObject)> {
) -> crate::Result<(OwnedEventId, CanonicalJsonObject)> {
let value: CanonicalJsonObject = serde_json::from_str(pdu.get()).map_err(|e| {
warn!("Error parsing incoming event {:?}: {:?}", pdu, e);
Error::BadServerResponse("Invalid PDU in server response")

View file

@ -1,6 +1,7 @@
use crate::Error;
use ruma::{
api::client::uiaa::UiaaResponse, signatures::CanonicalJsonValue, DeviceId, ServerName, UserId,
api::client::uiaa::UiaaResponse, signatures::CanonicalJsonValue, OwnedDeviceId,
OwnedServerName, OwnedUserId,
};
use std::ops::Deref;
@ -10,9 +11,9 @@ mod axum;
/// Extractor for Ruma request structs
pub struct Ruma<T> {
pub body: T,
pub sender_user: Option<Box<UserId>>,
pub sender_device: Option<Box<DeviceId>>,
pub sender_servername: Option<Box<ServerName>>,
pub sender_user: Option<OwnedUserId>,
pub sender_device: Option<OwnedDeviceId>,
pub sender_servername: Option<OwnedServerName>,
// This is None when body is not a valid string
pub json_body: Option<CanonicalJsonValue>,
pub from_appservice: bool,

View file

@ -18,7 +18,7 @@ use http::StatusCode;
use ruma::{
api::{client::error::ErrorKind, AuthScheme, IncomingRequest, OutgoingResponse},
signatures::CanonicalJsonValue,
DeviceId, ServerName, UserId,
OwnedDeviceId, OwnedServerName, UserId,
};
use serde::Deserialize;
use tracing::{debug, error, warn};
@ -133,7 +133,7 @@ where
}
Some((user_id, device_id)) => (
Some(user_id),
Some(Box::<DeviceId>::from(device_id)),
Some(OwnedDeviceId::from(device_id)),
None,
false,
),
@ -300,7 +300,7 @@ where
}
struct XMatrix {
origin: Box<ServerName>,
origin: OwnedServerName,
key: String, // KeyName?
sig: String,
}

View file

@ -54,8 +54,8 @@ use ruma::{
signatures::{CanonicalJsonObject, CanonicalJsonValue},
state_res::{self, RoomVersion, StateMap},
to_device::DeviceIdOrAllDevices,
uint, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, ServerName,
ServerSigningKeyId,
uint, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedServerName,
OwnedServerSigningKeyId, OwnedUserId, RoomId, RoomVersionId, ServerName,
};
use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use std::{
@ -282,7 +282,7 @@ where
let response = T::IncomingResponse::try_from_http_response(http_response);
if response.is_ok() && write_destination_to_cache {
globals.actual_destination_cache.write().unwrap().insert(
Box::<ServerName>::from(destination),
OwnedServerName::from(destination),
(actual_destination, host),
);
}
@ -526,7 +526,7 @@ pub async fn get_server_keys_route(db: DatabaseGuard) -> Result<impl IntoRespons
return Err(Error::bad_config("Federation is disabled."));
}
let mut verify_keys: BTreeMap<Box<ServerSigningKeyId>, VerifyKey> = BTreeMap::new();
let mut verify_keys: BTreeMap<OwnedServerSigningKeyId, VerifyKey> = BTreeMap::new();
verify_keys.insert(
format!("ed25519:{}", db.globals.keypair().version())
.try_into()
@ -691,7 +691,7 @@ pub async fn send_transaction_message_route(
.roomid_mutex_federation
.write()
.unwrap()
.entry(room_id.clone())
.entry(room_id.to_owned())
.or_default(),
);
let mutex_lock = mutex.lock().await;
@ -2397,7 +2397,7 @@ pub async fn get_missing_events_route(
continue;
}
queued_events.extend_from_slice(
&serde_json::from_value::<Vec<Box<EventId>>>(
&serde_json::from_value::<Vec<OwnedEventId>>(
serde_json::to_value(pdu.get("prev_events").cloned().ok_or_else(|| {
Error::bad_database("Event in db has no prev_events field.")
})?)
@ -2835,7 +2835,7 @@ async fn create_join_event(
}
};
let origin: Box<ServerName> = serde_json::from_value(
let origin: OwnedServerName = serde_json::from_value(
serde_json::to_value(value.get("origin").ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Event needs an origin field.",
@ -2981,10 +2981,10 @@ pub async fn create_invite_route(
// Add event_id back
signed_event.insert(
"event_id".to_owned(),
CanonicalJsonValue::String(event_id.into()),
CanonicalJsonValue::String(event_id.to_string()),
);
let sender: Box<_> = serde_json::from_value(
let sender: OwnedUserId = serde_json::from_value(
signed_event
.get("sender")
.ok_or(Error::BadRequest(
@ -2996,7 +2996,7 @@ pub async fn create_invite_route(
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "sender is not a user id."))?;
let invited_user: Box<_> = serde_json::from_value(
let invited_user: OwnedUserId = serde_json::from_value(
signed_event
.get("state_key")
.ok_or(Error::BadRequest(
@ -3255,7 +3255,7 @@ pub(crate) async fn fetch_required_signing_keys(
// the PDUs and either cache the key or add it to the list that needs to be retrieved.
fn get_server_keys_from_cache(
pdu: &RawJsonValue,
servers: &mut BTreeMap<Box<ServerName>, BTreeMap<Box<ServerSigningKeyId>, QueryCriteria>>,
servers: &mut BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>>,
room_version: &RoomVersionId,
pub_key_map: &mut RwLockWriteGuard<'_, BTreeMap<String, BTreeMap<String, Base64>>>,
db: &Database,
@ -3346,7 +3346,7 @@ pub(crate) async fn fetch_join_signing_keys(
pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
db: &Database,
) -> Result<()> {
let mut servers: BTreeMap<Box<ServerName>, BTreeMap<Box<ServerSigningKeyId>, QueryCriteria>> =
let mut servers: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>> =
BTreeMap::new();
{