* fix(config): report settings persistence failures (#220) Settings saves now go through one serialized config store (py/config_store.py). A commit re-reads config.json under a process lock, applies the change to a copy and replaces the file atomically (temp file beside it, fsync, close, os.replace), so a failed write leaves the old file in place. POST /prompt_manager/settings commits first and only then publishes the values at runtime. A write failure is 500 config-write-failed, an unparseable config.json is 409 config-unreadable (the file is kept instead of replaced) and a stale expected_revision is 409 settings-changed. A save reports persisted, revision, runtime_applied and restart_required_fields; GET adds the revision. Only submitted keys are written; other sections and the CivitAI key are kept. * fix(lora): report integration save failures (#220) POST /prompt_manager/lora/enable commits integrations.lora_manager through the config store and publishes the runtime values only after config.json holds them. Before, it set the runtime values, rewrote the whole runtime config (dropping sections it did not know) and reported success even when the write had failed. A write failure is 500 config-write-failed and changes nothing at runtime; an unparseable config.json is 409 config-unreadable. The body goes through the capped JSON reader and the flags must be booleans. A trigger word cache that fails to load is reported as persisted:true, cache_loaded:false. The CivitAI key is never echoed. The LoRA tests now write to a temporary config path. * fix(jobs): refuse legacy record-changing operations while a job runs The job registry gains admission classes. A records job is refused while any records or guarded job runs, a guarded job while a records job runs, and read jobs share only the one-job-per-kind rule. record_changing=True stays as the spelling of records. Job summaries add cancellable and admission, and a non-cancellable job ignores cancel. JobRegistry.hold() registers a running, non-cancellable job for a legacy-page operation and ends it when the request does. The legacy restore, maintenance, prompt cleanup, duplicate image delete, LoRA import and batch auto-tag routes hold as records; thumbnail generation (both routes) and thumbnail clear hold as guarded. A maintenance run of only read checks holds as read. So a restore during a scan, or a scan during a legacy restore, is refused with the running job named instead of interleaving; this closes the gap noted on #269. Refusals keep each route's shape: the JSON routes return the legacy 409 "<title> already running", and the thumbnail and LoRA streams send their existing error event. * test(lora): keep the preserved-section fixture free of secret values CodeQL flagged the fixture that writes the secret constant into a test config file as clear-text storage. The test only needs a marker value to prove the stored key survives a save. * fix(config): read under the commit lock and publish saves in write order - ConfigStore.read takes the commit lock, so no read handle is open while config.json is replaced (Windows refuses that replace). - os.replace is retried briefly on a Windows PermissionError (antivirus or indexer handles) before the save is reported as not written. - The temp file is written beside realpath(config.json), so a symlinked config keeps its link and a bind mount fails truthfully. - commit() takes a publish callback that runs under the lock after the write; settings and LoRA saves publish there, so two concurrent saves reach the runtime in write order and the runtime ends on the last one. - The concurrency tests now wait until the second caller is blocked on the lock (tests/lock_probe.py) before releasing the first. * fix(jobs): require an admission class, admit holds on entry, true Activity states - JobRegistry.start raises TypeError when neither admission nor record_changing is given, so a new job never runs as "read" beside a scan by omission. - hold() admits when its block is entered, so a hold that is never entered leaves no running records job behind; callers that answer a refusal in their own way check blocker() first, with no await before the block. - A held SSE operation that ends in an error event (thumbnail generation, legacy batch auto-tag) is listed as failed, and refused input (duplicate delete without paths, an unreadable thumbnail body) is answered before the hold, so it is not listed as a job. - Activity keeps a job's cancellable flag (true when an older server omits it) and shows Cancel only for a running, cancellable job, in Recent work and in the job view. A held legacy job no longer offers a Cancel that does nothing. * fix(admin): legacy pages show why a request was refused A job running in the workspace refuses the legacy record-changing requests, and a corrupt config.json refuses a settings save. The legacy pages now name the reason instead of hiding it: - LoRA import: the busy and failure frames carry status and progress, and the admin modal handles type "error": it shows the message, notifies and closes, instead of staying on "Initializing..." at 0%. - Legacy batch auto-tag: a refusal by another job is a 200 stream with one error frame ({type, status, message}), which both pages already render; a second batch keeps its exact JSON 409. - Gallery cache clear: a refused server clear shows the reason and stops before the success toast and the "Not generated" reset. - Admin settings save and maintenance show the reply's error ("config.json cannot be read...", "Scan for metadata already running") instead of "Failed to save settings" or "HTTP 409: Conflict". - Tests cover the read-only /maintenance branch: a read-only selection runs during a scan as a read hold; a mixed or default selection is refused. * refactor(api): move the settings routes out of admin.py GET and POST /prompt_manager/settings, their validation, the config commit and runtime publication, and the shared commit-failure reply now live in py/api/settings_routes.py as SettingsRoutesMixin, before S3 adds host fields there. No behaviour change: the same routes, payloads and status codes; admin.py drops about 300 lines. * chore(coverage): raise the floors of the frontend files this round touched admin.js, gallery.js, activity.mjs and activity-job-view.mjs, to their measured coverage. No floor is lowered. * fix(admin): the gallery starts no thumbnail status read while it leaves The gallery's startup thumbnail check runs one second after load. When that second ended while the page was leaving (CI, WebKit: the workflow test navigates from the gallery to the admin page), WebKit failed the new read with "Fetch API cannot load ... due to access control checks." and Playwright reported a page error. Like the admin page (#290), the gallery now has a page lifetime that ends on beforeunload and pagehide (and starts again on a back/forward restore). The check starts no read once it has ended and passes it as the read's signal. A page-clock workflow test that leaves before the second ends failed on both events, in Chromium and WebKit, before this change.
340 lines
13 KiB
Python
340 lines
13 KiB
Python
"""Settings API routes: GET and POST /prompt_manager/settings (#220).
|
|
|
|
A save validates the payload, commits it to config.json through the config
|
|
store and publishes it at runtime inside that commit; a save that cannot be
|
|
written changes nothing at runtime and says so. ``_config_commit_failure``
|
|
is shared with the LoRA integration's save.
|
|
"""
|
|
|
|
import os
|
|
|
|
from aiohttp import web
|
|
|
|
from ..config_store import (
|
|
ConfigUnreadable,
|
|
RevisionConflict,
|
|
get_config_store,
|
|
)
|
|
from .admin import _current_image_monitor
|
|
|
|
try:
|
|
from ...utils.validators import validate_result_timeout, validate_worker_threads
|
|
except ImportError:
|
|
from utils.validators import validate_result_timeout, validate_worker_threads
|
|
|
|
|
|
# Settings owned by POST /settings: config attribute -> (section, key).
|
|
_SETTINGS_FILE_KEYS = {
|
|
"RESULT_TIMEOUT": ("web_ui", "result_timeout"),
|
|
"WEBUI_DISPLAY_MODE": ("web_ui", "webui_display_mode"),
|
|
"INFINITE_SCROLL": ("web_ui", "infinite_scroll"),
|
|
"WORKER_THREADS": ("performance", "worker_threads"),
|
|
}
|
|
|
|
|
|
def _section(config, name):
|
|
"""``config[name]`` as a fresh dict (a non-object section starts empty)."""
|
|
value = config.get(name)
|
|
return dict(value) if isinstance(value, dict) else {}
|
|
|
|
|
|
def _settings_mutation(updates, new_roots):
|
|
"""The config commit for a settings save: only the submitted keys change.
|
|
|
|
Every other section and key (integrations and the CivitAI key, database,
|
|
unknown sections) is kept as it is on disk.
|
|
"""
|
|
|
|
def mutate(config):
|
|
for name, value in updates.items():
|
|
section, key = _SETTINGS_FILE_KEYS[name]
|
|
merged = _section(config, section)
|
|
merged[key] = value
|
|
config[section] = merged
|
|
if new_roots is not None:
|
|
gallery = _section(config, "gallery")
|
|
monitoring = _section(gallery, "monitoring")
|
|
monitoring["directories"] = list(new_roots)
|
|
gallery["monitoring"] = monitoring
|
|
config["gallery"] = gallery
|
|
return config
|
|
|
|
return mutate
|
|
|
|
|
|
async def _read_json(request):
|
|
"""Parse a JSON object body through the package's capped reader."""
|
|
from . import _read_json_body
|
|
|
|
return await _read_json_body(request)
|
|
|
|
|
|
class SettingsRoutesMixin:
|
|
"""Mixin providing the settings read and save endpoints."""
|
|
|
|
def _register_settings_routes(self, routes):
|
|
@routes.get("/prompt_manager/settings")
|
|
async def get_settings_route(request):
|
|
return await self.get_settings(request)
|
|
|
|
@routes.post("/prompt_manager/settings")
|
|
async def save_settings_route(request):
|
|
return await self.save_settings(request)
|
|
|
|
async def get_settings(self, request):
|
|
"""Get current settings."""
|
|
try:
|
|
from ..config import PromptManagerConfig, GalleryConfig
|
|
|
|
root_paths = [
|
|
self._public_path(d) for d in GalleryConfig.MONITORING_DIRECTORIES
|
|
]
|
|
revision = await self._run_in_executor(self._config_revision)
|
|
return web.json_response(
|
|
{
|
|
"success": True,
|
|
**revision,
|
|
"settings": {
|
|
"result_timeout": PromptManagerConfig.RESULT_TIMEOUT,
|
|
"webui_display_mode": PromptManagerConfig.WEBUI_DISPLAY_MODE,
|
|
"infinite_scroll": PromptManagerConfig.INFINITE_SCROLL,
|
|
"worker_threads": PromptManagerConfig.WORKER_THREADS,
|
|
"cpu_count": PromptManagerConfig.max_worker_threads(),
|
|
"gallery_root_paths": root_paths,
|
|
"gallery_root_path": root_paths[0] if root_paths else "",
|
|
"monitored_directories": [
|
|
self._public_path(d) for d in self._monitored_directories()
|
|
],
|
|
},
|
|
}
|
|
)
|
|
except Exception as e:
|
|
self.logger.error(f"Get settings error: {e}", exc_info=True)
|
|
return web.json_response(
|
|
{"success": False, "error": "Failed to get settings"},
|
|
status=500,
|
|
)
|
|
|
|
def _monitored_directories(self):
|
|
"""Directories the running image monitor watches, else the configured roots."""
|
|
from ..config import GalleryConfig
|
|
|
|
monitor = _current_image_monitor()
|
|
if monitor is not None:
|
|
return list(getattr(monitor, "monitored_directories", []))
|
|
return list(GalleryConfig.MONITORING_DIRECTORIES)
|
|
|
|
async def save_settings(self, request):
|
|
"""Save settings: validate, commit to config.json, then publish (#220).
|
|
|
|
Nothing changes at runtime until config.json holds the new values, so
|
|
a save that cannot be written reports ``persisted: false`` and leaves
|
|
the running settings as they were. ``expected_revision`` (the
|
|
``revision`` from GET) refuses to overwrite a file changed meanwhile;
|
|
without it the payload merges into what is on disk (legacy page).
|
|
"""
|
|
try:
|
|
data, error_response = await _read_json(request)
|
|
if error_response is not None:
|
|
return error_response
|
|
|
|
expected_revision = data.get("expected_revision")
|
|
if expected_revision is not None and not isinstance(expected_revision, str):
|
|
return web.json_response(
|
|
{"success": False, "error": "expected_revision must be a string"},
|
|
status=400,
|
|
)
|
|
try:
|
|
updates = self._validate_settings(data)
|
|
except ValueError as ve:
|
|
return web.json_response(
|
|
{"success": False, "error": str(ve)}, status=400
|
|
)
|
|
|
|
new_roots, error = self._parse_gallery_roots(data)
|
|
if error:
|
|
return web.json_response({"success": False, "error": error}, status=400)
|
|
|
|
published = {}
|
|
|
|
def publish(_config):
|
|
# Under the commit lock: saves reach the runtime in the order
|
|
# they were written, so the runtime ends on the last one.
|
|
published.update(self._publish_settings(updates, new_roots))
|
|
|
|
try:
|
|
_saved, revision = await self._run_in_executor(
|
|
get_config_store().commit,
|
|
_settings_mutation(updates, new_roots),
|
|
expected_revision=expected_revision,
|
|
publish=publish,
|
|
)
|
|
except (ConfigUnreadable, RevisionConflict, OSError) as exc:
|
|
return self._config_commit_failure(exc)
|
|
|
|
return web.json_response(
|
|
{
|
|
"success": True,
|
|
"message": "Settings saved successfully",
|
|
"restart_required": bool(published["restart_required_fields"]),
|
|
"persisted": True,
|
|
"revision": revision,
|
|
**published,
|
|
}
|
|
)
|
|
except Exception as e:
|
|
self.logger.error(f"Save settings error: {e}", exc_info=True)
|
|
return web.json_response(
|
|
{"success": False, "error": "Failed to save settings"},
|
|
status=500,
|
|
)
|
|
|
|
def _publish_settings(self, updates, new_roots):
|
|
"""Install committed settings at runtime (inside the config commit).
|
|
|
|
The values are already durable. A publication that fails is reported
|
|
as ``runtime_applied: false`` with the fields that need a restart;
|
|
nothing is retried or rolled back. Never raises.
|
|
"""
|
|
from ..config import PromptManagerConfig
|
|
|
|
for name, value in updates.items():
|
|
setattr(PromptManagerConfig, name, value)
|
|
restart_fields = []
|
|
runtime_applied = True
|
|
if new_roots is not None:
|
|
try:
|
|
if self._apply_gallery_roots(new_roots):
|
|
restart_fields.append("gallery_root_paths")
|
|
except Exception as e:
|
|
self.logger.error(
|
|
f"Saved gallery roots could not be applied: {e}", exc_info=True
|
|
)
|
|
runtime_applied = False
|
|
restart_fields.append("gallery_root_paths")
|
|
return {
|
|
"runtime_applied": runtime_applied,
|
|
"restart_required_fields": restart_fields,
|
|
}
|
|
|
|
def _config_commit_failure(self, exc):
|
|
"""The response for a config commit that wrote nothing."""
|
|
not_saved = {"success": False, "persisted": False, "runtime_applied": False}
|
|
if isinstance(exc, ConfigUnreadable):
|
|
self.logger.warning(f"Settings not saved: {exc}")
|
|
return web.json_response(
|
|
{
|
|
**not_saved,
|
|
"code": "config-unreadable",
|
|
"error": (
|
|
"config.json cannot be read, so nothing was saved. "
|
|
"Fix or remove the file, then save again."
|
|
),
|
|
},
|
|
status=409,
|
|
)
|
|
if isinstance(exc, RevisionConflict):
|
|
return web.json_response(
|
|
{
|
|
**not_saved,
|
|
"code": "settings-changed",
|
|
"error": "Settings changed since they were loaded. Reload them.",
|
|
"revision": exc.current,
|
|
},
|
|
status=409,
|
|
)
|
|
self.logger.error(f"Could not write config.json: {exc}")
|
|
return web.json_response(
|
|
{
|
|
**not_saved,
|
|
"code": "config-write-failed",
|
|
"error": "Settings could not be written to config.json.",
|
|
},
|
|
status=500,
|
|
)
|
|
|
|
@staticmethod
|
|
def _config_revision():
|
|
"""``{"revision": ...}``, or a null revision with ``config_error``."""
|
|
try:
|
|
_data, revision = get_config_store().read()
|
|
except ConfigUnreadable:
|
|
return {"revision": None, "config_error": "config-unreadable"}
|
|
return {"revision": revision}
|
|
|
|
@staticmethod
|
|
def _validate_settings(data):
|
|
"""Scalar settings of a payload as ``{CONFIG_ATTR: value}``.
|
|
|
|
Raises ValueError with a user-facing message on the first bad value;
|
|
nothing is applied until every value passed.
|
|
"""
|
|
from ..config import PromptManagerConfig
|
|
|
|
updates = {}
|
|
if "result_timeout" in data:
|
|
updates["RESULT_TIMEOUT"] = validate_result_timeout(data["result_timeout"])
|
|
if "webui_display_mode" in data:
|
|
mode = data["webui_display_mode"]
|
|
if mode not in ("popup", "newtab"):
|
|
raise ValueError("webui_display_mode must be 'popup' or 'newtab'")
|
|
updates["WEBUI_DISPLAY_MODE"] = mode
|
|
if "infinite_scroll" in data:
|
|
if not isinstance(data["infinite_scroll"], bool):
|
|
raise ValueError("infinite_scroll must be true or false")
|
|
updates["INFINITE_SCROLL"] = data["infinite_scroll"]
|
|
if "worker_threads" in data:
|
|
updates["WORKER_THREADS"] = validate_worker_threads(
|
|
data["worker_threads"], PromptManagerConfig.max_worker_threads()
|
|
)
|
|
return updates
|
|
|
|
def _parse_gallery_roots(self, data):
|
|
"""Extract and validate gallery roots from a settings payload.
|
|
|
|
Accepts ``gallery_root_paths`` (list, preferred) or the legacy single
|
|
``gallery_root_path`` string. Blank entries are dropped.
|
|
|
|
Returns:
|
|
(roots, error): ``roots`` is the validated list, or ``None`` when
|
|
the payload carries no gallery root key; ``error`` is a message
|
|
when validation failed (and ``roots`` is then ``None``).
|
|
"""
|
|
if "gallery_root_paths" in data:
|
|
raw = data["gallery_root_paths"]
|
|
if not isinstance(raw, list):
|
|
return None, "gallery_root_paths must be a list"
|
|
elif "gallery_root_path" in data:
|
|
raw = [data["gallery_root_path"]]
|
|
else:
|
|
return None, None
|
|
|
|
from ..config import GalleryConfig
|
|
|
|
roots = []
|
|
for entry in raw:
|
|
if not isinstance(entry, str):
|
|
return None, "Gallery root paths must be strings"
|
|
entry = entry.strip()
|
|
if not entry:
|
|
continue
|
|
ok, reason = GalleryConfig.validate_gallery_root(entry)
|
|
if not ok:
|
|
return (
|
|
None,
|
|
f"Invalid gallery root '{os.path.basename(entry)}': {reason}",
|
|
)
|
|
roots.append(GalleryConfig.resolve_gallery_root(entry))
|
|
return roots, None
|
|
|
|
def _apply_gallery_roots(self, roots):
|
|
"""Install validated gallery roots; returns True when they changed."""
|
|
from ..config import GalleryConfig
|
|
|
|
if roots == list(GalleryConfig.MONITORING_DIRECTORIES):
|
|
return False
|
|
GalleryConfig.MONITORING_DIRECTORIES = roots
|
|
self._cached_output_dir = None
|
|
self.reset_gallery_roots_cache()
|
|
return True
|