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
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Redis SubmissionStore implementations and their atomic Lua admission boundary."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from datetime import timedelta
|
|
7
|
+
from typing import Any, Protocol, TypeGuard
|
|
8
|
+
|
|
9
|
+
from ..broker.redis_calls import RedisKeyspace, batch_submit_call, submit_call
|
|
10
|
+
from ..capabilities import DedupGuarantee, SubmissionCapabilities
|
|
11
|
+
from ..errors import BrokerClosedError, ValidationError
|
|
12
|
+
from ..types import SubmitDecision, SubmitResult
|
|
13
|
+
from .base import PreparedSubmission
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RedisSubmissionBackend(RedisKeyspace, Protocol):
|
|
17
|
+
"""Internal Store dependency contract, including its Redis client adapter."""
|
|
18
|
+
|
|
19
|
+
_redis: Any
|
|
20
|
+
|
|
21
|
+
def _ensure_open(self) -> None: ...
|
|
22
|
+
def _dedup_key(self, scope: str, key: str) -> str: ...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _RedisStoreBackend:
|
|
26
|
+
"""Minimal backend adapter for configuring a store from a Redis client."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, redis: Any, namespace: str) -> None:
|
|
29
|
+
self._redis, self._namespace, self._closed = redis, namespace, False
|
|
30
|
+
|
|
31
|
+
def _ensure_open(self) -> None:
|
|
32
|
+
if self._closed:
|
|
33
|
+
raise BrokerClosedError("broker 已关闭")
|
|
34
|
+
|
|
35
|
+
def _queue_key(self, queue: str, kind: str) -> str:
|
|
36
|
+
return f"{self._namespace}:queue:{{{queue}}}:{kind}"
|
|
37
|
+
|
|
38
|
+
def _message_key(self, queue: str, message_id: str) -> str:
|
|
39
|
+
return f"{self._namespace}:queue:{{{queue}}}:message:{message_id}"
|
|
40
|
+
|
|
41
|
+
def _dedup_key(self, scope: str, key: str) -> str:
|
|
42
|
+
return f"{self._namespace}:dedup:{hashlib.sha256(scope.encode()).hexdigest()}:{hashlib.sha256(key.encode()).hexdigest()}"
|
|
43
|
+
|
|
44
|
+
def _group_name(self) -> str:
|
|
45
|
+
return "taskqx"
|
|
46
|
+
|
|
47
|
+
def _message_index_key(self) -> str:
|
|
48
|
+
return f"{self._namespace}:message-index"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _is_submission_backend(value: object) -> TypeGuard[RedisSubmissionBackend]:
|
|
52
|
+
return all(
|
|
53
|
+
hasattr(value, name)
|
|
54
|
+
for name in (
|
|
55
|
+
"_redis",
|
|
56
|
+
"_ensure_open",
|
|
57
|
+
"_dedup_key",
|
|
58
|
+
"_message_key",
|
|
59
|
+
"_queue_key",
|
|
60
|
+
"_group_name",
|
|
61
|
+
"_message_index_key",
|
|
62
|
+
)
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class RedisSubmissionStore:
|
|
67
|
+
"""Redis Lua submission store; the default variant refuses dedup requests."""
|
|
68
|
+
|
|
69
|
+
capabilities = SubmissionCapabilities(
|
|
70
|
+
dedup_guarantee=DedupGuarantee.NONE,
|
|
71
|
+
per_key_dedup_ttl=False,
|
|
72
|
+
stores_original_message_id=False,
|
|
73
|
+
atomic_submit=True,
|
|
74
|
+
batch_submit=True,
|
|
75
|
+
batch_atomic=True,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
def __init__(self, broker: object, *, namespace: str = "taskqx") -> None:
|
|
79
|
+
self._broker: RedisSubmissionBackend = (
|
|
80
|
+
broker
|
|
81
|
+
if _is_submission_backend(broker)
|
|
82
|
+
else _RedisStoreBackend(broker, namespace)
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def _dedup_redis_key(self, submission: PreparedSubmission) -> str:
|
|
86
|
+
if submission.dedup_key is not None:
|
|
87
|
+
raise ValidationError("当前 SubmissionStore 不支持 dedup")
|
|
88
|
+
return ""
|
|
89
|
+
|
|
90
|
+
async def submit(self, submission: PreparedSubmission) -> SubmitResult:
|
|
91
|
+
self._broker._ensure_open()
|
|
92
|
+
values = await submit_call(
|
|
93
|
+
self._broker, submission, self._dedup_redis_key(submission)
|
|
94
|
+
).execute(self._broker._redis)
|
|
95
|
+
if int(values[0]) == 0:
|
|
96
|
+
ttl_left = int(values[2])
|
|
97
|
+
return SubmitResult(
|
|
98
|
+
str(values[1]),
|
|
99
|
+
False,
|
|
100
|
+
SubmitDecision.DUPLICATE,
|
|
101
|
+
str(values[1]),
|
|
102
|
+
dedup_expires_at=submission.created_at
|
|
103
|
+
+ timedelta(milliseconds=max(ttl_left, 0)),
|
|
104
|
+
)
|
|
105
|
+
return SubmitResult(
|
|
106
|
+
submission.message_id,
|
|
107
|
+
True,
|
|
108
|
+
SubmitDecision.ACCEPTED,
|
|
109
|
+
stream_entry_id=str(values[3]),
|
|
110
|
+
dedup_expires_at=(
|
|
111
|
+
submission.created_at + timedelta(milliseconds=submission.dedup_ttl_ms)
|
|
112
|
+
if submission.dedup_ttl_ms is not None
|
|
113
|
+
else None
|
|
114
|
+
),
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
async def submit_many(
|
|
118
|
+
self, submissions: list[PreparedSubmission]
|
|
119
|
+
) -> list[SubmitResult]:
|
|
120
|
+
if not submissions:
|
|
121
|
+
return []
|
|
122
|
+
self._broker._ensure_open()
|
|
123
|
+
values = await batch_submit_call(
|
|
124
|
+
self._broker,
|
|
125
|
+
submissions,
|
|
126
|
+
[self._dedup_redis_key(submission) for submission in submissions],
|
|
127
|
+
).execute(self._broker._redis)
|
|
128
|
+
results: list[SubmitResult] = []
|
|
129
|
+
for index, submission in enumerate(submissions):
|
|
130
|
+
accepted, message_id, ttl_or_entry, entry = values[
|
|
131
|
+
index * 4 : index * 4 + 4
|
|
132
|
+
]
|
|
133
|
+
if int(accepted) == 0:
|
|
134
|
+
results.append(
|
|
135
|
+
SubmitResult(
|
|
136
|
+
str(message_id),
|
|
137
|
+
False,
|
|
138
|
+
SubmitDecision.DUPLICATE,
|
|
139
|
+
str(message_id),
|
|
140
|
+
dedup_expires_at=submission.created_at
|
|
141
|
+
+ timedelta(milliseconds=max(int(ttl_or_entry), 0)),
|
|
142
|
+
)
|
|
143
|
+
)
|
|
144
|
+
else:
|
|
145
|
+
results.append(
|
|
146
|
+
SubmitResult(
|
|
147
|
+
submission.message_id,
|
|
148
|
+
True,
|
|
149
|
+
SubmitDecision.ACCEPTED,
|
|
150
|
+
stream_entry_id=str(entry),
|
|
151
|
+
dedup_expires_at=(
|
|
152
|
+
submission.created_at
|
|
153
|
+
+ timedelta(milliseconds=submission.dedup_ttl_ms)
|
|
154
|
+
if submission.dedup_ttl_ms is not None
|
|
155
|
+
else None
|
|
156
|
+
),
|
|
157
|
+
)
|
|
158
|
+
)
|
|
159
|
+
return results
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class RedisStringDedupSubmissionStore(RedisSubmissionStore):
|
|
163
|
+
"""Exact dedup admission implemented as Redis string + PX TTL in the same Lua call."""
|
|
164
|
+
|
|
165
|
+
capabilities = SubmissionCapabilities(
|
|
166
|
+
dedup_guarantee=DedupGuarantee.EXACT,
|
|
167
|
+
per_key_dedup_ttl=True,
|
|
168
|
+
stores_original_message_id=True,
|
|
169
|
+
atomic_submit=True,
|
|
170
|
+
batch_submit=True,
|
|
171
|
+
batch_atomic=True,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
def _dedup_redis_key(self, submission: PreparedSubmission) -> str:
|
|
175
|
+
if submission.dedup_key is None:
|
|
176
|
+
return ""
|
|
177
|
+
assert (
|
|
178
|
+
submission.dedup_scope is not None and submission.dedup_ttl_ms is not None
|
|
179
|
+
)
|
|
180
|
+
return self._broker._dedup_key(submission.dedup_scope, submission.dedup_key)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""SubmissionStore profile routing shared by all broker backends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any, Protocol
|
|
7
|
+
|
|
8
|
+
from ..capabilities import SubmissionCapabilities
|
|
9
|
+
from ..errors import ValidationError
|
|
10
|
+
from ..naming import validate_persistent_name
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class _QueueValidator(Protocol):
|
|
14
|
+
_allow_legacy_names: bool
|
|
15
|
+
|
|
16
|
+
def _validate_queue(self, queue: str) -> None: ...
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SubmissionRouter:
|
|
20
|
+
"""Validate and select configured SubmissionStore profiles.
|
|
21
|
+
|
|
22
|
+
Store implementations are intentionally duck-typed at this extension
|
|
23
|
+
boundary, so third-party stores do not have to inherit a framework class.
|
|
24
|
+
The dynamic check is contained here rather than duplicated by brokers.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
owner: _QueueValidator,
|
|
30
|
+
*,
|
|
31
|
+
default_store: Any,
|
|
32
|
+
submission_store: Any | None,
|
|
33
|
+
submission_stores: Mapping[str, Any] | None,
|
|
34
|
+
queue_submission_profiles: Mapping[str, str] | None,
|
|
35
|
+
) -> None:
|
|
36
|
+
if submission_store is not None and submission_stores is not None:
|
|
37
|
+
raise ValidationError("submission_store 与 submission_stores 不能同时配置")
|
|
38
|
+
configured = dict(
|
|
39
|
+
submission_stores or {"default": submission_store or default_store}
|
|
40
|
+
)
|
|
41
|
+
if "default" not in configured:
|
|
42
|
+
raise ValidationError("submission_stores 必须包含 default profile")
|
|
43
|
+
self._stores = {
|
|
44
|
+
name: store(owner)
|
|
45
|
+
if callable(store) and not hasattr(store, "submit")
|
|
46
|
+
else store
|
|
47
|
+
for name, store in configured.items()
|
|
48
|
+
}
|
|
49
|
+
for name in self._stores:
|
|
50
|
+
validate_persistent_name(
|
|
51
|
+
name, label="submission profile", allow_legacy=owner._allow_legacy_names
|
|
52
|
+
)
|
|
53
|
+
if any(
|
|
54
|
+
not hasattr(store, "submit")
|
|
55
|
+
or not hasattr(store, "submit_many")
|
|
56
|
+
or not hasattr(store, "capabilities")
|
|
57
|
+
for store in self._stores.values()
|
|
58
|
+
):
|
|
59
|
+
raise ValidationError(
|
|
60
|
+
"每个 submission store 都必须实现 submit 与 submit_many"
|
|
61
|
+
)
|
|
62
|
+
self._profiles = dict(queue_submission_profiles or {})
|
|
63
|
+
for queue, profile in self._profiles.items():
|
|
64
|
+
owner._validate_queue(queue)
|
|
65
|
+
if profile not in self._stores:
|
|
66
|
+
raise ValidationError(
|
|
67
|
+
f"queue {queue!r} 使用了未知 submission profile {profile!r}"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def default(self) -> Any:
|
|
72
|
+
return self._stores["default"]
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def stores(self) -> Mapping[str, Any]:
|
|
76
|
+
return self._stores
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def profiles(self) -> Mapping[str, str]:
|
|
80
|
+
return self._profiles
|
|
81
|
+
|
|
82
|
+
def profile_for(self, queue: str) -> str:
|
|
83
|
+
return self._profiles.get(queue, "default")
|
|
84
|
+
|
|
85
|
+
def for_queue(self, queue: str) -> Any:
|
|
86
|
+
return (
|
|
87
|
+
self.default
|
|
88
|
+
if self.profile_for(queue) == "default"
|
|
89
|
+
else self._stores[self.profile_for(queue)]
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def capabilities(self, queue: str) -> SubmissionCapabilities:
|
|
93
|
+
return self.for_queue(queue).capabilities
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Shared public submission orchestration for broker façades."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
6
|
+
from typing import Any, Protocol
|
|
7
|
+
|
|
8
|
+
from ..errors import ValidationError
|
|
9
|
+
from ..middleware import Middleware
|
|
10
|
+
from ..types import BatchSubmitItemResult, SubmitRequest, SubmitResult, TaskMessage
|
|
11
|
+
from .base import PreparedSubmission
|
|
12
|
+
|
|
13
|
+
PrepareSubmission = Callable[..., Awaitable[tuple[PreparedSubmission, TaskMessage]]]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _SubmissionStore(Protocol):
|
|
17
|
+
async def submit(self, submission: PreparedSubmission) -> SubmitResult: ...
|
|
18
|
+
async def submit_many(
|
|
19
|
+
self, submissions: list[PreparedSubmission]
|
|
20
|
+
) -> list[SubmitResult]: ...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class SubmissionOwner(Protocol):
|
|
24
|
+
"""Stable broker façade needed by shared submission orchestration."""
|
|
25
|
+
|
|
26
|
+
middleware: Middleware
|
|
27
|
+
_queue_submission_profiles: Mapping[str, str]
|
|
28
|
+
|
|
29
|
+
def _submission_store_for(self, queue: str) -> _SubmissionStore: ...
|
|
30
|
+
async def _record_submitted(
|
|
31
|
+
self, prepared: PreparedSubmission, message: TaskMessage, result: SubmitResult
|
|
32
|
+
) -> None: ...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SubmissionService:
|
|
36
|
+
"""Apply middleware, profile rules and result observation around Store calls."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, owner: SubmissionOwner, prepare: PrepareSubmission) -> None:
|
|
39
|
+
self._owner = owner
|
|
40
|
+
self._prepare = prepare
|
|
41
|
+
|
|
42
|
+
async def submit(self, **kwargs: Any) -> SubmitResult:
|
|
43
|
+
prepared, message = await self._prepare(**kwargs)
|
|
44
|
+
await self._owner.middleware.emit("before_submit", message)
|
|
45
|
+
result = await self._owner._submission_store_for(prepared.queue).submit(
|
|
46
|
+
prepared
|
|
47
|
+
)
|
|
48
|
+
await self._owner._record_submitted(prepared, message, result)
|
|
49
|
+
return result
|
|
50
|
+
|
|
51
|
+
async def submit_request(self, request: SubmitRequest) -> SubmitResult:
|
|
52
|
+
"""Submit one normalized draft through the existing atomic boundary."""
|
|
53
|
+
|
|
54
|
+
return await self.submit(**_request_kwargs(request))
|
|
55
|
+
|
|
56
|
+
async def submit_many(
|
|
57
|
+
self, messages: list[SubmitRequest], *, atomic: bool
|
|
58
|
+
) -> list[SubmitResult] | list[BatchSubmitItemResult]:
|
|
59
|
+
if not atomic:
|
|
60
|
+
results: list[BatchSubmitItemResult] = []
|
|
61
|
+
for index, request in enumerate(messages):
|
|
62
|
+
try:
|
|
63
|
+
result = await self.submit(**_request_kwargs(request))
|
|
64
|
+
except Exception as exc: # noqa: BLE001 - a failed item must not abort later items.
|
|
65
|
+
results.append(BatchSubmitItemResult(index=index, error=exc))
|
|
66
|
+
else:
|
|
67
|
+
results.append(BatchSubmitItemResult(index=index, result=result))
|
|
68
|
+
return results
|
|
69
|
+
|
|
70
|
+
prepared_messages = [
|
|
71
|
+
await self._prepare(**_request_kwargs(request)) for request in messages
|
|
72
|
+
]
|
|
73
|
+
for _, message in prepared_messages:
|
|
74
|
+
await self._owner.middleware.emit("before_submit", message)
|
|
75
|
+
profiles = {
|
|
76
|
+
self._owner._queue_submission_profiles.get(prepared.queue, "default")
|
|
77
|
+
for prepared, _ in prepared_messages
|
|
78
|
+
}
|
|
79
|
+
if len(profiles) > 1:
|
|
80
|
+
raise ValidationError("submit_many 不支持混合 SubmissionStore profile")
|
|
81
|
+
atomic_results: list[SubmitResult] = []
|
|
82
|
+
if prepared_messages:
|
|
83
|
+
store = self._owner._submission_store_for(prepared_messages[0][0].queue)
|
|
84
|
+
atomic_results = await store.submit_many(
|
|
85
|
+
[prepared for prepared, _ in prepared_messages]
|
|
86
|
+
)
|
|
87
|
+
for result, (prepared, message) in zip(
|
|
88
|
+
atomic_results, prepared_messages, strict=True
|
|
89
|
+
):
|
|
90
|
+
await self._owner._record_submitted(prepared, message, result)
|
|
91
|
+
return atomic_results
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _request_kwargs(request: SubmitRequest) -> dict[str, Any]:
|
|
95
|
+
return {
|
|
96
|
+
"queue": request.queue,
|
|
97
|
+
"payload": request.payload,
|
|
98
|
+
"metadata": request.metadata,
|
|
99
|
+
"dedup_key": request.dedup_key,
|
|
100
|
+
"dedup_scope": request.dedup_scope,
|
|
101
|
+
"dedup_ttl": request.dedup_ttl,
|
|
102
|
+
"delay": request.delay,
|
|
103
|
+
"expires_at": request.expires_at,
|
|
104
|
+
"max_attempts": request.max_attempts,
|
|
105
|
+
"workflow_id": request.workflow_id,
|
|
106
|
+
"parent_id": request.parent_id,
|
|
107
|
+
"payload_type": request.payload_type,
|
|
108
|
+
"payload_schema_name": request.payload_schema_name,
|
|
109
|
+
"payload_schema_version": request.payload_schema_version,
|
|
110
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""SQLite SubmissionStore: transactional batch admission and exact dedup."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from datetime import datetime, timedelta
|
|
7
|
+
from typing import Protocol
|
|
8
|
+
|
|
9
|
+
import aiosqlite
|
|
10
|
+
|
|
11
|
+
from ..broker._time import datetime_from_timestamp as _datetime
|
|
12
|
+
from ..broker._time import timestamp as _timestamp
|
|
13
|
+
from ..capabilities import DedupGuarantee, SubmissionCapabilities
|
|
14
|
+
from ..types import MessageStatus, SubmitDecision, SubmitResult
|
|
15
|
+
from .base import PreparedSubmission
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SQLiteSubmissionBackend(Protocol):
|
|
19
|
+
"""Stable SQLite transaction hooks required by the submission Store."""
|
|
20
|
+
|
|
21
|
+
_lock: asyncio.Lock
|
|
22
|
+
_connection: aiosqlite.Connection | None
|
|
23
|
+
|
|
24
|
+
async def start(self) -> None: ...
|
|
25
|
+
async def _counter(
|
|
26
|
+
self, cursor: aiosqlite.Cursor, queue: str, column: str
|
|
27
|
+
) -> None: ...
|
|
28
|
+
async def _expire(
|
|
29
|
+
self,
|
|
30
|
+
cursor: aiosqlite.Cursor,
|
|
31
|
+
message_id: str,
|
|
32
|
+
now: datetime,
|
|
33
|
+
old_status: MessageStatus,
|
|
34
|
+
attempt: int,
|
|
35
|
+
) -> None: ...
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SQLiteSubmissionStore:
|
|
39
|
+
"""Commit dedup admission, initial message state and counters in one transaction."""
|
|
40
|
+
|
|
41
|
+
capabilities = SubmissionCapabilities(
|
|
42
|
+
dedup_guarantee=DedupGuarantee.EXACT,
|
|
43
|
+
per_key_dedup_ttl=True,
|
|
44
|
+
stores_original_message_id=True,
|
|
45
|
+
atomic_submit=True,
|
|
46
|
+
batch_submit=True,
|
|
47
|
+
batch_atomic=True,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
def __init__(self, broker: SQLiteSubmissionBackend) -> None:
|
|
51
|
+
self._broker = broker
|
|
52
|
+
|
|
53
|
+
async def submit(self, submission: PreparedSubmission) -> SubmitResult:
|
|
54
|
+
results = await self._submit_all([submission])
|
|
55
|
+
return results[0]
|
|
56
|
+
|
|
57
|
+
async def submit_many(
|
|
58
|
+
self, submissions: list[PreparedSubmission]
|
|
59
|
+
) -> list[SubmitResult]:
|
|
60
|
+
"""Run every per-message dedup and state write under one ``BEGIN IMMEDIATE``."""
|
|
61
|
+
return await self._submit_all(submissions)
|
|
62
|
+
|
|
63
|
+
async def _submit_all(
|
|
64
|
+
self, submissions: list[PreparedSubmission]
|
|
65
|
+
) -> list[SubmitResult]:
|
|
66
|
+
if not submissions:
|
|
67
|
+
return []
|
|
68
|
+
broker = self._broker
|
|
69
|
+
await broker.start()
|
|
70
|
+
results: list[SubmitResult] = []
|
|
71
|
+
async with broker._lock:
|
|
72
|
+
assert broker._connection is not None
|
|
73
|
+
cursor = await broker._connection.cursor()
|
|
74
|
+
try:
|
|
75
|
+
await cursor.execute("BEGIN IMMEDIATE")
|
|
76
|
+
for submission in submissions:
|
|
77
|
+
results.append(
|
|
78
|
+
await self._submit_in_transaction(cursor, submission)
|
|
79
|
+
)
|
|
80
|
+
await cursor.execute("COMMIT")
|
|
81
|
+
except Exception:
|
|
82
|
+
await cursor.execute("ROLLBACK")
|
|
83
|
+
raise
|
|
84
|
+
return results
|
|
85
|
+
|
|
86
|
+
async def _submit_in_transaction(
|
|
87
|
+
self, cursor: aiosqlite.Cursor, submission: PreparedSubmission
|
|
88
|
+
) -> SubmitResult:
|
|
89
|
+
broker, now = self._broker, submission.created_at
|
|
90
|
+
if submission.dedup_key is not None:
|
|
91
|
+
assert (
|
|
92
|
+
submission.dedup_scope is not None
|
|
93
|
+
and submission.dedup_ttl_ms is not None
|
|
94
|
+
)
|
|
95
|
+
await cursor.execute(
|
|
96
|
+
"DELETE FROM dedup_records WHERE scope=? AND dedup_key=? AND expires_at<=?",
|
|
97
|
+
(submission.dedup_scope, submission.dedup_key, _timestamp(now)),
|
|
98
|
+
)
|
|
99
|
+
existing = await (
|
|
100
|
+
await cursor.execute(
|
|
101
|
+
"SELECT message_id, expires_at FROM dedup_records WHERE scope=? AND dedup_key=?",
|
|
102
|
+
(submission.dedup_scope, submission.dedup_key),
|
|
103
|
+
)
|
|
104
|
+
).fetchone()
|
|
105
|
+
if existing is not None:
|
|
106
|
+
return SubmitResult(
|
|
107
|
+
existing["message_id"],
|
|
108
|
+
False,
|
|
109
|
+
SubmitDecision.DUPLICATE,
|
|
110
|
+
existing["message_id"],
|
|
111
|
+
dedup_expires_at=_datetime(existing["expires_at"]),
|
|
112
|
+
)
|
|
113
|
+
await cursor.execute(
|
|
114
|
+
"INSERT INTO dedup_records VALUES (?, ?, ?, ?)",
|
|
115
|
+
(
|
|
116
|
+
submission.dedup_scope,
|
|
117
|
+
submission.dedup_key,
|
|
118
|
+
submission.message_id,
|
|
119
|
+
_timestamp(now + timedelta(milliseconds=submission.dedup_ttl_ms)),
|
|
120
|
+
),
|
|
121
|
+
)
|
|
122
|
+
await cursor.execute(
|
|
123
|
+
"""
|
|
124
|
+
INSERT INTO messages (id, queue, envelope, serializer_name, serializer_version, status, attempt,
|
|
125
|
+
max_attempts, created_at, available_at, expires_at, workflow_id, parent_id)
|
|
126
|
+
VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)
|
|
127
|
+
""",
|
|
128
|
+
(
|
|
129
|
+
submission.message_id,
|
|
130
|
+
submission.queue,
|
|
131
|
+
submission.envelope,
|
|
132
|
+
submission.serializer_name,
|
|
133
|
+
submission.serializer_version,
|
|
134
|
+
submission.status,
|
|
135
|
+
submission.max_attempts,
|
|
136
|
+
_timestamp(now),
|
|
137
|
+
submission.available_at_ms / 1000
|
|
138
|
+
if submission.available_at_ms is not None
|
|
139
|
+
else None,
|
|
140
|
+
submission.expires_at_ms / 1000
|
|
141
|
+
if submission.expires_at_ms is not None
|
|
142
|
+
else None,
|
|
143
|
+
submission.workflow_id,
|
|
144
|
+
submission.parent_id,
|
|
145
|
+
),
|
|
146
|
+
)
|
|
147
|
+
await broker._counter(cursor, submission.queue, "submitted_total")
|
|
148
|
+
if submission.status == MessageStatus.EXPIRED.value:
|
|
149
|
+
await broker._expire(
|
|
150
|
+
cursor, submission.message_id, now, MessageStatus.READY, 0
|
|
151
|
+
)
|
|
152
|
+
return SubmitResult(
|
|
153
|
+
submission.message_id,
|
|
154
|
+
True,
|
|
155
|
+
SubmitDecision.ACCEPTED,
|
|
156
|
+
dedup_expires_at=(
|
|
157
|
+
now + timedelta(milliseconds=submission.dedup_ttl_ms)
|
|
158
|
+
if submission.dedup_ttl_ms is not None
|
|
159
|
+
else None
|
|
160
|
+
),
|
|
161
|
+
)
|