|
1 | 1 | use std::collections::HashMap; |
2 | 2 |
|
3 | | -use tauri::{Manager, Runtime, plugin::Builder as PluginBuilder}; |
| 3 | +use tauri::{Manager, RunEvent, Runtime, plugin::Builder as PluginBuilder}; |
4 | 4 | use tokio::sync::RwLock; |
| 5 | +use tracing::{debug, info, warn}; |
5 | 6 |
|
6 | 7 | mod commands; |
7 | 8 | mod decode; |
@@ -57,10 +58,55 @@ impl Builder { |
57 | 58 | ]) |
58 | 59 | .setup(|app, _api| { |
59 | 60 | app.manage(DbInstances::default()); |
| 61 | + debug!("SQLite plugin initialized"); |
60 | 62 | // Future PR: Possibly handle migrations here |
61 | | - // Future PR: Cleanup on app exit |
62 | 63 | Ok(()) |
63 | 64 | }) |
| 65 | + .on_event(|app, event| { |
| 66 | + match event { |
| 67 | + RunEvent::ExitRequested { api, code, .. } => { |
| 68 | + info!("App exit requested (code: {:?}) - closing databases before exit", code); |
| 69 | + |
| 70 | + // Prevent immediate exit so we can close connections and checkpoint WAL |
| 71 | + api.prevent_exit(); |
| 72 | + |
| 73 | + let instances = app.state::<DbInstances>(); |
| 74 | + let app_handle = app.clone(); |
| 75 | + |
| 76 | + tokio::task::block_in_place(|| { |
| 77 | + tokio::runtime::Handle::current().block_on(async { |
| 78 | + let mut instances = instances.0.write().await; |
| 79 | + let wrappers: Vec<DatabaseWrapper> = instances.drain().map(|(_, v)| v).collect(); |
| 80 | + |
| 81 | + for wrapper in wrappers { |
| 82 | + if let Err(e) = wrapper.close().await { |
| 83 | + warn!("Error closing database during exit: {:?}", e); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + debug!("All databases closed, calling exit()..."); |
| 88 | + }) |
| 89 | + }); |
| 90 | + |
| 91 | + app_handle.exit(code.unwrap_or(0)); |
| 92 | + } |
| 93 | + RunEvent::Exit => { |
| 94 | + // ExitRequested should have already closed all databases |
| 95 | + // This is just a safety check |
| 96 | + let instances = app.state::<DbInstances>(); |
| 97 | + if let Ok(instances) = instances.0.try_read() { |
| 98 | + if !instances.is_empty() { |
| 99 | + warn!("Exit event fired with {} database(s) still open - cleanup may have been skipped", instances.len()); |
| 100 | + } else { |
| 101 | + debug!("Exit event: all databases already closed"); |
| 102 | + } |
| 103 | + } |
| 104 | + } |
| 105 | + _ => { |
| 106 | + // Other events don't require action |
| 107 | + } |
| 108 | + } |
| 109 | + }) |
64 | 110 | .build() |
65 | 111 | } |
66 | 112 | } |
|
0 commit comments