1use crate::cleanup::cleanup_api_clients;
2use crate::cleanup::cleanup_roles;
3use crate::cleanup::CleanupTaskType;
4use crate::context::RelatedAuth;
5use crate::context::RelatedPermission;
6use crate::context::RelatedResource;
7use crate::context::RelatedStorage;
8use crate::marker::Marker;
9
10use std::collections::BTreeSet;
11use std::sync::Arc;
12
13use crate::cleanup::CleanupTask;
14use qm_entity::ids::CustomerId;
15use qm_entity::ids::CustomerIds;
16
17use qm_entity::ids::InstitutionId;
18use qm_entity::ids::InstitutionIds;
19
20use qm_entity::ids::OrganizationId;
21use qm_entity::ids::OrganizationIds;
22
23use qm_entity::ids::INSTITUTION_ID_PREFIX;
24use qm_entity::ids::ORGANIZATION_ID_PREFIX;
25use qm_kafka::producer::EventNs;
26use qm_mongodb::bson::doc;
27
28use qm_mongodb::bson::Document;
29use qm_mongodb::ClientSession;
30use qm_mongodb::DB;
31use qm_role::AccessLevel;
32use sqlx::types::Uuid;
33
34use qm_redis::AsyncWorker;
35pub use qm_redis::Producer;
36use qm_redis::Work;
37use qm_redis::WorkerContext;
38use qm_redis::Workers;
39
40lazy_static::lazy_static! {
41 static ref PREFIX: String = {
42 std::env::var("CUSTOMER_CLEANUP_TASK_PREFIX").unwrap_or("cleanup_tasks".to_string())
43 };
44}
45
46pub trait CleanupTaskProducer {
47 fn cleanup_task_producer(&self) -> &qm_redis::Producer;
48}
49
50#[derive(Clone)]
51pub struct CleanupProducer {
52 inner: Arc<Producer>,
53}
54
55impl CleanupProducer {
56 pub fn new(redis: Arc<deadpool_redis::Pool>) -> Self {
57 Self {
58 inner: Arc::new(Producer::new_with_client(redis, PREFIX.as_str())),
59 }
60 }
61}
62
63impl AsRef<Producer> for CleanupProducer {
64 fn as_ref(&self) -> &Producer {
65 self.inner.as_ref()
66 }
67}
68
69pub struct CleanupWorkerCtx<Auth, Store, Resource, Permission> {
70 pub store: Store,
71 _marker: Marker<Auth, Store, Resource, Permission, ()>,
72}
73
74impl<Auth, Store, Resource, Permission> CleanupWorkerCtx<Auth, Store, Resource, Permission> {
75 pub fn new(store: Store) -> Self {
76 Self {
77 store,
78 _marker: std::marker::PhantomData,
79 }
80 }
81}
82
83impl<Auth, Store, Resource, Permission> Clone
84 for CleanupWorkerCtx<Auth, Store, Resource, Permission>
85where
86 Store: RelatedStorage,
87{
88 fn clone(&self) -> Self {
89 Self {
90 store: self.store.clone(),
91 _marker: self._marker,
92 }
93 }
94}
95
96async fn remove_documents(
97 db: &DB,
98 session: &mut ClientSession,
99 collection: &str,
100 query: &Document,
101) -> anyhow::Result<u64> {
102 let result = db
103 .get()
104 .collection::<Document>(collection)
105 .delete_many(query.clone())
106 .session(session)
107 .await?;
108 Ok(result.deleted_count)
109}
110
111async fn cleanup_customers<Auth, Store, Resource, Permission>(
112 worker_ctx: WorkerContext<CleanupWorkerCtx<Auth, Store, Resource, Permission>>,
113 ty: &str,
114 id: Uuid,
115 cids: &CustomerIds,
116) -> anyhow::Result<()>
117where
118 Auth: RelatedAuth<Resource, Permission>,
119 Store: RelatedStorage,
120 Resource: RelatedResource,
121 Permission: RelatedPermission,
122{
123 let store: &Store = &worker_ctx.ctx().store;
124 let db: &DB = store.as_ref();
125 let mut session = db.session().await?;
126 let mut roles = BTreeSet::new();
127 let existing_roles = store.cache_db().roles().await;
128 let access_roles: Vec<&str> = existing_roles
129 .iter()
130 .filter(|k| k.name.contains("access@"))
131 .map(|v| v.name.as_ref())
132 .collect();
133 let mut client_ids = Vec::with_capacity(cids.len());
134 for cid in cids.iter() {
135 client_ids.push(cid.to_string());
136 roles.insert(
137 qm_role::Access::new(AccessLevel::Customer)
138 .with_fmt_id(Some(cid))
139 .to_string(),
140 );
141 extend_roles_with_children(
142 cid,
143 &[INSTITUTION_ID_PREFIX, ORGANIZATION_ID_PREFIX],
144 &access_roles,
145 &mut roles,
146 );
147 }
148 let cids: Vec<i64> = cids.iter().map(CustomerId::unzip).collect();
149 let query = doc! {
150 "owner.cid": {
151 "$in": &cids
152 },
153 };
154 for collection in db
155 .get()
156 .list_collection_names()
157 .session(&mut session)
158 .await?
159 {
160 tracing::debug!("remove all organization related resources from db {collection}");
161 remove_documents(db, &mut session, &collection, &query).await?;
162 }
163 tracing::debug!("cleanup api clients");
164 cleanup_api_clients(store.keycloak(), client_ids).await?;
165 tracing::debug!("cleanup roles");
166 cleanup_roles(store.keycloak(), roles).await?;
167 if let Some(producer) = store.mutation_event_producer() {
169 producer
170 .delete_event(&EventNs::Customer, "customer", "sys", cids)
171 .await?;
172 }
173 worker_ctx.complete().await?;
174 tracing::debug!("finished cleanup task '{ty}' with id '{id}'");
175 Ok(())
176}
177
178fn extend_roles_with_children(
179 v: &impl std::fmt::Display,
180 allowed_prefixes: &[char],
181 access_roles: &[&str],
182 roles: &mut BTreeSet<String>,
183) {
184 let id = v.to_string();
185 for role in access_roles.iter() {
186 if let Some((_, role_id)) = role.rsplit_once("access@") {
187 if !role_id.is_empty()
188 && !id.is_empty()
189 && allowed_prefixes.iter().any(|v| role_id.starts_with(*v))
190 && role_id[1..].starts_with(&id[1..])
191 {
192 roles.insert(role.to_string());
193 }
194 }
195 }
196}
197
198async fn cleanup_organizations<Auth, Store, Resource, Permission>(
199 worker_ctx: WorkerContext<CleanupWorkerCtx<Auth, Store, Resource, Permission>>,
200 ty: &str,
201 id: Uuid,
202 strict_oids: &OrganizationIds,
203) -> anyhow::Result<()>
204where
205 Auth: RelatedAuth<Resource, Permission>,
206 Store: RelatedStorage,
207 Resource: RelatedResource,
208 Permission: RelatedPermission,
209{
210 let store: &Store = &worker_ctx.ctx().store;
211 let db: &DB = store.as_ref();
212 let mut session = db.session().await?;
213 let mut roles = BTreeSet::new();
214 let existing_roles = store.cache_db().roles().await;
215 let access_roles: Vec<&str> = existing_roles
216 .iter()
217 .filter(|k| k.name.contains("access@"))
218 .map(|v| v.name.as_ref())
219 .collect();
220 let mut client_ids = Vec::with_capacity(strict_oids.len());
221 for v in strict_oids.iter() {
222 client_ids.push(v.to_string());
223 roles.insert(
224 qm_role::Access::new(AccessLevel::Organization)
225 .with_fmt_id(Some(&v))
226 .to_string(),
227 );
228 extend_roles_with_children(v, &[INSTITUTION_ID_PREFIX], &access_roles, &mut roles);
229 }
230 let (cids, oids): (Vec<i64>, Vec<i64>) = strict_oids.iter().map(OrganizationId::unzip).unzip();
231 let query = doc! {
232 "owner.cid": {
233 "$in": &cids
234 },
235 "owner.oid": {
236 "$in": &oids
237 }
238 };
239 for collection in db
240 .get()
241 .list_collection_names()
242 .session(&mut session)
243 .await?
244 {
245 tracing::debug!("remove all organization related resources from db {collection}");
246 remove_documents(db, &mut session, &collection, &query).await?;
247 }
248 tracing::debug!("cleanup api clients");
249 cleanup_api_clients(store.keycloak(), client_ids).await?;
250 tracing::debug!("cleanup roles");
251 cleanup_roles(store.keycloak(), roles).await?;
252 if let Some(producer) = store.mutation_event_producer() {
254 producer
255 .delete_event(&EventNs::Organization, "organization", "sys", strict_oids)
256 .await?;
257 }
258 worker_ctx.complete().await?;
259 tracing::debug!("finished cleanup task '{ty}' with id '{id}'");
260 Ok(())
261}
262
263async fn cleanup_institutions<Auth, Store, Resource, Permission>(
264 worker_ctx: WorkerContext<CleanupWorkerCtx<Auth, Store, Resource, Permission>>,
265 ty: &str,
266 id: Uuid,
267 strict_iids: &InstitutionIds,
268) -> anyhow::Result<()>
269where
270 Auth: RelatedAuth<Resource, Permission>,
271 Store: RelatedStorage,
272 Resource: RelatedResource,
273 Permission: RelatedPermission,
274{
275 let store: &Store = &worker_ctx.ctx().store;
276 let db = store.as_ref();
277 let mut session = db.session().await?;
278 let mut roles = BTreeSet::new();
279 let mut client_ids = Vec::with_capacity(strict_iids.len());
280 for id in strict_iids.iter() {
281 client_ids.push(id.to_string());
282 roles.insert(
283 qm_role::Access::new(AccessLevel::Institution)
284 .with_fmt_id(Some(&id))
285 .to_string(),
286 );
287 }
288 let (cids, (oids, iids)): (Vec<i64>, (Vec<i64>, Vec<i64>)) =
289 strict_iids.iter().map(InstitutionId::untuple).unzip();
290 let query = doc! {
291 "owner.cid": {
292 "$in": &cids
293 },
294 "owner.oid": {
295 "$in": &oids
296 },
297 "owner.iid": {
298 "$in": &iids
299 }
300 };
301 for collection in db
302 .get()
303 .list_collection_names()
304 .session(&mut session)
305 .await?
306 {
307 tracing::debug!("remove all organization related resources from db {collection}");
308 remove_documents(db, &mut session, &collection, &query).await?;
309 }
310 tracing::debug!("cleanup api clients");
311 cleanup_api_clients(store.keycloak(), client_ids).await?;
312 tracing::debug!("cleanup roles");
313 cleanup_roles(store.keycloak(), roles).await?;
314 if let Some(producer) = store.mutation_event_producer() {
316 producer
317 .delete_event(&EventNs::Institution, "institution", "sys", strict_iids)
318 .await?;
319 }
320 worker_ctx.complete().await?;
321 tracing::debug!("finished cleanup task '{ty}' with id '{id}'");
322 Ok(())
323}
324
325pub struct CleanupWorker;
326
327#[async_trait::async_trait]
328impl<Auth, Store, Resource, Permission>
329 Work<CleanupWorkerCtx<Auth, Store, Resource, Permission>, CleanupTask> for CleanupWorker
330where
331 Auth: RelatedAuth<Resource, Permission>,
332 Store: RelatedStorage,
333 Resource: RelatedResource,
334 Permission: RelatedPermission,
335{
336 async fn run(
337 &self,
338 ctx: WorkerContext<CleanupWorkerCtx<Auth, Store, Resource, Permission>>,
339 item: CleanupTask,
340 ) -> anyhow::Result<()> {
341 tracing::debug!(
342 "start cleanup task '{}' with id '{}'",
343 item.ty.as_ref(),
344 item.id
345 );
346 match &item.ty {
347 CleanupTaskType::Customers(ids) => {
348 cleanup_customers(ctx, item.ty.as_ref(), item.id, ids).await?;
349 }
350 CleanupTaskType::Organizations(ids) => {
351 cleanup_organizations(ctx, item.ty.as_ref(), item.id, ids).await?;
352 }
353 CleanupTaskType::Institutions(ids) => {
354 cleanup_institutions(ctx, item.ty.as_ref(), item.id, ids).await?;
355 }
356 CleanupTaskType::None => {
357 ctx.complete().await?;
358 }
359 }
360 Ok(())
361 }
362}
363
364pub async fn run<Auth, Store, Resource, Permission>(
365 workers: &Workers,
366 ctx: CleanupWorkerCtx<Auth, Store, Resource, Permission>,
367 num_workers: usize,
368) -> anyhow::Result<()>
369where
370 Auth: RelatedAuth<Resource, Permission>,
371 Store: RelatedStorage,
372 Resource: RelatedResource,
373 Permission: RelatedPermission,
374{
375 workers
376 .start(
377 ctx,
378 AsyncWorker::new(PREFIX.as_str())
379 .with_num_workers(num_workers)
380 .run(CleanupWorker),
381 )
382 .await?;
383 Ok(())
384}