From 34d3f74f363719ab60263da62477cf0cd56bbbb0 Mon Sep 17 00:00:00 2001
From: Jonas Platte <jplatte+git@posteo.de>
Date: Sat, 27 Nov 2021 17:44:52 +0100
Subject: [PATCH] Use Arc for EventIds in PDUs

Upgrades Ruma again to make this work.
---
 Cargo.lock                      | 36 ++++++++++++++--------------
 Cargo.toml                      |  4 ++--
 src/client_server/account.rs    |  4 ++++
 src/client_server/membership.rs |  7 +++++-
 src/client_server/message.rs    |  2 +-
 src/client_server/redact.rs     |  4 +++-
 src/client_server/room.rs       | 14 +++++------
 src/client_server/state.rs      |  4 +++-
 src/database/rooms.rs           | 12 +++++-----
 src/pdu.rs                      | 28 ++++++++++++----------
 src/server_server.rs            | 42 +++++++++++++--------------------
 11 files changed, 81 insertions(+), 76 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index 8b25b4784..fbf4b3f2a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1984,7 +1984,7 @@ dependencies = [
 [[package]]
 name = "ruma"
 version = "0.4.0"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "assign",
  "js_int",
@@ -2005,7 +2005,7 @@ dependencies = [
 [[package]]
 name = "ruma-api"
 version = "0.18.5"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "bytes",
  "http",
@@ -2021,7 +2021,7 @@ dependencies = [
 [[package]]
 name = "ruma-api-macros"
 version = "0.18.5"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "proc-macro-crate",
  "proc-macro2",
@@ -2032,7 +2032,7 @@ dependencies = [
 [[package]]
 name = "ruma-appservice-api"
 version = "0.4.0"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "ruma-api",
  "ruma-common",
@@ -2046,7 +2046,7 @@ dependencies = [
 [[package]]
 name = "ruma-client-api"
 version = "0.12.3"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "assign",
  "bytes",
@@ -2066,7 +2066,7 @@ dependencies = [
 [[package]]
 name = "ruma-common"
 version = "0.6.0"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "indexmap",
  "js_int",
@@ -2081,7 +2081,7 @@ dependencies = [
 [[package]]
 name = "ruma-events"
 version = "0.24.6"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "indoc",
  "js_int",
@@ -2097,7 +2097,7 @@ dependencies = [
 [[package]]
 name = "ruma-events-macros"
 version = "0.24.6"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "proc-macro-crate",
  "proc-macro2",
@@ -2108,7 +2108,7 @@ dependencies = [
 [[package]]
 name = "ruma-federation-api"
 version = "0.3.1"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "js_int",
  "ruma-api",
@@ -2123,7 +2123,7 @@ dependencies = [
 [[package]]
 name = "ruma-identifiers"
 version = "0.20.0"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "percent-encoding",
  "rand 0.8.4",
@@ -2137,7 +2137,7 @@ dependencies = [
 [[package]]
 name = "ruma-identifiers-macros"
 version = "0.20.0"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "quote",
  "ruma-identifiers-validation",
@@ -2147,7 +2147,7 @@ dependencies = [
 [[package]]
 name = "ruma-identifiers-validation"
 version = "0.5.0"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "thiserror",
 ]
@@ -2155,7 +2155,7 @@ dependencies = [
 [[package]]
 name = "ruma-identity-service-api"
 version = "0.3.0"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "js_int",
  "ruma-api",
@@ -2168,7 +2168,7 @@ dependencies = [
 [[package]]
 name = "ruma-push-gateway-api"
 version = "0.3.0"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "js_int",
  "ruma-api",
@@ -2183,7 +2183,7 @@ dependencies = [
 [[package]]
 name = "ruma-serde"
 version = "0.5.0"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "bytes",
  "form_urlencoded",
@@ -2197,7 +2197,7 @@ dependencies = [
 [[package]]
 name = "ruma-serde-macros"
 version = "0.5.0"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "proc-macro-crate",
  "proc-macro2",
@@ -2208,7 +2208,7 @@ dependencies = [
 [[package]]
 name = "ruma-signatures"
 version = "0.9.0"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "base64 0.13.0",
  "ed25519-dalek",
@@ -2225,7 +2225,7 @@ dependencies = [
 [[package]]
 name = "ruma-state-res"
 version = "0.4.1"
-source = "git+https://github.com/ruma/ruma?rev=bba7d624425da2c65a834bbd0e633b7577488cdf#bba7d624425da2c65a834bbd0e633b7577488cdf"
+source = "git+https://github.com/ruma/ruma?rev=16f031fabb7871fcd738b0f25391193ee4ca28a9#16f031fabb7871fcd738b0f25391193ee4ca28a9"
 dependencies = [
  "itertools 0.10.1",
  "js_int",
diff --git a/Cargo.toml b/Cargo.toml
index b24afb5c9..02159e310 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -19,7 +19,7 @@ rocket = { version = "0.5.0-rc.1", features = ["tls"] } # Used to handle request
 
 # 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 = "bba7d624425da2c65a834bbd0e633b7577488cdf", 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 = "16f031fabb7871fcd738b0f25391193ee4ca28a9", 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/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"] }
 
@@ -40,7 +40,7 @@ serde_json = { version = "1.0.67", features = ["raw_value"] }
 # Used for appservice registration files
 serde_yaml = "0.8.20"
 # Used for pdu definition
-serde = "1.0.130"
+serde = { version = "1.0.130", features = ["rc"] }
 # Used for secure identifiers
 rand = "0.8.4"
 # Used to hash passwords
diff --git a/src/client_server/account.rs b/src/client_server/account.rs
index 3149187f3..c4e118c9c 100644
--- a/src/client_server/account.rs
+++ b/src/client_server/account.rs
@@ -306,6 +306,7 @@ pub async fn register_route(
                     third_party_invite: None,
                     blurhash: None,
                     reason: None,
+                    join_authorized_via_users_server: None,
                 })
                 .expect("event is valid, we just created it"),
                 unsigned: None,
@@ -463,6 +464,7 @@ pub async fn register_route(
                     third_party_invite: None,
                     blurhash: None,
                     reason: None,
+                    join_authorized_via_users_server: None,
                 })
                 .expect("event is valid, we just created it"),
                 unsigned: None,
@@ -485,6 +487,7 @@ pub async fn register_route(
                     third_party_invite: None,
                     blurhash: None,
                     reason: None,
+                    join_authorized_via_users_server: None,
                 })
                 .expect("event is valid, we just created it"),
                 unsigned: None,
@@ -701,6 +704,7 @@ pub async fn deactivate_route(
             third_party_invite: None,
             blurhash: None,
             reason: None,
+            join_authorized_via_users_server: None,
         };
 
         let mutex_state = Arc::clone(
diff --git a/src/client_server/membership.rs b/src/client_server/membership.rs
index e28f9a31a..cede51f01 100644
--- a/src/client_server/membership.rs
+++ b/src/client_server/membership.rs
@@ -286,6 +286,7 @@ pub async fn ban_user_route(
                 third_party_invite: None,
                 blurhash: db.users.blurhash(&body.user_id)?,
                 reason: None,
+                join_authorized_via_users_server: None,
             }),
             |event| {
                 serde_json::from_str(event.content.get())
@@ -604,6 +605,7 @@ async fn join_room_by_id_helper(
                 third_party_invite: None,
                 blurhash: db.users.blurhash(sender_user)?,
                 reason: None,
+                join_authorized_via_users_server: None,
             })
             .expect("event is valid, we just created it"),
         );
@@ -757,6 +759,7 @@ async fn join_room_by_id_helper(
             third_party_invite: None,
             blurhash: db.users.blurhash(sender_user)?,
             reason: None,
+            join_authorized_via_users_server: None,
         };
 
         db.rooms.build_and_append_pdu(
@@ -906,6 +909,7 @@ pub(crate) async fn invite_helper<'a>(
                 third_party_invite: None,
                 blurhash: None,
                 reason: None,
+                join_authorized_via_users_server: None,
             })
             .expect("member event is valid value");
 
@@ -939,7 +943,7 @@ pub(crate) async fn invite_helper<'a>(
             }
 
             let pdu = PduEvent {
-                event_id: ruma::event_id!("$thiswillbefilledinlater").to_owned(),
+                event_id: ruma::event_id!("$thiswillbefilledinlater").into(),
                 room_id: room_id.to_owned(),
                 sender: sender_user.to_owned(),
                 origin_server_ts: utils::millis_since_unix_epoch()
@@ -1117,6 +1121,7 @@ pub(crate) async fn invite_helper<'a>(
                 third_party_invite: None,
                 blurhash: db.users.blurhash(user_id)?,
                 reason: None,
+                join_authorized_via_users_server: None,
             })
             .expect("event is valid, we just created it"),
             unsigned: None,
diff --git a/src/client_server/message.rs b/src/client_server/message.rs
index e5219433d..60c756a3f 100644
--- a/src/client_server/message.rs
+++ b/src/client_server/message.rs
@@ -98,7 +98,7 @@ pub async fn send_message_event_route(
 
     db.flush()?;
 
-    Ok(send_message_event::Response::new(event_id).into())
+    Ok(send_message_event::Response::new((*event_id).to_owned()).into())
 }
 
 /// # `GET /_matrix/client/r0/rooms/{roomId}/messages`
diff --git a/src/client_server/redact.rs b/src/client_server/redact.rs
index 7435c5c56..85de2330c 100644
--- a/src/client_server/redact.rs
+++ b/src/client_server/redact.rs
@@ -25,6 +25,7 @@ pub async fn redact_event_route(
     body: Ruma<redact_event::Request<'_>>,
 ) -> ConduitResult<redact_event::Response> {
     let sender_user = body.sender_user.as_ref().expect("user is authenticated");
+    let body = body.body;
 
     let mutex_state = Arc::clone(
         db.globals
@@ -45,7 +46,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.clone()),
+            redacts: Some(body.event_id.into()),
         },
         sender_user,
         &body.room_id,
@@ -57,5 +58,6 @@ pub async fn redact_event_route(
 
     db.flush()?;
 
+    let event_id = (*event_id).to_owned();
     Ok(redact_event::Response { event_id }.into())
 }
diff --git a/src/client_server/room.rs b/src/client_server/room.rs
index 83571f1d5..52d254257 100644
--- a/src/client_server/room.rs
+++ b/src/client_server/room.rs
@@ -22,6 +22,7 @@
         },
         EventType,
     },
+    int,
     serde::{CanonicalJsonObject, JsonObject},
     RoomAliasId, RoomId, RoomVersionId,
 };
@@ -195,6 +196,7 @@ pub async fn create_room_route(
                 third_party_invite: None,
                 blurhash: db.users.blurhash(sender_user)?,
                 reason: None,
+                join_authorized_via_users_server: None,
             })
             .expect("event is valid, we just created it"),
             unsigned: None,
@@ -220,11 +222,11 @@ pub async fn create_room_route(
         });
 
     let mut users = BTreeMap::new();
-    users.insert(sender_user.clone(), 100.into());
+    users.insert(sender_user.clone(), int!(100));
 
     if preset == create_room::RoomPreset::TrustedPrivateChat {
         for invite_ in &body.invite {
-            users.insert(invite_.clone(), 100.into());
+            users.insert(invite_.clone(), int!(100));
         }
     }
 
@@ -569,7 +571,7 @@ pub async fn upgrade_room_route(
     // Use the m.room.tombstone event as the predecessor
     let predecessor = Some(ruma::events::room::create::PreviousRoom::new(
         body.room_id.clone(),
-        tombstone_event_id,
+        (*tombstone_event_id).to_owned(),
     ));
 
     // Send a m.room.create event containing a predecessor field and the applicable room_version
@@ -633,6 +635,7 @@ pub async fn upgrade_room_route(
                 third_party_invite: None,
                 blurhash: db.users.blurhash(sender_user)?,
                 reason: None,
+                join_authorized_via_users_server: None,
             })
             .expect("event is valid, we just created it"),
             unsigned: None,
@@ -697,10 +700,7 @@ pub async fn upgrade_room_route(
     .map_err(|_| Error::bad_database("Invalid room event in database."))?;
 
     // Setting events_default and invite to the greater of 50 and users_default + 1
-    let new_level = max(
-        50.into(),
-        power_levels_event_content.users_default + 1.into(),
-    );
+    let new_level = max(int!(50), power_levels_event_content.users_default + int!(1));
     power_levels_event_content.events_default = new_level;
     power_levels_event_content.invite = new_level;
 
diff --git a/src/client_server/state.rs b/src/client_server/state.rs
index 0ba20620c..e42694aee 100644
--- a/src/client_server/state.rs
+++ b/src/client_server/state.rs
@@ -52,6 +52,7 @@ pub async fn send_state_event_for_key_route(
 
     db.flush()?;
 
+    let event_id = (*event_id).to_owned();
     Ok(send_state_event::Response { event_id }.into())
 }
 
@@ -93,6 +94,7 @@ pub async fn send_state_event_for_empty_key_route(
 
     db.flush()?;
 
+    let event_id = (*event_id).to_owned();
     Ok(send_state_event::Response { event_id }.into())
 }
 
@@ -267,7 +269,7 @@ async fn send_state_event_for_key_helper(
     event_type: EventType,
     json: &Raw<AnyStateEventContent>,
     state_key: String,
-) -> Result<Box<EventId>> {
+) -> Result<Arc<EventId>> {
     let sender_user = sender;
 
     // TODO: Review this check, error if event is unparsable, use event type, allow alias if it
diff --git a/src/database/rooms.rs b/src/database/rooms.rs
index 4c092bf74..fb9ecbf0f 100644
--- a/src/database/rooms.rs
+++ b/src/database/rooms.rs
@@ -1162,14 +1162,14 @@ fn replace_pdu(&self, pdu_id: &[u8], pdu: &PduEvent) -> Result<()> {
 
     /// Returns the leaf pdus of a room.
     #[tracing::instrument(skip(self))]
-    pub fn get_pdu_leaves(&self, room_id: &RoomId) -> Result<HashSet<Box<EventId>>> {
+    pub fn get_pdu_leaves(&self, room_id: &RoomId) -> Result<HashSet<Arc<EventId>>> {
         let mut prefix = room_id.as_bytes().to_vec();
         prefix.push(0xff);
 
         self.roomid_pduleaves
             .scan_prefix(prefix)
             .map(|(_, bytes)| {
-                EventId::parse(utils::string_from_bytes(&bytes).map_err(|_| {
+                EventId::parse_arc(utils::string_from_bytes(&bytes).map_err(|_| {
                     Error::bad_database("EventID in roomid_pduleaves is invalid unicode.")
                 })?)
                 .map_err(|_| Error::bad_database("EventId in roomid_pduleaves is invalid."))
@@ -1178,7 +1178,7 @@ pub fn get_pdu_leaves(&self, room_id: &RoomId) -> Result<HashSet<Box<EventId>>>
     }
 
     #[tracing::instrument(skip(self, room_id, event_ids))]
-    pub fn mark_as_referenced(&self, room_id: &RoomId, event_ids: &[Box<EventId>]) -> Result<()> {
+    pub fn mark_as_referenced(&self, room_id: &RoomId, event_ids: &[Arc<EventId>]) -> Result<()> {
         for prev in event_ids {
             let mut key = room_id.as_bytes().to_vec();
             key.extend_from_slice(prev.as_bytes());
@@ -1953,7 +1953,7 @@ pub fn build_and_append_pdu(
         room_id: &RoomId,
         db: &Database,
         _mutex_lock: &MutexGuard<'_, ()>, // Take mutex guard to make sure users get the room mutex
-    ) -> Result<Box<EventId>> {
+    ) -> Result<Arc<EventId>> {
         let PduBuilder {
             event_type,
             content,
@@ -2019,7 +2019,7 @@ pub fn build_and_append_pdu(
         }
 
         let mut pdu = PduEvent {
-            event_id: ruma::event_id!("$thiswillbefilledinlater").to_owned(),
+            event_id: ruma::event_id!("$thiswillbefilledinlater").into(),
             room_id: room_id.to_owned(),
             sender: sender.to_owned(),
             origin_server_ts: utils::millis_since_unix_epoch()
@@ -2086,7 +2086,7 @@ pub fn build_and_append_pdu(
         .expect("event is valid, we just created it");
 
         // Generate event id
-        pdu.event_id = EventId::parse(format!(
+        pdu.event_id = EventId::parse_arc(format!(
             "${}",
             ruma::signatures::reference_hash(&pdu_json, &room_version_id)
                 .expect("ruma can calculate reference hashes")
diff --git a/src/pdu.rs b/src/pdu.rs
index c1f3d27dc..db9375e47 100644
--- a/src/pdu.rs
+++ b/src/pdu.rs
@@ -13,7 +13,7 @@
     json,
     value::{to_raw_value, RawValue as RawJsonValue},
 };
-use std::{cmp::Ordering, collections::BTreeMap, convert::TryInto, ops::Deref};
+use std::{cmp::Ordering, collections::BTreeMap, convert::TryInto, sync::Arc};
 use tracing::warn;
 
 /// Content hashes of a PDU.
@@ -25,7 +25,7 @@ pub struct EventHash {
 
 #[derive(Clone, Deserialize, Serialize, Debug)]
 pub struct PduEvent {
-    pub event_id: Box<EventId>,
+    pub event_id: Arc<EventId>,
     pub room_id: Box<RoomId>,
     pub sender: Box<UserId>,
     pub origin_server_ts: UInt,
@@ -34,11 +34,11 @@ pub struct PduEvent {
     pub content: Box<RawJsonValue>,
     #[serde(skip_serializing_if = "Option::is_none")]
     pub state_key: Option<String>,
-    pub prev_events: Vec<Box<EventId>>,
+    pub prev_events: Vec<Arc<EventId>>,
     pub depth: UInt,
-    pub auth_events: Vec<Box<EventId>>,
+    pub auth_events: Vec<Arc<EventId>>,
     #[serde(skip_serializing_if = "Option::is_none")]
-    pub redacts: Option<Box<EventId>>,
+    pub redacts: Option<Arc<EventId>>,
     #[serde(default, skip_serializing_if = "Option::is_none")]
     pub unsigned: Option<Box<RawJsonValue>>,
     pub hashes: EventHash,
@@ -266,7 +266,9 @@ pub fn from_id_val(
 }
 
 impl state_res::Event for PduEvent {
-    fn event_id(&self) -> &EventId {
+    type Id = Arc<EventId>;
+
+    fn event_id(&self) -> &Self::Id {
         &self.event_id
     }
 
@@ -294,16 +296,16 @@ fn state_key(&self) -> Option<&str> {
         self.state_key.as_deref()
     }
 
-    fn prev_events(&self) -> Box<dyn DoubleEndedIterator<Item = &EventId> + '_> {
-        Box::new(self.prev_events.iter().map(Deref::deref))
+    fn prev_events(&self) -> Box<dyn DoubleEndedIterator<Item = &Self::Id> + '_> {
+        Box::new(self.prev_events.iter())
     }
 
-    fn auth_events(&self) -> Box<dyn DoubleEndedIterator<Item = &EventId> + '_> {
-        Box::new(self.auth_events.iter().map(Deref::deref))
+    fn auth_events(&self) -> Box<dyn DoubleEndedIterator<Item = &Self::Id> + '_> {
+        Box::new(self.auth_events.iter())
     }
 
-    fn redacts(&self) -> Option<&EventId> {
-        self.redacts.as_deref()
+    fn redacts(&self) -> Option<&Self::Id> {
+        self.redacts.as_ref()
     }
 }
 
@@ -357,7 +359,7 @@ pub struct PduBuilder {
     pub content: Box<RawJsonValue>,
     pub unsigned: Option<BTreeMap<String, serde_json::Value>>,
     pub state_key: Option<String>,
-    pub redacts: Option<Box<EventId>>,
+    pub redacts: Option<Arc<EventId>>,
 }
 
 /// Direct conversion prevents loss of the empty `state_key` that ruma requires.
diff --git a/src/server_server.rs b/src/server_server.rs
index ca6bb3fd5..594152aed 100644
--- a/src/server_server.rs
+++ b/src/server_server.rs
@@ -995,13 +995,9 @@ pub(crate) async fn handle_incoming_pdu<'a>(
     }
 
     // 9. Fetch any missing prev events doing all checks listed here starting at 1. These are timeline events
-    let mut graph = HashMap::new();
+    let mut graph: HashMap<Arc<EventId>, _> = HashMap::new();
     let mut eventid_info = HashMap::new();
-    let mut todo_outlier_stack: Vec<Arc<EventId>> = incoming_pdu
-        .prev_events
-        .iter()
-        .map(|x| Arc::from(&**x))
-        .collect();
+    let mut todo_outlier_stack: Vec<Arc<EventId>> = incoming_pdu.prev_events.clone();
 
     let mut amount = 0;
 
@@ -1020,7 +1016,7 @@ pub(crate) async fn handle_incoming_pdu<'a>(
             if amount > 100 {
                 // Max limit reached
                 warn!("Max prev event limit reached!");
-                graph.insert((*prev_event_id).to_owned(), HashSet::new());
+                graph.insert(prev_event_id.clone(), HashSet::new());
                 continue;
             }
 
@@ -1031,27 +1027,27 @@ pub(crate) async fn handle_incoming_pdu<'a>(
                     amount += 1;
                     for prev_prev in &pdu.prev_events {
                         if !graph.contains_key(prev_prev) {
-                            todo_outlier_stack.push(dbg!(Arc::from(&**prev_prev)));
+                            todo_outlier_stack.push(dbg!(prev_prev.clone()));
                         }
                     }
 
                     graph.insert(
-                        (*prev_event_id).to_owned(),
+                        prev_event_id.clone(),
                         pdu.prev_events.iter().cloned().collect(),
                     );
                 } else {
                     // Time based check failed
-                    graph.insert((*prev_event_id).to_owned(), HashSet::new());
+                    graph.insert(prev_event_id.clone(), HashSet::new());
                 }
 
                 eventid_info.insert(prev_event_id.clone(), (pdu, json));
             } else {
                 // Get json failed
-                graph.insert((*prev_event_id).to_owned(), HashSet::new());
+                graph.insert(prev_event_id.clone(), HashSet::new());
             }
         } else {
             // Fetch and handle failed
-            graph.insert((*prev_event_id).to_owned(), HashSet::new());
+            graph.insert(prev_event_id.clone(), HashSet::new());
         }
     }
 
@@ -1401,14 +1397,13 @@ async fn upgrade_outlier_to_timeline_pdu(
                         .get_statekey_from_short(k)
                         .map_err(|_| "Failed to get_statekey_from_short.".to_owned())?;
 
-                    state.insert(k, (*id).to_owned());
+                    state.insert(k, id.clone());
                     starting_events.push(id);
                 }
 
                 auth_chain_sets.push(
                     get_auth_chain(room_id, starting_events, db)
                         .map_err(|_| "Failed to load auth chain.".to_owned())?
-                        .map(|event_id| (*event_id).to_owned())
                         .collect(),
                 );
 
@@ -1435,7 +1430,7 @@ async fn upgrade_outlier_to_timeline_pdu(
                                 .rooms
                                 .get_or_create_shortstatekey(&event_type, &state_key, &db.globals)
                                 .map_err(|_| "Failed to get_or_create_shortstatekey".to_owned())?;
-                            Ok((shortstatekey, Arc::from(event_id)))
+                            Ok((shortstatekey, event_id))
                         })
                         .collect::<Result<_, String>>()?,
                 ),
@@ -1752,7 +1747,6 @@ async fn upgrade_outlier_to_timeline_pdu(
                         db,
                     )
                     .map_err(|_| "Failed to load auth chain.".to_owned())?
-                    .map(|event_id| (*event_id).to_owned())
                     .collect(),
                 );
             }
@@ -1761,11 +1755,7 @@ async fn upgrade_outlier_to_timeline_pdu(
                 .into_iter()
                 .map(|map| {
                     map.into_iter()
-                        .map(|(k, id)| {
-                            db.rooms
-                                .get_statekey_from_short(k)
-                                .map(|k| (k, (*id).to_owned()))
-                        })
+                        .map(|(k, id)| db.rooms.get_statekey_from_short(k).map(|k| (k, id)))
                         .collect::<Result<StateMap<_>>>()
                 })
                 .collect::<Result<_>>()
@@ -2136,8 +2126,7 @@ fn append_incoming_pdu<'a>(
     if soft_fail {
         db.rooms
             .mark_as_referenced(&pdu.room_id, &pdu.prev_events)?;
-        db.rooms
-            .replace_pdu_leaves(&pdu.room_id, new_room_leaves.clone())?;
+        db.rooms.replace_pdu_leaves(&pdu.room_id, new_room_leaves)?;
         return Ok(None);
     }
 
@@ -2282,7 +2271,7 @@ fn get_auth_chain_inner(
     event_id: &EventId,
     db: &Database,
 ) -> Result<HashSet<u64>> {
-    let mut todo = vec![event_id.to_owned()];
+    let mut todo = vec![Arc::from(event_id)];
     let mut found = HashSet::new();
 
     while let Some(event_id) = todo.pop() {
@@ -2298,7 +2287,7 @@ fn get_auth_chain_inner(
 
                     if !found.contains(&sauthevent) {
                         found.insert(sauthevent);
-                        todo.push(auth_event.to_owned());
+                        todo.push(auth_event.clone());
                     }
                 }
             }
@@ -2676,6 +2665,7 @@ pub fn create_join_event_template_route(
         membership: MembershipState::Join,
         third_party_invite: None,
         reason: None,
+        join_authorized_via_users_server: None,
     })
     .expect("member event is valid value");
 
@@ -2709,7 +2699,7 @@ pub fn create_join_event_template_route(
     }
 
     let pdu = PduEvent {
-        event_id: ruma::event_id!("$thiswillbefilledinlater").to_owned(),
+        event_id: ruma::event_id!("$thiswillbefilledinlater").into(),
         room_id: body.room_id.clone(),
         sender: body.user_id.clone(),
         origin_server_ts: utils::millis_since_unix_epoch()
-- 
GitLab