-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathcfquant_web_server.py
More file actions
4235 lines (3818 loc) · 161 KB
/
Copy pathcfquant_web_server.py
File metadata and controls
4235 lines (3818 loc) · 161 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
# -*- coding: utf-8 -*-
import argparse
import base64
import email.parser
import email.policy
import fnmatch
import hashlib
import json
import math
import mimetypes
import os
import posixpath
import re
import secrets
import shutil
import sqlite3
import socket
import stat
import subprocess
import sys
import tempfile
import threading
import time
import urllib.parse
import urllib.request
import zipfile
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
_PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
_LTTX_TX_DIR = os.path.join(_PROJECT_DIR, "LTtx", "tx")
def _prepend_import_path(path):
path = os.path.abspath(path)
if not os.path.isdir(path):
return
normalized = path.lower()
sys.path = [
item for item in sys.path
if os.path.abspath(item or os.curdir).lower() != normalized
]
sys.path.insert(0, path)
_prepend_import_path(_PROJECT_DIR)
_prepend_import_path(_LTTX_TX_DIR)
from cfquant.client import CfquantError, CfquantTimeout, LTtxRpcClient
from cfquant.channels import configured_bridges, normalize_bridge_id
from cfquant.protocol import new_id
from tx import txl
BASE_DIR = _PROJECT_DIR
STATIC_DIR = os.path.join(BASE_DIR, "web_dashboard")
LOG_FILE = os.path.join(BASE_DIR, "cfquant_web_server.runtime.log")
LOG_RETENTION_DAYS = int(os.environ.get("CFQUANT_LOG_RETENTION_DAYS", "5"))
LOG_CLEANUP_INTERVAL_SECONDS = float(os.environ.get("CFQUANT_LOG_CLEANUP_INTERVAL_SECONDS", "21600"))
LTTX_HOST = os.environ.get("CFQUANT_LTTX_HOST", "127.0.0.1")
LTTX_PORT = int(os.environ.get("CFQUANT_LTTX_PORT", "2049"))
LTTX_DIR = os.path.join(BASE_DIR, "LTtx", "tx")
LTTX_ENTRY = os.environ.get("CFQUANT_LTTX_ENTRY") or os.path.join(LTTX_DIR, "LTtx_server.py")
LTTX_STDOUT_LOG = os.path.join(BASE_DIR, "lttx_server.stdout.log")
LTTX_STDERR_LOG = os.path.join(BASE_DIR, "lttx_server.stderr.log")
try:
_LOG_FP = open(LOG_FILE, "a", encoding="utf-8", buffering=1)
_WINDOWLESS = os.path.basename(sys.executable).lower() == "pythonw.exe"
if _WINDOWLESS or sys.stdout is None:
sys.stdout = _LOG_FP
if _WINDOWLESS or sys.stderr is None:
sys.stderr = _LOG_FP
except Exception:
_LOG_FP = None
DEFAULT_ACCOUNT_ID = os.environ.get("CFQUANT_ACCOUNT_ID", "2220009880")
WEB_CONFIG_FILE = os.environ.get("CFQUANT_WEB_CONFIG_FILE") or os.path.join(BASE_DIR, "cfquant_web_config.json")
WEB_SETTINGS_DB_FILE = os.environ.get("CFQUANT_WEB_SETTINGS_DB_FILE") or os.path.join(BASE_DIR, "cfquant_web_config.db")
RECONNECT_COOLDOWN_SECONDS = float(os.environ.get("CFQUANT_WEB_RECONNECT_COOLDOWN", "30"))
ENV_BRIDGES = configured_bridges()
BRIDGES = dict(ENV_BRIDGES)
DEFAULT_BRIDGE_ID = normalize_bridge_id(
os.environ.get("CFQUANT_WEB_DEFAULT_BRIDGE_ID") or next(iter(ENV_BRIDGES.keys()))
)
if DEFAULT_BRIDGE_ID not in ENV_BRIDGES:
DEFAULT_BRIDGE_ID = next(iter(ENV_BRIDGES.keys()))
CHANNELS = ENV_BRIDGES[DEFAULT_BRIDGE_ID]["channels"]
CALLBACK_EVENT_CHANNEL = CHANNELS["callback"]
STATUS_CHECK_INTERVAL_SECONDS = float(os.environ.get("CFQUANT_WEB_STATUS_INTERVAL", "15"))
STATUS_PROBE_TIMEOUT_SECONDS = float(os.environ.get("CFQUANT_WEB_STATUS_PROBE_TIMEOUT", "8"))
ACCOUNT_CACHE_REFRESH_SECONDS = float(os.environ.get("CFQUANT_WEB_ACCOUNT_CACHE_INTERVAL", "5"))
ACCOUNT_QUERY_TIMEOUT_SECONDS = float(os.environ.get("CFQUANT_WEB_ACCOUNT_QUERY_TIMEOUT", "30"))
UPDATE_UPLOAD_MAX_BYTES = int(os.environ.get("CFQUANT_UPDATE_UPLOAD_MAX_BYTES", str(80 * 1024 * 1024)))
DEFAULT_UPDATE_REPO_URL = os.environ.get("CFQUANT_UPDATE_REPO_URL", "https://github.com/95ge/cfquant.git").strip()
DEFAULT_UPDATE_REF = os.environ.get("CFQUANT_UPDATE_REF", "main").strip()
UPDATE_REMOTE_CACHE_SECONDS = float(os.environ.get("CFQUANT_UPDATE_REMOTE_CACHE_SECONDS", "300"))
UPDATE_REMOTE_TIMEOUT_SECONDS = float(os.environ.get("CFQUANT_UPDATE_REMOTE_TIMEOUT_SECONDS", "12"))
WEB_BOUND_HOST = None
WEB_BOUND_PORT = None
WEB_RESTART_REQUEST = None
WEB_RESTART_LOCK = threading.RLock()
WEB_AUTH_TOKENS = {}
WEB_AUTH_LOCK = threading.RLock()
STOCK_BUY = 23
STOCK_SELL = 24
FIX_PRICE = 11
ACCOUNT_ACTIONS = {
"asset": "xttrader.query_stock_asset",
"positions": "xttrader.query_stock_positions",
"orders": "xttrader.query_stock_orders",
"trades": "xttrader.query_stock_trades",
}
def get_lan_ip():
sock = None
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(("10.255.255.255", 1))
return sock.getsockname()[0]
except Exception:
return "127.0.0.1"
finally:
if sock is not None:
try:
sock.close()
except Exception:
pass
def normalize_web_port(value, default=8765, strict=False):
if value is None or value == "":
if strict:
raise ValueError("web port is required")
return int(default)
try:
port = int(value)
except Exception:
if strict:
raise ValueError("web port must be an integer")
return int(default)
if port < 1 or port > 65535:
if strict:
raise ValueError("web port must be between 1 and 65535")
return int(default)
return port
def normalize_domain_patterns(value):
if isinstance(value, str):
raw_items = re.split(r"[\s,;]+", value)
elif isinstance(value, (list, tuple, set)):
raw_items = value
else:
raw_items = []
result = []
for item in raw_items:
item = str(item or "").strip().lower()
if not item:
continue
if "://" in item:
parsed = urllib.parse.urlparse(item)
item = (parsed.hostname or "").lower()
if item.startswith("[") and item.endswith("]"):
item = item[1:-1]
if item and item not in result:
result.append(item)
return result
def extract_host_name(value):
value = str(value or "").strip()
if not value:
return ""
try:
if "://" in value:
return (urllib.parse.urlparse(value).hostname or "").lower()
if value.startswith("["):
end = value.find("]")
return value[1:end].lower() if end >= 0 else value.strip("[]").lower()
return value.split(":", 1)[0].lower()
except Exception:
return ""
def is_loopback_host(host):
host = extract_host_name(host)
return host in ("localhost", "::1", "0:0:0:0:0:0:0:1") or host.startswith("127.")
def host_matches_patterns(host, patterns):
host = extract_host_name(host)
if not host:
return True
if is_loopback_host(host):
return True
for pattern in normalize_domain_patterns(patterns):
if pattern == "*" or fnmatch.fnmatch(host, pattern):
return True
return False
def web_password_hash(password, salt):
salt_bytes = bytes.fromhex(str(salt))
digest = hashlib.pbkdf2_hmac(
"sha256",
str(password or "").encode("utf-8"),
salt_bytes,
120000,
)
return digest.hex()
def mask_text(value):
value = str(value or "")
if not value:
return ""
if len(value) <= 2:
return "*" * len(value)
return "%s%s" % (value[:1], "*" * (len(value) - 1))
def clear_web_auth_tokens():
with WEB_AUTH_LOCK:
WEB_AUTH_TOKENS.clear()
def issue_web_auth_token(username):
token = secrets.token_urlsafe(32)
with WEB_AUTH_LOCK:
WEB_AUTH_TOKENS[token] = {
"username": str(username or ""),
"created_at": time.time(),
}
return token
def web_auth_token_info(token):
token = str(token or "").strip()
if not token:
return None
with WEB_AUTH_LOCK:
return dict(WEB_AUTH_TOKENS.get(token) or {}) or None
def revoke_web_auth_token(token):
token = str(token or "").strip()
if not token:
return
with WEB_AUTH_LOCK:
WEB_AUTH_TOKENS.pop(token, None)
class WebRuntimeConfig(object):
def __init__(self, path, settings_db_path=None):
self.path = path
self.settings_db_path = settings_db_path or WEB_SETTINGS_DB_FILE
self._lock = threading.RLock()
self._data = {
"bridges": {},
"account_pairs": {},
"api_key": "",
"allow_remote": False,
"api_base_url": "",
"web_port": normalize_web_port(os.environ.get("CFQUANT_WEB_PORT"), default=8765),
"web_allowed_domains": "",
"web_auth_enabled": False,
"web_auth_username": "",
"web_auth_salt": "",
"web_auth_hash": "",
"cleanup_qmt_userdata_logs": False,
}
self.load()
def load(self):
with self._lock:
legacy_settings = {}
if os.path.isfile(self.path):
try:
with open(self.path, "r", encoding="utf-8") as f:
raw = json.load(f)
if isinstance(raw, dict):
self._data["bridges"] = self._normalize_bridges(raw.get("bridges") or {})
self._data["account_pairs"] = self._normalize_pairs(raw.get("account_pairs") or {})
web_server = raw.get("web_server") if isinstance(raw.get("web_server"), dict) else {}
web_port = raw.get("web_port")
if web_port in (None, ""):
web_port = web_server.get("port")
self._data["web_port"] = normalize_web_port(web_port, default=self._data["web_port"])
legacy_settings = {
"api_key": str(raw.get("api_key") or "").strip(),
"allow_remote": "1" if bool(raw.get("allow_remote")) else "0",
"api_base_url": str(raw.get("api_base_url") or "").strip(),
}
except Exception as e:
safe_print("web runtime config load failed: %s" % e)
try:
self._ensure_settings_db_locked()
self._migrate_legacy_settings_locked(legacy_settings)
self._load_settings_locked()
except Exception as e:
safe_print("web sqlite settings load failed: %s" % e)
def snapshot(self):
with self._lock:
return json.loads(json.dumps(self._data, ensure_ascii=False))
def bridges(self):
bridges = dict(ENV_BRIDGES)
with self._lock:
custom = self._normalize_bridges(self._data.get("bridges") or {})
bridges.update(custom)
return bridges
def account_pairs(self):
with self._lock:
return dict(self._data.get("account_pairs") or {})
def api_key(self):
with self._lock:
return str(self._data.get("api_key") or "").strip()
def api_key_info(self, include_secret=True):
api_key = self.api_key()
if not api_key:
return {"enabled": False, "masked": "", "api_key": ""}
if len(api_key) <= 8:
masked = "*" * len(api_key)
else:
masked = "%s%s" % (api_key[:4], "*" * (len(api_key) - 8) + api_key[-4:])
return {"enabled": True, "masked": masked, "api_key": api_key if include_secret else ""}
def set_api_key(self, api_key):
api_key = str(api_key or "").strip()
with self._lock:
self._data["api_key"] = api_key
self._save_settings_locked({"api_key": api_key})
return self.api_key_info()
def generate_api_key(self):
api_key = "cfq_%s" % secrets.token_urlsafe(24)
info = self.set_api_key(api_key)
info["api_key"] = api_key
return info
def allow_remote(self):
with self._lock:
return bool(self._data.get("allow_remote"))
def web_port(self):
with self._lock:
return normalize_web_port(self._data.get("web_port"), default=8765)
def allowed_domains(self):
with self._lock:
return normalize_domain_patterns(self._data.get("web_allowed_domains") or "")
def web_auth_enabled(self):
with self._lock:
return bool(self._data.get("web_auth_enabled"))
def web_auth_info(self, include_username=True):
with self._lock:
username = str(self._data.get("web_auth_username") or "").strip()
enabled = bool(self._data.get("web_auth_enabled"))
configured = bool(self._data.get("web_auth_hash"))
return {
"enabled": enabled,
"configured": configured,
"username": username if include_username else "",
"username_masked": mask_text(username),
}
def verify_web_auth(self, username, password):
with self._lock:
if not self._data.get("web_auth_enabled"):
return False
expected_user = str(self._data.get("web_auth_username") or "").strip()
salt = str(self._data.get("web_auth_salt") or "").strip()
expected_hash = str(self._data.get("web_auth_hash") or "").strip()
if not expected_user or not salt or not expected_hash:
return False
if str(username or "").strip() != expected_user:
return False
try:
actual_hash = web_password_hash(password, salt)
except Exception:
return False
return secrets.compare_digest(actual_hash, expected_hash)
def set_allow_remote(self, value, api_base_url=None):
with self._lock:
self._data["allow_remote"] = bool(value)
if api_base_url is not None:
self._data["api_base_url"] = str(api_base_url or "").strip()
self._save_settings_locked({
"allow_remote": "1" if self._data["allow_remote"] else "0",
"api_base_url": self._data["api_base_url"],
})
return self.server_access_info()
def set_server_access_settings(
self,
allow_remote=None,
api_base_url=None,
web_port=None,
allowed_domains=None,
web_auth_enabled=None,
web_auth_username=None,
web_auth_password=None,
):
auth_changed = False
with self._lock:
settings_values = {}
json_dirty = False
next_allow_remote = bool(self._data.get("allow_remote"))
next_api_base_url = str(self._data.get("api_base_url") or "").strip()
next_web_port = normalize_web_port(self._data.get("web_port"), default=8765)
next_domains_text = ",".join(self.allowed_domains())
next_auth_enabled = bool(self._data.get("web_auth_enabled"))
next_auth_username = str(self._data.get("web_auth_username") or "").strip()
next_auth_salt = str(self._data.get("web_auth_salt") or "").strip()
next_auth_hash = str(self._data.get("web_auth_hash") or "").strip()
if allow_remote is not None:
next_allow_remote = bool(allow_remote)
if api_base_url is not None:
next_api_base_url = str(api_base_url or "").strip()
if web_port is not None:
next_web_port = normalize_web_port(web_port, default=8765, strict=True)
if allowed_domains is not None:
next_domains_text = ",".join(normalize_domain_patterns(allowed_domains))
if web_auth_enabled is not None:
next_auth_enabled = bool(web_auth_enabled)
if web_auth_username is not None:
next_auth_username = str(web_auth_username or "").strip()
if next_auth_enabled and not next_auth_username:
next_auth_username = "admin"
if web_auth_password is not None and str(web_auth_password) != "":
next_auth_salt = secrets.token_hex(16)
next_auth_hash = web_password_hash(web_auth_password, next_auth_salt)
if next_auth_enabled and not next_auth_hash:
raise ValueError("web auth password is required when web auth is enabled")
if bool(self._data.get("allow_remote")) != next_allow_remote:
self._data["allow_remote"] = next_allow_remote
settings_values["allow_remote"] = "1" if next_allow_remote else "0"
if str(self._data.get("api_base_url") or "").strip() != next_api_base_url:
self._data["api_base_url"] = next_api_base_url
settings_values["api_base_url"] = next_api_base_url
if normalize_web_port(self._data.get("web_port"), default=8765) != next_web_port:
self._data["web_port"] = next_web_port
json_dirty = True
if str(self._data.get("web_allowed_domains") or "") != next_domains_text:
self._data["web_allowed_domains"] = next_domains_text
settings_values["web_allowed_domains"] = next_domains_text
current_auth = (
bool(self._data.get("web_auth_enabled")),
str(self._data.get("web_auth_username") or "").strip(),
str(self._data.get("web_auth_salt") or "").strip(),
str(self._data.get("web_auth_hash") or "").strip(),
)
next_auth = (next_auth_enabled, next_auth_username, next_auth_salt, next_auth_hash)
if current_auth != next_auth:
auth_changed = True
self._data["web_auth_enabled"] = next_auth_enabled
self._data["web_auth_username"] = next_auth_username
self._data["web_auth_salt"] = next_auth_salt
self._data["web_auth_hash"] = next_auth_hash
settings_values.update({
"web_auth_enabled": "1" if next_auth_enabled else "0",
"web_auth_username": next_auth_username,
"web_auth_salt": next_auth_salt,
"web_auth_hash": next_auth_hash,
})
if settings_values:
self._save_settings_locked(settings_values)
if json_dirty:
self._save_locked()
if auth_changed:
clear_web_auth_tokens()
return self.server_access_info()
def qmt_userdata_log_cleanup_enabled(self):
with self._lock:
return bool(self._data.get("cleanup_qmt_userdata_logs"))
def log_cleanup_info(self):
return {
"retention_days": LOG_RETENTION_DAYS,
"local_cfquant_logs_enabled": True,
"qmt_userdata_log_cleanup_enabled": self.qmt_userdata_log_cleanup_enabled(),
}
def set_log_cleanup_settings(self, cleanup_qmt_userdata_logs=None):
with self._lock:
if cleanup_qmt_userdata_logs is not None:
self._data["cleanup_qmt_userdata_logs"] = bool(cleanup_qmt_userdata_logs)
self._save_settings_locked({
"cleanup_qmt_userdata_logs": "1" if self._data.get("cleanup_qmt_userdata_logs") else "0",
})
return self.log_cleanup_info()
def server_access_info(self, bound_host=None, bound_port=None, include_auth_details=True):
allow_remote = self.allow_remote()
with self._lock:
api_base_url = str(self._data.get("api_base_url") or "").strip()
configured_host = "0.0.0.0" if allow_remote else "127.0.0.1"
configured_port = self.web_port()
host = bound_host if bound_host is not None else configured_host
active_port = normalize_web_port(bound_port, default=configured_port) if bound_port else configured_port
lan_ip = get_lan_ip()
port_part = ":%s" % active_port if active_port else ""
local_url = "http://127.0.0.1%s" % port_part if bound_port else ""
lan_url = "http://%s%s" % (lan_ip, port_part) if bound_port and lan_ip != "127.0.0.1" else ""
configured_local_url = "http://127.0.0.1:%s/" % configured_port
configured_lan_url = "http://%s:%s/" % (lan_ip, configured_port) if lan_ip != "127.0.0.1" else ""
host_needs_restart = bound_host is not None and host != configured_host
port_needs_restart = bound_port is not None and int(bound_port) != int(configured_port)
domains = self.allowed_domains()
web_auth = self.web_auth_info(include_username=include_auth_details)
return {
"allow_remote": allow_remote,
"configured_host": configured_host,
"configured_port": configured_port,
"web_port": configured_port,
"bound_host": host,
"bound_port": bound_port,
"local_ip": lan_ip,
"local_url": local_url,
"lan_url": lan_url,
"configured_local_url": configured_local_url,
"configured_lan_url": configured_lan_url,
"next_url": configured_local_url,
"api_base_url": api_base_url,
"allowed_domains": domains,
"allowed_domains_text": ",".join(domains),
"web_auth": web_auth,
"web_auth_enabled": web_auth["enabled"],
"web_auth_username": web_auth["username"],
"web_auth_username_masked": web_auth["username_masked"],
"requires_restart": host_needs_restart or port_needs_restart,
"restart_required": host_needs_restart or port_needs_restart,
}
def save_bridge(self, bridge):
bridge_id = normalize_bridge_id((bridge or {}).get("id") or (bridge or {}).get("bridge_id"))
if not bridge_id:
raise ValueError("bridge id is required")
name = str((bridge or {}).get("name") or bridge_id).strip() or bridge_id
channels = (bridge or {}).get("channels") or {}
python_dir = normalize_optional_path((bridge or {}).get("python_dir") or (bridge or {}).get("project_dir"))
row = {
"id": bridge_id,
"name": name,
"python_dir": python_dir,
"channels": {
"normal": str(channels.get("normal") or ("cfquant.%s.normal.request" % bridge_id if bridge_id != "default" else CHANNELS["normal"])).strip(),
"trade": str(channels.get("trade") or ("cfquant.%s.trade.request" % bridge_id if bridge_id != "default" else CHANNELS["trade"])).strip(),
"callback": str(channels.get("callback") or ("cfquant.%s.callback.event" % bridge_id if bridge_id != "default" else CHANNELS["callback"])).strip(),
},
}
with self._lock:
self._data.setdefault("bridges", {})[bridge_id] = row
self._save_locked()
return row
def delete_bridge(self, bridge_id):
bridge_id = normalize_bridge_id(bridge_id)
if bridge_id in ENV_BRIDGES:
raise ValueError("environment bridge cannot be deleted from web: %s" % bridge_id)
with self._lock:
self._data.setdefault("bridges", {}).pop(bridge_id, None)
pairs = self._data.setdefault("account_pairs", {})
for account_id, pair in list(pairs.items()):
if normalize_bridge_id(pair.get("bridge_id")) == bridge_id:
pairs.pop(account_id, None)
self._save_locked()
def save_pair(self, account_id, bridge_id):
account_id = str(account_id or "").strip()
bridge_id = normalize_bridge_id(bridge_id)
if not account_id:
raise ValueError("account_id is required")
if bridge_id not in self.bridges():
raise ValueError("unknown bridge_id: %s" % bridge_id)
row = {
"account_id": account_id,
"bridge_id": bridge_id,
"updated_at": time.time(),
}
with self._lock:
self._data.setdefault("account_pairs", {})[account_id] = row
self._save_locked()
return row
def delete_pair(self, account_id):
account_id = str(account_id or "").strip()
with self._lock:
self._data.setdefault("account_pairs", {}).pop(account_id, None)
self._save_locked()
def _ensure_settings_db_locked(self):
db_dir = os.path.dirname(os.path.abspath(self.settings_db_path))
if db_dir and not os.path.isdir(db_dir):
os.makedirs(db_dir)
with sqlite3.connect(self.settings_db_path) as conn:
conn.execute(
"create table if not exists settings ("
"key text primary key,"
"value text not null,"
"updated_at real not null)"
)
def _settings_keys_locked(self):
self._ensure_settings_db_locked()
with sqlite3.connect(self.settings_db_path) as conn:
rows = conn.execute("select key from settings").fetchall()
return set(row[0] for row in rows)
def _migrate_legacy_settings_locked(self, legacy_settings):
if not legacy_settings:
return
existing = self._settings_keys_locked()
values = {}
api_key = str(legacy_settings.get("api_key") or "").strip()
api_base_url = str(legacy_settings.get("api_base_url") or "").strip()
if "api_key" not in existing and api_key:
values["api_key"] = api_key
if "allow_remote" not in existing:
values["allow_remote"] = "1" if legacy_settings.get("allow_remote") == "1" else "0"
if "api_base_url" not in existing and api_base_url:
values["api_base_url"] = api_base_url
if values:
self._save_settings_locked(values)
def _load_settings_locked(self):
self._ensure_settings_db_locked()
with sqlite3.connect(self.settings_db_path) as conn:
rows = conn.execute("select key, value from settings").fetchall()
settings = dict((str(key), str(value)) for key, value in rows)
if "api_key" in settings:
self._data["api_key"] = settings.get("api_key") or ""
if "allow_remote" in settings:
self._data["allow_remote"] = self._settings_bool(settings.get("allow_remote"))
if "api_base_url" in settings:
self._data["api_base_url"] = settings.get("api_base_url") or ""
if "web_allowed_domains" in settings:
self._data["web_allowed_domains"] = settings.get("web_allowed_domains") or ""
if "web_auth_enabled" in settings:
self._data["web_auth_enabled"] = self._settings_bool(settings.get("web_auth_enabled"))
if "web_auth_username" in settings:
self._data["web_auth_username"] = settings.get("web_auth_username") or ""
if "web_auth_salt" in settings:
self._data["web_auth_salt"] = settings.get("web_auth_salt") or ""
if "web_auth_hash" in settings:
self._data["web_auth_hash"] = settings.get("web_auth_hash") or ""
if "cleanup_qmt_userdata_logs" in settings:
self._data["cleanup_qmt_userdata_logs"] = self._settings_bool(settings.get("cleanup_qmt_userdata_logs"))
def _save_settings_locked(self, values):
self._ensure_settings_db_locked()
rows = [(str(key), str(value or ""), time.time()) for key, value in (values or {}).items()]
if not rows:
return
with sqlite3.connect(self.settings_db_path) as conn:
conn.executemany(
"insert or replace into settings (key, value, updated_at) values (?, ?, ?)",
rows,
)
def _settings_bool(self, value):
return str(value or "").strip().lower() in ("1", "true", "yes", "on")
def _save_locked(self):
temp_path = self.path + ".tmp"
with open(temp_path, "w", encoding="utf-8") as f:
json.dump({
"bridges": self._data.get("bridges") or {},
"account_pairs": self._data.get("account_pairs") or {},
"web_port": normalize_web_port(self._data.get("web_port"), default=8765),
}, f, ensure_ascii=False, indent=2, sort_keys=True)
os.replace(temp_path, self.path)
def _normalize_bridges(self, value):
result = {}
if isinstance(value, list):
items = value
elif isinstance(value, dict):
items = value.values()
else:
items = []
for item in items:
if not isinstance(item, dict):
continue
bridge_id = normalize_bridge_id(item.get("id") or item.get("bridge_id"))
channels = item.get("channels") or {}
result[bridge_id] = {
"id": bridge_id,
"name": str(item.get("name") or bridge_id),
"python_dir": normalize_optional_path(item.get("python_dir") or item.get("project_dir")),
"channels": {
"normal": str(channels.get("normal") or ("cfquant.%s.normal.request" % bridge_id if bridge_id != "default" else CHANNELS["normal"])),
"trade": str(channels.get("trade") or ("cfquant.%s.trade.request" % bridge_id if bridge_id != "default" else CHANNELS["trade"])),
"callback": str(channels.get("callback") or ("cfquant.%s.callback.event" % bridge_id if bridge_id != "default" else CHANNELS["callback"])),
},
}
return result
def _normalize_pairs(self, value):
result = {}
if isinstance(value, list):
items = value
elif isinstance(value, dict):
items = value.values()
else:
items = []
for item in items:
if not isinstance(item, dict):
continue
account_id = str(item.get("account_id") or "").strip()
bridge_id = normalize_bridge_id(item.get("bridge_id"))
if account_id and bridge_id:
result[account_id] = {
"account_id": account_id,
"bridge_id": bridge_id,
"updated_at": float(item.get("updated_at") or 0),
}
return result
WEB_CONFIG = None
def current_bridges():
if WEB_CONFIG is not None:
return WEB_CONFIG.bridges()
return dict(ENV_BRIDGES)
def bridge_config(bridge_id=None):
bridge_id = normalize_bridge_id(bridge_id or DEFAULT_BRIDGE_ID)
bridges = current_bridges()
if bridge_id not in bridges:
raise ValueError("unknown bridge_id: %s" % bridge_id)
return bridges[bridge_id]
def bridge_channels(bridge_id=None):
return bridge_config(bridge_id)["channels"]
def resolve_bridge_id(account_id=None, bridge_id=None):
raw_bridge_id = str(bridge_id or "").strip()
if raw_bridge_id:
return normalize_bridge_id(raw_bridge_id)
account_id = str(account_id or "").strip()
if account_id:
pair = WEB_CONFIG.account_pairs().get(account_id)
if pair and pair.get("bridge_id"):
return normalize_bridge_id(pair.get("bridge_id"))
return DEFAULT_BRIDGE_ID
def callback_channels():
channels = []
for bridge in current_bridges().values():
channel = bridge["channels"]["callback"]
if channel not in channels:
channels.append(channel)
return channels
class GlobalTxClient(object):
def __init__(self):
self._lock = threading.RLock()
self._client = None
self.client_id = os.environ.get("CFQUANT_WEB_CLIENT_ID") or new_id("cfquant_web")
self._cooldown_until = {}
self._last_error = {}
def start(self):
self._get_client().start()
def request(self, bridge_id, channel_key, action, params=None, timeout=8.0, mark_offline_on_timeout=False, ignore_cooldown=False):
channels = bridge_channels(bridge_id)
if channel_key not in ("normal", "trade"):
raise ValueError("unknown channel: %s" % channel_key)
cooldown_key = (normalize_bridge_id(bridge_id), channel_key)
if not ignore_cooldown:
self._check_cooldown(cooldown_key)
client = self._get_client()
try:
result = client.request(
action,
params or {},
timeout=timeout,
request_channel=channels[channel_key],
)
self._cooldown_until.pop(cooldown_key, None)
self._last_error.pop(cooldown_key, None)
return result
except CfquantError:
raise
except CfquantTimeout as e:
if mark_offline_on_timeout:
self._mark_failed(cooldown_key, e)
raise
except Exception as e:
self._mark_failed(cooldown_key, e)
self.close()
raise
def close(self):
with self._lock:
client = self._client
self._client = None
if client is not None:
try:
client.close()
except Exception:
pass
def _check_cooldown(self, cooldown_key):
now = time.time()
cooldown_until = self._cooldown_until.get(cooldown_key, 0)
if now < cooldown_until:
last_error = self._last_error.get(cooldown_key, "previous connection failed")
raise RuntimeError(
"bridge %s channel %s is in reconnect cooldown %.1fs: %s"
% (cooldown_key[0], cooldown_key[1], cooldown_until - now, last_error)
)
def _get_client(self):
with self._lock:
if self._client is None:
self._client = LTtxRpcClient(
request_channel=CHANNELS["normal"],
client_id=self.client_id,
)
return self._client
def _mark_failed(self, cooldown_key, error=None):
self._cooldown_until[cooldown_key] = time.time() + RECONNECT_COOLDOWN_SECONDS
if error is not None:
self._last_error[cooldown_key] = str(error)
def add_callback(self, event, callback):
self._get_client().add_callback(event, callback)
def remove_callback(self, event, callback):
client = self._client
if client is not None:
client.remove_callback(event, callback)
CLIENTS = GlobalTxClient()
class WebSocketCallbackClient(object):
def __init__(self, sock, bridge_id="", account_id=""):
self.sock = sock
self.bridge_id = normalize_bridge_id(bridge_id) if bridge_id else ""
self.account_id = str(account_id or "").strip()
self._lock = threading.RLock()
self.alive = True
def matches(self, event):
if self.bridge_id and normalize_bridge_id(event.get("bridge_id") or "default") != self.bridge_id:
return False
if self.account_id and CallbackEventStore.event_account_id_static(event) != self.account_id:
return False
return True
def send_json(self, payload):
raw = json.dumps(to_jsonable(payload), ensure_ascii=False, separators=(",", ":")).encode("utf-8")
frame = self._frame(raw)
with self._lock:
self.sock.sendall(frame)
def close(self):
self.alive = False
try:
self.sock.close()
except Exception:
pass
def _frame(self, payload):
length = len(payload)
header = bytearray([0x81])
if length < 126:
header.append(length)
elif length <= 0xFFFF:
header.append(126)
header.extend(length.to_bytes(2, "big"))
else:
header.append(127)
header.extend(length.to_bytes(8, "big"))
return bytes(header) + payload
class WebSocketCallbackManager(object):
def __init__(self):
self._lock = threading.RLock()
self._clients = set()
def add(self, client):
with self._lock:
self._clients.add(client)
def remove(self, client):
with self._lock:
self._clients.discard(client)
client.close()
def broadcast(self, event):
dead = []
with self._lock:
clients = list(self._clients)
for client in clients:
if not client.alive or not client.matches(event):
continue
try:
client.send_json({
"type": "callback",
"event": event,
})
except Exception:
dead.append(client)
for client in dead:
self.remove(client)
def count(self):
with self._lock:
return len(self._clients)
WS_CALLBACKS = WebSocketCallbackManager()
class WebSocketQuoteClient(WebSocketCallbackClient):
def __init__(self, sock, subscribe_id=None):
WebSocketCallbackClient.__init__(self, sock)
self.subscribe_id = str(subscribe_id or "").strip()
def matches(self, event):
if self.subscribe_id and str(event.get("subscribe_id") or "") != self.subscribe_id:
return False
return True
class WebSocketQuoteManager(object):
def __init__(self):
self._lock = threading.RLock()
self._clients = set()
self.on_empty = None
def add(self, client):
with self._lock:
self._clients.add(client)
def remove(self, client):
with self._lock:
self._clients.discard(client)
empty = not self._clients
client.close()
if empty and callable(self.on_empty):
try:
self.on_empty()
except Exception as e:
safe_print("websocket quotes empty callback failed: %s" % e)
def broadcast(self, event):
dead = []
with self._lock:
clients = list(self._clients)
for client in clients:
if not client.alive or not client.matches(event):
continue
try:
client.send_json({
"type": "quote",
"event": event,
})
except Exception:
dead.append(client)
for client in dead:
self.remove(client)
def count(self):
with self._lock:
return len(self._clients)
WS_QUOTES = WebSocketQuoteManager()