convenience-toolkit 0.0.1__py3-none-any.whl
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.
- convenience_toolkit/__init__.py +90 -0
- convenience_toolkit/file_change.py +276 -0
- convenience_toolkit/file_watch.py +832 -0
- convenience_toolkit/py.typed +0 -0
- convenience_toolkit/reactive_engine.py +1706 -0
- convenience_toolkit/sqlite_pool_manager.py +676 -0
- convenience_toolkit/state_machine.py +1686 -0
- convenience_toolkit-0.0.1.dist-info/METADATA +474 -0
- convenience_toolkit-0.0.1.dist-info/RECORD +11 -0
- convenience_toolkit-0.0.1.dist-info/WHEEL +5 -0
- convenience_toolkit-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""convenience_toolkit —— 便利工具箱。
|
|
3
|
+
|
|
4
|
+
把五个常用工具聚合到一个 Python 包中,便于通过 pip / uv 统一安装:
|
|
5
|
+
|
|
6
|
+
- ``file_change`` 文件变化检测(基于 xxhash 的三级指纹判定 + LRU 缓存)
|
|
7
|
+
- ``file_watch`` 文件系统监听(基于 watchdog,支持去抖、黑白名单、线程池)
|
|
8
|
+
- ``reactive_engine`` 响应式编程引擎(Observable / Computed / Effect 依赖追踪)
|
|
9
|
+
- ``sqlite_pool_manager`` SQLite 连接池与通用 CRUD(基于 DBUtils.PersistentDB)
|
|
10
|
+
- ``state_machine`` 有限状态机(同步/异步 API、守卫、回调、快照、Mermaid 可视化)
|
|
11
|
+
|
|
12
|
+
推荐两种导入方式:
|
|
13
|
+
|
|
14
|
+
# 方式一:从包顶层直接导入常用符号
|
|
15
|
+
from convenience_toolkit import changed, Observable, StateMachine, SQLitePoolManager
|
|
16
|
+
|
|
17
|
+
# 方式二:导入具体子模块(符号最全)
|
|
18
|
+
from convenience_toolkit.file_change import changed
|
|
19
|
+
from convenience_toolkit.reactive_engine import ReactiveEngine
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import importlib as _importlib
|
|
25
|
+
|
|
26
|
+
__version__ = "0.0.1"
|
|
27
|
+
|
|
28
|
+
# 公开符号 -> 所在子模块的映射。采用惰性导入:某个子模块的可选依赖缺失时,
|
|
29
|
+
# 不影响其它工具的使用,只有在真正访问对应符号时才触发该子模块导入。
|
|
30
|
+
_SYMBOL_TO_MODULE: dict[str, str] = {}
|
|
31
|
+
|
|
32
|
+
def _register(module: str, *names: str) -> None:
|
|
33
|
+
for _n in names:
|
|
34
|
+
_SYMBOL_TO_MODULE[_n] = module
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_register(
|
|
38
|
+
"convenience_toolkit.file_change",
|
|
39
|
+
"changed", "get_stats", "remove_from_cache", "clear_cache_for_directory",
|
|
40
|
+
)
|
|
41
|
+
_register(
|
|
42
|
+
"convenience_toolkit.file_watch",
|
|
43
|
+
"Watcher", "CustomEventHandler", "EventHandler", "debounce",
|
|
44
|
+
"catch_exception", "set_thread_pool", "new_thread_pool", "get_dir", "cleanup",
|
|
45
|
+
)
|
|
46
|
+
_register(
|
|
47
|
+
"convenience_toolkit.reactive_engine",
|
|
48
|
+
"ReactiveEngine", "Observable", "Computed", "Effect", "EffectPriority",
|
|
49
|
+
"WatchOptions", "WatchHandle", "WatchEffect", "EffectScheduler",
|
|
50
|
+
"DependencyGraph", "DependencyTracker", "Container", "ReactiveValue",
|
|
51
|
+
"ReactiveObserver", "CircularDependencyError",
|
|
52
|
+
)
|
|
53
|
+
_register(
|
|
54
|
+
"convenience_toolkit.sqlite_pool_manager",
|
|
55
|
+
"SQLitePoolManager", "SQLiteGenericCRUD", "GenericSQLBuilder",
|
|
56
|
+
)
|
|
57
|
+
_register(
|
|
58
|
+
"convenience_toolkit.state_machine",
|
|
59
|
+
"StateMachine", "State", "Transition", "WILDCARD", "StateMachineError",
|
|
60
|
+
"InvalidStateError", "TransitionNotAllowed", "CallbackError",
|
|
61
|
+
"StateMachineOverflow",
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
__all__ = sorted(_SYMBOL_TO_MODULE) + [
|
|
65
|
+
"file_change", "file_watch", "reactive_engine",
|
|
66
|
+
"sqlite_pool_manager", "state_machine", "__version__",
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
_SUBMODULES = {
|
|
70
|
+
"file_change", "file_watch", "reactive_engine",
|
|
71
|
+
"sqlite_pool_manager", "state_machine",
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def __getattr__(name: str):
|
|
76
|
+
"""按需加载子模块或符号,避免可选依赖缺失时拖垮整个包。"""
|
|
77
|
+
if name in _SUBMODULES:
|
|
78
|
+
mod = _importlib.import_module(f"convenience_toolkit.{name}")
|
|
79
|
+
globals()[name] = mod
|
|
80
|
+
return mod
|
|
81
|
+
module = _SYMBOL_TO_MODULE.get(name)
|
|
82
|
+
if module is not None:
|
|
83
|
+
value = getattr(_importlib.import_module(module), name)
|
|
84
|
+
globals()[name] = value # 缓存,后续访问不再走 __getattr__
|
|
85
|
+
return value
|
|
86
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def __dir__():
|
|
90
|
+
return sorted(set(globals()) | set(__all__))
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
# 2026-12-01 20:08:05
|
|
2
|
+
# 文件结构:本文件按使用流程分为五个部分,顺序如下。
|
|
3
|
+
# - 缓存状态与配置:定义缓存容量上限、路径指纹缓存、统计字典与统计锁、上次清理时间戳。
|
|
4
|
+
# 职责:集中承载跨调用共享的可变状态,供后续检测与统计逻辑读写。
|
|
5
|
+
# - 文件变化检测:changed 为对外入口,按快速检查、采样检查、全量检查三级判定文件是否变化。
|
|
6
|
+
# 职责:返回内容是否变化与是否仅元数据抖动的判定结果。
|
|
7
|
+
# - 指纹计算:_get_sample_hash 与 _get_full_hash 提供采样与全量 xxhash 指纹。
|
|
8
|
+
# 职责:为变化检测提供指纹依据,读取失败时返回 0。
|
|
9
|
+
# - 缓存维护:_cleanup_cache 清理已失效路径,配合检测入口的容量上限约束。
|
|
10
|
+
# 职责:防止缓存随文件删除无限增长。
|
|
11
|
+
# - 统计与缓存管理:get_stats、remove_from_cache、clear_cache_for_directory。
|
|
12
|
+
# 职责:对外提供统计快照与按路径/目录主动清理缓存的能力。
|
|
13
|
+
# - 使用示例:__main__ 块演示上述入口的典型调用顺序。
|
|
14
|
+
# 使用流程:调用方先以 changed 检测目标路径(必要时结合返回的第二项区分元数据抖动);
|
|
15
|
+
# 再按需要用 get_stats 观察命中率、用 remove_from_cache 或 clear_cache_for_directory 主动失效缓存;
|
|
16
|
+
# 维护者按上述分区顺序阅读与修改,先改检测入口,再改指纹计算与缓存维护,最后改统计与管理接口。
|
|
17
|
+
|
|
18
|
+
import xxhash
|
|
19
|
+
import pathlib
|
|
20
|
+
import time
|
|
21
|
+
import threading
|
|
22
|
+
from typing import Tuple
|
|
23
|
+
from collections import OrderedDict
|
|
24
|
+
|
|
25
|
+
# ==============================================================================
|
|
26
|
+
# 缓存状态与配置
|
|
27
|
+
# ==============================================================================
|
|
28
|
+
_CACHE_MAX_SIZE = 1000
|
|
29
|
+
# 路径到指纹四元组 (size, mtime_ns, sample_hash, full_hash) 的映射;按最近使用排序,超出容量从最旧端淘汰。
|
|
30
|
+
_CHANGED_CACHE = OrderedDict()
|
|
31
|
+
# 累计计数字典:total_checks/fast_passes/sample_passes/full_hashes/errors 均为非负整数,读写须持 _stats_lock。
|
|
32
|
+
_stats = {
|
|
33
|
+
'total_checks': 0, 'fast_passes': 0, 'sample_passes': 0,
|
|
34
|
+
'full_hashes': 0, 'errors': 0
|
|
35
|
+
}
|
|
36
|
+
# 保护 _stats 各计数字段的互斥锁;每次读写统计值都须持有该锁。
|
|
37
|
+
_stats_lock = threading.Lock()
|
|
38
|
+
# 上次按文件存在性清理缓存的 Unix 时间戳(秒);由 changed 在超过 3600 秒时触发 _cleanup_cache。
|
|
39
|
+
_LAST_CLEANUP = time.time()
|
|
40
|
+
|
|
41
|
+
# ==============================================================================
|
|
42
|
+
# 文件变化检测
|
|
43
|
+
# ==============================================================================
|
|
44
|
+
def changed(path: str | pathlib.Path, /, sample: int = 4 * 1024) -> Tuple[bool, bool]:
|
|
45
|
+
"""检测文件路径的内容是否发生变化。
|
|
46
|
+
|
|
47
|
+
按文件大小与修改时间、采样指纹、全量指纹三级依次判定;命中任一级即更新缓存并返回。
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
path: 待检测的文件路径,字符串或 pathlib.Path;会被解析为绝对路径作为缓存键。
|
|
51
|
+
sample: 采样检查时每段读取的字节数,默认 4096;影响采样指纹覆盖的文件范围。
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
Tuple[bool, bool]: 第一项表示文件内容是否发生变化;第二项表示是否仅元数据(大小/时间)变化而内容未变。
|
|
55
|
+
|
|
56
|
+
Side Effects:
|
|
57
|
+
更新 _CHANGED_CACHE、_LAST_CLEANUP 与 _stats;缓存超容量时淘汰最旧条目。
|
|
58
|
+
"""
|
|
59
|
+
global _LAST_CLEANUP
|
|
60
|
+
|
|
61
|
+
with _stats_lock:
|
|
62
|
+
_stats['total_checks'] += 1
|
|
63
|
+
|
|
64
|
+
# 定期清理
|
|
65
|
+
current_time = time.time()
|
|
66
|
+
if current_time - _LAST_CLEANUP > 3600:
|
|
67
|
+
_cleanup_cache()
|
|
68
|
+
_LAST_CLEANUP = current_time
|
|
69
|
+
|
|
70
|
+
p = pathlib.Path(path).resolve()
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
st = p.stat()
|
|
74
|
+
except (OSError, FileNotFoundError):
|
|
75
|
+
with _stats_lock:
|
|
76
|
+
_stats['errors'] += 1
|
|
77
|
+
_CHANGED_CACHE.pop(p, None)
|
|
78
|
+
return False, False
|
|
79
|
+
|
|
80
|
+
size, mtime = st.st_size, st.st_mtime_ns
|
|
81
|
+
old = _CHANGED_CACHE.get(p)
|
|
82
|
+
|
|
83
|
+
# ① 快速检查
|
|
84
|
+
if old and old[:2] == (size, mtime):
|
|
85
|
+
with _stats_lock:
|
|
86
|
+
_stats['fast_passes'] += 1
|
|
87
|
+
_CHANGED_CACHE.move_to_end(p)
|
|
88
|
+
return False, False
|
|
89
|
+
|
|
90
|
+
# ② 采样检查
|
|
91
|
+
sample_hash = _get_sample_hash(p, size, sample)
|
|
92
|
+
if old and old[2] == sample_hash:
|
|
93
|
+
with _stats_lock:
|
|
94
|
+
_stats['sample_passes'] += 1
|
|
95
|
+
_CHANGED_CACHE[p] = (size, mtime, *old[2:])
|
|
96
|
+
_CHANGED_CACHE.move_to_end(p)
|
|
97
|
+
return False, True
|
|
98
|
+
|
|
99
|
+
# ③ 全量检查
|
|
100
|
+
full_hash = _get_full_hash(p, size)
|
|
101
|
+
changed_flag = not old or old[3] != full_hash
|
|
102
|
+
|
|
103
|
+
# 更新缓存
|
|
104
|
+
_CHANGED_CACHE[p] = (size, mtime, sample_hash, full_hash)
|
|
105
|
+
_CHANGED_CACHE.move_to_end(p)
|
|
106
|
+
|
|
107
|
+
if len(_CHANGED_CACHE) > _CACHE_MAX_SIZE:
|
|
108
|
+
_CHANGED_CACHE.popitem(last=False)
|
|
109
|
+
|
|
110
|
+
with _stats_lock:
|
|
111
|
+
_stats['full_hashes'] += 1
|
|
112
|
+
|
|
113
|
+
return changed_flag, False
|
|
114
|
+
|
|
115
|
+
# ==============================================================================
|
|
116
|
+
# 指纹计算
|
|
117
|
+
# ==============================================================================
|
|
118
|
+
def _get_sample_hash(p, size, sample):
|
|
119
|
+
"""计算文件首/中/尾三处采样的 xxhash 指纹。
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
p: 已打开路径对应的 pathlib.Path 对象。
|
|
123
|
+
size: 文件字节数,用于判断是否需要分段采样。
|
|
124
|
+
sample: 每段采样字节数。
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
int: 采样内容的 xxhash64 整数指纹;读取失败时返回 0。
|
|
128
|
+
"""
|
|
129
|
+
try:
|
|
130
|
+
with p.open("rb") as f:
|
|
131
|
+
if size <= 2 * sample:
|
|
132
|
+
# 小文件:直接读取
|
|
133
|
+
return xxhash.xxh64(f.read()).intdigest()
|
|
134
|
+
else:
|
|
135
|
+
# 大文件:多位置采样
|
|
136
|
+
sample_data = f.read(sample)
|
|
137
|
+
f.seek(size // 2)
|
|
138
|
+
sample_data += f.read(sample)
|
|
139
|
+
f.seek(max(0, size - sample))
|
|
140
|
+
sample_data += f.read(sample)
|
|
141
|
+
return xxhash.xxh64(sample_data).intdigest()
|
|
142
|
+
except (OSError, IOError):
|
|
143
|
+
return 0
|
|
144
|
+
|
|
145
|
+
def _get_full_hash(p, size):
|
|
146
|
+
"""计算文件全部内容的 xxhash 指纹。
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
p: 待读取文件的 pathlib.Path 对象。
|
|
150
|
+
size: 文件字节数,超过 10 MiB 时改用分块增量哈希以限制内存占用。
|
|
151
|
+
|
|
152
|
+
Returns:
|
|
153
|
+
int: 全量内容的 xxhash64 整数指纹;读取失败时返回 0。
|
|
154
|
+
"""
|
|
155
|
+
try:
|
|
156
|
+
if size > 10 * 1024 * 1024: # 大文件增量哈希
|
|
157
|
+
hasher = xxhash.xxh64()
|
|
158
|
+
with p.open("rb") as f:
|
|
159
|
+
while chunk := f.read(64 * 1024):
|
|
160
|
+
hasher.update(chunk)
|
|
161
|
+
return hasher.intdigest()
|
|
162
|
+
else: # 小文件直接哈希
|
|
163
|
+
return xxhash.xxh64(p.read_bytes()).intdigest()
|
|
164
|
+
except (OSError, IOError):
|
|
165
|
+
return 0
|
|
166
|
+
|
|
167
|
+
# ==============================================================================
|
|
168
|
+
# 缓存维护
|
|
169
|
+
# ==============================================================================
|
|
170
|
+
def _cleanup_cache():
|
|
171
|
+
"""从缓存中移除已不存在的路径条目。
|
|
172
|
+
|
|
173
|
+
Side Effects:
|
|
174
|
+
原地删减 _CHANGED_CACHE 中 path.exists() 为假的条目。
|
|
175
|
+
"""
|
|
176
|
+
expired = [p for p in _CHANGED_CACHE if not p.exists()]
|
|
177
|
+
for p in expired:
|
|
178
|
+
_CHANGED_CACHE.pop(p, None)
|
|
179
|
+
|
|
180
|
+
# ==============================================================================
|
|
181
|
+
# 统计与缓存管理
|
|
182
|
+
# ==============================================================================
|
|
183
|
+
def get_stats():
|
|
184
|
+
"""返回当前检测统计与缓存规模的快照。
|
|
185
|
+
|
|
186
|
+
Returns:
|
|
187
|
+
dict: 含 total_checks/fast_passes/sample_passes/full_hashes/errors/cache_size 的副本;
|
|
188
|
+
当 total_checks 大于 0 时另含 fast_pass_rate 与 sample_pass_rate 两个命中率(0 到 1 的浮点数)。
|
|
189
|
+
"""
|
|
190
|
+
with _stats_lock:
|
|
191
|
+
stats = _stats.copy()
|
|
192
|
+
stats['cache_size'] = len(_CHANGED_CACHE)
|
|
193
|
+
if stats['total_checks'] > 0:
|
|
194
|
+
stats['fast_pass_rate'] = stats['fast_passes'] / stats['total_checks']
|
|
195
|
+
stats['sample_pass_rate'] = stats['sample_passes'] / stats['total_checks']
|
|
196
|
+
return stats
|
|
197
|
+
|
|
198
|
+
def remove_from_cache(path: str | pathlib.Path):
|
|
199
|
+
"""从缓存中移除指定路径并打印结果。
|
|
200
|
+
|
|
201
|
+
Args:
|
|
202
|
+
path: 待移除的文件路径,字符串或 pathlib.Path;按解析后的绝对路径匹配缓存键。
|
|
203
|
+
|
|
204
|
+
Side Effects:
|
|
205
|
+
命中时从 _CHANGED_CACHE 删除该条目,并向标准输出打印操作结果。
|
|
206
|
+
"""
|
|
207
|
+
p = pathlib.Path(path).resolve()
|
|
208
|
+
if p in _CHANGED_CACHE:
|
|
209
|
+
_CHANGED_CACHE.pop(p)
|
|
210
|
+
print(f"已从缓存中移除: {p}")
|
|
211
|
+
else:
|
|
212
|
+
print(f"路径不在缓存中: {p}")
|
|
213
|
+
|
|
214
|
+
def clear_cache_for_directory(directory: str | pathlib.Path):
|
|
215
|
+
"""清除指定目录及其子目录下所有文件的缓存并打印数量。
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
directory: 目标目录路径,字符串或 pathlib.Path;按解析后的绝对路径匹配缓存键前缀。
|
|
219
|
+
|
|
220
|
+
Side Effects:
|
|
221
|
+
从 _CHANGED_CACHE 删除所有以该目录为前缀的条目,并向标准输出打印移除数量。
|
|
222
|
+
"""
|
|
223
|
+
dir_path = pathlib.Path(directory).resolve()
|
|
224
|
+
removed_count = 0
|
|
225
|
+
|
|
226
|
+
# 收集要移除的路径
|
|
227
|
+
to_remove = [p for p in _CHANGED_CACHE if p.is_relative_to(dir_path)]
|
|
228
|
+
|
|
229
|
+
for p in to_remove:
|
|
230
|
+
_CHANGED_CACHE.pop(p)
|
|
231
|
+
removed_count += 1
|
|
232
|
+
|
|
233
|
+
print(f"已从缓存中移除 {removed_count} 个路径 (目录: {dir_path})")
|
|
234
|
+
|
|
235
|
+
# ==============================================================================
|
|
236
|
+
# 使用示例
|
|
237
|
+
# ==============================================================================
|
|
238
|
+
if __name__ == "__main__":
|
|
239
|
+
"""基础使用示例"""
|
|
240
|
+
test_file = pathlib.Path("test.txt")
|
|
241
|
+
|
|
242
|
+
# 创建测试文件
|
|
243
|
+
test_file.write_text("Hello World")
|
|
244
|
+
|
|
245
|
+
# 第一次检查 - 文件肯定改变了
|
|
246
|
+
has_changed, is_metadata_only = changed(test_file)
|
|
247
|
+
print(f"第一次检查: 改变={has_changed}, 元数据抖动={is_metadata_only}")
|
|
248
|
+
# 输出: 第一次检查: 改变=True, 元数据抖动=False
|
|
249
|
+
|
|
250
|
+
# remove_from_cache(test_file)
|
|
251
|
+
|
|
252
|
+
# 立即再次检查 - 文件没有改变
|
|
253
|
+
has_changed, is_metadata_only = changed(test_file)
|
|
254
|
+
print(f"第二次检查: 改变={has_changed}, 元数据抖动={is_metadata_only}")
|
|
255
|
+
# 输出: 第二次检查: 改变=False, 元数据抖动=False
|
|
256
|
+
|
|
257
|
+
# 修改文件内容
|
|
258
|
+
test_file.write_text("Hello World Modified")
|
|
259
|
+
|
|
260
|
+
# 检查修改后的文件
|
|
261
|
+
has_changed, is_metadata_only = changed(test_file)
|
|
262
|
+
print(f"修改后检查: 改变={has_changed}, 元数据抖动={is_metadata_only}")
|
|
263
|
+
# 输出: 修改后检查: 改变=True, 元数据抖动=False
|
|
264
|
+
|
|
265
|
+
# 只修改文件时间戳(模拟元数据抖动)
|
|
266
|
+
import os
|
|
267
|
+
current_time = time.time()
|
|
268
|
+
os.utime(test_file, (current_time, current_time))
|
|
269
|
+
|
|
270
|
+
has_changed, is_metadata_only = changed(test_file)
|
|
271
|
+
print(f"时间戳修改后: 改变={has_changed}, 元数据抖动={is_metadata_only}")
|
|
272
|
+
# 输出: 时间戳修改后: 改变=False, 元数据抖动=True
|
|
273
|
+
|
|
274
|
+
# 查看统计信息
|
|
275
|
+
print("统计信息:", get_stats())
|
|
276
|
+
|