Repository navigation
Expand file tree
/
Copy pathconfig_manager.py
More file actions
1551 lines (1327 loc) · 60 KB
/
Copy pathconfig_manager.py
File metadata and controls
1551 lines (1327 loc) · 60 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Unified Configuration Manager for Condor Bot.
Manages servers, users, permissions, and settings in a single config.yml file.
"""
import asyncio
import logging
import secrets
import shutil
import time
from enum import Enum
from pathlib import Path
from typing import Any, Dict, Optional, Tuple
import yaml
from aiohttp import ClientTimeout
logger = logging.getLogger(__name__)
class UserRole(str, Enum):
"""User roles in the system"""
ADMIN = "admin"
USER = "user"
PENDING = "pending"
BLOCKED = "blocked"
class ServerPermission(str, Enum):
"""Permission levels for server access"""
OWNER = "owner"
TRADER = "trader"
PERMISSION_HIERARCHY = {
ServerPermission.TRADER: 0,
ServerPermission.OWNER: 1,
}
# The user preference that hands a non-admin seat the in-process code runner
# (SEC-151). It is stored under ``user_preferences[<id>]`` like any other
# preference, but it is a *capability grant*: only an admin may set it, and
# ``condor/web/routes/code.py`` reads it as the fallback arm of its gate.
# Declared here so the gate and the thing that grants it share one spelling.
CODE_RUN_PREFERENCE = "code_run"
# The sentinel `main.py` used to write into `username` when Telegram gave it
# none (FEAT-088). It only ever meant "absent", but stored it is indistinguishable
# from a real handle, so the panel renders `@No username` forever. It is dropped
# on load and never written again — an absent handle is an absent key.
ABSENT_USERNAME = "No username"
# How stale `last_seen` is allowed to get before a contact rewrites config.yml.
# `restricted` runs on every message *and* every button press, and each write is
# a full YAML dump of the file, so recording the exact second would turn a menu
# walk into a dozen rewrites. Five minutes is far finer than the "2 days ago"
# the panel renders.
LAST_SEEN_RESOLUTION_SEC = 300
# Preference keys that are capability grants rather than settings. They live in
# the same ``user_preferences`` map as a UI toggle, so any endpoint that merges
# a caller-supplied dict into that map is a privilege-escalation path unless it
# refuses these first (SEC-250). Writing one goes through its own audited setter
# — ``set_code_run_grant`` for ``code_run`` — never through a bulk merge.
RESERVED_PREFERENCE_KEYS = frozenset({CODE_RUN_PREFERENCE})
class ConfigManager:
"""
Unified configuration manager for Condor Bot.
Handles servers, users, permissions, and chat defaults in a single YAML file.
Uses singleton pattern - access via ConfigManager.instance()
"""
VERSION = 1
MAX_AUDIT_LOG_ENTRIES = 500
_instance: Optional["ConfigManager"] = None
def __init__(self, config_path: str = "config.yml"):
self.config_path = Path(config_path)
self.audit_log_path = Path("audit_log.yml")
self._data: dict = {}
self._audit_log: list = []
self._clients: Dict[str, Tuple[Any, float]] = (
{}
) # server_name -> (client, connect_time)
self._client_ttl = 300 # 5 minutes
self._client_verify_interval = 60 # seconds between liveness checks
self._client_locks: Dict[str, asyncio.Lock] = (
{}
) # per-server lock for get_client
# When a connect last failed, per server. Client creation is serialized
# by _client_locks, so without this every caller queued behind a down
# server pays the full connect timeout again, one after another: the 10
# concurrent fetches SDS fires per server at boot turned one unreachable
# host into ~110s of serial timeouts before the dashboard could bind.
self._client_failures: Dict[str, float] = {} # server_name -> failed_at
self._client_failure_ttl = 30 # seconds to fail fast after a failure
# Short-lived memo of check_server_status results so the N parallel
# probes fired by one menu render (and repeated taps) collapse to one
# probe per server. Kept well under _client_verify_interval.
self._status_cache: Dict[str, Tuple[dict, float]] = (
{}
) # server_name -> (status_result, checked_at)
self._status_ttl = 15 # seconds
self._status_locks: Dict[str, asyncio.Lock] = (
{}
) # per-server lock for check_server_status
# True when an existing config file could not be read: the in-memory
# state is empty and MUST NOT be written back over the file on disk.
self._load_failed = False
self._load_config()
self._load_audit_log()
@classmethod
def instance(cls, config_path: str = "config.yml") -> "ConfigManager":
"""Get the singleton instance."""
if cls._instance is None:
cls._instance = cls(config_path)
return cls._instance
@classmethod
def reset_instance(cls) -> None:
"""Reset the singleton (for testing)."""
cls._instance = None
def _get_admin_from_env(self) -> Optional[int]:
"""Get admin user ID from environment."""
from utils.config import ADMIN_USER_ID
return ADMIN_USER_ID
@property
def _backup_path(self) -> Path:
"""Path of the rotating backup written before each save."""
return self.config_path.with_suffix(self.config_path.suffix + ".bak")
def _read_config_file(self, path: Path) -> Optional[dict]:
"""Read and parse a config file. Returns None if unreadable."""
try:
with open(path, "r") as f:
return yaml.safe_load(f) or {}
except Exception as e:
logger.error(f"Failed to load config from {path}: {e}")
return None
def _load_config(self):
"""Load configuration from YAML file.
A read failure is never a write: an existing but unreadable config is
left untouched on disk (we fall back to the `.bak`, and otherwise run
with empty in-memory state and refuse to save) so it can be recovered
by hand.
"""
if not self.config_path.exists():
self._init_default_config()
return
data = self._read_config_file(self.config_path)
if data is None and self._backup_path.exists():
logger.warning(
f"Config {self.config_path} unreadable, "
f"attempting recovery from {self._backup_path}"
)
data = self._read_config_file(self._backup_path)
if data is not None:
logger.info("Successfully recovered config from backup")
if data is None:
self._load_failed = True
self._data = self._default_data()
self._audit_log = []
admin_id = self._data.get("admin_id")
if admin_id:
self._ensure_admin_user(admin_id)
logger.error(
f"Config {self.config_path} is unreadable and no usable backup "
f"exists. Running with empty in-memory config and REFUSING to "
f"save, so the file is preserved for manual recovery. "
f"Fix or remove it and restart."
)
return
self._data = data
# Ensure all sections exist
self._data.setdefault("servers", {})
self._data.setdefault("default_server", None)
self._data.setdefault("users", {})
self._data.setdefault("server_access", {})
self._data.setdefault("chat_defaults", {})
self._data.setdefault("user_preferences", {})
self._data.setdefault("telemetry", {})
self._data.setdefault("sharing", {})
# Drop the `"No username"` sentinel (FEAT-088). It is not a migration of
# meaning — the string only ever stood for "Telegram told us nothing" —
# so leaving it would keep `@No username` renderable for the life of the
# install. Healed on load and rewritten on the next save.
users = self._data["users"]
if any(
isinstance(r, dict) and r.get("username") == ABSENT_USERNAME
for r in users.values()
):
for record in users.values():
if isinstance(record, dict) and record.get("username") == (
ABSENT_USERNAME
):
record.pop("username", None)
self._save_config()
# Migrate audit_log from config.yml to separate file (one-time)
if "audit_log" in self._data:
self._audit_log = self._data.pop("audit_log")
self._save_audit_log()
self._save_config() # Save config without audit_log
# Always trust admin_id from env
admin_id = self._get_admin_from_env()
if admin_id:
self._data["admin_id"] = admin_id
self._ensure_admin_user(admin_id)
logger.info(f"Loaded config from {self.config_path}")
def _default_data(self) -> dict:
"""Build an empty config structure."""
return {
"servers": {},
"default_server": None,
"admin_id": self._get_admin_from_env(),
"users": {},
"server_access": {},
"chat_defaults": {},
"user_preferences": {},
"telemetry": {},
"version": self.VERSION,
}
def _init_default_config(self):
"""Initialize with default configuration."""
self._data = self._default_data()
self._audit_log = []
admin_id = self._data.get("admin_id")
if admin_id:
self._ensure_admin_user(admin_id)
self._save_config()
logger.info(f"Created new config at {self.config_path}")
def _ensure_admin_user(self, admin_id: int):
"""Ensure admin user exists in users dict."""
if admin_id not in self._data["users"]:
self._data["users"][admin_id] = {
"user_id": admin_id,
"role": UserRole.ADMIN.value,
"created_at": time.time(),
"notes": "Primary admin from ADMIN_USER_ID",
}
self._save_config()
def _save_config(self):
"""Save configuration to YAML file."""
if self._load_failed:
logger.warning(
f"Not saving config: {self.config_path} could not be read at "
f"startup and would be overwritten with empty state"
)
return
try:
data = {
"servers": self._data.get("servers", {}),
"default_server": self._data.get("default_server"),
"admin_id": self._data.get("admin_id"),
"users": self._data.get("users", {}),
"server_access": self._data.get("server_access", {}),
"chat_defaults": self._data.get("chat_defaults", {}),
# Omitting this dropped every preference on the next save —
# including the code_run grant, which _load_config reads back
# and routes/code.py gates on (ARCH-177).
"user_preferences": self._data.get("user_preferences", {}),
"web_jwt_secret": self._data.get("web_jwt_secret"),
"telemetry": self._data.get("telemetry", {}),
# Same omission as ARCH-177 above, one section newer: without
# this the admin's sharing veto, each user's standing answer and
# the share_secret behind the stable pseudonyms were re-minted
# on every restart (CORR-244).
"sharing": self._data.get("sharing", {}),
"version": self._data.get("version", self.VERSION),
}
# Keep a copy of the last known-good file before truncating it,
# so a partial write can be recovered from on the next load.
if self.config_path.exists():
try:
shutil.copy2(self.config_path, self._backup_path)
except OSError as e:
logger.warning(f"Failed to back up config: {e}")
with open(self.config_path, "w") as f:
yaml.dump(
data,
f,
default_flow_style=False,
sort_keys=False,
allow_unicode=True,
)
logger.debug(f"Saved config to {self.config_path}")
except Exception as e:
logger.error(f"Failed to save config: {e}")
raise
def _load_audit_log(self):
"""Load audit log from separate file."""
if not self.audit_log_path.exists():
self._audit_log = []
return
try:
with open(self.audit_log_path, "r") as f:
data = yaml.safe_load(f) or {}
self._audit_log = data.get("entries", [])
logger.debug(f"Loaded {len(self._audit_log)} audit log entries")
except Exception as e:
logger.error(f"Failed to load audit log: {e}")
self._audit_log = []
def _save_audit_log(self):
"""Save audit log to separate file."""
try:
# Trim to max entries
if len(self._audit_log) > self.MAX_AUDIT_LOG_ENTRIES:
self._audit_log = self._audit_log[-self.MAX_AUDIT_LOG_ENTRIES :]
data = {"entries": self._audit_log}
with open(self.audit_log_path, "w") as f:
yaml.dump(
data,
f,
default_flow_style=False,
sort_keys=False,
allow_unicode=True,
)
logger.debug(f"Saved {len(self._audit_log)} audit log entries")
except Exception as e:
logger.error(f"Failed to save audit log: {e}")
def reload(self):
"""Reload configuration from file."""
self._load_config()
self._load_audit_log()
@property
def admin_id(self) -> Optional[int]:
return self._data.get("admin_id")
# =========================================================================
# SERVER MANAGEMENT
# =========================================================================
def list_servers(self) -> Dict[str, dict]:
"""List all configured servers."""
return self._data.get("servers", {}).copy()
def get_server(self, name: str) -> Optional[dict]:
"""Get a specific server configuration."""
return self._data.get("servers", {}).get(name)
def server_name_for_client(self, client: Any) -> Optional[str]:
"""The configured server a client talks to, or ``None`` if it matches none.
By identity against the clients this manager handed out, else by the
``base_url`` :meth:`get_client` builds from a server's host and port — so
a caller holding only a client (the fetchers) can still ask for the
server-keyed caches, such as market rates.
"""
for name, (cached, _) in list(self._clients.items()):
if cached is client:
return name
base_url = str(getattr(client, "base_url", "") or "").rstrip("/")
if not base_url:
return None
for name, server in self._data.get("servers", {}).items():
if f"http://{server.get('host')}:{server.get('port')}" == base_url:
return name
return None
def add_server(
self,
name: str,
host: str,
port: int,
username: str,
password: str,
owner_id: int = None,
) -> bool:
"""Add a new server."""
servers = self._data["servers"]
if name in servers:
logger.error(f"Server '{name}' already exists")
return False
servers[name] = {
"host": host,
"port": port,
"username": username,
"password": password,
}
# Register ownership
if owner_id:
self.register_server_owner(name, owner_id)
self._save_config()
logger.info(f"Added server '{name}'")
return True
def modify_server(
self,
name: str,
host: str = None,
port: int = None,
username: str = None,
password: str = None,
) -> bool:
"""Modify an existing server."""
servers = self._data["servers"]
if name not in servers:
logger.error(f"Server '{name}' not found")
return False
# Clear cached client and any memoized status
self._invalidate_server_caches(name)
if host is not None:
servers[name]["host"] = host
if port is not None:
servers[name]["port"] = port
if username is not None:
servers[name]["username"] = username
if password is not None:
servers[name]["password"] = password
self._save_config()
logger.info(f"Modified server '{name}'")
return True
def delete_server(self, name: str, actor_id: int = None) -> bool:
"""Delete a server."""
servers = self._data["servers"]
if name not in servers:
logger.error(f"Server '{name}' not found")
return False
# Clear cached client and any memoized status
self._invalidate_server_caches(name)
del servers[name]
# Unregister from access control
if name in self._data["server_access"]:
del self._data["server_access"][name]
self._save_config()
logger.info(f"Deleted server '{name}'")
return True
def get_default_server(self) -> Optional[str]:
"""Get the default server name."""
return self._data.get("default_server")
def set_default_server(self, name: str) -> bool:
"""Set the default server."""
if name not in self._data["servers"]:
logger.error(f"Server '{name}' not found")
return False
self._data["default_server"] = name
self._save_config()
logger.info(f"Set default server to '{name}'")
return True
def get_or_create_web_jwt_secret(self) -> str:
"""Return the web dashboard JWT signing secret, generating one on demand.
On first use a strong random secret is generated and persisted to
``config.yml`` so web sessions survive restarts. The web layer prefers an
explicit ``WEB_JWT_SECRET`` env var over this value for multi-instance or
rotation scenarios; this is the zero-config default for everyone else.
"""
secret = self._data.get("web_jwt_secret")
if secret:
return secret
secret = secrets.token_urlsafe(32)
self._data["web_jwt_secret"] = secret
self._save_config()
logger.info(
"Generated and persisted a new web dashboard JWT secret in %s",
self.config_path,
)
return secret
def _invalidate_server_caches(self, name: str):
"""Drop every cached artefact of a server: the pooled client, the memoized
status, and the whole SDS data cache for that name.
Called whenever the server's credentials or existence change, so a
cached client or status can never outlive the config it was built from.
The data cache is keyed by server *name* (CacheKey, server_data_service.py),
never by host, so repointing a server at a different host/port would
otherwise keep serving the previous host's answers under the same name
until each type's TTL expires on its own.
"""
self._clients.pop(name, None)
self._status_cache.pop(name, None)
# New credentials deserve a real attempt, not the old failure's cooldown.
self._client_failures.pop(name, None)
try:
# Lazy, mirroring the direction SDS already imports this module in
# (server_data_service.py) — no cycle, and a cache layer must never
# be able to fail a config write.
from condor.server_data_service import get_server_data_service
get_server_data_service().invalidate_server(name)
except Exception:
logger.debug("SDS invalidation skipped for '%s'", name, exc_info=True)
async def get_client(self, name: str = None):
"""Get or create API client for a server."""
from hummingbot_api_client import HummingbotAPIClient
if name is None:
name = self.get_default_server()
if not name:
if self._data["servers"]:
name = list(self._data["servers"].keys())[0]
else:
raise ValueError("No servers configured")
if name not in self._data["servers"]:
raise ValueError(f"Server '{name}' not found")
# Fast path (no lock): return cached client if recently verified
if name in self._clients:
client, last_verified = self._clients[name]
if time.time() - last_verified < self._client_verify_interval:
return client
# Serialize client creation/verification per server to prevent
# concurrent coroutines from creating duplicate sessions
if name not in self._client_locks:
self._client_locks[name] = asyncio.Lock()
async with self._client_locks[name]:
return await self._get_or_create_client(name, HummingbotAPIClient)
async def _get_or_create_client(self, name: str, HummingbotAPIClient):
"""Inner client acquisition — must be called under _client_locks[name]."""
# Re-check under lock (another coroutine may have just created it)
if name in self._clients:
client, last_verified = self._clients[name]
if time.time() - last_verified < self._client_verify_interval:
# Fast path: recently verified
return client
elif time.time() - last_verified < self._client_ttl:
# Needs liveness check
try:
await asyncio.wait_for(client.accounts.list_accounts(), timeout=5)
self._clients[name] = (client, time.time())
return client
except Exception:
logger.warning(
f"Stale connection to '{name}' detected, reconnecting"
)
try:
await client.close()
except Exception:
pass
del self._clients[name]
else:
try:
await client.close()
except Exception:
pass
del self._clients[name]
# Fail fast while a recent connect failure is still fresh, so a queue of
# callers behind an unreachable host costs one connect timeout in total
# rather than one each. Cleared on success, on a config change, and by
# simply ageing out — so a server that comes back is retried within
# _client_failure_ttl without anything having to notice it recovered.
failed_at = self._client_failures.get(name)
if failed_at is not None:
if time.time() - failed_at < self._client_failure_ttl:
raise ConnectionError(
f"Server '{name}' is unreachable (last attempt "
f"{time.time() - failed_at:.0f}s ago); not retrying yet"
)
del self._client_failures[name]
# Create new client
server = self._data["servers"][name]
base_url = f"http://{server['host']}:{server['port']}"
client = HummingbotAPIClient(
base_url=base_url,
username=server["username"],
password=server["password"],
timeout=ClientTimeout(total=60, connect=10),
)
try:
await client.init()
await client.accounts.list_accounts()
self._clients[name] = (client, time.time())
self._client_failures.pop(name, None)
logger.info(f"Connected to server '{name}' at {base_url}")
return client
except Exception as e:
await client.close()
self._client_failures[name] = time.time()
logger.error(f"Failed to connect to '{name}': {e}")
raise
async def get_client_for_chat(
self, chat_id: int, user_id: int = None, preferred_server: str = None
):
"""Get the API client for a user's preferred or first accessible server.
Priority:
1. preferred_server (from user preferences/context) if accessible
2. chat_defaults[chat_id] if accessible
3. First accessible server for the user
4. If no user_id, use chat default or any available server
"""
if user_id:
accessible = self.get_accessible_servers(user_id)
if not accessible:
raise ValueError(
"No servers available. Ask the admin to share a server with you."
)
# 1. User's preferred server if accessible
if preferred_server and preferred_server in accessible:
return await self.get_client(preferred_server)
# 2. Chat's default server if accessible
chat_default = self._data.get("chat_defaults", {}).get(chat_id)
if chat_default and chat_default in accessible:
return await self.get_client(chat_default)
# 3. First accessible server
return await self.get_client(accessible[0])
# No user_id — no access list to check against, so the caller's explicit
# choice wins over the chat default. This branch used to drop
# preferred_server entirely, which meant a routine run (web, MCP or agent)
# and any handler that omits user_id ran against the chat default no matter
# which server was actually selected.
if preferred_server and preferred_server in self._data["servers"]:
return await self.get_client(preferred_server)
server_name = self.get_chat_default_server(chat_id)
if not server_name:
raise ValueError("No servers configured")
return await self.get_client(server_name)
STATUS_PROBE_TIMEOUT = 3 # seconds — a dead server must not stall a menu
@staticmethod
def _classify_status_error(exc: Exception) -> dict:
"""Map a failed liveness probe to the status shown in the menus."""
error_msg = str(exc)
if isinstance(exc, asyncio.TimeoutError):
return {"status": "offline", "message": "Connection timeout"}
if "401" in error_msg:
return {"status": "auth_error", "message": "Invalid credentials"}
if "timeout" in error_msg.lower():
return {"status": "offline", "message": "Connection timeout"}
if "connect" in error_msg.lower():
return {"status": "offline", "message": "Cannot reach server"}
return {"status": "error", "message": f"Error: {error_msg[:80]}"}
def _pooled_client(self, name: str):
"""Return the pooled client for a server if it is still within TTL."""
entry = self._clients.get(name)
if not entry:
return None
client, connected_at = entry
if time.time() - connected_at >= self._client_ttl:
return None
return client
async def check_server_status(self, name: str) -> dict:
"""Check if a server is online.
Probes through the pooled client when ConfigManager already holds one,
and only builds a short-timeout throwaway client when there is none (or
when the pooled session itself is broken). Results are memoized per
server for _status_ttl seconds so one menu render costs at most one
probe per server.
"""
if name not in self._data["servers"]:
return {"status": "error", "message": "Server not found"}
cached = self._status_cache.get(name)
if cached and time.time() - cached[1] < self._status_ttl:
return dict(cached[0])
lock = self._status_locks.setdefault(name, asyncio.Lock())
async with lock:
# Re-check: a concurrent probe for this server may have just landed
cached = self._status_cache.get(name)
if cached and time.time() - cached[1] < self._status_ttl:
return dict(cached[0])
result = await self._probe_server_status(name)
self._status_cache[name] = (result, time.time())
return dict(result)
async def _probe_server_status(self, name: str) -> dict:
"""Run one liveness probe, preferring the pooled client."""
# Same call shape as condor/fetchers/server_status.py:fetch_server_status
# so the two liveness probes stay in step.
client = self._pooled_client(name)
if client is not None:
try:
await asyncio.wait_for(
client.accounts.list_accounts(),
timeout=self.STATUS_PROBE_TIMEOUT,
)
return {"status": "online", "message": "Connected and authenticated"}
except Exception as e:
# The pooled session may simply be stale — confirm with a fresh
# short-timeout client rather than reporting a false outage.
# The pooled client is never closed here: get_client owns it.
logger.debug(f"Pooled status probe for '{name}' failed: {e}")
return await self._probe_server_status_fresh(name)
async def _probe_server_status_fresh(self, name: str) -> dict:
"""Liveness probe over a throwaway short-timeout client."""
from hummingbot_api_client import HummingbotAPIClient
server = self._data["servers"][name]
base_url = f"http://{server['host']}:{server['port']}"
client = HummingbotAPIClient(
base_url=base_url,
username=server["username"],
password=server["password"],
timeout=ClientTimeout(total=3, connect=2),
)
try:
await client.init()
await client.accounts.list_accounts()
return {"status": "online", "message": "Connected and authenticated"}
except Exception as e:
return self._classify_status_error(e)
finally:
try:
await client.close()
except Exception:
pass
async def close_all_clients(self):
"""Close all cached client connections."""
for name, (client, _) in list(self._clients.items()):
try:
await client.close()
logger.info(f"Closed connection to '{name}'")
except Exception as e:
logger.error(f"Error closing client '{name}': {e}")
self._clients.clear()
self._status_cache.clear()
# =========================================================================
# USER MANAGEMENT
# =========================================================================
# ── Telemetry (FEAT-023) ──
# Consent and the install's random identity live here because this file is
# the one durable, process-wide store the MCP subprocess can also read.
# Nothing in this section is transmitted except `install_id` and `level`;
# `install_secret` never leaves the machine. See PRIVACY.md.
def get_telemetry(self) -> dict:
"""The telemetry section. Empty dict on an install that never opted in."""
section = self._data.get("telemetry")
return dict(section) if isinstance(section, dict) else {}
def update_telemetry(self, **changes) -> dict:
"""Merge keys into the telemetry section and persist."""
section = self._data.setdefault("telemetry", {})
if not isinstance(section, dict):
section = {}
self._data["telemetry"] = section
section.update(changes)
self._save_config()
return dict(section)
def get_sharing(self) -> dict:
"""The conversation-sharing section (FEAT-054). Empty on a fresh install.
Deliberately separate from :meth:`get_telemetry`: the two record
different promises to different people. Telemetry consent is the
admin's, install-wide, and anonymous counts; sharing holds an admin veto
plus this install's own random ids, and the content it gates belongs to
individual users.
"""
section = self._data.get("sharing")
return dict(section) if isinstance(section, dict) else {}
def update_sharing(self, **changes) -> dict:
"""Merge keys into the sharing section and persist."""
section = self._data.setdefault("sharing", {})
if not isinstance(section, dict):
section = {}
self._data["sharing"] = section
section.update(changes)
self._save_config()
return dict(section)
def get_user(self, user_id: int) -> Optional[dict]:
"""Get user record."""
return self._data.get("users", {}).get(user_id)
def get_user_role(self, user_id: int) -> Optional[UserRole]:
"""Get user's role."""
user = self.get_user(user_id)
if user:
try:
return UserRole(user["role"])
except ValueError:
return None
return None
def is_admin(self, user_id: int) -> bool:
return self.get_user_role(user_id) == UserRole.ADMIN
def is_approved(self, user_id: int) -> bool:
role = self.get_user_role(user_id)
return role in (UserRole.ADMIN, UserRole.USER)
def register_pending(
self,
user_id: int,
username: str = None,
first_name: str = None,
last_name: str = None,
) -> bool:
"""Register a new pending user.
Records the names Telegram supplied alongside the handle (FEAT-088):
the admin panel has to answer *who this is*, and a handle is optional on
Telegram while a first name is not. Absent fields are left out of the
record rather than stored as `None` or as a `"No username"` placeholder,
so "we were never told" and "they are called this" stay distinguishable.
"""
users = self._data["users"]
if user_id in users:
return False
record = {
"user_id": user_id,
"role": UserRole.PENDING.value,
"created_at": time.time(),
}
for key, value in (
("username", username),
("first_name", first_name),
("last_name", last_name),
):
value = (value or "").strip()
if value and value != ABSENT_USERNAME:
record[key] = value
users[user_id] = record
self._audit("user_registered", "user", str(user_id), user_id)
self._save_config()
logger.info(f"Registered pending user {user_id}")
return True
def touch_user_identity(
self,
user_id: int,
*,
username: str = None,
first_name: str = None,
last_name: str = None,
) -> bool:
"""Record what Telegram currently says this person is called.
Called on every authorized contact, because a handle changes silently:
captured once at registration it is stale forever, and the admin panel
ends up naming someone by a handle nobody answers to.
**Never writes a falsy value over a stored one.** Telegram updates carry
whichever fields they carry, and a message that simply omits the username
must not erase the handle we already know — that would make the record
worse the more often we look at it. Only a differing, non-empty value is
a write.
Returns True when something changed, so callers can tell a real capture
from the overwhelmingly common no-op; the save happens here, like every
other verb on this class.
"""
user = self._data.get("users", {}).get(user_id)
if user is None:
return False
changed = False
for key, value in (
("username", username),
("first_name", first_name),
("last_name", last_name),
):
value = (value or "").strip()
if not value or value == ABSENT_USERNAME:
continue
if user.get(key) != value:
user[key] = value
changed = True
now = time.time()
if now - float(user.get("last_seen") or 0) >= LAST_SEEN_RESOLUTION_SEC:
user["last_seen"] = now
changed = True
if changed:
self._save_config()
return changed
def approve_user(self, user_id: int, admin_id: int) -> bool:
"""Approve a pending user."""
users = self._data["users"]
if user_id not in users:
return False
if users[user_id]["role"] == UserRole.BLOCKED.value:
return False
users[user_id]["role"] = UserRole.USER.value
users[user_id]["approved_by"] = admin_id
users[user_id]["approved_at"] = time.time()
self._audit("user_approved", "user", str(user_id), admin_id)
self._save_config()
logger.info(f"User {user_id} approved by {admin_id}")
return True
def reject_user(self, user_id: int, admin_id: int) -> bool:
"""Reject a pending user."""
users = self._data["users"]
if user_id not in users or users[user_id]["role"] != UserRole.PENDING.value:
return False
del users[user_id]
self._audit("user_rejected", "user", str(user_id), admin_id)
self._save_config()
return True
def block_user(self, user_id: int, admin_id: int) -> bool:
"""Block a user."""
users = self._data["users"]
if user_id not in users or user_id == admin_id:
return False
if users[user_id]["role"] == UserRole.ADMIN.value:
return False
users[user_id]["role"] = UserRole.BLOCKED.value
self._audit("user_blocked", "user", str(user_id), admin_id)
self._save_config()
return True
def unblock_user(self, user_id: int, admin_id: int) -> bool:
"""Unblock a user (sets to pending)."""
users = self._data["users"]
if user_id not in users or users[user_id]["role"] != UserRole.BLOCKED.value:
return False
users[user_id]["role"] = UserRole.PENDING.value
self._audit("user_unblocked", "user", str(user_id), admin_id)
self._save_config()
return True
def get_pending_users(self) -> list:
return [
u
for u in self._data.get("users", {}).values()
if u.get("role") == UserRole.PENDING.value
]
def get_all_users(self) -> list:
return list(self._data.get("users", {}).values())
# =========================================================================
# USER PREFERENCES (persisted in config.yml, shared across TG + Web)