1010//! stored — they stay ephemeral.
1111
1212use std:: collections:: HashMap ;
13- use std:: fs;
13+ use std:: ffi:: OsString ;
14+ use std:: fs:: { self , File , OpenOptions } ;
1415use std:: path:: { Path , PathBuf } ;
15- use std:: sync:: Mutex ;
1616
17+ use fs2:: FileExt ;
1718use serde:: { Deserialize , Serialize } ;
1819use uuid:: Uuid ;
1920
@@ -33,17 +34,14 @@ struct StoreFile {
3334/// Process-wide durable session binding store.
3435pub struct SessionStore {
3536 path : PathBuf ,
36- inner : Mutex < StoreFile > ,
37+ lock_path : PathBuf ,
3738}
3839
3940impl SessionStore {
4041 /// Open or create the store at the resolved path.
4142 pub fn open ( path : PathBuf ) -> Self {
42- let data = load_store ( & path) ;
43- Self {
44- path,
45- inner : Mutex :: new ( data) ,
46- }
43+ let lock_path = sibling_lock_path ( & path) ;
44+ Self { path, lock_path }
4745 }
4846
4947 /// Resolve the default store path for this agent identity.
@@ -70,10 +68,15 @@ impl SessionStore {
7068 channel_id : & Uuid ,
7169 ) -> Option < String > {
7270 let key = binding_key ( agent_command, agent_args, channel_id) ;
73- self . inner
74- . lock ( )
75- . ok ( )
76- . and_then ( |guard| guard. sessions . get ( & key) . cloned ( ) )
71+ let lock = self . acquire_lock ( false ) ?;
72+ let result = load_store ( & self . path )
73+ . map ( |data| data. sessions . get ( & key) . cloned ( ) )
74+ . unwrap_or_else ( |e| {
75+ self . warn_io ( "failed to read ACP session bindings" , & e) ;
76+ None
77+ } ) ;
78+ self . release_lock ( & lock) ;
79+ result
7780 }
7881
7982 /// Persist a channel → session binding.
@@ -85,38 +88,94 @@ impl SessionStore {
8588 session_id : & str ,
8689 ) {
8790 let key = binding_key ( agent_command, agent_args, channel_id) ;
88- let Ok ( mut guard ) = self . inner . lock ( ) else {
91+ let Some ( lock ) = self . acquire_lock ( true ) else {
8992 return ;
9093 } ;
91- guard . version = 1 ;
92- guard . sessions . insert ( key , session_id . to_owned ( ) ) ;
93- if let Err ( e ) = save_store ( & self . path , & guard ) {
94- tracing :: warn! (
95- target : "session_store" ,
96- path = % self . path . display ( ) ,
97- error = %e ,
98- "failed to persist ACP session binding"
99- ) ;
94+ match load_store ( & self . path ) {
95+ Ok ( mut data ) => {
96+ data . version = 1 ;
97+ data . sessions . insert ( key , session_id . to_owned ( ) ) ;
98+ if let Err ( e ) = save_store ( & self . path , & data ) {
99+ self . warn_io ( "failed to persist ACP session binding" , & e ) ;
100+ }
101+ }
102+ Err ( e ) => self . warn_io ( "failed to read ACP session bindings before update" , & e ) ,
100103 }
104+ self . release_lock ( & lock) ;
101105 }
102106
103107 /// Remove a binding (after invalidation / failed load).
104108 pub fn remove ( & self , agent_command : & str , agent_args : & [ String ] , channel_id : & Uuid ) {
105109 let key = binding_key ( agent_command, agent_args, channel_id) ;
106- let Ok ( mut guard ) = self . inner . lock ( ) else {
110+ let Some ( lock ) = self . acquire_lock ( true ) else {
107111 return ;
108112 } ;
109- if guard. sessions . remove ( & key) . is_some ( ) {
110- if let Err ( e) = save_store ( & self . path , & guard) {
111- tracing:: warn!(
112- target: "session_store" ,
113- path = %self . path. display( ) ,
114- error = %e,
115- "failed to persist ACP session binding removal"
116- ) ;
113+ match load_store ( & self . path ) {
114+ Ok ( mut data) => {
115+ if data. sessions . remove ( & key) . is_some ( ) {
116+ if let Err ( e) = save_store ( & self . path , & data) {
117+ self . warn_io ( "failed to persist ACP session binding removal" , & e) ;
118+ }
119+ }
120+ }
121+ Err ( e) => self . warn_io ( "failed to read ACP session bindings before removal" , & e) ,
122+ }
123+ self . release_lock ( & lock) ;
124+ }
125+
126+ fn acquire_lock ( & self , exclusive : bool ) -> Option < File > {
127+ if let Some ( parent) = self . lock_path . parent ( ) {
128+ if let Err ( e) = fs:: create_dir_all ( parent) {
129+ self . warn_io ( "failed to create ACP session store directory" , & e) ;
130+ return None ;
117131 }
118132 }
133+ let lock = match OpenOptions :: new ( )
134+ . read ( true )
135+ . write ( true )
136+ . create ( true )
137+ . truncate ( false )
138+ . open ( & self . lock_path )
139+ {
140+ Ok ( lock) => lock,
141+ Err ( e) => {
142+ self . warn_io ( "failed to open ACP session store lock" , & e) ;
143+ return None ;
144+ }
145+ } ;
146+ let result = if exclusive {
147+ FileExt :: lock_exclusive ( & lock)
148+ } else {
149+ FileExt :: lock_shared ( & lock)
150+ } ;
151+ if let Err ( e) = result {
152+ self . warn_io ( "failed to lock ACP session store" , & e) ;
153+ return None ;
154+ }
155+ Some ( lock)
156+ }
157+
158+ fn release_lock ( & self , lock : & File ) {
159+ if let Err ( e) = FileExt :: unlock ( lock) {
160+ self . warn_io ( "failed to unlock ACP session store" , & e) ;
161+ }
119162 }
163+
164+ fn warn_io ( & self , message : & ' static str , error : & std:: io:: Error ) {
165+ tracing:: warn!(
166+ target: "session_store" ,
167+ path = %self . path. display( ) ,
168+ lock_path = %self . lock_path. display( ) ,
169+ error = %error,
170+ "{message}"
171+ ) ;
172+ }
173+ }
174+
175+ fn sibling_lock_path ( path : & Path ) -> PathBuf {
176+ let mut name = path. as_os_str ( ) . to_owned ( ) ;
177+ name. push ( OsString :: from ( ".lock" ) ) ;
178+ PathBuf :: from ( name)
120179}
121180
122181fn store_identity ( agent_command : & str , agent_args : & [ String ] ) -> String {
@@ -152,30 +211,12 @@ fn binding_key(agent_command: &str, agent_args: &[String], channel_id: &Uuid) ->
152211 )
153212}
154213
155- fn load_store ( path : & Path ) -> StoreFile {
214+ fn load_store ( path : & Path ) -> std :: io :: Result < StoreFile > {
156215 match fs:: read_to_string ( path) {
157- Ok ( text) => match serde_json:: from_str ( & text) {
158- Ok ( data) => data,
159- Err ( e) => {
160- tracing:: warn!(
161- target: "session_store" ,
162- path = %path. display( ) ,
163- error = %e,
164- "corrupt session store — starting empty"
165- ) ;
166- StoreFile :: default ( )
167- }
168- } ,
169- Err ( e) if e. kind ( ) == std:: io:: ErrorKind :: NotFound => StoreFile :: default ( ) ,
170- Err ( e) => {
171- tracing:: warn!(
172- target: "session_store" ,
173- path = %path. display( ) ,
174- error = %e,
175- "could not read session store — starting empty"
176- ) ;
177- StoreFile :: default ( )
178- }
216+ Ok ( text) => serde_json:: from_str ( & text)
217+ . map_err ( |e| std:: io:: Error :: new ( std:: io:: ErrorKind :: InvalidData , e) ) ,
218+ Err ( e) if e. kind ( ) == std:: io:: ErrorKind :: NotFound => Ok ( StoreFile :: default ( ) ) ,
219+ Err ( e) => Err ( e) ,
179220 }
180221}
181222
@@ -245,4 +286,47 @@ mod tests {
245286 Some ( "b" )
246287 ) ;
247288 }
289+
290+ #[ test]
291+ fn independently_opened_stores_do_not_lose_updates ( ) {
292+ let dir = tempdir ( ) . unwrap ( ) ;
293+ let path = dir. path ( ) . join ( "sessions.json" ) ;
294+ let store_a = SessionStore :: open ( path. clone ( ) ) ;
295+ let store_b = SessionStore :: open ( path. clone ( ) ) ;
296+ let channel_a = Uuid :: new_v4 ( ) ;
297+ let channel_b = Uuid :: new_v4 ( ) ;
298+ let channel_c = Uuid :: new_v4 ( ) ;
299+ let args = [ "acp" . into ( ) ] ;
300+
301+ store_a. put ( "hermes" , & args, & channel_a, "session-a" ) ;
302+ store_b. put ( "hermes" , & args, & channel_b, "session-b" ) ;
303+
304+ let reopened = SessionStore :: open ( path. clone ( ) ) ;
305+ assert_eq ! (
306+ reopened. get( "hermes" , & args, & channel_a) . as_deref( ) ,
307+ Some ( "session-a" )
308+ ) ;
309+ assert_eq ! (
310+ reopened. get( "hermes" , & args, & channel_b) . as_deref( ) ,
311+ Some ( "session-b" )
312+ ) ;
313+
314+ // Open both before either mutation. A stale process-local snapshot would
315+ // resurrect channel A when the second store writes channel C.
316+ let remover = SessionStore :: open ( path. clone ( ) ) ;
317+ let writer = SessionStore :: open ( path. clone ( ) ) ;
318+ remover. remove ( "hermes" , & args, & channel_a) ;
319+ writer. put ( "hermes" , & args, & channel_c, "session-c" ) ;
320+
321+ let final_store = SessionStore :: open ( path) ;
322+ assert ! ( final_store. get( "hermes" , & args, & channel_a) . is_none( ) ) ;
323+ assert_eq ! (
324+ final_store. get( "hermes" , & args, & channel_b) . as_deref( ) ,
325+ Some ( "session-b" )
326+ ) ;
327+ assert_eq ! (
328+ final_store. get( "hermes" , & args, & channel_c) . as_deref( ) ,
329+ Some ( "session-c" )
330+ ) ;
331+ }
248332}
0 commit comments