agentmux_srv_core/migrations/
m0039_vault_into_warden.rs1use std::path::Path;
22use std::sync::Arc;
23
24use serde_json::{Map, Value};
25
26#[cfg(not(any(test, feature = "test-support")))]
27use crate::backend::config_watcher_fs::resolve_settings_dir;
28use crate::backend::storage::store::Store;
29
30use super::{Migration, MigrationContext, MigrationError, MigrationScope, VerifyOutcome};
31
32pub struct M0039VaultIntoWarden;
33
34impl Migration for M0039VaultIntoWarden {
35 fn id(&self) -> &'static str { "0039_vault_into_warden" }
36 fn scope(&self) -> MigrationScope { MigrationScope::Channel }
37 fn description(&self) -> &'static str { "Move saved Vault panes to Warden's Vault section" }
38
39 fn up(&self, ctx: &MigrationContext) -> Result<(), MigrationError> {
40 if ctx.channel_store_path.exists() {
41 let store = Arc::new(
42 Store::open(&ctx.channel_store_path)
43 .map_err(|e| MigrationError(format!("vault_into_warden: open store: {e}")))?,
44 );
45 let blocks = migrate_blocks(&store).map_err(MigrationError)?;
46 let snapshots = migrate_client_snapshots(&store).map_err(MigrationError)?;
47 if blocks + snapshots > 0 {
48 tracing::info!(blocks, snapshots, "vault_into_warden: moved saved Vault panes to Warden");
49 }
50 }
51 if let Some(settings_dir) = settings_dir() {
52 migrate_widgets_file(&settings_dir.join(crate::backend::user_widgets::USER_WIDGETS_FILE));
53 }
54 Ok(())
55 }
56
57 fn verify(&self, ctx: &MigrationContext) -> VerifyOutcome {
58 if !ctx.channel_store_path.exists() {
59 return VerifyOutcome::Ok("no channel store".into());
60 }
61 let store = match Store::open(&ctx.channel_store_path) {
62 Ok(s) => s,
63 Err(e) => return VerifyOutcome::Error(format!("open store: {e}")),
64 };
65 match vault_block_count(&store) {
66 Ok(0) => VerifyOutcome::Ok("no block saved as a Vault pane".into()),
67 Ok(n) => VerifyOutcome::Mismatch(format!("{n} block(s) still saved as a Vault pane")),
68 Err(e) => VerifyOutcome::Error(e),
69 }
70 }
71}
72
73#[cfg(not(any(test, feature = "test-support")))]
76fn settings_dir() -> Option<std::path::PathBuf> {
77 Some(resolve_settings_dir())
78}
79#[cfg(any(test, feature = "test-support"))]
80fn settings_dir() -> Option<std::path::PathBuf> {
81 None
82}
83
84fn migrate_meta(meta: &mut Map<String, Value>) -> bool {
86 if meta.get("view").and_then(Value::as_str) != Some("vault") {
87 return false;
88 }
89 meta.insert("view".into(), "warden".into());
90 meta.insert("warden:section".into(), "vault".into());
91 true
92}
93
94fn migrate_tree(value: &mut Value) -> usize {
96 match value {
97 Value::Object(map) => {
98 let mut n = usize::from(migrate_meta(map));
99 for child in map.values_mut() {
100 n += migrate_tree(child);
101 }
102 n
103 }
104 Value::Array(items) => items.iter_mut().map(migrate_tree).sum(),
105 _ => 0,
106 }
107}
108
109fn read_rows(store: &Store, table: &str) -> Result<Vec<(String, Vec<u8>)>, String> {
110 let conn = store.conn().lock().unwrap();
111 let mut stmt = conn
112 .prepare(&format!("SELECT oid, data FROM {table}"))
113 .map_err(|e| format!("vault_into_warden: read {table}: {e}"))?;
114 let rows = stmt
115 .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?)))
116 .map_err(|e| format!("vault_into_warden: read {table}: {e}"))?
117 .filter_map(Result::ok)
118 .collect();
119 Ok(rows)
120}
121
122fn migrate_blocks(store: &Store) -> Result<usize, String> {
123 let mut changed = 0;
124 for (oid, data) in read_rows(store, "db_block")? {
125 let Ok(mut block) = serde_json::from_slice::<Value>(&data) else { continue };
126 let moved = match block.get_mut("meta") {
127 Some(Value::Object(meta)) => migrate_meta(meta),
128 _ => false,
129 };
130 if moved {
131 store
132 .update_raw("block", &oid, &block)
133 .map_err(|e| format!("vault_into_warden: update block {oid}: {e}"))?;
134 changed += 1;
135 }
136 }
137 Ok(changed)
138}
139
140const SNAPSHOT_META_KEY: &str = "session:last_topology";
141
142fn migrate_client_snapshots(store: &Store) -> Result<usize, String> {
143 let mut changed = 0;
144 for (oid, data) in read_rows(store, "db_client")? {
145 let Ok(mut client) = serde_json::from_slice::<Value>(&data) else { continue };
146 let moved = client
147 .get_mut("meta")
148 .and_then(|m| m.get_mut(SNAPSHOT_META_KEY))
149 .map(migrate_tree)
150 .unwrap_or(0);
151 if moved > 0 {
152 store
153 .update_raw("client", &oid, &client)
154 .map_err(|e| format!("vault_into_warden: update client {oid}: {e}"))?;
155 changed += moved;
156 }
157 }
158 Ok(changed)
159}
160
161fn vault_block_count(store: &Store) -> Result<usize, String> {
162 Ok(read_rows(store, "db_block")?
163 .into_iter()
164 .filter(|(_, data)| {
165 serde_json::from_slice::<Value>(data)
166 .ok()
167 .and_then(|b| b.get("meta")?.get("view")?.as_str().map(|v| v == "vault"))
168 .unwrap_or(false)
169 })
170 .count())
171}
172
173fn migrated_widgets(widgets: &Map<String, Value>) -> Option<Map<String, Value>> {
177 let mut out = widgets.clone();
178 let mut changed = false;
179 for entry in out.values_mut() {
180 let moved = match entry.get_mut("blockdef").and_then(|b| b.get_mut("meta")) {
181 Some(Value::Object(meta)) => migrate_meta(meta),
182 _ => false,
183 };
184 if moved {
185 if let Some(obj) = entry.as_object_mut() {
186 let section = obj.get("section").and_then(Value::as_str).unwrap_or("").to_string();
187 if !section.is_empty() && section != "vault" && !section.starts_with("vault/") {
188 obj.insert("section".into(), Value::String(format!("vault/{section}")));
189 }
190 }
191 }
192 changed |= moved;
193 }
194 changed.then_some(out)
195}
196
197fn migrate_widgets_file(path: &Path) {
198 let Ok(content) = std::fs::read_to_string(path) else { return };
199 if content.trim().is_empty() {
200 return;
201 }
202 let widgets: Map<String, Value> = match serde_json::from_str(&content) {
203 Ok(w) => w,
204 Err(e) => {
205 tracing::warn!(error = %e, "vault_into_warden: widgets.json doesn't parse; left alone");
206 return;
207 }
208 };
209 let Some(next) = migrated_widgets(&widgets) else { return };
210 let text = match serde_json::to_string_pretty(&next) {
211 Ok(t) => t + "\n",
212 Err(_) => return,
213 };
214 match std::fs::write(path, text) {
215 Ok(()) => tracing::info!("vault_into_warden: widgets.json moved to Warden's Vault section"),
216 Err(e) => tracing::warn!(error = %e, "vault_into_warden: couldn't write widgets.json; left as it was"),
217 }
218}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223 use serde_json::json;
224
225 fn meta(v: Value) -> Map<String, Value> {
226 v.as_object().unwrap().clone()
227 }
228
229 #[test]
230 fn a_vault_pane_moves_to_wardens_vault_section_keeping_its_own_section() {
231 let mut m = meta(json!({ "view": "vault", "vault:section": "cards", "vault:request": "r1", "term:zoom": 1.1 }));
232 assert!(migrate_meta(&mut m));
233 assert_eq!(
234 Value::Object(m.clone()),
235 json!({ "view": "warden", "warden:section": "vault", "vault:section": "cards", "vault:request": "r1", "term:zoom": 1.1 })
236 );
237 assert!(!migrate_meta(&mut m));
239 assert!(!migrate_meta(&mut meta(json!({ "view": "warden", "warden:section": "host" }))));
240 assert!(!migrate_meta(&mut meta(json!({ "view": "browser", "url": "https://vault.example" }))));
241 }
242
243 #[test]
244 fn the_session_snapshot_and_widgets_file_move_too() {
245 let mut snapshot = json!({ "tabs": [{ "blocks": [{ "view": "vault" }, { "view": "term" }] }] });
246 assert_eq!(migrate_tree(&mut snapshot), 1);
247 assert_eq!(snapshot["tabs"][0]["blocks"][0], json!({ "view": "warden", "warden:section": "vault" }));
248 assert_eq!(migrate_tree(&mut snapshot), 0);
249
250 let widgets = meta(json!({
251 "my@cards": { "label": "Cards", "blockdef": { "meta": { "view": "vault", "vault:section": "cards" } } },
252 "my@term": { "label": "Term", "blockdef": { "meta": { "view": "term" } } }
253 }));
254 let next = migrated_widgets(&widgets).unwrap();
255 assert_eq!(next["my@cards"]["blockdef"]["meta"], json!({ "view": "warden", "warden:section": "vault", "vault:section": "cards" }));
256 assert_eq!(next["my@term"], widgets["my@term"]);
257 assert!(migrated_widgets(&next).is_none());
258 }
259
260 #[test]
261 fn an_entrys_own_section_becomes_the_vaults_section_on_warden() {
262 let widgets = meta(json!({
263 "my@cards": { "label": "Cards", "section": "cards", "blockdef": { "meta": { "view": "vault" } } },
264 "my@vault": { "label": "Vault", "blockdef": { "meta": { "view": "vault" } } }
265 }));
266 let next = migrated_widgets(&widgets).unwrap();
267 assert_eq!(next["my@cards"]["section"], "vault/cards");
268 assert!(next["my@vault"].get("section").is_none());
269 let mut cards: crate::backend::wconfig::WidgetConfigType = serde_json::from_value(next["my@cards"].clone()).unwrap();
271 cards.resolve_section();
272 assert_eq!(cards.block_def.meta.get("view").and_then(|v| v.as_str()), Some("vault"));
273 assert!(cards.block_def.meta.get("warden:section").is_none());
274 assert_eq!(cards.block_def.meta.get("vault:section").and_then(|v| v.as_str()), Some("cards"));
275 }
276
277 #[test]
278 fn the_widgets_file_is_rewritten_only_when_something_moved() {
279 let dir = tempfile::tempdir().unwrap();
280 let path = dir.path().join("widgets.json");
281 std::fs::write(&path, r#"{"a@b":{"blockdef":{"meta":{"view":"vault"}}}}"#).unwrap();
282 migrate_widgets_file(&path);
283 let after: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
284 assert_eq!(after["a@b"]["blockdef"]["meta"]["view"], "warden");
285 std::fs::write(&path, "{ not json").unwrap();
287 migrate_widgets_file(&path);
288 assert_eq!(std::fs::read_to_string(&path).unwrap(), "{ not json");
289 }
290}