convenience-toolkit 0.0.1__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.
@@ -0,0 +1,474 @@
1
+ Metadata-Version: 2.4
2
+ Name: convenience-toolkit
3
+ Version: 0.0.1
4
+ Summary: 一组开箱即用的便利工具:文件变化检测、文件监听、响应式引擎、SQLite 连接池、有限状态机。
5
+ Author: Revision-Extra
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://pypi.org/project/convenience-toolkit/
8
+ Project-URL: Repository, https://pypi.org/project/convenience-toolkit/
9
+ Keywords: file-watch,file-change,reactive,sqlite-pool,state-machine,toolkit
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ Requires-Dist: xxhash>=3.0
20
+ Requires-Dist: watchdog>=4.0
21
+ Requires-Dist: DBUtils>=3.0
22
+ Provides-Extra: all
23
+ Requires-Dist: xxhash>=3.0; extra == "all"
24
+ Requires-Dist: watchdog>=4.0; extra == "all"
25
+ Requires-Dist: DBUtils>=3.0; extra == "all"
26
+
27
+ # convenience-toolkit(便利工具箱)
28
+
29
+ 一组开箱即用的 Python 便利工具,把五个常用模块打包成一个可统一安装的工具箱。支持 `pip` 与 `uv` 安装,当前版本 `0.0.1`。
30
+
31
+ - 版本号:`0.0.1`
32
+ - Python 要求:`>=3.10`
33
+ - 许可:MIT
34
+
35
+ > 本页所有示例代码均已逐条实际运行验证通过(含文件监听的真实事件触发、异步状态机等)。
36
+
37
+ ---
38
+
39
+ ## 工具一览
40
+
41
+ | # | 子模块 | 核心类 / 函数 | 作用 | 外部依赖 |
42
+ |---|--------|---------------|------|----------|
43
+ | 1 | `file_change` | `changed()`、`get_stats()`、`remove_from_cache()`、`clear_cache_for_directory()` | 文件变化检测:大小/修改时间 → 采样哈希 → 全量哈希三级判定,带 LRU 指纹缓存与命中统计 | `xxhash` |
44
+ | 2 | `file_watch` | `Watcher`、`CustomEventHandler`、`EventHandler`、`debounce()` | 文件系统监听:基于 watchdog,支持递归、去抖、黑白名单过滤、线程池提交回调、退出清理 | `watchdog>=4.0` |
45
+ | 3 | `reactive_engine` | `ReactiveEngine`、`Observable`、`Computed`、`Effect`、`watch()` | 响应式编程引擎:依赖自动追踪、计算节点缓存、副作用调度、依赖图与环检测、DI 容器 | 无(纯标准库) |
46
+ | 4 | `sqlite_pool_manager` | `SQLitePoolManager`、`SQLiteGenericCRUD`、`GenericSQLBuilder` | SQLite 连接池(线程专用连接)+ 通用 CRUD,建库/建表/查询/批量写入 | `DBUtils` |
47
+ | 5 | `state_machine` | `StateMachine`、`State`、`Transition` | 有限状态机:同步/异步 API、守卫/动作/回调、通配符、快照恢复、Mermaid 可视化 | 无(纯标准库) |
48
+
49
+ ---
50
+
51
+ ## 安装
52
+
53
+ 本工具箱发布在 PyPI,可用 `pip` 或 `uv` 安装。
54
+
55
+ ```bash
56
+ # 用 pip 安装
57
+ pip install convenience-toolkit
58
+
59
+ # 用 uv 安装到当前环境(类似 pip install)
60
+ uv pip install convenience-toolkit
61
+
62
+ # 用 uv 作为项目依赖管理(写入 pyproject.toml 与 uv.lock)
63
+ uv add convenience-toolkit
64
+ ```
65
+
66
+ 安装后验证版本:
67
+
68
+ ```bash
69
+ python -c "import convenience_toolkit as ct; print(ct.__version__)" # 期望输出:0.0.1
70
+ ```
71
+
72
+ ---
73
+
74
+ ## 通用导入方式
75
+
76
+ ```python
77
+ # 方式一:从顶层直接导入常用符号(内部按需惰性加载)
78
+ from convenience_toolkit import changed, Observable, StateMachine, SQLitePoolManager
79
+
80
+ # 方式二:导入具体子模块(符号最全、来源最清晰,推荐)
81
+ from convenience_toolkit.file_change import changed
82
+ from convenience_toolkit.file_watch import Watcher, CustomEventHandler
83
+ from convenience_toolkit.reactive_engine import ReactiveEngine
84
+ from convenience_toolkit.sqlite_pool_manager import SQLitePoolManager, SQLiteGenericCRUD
85
+ from convenience_toolkit.state_machine import StateMachine
86
+ ```
87
+
88
+ **导入流程与说明**:顶层 `convenience_toolkit` 用惰性加载(PEP 562 `__getattr__`)——只有当真正访问某个符号时才加载对应子模块。参数无;返回对应符号的引用。这样即使某个子模块的可选依赖暂未安装,也不影响其它工具的使用。
89
+
90
+ ---
91
+
92
+ ## 1. file_change —— 文件变化检测
93
+
94
+ ### 导入
95
+
96
+ ```python
97
+ from convenience_toolkit.file_change import (
98
+ changed, get_stats, remove_from_cache, clear_cache_for_directory,
99
+ )
100
+ ```
101
+
102
+ ### API 参数表
103
+
104
+ | 函数 | 签名 | 参数意义与可选值 | 返回 |
105
+ |------|------|------------------|------|
106
+ | `changed` | `changed(path, /, sample=4096)` | `path`:文件/目录路径(`str` 或 `pathlib.Path`),位置参数;`sample`:采样检查每段读取字节数,默认 4096,值越大采样覆盖越全、开销越高 | `Tuple[bool, bool]`:`(内容是否变化, 是否仅元数据抖动)` |
107
+ | `get_stats` | `get_stats()` | 无参数 | 统计 dict:`total_checks/fast_passes/sample_passes/full_hashes/errors/cache_size/...` |
108
+ | `remove_from_cache` | `remove_from_cache(path)` | `path`:要从指纹缓存移除的路径 | `None` |
109
+ | `clear_cache_for_directory` | `clear_cache_for_directory(directory)` | `directory`:目录路径,清除其下所有缓存条目 | `None` |
110
+
111
+ **判定流程**:先用文件大小 + mtime 快速比对 → 命中则判定未变;否则读采样哈希 → 仍一致则读全量 xxhash。返回第二项用于区分“只有元数据变了但内容没变”的抖动。
112
+
113
+ ### 使用示例(已验证)
114
+
115
+ ```python
116
+ from convenience_toolkit.file_change import changed, get_stats
117
+
118
+ path = "example.txt"
119
+ open(path, "w", encoding="utf-8").write("hello")
120
+
121
+ # 流程第 1 步:首次调用建立基线缓存。
122
+ # 参数 path 是位置参数(签名里 "/" 之前不接受关键字);sample 省略用默认 4096。
123
+ c0, meta0 = changed(path)
124
+
125
+ # 流程第 2 步:内容没变时再次检测,返回 (False, False)。
126
+ c1, meta1 = changed(path)
127
+ assert (c1, meta1) == (False, False)
128
+
129
+ # 流程第 3 步:追加内容后检测,第一项为 True(内容已变)。
130
+ open(path, "a", encoding="utf-8").write(" world")
131
+ c2, meta2 = changed(path)
132
+ assert c2 is True
133
+
134
+ # 流程第 4 步:查看命中率统计,确认缓存工作机制。
135
+ print(c0, meta0, c1, meta1, c2, meta2)
136
+ print(get_stats())
137
+ ```
138
+
139
+ ---
140
+
141
+ ## 2. file_watch —— 文件系统监听
142
+
143
+ ### 导入
144
+
145
+ ```python
146
+ from convenience_toolkit.file_watch import Watcher, CustomEventHandler, EventHandler, debounce
147
+ ```
148
+
149
+ ### API 参数表
150
+
151
+ | 名称 | 签名 | 参数意义与可选值 |
152
+ |------|------|------------------|
153
+ | `Watcher.start_watching` | `start_watching(paths, EventHandler)` | `paths`:路径列表,元素为路径字符串或 `(路径, 是否递归)` 元组,不存在的路径跳过;`EventHandler`:处理器**类**(自动实例化)或**实例**。该方法**阻塞**直到停止事件置位 |
154
+ | `Watcher.add_watch` | `add_watch(paths, EventHandler)` | 参数同上,向已启动的观察器追加监听(非阻塞) |
155
+ | `Watcher.stop_watch` | `stop_watch(watch)` | `watch`:路径字符串 / 台账 dict / `ObservedWatch` 对象,其他类型抛 `TypeError` |
156
+ | `Watcher.get_watches` | `get_watches()` | 无参数,返回 `list[tuple[路径, 是否递归]]` |
157
+ | `CustomEventHandler` | 抽象基类 | 子类**必须实现 5 个抽象方法**:`on_any_event_handle`、`on_moved_handle`、`on_created_handle`、`on_deleted_handle`、`on_modified_handle`;自带 `add_white_list`/`add_black_list` 等过滤方法 |
158
+ | `EventHandler` | 具体类 | 可直接实例化的最小处理器(把事件打印出来) |
159
+ | `debounce` | `@debounce(delay=0.5)` | `delay`:去抖等待秒数(float,默认 0.5)。装饰签名为 `(self, event)` 的处理器方法;同一实例+同一路径的新事件会取消旧定时器,只执行最后一次。无返回值 |
160
+
161
+ **事件处理流程**:模块加载 → `start_watching`(内部创建单例 Observer,注册路径并初始化指纹缓存)→ watchdog 回调线程分发事件 → 基类做黑白名单过滤与去抖 → 调用子类 `on_*_handle` → `stop_watch` 清理过滤名单与缓存。
162
+
163
+ ### 使用示例(已验证:真实创建文件触发事件)
164
+
165
+ ```python
166
+ from convenience_toolkit.file_watch import Watcher, CustomEventHandler
167
+ import os, threading, time
168
+
169
+ # 步骤 1:继承 CustomEventHandler,实现全部 5 个抽象方法。
170
+ # 参数 event 是 watchdog 的事件对象,event.src_path 为源路径。
171
+ class MyHandler(CustomEventHandler):
172
+ def __init__(self):
173
+ super().__init__()
174
+ self.events = []
175
+ def on_any_event_handle(self, event): # 通用事件(基类要求,示例中留空)
176
+ pass
177
+ def on_created_handle(self, event): # 创建:文件名
178
+ self.events.append(("created", os.path.basename(event.src_path)))
179
+ def on_modified_handle(self, event): # 修改
180
+ self.events.append(("modified", os.path.basename(event.src_path)))
181
+ def on_deleted_handle(self, event): # 删除
182
+ self.events.append(("deleted", os.path.basename(event.src_path)))
183
+ def on_moved_handle(self, event): # 移动/重命名
184
+ self.events.append(("moved", os.path.basename(event.src_path)))
185
+
186
+ os.makedirs("watch_demo", exist_ok=True)
187
+ handler = MyHandler()
188
+
189
+ # 步骤 2:start_watching 会阻塞,放到子线程。
190
+ # 参数 paths=["watch_demo"] 表示监听该目录(默认递归);第二个参数传处理器实例。
191
+ t = threading.Thread(target=Watcher.start_watching, args=(["watch_demo"], handler), daemon=True)
192
+ t.start()
193
+ time.sleep(0.5) # 等待观察器就绪
194
+
195
+ # 步骤 3:在别处触发一个创建事件
196
+ with open("watch_demo/a.txt", "w", encoding="utf-8") as f:
197
+ f.write("hello")
198
+ time.sleep(1.2)
199
+
200
+ # 步骤 4:停止监听。参数传路径字符串即可按目标目录匹配。
201
+ Watcher.stop_watch("watch_demo")
202
+ print(handler.events) # 期望类似 [('created','a.txt'), ('modified','a.txt')]
203
+ ```
204
+
205
+ 黑白名单与去抖(已验证):
206
+
207
+ ```python
208
+ from convenience_toolkit.file_watch import debounce
209
+ from watchdog.events import FileModifiedEvent
210
+
211
+ h = MyHandler()
212
+ h.add_white_list("watch_demo/a.txt") # 白名单:只关心这些路径
213
+ h.add_black_list("watch_demo/tmp.log") # 黑名单:排除这些路径(参数均为可变数量路径)
214
+
215
+ class DebouncedHandler(CustomEventHandler):
216
+ def __init__(self):
217
+ super().__init__()
218
+ self.fired = []
219
+ def on_any_event_handle(self, event): pass
220
+ def on_moved_handle(self, event): pass
221
+ def on_deleted_handle(self, event): pass
222
+ @debounce(0.1) # delay=0.1 秒;连续多次同路径事件只触发最后一次
223
+ def on_modified_handle(self, event):
224
+ self.fired.append(event.src_path)
225
+ @debounce(0.1)
226
+ def on_created_handle(self, event):
227
+ self.fired.append(event.src_path)
228
+
229
+ dh = DebouncedHandler()
230
+ for _ in range(5): # 连发 5 次同一路径的修改事件
231
+ dh.on_modified_handle(FileModifiedEvent("x.txt"))
232
+ # 等待 0.25 秒后 dh.fired == ["x.txt"](只触发一次)
233
+ ```
234
+
235
+ ---
236
+
237
+ ## 3. reactive_engine —— 响应式编程引擎
238
+
239
+ ### 导入
240
+
241
+ ```python
242
+ from convenience_toolkit.reactive_engine import ReactiveEngine, WatchOptions
243
+ ```
244
+
245
+ ### API 参数表
246
+
247
+ | 名称 | 签名 | 参数意义与可选值 | 返回 |
248
+ |------|------|------------------|------|
249
+ | `ReactiveEngine.observe` | `observe(initial)` | `initial`:初始值,任意类型 | `Observable`,用 `.get()` 读、`.set(v)` 写 |
250
+ | `ReactiveEngine.computed` | `computed(fn)` | `fn`:无参计算函数,内部读取 Observable 即建立依赖 | `Computed`,用 `.get()` 取值(带缓存,依赖变化时重算) |
251
+ | `ReactiveEngine.effect` | `effect(fn=None, priority=EffectPriority.NORMAL)` | `fn`:副作用函数(同步/`async def`);`None` 时返回装饰器工厂;`priority`:`EffectPriority` 枚举(如 `NORMAL`)控制调度优先级 | `Effect`(**创建时自动执行一次**,依赖变化自动重跑) |
252
+ | `ReactiveEngine.watch` | `watch(source, callback, options=WatchOptions())` | `source`:单个或列表形式的 Observable/Computed;`callback(new, old)`:变化回调;`options`:`WatchOptions` | `WatchHandle`,`.stop()` 停止监听 |
253
+ | `WatchOptions` | dataclass | `immediate`:创建时立即执行回调(默认 `False`);`deep`:深度监听占位(默认 `False`);`once`:触发一次后自动停止(默认 `False`) | — |
254
+
255
+ **响应式流程**:`observe` 建状态 → `computed` 声明派生值(自动追踪依赖)→ `effect` 声明副作用(创建即运行并建立依赖)→ `.set()` 改状态触发依赖图中受影响的 Computed 重算与 Effect 重跑 → `watch` 显式监听并回调 → `.stop()` 停止。
256
+
257
+ ### 使用示例(已验证)
258
+
259
+ ```python
260
+ from convenience_toolkit.reactive_engine import ReactiveEngine, WatchOptions
261
+
262
+ engine = ReactiveEngine()
263
+
264
+ # 步骤 1:创建可观察状态,initial=1
265
+ count = engine.observe(1)
266
+
267
+ # 步骤 2:创建计算节点,lambda 内读取 count.get() 即建立依赖
268
+ doubled = engine.computed(lambda: count.get() * 2)
269
+
270
+ # 步骤 3:创建副作用。@engine.effect 在装饰(创建 Effect)时就会自动执行一次;
271
+ # 之后 count 变化导致 doubled 变化时,副作用自动重跑。
272
+ seen = []
273
+ @engine.effect
274
+ def log_effect():
275
+ seen.append(doubled.get())
276
+ # 此刻 seen == [2]
277
+
278
+ # 步骤 4:改状态,触发自动重算与副作用
279
+ count.set(3)
280
+ assert doubled.get() == 6 and seen[-1] == 6
281
+
282
+ # 步骤 5:显式 watch。WatchOptions(immediate=True) 表示创建时立即回调一次;
283
+ # 回调收到 (new, old),immediate 那次 old==new==当前值。
284
+ hits = []
285
+ handle = engine.watch(count, lambda new, old: hits.append((old, new)),
286
+ WatchOptions(immediate=True))
287
+ count.set(5) # 触发回调 (3, 5)
288
+ handle.stop() # 停止监听,之后不再回调
289
+ print(seen, hits) # 期望 seen=[2,6,10],hits 末项=(3,5)
290
+ ```
291
+
292
+ `Observable` 还支持 `.on_before_change(cb)` / `.on_after_change(cb)` / `.on_dispose(cb)` 注册生命周期回调(参数 `cb(old, new)` 或 `cb()`,返回自身支持链式调用)。
293
+
294
+ ---
295
+
296
+ ## 4. sqlite_pool_manager —— SQLite 连接池与 CRUD
297
+
298
+ ### 导入
299
+
300
+ ```python
301
+ from convenience_toolkit.sqlite_pool_manager import SQLitePoolManager, SQLiteGenericCRUD
302
+ ```
303
+
304
+ ### API 参数表
305
+
306
+ | 类 / 方法 | 签名 | 参数意义与可选值 | 返回 |
307
+ |-----------|------|------------------|------|
308
+ | `SQLitePoolManager` | `__init__(database_path="sqlite.db", **kwargs)` | `database_path`:库文件路径(默认 `sqlite.db`);`kwargs` 覆盖 PersistentDB 连接参数(如 `maxusage`、`ping`) | 实例 |
309
+ | `.create_database` | `create_database(force=False)` | `force=True` 时先删旧库再建(默认 `False`) | `bool` |
310
+ | `.create_table` | `create_table(table_name, columns, primary_key=None, if_not_exists=True)` | `columns`:字段名字典 `{字段名: 类型串}`;`primary_key`:主键字段名或 `None`;`if_not_exists`:加 `IF NOT EXISTS`(默认 `True`) | `bool` |
311
+ | `.execute_sql` | `execute_sql(sql, params=None)` | `sql`:非查询语句;`params`:占位符参数元组或 `None` | 影响行数 |
312
+ | `.query_sql` | `query_sql(sql, params=None, fetch_one=False)` | `fetch_one=True` 只取一条(返回空列表或单元素列表),默认取全部 | 元组列表 |
313
+ | `.list_tables` / `.table_exists` / `.drop_table` | 见源码 | 表管理 | 视方法而定 |
314
+ | `.close_pool_connections` | 无参 | 关闭池连接,下次取用自动重建 | 关闭数量 |
315
+ | `SQLiteGenericCRUD.insert` | `insert(table_name, data)` | `data`:`{列: 值}` | 影响行数 |
316
+ | `.insert_many` | `insert_many(table_name, data_list)` | `data_list`:字典列表,列名取第一条的键 | 影响行数 |
317
+ | `.select` | `select(table_name, columns=None, conditions=None, order_by=None, limit=None, fetch_one=False)` | `columns` 默认全列;`conditions` 为 `{列: 值}` 的等值 WHERE;`order_by` 排序表达式;`limit` 行数上限 | 元组列表 |
318
+ | `.update` / `.delete` / `.count` | 见源码 | `conditions` 为 `{列: 值}`,为空表示全表 | 影响行数/计数 |
319
+
320
+ **操作流程**:建管理器 → `create_database()` 建库 → `create_table()` 建表 → 用 `SQLiteGenericCRUD` 做增删改查,或用 `execute_sql`/`query_sql` 写原生 SQL → `close_pool_connections()` 释放。
321
+
322
+ ### 使用示例(已验证)
323
+
324
+ ```python
325
+ from convenience_toolkit.sqlite_pool_manager import SQLitePoolManager, SQLiteGenericCRUD
326
+
327
+ # 步骤 1:建连接池管理器,database_path 为库文件路径
328
+ pool = SQLitePoolManager("demo.db")
329
+ assert pool.create_database() is True # force 默认 False,不覆盖已有库
330
+
331
+ # 步骤 2:建表。columns 用 {字段名: SQLite 类型};
332
+ # "id INTEGER PRIMARY KEY" 已含主键约束,primary_key 参数省略即可。
333
+ pool.create_table("users", {"id": "INTEGER PRIMARY KEY", "name": "TEXT", "age": "INTEGER"})
334
+
335
+ # 步骤 3:通用 CRUD —— 插入单条与批量
336
+ crud = SQLiteGenericCRUD(pool)
337
+ crud.insert("users", {"id": 1, "name": "张三", "age": 18})
338
+ crud.insert_many("users", [
339
+ {"id": 2, "name": "李四", "age": 20},
340
+ {"id": 3, "name": "王五", "age": 22},
341
+ ])
342
+
343
+ # 步骤 4:按条件查询(conditions 是等值匹配)
344
+ rows = crud.select("users", conditions={"age": 20})
345
+ assert rows == [(2, "李四", 20)]
346
+ assert crud.count("users") == 3
347
+
348
+ # 步骤 5:原生 SQL(占位符用 ?,参数用元组传)
349
+ print(pool.query_sql("SELECT name FROM users WHERE age > ?", (19,)))
350
+
351
+ # 步骤 6:释放连接池
352
+ pool.close_pool_connections()
353
+ ```
354
+
355
+ > 依赖:本模块需要 `DBUtils`,安装工具箱时已作为依赖自动安装。
356
+
357
+ ---
358
+
359
+ ## 5. state_machine —— 有限状态机
360
+
361
+ ### 导入
362
+
363
+ ```python
364
+ from convenience_toolkit.state_machine import StateMachine
365
+ ```
366
+
367
+ ### API 参数表
368
+
369
+ | 方法 | 签名 | 参数意义与可选值 |
370
+ |------|------|------------------|
371
+ | `StateMachine.__init__` | `(name="fsm", initial=None, context=None, *, strict=False, thread_safe=False, on_error="raise")` | `name`:名称(日志用);`initial`:初始状态,`None` 表示延迟到 `start` 指定;`context`:共享上下文字典;`strict=True` 时无可用转移抛异常(默认 `False` 静默忽略);`thread_safe=True` 启用 RLock;`on_error` 取 `"raise"` 或 `"log"` |
372
+ | `.add_state` | `(name, on_enter=None, on_exit=None, final=False, **meta)` | `name`:状态名(str/Enum);`on_enter`/`on_exit`:进入/退出回调;`final=True` 标记为终态;`**meta` 附加元数据 |
373
+ | `.add_transition` | `(source, event, target=None, guard=None, action=None, priority=0)` | `source`/`event`:源状态/事件名,`"*"` 为通配符;`target=None` 表示内部转移(不改状态);`guard`:守卫(返回假则跳过);`action`:动作;`priority`:越大越先尝试 |
374
+ | `.start` / `.trigger` | `start(initial=None)` / `trigger(event, **kwargs)` | `trigger` 别名 `fire`;`kwargs` 注入回调上下文 |
375
+ | `.can` / `.available_events` | `can(event, **kwargs)` / `available_events(state=None)` | 判断事件能否触发 / 列出可用事件 |
376
+ | 只读属性 | `.current` / `.is_final` / `.is_started` / `.history` / `.states` / `.transitions` | **均为属性,不是方法**(如 `fsm.history` 不加括号) |
377
+ | `.snapshot` / `.restore` | `snapshot()` / `restore(snap)` | 导出 / 恢复运行态 |
378
+ | `.to_mermaid` | `to_mermaid(direction="LR")` | 生成 Mermaid 状态图文本;`direction` 取 `LR`/`TB` 等 |
379
+ | 异步 API | `async_start()` / `async_trigger()` / `async_can()` / `async_reset()` | 语义同同步版,回调可为 `async def`;`async_trigger` 别名 `async_fire` |
380
+ | `StateMachine.from_dict` | `from_dict(spec, name="fsm", context=None, *, auto_start=False)` | `spec`:`{"initial", "states", "transitions"}` 字典;`states` 可为列表或映射;`transitions` 中每条为 `{"source","event","target"}` **字典**;`auto_start=True` 构建后立即启动 |
381
+
382
+ **状态流转流程**:构造(定义 name/initial/strict 等)→ `add_state` 注册状态 → `add_transition` 注册转移 → `start()` 启动 → `trigger(event)` 触发事件,内部按 `on_exit → action → on_enter` 顺序执行回调并更新状态 → 通过属性读取当前状态/历史 → `snapshot()` 持久化。回调按签名自动注入 `fsm/state/source/target/event/context/result` 等上下文键。
383
+
384
+ ### 使用示例(同步,已验证)
385
+
386
+ ```python
387
+ from convenience_toolkit.state_machine import StateMachine
388
+
389
+ # 步骤 1:构造。initial 指定初始态;thread_safe=True 启用线程锁。
390
+ fsm = StateMachine("order", initial="created", thread_safe=True)
391
+
392
+ # 步骤 2:注册状态。on_enter 回调收到 state 名;final=True 标记终态。
393
+ fsm.add_state("created", on_enter=lambda state: print("进入", state))
394
+ fsm.add_state("paid")
395
+ fsm.add_state("done", final=True)
396
+
397
+ # 步骤 3:注册转移 source --event--> target。
398
+ fsm.add_transition("created", "pay", "paid")
399
+ fsm.add_transition("paid", "ship", "done")
400
+
401
+ # 步骤 4:启动并触发事件
402
+ fsm.start()
403
+ fsm.trigger("pay") # created -> paid
404
+ fsm.trigger("ship") # paid -> done
405
+
406
+ # 步骤 5:读取只读属性与可视化(注意 history 是属性,不加括号)
407
+ assert fsm.is_final
408
+ print(fsm.history) # 期望 [('pay','created','paid'), ('ship','paid','done')]
409
+ print(fsm.to_mermaid()) # 输出 Mermaid 状态图文本
410
+ ```
411
+
412
+ ### 使用示例(异步,已验证)
413
+
414
+ ```python
415
+ import asyncio
416
+ from convenience_toolkit.state_machine import StateMachine
417
+
418
+ async def main():
419
+ # on_enter 回调可为 async def,参数按签名注入 state、fsm
420
+ async def on_enter_loading(state, fsm):
421
+ print("异步进入:", state)
422
+
423
+ fsm = StateMachine("loader", initial="idle")
424
+ fsm.add_state("idle")
425
+ fsm.add_state("loading", on_enter=on_enter_loading)
426
+ fsm.add_state("ready", final=True)
427
+ fsm.add_transition("idle", "load", "loading")
428
+ fsm.add_transition("loading", "done", "ready")
429
+
430
+ # 异步 API 需 await,回调中的 awaitable 会自动等待
431
+ await fsm.async_start()
432
+ await fsm.async_trigger("load") # 别名 async_fire
433
+ await fsm.async_trigger("done")
434
+ assert fsm.is_final
435
+
436
+ asyncio.run(main())
437
+ ```
438
+
439
+ ### 使用示例(字典一次构建,已验证)
440
+
441
+ ```python
442
+ from convenience_toolkit.state_machine import StateMachine
443
+
444
+ # spec.transitions 每条必须是字典 {source, event, target},不能用元组
445
+ fsm = StateMachine.from_dict({
446
+ "initial": "a",
447
+ "states": ["a", "b"],
448
+ "transitions": [{"source": "a", "event": "go", "target": "b"}],
449
+ }, name="simple")
450
+ fsm.start()
451
+ fsm.trigger("go")
452
+ assert fsm.current == "b"
453
+ ```
454
+
455
+ ---
456
+
457
+ ## 依赖与兼容性说明
458
+
459
+ | 依赖 | 用途 | 说明 |
460
+ |------|------|------|
461
+ | `xxhash` | `file_change` 哈希计算 | 安装工具箱时自动安装 |
462
+ | `watchdog>=4.0` | `file_watch` 文件系统事件 | 需要 4.0+ 的 `FileOpenedEvent`/`FileClosedNoWriteEvent`;自动安装 |
463
+ | `DBUtils` | `sqlite_pool_manager` 连接池 | 安装工具箱时自动安装 |
464
+
465
+ `reactive_engine` 与 `state_machine` 仅用标准库,无外部依赖。
466
+
467
+ - 同步 API 与异步 API 共存:状态机同步 API 要求回调为同步函数;异步 API 同时支持同步与 `async def` 回调。
468
+ - 不要在同一个状态机上并发混用同步与异步两套 API。
469
+
470
+ ---
471
+
472
+ ## 版本历史
473
+
474
+ - **0.0.1**:首个版本,聚合 5 个工具模块,支持 pip / uv 安装。