From 8d5f5fd0a8e7b39a0c90e2f2197f24e0d24913a6 Mon Sep 17 00:00:00 2001 From: Nan Gao Date: Sun, 18 Oct 2026 11:10:31 +0800 Subject: [PATCH] feat(channels): share encrypted runtime channel config across Gateway instances (#6988) * feat(channels): share encrypted runtime channel config across Gateway instances IM bot credentials entered in the web UI lived in each host's plaintext channels/runtime-config.json, and the router cached the merged config on app.state for the life of the process. With several Gateway instances a save or disconnect served by an instance that does not hold the provider's leader lease never reached the transport holder: it kept the old credentials until it next started the channel, and a disconnect could leave the old bot connected. - New shared table channel_runtime_configs (migration 0044): one row per provider with the config block encrypted under DEER_FLOW_CREDENTIALS_KEY, a plaintext disconnect tombstone, and a version bumped by every save. - SqlChannelRuntimeConfigStore replaces the JSON file for sqlite/postgres (memory keeps the file); it is synchronous on app_sync_sqlalchemy_url because its callers already run in worker threads. - The router re-reads the store on every request instead of caching the merged config, and refuses (503) to save credentials without a key. - The leader-lease supervisor compares the versions on each renewal tick and restarts or stops the holder's transport when a provider's config changed; a takeover reads a disconnect instead of reviving cached credentials. - The first start imports an existing runtime-config.json (rows already in the table win) and deletes the plaintext file. * docs(changelog): reference #6988 for the shared runtime channel config * ci: rerun checks after #6999 fixed the frontend guidance budget on main * fix(channels): start a held transport that is down when its runtime config changes When the lease holder's transport was down (a start that failed on the old credentials), applying a peer-saved config only updated the cached config, and the transport started on the next lease round: two renewal ticks instead of the one the docs promise. The apply step now starts it on the held lease right away, with the lease round's backoff bookkeeping. --- CHANGELOG.md | 19 + CHANGELOG_zh.md | 14 + README.md | 2 +- backend/app/channels/AGENTS.md | 6 +- backend/app/channels/runtime_config_store.py | 309 +++++++++++++- backend/app/channels/service.py | 171 ++++++-- backend/app/gateway/deps.py | 3 +- .../gateway/routers/channel_connections.py | 66 +-- backend/docs/API.md | 13 + backend/docs/CONFIGURATION.md | 6 +- backend/docs/IM_CHANNEL_CONNECTIONS.md | 44 +- .../channel_runtime_configs/__init__.py | 15 + .../channel_runtime_configs/model.py | 52 +++ .../channel_runtime_configs/sql.py | 111 +++++ .../deerflow/persistence/migrations/AGENTS.md | 4 +- .../versions/0044_channel_runtime_configs.py | 57 +++ .../deerflow/persistence/models/__init__.py | 2 + .../blocking_io/test_channel_leader_lease.py | 53 ++- .../test_channel_runtime_config_store.py | 52 ++- .../tests/test_channel_connections_router.py | 62 ++- .../test_channel_runtime_config_db_store.py | 297 +++++++++++++ .../test_channel_runtime_config_replicas.py | 395 ++++++++++++++++++ ...migration_0027_0028_notification_outbox.py | 2 +- ...st_migration_0029_scheduler_agent_tasks.py | 2 +- ...migration_0032_activity_and_task_events.py | 2 +- ..._migration_0034_run_event_seq_watermark.py | 2 +- .../test_migration_0035_login_throttle.py | 2 +- ...gration_0037_project_document_summaries.py | 6 +- ..._migration_0038_channel_thread_bindings.py | 2 +- ...t_migration_0040_scheduled_group_notice.py | 2 +- .../test_migration_0042_channel_leases.py | 6 +- ..._migration_0044_channel_runtime_configs.py | 162 +++++++ deploy/helm/deer-flow/README.md | 11 +- .../en/application/deployment-guide.mdx | 2 +- .../zh/application/deployment-guide.mdx | 2 +- 35 files changed, 1788 insertions(+), 168 deletions(-) create mode 100644 backend/packages/harness/deerflow/persistence/channel_runtime_configs/__init__.py create mode 100644 backend/packages/harness/deerflow/persistence/channel_runtime_configs/model.py create mode 100644 backend/packages/harness/deerflow/persistence/channel_runtime_configs/sql.py create mode 100644 backend/packages/harness/deerflow/persistence/migrations/versions/0044_channel_runtime_configs.py create mode 100644 backend/tests/test_channel_runtime_config_db_store.py create mode 100644 backend/tests/test_channel_runtime_config_replicas.py create mode 100644 backend/tests/test_migration_0044_channel_runtime_configs.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f259b8e9d0..43a7e49d8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,24 @@ This release closes that milestone with **621 merged pull requests**. ### Added +- **channels:** IM bot credentials entered in the web UI now live in the shared + `channel_runtime_configs` table (migration `0044_channel_runtime_configs`) + instead of each host's plaintext `channels/runtime-config.json`. Each + provider's config is encrypted with `DEER_FLOW_CREDENTIALS_KEY`, a disconnect + is a plaintext tombstone that still overrides `config.yaml`, and every save + bumps a per-provider `version`. Every Gateway instance re-reads the table on + each request (the router no longer caches the merged config on `app.state`), + and under `channels.leader_lease` the holder compares the versions on every + renewal tick, so credentials saved or a disconnect made on any instance reach + the platform connection within one renewal interval instead of on the + holder's next restart; an instance taking a lease over reads a disconnect + instead of reviving cached credentials. The first start imports an existing + `runtime-config.json` (providers already in the table keep their row) and + deletes the plaintext file, so a downgrade must re-enter UI-configured bots. + Without a usable key, saving credentials answers `503` instead of storing + plaintext, and rows the key cannot decrypt read as not configured. + `database.backend: memory` keeps the JSON file. ([#6988]) + - **channels:** Option-based clarifications on the Feishu channel render as an interactive button card instead of plain text: each option becomes a button (up to 4 — beyond that the plain-text path reads better), a click resolves @@ -11800,4 +11818,5 @@ with **180 merged pull requests** since the first 2.0 milestone tag. [#6909]: https://github.com/bytedance/deer-flow/pull/6909 [#6913]: https://github.com/bytedance/deer-flow/pull/6913 [#6930]: https://github.com/bytedance/deer-flow/pull/6930 +[#6988]: https://github.com/bytedance/deer-flow/pull/6988 [#6991]: https://github.com/bytedance/deer-flow/pull/6991 diff --git a/CHANGELOG_zh.md b/CHANGELOG_zh.md index 915559b778..94e3b01ede 100644 --- a/CHANGELOG_zh.md +++ b/CHANGELOG_zh.md @@ -14,6 +14,19 @@ ### 新增 +- **渠道:** 在 Web UI 中填写的 IM 机器人凭据改存到共享的 `channel_runtime_configs` + 表(迁移 `0044_channel_runtime_configs`),不再写入每台主机上明文的 + `channels/runtime-config.json`。每个 provider 的配置用 `DEER_FLOW_CREDENTIALS_KEY` + 加密;断开连接记为一条明文墓碑,仍会覆盖 `config.yaml` 中的配置;每次保存都会递增 + 该 provider 的 `version`。每个 Gateway 实例在每次请求时重新读表(路由不再把合并后 + 的配置缓存在 `app.state` 上);启用 `channels.leader_lease` 时,持有者在每个续约 + 周期比对版本号,因此在任一实例上保存凭据或断开连接,都会在一个续约周期内到达平台 + 连接,而不必等持有者下次重启;接管租约的实例会读到断开状态,不会复活缓存中的旧凭据。 + 首次启动会导入已有的 `runtime-config.json`(表中已有的 provider 保留其行)并删除该 + 明文文件,因此回退到旧版本需要重新填写 UI 配置的机器人。没有可用密钥时,保存凭据 + 返回 `503` 而不是以明文存储,密钥无法解密的行视为未配置。`database.backend: memory` + 仍使用 JSON 文件。 ([#6988]) + - **渠道:** 飞书渠道上基于选项的澄清改为渲染为可交互的按钮卡片,而不是纯文本:每个 选项变成一个按钮(最多 4 个——再多时纯文本路径更易读),点击选项即可完成澄清, 效果与输入该选项完全相同,卡片会原地更新以显示所作决定。渠道管理器把澄清中间件 @@ -9407,4 +9420,5 @@ DeerFlow 2.0 是围绕"超级智能体"框架的彻底重写,核心包含子 [#6909]: https://github.com/bytedance/deer-flow/pull/6909 [#6913]: https://github.com/bytedance/deer-flow/pull/6913 [#6930]: https://github.com/bytedance/deer-flow/pull/6930 +[#6988]: https://github.com/bytedance/deer-flow/pull/6988 [#6991]: https://github.com/bytedance/deer-flow/pull/6991 diff --git a/README.md b/README.md index 06661b2917..13dd654da5 100644 --- a/README.md +++ b/README.md @@ -580,7 +580,7 @@ Administrators can suspend and restore accounts from **Settings → Users** (adm DeerFlow still uses `Forwarded` / `X-Forwarded-*` headers to recover the browser-facing scheme and origin behind a proxy. The bundled nginx sets `X-Forwarded-Proto`, but preserves an upstream HTTPS value and does not overwrite every forwarded header. Configure the outer trusted proxy to replace or strip client-supplied forwarding headers before traffic reaches DeerFlow. > [!IMPORTANT] -> The Gateway still owns active run tasks in process, so production defaults to a single Gateway worker (`GATEWAY_WORKERS=1`). Multi-worker deployments require Postgres, the Redis stream bridge (`stream_bridge.type: redis`), `run_ownership.heartbeat_enabled: true`, and `run_events.backend: db`; process-local memory/JSONL event stores cannot enforce singleton delivery receipts across workers. Kubernetes replicas run one worker per Pod, which the worker count cannot see: declare them with `deployment.multi_instance: true` (or `DEER_FLOW_MULTI_INSTANCE=1`, which deploy tooling such as a Helm chart can set from its replica count) so the startup gate enforces the same prerequisites instead of staying inert. Declared instances that store credentials (`channel_connections`) must also share one at-rest `DEER_FLOW_CREDENTIALS_KEY` (the Helm chart and `make up` generate it; back it up, see [backend/docs/CONFIGURATION.md](backend/docs/CONFIGURATION.md#credentials-encryption-key-deer_flow_credentials_key)). The bridge shares SSE delivery and bounded `Last-Event-ID` replay across workers. When a valid reconnect cursor has been trimmed, or a subscriber that already established an empty-stream wait falls behind before its first delivery, Memory and Redis emit a machine-readable SSE `gap` event instead of silently returning a partial replay; the Web UI reloads durable thread/event state and resumes from the retained tail. An already-observed Redis stream removed during replay also signals a gap, so slow subscribers reload durable state instead of heartbeating forever after cleanup. Lease reconciliation marks runs from dead workers as errors, persists their delivery receipts, publishes the terminal stream marker, schedules retained-stream cleanup, and updates the affected thread status. SSE, `/wait`, and internal stream consumers use `stream_bridge.heartbeat_interval_seconds` (default `15`) for idle liveness checks; changing it requires a Gateway restart. Malformed Redis reconnect IDs live-tail new events instead of replaying the retained buffer, and the rolling retained-buffer TTL (`stream_ttl_seconds`) remains a cleanup safety net rather than a run timeout. Failed-login counters and lockouts for `POST /api/v1/auth/login/local` (`auth.local.max_login_attempts` / `lockout_seconds`) are kept in the shared `login_throttle` table whenever the application database is SQLite or Postgres (`auth.local.throttle_storage: auto`, the default), so every replica enforces one lockout per client IP; `memory` keeps the historical per-process counter, which under N replicas hands an attacker N × `max_login_attempts` guesses and logs a startup warning. IM chat-to-thread bindings live in the shared `channel_thread_bindings` table whenever the application database is SQLite or Postgres (an existing `channels/store.json` is imported once at startup and renamed `store.json.migrated`); each provider's platform connection is held by one instance through the shared `channel_leases` table — `channels.leader_lease` (default `auto`, on wherever the multi-process signal is) hands it to another instance when the holder dies, and the startup gate refuses `enabled: false` while an IM channel other than GitHub is enabled (see [IM channel leader lease](backend/docs/CONFIGURATION.md#im-channel-leader-lease-channelsleader_lease)); follow-up buffers still need their own multi-worker coordination. To try this topology on one machine, `make dev-multi` starts two Gateways on shared Postgres, Redis and `DEER_FLOW_HOME`, and `make dev-multi-check` runs the cross-instance checks; see the local two-Gateway harness in [backend/docs/CONFIGURATION.md](backend/docs/CONFIGURATION.md#local-two-gateway-harness). +> The Gateway still owns active run tasks in process, so production defaults to a single Gateway worker (`GATEWAY_WORKERS=1`). Multi-worker deployments require Postgres, the Redis stream bridge (`stream_bridge.type: redis`), `run_ownership.heartbeat_enabled: true`, and `run_events.backend: db`; process-local memory/JSONL event stores cannot enforce singleton delivery receipts across workers. Kubernetes replicas run one worker per Pod, which the worker count cannot see: declare them with `deployment.multi_instance: true` (or `DEER_FLOW_MULTI_INSTANCE=1`, which deploy tooling such as a Helm chart can set from its replica count) so the startup gate enforces the same prerequisites instead of staying inert. Declared instances that store credentials (`channel_connections`) must also share one at-rest `DEER_FLOW_CREDENTIALS_KEY` (the Helm chart and `make up` generate it; back it up, see [backend/docs/CONFIGURATION.md](backend/docs/CONFIGURATION.md#credentials-encryption-key-deer_flow_credentials_key)). The bridge shares SSE delivery and bounded `Last-Event-ID` replay across workers. When a valid reconnect cursor has been trimmed, or a subscriber that already established an empty-stream wait falls behind before its first delivery, Memory and Redis emit a machine-readable SSE `gap` event instead of silently returning a partial replay; the Web UI reloads durable thread/event state and resumes from the retained tail. An already-observed Redis stream removed during replay also signals a gap, so slow subscribers reload durable state instead of heartbeating forever after cleanup. Lease reconciliation marks runs from dead workers as errors, persists their delivery receipts, publishes the terminal stream marker, schedules retained-stream cleanup, and updates the affected thread status. SSE, `/wait`, and internal stream consumers use `stream_bridge.heartbeat_interval_seconds` (default `15`) for idle liveness checks; changing it requires a Gateway restart. Malformed Redis reconnect IDs live-tail new events instead of replaying the retained buffer, and the rolling retained-buffer TTL (`stream_ttl_seconds`) remains a cleanup safety net rather than a run timeout. Failed-login counters and lockouts for `POST /api/v1/auth/login/local` (`auth.local.max_login_attempts` / `lockout_seconds`) are kept in the shared `login_throttle` table whenever the application database is SQLite or Postgres (`auth.local.throttle_storage: auto`, the default), so every replica enforces one lockout per client IP; `memory` keeps the historical per-process counter, which under N replicas hands an attacker N × `max_login_attempts` guesses and logs a startup warning. IM chat-to-thread bindings live in the shared `channel_thread_bindings` table whenever the application database is SQLite or Postgres (an existing `channels/store.json` is imported once at startup and renamed `store.json.migrated`); IM bot credentials entered in the web UI live in the shared `channel_runtime_configs` table, encrypted with `DEER_FLOW_CREDENTIALS_KEY` (an existing `channels/runtime-config.json` is imported once and then deleted), so a save on any instance reaches the provider's connection within one lease renewal; each provider's platform connection is held by one instance through the shared `channel_leases` table — `channels.leader_lease` (default `auto`, on wherever the multi-process signal is) hands it to another instance when the holder dies, and the startup gate refuses `enabled: false` while an IM channel other than GitHub is enabled (see [IM channel leader lease](backend/docs/CONFIGURATION.md#im-channel-leader-lease-channelsleader_lease)); follow-up buffers still need their own multi-worker coordination. To try this topology on one machine, `make dev-multi` starts two Gateways on shared Postgres, Redis and `DEER_FLOW_HOME`, and `make dev-multi-check` runs the cross-instance checks; see the local two-Gateway harness in [backend/docs/CONFIGURATION.md](backend/docs/CONFIGURATION.md#local-two-gateway-harness). > > The local two-Gateway harness disables IM providers under both `channels` and `channel_connections` by default. `DEERFLOW_MI_KEEP_CHANNELS=1` preserves them; `channels.leader_lease` stays as configured. > diff --git a/backend/app/channels/AGENTS.md b/backend/app/channels/AGENTS.md index 09f80712bb..3eebff65cf 100644 --- a/backend/app/channels/AGENTS.md +++ b/backend/app/channels/AGENTS.md @@ -14,12 +14,12 @@ Finalize asyncgens; keep primary errors; propagate lone Bot errors. **Components**: - `message_bus.py` - Inbound queue → dispatcher; outbound uses a dispatch-start listener snapshot. Unsubscribe neither cancels nor drains captured callbacks. - `store.py` - `ChannelStore` protocol (async `get_thread_id`/`set_thread_id`/`remove`/`list_entries`) for `channel_name:chat_id[:topic_id]` → `thread_id`. `SqlChannelStore` (`channel_thread_bindings`, harness `persistence/channel_thread_bindings/`; upsert keeps `created_at`, topic-less `remove` deletes by key prefix) for sqlite/postgres, so replicas share bindings; `JsonChannelStore` (`{base_dir}/channels/store.json`, loaded once per process, file I/O via `to_thread` under `_lock`) only for `database.backend: memory`. `resolve_channel_store` picks; `ChannelService.start()` runs `SqlChannelStore.import_legacy_json` once (file + empty table → `INSERT … ON CONFLICT DO NOTHING`, rename to `store.json.migrated`, a peer's rename tolerated; populated table → file kept). Feishu's sync lark callback (on the SDK's own loop) bridges `_resolve_routing_bounded` to the Gateway loop via `_run_store_call` (tracked future; refuses only a wait from the Gateway loop itself). Store calls run under `FEISHU_STORE_LOOKUP_TIMEOUT_SECONDS` (3s; the SDK loop also services ws keepalives); timeout or store error = *unresolved* (`StoreLookupUnresolved`), never a miss: the message joins a per-chat FIFO drained on the Gateway loop with backoff up to `FEISHU_STORE_RESOLVE_TOTAL_BUDGET_SECONDS` (30s), then is dropped with a warning, never routed to a new conversation; each deferred message holds a bus intake reservation (the `inbound_queue_maxsize` bound) and its 30s budget runs from arrival. `discord.py` reads `channels_dir`. Tests: `test_channel_thread_binding_store.py` (also under `blocking_io/`). -- `manager.py` - Core dispatcher: creates threads via `client.threads.create()`, routes commands including `/goal` (setting a goal persists it through Gateway and then routes the objective as a chat turn) and `/agent` (`list` is owner-scoped; `use` creates a fresh thread and persists the Custom Agent selection under both the channel restart key and Web's canonical routing metadata so existing checkpoint lineage never changes agent across IM/Web), keeps Slack/Discord on `client.runs.wait()`, uses `client.runs.stream(["messages-tuple", "values"])` for Feishu/Telegram incremental outbound updates, serializes same-thread Feishu turns in-manager when the channel's `ChannelRunPolicy.serialize_thread_runs=True` so rapid follow-ups queue instead of tripping the runtime busy reply, and switches to `client.runs.create()` (fire-and-forget, returns once the run is `pending`) for channels whose `ChannelRunPolicy.fire_and_forget=True` so long autonomous runs do not hit the SDK default 300s `httpx.ReadTimeout`; `runs.wait`/`runs.stream` pass `on_disconnect: continue`, so a run outlives the instance that requested it (reply lost, thread persisted); hence once a run request is sent, cancellation or a post-request transport error keeps the inbound dedupe key (`_keep_dedupe_key_after`) and only Gateway rejections, pre-request failures and `error` frames release it +- `manager.py` - Core dispatcher: creates threads via `client.threads.create()`, routes commands including `/goal` (setting a goal persists it through Gateway and then routes the objective as a chat turn) and `/agent` (`list` is owner-scoped; `use` creates a fresh thread and persists the Custom Agent selection under both the channel restart key and Web's canonical routing metadata so existing checkpoint lineage never changes agent across IM/Web), keeps Slack/Discord on `client.runs.wait()`, uses `client.runs.stream(["messages-tuple", "values"])` for Feishu/Telegram incremental outbound updates, serializes same-thread Feishu turns in-manager when the channel's `ChannelRunPolicy.serialize_thread_runs=True` so rapid follow-ups queue instead of tripping the runtime busy reply, and switches to `client.runs.create()` (fire-and-forget, returns once the run is `pending`) for channels whose `ChannelRunPolicy.fire_and_forget=True` so long autonomous runs do not hit the SDK default 300s `httpx.ReadTimeout`; `runs.wait`/`runs.stream` pass `on_disconnect: continue` (a run outlives its requester; reply lost, thread kept), so once a request is sent, cancellation or a transport error keeps the inbound dedupe key (`_keep_dedupe_key_after`); only Gateway rejections, pre-request failures and `error` frames release it Streaming `error` frames use the same failure path as transport exceptions. Publish the final outbound before releasing the inbound dedupe key, so provider redelivery can retry without overtaking the terminal reply. Log the frame's error name and message at WARNING with the thread ID; keep the synthetic error generic so payload details do not change reply selection. **What may be published from the stream is an allowlist, not a denylist** (`_accumulate_stream_text`): only assistant message types — LangChain serializes `AIMessage.type` as `"ai"` and `AIMessageChunk.type` as `"AIMessageChunk"`, plus the OpenAI-style `"assistant"` spelling for foreign runtimes — become displayable text. The previous rule rejected only payloads whose `type` contained `"tool"` and therefore published everything else, which leaked DeerFlow's hidden model context to every streaming IM channel: `DynamicContextMiddleware` injects recalled memory as a hidden `HumanMessage` (`type == "human"`) and rewrites the user's own turn into a new `HumanMessage`, `DurableContextMiddleware` injects a hidden `` `HumanMessage`, and LangGraph fans those state writes out on the `messages-tuple` stream. Proved live on a Buzz relay. Matching is by prefix (`ai` / `assistant`), never substring, because ordinary words contain `"ai"` (`chain`, `domain`). The message type is resolved by `_stream_payload_type`, which handles both the `model_dump()` shape DeerFlow's own gateway emits and LangChain's `to_json()` constructor shape (whose top-level `type` is the literal `"constructor"`, with the class name at the tail of the `id` path). A bare `str` payload is no longer accepted at all: it carries no type information, so it cannot be attributed to the assistant, and nothing in DeerFlow produces one (`runtime/serialization.py::serialize_messages_tuple` always emits `[message_dict, metadata]`). - `base.py` - Abstract `Channel` base class (start/stop/send lifecycle). Provider callbacks that submit coroutines from SDK threads must use `_submit_threadsafe_coroutine()` (or `_submit_threadsafe_coroutine_future()` to await the outcome through `asyncio.shield`): it creates and retains the real `asyncio.Task` on the owner loop instead of treating `run_coroutine_threadsafe()`'s proxy Future as a completion signal. Submission is closed atomically with shutdown, and `stop()` must call `_close_and_drain_threadsafe_futures()` before tearing down SDK resources. Blocking SDK teardown in `stop()` (a client `close()`, a thread `join()`) must run off the event loop through `asyncio.to_thread`: the shared Gateway loop also serves `POST /api/channels/{name}/restart`; Slack cleanup awaits connect then closes off-loop; a 5s deadline/cancellation retains it for retry. SDK close errors propagate. Anchored by `tests/blocking_io/test_channel_stop_offloop.py`. **Proactive push**: WeCom, Feishu, WeChat and QQ C2C share the outbox; `capabilities.py` gates enqueue/UI. Unsupported rows fail terminally. Await ACK; `ChannelUnavailable` parks, business rejection counts. WeCom parks socket `RuntimeError` except `Reply ack error`. Feishu/QQ/WeCom group hooks use owner connection IDs; Feishu p2p resolves owner. `group_name`: OAuth state only, no suffix/raw-ID labels. WeCom legacy-group fallback excludes private bindings. QQ: owner/current-App C2C only, never member OpenIDs/passive context. WeChat: encrypted owner/bot/private context across restart; ignore public tokens. `store_connection_context` locks/checks the active identity before merging encrypted extra; browser responses strip legacy tokens. Preferences gate enqueue/send/retry, cancel pending/sending and fence late writes; reenable never replays. In-flight sends may finish. Binding lookup errors park; revoked targets fail before liveness. `_on_finalization` commits one notice with the outcome (stop > pause > finish > run); recovery dedupes, idle uses `idle:`, trials/interrupts stay silent. Web/background events default off: confirm durable terminal state; recheck Human Input before send/retry. Text: localized, no IDs/links. Delivery starts after channels/stops first; failure detaches enqueue. [IM guide](../../docs/IM_CHANNEL_CONNECTIONS.md#proactive-notification-settings). - `wecom.py` - WeCom WebSocket channel with proactive `send_notification`; `_ws_transport_up` maps disconnects to `ChannelUnavailable` (no retry used). `capabilities.py` - SDK-free `CHANNEL_CAPABILITIES`. -- `service.py` - Drain manager work before transports; retain timed-out instances for retry. Feishu/DingTalk `stop()` stop the SDK thread's private loop via `_request_*_shutdown` (Feishu disarms lark's `_auto_reconnect` first, else its reconnect branch eats the stop; DingTalk runs its own copy of the SDK connect loop), then join; a live join or Slack cleanup raises `ChannelStopTimeout`: retain, defer replacement/restart, log WARNING without traceback; wedged instances report not running. Reload returns snapshots; restart owns cached fallback/publication under the channel lock. `_stopping` fences starts/publication (including after pre-start I/O) until shutdown succeeds. Lock manager startup through stale cleanup; capture the shutdown generation before locking to fence queued starts. `stop()` stays unlocked to fence in-flight startup. Leader lease (`leadership.py`): only the `channel_leases` holder starts a non-GitHub transport (`_start_channel` checks `holds()`; callers acquire first); `_supervise` renews at a fixed rate, runs starts/stops per provider, stops a transport before its lease lapses. +- `service.py` - Drain manager work before transports; retain timed-out instances for retry. Feishu/DingTalk `stop()` stop the SDK thread's private loop via `_request_*_shutdown` (Feishu first disarms lark's `_auto_reconnect`; DingTalk runs its own SDK connect-loop copy), then join; a live join or Slack cleanup raises `ChannelStopTimeout`: retain, defer replacement/restart, log WARNING without traceback; wedged instances report not running. Reload returns snapshots; restart owns cached fallback/publication under the channel lock. `_stopping` fences starts/publication (including after pre-start I/O) until shutdown succeeds. Lock manager startup through stale cleanup; capture the shutdown generation before locking to fence queued starts. `stop()` stays unlocked to fence in-flight startup. Leader lease (`leadership.py`): only the `channel_leases` holder starts a non-GitHub transport (`_start_channel` checks `holds()`; callers acquire first); `_supervise` renews at a fixed rate, runs starts/stops per provider, stops a transport before its lease lapses, re-applies runtime config whose `version` changed; reloads read a disconnect as its tombstone. - `slack.py` / `feishu.py` / `telegram.py` / `discord.py` / `dingtalk.py` - Platform-specific implementations (`feishu.py` tracks the running card `message_id` in memory and patches the same card in place; `telegram.py` accepts inbound text/photos/documents, preserves media captions, hands token-free attachment bytes to the shared upload pipeline, edits the "Working on it..." stream target in place via `editMessageText`, and can optionally send final Markdown replies as Rich Messages through `channels.telegram.rich_messages` — the Rich path only fires when `rich_messages` is on **and** the text contains a rich construct (fenced code, emphasis, a table, a task list, `
`, block math, or a link), so structured command/error replies stay plain text and their newlines and `` tokens survive; `discord.py` runs `_on_message` on discord.py's private loop, so connection-repository work (identity lookup with the reservation commit, `/connect` binding) goes to the Gateway loop through `_submit_threadsafe_coroutine` — the SQLAlchemy engine is bound there — and bind replies return through `_run_on_discord_loop`; typing registers before that hand-off settles, and a failed hand-off skips the ack and stops the indicator it started unless another message still relies on it; `discord.py` registers typing loops before inbound handling yields and `_start_typing()` refuses work once `_running` is false; each tick sends the indicator with discord.py 2.x's `await channel.typing()`; because `stop()` runs on the main loop while typing tasks belong to `_discord_loop`, normal cross-thread cancellation, awaiting, and map cleanup are scheduled there with a bounded wait, while `_run_client()` drains tasks in its `finally` block before an exception/disconnect can make that loop unusable; an already-stopped foreign loop must never have its tasks awaited from the main loop; to that end every outbound cross-loop call (`send` / `send_file` / `_get_channel_or_thread`) goes through `_run_on_discord_loop`, which bounds the await (`DISCORD_OUTBOUND_TIMEOUT_SECONDS` 30s; `DISCORD_UPLOAD_TIMEOUT_SECONDS` 120s for file uploads: slow uplink plus 429 retry-after) and fails fast with a `RuntimeError` when the client loop is missing or not running — a dead client becomes a logged send failure instead of a permanently hung `ChannelManager` worker — and `is_running` reports client-thread aliveness (like `feishu.py`) so `ensure_channel_ready` can restart the channel after `_run_client()` exits on a fatal error; `dingtalk.py` optionally uses AI Card streaming for in-place updates when `card_template_id` is configured, and overrides `receive_file` to download inbound images (`picture`/`richText`) and documents (`file`) by `downloadCode` into the thread uploads bucket, mirroring `feishu.py`) - `buzz.py` - Buzz (Nostr relay) implementation: one NIP-42-authenticated websocket, pubkey-allowlist + mention/DM/thread-follow gating (thread-follow reads via the manager's `connection_identity.lookup_thread_id`, so bound authors' repo-only threads count), streaming replies via in-place kind-40003 edits; requires the `buzz` dependency extra. Its durable seen-event replay guard uses async `aseen()` / `arecord()` / `aflush()` boundaries: initial JSON reads and coalesced atomic writes run off the Gateway event loop, and `stop()` awaits the final flush before returning. **Subscription model** (operator-facing version in [IM_CHANNEL_CONNECTIONS.md](../../docs/IM_CHANNEL_CONNECTIONS.md#buzz-subscription-model)): the relay fans kind-9 chat events out **only** to channel-scoped subscriptions, proved on a live relay: `REQ {"kinds":[9]}` is accepted and answered with `EOSE` but never receives an event, `REQ {"kinds":[9],"#h":[uuid]}` works, and a multi-value `#h` matches nothing, so it is strictly one REQ per channel. Every connection therefore rebuilds three kinds of subscription after NIP-42 auth: `buzz-discovery` (`{"kinds":[39000]}`, a historical query returning exactly the channels this identity belongs to, one stored event each then `EOSE` — adding `#p` returns zero, do not "narrow" it), `buzz-membership` (`{"kinds":[44100,44101],"#p":[us],"since":}`, the relay-signed member-added/member-removed notifications whose `p` tag names the affected member and `h` tag the channel), and one `buzz-chat-` per discovered channel. Chat subscriptions open as each kind-39000 arrives; the discovery `EOSE` is the completeness barrier that retries any that failed and warns when discovery found nothing. A kind-44100 for our pubkey subscribes to the new channel **live** (then re-issues discovery so its name/type reach the DM-detection cache, but only when that channel's metadata is actually missing — an unconditional refresh is how a burst of 44100s multiplied into one discovery pass each); a kind-44101 issues `buzz_nostr.close_frame` for exactly that channel's subscription and drops its metadata. **The membership subscription is scoped to LIVE events** and this is load-bearing: buzz-relay *stores* 44100/44101 and serves history newest-first (default limit 2000), so an unscoped filter replayed the whole membership history on every connect — every stored add read as live, re-running discovery once each (M+1 discovery passes × N stored kind-39000 events per connect, observed live as two `channel discovery complete` lines and one channel logged `` because the 44100 path subscribed before its metadata arrived), re-subscribing channels we have since been removed from, and letting a stored 44101 transiently unsubscribe a channel we are still in. `since` is anchored at the moment the socket opened (`_session_started_at`) minus `MEMBERSHIP_LOOKBACK_SECONDS` (60) of slack, which covers both relay clock skew and a membership change published *during* the connect/auth handshake; the slack can only cost an idempotent replay of the last minute. **A relay `CLOSED` frame is recovered** — every subscription on the socket fails silently when dropped, so `_handle_closed` re-issues it, bounded by `MAX_RESUBSCRIBE_ATTEMPTS` (3) per subscription id per connection *and per auth epoch* (`_resubscribe_attempts` is reset on session start, on re-auth, and by `stop()`, so pre-auth rejections — which the auth branch already recovers wholesale — never spend the authenticated session's budget). The first retry is immediate (a one-off hiccup is the common case); later ones back off 1s then 2s, awaited inline in the read loop, not in a background task that could outlive its socket. **`auth-required:` before this socket has completed its NIP-42 handshake is the expected bootstrap sequence, not a refusal**, and `_handle_closed` short-circuits it ahead of every recovery path: the connector opens its control REQs immediately in case the relay serves unauthenticated reads, a closed relay answers `auth-required:` plus an `AUTH` challenge, and the auth branch re-opens everything. That case is logged at DEBUG and consumes neither the permanent-refusal branch nor the retry budget (a chat subscription is still dropped from `_chat_subscriptions`, since it genuinely is not subscribed and discovery is what re-opens it). Treating it as permanent produced a false operator-facing warning that discovery/membership tracking was DOWN while discovery then completed normally. The boundary is the per-socket `_auth_completed` flag, set once the signed AUTH event has been sent and cleared on session entry, session exit, and `stop()`; the same reason *after* that stays loud, and says the subscription is down until the relay's next AUTH challenge or the next reconnect rather than borrowing the non-auth wording. Then `_is_transient_close` decides whether to retry at all: NIP-01/NIP-42 `auth-required:`/`restricted:`/`blocked:`/`mute:`/`invalid:`/`pow:` prefixes and buzz-relay's own removal/revocation prose are permanent (do not fight the relay over a channel that is no longer ours), `rate-limited:`/`error:`/no-reason-at-all and anything unrecognized are transient — the default resolves toward "keep listening" because going silently deaf is the failure this exists to remove, and the attempt budget bounds a wrong guess. A chat `CLOSED` is only ever recovered for a channel already in `_chat_subscriptions`: a `CLOSED` is relay-supplied, so acting on an unknown one would let a relay induce a subscription just by naming a channel. Every subscription that goes unlistened is logged at WARNING, never INFO. Subscription ids are deterministic per channel so one can be replaced or closed without disturbing the others, and `_chat_subscriptions` is per-socket state cleared on session end, on re-auth (a pre-auth REQ may have been rejected), and by `stop()`. Three bounds on remote-fed state: `MAX_CACHED_CHANNELS` (512) caps the kind-39000 metadata cache, the watermark map, and the resubscribe-attempt map; `MAX_CHANNEL_SUBSCRIPTIONS` (256, well under buzz-relay's own 1024-per-connection ceiling) caps live chat subscriptions — at the cap new channels are refused and named in a warning rather than evicting a working subscription. **Backlog paging:** freeze the read floor and track `_backlog_until`; stop/warn on stalled timestamps, never skip a tied second. Removal/live close clears paging and closes backlog; ignore stale frames. Reset cursors per socket. Bounds: [subscription model](../../docs/IM_CHANNEL_CONNECTIONS.md#buzz-subscription-model). **Trust model** (operator-facing version in [IM_CHANNEL_CONNECTIONS.md](../../docs/IM_CHANNEL_CONNECTIONS.md#buzz-trust-model)): every inbound `EVENT` is authenticated at the single `handle_relay_frame` choke point — the NIP-01 id is recomputed from the delivered payload and the BIP-340 Schnorr signature verified against the claimed `pubkey` (`buzz_nostr.verify_event`, pure and total: malformed input returns `False`, never raises) — so `ev["pubkey"]`, the authorization principal for both the allowlist and the `/connect` bind, cannot be forged by a relay the DeerFlow operator does not run. What remains trusted is the *authorship* of kind-39000 channel metadata: any member can sign one, and because per-channel subscriptions are now driven by discovery, a forged kind-39000 has two effects rather than one — it can mark a channel `type: "dm"` (relaxing `require_mention` for that channel) **and** it can induce a chat subscription for a channel of the forger's choosing, since the channels we listen to are exactly the channels we hold metadata for. Neither makes anything be *acted on*: `allowed_users` and per-event signature verification are independent gates, so an induced subscription only means the relay reads its own traffic back to a subscriber that drops it, bounded by `MAX_CHANNEL_SUBSCRIPTIONS` (which refuses rather than evicts, so it cannot displace a real channel). Same for a forged kind-44100, except its `p` tag is re-checked locally so it must at least name us. Closing this needs a configured trusted relay pubkey, which `relay_url` is not. `allowed_users` is deny-by-default (empty = nobody, unlike siblings' empty = everyone), so `start()` logs a WARNING when it is empty and each drop logs at DEBUG. The resubscribe cursor (`since`) is **per channel**, advances only for events that were actually processed, and never past `now + MAX_FUTURE_SKEW_SECONDS`, because it is peer-supplied (`created_at`) and a single future-dated event otherwise made the connector permanently deaf. Per channel rather than global is the safety-critical half: one shared cursor is the newest event seen in *any* channel, so a busy channel would drag it past a quiet channel's unread messages, skipping them on the next reconnect. Per-channel cursors can only ever cost duplicate delivery (absorbed by the manager's `event_id` dedupe), and an evicted cursor degrades to "no `since`", i.e. the relay's default backlog — both fail toward replay, never toward a miss. Streaming tracks every oversize chunk index (`_stream_targets` for chunk 0, `_stream_tails` for the rest), since the manager republishes cumulative text and reposting `chunks[1:]` per update flooded the channel; all of it is per-connection state cleared by `stop()`, and the remote-fed kind-39000 cache is capped at `MAX_CACHED_CHANNELS`. **`send()` refuses outright to publish text carrying a hidden model-context wrapper** (``, ``, `` — `_HIDDEN_CONTEXT_MARKERS`), logging at ERROR and clearing the stream bookkeeping on a blocked `is_final`. This is defense in depth behind the manager's allowlist, and it lives here rather than in a sibling connector because on Buzz a leak is permanent: every streaming update is an immutable public Nostr event, so a corrective edit only changes what clients render while the original leaked event stays on the relay. Matching is on the literal opening tag, so a reply that merely talks about memory is still published Buzz seen-event shutdown stays bounded and retryable: `aflush()` awaits any in-flight write, attempts at most one final snapshot, leaves a still-changing generation dirty for fail-open replay, and returns without a live persistence timer. A Gateway cancellation does not cancel the underlying worker-thread write; `BuzzChannel.stop()` tracks cleanup completion separately from transport admission so ChannelService can retry the retained channel without racing a second snapshot against that write. The store is quiesced before stop (including the already-stopped guard), so a timed-out relay task that records after stop only marks data dirty and cannot schedule detached file work; a repeated `stop()` still drains that dirty state, while `BuzzChannel.start()` explicitly resumes scheduling and flushes it automatically. @@ -73,7 +73,7 @@ The cached value is reused for both the blocking (`runs.wait`) and streaming (`_ - WeCom outbound content is capped at the protocol's 20480 UTF-8 bytes: stream replies clip on a character boundary with a truncation marker (one stream carries the whole reply and cannot split mid-way), while proactive pushes split into at most 10 sequential markdown messages per push, with the remaining tail clipped and marker-terminated. Both paths measure bytes, not characters. A per-chat send lock serializes each split batch end to end, because manager workers run concurrently and two long pushes to the same chat would otherwise interleave chunks; locks are reference-counted and reclaimed once no sender holds or waits on them, so the registry does not grow for the life of the Gateway. - Frontend APIs: `GET /api/channels/providers`, `GET /api/channels/connections`, `POST /api/channels/{provider}/connect`, and `DELETE /api/channels/connections/{connection_id}`. - Browser APIs remain protected by normal Gateway auth/CSRF. Provider messages arrive through the already-configured channel workers. -- Runtime credential configure/disconnect treats the runtime-config file write and `app.state.channels_config` reconciliation as one cancellation-owned commit; do not let caller cancellation escape between them. +- Runtime credentials (`runtime_config_store.py`): encrypted `channel_runtime_configs` rows (JSON only for `memory`), re-read per request, never cached on `app.state`; a save is one cancellation-owned commit. - Provider-level `connection_status` reflects the user's newest connection row. With no binding it is `not_connected`, except in auth-disabled local mode where a configured running channel reports `connected` because all channel messages already route to the default user. - Slack replies use the configured operator bot token from `channels.slack` unless per-connection credentials are present; unreadable or corrupt stored credentials are treated as unavailable. - Telegram, Slack, Discord, Feishu/Lark, DingTalk, WeChat, and WeCom workers resolve incoming platform identities to connection records before reaching `ChannelManager`. diff --git a/backend/app/channels/runtime_config_store.py b/backend/app/channels/runtime_config_store.py index e03db79109..715170c110 100644 --- a/backend/app/channels/runtime_config_store.py +++ b/backend/app/channels/runtime_config_store.py @@ -1,4 +1,26 @@ -"""Local persistence for runtime IM channel configuration.""" +"""Persistence for IM channel configuration entered from the web UI ("runtime config"). + +An admin can connect a provider from the browser instead of editing +``config.yaml``: the credentials it enters, and a later disconnect, are stored +per provider and overlaid on the ``channels.*`` blocks by +:func:`merge_runtime_channel_configs`. Two stores share the +:class:`RuntimeConfigStore` protocol: + +- :class:`SqlChannelRuntimeConfigStore` keeps them in the + ``channel_runtime_configs`` table of the application database (SQLite or + PostgreSQL), so every Gateway instance reads the same rows. Each provider's + config is stored as ``DEER_FLOW_CREDENTIALS_KEY`` ciphertext + (``deerflow.config.credentials_key``); a disconnect is a plaintext tombstone + with no secret. Every save bumps the provider's ``version``, which the leader + lease supervisor in ``ChannelService`` polls to apply a save made on a peer. +- :class:`ChannelRuntimeConfigStore` is the historical JSON file + ``{base_dir}/channels/runtime-config.json`` (plaintext, mode 0600). It stays + for ``database.backend: memory`` (one process, nothing to share) and as the + source of the SQL store's one-time import, which deletes the file afterwards. + +:func:`resolve_runtime_config_store` picks one. Every store call may block (a +file or a database round trip), so async callers run it in a worker thread. +""" from __future__ import annotations @@ -7,16 +29,46 @@ import logging import os import tempfile import threading +import time from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any, Protocol + +if TYPE_CHECKING: + from deerflow.config.credentials_key import CredentialsCipher + from deerflow.persistence.channel_runtime_configs import SqlChannelRuntimeConfigRepository, StoredChannelRuntimeConfig logger = logging.getLogger(__name__) RUNTIME_CHANNEL_DISABLED_FLAG = "_runtime_disabled" +class ChannelRuntimeConfigEncryptionUnavailable(RuntimeError): + """The database store has no credentials key, so it refuses to persist credentials.""" + + +class RuntimeConfigStore(Protocol): + """Provider -> runtime config block, as entered from the web UI. Calls may block.""" + + @property + def can_store_credentials(self) -> bool: + """False when :meth:`set_provider_config` would refuse (no encryption key for the database).""" + ... + + def load_all(self) -> dict[str, dict[str, Any]]: ... + + def get_provider_config(self, provider: str) -> dict[str, Any] | None: ... + + def set_provider_config(self, provider: str, config: dict[str, Any]) -> None: ... + + def set_provider_disconnected(self, provider: str) -> None: ... + + def versions(self) -> dict[str, int]: + """``provider -> version`` that changes on every save, for noticing saves made by another instance.""" + ... + + @contextmanager def _runtime_config_file_lock(path: Path) -> Iterator[None]: """Exclude read-modify-write cycles of this file in other Gateway processes. @@ -58,15 +110,15 @@ class ChannelRuntimeConfigStore: This intentionally mirrors ``JsonChannelStore``: local/private deployments get durable runtime configuration without needing a public callback URL or a - config.yaml edit. + config.yaml edit. It serves ``database.backend: memory`` (a single process); + a sqlite/postgres database uses :class:`SqlChannelRuntimeConfigStore`. """ - def __init__(self, path: str | Path | None = None) -> None: - if path is None: - from deerflow.config.paths import get_paths + #: The file is plaintext (mode 0600), as it always was; there is no key to miss. + can_store_credentials = True - path = Path(get_paths().base_dir) / "channels" / "runtime-config.json" - self._path = Path(path) + def __init__(self, path: str | Path | None = None) -> None: + self._path = Path(path) if path is not None else default_runtime_config_path() self._path.parent.mkdir(parents=True, exist_ok=True) self._data: dict[str, dict[str, Any]] = self._load() self._lock = threading.Lock() @@ -158,32 +210,238 @@ class ChannelRuntimeConfigStore: self._save(data) return True + def versions(self) -> dict[str, int]: + # One process owns the file (a ``memory`` database cannot be shared), so + # every save already went through this process: there is no peer save + # to notice. + return {} + + +_TOMBSTONE: dict[str, Any] = {"enabled": False, RUNTIME_CHANNEL_DISABLED_FLAG: True} + + +class SqlChannelRuntimeConfigStore: + """Database-backed store over ``channel_runtime_configs``, shared by every instance using the database. + + ``cipher`` is the deployment ``CredentialsCipher``. Without one a + credential save raises :class:`ChannelRuntimeConfigEncryptionUnavailable` + rather than storing plaintext, and stored credentials read as not + configured; disconnect tombstones need no key either way. A row the key + cannot decrypt (lost or replaced key) also reads as not configured, with + one error per row version. + """ + + def __init__(self, repo: SqlChannelRuntimeConfigRepository, *, cipher: CredentialsCipher | None, legacy_path: str | Path | None = None) -> None: + self._repo = repo + self._cipher = cipher + self._legacy_path = Path(legacy_path) if legacy_path is not None else None + self._reported: set[tuple[str, int]] = set() + + @property + def legacy_path(self) -> Path | None: + """The ``runtime-config.json`` that :meth:`import_legacy_json` moves into the table.""" + return self._legacy_path + + @property + def can_store_credentials(self) -> bool: + return self._cipher is not None + + def load_all(self) -> dict[str, dict[str, Any]]: + configs: dict[str, dict[str, Any]] = {} + for row in self._repo.list_all(): + config = self._decode(row) + if config is not None: + configs[row.provider] = config + return configs + + def get_provider_config(self, provider: str) -> dict[str, Any] | None: + row = self._repo.get(provider) + return self._decode(row) if row is not None else None + + def set_provider_config(self, provider: str, config: dict[str, Any]) -> None: + self._repo.save(provider, config_ciphertext=self._encrypt(config), disconnected=False, now=time.time()) + + def set_provider_disconnected(self, provider: str) -> None: + self._repo.save(provider, config_ciphertext=None, disconnected=True, now=time.time()) + + def versions(self) -> dict[str, int]: + return self._repo.versions() + + def import_legacy_json(self) -> int: + """Move ``runtime-config.json`` into the table once, then delete it; returns how many rows this call inserted. + + Every well-formed entry is inserted with ``ON CONFLICT DO NOTHING``: a + provider already in the table keeps its row (it was saved after the + table took over, so it is newer than the file), any other provider is + imported, and two instances importing the same file at once neither + duplicate nor clobber a row. The file is then deleted, not renamed: a + plaintext copy left on disk would keep the credentials the table + encrypts. No file is a no-op; a corrupt file is kept and reported, and + so is a file with credentials while there is no key to encrypt them. + """ + from deerflow.persistence.channel_runtime_configs import CHANNEL_RUNTIME_CONFIG_PROVIDER_LENGTH, StoredChannelRuntimeConfig + + path = self._legacy_path + if path is None: + return 0 + entries = _read_legacy_file(path) + if entries is None: + return 0 + rows: list[StoredChannelRuntimeConfig] = [] + skipped = 0 + for provider, config in entries.items(): + if not isinstance(config, dict) or not provider or len(provider) > CHANNEL_RUNTIME_CONFIG_PROVIDER_LENGTH: + skipped += 1 + continue + if runtime_channel_disconnected(config): + rows.append(StoredChannelRuntimeConfig(provider=provider, config_ciphertext=None, disconnected=True, version=1)) + continue + if self._cipher is None: + logger.error("Channel runtime config %s holds credentials but no credentials key is available to encrypt them; keeping the file and not importing it", path) + return 0 + rows.append(StoredChannelRuntimeConfig(provider=provider, config_ciphertext=self._encrypt(config), disconnected=False, version=1)) + if skipped: + logger.warning("Skipping %d malformed entries in channel runtime config %s (not an object, or an empty or oversized provider name)", skipped, path) + inserted = self._repo.insert_missing(rows, now=time.time()) + removed = _remove_legacy_file(path) + logger.info( + "Imported %d of %d channel runtime configs from %s into channel_runtime_configs%s", + inserted, + len(rows), + path, + "; deleted the plaintext file" if removed else " (file already removed by a peer)", + ) + return inserted + + def _encrypt(self, config: dict[str, Any]) -> str: + if self._cipher is None: + raise ChannelRuntimeConfigEncryptionUnavailable("channel credentials cannot be stored: the DEER_FLOW_CREDENTIALS_KEY credentials key is unavailable") + return self._cipher.encrypt_text(json.dumps(config, ensure_ascii=False)) + + def _decode(self, row: StoredChannelRuntimeConfig) -> dict[str, Any] | None: + if row.disconnected: + return dict(_TOMBSTONE) + if row.config_ciphertext is None: + return None + if self._cipher is None: + self._report(row, "Channel runtime config for %s is stored encrypted but no DEER_FLOW_CREDENTIALS_KEY credentials key is available; treating the provider as not configured") + return None + from deerflow.config.credentials_key import CredentialsDecryptError + + try: + value = json.loads(self._cipher.decrypt_text(row.config_ciphertext)) + except (CredentialsDecryptError, json.JSONDecodeError): + self._report( + row, "Channel runtime config for %s cannot be decrypted with the configured DEER_FLOW_CREDENTIALS_KEY; treating the provider as not configured until the key that wrote it is restored or its credentials are saved again" + ) + return None + return dict(value) if isinstance(value, dict) else None + + def _report(self, row: StoredChannelRuntimeConfig, message: str) -> None: + key = (row.provider, row.version) + if key not in self._reported: + self._reported.add(key) + logger.error(message, row.provider) + + +def _read_legacy_file(path: Path) -> dict[str, Any] | None: + """Parse ``runtime-config.json``; ``None`` when it is missing, unreadable or not an object (kept in place).""" + try: + raw = path.read_text(encoding="utf-8") + except FileNotFoundError: + return None + except OSError: + logger.warning("Cannot read channel runtime config %s; skipping the import (file kept)", path, exc_info=True) + return None + try: + data = json.loads(raw) + except json.JSONDecodeError: + data = None + if not isinstance(data, dict): + logger.warning("Corrupt channel runtime config %s; skipping the import (file kept)", path) + return None + return data + + +def _remove_legacy_file(path: Path) -> bool: + """Delete the imported plaintext file; ``False`` when a peer already did.""" + try: + path.unlink() + except FileNotFoundError: + return False + except OSError: + logger.warning("Imported channel runtime config %s but could not delete it; it still holds plaintext credentials, remove it by hand", path, exc_info=True) + return False + return True + + +def default_runtime_config_path() -> Path: + """``{base_dir}/channels/runtime-config.json`` (resolves ``base_dir`` through realpath: call off the loop).""" + from deerflow.config.paths import get_paths + + return Path(get_paths().base_dir) / "channels" / "runtime-config.json" + + +def resolve_runtime_config_store(app_config: Any, *, cipher: CredentialsCipher | None, path: str | Path | None = None) -> RuntimeConfigStore: + """Pick the store for ``database.backend``: the JSON file for ``memory`` (or no config), the table for a database. + + The table needs the persistence engine the Gateway lifespan initialises + (its Alembic bootstrap creates the table); without it a configured + database falls back to the JSON file with a warning, so a bare + ``ChannelService`` keeps working. ``path`` is the JSON file (default + :func:`default_runtime_config_path`), also the table's import source. + Blocks (path resolution, the JSON file's first read): call off the loop. + """ + database = getattr(app_config, "database", None) + backend = getattr(database, "backend", None) + store_path = Path(path) if path is not None else default_runtime_config_path() + if backend in ("sqlite", "postgres"): + from deerflow.persistence.engine import get_session_factory + + if get_session_factory() is not None: + from deerflow.persistence.agents.sql import get_sync_sessionmaker + from deerflow.persistence.channel_runtime_configs import SqlChannelRuntimeConfigRepository + + repo = SqlChannelRuntimeConfigRepository(get_sync_sessionmaker(database.app_sync_sqlalchemy_url)) + return SqlChannelRuntimeConfigStore(repo, cipher=cipher, legacy_path=store_path) + logger.warning("database.backend=%s but no persistence engine is initialised; IM channel runtime config falls back to %s for this process", backend, store_path) + return ChannelRuntimeConfigStore(store_path) + def _provider_enabled(channel_connections_config: Any, provider: str) -> bool: provider_config = getattr(channel_connections_config, provider, None) return bool(getattr(provider_config, "enabled", False)) -def _runtime_channel_disconnected(runtime_config: dict[str, Any]) -> bool: +def runtime_channel_disconnected(runtime_config: dict[str, Any]) -> bool: return runtime_config.get(RUNTIME_CHANNEL_DISABLED_FLAG) is True and runtime_config.get("enabled") is False -def merge_runtime_channel_configs( +def overlay_runtime_channel_configs( channels_config: dict[str, Any], channel_connections_config: Any, + runtime_configs: dict[str, dict[str, Any]], *, - store: ChannelRuntimeConfigStore | None = None, + keep_disconnected: bool = False, ) -> None: - """Merge persisted runtime provider config into ``channels_config`` in-place.""" + """Overlay already-loaded runtime configs onto ``channels_config`` in place. + + The runtime block wins key by key over the ``config.yaml`` block. A + disconnect removes the provider, or with ``keep_disconnected`` leaves the + tombstone in its place (a disabled block), so a single-provider reload can + tell "disconnected" from "absent". + """ if channel_connections_config is None or not getattr(channel_connections_config, "enabled", False): return - runtime_store = store or ChannelRuntimeConfigStore() - for provider, runtime_config in runtime_store.load_all().items(): + for provider, runtime_config in runtime_configs.items(): if not _provider_enabled(channel_connections_config, provider): continue - if _runtime_channel_disconnected(runtime_config): - channels_config.pop(provider, None) + if runtime_channel_disconnected(runtime_config): + if keep_disconnected: + channels_config[provider] = dict(runtime_config) + else: + channels_config.pop(provider, None) continue existing = channels_config.get(provider) merged = dict(existing) if isinstance(existing, dict) else {} @@ -191,22 +449,33 @@ def merge_runtime_channel_configs( channels_config[provider] = merged +def merge_runtime_channel_configs( + channels_config: dict[str, Any], + channel_connections_config: Any, + *, + store: RuntimeConfigStore, +) -> None: + """Merge persisted runtime provider config into ``channels_config`` in-place (blocks: reads ``store``).""" + if channel_connections_config is None or not getattr(channel_connections_config, "enabled", False): + return + overlay_runtime_channel_configs(channels_config, channel_connections_config, store.load_all()) + + def apply_runtime_connection_config( channel_connections_config: Any, *, - store: ChannelRuntimeConfigStore | None = None, + store: RuntimeConfigStore, ) -> Any: """Apply persisted connection metadata that lives outside ``channels``. Telegram uses a bot username for deep links; UI-entered values are stored with the runtime channel config so local restarts keep the provider - configured. + configured. Blocks: reads ``store``. """ if channel_connections_config is None or not getattr(channel_connections_config, "enabled", False): return channel_connections_config - runtime_store = store or ChannelRuntimeConfigStore() - telegram_runtime_config = runtime_store.get_provider_config("telegram") + telegram_runtime_config = store.get_provider_config("telegram") bot_username = "" if isinstance(telegram_runtime_config, dict): bot_username = str(telegram_runtime_config.get("bot_username") or "").strip() diff --git a/backend/app/channels/service.py b/backend/app/channels/service.py index f35ad04269..66ce7429bb 100644 --- a/backend/app/channels/service.py +++ b/backend/app/channels/service.py @@ -16,7 +16,7 @@ from app.channels.base import Channel, ChannelStopTimeout from app.channels.leadership import ChannelLeadership, RenewOutcome from app.channels.manager import DEFAULT_CHANNEL_MAX_CONCURRENCY, DEFAULT_CHANNEL_SHUTDOWN_GRACE_PERIOD_SECONDS, DEFAULT_GATEWAY_URL, DEFAULT_LANGGRAPH_URL, ChannelManager from app.channels.message_bus import DEFAULT_INBOUND_QUEUE_MAXSIZE, MessageBus -from app.channels.runtime_config_store import merge_runtime_channel_configs +from app.channels.runtime_config_store import RuntimeConfigStore, SqlChannelRuntimeConfigStore, merge_runtime_channel_configs, overlay_runtime_channel_configs, resolve_runtime_config_store, runtime_channel_disconnected from app.channels.store import ChannelStore, SqlChannelStore, resolve_channel_store from deerflow.config.channel_leader_lease_config import CHANNEL_LEADER_LEASE_FIELD, CHANNEL_LEADER_LEASE_KEY, ChannelLeaderLeaseConfig, channel_leader_lease_config from deerflow.utils.file_io import await_drained @@ -132,9 +132,26 @@ def _resolve_non_negative_float(config: dict[str, Any], config_key: str, default return float(value) -def _merge_channel_connection_runtime_config(channels_config: dict[str, Any], app_config: AppConfig) -> None: +def _runtime_config_enabled(app_config: Any) -> bool: connection_config = getattr(app_config, "channel_connections", None) - merge_runtime_channel_configs(channels_config, connection_config) + return connection_config is not None and bool(getattr(connection_config, "enabled", False)) + + +def _prepare_runtime_config(channels_config: dict[str, Any], app_config: AppConfig, *, credentials_cipher: Any | None) -> RuntimeConfigStore | None: + """Overlay the web-UI runtime config on ``channels_config`` and return the store it came from. + + ``None`` when ``channel_connections`` is off (no runtime config applies). + The database store first moves a pre-table ``runtime-config.json`` into + the table (idempotent, tolerant of a peer importing concurrently), so the + overlay already sees it. Blocks: ``from_app_config`` runs off the loop. + """ + if not _runtime_config_enabled(app_config): + return None + store = resolve_runtime_config_store(app_config, cipher=credentials_cipher) + if isinstance(store, SqlChannelRuntimeConfigStore): + store.import_legacy_json() + merge_runtime_channel_configs(channels_config, app_config.channel_connections, store=store) + return store def _make_connection_repo(connection_config: ChannelConnectionsConfig | None, *, credentials_cipher: Any | None = None): @@ -199,6 +216,8 @@ class ChannelService: get_stream_bridge: Callable[[], StreamBridge | None] | None = None, store: ChannelStore | None = None, leadership: ChannelLeadership | None = None, + runtime_config_store: RuntimeConfigStore | None = None, + credentials_cipher: Any | None = None, ) -> None: config = dict(channels_config or {}) # ``channels.leader_lease`` is a settings block, not a provider: take it @@ -254,6 +273,13 @@ class ChannelService: self._lease_actions: dict[str, asyncio.Task] = {} # provider -> (consecutive failed starts, monotonic time of next retry) self._lease_start_backoff: dict[str, tuple[int, float]] = {} + # Web-UI runtime config (``channel_runtime_configs`` for a database). + # Resolved on first reload when not given; the cipher decrypts it then. + self._runtime_config_store = runtime_config_store + self._credentials_cipher = credentials_cipher + # provider -> runtime config version this instance has applied; the + # lease supervisor compares it with the store to apply peers' saves. + self._runtime_config_versions: dict[str, int] = {} @classmethod def from_app_config( @@ -286,7 +312,7 @@ class ChannelService: extra = app_config.model_extra or {} if "channels" in extra: channels_config = dict(extra["channels"] or {}) - _merge_channel_connection_runtime_config(channels_config, app_config) + runtime_config_store = _prepare_runtime_config(channels_config, app_config, credentials_cipher=credentials_cipher) connection_config = getattr(app_config, "channel_connections", None) connections_enabled = connection_config is not None and getattr(connection_config, "enabled", False) require_bound_identity = bool(connections_enabled and getattr(connection_config, "require_bound_identity", True)) @@ -299,6 +325,8 @@ class ChannelService: app_config=app_config, get_stream_bridge=get_stream_bridge, leadership=leadership, + runtime_config_store=runtime_config_store, + credentials_cipher=credentials_cipher, ) async def start(self) -> None: @@ -493,31 +521,48 @@ class ChannelService: logger.info("ChannelService stopped") def _load_channel_config(self, name: str) -> dict[str, Any] | None: - """Load the latest config for a specific channel from disk. + """Load the latest config for a specific channel (see :meth:`_read_channel_config`). - Uses ``get_app_config()`` which detects file changes via config - signature, so edits to ``config.yaml`` are picked up without a process - restart. - The UI runtime-config overlay applied at startup is re-applied here - so a file-driven reload neither drops credentials entered from the - browser nor resurrects a channel disconnected from it. Returns a snapshot without mutating shared state, or ``None`` when unavailable. The restart caller owns publication and cached fallback. """ try: - from deerflow.config.app_config import get_app_config - - app_config = get_app_config() - extra = app_config.model_extra or {} - channels_config = dict(extra.get("channels") or {}) - _merge_channel_connection_runtime_config(channels_config, app_config) - channel_config = channels_config.get(name) - if isinstance(channel_config, dict): - return channel_config + return self._read_channel_config(name) except Exception: logger.exception("Failed to load config snapshot for channel %s", name) return None + def _read_channel_config(self, name: str) -> dict[str, Any] | None: + """Read ``name``'s current config; blocks (call off the loop) and raises on failure. + + Uses ``get_app_config()`` which detects file changes via config + signature, so edits to ``config.yaml`` are picked up without a process + restart. The web-UI runtime config is re-read from its store and + overlaid, so a reload neither drops credentials entered from the + browser (on any instance) nor resurrects a channel disconnected from + it. A disconnect reads as its disabled tombstone, not as absent: a + caller that falls back to its cached config for an absent provider + must not revive credentials a peer disconnected. + """ + from deerflow.config.app_config import get_app_config + + app_config = get_app_config() + extra = app_config.model_extra or {} + channels_config = dict(extra.get("channels") or {}) + store = self._runtime_store(app_config) + if store is not None: + overlay_runtime_channel_configs(channels_config, app_config.channel_connections, store.load_all(), keep_disconnected=True) + channel_config = channels_config.get(name) + return dict(channel_config) if isinstance(channel_config, dict) else None + + def _runtime_store(self, app_config: Any) -> RuntimeConfigStore | None: + """The runtime config store, resolved on first use (blocks); ``None`` while ``channel_connections`` is off.""" + if not _runtime_config_enabled(app_config): + return None + if self._runtime_config_store is None: + self._runtime_config_store = resolve_runtime_config_store(app_config, cipher=self._credentials_cipher) + return self._runtime_config_store + def _channel_lock(self, name: str) -> asyncio.Lock: """Return the per-channel lifecycle lock ensuring serialized mutations.""" return self._readiness_locks.setdefault(name, asyncio.Lock()) @@ -591,9 +636,9 @@ class ChannelService: if not await self._claim_transport(name): leader = self.leader_of(name) if accept_peer_leader and leader is not None: - # Runtime config does not reach the holder yet: it keeps the - # config it started with until it starts the channel again. - logger.warning("Channel %s is connected by Gateway instance %s, which keeps its current configuration until it next starts the channel", name, leader) + # The caller persists the config to the shared runtime config + # store; the holder applies it on its next lease round. + logger.info("Channel %s is connected by Gateway instance %s, which applies the saved configuration on its next leader lease round", name, leader) return True return False @@ -778,6 +823,8 @@ class ChannelService: # running on every instance. ``_supervise`` renews held leases every # ``renew_interval`` seconds, takes free ones, and stops a transport # *before* giving its lease up for lost (see ``app.channels.leadership``). + # The same round applies web-UI runtime config saved on any instance: the + # store's per-provider ``version`` says which providers to re-read. def _arbitrated(self, name: str) -> bool: """Whether ``name``'s transport is subject to the leader lease in this process.""" @@ -822,8 +869,8 @@ class ChannelService: its own transport, and a claim here would only park the row for the channel-down interval. The peer check covers a provider connected from the web UI on another instance, which never enters this instance's - config. Providers no instance runs stay claimable, so their rows still - settle. + config until its next round applies the runtime config. Providers no + instance runs stay claimable, so their rows still settle. """ if self._leadership is None: return None @@ -870,9 +917,23 @@ class ChannelService: # handed to per-provider tasks so it never delays a renewal. The # whole-table read keeps status and notification claims aware of # leases this instance has no config for. - observed, *decisions = await asyncio.gather(self._leadership.observe_all(), *(self._lease_round(name) for name in ordered), return_exceptions=True) + observed, versions, *decisions = await asyncio.gather( + self._leadership.observe_all(), + self._read_runtime_config_versions(), + *(self._lease_round(name) for name in ordered), + return_exceptions=True, + ) if isinstance(observed, BaseException): logger.error("Channel leader lease table read failed", exc_info=observed) + if isinstance(versions, BaseException): + logger.error("Channel runtime config versions read failed; retrying on the next tick", exc_info=versions) + elif self._running: + # Scheduled before the lease decisions: applying a provider's new + # config outranks a plain start of the same provider this round, + # while a fail-closed stop below still preempts it. + for name, version in sorted(versions.items()): + if self._arbitrated(name) and self._runtime_config_versions.get(name) != version: + self._schedule_lease_action(name, lambda name=name, version=version: self._apply_runtime_config(name, version), preempt=False) for name, decision in zip(ordered, decisions): if isinstance(decision, BaseException): logger.error("Channel %s leader lease round failed", name, exc_info=decision) @@ -915,6 +976,64 @@ class ChannelService: return (lambda: self._start_led_transport(name, reload_config=True)), False return None + async def _read_runtime_config_versions(self) -> dict[str, int]: + store = self._runtime_config_store + if store is None: + return {} + return await asyncio.wait_for(asyncio.to_thread(store.versions), timeout=self._leadership.operation_timeout) + + async def _apply_runtime_config(self, name: str, version: int) -> None: + """Apply the runtime config of ``name`` as saved on any instance, then record ``version``. + + Acts only when the freshly read config differs from the one this + instance runs on: a transport running here restarts with it, or stops + and hands its lease back when the provider was disabled or + disconnected, and a held lease whose transport is down (a start that + failed on the old credentials) starts it now rather than on the next + round. Without a lease here only the cached config changes, so the + next lease round competes for the provider (or leaves it) on current + credentials. A read that races a local reconfiguration is dropped + unrecorded, and so is a failed one: the next round retries. + """ + if not self._running: + return + epoch = self._config_epochs.get(name, 0) + config = await asyncio.to_thread(self._read_channel_config, name) + async with self._channel_lock(name): + if not self._running or self._config_epochs.get(name, 0) != epoch: + return + current = self._config.get(name) + if config is not None and current is None and runtime_channel_disconnected(config): + config = None # a disconnect this instance already applied by never loading the provider + started = False + if config != current: + self._bump_config_epoch(name) + try: + if config is None: + self._config.pop(name, None) + else: + self._config[name] = config + # New credentials deserve an immediate start, not the backoff earned by the old ones. + self._lease_start_backoff.pop(name, None) + channel = self._channels.get(name) + if channel is not None: + if self._wants_transport(name): + await self._restart_channel_locked(name, reload_config=False) + else: + await self._stop_and_discard_channel(name, channel) + elif self._wants_transport(name) and self._leadership.has_record(name): + await self._restart_channel_locked(name, reload_config=False) + started = True + if name not in self._channels: + await self._release_idle_lease(name) + finally: + self._bump_config_epoch(name) + logger.info("Applied runtime config version %d of channel %s", version, name) + self._runtime_config_versions[name] = version + if started: + # Same retry bookkeeping as a start from the lease round. + self._record_lease_start(name, ok=self._transport_running(name) or not self._wants_transport(name)) + def _schedule_lease_action(self, name: str, action: Callable[[], Awaitable[None]], *, preempt: bool) -> None: current = self._lease_actions.get(name) if current is not None and not current.done(): diff --git a/backend/app/gateway/deps.py b/backend/app/gateway/deps.py index 9a97340dac..230bb67838 100644 --- a/backend/app/gateway/deps.py +++ b/backend/app/gateway/deps.py @@ -303,7 +303,8 @@ def credentials_key_consumers(config: AppConfig) -> list[str]: consumers: list[str] = [] connections = getattr(config, "channel_connections", None) if connections is not None and getattr(connections, "enabled", False): - # ChannelConnectionRepository encrypts per-connection credentials. + # ChannelConnectionRepository encrypts per-connection credentials, and + # the runtime config store the bot credentials entered in the web UI. consumers.append("channel_connections.enabled=true") return consumers diff --git a/backend/app/gateway/routers/channel_connections.py b/backend/app/gateway/routers/channel_connections.py index 572db0213d..adc5426145 100644 --- a/backend/app/gateway/routers/channel_connections.py +++ b/backend/app/gateway/routers/channel_connections.py @@ -14,9 +14,10 @@ from pydantic import BaseModel, Field from app.channels.capabilities import supports_proactive_group_notifications, supports_proactive_notifications from app.channels.runtime_config_store import ( - ChannelRuntimeConfigStore, + RuntimeConfigStore, apply_runtime_connection_config, merge_runtime_channel_configs, + resolve_runtime_config_store, ) from app.channels.wechat_qr_login import QRLoginError, WechatQRLogin from app.gateway.deps import require_admin_user @@ -182,34 +183,34 @@ def _get_app_config(): return get_app_config() -async def _get_runtime_config_store(request: Request) -> ChannelRuntimeConfigStore: +async def _get_runtime_config_store(request: Request) -> RuntimeConfigStore: + """The runtime config store, resolved once per process; every call on it blocks, so offload them.""" store = getattr(request.app.state, "channel_runtime_config_store", None) - if isinstance(store, ChannelRuntimeConfigStore): + if store is not None: return store - # Constructing the store reads its JSON file from disk; keep it off the - # event loop. - store = await asyncio.to_thread(ChannelRuntimeConfigStore) + # Resolving reads paths (and the JSON store's file) from disk; keep it off + # the event loop. The database store holds no state of its own. + store = await asyncio.to_thread(resolve_runtime_config_store, _get_app_config(), cipher=getattr(request.app.state, "credentials_cipher", None)) request.app.state.channel_runtime_config_store = store return store async def _get_channel_connections_config(request: Request) -> ChannelConnectionsConfig: + # Re-read on every request, never cached on app.state: another Gateway + # instance may have saved the runtime config (e.g. the Telegram username) + # since the last one. config = getattr(request.app.state, "channel_connections_config", None) if not isinstance(config, ChannelConnectionsConfig): config = _get_app_config().channel_connections - config = apply_runtime_connection_config(config, store=await _get_runtime_config_store(request)) - request.app.state.channel_connections_config = config - return config + if not (config.enabled and config.telegram.enabled): + # Only the Telegram deep-link username comes from the runtime store. + return config + return await asyncio.to_thread(apply_runtime_connection_config, config, store=await _get_runtime_config_store(request)) async def _get_channels_config(request: Request) -> dict[str, Any]: - state_config = getattr(request.app.state, "channels_config", None) - if isinstance(state_config, dict): - return state_config - - result = await _load_channels_config(request, await _get_channel_connections_config(request)) - request.app.state.channels_config = result - return result + """``channels.*`` from config.yaml with the runtime config overlaid, read fresh for every request.""" + return await _load_channels_config(request, await _get_channel_connections_config(request)) async def _load_channels_config(request: Request, config: ChannelConnectionsConfig) -> dict[str, Any]: @@ -217,11 +218,7 @@ async def _load_channels_config(request: Request, config: ChannelConnectionsConf extra = app_config.model_extra or {} channels_config = extra.get("channels") result = dict(channels_config) if isinstance(channels_config, dict) else {} - merge_runtime_channel_configs( - result, - config, - store=await _get_runtime_config_store(request), - ) + await asyncio.to_thread(merge_runtime_channel_configs, result, config, store=await _get_runtime_config_store(request)) return result @@ -743,7 +740,11 @@ async def _commit_runtime_channel_config( provider: str, runtime_config: dict[str, Any] | None, ) -> dict[str, Any]: - """Persist one runtime config change and reconcile the live cache atomically to cancellation.""" + """Persist one runtime config change, owned across cancellation, and return the config as now stored. + + The write bumps the provider's version in a database store, which is how + the instance holding the provider's leader lease learns about it. + """ async def _commit() -> dict[str, Any]: store = await _get_runtime_config_store(request) @@ -751,22 +752,21 @@ async def _commit_runtime_channel_config( await run_drained_write("Disconnect channel runtime config", store.set_provider_disconnected, (), provider) else: await run_drained_write("Save channel runtime config", store.set_provider_config, (), provider, runtime_config) - - # Re-read the live cached config after the durable write so concurrent - # mutations for sibling providers are preserved. The outer drain keeps - # cancellation owned until this in-memory reconciliation also lands. - live_channels_config = await _get_channels_config(request) - if runtime_config is None: - live_channels_config.pop(provider, None) - else: - live_channels_config[provider] = runtime_config - request.app.state.channels_config = live_channels_config - return live_channels_config + # Read back, so the response also reflects sibling providers saved + # meanwhile (on this or another instance). + return await _get_channels_config(request) return await await_drained(_commit()) async def _apply_runtime_channel_config(request: Request, config: ChannelConnectionsConfig, provider: str, runtime_config: dict[str, Any]) -> ChannelProviderResponse: + # Refuse before starting anything: a transport started on credentials the + # store then cannot persist would run on settings nobody can see. + if not (await _get_runtime_config_store(request)).can_store_credentials: + raise HTTPException( + status_code=503, + detail="Channel credentials cannot be stored: the credentials encryption key (DEER_FLOW_CREDENTIALS_KEY) is unavailable. Check the Gateway logs, or configure the channel in config.yaml.", + ) started = await _restart_runtime_channel_if_available(provider, runtime_config) if started is False: display_name = _PROVIDER_META[provider]["display_name"] diff --git a/backend/docs/API.md b/backend/docs/API.md index 60be71c3e8..2232432a07 100644 --- a/backend/docs/API.md +++ b/backend/docs/API.md @@ -1734,6 +1734,19 @@ see `backend/docs/CONFIGURATION.md` for the events and the merge rule. { "provider": "wecom", "display_name": "WeCom", "connection_status": "connected", "proactive_notifications": true } ``` +**Runtime bot credentials.** `POST /api/channels/{provider}/runtime-config` +(body `{"values": {...}}`, keyed by the provider's `credential_fields`) and +`DELETE /api/channels/{provider}/runtime-config` are admin-only; they save or +disconnect the deployment's bot for that provider and answer with its provider +item. Password values come back masked (`********`); sending the mask back +keeps the stored value. A save whose channel fails to start on the serving +instance, or a disconnect whose channel fails to stop there, answers `400` and +stores nothing (under `channels.leader_lease` a non-holder stores the save and +the holder applies it on its next renewal tick). With a SQLite or +PostgreSQL database the values are stored encrypted with +`DEER_FLOW_CREDENTIALS_KEY` and shared by every Gateway instance; without a +usable key a save answers `503`. See `backend/docs/IM_CHANNEL_CONNECTIONS.md`. + --- ## Error Responses diff --git a/backend/docs/CONFIGURATION.md b/backend/docs/CONFIGURATION.md index 2a673b557e..f2d344d71a 100644 --- a/backend/docs/CONFIGURATION.md +++ b/backend/docs/CONFIGURATION.md @@ -822,14 +822,14 @@ Every IM channel except GitHub connects outbound to its platform (Telegram long - Ownership is decided against the **database clock** inside each SQL statement (an expired lease changes hands only once it has been expired for `grace_seconds`, and every acquisition bumps a fencing `epoch`), so clock skew between hosts cannot hand a provider to two instances. The holder fails closed on its own monotonic clock: when a renewal is rejected, or cannot be confirmed for long enough that the next renewal would come too late, it stops the transport first — at least `grace_seconds` before a peer is allowed to connect. - Every instance tries to take every free lease of a provider it has enabled, so providers spread across instances by whoever starts first. A holder whose transport fails to start keeps the lease and retries with backoff (up to 5 minutes); a transport that cannot be stopped within its bounded teardown keeps its lease until it expires rather than invite a second connection. - `GET /api/channels/` reports, per arbitrated provider, `leader` (the holder's instance id, the RunManager worker id `hostname:uuid`) and `leader_here`, and `running` reflects the holder's transport on every instance, so `GET /api/channels/providers` and `POST /api/channels/{provider}/connect` behave the same wherever the load balancer sends them. `POST /api/channels/{name}/restart` on a non-holder answers `success: false` and names the holder. Scheduled-task IM notifications are claimed only by the holder of their provider. -- Runtime channel configuration does not cross instances yet: `POST /api/channels/{provider}/runtime-config` saves the values (in the shared `runtime-config.json`) and applies them only where the provider's transport runs — a non-holder accepts them without restarting the holder, which keeps its current credentials until it next starts the channel (an instance taking a lease over reloads the provider's saved config first). Make credential changes on a single instance or restart the holder afterwards. +- Runtime channel configuration crosses instances: `POST` / `DELETE /api/channels/{provider}/runtime-config` writes the provider's row in the shared `channel_runtime_configs` table (migration `0044_channel_runtime_configs`, encrypted with [`DEER_FLOW_CREDENTIALS_KEY`](#credentials-encryption-key-deer_flow_credentials_key)) and bumps its `version`. Every instance compares those versions on each renewal tick, so credentials saved or a disconnect made on any instance reach the holder within one renewal interval: it restarts the transport with the new credentials (or starts it, if a start on the old ones had failed), or stops it and releases the lease. A save served by a non-holder answers before the holder has tried the credentials; a failed restart shows as `running: false` and retries with the usual backoff. An instance taking a lease over reads the provider's current config, a disconnect included, before connecting. - The block is validated on every topology: an unknown key, a non-mapping value, `enabled` outside `auto | true | false`, `lease_seconds < 3` or `grace_seconds < 0` stop startup with the dotted path in the message. - Restart-required (`channels.leader_lease` in the reload-boundary registry): the gate evaluates it once and `ChannelService` captures it at construction. Change it on every instance and restart them together. - Known limits: a leader change loses the IM replies in flight on the old holder. The runs themselves continue on the Gateway executing them (channel runs are created with `on_disconnect: continue`) and their thread state is persisted, so the answer stays readable in the web UI, but the transport-local state that would deliver it (a Telegram placeholder message, a Feishu running card, a DingTalk replier) is gone with the old holder; a run executing on the instance that died is recovered as an error like any run of a dead worker. ### Credentials encryption key (`DEER_FLOW_CREDENTIALS_KEY`) -DeerFlow encrypts credentials it stores at rest (today: per-connection IM channel credentials in the `channel_credentials` table) with a deployment key read **only** from the environment — there is no `config.yaml` key, and it is never derived from `AUTH_JWT_SECRET`. +DeerFlow encrypts credentials it stores at rest (today: per-connection IM channel credentials in the `channel_credentials` table, and the IM bot credentials an admin enters in the web UI, in `channel_runtime_configs`) with a deployment key read **only** from the environment — there is no `config.yaml` key, and it is never derived from `AUTH_JWT_SECRET`. ```bash # Generate a key (urlsafe base64 of 32 random bytes, a Fernet key): @@ -841,7 +841,7 @@ export DEER_FLOW_CREDENTIALS_KEY= - **Single instance:** when the variable is unset or blank, the Gateway generates `{DEER_FLOW_HOME}/.credentials_key` (mode `0600`) on first use and reuses it. The file is created exclusively, so uvicorn workers sharing the runtime home converge on one key. It is only created when a feature that stores credentials is enabled. - **Multi-instance:** instances that do not share a runtime home would each generate their own file and could not decrypt what their peers stored. Startup therefore refuses a declared multi-instance deployment (`deployment.multi_instance: true` / `DEER_FLOW_MULTI_INSTANCE=1`) that enables `channel_connections` without the variable. Multiple workers of one process tree (`GATEWAY_WORKERS > 1` without the declaration) share the file and are not refused. Deployments that store no credentials keep booting without a key. - **Malformed keys** (wrong length, standard rather than urlsafe base64, any bad entry in the list) stop startup with an error that never repeats the key material. -- **Backup:** losing the key makes every stored credential unreadable. Unreadable values are treated as missing (logged as a warning), never as a crash — Slack, for example, falls back to the deployment bot token. +- **Backup:** losing the key makes every stored credential unreadable. Unreadable values are treated as missing (logged), never as a crash — Slack, for example, falls back to the deployment bot token, and a bot configured from the web UI reads as not configured until its credentials are saved again. If no key can be loaded at all (an unreadable key file), saving bot credentials from the web UI answers `503` instead of storing them in plaintext. - **Deployment tooling:** the Helm chart generates the key into its app Secret and preserves it across upgrades; `make up` (`scripts/deploy.sh`) honors a shell or `.env` value and otherwise generates and persists `$DEER_FLOW_HOME/.credentials_key` — the same file the Gateway would generate, so whichever side created it first wins. - The persisted `.jwt_secret` (used when `AUTH_JWT_SECRET` is unset) is created the same exclusive way, so replicas cold-starting on a shared volume no longer keep different session-signing secrets. diff --git a/backend/docs/IM_CHANNEL_CONNECTIONS.md b/backend/docs/IM_CHANNEL_CONNECTIONS.md index c3aa0da381..e15ce9b4e5 100644 --- a/backend/docs/IM_CHANNEL_CONNECTIONS.md +++ b/backend/docs/IM_CHANNEL_CONNECTIONS.md @@ -617,25 +617,34 @@ Incoming messages that resolve to a connection carry `connection_id`, `owner_use Runtime provider credentials are deployment-level bot secrets, not user-owned connection credentials. They can come from `channels.*` in `config.yaml` or -from the browser runtime setup flow, which persists them through -`ChannelRuntimeConfigStore` so local/private deployments can configure bots -without editing YAML. The runtime store is a local plaintext JSON fallback with -owner-only file permissions (`0600`); use it only where the DeerFlow data -directory is already trusted as secret storage. Every Gateway worker keeps its own copy -of the file; a save or disconnect rereads it under an advisory sidecar lock -(`.runtime-config.json.lock`) and changes only that provider, so workers sharing -`DEER_FLOW_HOME` do not overwrite each other's bots. Reads still serve the copy -the worker last loaded or wrote. WeChat QR login auth state -follows the same local-runtime model and may persist a QR-derived bot token in -the channel state directory. +from the browser runtime setup flow (`POST` / `DELETE +/api/channels/{provider}/runtime-config`, admin only), so local/private +deployments can configure bots without editing YAML. With a `sqlite` or +`postgres` database the flow stores one row per provider in +`channel_runtime_configs`: the provider's config block encrypted with +`DEER_FLOW_CREDENTIALS_KEY`, a plaintext disconnect flag (a disconnect keeps +suppressing the provider's `config.yaml` block, key or no key), and a +`version` bumped on every save. Every request re-reads the table, so all +Gateway instances serve the same providers. Without a usable key, saving +credentials answers `503` rather than storing plaintext, and rows the key +cannot decrypt read as not configured. The first start after the upgrade +imports an existing `{DEER_FLOW_HOME}/channels/runtime-config.json` (a +provider already in the table keeps its row) and then deletes the plaintext +file, so a downgrade to a build without the table must re-enter UI-configured +bots. With `database.backend: memory` that file (mode `0600`, saves under an +advisory sidecar lock) remains the store; use it only where the DeerFlow data +directory is already trusted as secret storage. WeChat QR login auth state +follows the local-runtime model and may persist a QR-derived bot token in the +channel state directory. With several Gateway instances, `channels.leader_lease` gives each provider's platform connection to one instance: the holder of the provider's row in `channel_leases`. Bindings, connect codes and conversations are shared SQL state, so the connect flow works on any instance; `GET /api/channels/` names -each provider's `leader`. Runtime credentials saved on an instance that does -not hold the provider apply on the holder only when it next starts the -channel. Channel runs are created with `on_disconnect: continue`, so a run +each provider's `leader`. Runtime credentials saved, or a disconnect made, on +any instance reach the holder within one lease renewal interval: it compares +each provider's `version` in `channel_runtime_configs` on every tick and +restarts, starts or stops its transport when the config changed. Channel runs are created with `on_disconnect: continue`, so a run keeps executing when the request that created it dies with its instance (a leader hand-off, a rolling restart, a crash): its thread state is persisted and the answer stays readable in the web UI, while the IM reply itself is @@ -660,9 +669,10 @@ the request was sent, still releases the key for a retry. See credential material cannot be decrypted — a lost or changed key — DeerFlow treats it as unavailable instead of using corrupt secrets. A declared multi-instance deployment with channel connections enabled must set the key. -- The local plaintext runtime credential fallback is documented above; prefer - deployment-managed environment/config secrets for non-local deployments until - a dedicated secret backend is configured. +- Runtime bot credentials entered in the browser are encrypted with the same + key in `channel_runtime_configs`. Only `database.backend: memory` keeps the + plaintext JSON fallback documented above; prefer deployment-managed + environment/config secrets there. - `allowed_users` is **not** a bind-time defense. Because connect codes are processed before the allowlist (see Connect Flow), anyone who possesses a valid code can consume it — not only allowlisted users. Bind security therefore rests entirely on the code's confidentiality: it is 128-bit random, expires after 10 minutes, is single-use, and is shown only in the initiating user's browser (never echoed back to chat). Treat connect codes like one-time passwords and do not forward them. - An external identity — `(provider, external account, workspace/team/guild)` — has at most one active owner. The most recent successful bind wins: connecting an identity that another DeerFlow user already holds transfers ownership and revokes the previous owner's binding (and its stored credentials). This is enforced at the database layer, so two users racing to bind the same identity cannot both end up connected. - Provider bot tokens remain in `channels.*` and are never returned to the browser. diff --git a/backend/packages/harness/deerflow/persistence/channel_runtime_configs/__init__.py b/backend/packages/harness/deerflow/persistence/channel_runtime_configs/__init__.py new file mode 100644 index 0000000000..80cc975962 --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/channel_runtime_configs/__init__.py @@ -0,0 +1,15 @@ +"""UI-entered IM channel runtime configuration shared by every Gateway instance (``channel_runtime_configs``).""" + +from deerflow.persistence.channel_runtime_configs.model import ( + CHANNEL_RUNTIME_CONFIG_PROVIDER_LENGTH, + ChannelRuntimeConfigRow, + StoredChannelRuntimeConfig, +) +from deerflow.persistence.channel_runtime_configs.sql import SqlChannelRuntimeConfigRepository + +__all__ = [ + "CHANNEL_RUNTIME_CONFIG_PROVIDER_LENGTH", + "ChannelRuntimeConfigRow", + "SqlChannelRuntimeConfigRepository", + "StoredChannelRuntimeConfig", +] diff --git a/backend/packages/harness/deerflow/persistence/channel_runtime_configs/model.py b/backend/packages/harness/deerflow/persistence/channel_runtime_configs/model.py new file mode 100644 index 0000000000..801acd5962 --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/channel_runtime_configs/model.py @@ -0,0 +1,52 @@ +"""ORM model for UI-entered IM channel runtime configuration (``channel_runtime_configs``). + +One row per IM provider (``slack``, ``telegram``, ...), shared by every Gateway +instance using the application database. It replaces the per-host +``{base_dir}/channels/runtime-config.json``: + +- ``config_ciphertext`` is the provider's whole runtime config block (bot + tokens, app secrets, ``enabled``, the Telegram deep-link username) as JSON, + encrypted with the deployment credentials key (``DEER_FLOW_CREDENTIALS_KEY``, + ``deerflow.config.credentials_key``). It is NULL for a disconnect. +- ``disconnected`` marks a disconnect from the web UI: a tombstone that keeps + overriding a ``config.yaml`` block for the provider. It carries no secret, so + it stays plaintext and still applies when the key cannot decrypt anything. +- ``version`` grows by one on every save, so an instance that applied version + ``n`` notices a save made on a peer by comparing numbers, without decrypting. + Rows are never deleted, so a provider's version never restarts. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from sqlalchemy import BigInteger, Boolean, Double, PrimaryKeyConstraint, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from deerflow.persistence.base import Base + +#: Longest provider key (registry names are short; this leaves headroom). +CHANNEL_RUNTIME_CONFIG_PROVIDER_LENGTH = 64 + + +class ChannelRuntimeConfigRow(Base): + __tablename__ = "channel_runtime_configs" + + provider: Mapped[str] = mapped_column(String(CHANNEL_RUNTIME_CONFIG_PROVIDER_LENGTH), nullable=False) + config_ciphertext: Mapped[str | None] = mapped_column(Text, nullable=True) + disconnected: Mapped[bool] = mapped_column(Boolean, nullable=False) + version: Mapped[int] = mapped_column(BigInteger, nullable=False) + # Epoch seconds of the last save, for operators; nothing compares it. + updated_at: Mapped[float] = mapped_column(Double, nullable=False) + + __table_args__ = (PrimaryKeyConstraint("provider", name="pk_channel_runtime_configs"),) + + +@dataclass(frozen=True) +class StoredChannelRuntimeConfig: + """One provider's row as stored: the ciphertext is opaque to this layer.""" + + provider: str + config_ciphertext: str | None + disconnected: bool + version: int diff --git a/backend/packages/harness/deerflow/persistence/channel_runtime_configs/sql.py b/backend/packages/harness/deerflow/persistence/channel_runtime_configs/sql.py new file mode 100644 index 0000000000..2221261f34 --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/channel_runtime_configs/sql.py @@ -0,0 +1,111 @@ +"""Synchronous SQL repository for ``channel_runtime_configs`` (SQLite or PostgreSQL). + +The callers of the runtime config store are synchronous and already run off the +event loop (``ChannelService.from_app_config`` and its config reloads run in +worker threads, the Gateway router offloads every store call), so this +repository uses a synchronous session factory over the application database, +the same split as the ``agent_storage.backend: db`` store +(``deerflow.persistence.agents.sql.get_sync_sessionmaker``). + +- ``save`` is one dialect-native upsert that bumps ``version``: ``INSERT ... + ON CONFLICT (provider) DO UPDATE SET ..., version = version + 1``. Two + instances saving the same provider serialize on the row, so each save gets + its own version. The new version is read back inside the same transaction. +- ``insert_missing`` imports rows with ``ON CONFLICT DO NOTHING``: a provider + already in the table is never overwritten, so two instances importing the + same legacy file at once neither duplicate nor clobber a row. + +Ciphertext is opaque here; encryption lives in the application store +(``app.channels.runtime_config_store``). Database errors propagate. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +from sqlalchemy import func, select +from sqlalchemy.dialects.postgresql import insert as pg_insert +from sqlalchemy.dialects.sqlite import insert as sqlite_insert +from sqlalchemy.orm import Session, sessionmaker + +from deerflow.persistence.channel_runtime_configs.model import ChannelRuntimeConfigRow, StoredChannelRuntimeConfig + + +def _insert(session: Session): + name = session.get_bind().dialect.name + if name == "postgresql": + return pg_insert + if name == "sqlite": + return sqlite_insert + raise ValueError(f"Unsupported channel runtime config database dialect: {name}") + + +def _stored(row: ChannelRuntimeConfigRow) -> StoredChannelRuntimeConfig: + return StoredChannelRuntimeConfig(provider=row.provider, config_ciphertext=row.config_ciphertext, disconnected=bool(row.disconnected), version=int(row.version)) + + +class SqlChannelRuntimeConfigRepository: + """Persistence facade for ``channel_runtime_configs``; every call blocks, so run it off the event loop.""" + + def __init__(self, session_factory: sessionmaker[Session]) -> None: + self._sf = session_factory + + def list_all(self) -> list[StoredChannelRuntimeConfig]: + with self._sf() as session: + rows = session.scalars(select(ChannelRuntimeConfigRow).order_by(ChannelRuntimeConfigRow.provider)).all() + return [_stored(row) for row in rows] + + def get(self, provider: str) -> StoredChannelRuntimeConfig | None: + with self._sf() as session: + row = session.get(ChannelRuntimeConfigRow, provider) + return _stored(row) if row is not None else None + + def versions(self) -> dict[str, int]: + """``provider -> version`` for every row, without reading the ciphertext.""" + with self._sf() as session: + rows = session.execute(select(ChannelRuntimeConfigRow.provider, ChannelRuntimeConfigRow.version)).all() + return {row.provider: int(row.version) for row in rows} + + def count(self) -> int: + with self._sf() as session: + return int(session.scalar(select(func.count()).select_from(ChannelRuntimeConfigRow)) or 0) + + def save(self, provider: str, *, config_ciphertext: str | None, disconnected: bool, now: float) -> int: + """Create or replace ``provider``'s row and return its new version (1 for a new row).""" + with self._sf() as session: + insert = _insert(session) + stmt = insert(ChannelRuntimeConfigRow).values(provider=provider, config_ciphertext=config_ciphertext, disconnected=disconnected, version=1, updated_at=now) + stmt = stmt.on_conflict_do_update( + index_elements=[ChannelRuntimeConfigRow.provider], + set_={ + "config_ciphertext": config_ciphertext, + "disconnected": disconnected, + "version": ChannelRuntimeConfigRow.version + 1, + "updated_at": now, + }, + ) + session.execute(stmt) + # Our own write, read inside the transaction that still holds it. + version = session.scalar(select(ChannelRuntimeConfigRow.version).where(ChannelRuntimeConfigRow.provider == provider)) + session.commit() + return int(version) + + def insert_missing(self, rows: Sequence[StoredChannelRuntimeConfig], *, now: float) -> int: + """Insert the rows whose provider has none yet (at version 1); returns how many were inserted.""" + if not rows: + return 0 + inserted = 0 + with self._sf() as session: + insert = _insert(session) + for row in rows: + stmt = ( + insert(ChannelRuntimeConfigRow) + .values(provider=row.provider, config_ciphertext=row.config_ciphertext, disconnected=row.disconnected, version=1, updated_at=now) + .on_conflict_do_nothing(index_elements=[ChannelRuntimeConfigRow.provider]) + .returning(ChannelRuntimeConfigRow.provider) + ) + # Counted from RETURNING (a row only when inserted): psycopg + # reports rowcount -1 for ON CONFLICT DO NOTHING. + inserted += len(session.execute(stmt).all()) + session.commit() + return inserted diff --git a/backend/packages/harness/deerflow/persistence/migrations/AGENTS.md b/backend/packages/harness/deerflow/persistence/migrations/AGENTS.md index c3f0326019..ad447b9212 100644 --- a/backend/packages/harness/deerflow/persistence/migrations/AGENTS.md +++ b/backend/packages/harness/deerflow/persistence/migrations/AGENTS.md @@ -32,7 +32,8 @@ The empty-DB path keeps using `create_all` because `Base.metadata` is the only a `0035_login_throttle` → `0036_run_idempotency_request` → `0037_project_document_summaries` → `0038_channel_thread_bindings` → `0039_user_disabled` → `0040_scheduled_group_notice` → `0041_im_notice_preferences` → -`0042_channel_leases` (current head). The preference +`0042_channel_leases` → `0043_runtime_im_notices` → +`0044_channel_runtime_configs` (current head). The preference revision adds a separate owner/key table with a cascading users foreign key and does not alter users; the project-documents revision adds a new owner-scoped shelf table, and the MCP lease-token revision adds two nullable token columns to @@ -186,6 +187,7 @@ on installs that never enabled it. The convention is: - `migrations/versions/0037_project_document_summaries.py` — adds nullable `project_documents.summary` (best-effort LLM one-line description, off by default; no backfill, so legacy rows stay NULL and the bootstrap forward-compat floor is unchanged); chains after `0036_run_idempotency_request`. Test: `tests/test_migration_0037_project_document_summaries.py` - `migrations/versions/0038_channel_thread_bindings.py` — creates `channel_thread_bindings` (`key` PK = the legacy `channel_name:chat_id[:topic_id]` string, parsed `channel_name`/`chat_id`/nullable `topic_id`, `thread_id`, `user_id` (`""` when unknown, never NULL), epoch `Double` `created_at`/`updated_at` + `ix_channel_thread_bindings_channel_chat`), the shared successor of the per-process `channels/store.json` that `ChannelManager` used for unbound IM conversations (`persistence/channel_thread_bindings/`: `SqlChannelThreadBindingRepository` upserts with a dialect-native `ON CONFLICT (key) DO UPDATE` that keeps `created_at`, deletes a chat's base + topic rows by key prefix with `startswith(autoescape=True)`, and imports with batched `ON CONFLICT DO NOTHING` so two replicas importing the same file concurrently neither duplicate nor clobber a row; `app/channels/store.py::SqlChannelStore.import_legacy_json` runs that once from `ChannelService.start()` and renames the file to `store.json.migrated`). The shape is 1:1 with the JSON entries so the import is lossless; `split_binding_key` parses legacy keys on the first two colons exactly as the old `list_entries()` did (lookups always match the full `key`). Table create/drop and the index are guarded with a fresh inspector in both directions. New table, so the bootstrap forward-compat floor is unchanged; chains after `0037_project_document_summaries`. Test: `tests/test_migration_0038_channel_thread_bindings.py` - `migrations/versions/0042_channel_leases.py` — creates `channel_leases` (`provider` PK, `owner_id`, fencing `epoch` BIGINT, database-clock epoch `Double` `lease_expires_at`/`updated_at`, `transport_running`), the per-provider IM leader lease behind `channels.leader_lease` (`persistence/channel_leases/`: acquire is one dialect-native upsert whose `DO UPDATE ... WHERE lease_expires_at + grace < now OR owner_id = :me` bumps the epoch; renew extends only a live lease at the holder's epoch; release sets the expiry to 0; every `now` is the database clock, never an instance's). Table create/drop is guarded with a fresh inspector in both directions. New table, so the bootstrap forward-compat floor is unchanged; chains after `0041_im_notice_preferences`. Test: `tests/test_migration_0042_channel_leases.py` +- `migrations/versions/0044_channel_runtime_configs.py` — creates `channel_runtime_configs` (`provider` PK, nullable `config_ciphertext`, `disconnected`, `version` BIGINT, `updated_at`), the shared successor of `channels/runtime-config.json`. `persistence/channel_runtime_configs/` is a sync repository on `app_sync_sqlalchemy_url` (callers run in threads): `save` upserts and bumps `version`, `insert_missing` uses `ON CONFLICT DO NOTHING`. `app/channels/runtime_config_store.py` encrypts the JSON block with `DEER_FLOW_CREDENTIALS_KEY`; a disconnect has NULL ciphertext. Rows are never deleted. Table-guarded both ways; no data moved (the Gateway imports the JSON file). Test: `tests/test_migration_0044_channel_runtime_configs.py` - `persistence/bootstrap.py` — `bootstrap_schema(engine, backend=...)`, the three-branch provisioning decision, locked revision validation, and the narrow 0019 forward-compatibility exception - `extensions/loader.py::load_extensions` — registers each spec's `table_prefix` with `register_extension_table_prefix()` - Tests: `tests/test_persistence_bootstrap.py` (branches), `tests/test_persistence_bootstrap_concurrency.py` (concurrency), `tests/test_persistence_bootstrap_regression.py` (issue #3682), `tests/test_persistence_migrations_env.py` (filter, including extension-owned tables), `tests/test_extension_loader.py::TestTablePrefixRegistration` (spec-to-filter wiring), `tests/blocking_io/test_persistence_bootstrap.py` (asyncio.to_thread anchor), `tests/test_migration_0004_run_ownership_dedupe.py` + `tests/test_migration_0007_scheduled_run_active_dedupe.py` (dedupe-before-unique-index pre-steps), `tests/test_migration_0025_repair_run_change_seq.py` (issue #5516 skipped-revision heal) diff --git a/backend/packages/harness/deerflow/persistence/migrations/versions/0044_channel_runtime_configs.py b/backend/packages/harness/deerflow/persistence/migrations/versions/0044_channel_runtime_configs.py new file mode 100644 index 0000000000..261c7af825 --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/migrations/versions/0044_channel_runtime_configs.py @@ -0,0 +1,57 @@ +"""Shared, encrypted IM channel runtime configuration. + +Revision ID: 0044_channel_runtime_configs +Revises: 0043_runtime_im_notices + +Creates ``channel_runtime_configs``: one row per IM provider holding the +credentials an admin entered in the web UI, as ``DEER_FLOW_CREDENTIALS_KEY`` +ciphertext of the provider's JSON config block (NULL for a disconnect), a +plaintext ``disconnected`` tombstone flag, a ``version`` bumped on every save +so peers notice changes, and ``updated_at``. It succeeds the per-host +``{base_dir}/channels/runtime-config.json``, which the Gateway imports once +and deletes (``app.channels.runtime_config_store``); this revision moves no +data, so a database without IM channels gets an empty table. + +``_helpers.py`` only guards columns, so the table is guarded with a fresh +inspector in both directions: an upgrade that finds the table (an interrupted +earlier attempt, or an empty-database bootstrap that already ran +``create_all``) completes, and a downgrade after the table is gone still +moves the version row. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +revision: str = "0044_channel_runtime_configs" +down_revision: str | Sequence[str] | None = "0043_runtime_im_notices" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + +_TABLE = "channel_runtime_configs" + + +def _has_table() -> bool: + return sa.inspect(op.get_bind()).has_table(_TABLE) + + +def upgrade() -> None: + if _has_table(): + return + op.create_table( + _TABLE, + sa.Column("provider", sa.String(length=64), nullable=False), + sa.Column("config_ciphertext", sa.Text(), nullable=True), + sa.Column("disconnected", sa.Boolean(), nullable=False), + sa.Column("version", sa.BigInteger(), nullable=False), + sa.Column("updated_at", sa.Double(), nullable=False), + sa.PrimaryKeyConstraint("provider", name="pk_channel_runtime_configs"), + ) + + +def downgrade() -> None: + if _has_table(): + op.drop_table(_TABLE) diff --git a/backend/packages/harness/deerflow/persistence/models/__init__.py b/backend/packages/harness/deerflow/persistence/models/__init__.py index dae0670d31..3f8fa7ddb6 100644 --- a/backend/packages/harness/deerflow/persistence/models/__init__.py +++ b/backend/packages/harness/deerflow/persistence/models/__init__.py @@ -22,6 +22,7 @@ from deerflow.persistence.channel_connections.model import ( ChannelOAuthStateRow, ) from deerflow.persistence.channel_leases.model import ChannelLeaseRow +from deerflow.persistence.channel_runtime_configs.model import ChannelRuntimeConfigRow from deerflow.persistence.channel_thread_bindings.model import ChannelThreadBindingRow from deerflow.persistence.feedback.model import FeedbackRow from deerflow.persistence.login_throttle.model import LoginThrottleRow @@ -49,6 +50,7 @@ __all__ = [ "ChannelCredentialRow", "ChannelLeaseRow", "ChannelOAuthStateRow", + "ChannelRuntimeConfigRow", "ChannelThreadBindingRow", "FeedbackRow", "LoginThrottleRow", diff --git a/backend/tests/blocking_io/test_channel_leader_lease.py b/backend/tests/blocking_io/test_channel_leader_lease.py index 8a4e170daf..ac5fab5913 100644 --- a/backend/tests/blocking_io/test_channel_leader_lease.py +++ b/backend/tests/blocking_io/test_channel_leader_lease.py @@ -4,9 +4,11 @@ Gateway event loop: at startup, on every supervision tick (every ``lease_seconds // 3`` seconds per provider), from readiness requests and at shutdown. Every statement goes through the async session (aiosqlite / -asyncpg) and every ``wait_for`` bound is a loop timer. If any of it regresses -onto the loop — a synchronous driver call, a blocking clock or lock — the -strict Blockbuster gate raises ``BlockingError`` here. +asyncpg) and every ``wait_for`` bound is a loop timer. The same tick reads the +runtime config versions and re-reads a changed provider's config through the +synchronous runtime config store, both in worker threads. If any of it +regresses onto the loop — a synchronous driver call, a blocking clock or +lock — the strict Blockbuster gate raises ``BlockingError`` here. The engine and schema are built off the loop: that is fixture work, not the production path under test. @@ -21,16 +23,22 @@ from pathlib import Path import pytest import pytest_asyncio import sqlalchemy as sa +from cryptography.fernet import Fernet from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine +from sqlalchemy.orm import sessionmaker # Pre-import so lazy imports inside the service are cached no-ops under the gate. import deerflow.persistence.models # noqa: F401 from app.channels.leadership import ChannelLeadership, RenewOutcome +from app.channels.runtime_config_store import SqlChannelRuntimeConfigStore from app.channels.service import ChannelService from app.channels.store import JsonChannelStore from deerflow import reflection +from deerflow.config.app_config import AppConfig, reset_app_config, set_app_config +from deerflow.config.credentials_key import CredentialsCipher from deerflow.persistence.base import Base from deerflow.persistence.channel_leases import ChannelLeaseRow, SqlChannelLeaseRepository +from deerflow.persistence.channel_runtime_configs import ChannelRuntimeConfigRow, SqlChannelRuntimeConfigRepository pytestmark = pytest.mark.asyncio @@ -55,6 +63,7 @@ async def repo(tmp_path) -> AsyncIterator[SqlChannelLeaseRepository]: class _Transport: def __init__(self, *, bus: object, config: dict) -> None: + self.config = config self.is_running = False async def start(self) -> None: @@ -96,3 +105,41 @@ async def test_service_supervision_and_shutdown_do_not_block_loop(repo, tmp_path assert service.get_status()["channels"]["telegram"]["leader"] == "A" await service.stop() assert (await repo.get("telegram")).live is False + + +def _build_runtime_store(path: Path) -> SqlChannelRuntimeConfigStore: + engine = sa.create_engine(f"sqlite:///{path.as_posix()}") + Base.metadata.create_all(engine, tables=[ChannelRuntimeConfigRow.__table__]) + cipher = CredentialsCipher.from_keys([Fernet.generate_key()]) + store = SqlChannelRuntimeConfigStore(SqlChannelRuntimeConfigRepository(sessionmaker(engine, expire_on_commit=False)), cipher=cipher) + store.set_provider_config("telegram", {"enabled": True, "bot_token": "t-1"}) + return store + + +async def test_supervision_applies_a_peer_runtime_config_save_without_blocking_loop(repo, tmp_path, monkeypatch) -> None: + monkeypatch.setattr(reflection, "resolve_class", lambda *_args, **_kwargs: _Transport) + set_app_config(AppConfig.model_validate({"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"}, "channel_connections": {"enabled": True, "telegram": {"enabled": True}}})) + runtime_store = await asyncio.to_thread(_build_runtime_store, tmp_path / "runtime.db") + store_path = await asyncio.to_thread(lambda: tmp_path / "store.json") + service = ChannelService( + channels_config={"telegram": {"enabled": True, "bot_token": "t-1"}}, + store=JsonChannelStore(store_path), + leadership=ChannelLeadership(repo, owner_id="A", lease_seconds=30, grace_seconds=10), + runtime_config_store=runtime_store, + ) + + async def noop() -> None: + return None + + service.manager.start = noop + service.manager.stop = noop + service._start_supervisor = lambda: None + try: + await service.start() + await asyncio.to_thread(runtime_store.set_provider_config, "telegram", {"enabled": True, "bot_token": "t-2"}) + await service._supervise_once() + await asyncio.gather(*list(service._lease_actions.values())) + assert service.get_channel("telegram").config["bot_token"] == "t-2" + await service.stop() + finally: + reset_app_config() diff --git a/backend/tests/blocking_io/test_channel_runtime_config_store.py b/backend/tests/blocking_io/test_channel_runtime_config_store.py index 8f86e68e09..8608ae6b17 100644 --- a/backend/tests/blocking_io/test_channel_runtime_config_store.py +++ b/backend/tests/blocking_io/test_channel_runtime_config_store.py @@ -1,9 +1,12 @@ """Regression anchors: channel runtime-config handlers must not block the event loop. ``configure_channel_provider_runtime`` and ``disconnect_channel_provider_runtime`` -persist UI-entered channel credentials through ``ChannelRuntimeConfigStore``, -whose construction reads its JSON file and whose setters rewrite it -(``json.dump`` + ``Path.replace`` + ``chmod``). The handlers offload both via +persist UI-entered channel credentials through the runtime config store: the +JSON ``ChannelRuntimeConfigStore`` reads its file on construction and rewrites +it on every save (``json.dump`` + ``Path.replace`` + ``chmod``), and the +database ``SqlChannelRuntimeConfigStore`` runs synchronous SQL (plus Fernet +encryption) on every read and save. The handlers, and the provider listing +that re-reads the store on every request, offload all of it via ``asyncio.to_thread``; if that regresses back onto the event loop, the strict Blockbuster gate raises ``BlockingError`` and these tests fail. @@ -25,16 +28,23 @@ from unittest import mock from uuid import UUID import pytest +import sqlalchemy as sa +from cryptography.fernet import Fernet from fastapi import FastAPI, Request +from sqlalchemy.orm import sessionmaker -from app.channels.runtime_config_store import ChannelRuntimeConfigStore +from app.channels.runtime_config_store import ChannelRuntimeConfigStore, SqlChannelRuntimeConfigStore from app.gateway.routers.channel_connections import ( ChannelRuntimeConfigRequest, configure_channel_provider_runtime, disconnect_channel_provider_runtime, + get_channel_providers, ) from deerflow.config.app_config import AppConfig, reset_app_config, set_app_config from deerflow.config.channel_connections_config import ChannelConnectionsConfig +from deerflow.config.credentials_key import CredentialsCipher +from deerflow.persistence.base import Base +from deerflow.persistence.channel_runtime_configs import ChannelRuntimeConfigRow, SqlChannelRuntimeConfigRepository # Pre-import: the handlers import this module lazily; the import's file IO # must happen at collection time, not on the event loop under the gate. @@ -50,7 +60,7 @@ def _stub_app_config(): reset_app_config() -def _make_request(tmp_path) -> Request: +def _make_request(tmp_path, store=None) -> Request: app = FastAPI() app.state.channel_connections_config = ChannelConnectionsConfig.model_validate( { @@ -58,12 +68,12 @@ def _make_request(tmp_path) -> Request: "slack": {"enabled": True}, } ) - app.state.channels_config = {} # No channel_connection_repo is set: _get_repository's isinstance gate then # falls through to get_session_factory() (None in tests) and the handlers # take the repo-less 503 path. These tests only assert the store's file IO # is offloaded off the event loop, so the DB repo is intentionally absent. - store = ChannelRuntimeConfigStore(tmp_path / "channels" / "runtime-config.json") + if store is None: + store = ChannelRuntimeConfigStore(tmp_path / "channels" / "runtime-config.json") app.state.channel_runtime_config_store = store user = SimpleNamespace(id=UUID("11111111-2222-3333-4444-555555555555"), system_role="admin") return Request({"type": "http", "app": app, "headers": [], "state": {"user": user}}) @@ -95,9 +105,6 @@ async def test_disconnect_runtime_channel_does_not_block_event_loop(tmp_path) -> "slack", {"enabled": True, "bot_token": "xoxb-ui", "app_token": "xapp-ui"}, ) - request.app.state.channels_config = { - "slack": {"enabled": True, "bot_token": "xoxb-ui", "app_token": "xapp-ui"}, - } response = await disconnect_channel_provider_runtime("slack", request) @@ -177,3 +184,28 @@ async def test_runtime_config_store_chmod_failure_is_logged_not_fatal(tmp_path, mode = await asyncio.to_thread(lambda: path.stat().st_mode & 0o777) assert mode == 0o600 assert await asyncio.to_thread(store.get_provider_config, "slack") == {"enabled": True, "bot_token": "xoxb-ui"} + + +def _make_database_store(tmp_path) -> SqlChannelRuntimeConfigStore: + engine = sa.create_engine(f"sqlite:///{(tmp_path / 'runtime.db').as_posix()}") + Base.metadata.create_all(engine, tables=[ChannelRuntimeConfigRow.__table__]) + cipher = CredentialsCipher.from_keys([Fernet.generate_key()]) + return SqlChannelRuntimeConfigStore(SqlChannelRuntimeConfigRepository(sessionmaker(engine, expire_on_commit=False)), cipher=cipher) + + +async def test_database_store_configure_list_and_disconnect_do_not_block_event_loop(tmp_path) -> None: + store = await asyncio.to_thread(_make_database_store, tmp_path) + request = await asyncio.to_thread(_make_request, tmp_path, store) + + configured = await configure_channel_provider_runtime( + "slack", + ChannelRuntimeConfigRequest(values={"bot_token": "xoxb-ui", "app_token": "xapp-ui"}), + request, + ) + listed = await get_channel_providers(request) + disconnected = await disconnect_channel_provider_runtime("slack", request) + + assert configured.configured is True + assert [provider.configured for provider in listed.providers] == [True] + assert disconnected.configured is False + assert await asyncio.to_thread(store.load_all) == {"slack": {"enabled": False, "_runtime_disabled": True}} diff --git a/backend/tests/test_channel_connections_router.py b/backend/tests/test_channel_connections_router.py index 4b66cae761..6e484dc754 100644 --- a/backend/tests/test_channel_connections_router.py +++ b/backend/tests/test_channel_connections_router.py @@ -13,7 +13,7 @@ import pytest from _router_auth_helpers import make_authed_test_app from fastapi.testclient import TestClient -from app.channels.runtime_config_store import ChannelRuntimeConfigStore +from app.channels.runtime_config_store import ChannelRuntimeConfigStore, merge_runtime_channel_configs from app.gateway.auth.models import User from app.gateway.routers import channel_connections from deerflow.config.app_config import AppConfig, reset_app_config, set_app_config @@ -70,7 +70,8 @@ def _make_app( app.state.channel_connections_config = config app.state.channel_connection_repo = repo if set_channels_config_state: - app.state.channels_config = channels_config or {} + # The ``channels`` blocks of config.yaml; the router overlays the runtime store on every request. + set_app_config(AppConfig.model_validate({"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"}, "channels": channels_config or {}})) if runtime_config_store is None: runtime_config_dir = TemporaryDirectory() app.state.channel_runtime_config_tmpdir = runtime_config_dir @@ -80,6 +81,15 @@ def _make_app( return app +def _channels(app) -> dict: + """The channel configs the router serves now: config.yaml ``channels`` with the runtime store overlaid.""" + from deerflow.config.app_config import get_app_config + + result = dict((get_app_config().model_extra or {}).get("channels") or {}) + merge_runtime_channel_configs(result, app.state.channel_connections_config, store=app.state.channel_runtime_config_store) + return result + + def _enabled_connections_config() -> ChannelConnectionsConfig: return ChannelConnectionsConfig.model_validate( { @@ -704,7 +714,7 @@ def test_configure_provider_runtime_credentials_enables_connect_without_file_edi assert configured["configured"] is True assert configured["connectable"] is True assert configured["connection_status"] == "not_connected" - assert app.state.channels_config["slack"] == { + assert _channels(app)["slack"] == { "enabled": True, "bot_token": "xoxb-ui", "app_token": "xapp-ui", @@ -728,7 +738,6 @@ def test_runtime_config_endpoints_require_admin(tmp_path): app = make_authed_test_app(user_factory=_non_admin_user) app.state.channel_connections_config = config app.state.channel_connection_repo = repo - app.state.channels_config = {} runtime_config_dir = TemporaryDirectory() app.state.channel_runtime_config_tmpdir = runtime_config_dir app.state.channel_runtime_config_store = ChannelRuntimeConfigStore(f"{runtime_config_dir.name}/runtime-config.json") @@ -793,7 +802,7 @@ def test_configure_provider_runtime_rolls_back_visible_state_when_start_fails(tm "app_token": "xapp-new", }, ) - assert app.state.channels_config["slack"] == existing_runtime_config + assert _channels(app)["slack"] == existing_runtime_config assert runtime_config_store.get_provider_config("slack") == existing_runtime_config anyio.run(repo.close) @@ -869,7 +878,7 @@ def test_configure_provider_runtime_credentials_survive_local_restart(tmp_path): assert by_provider["slack"]["configured"] is True assert by_provider["slack"]["connectable"] is True assert by_provider["slack"]["connection_status"] == "not_connected" - assert restarted_app.state.channels_config["slack"] == { + assert _channels(restarted_app)["slack"] == { "enabled": True, "bot_token": "xoxb-ui", "app_token": "xapp-ui", @@ -975,7 +984,7 @@ def test_configure_provider_runtime_credentials_preserves_masked_secrets(tmp_pat providers_response = client.get("/api/channels/providers") assert configure_response.status_code == 200 - assert app.state.channels_config["feishu"] == { + assert _channels(app)["feishu"] == { "enabled": True, "app_id": "new-app-id", "app_secret": "old-secret", @@ -1002,7 +1011,7 @@ def test_configure_provider_runtime_credentials_preserves_masked_secrets(tmp_pat (None, {"enabled": False, "_runtime_disabled": True}), ], ) -async def test_runtime_config_commit_drains_persistence_and_cache_across_cancellation( +async def test_runtime_config_commit_drains_persistence_across_cancellation( monkeypatch, runtime_config, expected_persisted, @@ -1038,7 +1047,7 @@ async def test_runtime_config_commit_drains_persistence_and_cache_across_cancell monkeypatch.setattr(channel_connections, "_get_runtime_config_store", get_store) monkeypatch.setattr(channel_connections, "_get_channels_config", get_channels_config) - request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(channels_config=live_channels_config))) + request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace())) task = asyncio.create_task(channel_connections._commit_runtime_channel_config(request, "slack", runtime_config)) try: @@ -1059,14 +1068,6 @@ async def test_runtime_config_commit_drains_persistence_and_cache_across_cancell await asyncio.gather(task, return_exceptions=True) assert persisted["slack"] == expected_persisted - assert request.app.state.channels_config["telegram"] == { - "enabled": True, - "bot_token": "sibling", - } - if runtime_config is None: - assert "slack" not in request.app.state.channels_config - else: - assert request.app.state.channels_config["slack"] == runtime_config def test_disconnect_provider_runtime_config_clears_connected_state(tmp_path): @@ -1170,7 +1171,7 @@ def test_disconnect_provider_runtime_config_suppresses_file_config_and_stops_cha assert disconnected["configured"] is False assert disconnected["connectable"] is False assert disconnected["connection_status"] == "not_connected" - assert "feishu" not in app.state.channels_config + assert "feishu" not in _channels(app) service.remove_channel.assert_awaited_once_with("feishu") service.configure_channel.assert_not_awaited() @@ -1294,11 +1295,8 @@ def test_configure_provider_runtime_does_not_clobber_concurrent_config_update(tm async def configure_channel(provider, runtime_config): # Simulate a concurrent admin request for a *different* provider whose - # write to app.state lands while this request awaits the worker restart. - app.state.channels_config = { - **app.state.channels_config, - "telegram": {"enabled": True, "bot_token": "tg-token"}, - } + # save lands while this request awaits the worker restart. + await asyncio.to_thread(runtime_config_store.set_provider_config, "telegram", {"enabled": True, "bot_token": "tg-token"}) return True service = SimpleNamespace(configure_channel=configure_channel) @@ -1312,8 +1310,8 @@ def test_configure_provider_runtime_does_not_clobber_concurrent_config_update(tm assert response.status_code == 200 # The concurrent telegram write must survive alongside the slack write. - assert app.state.channels_config["slack"]["bot_token"] == "xoxb-ui" - assert app.state.channels_config["telegram"]["bot_token"] == "tg-token" + assert _channels(app)["slack"]["bot_token"] == "xoxb-ui" + assert _channels(app)["telegram"]["bot_token"] == "tg-token" anyio.run(repo.close) @@ -1347,7 +1345,7 @@ def test_disconnect_provider_runtime_keeps_state_consistent_when_revoke_fails(tm # When the DB revoke fails, the store/cache must not be left diverged from # the DB: the provider stays configured so a later re-configure cannot # silently reactivate un-revoked connection rows. - assert app.state.channels_config["slack"]["bot_token"] == "xoxb-ui" + assert _channels(app)["slack"]["bot_token"] == "xoxb-ui" assert runtime_config_store.get_provider_config("slack") == { "enabled": True, "bot_token": "xoxb-ui", @@ -1440,8 +1438,8 @@ def test_wechat_qr_login_saves_credentials_without_exposing_token(monkeypatch, w assert confirmed.json()["status"] == "confirmed" assert confirmed.json()["provider"]["credential_values"]["bot_token"] == "********" assert "new-secret" not in confirmed.text - assert app.state.channels_config["wechat"]["bot_token"] == "new-secret" - assert app.state.channels_config["wechat"]["ilink_bot_id"] == "bot-1" + assert _channels(app)["wechat"]["bot_token"] == "new-secret" + assert _channels(app)["wechat"]["ilink_bot_id"] == "bot-1" saved = ChannelRuntimeConfigStore(app.state.channel_runtime_config_store._path).get_provider_config("wechat") assert saved["bot_token"] == "new-secret" assert saved["ilink_bot_id"] == "bot-1" @@ -1495,7 +1493,7 @@ def test_manual_wechat_setup_invalidates_pending_qr(monkeypatch): session = client.post("/api/channels/wechat/qr-login").json() assert client.post("/api/channels/wechat/runtime-config", json={"values": {"bot_token": "manual-token"}}).status_code == 200 assert client.post(f"/api/channels/wechat/qr-login/{session['id']}/poll").status_code == 404 - assert app.state.channels_config["wechat"]["bot_token"] == "manual-token" + assert _channels(app)["wechat"]["bot_token"] == "manual-token" def test_wechat_pairing_code_is_validated_and_forwarded_without_echo(monkeypatch): @@ -1552,7 +1550,7 @@ def test_wechat_qr_confirmation_preserves_bot_id_unless_replaced(monkeypatch, re expected = {**existing, "bot_token": "new-token", "ilink_bot_id": expected_id} restart.assert_awaited_once_with("wechat", expected) - assert app.state.channels_config["wechat"] == expected + assert _channels(app)["wechat"] == expected saved = ChannelRuntimeConfigStore(app.state.channel_runtime_config_store._path).get_provider_config("wechat") assert saved == expected @@ -1604,7 +1602,7 @@ def test_manual_wechat_setup_remains_available_with_multiple_workers(monkeypatch with TestClient(app) as client: result = client.post("/api/channels/wechat/runtime-config", json={"values": {"bot_token": "manual-token"}}) assert result.status_code == 200 - assert app.state.channels_config["wechat"]["bot_token"] == "manual-token" + assert _channels(app)["wechat"]["bot_token"] == "manual-token" restart.assert_awaited_once() @@ -1678,7 +1676,7 @@ def test_qq_runtime_credentials_can_be_configured_from_browser(tmp_path): assert response.status_code == 200 assert response.json()["configured"] is True assert "fixture-private-secret" not in response.text - assert app.state.channels_config["qq"]["client_secret"] == "fixture-private-secret" + assert _channels(app)["qq"]["client_secret"] == "fixture-private-secret" assert client.post("/api/channels/qq/connect").status_code == 200 finally: anyio.run(repo.close) diff --git a/backend/tests/test_channel_runtime_config_db_store.py b/backend/tests/test_channel_runtime_config_db_store.py new file mode 100644 index 0000000000..074582839d --- /dev/null +++ b/backend/tests/test_channel_runtime_config_db_store.py @@ -0,0 +1,297 @@ +"""Shared, encrypted IM channel runtime configuration (``channel_runtime_configs``). + +``SqlChannelRuntimeConfigStore`` replaces ``{base_dir}/channels/runtime-config.json`` +for a sqlite/postgres database: every Gateway instance reads the same rows, the +UI-entered credentials are stored as ``DEER_FLOW_CREDENTIALS_KEY`` ciphertext, +a disconnect is a plaintext tombstone with no secrets, and every save bumps the +provider's ``version`` so a peer notices it. The old JSON file is imported once +and then deleted, because a plaintext copy left on disk is the leak the table +closes. +""" + +from __future__ import annotations + +import json +import logging +import os +import uuid +from pathlib import Path + +import pytest +import sqlalchemy as sa +from cryptography.fernet import Fernet +from sqlalchemy.engine import make_url +from sqlalchemy.orm import Session, sessionmaker + +from app.channels.runtime_config_store import ( + RUNTIME_CHANNEL_DISABLED_FLAG, + ChannelRuntimeConfigEncryptionUnavailable, + ChannelRuntimeConfigStore, + SqlChannelRuntimeConfigStore, + resolve_runtime_config_store, +) +from deerflow.config.app_config import AppConfig +from deerflow.config.credentials_key import CredentialsCipher +from deerflow.persistence.base import Base +from deerflow.persistence.channel_runtime_configs import ChannelRuntimeConfigRow, SqlChannelRuntimeConfigRepository +from deerflow.persistence.postgres_schema import dsn_with_search_path + +SLACK = {"enabled": True, "bot_token": "xoxb-secret-token", "app_token": "xapp-secret-token"} +TOMBSTONE = {"enabled": False, RUNTIME_CHANNEL_DISABLED_FLAG: True} + + +@pytest.fixture(params=["sqlite", "postgres"]) +def session_factory(request, tmp_path) -> sessionmaker[Session]: + """The synchronous session factory the Gateway builds from ``app_sync_sqlalchemy_url``, on each dialect.""" + schema = None + if request.param == "sqlite": + engine = sa.create_engine(f"sqlite:///{(tmp_path / 'runtime.db').as_posix()}") + else: + uri = os.environ.get("TEST_POSTGRES_URI") + if not uri: + pytest.skip("requires TEST_POSTGRES_URI (real Postgres channel_runtime_configs)") + schema = f"channel_runtime_configs_{uuid.uuid4().hex}" + admin = sa.create_engine(make_url(uri).set(drivername="postgresql+psycopg")) + with admin.begin() as conn: + conn.execute(sa.text(f'CREATE SCHEMA "{schema}"')) + admin.dispose() + engine = sa.create_engine(make_url(dsn_with_search_path(uri, schema)).set(drivername="postgresql+psycopg")) + Base.metadata.create_all(engine, tables=[ChannelRuntimeConfigRow.__table__]) + yield sessionmaker(engine, expire_on_commit=False) + if schema is not None: + with engine.begin() as conn: + conn.execute(sa.text(f'DROP SCHEMA "{schema}" CASCADE')) + engine.dispose() + + +def _cipher(*keys: bytes) -> CredentialsCipher: + return CredentialsCipher.from_keys(list(keys) or [Fernet.generate_key()]) + + +def _store(session_factory, *, cipher: CredentialsCipher | None = None, legacy_path: Path | None = None) -> SqlChannelRuntimeConfigStore: + return SqlChannelRuntimeConfigStore(SqlChannelRuntimeConfigRepository(session_factory), cipher=cipher, legacy_path=legacy_path) + + +def _row(session_factory, provider: str) -> ChannelRuntimeConfigRow | None: + with session_factory() as session: + return session.get(ChannelRuntimeConfigRow, provider) + + +def _write_legacy(path: Path, data: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data), encoding="utf-8") + + +# -- storage --------------------------------------------------------------- + + +def test_saved_config_round_trips_and_is_encrypted_at_rest(session_factory): + store = _store(session_factory, cipher=_cipher()) + + store.set_provider_config("slack", SLACK) + + assert store.get_provider_config("slack") == SLACK + assert store.load_all() == {"slack": SLACK} + row = _row(session_factory, "slack") + assert row.disconnected is False + assert row.config_ciphertext.startswith("fernet:v2:") + assert "xoxb-secret-token" not in row.config_ciphertext + + +def test_every_save_bumps_the_provider_version(session_factory): + store = _store(session_factory, cipher=_cipher()) + assert store.versions() == {} + + store.set_provider_config("slack", SLACK) + store.set_provider_config("telegram", {"enabled": True, "bot_token": "t"}) + store.set_provider_config("slack", {**SLACK, "bot_token": "xoxb-rotated"}) + store.set_provider_disconnected("slack") + + assert store.versions() == {"slack": 3, "telegram": 1} + + +def test_concurrent_saves_from_two_instances_each_get_their_own_version(session_factory): + from concurrent.futures import ThreadPoolExecutor + + repo = SqlChannelRuntimeConfigRepository(session_factory) + + def save_many(instance: str) -> list[int]: + return [repo.save("slack", config_ciphertext=f"{instance}-{n}", disconnected=False, now=float(n)) for n in range(10)] + + with ThreadPoolExecutor(max_workers=2) as pool: + versions = [version for batch in pool.map(save_many, ["a", "b"]) for version in batch] + + # The upsert serializes on the row: no save is lost and no version is handed out twice. + assert sorted(versions) == list(range(1, 21)) + assert repo.versions() == {"slack": 20} + + +def test_disconnect_is_a_plaintext_tombstone_without_secrets(session_factory): + cipher = _cipher() + _store(session_factory, cipher=cipher).set_provider_config("feishu", {"enabled": True, "app_id": "a", "app_secret": "s"}) + + _store(session_factory, cipher=cipher).set_provider_disconnected("feishu") + + row = _row(session_factory, "feishu") + assert (row.disconnected, row.config_ciphertext) == (True, None) + # The tombstone needs no key: it still suppresses a config.yaml block when the key is unavailable. + assert _store(session_factory, cipher=None).load_all() == {"feishu": TOMBSTONE} + + +def test_a_peer_store_reads_a_save_without_restarting(session_factory): + cipher = _cipher() + replica_a, replica_b = _store(session_factory, cipher=cipher), _store(session_factory, cipher=cipher) + assert replica_b.load_all() == {} + + replica_a.set_provider_config("slack", SLACK) + + assert replica_b.get_provider_config("slack") == SLACK + replica_b.set_provider_disconnected("slack") + assert replica_a.load_all() == {"slack": TOMBSTONE} + + +def test_a_row_the_configured_key_cannot_decrypt_reads_as_not_configured(session_factory, caplog): + _store(session_factory, cipher=_cipher()).set_provider_config("slack", SLACK) + _store(session_factory, cipher=_cipher()).set_provider_disconnected("discord") + + with caplog.at_level(logging.ERROR, logger="app.channels.runtime_config_store"): + configs = _store(session_factory, cipher=_cipher()).load_all() + + assert configs == {"discord": TOMBSTONE} + assert "slack" in caplog.text and "DEER_FLOW_CREDENTIALS_KEY" in caplog.text + assert "xoxb" not in caplog.text + + +def test_a_rotated_key_list_still_reads_rows_written_with_the_old_key(session_factory): + old, new = Fernet.generate_key(), Fernet.generate_key() + _store(session_factory, cipher=_cipher(old)).set_provider_config("slack", SLACK) + + assert _store(session_factory, cipher=_cipher(new, old)).load_all() == {"slack": SLACK} + + +def test_without_a_cipher_credentials_are_refused_not_stored_in_plaintext(session_factory): + store = _store(session_factory, cipher=None) + assert store.can_store_credentials is False + + with pytest.raises(ChannelRuntimeConfigEncryptionUnavailable): + store.set_provider_config("slack", SLACK) + + assert _row(session_factory, "slack") is None + assert _store(session_factory, cipher=_cipher()).can_store_credentials is True + + +# -- one-time import of runtime-config.json -------------------------------- + + +def test_import_moves_the_plaintext_file_into_the_table_and_deletes_it(session_factory, tmp_path): + legacy = tmp_path / "channels" / "runtime-config.json" + _write_legacy(legacy, {"slack": SLACK, "feishu": TOMBSTONE}) + store = _store(session_factory, cipher=_cipher(), legacy_path=legacy) + + assert store.import_legacy_json() == 2 + + assert not legacy.exists() + assert store.load_all() == {"slack": SLACK, "feishu": TOMBSTONE} + assert "xoxb-secret-token" not in _row(session_factory, "slack").config_ciphertext + assert _row(session_factory, "feishu").disconnected is True + + +def test_import_keeps_rows_already_in_the_table(session_factory, tmp_path): + cipher = _cipher() + _store(session_factory, cipher=cipher).set_provider_config("slack", SLACK) + legacy = tmp_path / "runtime-config.json" + _write_legacy(legacy, {"slack": {"enabled": True, "bot_token": "stale", "app_token": "stale"}, "telegram": {"enabled": True, "bot_token": "t"}}) + store = _store(session_factory, cipher=cipher, legacy_path=legacy) + + assert store.import_legacy_json() == 1 + + # The table is newer than the file for every provider it already has; the rest is imported. + assert store.load_all() == {"slack": SLACK, "telegram": {"enabled": True, "bot_token": "t"}} + assert store.versions() == {"slack": 1, "telegram": 1} + assert not legacy.exists() + + +def test_replicas_importing_the_same_file_neither_duplicate_nor_fail(session_factory, tmp_path): + cipher = _cipher() + legacy = tmp_path / "runtime-config.json" + _write_legacy(legacy, {"slack": SLACK}) + + assert _store(session_factory, cipher=cipher, legacy_path=legacy).import_legacy_json() == 1 + # The peer finds the file gone (and would find the row present). + assert _store(session_factory, cipher=cipher, legacy_path=legacy).import_legacy_json() == 0 + _write_legacy(legacy, {"slack": SLACK}) + assert _store(session_factory, cipher=cipher, legacy_path=legacy).import_legacy_json() == 0 + + assert _store(session_factory, cipher=cipher).versions() == {"slack": 1} + + +def test_a_corrupt_legacy_file_is_kept(session_factory, tmp_path): + legacy = tmp_path / "runtime-config.json" + legacy.write_text("{not json", encoding="utf-8") + + assert _store(session_factory, cipher=_cipher(), legacy_path=legacy).import_legacy_json() == 0 + + assert legacy.read_text(encoding="utf-8") == "{not json" + + +def test_without_a_cipher_the_import_keeps_the_file(session_factory, tmp_path): + legacy = tmp_path / "runtime-config.json" + _write_legacy(legacy, {"slack": SLACK}) + + assert _store(session_factory, cipher=None, legacy_path=legacy).import_legacy_json() == 0 + + assert legacy.exists() + assert _row(session_factory, "slack") is None + + +def test_import_skips_malformed_entries(session_factory, tmp_path): + legacy = tmp_path / "runtime-config.json" + _write_legacy(legacy, {"slack": SLACK, "discord": "not an object", "x" * 65: {"enabled": True}}) + store = _store(session_factory, cipher=_cipher(), legacy_path=legacy) + + assert store.import_legacy_json() == 1 + + assert store.load_all() == {"slack": SLACK} + + +def test_no_legacy_file_is_a_no_op(session_factory, tmp_path): + assert _store(session_factory, cipher=_cipher(), legacy_path=tmp_path / "missing.json").import_legacy_json() == 0 + assert _store(session_factory, cipher=_cipher()).import_legacy_json() == 0 + + +# -- selection ------------------------------------------------------------- + + +def _app_config(tmp_path, backend: str) -> AppConfig: + database = {"backend": backend, "sqlite_dir": str(tmp_path)} if backend != "memory" else {"backend": "memory"} + return AppConfig.model_validate({"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"}, "database": database}) + + +def test_a_memory_database_keeps_the_json_file(tmp_path): + store = resolve_runtime_config_store(_app_config(tmp_path, "memory"), cipher=_cipher(), path=tmp_path / "runtime-config.json") + + assert isinstance(store, ChannelRuntimeConfigStore) + + +def test_a_sql_database_uses_the_shared_table(tmp_path, monkeypatch): + import deerflow.persistence.engine as engine_module + + monkeypatch.setattr(engine_module, "get_session_factory", lambda: object()) + legacy = tmp_path / "runtime-config.json" + + store = resolve_runtime_config_store(_app_config(tmp_path, "sqlite"), cipher=_cipher(), path=legacy) + + assert isinstance(store, SqlChannelRuntimeConfigStore) + assert store.legacy_path == legacy + + +def test_a_sql_database_without_an_initialised_engine_falls_back_to_the_file(tmp_path, monkeypatch, caplog): + import deerflow.persistence.engine as engine_module + + monkeypatch.setattr(engine_module, "get_session_factory", lambda: None) + + with caplog.at_level(logging.WARNING, logger="app.channels.runtime_config_store"): + store = resolve_runtime_config_store(_app_config(tmp_path, "sqlite"), cipher=_cipher(), path=tmp_path / "runtime-config.json") + + assert isinstance(store, ChannelRuntimeConfigStore) + assert "runtime-config.json" in caplog.text diff --git a/backend/tests/test_channel_runtime_config_replicas.py b/backend/tests/test_channel_runtime_config_replicas.py new file mode 100644 index 0000000000..2357923c25 --- /dev/null +++ b/backend/tests/test_channel_runtime_config_replicas.py @@ -0,0 +1,395 @@ +"""Runtime IM channel configuration across Gateway instances (``channel_runtime_configs``). + +Two routers, or two ``ChannelService`` instances under ``channels.leader_lease``, +share one runtime config table, as two Gateway replicas share the application +database. Before the table each replica read its own ``runtime-config.json`` +once and cached the merged config in ``app.state``: credentials saved on one +replica never reached the other, and a disconnect on a replica that did not +hold the provider's lease left the holder connected with the old credentials. +""" + +from __future__ import annotations + +import asyncio +import time +from collections.abc import AsyncIterator +from pathlib import Path +from uuid import UUID + +import anyio +import pytest +import pytest_asyncio +import sqlalchemy as sa +from _router_auth_helpers import make_authed_test_app +from cryptography.fernet import Fernet +from fastapi.testclient import TestClient +from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine +from sqlalchemy.orm import Session, sessionmaker + +from app.channels.leadership import ChannelLeadership +from app.channels.runtime_config_store import SqlChannelRuntimeConfigStore +from app.channels.service import ChannelService +from app.channels.store import JsonChannelStore +from app.gateway.auth.models import User +from app.gateway.routers import channel_connections +from deerflow import reflection +from deerflow.config.app_config import AppConfig, reset_app_config, set_app_config +from deerflow.config.credentials_key import CredentialsCipher +from deerflow.persistence.base import Base +from deerflow.persistence.channel_leases import ChannelLeaseRow, SqlChannelLeaseRepository +from deerflow.persistence.channel_runtime_configs import ChannelRuntimeConfigRow, SqlChannelRuntimeConfigRepository + +CIPHER = CredentialsCipher.from_keys([Fernet.generate_key()]) + + +@pytest.fixture(autouse=True) +def _app_config(monkeypatch): + monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "0") + monkeypatch.delenv("DEER_FLOW_MULTI_INSTANCE", raising=False) + set_app_config( + AppConfig.model_validate( + { + "sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"}, + "channel_connections": {"enabled": True, "slack": {"enabled": True}, "telegram": {"enabled": True, "bot_username": "deerflow_bot"}, "discord": {"enabled": True}}, + } + ) + ) + yield + reset_app_config() + + +@pytest.fixture +def runtime_sessions(tmp_path) -> sessionmaker[Session]: + engine = sa.create_engine(f"sqlite:///{(tmp_path / 'runtime.db').as_posix()}") + Base.metadata.create_all(engine, tables=[ChannelRuntimeConfigRow.__table__]) + yield sessionmaker(engine, expire_on_commit=False) + engine.dispose() + + +def _runtime_store(runtime_sessions, *, cipher: CredentialsCipher | None = CIPHER) -> SqlChannelRuntimeConfigStore: + return SqlChannelRuntimeConfigStore(SqlChannelRuntimeConfigRepository(runtime_sessions), cipher=cipher) + + +# -- router ---------------------------------------------------------------- + + +def _admin() -> User: + return User(id=UUID("11111111-2222-3333-4444-555555555555"), email="admin@example.com", password_hash="x", system_role="admin") + + +async def _connection_repo(tmp_path): + from deerflow.persistence.channel_connections import ChannelConnectionRepository + from deerflow.persistence.engine import get_session_factory, init_engine + + await init_engine("sqlite", url=f"sqlite+aiosqlite:///{tmp_path / 'router.db'}", sqlite_dir=str(tmp_path)) + return ChannelConnectionRepository(get_session_factory()) + + +def _replica(connection_repo, runtime_store): + app = make_authed_test_app(user_factory=_admin) + app.state.channel_connection_repo = connection_repo + app.state.channel_runtime_config_store = runtime_store + app.include_router(channel_connections.router) + return app + + +def _provider(client: TestClient, name: str) -> dict: + response = client.get("/api/channels/providers") + assert response.status_code == 200 + return next(provider for provider in response.json()["providers"] if provider["provider"] == name) + + +def test_credentials_saved_on_one_replica_are_served_by_the_other(tmp_path, runtime_sessions): + connection_repo = anyio.run(_connection_repo, tmp_path) + replica_a = _replica(connection_repo, _runtime_store(runtime_sessions)) + replica_b = _replica(connection_repo, _runtime_store(runtime_sessions)) + + with TestClient(replica_a) as client_a, TestClient(replica_b) as client_b: + # B has served the provider list before A saves anything. + assert _provider(client_b, "slack")["configured"] is False + + saved = client_a.post("/api/channels/slack/runtime-config", json={"values": {"bot_token": "xoxb-ui", "app_token": "xapp-ui"}}) + assert saved.status_code == 200 + + slack_on_b = _provider(client_b, "slack") + assert slack_on_b["configured"] is True + assert slack_on_b["credential_values"] == {"bot_token": "********", "app_token": "********"} + + # The telegram deep-link username follows the same path. + assert client_b.post("/api/channels/telegram/runtime-config", json={"values": {"bot_token": "123:abc", "bot_username": "ui_bot"}}).status_code == 200 + assert _provider(client_a, "telegram")["credential_values"]["bot_username"] == "ui_bot" + + disconnected = client_b.delete("/api/channels/slack/runtime-config") + assert disconnected.status_code == 200 + assert _provider(client_a, "slack")["configured"] is False + + anyio.run(connection_repo.close) + + +def test_saving_credentials_without_an_encryption_key_is_refused(tmp_path, runtime_sessions): + connection_repo = anyio.run(_connection_repo, tmp_path) + app = _replica(connection_repo, _runtime_store(runtime_sessions, cipher=None)) + + with TestClient(app) as client: + response = client.post("/api/channels/slack/runtime-config", json={"values": {"bot_token": "xoxb-ui", "app_token": "xapp-ui"}}) + + assert response.status_code == 503 + assert "DEER_FLOW_CREDENTIALS_KEY" in response.json()["detail"] + assert _runtime_store(runtime_sessions).load_all() == {} + anyio.run(connection_repo.close) + + +# -- ChannelService under the leader lease -------------------------------- + + +class FakeTransport: + started: list[FakeTransport] = [] + #: Credentials the platform rejects: a transport started on one of them never comes up. + rejected_tokens: set[str] = set() + + def __init__(self, *, bus: object, config: dict) -> None: + self.config = config + self.is_running = False + + async def start(self) -> None: + if self.config.get("bot_token") in FakeTransport.rejected_tokens: + return + self.is_running = True + FakeTransport.started.append(self) + + async def stop(self) -> None: + self.is_running = False + + +@pytest.fixture +def fake_transports(monkeypatch): + FakeTransport.started = [] + FakeTransport.rejected_tokens = set() + monkeypatch.setattr(reflection, "resolve_class", lambda *_args, **_kwargs: FakeTransport) + yield + + +@pytest_asyncio.fixture +async def lease_engine(tmp_path) -> AsyncIterator[AsyncEngine]: + engine = create_async_engine(f"sqlite+aiosqlite:///{(tmp_path / 'leases.db').as_posix()}") + async with engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all, tables=[ChannelLeaseRow.__table__]) + try: + yield engine + finally: + await engine.dispose() + + +def _service(lease_engine, owner: str, tmp_path: Path, runtime_store: SqlChannelRuntimeConfigStore) -> ChannelService: + leadership = ChannelLeadership(SqlChannelLeaseRepository(async_sessionmaker(lease_engine, expire_on_commit=False)), owner_id=owner, lease_seconds=30, grace_seconds=10, clock=time.monotonic) + # What from_app_config hands over: config.yaml has no channels, the runtime table has the rest. + channels = {name: dict(config) for name, config in runtime_store.load_all().items() if config.get("enabled")} + service = ChannelService(channels_config=channels, store=JsonChannelStore(tmp_path / owner / "store.json"), leadership=leadership, runtime_config_store=runtime_store) + + async def noop() -> None: + return None + + service.manager.start = noop + service.manager.stop = noop + service._start_supervisor = lambda: None + return service + + +async def _round(service: ChannelService) -> None: + """One supervision round, then wait for the transport actions it scheduled.""" + await service._supervise_once() + while service._lease_actions: + await asyncio.gather(*list(service._lease_actions.values())) + + +async def _lease(lease_engine, provider: str) -> ChannelLeaseRow | None: + async with async_sessionmaker(lease_engine)() as session: + return await session.get(ChannelLeaseRow, provider) + + +pytest_lease = pytest.mark.usefixtures("fake_transports") + + +@pytest_lease +@pytest.mark.asyncio +async def test_the_holder_reconnects_with_credentials_saved_on_a_peer(lease_engine, runtime_sessions, tmp_path): + shared = _runtime_store(runtime_sessions) + shared.set_provider_config("telegram", {"enabled": True, "bot_token": "t-1"}) + holder, peer = _service(lease_engine, "A", tmp_path, shared), _service(lease_engine, "B", tmp_path, shared) + await holder.start() + await peer.start() + try: + assert holder._channels["telegram"].config["bot_token"] == "t-1" + assert "telegram" not in peer._channels + for service in (holder, peer): + await _round(service) # first rounds only record the versions they started from + starts = len(FakeTransport.started) + + # The peer's router saved new credentials (it cannot restart the holder's transport itself). + assert await peer.configure_channel("telegram", {"enabled": True, "bot_token": "t-2"}) is True + shared.set_provider_config("telegram", {"enabled": True, "bot_token": "t-2"}) + await _round(holder) + + assert holder._channels["telegram"].config["bot_token"] == "t-2" + assert holder._channels["telegram"].is_running + assert len(FakeTransport.started) == starts + 1 + await _round(holder) + await _round(peer) + assert len(FakeTransport.started) == starts + 1 # applied once, on the holder only + assert "telegram" not in peer._channels + finally: + await holder.stop() + await peer.stop() + + +@pytest_lease +@pytest.mark.asyncio +async def test_a_holder_whose_transport_is_down_connects_on_new_credentials_in_the_same_round(lease_engine, runtime_sessions, tmp_path): + shared = _runtime_store(runtime_sessions) + shared.set_provider_config("telegram", {"enabled": True, "bot_token": "revoked"}) + FakeTransport.rejected_tokens = {"revoked"} + holder, peer = _service(lease_engine, "A", tmp_path, shared), _service(lease_engine, "B", tmp_path, shared) + await holder.start() + await peer.start() + try: + # The holder took the lease but its transport cannot start on the old credentials. + await _round(holder) + assert holder.get_status()["channels"]["telegram"]["leader_here"] is True + assert not holder._transport_running("telegram") + + shared.set_provider_config("telegram", {"enabled": True, "bot_token": "t-2"}) + await _round(holder) # one renewal interval, not one to apply the config and another to start + + assert holder._channels["telegram"].is_running + assert holder._channels["telegram"].config["bot_token"] == "t-2" + assert "telegram" not in holder._lease_start_backoff + assert "telegram" not in peer._channels + finally: + await holder.stop() + await peer.stop() + + +@pytest_lease +@pytest.mark.asyncio +async def test_a_disconnect_saved_on_a_peer_stops_the_holder_and_nobody_takes_over(lease_engine, runtime_sessions, tmp_path): + shared = _runtime_store(runtime_sessions) + shared.set_provider_config("telegram", {"enabled": True, "bot_token": "t-1"}) + holder, peer = _service(lease_engine, "A", tmp_path, shared), _service(lease_engine, "B", tmp_path, shared) + await holder.start() + await peer.start() + try: + # The peer's router: stop locally (nothing runs here), then persist the tombstone. + assert await peer.remove_channel("telegram") is True + shared.set_provider_disconnected("telegram") + await _round(holder) + + assert "telegram" not in holder._channels + assert (await _lease(lease_engine, "telegram")).lease_expires_at == 0.0 # handed back + for _ in range(2): + await _round(peer) + await _round(holder) + assert "telegram" not in peer._channels and "telegram" not in holder._channels + assert all(not service.get_status()["channels"]["telegram"]["enabled"] for service in (holder, peer)) + finally: + await holder.stop() + await peer.stop() + + +@pytest_lease +@pytest.mark.asyncio +async def test_the_instance_that_saved_the_config_does_not_restart_twice(lease_engine, runtime_sessions, tmp_path): + shared = _runtime_store(runtime_sessions) + shared.set_provider_config("telegram", {"enabled": True, "bot_token": "t-1"}) + holder = _service(lease_engine, "A", tmp_path, shared) + await holder.start() + try: + await _round(holder) + # The holder's own router: restart with the new config first, then persist it. + assert await holder.configure_channel("telegram", {"enabled": True, "bot_token": "t-2"}) is True + shared.set_provider_config("telegram", {"enabled": True, "bot_token": "t-2"}) + starts = len(FakeTransport.started) + + await _round(holder) + + assert len(FakeTransport.started) == starts + assert holder._channels["telegram"].config["bot_token"] == "t-2" + finally: + await holder.stop() + + +@pytest_lease +@pytest.mark.asyncio +async def test_a_peer_learns_a_provider_connected_elsewhere_and_takes_it_over(lease_engine, runtime_sessions, tmp_path): + shared = _runtime_store(runtime_sessions) + holder, peer = _service(lease_engine, "A", tmp_path, shared), _service(lease_engine, "B", tmp_path, shared) + await holder.start() + await peer.start() + try: + discord = {"enabled": True, "bot_token": "d-1"} + assert await holder.configure_channel("discord", discord) is True + shared.set_provider_config("discord", discord) + await _round(peer) + assert peer.get_channel_config("discord") == discord + assert "discord" not in peer._channels + + await holder.stop() # releases the lease + await _round(peer) + + assert peer._channels["discord"].is_running + assert peer._channels["discord"].config["bot_token"] == "d-1" + finally: + await holder.stop() + await peer.stop() + + +@pytest_lease +@pytest.mark.asyncio +async def test_a_takeover_reads_a_disconnect_instead_of_reviving_cached_credentials(lease_engine, runtime_sessions, tmp_path): + shared = _runtime_store(runtime_sessions) + shared.set_provider_config("telegram", {"enabled": True, "bot_token": "t-1"}) + holder, peer = _service(lease_engine, "A", tmp_path, shared), _service(lease_engine, "B", tmp_path, shared) + await holder.start() + await peer.start() + try: + await holder.stop() # releases the lease + shared.set_provider_disconnected("telegram") + + # The peer has not reconciled yet: its cached config still says enabled. + # A takeover (what its next lease round would run) must read the + # disconnect, not fall back to the cached credentials. + await peer._take_over_channel("telegram") + + assert "telegram" not in peer._channels + assert peer.get_status()["channels"]["telegram"]["enabled"] is False + finally: + await holder.stop() + await peer.stop() + + +def test_startup_imports_the_legacy_file_before_overlaying_runtime_config(runtime_sessions, tmp_path, monkeypatch): + import json + from types import SimpleNamespace + + from app.channels import service as service_module + from deerflow.config import paths as paths_module + from deerflow.config.channel_connections_config import ChannelConnectionsConfig + + monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path)) + monkeypatch.setattr(paths_module, "_paths", None) + legacy = tmp_path / "channels" / "runtime-config.json" + legacy.parent.mkdir(parents=True, exist_ok=True) + legacy.write_text(json.dumps({"slack": {"enabled": True, "bot_token": "xoxb-ui", "app_token": "xapp-ui"}, "feishu": {"enabled": False, "_runtime_disabled": True}}), encoding="utf-8") + store = SqlChannelRuntimeConfigStore(SqlChannelRuntimeConfigRepository(runtime_sessions), cipher=CIPHER, legacy_path=legacy) + monkeypatch.setattr(service_module, "resolve_runtime_config_store", lambda app_config, *, cipher: store) + app_config = SimpleNamespace( + model_extra={"channels": {"feishu": {"enabled": True, "app_id": "file-app", "app_secret": "file-secret"}}}, + channel_connections=ChannelConnectionsConfig.model_validate({"enabled": True, "slack": {"enabled": True}, "feishu": {"enabled": True}}), + ) + + service = ChannelService.from_app_config(app_config, credentials_cipher=CIPHER) + + # The very first start after the upgrade already runs on the imported config. + assert service._config["slack"] == {"enabled": True, "bot_token": "xoxb-ui", "app_token": "xapp-ui"} + assert "feishu" not in service._config # the imported disconnect still suppresses config.yaml + assert not legacy.exists() + assert service._runtime_config_store is store diff --git a/backend/tests/test_migration_0027_0028_notification_outbox.py b/backend/tests/test_migration_0027_0028_notification_outbox.py index cf828618a3..ac434b2e5f 100644 --- a/backend/tests/test_migration_0027_0028_notification_outbox.py +++ b/backend/tests/test_migration_0027_0028_notification_outbox.py @@ -23,7 +23,7 @@ OUTBOX = "0027_notification_deliveries" PARKED = "0028_parked_attempts" SCHEDULER = "0029_scheduler_agent_tasks" CLAIM_TOKENS = "0030_notification_claim_tokens" -HEAD = "0043_runtime_im_notices" +HEAD = "0044_channel_runtime_configs" PREVIOUS = "0026_mcp_task_lease_tokens" TABLE = "notification_deliveries" diff --git a/backend/tests/test_migration_0029_scheduler_agent_tasks.py b/backend/tests/test_migration_0029_scheduler_agent_tasks.py index 37a46739a2..4edafee0b7 100644 --- a/backend/tests/test_migration_0029_scheduler_agent_tasks.py +++ b/backend/tests/test_migration_0029_scheduler_agent_tasks.py @@ -23,7 +23,7 @@ from deerflow.persistence.postgres_schema import build_asyncpg_connect_args from deerflow.persistence.scheduled_tasks import ScheduledTaskRepository REVISION = "0029_scheduler_agent_tasks" -CURRENT_HEAD = "0043_runtime_im_notices" +CURRENT_HEAD = "0044_channel_runtime_configs" NEXT = "0030_notification_claim_tokens" PREVIOUS = "0028_parked_attempts" TASK_FIELDS = {"origin_thread_id", "goal_objective", "max_runs", "end_at", "standing_notes"} diff --git a/backend/tests/test_migration_0032_activity_and_task_events.py b/backend/tests/test_migration_0032_activity_and_task_events.py index ad9a8cca43..e519ead02f 100644 --- a/backend/tests/test_migration_0032_activity_and_task_events.py +++ b/backend/tests/test_migration_0032_activity_and_task_events.py @@ -24,7 +24,7 @@ IDEMPOTENCY = "0036_run_idempotency_request" DOCUMENT_SUMMARIES = "0037_project_document_summaries" CHANNEL_BINDINGS = "0038_channel_thread_bindings" USER_DISABLED = "0039_user_disabled" -CURRENT_HEAD = "0043_runtime_im_notices" +CURRENT_HEAD = "0044_channel_runtime_configs" PREVIOUS = "0031_scheduled_streak_boundary" TABLES = {"thread_read_markers", "thread_read_versions", "scheduled_task_events"} INDEXES = { diff --git a/backend/tests/test_migration_0034_run_event_seq_watermark.py b/backend/tests/test_migration_0034_run_event_seq_watermark.py index 70f23e9b1a..2276ba81f9 100644 --- a/backend/tests/test_migration_0034_run_event_seq_watermark.py +++ b/backend/tests/test_migration_0034_run_event_seq_watermark.py @@ -24,7 +24,7 @@ IDEMPOTENCY = "0036_run_idempotency_request" DOCUMENT_SUMMARIES = "0037_project_document_summaries" CHANNEL_BINDINGS = "0038_channel_thread_bindings" USER_DISABLED = "0039_user_disabled" -CURRENT_HEAD = "0043_runtime_im_notices" +CURRENT_HEAD = "0044_channel_runtime_configs" TABLE = "run_event_thread_seq" pytestmark = pytest.mark.asyncio diff --git a/backend/tests/test_migration_0035_login_throttle.py b/backend/tests/test_migration_0035_login_throttle.py index a01a31b17a..959a203305 100644 --- a/backend/tests/test_migration_0035_login_throttle.py +++ b/backend/tests/test_migration_0035_login_throttle.py @@ -25,7 +25,7 @@ IDEMPOTENCY = "0036_run_idempotency_request" DOCUMENT_SUMMARIES = "0037_project_document_summaries" CHANNEL_BINDINGS = "0038_channel_thread_bindings" USER_DISABLED = "0039_user_disabled" -CURRENT_HEAD = "0043_runtime_im_notices" +CURRENT_HEAD = "0044_channel_runtime_configs" PREVIOUS = "0034_run_event_seq_watermark" TABLE = "login_throttle" COLUMNS = {"ip", "fail_count", "locked_at", "lock_duration_seconds", "updated_at"} diff --git a/backend/tests/test_migration_0037_project_document_summaries.py b/backend/tests/test_migration_0037_project_document_summaries.py index ebfbac75ac..0eb68fb1b8 100644 --- a/backend/tests/test_migration_0037_project_document_summaries.py +++ b/backend/tests/test_migration_0037_project_document_summaries.py @@ -23,7 +23,8 @@ USER_DISABLED = "0039_user_disabled" GROUP_NOTICE = "0040_scheduled_group_notice" IM_NOTICE_PREFERENCES = "0041_im_notice_preferences" CHANNEL_LEASES = "0042_channel_leases" -CURRENT_HEAD = "0043_runtime_im_notices" +RUNTIME_IM_NOTICES = "0043_runtime_im_notices" +CURRENT_HEAD = "0044_channel_runtime_configs" pytestmark = pytest.mark.asyncio @@ -35,7 +36,8 @@ async def test_0037_chains_after_0036_and_is_single_head(): assert script.get_revision(GROUP_NOTICE).down_revision == USER_DISABLED assert script.get_revision(IM_NOTICE_PREFERENCES).down_revision == GROUP_NOTICE assert script.get_revision(CHANNEL_LEASES).down_revision == IM_NOTICE_PREFERENCES - assert script.get_revision(CURRENT_HEAD).down_revision == CHANNEL_LEASES + assert script.get_revision(RUNTIME_IM_NOTICES).down_revision == CHANNEL_LEASES + assert script.get_revision(CURRENT_HEAD).down_revision == RUNTIME_IM_NOTICES assert script.get_revision(REVISION).down_revision == PREVIOUS # alembic_version.version_num is VARCHAR(32). assert len(REVISION) <= 32 diff --git a/backend/tests/test_migration_0038_channel_thread_bindings.py b/backend/tests/test_migration_0038_channel_thread_bindings.py index 5c4ed15ea0..d137cc0895 100644 --- a/backend/tests/test_migration_0038_channel_thread_bindings.py +++ b/backend/tests/test_migration_0038_channel_thread_bindings.py @@ -22,7 +22,7 @@ from deerflow.persistence.postgres_schema import build_asyncpg_connect_args REVISION = "0038_channel_thread_bindings" PREVIOUS = "0037_project_document_summaries" -CURRENT_HEAD = "0043_runtime_im_notices" +CURRENT_HEAD = "0044_channel_runtime_configs" TABLE = "channel_thread_bindings" COLUMNS = {"key", "channel_name", "chat_id", "topic_id", "thread_id", "user_id", "created_at", "updated_at"} INDEX = "ix_channel_thread_bindings_channel_chat" diff --git a/backend/tests/test_migration_0040_scheduled_group_notice.py b/backend/tests/test_migration_0040_scheduled_group_notice.py index a68f6cf3a5..4e595dbb1d 100644 --- a/backend/tests/test_migration_0040_scheduled_group_notice.py +++ b/backend/tests/test_migration_0040_scheduled_group_notice.py @@ -16,7 +16,7 @@ from deerflow.persistence.postgres_schema import build_asyncpg_connect_args REVISION = "0040_scheduled_group_notice" PREVIOUS = "0039_user_disabled" -CURRENT_HEAD = "0043_runtime_im_notices" +CURRENT_HEAD = "0044_channel_runtime_configs" COLUMN = "notification_group_connection_id" diff --git a/backend/tests/test_migration_0042_channel_leases.py b/backend/tests/test_migration_0042_channel_leases.py index 3e80c4e47c..1d6b518671 100644 --- a/backend/tests/test_migration_0042_channel_leases.py +++ b/backend/tests/test_migration_0042_channel_leases.py @@ -22,7 +22,8 @@ from deerflow.persistence.postgres_schema import build_asyncpg_connect_args REVISION = "0042_channel_leases" PREVIOUS = "0041_im_notice_preferences" -CURRENT_HEAD = "0043_runtime_im_notices" +NEXT = "0043_runtime_im_notices" +CURRENT_HEAD = "0044_channel_runtime_configs" TABLE = "channel_leases" COLUMNS = {"provider", "owner_id", "epoch", "lease_expires_at", "transport_running", "updated_at"} pytestmark = pytest.mark.asyncio @@ -31,7 +32,8 @@ pytestmark = pytest.mark.asyncio async def test_0042_remains_in_the_single_migration_chain(): script = ScriptDirectory(str(bootstrap._MIGRATIONS_DIR)) assert script.get_heads() == [CURRENT_HEAD] - assert script.get_revision(CURRENT_HEAD).down_revision == REVISION + assert script.get_revision(CURRENT_HEAD).down_revision == NEXT + assert script.get_revision(NEXT).down_revision == REVISION assert script.get_revision(REVISION).down_revision == PREVIOUS # alembic_version.version_num is VARCHAR(32). assert len(REVISION) <= 32 diff --git a/backend/tests/test_migration_0044_channel_runtime_configs.py b/backend/tests/test_migration_0044_channel_runtime_configs.py new file mode 100644 index 0000000000..68228d311b --- /dev/null +++ b/backend/tests/test_migration_0044_channel_runtime_configs.py @@ -0,0 +1,162 @@ +"""Migration 0044: the shared, encrypted ``channel_runtime_configs`` table (UI-entered IM channel credentials).""" + +from __future__ import annotations + +import asyncio +import os +import uuid + +import pytest +import sqlalchemy as sa +from alembic import command +from alembic.autogenerate import compare_metadata +from alembic.migration import MigrationContext +from alembic.script import ScriptDirectory +from sqlalchemy.ext.asyncio import create_async_engine +from support.postgres import asyncpg_test_url + +from deerflow.persistence import bootstrap +from deerflow.persistence.base import Base +from deerflow.persistence.channel_runtime_configs import ChannelRuntimeConfigRow +from deerflow.persistence.postgres_schema import build_asyncpg_connect_args + +REVISION = "0044_channel_runtime_configs" +PREVIOUS = "0043_runtime_im_notices" +CURRENT_HEAD = REVISION +TABLE = "channel_runtime_configs" +COLUMNS = {"provider", "config_ciphertext", "disconnected", "version", "updated_at"} +pytestmark = pytest.mark.asyncio + + +async def test_0044_remains_in_the_single_migration_chain(): + script = ScriptDirectory(str(bootstrap._MIGRATIONS_DIR)) + assert script.get_heads() == [CURRENT_HEAD] + assert script.get_revision(REVISION).down_revision == PREVIOUS + # alembic_version.version_num is VARCHAR(32). + assert len(REVISION) <= 32 + + +def _engine(tmp_path, backend): + if backend == "sqlite": + return create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'migration.db'}"), None + uri = os.environ.get("TEST_POSTGRES_URI") + if not uri: + pytest.skip("requires TEST_POSTGRES_URI (real Postgres migration 0044)") + schema = f"channel_runtime_configs_{uuid.uuid4().hex}" + return create_async_engine(asyncpg_test_url(uri), connect_args=build_asyncpg_connect_args(schema)), schema + + +async def _shape(engine) -> dict: + async with engine.connect() as conn: + + def read(sync): + inspector = sa.inspect(sync) + tables = set(inspector.get_table_names()) + if TABLE not in tables: + return {"tables": tables} + return { + "tables": tables, + "columns": {col["name"]: col for col in inspector.get_columns(TABLE)}, + "pk": inspector.get_pk_constraint(TABLE), + } + + return await conn.run_sync(read) + + +async def _orm_diff(engine) -> list: + """Alembic's own drift check, restricted to the table this revision owns.""" + + def only_runtime_configs(obj, name, type_, reflected, compare_to): + if type_ == "table": + return name == TABLE + return getattr(getattr(obj, "table", None), "name", TABLE) == TABLE + + async with engine.connect() as conn: + + def diff(sync): + context = MigrationContext.configure(sync, opts={"include_object": only_runtime_configs, "compare_type": True, "compare_server_default": True}) + return compare_metadata(context, Base.metadata) + + return await conn.run_sync(diff) + + +async def _drop_schema(engine, schema): + if schema: + async with engine.begin() as conn: + await conn.execute(sa.text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE')) + + +@pytest.mark.parametrize("backend", ["sqlite", "postgres"]) +async def test_0044_creates_the_table_matching_the_orm_and_downgrades_cleanly(tmp_path, backend): + engine, schema = _engine(tmp_path, backend) + cfg = bootstrap._get_alembic_config(engine, postgres_schema=schema or "") + try: + if schema: + async with engine.begin() as conn: + await conn.execute(sa.text(f'CREATE SCHEMA "{schema}"')) + await asyncio.to_thread(command.upgrade, cfg, PREVIOUS) + assert TABLE not in (await _shape(engine))["tables"] + + await asyncio.to_thread(command.upgrade, cfg, REVISION) + shape = await _shape(engine) + assert set(shape["columns"]) == COLUMNS + assert shape["pk"]["constrained_columns"] == ["provider"] + assert shape["pk"]["name"] in ("pk_channel_runtime_configs", None) # SQLite does not report constraint names + # Only the ciphertext may be NULL: a disconnect tombstone carries no secret. + assert {name for name, column in shape["columns"].items() if column["nullable"]} == {"config_ciphertext"} + # ``make migrate-rev`` would propose nothing: the revision matches the ORM model. + assert await _orm_diff(engine) == [] + + async with engine.begin() as conn: + await conn.execute(sa.insert(ChannelRuntimeConfigRow).values(provider="slack", config_ciphertext="fernet:v2:token", disconnected=False, version=1, updated_at=1_700_000_000.0)) + await conn.execute(sa.insert(ChannelRuntimeConfigRow).values(provider="feishu", config_ciphertext=None, disconnected=True, version=3, updated_at=1_700_000_000.0)) + with pytest.raises(sa.exc.IntegrityError): + async with engine.begin() as conn: + await conn.execute(sa.insert(ChannelRuntimeConfigRow).values(provider="slack", config_ciphertext=None, disconnected=True, version=1, updated_at=1.0)) + + await asyncio.to_thread(command.downgrade, cfg, PREVIOUS) + assert TABLE not in (await _shape(engine))["tables"] + await asyncio.to_thread(command.upgrade, cfg, REVISION) + assert TABLE in (await _shape(engine))["tables"] + finally: + await _drop_schema(engine, schema) + await engine.dispose() + + +@pytest.mark.parametrize("backend", ["sqlite", "postgres"]) +async def test_0044_completes_after_create_all_and_downgrades_after_a_manual_drop(tmp_path, backend): + """The table already exists (an interrupted earlier attempt): upgrade still lands, and vice versa.""" + engine, schema = _engine(tmp_path, backend) + cfg = bootstrap._get_alembic_config(engine, postgres_schema=schema or "") + try: + if schema: + async with engine.begin() as conn: + await conn.execute(sa.text(f'CREATE SCHEMA "{schema}"')) + await asyncio.to_thread(command.upgrade, cfg, PREVIOUS) + async with engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all, tables=[ChannelRuntimeConfigRow.__table__]) + + await asyncio.to_thread(command.upgrade, cfg, REVISION) + async with engine.connect() as conn: + assert (await conn.execute(sa.text("SELECT version_num FROM alembic_version"))).scalar_one() == REVISION + + async with engine.begin() as conn: + await conn.execute(sa.text(f"DROP TABLE {TABLE}")) + await asyncio.to_thread(command.downgrade, cfg, PREVIOUS) + async with engine.connect() as conn: + assert (await conn.execute(sa.text("SELECT version_num FROM alembic_version"))).scalar_one() == PREVIOUS + finally: + await _drop_schema(engine, schema) + await engine.dispose() + + +async def test_bootstrap_provisions_the_table_on_an_empty_database(tmp_path): + engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'bootstrap.db'}") + try: + await bootstrap.bootstrap_schema(engine, backend="sqlite") + await bootstrap.bootstrap_schema(engine, backend="sqlite") + assert set((await _shape(engine))["columns"]) == COLUMNS + async with engine.connect() as conn: + assert (await conn.execute(sa.text("SELECT version_num FROM alembic_version"))).scalar_one() == CURRENT_HEAD + finally: + await engine.dispose() diff --git a/deploy/helm/deer-flow/README.md b/deploy/helm/deer-flow/README.md index 1b8ba0bc7e..a81c19d13b 100644 --- a/deploy/helm/deer-flow/README.md +++ b/deploy/helm/deer-flow/README.md @@ -307,10 +307,11 @@ kubectl -n deer-flow exec deploy/deer-flow-provisioner -- curl -s localhost:8002 replaced within `lease_seconds + grace_seconds` plus one renewal interval (50 s by default) and a Pod stopped cleanly hands its providers over on the next heartbeat. The startup gate refuses `enabled: false` while channels are - enabled. Credentials saved from the web UI reach the holding Pod only when it - next starts the channel, so restart it after changing them, and a failover - loses the IM replies in flight on the old holder, though the runs themselves - finish and their threads stay readable in the web UI. `gateway.replicas: 1` + enabled. Credentials saved (or a disconnect made) from the web UI on any Pod + reach the holding Pod within one renewal interval through the shared, + encrypted `channel_runtime_configs` table. A failover loses the IM replies in + flight on the old holder, though the runs themselves finish and their + threads stay readable in the web UI. `gateway.replicas: 1` stays the default because the WeChat QR login and browser tools are still single-instance. Before raising replicas, also set `persistence.home.accessMode: ReadWriteMany` on multi-node clusters (thread @@ -389,7 +390,7 @@ kubectl -n deer-flow exec deploy/deer-flow-provisioner -- curl -s localhost:8002 ``` - **Credentials key.** The app Secret also holds `DEER_FLOW_CREDENTIALS_KEY`, the Fernet key the gateway encrypts stored credentials with (per-connection - IM channel credentials today). The chart generates it once (32 random bytes, + IM channel credentials and the bot credentials entered in the web UI). The chart generates it once (32 random bytes, urlsafe base64) and preserves it across upgrades via `lookup`; every gateway Pod reads the same value. **Back it up**: deleting the Secret or the release generates a new key, and credentials stored under the old one become diff --git a/frontend/src/content/en/application/deployment-guide.mdx b/frontend/src/content/en/application/deployment-guide.mdx index 40b5a4fed2..042ea4fd55 100644 --- a/frontend/src/content/en/application/deployment-guide.mdx +++ b/frontend/src/content/en/application/deployment-guide.mdx @@ -156,7 +156,7 @@ The Helm chart ships `gateway.replicas: 1`. Raising it is supported for the web The chart exports `DEER_FLOW_MULTI_INSTANCE=true` when `gateway.replicas > 1`, and the Gateway refuses to start if any of these is missing. If you scale with `kubectl scale` or an HPA instead of `gateway.replicas`, set `gateway.multiInstance: true` first so the declaration, the PodDisruptionBudget and the required shared `AUTH_JWT_SECRET` do not keep their single-replica rendering (the PodDisruptionBudget then blocks node drains of the single Pod until the scale-up happens; disable it with `gateway.podDisruptionBudget.enabled: false` for that interim if needed). On multi-node clusters also set `persistence.home.accessMode: ReadWriteMany` (uploads, outputs, memory and `extensions_config.json` live on that volume; MCP and skill changes made through one Pod are then visible to the others on their next request) and `agent_storage.backend: db` so custom agents are visible on every Pod. -IM channels work on several replicas through `channels.leader_lease` in `config` (default `auto`): one Pod holds each platform connection, and when it dies another Pod takes over within `lease_seconds + grace_seconds` plus one renewal interval (50 seconds by default). The startup gate refuses `enabled: false` while channels are enabled. Channel credentials saved from the web UI reach the Pod holding that platform only when it next starts the channel, so restart that Pod after changing them; a takeover loses the IM replies the old Pod was still delivering, although the runs themselves finish and their threads stay readable in the web UI. Still single-instance: the WeChat QR login and browser tools. Keep one replica while those are enabled. +IM channels work on several replicas through `channels.leader_lease` in `config` (default `auto`): one Pod holds each platform connection, and when it dies another Pod takes over within `lease_seconds + grace_seconds` plus one renewal interval (50 seconds by default). The startup gate refuses `enabled: false` while channels are enabled. Channel credentials saved from the web UI on any Pod are stored encrypted in the database and reach the Pod holding that platform within one renewal interval; a takeover loses the IM replies the old Pod was still delivering, although the runs themselves finish and their threads stay readable in the web UI. Still single-instance: the WeChat QR login and browser tools. Keep one replica while those are enabled. ### K8s Provisioner setup diff --git a/frontend/src/content/zh/application/deployment-guide.mdx b/frontend/src/content/zh/application/deployment-guide.mdx index 3fb3d9cc34..8a9fe4f625 100644 --- a/frontend/src/content/zh/application/deployment-guide.mdx +++ b/frontend/src/content/zh/application/deployment-guide.mdx @@ -153,7 +153,7 @@ Helm chart 默认 `gateway.replicas: 1`。当所有副本共享同一个 Postgre 当 `gateway.replicas > 1` 时,chart 会导出 `DEER_FLOW_MULTI_INSTANCE=true`,缺少上述任一项时 Gateway 会拒绝启动。如果你通过 `kubectl scale` 或 HPA 而不是 `gateway.replicas` 扩容,请先设置 `gateway.multiInstance: true`:它们在不执行 Helm upgrade 的情况下改变副本数,否则该声明、PodDisruptionBudget 和必需的共享 `AUTH_JWT_SECRET` 都会停留在单副本的渲染结果上(在真正扩容之前,PodDisruptionBudget 会阻止驱逐唯一的 Pod 和排空节点;如有需要,可在此期间设置 `gateway.podDisruptionBudget.enabled: false`)。多节点集群还需要把 `persistence.home.accessMode` 设为 `ReadWriteMany`(上传、产物、记忆与 `extensions_config.json` 都在该卷上;在一个 Pod 上修改的 MCP 与技能配置会在其他 Pod 的下一次请求中生效),并设置 `agent_storage.backend: db` 让自定义 agent 在每个 Pod 上可见。 -IM 通道可以通过 `config` 中的 `channels.leader_lease`(默认 `auto`)在多副本下运行:每个平台的连接只由一个 Pod 持有,该 Pod 宕机后,另一个 Pod 会在 `lease_seconds + grace_seconds` 再加一个续约周期内接管(默认 50 秒)。启用通道时启动门禁会拒绝 `enabled: false`。在 Web UI 中保存的通道凭据要等持有该平台的 Pod 下次启动通道时才会生效,修改后请重启该 Pod;接管会丢失旧 Pod 上仍在投递的 IM 回复,但运行本身会继续完成,其对话线程仍可在 Web UI 中查看。仍然只能单实例运行的部分:WeChat 扫码登录、浏览器工具。启用这些功能时请保持 1 个副本。 +IM 通道可以通过 `config` 中的 `channels.leader_lease`(默认 `auto`)在多副本下运行:每个平台的连接只由一个 Pod 持有,该 Pod 宕机后,另一个 Pod 会在 `lease_seconds + grace_seconds` 再加一个续约周期内接管(默认 50 秒)。启用通道时启动门禁会拒绝 `enabled: false`。在任一 Pod 的 Web UI 中保存的通道凭据会加密存入数据库,并在一个续约周期内传到持有该平台的 Pod;接管会丢失旧 Pod 上仍在投递的 IM 回复,但运行本身会继续完成,其对话线程仍可在 Web UI 中查看。仍然只能单实例运行的部分:WeChat 扫码登录、浏览器工具。启用这些功能时请保持 1 个副本。 ### K8s Provisioner 配置