RedisBackend
class reference
In most cases, you don't need to interact with backends directly, as they are used internally by Queue
. For usual usage, see the Queue reference and Getting Started guides to learn how to configure and use different backends.
If you need to implement a custom backend or want to understand how existing backends work, here's the reference information for the backend classes.
sheppy.RedisBackend
RedisBackend(
url: str = "redis://127.0.0.1:6379",
consumer_group: str = "workers",
ttl: int | None = 24 * 60 * 60,
**kwargs: Any,
)
Bases: Backend
Source code in src/sheppy/backend/redis.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 | def __init__(
self,
url: str = "redis://127.0.0.1:6379",
consumer_group: str = "workers",
ttl: int | None = 24 * 60 * 60, # 24 hours
**kwargs: Any
):
self.url = url
self.consumer_group = consumer_group
self.consumer_name = generate_unique_worker_id("consumer")
self.ttl = ttl
self.redis_kwargs = kwargs
self._client: redis.Redis | None = None
self._pool: redis.ConnectionPool | None = None
self._pending_messages: dict[str, tuple[str, str]] = {} # task_id -> (queue_name, message_id)
self._initialized_groups: set[str] = set()
self._results_stream_ttl = 60
|
consumer_group
consumer_group = consumer_group
consumer_name
consumer_name = generate_unique_worker_id('consumer')
connect
Source code in src/sheppy/backend/redis.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 | async def connect(self) -> None:
try:
self._pool = redis.ConnectionPool.from_url(
self.url,
#decode_responses=self.decode_responses,
#max_connections=self.max_connections,
#protocol=3, # enable RESP version 3
**self.redis_kwargs
)
self._client = redis.Redis.from_pool(self._pool)
await self._client.ping()
except Exception as e:
self._client = None
self._pool = None
raise BackendError(f"Failed to connect to Redis: {e}") from e
|
disconnect
Source code in src/sheppy/backend/redis.py
| async def disconnect(self) -> None:
if self._client:
await self._client.aclose()
self._client = None
self._pool = None
self._pending_messages.clear()
self._initialized_groups.clear()
|
append
append(
queue_name: str,
tasks: list[dict[str, Any]],
unique: bool = True,
) -> list[bool]
Add new tasks to be processed.
Source code in src/sheppy/backend/redis.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141 | async def append(self, queue_name: str, tasks: list[dict[str, Any]], unique: bool = True) -> list[bool]:
"""Add new tasks to be processed."""
tasks_metadata_key = self._tasks_metadata_key(queue_name)
pending_tasks_key = self._pending_tasks_key(queue_name)
await self._ensure_consumer_group(pending_tasks_key)
if unique:
success = await self._create_tasks(queue_name, tasks)
to_queue = [t for i, t in enumerate(tasks) if success[i]]
else:
success = [True] * len(tasks)
to_queue = tasks
try:
async with self.client.pipeline(transaction=False) as pipe:
for t in to_queue:
_task_data = json.dumps(t)
if not unique:
pipe.set(f"{tasks_metadata_key}:{t['id']}", _task_data)
# add to pending stream
pipe.xadd(pending_tasks_key, {"data": _task_data})
await pipe.execute()
except Exception as e:
raise BackendError(f"Failed to enqueue task: {e}") from e
return success
|
pop
pop(
queue_name: str,
limit: int = 1,
timeout: float | None = None,
) -> list[dict[str, Any]]
Get next tasks to process. Used primarily by workers.
Source code in src/sheppy/backend/redis.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177 | async def pop(self, queue_name: str, limit: int = 1, timeout: float | None = None) -> list[dict[str, Any]]:
"""Get next tasks to process. Used primarily by workers."""
pending_tasks_key = self._pending_tasks_key(queue_name)
await self._ensure_consumer_group(pending_tasks_key)
try:
result = await self.client.xreadgroup(
groupname=self.consumer_group,
consumername=self.consumer_name,
streams={pending_tasks_key: ">"}, # ">" means only new messages (not delivered to other consumers)
count=limit,
block=None if timeout is None or timeout == 0 else int(timeout * 1000)
)
if not result:
return []
messages = result[0][1] # [['stream-name', [(message_id, dict_data)]]]
if not messages:
return []
tasks = []
for message_id, fields in messages:
task_data = json.loads(fields[b"data"])
# store message_id for acknowledge()
self._pending_messages[task_data["id"]] = (queue_name, message_id.decode())
tasks.append(task_data)
return tasks
except Exception as e:
raise BackendError(f"Failed to dequeue task: {e}") from e
|
get_pending
get_pending(
queue_name: str, count: int = 1
) -> list[dict[str, Any]]
Source code in src/sheppy/backend/redis.py
179
180
181
182
183
184
185
186 | async def get_pending(self, queue_name: str, count: int = 1) -> list[dict[str, Any]]:
pending_tasks_key = self._pending_tasks_key(queue_name)
await self._ensure_consumer_group(pending_tasks_key)
messages = await self.client.xrange(pending_tasks_key, count=count)
return [json.loads(fields[b"data"]) for _message_id, fields in messages]
|
size
size(queue_name: str) -> int
Source code in src/sheppy/backend/redis.py
| async def size(self, queue_name: str) -> int:
pending_tasks_key = self._pending_tasks_key(queue_name)
await self._ensure_consumer_group(pending_tasks_key)
return int(await self.client.xlen(pending_tasks_key))
|
clear
clear(queue_name: str) -> int
Source code in src/sheppy/backend/redis.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212 | async def clear(self, queue_name: str) -> int:
tasks_metadata_key = self._tasks_metadata_key(queue_name)
pending_tasks_key = self._pending_tasks_key(queue_name)
scheduled_key = self._scheduled_tasks_key(queue_name)
await self._ensure_consumer_group(pending_tasks_key)
keys = await self.client.keys(f"{tasks_metadata_key}:*")
if not keys:
return 0
count = await self.client.delete(*keys)
await self.client.xtrim(pending_tasks_key, maxlen=0)
await self.client.delete(scheduled_key)
# await self.client.delete(tasks_metadata_key)
return int(count)
|
get_tasks
get_tasks(
queue_name: str, task_ids: list[str]
) -> dict[str, dict[str, Any]]
Source code in src/sheppy/backend/redis.py
214
215
216
217
218
219
220
221
222
223 | async def get_tasks(self, queue_name: str, task_ids: list[str]) -> dict[str,dict[str, Any]]:
tasks_metadata_key = self._tasks_metadata_key(queue_name)
if not task_ids:
return {}
task_json = await self.client.mget([f"{tasks_metadata_key}:{t}" for t in task_ids])
tasks = [json.loads(d) for d in task_json if d]
return {t['id']: t for t in tasks}
|
schedule
schedule(
queue_name: str,
task_data: dict[str, Any],
at: datetime,
unique: bool = True,
) -> bool
Source code in src/sheppy/backend/redis.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246 | async def schedule(self, queue_name: str, task_data: dict[str, Any], at: datetime, unique: bool = True) -> bool:
tasks_metadata_key = self._tasks_metadata_key(queue_name)
scheduled_key = self._scheduled_tasks_key(queue_name)
if unique:
success = await self._create_tasks(queue_name, [task_data])
if not success[0]:
return False
try:
_task_data = json.dumps(task_data)
if not unique:
await self.client.set(f"{tasks_metadata_key}:{task_data['id']}", _task_data)
# add to sorted set with timestamp as score
score = at.timestamp()
await self.client.zadd(scheduled_key, {_task_data: score})
return True
except Exception as e:
raise BackendError(f"Failed to schedule task: {e}") from e
|
pop_scheduled
pop_scheduled(
queue_name: str, now: datetime | None = None
) -> list[dict[str, Any]]
Source code in src/sheppy/backend/redis.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265 | async def pop_scheduled(self, queue_name: str, now: datetime | None = None) -> list[dict[str, Any]]:
scheduled_key = self._scheduled_tasks_key(queue_name)
score = now.timestamp() if now else time()
task_jsons = await self.client.zrangebyscore(scheduled_key, 0, score)
tasks = []
for task_json in task_jsons:
removed = await self.client.zrem(scheduled_key, task_json)
if removed <= 0:
# some other worker already got this task at the same time, skip
continue
tasks.append(json.loads(task_json))
return tasks
|
store_result
store_result(
queue_name: str, task_data: dict[str, Any]
) -> bool
Source code in src/sheppy/backend/redis.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299 | async def store_result(self, queue_name: str, task_data: dict[str, Any]) -> bool:
tasks_metadata_key = self._tasks_metadata_key(queue_name)
finished_tasks_key = self._finished_tasks_key(queue_name)
pending_tasks_key = self._pending_tasks_key(queue_name)
await self._ensure_consumer_group(finished_tasks_key)
message_id = None
if task_data["id"] in self._pending_messages:
stored_queue, message_id = self._pending_messages[task_data["id"]]
if queue_name != stored_queue: # this should never happen
raise BackendError("queue name mismatch")
try:
# trim older messages to keep the stream small
min_id = f"{int((time() - self._results_stream_ttl) * 1000)}-0"
async with self.client.pipeline(transaction=True) as pipe:
# update task metadata with the results
pipe.set(f"{tasks_metadata_key}:{task_data['id']}", json.dumps(task_data), ex=self.ttl)
# add to finished stream for get_result notifications
if task_data["finished_at"] is not None: # only send notification on finished task (for retriable tasks we continue to wait)
pipe.xadd(finished_tasks_key, {"task_id": task_data["id"]}, minid=min_id)
# ack and delete the task from the stream (cleanup)
if message_id:
pipe.xackdel(pending_tasks_key, self.consumer_group, message_id)
await (pipe.execute())
return True
except Exception as e:
raise BackendError(f"Failed to store task result: {e}") from e
|
get_stats
get_stats(queue_name: str) -> dict[str, int]
Source code in src/sheppy/backend/redis.py
301
302
303
304
305
306
307
308
309
310
311
312
313 | async def get_stats(self, queue_name: str) -> dict[str, int]:
scheduled_tasks_key = self._scheduled_tasks_key(queue_name)
pending_tasks_key = self._pending_tasks_key(queue_name)
finished_tasks_key = self._finished_tasks_key(queue_name)
pending = await self.client.xlen(pending_tasks_key)
completed = await self.client.xlen(finished_tasks_key)
return {
"pending": pending,
"completed": completed,
"scheduled": await self.client.zcard(scheduled_tasks_key),
}
|
get_all_tasks
get_all_tasks(queue_name: str) -> list[dict[str, Any]]
Source code in src/sheppy/backend/redis.py
315
316
317
318
319
320
321
322
323
324 | async def get_all_tasks(self, queue_name: str) -> list[dict[str, Any]]:
tasks_metadata_key = self._tasks_metadata_key(queue_name)
keys = await self.client.keys(f"{tasks_metadata_key}:*")
if not keys:
return []
all_tasks_data = await self.client.mget(keys)
return [json.loads(task_json) for task_json in all_tasks_data]
|
get_results
get_results(
queue_name: str,
task_ids: list[str],
timeout: float | None = None,
) -> dict[str, dict[str, Any]]
Source code in src/sheppy/backend/redis.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393 | async def get_results(self, queue_name: str, task_ids: list[str], timeout: float | None = None) -> dict[str,dict[str, Any]]:
tasks_metadata_key = self._tasks_metadata_key(queue_name)
finished_tasks_key = self._finished_tasks_key(queue_name)
if not task_ids:
return {}
results = {}
remaining_ids = task_ids[:]
last_id = "0-0"
if timeout is not None and timeout >= 0:
with contextlib.suppress(redis.ResponseError):
last_id = (await self.client.xinfo_stream(finished_tasks_key))["last-generated-id"]
tasks = await self.client.mget([f"{tasks_metadata_key}:{t}" for t in task_ids])
for task_json in tasks:
if not task_json:
continue
t = json.loads(task_json)
if t.get("finished_at"):
results[t["id"]] = t
remaining_ids.remove(t["id"])
if not remaining_ids:
return results
if timeout is None or timeout < 0:
return results
# endless wait if timeout == 0
deadline = None if timeout == 0 else asyncio.get_event_loop().time() + timeout
while True:
if deadline:
remaining = deadline - asyncio.get_event_loop().time()
if remaining <= 0:
raise TimeoutError(f"Did not complete within {timeout} seconds")
else:
remaining = 0
messages = await self.client.xread(
{finished_tasks_key: last_id},
block=int(remaining * 1000),
count=100
)
if not messages:
continue
for _, stream_messages in messages:
for msg_id, data in stream_messages:
last_id = msg_id
task_id = data.get(b"task_id").decode()
if task_id in remaining_ids:
task_json = await self.client.get(f"{tasks_metadata_key}:{task_id}")
if not task_json:
continue
t = json.loads(task_json)
if t.get("finished_at"): # should be always true because we only get notifications for finished tasks
results[t["id"]] = t
remaining_ids.remove(t["id"])
if not remaining_ids:
return results
|
list_queues
list_queues() -> dict[str, int]
Source code in src/sheppy/backend/redis.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423 | async def list_queues(self) -> dict[str, int]:
queue_names = set()
for key in await self.client.keys("sheppy:*:*"):
queue_names.add(key.decode().split(":")[2])
queues = {}
for queue_name in sorted(queue_names):
try:
pending_count = await self.client.xlen(self._pending_tasks_key(queue_name))
queues[queue_name] = int(pending_count)
except redis.ResponseError:
queues[queue_name] = 0
return queues
|
get_scheduled
get_scheduled(queue_name: str) -> list[dict[str, Any]]
Source code in src/sheppy/backend/redis.py
425
426
427
428
429
430
431
432
433
434 | async def get_scheduled(self, queue_name: str) -> list[dict[str, Any]]:
scheduled_key = self._scheduled_tasks_key(queue_name)
task_jsons = await self.client.zrange(scheduled_key, 0, -1, withscores=True)
tasks = []
for task_json, _score in task_jsons:
tasks.append(json.loads(task_json))
return tasks
|
add_cron
add_cron(
queue_name: str,
deterministic_id: str,
task_cron: dict[str, Any],
) -> bool
Source code in src/sheppy/backend/redis.py
| async def add_cron(self, queue_name: str, deterministic_id: str, task_cron: dict[str, Any]) -> bool:
cron_tasks_key = self._cron_tasks_key(queue_name)
return bool(await self.client.set(f"{cron_tasks_key}:{deterministic_id}", json.dumps(task_cron), nx=True))
|
delete_cron
delete_cron(queue_name: str, deterministic_id: str) -> bool
Source code in src/sheppy/backend/redis.py
| async def delete_cron(self, queue_name: str, deterministic_id: str) -> bool:
cron_tasks_key = self._cron_tasks_key(queue_name)
return bool(await self.client.delete(f"{cron_tasks_key}:{deterministic_id}"))
|
get_crons
get_crons(queue_name: str) -> list[dict[str, Any]]
Source code in src/sheppy/backend/redis.py
444
445
446
447
448
449
450
451 | async def get_crons(self, queue_name: str) -> list[dict[str, Any]]:
cron_tasks_key = self._cron_tasks_key(queue_name)
cron_tasks = await self.client.keys(f"{cron_tasks_key}:*")
if not cron_tasks:
return []
return [json.loads(d) for d in await self.client.mget(cron_tasks) if d is not None]
|