ys_base 0.2.2__tar.gz → 0.2.4__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.
Files changed (55) hide show
  1. {ys_base-0.2.2 → ys_base-0.2.4}/.gitignore +3 -0
  2. {ys_base-0.2.2 → ys_base-0.2.4}/PKG-INFO +50 -1
  3. {ys_base-0.2.2 → ys_base-0.2.4}/README.md +49 -0
  4. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_app_server.py +5 -1
  5. ys_base-0.2.4/tests/test_cache.py +305 -0
  6. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_logging.py +19 -4
  7. ys_base-0.2.4/tests/test_runtime_info.py +25 -0
  8. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_search.py +33 -0
  9. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/__init__.py +1 -1
  10. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/auth/client.py +4 -0
  11. ys_base-0.2.4/ys_base/cache.py +382 -0
  12. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/search.py +128 -9
  13. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/server/app_server.py +7 -0
  14. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/server/logging.py +8 -6
  15. ys_base-0.2.4/ys_base/server/runtime_info.py +61 -0
  16. {ys_base-0.2.2 → ys_base-0.2.4}/.python-version +0 -0
  17. {ys_base-0.2.2 → ys_base-0.2.4}/pyproject.toml +0 -0
  18. {ys_base-0.2.2 → ys_base-0.2.4}/tests/memory_store.py +0 -0
  19. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_api_token.py +0 -0
  20. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_contracts.py +0 -0
  21. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_crypto.py +0 -0
  22. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_files.py +0 -0
  23. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_files_migrate.py +0 -0
  24. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_http_errors.py +0 -0
  25. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_iso_reference.py +0 -0
  26. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_mongo_store.py +0 -0
  27. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_rpc_client.py +0 -0
  28. {ys_base-0.2.2 → ys_base-0.2.4}/tests/test_store_delta.py +0 -0
  29. {ys_base-0.2.2 → ys_base-0.2.4}/uv.lock +0 -0
  30. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/_pinyin_data.py +0 -0
  31. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/auth/__init__.py +0 -0
  32. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/auth/api_token.py +0 -0
  33. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/auth/delta.py +0 -0
  34. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/contracts/__init__.py +0 -0
  35. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/contracts/authorization.py +0 -0
  36. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/contracts/base.py +0 -0
  37. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/contracts/enums.py +0 -0
  38. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/contracts/iso_reference.py +0 -0
  39. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/contracts/master.py +0 -0
  40. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/contracts/platform.py +0 -0
  41. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/contracts/relations.py +0 -0
  42. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/crypto.py +0 -0
  43. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/files.py +0 -0
  44. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/files_migrate.py +0 -0
  45. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/py.typed +0 -0
  46. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/server/__init__.py +0 -0
  47. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/server/errors.py +0 -0
  48. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/server/http_errors.py +0 -0
  49. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/server/jwt_verify.py +0 -0
  50. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/server/router.py +0 -0
  51. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/store/__init__.py +0 -0
  52. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/store/base.py +0 -0
  53. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/store/mongo.py +0 -0
  54. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/ws/__init__.py +0 -0
  55. {ys_base-0.2.2 → ys_base-0.2.4}/ys_base/ws/rpc_client.py +0 -0
@@ -22,3 +22,6 @@ ys_base/.pypi_token
22
22
  ys_web/**/dist/
23
23
  smoke_app.log
24
24
  /data/
