mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Unified prefs writing
This commit is contained in:
1 parent
957525393b
commit
4e9472c14a
8 files changed
+274
-69
No files matched your search
+68
-31
@@ -3,10 +3,19 @@
|
||||
A self-contained JSON file in the app's per-OS user-writable data dir (see
|
||||
``paths.app_data_dir``) so it survives a frozen/packaged build and works the same
|
||||
on every platform. Best-effort: any I/O error degrades to "no prefs".
|
||||
|
||||
**Every read-modify-write holds ``_LOCK`` and every write is atomic.** FastAPI
|
||||
runs ``PATCH /api/prefs`` on a thread pool, and the UI sends several at once on
|
||||
launch. Unlocked, with ``write_text`` truncating before it wrote, a reader could
|
||||
catch the file empty, take it for "no prefs" and write back only its own key —
|
||||
wiping everything else (measured: 249 of 300 trials of three concurrent patches).
|
||||
A file that exists but will not parse is moved aside before it is replaced, so
|
||||
it is never silently overwritten.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from . import paths
|
||||
@@ -16,6 +25,9 @@ from . import paths
|
||||
_PREFS_PATH = paths.app_data_dir() / "userprefs.json"
|
||||
_LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json"
|
||||
|
||||
# Reentrant: the helpers below read and write inside one critical section.
|
||||
_LOCK = threading.RLock()
|
||||
|
||||
|
||||
def _migrate_legacy() -> None:
|
||||
"""One-time: if the new file is absent but a legacy package-relative one
|
||||
@@ -27,29 +39,52 @@ def _migrate_legacy() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def load_prefs() -> dict:
|
||||
def _read(*, for_write: bool) -> dict:
|
||||
"""The stored prefs, or {} if there are none or they cannot be read.
|
||||
|
||||
With ``for_write``, a file that exists but is not a JSON object is renamed
|
||||
to ``userprefs.json.corrupt`` first, since the caller is about to replace it.
|
||||
"""
|
||||
try:
|
||||
_migrate_legacy()
|
||||
data = json.loads(_PREFS_PATH.read_text())
|
||||
return data if isinstance(data, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
text = _PREFS_PATH.read_text()
|
||||
except OSError:
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(text)
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
except ValueError:
|
||||
pass
|
||||
if for_write:
|
||||
try:
|
||||
_PREFS_PATH.replace(_PREFS_PATH.with_name(_PREFS_PATH.name + ".corrupt"))
|
||||
except OSError:
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def load_prefs() -> dict:
|
||||
with _LOCK:
|
||||
return _read(for_write=False)
|
||||
|
||||
|
||||
def save_prefs(prefs: dict) -> None:
|
||||
try:
|
||||
_PREFS_PATH.write_text(json.dumps(prefs, indent=2))
|
||||
except OSError:
|
||||
pass # non-fatal — prefs are a convenience, not a requirement
|
||||
with _LOCK:
|
||||
try:
|
||||
paths.write_json(_PREFS_PATH, prefs)
|
||||
except OSError:
|
||||
pass # non-fatal — prefs are a convenience, not a requirement
|
||||
|
||||
|
||||
def update_prefs(patch: dict) -> dict:
|
||||
"""Shallow-merge `patch` into the stored prefs and persist. Returns the
|
||||
full updated prefs dict."""
|
||||
prefs = load_prefs()
|
||||
prefs.update(patch)
|
||||
save_prefs(prefs)
|
||||
return prefs
|
||||
with _LOCK:
|
||||
prefs = _read(for_write=True)
|
||||
prefs.update(patch)
|
||||
save_prefs(prefs)
|
||||
return prefs
|
||||
|
||||
|
||||
def get_path_mapping(collection_path: str) -> dict | None:
|
||||
@@ -69,16 +104,17 @@ def set_path_mapping(
|
||||
collection_path: str, from_prefix: str | None, to_prefix: str | None
|
||||
) -> None:
|
||||
"""Persist (or, when either prefix is blank, clear) a collection's mapping."""
|
||||
prefs = load_prefs()
|
||||
mappings = prefs.get("path_mappings")
|
||||
if not isinstance(mappings, dict):
|
||||
mappings = {}
|
||||
if from_prefix and to_prefix:
|
||||
mappings[collection_path] = {"from": from_prefix, "to": to_prefix}
|
||||
else:
|
||||
mappings.pop(collection_path, None)
|
||||
prefs["path_mappings"] = mappings
|
||||
save_prefs(prefs)
|
||||
with _LOCK:
|
||||
prefs = _read(for_write=True)
|
||||
mappings = prefs.get("path_mappings")
|
||||
if not isinstance(mappings, dict):
|
||||
mappings = {}
|
||||
if from_prefix and to_prefix:
|
||||
mappings[collection_path] = {"from": from_prefix, "to": to_prefix}
|
||||
else:
|
||||
mappings.pop(collection_path, None)
|
||||
prefs["path_mappings"] = mappings
|
||||
save_prefs(prefs)
|
||||
|
||||
|
||||
def get_last_collection(platform: str | None = None) -> str | None:
|
||||
@@ -105,12 +141,13 @@ def get_last_collection(platform: str | None = None) -> str | None:
|
||||
|
||||
def set_last_collection(path: str, platform: str | None = None) -> None:
|
||||
"""Record a library as the last opened, globally and for its platform."""
|
||||
prefs = load_prefs()
|
||||
prefs["last_collection"] = path
|
||||
if platform:
|
||||
by_platform = prefs.get("last_collection_by_platform")
|
||||
if not isinstance(by_platform, dict):
|
||||
by_platform = {}
|
||||
by_platform[platform] = path
|
||||
prefs["last_collection_by_platform"] = by_platform
|
||||
save_prefs(prefs)
|
||||
with _LOCK:
|
||||
prefs = _read(for_write=True)
|
||||
prefs["last_collection"] = path
|
||||
if platform:
|
||||
by_platform = prefs.get("last_collection_by_platform")
|
||||
if not isinstance(by_platform, dict):
|
||||
by_platform = {}
|
||||
by_platform[platform] = path
|
||||
prefs["last_collection_by_platform"] = by_platform
|
||||
save_prefs(prefs)
|
||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
source .venv/bin/activate
|
||||
|
||||
fail=0
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""userprefs.json under concurrent writes.
|
||||
|
||||
The UI sends several `PATCH /api/prefs` at once on launch (column layout, deck
|
||||
zoom, loop size), and FastAPI runs them on a thread pool. Before the lock and
|
||||
the atomic write, a reader could catch the file truncated mid-write, take it for
|
||||
"no prefs" and write back only its own key — the column layout, and with it
|
||||
every other pref, vanished between sessions (249 of 300 trials of the burst
|
||||
below lost the other keys). Nothing failed; the app just forgot.
|
||||
|
||||
Prefs are redirected to a temp file — a test must never rewrite the user's own.
|
||||
"""
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from konduktor import prefs
|
||||
|
||||
_TMP = tempfile.TemporaryDirectory()
|
||||
prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json"
|
||||
prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json"
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
BASE = {"columns": {"order": ["a", "b"]}, "autoCueTemplate": [1, 2, 3], "beatSize": 4}
|
||||
PATCHES = [
|
||||
{"columns": {"order": ["b", "a"]}},
|
||||
{"mainZoomSec": 16},
|
||||
{"beatSize": 8},
|
||||
{"stemDevice": "cpu"},
|
||||
]
|
||||
|
||||
# The launch burst, many times over: every patch lands and nothing else is lost.
|
||||
TRIALS = 200
|
||||
bad = []
|
||||
for i in range(TRIALS):
|
||||
prefs.save_prefs(BASE)
|
||||
go = threading.Barrier(len(PATCHES) + 1)
|
||||
|
||||
def write(p):
|
||||
go.wait()
|
||||
prefs.update_prefs(p)
|
||||
|
||||
def read():
|
||||
go.wait()
|
||||
for _ in range(20):
|
||||
if "autoCueTemplate" not in prefs.load_prefs():
|
||||
bad.append(f"trial {i}: a reader saw no prefs")
|
||||
return
|
||||
|
||||
threads = [threading.Thread(target=write, args=(p,)) for p in PATCHES]
|
||||
threads.append(threading.Thread(target=read))
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
got = prefs.load_prefs()
|
||||
want = {**BASE, **{k: v for p in PATCHES for k, v in p.items()}}
|
||||
if got != want:
|
||||
bad.append(f"trial {i}: {got}")
|
||||
check(f"{TRIALS} concurrent bursts keep every key and every patch", not bad,
|
||||
bad[0] if bad else "")
|
||||
|
||||
# The path-specific helpers share the lock: a burst of them loses nothing either.
|
||||
prefs.save_prefs({"autoCueTemplate": [1]})
|
||||
threads = [threading.Thread(target=prefs.set_last_collection, args=(f"/lib/{p}", p))
|
||||
for p in ("traktor", "rekordbox", "onelibrary")]
|
||||
threads += [threading.Thread(target=prefs.set_path_mapping, args=(f"/c{n}", "X:", "/Volumes/X"))
|
||||
for n in range(3)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
got = prefs.load_prefs()
|
||||
check("concurrent last-collection writes keep every platform",
|
||||
set(got.get("last_collection_by_platform", {})) == {"traktor", "rekordbox", "onelibrary"},
|
||||
str(got))
|
||||
check("concurrent path mappings keep every collection",
|
||||
set(got.get("path_mappings", {})) == {"/c0", "/c1", "/c2"}, str(got))
|
||||
check("and the unrelated key survives", got.get("autoCueTemplate") == [1])
|
||||
|
||||
# A file that will not parse is moved aside, never silently overwritten.
|
||||
prefs._PREFS_PATH.write_text('{"columns": {"order": ["a"')
|
||||
check("an unreadable file reads as no prefs", prefs.load_prefs() == {})
|
||||
check("reading leaves it in place", prefs._PREFS_PATH.read_text().startswith('{"columns"'))
|
||||
prefs.update_prefs({"beatSize": 2})
|
||||
corrupt = prefs._PREFS_PATH.with_name("userprefs.json.corrupt")
|
||||
check("writing over it keeps the old bytes beside it",
|
||||
corrupt.exists() and corrupt.read_text() == '{"columns": {"order": ["a"')
|
||||
check("and the new file holds the patch", prefs.load_prefs() == {"beatSize": 2})
|
||||
|
||||
check("no temp file is left behind",
|
||||
not [p for p in Path(_TMP.name).iterdir() if ".tmp" in p.name])
|
||||
|
||||
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
|
||||
_TMP.cleanup()
|
||||
raise SystemExit(1 if failed else 0)
|
||||
Reference in new issue
Block a user