ys_base 0.2.1__tar.gz → 0.2.2__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.2}/PKG-INFO +2 -2
- {ys_base-0.2.1 → ys_base-0.2.2}/README.md +1 -1
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_app_server.py +46 -0
- ys_base-0.2.2/tests/test_mongo_store.py +148 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/__init__.py +1 -1
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/auth/client.py +17 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/server/app_server.py +9 -1
- {ys_base-0.2.1 → ys_base-0.2.2}/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.2}/.gitignore +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/.python-version +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/pyproject.toml +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/memory_store.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_api_token.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_contracts.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_crypto.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_files.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_files_migrate.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_http_errors.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_iso_reference.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_logging.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_rpc_client.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_search.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/tests/test_store_delta.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/uv.lock +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/_pinyin_data.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/auth/__init__.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/auth/api_token.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/auth/delta.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/contracts/__init__.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/contracts/authorization.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/contracts/base.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/contracts/enums.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/contracts/iso_reference.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/contracts/master.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/contracts/platform.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/contracts/relations.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/crypto.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/files.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/files_migrate.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/py.typed +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/search.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/server/__init__.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/server/errors.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/server/http_errors.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/server/jwt_verify.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/server/logging.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/server/router.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/store/__init__.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/store/base.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/ys_base/ws/__init__.py +0 -0
- {ys_base-0.2.1 → ys_base-0.2.2}/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.2
|
|
4
4
|
Summary: YS 统一 SDK:契约模型 / auth 客户端与差量同步 / 应用服务骨架
|
|
5
5
|
Author-email: ys <popsars@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -469,7 +469,7 @@ uv add "ys_base==$version"
|
|
|
469
469
|
|
|
470
470
|
交易客户端、行情、静态信息和收益数据服务在 `ys_trade_sdk`。每个 `TradeManager` 独占一个 `TradeRuntime`。
|
|
471
471
|
|
|
472
|
-
|
|
472
|
+
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
473
|
|
|
474
474
|
```python
|
|
475
475
|
from ys_trade_sdk import (
|
|
@@ -450,7 +450,7 @@ uv add "ys_base==$version"
|
|
|
450
450
|
|
|
451
451
|
交易客户端、行情、静态信息和收益数据服务在 `ys_trade_sdk`。每个 `TradeManager` 独占一个 `TradeRuntime`。
|
|
452
452
|
|
|
453
|
-
|
|
453
|
+
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
454
|
|
|
455
455
|
```python
|
|
456
456
|
from ys_trade_sdk import (
|
|
@@ -1166,3 +1166,49 @@ async def test_front_reply_to_closed_connection_is_swallowed():
|
|
|
1166
1166
|
raise RuntimeError("Cannot call send once a close message has been sent")
|
|
1167
1167
|
|
|
1168
1168
|
await server._handle_front_msg(ClosedWs(), {"id": "1", "event": "ping", "data": {}})
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
@pytest.mark.asyncio
|
|
1172
|
+
async def test_auth_client_keeps_auth_public_url_for_browsers():
|
|
1173
|
+
client = _client()
|
|
1174
|
+
client._apply_auth_public_url({"app_id": "a1"}) # 旧版 Auth 不带:保持空
|
|
1175
|
+
assert client.auth_public_url == ""
|
|
1176
|
+
client._apply_auth_public_url({"auth_public_url": " https://auth.example.com/ "})
|
|
1177
|
+
assert client.auth_public_url == "https://auth.example.com"
|
|
1178
|
+
client._mark_disconnected()
|
|
1179
|
+
assert client.auth_public_url == "https://auth.example.com" # 断线保留最后的值
|
|
1180
|
+
client._apply_auth_public_url({"auth_public_url": "http://auth.example.com:8100"})
|
|
1181
|
+
assert client.auth_public_url == "http://auth.example.com:8100"
|
|
1182
|
+
# 格式不对(带路径、非 http(s)、不是字符串)按没配置处理,不影响注册。
|
|
1183
|
+
for bad in ("https://auth.example.com/login", "javascript:alert(1)", "auth.example.com", 1):
|
|
1184
|
+
client._apply_auth_public_url({"auth_public_url": bad})
|
|
1185
|
+
assert client.auth_public_url == ""
|
|
1186
|
+
client._apply_auth_public_url({"auth_public_url": ""}) # Auth 没配置
|
|
1187
|
+
assert client.auth_public_url == ""
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
@pytest.mark.asyncio
|
|
1191
|
+
async def test_app_server_exposes_auth_public_url():
|
|
1192
|
+
server = AppServer(_settings(), app_version="0.1.0", store=MemoryStore())
|
|
1193
|
+
assert server.auth_public_url == ""
|
|
1194
|
+
server.auth = _client()
|
|
1195
|
+
server.auth.auth_public_url = "https://auth.example.com"
|
|
1196
|
+
assert server.auth_public_url == "https://auth.example.com"
|
|
1197
|
+
|
|
1198
|
+
|
|
1199
|
+
@pytest.mark.asyncio
|
|
1200
|
+
async def test_start_keeps_synced_user_app_mirror(monkeypatch):
|
|
1201
|
+
# user_app 自 0.1.89 起可授权下发,启动时不能再把本地副本和游标删掉(否则每次重启都整表重拉、中间是空表)。
|
|
1202
|
+
store = MemoryStore()
|
|
1203
|
+
server = AppServer(_settings(), app_version="0.1.0", store=store)
|
|
1204
|
+
await store.open()
|
|
1205
|
+
store.tables["_auth_user_app"] = {"ua1": {"_id": "ua1", "user_id": "u1", "app_id": "a1"}}
|
|
1206
|
+
store.cursors["_auth_user_app"] = 7
|
|
1207
|
+
|
|
1208
|
+
async def no_connect(self) -> None:
|
|
1209
|
+
return None
|
|
1210
|
+
|
|
1211
|
+
monkeypatch.setattr(AuthClient, "start", no_connect)
|
|
1212
|
+
await server.start()
|
|
1213
|
+
assert await store.get("_auth_user_app", "ua1") is not None
|
|
1214
|
+
assert store.cursors["_auth_user_app"] == 7
|
|
@@ -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")
|
|
@@ -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]]
|
|
@@ -81,6 +84,8 @@ class AuthClient(WsRpcClient):
|
|
|
81
84
|
self.server_contracts_version: str = ""
|
|
82
85
|
# Auth 应用管理里的「应用别名」,子系统对外显示的系统名称;注册成功和 Root 修改时更新,断线保留最后的值。
|
|
83
86
|
self.app_cname: str = ""
|
|
87
|
+
# Auth 对浏览器公开的地址(注册成功时下发);Auth 没配置时为空串,断线保留最后的值。
|
|
88
|
+
self.auth_public_url: str = ""
|
|
84
89
|
self._app_profile_callbacks: list[AppProfileCallback] = []
|
|
85
90
|
self._business_peers_callbacks: list[Callable[[], Awaitable[None]]] = []
|
|
86
91
|
self._revoked_callbacks: list[RevokedCallback] = []
|
|
@@ -165,6 +170,17 @@ class AuthClient(WsRpcClient):
|
|
|
165
170
|
except Exception:
|
|
166
171
|
logger.exception("app_profile 回调异常")
|
|
167
172
|
|
|
173
|
+
def _apply_auth_public_url(self, data: dict[str, Any]) -> None:
|
|
174
|
+
"""记下 Auth 下发的浏览器地址。格式不对只记日志、按没配置处理,不影响注册。"""
|
|
175
|
+
if "auth_public_url" not in data:
|
|
176
|
+
return
|
|
177
|
+
value = data.get("auth_public_url")
|
|
178
|
+
url = value.strip().rstrip("/") if isinstance(value, str) else ""
|
|
179
|
+
if url and not _PUBLIC_URL_RE.fullmatch(url):
|
|
180
|
+
logger.warning("Auth 下发的 auth_public_url 格式无效,按没配置处理")
|
|
181
|
+
url = ""
|
|
182
|
+
self.auth_public_url = url
|
|
183
|
+
|
|
168
184
|
def on_tables_configured(self, callback: TablesConfiguredCallback) -> None:
|
|
169
185
|
"""注册 Auth 最终表集合到达后的校验回调。"""
|
|
170
186
|
self._tables_configured_callbacks.append(callback)
|
|
@@ -221,6 +237,7 @@ class AuthClient(WsRpcClient):
|
|
|
221
237
|
self.authorization_version = int(result.get("authorization_version", 0) or 0)
|
|
222
238
|
self.table_policies = table_policies
|
|
223
239
|
await self._apply_app_profile(result)
|
|
240
|
+
self._apply_auth_public_url(result)
|
|
224
241
|
force_resync = result.get(
|
|
225
242
|
"force_resync",
|
|
226
243
|
applied_authorization_version != self.authorization_version,
|
|
@@ -289,7 +289,6 @@ class AppServer:
|
|
|
289
289
|
|
|
290
290
|
async def start(self) -> None:
|
|
291
291
|
await self.store.open()
|
|
292
|
-
await self.store.drop_mirror("_auth_user_app")
|
|
293
292
|
self.delta = DeltaSync(self.store, tables=[])
|
|
294
293
|
for table, handlers in self._table_handlers.items():
|
|
295
294
|
for handler, critical in handlers:
|
|
@@ -341,6 +340,15 @@ class AppServer:
|
|
|
341
340
|
|
|
342
341
|
self.auth._handle_hello = hooked # type: ignore[method-assign]
|
|
343
342
|
|
|
343
|
+
@property
|
|
344
|
+
def auth_public_url(self) -> str:
|
|
345
|
+
"""Auth 对浏览器公开的地址(如 https://auth.example.com),注册成功时由 Auth 下发;没配置或还没连上时为空串。
|
|
346
|
+
|
|
347
|
+
只用于给浏览器跳转(例如设置中心「前往 Auth 修改密码」)。不要用 settings.auth_uri 代替:那是服务器之间互连的地址,
|
|
348
|
+
通常是内网地址,浏览器在外网打不开。
|
|
349
|
+
"""
|
|
350
|
+
return str(getattr(self.auth, "auth_public_url", "") or "")
|
|
351
|
+
|
|
344
352
|
@property
|
|
345
353
|
def app_cname(self) -> str:
|
|
346
354
|
"""Auth 下发的应用别名(系统名称);Auth 还没连上时为空串,前端用缓存或应用标识兜底。"""
|
|
@@ -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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|