25
+
26
+ # 生产配置不提交,按 config.example.yaml 复制填写
27
+ /config.yaml
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ys_base
3
- Version: 0.2.2
3
+ Version: 0.2.4
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` 完全相同
@@ -66,6 +72,49 @@ match = ys_matcher(keyword) # 或自己循环:match(text) -> bool
66
72
 
67
73
  `Decimal`、`bson.Decimal128` 按数字处理;`bool` 写成 `true`/`false`,`list`/`tuple` 展开,`None`、空串跳过。
68
74
 
75
+ 模糊匹配(0.2.4 起,默认关闭、按表开启):名称有通行简称的列表(机构、银行、公司)才开,规则与前端
76
+ `ysFilter(..., { fuzzy: true })` 相同——关键词的字按顺序出现在同一列即命中(「建行」→「中国建设银行」),
77
+ 纯字母按拼音首字母;单字、带数字、汉字字母混写、顺序反了、跨度超过关键词长度 4 倍的不做模糊;
78
+ 开了模糊的 `ys_filter` 按原文 > 拼音 > 模糊、字越紧越靠前排序。
79
+
80
+ ```python
81
+ rows = ys_filter(rows, keyword, text_of, fuzzy=True)
82
+ ys_match_detail(text_of(row), "建行", fuzzy=True) # YsMatchDetail(score=1.5, kind="fuzzy")
83
+ ```
84
+
85
+ ## 搜索缓存(0.2.4 起,按需使用)
86
+
87
+ 数据多(几万行以上)、读远多于写、用户会逐字输入关键词的列表(联行号、机构、产品目录)用 `YsSearchCache`,其他列表不加:
88
+
89
+ ```python
90
+ from ys_base.cache import YsSearchCache
91
+
92
+ cnaps_cache = YsSearchCache(text_of=lambda row: row["_search"], name="cnaps")
93
+
94
+
95
+ async def load_scope(scope):
96
+ bank_id, deleted = scope # scope 由调用方定义,可哈希
97
+ rows = (
98
+ await db.cnaps.find({"bank_id": bank_id, "deleted_at": {"$ne": None} if deleted else None})
99
+ .sort("code", 1)
100
+ .to_list(None)
101
+ )
102
+ for row in rows:
103
+ row["_search"] = ys_search_text(row["code"], row["name"], row["address"])
104
+ return rows
105
+
106
+
107
+ result = await cnaps_cache.search((bank_id, False), keyword, load_scope, offset=offset, limit=limit)
108
+ return {"rows": result.rows, "total": result.total} # result.source:hit / narrowed / filtered / loaded
109
+
110
+ cnaps_cache.invalidate() # 导入、编辑、删除之后;只影响一个范围时传 scope
111
+ ```
112
+
113
+ - 底表(一个范围的全部行)只读一次库,按范围个数淘汰(`max_scopes`);关键词结果按 LRU 缓存,按总行数淘汰(`max_rows`,只存行的引用),结果再多也挤不掉底表。
114
+ - 逐字输入时,每个旧词都是新词的前缀(且不开模糊)就只在上一次的结果里再筛;同一关键词同时只算一次;要筛的行数超过 `offload_rows` 放进线程。
115
+ - 只在本进程内:写入后 `invalidate`,`ttl`(默认 600 秒)兜底;多实例部署各自缓存,需要跨进程立即一致的数据不要用。不要原地修改返回的行。
116
+ - 通用进程内缓存用 `YsLruCache`:`maxsize`、`max_weight` + `weigh`、`ttl`,`await cache.get_or_load(key, loader)` 同一 key 并发只加载一次,`invalidate(key)` / `invalidate(where=...)` / `invalidate()`。
117
+
69
118
  ## 文件存储(0.1.99 起,0.1.100 改为内容寻址)
70
119
 
71
120
  业务文件(附件、凭证、材料)存进本系统 Mongo,用 `ys_base.files` 统一处理分块、压缩、加密、上传会话、秒传、断点续传、
@@ -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` 完全相同
@@ -47,6 +53,49 @@ match = ys_matcher(keyword) # 或自己循环:match(text) -> bool
47
53
 
48
54
  `Decimal`、`bson.Decimal128` 按数字处理;`bool` 写成 `true`/`false`,`list`/`tuple` 展开,`None`、空串跳过。
49
55
 
