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.
Files changed (52) hide show
  1. taskqx/__init__.py +118 -0
  2. taskqx/__main__.py +5 -0
  3. taskqx/admin.py +29 -0
  4. taskqx/broker/__init__.py +12 -0
  5. taskqx/broker/_time.py +25 -0
  6. taskqx/broker/redis.py +1665 -0
  7. taskqx/broker/redis_admin.py +395 -0
  8. taskqx/broker/redis_calls.py +387 -0
  9. taskqx/broker/redis_components.py +111 -0
  10. taskqx/broker/redis_maintenance.py +117 -0
  11. taskqx/broker/redis_observability.py +120 -0
  12. taskqx/broker/redis_scripts.py +177 -0
  13. taskqx/broker/redis_state_machine.py +214 -0
  14. taskqx/broker/sqlite.py +1385 -0
  15. taskqx/broker/sqlite_admin.py +469 -0
  16. taskqx/broker/sqlite_components.py +124 -0
  17. taskqx/broker/sqlite_maintenance.py +218 -0
  18. taskqx/broker/sqlite_migrations.py +57 -0
  19. taskqx/broker/sqlite_state_machine.py +363 -0
  20. taskqx/capabilities.py +46 -0
  21. taskqx/cli.py +227 -0
  22. taskqx/config.py +57 -0
  23. taskqx/consistency.py +50 -0
  24. taskqx/errors.py +37 -0
  25. taskqx/health.py +27 -0
  26. taskqx/interactive.py +40 -0
  27. taskqx/middleware.py +39 -0
  28. taskqx/naming.py +35 -0
  29. taskqx/observability.py +158 -0
  30. taskqx/pagination.py +43 -0
  31. taskqx/payloads.py +208 -0
  32. taskqx/protocols.py +180 -0
  33. taskqx/py.typed +1 -0
  34. taskqx/retry.py +139 -0
  35. taskqx/scheduler.py +134 -0
  36. taskqx/serialization.py +78 -0
  37. taskqx/shell.py +303 -0
  38. taskqx/submission/__init__.py +19 -0
  39. taskqx/submission/base.py +62 -0
  40. taskqx/submission/observability.py +71 -0
  41. taskqx/submission/redis.py +180 -0
  42. taskqx/submission/routing.py +93 -0
  43. taskqx/submission/service.py +110 -0
  44. taskqx/submission/sqlite.py +161 -0
  45. taskqx/tui.py +1048 -0
  46. taskqx/types.py +280 -0
  47. taskqx/worker.py +300 -0
  48. taskqx-0.7.0.dev0.dist-info/METADATA +275 -0
  49. taskqx-0.7.0.dev0.dist-info/RECORD +52 -0
  50. taskqx-0.7.0.dev0.dist-info/WHEEL +4 -0
  51. taskqx-0.7.0.dev0.dist-info/entry_points.txt +2 -0
  52. taskqx-0.7.0.dev0.dist-info/licenses/LICENSE +21 -0
