envs.py
12.7 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
"""演示版本(环境):每个演示版本是一个独立的 MySQL 库,表名与主库完全相同。
为什么按库、不按表名加版本号:表名一变,ORM 映射就得跟着改,老版本也没法和新代码共存;
按库隔离则代码零改动,版本之间、版本与开发数据之间互不污染。
- 开发环境 `dev`:主库(settings.db_name,默认 ai_ontology_dev)。
- 演示版本 `v1`、`v2`……:从开发环境「保存为演示版本」时整库复制出来:
ai_ontology_demo_v1 演示时读写的库
ai_ontology_demo_v1_base 冻结的底稿,「重置本版本数据」时用它覆盖上面那个
编号自动递增;说明(label)和对外展示哪些菜单(nav)由保存的人填。
- 请求头 `X-Onto-Env`(或 ?env=)决定这次请求走哪个库,由 main.py 的中间件放进 contextvar;
不认识的值一律按开发环境处理。
注册表 otlg_demo_env 只存在主库里。快照里的数据源如果指向主库本身(demo 业务表 otlg_dm_* 就在主库),
会改指向快照库 —— 演示时的写回只落在快照自己的 otlg_dm_* 上,开发数据不受影响。
"""
from __future__ import annotations
import contextvars
import datetime as dt
import logging
import re
import shutil
import subprocess
import threading
import time
from pathlib import Path
from sqlalchemy import DateTime, Integer, String, Text, create_engine, inspect, select, text as sa_text
from sqlalchemy.orm import Mapped, Session, mapped_column
from . import db as core_db
from .config import get_settings
from .db import _NOW, Base
log = logging.getLogger(__name__)
DEV = "dev"
DEMO_DB_PREFIX = "ai_ontology_demo_"
REGISTRY_TABLE = "otlg_demo_env"
# 知识图谱、向量索引、上传文件存在数据目录里,跟着快照复制一份;LLM 缓存按内容寻址,各环境共用
DATA_ITEMS = ("graph.json", "communities.json", "index", "uploads")
_current: contextvars.ContextVar[str] = contextvars.ContextVar("otlg_env", default=DEV)
class DemoEnv(Base):
__tablename__ = REGISTRY_TABLE
id: Mapped[str] = mapped_column(String(16), primary_key=True) # v1 / v2 …
seq: Mapped[int] = mapped_column(Integer, default=0)
label: Mapped[str] = mapped_column(String(255), default="")
db_name: Mapped[str] = mapped_column(String(128), default="")
base_db: Mapped[str] = mapped_column(String(128), default="")
nav_json: Mapped[str] = mapped_column(Text, default="[]") # 对外展示的菜单 key
git_commit: Mapped[str] = mapped_column(String(64), default="")
created_by: Mapped[str] = mapped_column(String(64), default="")
created_at: Mapped[dt.datetime] = mapped_column(DateTime, server_default=_NOW)
reset_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
# ---------- 当前环境 ----------
def current() -> str:
return _current.get()
def set_current(env_id: str):
return _current.set(env_id or DEV)
def reset(token) -> None:
_current.reset(token)
def is_dev() -> bool:
return current() == DEV
# ---------- 注册表(永远读主库) ----------
_known: tuple[float, dict[str, dict]] = (0.0, {})
_known_lock = threading.Lock()
_KNOWN_TTL = 10.0
def _primary() -> Session:
return Session(core_db.engine)
def _dict(e: DemoEnv) -> dict:
import json
try:
nav = json.loads(e.nav_json or "[]")
except ValueError:
nav = []
return {"id": e.id, "seq": e.seq, "label": e.label, "db_name": e.db_name, "base_db": e.base_db,
"nav": nav, "git_commit": e.git_commit, "created_by": e.created_by,
"created_at": e.created_at.isoformat(sep=" ", timespec="seconds") if e.created_at else "",
"reset_at": e.reset_at.isoformat(sep=" ", timespec="seconds") if e.reset_at else ""}
def list_envs() -> list[dict]:
with _primary() as s:
return [_dict(e) for e in s.scalars(select(DemoEnv).order_by(DemoEnv.seq)).all()]
def get_env(env_id: str) -> dict | None:
return known().get(env_id)
def known() -> dict[str, dict]:
"""已登记的演示版本(带 10 秒缓存;中间件每个请求都要查)。"""
global _known
with _known_lock:
if time.time() - _known[0] < _KNOWN_TTL:
return _known[1]
try:
envs = {e["id"]: e for e in list_envs()}
except Exception: # noqa: BLE001 注册表还没建(首次启动前)时当作没有演示版本
envs = {}
with _known_lock:
_known = (time.time(), envs)
return envs
def _invalidate() -> None:
global _known
with _known_lock:
_known = (0.0, {})
def resolve(raw: str) -> str:
"""把请求带来的环境 id 规整成已登记的 id;不认识就回开发环境。"""
raw = (raw or "").strip()
if not raw or raw == DEV:
return DEV
return raw if raw in known() else DEV
# ---------- 引擎 ----------
_engines: dict[str, object] = {}
_engine_lock = threading.RLock()
def engine_for(env_id: str):
if env_id == DEV:
return core_db.engine
eng = _engines.get(env_id)
if eng is not None:
return eng
with _engine_lock:
eng = _engines.get(env_id)
if eng is not None:
return eng
env = get_env(env_id)
if env is None:
return core_db.engine
eng = create_engine(get_settings().url_for(env["db_name"]), pool_pre_ping=True,
pool_recycle=1800, future=True)
core_db.init_schema(eng) # 快照是老代码时建的,新代码加的表 / 列在这里补上
_engines[env_id] = eng
return eng
def engine_for_current():
return engine_for(current())
def _dispose(env_id: str) -> None:
with _engine_lock:
eng = _engines.pop(env_id, None)
if eng is not None:
eng.dispose()
# ---------- 数据目录 ----------
def data_dir(env_id: str | None = None) -> Path:
"""当前环境的数据目录:开发环境是 DATA_DIR 本身,演示版本是 DATA_DIR/envs/<id>。"""
base = get_settings().data_path
env_id = env_id or current()
if env_id == DEV:
return base
d = base / "envs" / env_id
if not d.exists():
return base
return d
def _copy_data(src: Path, dst: Path) -> None:
if dst.exists():
shutil.rmtree(dst)
dst.mkdir(parents=True, exist_ok=True)
for name in DATA_ITEMS:
p = src / name
if p.is_dir():
shutil.copytree(p, dst / name)
elif p.exists():
shutil.copy2(p, dst / name)
(dst / "uploads").mkdir(exist_ok=True)
(dst / "index").mkdir(exist_ok=True)
# ---------- 快照 ----------
_ID_RE = re.compile(r"^v(\d{1,4})$")
_snap_lock = threading.Lock()
def _git_commit() -> str:
try:
root = Path(__file__).resolve().parents[2]
out = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=root, capture_output=True,
text=True, timeout=5)
dirty = subprocess.run(["git", "status", "--porcelain"], cwd=root, capture_output=True,
text=True, timeout=5)
sha = out.stdout.strip()
return f"{sha}+改动未提交" if sha and dirty.stdout.strip() else sha
except Exception: # noqa: BLE001
return ""
def _tables(conn, schema: str) -> list[str]:
rows = conn.execute(sa_text(
"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA=:s "
"AND TABLE_TYPE='BASE TABLE' ORDER BY TABLE_NAME"), {"s": schema}).fetchall()
return [r[0] for r in rows if r[0].startswith("otlg_") and r[0] != REGISTRY_TABLE]
def _clone_db(conn, src: str, dst: str) -> int:
"""同一台 MySQL 内整库复制(CREATE TABLE LIKE + INSERT SELECT),返回复制的行数。"""
conn.execute(sa_text(f"DROP DATABASE IF EXISTS `{dst}`"))
conn.execute(sa_text(f"CREATE DATABASE `{dst}` CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci"))
rows = 0
for t in _tables(conn, src):
conn.execute(sa_text(f"CREATE TABLE `{dst}`.`{t}` LIKE `{src}`.`{t}`"))
rows += conn.execute(sa_text(f"INSERT INTO `{dst}`.`{t}` SELECT * FROM `{src}`.`{t}`")).rowcount or 0
return rows
def _repoint_datasources(conn, src: str, dst: str) -> None:
"""数据源若指向源库本身(demo 业务表就在里面),改指向快照库。"""
st = get_settings()
if "otlg_datasource" not in _tables(conn, dst):
return
conn.execute(sa_text(
f"UPDATE `{dst}`.`otlg_datasource` SET db_name=:dst "
f"WHERE ds_type='mysql' AND db_name=:src AND host=:h AND port=:p"),
{"dst": dst, "src": src, "h": st.db_host, "p": st.db_port})
def next_id() -> str:
seqs = [e["seq"] for e in list_envs()]
return f"v{(max(seqs) if seqs else 0) + 1}"
def create_snapshot(label: str, nav: list[str], created_by: str = "") -> dict:
"""把开发环境(主库 + 数据目录)冻结成一个新的演示版本。"""
import json
if not is_dev():
raise ValueError("只能从开发环境保存演示版本")
with _snap_lock:
env_id = next_id()
seq = int(env_id[1:])
live, base = f"{DEMO_DB_PREFIX}{env_id}", f"{DEMO_DB_PREFIX}{env_id}_base"
primary = get_settings().db_name
t0 = time.time()
with core_db.engine.begin() as conn:
rows = _clone_db(conn, primary, live)
_repoint_datasources(conn, primary, live)
_clone_db(conn, live, base)
data = get_settings().data_path
_copy_data(data, data / "envs" / env_id)
_copy_data(data / "envs" / env_id, data / "envs" / f"{env_id}.base")
with _primary() as s:
s.add(DemoEnv(id=env_id, seq=seq, label=label.strip() or env_id, db_name=live, base_db=base,
nav_json=json.dumps(list(nav), ensure_ascii=False), git_commit=_git_commit(),
created_by=created_by))
s.commit()
_invalidate()
log.info("已保存演示版本 %s(%d 行,%.1fs)", env_id, rows, time.time() - t0)
return get_env(env_id) or {"id": env_id}
def update_env(env_id: str, *, label: str | None = None, nav: list[str] | None = None) -> dict:
import json
with _primary() as s:
e = s.get(DemoEnv, env_id)
if e is None:
raise KeyError(env_id)
if label is not None:
e.label = label.strip() or e.label
if nav is not None:
e.nav_json = json.dumps(list(nav), ensure_ascii=False)
s.commit()
_invalidate()
return get_env(env_id) or {}
def reset_snapshot(env_id: str) -> dict:
"""用冻结的底稿覆盖演示库:排练弄脏了,正式汇报前一键恢复。"""
env = get_env(env_id)
if env is None:
raise KeyError(env_id)
with _snap_lock:
_dispose(env_id)
with core_db.engine.begin() as conn:
_clone_db(conn, env["base_db"], env["db_name"])
data = get_settings().data_path / "envs"
if (data / f"{env_id}.base").exists():
_copy_data(data / f"{env_id}.base", data / env_id)
with _primary() as s:
e = s.get(DemoEnv, env_id)
e.reset_at = dt.datetime.now()
s.commit()
_invalidate()
_drop_caches()
return get_env(env_id) or {}
def delete_snapshot(env_id: str) -> None:
env = get_env(env_id)
if env is None:
raise KeyError(env_id)
with _snap_lock:
_dispose(env_id)
with core_db.engine.begin() as conn:
for name in (env["db_name"], env["base_db"]):
if name.startswith(DEMO_DB_PREFIX): # 只删自己建的库,防手滑
conn.execute(sa_text(f"DROP DATABASE IF EXISTS `{name}`"))
data = get_settings().data_path / "envs"
for d in (data / env_id, data / f"{env_id}.base"):
if d.exists():
shutil.rmtree(d, ignore_errors=True)
with _primary() as s:
e = s.get(DemoEnv, env_id)
if e is not None:
s.delete(e)
s.commit()
_invalidate()
_drop_caches()
def _drop_caches() -> None:
"""快照被覆盖 / 删除后,清掉各处按环境缓存的东西。"""
from ..api import deps
from ..governance import users
from ..kernel import linker, service
for fn in (users.invalidate, linker.invalidate, service.invalidate_runtime, deps.reset_state):
try:
fn()
except Exception: # noqa: BLE001
log.warning("清缓存失败:%s", fn, exc_info=True)
def table_counts(env_id: str) -> dict[str, int]:
eng = engine_for(env_id)
with eng.connect() as c:
return {t: c.execute(sa_text(f"SELECT COUNT(*) FROM `{t}`")).scalar() or 0
for t in inspect(eng).get_table_names() if t.startswith("otlg_")}