56
+ 模糊匹配(0.2.4 起,默认关闭、按表开启):名称有通行简称的列表(机构、银行、公司)才开,规则与前端
57
+ `ysFilter(..., { fuzzy: true })` 相同——关键词的字按顺序出现在同一列即命中(「建行」→「中国建设银行」),
58
+ 纯字母按拼音首字母;单字、带数字、汉字字母混写、顺序反了、跨度超过关键词长度 4 倍的不做模糊;
59
+ 开了模糊的 `ys_filter` 按原文 > 拼音 > 模糊、字越紧越靠前排序。
60
+
61
+ ```python
62
+ rows = ys_filter(rows, keyword, text_of, fuzzy=True)
63
+ ys_match_detail(text_of(row), "建行", fuzzy=True) # YsMatchDetail(score=1.5, kind="fuzzy")
64
+ ```
65
+
66
+ ## 搜索缓存(0.2.4 起,按需使用)
67
+
68
+ 数据多(几万行以上)、读远多于写、用户会逐字输入关键词的列表(联行号、机构、产品目录)用 `YsSearchCache`,其他列表不加:
69
+
70
+ ```python
71
+ from ys_base.cache import YsSearchCache
72
+
73
+ cnaps_cache = YsSearchCache(text_of=lambda row: row["_search"], name="cnaps")
74
+
75
+
76
+ async def load_scope(scope):
77
+ bank_id, deleted = scope # scope 由调用方定义,可哈希
78
+ rows = (
79
+ await db.cnaps.find({"bank_id": bank_id, "deleted_at": {"$ne": None} if deleted else None})
80
+ .sort("code", 1)
81
+ .to_list(None)
82
+ )
83
+ for row in rows:
84
+ row["_search"] = ys_search_text(row["code"], row["name"], row["address"])
85
+ return rows
86
+
87
+
88
+ result = await cnaps_cache.search((bank_id, False), keyword, load_scope, offset=offset, limit=limit)
89
+ return {"rows": result.rows, "total": result.total} # result.source:hit / narrowed / filtered / loaded
90
+
91
+ cnaps_cache.invalidate() # 导入、编辑、删除之后;只影响一个范围时传 scope
92
+ ```
93
+
94
+ - 底表(一个范围的全部行)只读一次库,按范围个数淘汰(`max_scopes`);关键词结果按 LRU 缓存,按总行数淘汰(`max_rows`,只存行的引用),结果再多也挤不掉底表。
95
+ - 逐字输入时,每个旧词都是新词的前缀(且不开模糊)就只在上一次的结果里再筛;同一关键词同时只算一次;要筛的行数超过 `offload_rows` 放进线程。
96
+ - 只在本进程内:写入后 `invalidate`,`ttl`(默认 600 秒)兜底;多实例部署各自缓存,需要跨进程立即一致的数据不要用。不要原地修改返回的行。
97
+ - 通用进程内缓存用 `YsLruCache`:`maxsize`、`max_weight` + `weigh`、`ttl`,`await cache.get_or_load(key, loader)` 同一 key 并发只加载一次,`invalidate(key)` / `invalidate(where=...)` / `invalidate()`。
98
+
50
99
  ## 文件存储(0.1.99 起,0.1.100 改为内容寻址)
51
100
 
52
101
  业务文件(附件、凭证、材料)存进本系统 Mongo,用 `ys_base.files` 统一处理分块、压缩、加密、上传会话、秒传、断点续传、
@@ -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
- "data": {"username": "u", "password": "p", "app_name": "auth"},
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
  ]
