Rename `EventEmitter` to `EventHandler`

master
Cédric Barreteau 2021-02-13 11:01:31 +01:00
parent e3e48148f0
commit b6f2c43330
10 changed files with 80 additions and 80 deletions

View File

@ -22,7 +22,7 @@ In addition to Http, the `AsyncClient` passes along methods from the `BaseClient
Given a Matrix response the crypto machine will update its own internal state, along with encryption information. `BaseClient` and the crypto machine together keep track of when to encrypt. It knows when encryption needs to happen based on signals from the `BaseClient`. The crypto state machine is given responses that relate to encryption and can create encrypted request bodies for encryption-related requests. Basically it tells the `BaseClient` to send to-device messages out, and the `BaseClient` is responsible for notifying the crypto state machine when it sent the message so crypto can update state.
#### Client State/Room and RoomMember
The `BaseClient` is responsible for keeping state in sync through the `IncomingResponse`s of `AsyncClient` or querying the `StateStore`. By processing and then delegating incoming `RoomEvent`s, `StateEvent`s, `PresenceEvent`, `IncomingAccountData` and `EphemeralEvent`s to the correct `Room` in the base clients `HashMap<RoomId, Room>` or further to `Room`'s `RoomMember` via the members `HashMap<UserId, RoomMember>`. The `BaseClient` is also responsible for emitting the incoming events to the `EventEmitter` trait.
The `BaseClient` is responsible for keeping state in sync through the `IncomingResponse`s of `AsyncClient` or querying the `StateStore`. By processing and then delegating incoming `RoomEvent`s, `StateEvent`s, `PresenceEvent`, `IncomingAccountData` and `EphemeralEvent`s to the correct `Room` in the base clients `HashMap<RoomId, Room>` or further to `Room`'s `RoomMember` via the members `HashMap<UserId, RoomMember>`. The `BaseClient` is also responsible for forwarding the incoming events to the `EventHandler` trait.
```rust
/// A Matrix room.
@ -95,6 +95,6 @@ The `BaseClient` also has access to a `dyn StateStore` this is an abstraction ar
The state store will restore our client state in the `BaseClient` and client authors can just get the latest state that they want to present from the client object. No need to ask the state store for it, this may change if custom setups request this. `StateStore`'s main purpose is to provide load/store functionality and, internally to the crate, update the `BaseClient`.
#### Event Emitter
The consumer of this crate can implement the `EventEmitter` trait for full control over how incoming events are handled by their client. If that isn't enough, it is possible to receive every incoming response with the `AsyncClient::sync_forever` callback.
- list the methods for `EventEmitter`?
#### Event Handler
The consumer of this crate can implement the `EventHandler` trait for full control over how incoming events are handled by their client. If that isn't enough, it is possible to receive every incoming response with the `AsyncClient::sync_forever` callback.
- list the methods for `EventHandler`?

View File

