appservice: Rename Appservice to AppService

master
Johannes Becker 2021-06-15 12:09:01 +02:00
parent dbf8cf231d
commit da4876acee
6 changed files with 59 additions and 59 deletions

View File

@ -501,7 +501,7 @@ impl RequestConfig {
/// All outgoing http requests will have a GET query key-value appended with /// All outgoing http requests will have a GET query key-value appended with
/// `user_id` being the key and the `user_id` from the `Session` being /// `user_id` being the key and the `user_id` from the `Session` being
/// the value. Will error if there's no `Session`. This is called /// the value. Will error if there's no `Session`. This is called
/// [identity assertion] in the Matrix Appservice Spec /// [identity assertion] in the Matrix Application Service Spec
/// ///
/// [identity assertion]: https://spec.matrix.org/unstable/application-service-api/#identity-assertion /// [identity assertion]: https://spec.matrix.org/unstable/application-service-api/#identity-assertion
#[cfg(feature = "appservice")] #[cfg(feature = "appservice")]

View File

@ -11,16 +11,16 @@ use matrix_sdk_appservice::{
room::Room, room::Room,
EventHandler, EventHandler,
}, },
Appservice, AppserviceRegistration, AppService, AppServiceRegistration,
}; };
use tracing::{error, trace}; use tracing::{error, trace};
struct AppserviceEventHandler { struct AppServiceEventHandler {
appservice: Appservice, appservice: AppService,
} }
impl AppserviceEventHandler { impl AppServiceEventHandler {
pub fn new(appservice: Appservice) -> Self { pub fn new(appservice: AppService) -> Self {
Self { appservice } Self { appservice }
} }
@ -47,7 +47,7 @@ impl AppserviceEventHandler {
} }
#[async_trait] #[async_trait]
impl EventHandler for AppserviceEventHandler { impl EventHandler for AppServiceEventHandler {
async fn on_room_member(&self, room: Room, event: &SyncStateEvent<MemberEventContent>) { async fn on_room_member(&self, room: Room, event: &SyncStateEvent<MemberEventContent>) {
match self.handle_room_member(room, event).await { match self.handle_room_member(room, event).await {
Ok(_) => (), Ok(_) => (),
@ -63,10 +63,10 @@ pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
let homeserver_url = "http://localhost:8008"; let homeserver_url = "http://localhost:8008";
let server_name = "localhost"; let server_name = "localhost";
let registration = AppserviceRegistration::try_from_yaml_file("./tests/registration.yaml")?; let registration = AppServiceRegistration::try_from_yaml_file("./tests/registration.yaml")?;
let mut appservice = Appservice::new(homeserver_url, server_name, registration).await?; let mut appservice = AppService::new(homeserver_url, server_name, registration).await?;
appservice.set_event_handler(Box::new(AppserviceEventHandler::new(appservice.clone()))).await?; appservice.set_event_handler(Box::new(AppServiceEventHandler::new(appservice.clone()))).await?;
let (host, port) = appservice.registration().get_host_and_port()?; let (host, port) = appservice.registration().get_host_and_port()?;
appservice.run(host, port).await?; appservice.run(host, port).await?;

View File

@ -41,11 +41,11 @@
//! # #[async_trait] //! # #[async_trait]
//! # impl EventHandler for MyEventHandler {} //! # impl EventHandler for MyEventHandler {}
//! # //! #
//! use matrix_sdk_appservice::{Appservice, AppserviceRegistration}; //! use matrix_sdk_appservice::{AppService, AppServiceRegistration};
//! //!
//! let homeserver_url = "http://127.0.0.1:8008"; //! let homeserver_url = "http://127.0.0.1:8008";
//! let server_name = "localhost"; //! let server_name = "localhost";
//! let registration = AppserviceRegistration::try_from_yaml_str( //! let registration = AppServiceRegistration::try_from_yaml_str(
//! r" //! r"
//! id: appservice //! id: appservice
//! url: http://127.0.0.1:9009 //! url: http://127.0.0.1:9009
@ -58,7 +58,7 @@
//! regex: '@_appservice_.*' //! regex: '@_appservice_.*'
//! ")?; //! ")?;
//! //!
//! let mut appservice = Appservice::new(homeserver_url, server_name, registration).await?; //! let mut appservice = AppService::new(homeserver_url, server_name, registration).await?;
//! appservice.set_event_handler(Box::new(MyEventHandler)).await?; //! appservice.set_event_handler(Box::new(MyEventHandler)).await?;
//! //!
//! let (host, port) = appservice.registration().get_host_and_port()?; //! let (host, port) = appservice.registration().get_host_and_port()?;
@ -112,15 +112,15 @@ pub type Result<T> = std::result::Result<T, Error>;
pub type Host = String; pub type Host = String;
pub type Port = u16; pub type Port = u16;
/// Appservice Registration /// AppService Registration
/// ///
/// Wrapper around [`Registration`] /// Wrapper around [`Registration`]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct AppserviceRegistration { pub struct AppServiceRegistration {
inner: Registration, inner: Registration,
} }
impl AppserviceRegistration { impl AppServiceRegistration {
/// Try to load registration from yaml string /// Try to load registration from yaml string
/// ///
/// See the fields of [`Registration`] for the required format /// See the fields of [`Registration`] for the required format
@ -158,13 +158,13 @@ impl AppserviceRegistration {
} }
} }
impl From<Registration> for AppserviceRegistration { impl From<Registration> for AppServiceRegistration {
fn from(value: Registration) -> Self { fn from(value: Registration) -> Self {
Self { inner: value } Self { inner: value }
} }
} }
impl Deref for AppserviceRegistration { impl Deref for AppServiceRegistration {
type Target = Registration; type Target = Registration;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@ -175,7 +175,7 @@ impl Deref for AppserviceRegistration {
type Localpart = String; type Localpart = String;
/// The `localpart` of the user associated with the application service via /// The `localpart` of the user associated with the application service via
/// `sender_localpart` in [`AppserviceRegistration`]. /// `sender_localpart` in [`AppServiceRegistration`].
/// ///
/// Dummy type for shared documentation /// Dummy type for shared documentation
#[allow(dead_code)] #[allow(dead_code)]
@ -183,23 +183,23 @@ pub type MainUser = ();
/// The application service may specify the virtual user to act as through use /// The application service may specify the virtual user to act as through use
/// of a user_id query string parameter on the request. The user specified in /// of a user_id query string parameter on the request. The user specified in
/// the query string must be covered by one of the [`AppserviceRegistration`]'s /// the query string must be covered by one of the [`AppServiceRegistration`]'s
/// `users` namespaces. /// `users` namespaces.
/// ///
/// Dummy type for shared documentation /// Dummy type for shared documentation
pub type VirtualUser = (); pub type VirtualUser = ();
/// Appservice /// AppService
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Appservice { pub struct AppService {
homeserver_url: Url, homeserver_url: Url,
server_name: ServerNameBox, server_name: ServerNameBox,
registration: Arc<AppserviceRegistration>, registration: Arc<AppServiceRegistration>,
clients: Arc<DashMap<Localpart, Client>>, clients: Arc<DashMap<Localpart, Client>>,
} }
impl Appservice { impl AppService {
/// Create new Appservice /// Create new AppService
/// ///
/// Also creates and caches a [`Client`] for the [`MainUser`]. /// Also creates and caches a [`Client`] for the [`MainUser`].
/// The default [`ClientConfig`] is used, if you want to customize it /// The default [`ClientConfig`] is used, if you want to customize it
@ -210,14 +210,14 @@ impl Appservice {
/// * `homeserver_url` - The homeserver that the client should connect to. /// * `homeserver_url` - The homeserver that the client should connect to.
/// * `server_name` - The server name to use when constructing user ids from /// * `server_name` - The server name to use when constructing user ids from
/// the localpart. /// the localpart.
/// * `registration` - The [Appservice Registration] to use when interacting /// * `registration` - The [AppService Registration] to use when interacting
/// with the homeserver. /// with the homeserver.
/// ///
/// [Appservice Registration]: https://matrix.org/docs/spec/application_service/r0.1.2#registration /// [AppService Registration]: https://matrix.org/docs/spec/application_service/r0.1.2#registration
pub async fn new( pub async fn new(
homeserver_url: impl TryInto<Url, Error = url::ParseError>, homeserver_url: impl TryInto<Url, Error = url::ParseError>,
server_name: impl TryInto<ServerNameBox, Error = identifiers::Error>, server_name: impl TryInto<ServerNameBox, Error = identifiers::Error>,
registration: AppserviceRegistration, registration: AppServiceRegistration,
) -> Result<Self> { ) -> Result<Self> {
let appservice = Self::new_with_config( let appservice = Self::new_with_config(
homeserver_url, homeserver_url,
@ -235,7 +235,7 @@ impl Appservice {
pub async fn new_with_config( pub async fn new_with_config(
homeserver_url: impl TryInto<Url, Error = url::ParseError>, homeserver_url: impl TryInto<Url, Error = url::ParseError>,
server_name: impl TryInto<ServerNameBox, Error = identifiers::Error>, server_name: impl TryInto<ServerNameBox, Error = identifiers::Error>,
registration: AppserviceRegistration, registration: AppServiceRegistration,
client_config: ClientConfig, client_config: ClientConfig,
) -> Result<Self> { ) -> Result<Self> {
let homeserver_url = homeserver_url.try_into()?; let homeserver_url = homeserver_url.try_into()?;
@ -244,7 +244,7 @@ impl Appservice {
let clients = Arc::new(DashMap::new()); let clients = Arc::new(DashMap::new());
let sender_localpart = registration.sender_localpart.clone(); let sender_localpart = registration.sender_localpart.clone();
let appservice = Appservice { homeserver_url, server_name, registration, clients }; let appservice = AppService { homeserver_url, server_name, registration, clients };
// we create and cache the [`MainUser`] by default // we create and cache the [`MainUser`] by default
appservice.create_and_cache_client(&sender_localpart, client_config).await?; appservice.create_and_cache_client(&sender_localpart, client_config).await?;
@ -354,12 +354,12 @@ impl Appservice {
/// Convenience wrapper around [`Client::set_event_handler()`] that attaches /// Convenience wrapper around [`Client::set_event_handler()`] that attaches
/// the event handler to the [`MainUser`]'s [`Client`] /// the event handler to the [`MainUser`]'s [`Client`]
/// ///
/// Note that the event handler in the [`Appservice`] context only triggers /// Note that the event handler in the [`AppService`] context only triggers
/// [`join` room `timeline` events], so no state events or events from the /// [`join` room `timeline` events], so no state events or events from the
/// `invite`, `knock` or `leave` scope. The rationale behind that is /// `invite`, `knock` or `leave` scope. The rationale behind that is
/// that incoming Appservice transactions from the homeserver are not /// that incoming AppService transactions from the homeserver are not
/// necessarily bound to a specific user but can cover a multitude of /// necessarily bound to a specific user but can cover a multitude of
/// namespaces, and as such the Appservice basically only "observes /// namespaces, and as such the AppService basically only "observes
/// joined rooms". Also currently homeservers only push PDUs to appservices, /// joined rooms". Also currently homeservers only push PDUs to appservices,
/// no EDUs. There's the open [MSC2409] regarding supporting EDUs in the /// no EDUs. There's the open [MSC2409] regarding supporting EDUs in the
/// future, though it seems to be planned to put EDUs into a different /// future, though it seems to be planned to put EDUs into a different
@ -410,10 +410,10 @@ impl Appservice {
Ok(()) Ok(())
} }
/// Get the Appservice [registration] /// Get the AppService [registration]
/// ///
/// [registration]: https://matrix.org/docs/spec/application_service/r0.1.2#registration /// [registration]: https://matrix.org/docs/spec/application_service/r0.1.2#registration
pub fn registration(&self) -> &AppserviceRegistration { pub fn registration(&self) -> &AppServiceRegistration {
&self.registration &self.registration
} }
@ -424,11 +424,11 @@ impl Appservice {
self.registration.hs_token == hs_token.as_ref() self.registration.hs_token == hs_token.as_ref()
} }
/// Check if given `user_id` is in any of the [`AppserviceRegistration`]'s /// Check if given `user_id` is in any of the [`AppServiceRegistration`]'s
/// `users` namespaces /// `users` namespaces
pub fn user_id_is_in_namespace(&self, user_id: impl AsRef<str>) -> Result<bool> { pub fn user_id_is_in_namespace(&self, user_id: impl AsRef<str>) -> Result<bool> {
for user in &self.registration.namespaces.users { for user in &self.registration.namespaces.users {
// TODO: precompile on Appservice construction // TODO: precompile on AppService construction
let re = Regex::new(&user.regex)?; let re = Regex::new(&user.regex)?;
if re.is_match(user_id.as_ref()) { if re.is_match(user_id.as_ref()) {
return Ok(true); return Ok(true);
@ -477,7 +477,7 @@ impl Appservice {
pub async fn run(&self, host: impl Into<String>, port: impl Into<u16>) -> Result<()> { pub async fn run(&self, host: impl Into<String>, port: impl Into<u16>) -> Result<()> {
let host = host.into(); let host = host.into();
let port = port.into(); let port = port.into();
info!("Starting Appservice on {}:{}", &host, &port); info!("Starting AppService on {}:{}", &host, &port);
#[cfg(feature = "actix")] #[cfg(feature = "actix")]
{ {

View File

@ -26,10 +26,10 @@ use futures::Future;
use futures_util::TryStreamExt; use futures_util::TryStreamExt;
use ruma::api::appservice as api; use ruma::api::appservice as api;
use crate::{error::Error, Appservice}; use crate::{error::Error, AppService};
pub async fn run_server( pub async fn run_server(
appservice: Appservice, appservice: AppService,
host: impl Into<String>, host: impl Into<String>,
port: impl Into<u16>, port: impl Into<u16>,
) -> Result<(), Error> { ) -> Result<(), Error> {
@ -55,7 +55,7 @@ pub fn configure(config: &mut actix_web::web::ServiceConfig) {
#[put("/transactions/{txn_id}")] #[put("/transactions/{txn_id}")]
async fn push_transactions( async fn push_transactions(
request: IncomingRequest<api::event::push_events::v1::IncomingRequest>, request: IncomingRequest<api::event::push_events::v1::IncomingRequest>,
appservice: Data<Appservice>, appservice: Data<AppService>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
if !appservice.compare_hs_token(request.access_token) { if !appservice.compare_hs_token(request.access_token) {
return Ok(HttpResponse::Unauthorized().finish()); return Ok(HttpResponse::Unauthorized().finish());
@ -70,7 +70,7 @@ async fn push_transactions(
#[get("/users/{user_id}")] #[get("/users/{user_id}")]
async fn query_user_id( async fn query_user_id(
request: IncomingRequest<api::query::query_user_id::v1::IncomingRequest>, request: IncomingRequest<api::query::query_user_id::v1::IncomingRequest>,
appservice: Data<Appservice>, appservice: Data<AppService>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
if !appservice.compare_hs_token(request.access_token) { if !appservice.compare_hs_token(request.access_token) {
return Ok(HttpResponse::Unauthorized().finish()); return Ok(HttpResponse::Unauthorized().finish());
@ -83,7 +83,7 @@ async fn query_user_id(
#[get("/rooms/{room_alias}")] #[get("/rooms/{room_alias}")]
async fn query_room_alias( async fn query_room_alias(
request: IncomingRequest<api::query::query_room_alias::v1::IncomingRequest>, request: IncomingRequest<api::query::query_room_alias::v1::IncomingRequest>,
appservice: Data<Appservice>, appservice: Data<AppService>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
if !appservice.compare_hs_token(request.access_token) { if !appservice.compare_hs_token(request.access_token) {
return Ok(HttpResponse::Unauthorized().finish()); return Ok(HttpResponse::Unauthorized().finish());

View File

@ -19,10 +19,10 @@ use matrix_sdk::Bytes;
use serde::Serialize; use serde::Serialize;
use warp::{filters::BoxedFilter, path::FullPath, Filter, Rejection, Reply}; use warp::{filters::BoxedFilter, path::FullPath, Filter, Rejection, Reply};
use crate::{Appservice, Error, Result}; use crate::{AppService, Error, Result};
pub async fn run_server( pub async fn run_server(
appservice: Appservice, appservice: AppService,
host: impl Into<String>, host: impl Into<String>,
port: impl Into<u16>, port: impl Into<u16>,
) -> Result<()> { ) -> Result<()> {
@ -37,7 +37,7 @@ pub async fn run_server(
} }
} }
pub fn warp_filter(appservice: Appservice) -> BoxedFilter<(impl Reply,)> { pub fn warp_filter(appservice: AppService) -> BoxedFilter<(impl Reply,)> {
// TODO: try to use a struct instead of needlessly cloning appservice multiple // TODO: try to use a struct instead of needlessly cloning appservice multiple
// times on every request // times on every request
warp::any() warp::any()
@ -51,7 +51,7 @@ pub fn warp_filter(appservice: Appservice) -> BoxedFilter<(impl Reply,)> {
mod filters { mod filters {
use super::*; use super::*;
pub fn users(appservice: Appservice) -> BoxedFilter<(impl Reply,)> { pub fn users(appservice: AppService) -> BoxedFilter<(impl Reply,)> {
warp::get() warp::get()
.and( .and(
warp::path!("_matrix" / "app" / "v1" / "users" / String) warp::path!("_matrix" / "app" / "v1" / "users" / String)
@ -65,7 +65,7 @@ mod filters {
.boxed() .boxed()
} }
pub fn rooms(appservice: Appservice) -> BoxedFilter<(impl Reply,)> { pub fn rooms(appservice: AppService) -> BoxedFilter<(impl Reply,)> {
warp::get() warp::get()
.and( .and(
warp::path!("_matrix" / "app" / "v1" / "rooms" / String) warp::path!("_matrix" / "app" / "v1" / "rooms" / String)
@ -79,7 +79,7 @@ mod filters {
.boxed() .boxed()
} }
pub fn transactions(appservice: Appservice) -> BoxedFilter<(impl Reply,)> { pub fn transactions(appservice: AppService) -> BoxedFilter<(impl Reply,)> {
warp::put() warp::put()
.and( .and(
warp::path!("_matrix" / "app" / "v1" / "transactions" / String) warp::path!("_matrix" / "app" / "v1" / "transactions" / String)
@ -93,7 +93,7 @@ mod filters {
.boxed() .boxed()
} }
fn common(appservice: Appservice) -> BoxedFilter<(Appservice, http::Request<Bytes>)> { fn common(appservice: AppService) -> BoxedFilter<(AppService, http::Request<Bytes>)> {
warp::any() warp::any()
.and(filters::valid_access_token(appservice.registration().hs_token.clone())) .and(filters::valid_access_token(appservice.registration().hs_token.clone()))
.map(move || appservice.clone()) .map(move || appservice.clone())
@ -156,7 +156,7 @@ mod handlers {
pub async fn user( pub async fn user(
_user_id: String, _user_id: String,
_appservice: Appservice, _appservice: AppService,
_request: http::Request<Bytes>, _request: http::Request<Bytes>,
) -> StdResult<impl warp::Reply, Rejection> { ) -> StdResult<impl warp::Reply, Rejection> {
Ok(warp::reply::json(&String::from("{}"))) Ok(warp::reply::json(&String::from("{}")))
@ -164,7 +164,7 @@ mod handlers {
pub async fn room( pub async fn room(
_room_id: String, _room_id: String,
_appservice: Appservice, _appservice: AppService,
_request: http::Request<Bytes>, _request: http::Request<Bytes>,
) -> StdResult<impl warp::Reply, Rejection> { ) -> StdResult<impl warp::Reply, Rejection> {
Ok(warp::reply::json(&String::from("{}"))) Ok(warp::reply::json(&String::from("{}")))
@ -172,7 +172,7 @@ mod handlers {
pub async fn transaction( pub async fn transaction(
_txn_id: String, _txn_id: String,
appservice: Appservice, appservice: AppService,
request: http::Request<Bytes>, request: http::Request<Bytes>,
) -> StdResult<impl warp::Reply, Rejection> { ) -> StdResult<impl warp::Reply, Rejection> {
let incoming_transaction: matrix_sdk::api_appservice::event::push_events::v1::IncomingRequest = let incoming_transaction: matrix_sdk::api_appservice::event::push_events::v1::IncomingRequest =

View File

@ -19,7 +19,7 @@ fn registration_string() -> String {
include_str!("../tests/registration.yaml").to_owned() include_str!("../tests/registration.yaml").to_owned()
} }
async fn appservice(registration: Option<Registration>) -> Result<Appservice> { async fn appservice(registration: Option<Registration>) -> Result<AppService> {
// env::set_var( // env::set_var(
// "RUST_LOG", // "RUST_LOG",
// "mockito=debug,matrix_sdk=debug,ruma=debug,actix_web=debug,warp=debug", // "mockito=debug,matrix_sdk=debug,ruma=debug,actix_web=debug,warp=debug",
@ -28,7 +28,7 @@ async fn appservice(registration: Option<Registration>) -> Result<Appservice> {
let registration = match registration { let registration = match registration {
Some(registration) => registration.into(), Some(registration) => registration.into(),
None => AppserviceRegistration::try_from_yaml_str(registration_string()).unwrap(), None => AppServiceRegistration::try_from_yaml_str(registration_string()).unwrap(),
}; };
let homeserver_url = mockito::server_url(); let homeserver_url = mockito::server_url();
@ -37,7 +37,7 @@ async fn appservice(registration: Option<Registration>) -> Result<Appservice> {
let client_config = let client_config =
ClientConfig::default().request_config(RequestConfig::default().disable_retry()); ClientConfig::default().request_config(RequestConfig::default().disable_retry());
Ok(Appservice::new_with_config( Ok(AppService::new_with_config(
homeserver_url.as_ref(), homeserver_url.as_ref(),
server_name, server_name,
registration, registration,
@ -355,7 +355,7 @@ mod registration {
#[test] #[test]
fn test_registration() -> Result<()> { fn test_registration() -> Result<()> {
let registration: Registration = serde_yaml::from_str(&registration_string())?; let registration: Registration = serde_yaml::from_str(&registration_string())?;
let registration: AppserviceRegistration = registration.into(); let registration: AppServiceRegistration = registration.into();
assert_eq!(registration.id, "appservice"); assert_eq!(registration.id, "appservice");
@ -364,7 +364,7 @@ mod registration {
#[test] #[test]
fn test_registration_from_yaml_file() -> Result<()> { fn test_registration_from_yaml_file() -> Result<()> {
let registration = AppserviceRegistration::try_from_yaml_file("./tests/registration.yaml")?; let registration = AppServiceRegistration::try_from_yaml_file("./tests/registration.yaml")?;
assert_eq!(registration.id, "appservice"); assert_eq!(registration.id, "appservice");
@ -373,7 +373,7 @@ mod registration {
#[test] #[test]
fn test_registration_from_yaml_str() -> Result<()> { fn test_registration_from_yaml_str() -> Result<()> {
let registration = AppserviceRegistration::try_from_yaml_str(registration_string())?; let registration = AppServiceRegistration::try_from_yaml_str(registration_string())?;
assert_eq!(registration.id, "appservice"); assert_eq!(registration.id, "appservice");