Skip to content

An always-on second brain you talk to. Voice notes in Telegram → typed, linked knowledge in your Obsidian vault. Runs 24/7 on the Claude subscription you already have.

feat(bot): ensure session at boot + systemd watchdog ping

smixs697ae10d69ed
diff --git a/src/d_brain/bot/main.py b/src/d_brain/bot/main.py
index 022a419..32fd6a8 100644
--- a/src/d_brain/bot/main.py
+++ b/src/d_brain/bot/main.py
@@ -1,5 +1,6 @@
"""Telegram bot initialization and polling."""
+import asyncio
import logging
from collections.abc import Awaitable, Callable
from typing import Any
@@ -11,6 +12,8 @@ from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.types import Update
from d_brain.config import Settings
+from d_brain.services.runtime import get_session
+from d_brain.services.systemd_notify import notify, watchdog_interval
logger = logging.getLogger(__name__)
@@ -25,7 +28,17 @@ def create_bot(settings: Settings) -> Bot:
def create_dispatcher() -> Dispatcher:
"""Create and configure the dispatcher with routers."""
- from d_brain.bot.handlers import buttons, commands, do, forward, photo, process, text, voice, weekly
+ from d_brain.bot.handlers import (
+ buttons,
+ commands,
+ do,
+ forward,
+ photo,
+ process,
+ text,
+ voice,
+ weekly,
+ )
# Use memory storage for FSM (required for /do command state)
dp = Dispatcher(storage=MemoryStorage())
@@ -67,7 +80,10 @@ def create_auth_middleware(settings: Settings) -> MiddlewareType:
# If no users allowed and not allow_all_users -> deny everyone
if not settings.allowed_user_ids:
- logger.warning("Access denied: no allowed_user_ids configured and allow_all_users is False")
+ logger.warning(
+ "Access denied: no allowed_user_ids configured and "
+ "allow_all_users is False"
+ )
return None
# Check if user is in allowed list
@@ -80,6 +96,14 @@ def create_auth_middleware(settings: Settings) -> MiddlewareType:
return auth_middleware
+async def _watchdog_pinger() -> None:
+ """Ping systemd's watchdog while the event loop is healthy."""
+ interval = watchdog_interval()
+ while True:
+ await asyncio.sleep(interval)
+ notify("WATCHDOG=1")
+
+
async def run_bot(settings: Settings) -> None:
"""Run the bot with polling."""
bot = create_bot(settings)
@@ -88,8 +112,19 @@ async def run_bot(settings: Settings) -> None:
# Always add auth middleware for security (it handles allow_all_users internally)
dp.update.middleware(create_auth_middleware(settings))
+ # Bring the persistent Claude session up before serving requests; failure
+ # here is non-fatal (ask() will retry ensure on demand).
+ try:
+ await asyncio.to_thread(get_session(settings).ensure_session)
+ except Exception:
+ logger.exception("Claude session failed to start at boot; retrying on demand")
+
+ notify("READY=1")
+ pinger = asyncio.create_task(_watchdog_pinger())
+
logger.info("Starting bot polling...")
try:
await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types())
finally:
+ pinger.cancel()
await bot.session.close()
diff --git a/src/d_brain/services/systemd_notify.py b/src/d_brain/services/systemd_notify.py
new file mode 100644
index 0000000..eb99c27
--- /dev/null
+++ b/src/d_brain/services/systemd_notify.py
@@ -0,0 +1,40 @@
+"""Minimal sd_notify client (no external deps).
+
+Lets the bot/watchdog talk to systemd's Type=notify + WatchdogSec without
+pulling in a library. All functions are no-ops when not run under systemd
+(NOTIFY_SOCKET unset), so the code runs fine in dev and tests.
+"""
+
+import os
+import socket
+
+
+def notify(state: str) -> bool:
+ """Send a state line to systemd (e.g. 'READY=1', 'WATCHDOG=1').
+
+ Returns False if not running under systemd or on socket error.
+ """
+ addr = os.environ.get("NOTIFY_SOCKET")
+ if not addr:
+ return False
+ # Abstract namespace sockets start with '@'.
+ if addr.startswith("@"):
+ addr = "\0" + addr[1:]
+ try:
+ with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as sock:
+ sock.connect(addr)
+ sock.sendall(state.encode())
+ return True
+ except OSError:
+ return False
+
+
+def watchdog_interval(default: float = 60.0) -> float:
+ """Ping interval = half of WATCHDOG_USEC (systemd's deadline), or default."""
+ usec = os.environ.get("WATCHDOG_USEC")
+ if not usec:
+ return default
+ try:
+ return max(1.0, (int(usec) / 1_000_000) / 2)
+ except ValueError:
+ return default
diff --git a/tests/test_systemd_notify.py b/tests/test_systemd_notify.py
new file mode 100644
index 0000000..17fa4eb
--- /dev/null
+++ b/tests/test_systemd_notify.py
@@ -0,0 +1,23 @@
+"""Tests for the minimal sd_notify client."""
+
+from d_brain.services.systemd_notify import notify, watchdog_interval
+
+
+def test_notify_no_socket_returns_false(monkeypatch):
+ monkeypatch.delenv("NOTIFY_SOCKET", raising=False)
+ assert notify("READY=1") is False
+
+
+def test_watchdog_interval_default_when_unset(monkeypatch):
+ monkeypatch.delenv("WATCHDOG_USEC", raising=False)
+ assert watchdog_interval(60) == 60
+
+
+def test_watchdog_interval_is_half_of_usec(monkeypatch):
+ monkeypatch.setenv("WATCHDOG_USEC", "20000000") # 20s deadline
+ assert watchdog_interval() == 10.0
+
+
+def test_watchdog_interval_bad_value_falls_back(monkeypatch):
+ monkeypatch.setenv("WATCHDOG_USEC", "not-a-number")
+ assert watchdog_interval(30) == 30