diff --git a/README.md b/README.md index 0bd1808..44cddaa 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,9 @@ with Client(fallback_provider=FileFallback("/var/lib/my-app/reflag")) as client: To store snapshots elsewhere, such as Redis or S3, implement `load` and `save`. Use `namespace` as the storage key, and store the snapshot unchanged. `AsyncClient` also -accepts providers with `async` methods. +accepts providers with `async` methods. The Redis example uses a Lua script to check the +stored `flagStateVersion` and write in one operation. The Redis user needs `EVAL`, `GET`, +and `SET` permissions for this provider. ```python import json @@ -162,7 +164,29 @@ class RedisFallback: return None if value is None else json.loads(value) def save(self, namespace: str, snapshot: Mapping[str, object]) -> None: - self._redis.set(f"reflag:flags-fallback:{namespace}", json.dumps(snapshot)) + version = snapshot.get("flagStateVersion") + self._redis.eval( + """ + local current = redis.call('GET', KEYS[1]) + if current then + local ok, snapshot = pcall(cjson.decode, current) + if ok and type(snapshot) == 'table' and snapshot.schemaVersion == 2 then + local version = snapshot.flagStateVersion + if type(version) == 'number' and version >= 0 + and version <= 9007199254740991 and version % 1 == 0 + and version > tonumber(ARGV[2]) then + return 0 + end + end + end + redis.call('SET', KEYS[1], ARGV[1]) + return 1 + """, + 1, + f"reflag:flags-fallback:{namespace}", + json.dumps(snapshot), + version if type(version) is int else -1, + ) ``` ## Testing diff --git a/src/reflag/fallback.py b/src/reflag/fallback.py index 08baefb..73bf849 100644 --- a/src/reflag/fallback.py +++ b/src/reflag/fallback.py @@ -1,16 +1,47 @@ """Opt-in startup fallback storage. Providers must not log or store credentials.""" +import errno import inspect import json import os import re +import sys import tempfile +import time from collections.abc import Mapping from datetime import UTC, datetime from pathlib import Path from typing import Protocol -from ._internal.compatibility import copy_json +from ._internal.compatibility import MAX_SAFE_INTEGER, copy_json + +if sys.platform == "win32": + import msvcrt +else: + import fcntl + + +def _snapshot_version(snapshot: Mapping[str, object] | None) -> int: + if snapshot is not None and snapshot.get("schemaVersion") == 2: + version = snapshot.get("flagStateVersion") + if type(version) is int and 0 <= version <= MAX_SAFE_INTEGER: + return version + return -1 + + +def _lock_file(fd: int) -> None: + deadline = time.monotonic() + 2 + while True: + try: + if sys.platform == "win32": + msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) + else: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + return + except OSError as error: + if error.errno not in (errno.EACCES, errno.EAGAIN) or time.monotonic() >= deadline: + raise + time.sleep(0.02) class FallbackProvider(Protocol): @@ -60,10 +91,7 @@ def save(self, namespace: str, snapshot: Mapping[str, object]) -> None: class FileFallback: - """Private, atomically replaced files. Use one writer per namespace/path. - - Atomic replacement prevents partial JSON, not stale writes between processes. - """ + """Private, atomically replaced files with a per-namespace writer lock.""" def __init__(self, directory: str | Path) -> None: self.directory = Path(directory) @@ -97,7 +125,18 @@ def save(self, namespace: str, snapshot: Mapping[str, object]) -> None: ) stream.flush() os.fsync(stream.fileno()) - os.replace(temporary, path) + # Keep the lock file in place: deleting it can split writers across inodes. + fd = os.open(path.with_suffix(".lock"), os.O_CREAT | os.O_RDWR, 0o600) + try: + _lock_file(fd) + try: + current = self.load(namespace) + except ValueError: + current = None # A corrupt file must not block recovery. + if _snapshot_version(snapshot) >= _snapshot_version(current): + os.replace(temporary, path) + finally: + os.close(fd) finally: if temporary is not None: Path(temporary).unlink(missing_ok=True) diff --git a/tests/test_fallback.py b/tests/test_fallback.py index a1de0ed..89e69a2 100644 --- a/tests/test_fallback.py +++ b/tests/test_fallback.py @@ -1,6 +1,8 @@ import os +from concurrent.futures import ThreadPoolExecutor from copy import deepcopy from datetime import UTC, datetime +from threading import Barrier import httpx import pytest @@ -37,6 +39,57 @@ async def test_file_fallback_roundtrip_and_permissions(factory, collection, tmp_ assert "if-none-match" not in other_http.gets[0].headers +def test_file_fallback_keeps_the_highest_version(tmp_path, collection): + namespace = "a" * 64 + provider = FileFallback(tmp_path) + other = FileFallback(tmp_path) + snapshot = {"schemaVersion": 2, "savedAt": "2026-03-01T00:00:00Z", **collection} + newer = dict(snapshot, flagStateVersion=3) + provider.save(namespace, newer) + + other.save(namespace, dict(snapshot, flagStateVersion=2, savedAt="2026-03-02T00:00:00Z")) + other.save(namespace, snapshot) + assert provider.load(namespace) == newer + + refreshed = dict(newer, savedAt="2026-03-02T00:00:00Z") + other.save(namespace, refreshed) + assert provider.load(namespace) == refreshed + + +def test_file_fallback_serializes_concurrent_writers(tmp_path, collection): + namespace = "a" * 64 + barrier = Barrier(8, timeout=5) + + def save(version): + provider = FileFallback(tmp_path) + barrier.wait() + provider.save( + namespace, + { + "schemaVersion": 2, + "savedAt": "2026-03-01T00:00:00Z", + **collection, + "flagStateVersion": version, + }, + ) + + with ThreadPoolExecutor(max_workers=8) as pool: + list(pool.map(save, reversed(range(8)))) + + assert FileFallback(tmp_path).load(namespace)["flagStateVersion"] == 7 + assert len(list(tmp_path.iterdir())) == 2 # Snapshot and persistent lock file. + + +def test_file_fallback_repairs_a_corrupt_snapshot(tmp_path, collection): + namespace = "a" * 64 + path = tmp_path / f"flags-fallback-v2-{namespace}.json" + path.write_text("{broken", encoding="utf-8") + provider = FileFallback(tmp_path) + snapshot = {"schemaVersion": 2, "savedAt": "2026-03-01T00:00:00Z", **collection} + provider.save(namespace, snapshot) + assert provider.load(namespace) == snapshot + + @pytest.mark.parametrize( "options", [