Sync shared snapshot from 8701874
Security / Secrets (gitleaks) (push) Successful in 1m1s
Security / Dependencies (Trivy) (push) Successful in 51s
Security / Code (Semgrep) (push) Successful in 1m29s
Docker / Docker Build & Push (push) Successful in 5m28s

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Haiku 5.5 committed 2026-11-21 00:23:35 +01:00
1 parent 01b18be1e4
commit 362cee26fd
20 files changed
+4908 -61

No files matched your search

+82 -9
View File
@@ -110,7 +110,8 @@ give it, and updated live whenever ProjectConfigurator pushes a fresh
`PUT /api/core-services/internal`. A service wires the actual route itself:
```python
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore, internal_secret_matches
from fastapi.responses import JSONResponse
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore, handle_core_services_push
auth_client = AuthClient("") # pending: no URL yet, still safe to use
core_config = CoreConfigStore(CoreConfigInfo(auth_guard_url=""))
@@ -118,17 +119,42 @@ core_config.on_update(lambda info: auth_client.set_base_url(info.auth_guard_url)
# in your framework's route for PUT /api/core-services/internal:
@app.put("/api/core-services/internal")
async def push_core_services(request):
if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET):
raise HTTPException(status_code=401)
body = await request.json()
try:
info = core_config.set(CoreConfigInfo.from_json(body))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"ok": True, "info": info.to_json()}
status, body = handle_core_services_push(
core_config, SECRET, request.headers.get("X-Internal-Auth"), await request.body()
)
return JSONResponse(body, status_code=status)
```
`handle_core_services_push` is the framework-neutral body of the route. It returns
`(status, body)`, so any framework can send it, and it does the checks in this order:
- `X-Internal-Auth` must equal SECRET, compared in constant time, or the response is
401 `{"error": "internal service authentication required"}`. A SECRET that is not usable
(see below) gets 401 for every caller.
- A body over 4096 bytes, or one that is not a JSON object, gets 400
`{"error": "invalid JSON body"}`.
- A non-empty `omniLoggerUrl`, `authGuardUrl` or `carrierNodeUrl(s)` that is not an http or
https URL with a host gets 400 `{"error": "core service URL must be an http or https URL with a host"}`.
- Otherwise it returns 200 `{"ok": true}`. The response never includes the ingest token.
Other fields are ignored.
The store keeps the last non-empty value of each field, so a partial push never clears a stored
one. OmniLogger's URL and this service's ingest token (`CoreConfigInfo.omni_logger_url` and
`omni_logger_ingest_token`) are not used by the store's AuthGuard or CarrierNode logic. A
log shipper follows them through `follow_omnilogger`:
```python
shipper = Shipper.from_env("myservice") or Shipper(base_url="", ingest_token="", service="myservice")
follow_omnilogger(core_config, shipper) # once, at startup; later pushes call shipper.set_credentials
```
`follow_omnilogger` calls `shipper.set_credentials(url, token)` after a push, but only once
both values are stored, so a token-only push never disables or re-points the shipper.
Don't seed the store with `OMNILOGGER_*` values from the environment. Those belong to the
shipper, and seeding them would make a token-only push re-point it.
`internal_secret_matches` also refuses a SECRET shorter than `MIN_INTERNAL_SECRET_LENGTH`
(16 characters) or equal to an example placeholder (`EXAMPLE_INTERNAL_SECRETS`), so every
internal route gated by it rejects all callers until the secret is set properly. Call
@@ -191,3 +217,50 @@ This mounts `/status`, `/me` (GET/PUT), `/admin-needed`, `/setup`, `/login`,
— the same URL paths and JSON response shapes as `shared/backend/auth`
(Go)'s `Service`, so a project migrating onto this module gets the same
standardized wire format that Go consumers of that engine already have.
## `logshipper`: mirroring logs to OmniLogger
`shared_backend.logshipper` is the Python counterpart of `shared/backend/logshipper`
(Go): it sends log entries to the workspace's central OmniLogger, and it is additive.
A service keeps its console logging as it is and adds an `OmniLoggerHandler` beside
its existing handlers, so each record also reaches OmniLogger:
```python
import logging
from shared_backend import OmniLoggerHandler, Shipper
shipper = Shipper.from_env("myservice", level="info") # None unless both env vars are set
if shipper is not None:
logging.getLogger().addHandler(OmniLoggerHandler(shipper))
...
if shipper is not None:
shipper.close() # on graceful shutdown; also runs at interpreter exit
```
`from_env` reads `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` and returns `None` when
either is unset or empty, so a disabled service makes no network calls and logs
exactly as before. The `level` argument is the threshold (`debug`, `info`, `warn`,
`error`, `critical`, or `silent`); it defaults to `info`.
`set_credentials(base_url, token)` changes where entries are sent, and the ingest token
used, while the service runs. It is thread-safe and takes effect from the next flush, and
the background thread keeps running. An empty base URL or token disables shipping: entries
are no longer buffered, anything already buffered is dropped, and console output is
unchanged. `Shipper(base_url="", ingest_token="", service=...)` builds a disabled shipper
up front, so a push from ProjectConfigurator can enable it later (see `coreconfig` above).
The handler maps `DEBUG`, `INFO`, `WARNING`, `ERROR` and `CRITICAL` to `debug`, `info`,
`warn`, `error` and `critical`. Entries are batched in a daemon thread and sent every 2
seconds, or as soon as 100 are buffered, with a 5-second HTTP timeout and bearer auth.
The buffer holds 2000 entries and drops new ones when full. Failures and drops are
reported on stderr at most once a minute and never raise into the caller.
Entries are clamped before buffering, because OmniLogger rejects a whole batch when
one entry breaks a limit. A message over 8192 bytes is cut on a character boundary
and given a ` [truncated]` suffix. A context over 16384 bytes, or one containing a NUL,
becomes `{"context_dropped":true}`. A NUL in a message is written as the text `\u0000`.
Batches are split to stay within 1000 entries and under 2 MiB per request. `Shipper`
never prints, so the service's own console output is unchanged.
@@ -28,9 +28,16 @@ from .authclient import (
token_from_request,
)
from .config import DatabaseConfig, database_url_from_env
from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches, internal_secret_usable
from .coreconfig import (
MIN_INTERNAL_SECRET_LENGTH,
follow_omnilogger,
handle_core_services_push,
internal_secret_matches,
internal_secret_usable,
)
from .coreconfig import Info as CoreConfigInfo
from .coreconfig import Store as CoreConfigStore
from .logshipper import OmniLoggerHandler, Shipper
from .postgres import Database
from .tokens import hash_token, new_session_token
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp, verify_totp_step
@@ -46,6 +53,8 @@ __all__ = [
"token_from_request",
"CoreConfigInfo",
"CoreConfigStore",
"follow_omnilogger",
"handle_core_services_push",
"internal_secret_matches",
"internal_secret_usable",
"MIN_INTERNAL_SECRET_LENGTH",
@@ -65,6 +74,8 @@ __all__ = [
"hash_token",
"new_session_token",
"normalize_role",
"OmniLoggerHandler",
"Shipper",
"password_hash_needs_upgrade",
"totp_provisioning_uri",
"verify_and_upgrade_password",
@@ -7,22 +7,28 @@ ProjectConfigurator/README.md's "Pushing core service info to other
projects" section for the wire contract this module implements the
receiving end of.
It also carries OmniLogger's URL and this service's ingest token (see `Info`).
`follow_omnilogger` keeps a log shipper's credentials in step with those pushes,
and `handle_core_services_push` is the framework-neutral body of the
PUT /api/core-services/internal route.
Framework-agnostic, like the rest of this package (see the top-level
README's "HTTP framework adapters stay in each service" note): this module
has no HTTP server of its own. A service wires the actual
has no HTTP server of its own. A service mounts the actual
PUT /api/core-services/internal route in its own framework (FastAPI,
aiohttp, ...), gated behind its own SECRET check the same
way its other internal-service routes already are, decodes the JSON body
into an `Info`, and calls `Store.set(info)` -- see `Store.set`'s doc comment
for a minimal FastAPI example.
aiohttp, ...) and passes the raw body to `handle_core_services_push`, which
returns (status, body) for the service to send -- see that function's doc
comment for a minimal FastAPI example.
"""
from __future__ import annotations
import dataclasses
import hmac
import json
import threading
from dataclasses import dataclass, field
from typing import Callable, Optional
from typing import Callable, Optional, Protocol
from urllib.parse import urlsplit
MIN_INTERNAL_SECRET_LENGTH = 16
@@ -76,6 +82,12 @@ class Info:
# registered, in priority order (the first entry is the same as
# carrier_node_url).
carrier_node_urls: list = field(default_factory=list)
# omni_logger_url is OmniLogger's base URL, the instance that receives this
# service's log entries (Go: coreconfig.Info.OmniLoggerURL).
omni_logger_url: str = ""
# omni_logger_ingest_token is this service's OmniLogger ingest token. repr=False
# keeps it out of logs and reprs. to_json never includes it (see below).
omni_logger_ingest_token: str = field(default="", repr=False)
@classmethod
def from_json(cls, data: dict) -> "Info":
@@ -88,13 +100,18 @@ class Info:
auth_guard_url=str(data.get("authGuardUrl") or "").strip(),
carrier_node_url=urls[0] if urls else "",
carrier_node_urls=urls,
omni_logger_url=str(data.get("omniLoggerUrl") or "").strip(),
omni_logger_ingest_token=str(data.get("omniLoggerIngestToken") or "").strip(),
)
def to_json(self) -> dict:
# omniLoggerIngestToken is deliberately left out: a to_json result may be sent back
# to a caller, and the token must never be echoed.
return {
"authGuardUrl": self.auth_guard_url,
"carrierNodeUrl": self.carrier_node_url,
"carrierNodeUrls": list(self.carrier_node_urls),
"omniLoggerUrl": self.omni_logger_url,
}
@@ -110,6 +127,7 @@ class Store:
self._lock = threading.Lock()
self._info = _normalize(fallback or Info())
self._on_update: Optional[Callable[[Info], None]] = None
self._subscribers: list[Callable[[Info], None]] = []
def get(self) -> Info:
with self._lock:
@@ -136,26 +154,25 @@ class Store:
with self._lock:
self._on_update = fn
def subscribe(self, fn: Callable[[Info], None]) -> None:
"""Registers fn to be called (synchronously, so keep it fast) with the new Info after every
set(), in addition to on_update's single callback, which it does not replace. Use it when
more than one component follows the pushed values, such as an AuthClient and a log shipper
(see follow_omnilogger). Subscribers cannot be removed; they live as long as the Store."""
with self._lock:
self._subscribers.append(fn)
def set(self, next_info: Info) -> Info:
"""Replaces the current Info, field by field, ignoring a
blank/empty field so a partial push (e.g. only carrierNodeUrl(s)
changed) never clobbers the other value. Returns the resulting
Info. Every URL must be an http or https URL with a host; otherwise
nothing is changed and ValueError is raised. Minimal FastAPI usage:
@app.put("/api/core-services/internal")
async def push_core_services(request: Request):
if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET):
raise HTTPException(status_code=401)
body = await request.json()
try:
info = core_config_store.set(Info.from_json(body))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"ok": True, "info": info.to_json()}
"""
Info (a copy). Every URL must be an http or https URL with a host;
otherwise nothing is changed and ValueError is raised. The receiving
route is normally handle_core_services_push, which calls this; see its
doc comment for the FastAPI wiring."""
next_info = _normalize(next_info)
for url in [next_info.auth_guard_url, *next_info.carrier_node_urls]:
urls = [next_info.auth_guard_url, next_info.omni_logger_url, *next_info.carrier_node_urls]
for url in urls:
if url and not _is_service_url(url):
raise ValueError(
f"core service URL must be an http or https URL with a host: {url}"
@@ -166,10 +183,19 @@ class Store:
if next_info.carrier_node_urls:
self._info.carrier_node_urls = next_info.carrier_node_urls
self._info.carrier_node_url = next_info.carrier_node_urls[0]
current = self._info
if next_info.omni_logger_url:
self._info.omni_logger_url = next_info.omni_logger_url
if next_info.omni_logger_ingest_token:
self._info.omni_logger_ingest_token = next_info.omni_logger_ingest_token
current = dataclasses.replace(
self._info, carrier_node_urls=list(self._info.carrier_node_urls)
)
callback = self._on_update
subscribers = list(self._subscribers)
if callback is not None:
callback(current)
for fn in subscribers:
fn(current)
return current
@@ -181,4 +207,89 @@ def _normalize(info: Info) -> Info:
auth_guard_url=info.auth_guard_url.strip(),
carrier_node_url=cleaned[0] if cleaned else "",
carrier_node_urls=cleaned,
omni_logger_url=info.omni_logger_url.strip().rstrip("/"),
omni_logger_ingest_token=info.omni_logger_ingest_token.strip(),
)
class SupportsSetCredentials(Protocol):
"""What follow_omnilogger needs from a log shipper: logshipper.Shipper satisfies it."""
def set_credentials(self, base_url: str, token: str) -> None: ...
def follow_omnilogger(store: Store, shipper: SupportsSetCredentials) -> None:
"""Keeps shipper's OmniLogger endpoint and ingest token in step with pushes, as Go's
logshipper.Shipper.Follow does. Whenever a set() leaves both omniLoggerUrl and
omniLoggerIngestToken non-empty in the store, shipper.set_credentials(url, token) is called.
Until both are stored, the shipper is left alone, so a push with a token but no URL never
disables or re-points an environment-configured shipper.
Call it once at startup, after creating the shipper. The Store must not be seeded with
OmniLogger values from the environment: those belong to the shipper, and seeding them would
make a token-only push re-point it."""
def apply(info: Info) -> None:
if info.omni_logger_url and info.omni_logger_ingest_token:
shipper.set_credentials(info.omni_logger_url, info.omni_logger_ingest_token)
apply(store.get())
store.subscribe(apply)
MAX_PUSH_BODY_BYTES = 4096
"""Largest PUT /api/core-services/internal body that handle_core_services_push reads."""
PUSH_AUTH_ERROR = "internal service authentication required"
PUSH_INVALID_JSON_ERROR = "invalid JSON body"
PUSH_INVALID_URL_ERROR = "core service URL must be an http or https URL with a host"
def handle_core_services_push(
store: Store,
secret: Optional[str],
provided_auth: Optional[str],
body: bytes,
) -> tuple[int, dict]:
"""The framework-neutral body of PUT /api/core-services/internal, the route
ProjectConfigurator pushes to. It returns (status, json_body) for the service to send.
- provided_auth is the X-Internal-Auth header (None when absent). A provided value that does
not equal secret, or any secret that is not usable (see internal_secret_usable), gets 401.
- body is the raw request body. Over MAX_PUSH_BODY_BYTES, or not a JSON object, gets 400.
- A non-empty omniLoggerUrl, authGuardUrl or carrierNodeUrl(s) value that is not an http or
https URL with a host gets 400 (Store.set validates them). Other fields are ignored.
- Success is 200 {"ok": True}. The response never includes the ingest token.
Mount it at PUT /api/core-services/internal, for example in FastAPI:
@app.put("/api/core-services/internal")
async def push_core_services(request: Request):
status, body = handle_core_services_push(
core_config_store, SECRET, request.headers.get("X-Internal-Auth"),
await request.body(),
)
return JSONResponse(body, status_code=status)
"""
if not internal_secret_matches(provided_auth, secret):
return 401, {"error": PUSH_AUTH_ERROR}
if len(body) > MAX_PUSH_BODY_BYTES:
return 400, {"error": PUSH_INVALID_JSON_ERROR}
try:
data = json.loads(body)
except (ValueError, RecursionError): # JSONDecodeError and UnicodeDecodeError are ValueErrors
return 400, {"error": PUSH_INVALID_JSON_ERROR}
if not isinstance(data, dict):
return 400, {"error": PUSH_INVALID_JSON_ERROR}
# Info.from_json reads these fields; a wrong type gets 400 here instead of an error inside it.
for key in ("authGuardUrl", "carrierNodeUrl", "omniLoggerUrl", "omniLoggerIngestToken"):
if data.get(key) is not None and not isinstance(data[key], str):
return 400, {"error": PUSH_INVALID_JSON_ERROR}
urls = data.get("carrierNodeUrls")
if urls is not None and not isinstance(urls, list):
return 400, {"error": PUSH_INVALID_JSON_ERROR}
try:
store.set(Info.from_json(data))
except ValueError:
return 400, {"error": PUSH_INVALID_URL_ERROR}
return 200, {"ok": True}
@@ -0,0 +1,415 @@
"""Client-side adapter for OmniLogger, the workspace's central log sink. Python counterpart of
shared/backend/logshipper (Go), and it follows the same wire contract.
Shipping is additive. A service keeps its own console logging unchanged and adds an
`OmniLoggerHandler` next to its existing handlers, so each record also reaches OmniLogger.
`Shipper` never prints anything itself.
Shipping is enabled only when both OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are set; see
`Shipper.from_env`, which returns None otherwise.
Entries are clamped to OmniLogger's limits before they are buffered, because OmniLogger rejects
a whole batch when any one entry breaks a limit. A batch that fails with a network error, an HTTP
5xx or 429 is kept and sent again on a later flush, while any other rejection is dropped. Nothing
here raises into the caller or blocks it: failures and a full buffer are reported with a
rate-limited line on stderr.
"""
from __future__ import annotations
import atexit
import json
import logging
import os
import sys
import threading
import time
import urllib.error
import urllib.request
from collections.abc import Iterator, Mapping
from datetime import datetime, timezone
from typing import Any
__all__ = ["OmniLoggerHandler", "Shipper", "to_omnilogger_level"]
ENV_URL = "OMNILOGGER_URL"
ENV_TOKEN = "OMNILOGGER_INGEST_TOKEN"
FLUSH_INTERVAL = 2.0 # seconds between background flushes
MAX_BATCH_SIZE = 100 # buffering this many entries flushes early
BUFFER_CAPACITY = 2000 # beyond this, new entries are dropped
HTTP_TIMEOUT = 5.0
WARN_INTERVAL = 60.0 # at most one stderr warning per this many seconds
# OmniLogger's limits (Central/OmniLogger/internal/httpapi/validate.go).
MAX_BATCH_ENTRIES = 1000
MAX_BODY_BYTES = 2 * 1024 * 1024
MAX_MESSAGE_BYTES = 8 * 1024
MAX_CONTEXT_BYTES = 16 * 1024
TRUNCATED_MARKER = " [truncated]"
DROPPED_CONTEXT = '{"context_dropped":true}'
# Severity ranks, matching the Go shipper's scale (debug 10 ... critical 50).
_RANKS = {"debug": 10, "info": 20, "warn": 30, "error": 40, "critical": 50}
_SILENT = 100
_LEVEL_NAMES = {
"debug": "debug",
"info": "info",
"warn": "warn",
"warning": "warn",
"error": "error",
"critical": "critical",
}
_THRESHOLD_RANKS = {**_RANKS, "silent": _SILENT, "none": _SILENT, "off": _SILENT}
def to_omnilogger_level(levelno: int) -> str:
"""Maps a standard-library logging level number to OmniLogger's level name.
DEBUG, INFO, WARNING, ERROR and CRITICAL map to debug, info, warn, error and critical. A level
between two of them takes the name of the lower one, and anything below INFO is debug.
"""
if levelno >= logging.CRITICAL:
return "critical"
if levelno >= logging.ERROR:
return "error"
if levelno >= logging.WARNING:
return "warn"
if levelno >= logging.INFO:
return "info"
return "debug"
class _NoRedirect(urllib.request.HTTPRedirectHandler):
"""Refuses redirects, so the bearer token only ever goes to the configured URL."""
def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001, ARG002
return None
_OPENER = urllib.request.build_opener(_NoRedirect)
def _json_text(value: str) -> str:
return json.dumps(value, ensure_ascii=False)
def _clean_message(message: object) -> str:
# OmniLogger rejects a message with a NUL byte (PostgreSQL cannot store it) and then rejects the
# whole batch, so NUL is written as its escape text. Lone surrogates cannot be encoded as UTF-8.
text = message if isinstance(message, str) else str(message)
text = text.replace("\x00", "\\u0000")
return text.encode("utf-8", "replace").decode("utf-8")
def _clamp_message(text: str) -> str:
data = text.encode("utf-8")
if len(data) <= MAX_MESSAGE_BYTES:
return text
cut = MAX_MESSAGE_BYTES - len(TRUNCATED_MARKER.encode("utf-8"))
# Decoding with "ignore" drops a character that the cut split in half, so the cut lands on a
# character boundary.
return data[:cut].decode("utf-8", "ignore") + TRUNCATED_MARKER
def _clamp_context(context: Mapping[str, Any]) -> str:
try:
raw = json.dumps(
dict(context), ensure_ascii=False, separators=(",", ":"), default=str, allow_nan=False
)
except (TypeError, ValueError, RecursionError):
return DROPPED_CONTEXT
# json.dumps writes a NUL as the escape \u0000, which OmniLogger refuses in context.
if "\\u0000" in raw or len(raw.encode("utf-8", "replace")) > MAX_CONTEXT_BYTES:
return DROPPED_CONTEXT
return raw
def _timestamp() -> str:
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
def _encode_entry(
service: str, level: str, message: object, context: Mapping[str, Any] | None
) -> bytes:
fields = [
f'"service":{_json_text(service)}',
f'"level":"{level}"',
f'"message":{_json_text(_clamp_message(_clean_message(message)))}',
]
if context is not None:
fields.append(f'"context":{_clamp_context(context)}')
fields.append(f'"occurred_at":"{_timestamp()}"')
return ("{" + ",".join(fields) + "}").encode("utf-8", "replace")
def _batch_bodies(entries: list[bytes]) -> Iterator[tuple[bytes, int]]:
"""Groups encoded entries into request bodies of at most MAX_BATCH_ENTRIES entries and under
MAX_BODY_BYTES bytes each. Yields (body, entry count)."""
group: list[bytes] = []
size = 2 # the enclosing brackets
for entry in entries:
extra = len(entry) + (1 if group else 0) # the comma before it, if any
if group and (len(group) >= MAX_BATCH_ENTRIES or size + extra >= MAX_BODY_BYTES):
yield b"[" + b",".join(group) + b"]", len(group)
group, size, extra = [], 2, len(entry)
group.append(entry)
size += extra
if group:
yield b"[" + b",".join(group) + b"]", len(group)
class Shipper:
"""Buffers log entries and sends them to OmniLogger in batches from a background thread.
Create one at startup with `Shipper.from_env(service)` and call `close()` on graceful shutdown.
`close()` also runs at interpreter exit (atexit), so a final flush happens even without it.
A Shipper is safe to use from many threads.
"""
def __init__(
self,
*,
base_url: str,
ingest_token: str,
service: str,
level: str | None = None,
flush_interval: float = FLUSH_INTERVAL,
max_batch_size: int = MAX_BATCH_SIZE,
buffer_capacity: int = BUFFER_CAPACITY,
http_timeout: float = HTTP_TIMEOUT,
) -> None:
"""`level` is the threshold, using the same names as the services' LOG setting (debug, info,
warn, error, critical, silent). It defaults to info."""
self._service = service
self._threshold = _THRESHOLD_RANKS.get((level or "info").strip().lower(), _RANKS["info"])
self._flush_interval = flush_interval if flush_interval > 0 else FLUSH_INTERVAL
self._max_batch_size = max_batch_size
self._buffer_capacity = buffer_capacity
self._http_timeout = http_timeout
self._buffer: list[bytes] = []
self._buffer_lock = threading.Lock()
self._cred_lock = threading.Lock()
self._url: str | None = None # None while shipping is disabled
self._token = ""
self.set_credentials(base_url, ingest_token)
self._wake = threading.Event()
self._stop = threading.Event()
self._close_lock = threading.Lock()
self._closed = False
self._warn_lock = threading.Lock()
self._last_warn: float | None = None
self._thread = threading.Thread(target=self._run, name=f"logshipper-{service}", daemon=True)
self._thread.start()
atexit.register(self.close)
@classmethod
def from_env(
cls,
service: str,
*,
level: str | None = None,
environ: Mapping[str, str] | None = None,
) -> Shipper | None:
"""Returns a Shipper configured from OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN, or None
when either is unset or empty, which leaves the service with no shipping at all."""
env = os.environ if environ is None else environ
url = (env.get(ENV_URL) or "").strip()
token = (env.get(ENV_TOKEN) or "").strip()
if not url or not token:
return None
return cls(base_url=url, ingest_token=token, service=service, level=level)
def handler(self, level: int = logging.NOTSET) -> OmniLoggerHandler:
"""Returns a logging handler that ships records to this Shipper."""
return OmniLoggerHandler(self, level)
def set_credentials(self, base_url: str, token: str) -> None:
"""Sets where, and as which ingest token, entries are sent. It is thread-safe, takes effect
from the next flush, and does not restart the background thread.
An empty base URL or token disables shipping: entries are no longer buffered, anything
already buffered is dropped, and the service's own console output carries on unchanged.
Otherwise entries go to `base_url` + "/api/logs" with `token` as the bearer token."""
base = (base_url or "").strip().rstrip("/")
token = (token or "").strip()
url = base + "/api/logs" if base and token else None
with self._cred_lock:
self._url = url
self._token = token
if url is None:
with self._buffer_lock:
self._buffer = []
def _enabled(self) -> bool:
with self._cred_lock:
return self._url is not None
def log(self, level: str, message: str, context: Mapping[str, Any] | None = None) -> None:
"""Queues one entry. `level` is debug, info, warn (or warning), error or critical; any
other value is sent as info. `context` is an optional mapping sent as JSON."""
name = _LEVEL_NAMES.get(str(level).strip().lower(), "info")
if _RANKS[name] < self._threshold or not self._enabled():
return
try:
entry = _encode_entry(self._service, name, message, context)
except Exception: # noqa: BLE001 - a log sink must never fail its host
return
self._buffer_entry(entry)
def debug(self, message: str, context: Mapping[str, Any] | None = None) -> None:
self.log("debug", message, context)
def info(self, message: str, context: Mapping[str, Any] | None = None) -> None:
self.log("info", message, context)
def warning(self, message: str, context: Mapping[str, Any] | None = None) -> None:
self.log("warn", message, context)
def error(self, message: str, context: Mapping[str, Any] | None = None) -> None:
self.log("error", message, context)
def critical(self, message: str, context: Mapping[str, Any] | None = None) -> None:
self.log("critical", message, context)
def flush(self) -> None:
"""Sends everything buffered now, in the calling thread. A batch that fails for a reason
that may pass (no connection, HTTP 5xx or 429) stays in the buffer with every later entry of
this flush, in order, and the rest of the flush waits for the next one. Other failures are
only reported on stderr, and at most once a minute."""
with self._buffer_lock:
if not self._buffer:
return
pending, self._buffer = self._buffer, []
sent = 0
for body, count in _batch_bodies(pending):
if self._post(body, count):
self._requeue(pending[sent:])
return
sent += count
def _requeue(self, entries: list[bytes]) -> None:
"""Puts entries that failed to send back at the front of the buffer, so the next flush
sends them before newer entries. The buffer stays within its capacity: when the waiting
entries and the buffer do not all fit, the newest entries are dropped, as _buffer_entry
drops them."""
with self._buffer_lock:
if not self._enabled():
return # shipping was disabled during the flush, so these go with the buffer
combined = entries + self._buffer
dropped = max(0, len(combined) - self._buffer_capacity)
self._buffer = combined[: self._buffer_capacity]
if dropped:
self._warn(
f"buffer full while retrying, dropping {dropped} log entries for service "
f"{self._service!r}"
)
def close(self) -> None:
"""Stops the background thread after a final flush of whatever is buffered. Safe to call
more than once."""
with self._close_lock:
if self._closed:
return
self._closed = True
self._stop.set()
self._wake.set()
if threading.current_thread() is not self._thread:
self._thread.join()
self.flush()
atexit.unregister(self.close)
def _buffer_entry(self, entry: bytes) -> None:
if self._closed or not self._enabled():
return
with self._buffer_lock:
full = len(self._buffer) >= self._buffer_capacity
if not full:
self._buffer.append(entry)
ready = len(self._buffer) >= self._max_batch_size
if full:
self._warn(
f"buffer full (cap={self._buffer_capacity}), dropping log entries for service "
f"{self._service!r}"
)
elif ready:
self._wake.set()
def _run(self) -> None:
while not self._stop.is_set():
self._wake.wait(self._flush_interval)
# Cleared before the flush takes its snapshot, so an entry that arrives during the
# flush sets the event again and is not left waiting for the next interval.
self._wake.clear()
if self._stop.is_set():
break
try:
self.flush()
except Exception: # noqa: BLE001 - keep the background thread alive
pass
def _post(self, body: bytes, count: int) -> bool:
"""Sends one request body. Returns True when it failed for a reason that may pass (no
connection, HTTP 5xx or 429), so the caller keeps its entries for a later flush. A request
OmniLogger rejects with any other status is reported and dropped, and returns False."""
with self._cred_lock:
url, token = self._url, self._token
if url is None:
return False # shipping was disabled after these entries were taken for a flush
request = urllib.request.Request(
url,
data=body,
method="POST",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
},
)
try:
with _OPENER.open(request, timeout=self._http_timeout):
return False
except urllib.error.HTTPError as exc:
exc.close()
if exc.code == 429 or exc.code >= 500:
self._warn(f"OmniLogger answered HTTP {exc.code} for {count} entries, will retry")
return True
self._warn(f"OmniLogger rejected {count} entries: HTTP {exc.code}")
return False
except Exception as exc: # noqa: BLE001 - unreachable or misconfigured sink
self._warn(f"send {count} entries to {url}: {exc}")
return True
def _warn(self, detail: str) -> None:
now = time.monotonic()
with self._warn_lock:
if self._last_warn is not None and now - self._last_warn < WARN_INTERVAL:
return
self._last_warn = now
try:
stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
sys.stderr.write(f"[{stamp}] [logshipper] logshipper: {detail}\n")
sys.stderr.flush()
except Exception: # noqa: BLE001 - stderr may be closed or missing
pass
class OmniLoggerHandler(logging.Handler):
"""A logging handler that ships each record to a Shipper and writes nothing locally.
Keep the service's own console handler and add this one beside it, so the console output is
unchanged. The shipped message is the record's formatted message, with any traceback appended.
The record's logger name goes in the entry's context.
"""
def __init__(self, shipper: Shipper, level: int = logging.NOTSET) -> None:
super().__init__(level)
self._shipper = shipper
def emit(self, record: logging.LogRecord) -> None:
try:
message = self.format(record)
self._shipper.log(to_omnilogger_level(record.levelno), message, {"logger": record.name})
except Exception: # noqa: BLE001 - a log sink must never fail its host
pass
@@ -1,9 +1,12 @@
import json
import unittest
from shared_backend.coreconfig import (
MIN_INTERNAL_SECRET_LENGTH,
Info,
Store,
follow_omnilogger,
handle_core_services_push,
internal_secret_matches,
internal_secret_usable,
)
@@ -117,5 +120,192 @@ class UrlValidationTests(unittest.TestCase):
self.assertEqual(store.auth_guard_url, "http://auth.example.com")
class OmniLoggerStoreTests(unittest.TestCase):
def test_from_json_reads_omni_fields_and_to_json_never_carries_the_token(self):
info = Info.from_json(
{"omniLoggerUrl": "http://omni.example.com", "omniLoggerIngestToken": "tok-123"}
)
self.assertEqual(info.omni_logger_url, "http://omni.example.com")
self.assertEqual(info.omni_logger_ingest_token, "tok-123")
self.assertEqual(info.to_json()["omniLoggerUrl"], "http://omni.example.com")
self.assertNotIn("omniLoggerIngestToken", info.to_json())
self.assertNotIn("tok-123", json.dumps(info.to_json()))
self.assertNotIn("tok-123", repr(info))
def test_keeps_last_non_blank_values_and_strips_the_trailing_slash(self):
store = Store()
store.set(
Info(omni_logger_url="http://omni.example.com/", omni_logger_ingest_token="tok-1")
)
store.set(Info(omni_logger_url=" ", omni_logger_ingest_token=""))
info = store.get()
self.assertEqual(info.omni_logger_url, "http://omni.example.com")
self.assertEqual(info.omni_logger_ingest_token, "tok-1")
def test_a_bad_omni_url_is_refused_and_nothing_changes(self):
store = Store()
store.set(Info(omni_logger_url="http://omni.example.com", omni_logger_ingest_token="tok-1"))
for bad in ["omni.example.com", "ftp://omni.example.com", "http://"]:
with self.subTest(url=bad), self.assertRaises(ValueError):
store.set(Info(omni_logger_url=bad, omni_logger_ingest_token="tok-2"))
self.assertEqual(store.get().omni_logger_url, "http://omni.example.com")
self.assertEqual(store.get().omni_logger_ingest_token, "tok-1")
def test_subscribers_and_on_update_both_see_every_set(self):
store = Store()
from_on_update, from_subscriber = [], []
store.on_update(from_on_update.append)
store.subscribe(from_subscriber.append)
store.set(Info(auth_guard_url="http://auth.example.com"))
self.assertEqual(len(from_on_update), 1)
self.assertEqual(len(from_subscriber), 1)
self.assertEqual(from_subscriber[0].auth_guard_url, "http://auth.example.com")
class _RecordingShipper:
def __init__(self):
self.calls = []
def set_credentials(self, base_url, token):
self.calls.append((base_url, token))
class FollowOmniLoggerTests(unittest.TestCase):
def setUp(self):
self.store = Store()
self.shipper = _RecordingShipper()
follow_omnilogger(self.store, self.shipper)
def test_a_push_with_both_values_sets_the_shipper(self):
self.store.set(
Info(omni_logger_url="http://omni.example.com", omni_logger_ingest_token="tok-1")
)
self.assertEqual(self.shipper.calls, [("http://omni.example.com", "tok-1")])
def test_a_token_without_a_url_leaves_the_shipper_alone(self):
self.store.set(Info(omni_logger_ingest_token="tok-1"))
self.assertEqual(self.shipper.calls, [])
def test_a_url_pushed_after_a_token_applies_both(self):
self.store.set(Info(omni_logger_ingest_token="tok-1"))
self.store.set(Info(omni_logger_url="http://omni.example.com"))
self.assertEqual(self.shipper.calls, [("http://omni.example.com", "tok-1")])
def test_a_later_token_only_push_reuses_the_stored_url(self):
self.store.set(
Info(omni_logger_url="http://omni.example.com", omni_logger_ingest_token="tok-1")
)
self.store.set(Info(omni_logger_ingest_token="tok-2"))
self.assertEqual(
self.shipper.calls,
[("http://omni.example.com", "tok-1"), ("http://omni.example.com", "tok-2")],
)
def test_pushes_without_omni_fields_do_not_touch_the_shipper(self):
self.store.set(Info(auth_guard_url="http://auth.example.com"))
self.assertEqual(self.shipper.calls, [])
def test_a_store_without_omni_values_does_not_apply_at_startup(self):
follow_omnilogger(Store(), self.shipper)
self.assertEqual(self.shipper.calls, [])
INTERNAL_SECRET = "a-sufficiently-long-secret-value"
PUSH_BODY = {"omniLoggerUrl": "http://omni.example.com", "omniLoggerIngestToken": "tok-secret-1"}
AUTH_ERROR = {"error": "internal service authentication required"}
JSON_ERROR = {"error": "invalid JSON body"}
URL_ERROR = {"error": "core service URL must be an http or https URL with a host"}
class HandleCoreServicesPushTests(unittest.TestCase):
def setUp(self):
self.store = Store()
self.shipper = _RecordingShipper()
follow_omnilogger(self.store, self.shipper)
def push(self, body, auth=INTERNAL_SECRET, secret=INTERNAL_SECRET):
raw = body if isinstance(body, bytes) else json.dumps(body).encode("utf-8")
return handle_core_services_push(self.store, secret, auth, raw)
def test_a_missing_or_wrong_x_internal_auth_gets_401(self):
for auth in (None, "", "wrong-secret-value-here", INTERNAL_SECRET + "x"):
with self.subTest(auth=auth):
self.assertEqual(self.push(PUSH_BODY, auth=auth), (401, AUTH_ERROR))
self.assertEqual(self.shipper.calls, [])
self.assertEqual(self.store.get().omni_logger_url, "")
def test_an_unusable_secret_refuses_every_caller(self):
for secret in (None, "", "SECRET", "change-me-to-a-long-random-value", "short"):
with self.subTest(secret=secret):
status, _ = self.push(PUSH_BODY, auth=secret, secret=secret)
self.assertEqual(status, 401)
status, _ = self.push(PUSH_BODY, auth=INTERNAL_SECRET, secret=secret)
self.assertEqual(status, 401)
self.assertEqual(self.shipper.calls, [])
def test_a_valid_push_sets_the_shipper_and_never_echoes_the_token(self):
status, body = self.push(PUSH_BODY)
self.assertEqual((status, body), (200, {"ok": True}))
self.assertEqual(self.shipper.calls, [("http://omni.example.com", "tok-secret-1")])
self.assertNotIn("tok-secret-1", json.dumps(body))
def test_a_token_without_a_url_does_not_change_the_shipper(self):
status, body = self.push({"omniLoggerIngestToken": "tok-secret-1"})
self.assertEqual((status, body), (200, {"ok": True}))
self.assertEqual(self.shipper.calls, [])
def test_a_bad_omni_url_gets_400_and_changes_nothing(self):
for bad in ["omni.example.com", "ftp://omni.example.com", "javascript:alert(1)"]:
with self.subTest(url=bad):
body = {"omniLoggerUrl": bad, "omniLoggerIngestToken": "tok-secret-1"}
self.assertEqual(self.push(body), (400, URL_ERROR))
self.assertEqual(self.shipper.calls, [])
def test_a_bad_auth_guard_url_gets_400(self):
self.assertEqual(self.push({"authGuardUrl": "auth.example.com"}), (400, URL_ERROR))
def test_a_field_of_the_wrong_type_gets_400_not_a_server_error(self):
for body in (
{"carrierNodeUrls": 5},
{"carrierNodeUrls": True},
{"carrierNodeUrls": "http://carrier.example.com"},
{"carrierNodeUrl": ["http://carrier.example.com"]},
{"authGuardUrl": 5},
):
with self.subTest(body=body):
self.assertEqual(self.push(body), (400, JSON_ERROR))
self.assertEqual(self.shipper.calls, [])
def test_an_oversized_body_or_a_body_that_is_not_a_json_object_gets_400(self):
cases = [
json.dumps({"x": "a" * 4096}).encode("utf-8"),
b"not json",
b"[1, 2]",
b'"a string"',
b"\xff\xfe\x00",
json.dumps({"omniLoggerUrl": 5}).encode("utf-8"),
json.dumps({"omniLoggerIngestToken": ["tok"]}).encode("utf-8"),
]
for raw in cases:
with self.subTest(raw=raw[:20]):
self.assertEqual(self.push(raw), (400, JSON_ERROR))
def test_a_body_of_exactly_4096_bytes_is_read(self):
raw = json.dumps({"x": "a" * 4087}).encode("utf-8")
self.assertEqual(len(raw), 4096)
self.assertEqual(self.push(raw), (200, {"ok": True}))
def test_other_fields_and_null_values_are_ignored(self):
body = {
"contentScannerUrl": "not a url",
"comfyUiUrl": 7,
"carrierNodeSecret": "not-used-here",
"omniLoggerIngestToken": None,
"omniLoggerUrl": "http://omni.example.com",
}
self.assertEqual(self.push(body), (200, {"ok": True}))
self.assertEqual(self.shipper.calls, [])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,688 @@
import contextlib
import io
import json
import logging
import socket
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from unittest import mock
from shared_backend.logshipper import (
DROPPED_CONTEXT,
MAX_BATCH_ENTRIES,
MAX_BODY_BYTES,
MAX_CONTEXT_BYTES,
MAX_MESSAGE_BYTES,
TRUNCATED_MARKER,
OmniLoggerHandler,
Shipper,
to_omnilogger_level,
)
class _FakeOmniLogger:
"""Local stand-in for OmniLogger's POST /api/logs. It records every request. Each request is
answered with the next status in `statuses`, and with `status` once that list is used up.
Only requests answered with a 2xx count as delivered, so `batches()` and `entries()` leave out
the refused ones."""
def __init__(self, status: int = 202) -> None:
self.status = status
self.statuses: list[int] = []
self.requests: list[dict] = []
self._lock = threading.Lock()
fake = self
class Handler(BaseHTTPRequestHandler):
def do_POST(self): # noqa: N802 - http.server's naming
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length)
with fake._lock:
status = fake.statuses.pop(0) if fake.statuses else fake.status
fake.requests.append(
{
"path": self.path,
"authorization": self.headers.get("Authorization"),
"content_type": self.headers.get("Content-Type"),
"body": raw,
"status": status,
}
)
self.send_response(status)
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *args): # keep the test output quiet
pass
self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.url = f"http://127.0.0.1:{self._server.server_port}"
self._thread = threading.Thread(
target=self._server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True
)
self._thread.start()
def stop(self) -> None:
self._server.shutdown()
self._server.server_close()
def batches(self) -> list[list[dict]]:
with self._lock:
return [
json.loads(request["body"])
for request in self.requests
if 200 <= request["status"] < 300
]
def entries(self) -> list[dict]:
return [entry for batch in self.batches() for entry in batch]
def _unused_url() -> str:
"""A URL nothing listens on, so connecting to it is refused at once."""
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
return f"http://127.0.0.1:{port}"
def _wait_for(predicate, timeout: float = 5.0) -> bool:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return True
time.sleep(0.01)
return predicate()
class ShipperTestCase(unittest.TestCase):
def setUp(self) -> None:
self.omni = _FakeOmniLogger()
self.addCleanup(self.omni.stop)
def make_shipper(self, **overrides) -> Shipper:
"""A shipper that does not flush on its own, so each test decides when entries go out."""
options = {
"base_url": self.omni.url,
"ingest_token": "secret-token",
"service": "svc",
"flush_interval": 3600,
}
options.update(overrides)
shipper = Shipper(**options)
self.addCleanup(shipper.close)
return shipper
class BatchingTests(ShipperTestCase):
def test_flush_sends_every_buffered_entry_in_one_request(self):
shipper = self.make_shipper()
shipper.info("one")
shipper.error("two")
shipper.flush()
shipper.flush() # nothing left, so no second request
self.assertEqual(len(self.omni.requests), 1)
self.assertEqual([e["message"] for e in self.omni.entries()], ["one", "two"])
def test_reaching_the_batch_size_flushes_without_waiting_for_the_interval(self):
shipper = self.make_shipper(max_batch_size=2)
shipper.info("a")
shipper.info("b")
self.assertTrue(_wait_for(lambda: len(self.omni.entries()) == 2))
def test_the_interval_flushes_a_partial_batch(self):
shipper = self.make_shipper(flush_interval=0.05)
shipper.info("lone entry")
self.assertTrue(_wait_for(lambda: len(self.omni.entries()) == 1))
def test_a_batch_never_exceeds_1000_entries(self):
shipper = self.make_shipper(max_batch_size=10**6, buffer_capacity=5000)
for i in range(2500):
shipper.info(f"entry {i}")
shipper.flush()
batches = self.omni.batches()
self.assertTrue(all(len(batch) <= MAX_BATCH_ENTRIES for batch in batches))
self.assertEqual(sum(len(batch) for batch in batches), 2500)
self.assertEqual(self.omni.entries()[-1]["message"], "entry 2499")
def test_a_batch_body_stays_under_2_mib(self):
shipper = self.make_shipper(max_batch_size=10**6, buffer_capacity=1000)
for _ in range(600):
shipper.info("x" * MAX_MESSAGE_BYTES) # about 8 KiB each, so 600 cannot fit in one body
shipper.flush()
self.assertGreater(len(self.omni.requests), 1)
self.assertTrue(all(len(r["body"]) < MAX_BODY_BYTES for r in self.omni.requests))
self.assertEqual(len(self.omni.entries()), 600)
def test_close_sends_what_is_left_and_is_idempotent(self):
shipper = self.make_shipper()
shipper.info("last words")
shipper.close()
shipper.close()
self.assertEqual([e["message"] for e in self.omni.entries()], ["last words"])
def test_logging_after_close_is_ignored(self):
shipper = self.make_shipper()
shipper.close()
shipper.info("too late")
shipper.flush()
self.assertEqual(self.omni.requests, [])
class WireFormatTests(ShipperTestCase):
def test_request_uses_bearer_auth_json_and_the_api_logs_path(self):
shipper = self.make_shipper(base_url=self.omni.url + "/")
shipper.info("hello")
shipper.flush()
request = self.omni.requests[0]
self.assertEqual(request["path"], "/api/logs")
self.assertEqual(request["authorization"], "Bearer secret-token")
self.assertEqual(request["content_type"], "application/json")
def test_every_entry_carries_the_service_name(self):
shipper = self.make_shipper(service="heretic")
shipper.info("a")
shipper.critical("b")
shipper.flush()
self.assertEqual({e["service"] for e in self.omni.entries()}, {"heretic"})
def test_entry_fields_and_occurred_at_format(self):
shipper = self.make_shipper()
shipper.warning("careful", {"path": "/x", "status": 503})
shipper.info("plain")
shipper.flush()
warned, plain = self.omni.entries()
self.assertEqual(warned["level"], "warn")
self.assertEqual(warned["context"], {"path": "/x", "status": 503})
self.assertNotIn("context", plain)
for entry in (warned, plain):
self.assertRegex(entry["occurred_at"], r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$")
def test_context_is_sent_unscrubbed(self):
shipper = self.make_shipper()
shipper.info("request", {"userId": 7})
shipper.flush()
self.assertEqual(self.omni.entries()[0]["context"], {"userId": 7})
class ClampingTests(ShipperTestCase):
def test_a_long_message_is_cut_on_a_character_boundary_with_the_marker(self):
shipper = self.make_shipper()
shipper.info("é" * 5000) # 10000 bytes, and 8181 is an odd byte count to cut at
shipper.flush()
message = self.omni.entries()[0]["message"]
self.assertLessEqual(len(message.encode("utf-8")), MAX_MESSAGE_BYTES)
self.assertTrue(message.endswith(TRUNCATED_MARKER))
self.assertTrue(set(message[: -len(TRUNCATED_MARKER)]) <= {"é"})
def test_a_message_of_exactly_the_limit_is_untouched(self):
shipper = self.make_shipper()
exact = "y" * MAX_MESSAGE_BYTES
shipper.info(exact)
shipper.flush()
self.assertEqual(self.omni.entries()[0]["message"], exact)
def test_a_nul_byte_in_a_message_is_written_as_escape_text(self):
shipper = self.make_shipper()
shipper.info("before\x00after")
shipper.flush()
self.assertEqual(self.omni.entries()[0]["message"], "before\\u0000after")
def test_an_oversized_context_is_replaced_by_the_dropped_marker(self):
shipper = self.make_shipper()
shipper.info("big", {"blob": "x" * MAX_CONTEXT_BYTES})
shipper.flush()
entry = self.omni.entries()[0]
self.assertEqual(entry["context"], {"context_dropped": True})
self.assertEqual(entry["message"], "big")
def test_a_context_with_a_nul_is_replaced_but_an_ordinary_one_is_kept(self):
shipper = self.make_shipper()
shipper.info("nul", {"s": "a\x00b"})
shipper.info("fine", {"ok": True})
shipper.flush()
nul, fine = self.omni.entries()
self.assertEqual(json.loads(DROPPED_CONTEXT), nul["context"])
self.assertEqual(fine["context"], {"ok": True})
def test_an_unserialisable_context_is_replaced_not_lost(self):
shipper = self.make_shipper()
shipper.info("nan", {"value": float("nan")})
shipper.flush()
entry = self.omni.entries()[0]
self.assertEqual(entry["message"], "nan")
self.assertEqual(entry["context"], {"context_dropped": True})
class DisabledModeTests(unittest.TestCase):
def test_from_env_returns_none_unless_both_variables_are_set(self):
cases = [
{},
{"OMNILOGGER_URL": "http://omni:8080"},
{"OMNILOGGER_INGEST_TOKEN": "token"},
{"OMNILOGGER_URL": "", "OMNILOGGER_INGEST_TOKEN": "token"},
{"OMNILOGGER_URL": "http://omni:8080", "OMNILOGGER_INGEST_TOKEN": " "},
]
for environ in cases:
with self.subTest(environ=environ):
self.assertIsNone(Shipper.from_env("svc", environ=environ))
def test_from_env_builds_a_shipper_when_both_are_set(self):
omni = _FakeOmniLogger()
self.addCleanup(omni.stop)
shipper = Shipper.from_env(
"heretic",
environ={"OMNILOGGER_URL": omni.url, "OMNILOGGER_INGEST_TOKEN": "tok"},
level="warn",
)
self.addCleanup(shipper.close)
self.assertIsNotNone(shipper)
shipper.info("below the warn threshold")
shipper.error("shipped")
shipper.flush()
self.assertEqual([e["message"] for e in omni.entries()], ["shipped"])
self.assertEqual(omni.requests[0]["authorization"], "Bearer tok")
self.assertEqual(omni.entries()[0]["service"], "heretic")
def test_from_env_reads_os_environ_by_default(self):
omni = _FakeOmniLogger()
self.addCleanup(omni.stop)
with mock.patch.dict(
"os.environ",
{"OMNILOGGER_URL": omni.url, "OMNILOGGER_INGEST_TOKEN": "env-token"},
):
shipper = Shipper.from_env("svc")
self.assertIsNotNone(shipper)
self.addCleanup(shipper.close)
def test_disabled_logging_makes_no_network_calls_and_prints_nothing_extra(self):
omni = _FakeOmniLogger()
self.addCleanup(omni.stop)
stdout, stderr = io.StringIO(), io.StringIO()
logger = logging.getLogger("tests.logshipper.disabled")
logger.addHandler(logging.StreamHandler(stdout))
logger.setLevel(logging.INFO)
self.addCleanup(logger.handlers.clear)
with contextlib.redirect_stderr(stderr):
shipper = Shipper.from_env("svc", environ={})
logger.info("local only")
self.assertIsNone(shipper)
self.assertEqual(omni.requests, [])
self.assertEqual(stderr.getvalue(), "")
self.assertEqual(stdout.getvalue(), "local only\n")
class LevelMappingTests(ShipperTestCase):
def test_standard_levels_map_to_omnilogger_names(self):
self.assertEqual(
[
to_omnilogger_level(logging.DEBUG),
to_omnilogger_level(logging.INFO),
to_omnilogger_level(logging.WARNING),
to_omnilogger_level(logging.ERROR),
to_omnilogger_level(logging.CRITICAL),
],
["debug", "info", "warn", "error", "critical"],
)
def test_levels_between_standard_ones_take_the_lower_name(self):
self.assertEqual(to_omnilogger_level(25), "info")
self.assertEqual(to_omnilogger_level(35), "warn")
self.assertEqual(to_omnilogger_level(55), "critical")
self.assertEqual(to_omnilogger_level(5), "debug")
def test_handler_ships_each_record_at_its_mapped_level(self):
shipper = self.make_shipper(level="debug")
logger = logging.getLogger("tests.logshipper.levels")
logger.handlers.clear()
logger.addHandler(OmniLoggerHandler(shipper))
logger.setLevel(logging.DEBUG)
logger.propagate = False
self.addCleanup(setattr, logger, "propagate", True)
self.addCleanup(logger.handlers.clear)
logger.debug("d")
logger.info("i")
logger.warning("w")
logger.error("e")
logger.critical("c")
shipper.flush()
entries = self.omni.entries()
self.assertEqual(
[(e["level"], e["message"]) for e in entries],
[("debug", "d"), ("info", "i"), ("warn", "w"), ("error", "e"), ("critical", "c")],
)
self.assertEqual({e["context"]["logger"] for e in entries}, {"tests.logshipper.levels"})
def test_handler_writes_nothing_locally(self):
shipper = self.make_shipper()
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
OmniLoggerHandler(shipper).handle(
logging.LogRecord("n", logging.ERROR, __file__, 1, "quiet", None, None)
)
self.assertEqual(stderr.getvalue(), "")
def test_handler_appends_a_traceback_to_the_message(self):
shipper = self.make_shipper()
logger = logging.getLogger("tests.logshipper.traceback")
logger.handlers.clear()
logger.addHandler(OmniLoggerHandler(shipper))
logger.propagate = False
self.addCleanup(setattr, logger, "propagate", True)
self.addCleanup(logger.handlers.clear)
try:
raise ValueError("boom")
except ValueError:
logger.exception("failed")
shipper.flush()
message = self.omni.entries()[0]["message"]
self.assertTrue(message.startswith("failed\nTraceback"))
self.assertIn("ValueError: boom", message)
def test_threshold_filters_lower_levels_and_silent_ships_nothing(self):
warn_only = self.make_shipper(level="warn")
warn_only.info("skipped")
warn_only.warning("kept")
silent = self.make_shipper(level="silent")
silent.critical("never")
warn_only.flush()
silent.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], ["kept"])
class FailureTests(ShipperTestCase):
def test_a_rejecting_sink_never_raises_and_warns_once(self):
omni = _FakeOmniLogger(status=400)
self.addCleanup(omni.stop)
shipper = self.make_shipper(base_url=omni.url)
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
shipper.info("one")
shipper.flush()
shipper.info("two")
shipper.flush()
self.assertEqual(len(omni.requests), 2)
self.assertEqual(stderr.getvalue().count("OmniLogger rejected"), 1)
def test_an_unreachable_sink_never_raises(self):
shipper = self.make_shipper(base_url=_unused_url())
shipper.info("nobody home")
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
shipper.flush()
shipper.info("again")
shipper.flush() # inside the warning interval, so silent
self.assertIn("send 1 entries", stderr.getvalue())
self.assertEqual(stderr.getvalue().count("[logshipper]"), 1)
def test_a_full_buffer_drops_the_newest_entries_and_warns_once(self):
shipper = self.make_shipper(buffer_capacity=3, max_batch_size=10**6)
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
for i in range(10):
shipper.info(f"m{i}")
shipper.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], ["m0", "m1", "m2"])
self.assertEqual(stderr.getvalue().count("buffer full"), 1)
def test_a_redirect_is_not_followed_so_the_token_stays_with_the_configured_url(self):
class Redirect(BaseHTTPRequestHandler):
def do_POST(self): # noqa: N802
self.rfile.read(int(self.headers.get("Content-Length", "0")))
self.send_response(307)
self.send_header("Location", "http://127.0.0.1:1/elsewhere")
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Redirect)
threading.Thread(
target=server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True
).start()
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
shipper = self.make_shipper(base_url=f"http://127.0.0.1:{server.server_port}")
shipper.info("x")
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
shipper.flush()
self.assertIn("HTTP 307", stderr.getvalue())
def _buffered_messages(shipper: Shipper) -> list[str]:
return [json.loads(entry)["message"] for entry in shipper._buffer]
class RetryTests(ShipperTestCase):
def test_a_503_is_retried_and_each_entry_arrives_once_in_order(self):
self.omni.statuses = [503]
shipper = self.make_shipper()
with contextlib.redirect_stderr(io.StringIO()) as stderr:
shipper.info("a")
shipper.info("b")
shipper.flush() # refused with 503, so a and b wait for the next flush
shipper.info("c")
shipper.flush() # accepted: a, b and c, in order
shipper.flush() # nothing left, so no third request
self.assertEqual([r["status"] for r in self.omni.requests], [503, 202])
self.assertEqual([e["message"] for e in self.omni.entries()], ["a", "b", "c"])
self.assertIn("will retry", stderr.getvalue())
def test_a_429_or_another_5xx_is_retried_as_well(self):
for status in (429, 500):
with self.subTest(status=status):
self.omni.statuses = [status]
shipper = self.make_shipper()
with contextlib.redirect_stderr(io.StringIO()):
shipper.info(f"after {status}")
shipper.flush()
shipper.flush()
self.assertEqual(self.omni.requests[-1]["status"], 202)
messages = [e["message"] for e in self.omni.entries()]
self.assertEqual(messages.count(f"after {status}"), 1)
def test_a_400_is_dropped_and_not_retried(self):
self.omni.statuses = [400]
shipper = self.make_shipper()
with contextlib.redirect_stderr(io.StringIO()) as stderr:
shipper.info("rejected")
shipper.flush()
shipper.flush() # nothing was kept, so no second request
shipper.info("next")
shipper.flush()
self.assertEqual([r["status"] for r in self.omni.requests], [400, 202])
self.assertEqual([e["message"] for e in self.omni.entries()], ["next"])
self.assertEqual(_buffered_messages(shipper), [])
self.assertIn("OmniLogger rejected 1 entries: HTTP 400", stderr.getvalue())
def test_a_failed_batch_stops_the_rest_of_the_flush(self):
self.omni.statuses = [202, 503]
shipper = self.make_shipper(max_batch_size=10**6, buffer_capacity=1000)
# Each entry is about 8 KiB, so these 600 need three request bodies.
messages = [f"{i:04d}".ljust(MAX_MESSAGE_BYTES, "x") for i in range(600)]
with contextlib.redirect_stderr(io.StringIO()):
for message in messages:
shipper.info(message)
shipper.flush() # the first body is accepted, the second refused, the third never sent
self.assertEqual([r["status"] for r in self.omni.requests], [202, 503])
delivered = [e["message"] for e in self.omni.entries()]
self.assertEqual(delivered, messages[: len(delivered)])
shipper.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], messages)
def test_during_an_outage_the_buffer_holds_at_most_its_capacity_oldest_first(self):
self.omni.status = 503
shipper = self.make_shipper(buffer_capacity=3, max_batch_size=10**6)
with contextlib.redirect_stderr(io.StringIO()):
for message in ("a", "b", "c"):
shipper.info(message)
shipper.flush() # refused, so a, b and c wait for the next flush
for message in ("d", "e"):
shipper.info(message) # the buffer is full, so these are dropped
shipper.flush() # still refused
self.assertEqual(_buffered_messages(shipper), ["a", "b", "c"])
self.omni.status = 202
shipper.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], ["a", "b", "c"])
def test_entries_logged_while_a_retry_waits_are_dropped_newest_first(self):
self.omni.status = 503
shipper = self.make_shipper(buffer_capacity=3, max_batch_size=10**6)
for message in ("a", "b", "c"):
shipper.info(message)
send = shipper._post
def send_while_logging(body, count):
# d and e are logged while a, b and c are in flight, so the retried batch does not fit.
shipper.info("d")
shipper.info("e")
return send(body, count)
shipper._post = send_while_logging
with mock.patch.object(shipper, "_warn") as warn:
shipper.flush()
del shipper._post
self.assertEqual(_buffered_messages(shipper), ["a", "b", "c"])
warn.assert_any_call("buffer full while retrying, dropping 2 log entries for service 'svc'")
self.omni.status = 202
shipper.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], ["a", "b", "c"])
class ConstructionTests(unittest.TestCase):
def test_the_package_exports_the_shipper_and_handler(self):
import shared_backend
self.assertIs(shared_backend.Shipper, Shipper)
self.assertIs(shared_backend.OmniLoggerHandler, OmniLoggerHandler)
def test_the_trailing_slash_is_optional_and_the_level_defaults_to_info(self):
omni = _FakeOmniLogger()
self.addCleanup(omni.stop)
shipper = Shipper(base_url=omni.url + "///", ingest_token="t", service="svc")
self.addCleanup(shipper.close)
self.assertEqual(shipper._url, omni.url + "/api/logs")
self.assertEqual(shipper._threshold, 20)
self.assertEqual(shipper._thread.name, "logshipper-svc")
class SetCredentialsTests(ShipperTestCase):
def test_a_rotated_token_is_sent_from_the_next_flush(self):
shipper = self.make_shipper()
shipper.set_credentials(self.omni.url, "rotated-token")
shipper.info("after rotation")
shipper.flush()
request = self.omni.requests[0]
self.assertEqual(request["path"], "/api/logs")
self.assertEqual(request["authorization"], "Bearer rotated-token")
self.assertEqual(self.omni.entries()[0]["message"], "after rotation")
def test_a_new_url_is_used_and_its_trailing_slashes_are_stripped(self):
other = _FakeOmniLogger()
self.addCleanup(other.stop)
shipper = self.make_shipper()
shipper.set_credentials(other.url + "///", "t2")
shipper.info("to the new endpoint")
shipper.flush()
self.assertEqual(shipper._url, other.url + "/api/logs")
self.assertEqual(self.omni.requests, [])
self.assertEqual([e["message"] for e in other.entries()], ["to the new endpoint"])
def test_an_empty_url_or_token_disables_shipping_and_drops_the_buffer(self):
for base_url, token in ((self.omni.url, ""), ("", "secret-token"), (" ", "secret-token")):
with self.subTest(base_url=base_url, token=token):
shipper = self.make_shipper()
shipper.info("buffered before disabling")
shipper.set_credentials(base_url, token)
shipper.flush()
shipper.info("ignored while disabled")
shipper.flush()
self.assertEqual(self.omni.requests, [])
def test_disabled_shipper_buffers_nothing(self):
shipper = Shipper(base_url="", ingest_token="", service="svc", flush_interval=3600)
self.addCleanup(shipper.close)
shipper.info("nothing to send to")
shipper.error("still nothing")
self.assertEqual(shipper._buffer, [])
self.assertIsNone(shipper._url)
def test_re_enabling_after_disabling_ships_again(self):
shipper = self.make_shipper()
shipper.set_credentials("", "")
shipper.set_credentials(self.omni.url, "secret-token")
shipper.info("back on")
shipper.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], ["back on"])
def test_an_in_flight_flush_is_dropped_once_shipping_is_disabled(self):
shipper = self.make_shipper()
shipper.set_credentials("", "")
shipper._post(b'[{"message":"late"}]', 1)
self.assertEqual(self.omni.requests, [])
def test_changing_credentials_does_not_restart_the_background_thread(self):
shipper = self.make_shipper()
thread = shipper._thread
shipper.set_credentials("", "")
shipper.set_credentials(self.omni.url, "t2")
self.assertIs(shipper._thread, thread)
self.assertTrue(thread.is_alive())
if __name__ == "__main__":
unittest.main()