taskqx 0.7.0.dev0__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.
- taskqx/__init__.py +118 -0
- taskqx/__main__.py +5 -0
- taskqx/admin.py +29 -0
- taskqx/broker/__init__.py +12 -0
- taskqx/broker/_time.py +25 -0
- taskqx/broker/redis.py +1665 -0
- taskqx/broker/redis_admin.py +395 -0
- taskqx/broker/redis_calls.py +387 -0
- taskqx/broker/redis_components.py +111 -0
- taskqx/broker/redis_maintenance.py +117 -0
- taskqx/broker/redis_observability.py +120 -0
- taskqx/broker/redis_scripts.py +177 -0
- taskqx/broker/redis_state_machine.py +214 -0
- taskqx/broker/sqlite.py +1385 -0
- taskqx/broker/sqlite_admin.py +469 -0
- taskqx/broker/sqlite_components.py +124 -0
- taskqx/broker/sqlite_maintenance.py +218 -0
- taskqx/broker/sqlite_migrations.py +57 -0
- taskqx/broker/sqlite_state_machine.py +363 -0
- taskqx/capabilities.py +46 -0
- taskqx/cli.py +227 -0
- taskqx/config.py +57 -0
- taskqx/consistency.py +50 -0
- taskqx/errors.py +37 -0
- taskqx/health.py +27 -0
- taskqx/interactive.py +40 -0
- taskqx/middleware.py +39 -0
- taskqx/naming.py +35 -0
- taskqx/observability.py +158 -0
- taskqx/pagination.py +43 -0
- taskqx/payloads.py +208 -0
- taskqx/protocols.py +180 -0
- taskqx/py.typed +1 -0
- taskqx/retry.py +139 -0
- taskqx/scheduler.py +134 -0
- taskqx/serialization.py +78 -0
- taskqx/shell.py +303 -0
- taskqx/submission/__init__.py +19 -0
- taskqx/submission/base.py +62 -0
- taskqx/submission/observability.py +71 -0
- taskqx/submission/redis.py +180 -0
- taskqx/submission/routing.py +93 -0
- taskqx/submission/service.py +110 -0
- taskqx/submission/sqlite.py +161 -0
- taskqx/tui.py +1048 -0
- taskqx/types.py +280 -0
- taskqx/worker.py +300 -0
- taskqx-0.7.0.dev0.dist-info/METADATA +275 -0
- taskqx-0.7.0.dev0.dist-info/RECORD +52 -0
- taskqx-0.7.0.dev0.dist-info/WHEEL +4 -0
- taskqx-0.7.0.dev0.dist-info/entry_points.txt +2 -0
- taskqx-0.7.0.dev0.dist-info/licenses/LICENSE +21 -0
taskqx/cli.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Taskqx 的安全运维命令行,仅调用公开 Broker/Admin API。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
from dataclasses import asdict, is_dataclass
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .broker import RedisBroker, SQLiteBroker
|
|
14
|
+
from .errors import ValidationError
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main(argv: list[str] | None = None) -> int:
|
|
18
|
+
parser = argparse.ArgumentParser(prog="taskqx")
|
|
19
|
+
source = parser.add_mutually_exclusive_group()
|
|
20
|
+
source.add_argument("--sqlite", metavar="PATH", default="taskqx.db")
|
|
21
|
+
source.add_argument("--redis-url", metavar="URL")
|
|
22
|
+
parser.add_argument("--namespace", default="taskqx")
|
|
23
|
+
parser.add_argument("--json", action="store_true", dest="as_json")
|
|
24
|
+
parser.add_argument("--include-payload", action="store_true")
|
|
25
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
26
|
+
queue = commands.add_parser("queue").add_subparsers(
|
|
27
|
+
dest="queue_command", required=True
|
|
28
|
+
)
|
|
29
|
+
queue.add_parser("inspect").add_argument("queue")
|
|
30
|
+
queue.add_parser("list-dead-letters").add_argument("queue")
|
|
31
|
+
queue.add_parser("check-consistency").add_argument("queue")
|
|
32
|
+
repair = queue.add_parser("repair-consistency")
|
|
33
|
+
repair.add_argument("queue")
|
|
34
|
+
repair.add_argument("--apply", action="store_true")
|
|
35
|
+
repair.add_argument("--yes", action="store_true")
|
|
36
|
+
message = commands.add_parser("message").add_subparsers(
|
|
37
|
+
dest="message_command", required=True
|
|
38
|
+
)
|
|
39
|
+
message.add_parser("inspect").add_argument("message_id")
|
|
40
|
+
dlq = commands.add_parser("dlq").add_subparsers(dest="dlq_command", required=True)
|
|
41
|
+
replay = dlq.add_parser("replay")
|
|
42
|
+
replay.add_argument("queue")
|
|
43
|
+
replay.add_argument("message_id")
|
|
44
|
+
replay.add_argument("--target-queue")
|
|
45
|
+
replay.add_argument(
|
|
46
|
+
"--dedup-mode", choices=("keep", "remove", "replace"), default="keep"
|
|
47
|
+
)
|
|
48
|
+
replay.add_argument("--yes", action="store_true")
|
|
49
|
+
commands.add_parser("health")
|
|
50
|
+
redis = commands.add_parser("redis").add_subparsers(
|
|
51
|
+
dest="redis_command", required=True
|
|
52
|
+
)
|
|
53
|
+
migrate_keyspace = redis.add_parser("migrate-keyspace")
|
|
54
|
+
migrate_keyspace.add_argument("--apply", action="store_true")
|
|
55
|
+
migrate_keyspace.add_argument("--yes", action="store_true")
|
|
56
|
+
for interactive_command in ("tui", "shell"):
|
|
57
|
+
interactive = commands.add_parser(interactive_command)
|
|
58
|
+
interactive_source = interactive.add_mutually_exclusive_group()
|
|
59
|
+
interactive_source.add_argument(
|
|
60
|
+
"--sqlite", metavar="PATH", default=argparse.SUPPRESS
|
|
61
|
+
)
|
|
62
|
+
interactive_source.add_argument(
|
|
63
|
+
"--redis-url", metavar="URL", default=argparse.SUPPRESS
|
|
64
|
+
)
|
|
65
|
+
interactive.add_argument("--namespace", default=argparse.SUPPRESS)
|
|
66
|
+
args = parser.parse_args(argv)
|
|
67
|
+
try:
|
|
68
|
+
return asyncio.run(_run(args))
|
|
69
|
+
except ValidationError as exc:
|
|
70
|
+
print(f"taskqx: error: {exc}", file=sys.stderr)
|
|
71
|
+
return 2
|
|
72
|
+
except Exception as exc: # noqa: BLE001 - surface backend connection failures cleanly to operators
|
|
73
|
+
print(
|
|
74
|
+
f"taskqx: backend unavailable: {type(exc).__name__}: {exc}",
|
|
75
|
+
file=sys.stderr,
|
|
76
|
+
)
|
|
77
|
+
return 1
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
async def _run(args: argparse.Namespace) -> int:
|
|
81
|
+
broker: SQLiteBroker | RedisBroker
|
|
82
|
+
if args.redis_url:
|
|
83
|
+
broker = RedisBroker.from_url(args.redis_url, namespace=args.namespace)
|
|
84
|
+
else:
|
|
85
|
+
broker = SQLiteBroker(args.sqlite)
|
|
86
|
+
backend = "redis" if args.redis_url else "sqlite"
|
|
87
|
+
namespace = args.namespace if args.redis_url else None
|
|
88
|
+
context = {"backend": backend, "namespace": namespace}
|
|
89
|
+
if args.command in {"tui", "shell"}:
|
|
90
|
+
return await _run_interactive(
|
|
91
|
+
args, broker, backend=backend, namespace=namespace
|
|
92
|
+
)
|
|
93
|
+
async with broker:
|
|
94
|
+
if args.command == "redis":
|
|
95
|
+
if not args.redis_url:
|
|
96
|
+
raise ValidationError("redis migrate-keyspace 需要 --redis-url")
|
|
97
|
+
assert isinstance(broker, RedisBroker)
|
|
98
|
+
if args.apply and not args.yes:
|
|
99
|
+
raise ValidationError(
|
|
100
|
+
"迁移 Redis keyspace 会改变持久化消息;请同时传入 --apply --yes"
|
|
101
|
+
)
|
|
102
|
+
return _print(
|
|
103
|
+
await broker.migrate_keyspace(dry_run=not args.apply),
|
|
104
|
+
args,
|
|
105
|
+
)
|
|
106
|
+
if args.command == "health":
|
|
107
|
+
report = await broker.health_check()
|
|
108
|
+
_print(report, args)
|
|
109
|
+
return 0 if report.healthy else 1
|
|
110
|
+
if args.command == "queue":
|
|
111
|
+
if args.queue_command == "inspect":
|
|
112
|
+
return _print(
|
|
113
|
+
{
|
|
114
|
+
**context,
|
|
115
|
+
"queue": args.queue,
|
|
116
|
+
"stats": await broker.inspect(args.queue),
|
|
117
|
+
},
|
|
118
|
+
args,
|
|
119
|
+
)
|
|
120
|
+
if args.queue_command == "list-dead-letters":
|
|
121
|
+
return _print(
|
|
122
|
+
{
|
|
123
|
+
**context,
|
|
124
|
+
"queue": args.queue,
|
|
125
|
+
"dead_letters": await broker.admin.list_dead_letters(
|
|
126
|
+
args.queue
|
|
127
|
+
),
|
|
128
|
+
},
|
|
129
|
+
args,
|
|
130
|
+
)
|
|
131
|
+
if args.queue_command == "check-consistency":
|
|
132
|
+
consistency_report = await broker.check_consistency(args.queue)
|
|
133
|
+
_print(consistency_report, args)
|
|
134
|
+
return 0 if consistency_report.consistent else 1
|
|
135
|
+
if args.apply and not args.yes:
|
|
136
|
+
raise ValidationError(
|
|
137
|
+
"修复一致性会改变持久化索引;请同时传入 --apply --yes"
|
|
138
|
+
)
|
|
139
|
+
return _print(
|
|
140
|
+
await broker.repair_consistency(args.queue, dry_run=not args.apply),
|
|
141
|
+
args,
|
|
142
|
+
)
|
|
143
|
+
if args.command == "message":
|
|
144
|
+
value = await broker.inspect_message(args.message_id)
|
|
145
|
+
if value is None:
|
|
146
|
+
raise ValidationError("未找到指定消息")
|
|
147
|
+
return _print({**context, "message": value}, args)
|
|
148
|
+
if not args.yes:
|
|
149
|
+
raise ValidationError("DLQ replay 会改变队列状态;请显式传入 --yes")
|
|
150
|
+
await broker.admin.replay_dead_letter(
|
|
151
|
+
args.queue,
|
|
152
|
+
args.message_id,
|
|
153
|
+
target_queue=args.target_queue,
|
|
154
|
+
dedup_mode=args.dedup_mode,
|
|
155
|
+
)
|
|
156
|
+
return _print(
|
|
157
|
+
{
|
|
158
|
+
**context,
|
|
159
|
+
"replayed": args.message_id,
|
|
160
|
+
"queue": args.target_queue or args.queue,
|
|
161
|
+
},
|
|
162
|
+
args,
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
async def _run_interactive(
|
|
167
|
+
args: argparse.Namespace,
|
|
168
|
+
broker: SQLiteBroker | RedisBroker,
|
|
169
|
+
*,
|
|
170
|
+
backend: str,
|
|
171
|
+
namespace: str | None,
|
|
172
|
+
) -> int:
|
|
173
|
+
if not sys.stdin.isatty() or not sys.stdout.isatty():
|
|
174
|
+
print(
|
|
175
|
+
"taskqx: error: 交互式界面需要 TTY;请改用现有 JSON CLI", file=sys.stderr
|
|
176
|
+
)
|
|
177
|
+
return 2
|
|
178
|
+
try:
|
|
179
|
+
if args.command == "tui":
|
|
180
|
+
from .tui import run_tui
|
|
181
|
+
|
|
182
|
+
return await run_tui(
|
|
183
|
+
broker,
|
|
184
|
+
backend=backend,
|
|
185
|
+
namespace=namespace,
|
|
186
|
+
)
|
|
187
|
+
from .shell import run_shell
|
|
188
|
+
|
|
189
|
+
return await run_shell(broker, backend=backend, namespace=namespace)
|
|
190
|
+
except ModuleNotFoundError as exc:
|
|
191
|
+
if exc.name in {"rich", "textual", "prompt_toolkit"}:
|
|
192
|
+
print("taskqx: error: 交互式界面需要安装 taskqx[tui]", file=sys.stderr)
|
|
193
|
+
return 2
|
|
194
|
+
raise
|
|
195
|
+
finally:
|
|
196
|
+
await broker.close()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _print(value: Any, args: argparse.Namespace) -> int:
|
|
200
|
+
rendered = _safe_value(value, include_payload=args.include_payload)
|
|
201
|
+
if args.as_json:
|
|
202
|
+
print(json.dumps(rendered, ensure_ascii=False, default=str, sort_keys=True))
|
|
203
|
+
else:
|
|
204
|
+
print(
|
|
205
|
+
json.dumps(
|
|
206
|
+
rendered, ensure_ascii=False, default=str, indent=2, sort_keys=True
|
|
207
|
+
)
|
|
208
|
+
)
|
|
209
|
+
return 0
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _safe_value(value: Any, *, include_payload: bool) -> Any:
|
|
213
|
+
if is_dataclass(value):
|
|
214
|
+
value = asdict(value) # type: ignore[arg-type] # is_dataclass 是运行时 adapter 边界
|
|
215
|
+
if isinstance(value, datetime):
|
|
216
|
+
return value.isoformat()
|
|
217
|
+
if isinstance(value, list):
|
|
218
|
+
return [_safe_value(item, include_payload=include_payload) for item in value]
|
|
219
|
+
if isinstance(value, dict):
|
|
220
|
+
return {
|
|
221
|
+
key: (item if key != "payload" or include_payload else "<redacted>")
|
|
222
|
+
for key, item in (
|
|
223
|
+
(key, _safe_value(item, include_payload=include_payload))
|
|
224
|
+
for key, item in value.items()
|
|
225
|
+
)
|
|
226
|
+
}
|
|
227
|
+
return value
|
taskqx/config.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""统一的 queue 级运行配置。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import timedelta
|
|
7
|
+
|
|
8
|
+
from .errors import ValidationError
|
|
9
|
+
from .retry import RetryPolicy
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True, slots=True)
|
|
13
|
+
class QueueConfig:
|
|
14
|
+
"""一个队列的默认策略。
|
|
15
|
+
|
|
16
|
+
单次 ``submit``/``worker`` 参数优先于此配置,此配置再优先于 broker 默认值。
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
max_attempts: int = 3
|
|
20
|
+
lease: timedelta = timedelta(minutes=5)
|
|
21
|
+
# ``None`` preserves the message-level max_attempts limit. An explicit
|
|
22
|
+
# policy adds worker-side exception classification/backoff and may impose
|
|
23
|
+
# a stricter limit, exactly like the v0.2 worker argument.
|
|
24
|
+
retry_policy: RetryPolicy | None = None
|
|
25
|
+
default_dedup_ttl: timedelta | None = None
|
|
26
|
+
max_payload_bytes: int | None = None
|
|
27
|
+
ack_tombstone_ttl: timedelta | None = None
|
|
28
|
+
|
|
29
|
+
def __post_init__(self) -> None:
|
|
30
|
+
if (
|
|
31
|
+
isinstance(self.max_attempts, bool)
|
|
32
|
+
or not isinstance(self.max_attempts, int)
|
|
33
|
+
or self.max_attempts < 1
|
|
34
|
+
):
|
|
35
|
+
raise ValidationError("QueueConfig.max_attempts 必须大于等于 1")
|
|
36
|
+
if not isinstance(self.lease, timedelta) or self.lease.total_seconds() <= 0:
|
|
37
|
+
raise ValidationError("QueueConfig.lease 必须为正数 timedelta")
|
|
38
|
+
if self.retry_policy is not None and not isinstance(
|
|
39
|
+
self.retry_policy, RetryPolicy
|
|
40
|
+
):
|
|
41
|
+
raise ValidationError("QueueConfig.retry_policy 必须是 RetryPolicy 或 None")
|
|
42
|
+
if self.default_dedup_ttl is not None and (
|
|
43
|
+
not isinstance(self.default_dedup_ttl, timedelta)
|
|
44
|
+
or self.default_dedup_ttl.total_seconds() <= 0
|
|
45
|
+
):
|
|
46
|
+
raise ValidationError("QueueConfig.default_dedup_ttl 必须为正数")
|
|
47
|
+
if self.max_payload_bytes is not None and (
|
|
48
|
+
isinstance(self.max_payload_bytes, bool)
|
|
49
|
+
or not isinstance(self.max_payload_bytes, int)
|
|
50
|
+
or self.max_payload_bytes <= 0
|
|
51
|
+
):
|
|
52
|
+
raise ValidationError("QueueConfig.max_payload_bytes 必须为正整数")
|
|
53
|
+
if self.ack_tombstone_ttl is not None and (
|
|
54
|
+
not isinstance(self.ack_tombstone_ttl, timedelta)
|
|
55
|
+
or self.ack_tombstone_ttl.total_seconds() <= 0
|
|
56
|
+
):
|
|
57
|
+
raise ValidationError("QueueConfig.ack_tombstone_ttl 必须为正数或 None")
|
taskqx/consistency.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Read-only integrity reports and explicit repair results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class ConsistencyIssue:
|
|
10
|
+
"""A broken persisted lifecycle invariant."""
|
|
11
|
+
|
|
12
|
+
name: str
|
|
13
|
+
message_id: str | None = None
|
|
14
|
+
detail: str | None = None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class ConsistencyReport:
|
|
19
|
+
"""All issues found for one queue; an empty list means consistent."""
|
|
20
|
+
|
|
21
|
+
queue: str
|
|
22
|
+
backend: str
|
|
23
|
+
namespace: str | None
|
|
24
|
+
issues: tuple[ConsistencyIssue, ...]
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def consistent(self) -> bool:
|
|
28
|
+
return not self.issues
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class RepairReport:
|
|
33
|
+
"""The repair actions proposed or applied for a consistency report."""
|
|
34
|
+
|
|
35
|
+
queue: str
|
|
36
|
+
backend: str
|
|
37
|
+
namespace: str | None
|
|
38
|
+
dry_run: bool
|
|
39
|
+
repairs: tuple[ConsistencyIssue, ...]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class KeyspaceMigrationReport:
|
|
44
|
+
"""Result of an explicit Redis message-keyspace migration."""
|
|
45
|
+
|
|
46
|
+
namespace: str
|
|
47
|
+
dry_run: bool
|
|
48
|
+
migrated: tuple[str, ...]
|
|
49
|
+
resumed: tuple[str, ...]
|
|
50
|
+
conflicts: tuple[ConsistencyIssue, ...]
|
taskqx/errors.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Taskqx 的领域异常。"""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class TaskqxError(Exception):
|
|
5
|
+
"""所有 Taskqx 异常的基类。"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ValidationError(TaskqxError, ValueError):
|
|
9
|
+
"""调用参数或消息内容不符合公共契约。"""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LeaseLostError(TaskqxError):
|
|
13
|
+
"""投递租约已失效,当前消费者不再能改变消息状态。"""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class UnsupportedCapabilityError(TaskqxError):
|
|
17
|
+
"""当前 backend 未提供调用方所请求的能力。"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SerializerUnavailableError(ValidationError):
|
|
21
|
+
"""历史消息所需的 serializer 未注册或不可用。"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class PayloadDecodingError(TaskqxError):
|
|
25
|
+
"""类型化 payload 不兼容;Worker 会将原始 envelope 作为 poison message 写入 DLQ。"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class BrokerClosedError(TaskqxError):
|
|
29
|
+
"""broker 或消费者已经关闭。"""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RetryableError(TaskqxError):
|
|
33
|
+
"""提示高层 Worker 该失败可按 RetryPolicy 重试。"""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class RejectMessage(TaskqxError):
|
|
37
|
+
"""提示高层 Worker 直接拒绝当前消息并写入 DLQ。"""
|
taskqx/health.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Structured, backend-neutral diagnostic results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
HealthStatus = Literal["ok", "warning", "error"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True, slots=True)
|
|
12
|
+
class HealthCheck:
|
|
13
|
+
"""One non-mutating diagnostic check performed by a broker."""
|
|
14
|
+
|
|
15
|
+
name: str
|
|
16
|
+
status: HealthStatus
|
|
17
|
+
detail: str | None = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class HealthReport:
|
|
22
|
+
"""The diagnostic result returned by :meth:`TaskBroker.health_check`."""
|
|
23
|
+
|
|
24
|
+
healthy: bool
|
|
25
|
+
backend: str
|
|
26
|
+
namespace: str | None
|
|
27
|
+
checks: tuple[HealthCheck, ...]
|
taskqx/interactive.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Shared safe rendering for optional interactive operations clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import asdict, is_dataclass
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def safe_value(value: Any, *, include_payload: bool = False) -> Any:
|
|
12
|
+
"""Convert public API values for display without leaking payload by default."""
|
|
13
|
+
|
|
14
|
+
if is_dataclass(value):
|
|
15
|
+
value = asdict(value) # type: ignore[arg-type] # Runtime display adapter boundary.
|
|
16
|
+
if isinstance(value, datetime):
|
|
17
|
+
return value.isoformat()
|
|
18
|
+
if isinstance(value, list | tuple):
|
|
19
|
+
return [safe_value(item, include_payload=include_payload) for item in value]
|
|
20
|
+
if isinstance(value, dict):
|
|
21
|
+
return {
|
|
22
|
+
key: item if key != "payload" or include_payload else "<redacted>"
|
|
23
|
+
for key, item in (
|
|
24
|
+
(key, safe_value(item, include_payload=include_payload))
|
|
25
|
+
for key, item in value.items()
|
|
26
|
+
)
|
|
27
|
+
}
|
|
28
|
+
return value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def render_json(value: Any, *, include_payload: bool = False) -> str:
|
|
32
|
+
"""Return stable, copyable JSON suitable for a terminal view."""
|
|
33
|
+
|
|
34
|
+
return json.dumps(
|
|
35
|
+
safe_value(value, include_payload=include_payload),
|
|
36
|
+
ensure_ascii=False,
|
|
37
|
+
default=str,
|
|
38
|
+
indent=2,
|
|
39
|
+
sort_keys=True,
|
|
40
|
+
)
|
taskqx/middleware.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""不改变状态机语义的异步生命周期钩子。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import logging
|
|
7
|
+
from collections.abc import Awaitable, Callable
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
Hook = Callable[..., Awaitable[None] | None]
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Middleware:
|
|
15
|
+
"""轻量钩子容器,适合接入日志、指标和链路追踪。"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, *, fail_fast: bool = False) -> None:
|
|
18
|
+
self._hooks: dict[str, list[Hook]] = {}
|
|
19
|
+
self.fail_fast = fail_fast
|
|
20
|
+
|
|
21
|
+
def add(self, event: str, hook: Hook) -> None:
|
|
22
|
+
"""注册一个事件钩子。钩子不得修改传入的不可变消息。"""
|
|
23
|
+
|
|
24
|
+
self._hooks.setdefault(event, []).append(hook)
|
|
25
|
+
|
|
26
|
+
async def emit(self, event: str, *args: Any) -> None:
|
|
27
|
+
"""按注册顺序执行一个事件的所有钩子。"""
|
|
28
|
+
|
|
29
|
+
for hook in self._hooks.get(event, []):
|
|
30
|
+
try:
|
|
31
|
+
result = hook(*args)
|
|
32
|
+
if inspect.isawaitable(result):
|
|
33
|
+
await result
|
|
34
|
+
except Exception:
|
|
35
|
+
if self.fail_fast:
|
|
36
|
+
raise
|
|
37
|
+
logger.exception(
|
|
38
|
+
"taskqx middleware hook failed", extra={"event": event}
|
|
39
|
+
)
|
taskqx/naming.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""统一的持久化标识命名规则。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from .errors import ValidationError
|
|
8
|
+
|
|
9
|
+
_VALID_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
|
10
|
+
MAX_NAME_LENGTH = 128
|
|
11
|
+
_LEGACY_NAME = re.compile(r"^[A-Za-z0-9._-]+$")
|
|
12
|
+
LEGACY_MAX_NAME_LENGTH = 255
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def validate_persistent_name(
|
|
16
|
+
value: str, *, label: str, allow_legacy: bool = False
|
|
17
|
+
) -> None:
|
|
18
|
+
"""校验会直接进入 SQLite/Redis 键空间的稳定名称。
|
|
19
|
+
|
|
20
|
+
``allow_legacy`` 只用于读取 v0.2 已持久化名称;新部署应始终使用默认规则。
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
pattern = _LEGACY_NAME if allow_legacy else _VALID_NAME
|
|
24
|
+
maximum = LEGACY_MAX_NAME_LENGTH if allow_legacy else MAX_NAME_LENGTH
|
|
25
|
+
if (
|
|
26
|
+
not isinstance(value, str)
|
|
27
|
+
or not value
|
|
28
|
+
or len(value) > maximum
|
|
29
|
+
or pattern.fullmatch(value) is None
|
|
30
|
+
or set(value) <= {".", "-"}
|
|
31
|
+
):
|
|
32
|
+
expression = (
|
|
33
|
+
"[A-Za-z0-9._-]+" if allow_legacy else "[A-Za-z0-9][A-Za-z0-9._-]{0,127}"
|
|
34
|
+
)
|
|
35
|
+
raise ValidationError(f"{label} 必须匹配 {expression} 且长度不超过 {maximum}")
|
taskqx/observability.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""可替换的指标与结构化生命周期事件。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from typing import Any, Protocol
|
|
9
|
+
|
|
10
|
+
from .middleware import Middleware
|
|
11
|
+
from .types import TaskMessage, utc_now
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class EventSink(Protocol):
|
|
17
|
+
async def emit(self, event: TaskqxEvent) -> None: ...
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class MetricsSink(Protocol):
|
|
21
|
+
"""v0.2-compatible metrics contract."""
|
|
22
|
+
|
|
23
|
+
async def increment(self, name: str, value: int = 1, **labels: str) -> None: ...
|
|
24
|
+
async def observe(self, name: str, value: float, **labels: str) -> None: ...
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class GaugeMetricsSink(MetricsSink, Protocol):
|
|
28
|
+
"""Optional v0.3 extension for instantaneous queue measurements."""
|
|
29
|
+
|
|
30
|
+
async def gauge(self, name: str, value: float, **labels: str) -> None: ...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True, slots=True)
|
|
34
|
+
class TaskqxEvent:
|
|
35
|
+
"""Stable v0.3 event delivered to :class:`EventSink`."""
|
|
36
|
+
|
|
37
|
+
event_name: str
|
|
38
|
+
timestamp: datetime
|
|
39
|
+
queue: str
|
|
40
|
+
message_id: str
|
|
41
|
+
delivery_id: str | None = None
|
|
42
|
+
consumer_id: str | None = None
|
|
43
|
+
attempt: int | None = None
|
|
44
|
+
status: str | None = None
|
|
45
|
+
reason: str | None = None
|
|
46
|
+
error_type: str | None = None
|
|
47
|
+
backend: str | None = None
|
|
48
|
+
serializer_name: str | None = None
|
|
49
|
+
serializer_version: str | None = None
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def name(self) -> str:
|
|
53
|
+
"""Convenience spelling for consumers shared with legacy middleware."""
|
|
54
|
+
return self.event_name
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class BrokerEvent:
|
|
59
|
+
"""v0.2 middleware event shape, kept source- and positional-compatible."""
|
|
60
|
+
|
|
61
|
+
name: str
|
|
62
|
+
timestamp: datetime
|
|
63
|
+
queue: str
|
|
64
|
+
message_id: str
|
|
65
|
+
status: str | None = None
|
|
66
|
+
delivery_id: str | None = None
|
|
67
|
+
attempt: int | None = None
|
|
68
|
+
consumer_id: str | None = None
|
|
69
|
+
reason: str | None = None
|
|
70
|
+
serializer_name: str | None = None
|
|
71
|
+
serializer_version: str | None = None
|
|
72
|
+
error_type: str | None = None
|
|
73
|
+
backend: str | None = None
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def event_name(self) -> str:
|
|
77
|
+
return self.name
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
async def metric(
|
|
81
|
+
metrics: MetricsSink | None, name: str, value: float = 1, **labels: str
|
|
82
|
+
) -> None:
|
|
83
|
+
if metrics is None:
|
|
84
|
+
return
|
|
85
|
+
try:
|
|
86
|
+
gauge = getattr(metrics, "gauge", None)
|
|
87
|
+
if name in {"queue_ready", "queue_leased", "queue_delayed"} and callable(gauge):
|
|
88
|
+
await gauge(name, value, **labels)
|
|
89
|
+
elif isinstance(value, int):
|
|
90
|
+
await metrics.increment(name, value, **labels)
|
|
91
|
+
else:
|
|
92
|
+
await metrics.observe(name, value, **labels)
|
|
93
|
+
except Exception:
|
|
94
|
+
logger.exception("taskqx metrics sink failed", extra={"metric": name})
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
async def event(
|
|
98
|
+
middleware: Middleware,
|
|
99
|
+
name: str,
|
|
100
|
+
message: TaskMessage,
|
|
101
|
+
*,
|
|
102
|
+
status: str | None = None,
|
|
103
|
+
delivery: Any | None = None,
|
|
104
|
+
delivery_id: str | None = None,
|
|
105
|
+
consumer_id: str | None = None,
|
|
106
|
+
attempt: int | None = None,
|
|
107
|
+
reason: str | None = None,
|
|
108
|
+
error_type: str | None = None,
|
|
109
|
+
backend: str | None = None,
|
|
110
|
+
event_sink: EventSink | None = None,
|
|
111
|
+
serializer_name: str | None = None,
|
|
112
|
+
serializer_version: str | None = None,
|
|
113
|
+
) -> None:
|
|
114
|
+
delivery_id = (
|
|
115
|
+
getattr(delivery, "delivery_id", None) if delivery is not None else delivery_id
|
|
116
|
+
)
|
|
117
|
+
consumer_id = (
|
|
118
|
+
getattr(delivery, "consumer_id", None) if delivery is not None else consumer_id
|
|
119
|
+
)
|
|
120
|
+
attempt = getattr(delivery, "attempt", None) if delivery is not None else attempt
|
|
121
|
+
item = TaskqxEvent(
|
|
122
|
+
event_name=name,
|
|
123
|
+
timestamp=utc_now(),
|
|
124
|
+
queue=message.queue,
|
|
125
|
+
message_id=message.id,
|
|
126
|
+
delivery_id=delivery_id,
|
|
127
|
+
consumer_id=consumer_id,
|
|
128
|
+
attempt=attempt,
|
|
129
|
+
status=status,
|
|
130
|
+
reason=reason,
|
|
131
|
+
error_type=error_type,
|
|
132
|
+
backend=backend,
|
|
133
|
+
serializer_name=serializer_name,
|
|
134
|
+
serializer_version=serializer_version,
|
|
135
|
+
)
|
|
136
|
+
await middleware.emit(
|
|
137
|
+
"event",
|
|
138
|
+
BrokerEvent(
|
|
139
|
+
name,
|
|
140
|
+
item.timestamp,
|
|
141
|
+
item.queue,
|
|
142
|
+
item.message_id,
|
|
143
|
+
item.status,
|
|
144
|
+
item.delivery_id,
|
|
145
|
+
item.attempt,
|
|
146
|
+
item.consumer_id,
|
|
147
|
+
item.reason,
|
|
148
|
+
item.serializer_name,
|
|
149
|
+
item.serializer_version,
|
|
150
|
+
item.error_type,
|
|
151
|
+
item.backend,
|
|
152
|
+
),
|
|
153
|
+
)
|
|
154
|
+
if event_sink is not None:
|
|
155
|
+
try:
|
|
156
|
+
await event_sink.emit(item)
|
|
157
|
+
except Exception:
|
|
158
|
+
logger.exception("taskqx event sink failed", extra={"event": name})
|