mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-28 01:10:35 +00:00
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.
This commit is contained in:
parent
9b0c7cbc37
commit
8d5f5fd0a8
19
CHANGELOG.md
19
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
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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.
|
||||
>
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -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()
|
||||
|
||||
@ -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():
|
||||
|
||||
@ -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
|
||||
|
||||
|
||||
@ -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"]
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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=<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.
|
||||
|
||||
|
||||
@ -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.
|
||||
|
||||
@ -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",
|
||||
]
|
||||
@ -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
|
||||
@ -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
|
||||
@ -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)
|
||||
|
||||
@ -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)
|
||||
@ -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",
|
||||
|
||||
@ -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()
|
||||
|
||||
@ -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}}
|
||||
|
||||
@ -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)
|
||||
|
||||
297
backend/tests/test_channel_runtime_config_db_store.py
Normal file
297
backend/tests/test_channel_runtime_config_db_store.py
Normal file
@ -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
|
||||
395
backend/tests/test_channel_runtime_config_replicas.py
Normal file
395
backend/tests/test_channel_runtime_config_replicas.py
Normal file
@ -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
|
||||
@ -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"
|
||||
|
||||
|
||||
@ -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"}
|
||||
|
||||
@ -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 = {
|
||||
|
||||
@ -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
|
||||
|
||||
|
||||
@ -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"}
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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"
|
||||
|
||||
@ -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"
|
||||
|
||||
|
||||
|
||||
@ -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
|
||||
|
||||
162
backend/tests/test_migration_0044_channel_runtime_configs.py
Normal file
162
backend/tests/test_migration_0044_channel_runtime_configs.py
Normal file
@ -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()
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
|
||||
@ -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 配置
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user