Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -413,8 +413,8 @@ storage = LocalFileSystemStorage("/var/lib/myapp/queue.json")
# accepts str or pathlib.Path; parent directories are created automatically
```

Uses `fcntl.flock` for POSIX exclusive locking. The etag is a SHA-256 hex digest of
the file content.
Uses `fcntl.flock` on a sidecar `<path>.lock` for POSIX exclusive locking, and writes
via temp file + atomic rename. The etag is a SHA-256 hex digest of the file content.
**POSIX-only** (Linux, macOS). Not safe across machines or on NFS.

### S3Storage
Expand Down
68 changes: 45 additions & 23 deletions jqueue/adapters/storage/filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,27 @@
deterministic, and always changes when content changes — unlike mtime which
can be identical across rapid successive writes on fast machines.
A file that is absent or empty is treated as non-existent; its etag is None.
The jqueue codec always produces non-empty JSON, so a 0-byte file only occurs
transiently before the first write completes.
The jqueue codec always produces non-empty JSON.

CAS semantics
-------------
write(content, if_match) acquires an exclusive flock, re-reads the current
etag while holding the lock, and raises CASConflictError if it differs from
if_match. The write is performed atomically within the same lock scope.
write(content, if_match) takes an exclusive flock on ``<path>.lock``,
re-checks the etag, then writes a temp file, fsyncs it and os.replace()s it
over ``path``. A failed write leaves the old state intact, and readers never
see a partial file.

POSIX-only (Linux, macOS). Not compatible with NFS or distributed filesystems.
"""

from __future__ import annotations

import asyncio
import contextlib
import dataclasses
import fcntl
import hashlib
import os
import tempfile
from pathlib import Path

from jqueue.domain.errors import CASConflictError
Expand Down Expand Up @@ -72,37 +74,57 @@ async def write(
def _etag(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()

@property
def _lock_path(self) -> Path:
return self.path.with_name(self.path.name + ".lock")

def _sync_read(self) -> tuple[bytes, str | None]:
if not self.path.exists():
try:
content = self.path.read_bytes()
except FileNotFoundError:
return b"", None
with open(self.path, "rb") as fh:
fcntl.flock(fh, fcntl.LOCK_SH)
try:
content = fh.read()
finally:
fcntl.flock(fh, fcntl.LOCK_UN)
etag: str | None = self._etag(content) if content else None
return content, etag

def _sync_write(self, content: bytes, if_match: str | None) -> str:
self.path.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(str(self.path), os.O_RDWR | os.O_CREAT, 0o644)
directory = self.path.parent
directory.mkdir(parents=True, exist_ok=True)
lock_fd = os.open(str(self._lock_path), os.O_RDWR | os.O_CREAT, 0o644)
try:
fcntl.flock(fd, fcntl.LOCK_EX)

existing = os.read(fd, os.fstat(fd).st_size)
real_etag: str | None = self._etag(existing) if existing else None
fcntl.flock(lock_fd, fcntl.LOCK_EX)

_, real_etag = self._sync_read()
if real_etag != if_match:
raise CASConflictError(
f"ETag mismatch: expected {if_match!r}, got {real_etag!r}"
)

os.ftruncate(fd, 0)
os.lseek(fd, 0, os.SEEK_SET)
os.write(fd, content)
fd, tmp_name = tempfile.mkstemp(
dir=directory, prefix=f".{self.path.name}.", suffix=".tmp"
)
try:
with os.fdopen(fd, "wb") as fh:
fh.write(content)
fh.flush()
os.fsync(fh.fileno())
os.chmod(tmp_name, 0o644)
os.replace(tmp_name, self.path)
except BaseException:
with contextlib.suppress(FileNotFoundError):
os.unlink(tmp_name)
raise
_fsync_dir(directory)
finally:
fcntl.flock(fd, fcntl.LOCK_UN)
os.close(fd)
fcntl.flock(lock_fd, fcntl.LOCK_UN)
os.close(lock_fd)

return self._etag(content)


def _fsync_dir(directory: Path) -> None:
"""Persist a rename by fsyncing its directory."""
dir_fd = os.open(str(directory), os.O_RDONLY)
try:
os.fsync(dir_fd)
finally:
os.close(dir_fd)
95 changes: 95 additions & 0 deletions tests/test_storage_filesystem.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import asyncio
import os
import resource
import signal
import stat
from pathlib import Path

import pytest

from jqueue.adapters.storage.filesystem import LocalFileSystemStorage
Expand Down Expand Up @@ -98,3 +105,91 @@ async def test_path_accepts_string(tmp_path):
await storage.write(b"data", if_match=None)
content, _ = await storage.read()
assert content == b"data"


# ---------------------------------------------------------------------------
# Crash safety: a failed write never leaves a partial file
# ---------------------------------------------------------------------------


def _leftovers(tmp_path: Path) -> list[str]:
return sorted(p.name for p in tmp_path.iterdir() if p.name.endswith(".tmp"))


async def test_short_write_leaves_previous_content_intact(tmp_path):
path = tmp_path / "state.json"
storage = LocalFileSystemStorage(path)
old = b'{"version": 1, "jobs": []}'
etag = await storage.write(old)
new = b"x" * 4096

soft, hard = resource.getrlimit(resource.RLIMIT_FSIZE)
previous = signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
resource.setrlimit(resource.RLIMIT_FSIZE, (1024, hard))
try:
try:
await storage.write(new, if_match=etag)
except OSError:
pass
finally:
resource.setrlimit(resource.RLIMIT_FSIZE, (soft, hard))
signal.signal(signal.SIGXFSZ, previous)

assert path.read_bytes() in (old, new)
assert _leftovers(tmp_path) == []


async def test_failed_fsync_keeps_old_content_and_cleans_up(tmp_path, monkeypatch):
path = tmp_path / "state.json"
storage = LocalFileSystemStorage(path)
etag = await storage.write(b"old")

def boom(fd):
raise OSError("EIO")

monkeypatch.setattr(os, "fsync", boom)
with pytest.raises(OSError, match="EIO"):
await storage.write(b"new", if_match=etag)
monkeypatch.undo()

assert path.read_bytes() == b"old"
assert _leftovers(tmp_path) == []
content, still = await storage.read()
assert (content, still) == (b"old", etag)


async def test_successful_write_leaves_no_temp_files(tmp_path):
path = tmp_path / "state.json"
storage = LocalFileSystemStorage(path)
etag = await storage.write(b"one")
await storage.write(b"two", if_match=etag)

assert path.read_bytes() == b"two"
assert _leftovers(tmp_path) == []
assert stat.S_IMODE(path.stat().st_mode) == 0o644


async def test_failed_cas_leaves_no_temp_files(tmp_path):
storage = LocalFileSystemStorage(tmp_path / "state.json")
await storage.write(b"one")
with pytest.raises(CASConflictError):
await storage.write(b"two", if_match="stale")
assert _leftovers(tmp_path) == []


async def test_concurrent_writers_same_etag_exactly_one_wins(tmp_path):
path = tmp_path / "state.json"
etag = await LocalFileSystemStorage(path).write(b"base")

async def attempt(i: int) -> bool:
try:
await LocalFileSystemStorage(path).write(f"w{i}".encode(), etag)
except CASConflictError:
return False
return True

results = await asyncio.gather(*(attempt(i) for i in range(16)))

assert results.count(True) == 1
winner = results.index(True)
assert path.read_bytes() == f"w{winner}".encode()
Loading