| 498 | /// and deregister it from the controller. |
| 499 | #[tracing::instrument(level = "trace", skip_all)] |
| 500 | pub async fn exit_module_host(&self, replica_id: u64, timeout: Duration) -> Result<(), anyhow::Error> { |
| 501 | let Some(lock) = self.hosts.lock().remove(&replica_id) else { |
| 502 | return Ok(()); |
| 503 | }; |
| 504 | // To debug the potential deadlock issue reported in |
| 505 | // https://github.com/clockworklabs/SpacetimeDBPrivate/issues/2337 |
| 506 | // we'll log a warning every 5s if we can't acquire an exclusive lock. |
| 507 | let start = Instant::now(); |
| 508 | let mut t = interval_at(start + Duration::from_secs(5), Duration::from_secs(5)); |
| 509 | let warn_blocked = tokio::spawn(async move { |
| 510 | loop { |
| 511 | t.tick().await; |
| 512 | warn!( |
| 513 | "blocked waiting to exit module for replica {} since {}s", |
| 514 | replica_id, |
| 515 | start.elapsed().as_secs_f32() |
| 516 | ); |
| 517 | } |
| 518 | }); |
| 519 | defer!(warn_blocked.abort()); |
| 520 | |
| 521 | let shutdown = tokio::time::timeout(timeout, async { |
| 522 | let mut guard = lock.write_owned().await; |
| 523 | let Some(host) = guard.take() else { |
| 524 | return; |
| 525 | }; |
| 526 | let module = host.module.borrow().clone(); |
| 527 | let info = module.info(); |
| 528 | |
| 529 | let database_identity = info.database_identity; |
| 530 | let table_names = info.module_def.tables().map(|t| t.name.deref()); |
| 531 | |
| 532 | // Ensure we clear the metrics even if the future is cancelled. |
| 533 | defer!(remove_database_gauges(&database_identity, table_names)); |
| 534 | |
| 535 | info!("replica={replica_id} database={database_identity} exiting module"); |
| 536 | module.exit().await; |
| 537 | info!("replica={replica_id} database={database_identity} exiting database"); |
| 538 | module.relational_db().shutdown().await; |
| 539 | info!("replica={replica_id} database={database_identity} module host exited"); |
| 540 | }) |
| 541 | .await; |
| 542 | |
| 543 | if shutdown.is_err() { |
| 544 | warn!( |
| 545 | "replica={replica_id} shutdown timed out after {}s", |
| 546 | start.elapsed().as_secs_f32() |
| 547 | ); |
| 548 | } |
| 549 | |
| 550 | Ok(()) |
| 551 | } |
| 552 | |
| 553 | /// Get the [`ModuleHost`] identified by `replica_id` or return an error |
| 554 | /// if it is not registered with the controller. |