@ -4,7 +4,7 @@ use tokio::time::{sleep, Duration};
use matrix_sdk::{
self, async_trait,
events::{room::member::MemberEventContent, StrippedStateEvent},
Client, ClientConfig, EventEmitter, RoomState, SyncSettings,
Client, ClientConfig, EventHandler, RoomState, SyncSettings,
};
use url::Url;
@ -19,7 +19,7 @@ impl AutoJoinBot {
}
#[async_trait]
impl EventEmitter for AutoJoinBot {
impl EventHandler for AutoJoinBot {
async fn on_stripped_state_member(
&self,
room: RoomState,
@ -78,7 +78,7 @@ async fn login_and_sync(
println!("logged in as {}", username);
client
.set_event_emitter(Box::new(AutoJoinBot::new(client.clone())))
.set_event_handler(Box::new(AutoJoinBot::new(client.clone())))
.await;
client.sync(SyncSettings::default()).await;

View File

@ -6,7 +6,7 @@ use matrix_sdk::{
room::message::{MessageEventContent, TextMessageEventContent},
AnyMessageEventContent, SyncMessageEvent,
},
Client, ClientConfig, EventEmitter, RoomState, SyncSettings,
Client, ClientConfig, EventHandler, RoomState, SyncSettings,
};
use url::Url;
@ -23,7 +23,7 @@ impl CommandBot {
}
#[async_trait]
impl EventEmitter for CommandBot {
impl EventHandler for CommandBot {
async fn on_room_message(
&self,
room: RoomState,
@ -88,13 +88,13 @@ async fn login_and_sync(
// add our CommandBot to be notified of incoming messages, we do this after the initial
// sync to avoid responding to messages before the bot was running.
client
.set_event_emitter(Box::new(CommandBot::new(client.clone())))
.set_event_handler(Box::new(CommandBot::new(client.clone())))
.await;
// since we called `sync_once` before we entered our sync loop we must pass
// that sync token to `sync`
let settings = SyncSettings::default().token(client.sync_token().await.unwrap());
// this keeps state from the server streaming in to CommandBot via the EventEmitter trait
// this keeps state from the server streaming in to CommandBot via the EventHandler trait
client.sync(settings).await;
Ok(())

View File

@ -14,7 +14,7 @@ use matrix_sdk::{
room::message::{MessageEventContent, TextMessageEventContent},
SyncMessageEvent,
},
Client, EventEmitter, RoomState, SyncSettings,
Client, EventHandler, RoomState, SyncSettings,
};
use url::Url;
@ -31,7 +31,7 @@ impl ImageBot {
}
#[async_trait]
impl EventEmitter for ImageBot {
impl EventHandler for ImageBot {
async fn on_room_message(
&self,
room: RoomState,
@ -86,7 +86,7 @@ async fn login_and_sync(
client.sync_once(SyncSettings::default()).await.unwrap();
client
.set_event_emitter(Box::new(ImageBot::new(client.clone(), image)))
.set_event_handler(Box::new(ImageBot::new(client.clone(), image)))
.await;
let settings = SyncSettings::default().token(client.sync_token().await.unwrap());

View File

@ -7,13 +7,13 @@ use matrix_sdk::{
room::message::{MessageEventContent, TextMessageEventContent},
SyncMessageEvent,
},
Client, EventEmitter, RoomState, SyncSettings,
Client, EventHandler, RoomState, SyncSettings,
};
struct EventCallback;
#[async_trait]
impl EventEmitter for EventCallback {
impl EventHandler for EventCallback {
async fn on_room_message(
&self,
room: RoomState,
@ -44,7 +44,7 @@ async fn login(
let homeserver_url = Url::parse(&homeserver_url).expect("Couldn't parse the homeserver URL");
let client = Client::new(homeserver_url).unwrap();
client.set_event_emitter(Box::new(EventCallback)).await;
client.set_event_handler(Box::new(EventCallback)).await;
client
.login(username, password, None, Some("rust-sdk"))

View File

@ -41,7 +41,7 @@ use tracing::{error, info, instrument};
use matrix_sdk_base::{
deserialized_responses::{MembersResponse, SyncResponse},
BaseClient, BaseClientConfig, EventEmitter, InvitedRoom, JoinedRoom, LeftRoom, Session, Store,
BaseClient, BaseClientConfig, EventHandler, InvitedRoom, JoinedRoom, LeftRoom, Session, Store,
};
#[cfg(feature = "encryption")]
@ -553,11 +553,11 @@ impl Client {
Ok(())
}
/// Add `EventEmitter` to `Client`.
/// Add `EventHandler` to `Client`.
///
/// The methods of `EventEmitter` are called when the respective `RoomEvents` occur.
pub async fn set_event_emitter(&self, emitter: Box<dyn EventEmitter>) {
self.base_client.set_event_emitter(emitter).await;
/// The methods of `EventHandler` are called when the respective `RoomEvents` occur.
pub async fn set_event_handler(&self, handler: Box<dyn EventHandler>) {
self.base_client.set_event_handler(handler).await;
}
/// Returns the joined rooms this client knows about.

View File

@ -68,7 +68,7 @@ compile_error!("only one of 'native-tls' or 'rustls-tls' features can be enabled
#[cfg_attr(feature = "docs", doc(cfg(encryption)))]
pub use matrix_sdk_base::crypto::LocalTrust;
pub use matrix_sdk_base::{
CustomEvent, Error as BaseError, EventEmitter, InvitedRoom, JoinedRoom, LeftRoom, RoomInfo,
CustomEvent, Error as BaseError, EventHandler, InvitedRoom, JoinedRoom, LeftRoom, RoomInfo,
RoomMember, RoomState, Session, StateChanges, StoreError,
};

View File

@ -59,11 +59,11 @@ use zeroize::Zeroizing;
use crate::{
error::Result,
event_emitter::Emitter,
event_handler::Handler,
rooms::{RoomInfo, RoomType, StrippedRoomInfo},
session::Session,
store::{ambiguity_map::AmbiguityCache, Result as StoreResult, StateChanges, Store},
EventEmitter, RoomState,
EventHandler, RoomState,
};
pub type Token = String;
@ -150,7 +150,7 @@ fn hoist_room_event_prev_content(
Ok(ev)
}
/// Signals to the `BaseClient` which `RoomState` to send to `EventEmitter`.
/// Signals to the `BaseClient` which `RoomState` to send to `EventHandler`.
#[derive(Debug)]
pub enum RoomStateType {
/// Represents a joined room, the `joined_rooms` HashMap will be used.
@ -180,9 +180,9 @@ pub struct BaseClient {
cryptostore: Arc<Mutex<Option<Box<dyn CryptoStore>>>>,
store_path: Arc<Option<PathBuf>>,
store_passphrase: Arc<Option<Zeroizing<String>>>,
/// Any implementor of EventEmitter will act as the callbacks for various
/// Any implementor of EventHandler will act as the callbacks for various
/// events.
event_emitter: Arc<RwLock<Option<Emitter>>>,
event_handler: Arc<RwLock<Option<Handler>>>,
}
#[cfg(not(tarpaulin_include))]
@ -328,7 +328,7 @@ impl BaseClient {
cryptostore: Mutex::new(crypto_store).into(),
store_path: config.store_path.into(),
store_passphrase: config.passphrase.into(),
event_emitter: RwLock::new(None).into(),
event_handler: RwLock::new(None).into(),
})
}
@ -427,15 +427,15 @@ impl BaseClient {
self.sync_token.read().await.clone()
}
/// Add `EventEmitter` to `Client`.
/// Add `EventHandler` to `Client`.
///
/// The methods of `EventEmitter` are called when the respective `RoomEvents` occur.
pub async fn set_event_emitter(&self, emitter: Box<dyn EventEmitter>) {
let emitter = Emitter {
inner: emitter,
/// The methods of `EventHandler` are called when the respective `RoomEvents` occur.
pub async fn set_event_handler(&self, handler: Box<dyn EventHandler>) {
let handler = Handler {
inner: handler,
store: self.store.clone(),
};
*self.event_emitter.write().await = Some(emitter);
*self.event_handler.write().await = Some(handler);
}
async fn handle_timeline(
@ -942,8 +942,8 @@ impl BaseClient {
},
};
if let Some(emitter) = self.event_emitter.read().await.as_ref() {
emitter.emit_sync(&response).await;
if let Some(handler) = self.event_handler.read().await.as_ref() {
handler.handle_sync(&response).await;
}
Ok(response)

View File

@ -52,41 +52,41 @@ use crate::{
};
use matrix_sdk_common::async_trait;
pub(crate) struct Emitter {
pub(crate) inner: Box<dyn EventEmitter>,
pub(crate) struct Handler {
pub(crate) inner: Box<dyn EventHandler>,
pub(crate) store: Store,
}
impl Deref for Emitter {
type Target = dyn EventEmitter;
impl Deref for Handler {
type Target = dyn EventHandler;
fn deref(&self) -> &Self::Target {
&*self.inner
}
}
impl Emitter {
impl Handler {
fn get_room(&self, room_id: &RoomId) -> Option<RoomState> {
self.store.get_room(room_id)
}
pub(crate) async fn emit_sync(&self, response: &SyncResponse) {
pub(crate) async fn handle_sync(&self, response: &SyncResponse) {
for (room_id, room_info) in &response.rooms.join {
if let Some(room) = self.get_room(room_id) {
for event in &room_info.ephemeral.events {
self.emit_ephemeral_event(room.clone(), event).await;
self.handle_ephemeral_event(room.clone(), event).await;
}
for event in &room_info.account_data.events {
self.emit_account_data_event(room.clone(), event).await;
self.handle_account_data_event(room.clone(), event).await;
}
for event in &room_info.state.events {
self.emit_state_event(room.clone(), event).await;
self.handle_state_event(room.clone(), event).await;
}
for event in &room_info.timeline.events {
self.emit_timeline_event(room.clone(), event).await;
self.handle_timeline_event(room.clone(), event).await;
}
}
}
@ -94,15 +94,15 @@ impl Emitter {
for (room_id, room_info) in &response.rooms.leave {
if let Some(room) = self.get_room(room_id) {
for event in &room_info.account_data.events {
self.emit_account_data_event(room.clone(), event).await;
self.handle_account_data_event(room.clone(), event).await;
}
for event in &room_info.state.events {
self.emit_state_event(room.clone(), event).await;
self.handle_state_event(room.clone(), event).await;
}
for event in &room_info.timeline.events {
self.emit_timeline_event(room.clone(), event).await;
self.handle_timeline_event(room.clone(), event).await;
}
}
}
@ -110,7 +110,7 @@ impl Emitter {
for (room_id, room_info) in &response.rooms.invite {
if let Some(room) = self.get_room(room_id) {
for event in &room_info.invite_state.events {
self.emit_stripped_state_event(room.clone(), event).await;
self.handle_stripped_state_event(room.clone(), event).await;
}
}
}
@ -120,7 +120,7 @@ impl Emitter {
}
}
async fn emit_timeline_event(&self, room: RoomState, event: &AnySyncRoomEvent) {
async fn handle_timeline_event(&self, room: RoomState, event: &AnySyncRoomEvent) {
match event {
AnySyncRoomEvent::State(event) => match event {
AnySyncStateEvent::RoomMember(e) => self.on_room_member(room, e).await,
@ -160,7 +160,7 @@ impl Emitter {
}
}
async fn emit_state_event(&self, room: RoomState, event: &AnySyncStateEvent) {
async fn handle_state_event(&self, room: RoomState, event: &AnySyncStateEvent) {
match event {
AnySyncStateEvent::RoomMember(member) => self.on_state_member(room, &member).await,
AnySyncStateEvent::RoomName(name) => self.on_state_name(room, &name).await,
@ -185,9 +185,9 @@ impl Emitter {
}
}
pub(crate) async fn emit_stripped_state_event(
pub(crate) async fn handle_stripped_state_event(
&self,
// TODO these events are only emitted in invited rooms.
// TODO these events are only handleted in invited rooms.
room: RoomState,
event: &AnyStrippedStateEvent,
) {
@ -216,7 +216,7 @@ impl Emitter {
}
}
pub(crate) async fn emit_account_data_event(&self, room: RoomState, event: &AnyBasicEvent) {
pub(crate) async fn handle_account_data_event(&self, room: RoomState, event: &AnyBasicEvent) {
match event {
AnyBasicEvent::Presence(presence) => self.on_non_room_presence(room, &presence).await,
AnyBasicEvent::IgnoredUserList(ignored) => {
@ -227,7 +227,7 @@ impl Emitter {
}
}
pub(crate) async fn emit_ephemeral_event(
pub(crate) async fn handle_ephemeral_event(
&self,
room: RoomState,
event: &AnySyncEphemeralRoomEvent,
@ -262,7 +262,7 @@ pub enum CustomEvent<'c> {
StrippedState(&'c StrippedStateEvent<CustomEventContent>),
}
/// This trait allows any type implementing `EventEmitter` to specify event callbacks for each event.
/// This trait allows any type implementing `EventHandler` to specify event callbacks for each event.
/// The `Client` calls each method when the corresponding event is received.
///
/// # Examples
@ -276,14 +276,14 @@ pub enum CustomEvent<'c> {
/// # room::message::{MessageEventContent, TextMessageEventContent},
/// # SyncMessageEvent
/// # },
/// # EventEmitter, RoomState
/// # EventHandler, RoomState
/// # };
/// # use matrix_sdk_common::{async_trait, locks::RwLock};
///
/// struct EventCallback;
///
/// #[async_trait]
/// impl EventEmitter for EventCallback {
/// impl EventHandler for EventCallback {
/// async fn on_room_message(&self, room: RoomState, event: &SyncMessageEvent<MessageEventContent>) {
/// if let RoomState::Joined(room) = room {
/// if let SyncMessageEvent {
@ -304,7 +304,7 @@ pub enum CustomEvent<'c> {
/// ```
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait EventEmitter: Send + Sync {
pub trait EventHandler: Send + Sync {
// ROOM EVENTS from `IncomingTimeline`
/// Fires when `Client` receives a `RoomEvent::RoomMember` event.
async fn on_room_member(&self, _: RoomState, _: &SyncStateEvent<MemberEventContent>) {}
@ -496,11 +496,11 @@ mod test {
pub use wasm_bindgen_test::*;
#[derive(Clone)]
pub struct EvEmitterTest(Arc<Mutex<Vec<String>>>);
pub struct EvHandlerTest(Arc<Mutex<Vec<String>>>);
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl EventEmitter for EvEmitterTest {
impl EventHandler for EvHandlerTest {
async fn on_room_member(&self, _: RoomState, _: &SyncStateEvent<MemberEventContent>) {
self.0.lock().await.push("member".to_string())
}
@ -740,13 +740,13 @@ mod test {
}
#[async_test]
async fn event_emitter_joined() {
async fn event_handler_joined() {
let vec = Arc::new(Mutex::new(Vec::new()));
let test_vec = Arc::clone(&vec);
let emitter = Box::new(EvEmitterTest(vec));
let handler = Box::new(EvHandlerTest(vec));
let client = get_client().await;
client.set_event_emitter(emitter).await;
client.set_event_handler(handler).await;
let response = sync_response(SyncResponseFile::Default);
client.receive_sync_response(response).await.unwrap();
@ -772,13 +772,13 @@ mod test {
}
#[async_test]
async fn event_emitter_invite() {
async fn event_handler_invite() {
let vec = Arc::new(Mutex::new(Vec::new()));
let test_vec = Arc::clone(&vec);
let emitter = Box::new(EvEmitterTest(vec));
let handler = Box::new(EvHandlerTest(vec));
let client = get_client().await;
client.set_event_emitter(emitter).await;
client.set_event_handler(handler).await;
let response = sync_response(SyncResponseFile::Invite);
client.receive_sync_response(response).await.unwrap();
@ -795,13 +795,13 @@ mod test {
}
#[async_test]
async fn event_emitter_leave() {
async fn event_handler_leave() {
let vec = Arc::new(Mutex::new(Vec::new()));
let test_vec = Arc::clone(&vec);
let emitter = Box::new(EvEmitterTest(vec));
let handler = Box::new(EvHandlerTest(vec));
let client = get_client().await;
client.set_event_emitter(emitter).await;
client.set_event_handler(handler).await;
let response = sync_response(SyncResponseFile::Leave);
client.receive_sync_response(response).await.unwrap();
@ -825,13 +825,13 @@ mod test {
}
#[async_test]
async fn event_emitter_more_events() {
async fn event_handler_more_events() {
let vec = Arc::new(Mutex::new(Vec::new()));
let test_vec = Arc::clone(&vec);
let emitter = Box::new(EvEmitterTest(vec));
let handler = Box::new(EvHandlerTest(vec));
let client = get_client().await;
client.set_event_emitter(emitter).await;
client.set_event_handler(handler).await;
let response = sync_response(SyncResponseFile::All);
client.receive_sync_response(response).await.unwrap();
@ -850,13 +850,13 @@ mod test {
}
#[async_test]
async fn event_emitter_voip() {
async fn event_handler_voip() {
let vec = Arc::new(Mutex::new(Vec::new()));
let test_vec = Arc::clone(&vec);
let emitter = Box::new(EvEmitterTest(vec));
let handler = Box::new(EvHandlerTest(vec));
let client = get_client().await;
client.set_event_emitter(emitter).await;
client.set_event_handler(handler).await;
let response = sync_response(SyncResponseFile::Voip);
client.receive_sync_response(response).await.unwrap();

View File

@ -46,12 +46,12 @@ pub use matrix_sdk_common::*;
mod client;
mod error;
mod event_emitter;
mod event_handler;
mod rooms;
mod session;
mod store;
pub use event_emitter::{CustomEvent, EventEmitter};
pub use event_handler::{CustomEvent, EventHandler};
pub use rooms::{
InvitedRoom, JoinedRoom, LeftRoom, Room, RoomInfo, RoomMember, RoomState, StrippedRoom,
StrippedRoomInfo,