Author SHA1 Message Date
mattandClaude Sonnet 5.5 ad383b602e Configurable logging for the API and worker (SCR-5)
CI / notify (push) Successful in 6s
CI / lint (push) Successful in 18s
CI / test (push) Successful in 5m26s
CI / validate-monitoring (push) Successful in 15s
CI / federation-interop (push) Successful in 1m17s
CI / images (push) Successful in 33s
CI / assets (push) Successful in 9s
CI / python-package (push) Successful in 18s
CI / trigger-deploy (push) Successful in 3s
Shared LOG_LEVEL/LOG_FORMAT (text or json) set up in create_app, per-task
activity and duration logs in the worker, and more context on delivery,
inbox and import failures. Alembic's fileConfig no longer disables loggers.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-06 23:30:54 +01:00
mattandClaude Sonnet 5.5 65cd610468 Isolate concurrent federation interop runs (SCR-4)
CI / validate-monitoring (push) Successful in 16s
CI / lint (push) Successful in 17s
CI / federation-interop (push) Successful in 1m40s
CI / test (push) Successful in 5m23s
CI / python-package (push) Skipped
CI / assets (push) Successful in 13s
CI / images (push) Successful in 31s
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 5s
Let Docker allocate each run's network subnet instead of deriving a /24 from
the run number, trust private ranges in GoToSocial, and tag/clean up api and ui
images per run so overlapping runs (e.g. main push plus tag) cannot collide.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-06 23:12:41 +01:00
mattandClaude Sonnet 5.5 735556bf21 Merge feature/album-art-overrides into main
CI / test (push) Successful in 3m48s
CI / lint (push) Successful in 19s
CI / validate-monitoring (push) Successful in 14s
CI / federation-interop (push) Successful in 1m36s
CI / python-package (push) Successful in 16s
CI / images (push) Successful in 29s
CI / trigger-deploy (push) Successful in 2s
CI / assets (push) Successful in 1m22s
CI / notify (push) Successful in 6s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv
2026-10-06 22:58:11 +01:00
20 changed files with 228 additions and 18 deletions

No files matched your search

