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,120 @@
|
|
|
1
|
+
"""Redis lifecycle observation, isolated from committed state transitions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from ..observability import event as emit_event
|
|
9
|
+
from ..observability import metric
|
|
10
|
+
from ..types import FinishOutcome, MessageStatus
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from .redis import RedisBroker
|
|
14
|
+
from .redis_components import RedisDelivery
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RedisObservability:
|
|
20
|
+
"""Emit lifecycle metrics/events only after the corresponding Lua commit."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, broker: RedisBroker) -> None:
|
|
23
|
+
self._broker = broker
|
|
24
|
+
|
|
25
|
+
async def claimed(self, delivery: RedisDelivery) -> None:
|
|
26
|
+
broker = self._broker
|
|
27
|
+
await broker.middleware.emit("after_claim", delivery)
|
|
28
|
+
await metric(broker.metrics, "claimed_total", queue=delivery.message.queue)
|
|
29
|
+
await emit_event(
|
|
30
|
+
broker.middleware,
|
|
31
|
+
"claimed",
|
|
32
|
+
delivery.message,
|
|
33
|
+
status=MessageStatus.LEASED.value,
|
|
34
|
+
delivery=delivery,
|
|
35
|
+
backend="redis",
|
|
36
|
+
event_sink=broker.event_sink,
|
|
37
|
+
serializer_name=broker._serializer.name,
|
|
38
|
+
serializer_version=broker._serializer.version,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
async def finished(
|
|
42
|
+
self,
|
|
43
|
+
delivery: RedisDelivery,
|
|
44
|
+
outcome: FinishOutcome,
|
|
45
|
+
*,
|
|
46
|
+
reason: str | None,
|
|
47
|
+
error_type: str | None,
|
|
48
|
+
) -> None:
|
|
49
|
+
event_name, metric_name = {
|
|
50
|
+
FinishOutcome.EXPIRED: ("expired", "expired_total"),
|
|
51
|
+
FinishOutcome.ACKED: ("ack", "acked_total"),
|
|
52
|
+
FinishOutcome.RETRIED: ("retry", "retried_total"),
|
|
53
|
+
FinishOutcome.DEAD_LETTERED: ("dead_lettered", "dead_lettered_total"),
|
|
54
|
+
}[outcome]
|
|
55
|
+
broker = self._broker
|
|
56
|
+
await broker.middleware.emit(f"after_{event_name}", delivery, reason)
|
|
57
|
+
await metric(broker.metrics, metric_name, queue=delivery.message.queue)
|
|
58
|
+
await emit_event(
|
|
59
|
+
broker.middleware,
|
|
60
|
+
event_name,
|
|
61
|
+
delivery.message,
|
|
62
|
+
status=outcome.value,
|
|
63
|
+
delivery=delivery,
|
|
64
|
+
reason=reason,
|
|
65
|
+
error_type=error_type,
|
|
66
|
+
backend="redis",
|
|
67
|
+
event_sink=broker.event_sink,
|
|
68
|
+
serializer_name=broker._serializer.name,
|
|
69
|
+
serializer_version=broker._serializer.version,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
async def maintenance(
|
|
73
|
+
self,
|
|
74
|
+
queue: str,
|
|
75
|
+
message_id: str,
|
|
76
|
+
name: str,
|
|
77
|
+
status: str,
|
|
78
|
+
*,
|
|
79
|
+
reason: str | None = None,
|
|
80
|
+
error_type: str | None = None,
|
|
81
|
+
metric_name: str | None = None,
|
|
82
|
+
) -> None:
|
|
83
|
+
"""Best-effort sink isolation after a successful maintenance script."""
|
|
84
|
+
|
|
85
|
+
broker = self._broker
|
|
86
|
+
try:
|
|
87
|
+
fields = await broker._redis.hgetall(broker._message_key(queue, message_id))
|
|
88
|
+
if not fields:
|
|
89
|
+
return
|
|
90
|
+
message = broker._decode(
|
|
91
|
+
fields["envelope"],
|
|
92
|
+
fields.get("serializer_name"),
|
|
93
|
+
fields.get("serializer_version"),
|
|
94
|
+
)
|
|
95
|
+
if metric_name is not None:
|
|
96
|
+
await metric(broker.metrics, metric_name, queue=message.queue)
|
|
97
|
+
await emit_event(
|
|
98
|
+
broker.middleware,
|
|
99
|
+
name,
|
|
100
|
+
message,
|
|
101
|
+
status=status,
|
|
102
|
+
delivery_id=fields.get("last_delivery_id")
|
|
103
|
+
or fields.get("delivery_id")
|
|
104
|
+
or None,
|
|
105
|
+
consumer_id=fields.get("last_consumer_id")
|
|
106
|
+
or fields.get("consumer_id")
|
|
107
|
+
or None,
|
|
108
|
+
attempt=int(fields.get("attempt", 0)),
|
|
109
|
+
reason=reason,
|
|
110
|
+
error_type=error_type,
|
|
111
|
+
backend="redis",
|
|
112
|
+
event_sink=broker.event_sink,
|
|
113
|
+
serializer_name=fields.get("serializer_name"),
|
|
114
|
+
serializer_version=fields.get("serializer_version"),
|
|
115
|
+
)
|
|
116
|
+
except Exception:
|
|
117
|
+
logger.exception(
|
|
118
|
+
"taskqx failed to publish committed maintenance event",
|
|
119
|
+
extra={"event": name},
|
|
120
|
+
)
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""具名 Redis Lua 脚本;调用方的 key/arg 布局由相邻测试固定。"""
|
|
2
|
+
|
|
3
|
+
BATCH_SUBMIT = """
|
|
4
|
+
local count = tonumber(ARGV[1]); local output = {}
|
|
5
|
+
for index = 0, count - 1 do
|
|
6
|
+
local key = index * 8; local arg = 2 + index * 15
|
|
7
|
+
local duplicate = false
|
|
8
|
+
if ARGV[arg] ~= '' then
|
|
9
|
+
local old = redis.call('GET', KEYS[key + 1])
|
|
10
|
+
if old then
|
|
11
|
+
table.insert(output, 0); table.insert(output, old); table.insert(output, redis.call('PTTL', KEYS[key + 1])); table.insert(output, '')
|
|
12
|
+
duplicate = true
|
|
13
|
+
else
|
|
14
|
+
redis.call('SET', KEYS[key + 1], ARGV[arg + 1], 'PX', ARGV[arg + 2])
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
if not duplicate then
|
|
18
|
+
local entry = ''
|
|
19
|
+
if ARGV[arg + 5] == 'ready' then
|
|
20
|
+
entry = redis.call('XADD', KEYS[key + 3], '*', 'message_id', ARGV[arg + 1], 'envelope', ARGV[arg + 3])
|
|
21
|
+
redis.call('ZADD', KEYS[key + 7], ARGV[arg + 11], ARGV[arg + 1])
|
|
22
|
+
end
|
|
23
|
+
redis.call('HSET', KEYS[key + 2], 'envelope', ARGV[arg + 3], 'queue', ARGV[arg + 4], 'status', ARGV[arg + 5], 'entry_id', entry, 'attempt', '0', 'max_attempts', ARGV[arg + 6], 'created_at', ARGV[arg + 7], 'expires_at', ARGV[arg + 8], 'serializer_name', ARGV[arg + 9], 'serializer_version', ARGV[arg + 10], 'available_at', ARGV[arg + 12], 'workflow_id', ARGV[arg + 13], 'parent_id', ARGV[arg + 14])
|
|
24
|
+
if ARGV[arg + 5] == 'delayed' then redis.call('ZADD', KEYS[key + 8], ARGV[arg + 12], ARGV[arg + 1]) end
|
|
25
|
+
if ARGV[arg + 5] == 'expired' then redis.call('HSET', KEYS[key + 2], 'expired_at', ARGV[arg + 7], 'status_at_expiry', 'ready', 'last_delivery_id', ''); redis.call('LPUSH', KEYS[key + 5], ARGV[arg + 1]) end
|
|
26
|
+
if (ARGV[arg + 5] == 'ready' or ARGV[arg + 5] == 'delayed') and ARGV[arg + 8] ~= '0' then redis.call('ZADD', KEYS[key + 4], ARGV[arg + 8], ARGV[arg + 1]) end
|
|
27
|
+
redis.call('HINCRBY', KEYS[key + 6], 'submitted_total', 1)
|
|
28
|
+
table.insert(output, 1); table.insert(output, ARGV[arg + 1]); table.insert(output, ARGV[arg + 2]); table.insert(output, entry)
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
return output
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
# Replay scripts move the message hash to the target queue and update the global
|
|
35
|
+
# lookup index. They require one source and one target queue keyspace.
|
|
36
|
+
REPLAY_DEAD_LETTER = """
|
|
37
|
+
if ARGV[7] == '0' and KEYS[7] ~= '' then local current = redis.call('GET', KEYS[7]); if current and current ~= ARGV[1] then return -1 end end
|
|
38
|
+
local fields = redis.call('HGETALL', KEYS[1])
|
|
39
|
+
if #fields == 0 or redis.call('LREM', KEYS[2], 1, ARGV[1]) == 0 then return 0 end
|
|
40
|
+
if ARGV[7] == '0' then if KEYS[6] ~= '' and redis.call('GET', KEYS[6]) == ARGV[1] then redis.call('DEL', KEYS[6]) end; if KEYS[7] ~= '' then redis.call('SET', KEYS[7], ARGV[1], 'PX', ARGV[8]) end end
|
|
41
|
+
if KEYS[8] ~= KEYS[1] then redis.call('HSET', KEYS[8], unpack(fields)); redis.call('DEL', KEYS[1]) end
|
|
42
|
+
local entry = redis.call('XADD', KEYS[3], '*', 'message_id', ARGV[1], 'envelope', ARGV[2])
|
|
43
|
+
redis.call('HSET', KEYS[8], 'envelope', ARGV[2], 'queue', ARGV[3], 'status', 'ready', 'entry_id', entry, 'attempt', ARGV[4], 'last_action', 'replayed')
|
|
44
|
+
redis.call('HSET', KEYS[9], ARGV[1], ARGV[3])
|
|
45
|
+
if ARGV[5] ~= '0' then redis.call('ZADD', KEYS[4], ARGV[5], ARGV[1]) end
|
|
46
|
+
redis.call('ZADD', KEYS[5], ARGV[6], ARGV[1]); return 1
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
REPLAY_EXPIRED = """
|
|
50
|
+
if ARGV[5] == '0' and KEYS[7] ~= '' then local current = redis.call('GET', KEYS[7]); if current and current ~= ARGV[1] then return -1 end end
|
|
51
|
+
local fields = redis.call('HGETALL', KEYS[1])
|
|
52
|
+
if #fields == 0 or redis.call('LREM', KEYS[2], 1, ARGV[1]) == 0 then return 0 end
|
|
53
|
+
if ARGV[5] == '0' then if KEYS[6] ~= '' and redis.call('GET', KEYS[6]) == ARGV[1] then redis.call('DEL', KEYS[6]) end; if KEYS[7] ~= '' then redis.call('SET', KEYS[7], ARGV[1], 'PX', ARGV[6]) end end
|
|
54
|
+
if KEYS[8] ~= KEYS[1] then redis.call('HSET', KEYS[8], unpack(fields)); redis.call('DEL', KEYS[1]) end
|
|
55
|
+
local entry = redis.call('XADD', KEYS[3], '*', 'message_id', ARGV[1], 'envelope', ARGV[2])
|
|
56
|
+
redis.call('HSET', KEYS[8], 'envelope', ARGV[2], 'queue', ARGV[7], 'status', 'ready', 'entry_id', entry, 'expires_at', ARGV[3], 'last_action', 'replayed')
|
|
57
|
+
redis.call('HSET', KEYS[9], ARGV[1], ARGV[7])
|
|
58
|
+
if ARGV[3] ~= '0' then redis.call('ZADD', KEYS[4], ARGV[3], ARGV[1]) end
|
|
59
|
+
redis.call('ZADD', KEYS[5], ARGV[4], ARGV[1]); return 1
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
PEL_RECOVER = """
|
|
63
|
+
if redis.call('HGET', KEYS[1], 'status') ~= 'ready' or redis.call('HGET', KEYS[1], 'entry_id') ~= ARGV[2] then return 0 end
|
|
64
|
+
redis.call('XACK', KEYS[2], ARGV[1], ARGV[2]); redis.call('XDEL', KEYS[2], ARGV[2])
|
|
65
|
+
local next_entry = redis.call('XADD', KEYS[2], '*', 'message_id', ARGV[3], 'envelope', redis.call('HGET', KEYS[1], 'envelope'))
|
|
66
|
+
redis.call('HSET', KEYS[1], 'entry_id', next_entry, 'last_action', 'pel_recovered')
|
|
67
|
+
redis.call('HINCRBY', KEYS[3], 'reclaimed_total', 1); return 1
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
CLAIM = """
|
|
71
|
+
local state = redis.call('HGET', KEYS[1], 'status')
|
|
72
|
+
if state ~= 'ready' or redis.call('HGET', KEYS[1], 'entry_id') ~= ARGV[8] then redis.call('XACK', KEYS[5], ARGV[7], ARGV[8]); redis.call('XDEL', KEYS[5], ARGV[8]); return 0 end
|
|
73
|
+
local expires = tonumber(redis.call('HGET', KEYS[1], 'expires_at') or '0')
|
|
74
|
+
if expires > 0 and expires <= tonumber(ARGV[1]) then
|
|
75
|
+
redis.call('HSET', KEYS[1], 'status', 'expired', 'last_action', 'expired', 'expired_at', ARGV[1], 'status_at_expiry', 'ready')
|
|
76
|
+
redis.call('XACK', KEYS[5], ARGV[7], ARGV[8]); redis.call('XDEL', KEYS[5], ARGV[8]); redis.call('LPUSH', KEYS[3], ARGV[2]); redis.call('ZREM', KEYS[4], ARGV[2]); redis.call('ZREM', KEYS[6], ARGV[2]); return -1
|
|
77
|
+
end
|
|
78
|
+
local attempt = redis.call('HINCRBY', KEYS[1], 'attempt', 1)
|
|
79
|
+
redis.call('HSET', KEYS[1], 'status', 'leased', 'consumer_id', ARGV[3], 'delivery_id', ARGV[4], 'lease_token', ARGV[5], 'claimed_at', ARGV[1], 'lease_until', ARGV[6], 'last_action', '', 'entry_id', ARGV[8])
|
|
80
|
+
redis.call('ZADD', KEYS[2], ARGV[6], ARGV[2]); redis.call('ZREM', KEYS[6], ARGV[2]); return attempt
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
EXTEND_LEASE = """
|
|
84
|
+
local time = redis.call('TIME'); local now = tonumber(time[1]) + tonumber(time[2]) / 1000000
|
|
85
|
+
if redis.call('HGET', KEYS[1], 'status') ~= 'leased' or redis.call('HGET', KEYS[1], 'delivery_id') ~= ARGV[1] or redis.call('HGET', KEYS[1], 'lease_token') ~= ARGV[2] or tonumber(redis.call('HGET', KEYS[1], 'lease_until') or '0') <= now then return 0 end
|
|
86
|
+
local expires = tonumber(redis.call('HGET', KEYS[1], 'expires_at') or '0')
|
|
87
|
+
if expires > 0 and expires <= now then
|
|
88
|
+
local entry = redis.call('HGET', KEYS[1], 'entry_id'); redis.call('XACK', KEYS[3], ARGV[5], entry); redis.call('XDEL', KEYS[3], entry)
|
|
89
|
+
redis.call('HSET', KEYS[1], 'status', 'expired', 'last_action', 'expired', 'expired_at', now, 'status_at_expiry', 'leased', 'last_delivery_id', ARGV[1]); redis.call('HDEL', KEYS[1], 'consumer_id', 'delivery_id', 'lease_token', 'claimed_at', 'lease_until')
|
|
90
|
+
redis.call('ZREM', KEYS[2], ARGV[4]); redis.call('ZREM', KEYS[4], ARGV[4]); redis.call('LPUSH', KEYS[5], ARGV[4]); return -1
|
|
91
|
+
end
|
|
92
|
+
redis.call('HSET', KEYS[1], 'lease_until', ARGV[3]); redis.call('ZADD', KEYS[2], ARGV[3], ARGV[4]); return 1
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
# KEYS: message, leases, expiry, stream, eq, stats, dlq, ready, delayed, retention.
|
|
96
|
+
# ARGV: action, delivery_id, token, now, message_id, reason, error_type, group,
|
|
97
|
+
# retry_available_at, requested_max_attempts, ack_tombstone_ttl.
|
|
98
|
+
FINISH = """
|
|
99
|
+
local status = redis.call('HGET', KEYS[1], 'status'); local current = redis.call('HGET', KEYS[1], 'delivery_id')
|
|
100
|
+
if status ~= 'leased' then if redis.call('HGET', KEYS[1], 'last_delivery_id') == ARGV[2] and redis.call('HGET', KEYS[1], 'last_action') == ARGV[1] then return 2 end; return 0 end
|
|
101
|
+
if current ~= ARGV[2] or redis.call('HGET', KEYS[1], 'lease_token') ~= ARGV[3] or tonumber(redis.call('HGET', KEYS[1], 'lease_until') or '0') <= tonumber(ARGV[4]) then return 0 end
|
|
102
|
+
local entry = redis.call('HGET', KEYS[1], 'entry_id'); local expires = tonumber(redis.call('HGET', KEYS[1], 'expires_at') or '0')
|
|
103
|
+
if expires > 0 and expires <= tonumber(ARGV[4]) then
|
|
104
|
+
redis.call('HSET', KEYS[1], 'status', 'expired', 'last_action', 'expired', 'expired_at', ARGV[4], 'status_at_expiry', 'leased', 'last_delivery_id', ARGV[2]); redis.call('HDEL', KEYS[1], 'consumer_id', 'delivery_id', 'lease_token', 'claimed_at', 'lease_until')
|
|
105
|
+
redis.call('XACK', KEYS[4], ARGV[8], entry); redis.call('XDEL', KEYS[4], entry); redis.call('ZREM', KEYS[2], ARGV[5]); redis.call('ZREM', KEYS[3], ARGV[5]); redis.call('ZREM', KEYS[8], ARGV[5]); redis.call('ZREM', KEYS[9], ARGV[5]); redis.call('LPUSH', KEYS[5], ARGV[5]); return 3
|
|
106
|
+
end
|
|
107
|
+
local attempt = tonumber(redis.call('HGET', KEYS[1], 'attempt')); local stored_max = tonumber(redis.call('HGET', KEYS[1], 'max_attempts')); local requested_max = tonumber(ARGV[10]); local max_attempts = (requested_max > 0 and math.min(stored_max, requested_max)) or stored_max
|
|
108
|
+
redis.call('ZREM', KEYS[2], ARGV[5])
|
|
109
|
+
if ARGV[1] == 'ack' then
|
|
110
|
+
redis.call('XACK', KEYS[4], ARGV[8], entry); redis.call('XDEL', KEYS[4], entry); local retention_until = tonumber(ARGV[4]) + tonumber(ARGV[11]); redis.call('HSET', KEYS[1], 'status', 'acked', 'last_action', 'ack', 'last_delivery_id', ARGV[2], 'acked_at', ARGV[4], 'retention_until', retention_until); redis.call('HDEL', KEYS[1], 'consumer_id', 'delivery_id', 'lease_token', 'claimed_at', 'lease_until'); redis.call('ZREM', KEYS[3], ARGV[5]); redis.call('ZADD', KEYS[10], retention_until, ARGV[5]); redis.call('HINCRBY', KEYS[6], 'acked_total', 1); return 4
|
|
111
|
+
elseif ARGV[1] == 'retry' and attempt < max_attempts then
|
|
112
|
+
redis.call('XACK', KEYS[4], ARGV[8], entry); redis.call('XDEL', KEYS[4], entry); local next_status = 'ready'; local new_entry = ''
|
|
113
|
+
if tonumber(ARGV[9]) > 0 then next_status = 'delayed'; redis.call('ZADD', KEYS[9], ARGV[9], ARGV[5]) else new_entry = redis.call('XADD', KEYS[4], '*', 'message_id', ARGV[5], 'envelope', redis.call('HGET', KEYS[1], 'envelope')); redis.call('ZADD', KEYS[8], ARGV[4], ARGV[5]) end
|
|
114
|
+
redis.call('HSET', KEYS[1], 'status', next_status, 'entry_id', new_entry, 'available_at', ARGV[9], 'last_action', 'retry', 'last_reason', ARGV[6], 'last_delivery_id', ARGV[2]); redis.call('HDEL', KEYS[1], 'consumer_id', 'delivery_id', 'lease_token', 'claimed_at', 'lease_until'); redis.call('HINCRBY', KEYS[6], 'retried_total', 1); return 5
|
|
115
|
+
else
|
|
116
|
+
local source = ARGV[1] == 'reject' and 'reject' or 'retry_limit'; redis.call('XACK', KEYS[4], ARGV[8], entry); redis.call('XDEL', KEYS[4], entry); redis.call('HSET', KEYS[1], 'status', 'dead_lettered', 'last_action', ARGV[1], 'last_reason', ARGV[6], 'dead_source', source, 'failed_at', ARGV[4], 'error_type', ARGV[7], 'last_delivery_id', ARGV[2]); redis.call('HDEL', KEYS[1], 'consumer_id', 'delivery_id', 'lease_token', 'claimed_at', 'lease_until'); redis.call('ZREM', KEYS[3], ARGV[5]); redis.call('LPUSH', KEYS[7], ARGV[5]); redis.call('HINCRBY', KEYS[6], 'dead_lettered_total', 1); return 6
|
|
117
|
+
end
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
# Maintenance scripts are invoked for one message at a time. Their keys and
|
|
121
|
+
# argv order are fixed at RedisBroker.maintain and intentionally kept here.
|
|
122
|
+
DUE_DELAYED = """
|
|
123
|
+
if redis.call('HGET', KEYS[1], 'status') ~= 'delayed' then return 0 end
|
|
124
|
+
local available = tonumber(redis.call('HGET', KEYS[1], 'available_at') or '0'); if available == 0 or available > tonumber(ARGV[1]) then return 0 end
|
|
125
|
+
local expires = tonumber(redis.call('HGET', KEYS[1], 'expires_at') or '0')
|
|
126
|
+
if expires > 0 and expires <= tonumber(ARGV[1]) then
|
|
127
|
+
redis.call('HSET', KEYS[1], 'status', 'expired', 'last_action', 'expired', 'expired_at', ARGV[1], 'status_at_expiry', 'delayed', 'last_delivery_id', ''); redis.call('ZREM', KEYS[2], ARGV[2]); redis.call('ZREM', KEYS[3], ARGV[2]); redis.call('ZREM', KEYS[6], ARGV[2]); redis.call('LPUSH', KEYS[5], ARGV[2]); return 2
|
|
128
|
+
end
|
|
129
|
+
local entry = redis.call('XADD', KEYS[4], '*', 'message_id', ARGV[2], 'envelope', redis.call('HGET', KEYS[1], 'envelope'))
|
|
130
|
+
redis.call('HSET', KEYS[1], 'status', 'ready', 'entry_id', entry, 'available_at', '', 'last_action', 'due'); redis.call('ZREM', KEYS[2], ARGV[2]); redis.call('ZADD', KEYS[3], ARGV[1], ARGV[2]); return 1
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
EXPIRE = """
|
|
134
|
+
local status = redis.call('HGET', KEYS[1], 'status'); local expires = tonumber(redis.call('HGET', KEYS[1], 'expires_at') or '0')
|
|
135
|
+
if (status ~= 'ready' and status ~= 'leased' and status ~= 'delayed') or expires == 0 or expires > tonumber(ARGV[1]) then return 0 end
|
|
136
|
+
local entry = redis.call('HGET', KEYS[1], 'entry_id'); if entry and entry ~= '' then redis.call('XACK', KEYS[4], ARGV[2], entry); redis.call('XDEL', KEYS[4], entry) end
|
|
137
|
+
redis.call('HSET', KEYS[1], 'status', 'expired', 'last_action', 'expired', 'expired_at', ARGV[1], 'status_at_expiry', status, 'last_delivery_id', redis.call('HGET', KEYS[1], 'delivery_id') or ''); redis.call('HDEL', KEYS[1], 'consumer_id', 'delivery_id', 'lease_token', 'claimed_at', 'lease_until')
|
|
138
|
+
redis.call('ZREM', KEYS[2], ARGV[3]); redis.call('ZREM', KEYS[3], ARGV[3]); redis.call('ZREM', KEYS[6], ARGV[3]); redis.call('ZREM', KEYS[7], ARGV[3]); redis.call('LPUSH', KEYS[5], ARGV[3]); return 1
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
RECLAIM_LEASE = """
|
|
142
|
+
if redis.call('HGET', KEYS[1], 'status') ~= 'leased' or tonumber(redis.call('HGET', KEYS[1], 'lease_until') or '0') > tonumber(ARGV[1]) then return 0 end
|
|
143
|
+
local entry = redis.call('HGET', KEYS[1], 'entry_id'); local expires = tonumber(redis.call('HGET', KEYS[1], 'expires_at') or '0'); redis.call('XACK', KEYS[4], ARGV[2], entry); redis.call('XDEL', KEYS[4], entry); redis.call('ZREM', KEYS[2], ARGV[3])
|
|
144
|
+
if expires > 0 and expires <= tonumber(ARGV[1]) then
|
|
145
|
+
redis.call('HSET', KEYS[1], 'status', 'expired', 'last_action', 'expired', 'expired_at', ARGV[1], 'status_at_expiry', 'leased', 'last_delivery_id', redis.call('HGET', KEYS[1], 'delivery_id') or ''); redis.call('HDEL', KEYS[1], 'consumer_id', 'delivery_id', 'lease_token', 'claimed_at', 'lease_until'); redis.call('ZREM', KEYS[3], ARGV[3]); redis.call('LPUSH', KEYS[7], ARGV[3]); return 3
|
|
146
|
+
end
|
|
147
|
+
local attempt = tonumber(redis.call('HGET', KEYS[1], 'attempt')); local maximum = tonumber(redis.call('HGET', KEYS[1], 'max_attempts'))
|
|
148
|
+
if attempt >= maximum then
|
|
149
|
+
redis.call('HSET', KEYS[1], 'status', 'dead_lettered', 'dead_source', 'lease_timeout', 'last_action', 'lease_timeout', 'last_delivery_id', redis.call('HGET', KEYS[1], 'delivery_id') or ''); redis.call('HDEL', KEYS[1], 'consumer_id', 'delivery_id', 'lease_token', 'claimed_at', 'lease_until'); redis.call('ZREM', KEYS[3], ARGV[3]); redis.call('LPUSH', KEYS[5], ARGV[3]); redis.call('HINCRBY', KEYS[6], 'dead_lettered_total', 1); return 2
|
|
150
|
+
else
|
|
151
|
+
local next_entry = redis.call('XADD', KEYS[4], '*', 'message_id', ARGV[3], 'envelope', redis.call('HGET', KEYS[1], 'envelope')); redis.call('HSET', KEYS[1], 'status', 'ready', 'entry_id', next_entry, 'last_action', 'reclaimed', 'last_delivery_id', redis.call('HGET', KEYS[1], 'delivery_id') or ''); redis.call('HDEL', KEYS[1], 'consumer_id', 'delivery_id', 'lease_token', 'claimed_at', 'lease_until'); redis.call('ZADD', KEYS[8], ARGV[1], ARGV[3]); redis.call('HINCRBY', KEYS[6], 'reclaimed_total', 1)
|
|
152
|
+
end
|
|
153
|
+
return 1
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
# Prune the business envelope of a due ACKED message while retaining its
|
|
157
|
+
# lightweight operational tombstone and global lookup index.
|
|
158
|
+
CLEANUP_ACKED = """
|
|
159
|
+
local status = redis.call('HGET', KEYS[1], 'status')
|
|
160
|
+
if not status then redis.call('ZREM', KEYS[2], ARGV[2]); return 0 end
|
|
161
|
+
if status ~= 'acked' then redis.call('ZREM', KEYS[2], ARGV[2]); return 0 end
|
|
162
|
+
local retention_until = tonumber(redis.call('HGET', KEYS[1], 'retention_until') or '0')
|
|
163
|
+
if retention_until == 0 or retention_until > tonumber(ARGV[1]) then return 0 end
|
|
164
|
+
redis.call('HDEL', KEYS[1], 'envelope'); redis.call('HSET', KEYS[1], 'payload_pruned', '1'); redis.call('ZREM', KEYS[2], ARGV[2]); return 1
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
# Single submit: eight keys; arguments mirror RedisSubmissionStore.submit.
|
|
168
|
+
SUBMIT = """
|
|
169
|
+
if ARGV[1] ~= '' then local old = redis.call('GET', KEYS[1]); if old then return {0, old, redis.call('PTTL', KEYS[1])} end; redis.call('SET', KEYS[1], ARGV[2], 'PX', ARGV[3]) end
|
|
170
|
+
local entry = ''
|
|
171
|
+
if ARGV[6] == 'ready' then entry = redis.call('XADD', KEYS[3], '*', 'message_id', ARGV[2], 'envelope', ARGV[4]); redis.call('ZADD', KEYS[7], ARGV[12], ARGV[2]) end
|
|
172
|
+
redis.call('HSET', KEYS[2], 'envelope', ARGV[4], 'queue', ARGV[5], 'status', ARGV[6], 'entry_id', entry, 'attempt', '0', 'max_attempts', ARGV[7], 'created_at', ARGV[8], 'expires_at', ARGV[9], 'available_at', ARGV[13], 'serializer_name', ARGV[10], 'serializer_version', ARGV[11], 'workflow_id', ARGV[14], 'parent_id', ARGV[15])
|
|
173
|
+
if ARGV[6] == 'delayed' then redis.call('ZADD', KEYS[8], ARGV[13], ARGV[2]) end
|
|
174
|
+
if ARGV[6] == 'expired' then redis.call('HSET', KEYS[2], 'expired_at', ARGV[8], 'status_at_expiry', 'ready', 'last_delivery_id', ''); redis.call('LPUSH', KEYS[5], ARGV[2]) end
|
|
175
|
+
if (ARGV[6] == 'ready' or ARGV[6] == 'delayed') and ARGV[9] ~= '0' then redis.call('ZADD', KEYS[4], ARGV[9], ARGV[2]) end
|
|
176
|
+
redis.call('HINCRBY', KEYS[6], 'submitted_total', 1); return {1, ARGV[2], ARGV[3], entry}
|
|
177
|
+
"""
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Redis delivery state transitions and PEL crash-window recovery."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime, timedelta
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from ..errors import LeaseLostError, ValidationError
|
|
9
|
+
from ..observability import metric
|
|
10
|
+
from ..types import FinishOutcome, MessageStatus
|
|
11
|
+
from ._time import datetime_from_timestamp as _datetime
|
|
12
|
+
from ._time import timestamp as _timestamp
|
|
13
|
+
from .redis_calls import claim_call, extend_lease_call, finish_call, pel_recover_call
|
|
14
|
+
from .redis_components import RedisDelivery
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from .redis import RedisBroker
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RedisStateMachine:
|
|
21
|
+
"""Own Redis Stream/Lua delivery transitions; broker exposes delegates only."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, broker: RedisBroker) -> None:
|
|
24
|
+
self._broker = broker
|
|
25
|
+
|
|
26
|
+
async def claim(
|
|
27
|
+
self, queue: str, consumer_id: str, lease_seconds: float
|
|
28
|
+
) -> RedisDelivery | None:
|
|
29
|
+
broker = self._broker
|
|
30
|
+
await broker.maintain(queue)
|
|
31
|
+
await broker._ensure_group(queue)
|
|
32
|
+
now = await broker._now()
|
|
33
|
+
received = await broker._redis.xreadgroup(
|
|
34
|
+
broker._group_name(),
|
|
35
|
+
consumer_id,
|
|
36
|
+
{broker._queue_key(queue, "stream"): ">"},
|
|
37
|
+
count=1,
|
|
38
|
+
block=1,
|
|
39
|
+
)
|
|
40
|
+
if not received:
|
|
41
|
+
return None
|
|
42
|
+
_, entries = received[0]
|
|
43
|
+
entry_id, fields = entries[0]
|
|
44
|
+
message_id = fields["message_id"]
|
|
45
|
+
delivery_id, token = broker._id_factory(), broker._id_factory()
|
|
46
|
+
lease_until = now + timedelta(seconds=lease_seconds)
|
|
47
|
+
status = int(
|
|
48
|
+
await claim_call(
|
|
49
|
+
broker,
|
|
50
|
+
queue=queue,
|
|
51
|
+
message_id=message_id,
|
|
52
|
+
now=_timestamp(now),
|
|
53
|
+
consumer_id=consumer_id,
|
|
54
|
+
delivery_id=delivery_id,
|
|
55
|
+
token=token,
|
|
56
|
+
lease_until=_timestamp(lease_until),
|
|
57
|
+
entry_id=entry_id,
|
|
58
|
+
).execute(broker._redis)
|
|
59
|
+
)
|
|
60
|
+
if status == -1:
|
|
61
|
+
await broker._emit_maintenance_event(
|
|
62
|
+
queue,
|
|
63
|
+
message_id,
|
|
64
|
+
"expired",
|
|
65
|
+
MessageStatus.EXPIRED.value,
|
|
66
|
+
reason="expired_during_claim",
|
|
67
|
+
metric_name="expired_total",
|
|
68
|
+
)
|
|
69
|
+
return None
|
|
70
|
+
if status <= 0:
|
|
71
|
+
return None
|
|
72
|
+
fields = await broker._redis.hgetall(broker._message_key(queue, message_id))
|
|
73
|
+
delivery = RedisDelivery(
|
|
74
|
+
broker,
|
|
75
|
+
broker._decode(
|
|
76
|
+
fields["envelope"],
|
|
77
|
+
fields.get("serializer_name"),
|
|
78
|
+
fields.get("serializer_version"),
|
|
79
|
+
),
|
|
80
|
+
delivery_id,
|
|
81
|
+
token,
|
|
82
|
+
consumer_id,
|
|
83
|
+
status,
|
|
84
|
+
now,
|
|
85
|
+
lease_until,
|
|
86
|
+
)
|
|
87
|
+
await broker._observability.claimed(delivery)
|
|
88
|
+
return delivery
|
|
89
|
+
|
|
90
|
+
async def finish(
|
|
91
|
+
self,
|
|
92
|
+
delivery: RedisDelivery,
|
|
93
|
+
action: str,
|
|
94
|
+
reason: str | None = None,
|
|
95
|
+
error: BaseException | None = None,
|
|
96
|
+
delay: timedelta | None = None,
|
|
97
|
+
max_attempts: int | None = None,
|
|
98
|
+
) -> FinishOutcome:
|
|
99
|
+
broker = self._broker
|
|
100
|
+
now = await broker._now()
|
|
101
|
+
if delay is not None and delay.total_seconds() < 0:
|
|
102
|
+
raise ValidationError("delay 不能为负数")
|
|
103
|
+
if max_attempts is not None and max_attempts < 1:
|
|
104
|
+
raise ValidationError("max_attempts 必须大于等于 1")
|
|
105
|
+
queue, message_id = delivery.message.queue, delivery.message.id
|
|
106
|
+
error_type = type(error).__name__ if error else ""
|
|
107
|
+
result = int(
|
|
108
|
+
await finish_call(
|
|
109
|
+
broker,
|
|
110
|
+
queue=queue,
|
|
111
|
+
message_id=message_id,
|
|
112
|
+
action=action,
|
|
113
|
+
delivery_id=delivery.delivery_id,
|
|
114
|
+
token=delivery._lease_token,
|
|
115
|
+
now=_timestamp(now),
|
|
116
|
+
reason=reason or "",
|
|
117
|
+
error_type=error_type,
|
|
118
|
+
retry_available_at=_timestamp(now + delay)
|
|
119
|
+
if delay and delay.total_seconds() > 0
|
|
120
|
+
else None,
|
|
121
|
+
max_attempts=max_attempts,
|
|
122
|
+
ack_tombstone_ttl=broker._ack_tombstone_ttl(queue).total_seconds(),
|
|
123
|
+
).execute(broker._redis)
|
|
124
|
+
)
|
|
125
|
+
if result == 0:
|
|
126
|
+
await metric(broker.metrics, "lease_lost_total", queue=queue)
|
|
127
|
+
raise LeaseLostError("租约已经失效,不能终结当前投递")
|
|
128
|
+
if result == 2:
|
|
129
|
+
return FinishOutcome.IDEMPOTENT
|
|
130
|
+
outcome = {
|
|
131
|
+
3: FinishOutcome.EXPIRED,
|
|
132
|
+
4: FinishOutcome.ACKED,
|
|
133
|
+
5: FinishOutcome.RETRIED,
|
|
134
|
+
6: FinishOutcome.DEAD_LETTERED,
|
|
135
|
+
}[result]
|
|
136
|
+
await broker._observability.finished(
|
|
137
|
+
delivery, outcome, reason=reason, error_type=error_type or None
|
|
138
|
+
)
|
|
139
|
+
return outcome
|
|
140
|
+
|
|
141
|
+
async def extend(self, delivery: RedisDelivery, seconds: float | None) -> datetime:
|
|
142
|
+
broker = self._broker
|
|
143
|
+
period = seconds if seconds is not None else delivery._lease_seconds
|
|
144
|
+
if period <= 0:
|
|
145
|
+
raise ValidationError("续租时长必须为正数")
|
|
146
|
+
now = await broker._now()
|
|
147
|
+
until = now + timedelta(seconds=period)
|
|
148
|
+
fields = await broker._redis.hgetall(
|
|
149
|
+
broker._message_key(delivery.message.queue, delivery.message.id)
|
|
150
|
+
)
|
|
151
|
+
if fields.get("expires_at") and float(fields["expires_at"]) > 0:
|
|
152
|
+
until = min(until, _datetime(float(fields["expires_at"])) or until)
|
|
153
|
+
result = int(
|
|
154
|
+
await extend_lease_call(
|
|
155
|
+
broker,
|
|
156
|
+
queue=delivery.message.queue,
|
|
157
|
+
message_id=delivery.message.id,
|
|
158
|
+
delivery_id=delivery.delivery_id,
|
|
159
|
+
token=delivery._lease_token,
|
|
160
|
+
lease_until=_timestamp(until),
|
|
161
|
+
).execute(broker._redis)
|
|
162
|
+
)
|
|
163
|
+
if result == -1:
|
|
164
|
+
await broker._emit_maintenance_event(
|
|
165
|
+
delivery.message.queue,
|
|
166
|
+
delivery.message.id,
|
|
167
|
+
"expired",
|
|
168
|
+
MessageStatus.EXPIRED.value,
|
|
169
|
+
reason="expired_during_lease_extension",
|
|
170
|
+
metric_name="expired_total",
|
|
171
|
+
)
|
|
172
|
+
raise LeaseLostError("消息已过期")
|
|
173
|
+
if result != 1:
|
|
174
|
+
raise LeaseLostError("租约已经失效,不能续租")
|
|
175
|
+
return until
|
|
176
|
+
|
|
177
|
+
async def recover_uncommitted_pel(self, queue: str) -> int:
|
|
178
|
+
broker = self._broker
|
|
179
|
+
stream = broker._queue_key(queue, "stream")
|
|
180
|
+
try:
|
|
181
|
+
_, entries, _ = await broker._redis.xautoclaim(
|
|
182
|
+
stream,
|
|
183
|
+
broker._group_name(),
|
|
184
|
+
"taskqx-reclaimer",
|
|
185
|
+
min_idle_time=broker._pending_recovery_ms,
|
|
186
|
+
start_id="0-0",
|
|
187
|
+
count=100,
|
|
188
|
+
)
|
|
189
|
+
except Exception as exc:
|
|
190
|
+
if "NOGROUP" in str(exc):
|
|
191
|
+
return 0
|
|
192
|
+
raise
|
|
193
|
+
restored = 0
|
|
194
|
+
for entry_id, fields in entries:
|
|
195
|
+
message_id = fields["message_id"]
|
|
196
|
+
moved = int(
|
|
197
|
+
await pel_recover_call(
|
|
198
|
+
broker,
|
|
199
|
+
queue=queue,
|
|
200
|
+
message_id=message_id,
|
|
201
|
+
entry_id=entry_id,
|
|
202
|
+
).execute(broker._redis)
|
|
203
|
+
)
|
|
204
|
+
restored += moved
|
|
205
|
+
if moved:
|
|
206
|
+
await broker._emit_maintenance_event(
|
|
207
|
+
queue,
|
|
208
|
+
message_id,
|
|
209
|
+
"pel_recovered",
|
|
210
|
+
MessageStatus.READY.value,
|
|
211
|
+
reason="pending entry recovery",
|
|
212
|
+
metric_name="reclaimed_total",
|
|
213
|
+
)
|
|
214
|
+
return restored
|