@@ -0,0 +1,305 @@
1
+ # -*- coding: utf-8 -*-
2
+ """ys_base.cache:LRU 淘汰、TTL、并发只加载一次、失效与旧结果,搜索缓存的命中、逐步缩小和分页。"""
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ from collections.abc import Hashable, Sequence
8
+ from typing import Any
9
+
10
+ import pytest
11
+
12
+ from ys_base.cache import YsLruCache, YsSearchCache
13
+ from ys_base.search import ys_search_text
14
+
15
+
16
+ class FakeClock:
17
+ def __init__(self) -> None:
18
+ self.now = 1000.0
19
+
20
+ def __call__(self) -> float:
21
+ return self.now
22
+
23
+
24
+ # ---------- YsLruCache ----------
25
+
26
+
27
+ def test_lru_evicts_least_recently_used() -> None:
28
+ cache: YsLruCache[str, int] = YsLruCache(maxsize=2, ttl=None)
29
+ cache.set("a", 1)
30
+ cache.set("b", 2)
31
+ assert cache.get("a") == 1 # a 变成最近用过
32
+ cache.set("c", 3)
33
+ assert cache.peek("b") is None
34
+ assert cache.peek("a") == 1 and cache.peek("c") == 3
35
+ assert cache.stats.evictions == 1
36
+
37
+
38
+ def test_weight_limit_and_oversized_entry() -> None:
39
+ cache: YsLruCache[str, list[int]] = YsLruCache(maxsize=10, max_weight=5, ttl=None, weigh=len)
40
+ assert cache.set("a", [1, 2, 3])
41
+ assert cache.set("b", [1, 2])
42
+ assert cache.weight == 5
43
+ assert cache.set("c", [1]) # 超出权重,淘汰最旧的 a
44
+ assert cache.peek("a") is None and cache.weight == 3
45
+ assert not cache.set("huge", list(range(6))) # 单条超过上限:不缓存
46
+ assert cache.peek("huge") is None and cache.weight == 3
47
+
48
+
49
+ def test_ttl_expires() -> None:
50
+ clock = FakeClock()
51
+ cache: YsLruCache[str, int] = YsLruCache(ttl=10, clock=clock)
52
+ cache.set("a", 1)
53
+ clock.now += 9.9
54
+ assert cache.get("a") == 1
55
+ clock.now += 0.2
56
+ assert cache.get("a") is None
57
+ assert cache.stats.expirations == 1 and len(cache) == 0
58
+
59
+
60
+ def test_rejects_bad_settings() -> None:
61
+ with pytest.raises(ValueError):
62
+ YsLruCache(maxsize=0)
63
+ with pytest.raises(ValueError):
64
+ YsLruCache(max_weight=0)
65
+ with pytest.raises(ValueError):
66
+ YsLruCache(ttl=0)
67
+
68
+
69
+ async def test_concurrent_misses_load_once() -> None:
70
+ cache: YsLruCache[str, int] = YsLruCache()
71
+ calls = 0
72
+ gate = asyncio.Event()
73
+
74
+ async def loader() -> int:
75
+ nonlocal calls
76
+ calls += 1
77
+ await gate.wait()
78
+ return 42
79
+
80
+ tasks = [asyncio.create_task(cache.get_or_load("k", loader)) for _ in range(5)]
81
+ await asyncio.sleep(0)
82
+ gate.set()
83
+ assert await asyncio.gather(*tasks) == [42] * 5
84
+ assert calls == 1
85
+ assert cache.stats.loads == 1 and cache.stats.misses == 5
86
+ assert await cache.get_or_load("k", loader) == 42 and cache.stats.hits == 1
87
+
88
+
89
+ async def test_failed_load_is_not_cached_and_reaches_all_waiters() -> None:
90
+ cache: YsLruCache[str, int] = YsLruCache()
91
+ gate = asyncio.Event()
92
+
93
+ async def boom() -> int:
94
+ await gate.wait()
95
+ raise RuntimeError("读取失败")
96
+
97
+ tasks = [asyncio.create_task(cache.get_or_load("k", boom)) for _ in range(3)]
98
+ await asyncio.sleep(0)
99
+ gate.set()
100
+ results = await asyncio.gather(*tasks, return_exceptions=True)
101
+ assert all(isinstance(item, RuntimeError) for item in results)
102
+ assert cache.peek("k") is None
103
+
104
+ async def ok() -> int:
105
+ return 7
106
+
107
+ assert await cache.get_or_load("k", ok) == 7
108
+
109
+
110
+ async def test_invalidate_during_load_does_not_store_stale_value() -> None:
111
+ cache: YsLruCache[str, int] = YsLruCache()
112
+ gate = asyncio.Event()
113
+
114
+ async def loader() -> int:
115
+ await gate.wait()
116
+ return 1
117
+
118
+ task = asyncio.create_task(cache.get_or_load("k", loader))
119
+ await asyncio.sleep(0)
120
+ cache.invalidate() # 写入发生在加载期间
121
+ gate.set()
122
+ assert await task == 1 # 调用方照常拿到结果
123
+ assert cache.peek("k") is None # 但不留在缓存里
124
+
125
+
126
+ def test_invalidate_by_key_and_where() -> None:
127
+ cache: YsLruCache[tuple[str, int], int] = YsLruCache(ttl=None)
128
+ for scope in ("x", "y"):
129
+ for n in range(3):
130
+ cache.set((scope, n), n)
131
+ assert cache.invalidate(("x", 0)) == 1
132
+ assert cache.invalidate(where=lambda key: key[0] == "y") == 3
133
+ assert [key for key, _ in cache.items()] == [("x", 1), ("x", 2)]
134
+ assert cache.invalidate() == 2 and len(cache) == 0
135
+
136
+
137
+ # ---------- YsSearchCache ----------
138
+
139
+ BANKS = [
140
+ "中国建设银行",
141
+ "中国工商银行",
142
+ "中国农业银行",
143
+ "中国银行",
144
+ "交通银行",
145
+ "招商银行",
146
+ "上海浦东发展银行",
147
+ "中信银行",
148
+ ]
149
+
150
+
151
+ def _rows(scope: Hashable) -> list[dict[str, Any]]:
152
+ return [
153
+ {"_id": f"{scope}-{index}", "name": name, "_search": ys_search_text(name, f"B{index:03d}")}
154
+ for index, name in enumerate(BANKS, start=1)
155
+ ]
156
+
157
+
158
+ class Loader:
159
+ def __init__(self) -> None:
160
+ self.calls: list[Hashable] = []
161
+
162
+ async def __call__(self, scope: Hashable) -> Sequence[dict[str, Any]]:
163
+ self.calls.append(scope)
164
+ return _rows(scope)
165
+
166
+
167
+ def _names(rows: Sequence[dict[str, Any]]) -> list[str]:
168
+ return [row["name"] for row in rows]
169
+
170
+
171
+ async def test_search_loads_base_once_then_hits() -> None:
172
+ load = Loader()
173
+ cache: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"])
174
+ first = await cache.search("all", "银行", load)
175
+ assert first.source == "loaded" and first.total == 8 and first.all == 8
176
+ again = await cache.search("all", " 银行 ", load) # 规范化后同一个关键词
177
+ assert again.source == "hit"
178
+ other = await cache.search("all", "中国", load)
179
+ assert other.source == "filtered" and other.total == 4
180
+ assert load.calls == ["all"] # 底表只加载一次
181
+ assert (await cache.search("all", "", load)).source == "hit" # 空关键词就是底表
182
+
183
+
184
+ async def test_search_narrows_from_shorter_keyword() -> None:
185
+ load = Loader()
186
+ cache: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"])
187
+ await cache.search("all", "中国", load)
188
+ narrowed = await cache.search("all", "中国建", load)
189
+ assert narrowed.source == "narrowed" and _names(narrowed.rows) == ["中国建设银行"]
190
+ # 多出一个词也能缩小;拼音前缀同样成立(zg → zgj)
191
+ assert (await cache.search("all", "中国 建设", load)).source == "narrowed"
192
+ await cache.search("all", "zg", load)
193
+ assert (await cache.search("all", "zgj", load)).source == "narrowed"
194
+ # 不是前缀关系(「国」不是「中国」的前缀)就从底表筛
195
+ assert (await cache.search("all", "国建", load)).source == "filtered"
196
+ assert cache.stats["narrowed"] == 3
197
+ assert cache.stats["searches"] == 6
198
+
199
+
200
+ async def test_narrowing_gives_same_result_as_full_filter() -> None:
201
+ load = Loader()
202
+ cached: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"])
203
+ fresh: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"])
204
+ for keyword in ("z", "zg", "zgy", "zgyh", "中", "中国", "中国银", "中国银行"):
205
+ a = await cached.search("all", keyword, load)
206
+ fresh.invalidate()
207
+ b = await fresh.search("all", keyword, load)
208
+ assert _names(a.rows) == _names(b.rows), keyword
209
+
210
+
211
+ async def test_fuzzy_never_narrows_and_is_cached_separately() -> None:
212
+ load = Loader()
213
+ cache: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"])
214
+ exact = await cache.search("all", "建行", load)
215
+ assert exact.total == 0
216
+ fuzzy = await cache.search("all", "建行", load, fuzzy=True)
217
+ assert fuzzy.source == "filtered" and _names(fuzzy.rows) == ["中国建设银行"]
218
+ await cache.search("all", "中", load, fuzzy=True)
219
+ assert (await cache.search("all", "中行", load, fuzzy=True)).source == "filtered" # 模糊不逐步缩小
220
+ assert (await cache.search("all", "建行", load, fuzzy=True)).source == "hit"
221
+
222
+
223
+ async def test_scopes_are_separate_and_invalidate_by_scope() -> None:
224
+ load = Loader()
225
+ cache: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"])
226
+ await cache.search(("bank", 1), "中国", load)
227
+ await cache.search(("bank", 2), "中国", load)
228
+ assert load.calls == [("bank", 1), ("bank", 2)]
229
+ assert cache.invalidate(("bank", 1)) == 2 # 底表 + 「中国」的结果
230
+ assert (await cache.search(("bank", 2), "中国", load)).source == "hit"
231
+ assert (await cache.search(("bank", 1), "中国", load)).source == "loaded"
232
+ cache.invalidate()
233
+ assert cache.stats["entries"] == 0
234
+
235
+
236
+ async def test_paging_slices_cached_result() -> None:
237
+ load = Loader()
238
+ cache: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"])
239
+ page1 = await cache.search("all", "银行", load, offset=0, limit=3)
240
+ page3 = await cache.search("all", "银行", load, offset=6, limit=3)
241
+ assert page1.total == page3.total == 8
242
+ assert _names(page1.rows) == BANKS[:3] and _names(page3.rows) == BANKS[6:]
243
+ assert page3.source == "hit"
244
+ beyond = await cache.search("all", "银行", load, offset=100, limit=3)
245
+ assert beyond.rows == [] and beyond.total == 8
246
+
247
+
248
+ async def test_row_budget_evicts_results_but_never_the_base() -> None:
249
+ load = Loader()
250
+ cache: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"], max_rows=10)
251
+ await cache.search("all", "银行", load) # 结果 8 行
252
+ await cache.search("all", "中国", load) # 再 4 行,超过 10:淘汰最久没用的「银行」
253
+ stats = cache.stats
254
+ assert stats["rows"] <= 10 and stats["evictions"] >= 1
255
+ assert stats["scopes"] == 1 and stats["base_rows"] == 8 # 底表不占结果的预算,不会被挤掉
256
+ assert (await cache.search("all", "银行", load)).source == "filtered" # 结果重算,但不重新读库
257
+ assert load.calls == ["all"]
258
+
259
+
260
+ async def test_scope_limit_evicts_least_recent_base() -> None:
261
+ load = Loader()
262
+ cache: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"], max_scopes=2)
263
+ for scope in ("a", "b", "c"):
264
+ await cache.search(scope, "", load)
265
+ assert cache.stats["scopes"] == 2
266
+ assert (await cache.search("a", "", load)).source == "loaded" # a 最久没用,被淘汰后重新加载
267
+
268
+
269
+ async def test_concurrent_first_searches_share_one_base_load() -> None:
270
+ calls = 0
271
+ gate = asyncio.Event()
272
+
273
+ async def slow(scope: Hashable) -> Sequence[dict[str, Any]]:
274
+ nonlocal calls
275
+ calls += 1
276
+ await gate.wait()
277
+ return _rows(scope)
278
+
279
+ cache: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"])
280
+ tasks = [asyncio.create_task(cache.search("all", keyword, slow)) for keyword in ("中国", "银行", "招商")]
281
+ await asyncio.sleep(0)
282
+ gate.set()
283
+ results = await asyncio.gather(*tasks)
284
+ assert calls == 1
285
+ assert [item.total for item in results] == [4, 8, 1]
286
+
287
+
288
+ async def test_large_scope_filters_in_thread() -> None:
289
+ rows = [{"_search": ys_search_text(f"机构{index}")} for index in range(50)]
290
+
291
+ async def load(_scope: Hashable) -> Sequence[dict[str, Any]]:
292
+ return rows
293
+
294
+ cache: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"], offload_rows=10)
295
+ result = await cache.search("all", "机构4", load)
296
+ assert result.total == 11 # 机构4、机构40~49
297
+
298
+
299
+ async def test_result_larger_than_budget_is_returned_but_not_cached() -> None:
300
+ load = Loader()
301
+ cache: YsSearchCache[dict[str, Any]] = YsSearchCache(text_of=lambda row: row["_search"], max_rows=5)
302
+ result = await cache.search("all", "银行", load) # 8 行超过 5 行预算
303
+ assert result.total == 8 and result.all == 8
304
+ assert cache.stats["entries"] == 0
305
+ assert (await cache.search("all", "银行", load)).source == "filtered"
@@ -1,10 +1,11 @@
1
1
  # -*- coding: utf-8 -*-