+4
View File
@@ -10,6 +10,10 @@ CORS_ORIGINS=http://localhost:8080
# Where Last.fm clients are redirected to approve desktop auth tokens.
UI_BASE_URL=http://localhost:8080
# Logging: level (DEBUG, INFO, WARNING, ERROR) and format ("text", or "json" for log aggregators).
LOG_LEVEL=INFO
LOG_FORMAT=text
# Prometheus metrics are served on a separate port.
METRICS_PORT=9100
+3 -4
View File
@@ -87,11 +87,10 @@ jobs:
- uses: actions/checkout@v4
- name: Scrobbler <-> GoToSocial
env:
# Own compose project, network and image tags, so concurrent runs can't collide
INTEROP_PROJECT: interop-${{ github.run_id }}
run: |
# A subnet of its own, so concurrent runs can't collide
export INTEROP_SUBNET="172.30.$(( ${{ github.run_number }} % 200 + 20 )).0/24"
scripts/interop/run.sh
SCROBBLER_IMAGE_TAG: interop-${{ github.run_id }}
run: scripts/interop/run.sh
# ---- Publishing (main and v* tags only) -------------------------------------
+4 -5
View File
@@ -18,11 +18,10 @@ x-federation: &federation
FEDERATION_INSECURE_TESTING: "1"
UI_BASE_URL: https://scrobble.test
# Docker picks the network's subnet, so concurrent runs can't collide on one. GoToSocial
# is therefore told to trust any private range rather than one specific /24.
networks:
fedi:
ipam:
config:
- subnet: ${INTEROP_SUBNET:-172.30.0.0/24}
services:
db:
@@ -63,9 +62,9 @@ services:
GTS_PORT: "80"
GTS_DB_TYPE: sqlite
GTS_DB_ADDRESS: /gotosocial/storage/sqlite.db
GTS_HTTP_CLIENT_ALLOW_IPS: ${INTEROP_SUBNET:-172.30.0.0/24} # let it reach Scrobbler on this network
GTS_HTTP_CLIENT_ALLOW_IPS: ${INTEROP_PRIVATE_RANGES:-10.0.0.0/8,172.16.0.0/12,192.168.0.0/16} # let it reach Scrobbler on this network
GTS_HTTP_CLIENT_TLS_INSECURE_SKIP_VERIFY: "true" # Caddy's throwaway certificate
GTS_TRUSTED_PROXIES: ${INTEROP_SUBNET:-172.30.0.0/24}
GTS_TRUSTED_PROXIES: ${INTEROP_PRIVATE_RANGES:-10.0.0.0/8,172.16.0.0/12,192.168.0.0/16}
GTS_ACCOUNTS_REGISTRATION_OPEN: "false"
GTS_LOG_LEVEL: ${GTS_LOG_LEVEL:-info}
sysctls:
+4
View File
@@ -33,6 +33,8 @@ services:
UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080}
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
FORWARDED_ALLOW_IPS: "*"
LOG_LEVEL: ${LOG_LEVEL:-INFO}
LOG_FORMAT: ${LOG_FORMAT:-text}
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
@@ -68,6 +70,8 @@ services:
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
FEDERATION_KEY_SECRET: ${FEDERATION_KEY_SECRET:-}
RUN_MIGRATIONS: "0" # the api service applies them
LOG_LEVEL: ${LOG_LEVEL:-INFO}
LOG_FORMAT: ${LOG_FORMAT:-text}
expose:
- "9101" # metrics: internal network only
volumes:
+2
View File
@@ -54,6 +54,8 @@ read **Putting it behind TLS** below — the quick start above serves plain HTTP
| `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated origins allowed to call `/api/v1`: wherever browsers actually load the UI from |
| `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins, and (with federation on) the public identity users are found under |
| `OPENAPI_DOCS_ENABLED` | api | `1` | Set to `0` to hide `/api/docs` and `/api/redoc` |
| `LOG_LEVEL` | api, worker | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR`. The worker logs each task pass that did work at `INFO` (with its duration); idle polls show at `DEBUG` |
| `LOG_FORMAT` | api, worker | `text` | `json` writes one JSON object per line (with `task` and `duration_ms` fields for worker tasks), for log aggregators |
| `METRICS_PORT` | api | `9100` | Prometheus metrics port — keep it off the public network |
| `WEB_CONCURRENCY` | api | `2` | gunicorn workers |
| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start |
+10
View File
@@ -11,11 +11,21 @@ wsgi_app = "scrobbler:create_app()"
bind = os.environ.get("BIND", "0.0.0.0:8000")
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
accesslog = "-"
loglevel = os.environ.get("LOG_LEVEL", "INFO").lower()
forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")
# gunicorn 26's control socket lives in $HOME, which the container user doesn't have.
control_socket_disable = True
def post_fork(server, worker):
# Gunicorn's own messages go through the app's handler too, so the format is uniform.
import logging
gunicorn_error = logging.getLogger("gunicorn.error")
gunicorn_error.handlers.clear()
gunicorn_error.propagate = True
def on_starting(server):
# Stale files from a previous run would double-count.
shutil.rmtree(MULTIPROC_DIR, ignore_errors=True)
+1 -1
View File
@@ -2,6 +2,6 @@
# docker compose for the federation interop stack (Scrobbler + GoToSocial).
set -euo pipefail
root="$(cd "$(dirname "$0")/../.." && pwd)"
# INTEROP_PROJECT and INTEROP_SUBNET let concurrent runs (e.g. in CI) stay apart.
# INTEROP_PROJECT (with a distinct SCROBBLER_IMAGE_TAG) lets concurrent runs (e.g. in CI) stay apart.
exec docker compose -p "${INTEROP_PROJECT:-scrobbler-interop}" \
-f "$root/docker-compose.yml" -f "$root/deploy/interop/docker-compose.interop.yml" "$@"
+8 -1
View File
@@ -6,7 +6,14 @@ here="$(cd "$(dirname "$0")" && pwd)"
compose="$here/compose.sh"
keep=0; [ "${1:-}" = "--keep" ] && keep=1
cleanup() { [ "$keep" = 1 ] || "$compose" down -v --remove-orphans >/dev/null 2>&1; }
cleanup() {
[ "$keep" = 1 ] && return 0
"$compose" down -v --remove-orphans --rmi local >/dev/null 2>&1
# Per-run api/ui images (tagged with SCROBBLER_IMAGE_TAG) would otherwise pile up
[ -n "${SCROBBLER_IMAGE_TAG:-}" ] && "$compose" config --images 2>/dev/null \
| grep ":${SCROBBLER_IMAGE_TAG}$" | xargs -r docker rmi >/dev/null 2>&1
return 0
}
trap cleanup EXIT
"$compose" down -v --remove-orphans >/dev/null 2>&1
+4
View File
@@ -19,6 +19,10 @@ def create_app(config_object=None):
app = Flask(__name__, static_folder=None) # API only: the UI is hosted separately
app.config.from_object(config_object or Config)
from scrobbler.logsetup import configure_logging
configure_logging(app.config["LOG_LEVEL"], app.config["LOG_FORMAT"])
db.init_app(app)
migrate.init_app(app, db, directory=_migrations_dir())
http_metrics.init_app(app)
-1
View File
@@ -8,7 +8,6 @@ from flask.cli import AppGroup, with_appcontext
def _run_worker(once: bool, poll: float, serve_metrics: bool) -> None:
from scrobbler import worker
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
if serve_metrics:
from scrobbler.metrics.server import start_metrics_server
+5
View File
@@ -20,6 +20,9 @@ class Config:
CORS_ORIGINS = _csv(os.environ.get("CORS_ORIGINS", "http://localhost:8080"))
UI_BASE_URL = os.environ.get("UI_BASE_URL", "http://localhost:8080").rstrip("/")
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
LOG_FORMAT = os.environ.get("LOG_FORMAT", "text").lower() # "text" or "json"
METRICS_PORT = int(os.environ.get("METRICS_PORT", "9100"))
# Start the metrics HTTP server from create_app (dev server). Under gunicorn the
# server is started by gunicorn.conf.py instead, so this stays off there.
@@ -92,6 +95,8 @@ class TestConfig(Config):
"postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test",
)
START_METRICS_SERVER = False
LOG_LEVEL = "INFO"
LOG_FORMAT = "text"
# Tests never inherit optional features or URLs from a developer's .env or
# environment; tests that need them turn them on, or override them, explicitly.
LASTFM_API_KEY = ""
+16 -1
View File
@@ -68,6 +68,13 @@ def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | No
delivery.last_status, delivery.last_error = status, error[:1000]
if _now() - delivery.created_at >= GIVE_UP_AFTER:
delivery.status = "abandoned"
log.warning(
"delivery %s to %s abandoned after %s attempts: %s",
delivery.id,
delivery.inbox,
delivery.attempts,
error[:200],
)
return "abandoned"
delay = (
RETRY_DELAYS[delivery.attempts - 1]
@@ -75,6 +82,14 @@ def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | No
else LATER_DELAY
)
delivery.next_attempt_at = _now() + delay
log.warning(
"delivery %s to %s failed (attempt %s), retrying in %s: %s",
delivery.id,
delivery.inbox,
delivery.attempts,
delay,
error[:200],
)
return "retry"
@@ -135,7 +150,7 @@ def _deliver_in_context(app, delivery_id: int) -> str:
try:
return deliver(delivery_id)
except Exception:
log.exception("delivery %s failed unexpectedly", delivery_id)
log.exception("delivery %s failed unexpectedly (will be retried)", delivery_id)
db.session.rollback()
return "retry" # the lease expires and it becomes due again
finally:
+7 -1
View File
@@ -224,7 +224,13 @@ def process(item: FederationInboxItem) -> None:
db.session.rollback()
transient = isinstance(err, FetchError) and err.reason == "network"
if not transient:
log.exception("inbox item %s failed", item.id)
log.exception(
"inbox item %s (%s) failed on attempt %s of %s",
item.id,
item.activity_type,
item.attempts,
MAX_ATTEMPTS,
)
if item.attempts < MAX_ATTEMPTS:
_finish(item, "queued", f"retrying: {err}"[:255], done=False)
return
+44
View File
@@ -0,0 +1,44 @@
"""Logging set-up shared by the API and the worker (`LOG_LEVEL`, `LOG_FORMAT`).
`text` is human-readable; `json` is one object per line for log aggregators. Fields passed
as `extra=` to a log call (e.g. `task`, `duration_ms`) appear as keys in the JSON output.
"""
import json
import logging
import sys
from datetime import UTC, datetime
TEXT_FORMAT = "%(asctime)s %(levelname)s %(name)s %(message)s"
# Attributes every LogRecord has; anything else on a record came from `extra=`.
_STANDARD = set(logging.makeLogRecord({}).__dict__) | {"message", "asctime", "taskName"}
_HANDLER_FLAG = "_scrobbler_handler"
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
entry = {
"time": datetime.fromtimestamp(record.created, UTC).isoformat(timespec="milliseconds"),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
entry.update((k, v) for k, v in record.__dict__.items() if k not in _STANDARD)
if record.exc_info:
entry["exception"] = self.formatException(record.exc_info)
return json.dumps(entry, default=str)
def configure_logging(level: str = "INFO", fmt: str = "text") -> None:
"""Point the root logger at stderr. Safe to call repeatedly (it replaces its own
handler); an unknown level falls back to INFO."""
root = logging.getLogger()
for handler in [h for h in root.handlers if getattr(h, _HANDLER_FLAG, False)]:
root.removeHandler(handler)
handler = logging.StreamHandler(sys.stderr)
setattr(handler, _HANDLER_FLAG, True)
handler.setFormatter(JsonFormatter() if fmt == "json" else logging.Formatter(TEXT_FORMAT))
root.addHandler(handler)
resolved = logging.getLevelName(str(level).upper())
root.setLevel(resolved if isinstance(resolved, int) else logging.INFO)
+1 -1
View File
@@ -11,7 +11,7 @@ config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
fileConfig(config.config_file_name, disable_existing_loggers=False)
logger = logging.getLogger('alembic.env')
+1
View File
@@ -602,6 +602,7 @@ def resolve_one_pending() -> bool:
row.checked_at = datetime.now(UTC)
db.session.commit()
metrics.art_worker_resolve_seconds.observe(time.perf_counter() - start)
log.info("album art for %r/%r: %s", row.artist, row.album, result.status)
return True
+1 -1
View File
@@ -549,7 +549,7 @@ def process_job(job: ImportJob) -> None:
db.session.rollback()
_finish(job, "failed", err.message)
except Exception:
log.exception("import job %s failed", job.id)
log.exception("import job %s (%s) for user %s failed", job.id, job.source, job.user_id)
db.session.rollback()
_finish(
job, "failed", "The import failed unexpectedly. Try again, or check the server logs."
+28 -2
View File
@@ -50,18 +50,44 @@ def registered(app: Flask | None = None) -> list[str]:
def _call(task: _Task) -> bool:
started = time.monotonic()
try:
worked = bool(task.fn())
result = task.fn()
except Exception:
log.exception("worker task %s failed", task.name)
log.exception(
"worker task %s failed after %.0f ms",
task.name,
_elapsed_ms(started),
extra={"task": task.name, "outcome": "error", "duration_ms": _elapsed_ms(started)},
)
db.session.rollback()
metrics.worker_tasks_total.labels(task=task.name, outcome="error").inc()
return False
worked = bool(result)
if worked or task.every is not None:
metrics.worker_tasks_total.labels(task=task.name, outcome="worked").inc()
duration = _elapsed_ms(started)
# Queue tasks are polled every couple of seconds, so only passes that did work are
# worth an INFO line; periodic tasks say so only when they report work (a truthy result).
log.log(
logging.INFO if worked else logging.DEBUG,
"worker task %s %s in %.0f ms",
task.name,
"worked" if worked else "ran (nothing to do)",
duration,
extra={
"task": task.name,
"outcome": "worked" if worked else "idle",
"duration_ms": duration,
},
)
return worked
def _elapsed_ms(started: float) -> float:
return round((time.monotonic() - started) * 1000, 1)
def run_once() -> bool:
"""One pass: due periodic tasks, then each queue task once. True if any queue
task did work (so there may be more waiting)."""
+56
View File
@@ -0,0 +1,56 @@
import json
import logging
import pytest
from scrobbler.logsetup import JsonFormatter, configure_logging
@pytest.fixture(autouse=True)
def restore_root_logger():
root = logging.getLogger()
handlers, level = list(root.handlers), root.level
yield
root.handlers[:] = handlers
root.setLevel(level)
def _record(msg="hello %s", args=("world",), **extra):
record = logging.LogRecord("test.logger", logging.INFO, __file__, 1, msg, args, None)
record.__dict__.update(extra)
return record
def test_json_formatter_emits_fields_and_extras():
entry = json.loads(JsonFormatter().format(_record(task="art", duration_ms=12.5)))
assert entry["message"] == "hello world"
assert entry["level"] == "INFO"
assert entry["logger"] == "test.logger"
assert entry["task"] == "art"
assert entry["duration_ms"] == 12.5
assert "time" in entry
def test_json_formatter_includes_exceptions():
try:
raise ValueError("boom")
except ValueError:
record = _record()
import sys
record.exc_info = sys.exc_info()
assert "ValueError: boom" in json.loads(JsonFormatter().format(record))["exception"]
def test_configure_logging_is_idempotent_and_sets_level():
root = logging.getLogger()
configure_logging("DEBUG", "json")
configure_logging("warning", "text")
ours = [h for h in root.handlers if getattr(h, "_scrobbler_handler", False)]
assert len(ours) == 1
assert root.level == logging.WARNING
def test_unknown_level_falls_back_to_info():
configure_logging("LOUD", "text")
assert logging.getLogger().level == logging.INFO
+29
View File
@@ -89,3 +89,32 @@ def test_worker_cli_lists_and_runs_tasks(app, tasks):
assert ran == [1]
alias = app.test_cli_runner().invoke(args=["imports", "worker", "--once", "--no-metrics"])
assert alias.exit_code == 0, alias.output
def test_a_pass_that_did_work_is_logged_with_its_duration(tasks, caplog):
tasks.register_task("busy", lambda: True)
with caplog.at_level("INFO", logger="scrobbler.worker"):
worker.run_once()
record = next(r for r in caplog.records if r.__dict__.get("task") == "busy")
assert record.levelname == "INFO"
assert record.outcome == "worked"
assert record.duration_ms >= 0
def test_idle_passes_are_only_logged_at_debug(tasks, caplog):
tasks.register_task("idle", lambda: False)
with caplog.at_level("INFO", logger="scrobbler.worker"):
worker.run_once()
assert not [r for r in caplog.records if r.__dict__.get("task") == "idle"]
def test_failures_log_the_task_name_and_duration(tasks, caplog):
def boom():
raise RuntimeError("nope")
tasks.register_task("broken", boom)
with caplog.at_level("ERROR", logger="scrobbler.worker"):
worker.run_once()
record = next(r for r in caplog.records if r.__dict__.get("task") == "broken")
assert record.outcome == "error"
assert "broken" in record.getMessage()