taskqx/scheduler.py ADDED
@@ -0,0 +1,134 @@
1
+ """Backend-only lifecycle scheduler.
2
+
3
+ A scheduler advances persisted message state without claiming messages or running
4
+ application handlers. Multiple scheduler processes are safe: each backend
5
+ maintenance operation is conditional and idempotent.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ from collections.abc import Iterable
13
+ from datetime import timedelta
14
+ from typing import Protocol
15
+
16
+ from typing_extensions import Self
17
+
18
+ from .errors import ValidationError
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class SchedulerBackend(Protocol):
24
+ async def maintain(self, queue: str | None = None) -> int: ...
25
+ async def _scheduler_queues(self) -> Iterable[str]: ...
26
+
27
+
28
+ class BackendScheduler:
29
+ """Periodically run backend maintenance for selected queues.
30
+
31
+ ``queues=None`` discovers persisted queues before every tick. ``run()``
32
+ starts the scheduler and waits until ``close()`` is called or its task is
33
+ cancelled. A failing tick is logged and retried on the next interval;
34
+ it never stops independent workers.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ backend: SchedulerBackend,
40
+ *,
41
+ queues: Iterable[str] | None = None,
42
+ interval: timedelta = timedelta(seconds=1),
43
+ ) -> None:
44
+ if not isinstance(interval, timedelta) or interval.total_seconds() <= 0:
45
+ raise ValidationError("scheduler interval 必须为正数 timedelta")
46
+ self._backend = backend
47
+ self._queues = tuple(queues) if queues is not None else None
48
+ self._interval = interval.total_seconds()
49
+ self._closed = False
50
+ self._task: asyncio.Task[None] | None = None
51
+ self._stopped = asyncio.Event()
52
+
53
+ async def start(self) -> None:
54
+ """Start the maintenance loop; repeated calls are idempotent."""
55
+
56
+ if self._closed:
57
+ raise ValidationError("已关闭的 scheduler 不能重新启动")
58
+ if self._task is None:
59
+ self._task = asyncio.create_task(self._loop(), name="taskqx:scheduler")
60
+
61
+ async def close(self) -> None:
62
+ """Stop future ticks and wait for the current tick to complete."""
63
+
64
+ if self._closed:
65
+ return
66
+ self._closed = True
67
+ self._stopped.set()
68
+ task = self._task
69
+ if task is not None and task is not asyncio.current_task():
70
+ await task
71
+
72
+ async def tick(self) -> int:
73
+ """Run one idempotent maintenance pass for every selected queue."""
74
+
75
+ if self._closed:
76
+ return 0
77
+ queues = (
78
+ self._queues
79
+ if self._queues is not None
80
+ else tuple(await self._backend._scheduler_queues())
81
+ )
82
+ count = 0
83
+ for queue in queues:
84
+ count += await self._backend.maintain(queue)
85
+ return count
86
+
87
+ async def run(self) -> None:
88
+ """Run until closed or externally cancelled."""
89
+
90
+ await self.start()
91
+ try:
92
+ await self._stopped.wait()
93
+ finally:
94
+ await self.close()
95
+
96
+ async def _loop(self) -> None:
97
+ try:
98
+ while not self._closed:
99
+ try:
100
+ await self.tick()
101
+ except asyncio.CancelledError:
102
+ raise
103
+ except Exception as exc:
104
+ logger.exception(
105
+ "taskqx scheduler tick failed",
106
+ extra={
107
+ "backend": type(self._backend).__name__,
108
+ "namespace": getattr(self._backend, "_namespace", None),
109
+ "queue": None,
110
+ "message_id": None,
111
+ "delivery_id": None,
112
+ "consumer_id": None,
113
+ "attempt": None,
114
+ "max_attempts": None,
115
+ "action": "maintain",
116
+ "outcome": "failed",
117
+ "retry_delay": None,
118
+ "error_type": type(exc).__name__,
119
+ },
120
+ )
121
+ try:
122
+ await asyncio.wait_for(self._stopped.wait(), timeout=self._interval)
123
+ except asyncio.TimeoutError:
124
+ pass
125
+ finally:
126
+ self._closed = True
127
+ self._stopped.set()
128
+
129
+ async def __aenter__(self) -> Self:
130
+ await self.start()
131
+ return self
132
+
133
+ async def __aexit__(self, *_: object) -> None:
134
+ await self.close()
@@ -0,0 +1,78 @@
1
+ """默认且安全的 JSON 序列化实现。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Iterable
7
+ from typing import Any, Protocol
8
+
9
+ from .errors import SerializerUnavailableError, ValidationError
10
+
11
+
12
+ class Serializer(Protocol):
13
+ """可替换的消息序列化协议。"""
14
+
15
+ name: str
16
+ version: str
17
+
18
+ def dumps(self, value: Any) -> bytes: ...
19
+ def loads(self, payload: bytes) -> Any: ...
20
+
21
+
22
+ class JsonSerializer:
23
+ """仅接收 JSON 兼容值的默认序列化器。"""
24
+
25
+ name = "json"
26
+ version = "1"
27
+
28
+ def dumps(self, value: Any) -> bytes:
29
+ """编码值,并将不可编码值转成清晰的领域异常。"""
30
+
31
+ try:
32
+ return json.dumps(
33
+ value, ensure_ascii=False, separators=(",", ":"), allow_nan=False
34
+ ).encode()
35
+ except (TypeError, ValueError) as exc:
36
+ raise ValidationError("payload 与 metadata 必须是 JSON 兼容数据") from exc
37
+
38
+ def loads(self, payload: bytes) -> Any:
39
+ """解码 JSON 字节串。"""
40
+
41
+ return json.loads(payload.decode())
42
+
43
+
44
+ class SerializerRegistry:
45
+ """按持久化 name/version 选择 decoder 的显式注册表。"""
46
+
47
+ def __init__(self, serializers: Iterable[Serializer] = ()) -> None:
48
+ self._serializers: dict[tuple[str, str], Serializer] = {}
49
+ for serializer in serializers:
50
+ self.register(serializer)
51
+
52
+ def register(self, *args: Any) -> None:
53
+ """注册 serializer;支持 ``register(serializer)`` 和显式 name/version。"""
54
+ if len(args) == 1:
55
+ serializer = args[0]
56
+ name, version = serializer.name, serializer.version
57
+ elif len(args) == 3:
58
+ name, version, serializer = args
59
+ else:
60
+ raise TypeError(
61
+ "register(serializer) 或 register(name, version, serializer)"
62
+ )
63
+ if (
64
+ not isinstance(name, str)
65
+ or not isinstance(version, str)
66
+ or not name
67
+ or not version
68
+ ):
69
+ raise ValidationError("serializer name/version 必须为非空字符串")
70
+ self._serializers[(name, version)] = serializer
71
+
72
+ def resolve(self, name: str, version: str) -> Serializer:
73
+ try:
74
+ return self._serializers[(name, version)]
75
+ except KeyError as exc:
76
+ raise SerializerUnavailableError(
77
+ f"未注册 serializer {name!r} v{version!r}"
78
+ ) from exc
taskqx/shell.py ADDED
@@ -0,0 +1,303 @@
1
+ """Optional prompt_toolkit operations shell; imports its dependency only when launched."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shlex
6
+ from datetime import timedelta
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from .interactive import render_json
11
+
12
+ _COMMANDS = (
13
+ "health",
14
+ "queues",
15
+ "queue inspect",
16
+ "messages",
17
+ "message inspect",
18
+ "payload show",
19
+ "dlq list",
20
+ "dlq replay",
21
+ "dlq delete",
22
+ "eq list",
23
+ "eq replay",
24
+ "eq delete",
25
+ "consistency repair",
26
+ "help",
27
+ "quit",
28
+ )
29
+
30
+
31
+ def _prompt(backend: str, namespace: str | None) -> str:
32
+ return f"taskqx[{backend}:{namespace or '-'}]> "
33
+
34
+
35
+ def _replay_options(arguments: list[str]) -> tuple[str | None, str, dict[str, Any]]:
36
+ """Parse bounded replay options, including a complete replacement dedup key."""
37
+
38
+ target_queue: str | None = None
39
+ if arguments and arguments[0] not in {"keep", "remove", "replace"}:
40
+ target_queue = arguments.pop(0)
41
+ dedup_mode = arguments.pop(0) if arguments else "keep"
42
+ if dedup_mode not in {"keep", "remove", "replace"}:
43
+ raise ValueError("dedup mode 必须是 keep、remove 或 replace")
44
+ if dedup_mode != "replace":
45
+ if arguments:
46
+ raise ValueError("keep/remove 不接受额外的 dedup 参数")
47
+ return target_queue, dedup_mode, {}
48
+ if len(arguments) != 3:
49
+ raise ValueError("replace 需要 DEDUP_SCOPE DEDUP_KEY DEDUP_TTL_SECONDS")
50
+ try:
51
+ ttl = timedelta(seconds=float(arguments[2]))
52
+ except ValueError as exc:
53
+ raise ValueError("DEDUP_TTL_SECONDS 必须是正数") from exc
54
+ if ttl.total_seconds() <= 0:
55
+ raise ValueError("DEDUP_TTL_SECONDS 必须是正数")
56
+ return (
57
+ target_queue,
58
+ dedup_mode,
59
+ {
60
+ "dedup_scope": arguments[0],
61
+ "dedup_key": arguments[1],
62
+ "dedup_ttl": ttl,
63
+ },
64
+ )
65
+
66
+
67
+ async def run_shell(broker: Any, *, backend: str, namespace: str | None) -> int:
68
+ """Run the keyboard-first shell over public Broker/Admin APIs only."""
69
+
70
+ from prompt_toolkit import PromptSession # type: ignore[import-not-found]
71
+ from prompt_toolkit.completion import ( # type: ignore[import-not-found]
72
+ Completer,
73
+ Completion,
74
+ )
75
+ from prompt_toolkit.document import Document # type: ignore[import-not-found]
76
+ from prompt_toolkit.history import FileHistory # type: ignore[import-not-found]
77
+
78
+ class BrokerCompleter(Completer): # type: ignore[misc]
79
+ def get_completions(self, document: Document, complete_event: Any) -> tuple[()]:
80
+ del document, complete_event
81
+ return ()
82
+
83
+ async def get_completions_async(self, document: Document, complete_event: Any):
84
+ del complete_event
85
+ before = document.text_before_cursor
86
+ try:
87
+ words = shlex.split(before)
88
+ except ValueError:
89
+ return
90
+ partial = "" if before.endswith(" ") else (words.pop() if words else "")
91
+ candidates: tuple[str, ...] = _COMMANDS
92
+ try:
93
+ if words in (
94
+ ["queue", "inspect"],
95
+ ["messages"],
96
+ ["dlq", "list"],
97
+ ["eq", "list"],
98
+ ):
99
+ page = await broker.list_queues(limit=50)
100
+ candidates = tuple(item.queue for item in page.items)
101
+ elif len(words) == 3 and words[:2] in (
102
+ ["dlq", "replay"],
103
+ ["dlq", "delete"],
104
+ ):
105
+ page = await broker.admin.page_dead_letters(words[2], limit=50)
106
+ candidates = tuple(item.message.id for item in page.items)
107
+ elif len(words) == 3 and words[:2] in (
108
+ ["eq", "replay"],
109
+ ["eq", "delete"],
110
+ ):
111
+ page = await broker.admin.page_expired(words[2], limit=50)
112
+ candidates = tuple(item.message.id for item in page.items)
113
+ except Exception: # noqa: BLE001 - completion is bounded best effort.
114
+ return
115
+ for candidate in candidates:
116
+ if candidate.startswith(partial):
117
+ yield Completion(candidate, start_position=-len(partial))
118
+
119
+ session: Any = PromptSession(
120
+ history=FileHistory(str(Path.home() / ".taskqx_history")),
121
+ completer=BrokerCompleter(),
122
+ complete_while_typing=False,
123
+ )
124
+ while True:
125
+ try:
126
+ line = (await session.prompt_async(_prompt(backend, namespace))).strip()
127
+ except (EOFError, KeyboardInterrupt):
128
+ print()
129
+ return 0
130
+ if not line:
131
+ continue
132
+ try:
133
+ command = shlex.split(line)
134
+ except ValueError as exc:
135
+ print(f"错误:{exc}")
136
+ continue
137
+ if command[0] in {"quit", "exit"}:
138
+ return 0
139
+ if command[0] == "help":
140
+ print("""health
141
+ queues [CURSOR]
142
+ queue inspect QUEUE
143
+ messages QUEUE [CURSOR]
144
+ message inspect MESSAGE_ID
145
+ payload show MESSAGE_ID (显式显示敏感 payload)
146
+ dlq list QUEUE [CURSOR]
147
+ dlq replay QUEUE MESSAGE_ID [TARGET_QUEUE] [keep|remove]
148
+ dlq replay QUEUE MESSAGE_ID [TARGET_QUEUE] replace DEDUP_SCOPE DEDUP_KEY DEDUP_TTL_SECONDS
149
+ dlq delete QUEUE MESSAGE_ID
150
+ eq list QUEUE [CURSOR]
151
+ eq replay QUEUE MESSAGE_ID [TARGET_QUEUE] [keep|remove]
152
+ eq replay QUEUE MESSAGE_ID [TARGET_QUEUE] replace DEDUP_SCOPE DEDUP_KEY DEDUP_TTL_SECONDS
153
+ eq delete QUEUE MESSAGE_ID
154
+ consistency repair QUEUE (先显示 dry-run,再要求输入确认词)
155
+ quit""")
156
+ continue
157
+ try:
158
+ await _execute(session, broker, command)
159
+ except Exception as exc: # noqa: BLE001 - retain actionable backend diagnostics in the shell
160
+ print(f"操作失败:{type(exc).__name__}: {exc}")
161
+
162
+
163
+ async def _execute(session: Any, broker: Any, command: list[str]) -> None:
164
+ if command == ["health"]:
165
+ print(render_json(await broker.health_check()))
166
+ return
167
+ if 1 <= len(command) <= 2 and command[0] == "queues":
168
+ print(
169
+ render_json(
170
+ await broker.list_queues(
171
+ cursor=command[1] if len(command) == 2 else None, limit=50
172
+ )
173
+ )
174
+ )
175
+ return
176
+ if len(command) == 3 and command[:2] == ["queue", "inspect"]:
177
+ print(render_json(await broker.observe_queue(command[2])))
178
+ return
179
+ if 2 <= len(command) <= 3 and command[0] == "messages":
180
+ print(
181
+ render_json(
182
+ await broker.list_messages(
183
+ command[1],
184
+ cursor=command[2] if len(command) == 3 else None,
185
+ limit=50,
186
+ )
187
+ )
188
+ )
189
+ return
190
+ if len(command) == 3 and command[:2] == ["message", "inspect"]:
191
+ message = await broker.observe_message(command[2])
192
+ if message is None:
193
+ raise ValueError("未找到指定消息")
194
+ print(render_json(message))
195
+ return
196
+ if len(command) == 3 and command[:2] == ["payload", "show"]:
197
+ message = await broker.observe_message(command[2])
198
+ if message is None:
199
+ raise ValueError("未找到指定消息")
200
+ print("警告:payload 可能包含敏感数据;以下内容不会写入命令历史。")
201
+ print(render_json(message, include_payload=True))
202
+ return
203
+ if len(command) in {3, 4} and command[:2] in (["dlq", "list"], ["eq", "list"]):
204
+ queue = command[2]
205
+ cursor = command[3] if len(command) == 4 else None
206
+ page = (
207
+ await broker.admin.page_dead_letters(queue, cursor=cursor, limit=50)
208
+ if command[0] == "dlq"
209
+ else await broker.admin.page_expired(queue, cursor=cursor, limit=50)
210
+ )
211
+ print(render_json(page))
212
+ return
213
+ if len(command) >= 4 and command[0] in {"dlq", "eq"} and command[1] == "replay":
214
+ source, queue, message_id = command[0], command[2], command[3]
215
+ target_queue, dedup_mode, dedup_options = _replay_options(command[4:])
216
+ print(
217
+ render_json(
218
+ {
219
+ "operation": f"{source.upper()} replay",
220
+ "source_queue": queue,
221
+ "target_queue": target_queue or queue,
222
+ "message_id": message_id,
223
+ "dedup_mode": dedup_mode,
224
+ "dedup": "<replacement configured>"
225
+ if dedup_options
226
+ else "<existing policy>",
227
+ }
228
+ )
229
+ )
230
+ confirmation = await session.prompt_async(
231
+ f"输入 'replay {queue} {message_id}' 确认:"
232
+ )
233
+ if confirmation != f"replay {queue} {message_id}":
234
+ print("已取消。")
235
+ return
236
+ if source == "dlq":
237
+ await broker.admin.replay_dead_letter(
238
+ queue,
239
+ message_id,
240
+ target_queue=target_queue,
241
+ dedup_mode=dedup_mode,
242
+ **dedup_options,
243
+ )
244
+ else:
245
+ await broker.admin.replay_expired(
246
+ queue,
247
+ message_id,
248
+ expires_at=None,
249
+ target_queue=target_queue,
250
+ dedup_mode=dedup_mode,
251
+ **dedup_options,
252
+ )
253
+ print(
254
+ render_json(
255
+ {
256
+ "replay_enqueued": message_id,
257
+ "queue": target_queue or queue,
258
+ "note": "业务 handler 的处理结果由后续异步执行决定。",
259
+ }
260
+ )
261
+ )
262
+ return
263
+ if len(command) == 4 and command[0] in {"dlq", "eq"} and command[1] == "delete":
264
+ source, queue, message_id = command[0], command[2], command[3]
265
+ print(
266
+ render_json(
267
+ {
268
+ "operation": f"{source.upper()} delete",
269
+ "queue": queue,
270
+ "message_id": message_id,
271
+ }
272
+ )
273
+ )
274
+ confirmation = await session.prompt_async(
275
+ f"输入 'delete {queue} {message_id}' 确认:"
276
+ )
277
+ if confirmation != f"delete {queue} {message_id}":
278
+ print("已取消。")
279
+ return
280
+ delete = (
281
+ broker.admin.delete_dead_letter
282
+ if source == "dlq"
283
+ else broker.admin.delete_expired
284
+ )
285
+ print(
286
+ render_json(
287
+ {"deleted": await delete(queue, message_id), "message_id": message_id}
288
+ )
289
+ )
290
+ return
291
+ if len(command) == 3 and command[:2] == ["consistency", "repair"]:
292
+ queue = command[2]
293
+ proposal = await broker.repair_consistency(queue, dry_run=True)
294
+ print(render_json(proposal))
295
+ confirmation = await session.prompt_async(
296
+ f"输入 'repair {queue}' 应用以上修复:"
297
+ )
298
+ if confirmation != f"repair {queue}":
299
+ print("已取消。")
300
+ return
301
+ print(render_json(await broker.repair_consistency(queue, dry_run=False)))
302
+ return
303
+ raise ValueError("未知命令;输入 help 查看可用命令")
@@ -0,0 +1,19 @@
1
+ """提交准入相关的公共导出。"""
2
+
3
+ from .base import CallbackSubmissionStore, PreparedSubmission
4
+ from .observability import SubmissionObserver
5
+ from .redis import RedisStringDedupSubmissionStore, RedisSubmissionStore
6
+ from .routing import SubmissionRouter
7
+ from .service import SubmissionService
8
+ from .sqlite import SQLiteSubmissionStore
9
+
10
+ __all__ = [
11
+ "CallbackSubmissionStore",
12
+ "PreparedSubmission",
13
+ "RedisStringDedupSubmissionStore",
14
+ "RedisSubmissionStore",
15
+ "SQLiteSubmissionStore",
16
+ "SubmissionObserver",
17
+ "SubmissionRouter",
18
+ "SubmissionService",
19
+ ]
@@ -0,0 +1,62 @@
1
+ """提交准入扩展点使用的已准备提交对象。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable
6
+ from dataclasses import dataclass
7
+ from datetime import datetime
8
+
9
+ from ..capabilities import DedupGuarantee, SubmissionCapabilities
10
+ from ..types import SubmitResult
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class PreparedSubmission:
15
+ """Broker 已完成校验和序列化、可由任意 Store 原子提交的载荷。"""
16
+
17
+ message_id: str
18
+ queue: str
19
+ envelope: bytes
20
+ status: str
21
+ created_at: datetime
22
+ expires_at_ms: int | None
23
+ dedup_scope: str | None
24
+ dedup_key: str | None
25
+ dedup_ttl_ms: int | None
26
+ max_attempts: int
27
+ serializer_name: str
28
+ serializer_version: str
29
+ available_at_ms: int | None = None
30
+ workflow_id: str | None = None
31
+ parent_id: str | None = None
32
+
33
+
34
+ class CallbackSubmissionStore:
35
+ """兼容旧式 callable 的轻量适配器。
36
+
37
+ 内置 broker 使用专用 Store;此类仅保留给需要将外部提交函数接入协议的用户。
38
+ """
39
+
40
+ capabilities = SubmissionCapabilities(
41
+ dedup_guarantee=DedupGuarantee.EXACT,
42
+ per_key_dedup_ttl=True,
43
+ stores_original_message_id=True,
44
+ atomic_submit=True,
45
+ batch_submit=False,
46
+ )
47
+
48
+ def __init__(
49
+ self, submitter: Callable[[PreparedSubmission], Awaitable[SubmitResult]]
50
+ ) -> None:
51
+ self._submitter = submitter
52
+
53
+ async def submit(self, submission: PreparedSubmission) -> SubmitResult:
54
+ """将完整的已准备对象交给回调。"""
55
+ return await self._submitter(submission)
56
+
57
+ async def submit_many(
58
+ self, submissions: list[PreparedSubmission]
59
+ ) -> list[SubmitResult]:
60
+ """逐项委托;能力声明明确该适配器不提供批量原子性。"""
61
+
62
+ return [await self.submit(item) for item in submissions]
@@ -0,0 +1,71 @@
1
+ """Observability emitted after a submission store has committed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ..middleware import Middleware
6
+ from ..observability import EventSink, MetricsSink, event, metric
7
+ from ..serialization import Serializer
8
+ from ..types import MessageStatus, SubmitResult, TaskMessage
9
+ from .base import PreparedSubmission
10
+
11
+
12
+ class SubmissionObserver:
13
+ """Publish the stable lifecycle contract for completed submissions."""
14
+
15
+ def __init__(
16
+ self,
17
+ *,
18
+ backend: str,
19
+ middleware: Middleware,
20
+ metrics: MetricsSink | None,
21
+ event_sink: EventSink | None,
22
+ serializer: Serializer,
23
+ ) -> None:
24
+ self._backend = backend
25
+ self._middleware = middleware
26
+ self._metrics = metrics
27
+ self._event_sink = event_sink
28
+ self._serializer = serializer
29
+
30
+ async def record(
31
+ self, prepared: PreparedSubmission, message: TaskMessage, result: SubmitResult
32
+ ) -> None:
33
+ """Emit exactly the outcome committed by a submission store."""
34
+ if not result.accepted:
35
+ await metric(self._metrics, "duplicate_total", queue=message.queue)
36
+ await event(
37
+ self._middleware,
38
+ "duplicate",
39
+ message,
40
+ status=prepared.status,
41
+ backend=self._backend,
42
+ event_sink=self._event_sink,
43
+ serializer_name=self._serializer.name,
44
+ serializer_version=self._serializer.version,
45
+ )
46
+ return
47
+ await self._middleware.emit("after_submit", message, result)
48
+ await metric(self._metrics, "submitted_total", queue=message.queue)
49
+ await event(
50
+ self._middleware,
51
+ "submitted",
52
+ message,
53
+ status=prepared.status,
54
+ backend=self._backend,
55
+ event_sink=self._event_sink,
56
+ serializer_name=self._serializer.name,
57
+ serializer_version=self._serializer.version,
58
+ )
59
+ if prepared.status == MessageStatus.EXPIRED.value:
60
+ await metric(self._metrics, "expired_total", queue=message.queue)
61
+ await event(
62
+ self._middleware,
63
+ "expired",
64
+ message,
65
+ status=MessageStatus.EXPIRED.value,
66
+ reason="expired_on_submit",
67
+ backend=self._backend,
68
+ event_sink=self._event_sink,
69
+ serializer_name=self._serializer.name,
70
+ serializer_version=self._serializer.version,
71
+ )