2
- """进程日志:落盘 app/logs/app.log,接管 uvicorn 访问日志。"""
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 / "app" / "logs" / "app.log").read_text(encoding="utf-8")
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 / "app" / "logs" / "app.log").read_text(encoding="utf-8")
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 / "app" / "logs" / "app.log").read_text(encoding="utf-8")
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,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"] == {}
@@ -18,6 +18,7 @@ from ys_base.search import (
18
18
  search_tokens,
19
19
  ys_filter,
20
20
  ys_match,
21
+ ys_match_detail,
21
22
  ys_matcher,
22
23
  ys_search_text,
23
24
  )
@@ -100,3 +101,35 @@ def test_filter_fifty_thousand_rows_quickly() -> None:
100
101
  assert sum(1 for text in texts if match(text)) > 0
101
102
  # 宽松上限,只防止退化成指数级回溯;实测约在 1 秒内。
102
103
  assert time.perf_counter() - started < 10
104
+
105
+
106
+ @needs_repo
107
+ @pytest.mark.parametrize("case", _cases("fuzzy"), ids=repr)
108
+ def test_shared_fuzzy(case: dict[str, Any]) -> None:
109
+ text = ys_search_text(*case["parts"])
110
+ detail = ys_match_detail(text, case["keyword"], fuzzy=True)
111
+ assert ys_match(text, case["keyword"], fuzzy=True) is (case["kind"] is not None)
112
+ if case["kind"] is None:
113
+ assert detail is None
114
+ else:
115
+ assert detail is not None
116
+ assert detail.kind == case["kind"]
117
+ assert detail.score == pytest.approx(case["score"], abs=1e-9)
118
+
119
+
120
+ @needs_repo
121
+ @pytest.mark.parametrize("case", _samples().get("fuzzy_filter", {}).get("cases", []), ids=repr)
122
+ def test_shared_fuzzy_filter(case: dict[str, Any]) -> None:
123
+ rows = _samples()["fuzzy_filter"]["rows"]
124
+ result = ys_filter(rows, case["keyword"], ys_search_text, fuzzy=True)
125
+ if "order" in case:
126
+ assert result == case["order"]
127
+ if "first" in case:
128
+ assert result[0] == case["first"]
129
+
130
+
131
+ def test_fuzzy_is_off_by_default() -> None:
132
+ text = ys_search_text("中国建设银行")
133
+ assert not ys_match(text, "建行")
134
+ assert ys_filter(["中国建设银行"], "建行", ys_search_text) == []
135
+ assert ys_match_detail(text, "") == (0, "exact")
@@ -1,4 +1,4 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  """YS 统一 SDK:契约模型 / auth 客户端与差量同步 / 应用服务骨架。"""
3
3
 
