11//! Durable, owner-and-relay-scoped Bestie designation storage.
22
3- use std:: { fs, io:: ErrorKind , path:: Path } ;
3+ use std:: {
4+ fs,
5+ io:: ErrorKind ,
6+ path:: { Path , PathBuf } ,
7+ } ;
48
59use rusqlite:: { params, Connection , OptionalExtension } ;
610use serde:: Serialize ;
@@ -84,16 +88,17 @@ pub fn assignment_matches(conn: &Connection, agent_pubkey: &str) -> Result<bool,
8488 Ok ( get_assignment ( conn) ?. is_some_and ( |assignment| assignment. agent_pubkey == normalized) )
8589}
8690
87- /// Clear this agent's designation from every existing community scope.
88- ///
89- /// Call this while holding `managed_agents_store_lock` and before removing the
90- /// agent record. If one database cannot be updated, deletion stops while the
91- /// agent still exists, so no scope can be left pointing at a deleted agent.
92- pub fn clear_agent_assignments ( base_dir : & Path , agent_pubkey : & str ) -> Result < usize , String > {
91+ #[ derive( Clone ) ]
92+ struct ScopedAssignment {
93+ agent_pubkey : String ,
94+ path : PathBuf ,
95+ }
96+
97+ fn retention_db_paths ( base_dir : & Path ) -> Result < Vec < PathBuf > , String > {
9398 let retention_dir = base_dir. join ( "retention" ) ;
9499 let entries = match fs:: read_dir ( & retention_dir) {
95100 Ok ( entries) => entries,
96- Err ( error) if error. kind ( ) == ErrorKind :: NotFound => return Ok ( 0 ) ,
101+ Err ( error) if error. kind ( ) == ErrorKind :: NotFound => return Ok ( Vec :: new ( ) ) ,
97102 Err ( error) => {
98103 return Err ( format ! (
99104 "failed to read retention directory {}: {error}" ,
@@ -102,8 +107,7 @@ pub fn clear_agent_assignments(base_dir: &Path, agent_pubkey: &str) -> Result<us
102107 }
103108 } ;
104109
105- let normalized = agent_pubkey. trim ( ) . to_ascii_lowercase ( ) ;
106- let mut cleared = 0 ;
110+ let mut paths = Vec :: new ( ) ;
107111 for entry in entries {
108112 let entry = entry. map_err ( |error| {
109113 format ! (
@@ -115,21 +119,106 @@ pub fn clear_agent_assignments(base_dir: &Path, agent_pubkey: &str) -> Result<us
115119 if path. extension ( ) . and_then ( |extension| extension. to_str ( ) ) != Some ( "db" ) {
116120 continue ;
117121 }
122+ paths. push ( path) ;
123+ }
124+ paths. sort ( ) ;
125+ Ok ( paths)
126+ }
127+
128+ fn matching_assignments (
129+ base_dir : & Path ,
130+ agent_pubkey : & str ,
131+ ) -> Result < Vec < ScopedAssignment > , String > {
132+ let normalized = agent_pubkey. trim ( ) . to_ascii_lowercase ( ) ;
133+ let mut assignments = Vec :: new ( ) ;
134+ // Read and validate every scope before mutating any of them. A broken later
135+ // database therefore cannot leave an already-cleared prefix behind.
136+ for path in retention_db_paths ( base_dir) ? {
118137 let conn = open_retention_db ( & path) ?;
119138 ensure_table ( & conn) ?;
120- cleared += conn
121- . execute (
122- "DELETE FROM bestie_assignments WHERE singleton = 1 AND agent_pubkey = ?1" ,
123- params ! [ normalized] ,
124- )
125- . map_err ( |error| {
126- format ! (
127- "failed to clear bestie assignment in {}: {error}" ,
128- path. display( )
129- )
130- } ) ?;
139+ if assignment_matches ( & conn, & normalized) ? {
140+ assignments. push ( ScopedAssignment {
141+ agent_pubkey : normalized. clone ( ) ,
142+ path,
143+ } ) ;
144+ }
145+ }
146+ Ok ( assignments)
147+ }
148+
149+ fn clear_scope ( assignment : & ScopedAssignment ) -> Result < ( ) , String > {
150+ let conn = open_retention_db ( & assignment. path ) ?;
151+ conn. execute (
152+ "DELETE FROM bestie_assignments WHERE singleton = 1 AND agent_pubkey = ?1" ,
153+ params ! [ assignment. agent_pubkey] ,
154+ )
155+ . map_err ( |error| {
156+ format ! (
157+ "failed to clear bestie assignment in {}: {error}" ,
158+ assignment. path. display( )
159+ )
160+ } ) ?;
161+ Ok ( ( ) )
162+ }
163+
164+ fn restore_assignments ( assignments : & [ ScopedAssignment ] ) -> Result < ( ) , String > {
165+ let mut failures = Vec :: new ( ) ;
166+ for assignment in assignments {
167+ let result = open_retention_db ( & assignment. path ) . and_then ( |mut conn| {
168+ replace_assignment ( & mut conn, & assignment. agent_pubkey ) . map ( |_| ( ) )
169+ } ) ;
170+ if let Err ( error) = result {
171+ failures. push ( format ! ( "{}: {error}" , assignment. path. display( ) ) ) ;
172+ }
173+ }
174+ if failures. is_empty ( ) {
175+ Ok ( ( ) )
176+ } else {
177+ Err ( format ! (
178+ "failed to restore bestie assignments: {}" ,
179+ failures. join( "; " )
180+ ) )
181+ }
182+ }
183+
184+ fn clear_scoped_assignments (
185+ assignments : & [ ScopedAssignment ] ,
186+ mut clear : impl FnMut ( & ScopedAssignment ) -> Result < ( ) , String > ,
187+ ) -> Result < ( ) , String > {
188+ let mut cleared = Vec :: new ( ) ;
189+ for assignment in assignments {
190+ if let Err ( error) = clear ( assignment) {
191+ return match restore_assignments ( & cleared) {
192+ Ok ( ( ) ) => Err ( error) ,
193+ Err ( restore_error) => Err ( format ! ( "{error}; {restore_error}" ) ) ,
194+ } ;
195+ }
196+ cleared. push ( assignment. clone ( ) ) ;
197+ }
198+ Ok ( ( ) )
199+ }
200+
201+ /// Run agent deletion work with this agent's community-scoped Bestie
202+ /// assignments temporarily cleared.
203+ ///
204+ /// Call this while holding `managed_agents_store_lock`. Every matching scope is
205+ /// snapshotted before the first write. A partial clear, or any later stop/save
206+ /// failure returned by `delete`, restores the snapshot before the error is
207+ /// propagated. Assignments remain cleared only when `delete` succeeds.
208+ pub fn with_agent_assignments_cleared < T > (
209+ base_dir : & Path ,
210+ agent_pubkey : & str ,
211+ delete : impl FnOnce ( ) -> Result < T , String > ,
212+ ) -> Result < T , String > {
213+ let assignments = matching_assignments ( base_dir, agent_pubkey) ?;
214+ clear_scoped_assignments ( & assignments, clear_scope) ?;
215+ match delete ( ) {
216+ Ok ( value) => Ok ( value) ,
217+ Err ( error) => match restore_assignments ( & assignments) {
218+ Ok ( ( ) ) => Err ( error) ,
219+ Err ( restore_error) => Err ( format ! ( "{error}; {restore_error}" ) ) ,
220+ } ,
131221 }
132- Ok ( cleared)
133222}
134223
135224#[ cfg( test) ]
@@ -203,11 +292,8 @@ mod tests {
203292 )
204293 . unwrap_or_else ( |error| panic ! ( "assign third scope: {error}" ) ) ;
205294
206- assert_eq ! (
207- clear_agent_assignments( dir. path( ) , & agent)
208- . unwrap_or_else( |error| panic!( "clear agent assignments: {error}" ) ) ,
209- 2
210- ) ;
295+ with_agent_assignments_cleared ( dir. path ( ) , & agent, || Ok ( ( ) ) )
296+ . unwrap_or_else ( |error| panic ! ( "clear agent assignments: {error}" ) ) ;
211297 assert_eq ! (
212298 get_assignment(
213299 & open_retention_db( & first_path)
@@ -226,4 +312,74 @@ mod tests {
226312 Some ( other)
227313 ) ;
228314 }
315+
316+ #[ test]
317+ fn later_scope_clear_failure_restores_the_already_cleared_prefix ( ) {
318+ let dir = tempfile:: tempdir ( ) . unwrap_or_else ( |error| panic ! ( "temp dir: {error}" ) ) ;
319+ let retention_dir = dir. path ( ) . join ( "retention" ) ;
320+ fs:: create_dir_all ( & retention_dir)
321+ . unwrap_or_else ( |error| panic ! ( "create retention dir: {error}" ) ) ;
322+ let agent = "a" . repeat ( 64 ) ;
323+ for name in [ "first.db" , "second.db" ] {
324+ replace_assignment (
325+ & mut open_retention_db ( & retention_dir. join ( name) )
326+ . unwrap_or_else ( |error| panic ! ( "open {name}: {error}" ) ) ,
327+ & agent,
328+ )
329+ . unwrap_or_else ( |error| panic ! ( "assign {name}: {error}" ) ) ;
330+ }
331+
332+ let assignments = matching_assignments ( dir. path ( ) , & agent)
333+ . unwrap_or_else ( |error| panic ! ( "snapshot assignments: {error}" ) ) ;
334+ let result = clear_scoped_assignments ( & assignments, |assignment| {
335+ if assignment. path . ends_with ( "second.db" ) {
336+ Err ( "injected later retention DB failure" . to_string ( ) )
337+ } else {
338+ clear_scope ( assignment)
339+ }
340+ } ) ;
341+
342+ assert ! ( result. is_err( ) ) ;
343+ for name in [ "first.db" , "second.db" ] {
344+ let conn = open_retention_db ( & retention_dir. join ( name) )
345+ . unwrap_or_else ( |error| panic ! ( "reopen {name}: {error}" ) ) ;
346+ assert ! ( assignment_matches( & conn, & agent)
347+ . unwrap_or_else( |error| panic!( "read {name}: {error}" ) ) ) ;
348+ }
349+ }
350+
351+ fn assert_later_deletion_failure_restores_assignment ( failure : & str ) {
352+ let dir = tempfile:: tempdir ( ) . unwrap_or_else ( |error| panic ! ( "temp dir: {error}" ) ) ;
353+ let retention_dir = dir. path ( ) . join ( "retention" ) ;
354+ fs:: create_dir_all ( & retention_dir)
355+ . unwrap_or_else ( |error| panic ! ( "create retention dir: {error}" ) ) ;
356+ let path = retention_dir. join ( "owner.db" ) ;
357+ let agent = "a" . repeat ( 64 ) ;
358+ replace_assignment (
359+ & mut open_retention_db ( & path)
360+ . unwrap_or_else ( |error| panic ! ( "open assignment db: {error}" ) ) ,
361+ & agent,
362+ )
363+ . unwrap_or_else ( |error| panic ! ( "assign agent: {error}" ) ) ;
364+
365+ let result = with_agent_assignments_cleared ( dir. path ( ) , & agent, || {
366+ Err :: < ( ) , _ > ( failure. to_string ( ) )
367+ } ) ;
368+
369+ assert_eq ! ( result, Err ( failure. to_string( ) ) ) ;
370+ let conn = open_retention_db ( & path)
371+ . unwrap_or_else ( |error| panic ! ( "reopen assignment db: {error}" ) ) ;
372+ assert ! ( assignment_matches( & conn, & agent)
373+ . unwrap_or_else( |error| panic!( "read restored assignment: {error}" ) ) ) ;
374+ }
375+
376+ #[ test]
377+ fn stop_failure_after_cleanup_restores_assignment ( ) {
378+ assert_later_deletion_failure_restores_assignment ( "injected stop failure" ) ;
379+ }
380+
381+ #[ test]
382+ fn save_failure_after_cleanup_restores_assignment ( ) {
383+ assert_later_deletion_failure_restores_assignment ( "injected save failure" ) ;
384+ }
229385}
0 commit comments