Skip to main content

merry_runtime/
session_store.rs

1use merry_core::SessionId;
2use std::{
3    env,
4    ffi::OsStr,
5    fs::{File, OpenOptions as StdOpenOptions},
6    path::{Path, PathBuf},
7    sync::Arc,
8};
9use thiserror::Error;
10use tokio::{fs::OpenOptions, io::AsyncWriteExt, sync::Mutex};
11
12#[cfg(unix)]
13use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
14
15const JOURNAL_FILE_NAME: &str = "journal.jsonl";
16
17const LEGACY_STATE_FILE_NAME: &str = "state.json";
18
19const SESSION_LOCK_FILE_NAME: &str = ".session.lock";
20
21const PLANS_DIR_NAME: &str = "plans";
22
23#[cfg(test)]
24use std::sync::atomic::{AtomicBool, Ordering};
25
26#[cfg(test)]
27use tokio::sync::Notify;
28
29#[derive(Debug, Error)]
30pub enum SessionStoreError {
31    #[error("could not resolve XDG state home: neither XDG_STATE_HOME nor HOME is set")]
32    StateHomeUnavailable,
33    #[error("session store path {path} is invalid: {reason}")]
34    InvalidPath { path: PathBuf, reason: &'static str },
35    #[error("session store IO error at {path}: {source}")]
36    Io {
37        path: PathBuf,
38        #[source]
39        source: std::io::Error,
40    },
41    #[error("session state JSON error: {source}")]
42    Json {
43        #[from]
44        source: serde_json::Error,
45    },
46    #[error("session document format version {actual} is not supported")]
47    UnsupportedFormatVersion { actual: u32 },
48    #[error("session document id {actual} does not match requested session {requested}")]
49    SessionIdMismatch {
50        requested: SessionId,
51        actual: SessionId,
52    },
53    #[error("session {session_id} is already reserved by another run")]
54    SessionAlreadyReserved { session_id: SessionId },
55    #[error(
56        "session {session_id} has {pending_count} pending tool calls and cannot be saved at an incomplete tool boundary"
57    )]
58    UnsafePendingToolCalls {
59        session_id: SessionId,
60        pending_count: usize,
61    },
62    #[error("session document is invalid: {reason}")]
63    InvalidDocument { reason: &'static str },
64}
65
66/// File-backed session storage. Durable session facts append directly to `journal.jsonl`.
67///
68/// Store clones share an in-process append lock so runtime savepoints,
69/// compaction, and plan updates cannot interleave bytes or write duplicate
70/// headers. Callers that create or resume a live run should also hold a
71/// [`SessionReservation`] for cross-process exclusion.
72#[derive(Debug, Clone)]
73pub struct FileSessionStore {
74    sessions_dir: PathBuf,
75    write_lock: Arc<Mutex<()>>,
76    #[cfg(test)]
77    stage_pause: Option<SessionStoreStagePause>,
78    #[cfg(test)]
79    commit_pause: Option<SessionStoreCommitPause>,
80    #[cfg(test)]
81    fail_commit: bool,
82    #[cfg(test)]
83    fail_directory_sync: bool,
84}
85
86/// Exclusive ownership of one session's on-disk state for the lifetime of a
87/// run. The operating-system file lock is released when this value is dropped,
88/// including when the owning process is terminated.
89#[derive(Debug)]
90pub struct SessionReservation {
91    _lock_file: File,
92}
93
94/// Prepared in-memory journal append awaiting final transactional commit.
95///
96/// No temporary file is written for append-only commits: discarding simply
97/// drops the prepared bytes, while committing appends directly to
98/// `journal.jsonl` under the store's write lock and fsyncs once.
99#[derive(Debug)]
100pub(crate) struct StagedSessionBundle {
101    final_path: PathBuf,
102    header_bytes: Vec<u8>,
103    commit_bytes: Vec<u8>,
104    write_lock: Arc<Mutex<()>>,
105    search: Option<search::SessionSearchUpdate>,
106    rotation: Option<crate::session::PreparedJournalRotation>,
107    #[cfg(test)]
108    commit_pause: Option<SessionStoreCommitPause>,
109    #[cfg(test)]
110    fail_commit: bool,
111    #[cfg(test)]
112    fail_directory_sync: bool,
113}
114
115#[derive(Debug)]
116#[must_use = "an appended session commit must be checked for directory durability"]
117pub(crate) enum StagedSessionCommit {
118    Durable,
119    AppendedButNotSynced(SessionStoreError),
120}
121
122impl StagedSessionCommit {
123    pub(crate) fn require_durable(self) -> Result<(), SessionStoreError> {
124        match self {
125            Self::Durable => Ok(()),
126            Self::AppendedButNotSynced(error) => Err(error),
127        }
128    }
129}
130
131impl StagedSessionBundle {
132    pub(crate) async fn commit(self) -> Result<StagedSessionCommit, SessionStoreError> {
133        #[cfg(test)]
134        if self.fail_commit {
135            return Err(io_error(
136                self.final_path,
137                std::io::Error::other("injected session store commit failure"),
138            ));
139        }
140
141        let created = {
142            let _guard = self.write_lock.lock().await;
143            if let Some(rotation) = self.rotation {
144                crate::session::commit_journal_rotation(
145                    &self.final_path,
146                    &self.header_bytes,
147                    &self.commit_bytes,
148                    rotation,
149                )
150                .await?;
151                true
152            } else {
153                append_journal_bytes(&self.final_path, &self.header_bytes, &self.commit_bytes)
154                    .await?
155            }
156        };
157
158        #[cfg(test)]
159        if let Some(pause) = &self.commit_pause {
160            pause.pause_once().await;
161        }
162
163        if let Some(search) = self.search {
164            search::upsert_user_text(search).await;
165        }
166
167        #[cfg(test)]
168        if self.fail_directory_sync {
169            return Ok(StagedSessionCommit::AppendedButNotSynced(io_error(
170                self.final_path
171                    .parent()
172                    .unwrap_or(self.final_path.as_path())
173                    .to_path_buf(),
174                std::io::Error::other("injected session directory sync failure"),
175            )));
176        }
177
178        if created {
179            match sync_parent_directory(&self.final_path).await {
180                Ok(()) => Ok(StagedSessionCommit::Durable),
181                Err(error) => Ok(StagedSessionCommit::AppendedButNotSynced(error)),
182            }
183        } else {
184            Ok(StagedSessionCommit::Durable)
185        }
186    }
187
188    pub(crate) async fn discard(self) -> Result<(), SessionStoreError> {
189        Ok(())
190    }
191}
192
193#[cfg(test)]
194#[derive(Debug, Clone)]
195pub(crate) struct SessionStoreStagePause {
196    inner: Arc<SessionStoreStagePauseInner>,
197}
198
199#[cfg(test)]
200#[derive(Debug)]
201struct SessionStoreStagePauseInner {
202    claimed: AtomicBool,
203    staged: Notify,
204    resume: Notify,
205}
206
207#[cfg(test)]
208#[derive(Debug, Clone)]
209pub(crate) struct SessionStoreCommitPause {
210    inner: Arc<SessionStoreCommitPauseInner>,
211}
212
213#[cfg(test)]
214#[derive(Debug)]
215struct SessionStoreCommitPauseInner {
216    claimed: AtomicBool,
217    committed: Notify,
218    resume: Notify,
219}
220
221#[cfg(test)]
222impl SessionStoreStagePause {
223    pub(crate) fn new() -> Self {
224        Self {
225            inner: Arc::new(SessionStoreStagePauseInner {
226                claimed: AtomicBool::new(false),
227                staged: Notify::new(),
228                resume: Notify::new(),
229            }),
230        }
231    }
232
233    pub(crate) async fn wait_until_staged(&self) {
234        self.inner.staged.notified().await;
235    }
236
237    pub(crate) fn resume(&self) {
238        self.inner.resume.notify_one();
239    }
240
241    async fn pause_once(&self) {
242        if self.inner.claimed.swap(true, Ordering::AcqRel) {
243            return;
244        }
245        self.inner.staged.notify_one();
246        self.inner.resume.notified().await;
247    }
248}
249
250#[cfg(test)]
251impl SessionStoreCommitPause {
252    pub(crate) fn new() -> Self {
253        Self {
254            inner: Arc::new(SessionStoreCommitPauseInner {
255                claimed: AtomicBool::new(false),
256                committed: Notify::new(),
257                resume: Notify::new(),
258            }),
259        }
260    }
261
262    pub(crate) async fn wait_until_committed(&self) {
263        self.inner.committed.notified().await;
264    }
265
266    pub(crate) fn resume(&self) {
267        self.inner.resume.notify_one();
268    }
269
270    async fn pause_once(&self) {
271        if self.inner.claimed.swap(true, Ordering::AcqRel) {
272            return;
273        }
274        self.inner.committed.notify_one();
275        self.inner.resume.notified().await;
276    }
277}
278
279impl FileSessionStore {
280    pub fn default_sessions_dir() -> Result<PathBuf, SessionStoreError> {
281        let xdg_state_home = env::var_os("XDG_STATE_HOME");
282        if let Some(root) = non_empty_os_str(xdg_state_home.as_deref()) {
283            return Ok(PathBuf::from(root).join("merry").join("sessions"));
284        }
285        let local_appdata = env::var_os("LOCALAPPDATA").map(PathBuf::from);
286        if cfg!(windows)
287            && let Some(local) = local_appdata
288                .as_deref()
289                .filter(|path| !path.as_os_str().is_empty() && path.is_absolute())
290        {
291            return Ok(local.join("merry").join("sessions"));
292        }
293        let Some(home) = merry_core::host_paths::user_home_dir() else {
294            return Err(SessionStoreError::StateHomeUnavailable);
295        };
296        let state_base =
297            merry_core::host_paths::platform_state_base(&home, None, local_appdata.as_deref());
298        Ok(state_base.join("merry").join("sessions"))
299    }
300
301    pub fn default_store() -> Result<Self, SessionStoreError> {
302        Ok(Self::new(Self::default_sessions_dir()?))
303    }
304
305    /// Creates a store rooted at a directory.
306    ///
307    /// Each session is stored below `<root>/<session_id>/journal.jsonl`.
308    #[must_use]
309    pub fn new(root: impl AsRef<Path>) -> Self {
310        Self {
311            sessions_dir: root.as_ref().to_path_buf(),
312            write_lock: Arc::new(Mutex::new(())),
313            #[cfg(test)]
314            stage_pause: None,
315            #[cfg(test)]
316            commit_pause: None,
317            #[cfg(test)]
318            fail_commit: false,
319            #[cfg(test)]
320            fail_directory_sync: false,
321        }
322    }
323
324    #[must_use]
325    pub fn sessions_dir(&self) -> &Path {
326        &self.sessions_dir
327    }
328
329    /// Returns a child-scoped session store rooted at `<sessions_dir>/<parent_id>/subagents`.
330    ///
331    /// Storing child journals under a nested `subagents/` directory keeps them
332    /// durably paired with the parent session without polluting top-level
333    /// session discovery listings.
334    #[must_use]
335    pub fn subagents_store(&self, parent_session_id: &SessionId) -> Self {
336        Self::new(self.session_dir(parent_session_id).join("subagents"))
337    }
338
339    /// Synchronously reserves exclusive write ownership of a session id until
340    /// the returned guard is dropped.
341    ///
342    /// Uses a non-blocking OS file lock (`try_lock`), so this returns
343    /// [`SessionStoreError::SessionAlreadyReserved`] immediately when another
344    /// live handle already holds the lock.
345    pub fn try_reserve_session(
346        &self,
347        session_id: &SessionId,
348    ) -> Result<SessionReservation, SessionStoreError> {
349        let session_dir = self.session_dir(session_id);
350        std::fs::create_dir_all(&session_dir)
351            .map_err(|source| io_error(session_dir.clone(), source))?;
352        let lock_path = session_dir.join(SESSION_LOCK_FILE_NAME);
353        let mut options = StdOpenOptions::new();
354        options.read(true).write(true).create(true);
355        #[cfg(unix)]
356        options.mode(0o600);
357        let file = options
358            .open(&lock_path)
359            .map_err(|source| io_error(lock_path.clone(), source))?;
360        #[cfg(unix)]
361        file.set_permissions(std::fs::Permissions::from_mode(0o600))
362            .map_err(|source| io_error(lock_path.clone(), source))?;
363        match file.try_lock() {
364            Ok(()) => Ok(SessionReservation { _lock_file: file }),
365            Err(std::fs::TryLockError::WouldBlock) => {
366                Err(SessionStoreError::SessionAlreadyReserved {
367                    session_id: session_id.clone(),
368                })
369            }
370            Err(std::fs::TryLockError::Error(source)) => Err(io_error(lock_path, source)),
371        }
372    }
373
374    /// Reserves exclusive write ownership of a session id until the returned
375    /// guard is dropped.
376    ///
377    /// The lock is acquired before callers inspect or write `journal.jsonl`, so
378    /// independent runs cannot both pass a check-then-save collision window.
379    /// The lock file is intentionally retained as an empty per-session inode;
380    /// it is not session state and is ignored by session discovery.
381    pub async fn reserve_session(
382        &self,
383        session_id: &SessionId,
384    ) -> Result<SessionReservation, SessionStoreError> {
385        let store = self.clone();
386        let session_id = session_id.clone();
387        let lock_path = self.session_dir(&session_id).join(SESSION_LOCK_FILE_NAME);
388        tokio::task::spawn_blocking(move || store.try_reserve_session(&session_id))
389            .await
390            .map_err(|source| {
391                io_error(
392                    lock_path,
393                    std::io::Error::other(format!("session reservation task failed: {source}")),
394                )
395            })?
396    }
397
398    /// Releases a session reservation and removes its directory when it contains
399    /// no persisted files other than `.session.lock` (for example, when a newly
400    /// opened interactive session exits without recording any activity).
401    pub async fn release_empty_reservation(
402        &self,
403        session_id: &SessionId,
404        reservation: SessionReservation,
405    ) {
406        let session_dir = self.session_dir(session_id);
407        let mut has_other_entries = false;
408        match tokio::fs::read_dir(&session_dir).await {
409            Ok(mut entries) => {
410                while let Ok(Some(entry)) = entries.next_entry().await {
411                    if entry.file_name() != OsStr::new(SESSION_LOCK_FILE_NAME) {
412                        has_other_entries = true;
413                        break;
414                    }
415                }
416            }
417            Err(_) => {
418                drop(reservation);
419                return;
420            }
421        }
422        drop(reservation);
423        if has_other_entries {
424            return;
425        }
426        let _ = tokio::fs::remove_file(session_dir.join(SESSION_LOCK_FILE_NAME)).await;
427        let _ = tokio::fs::remove_dir(&session_dir).await;
428    }
429
430    /// Reports whether this store already holds committed state for a session id.
431    ///
432    /// Saving appends `journal.jsonl`, so a new run that reuses an id would
433    /// mix its transcript into an existing session. Callers that start a
434    /// session check this first and refuse the id. A legacy `state.json` still
435    /// occupies the id; those sessions are not resumed.
436    pub async fn contains_session(
437        &self,
438        session_id: &SessionId,
439    ) -> Result<bool, SessionStoreError> {
440        for name in [JOURNAL_FILE_NAME, LEGACY_STATE_FILE_NAME] {
441            let path = self.session_dir(session_id).join(name);
442            if tokio::fs::try_exists(&path)
443                .await
444                .map_err(|source| io_error(path.clone(), source))?
445            {
446                return Ok(true);
447            }
448        }
449        Ok(false)
450    }
451
452    /// Returns the directory containing durable state and archive files for `session_id`.
453    #[must_use]
454    pub fn session_dir(&self, session_id: &SessionId) -> PathBuf {
455        self.sessions_dir.join(session_id.as_str())
456    }
457
458    pub(crate) fn journal_path(&self, session_id: &SessionId) -> PathBuf {
459        self.session_dir(session_id).join(JOURNAL_FILE_NAME)
460    }
461
462    #[cfg(test)]
463    pub(crate) async fn overwrite_journal_bytes(
464        &self,
465        session_id: &SessionId,
466        bytes: &[u8],
467    ) -> Result<(), SessionStoreError> {
468        let session_dir = self.session_dir(session_id);
469        tokio::fs::create_dir_all(&session_dir)
470            .await
471            .map_err(|source| io_error(session_dir.clone(), source))?;
472        let path = self.journal_path(session_id);
473        let _guard = self.write_lock.lock().await;
474        tokio::fs::write(&path, bytes)
475            .await
476            .map_err(|source| io_error(path, source))
477    }
478
479    #[cfg(test)]
480    pub(crate) async fn write_state_bytes(
481        &self,
482        session_id: &SessionId,
483        bytes: &[u8],
484    ) -> Result<(), SessionStoreError> {
485        self.overwrite_journal_bytes(session_id, bytes).await
486    }
487
488    pub(crate) async fn stage_journal_append(
489        &self,
490        session_id: &SessionId,
491        header_bytes: Vec<u8>,
492        commit_bytes: Vec<u8>,
493        images: &[crate::session::JournalImageFile],
494        search_user_text: Option<String>,
495        rotation: Option<crate::session::PreparedJournalRotation>,
496    ) -> Result<StagedSessionBundle, SessionStoreError> {
497        let session_dir = self.session_dir(session_id);
498        tokio::fs::create_dir_all(&session_dir)
499            .await
500            .map_err(|source| io_error(session_dir.clone(), source))?;
501        self.write_journal_images(session_id, images).await?;
502        if let Some(rot) = rotation.as_ref() {
503            self.write_journal_images(session_id, &rot.archive_images)
504                .await?;
505        }
506
507        #[cfg(test)]
508        if let Some(pause) = &self.stage_pause {
509            pause.pause_once().await;
510        }
511
512        Ok(StagedSessionBundle {
513            final_path: session_dir.join(JOURNAL_FILE_NAME),
514            header_bytes,
515            commit_bytes,
516            write_lock: Arc::clone(&self.write_lock),
517            search: search_user_text.map(|user_text| search::SessionSearchUpdate {
518                sessions_dir: self.sessions_dir.clone(),
519                session_id: session_id.clone(),
520                user_text,
521            }),
522            rotation,
523            #[cfg(test)]
524            commit_pause: self.commit_pause.clone(),
525            #[cfg(test)]
526            fail_commit: self.fail_commit,
527            #[cfg(test)]
528            fail_directory_sync: self.fail_directory_sync,
529        })
530    }
531
532    async fn write_journal_images(
533        &self,
534        session_id: &SessionId,
535        images: &[crate::session::JournalImageFile],
536    ) -> Result<(), SessionStoreError> {
537        if images.is_empty() {
538            return Ok(());
539        }
540        let directory = self.session_dir(session_id).join("images");
541        tokio::fs::create_dir_all(&directory)
542            .await
543            .map_err(|source| io_error(directory.clone(), source))?;
544        for image in images {
545            if !crate::session::is_image_id(&image.id) {
546                return Err(SessionStoreError::InvalidDocument {
547                    reason: "session journal image id is invalid",
548                });
549            }
550            let path = directory.join(format!("{}.png", image.id));
551            let mut options = OpenOptions::new();
552            options.write(true).create_new(true);
553            #[cfg(unix)]
554            options.mode(0o600);
555            let mut file = match options.open(&path).await {
556                Ok(file) => file,
557                Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => continue,
558                Err(source) => return Err(io_error(path, source)),
559            };
560            file.write_all(&image.bytes)
561                .await
562                .map_err(|source| io_error(path.clone(), source))?;
563            file.sync_all()
564                .await
565                .map_err(|source| io_error(path, source))?;
566        }
567        Ok(())
568    }
569
570    pub(crate) async fn read_journal_bytes(
571        &self,
572        session_id: &SessionId,
573    ) -> Result<Vec<u8>, SessionStoreError> {
574        let path = self.journal_path(session_id);
575        tokio::fs::read(&path)
576            .await
577            .map_err(|source| io_error(path, source))
578    }
579
580    /// Truncates an incomplete trailing line after a crash so the next append
581    /// starts cleanly on a new line instead of gluing onto torn bytes.
582    pub(crate) async fn truncate_journal_tail(
583        &self,
584        session_id: &SessionId,
585        valid_len: u64,
586    ) -> Result<(), SessionStoreError> {
587        let path = self.journal_path(session_id);
588        let _guard = self.write_lock.lock().await;
589        let file = OpenOptions::new()
590            .write(true)
591            .open(&path)
592            .await
593            .map_err(|source| io_error(path.clone(), source))?;
594        let current_len = file
595            .metadata()
596            .await
597            .map_err(|source| io_error(path.clone(), source))?
598            .len();
599        if current_len > valid_len {
600            file.set_len(valid_len)
601                .await
602                .map_err(|source| io_error(path.clone(), source))?;
603            file.sync_all()
604                .await
605                .map_err(|source| io_error(path, source))?;
606        }
607        Ok(())
608    }
609
610    #[cfg(test)]
611    pub(crate) async fn read_state_bytes(
612        &self,
613        session_id: &SessionId,
614    ) -> Result<Vec<u8>, SessionStoreError> {
615        self.read_journal_bytes(session_id).await
616    }
617
618    /// Writes one named Markdown plan file under `<session_dir>/plans/<file_name>`.
619    pub(crate) async fn write_plan_file(
620        &self,
621        session_id: &SessionId,
622        file_name: &str,
623        content: &str,
624    ) -> Result<PathBuf, SessionStoreError> {
625        if crate::plan::validate_plan_file_name(file_name).is_err() {
626            return Err(SessionStoreError::InvalidDocument {
627                reason: "plan file name is invalid",
628            });
629        }
630        let directory = self.session_dir(session_id).join(PLANS_DIR_NAME);
631        tokio::fs::create_dir_all(&directory)
632            .await
633            .map_err(|source| io_error(directory.clone(), source))?;
634        let path = directory.join(file_name);
635        let tmp_path = directory.join(format!(".{file_name}.tmp"));
636        let mut options = OpenOptions::new();
637        options.write(true).create(true).truncate(true);
638        #[cfg(unix)]
639        options.mode(0o600);
640        let mut file = options
641            .open(&tmp_path)
642            .await
643            .map_err(|source| io_error(tmp_path.clone(), source))?;
644        file.write_all(content.as_bytes())
645            .await
646            .map_err(|source| io_error(tmp_path.clone(), source))?;
647        file.sync_all()
648            .await
649            .map_err(|source| io_error(tmp_path.clone(), source))?;
650        drop(file);
651        tokio::fs::rename(&tmp_path, &path)
652            .await
653            .map_err(|source| io_error(path.clone(), source))?;
654        Ok(path)
655    }
656
657    /// Reads one named Markdown plan file from `<session_dir>/plans/<file_name>`.
658    pub(crate) async fn read_plan_file(
659        &self,
660        session_id: &SessionId,
661        file_name: &str,
662    ) -> Result<Option<String>, SessionStoreError> {
663        if crate::plan::validate_plan_file_name(file_name).is_err() {
664            return Ok(None);
665        }
666        let path = self
667            .session_dir(session_id)
668            .join(PLANS_DIR_NAME)
669            .join(file_name);
670        match tokio::fs::read_to_string(&path).await {
671            Ok(content) => Ok(Some(content)),
672            Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
673            Err(source) => Err(io_error(path, source)),
674        }
675    }
676
677    pub(crate) async fn read_legacy_bytes(
678        &self,
679        session_id: &SessionId,
680        file_name: &str,
681    ) -> Result<Option<Vec<u8>>, SessionStoreError> {
682        let path = self.session_dir(session_id).join(file_name);
683        match tokio::fs::read(&path).await {
684            Ok(bytes) => Ok(Some(bytes)),
685            Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
686            Err(source) => Err(io_error(path, source)),
687        }
688    }
689
690    #[cfg(test)]
691    pub(crate) fn with_stage_pause_for_tests(mut self, pause: SessionStoreStagePause) -> Self {
692        self.stage_pause = Some(pause);
693        self
694    }
695
696    #[cfg(test)]
697    pub(crate) fn with_commit_pause_for_tests(mut self, pause: SessionStoreCommitPause) -> Self {
698        self.commit_pause = Some(pause);
699        self
700    }
701
702    #[cfg(test)]
703    pub(crate) fn with_commit_failure_for_tests(mut self) -> Self {
704        self.fail_commit = true;
705        self
706    }
707
708    #[cfg(test)]
709    pub(crate) fn with_directory_sync_failure_for_tests(mut self) -> Self {
710        self.fail_directory_sync = true;
711        self
712    }
713}
714
715#[cfg(test)]
716pub(crate) fn sessions_dir_from_env(
717    xdg_state_home: Option<&OsStr>,
718    home: Option<&OsStr>,
719) -> Result<PathBuf, SessionStoreError> {
720    if let Some(root) = non_empty_os_str(xdg_state_home) {
721        return Ok(PathBuf::from(root).join("merry").join("sessions"));
722    }
723
724    if let Some(root) = non_empty_os_str(home) {
725        return Ok(PathBuf::from(root).join(".local/state/merry/sessions"));
726    }
727
728    Err(SessionStoreError::StateHomeUnavailable)
729}
730
731fn non_empty_os_str(value: Option<&OsStr>) -> Option<&OsStr> {
732    value.filter(|value| !value.is_empty())
733}
734
735/// Appends one commit directly to `journal.jsonl`, prepending the header line
736/// atomically when the file is empty. Returns `true` when the journal started
737/// empty so the caller can sync the parent directory once.
738async fn append_journal_bytes(
739    final_path: &Path,
740    header_bytes: &[u8],
741    commit_bytes: &[u8],
742) -> Result<bool, SessionStoreError> {
743    let mut options = OpenOptions::new();
744    options.create(true).append(true);
745    #[cfg(unix)]
746    options.mode(0o600);
747    let mut file = options
748        .open(final_path)
749        .await
750        .map_err(|source| io_error(final_path.to_path_buf(), source))?;
751    let empty = file
752        .metadata()
753        .await
754        .map_err(|source| io_error(final_path.to_path_buf(), source))?
755        .len()
756        == 0;
757    if empty && !header_bytes.is_empty() {
758        file.write_all(header_bytes)
759            .await
760            .map_err(|source| io_error(final_path.to_path_buf(), source))?;
761    }
762    if !commit_bytes.is_empty() {
763        file.write_all(commit_bytes)
764            .await
765            .map_err(|source| io_error(final_path.to_path_buf(), source))?;
766    }
767    file.sync_all()
768        .await
769        .map_err(|source| io_error(final_path.to_path_buf(), source))?;
770    Ok(empty)
771}
772
773#[cfg(unix)]
774async fn sync_parent_directory(path: &Path) -> Result<(), SessionStoreError> {
775    let parent = path
776        .parent()
777        .ok_or_else(|| SessionStoreError::InvalidPath {
778            path: path.to_path_buf(),
779            reason: "session state path has no parent directory",
780        })?;
781    let directory = tokio::fs::File::open(parent)
782        .await
783        .map_err(|source| io_error(parent.to_path_buf(), source))?;
784    directory
785        .sync_all()
786        .await
787        .map_err(|source| io_error(parent.to_path_buf(), source))
788}
789
790#[cfg(not(unix))]
791async fn sync_parent_directory(_path: &Path) -> Result<(), SessionStoreError> {
792    Ok(())
793}
794
795fn io_error(path: PathBuf, source: std::io::Error) -> SessionStoreError {
796    SessionStoreError::Io { path, source }
797}
798
799mod search;
800
801#[cfg(test)]
802mod tests;