ys_base 0.2.3__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.
- {ys_base-0.2.3 → ys_base-0.2.4}/PKG-INFO +44 -1
- {ys_base-0.2.3 → ys_base-0.2.4}/README.md +43 -0
- ys_base-0.2.4/tests/test_cache.py +305 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_search.py +33 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/__init__.py +1 -1
- ys_base-0.2.4/ys_base/cache.py +382 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/search.py +128 -9
- {ys_base-0.2.3 → ys_base-0.2.4}/.gitignore +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/.python-version +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/pyproject.toml +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/memory_store.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_api_token.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_app_server.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_contracts.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_crypto.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_files.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_files_migrate.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_http_errors.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_iso_reference.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_logging.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_mongo_store.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_rpc_client.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_runtime_info.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/tests/test_store_delta.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/uv.lock +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/_pinyin_data.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/auth/__init__.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/auth/api_token.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/auth/client.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/auth/delta.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/contracts/__init__.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/contracts/authorization.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/contracts/base.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/contracts/enums.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/contracts/iso_reference.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/contracts/master.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/contracts/platform.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/contracts/relations.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/crypto.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/files.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/files_migrate.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/py.typed +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/server/__init__.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/server/app_server.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/server/errors.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/server/http_errors.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/server/jwt_verify.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/server/logging.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/server/router.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/server/runtime_info.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/store/__init__.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/store/base.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/store/mongo.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/ys_base/ws/__init__.py +0 -0
- {ys_base-0.2.3 → ys_base-0.2.4}/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.4
|
|
4
4
|
Summary: YS 统一 SDK:契约模型 / auth 客户端与差量同步 / 应用服务骨架
|
|
5
5
|
Author-email: ys <popsars@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -72,6 +72,49 @@ match = ys_matcher(keyword) # 或自己循环:match(text) -> bool
|
|
|
72
72
|
|
|
73
73
|
`Decimal`、`bson.Decimal128` 按数字处理;`bool` 写成 `true`/`false`,`list`/`tuple` 展开,`None`、空串跳过。
|
|
74
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
|
+
|
|
75
118
|
## 文件存储(0.1.99 起,0.1.100 改为内容寻址)
|
|
76
119
|
|
|
77
120
|
业务文件(附件、凭证、材料)存进本系统 Mongo,用 `ys_base.files` 统一处理分块、压缩、加密、上传会话、秒传、断点续传、
|
|
@@ -53,6 +53,49 @@ match = ys_matcher(keyword) # 或自己循环:match(text) -> bool
|
|
|
53
53
|
|
|
54
54
|
`Decimal`、`bson.Decimal128` 按数字处理;`bool` 写成 `true`/`false`,`list`/`tuple` 展开,`None`、空串跳过。
|
|
55
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
|
+
|
|
56
99
|
## 文件存储(0.1.99 起,0.1.100 改为内容寻址)
|
|
57
100
|
|
|
58
101
|
业务文件(附件、凭证、材料)存进本系统 Mongo,用 `ys_base.files` 统一处理分块、压缩、加密、上传会话、秒传、断点续传、
|
|
@@ -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"
|
|
@@ -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")
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""进程内 LRU 缓存(按需使用):数据多、查询重、读远多于写的列表和查询才用,不是每个接口都加。
|
|
3
|
+
|
|
4
|
+
两层:
|
|
5
|
+
|
|
6
|
+
- ``YsLruCache``:通用 LRU。条数上限 + 权重上限(如缓存的总行数)双重淘汰,TTL 兜底过期;
|
|
7
|
+
同一个 key 同时只加载一次(``get_or_load``),用户连续快速输入时相同请求共享一次计算;按 key、按范围失效;带命中统计。
|
|
8
|
+
- ``YsSearchCache``:列表搜索专用。一个范围(如「某银行、未删除」)的全量行只加载一次作为底表,
|
|
9
|
+
之后每个关键词在内存里用 ``ys_base.search.ys_filter`` 过滤(拼音、可选模糊与前端一致),结果按关键词缓存,分页只切片。
|
|
10
|
+
输入「中国建」时若「中国」的结果已缓存,就只在那批结果里再筛(逐步缩小);只在能证明结果不变时才这样做。
|
|
11
|
+
|
|
12
|
+
from ys_base.cache import YsSearchCache
|
|
13
|
+
|
|
14
|
+
cnaps_search = YsSearchCache(text_of=lambda row: row["_search"], name="cnaps")
|
|
15
|
+
|
|
16
|
+
async def load_scope(scope): # scope 由调用方定义,必须可哈希,如 (bank_id, deleted)
|
|
17
|
+
bank_id, deleted = scope
|
|
18
|
+
return await load_rows_with_search_text(bank_id, deleted)
|
|
19
|
+
|
|
20
|
+
result = await cnaps_search.search(("B001", False), keyword, load_scope, offset=0, limit=50)
|
|
21
|
+
result.rows, result.total, result.source # source: hit / narrowed / filtered / loaded
|
|
22
|
+
|
|
23
|
+
cnaps_search.invalidate() # 写入、导入后失效;只影响某个范围时传 scope
|
|
24
|
+
|
|
25
|
+
缓存只在本进程内:多进程或多实例部署时各自缓存,靠写入后的 invalidate 和 TTL 保证不过期太久;
|
|
26
|
+
需要跨进程立即一致的数据不要用它。缓存的是行对象的引用,调用方不要原地修改返回的行。
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import asyncio
|
|
32
|
+
import time
|
|
33
|
+
from collections import OrderedDict
|
|
34
|
+
from collections.abc import Awaitable, Callable, Hashable, Sequence
|
|
35
|
+
from dataclasses import dataclass, field
|
|
36
|
+
from typing import Any, Literal
|
|
37
|
+
|
|
38
|
+
from ys_base.search import search_tokens, ys_filter
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"YsCacheStats",
|
|
42
|
+
"YsLruCache",
|
|
43
|
+
"YsSearchCache",
|
|
44
|
+
"YsSearchResult",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class YsCacheStats:
|
|
50
|
+
"""命中统计:hits 直接命中,misses 需要加载,loads 实际加载次数(并发的相同 miss 只算一次),
|
|
51
|
+
evictions 因条数或权重超限淘汰,expirations 因 TTL 过期丢弃。"""
|
|
52
|
+
|
|
53
|
+
hits: int = 0
|
|
54
|
+
misses: int = 0
|
|
55
|
+
loads: int = 0
|
|
56
|
+
evictions: int = 0
|
|
57
|
+
expirations: int = 0
|
|
58
|
+
|
|
59
|
+
def as_dict(self) -> dict[str, int]:
|
|
60
|
+
return {
|
|
61
|
+
"hits": self.hits,
|
|
62
|
+
"misses": self.misses,
|
|
63
|
+
"loads": self.loads,
|
|
64
|
+
"evictions": self.evictions,
|
|
65
|
+
"expirations": self.expirations,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class _Entry[V]:
|
|
71
|
+
value: V
|
|
72
|
+
weight: int
|
|
73
|
+
expires_at: float
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class YsLruCache[K: Hashable, V]:
|
|
77
|
+
"""进程内 LRU。
|
|
78
|
+
|
|
79
|
+
- ``maxsize``:最多缓存多少个 key;``max_weight``:所有条目权重之和的上限(``weigh(value)`` 算,默认每条 1)。
|
|
80
|
+
超限时从最久没用的开始淘汰;单条权重超过 ``max_weight`` 的不缓存(照常返回,只是不留)。
|
|
81
|
+
- ``ttl``:秒,None 不过期。过期条目在下次访问时丢弃。
|
|
82
|
+
- ``get_or_load(key, loader)``:没有就调 loader 加载并缓存;同一个 key 正在加载时,其他调用等同一个结果,不重复加载。
|
|
83
|
+
loader 抛错不缓存,所有等待者都收到同一个错误。
|
|
84
|
+
- 只在一个事件循环里用(asyncio 单线程),不做线程锁。
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
*,
|
|
90
|
+
maxsize: int = 256,
|
|
91
|
+
max_weight: int | None = None,
|
|
92
|
+
ttl: float | None = 300.0,
|
|
93
|
+
weigh: Callable[[V], int] | None = None,
|
|
94
|
+
clock: Callable[[], float] = time.monotonic,
|
|
95
|
+
) -> None:
|
|
96
|
+
if maxsize < 1:
|
|
97
|
+
raise ValueError("maxsize 至少为 1")
|
|
98
|
+
if max_weight is not None and max_weight < 1:
|
|
99
|
+
raise ValueError("max_weight 至少为 1")
|
|
100
|
+
if ttl is not None and ttl <= 0:
|
|
101
|
+
raise ValueError("ttl 必须大于 0,不过期写 None")
|
|
102
|
+
self.maxsize = maxsize
|
|
103
|
+
self.max_weight = max_weight
|
|
104
|
+
self.ttl = ttl
|
|
105
|
+
self._weigh = weigh or (lambda _value: 1)
|
|
106
|
+
self._clock = clock
|
|
107
|
+
self._entries: OrderedDict[K, _Entry[V]] = OrderedDict()
|
|
108
|
+
self._loading: dict[K, asyncio.Future[V]] = {}
|
|
109
|
+
self._weight = 0
|
|
110
|
+
# 失效时加一:失效前开始、失效后才完成的加载结果是旧数据,不能写进缓存
|
|
111
|
+
self._generation = 0
|
|
112
|
+
self.stats = YsCacheStats()
|
|
113
|
+
|
|
114
|
+
def __len__(self) -> int:
|
|
115
|
+
return len(self._entries)
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def weight(self) -> int:
|
|
119
|
+
"""当前所有条目的权重之和。"""
|
|
120
|
+
return self._weight
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def generation(self) -> int:
|
|
124
|
+
"""每次失效加一。自己算好再 set 的调用方,算之前记下,算完相同才写入(中途失效过的结果是旧数据)。"""
|
|
125
|
+
return self._generation
|
|
126
|
+
|
|
127
|
+
def _alive(self, key: K) -> _Entry[V] | None:
|
|
128
|
+
entry = self._entries.get(key)
|
|
129
|
+
if entry is None:
|
|
130
|
+
return None
|
|
131
|
+
if entry.expires_at <= self._clock():
|
|
132
|
+
self._drop(key)
|
|
133
|
+
self.stats.expirations += 1
|
|
134
|
+
return None
|
|
135
|
+
return entry
|
|
136
|
+
|
|
137
|
+
def _drop(self, key: K) -> None:
|
|
138
|
+
entry = self._entries.pop(key, None)
|
|
139
|
+
if entry is not None:
|
|
140
|
+
self._weight -= entry.weight
|
|
141
|
+
|
|
142
|
+
def peek(self, key: K) -> V | None:
|
|
143
|
+
"""看一眼,不算命中、不调整新旧顺序;过期的照样丢弃。"""
|
|
144
|
+
entry = self._alive(key)
|
|
145
|
+
return None if entry is None else entry.value
|
|
146
|
+
|
|
147
|
+
def get(self, key: K) -> V | None:
|
|
148
|
+
entry = self._alive(key)
|
|
149
|
+
if entry is None:
|
|
150
|
+
return None
|
|
151
|
+
self._entries.move_to_end(key)
|
|
152
|
+
self.stats.hits += 1
|
|
153
|
+
return entry.value
|
|
154
|
+
|
|
155
|
+
def set(self, key: K, value: V) -> bool:
|
|
156
|
+
"""写入并返回是否真的缓存了(单条超过 max_weight 时不缓存)。"""
|
|
157
|
+
weight = max(0, int(self._weigh(value)))
|
|
158
|
+
self._drop(key)
|
|
159
|
+
if self.max_weight is not None and weight > self.max_weight:
|
|
160
|
+
return False
|
|
161
|
+
expires_at = float("inf") if self.ttl is None else self._clock() + self.ttl
|
|
162
|
+
self._entries[key] = _Entry(value, weight, expires_at)
|
|
163
|
+
self._weight += weight
|
|
164
|
+
while len(self._entries) > self.maxsize or (self.max_weight is not None and self._weight > self.max_weight):
|
|
165
|
+
oldest = next(iter(self._entries))
|
|
166
|
+
self._drop(oldest)
|
|
167
|
+
self.stats.evictions += 1
|
|
168
|
+
return True
|
|
169
|
+
|
|
170
|
+
def items(self) -> list[tuple[K, V]]:
|
|
171
|
+
"""未过期的条目,从最久没用到最近用过;不算命中。"""
|
|
172
|
+
now = self._clock()
|
|
173
|
+
return [(key, entry.value) for key, entry in self._entries.items() if entry.expires_at > now]
|
|
174
|
+
|
|
175
|
+
async def get_or_load(self, key: K, loader: Callable[[], Awaitable[V]]) -> V:
|
|
176
|
+
entry = self._alive(key)
|
|
177
|
+
if entry is not None:
|
|
178
|
+
self._entries.move_to_end(key)
|
|
179
|
+
self.stats.hits += 1
|
|
180
|
+
return entry.value
|
|
181
|
+
self.stats.misses += 1
|
|
182
|
+
pending = self._loading.get(key)
|
|
183
|
+
if pending is not None:
|
|
184
|
+
return await asyncio.shield(pending)
|
|
185
|
+
future: asyncio.Future[V] = asyncio.get_running_loop().create_future()
|
|
186
|
+
self._loading[key] = future
|
|
187
|
+
generation = self._generation
|
|
188
|
+
self.stats.loads += 1
|
|
189
|
+
try:
|
|
190
|
+
value = await loader()
|
|
191
|
+
except BaseException as exc:
|
|
192
|
+
if not future.done():
|
|
193
|
+
future.set_exception(exc)
|
|
194
|
+
# 没有其他等待者时避免 "exception was never retrieved"
|
|
195
|
+
future.exception()
|
|
196
|
+
raise
|
|
197
|
+
else:
|
|
198
|
+
if generation == self._generation:
|
|
199
|
+
self.set(key, value)
|
|
200
|
+
future.set_result(value)
|
|
201
|
+
return value
|
|
202
|
+
finally:
|
|
203
|
+
if self._loading.get(key) is future:
|
|
204
|
+
del self._loading[key]
|
|
205
|
+
|
|
206
|
+
def invalidate(self, key: K | None = None, *, where: Callable[[K], bool] | None = None) -> int:
|
|
207
|
+
"""失效并返回丢弃的条数:传 key 只丢这一条,传 where 丢满足条件的,都不传清空全部。
|
|
208
|
+
|
|
209
|
+
正在加载的结果完成后照常返回给调用方,但不再写入缓存(加载可能读到了失效前的数据)。
|
|
210
|
+
"""
|
|
211
|
+
self._generation += 1
|
|
212
|
+
if key is not None:
|
|
213
|
+
existed = key in self._entries
|
|
214
|
+
self._drop(key)
|
|
215
|
+
return int(existed)
|
|
216
|
+
if where is not None:
|
|
217
|
+
keys = [item for item in self._entries if where(item)]
|
|
218
|
+
for item in keys:
|
|
219
|
+
self._drop(item)
|
|
220
|
+
return len(keys)
|
|
221
|
+
count = len(self._entries)
|
|
222
|
+
self._entries.clear()
|
|
223
|
+
self._weight = 0
|
|
224
|
+
return count
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@dataclass
|
|
228
|
+
class YsSearchResult[Row]:
|
|
229
|
+
"""一次搜索的结果:rows 是本页,total 是命中总数。
|
|
230
|
+
|
|
231
|
+
source 说明结果从哪来:hit 直接命中缓存;narrowed 从更短关键词的缓存结果里再筛;
|
|
232
|
+
filtered 从已缓存的底表里筛;loaded 先加载了底表再筛(这一次最慢)。took_ms 是本次耗时。
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
rows: list[Row]
|
|
236
|
+
total: int
|
|
237
|
+
source: Literal["hit", "narrowed", "filtered", "loaded"]
|
|
238
|
+
took_ms: float
|
|
239
|
+
all: int = 0
|
|
240
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
_SearchKey = tuple[Hashable, tuple[str, ...], bool]
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class YsSearchCache[Row]:
|
|
247
|
+
"""列表搜索缓存:底表 + 按关键词缓存的结果,两者分开存放。
|
|
248
|
+
|
|
249
|
+
- ``text_of(row)``:这一行的搜索文本(``ys_search_text`` 拼好的,建议加载底表时就算好存在行里)。
|
|
250
|
+
- 底表按 scope 缓存(``load(scope)`` 返回这个范围的全部行,按页面默认顺序排好),最多 ``max_scopes`` 个范围,
|
|
251
|
+
只按范围个数淘汰——结果再多也挤不掉底表(底表最有价值,丢了就要重新读库)。
|
|
252
|
+
- 关键词结果按 (scope, 规范化后的关键词, 是否模糊) 缓存,最多 ``maxsize`` 条、总行数不超过 ``max_rows``
|
|
253
|
+
(结果只存行的引用,不复制行),超了从最久没用的淘汰。空关键词的结果就是底表本身。
|
|
254
|
+
- ``offload_rows``:要过滤的行数超过这个数就放进线程池(``asyncio.to_thread``),不卡事件循环。
|
|
255
|
+
- 逐步缩小:已缓存关键词的每个词都是新关键词对应位置词的前缀(新关键词可以多出几个词)时,
|
|
256
|
+
新结果一定是旧结果的子集,只在旧结果里筛。模糊匹配的跨度上限随词长变化,不满足这个推导,开了模糊只从底表筛。
|
|
257
|
+
"""
|
|
258
|
+
|
|
259
|
+
def __init__(
|
|
260
|
+
self,
|
|
261
|
+
*,
|
|
262
|
+
text_of: Callable[[Row], str],
|
|
263
|
+
name: str = "",
|
|
264
|
+
max_scopes: int = 16,
|
|
265
|
+
maxsize: int = 256,
|
|
266
|
+
max_rows: int = 500_000,
|
|
267
|
+
ttl: float | None = 600.0,
|
|
268
|
+
offload_rows: int = 20_000,
|
|
269
|
+
clock: Callable[[], float] = time.monotonic,
|
|
270
|
+
) -> None:
|
|
271
|
+
self.name = name
|
|
272
|
+
self._text_of = text_of
|
|
273
|
+
self._offload_rows = offload_rows
|
|
274
|
+
self._bases: YsLruCache[Hashable, Sequence[Row]] = YsLruCache(
|
|
275
|
+
maxsize=max_scopes, ttl=ttl, weigh=len, clock=clock
|
|
276
|
+
)
|
|
277
|
+
self._results: YsLruCache[_SearchKey, Sequence[Row]] = YsLruCache(
|
|
278
|
+
maxsize=maxsize, max_weight=max_rows, ttl=ttl, weigh=len, clock=clock
|
|
279
|
+
)
|
|
280
|
+
self.searches = 0
|
|
281
|
+
self.hits = 0
|
|
282
|
+
self.narrowed = 0
|
|
283
|
+
self.filtered = 0
|
|
284
|
+
|
|
285
|
+
@property
|
|
286
|
+
def stats(self) -> dict[str, int]:
|
|
287
|
+
"""searches 搜索次数:hits 直接命中、narrowed 逐步缩小、filtered 从底表筛;loads 读库加载底表的次数;
|
|
288
|
+
scopes、base_rows 是缓存的范围数和底表行数;entries、rows 是缓存的结果条数和行引用数;evictions 结果被淘汰的次数。"""
|
|
289
|
+
return {
|
|
290
|
+
"searches": self.searches,
|
|
291
|
+
"hits": self.hits,
|
|
292
|
+
"narrowed": self.narrowed,
|
|
293
|
+
"filtered": self.filtered,
|
|
294
|
+
"loads": self._bases.stats.loads,
|
|
295
|
+
"scopes": len(self._bases),
|
|
296
|
+
"base_rows": self._bases.weight,
|
|
297
|
+
"entries": len(self._results),
|
|
298
|
+
"rows": self._results.weight,
|
|
299
|
+
"evictions": self._results.stats.evictions + self._bases.stats.evictions,
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
@staticmethod
|
|
303
|
+
def _narrows(cached: tuple[str, ...], wanted: tuple[str, ...]) -> bool:
|
|
304
|
+
if len(cached) > len(wanted) or cached == wanted:
|
|
305
|
+
return False
|
|
306
|
+
return all(new.startswith(old) for old, new in zip(cached, wanted, strict=False))
|
|
307
|
+
|
|
308
|
+
def _best_superset(self, scope: Hashable, tokens: tuple[str, ...]) -> Sequence[Row] | None:
|
|
309
|
+
best: Sequence[Row] | None = None
|
|
310
|
+
for (cached_scope, cached_tokens, cached_fuzzy), rows in self._results.items():
|
|
311
|
+
if cached_scope != scope or cached_fuzzy:
|
|
312
|
+
continue
|
|
313
|
+
if self._narrows(cached_tokens, tokens) and (best is None or len(rows) < len(best)):
|
|
314
|
+
best = rows
|
|
315
|
+
return best
|
|
316
|
+
|
|
317
|
+
async def _filter(self, rows: Sequence[Row], keyword: str, fuzzy: bool) -> list[Row]:
|
|
318
|
+
if len(rows) > self._offload_rows:
|
|
319
|
+
return await asyncio.to_thread(ys_filter, rows, keyword, self._text_of, fuzzy=fuzzy)
|
|
320
|
+
return ys_filter(rows, keyword, self._text_of, fuzzy=fuzzy)
|
|
321
|
+
|
|
322
|
+
async def base(self, scope: Hashable, load: Callable[[Hashable], Awaitable[Sequence[Row]]]) -> Sequence[Row]:
|
|
323
|
+
"""这个范围的全部行(底表),没有就加载;并发的首次加载只调一次 load。"""
|
|
324
|
+
|
|
325
|
+
async def loader() -> Sequence[Row]:
|
|
326
|
+
return list(await load(scope))
|
|
327
|
+
|
|
328
|
+
return await self._bases.get_or_load(scope, loader)
|
|
329
|
+
|
|
330
|
+
async def search(
|
|
331
|
+
self,
|
|
332
|
+
scope: Hashable,
|
|
333
|
+
keyword: str,
|
|
334
|
+
load: Callable[[Hashable], Awaitable[Sequence[Row]]],
|
|
335
|
+
*,
|
|
336
|
+
fuzzy: bool = False,
|
|
337
|
+
offset: int = 0,
|
|
338
|
+
limit: int | None = None,
|
|
339
|
+
) -> YsSearchResult[Row]:
|
|
340
|
+
"""按关键词搜索这个范围,返回第 offset 起的 limit 行和总数;limit 为 None 返回全部。"""
|
|
341
|
+
started = time.perf_counter()
|
|
342
|
+
self.searches += 1
|
|
343
|
+
tokens = tuple(search_tokens(keyword))
|
|
344
|
+
key: _SearchKey = (scope, tokens, bool(fuzzy) and bool(tokens))
|
|
345
|
+
source: Literal["hit", "narrowed", "filtered", "loaded"]
|
|
346
|
+
had_base = self._bases.peek(scope) is not None
|
|
347
|
+
base_rows = await self.base(scope, load)
|
|
348
|
+
|
|
349
|
+
matched = base_rows if not tokens else self._results.get(key)
|
|
350
|
+
if matched is not None:
|
|
351
|
+
source = "hit" if had_base else "loaded"
|
|
352
|
+
self.hits += source == "hit"
|
|
353
|
+
else:
|
|
354
|
+
generation = self._results.generation
|
|
355
|
+
superset = None if fuzzy else self._best_superset(scope, tokens)
|
|
356
|
+
if superset is not None:
|
|
357
|
+
matched = await self._filter(superset, keyword, False)
|
|
358
|
+
self.narrowed += 1
|
|
359
|
+
source = "narrowed"
|
|
360
|
+
else:
|
|
361
|
+
matched = await self._filter(base_rows, keyword, fuzzy)
|
|
362
|
+
self.filtered += 1
|
|
363
|
+
source = "filtered" if had_base else "loaded"
|
|
364
|
+
# 过滤期间有写入失效过,结果照常返回但不缓存
|
|
365
|
+
if generation == self._results.generation:
|
|
366
|
+
self._results.set(key, matched)
|
|
367
|
+
|
|
368
|
+
start = max(0, offset)
|
|
369
|
+
page = list(matched[start:] if limit is None else matched[start : start + max(0, limit)])
|
|
370
|
+
return YsSearchResult(
|
|
371
|
+
rows=page,
|
|
372
|
+
total=len(matched),
|
|
373
|
+
source=source,
|
|
374
|
+
took_ms=round((time.perf_counter() - started) * 1000, 1),
|
|
375
|
+
all=len(base_rows),
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
def invalidate(self, scope: Hashable | None = None) -> int:
|
|
379
|
+
"""写入、导入后调用:不传 scope 清空全部;传 scope 只清这个范围的底表和结果。返回丢弃的条数。"""
|
|
380
|
+
if scope is None:
|
|
381
|
+
return self._bases.invalidate() + self._results.invalidate()
|
|
382
|
+
return self._bases.invalidate(scope) + self._results.invalidate(where=lambda key: key[0] == scope)
|
|
@@ -17,6 +17,9 @@
|
|
|
17
17
|
- 数字原值按 JavaScript 的 String(x) 写出,再加两位小数写法(toFixed(2)),1377 也能用 1377.00 搜到。
|
|
18
18
|
- 纯字母关键词还按拼音匹配连续的汉字:首字母、全拼、zh/ch/sh 声母、最后一个字只打一半全拼都算,
|
|
19
19
|
多音字任一读音都算。xx、xuexiao、xuex、xxiao 都能搜到「学校」,zhs 能搜到「张三」。
|
|
20
|
+
- 模糊匹配按需开启(fuzzy=True),规则同前端 ysMatchDetail / ysFilter:关键词里的字按顺序出现在同一字段里即命中
|
|
21
|
+
(「建行」→「中国建设银行」),纯字母关键词每个字母对一个字的拼音首字母;至少 2 个字,带数字、汉字字母混写的词不做模糊,
|
|
22
|
+
首尾跨度不超过关键词长度的 4 倍。分数:原文 3、拼音 2、模糊 1 + 关键词长度 / 跨度,多个词相加;ys_filter 开模糊时按分数排序。
|
|
20
23
|
- 拼音数据与前端同源(tools/pinyin/build.py 生成 _pinyin_data.py)。与前端一致,码点超过 U+FFFF 的
|
|
21
24
|
扩展区汉字不参与拼音匹配(前端按 UTF-16 逐位比较,这些字取不到读音),只能按原字搜。
|
|
22
25
|
|
|
@@ -32,15 +35,17 @@ import unicodedata
|
|
|
32
35
|
from collections.abc import Callable, Iterable
|
|
33
36
|
from decimal import ROUND_HALF_UP, Decimal
|
|
34
37
|
from functools import lru_cache
|
|
35
|
-
from typing import Any
|
|
38
|
+
from typing import Any, Literal, NamedTuple
|
|
36
39
|
|
|
37
40
|
from ys_base._pinyin_data import PINYIN_DATA
|
|
38
41
|
|
|
39
42
|
__all__ = [
|
|
43
|
+
"YsMatchDetail",
|
|
40
44
|
"normalize_search_text",
|
|
41
45
|
"search_tokens",
|
|
42
46
|
"ys_filter",
|
|
43
47
|
"ys_match",
|
|
48
|
+
"ys_match_detail",
|
|
44
49
|
"ys_matcher",
|
|
45
50
|
"ys_search_text",
|
|
46
51
|
]
|
|
@@ -241,14 +246,109 @@ def _pinyin_includes(text: str, token: str) -> bool:
|
|
|
241
246
|
return False
|
|
242
247
|
|
|
243
248
|
|
|
249
|
+
class YsMatchDetail(NamedTuple):
|
|
250
|
+
"""命中详情:score 越大越靠前(原文 3、拼音 2、模糊 1~2,多个词相加);kind 取多个词里最弱的一种。"""
|
|
251
|
+
|
|
252
|
+
score: float
|
|
253
|
+
kind: Literal["exact", "pinyin", "fuzzy"]
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
# 模糊:首尾跨度不超过关键词长度的这么多倍。
|
|
257
|
+
_FUZZY_SPAN_RATIO = 4
|
|
258
|
+
_HAS_DIGIT = re.compile("[0-9]")
|
|
259
|
+
_HAS_LETTER = re.compile("[a-z]")
|
|
260
|
+
_KIND_ORDER = {"exact": 0, "pinyin": 1, "fuzzy": 2}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _fuzzy_char(char: str, want: str, letters: bool) -> bool:
|
|
264
|
+
if not letters:
|
|
265
|
+
return char == want
|
|
266
|
+
syllables = _PINYIN.get(char)
|
|
267
|
+
return syllables is not None and any(s[0] == want for s in syllables)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _fuzzy_span(field: str, token: str, letters: bool) -> int:
|
|
271
|
+
"""在一个字段里找按顺序包含 token 各字的最短一段,返回跨度;找不到或太散返回 0。"""
|
|
272
|
+
limit = len(token) * _FUZZY_SPAN_RATIO
|
|
273
|
+
size = len(field)
|
|
274
|
+
best = 0
|
|
275
|
+
for start in range(size):
|
|
276
|
+
if not _fuzzy_char(field[start], token[0], letters):
|
|
277
|
+
continue
|
|
278
|
+
j = 1
|
|
279
|
+
i = start + 1
|
|
280
|
+
while i < size and j < len(token) and i - start < limit:
|
|
281
|
+
if _fuzzy_char(field[i], token[j], letters):
|
|
282
|
+
j += 1
|
|
283
|
+
i += 1
|
|
284
|
+
if j == len(token):
|
|
285
|
+
span = i - start
|
|
286
|
+
if not best or span < best:
|
|
287
|
+
best = span
|
|
288
|
+
if best == len(token):
|
|
289
|
+
break
|
|
290
|
+
return best
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _fuzzy_score(text: str, token: str) -> float:
|
|
294
|
+
if len(token) < 2 or _HAS_DIGIT.search(token):
|
|
295
|
+
return 0.0
|
|
296
|
+
letters = _LETTERS.fullmatch(token) is not None
|
|
297
|
+
if not letters and _HAS_LETTER.search(token):
|
|
298
|
+
return 0.0
|
|
299
|
+
best = 0.0
|
|
300
|
+
for field in text.split(FIELD_SEPARATOR):
|
|
301
|
+
span = _fuzzy_span(field, token, letters)
|
|
302
|
+
if span:
|
|
303
|
+
best = max(best, 1 + len(token) / span)
|
|
304
|
+
return best
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _token_detail(token: str, fuzzy: bool) -> Callable[[str], YsMatchDetail | None]:
|
|
308
|
+
letters = _LETTERS.fullmatch(token) is not None
|
|
309
|
+
|
|
310
|
+
def detail(text: str) -> YsMatchDetail | None:
|
|
311
|
+
if token in text:
|
|
312
|
+
return YsMatchDetail(3, "exact")
|
|
313
|
+
if letters and _pinyin_includes(text, token):
|
|
314
|
+
return YsMatchDetail(2, "pinyin")
|
|
315
|
+
if not fuzzy:
|
|
316
|
+
return None
|
|
317
|
+
score = _fuzzy_score(text, token)
|
|
318
|
+
return YsMatchDetail(score, "fuzzy") if score else None
|
|
319
|
+
|
|
320
|
+
return detail
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _detail_matcher(keyword: str, fuzzy: bool) -> Callable[[str], YsMatchDetail | None]:
|
|
324
|
+
details = [_token_detail(token, fuzzy) for token in search_tokens(keyword)]
|
|
325
|
+
|
|
326
|
+
def match(text: str) -> YsMatchDetail | None:
|
|
327
|
+
score = 0.0
|
|
328
|
+
kind: Literal["exact", "pinyin", "fuzzy"] = "exact"
|
|
329
|
+
for detail in details:
|
|
330
|
+
hit = detail(text)
|
|
331
|
+
if hit is None:
|
|
332
|
+
return None
|
|
333
|
+
score += hit.score
|
|
334
|
+
if _KIND_ORDER[hit.kind] > _KIND_ORDER[kind]:
|
|
335
|
+
kind = hit.kind
|
|
336
|
+
return YsMatchDetail(score, kind)
|
|
337
|
+
|
|
338
|
+
return match
|
|
339
|
+
|
|
340
|
+
|
|
244
341
|
def _token_matcher(token: str) -> Callable[[str], bool]:
|
|
245
342
|
if _LETTERS.fullmatch(token) is None:
|
|
246
343
|
return lambda text: token in text
|
|
247
344
|
return lambda text: token in text or _pinyin_includes(text, token)
|
|
248
345
|
|
|
249
346
|
|
|
250
|
-
def ys_matcher(keyword: str) -> Callable[[str], bool]:
|
|
251
|
-
"""预处理关键词,返回 match(text) -> bool
|
|
347
|
+
def ys_matcher(keyword: str, *, fuzzy: bool = False) -> Callable[[str], bool]:
|
|
348
|
+
"""预处理关键词,返回 match(text) -> bool;逐行过滤时只拆一次关键词。关键词为空时命中全部。默认不做模糊匹配。"""
|
|
349
|
+
if fuzzy:
|
|
350
|
+
detail = _detail_matcher(keyword, True)
|
|
351
|
+
return lambda text: detail(text) is not None
|
|
252
352
|
matchers = [_token_matcher(token) for token in search_tokens(keyword)]
|
|
253
353
|
if not matchers:
|
|
254
354
|
return lambda text: True
|
|
@@ -257,12 +357,31 @@ def ys_matcher(keyword: str) -> Callable[[str], bool]:
|
|
|
257
357
|
return lambda text: all(match(text) for match in matchers)
|
|
258
358
|
|
|
259
359
|
|
|
260
|
-
def ys_match(text: str, keyword: str) -> bool:
|
|
360
|
+
def ys_match(text: str, keyword: str, *, fuzzy: bool = False) -> bool:
|
|
261
361
|
"""text 用 ys_search_text 拼出;关键词为空时命中全部。空格分隔的每个词都要命中(可分别命中不同字段)。"""
|
|
262
|
-
return ys_matcher(keyword)(text)
|
|
362
|
+
return ys_matcher(keyword, fuzzy=fuzzy)(text)
|
|
263
363
|
|
|
264
364
|
|
|
265
|
-
def
|
|
266
|
-
"""
|
|
267
|
-
|
|
268
|
-
|
|
365
|
+
def ys_match_detail(text: str, keyword: str, *, fuzzy: bool = False) -> YsMatchDetail | None:
|
|
366
|
+
"""命中详情;没命中返回 None,关键词为空时 YsMatchDetail(0, "exact")。"""
|
|
367
|
+
return _detail_matcher(keyword, fuzzy)(text)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def ys_filter[T](rows: Iterable[T], keyword: str, text_of: Callable[[T], str], *, fuzzy: bool = False) -> list[T]:
|
|
371
|
+
"""按关键词过滤行:text_of(row) 返回 ys_search_text 拼出的文本。关键词为空时原样返回全部。
|
|
372
|
+
|
|
373
|
+
不开模糊时保持原顺序;开了模糊按命中程度排序(同分保持原顺序)。
|
|
374
|
+
"""
|
|
375
|
+
if not fuzzy:
|
|
376
|
+
match = ys_matcher(keyword)
|
|
377
|
+
return [row for row in rows if match(text_of(row))]
|
|
378
|
+
if not search_tokens(keyword):
|
|
379
|
+
return list(rows)
|
|
380
|
+
detail = _detail_matcher(keyword, True)
|
|
381
|
+
hits: list[tuple[float, int, T]] = []
|
|
382
|
+
for index, row in enumerate(rows):
|
|
383
|
+
hit = detail(text_of(row))
|
|
384
|
+
if hit is not None:
|
|
385
|
+
hits.append((-hit.score, index, row))
|
|
386
|
+
hits.sort(key=lambda item: (item[0], item[1]))
|
|
387
|
+
return [row for _, _, row in hits]
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|