ys_base 0.2.1__tar.gz → 0.2.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {ys_base-0.2.1 → ys_base-0.2.3}/.gitignore +3 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/PKG-INFO +8 -2
- {ys_base-0.2.1 → ys_base-0.2.3}/README.md +7 -1
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_app_server.py +51 -1
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_logging.py +19 -4
- ys_base-0.2.3/tests/test_mongo_store.py +148 -0
- ys_base-0.2.3/tests/test_runtime_info.py +25 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/__init__.py +1 -1
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/auth/client.py +21 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/server/app_server.py +16 -1
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/server/logging.py +8 -6
- ys_base-0.2.3/ys_base/server/runtime_info.py +61 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/store/mongo.py +1 -60
- ys_base-0.2.1/tests/test_mongo_store.py +0 -222
- {ys_base-0.2.1 → ys_base-0.2.3}/.python-version +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/pyproject.toml +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/memory_store.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_api_token.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_contracts.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_crypto.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_files.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_files_migrate.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_http_errors.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_iso_reference.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_rpc_client.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_search.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/tests/test_store_delta.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/uv.lock +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/_pinyin_data.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/auth/__init__.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/auth/api_token.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/auth/delta.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/contracts/__init__.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/contracts/authorization.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/contracts/base.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/contracts/enums.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/contracts/iso_reference.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/contracts/master.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/contracts/platform.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/contracts/relations.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/crypto.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/files.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/files_migrate.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/py.typed +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/search.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/server/__init__.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/server/errors.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/server/http_errors.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/server/jwt_verify.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/server/router.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/store/__init__.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/store/base.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/ws/__init__.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.3}/ys_base/ws/rpc_client.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: ys_base
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.3
|
|
4
4
|
Summary: YS 统一 SDK:契约模型 / auth 客户端与差量同步 / 应用服务骨架
|
|
5
5
|
Author-email: ys <popsars@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -44,6 +44,12 @@ uv sync --all-extras --frozen
|
|
|
44
44
|
uv run pytest
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
+
## 进程日志与运行环境上报(0.2.3 起)
|
|
48
|
+
|
|
49
|
+
- `configure_logging()` 写标准错误和 `app/logs/app-YYYY-MM-DD.log`:每天零点(进程所在时区,容器设 `TZ=Asia/Shanghai`)切新文件,保留 30 天。0.2.2 及以前只按 10 MB 滚动,写的是 `app.log`;升级后它不再写入,确认不需要后手动删除。
|
|
50
|
+
- `AppServer` 注册时向 Auth 上报 `runtime`:Python 版本、自家 Python 包(`ys-base`、装了的 `ys-trade-sdk`)版本、`web/package.json` 里 `@ysgroup/*` 的版本、主机名、进程号、启动时间。只报版本,不报路径、环境变量和配置。镜像里要带上 `web/package.json`(Template 的 `deploy/Dockerfile` 已复制),没有时前端版本为空。Auth 在应用管理「运行状态」里展示。
|
|
51
|
+
- 浏览器经业务系统登录(`login`)和兑换跳转码(`exchange_sso_code`)时,`AppServer` 把浏览器连接的对端地址写进转给 Auth 的 `client_ip`(覆盖浏览器自己带的值),Auth 只认已注册应用连接上报的这个字段。
|
|
52
|
+
|
|
47
53
|
## 列表搜索(0.1.98 起)
|
|
48
54
|
|
|
49
55
|
服务端过滤的列表用 `ys_base.search`,规则与前端 `@ysgroup/core` 的 `ysSearchText` / `ysMatch` 完全相同
|
|
@@ -469,7 +475,7 @@ uv add "ys_base==$version"
|
|
|
469
475
|
|
|
470
476
|
交易客户端、行情、静态信息和收益数据服务在 `ys_trade_sdk`。每个 `TradeManager` 独占一个 `TradeRuntime`。
|
|
471
477
|
|
|
472
|
-
|
|
478
|
+
Auth 协议逻辑表名继续保持 `users`、`owners`、`accounts`、`brokers`;Mongo 物理镜像统一为 `_auth_*`,同步状态为 `_auth_sync_state`,本地身份集合为 `_local_users`、`_local_user_roles`。`ys_base` 0.2.2 起启动不再把旧集合名原地改名;旧名 `auth_*`、`auth_sync_state`、`users`、`user_roles` 是非法表名。
|
|
473
479
|
|
|
474
480
|
```python
|
|
475
481
|
from ys_trade_sdk import (
|
|
@@ -25,6 +25,12 @@ uv sync --all-extras --frozen
|
|
|
25
25
|
uv run pytest
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
+
## 进程日志与运行环境上报(0.2.3 起)
|
|
29
|
+
|
|
30
|
+
- `configure_logging()` 写标准错误和 `app/logs/app-YYYY-MM-DD.log`:每天零点(进程所在时区,容器设 `TZ=Asia/Shanghai`)切新文件,保留 30 天。0.2.2 及以前只按 10 MB 滚动,写的是 `app.log`;升级后它不再写入,确认不需要后手动删除。
|
|
31
|
+
- `AppServer` 注册时向 Auth 上报 `runtime`:Python 版本、自家 Python 包(`ys-base`、装了的 `ys-trade-sdk`)版本、`web/package.json` 里 `@ysgroup/*` 的版本、主机名、进程号、启动时间。只报版本,不报路径、环境变量和配置。镜像里要带上 `web/package.json`(Template 的 `deploy/Dockerfile` 已复制),没有时前端版本为空。Auth 在应用管理「运行状态」里展示。
|
|
32
|
+
- 浏览器经业务系统登录(`login`)和兑换跳转码(`exchange_sso_code`)时,`AppServer` 把浏览器连接的对端地址写进转给 Auth 的 `client_ip`(覆盖浏览器自己带的值),Auth 只认已注册应用连接上报的这个字段。
|
|
33
|
+
|
|
28
34
|
## 列表搜索(0.1.98 起)
|
|
29
35
|
|
|
30
36
|
服务端过滤的列表用 `ys_base.search`,规则与前端 `@ysgroup/core` 的 `ysSearchText` / `ysMatch` 完全相同
|
|
@@ -450,7 +456,7 @@ uv add "ys_base==$version"
|
|
|
450
456
|
|
|
451
457
|
交易客户端、行情、静态信息和收益数据服务在 `ys_trade_sdk`。每个 `TradeManager` 独占一个 `TradeRuntime`。
|
|
452
458
|
|
|
453
|
-
|
|
459
|
+
Auth 协议逻辑表名继续保持 `users`、`owners`、`accounts`、`brokers`;Mongo 物理镜像统一为 `_auth_*`,同步状态为 `_auth_sync_state`,本地身份集合为 `_local_users`、`_local_user_roles`。`ys_base` 0.2.2 起启动不再把旧集合名原地改名;旧名 `auth_*`、`auth_sync_state`、`users`、`user_roles` 是非法表名。
|
|
454
460
|
|
|
455
461
|
```python
|
|
456
462
|
from ys_trade_sdk import (
|
|
@@ -300,6 +300,8 @@ async def test_front_login_forwards_server_app_name():
|
|
|
300
300
|
return {"user": {"_id": "u1"}, "access_token": "a", "refresh_token": "r"}
|
|
301
301
|
|
|
302
302
|
class FakeWs:
|
|
303
|
+
client = SimpleNamespace(host="10.1.2.3")
|
|
304
|
+
|
|
303
305
|
async def send_text(self, payload):
|
|
304
306
|
self.payload = payload
|
|
305
307
|
|
|
@@ -311,7 +313,8 @@ async def test_front_login_forwards_server_app_name():
|
|
|
311
313
|
{
|
|
312
314
|
"id": "1",
|
|
313
315
|
"event": "login",
|
|
314
|
-
|
|
316
|
+
# 浏览器自带的 client_ip 不可信,由本服务覆盖成真实来源。
|
|
317
|
+
"data": {"username": "u", "password": "p", "app_name": "auth", "client_ip": "9.9.9.9"},
|
|
315
318
|
},
|
|
316
319
|
)
|
|
317
320
|
|
|
@@ -322,6 +325,7 @@ async def test_front_login_forwards_server_app_name():
|
|
|
322
325
|
"username": "u",
|
|
323
326
|
"password": "p",
|
|
324
327
|
"app_name": "demo",
|
|
328
|
+
"client_ip": "10.1.2.3",
|
|
325
329
|
},
|
|
326
330
|
)
|
|
327
331
|
]
|
|
@@ -1166,3 +1170,49 @@ async def test_front_reply_to_closed_connection_is_swallowed():
|
|
|
1166
1170
|
raise RuntimeError("Cannot call send once a close message has been sent")
|
|
1167
1171
|
|
|
1168
1172
|
await server._handle_front_msg(ClosedWs(), {"id": "1", "event": "ping", "data": {}})
|
|
1173
|
+
|
|
1174
|
+
|
|
1175
|
+
@pytest.mark.asyncio
|
|
1176
|
+
async def test_auth_client_keeps_auth_public_url_for_browsers():
|
|
1177
|
+
client = _client()
|
|
1178
|
+
client._apply_auth_public_url({"app_id": "a1"}) # 旧版 Auth 不带:保持空
|
|
1179
|
+
assert client.auth_public_url == ""
|
|
1180
|
+
client._apply_auth_public_url({"auth_public_url": " https://auth.example.com/ "})
|
|
1181
|
+
assert client.auth_public_url == "https://auth.example.com"
|
|
1182
|
+
client._mark_disconnected()
|
|
1183
|
+
assert client.auth_public_url == "https://auth.example.com" # 断线保留最后的值
|
|
1184
|
+
client._apply_auth_public_url({"auth_public_url": "http://auth.example.com:8100"})
|
|
1185
|
+
assert client.auth_public_url == "http://auth.example.com:8100"
|
|
1186
|
+
# 格式不对(带路径、非 http(s)、不是字符串)按没配置处理,不影响注册。
|
|
1187
|
+
for bad in ("https://auth.example.com/login", "javascript:alert(1)", "auth.example.com", 1):
|
|
1188
|
+
client._apply_auth_public_url({"auth_public_url": bad})
|
|
1189
|
+
assert client.auth_public_url == ""
|
|
1190
|
+
client._apply_auth_public_url({"auth_public_url": ""}) # Auth 没配置
|
|
1191
|
+
assert client.auth_public_url == ""
|
|
1192
|
+
|
|
1193
|
+
|
|
1194
|
+
@pytest.mark.asyncio
|
|
1195
|
+
async def test_app_server_exposes_auth_public_url():
|
|
1196
|
+
server = AppServer(_settings(), app_version="0.1.0", store=MemoryStore())
|
|
1197
|
+
assert server.auth_public_url == ""
|
|
1198
|
+
server.auth = _client()
|
|
1199
|
+
server.auth.auth_public_url = "https://auth.example.com"
|
|
1200
|
+
assert server.auth_public_url == "https://auth.example.com"
|
|
1201
|
+
|
|
1202
|
+
|
|
1203
|
+
@pytest.mark.asyncio
|
|
1204
|
+
async def test_start_keeps_synced_user_app_mirror(monkeypatch):
|
|
1205
|
+
# user_app 自 0.1.89 起可授权下发,启动时不能再把本地副本和游标删掉(否则每次重启都整表重拉、中间是空表)。
|
|
1206
|
+
store = MemoryStore()
|
|
1207
|
+
server = AppServer(_settings(), app_version="0.1.0", store=store)
|
|
1208
|
+
await store.open()
|
|
1209
|
+
store.tables["_auth_user_app"] = {"ua1": {"_id": "ua1", "user_id": "u1", "app_id": "a1"}}
|
|
1210
|
+
store.cursors["_auth_user_app"] = 7
|
|
1211
|
+
|
|
1212
|
+
async def no_connect(self) -> None:
|
|
1213
|
+
return None
|
|
1214
|
+
|
|
1215
|
+
monkeypatch.setattr(AuthClient, "start", no_connect)
|
|
1216
|
+
await server.start()
|
|
1217
|
+
assert await store.get("_auth_user_app", "ua1") is not None
|
|
1218
|
+
assert store.cursors["_auth_user_app"] == 7
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
# -*- coding: utf-8 -*-
|
|
2
|
-
"""
|
|
2
|
+
"""进程日志:按天落盘 app/logs/app-YYYY-MM-DD.log,接管 uvicorn 访问日志。"""
|
|
3
3
|
|
|
4
4
|
from __future__ import annotations
|
|
5
5
|
|
|
6
6
|
import logging
|
|
7
7
|
import re
|
|
8
|
+
from datetime import date
|
|
8
9
|
|
|
9
10
|
import pytest
|
|
10
11
|
from loguru import logger
|
|
@@ -14,6 +15,10 @@ from ys_base.server import logging as logmod
|
|
|
14
15
|
TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}")
|
|
15
16
|
|
|
16
17
|
|
|
18
|
+
def _today_log(root):
|
|
19
|
+
return root / "app" / "logs" / f"app-{date.today():%Y-%m-%d}.log"
|
|
20
|
+
|
|
21
|
+
|
|
17
22
|
@pytest.fixture
|
|
18
23
|
def logging_cwd(tmp_path, monkeypatch):
|
|
19
24
|
monkeypatch.chdir(tmp_path)
|
|
@@ -30,7 +35,7 @@ def test_configure_logging_writes_timestamped_file(logging_cwd):
|
|
|
30
35
|
logger.info("hello-file-log")
|
|
31
36
|
logger.complete()
|
|
32
37
|
|
|
33
|
-
text = (logging_cwd
|
|
38
|
+
text = _today_log(logging_cwd).read_text(encoding="utf-8")
|
|
34
39
|
assert "hello-file-log" in text
|
|
35
40
|
assert TIMESTAMP.search(text)
|
|
36
41
|
assert " | INFO |" in text
|
|
@@ -43,7 +48,7 @@ def test_uvicorn_access_lines_get_the_same_timestamp(logging_cwd):
|
|
|
43
48
|
logging.getLogger("uvicorn.error").info("connection open")
|
|
44
49
|
logger.complete()
|
|
45
50
|
|
|
46
|
-
text = (logging_cwd
|
|
51
|
+
text = _today_log(logging_cwd).read_text(encoding="utf-8")
|
|
47
52
|
assert 'GET / HTTP/1.1" 200 OK' in text
|
|
48
53
|
assert "connection open" in text
|
|
49
54
|
assert TIMESTAMP.search(text)
|
|
@@ -55,5 +60,15 @@ def test_configure_logging_is_idempotent(logging_cwd):
|
|
|
55
60
|
logmod.configure_logging()
|
|
56
61
|
logger.info("once")
|
|
57
62
|
logger.complete()
|
|
58
|
-
text = (logging_cwd
|
|
63
|
+
text = _today_log(logging_cwd).read_text(encoding="utf-8")
|
|
59
64
|
assert text.count("once") == 1
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_log_file_is_split_by_day(logging_cwd):
|
|
68
|
+
# 只按大小切时,量少的系统几个月都写在一个文件里;现在每天零点换新文件,旧文件保留 30 天。
|
|
69
|
+
logmod.configure_logging()
|
|
70
|
+
logger.info("daily")
|
|
71
|
+
logger.complete()
|
|
72
|
+
files = sorted(path.name for path in (logging_cwd / "app" / "logs").glob("app-*.log"))
|
|
73
|
+
assert files == [f"app-{date.today():%Y-%m-%d}.log"]
|
|
74
|
+
assert not (logging_cwd / "app" / "logs" / "app.log").exists()
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""MongoStore 索引升级行为测试。"""
|
|
3
|
+
|
|
4
|
+
import importlib.util
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from pymongo import AsyncMongoClient
|
|
8
|
+
from pymongo.errors import OperationFailure
|
|
9
|
+
|
|
10
|
+
from ys_base.store.mongo import MongoStore, _check_table
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FakeCollection:
|
|
14
|
+
def __init__(self, indexes: dict, error_code: int = 86):
|
|
15
|
+
self.indexes = indexes
|
|
16
|
+
self.error_code = error_code
|
|
17
|
+
|
|
18
|
+
async def create_index(self, keys, *, unique=False):
|
|
19
|
+
raise OperationFailure("index conflict", self.error_code)
|
|
20
|
+
|
|
21
|
+
async def index_information(self):
|
|
22
|
+
return self.indexes
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class FakeDatabase:
|
|
26
|
+
def __init__(self, collection: FakeCollection):
|
|
27
|
+
self.collection = collection
|
|
28
|
+
self.commands: list[dict] = []
|
|
29
|
+
|
|
30
|
+
def __getitem__(self, table: str):
|
|
31
|
+
return self.collection
|
|
32
|
+
|
|
33
|
+
async def command(self, command: dict):
|
|
34
|
+
self.commands.append(command)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def make_store(collection: FakeCollection) -> tuple[MongoStore, FakeDatabase]:
|
|
38
|
+
store = MongoStore.__new__(MongoStore)
|
|
39
|
+
database = FakeDatabase(collection)
|
|
40
|
+
store.db = database
|
|
41
|
+
return store, database
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_mongo_store_uses_pymongo_async_without_motor():
|
|
45
|
+
store = MongoStore("mongodb://localhost:27017/Demo")
|
|
46
|
+
try:
|
|
47
|
+
assert isinstance(store.client, AsyncMongoClient)
|
|
48
|
+
assert store.db.name == "Demo"
|
|
49
|
+
assert importlib.util.find_spec("motor") is None
|
|
50
|
+
finally:
|
|
51
|
+
import asyncio
|
|
52
|
+
|
|
53
|
+
asyncio.run(store.close())
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def test_create_index_upgrades_matching_index_to_unique():
|
|
57
|
+
store, database = make_store(
|
|
58
|
+
FakeCollection(
|
|
59
|
+
{
|
|
60
|
+
"username_1": {"key": [("username", 1)]},
|
|
61
|
+
}
|
|
62
|
+
)
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
await store.create_index("_local_users", "username", unique=True)
|
|
66
|
+
|
|
67
|
+
assert database.commands == [
|
|
68
|
+
{
|
|
69
|
+
"collMod": "_local_users",
|
|
70
|
+
"index": {"name": "username_1", "prepareUnique": True},
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"collMod": "_local_users",
|
|
74
|
+
"index": {"name": "username_1", "unique": True},
|
|
75
|
+
},
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
async def test_create_index_accepts_matching_unique_index():
|
|
80
|
+
store, database = make_store(
|
|
81
|
+
FakeCollection(
|
|
82
|
+
{
|
|
83
|
+
"username_1": {
|
|
84
|
+
"key": [("username", 1)],
|
|
85
|
+
"unique": True,
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
)
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
await store.create_index("_local_users", "username", unique=True)
|
|
92
|
+
|
|
93
|
+
assert database.commands == []
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
async def test_create_index_preserves_unrelated_conflict():
|
|
97
|
+
store, _ = make_store(
|
|
98
|
+
FakeCollection(
|
|
99
|
+
{
|
|
100
|
+
"other_1": {"key": [("other", 1)]},
|
|
101
|
+
}
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
with pytest.raises(OperationFailure, match="index conflict"):
|
|
106
|
+
await store.create_index("_local_users", "username", unique=True)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def test_open_does_not_rename_collections():
|
|
110
|
+
class OpenDatabase(FakeDatabase):
|
|
111
|
+
def __init__(self):
|
|
112
|
+
super().__init__(FakeCollection({}))
|
|
113
|
+
self.indexed: list[str] = []
|
|
114
|
+
self.names = ["auth_users", "users", "_auth_sync_state"]
|
|
115
|
+
|
|
116
|
+
async def list_collection_names(self):
|
|
117
|
+
return list(self.names)
|
|
118
|
+
|
|
119
|
+
def __getitem__(self, table: str):
|
|
120
|
+
database = self
|
|
121
|
+
|
|
122
|
+
class IndexCollection:
|
|
123
|
+
async def create_index(self, keys, *, unique=False):
|
|
124
|
+
database.indexed.append(table)
|
|
125
|
+
|
|
126
|
+
return IndexCollection()
|
|
127
|
+
|
|
128
|
+
store = MongoStore.__new__(MongoStore)
|
|
129
|
+
store.db = OpenDatabase()
|
|
130
|
+
|
|
131
|
+
async def ping() -> None:
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
store.ping = ping
|
|
135
|
+
await store.open()
|
|
136
|
+
|
|
137
|
+
assert store.db.names == ["auth_users", "users", "_auth_sync_state"]
|
|
138
|
+
assert store.db.indexed == ["_auth_sync_state"]
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
async def test_table_name_allows_only_controlled_prefixed_collections():
|
|
142
|
+
for table in ("_auth_users", "_local_users", "orders"):
|
|
143
|
+
assert _check_table(table) == table
|
|
144
|
+
for table in ("auth_users", "auth_sync_state", "users", "user_roles"):
|
|
145
|
+
with pytest.raises(ValueError, match="非法表名"):
|
|
146
|
+
_check_table(table)
|
|
147
|
+
with pytest.raises(ValueError, match="非法表名"):
|
|
148
|
+
_check_table("_other_users")
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""注册时上报的运行环境:自家包版本、前端自家包版本,不带路径和配置。"""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
from ys_base import __version__
|
|
7
|
+
from ys_base.server.runtime_info import runtime_info
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_runtime_info_reports_own_packages_only(tmp_path):
|
|
11
|
+
web = tmp_path / "web"
|
|
12
|
+
(web / "dist").mkdir(parents=True)
|
|
13
|
+
(web / "package.json").write_text(
|
|
14
|
+
json.dumps({"dependencies": {"@ysgroup/ui": "0.1.46", "@ysgroup/core": "0.1.27", "vue": "3.5.0"}}),
|
|
15
|
+
encoding="utf-8",
|
|
16
|
+
)
|
|
17
|
+
info = runtime_info(web / "dist", started_at=1.0)
|
|
18
|
+
assert info["packages"]["ys-base"] == __version__
|
|
19
|
+
assert info["web_packages"] == {"@ysgroup/core": "0.1.27", "@ysgroup/ui": "0.1.46"}
|
|
20
|
+
assert info["started_at"] == 1.0 and info["python"] and info["hostname"]
|
|
21
|
+
assert str(tmp_path) not in json.dumps(info)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_runtime_info_without_package_json(tmp_path):
|
|
25
|
+
assert runtime_info(tmp_path / "web" / "dist")["web_packages"] == {}
|
|
@@ -22,6 +22,9 @@ from ys_base.auth.delta import DeltaSync
|
|
|
22
22
|
from ys_base.contracts import AUTHORIZATION_TABLES, EffectiveTablePolicy
|
|
23
23
|
from ys_base.ws.rpc_client import WsRpcClient, YsRejected
|
|
24
24
|
|
|
25
|
+
# 浏览器地址只接受 http(s)://主机[:端口],不带路径、参数和账号。
|
|
26
|
+
_PUBLIC_URL_RE = re.compile(r"https?://[A-Za-z0-9.-]+(?::\d{1,5})?")
|
|
27
|
+
|
|
25
28
|
RevokedCallback = Callable[[str, str, int | None], Awaitable[None]]
|
|
26
29
|
StatusCallback = Callable[[str], Awaitable[None]] # (app_status)
|
|
27
30
|
TablesConfiguredCallback = Callable[[list[str]], Awaitable[None]]
|
|
@@ -60,6 +63,7 @@ class AuthClient(WsRpcClient):
|
|
|
60
63
|
app_version: str = "",
|
|
61
64
|
instance_id: str = "",
|
|
62
65
|
pending_page: str = "",
|
|
66
|
+
runtime: dict[str, Any] | None = None,
|
|
63
67
|
**kwargs: Any,
|
|
64
68
|
):
|
|
65
69
|
super().__init__(uri, **kwargs)
|
|
@@ -68,6 +72,8 @@ class AuthClient(WsRpcClient):
|
|
|
68
72
|
self.app_version = app_version
|
|
69
73
|
# 待处理落地页,注册时上报;空串表示用系统消息页。
|
|
70
74
|
self.pending_page = normalize_pending_page(pending_page)
|
|
75
|
+
# 运行环境(Python、自家包版本、主机名等),注册时上报给 Auth 的应用运行状态面板。
|
|
76
|
+
self.runtime = dict(runtime or {})
|
|
71
77
|
self.instance_id = instance_id.strip() or uuid.uuid4().hex
|
|
72
78
|
if len(self.instance_id) > 200:
|
|
73
79
|
raise ValueError("AuthClient instance_id 不能超过 200 个字符")
|
|
@@ -81,6 +87,8 @@ class AuthClient(WsRpcClient):
|
|
|
81
87
|
self.server_contracts_version: str = ""
|
|
82
88
|
# Auth 应用管理里的「应用别名」,子系统对外显示的系统名称;注册成功和 Root 修改时更新,断线保留最后的值。
|
|
83
89
|
self.app_cname: str = ""
|
|
90
|
+
# Auth 对浏览器公开的地址(注册成功时下发);Auth 没配置时为空串,断线保留最后的值。
|
|
91
|
+
self.auth_public_url: str = ""
|
|
84
92
|
self._app_profile_callbacks: list[AppProfileCallback] = []
|
|
85
93
|
self._business_peers_callbacks: list[Callable[[], Awaitable[None]]] = []
|
|
86
94
|
self._revoked_callbacks: list[RevokedCallback] = []
|
|
@@ -165,6 +173,17 @@ class AuthClient(WsRpcClient):
|
|
|
165
173
|
except Exception:
|
|
166
174
|
logger.exception("app_profile 回调异常")
|
|
167
175
|
|
|
176
|
+
def _apply_auth_public_url(self, data: dict[str, Any]) -> None:
|
|
177
|
+
"""记下 Auth 下发的浏览器地址。格式不对只记日志、按没配置处理,不影响注册。"""
|
|
178
|
+
if "auth_public_url" not in data:
|
|
179
|
+
return
|
|
180
|
+
value = data.get("auth_public_url")
|
|
181
|
+
url = value.strip().rstrip("/") if isinstance(value, str) else ""
|
|
182
|
+
if url and not _PUBLIC_URL_RE.fullmatch(url):
|
|
183
|
+
logger.warning("Auth 下发的 auth_public_url 格式无效,按没配置处理")
|
|
184
|
+
url = ""
|
|
185
|
+
self.auth_public_url = url
|
|
186
|
+
|
|
168
187
|
def on_tables_configured(self, callback: TablesConfiguredCallback) -> None:
|
|
169
188
|
"""注册 Auth 最终表集合到达后的校验回调。"""
|
|
170
189
|
self._tables_configured_callbacks.append(callback)
|
|
@@ -206,6 +225,7 @@ class AuthClient(WsRpcClient):
|
|
|
206
225
|
"app_version": self.app_version,
|
|
207
226
|
"pending_page": self.pending_page,
|
|
208
227
|
"instance_id": self.instance_id,
|
|
228
|
+
"runtime": self.runtime,
|
|
209
229
|
"applied_authorization_version": applied_authorization_version,
|
|
210
230
|
},
|
|
211
231
|
)
|
|
@@ -221,6 +241,7 @@ class AuthClient(WsRpcClient):
|
|
|
221
241
|
self.authorization_version = int(result.get("authorization_version", 0) or 0)
|
|
222
242
|
self.table_policies = table_policies
|
|
223
243
|
await self._apply_app_profile(result)
|
|
244
|
+
self._apply_auth_public_url(result)
|
|
224
245
|
force_resync = result.get(
|
|
225
246
|
"force_resync",
|
|
226
247
|
applied_authorization_version != self.authorization_version,
|
|
@@ -34,6 +34,7 @@ from ys_base.server.http_errors import install_http_error_handlers
|
|
|
34
34
|
from ys_base.server.jwt_verify import JwtVerifier
|
|
35
35
|
from ys_base.server.logging import configure_logging, new_request_id
|
|
36
36
|
from ys_base.server.router import EventRouter
|
|
37
|
+
from ys_base.server.runtime_info import runtime_info
|
|
37
38
|
from ys_base.store import MongoStore
|
|
38
39
|
from ys_base.store.base import LOCAL_USERS_TABLE, LocalStore
|
|
39
40
|
from ys_base.ws.rpc_client import YsRejected
|
|
@@ -186,6 +187,7 @@ class AppServer:
|
|
|
186
187
|
注册时上报给 Auth,由 Auth 拼跳转地址。
|
|
187
188
|
"""
|
|
188
189
|
configure_logging()
|
|
190
|
+
self.started_at = time.time()
|
|
189
191
|
self.settings = settings
|
|
190
192
|
self.app_version = app_version
|
|
191
193
|
self.pending_page = normalize_pending_page(pending_page)
|
|
@@ -289,7 +291,6 @@ class AppServer:
|
|
|
289
291
|
|
|
290
292
|
async def start(self) -> None:
|
|
291
293
|
await self.store.open()
|
|
292
|
-
await self.store.drop_mirror("_auth_user_app")
|
|
293
294
|
self.delta = DeltaSync(self.store, tables=[])
|
|
294
295
|
for table, handlers in self._table_handlers.items():
|
|
295
296
|
for handler, critical in handlers:
|
|
@@ -307,6 +308,7 @@ class AppServer:
|
|
|
307
308
|
delta_sync=self.delta,
|
|
308
309
|
app_version=self.app_version,
|
|
309
310
|
pending_page=self.pending_page,
|
|
311
|
+
runtime=runtime_info(self.settings.web_dir, self.started_at),
|
|
310
312
|
)
|
|
311
313
|
self.auth.on_revoked(self._on_revoked)
|
|
312
314
|
self.auth.on_app_profile(self._broadcast_app_profile)
|
|
@@ -341,6 +343,15 @@ class AppServer:
|
|
|
341
343
|
|
|
342
344
|
self.auth._handle_hello = hooked # type: ignore[method-assign]
|
|
343
345
|
|
|
346
|
+
@property
|
|
347
|
+
def auth_public_url(self) -> str:
|
|
348
|
+
"""Auth 对浏览器公开的地址(如 https://auth.example.com),注册成功时由 Auth 下发;没配置或还没连上时为空串。
|
|
349
|
+
|
|
350
|
+
只用于给浏览器跳转(例如设置中心「前往 Auth 修改密码」)。不要用 settings.auth_uri 代替:那是服务器之间互连的地址,
|
|
351
|
+
通常是内网地址,浏览器在外网打不开。
|
|
352
|
+
"""
|
|
353
|
+
return str(getattr(self.auth, "auth_public_url", "") or "")
|
|
354
|
+
|
|
344
355
|
@property
|
|
345
356
|
def app_cname(self) -> str:
|
|
346
357
|
"""Auth 下发的应用别名(系统名称);Auth 还没连上时为空串,前端用缓存或应用标识兜底。"""
|
|
@@ -539,6 +550,10 @@ class AppServer:
|
|
|
539
550
|
return
|
|
540
551
|
try:
|
|
541
552
|
forwarded = data | {"app_name": self.settings.app_name} if event == "login" else data
|
|
553
|
+
if event in ("login", "exchange_sso_code"):
|
|
554
|
+
# 浏览器的地址由本服务填写(覆盖浏览器自带的同名字段),Auth 用它记登录来源、按来源限频。
|
|
555
|
+
client = getattr(ws, "client", None)
|
|
556
|
+
forwarded = forwarded | {"client_ip": str(getattr(client, "host", "") or "")}
|
|
542
557
|
result = await self.auth.call(event, forwarded)
|
|
543
558
|
if event in ("login", "exchange_sso_code", "refresh") and isinstance(result, dict):
|
|
544
559
|
login_user = result.get("user", {}) or {}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
# -*- coding: utf-8 -*-
|
|
2
|
-
"""loguru 进程级配置:stderr + app/logs
|
|
2
|
+
"""loguru 进程级配置:stderr + app/logs 按天落盘,接管标准库/uvicorn。"""
|
|
3
3
|
|
|
4
4
|
from __future__ import annotations
|
|
5
5
|
|
|
@@ -13,7 +13,9 @@ from loguru import logger
|
|
|
13
13
|
_CONFIGURED = False
|
|
14
14
|
|
|
15
15
|
LOG_DIR = Path("app") / "logs"
|
|
16
|
-
|
|
16
|
+
# 每天一个文件 app-YYYY-MM-DD.log,零点(容器时区,部署镜像为上海)切换;只保留最近 LOG_RETENTION 天。
|
|
17
|
+
LOG_FILE = LOG_DIR / "app-{time:YYYY-MM-DD}.log"
|
|
18
|
+
LOG_RETENTION = "30 days"
|
|
17
19
|
|
|
18
20
|
LOG_FORMAT = (
|
|
19
21
|
"{time:YYYY-MM-DD HH:mm:ss.SSS} | {level:<8} | {name}:{function}:{line} | "
|
|
@@ -53,7 +55,7 @@ def _intercept_stdlib() -> None:
|
|
|
53
55
|
def configure_logging() -> None:
|
|
54
56
|
"""每个进程只配置一次:enqueue 异步写、关闭 diagnose/backtrace。
|
|
55
57
|
|
|
56
|
-
同时写入标准错误与工作目录相对路径 ``app/logs/app.log
|
|
58
|
+
同时写入标准错误与工作目录相对路径 ``app/logs/app-YYYY-MM-DD.log``(每天零点切新文件)。
|
|
57
59
|
只读容器写文件失败时仍保留 stderr,不阻止启动。
|
|
58
60
|
"""
|
|
59
61
|
global _CONFIGURED
|
|
@@ -78,11 +80,11 @@ def configure_logging() -> None:
|
|
|
78
80
|
diagnose=False,
|
|
79
81
|
backtrace=False,
|
|
80
82
|
colorize=False,
|
|
81
|
-
rotation="
|
|
82
|
-
retention=
|
|
83
|
+
rotation="00:00",
|
|
84
|
+
retention=LOG_RETENTION,
|
|
83
85
|
encoding="utf-8",
|
|
84
86
|
)
|
|
85
|
-
logger.info("
|
|
87
|
+
logger.info("日志按天写入 {} 与标准错误", LOG_DIR.resolve())
|
|
86
88
|
except OSError:
|
|
87
89
|
logger.warning("无法写入 {},仅保留标准错误输出", LOG_FILE)
|
|
88
90
|
_intercept_stdlib()
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""注册时上报给 Auth 的运行环境:Python、自家包版本、前端自家包版本、主机名、进程启动时间。
|
|
3
|
+
|
|
4
|
+
只报版本号和主机名,不报路径、环境变量、配置或依赖全集。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import importlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import platform
|
|
13
|
+
import socket
|
|
14
|
+
import time
|
|
15
|
+
from importlib import metadata
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
# 自家 Python 包:装了哪个报哪个(模块名 → 包名),版本取模块的 __version__,与发布号一致。
|
|
20
|
+
PYTHON_PACKAGES = {"ys_base": "ys-base", "ys_trade_sdk": "ys-trade-sdk"}
|
|
21
|
+
# 自家前端包:从 web/package.json 读精确锁定的版本(镜像里要带上这个文件)。
|
|
22
|
+
WEB_SCOPE = "@ysgroup/"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _python_packages() -> dict[str, str]:
|
|
26
|
+
found: dict[str, str] = {}
|
|
27
|
+
for module, name in PYTHON_PACKAGES.items():
|
|
28
|
+
try:
|
|
29
|
+
version = getattr(importlib.import_module(module), "__version__", "") or metadata.version(name)
|
|
30
|
+
except (ImportError, metadata.PackageNotFoundError):
|
|
31
|
+
continue
|
|
32
|
+
found[name] = str(version)
|
|
33
|
+
return found
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _web_packages(web_dir: str | Path) -> dict[str, str]:
|
|
37
|
+
manifest = Path(web_dir).parent / "package.json"
|
|
38
|
+
try:
|
|
39
|
+
data = json.loads(manifest.read_text(encoding="utf-8"))
|
|
40
|
+
except (OSError, ValueError):
|
|
41
|
+
return {}
|
|
42
|
+
found: dict[str, str] = {}
|
|
43
|
+
for section in ("dependencies", "devDependencies"):
|
|
44
|
+
deps = data.get(section) if isinstance(data, dict) else None
|
|
45
|
+
if not isinstance(deps, dict):
|
|
46
|
+
continue
|
|
47
|
+
for name, version in deps.items():
|
|
48
|
+
if isinstance(name, str) and name.startswith(WEB_SCOPE) and isinstance(version, str):
|
|
49
|
+
found[name] = version.strip()
|
|
50
|
+
return dict(sorted(found.items()))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def runtime_info(web_dir: str | Path, started_at: float | None = None) -> dict[str, Any]:
|
|
54
|
+
return {
|
|
55
|
+
"python": platform.python_version(),
|
|
56
|
+
"packages": _python_packages(),
|
|
57
|
+
"web_packages": _web_packages(web_dir),
|
|
58
|
+
"hostname": socket.gethostname(),
|
|
59
|
+
"pid": os.getpid(),
|
|
60
|
+
"started_at": started_at if started_at is not None else time.time(),
|
|
61
|
+
}
|
|
@@ -12,17 +12,11 @@ from ys_base.store.base import (
|
|
|
12
12
|
AUTH_MIRROR_PREFIX,
|
|
13
13
|
AUTH_SYNC_STATE_TABLE,
|
|
14
14
|
AUTHORIZATION_VERSION_STATE_ID,
|
|
15
|
-
LOCAL_USER_ROLES_TABLE,
|
|
16
|
-
LOCAL_USERS_TABLE,
|
|
17
15
|
LocalStore,
|
|
18
16
|
)
|
|
19
17
|
|
|
20
18
|
_TABLE_RE = re.compile(r"^(?:[a-z][a-z0-9_]*|_(?:auth|local)_[a-z][a-z0-9_]*)$")
|
|
21
|
-
|
|
22
|
-
"users": LOCAL_USERS_TABLE,
|
|
23
|
-
"user_roles": LOCAL_USER_ROLES_TABLE,
|
|
24
|
-
}
|
|
25
|
-
_LEGACY_SYNC_STATE_TABLE = "auth_sync_state"
|
|
19
|
+
# 旧集合名不再改名。库里若还是这些名字,当非法表名拒绝,避免写进已经废弃的集合。
|
|
26
20
|
_LEGACY_TABLE_RE = re.compile(r"^(?:auth_[a-z][a-z0-9_]*|auth_sync_state|users|user_roles)$")
|
|
27
21
|
|
|
28
22
|
|
|
@@ -48,61 +42,8 @@ class MongoStore(LocalStore):
|
|
|
48
42
|
|
|
49
43
|
async def open(self) -> None:
|
|
50
44
|
await self.ping()
|
|
51
|
-
await self._migrate_collection_names()
|
|
52
45
|
await self.db[AUTH_SYNC_STATE_TABLE].create_index("updated_at")
|
|
53
46
|
|
|
54
|
-
async def _migrate_collection_names(self) -> None:
|
|
55
|
-
collections = set(await self.db.list_collection_names())
|
|
56
|
-
renames = {table: f"_{table}" for table in collections if table.startswith("auth_")}
|
|
57
|
-
if _LEGACY_SYNC_STATE_TABLE in collections:
|
|
58
|
-
renames[_LEGACY_SYNC_STATE_TABLE] = AUTH_SYNC_STATE_TABLE
|
|
59
|
-
renames.update({old: new for old, new in _LEGACY_LOCAL_TABLES.items() if old in collections})
|
|
60
|
-
for old, new in sorted(renames.items()):
|
|
61
|
-
if new in collections:
|
|
62
|
-
raise RuntimeError(f"Mongo 集合迁移冲突: {old} 与 {new} 同时存在")
|
|
63
|
-
|
|
64
|
-
legacy_state_ids = set()
|
|
65
|
-
canonical_state_ids = set()
|
|
66
|
-
for state_table in (_LEGACY_SYNC_STATE_TABLE, AUTH_SYNC_STATE_TABLE):
|
|
67
|
-
if state_table not in collections:
|
|
68
|
-
continue
|
|
69
|
-
for item in await self.db[state_table].find({}, {"_id": 1}).to_list(length=None):
|
|
70
|
-
state_id = str(item.get("_id", ""))
|
|
71
|
-
if state_id.startswith("auth_"):
|
|
72
|
-
legacy_state_ids.add(state_id)
|
|
73
|
-
elif state_id.startswith("_auth_"):
|
|
74
|
-
canonical_state_ids.add(state_id)
|
|
75
|
-
if {f"_{state_id}" for state_id in legacy_state_ids} & canonical_state_ids:
|
|
76
|
-
raise RuntimeError("Auth 同步状态迁移冲突: 旧状态键与新状态键同时存在")
|
|
77
|
-
|
|
78
|
-
completed_renames: list[tuple[str, str]] = []
|
|
79
|
-
completed_state_changes: list[tuple[str, str, dict[str, Any]]] = []
|
|
80
|
-
try:
|
|
81
|
-
for old, new in sorted(renames.items()):
|
|
82
|
-
await self.db[old].rename(new)
|
|
83
|
-
completed_renames.append((old, new))
|
|
84
|
-
collections.remove(old)
|
|
85
|
-
collections.add(new)
|
|
86
|
-
|
|
87
|
-
states = await self.db[AUTH_SYNC_STATE_TABLE].find({"_id": {"$regex": r"^auth_"}}).to_list(length=None)
|
|
88
|
-
for state in states:
|
|
89
|
-
old_id = str(state["_id"])
|
|
90
|
-
new_id = f"_{old_id}"
|
|
91
|
-
await self.db[AUTH_SYNC_STATE_TABLE].insert_one({**state, "_id": new_id})
|
|
92
|
-
try:
|
|
93
|
-
await self.db[AUTH_SYNC_STATE_TABLE].delete_one({"_id": old_id})
|
|
94
|
-
except Exception:
|
|
95
|
-
await self.db[AUTH_SYNC_STATE_TABLE].delete_one({"_id": new_id})
|
|
96
|
-
raise
|
|
97
|
-
completed_state_changes.append((old_id, new_id, dict(state)))
|
|
98
|
-
except Exception:
|
|
99
|
-
for old_id, new_id, state in reversed(completed_state_changes):
|
|
100
|
-
await self.db[AUTH_SYNC_STATE_TABLE].delete_one({"_id": new_id})
|
|
101
|
-
await self.db[AUTH_SYNC_STATE_TABLE].insert_one(state)
|
|
102
|
-
for old, new in reversed(completed_renames):
|
|
103
|
-
await self.db[new].rename(old)
|
|
104
|
-
raise
|
|
105
|
-
|
|
106
47
|
async def close(self) -> None:
|
|
107
48
|
await self.client.close()
|
|
108
49
|
|
|
@@ -1,222 +0,0 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""MongoStore 索引升级行为测试。"""
|
|
3
|
-
|
|
4
|
-
import importlib.util
|
|
5
|
-
|
|
6
|
-
import pytest
|
|
7
|
-
from pymongo import AsyncMongoClient
|
|
8
|
-
from pymongo.errors import OperationFailure
|
|
9
|
-
|
|
10
|
-
from ys_base.store.mongo import MongoStore, _check_table
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
class FakeCollection:
|
|
14
|
-
def __init__(self, indexes: dict, error_code: int = 86):
|
|
15
|
-
self.indexes = indexes
|
|
16
|
-
self.error_code = error_code
|
|
17
|
-
|
|
18
|
-
async def create_index(self, keys, *, unique=False):
|
|
19
|
-
raise OperationFailure("index conflict", self.error_code)
|
|
20
|
-
|
|
21
|
-
async def index_information(self):
|
|
22
|
-
return self.indexes
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
class FakeDatabase:
|
|
26
|
-
def __init__(self, collection: FakeCollection):
|
|
27
|
-
self.collection = collection
|
|
28
|
-
self.commands: list[dict] = []
|
|
29
|
-
|
|
30
|
-
def __getitem__(self, table: str):
|
|
31
|
-
return self.collection
|
|
32
|
-
|
|
33
|
-
async def command(self, command: dict):
|
|
34
|
-
self.commands.append(command)
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
class MigrationCursor:
|
|
38
|
-
def __init__(self, documents):
|
|
39
|
-
self.documents = documents
|
|
40
|
-
|
|
41
|
-
async def to_list(self, length=None):
|
|
42
|
-
return [dict(document) for document in self.documents]
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
class MigrationCollection:
|
|
46
|
-
def __init__(self, database, name):
|
|
47
|
-
self.database = database
|
|
48
|
-
self.name = name
|
|
49
|
-
|
|
50
|
-
def find(self, query=None, projection=None):
|
|
51
|
-
documents = list(self.database.documents.get(self.name, {}).values())
|
|
52
|
-
if query and "$regex" in query.get("_id", {}):
|
|
53
|
-
prefix = query["_id"]["$regex"].removeprefix("^")
|
|
54
|
-
documents = [document for document in documents if str(document.get("_id", "")).startswith(prefix)]
|
|
55
|
-
if projection:
|
|
56
|
-
documents = [{key: document[key] for key in projection if key in document} for document in documents]
|
|
57
|
-
return MigrationCursor(documents)
|
|
58
|
-
|
|
59
|
-
async def find_one(self, query):
|
|
60
|
-
return self.database.documents.get(self.name, {}).get(query.get("_id"))
|
|
61
|
-
|
|
62
|
-
async def insert_one(self, document):
|
|
63
|
-
self.database.documents.setdefault(self.name, {})[document["_id"]] = dict(document)
|
|
64
|
-
|
|
65
|
-
async def delete_one(self, query):
|
|
66
|
-
if self.database.fail_state_delete and self.name == "_auth_sync_state":
|
|
67
|
-
self.database.fail_state_delete = False
|
|
68
|
-
raise RuntimeError("state delete failed")
|
|
69
|
-
self.database.documents.setdefault(self.name, {}).pop(query.get("_id"), None)
|
|
70
|
-
|
|
71
|
-
async def rename(self, name):
|
|
72
|
-
self.database.documents[name] = self.database.documents.pop(self.name, {})
|
|
73
|
-
self.database.collections.remove(self.name)
|
|
74
|
-
self.database.collections.add(name)
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
class MigrationDatabase:
|
|
78
|
-
def __init__(self, documents):
|
|
79
|
-
self.documents = documents
|
|
80
|
-
self.collections = set(documents)
|
|
81
|
-
self.fail_state_delete = False
|
|
82
|
-
|
|
83
|
-
async def list_collection_names(self):
|
|
84
|
-
return sorted(self.collections)
|
|
85
|
-
|
|
86
|
-
def __getitem__(self, name):
|
|
87
|
-
return MigrationCollection(self, name)
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
def make_store(collection: FakeCollection) -> tuple[MongoStore, FakeDatabase]:
|
|
91
|
-
store = MongoStore.__new__(MongoStore)
|
|
92
|
-
database = FakeDatabase(collection)
|
|
93
|
-
store.db = database
|
|
94
|
-
return store, database
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
def test_mongo_store_uses_pymongo_async_without_motor():
|
|
98
|
-
store = MongoStore("mongodb://localhost:27017/Demo")
|
|
99
|
-
try:
|
|
100
|
-
assert isinstance(store.client, AsyncMongoClient)
|
|
101
|
-
assert store.db.name == "Demo"
|
|
102
|
-
assert importlib.util.find_spec("motor") is None
|
|
103
|
-
finally:
|
|
104
|
-
import asyncio
|
|
105
|
-
|
|
106
|
-
asyncio.run(store.close())
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
async def test_create_index_upgrades_matching_index_to_unique():
|
|
110
|
-
store, database = make_store(
|
|
111
|
-
FakeCollection(
|
|
112
|
-
{
|
|
113
|
-
"username_1": {"key": [("username", 1)]},
|
|
114
|
-
}
|
|
115
|
-
)
|
|
116
|
-
)
|
|
117
|
-
|
|
118
|
-
await store.create_index("_local_users", "username", unique=True)
|
|
119
|
-
|
|
120
|
-
assert database.commands == [
|
|
121
|
-
{
|
|
122
|
-
"collMod": "_local_users",
|
|
123
|
-
"index": {"name": "username_1", "prepareUnique": True},
|
|
124
|
-
},
|
|
125
|
-
{
|
|
126
|
-
"collMod": "_local_users",
|
|
127
|
-
"index": {"name": "username_1", "unique": True},
|
|
128
|
-
},
|
|
129
|
-
]
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
async def test_create_index_accepts_matching_unique_index():
|
|
133
|
-
store, database = make_store(
|
|
134
|
-
FakeCollection(
|
|
135
|
-
{
|
|
136
|
-
"username_1": {
|
|
137
|
-
"key": [("username", 1)],
|
|
138
|
-
"unique": True,
|
|
139
|
-
},
|
|
140
|
-
}
|
|
141
|
-
)
|
|
142
|
-
)
|
|
143
|
-
|
|
144
|
-
await store.create_index("_local_users", "username", unique=True)
|
|
145
|
-
|
|
146
|
-
assert database.commands == []
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
async def test_create_index_preserves_unrelated_conflict():
|
|
150
|
-
store, _ = make_store(
|
|
151
|
-
FakeCollection(
|
|
152
|
-
{
|
|
153
|
-
"other_1": {"key": [("other", 1)]},
|
|
154
|
-
}
|
|
155
|
-
)
|
|
156
|
-
)
|
|
157
|
-
|
|
158
|
-
with pytest.raises(OperationFailure, match="index conflict"):
|
|
159
|
-
await store.create_index("_local_users", "username", unique=True)
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
async def test_collection_name_migration_renames_data_and_state_ids():
|
|
163
|
-
store = MongoStore.__new__(MongoStore)
|
|
164
|
-
store.db = MigrationDatabase(
|
|
165
|
-
{
|
|
166
|
-
"auth_users": {"u1": {"_id": "u1", "username": "alice"}},
|
|
167
|
-
"auth_sync_state": {
|
|
168
|
-
"auth_users": {"_id": "auth_users", "cursor": 12},
|
|
169
|
-
},
|
|
170
|
-
"users": {"u1": {"_id": "u1", "username": "alice"}},
|
|
171
|
-
"user_roles": {"Admin": {"_id": "Admin", "code": "Admin"}},
|
|
172
|
-
}
|
|
173
|
-
)
|
|
174
|
-
|
|
175
|
-
await store._migrate_collection_names()
|
|
176
|
-
|
|
177
|
-
assert store.db.collections == {"_auth_users", "_auth_sync_state", "_local_users", "_local_user_roles"}
|
|
178
|
-
assert store.db.documents["_auth_users"]["u1"]["username"] == "alice"
|
|
179
|
-
assert store.db.documents["_auth_sync_state"] == {"_auth_users": {"_id": "_auth_users", "cursor": 12}}
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
async def test_collection_name_migration_rejects_conflicting_names_before_rename():
|
|
183
|
-
store = MongoStore.__new__(MongoStore)
|
|
184
|
-
store.db = MigrationDatabase(
|
|
185
|
-
{
|
|
186
|
-
"auth_users": {"u1": {"_id": "u1"}},
|
|
187
|
-
"_auth_users": {"u1": {"_id": "u1"}},
|
|
188
|
-
}
|
|
189
|
-
)
|
|
190
|
-
|
|
191
|
-
with pytest.raises(RuntimeError, match="迁移冲突"):
|
|
192
|
-
await store._migrate_collection_names()
|
|
193
|
-
assert store.db.collections == {"auth_users", "_auth_users"}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
async def test_collection_name_migration_restores_state_when_state_key_migration_fails():
|
|
197
|
-
store = MongoStore.__new__(MongoStore)
|
|
198
|
-
store.db = MigrationDatabase(
|
|
199
|
-
{
|
|
200
|
-
"auth_users": {"u1": {"_id": "u1"}},
|
|
201
|
-
"auth_sync_state": {
|
|
202
|
-
"auth_users": {"_id": "auth_users", "cursor": 12},
|
|
203
|
-
},
|
|
204
|
-
}
|
|
205
|
-
)
|
|
206
|
-
store.db.fail_state_delete = True
|
|
207
|
-
|
|
208
|
-
with pytest.raises(RuntimeError, match="state delete failed"):
|
|
209
|
-
await store._migrate_collection_names()
|
|
210
|
-
|
|
211
|
-
assert store.db.collections == {"auth_users", "auth_sync_state"}
|
|
212
|
-
assert store.db.documents["auth_sync_state"] == {"auth_users": {"_id": "auth_users", "cursor": 12}}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
async def test_table_name_allows_only_controlled_prefixed_collections():
|
|
216
|
-
for table in ("_auth_users", "_local_users", "orders"):
|
|
217
|
-
assert _check_table(table) == table
|
|
218
|
-
for table in ("auth_users", "auth_sync_state", "users", "user_roles"):
|
|
219
|
-
with pytest.raises(ValueError, match="非法表名"):
|
|
220
|
-
_check_table(table)
|
|
221
|
-
with pytest.raises(ValueError, match="非法表名"):
|
|
222
|
-
_check_table("_other_users")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|