mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-20 02:34:21 +01:00
python -m diet_guard claude-worker serves the phone's meal requests from RTDB (rtdb_relay RequestServer, one SSE stream, reconnects with backoff): validate, estimate with Claude, log through the signed log with source=claude under the oldest due slot (normal mode: nearest slot of the phone's hint), write the sealed result, delete only the request payload, then publish in the background. diet-guard-claude.service (Restart=on-failure, WantedBy=default.target) is installed by install.sh and started once the worker's own Firebase session exists. Nothing is deployed by this commit. Failure paths: - narrow peer pull fails (sync locked/unreachable): fail closed, no claim, no answer, no model call; the request stays pending, retried every 30 s - e2e key locked, no passphrase, no session: fail closed, nothing read or written; the worker waits and retries every 60 s - bad body, request older than 24 h (or no created): fail closed, an error result, nothing logged - Claude failure/timeout/invalid JSON: fail closed, an error result with retry, nothing logged - crash between log and result, or a duplicate event: idempotent, the entry id is uuid5 of the rid and is looked up (tombstones included) before the model call - request payload delete, old-answer cleanup and the post-answer publish failing: fail open on purpose (logged only); the answer and the local entry are already durable - due mode with nothing due: falls back to slot_for_log, not an error New log helpers log_meal_as / find_entry; log_meal's body is split into _entry_fields / _store_entry with the same output. The gate and CLI import none of the worker's dependencies at load time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
"""``python -m diet_guard claude-worker``: connect, serve, never idle-poll.
|
|
|
|
One SSE stream on ``requests`` does the waiting (``rtdb_relay.sse`` reconnects
|
|
forever with backoff). The only timers are fault retries: an unconfigured or
|
|
locked relay (no session, no passphrase, wrong key) writes nothing and is
|
|
tried again every :data:`RETRY_S`.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
from typing import TYPE_CHECKING, Final
|
|
|
|
from rtdb_relay.sse import StreamCancelledError
|
|
|
|
from diet_guard import _claude_connect, _device
|
|
from diet_guard._claude_worker import MealHandler, MealServer
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Awaitable, Callable
|
|
|
|
RETRY_S: Final = 60.0
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
|
|
async def serve(
|
|
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
|
|
) -> None:
|
|
"""Connect and serve until cancelled; a setup failure waits and retries."""
|
|
worker = f"claude-{_device.device_id()}"
|
|
while True:
|
|
try:
|
|
rtdb = await _claude_connect.connect_sealed()
|
|
except _claude_connect.RelaySetupError as err:
|
|
_logger.warning("relay not started, nothing written: %s", err)
|
|
await sleep(RETRY_S)
|
|
continue
|
|
try:
|
|
await MealServer(rtdb, worker, MealHandler()).run()
|
|
finally:
|
|
await rtdb.aclose()
|
|
|
|
|
|
def main() -> int:
|
|
"""Run the worker; 0 on Ctrl-C, 1 when RTDB cancelled the stream."""
|
|
logging.basicConfig(
|
|
level=logging.INFO, format="%(levelname)s %(name)s: %(message)s"
|
|
)
|
|
try:
|
|
asyncio.run(serve())
|
|
except KeyboardInterrupt:
|
|
return 0
|
|
except StreamCancelledError:
|
|
_logger.exception("the rules refuse the relay path")
|
|
return 1
|
|
return 0
|