Spaces:
Running
Running
File size: 2,842 Bytes
6eb6c4e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | """Locate the runtime settings file (``.env``) that backs the Settings UI.
WHY THIS EXISTS
---------------
The Settings page persists browser/HITL knobs by rewriting the ``.env`` file
that ``pydantic-settings`` loads at startup. That file has to be the SAME file
on both sides — the writer in ``settings_store.py`` and the reader in
``config.py`` — or a saved value silently disappears on the next boot.
Two environments need different paths:
* **Local / compose** — the process runs from the checkout, so ``.env`` in the
working directory is right and survives a restart.
* **Hugging Face Space** — the process runs from ``/app``, which is owned by
root and NOT writable by the unprivileged ``appuser`` the image drops to.
Writing ``/app/.env`` raised ``PermissionError``, which surfaced as HTTP
500 on every save (the live mutation had already been applied, so the
operator was told "failed" while the value was actually live). The Space
mounts persistent storage at ``/data``, which is writable and survives a
rebuild.
``DRACULL_ENV_FILE`` selects the file. It is read once, at import time, and
both modules resolve it through this helper so they can never disagree.
Resolution order:
1. ``DRACULL_ENV_FILE`` — absolute path, used verbatim.
2. ``.env`` in the current working directory (the local default).
3. ``/data/.env`` when the working directory is not writable — the hosted
fallback, so a save never fails for a reason the operator cannot fix.
"""
from __future__ import annotations
import os
from pathlib import Path
#: Environment variable that overrides the settings-file location.
ENV_FILE_ENV_VAR = "DRACULL_ENV_FILE"
#: Hosted fallback: the persistent storage mount on a Hugging Face Space.
HOSTED_FALLBACK = Path("/data/.env")
def _writable_dir(directory: Path) -> bool:
"""True when a file can be created in ``directory``.
Checked with a real touch-and-delete rather than an access() probe: the
container runs as an unprivileged user, so the mode bits alone do not
decide the outcome.
"""
probe = directory / ".dracull-write-probe"
try:
probe.touch()
except OSError:
return False
try:
probe.unlink()
except OSError:
pass
return True
def resolve_env_file() -> Path:
"""The settings file the backend reads at startup and writes on save."""
configured = os.environ.get(ENV_FILE_ENV_VAR, "").strip()
if configured:
return Path(configured).expanduser()
cwd_env = Path.cwd() / ".env"
if _writable_dir(cwd_env.parent):
return cwd_env
return HOSTED_FALLBACK
def ensure_parent(path: Path) -> None:
"""Create the parent directory of ``path`` when it is missing."""
parent = path.parent
if not parent.exists():
parent.mkdir(parents=True, exist_ok=True)
|