Skip to content

Database file locking — prevent concurrent access (#155) - #160

Merged
nockawa merged 1 commit into
mainfrom
feature/155-database-file-locking
Mar 12, 2026
Merged

nockawa merged 1 commit into
mainfrom
feature/155-database-file-locking

Conversation

@nockawa

@nockawa nockawa commented Mar 12, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • OS-level FileShare.Read: Changed from FileShare.None to FileShare.Read in PagedMMF.CreateFile() and LoadFile(). Backup tools can read while database is open; concurrent writers get IOException from the OS kernel.
  • Advisory .lock file: JSON lock file (pid, startedAt, machineName) created on database open, deleted on close. Provides clear error messages and handles stale-lock-after-crash via PID liveness check. Cross-machine locks (different machineName) are treated as live (conservative).
  • DatabaseLockedException: New StorageException subclass (error code DatabaseLocked = 2007) that propagates unwrapped for clear diagnostics.
  • Windows NTFS pending-delete: DeleteFileAndWait polls after File.Delete until the directory entry is actually removed, preventing IOException on subsequent WriteAllText to the same path.

Changed Files (6 files, +530 / -42)

  • PagedMMF.cs — FileShare.Read, lock file acquire/release, DeleteFileAndWait, DatabaseLockedException passthrough in constructor
  • PagedMMFOptions.cs — EnsureFileDeleted also removes .lock file, DeleteAndWait for NTFS
  • DatabaseLockedException.cs — New exception with PID, machine name, timestamp
  • TyphonErrorCode.cs — DatabaseLocked = 2007
  • ThrowHelper.cs — ThrowDatabaseLocked(...)
  • DatabaseFileLockingTests.cs — 8 tests (lock create/delete, stale PID, live PID, cross-machine, corrupt, FileShare read/write, EnsureDeleted)

Test Plan

  • Lock file created on open, deleted on close
  • Stale lock (dead PID) detected and cleaned up
  • Live lock (current process PID) throws DatabaseLockedException
  • Cross-machine lock throws (cannot verify remote PID)
  • Corrupt lock file removed gracefully
  • FileShare.Read allows read-only access by other processes
  • FileShare.Read prevents concurrent write access
  • EnsureFileDeleted removes both .bin and .lock files

Closes #155

@nockawa
nockawa merged commit 7b3112b into main Mar 12, 2026
5 checks passed
@nockawa
nockawa deleted the feature/155-database-file-locking branch March 12, 2026 08:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Database file locking — prevent concurrent access corruption

1 participant