4
- __version__ = "0.2.2"
4
+ __version__ = "0.2.4"
@@ -63,6 +63,7 @@ class AuthClient(WsRpcClient):
63
63
  app_version: str = "",
64
64
  instance_id: str = "",
65
65
  pending_page: str = "",
66
+ runtime: dict[str, Any] | None = None,
66
67
  **kwargs: Any,
67
68
  ):
68
69
  super().__init__(uri, **kwargs)
@@ -71,6 +72,8 @@ class AuthClient(WsRpcClient):
71
72
  self.app_version = app_version
72
73
  # 待处理落地页,注册时上报;空串表示用系统消息页。
73
74
  self.pending_page = normalize_pending_page(pending_page)
75
+ # 运行环境(Python、自家包版本、主机名等),注册时上报给 Auth 的应用运行状态面板。
76
+ self.runtime = dict(runtime or {})
74
77
  self.instance_id = instance_id.strip() or uuid.uuid4().hex
75
78
  if len(self.instance_id) > 200:
76
79
  raise ValueError("AuthClient instance_id 不能超过 200 个字符")
@@ -222,6 +225,7 @@ class AuthClient(WsRpcClient):
222
225
  "app_version": self.app_version,
223
226
  "pending_page": self.pending_page,
224
227
  "instance_id": self.instance_id,
228
+ "runtime": self.runtime,
225
229
  "applied_authorization_version": applied_authorization_version,
226
230
  },
227
231
  )