Skip to main content

tuwunel_service/
services.rs

1use std::{fmt, sync::Arc};
2
3use futures::{StreamExt, TryStreamExt};
4use tokio::sync::Mutex;
5use tuwunel_core::{
6	Result, Server, debug, debug_info, implement, info, trace, utils::stream::IterStream,
7};
8use tuwunel_database::Database;
9
10pub(crate) use crate::OnceServices;
11use crate::{
12	account_data, admin, appservice, client, config, deactivate, delayed_events, emergency,
13	federation, fetcher, globals, key_backups, login_ratelimit,
14	manager::Manager,
15	media, membership, oauth, presence, profile, pusher, registration_tokens, rendezvous,
16	resolver,
17	rooms::{self, retention},
18	sending, sendmail, server_keys,
19	service::{Args, Service},
20	storage, sync, tasks, threepid, transaction_ids, turn, uiaa, users,
21};
22
23pub struct Services {
24	pub account_data: Arc<account_data::Service>,
25	pub admin: Arc<admin::Service>,
26	pub appservice: Arc<appservice::Service>,
27	pub config: Arc<config::Service>,
28	pub client: Arc<client::Service>,
29	pub emergency: Arc<emergency::Service>,
30	pub fetcher: Arc<fetcher::Service>,
31	pub globals: Arc<globals::Service>,
32	pub key_backups: Arc<key_backups::Service>,
33	pub login_ratelimit: Arc<login_ratelimit::Service>,
34	pub media: Arc<media::Service>,
35	pub presence: Arc<presence::Service>,
36	pub pusher: Arc<pusher::Service>,
37	pub resolver: Arc<resolver::Service>,
38	pub alias: Arc<rooms::alias::Service>,
39	pub auth_chain: Arc<rooms::auth_chain::Service>,
40	pub delete: Arc<rooms::delete::Service>,
41	pub directory: Arc<rooms::directory::Service>,
42	pub event_handler: Arc<rooms::event_handler::Service>,
43	pub lazy_loading: Arc<rooms::lazy_loading::Service>,
44	pub metadata: Arc<rooms::metadata::Service>,
45	pub pdu_metadata: Arc<rooms::pdu_metadata::Service>,
46	pub read_receipt: Arc<rooms::read_receipt::Service>,
47	pub search: Arc<rooms::search::Service>,
48	pub short: Arc<rooms::short::Service>,
49	pub spaces: Arc<rooms::spaces::Service>,
50	pub state: Arc<rooms::state::Service>,
51	pub state_accessor: Arc<rooms::state_accessor::Service>,
52	pub state_cache: Arc<rooms::state_cache::Service>,
53	pub state_compressor: Arc<rooms::state_compressor::Service>,
54	pub storage: Arc<storage::Service>,
55	pub threads: Arc<rooms::threads::Service>,
56	pub timeline: Arc<rooms::timeline::Service>,
57	pub typing: Arc<rooms::typing::Service>,
58	pub federation: Arc<federation::Service>,
59	pub sending: Arc<sending::Service>,
60	pub server_keys: Arc<server_keys::Service>,
61	pub sync: Arc<sync::Service>,
62	pub tasks: Arc<tasks::Service>,
63	pub transaction_ids: Arc<transaction_ids::Service>,
64	pub uiaa: Arc<uiaa::Service>,
65	pub users: Arc<users::Service>,
66	pub membership: Arc<membership::Service>,
67	pub deactivate: Arc<deactivate::Service>,
68	/// Events clients scheduled to be sent later (MSC4140).
69	pub delayed_events: Arc<delayed_events::Service>,
70	pub oauth: Arc<oauth::Service>,
71	pub retention: Arc<retention::Service>,
72	pub registration_tokens: Arc<registration_tokens::Service>,
73	pub rendezvous: Arc<rendezvous::Service>,
74	pub sendmail: Arc<sendmail::Service>,
75	pub threepid: Arc<threepid::Service>,
76	pub profile: Arc<profile::Service>,
77	/// TURN credentials from an external provider, shared by all users.
78	pub turn: Arc<turn::Service>,
79
80	manager: Mutex<Option<Arc<Manager>>>,
81	pub server: Arc<Server>,
82	pub db: Arc<Database>,
83}
84
85#[implement(Services)]
86pub async fn build(server: Arc<Server>) -> Result<Arc<Self>> {
87	let db = Database::open(&server).await?;
88	let services = Arc::new(OnceServices::default());
89	let args = Args {
90		db: &db,
91		server: &server,
92		services: &services,
93	};
94
95	let res = Arc::new(Self {
96		account_data: account_data::Service::build(&args)?,
97		admin: admin::Service::build(&args)?,
98		appservice: appservice::Service::build(&args)?,
99		resolver: resolver::Service::build(&args)?,
100		client: client::Service::build(&args)?,
101		config: config::Service::build(&args)?,
102		emergency: emergency::Service::build(&args)?,
103		fetcher: fetcher::Service::build(&args)?,
104		globals: globals::Service::build(&args)?,
105		key_backups: key_backups::Service::build(&args)?,
106		media: media::Service::build(&args)?,
107		presence: presence::Service::build(&args)?,
108		pusher: pusher::Service::build(&args)?,
109		alias: rooms::alias::Service::build(&args)?,
110		auth_chain: rooms::auth_chain::Service::build(&args)?,
111		delete: rooms::delete::Service::build(&args)?,
112		directory: rooms::directory::Service::build(&args)?,
113		event_handler: rooms::event_handler::Service::build(&args)?,
114		lazy_loading: rooms::lazy_loading::Service::build(&args)?,
115		metadata: rooms::metadata::Service::build(&args)?,
116		pdu_metadata: rooms::pdu_metadata::Service::build(&args)?,
117		read_receipt: rooms::read_receipt::Service::build(&args)?,
118		search: rooms::search::Service::build(&args)?,
119		short: rooms::short::Service::build(&args)?,
120		spaces: rooms::spaces::Service::build(&args)?,
121		state: rooms::state::Service::build(&args)?,
122		state_accessor: rooms::state_accessor::Service::build(&args)?,
123		state_cache: rooms::state_cache::Service::build(&args)?,
124		state_compressor: rooms::state_compressor::Service::build(&args)?,
125		storage: storage::Service::build(&args)?,
126		threads: rooms::threads::Service::build(&args)?,
127		timeline: rooms::timeline::Service::build(&args)?,
128		typing: rooms::typing::Service::build(&args)?,
129		federation: federation::Service::build(&args)?,
130		sending: sending::Service::build(&args)?,
131		server_keys: server_keys::Service::build(&args)?,
132		sync: sync::Service::build(&args)?,
133		tasks: tasks::Service::build(&args)?,
134		transaction_ids: transaction_ids::Service::build(&args)?,
135		login_ratelimit: login_ratelimit::Service::build(&args)?,
136		uiaa: uiaa::Service::build(&args)?,
137		users: users::Service::build(&args)?,
138		membership: membership::Service::build(&args)?,
139		deactivate: deactivate::Service::build(&args)?,
140		delayed_events: delayed_events::Service::build(&args)?,
141		oauth: oauth::Service::build(&args)?,
142		retention: retention::Service::build(&args)?,
143		registration_tokens: registration_tokens::Service::build(&args)?,
144		rendezvous: rendezvous::Service::build(&args)?,
145		sendmail: sendmail::Service::build(&args)?,
146		threepid: threepid::Service::build(&args)?,
147		profile: profile::Service::build(&args)?,
148		turn: turn::Service::build(&args)?,
149
150		manager: Mutex::new(None),
151		server,
152		db,
153	});
154
155	Ok(services.set(res))
156}
157
158#[implement(Services)]
159pub(crate) fn services(&self) -> impl Iterator<Item = Arc<dyn Service>> + Send {
160	macro_rules! cast {
161		($s:expr) => {
162			<Arc<dyn Service> as Into<_>>::into($s.clone())
163		};
164	}
165
166	[
167		cast!(self.account_data),
168		cast!(self.admin),
169		cast!(self.appservice),
170		cast!(self.resolver),
171		cast!(self.client),
172		cast!(self.config),
173		cast!(self.emergency),
174		cast!(self.fetcher),
175		cast!(self.globals),
176		cast!(self.key_backups),
177		cast!(self.media),
178		cast!(self.presence),
179		cast!(self.pusher),
180		cast!(self.alias),
181		cast!(self.auth_chain),
182		cast!(self.delete),
183		cast!(self.directory),
184		cast!(self.event_handler),
185		cast!(self.lazy_loading),
186		cast!(self.metadata),
187		cast!(self.pdu_metadata),
188		cast!(self.read_receipt),
189		cast!(self.search),
190		cast!(self.short),
191		cast!(self.spaces),
192		cast!(self.state),
193		cast!(self.state_accessor),
194		cast!(self.state_cache),
195		cast!(self.state_compressor),
196		cast!(self.storage),
197		cast!(self.threads),
198		cast!(self.timeline),
199		cast!(self.typing),
200		cast!(self.federation),
201		cast!(self.sending),
202		cast!(self.server_keys),
203		cast!(self.sync),
204		cast!(self.tasks),
205		cast!(self.transaction_ids),
206		cast!(self.uiaa),
207		cast!(self.users),
208		cast!(self.membership),
209		cast!(self.deactivate),
210		cast!(self.delayed_events),
211		cast!(self.oauth),
212		cast!(self.retention),
213		cast!(self.registration_tokens),
214		cast!(self.rendezvous),
215		cast!(self.profile),
216		cast!(self.turn),
217	]
218	.into_iter()
219}
220
221impl fmt::Debug for Services {
222	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223		f.debug_struct("Services").finish()
224	}
225}
226
227#[implement(Services)]
228pub async fn start(self: &Arc<Self>) -> Result<Arc<Self>> {
229	debug_info!("Starting services...");
230
231	super::migrations::migrations(self).await?;
232	self.users.validate_server_user().await?;
233
234	self.manager
235		.lock()
236		.await
237		.insert(Manager::new(self))
238		.clone()
239		.start()
240		.await?;
241
242	debug_info!("Services startup complete.");
243
244	Ok(Arc::clone(self))
245}
246
247#[implement(Services)]
248pub async fn stop(&self) {
249	info!("Shutting down services...");
250
251	self.interrupt().await;
252	if let Some(manager) = self.manager.lock().await.as_ref() {
253		manager.stop().await;
254	}
255
256	debug_info!("Services shutdown complete.");
257}
258
259#[implement(Services)]
260pub(crate) async fn interrupt(&self) {
261	debug!("Interrupting services...");
262	for service in self.services() {
263		trace!(
264			name = ?service.name(),
265			"Interrupting Service"
266		);
267
268		service.interrupt().await;
269	}
270}
271
272#[implement(Services)]
273pub async fn poll(&self) -> Result {
274	if let Some(manager) = self.manager.lock().await.as_ref() {
275		trace!("Polling service manager...");
276		return manager.poll().await;
277	}
278
279	Ok(())
280}
281
282#[implement(Services)]
283pub async fn clear_cache(&self) {
284	// Uncorked, every per-key delete in a database-backed cache flushes the
285	// write-ahead log; the rows are reconstructible, so no fsync is owed.
286	let _cork = self.db.cork_and_flush();
287
288	self.services()
289		.stream()
290		.for_each(async |service| {
291			service.clear_cache().await;
292		})
293		.await;
294}
295
296#[implement(Services)]
297pub async fn memory_usage(&self) -> Result<String> {
298	self.services()
299		.try_stream()
300		.try_fold(String::new(), async |mut out, service| {
301			service.memory_usage(&mut out).await?;
302			Ok(out)
303		})
304		.await
305}