Skip to content

Commit 508d986

Browse files
committed
chore: streamline vacuuming and examples
1 parent 39d4192 commit 508d986

6 files changed

Lines changed: 79 additions & 22 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
88
## [Unreleased]
99

1010
- *chore*: add sentinel example
11-
- *feat**: idempotency for tasks (#67)
11+
- *feat*: idempotency for tasks (#67)
12+
- *chore*: streamline vacuuming and examples (#68)
1213

1314
## [1.0.0-rc.7] - 2026-04-09
1415

examples/vacuum.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
use std::env;
2+
3+
use apalis::prelude::*;
4+
use apalis_core::backend::Vacuum;
5+
use apalis_redis::{RedisConfig, RedisContext, RedisStorage};
6+
use redis::Client;
7+
8+
#[tokio::main]
9+
async fn main() {
10+
let client = Client::open(env::var("REDIS_URL").unwrap()).unwrap();
11+
let conn = client.get_connection_manager().await.unwrap();
12+
let mut backend = RedisStorage::new_with_config(
13+
conn,
14+
RedisConfig::default()
15+
.set_namespace("redis_vacuum_worker")
16+
.set_buffer_size(100),
17+
);
18+
backend.push(42).await.unwrap();
19+
async fn task(task: u32, ctx: RedisContext, wrk: WorkerContext) -> Result<(), BoxDynError> {
20+
let handle = std::thread::current();
21+
println!("{task:?}, {ctx:?}, Thread: {:?}", handle.id());
22+
wrk.stop().unwrap();
23+
Ok(())
24+
}
25+
26+
let worker = WorkerBuilder::new("rango-tango")
27+
.backend(backend.clone())
28+
.on_event(|ctx, ev| {
29+
println!("CTX {:?}, On Event = {:?}", ctx.name(), ev);
30+
})
31+
.build(task);
32+
worker.run().await.unwrap();
33+
34+
// You can combine this with apalis-cron to vacuum on interval
35+
backend.vacuum().await.unwrap();
36+
}

lua/vacuum.lua

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,25 @@
1-
-- Lua script to clean up data in Redis
1+
-- KEYS[1]: the task data hash
2+
-- KEYS[2]: the metadata prefix (e.g. "task_meta")
23

3-
-- Define the keys
4-
local done_list_key = KEYS[1]
5-
local data_hash = KEYS[2]
4+
local terminal_statuses = { Done = true, Failed = true, Killed = true }
5+
local result_hash = KEYS[2] .. ":result"
66

7-
-- Iterate through done_list
8-
local done_list_ids = redis.call('ZRANGE', done_list_key, 0, -1)
7+
local deleted = 0
98

10-
-- Initialize a variable to count the number of removed items
11-
local removed_items_count = 0
9+
local fields = redis.call("hgetall", KEYS[1])
1210

13-
for _, id in ipairs(done_list_ids) do
11+
-- fields is a flat list of [field, value, field, value, ...]
12+
for i = 1, #fields, 2 do
13+
local task_id = fields[i]
14+
local meta_key = KEYS[2] .. ':' .. task_id
15+
local status = redis.call("hget", meta_key, "status")
1416

15-
local is_member = redis.call('HEXISTS', data_hash, id)
16-
if is_member == 1 then
17-
-- Remove entry from data_hash
18-
redis.call('HDEL', data_hash, id)
19-
removed_items_count = removed_items_count + 1
20-
end
17+
if status and terminal_statuses[status] then
18+
redis.call("hdel", KEYS[1], task_id)
19+
redis.call("hdel", result_hash, task_id)
20+
redis.call("del", meta_key)
21+
deleted = deleted + 1
22+
end
2123
end
2224

23-
-- Clean the done_list
24-
redis.call('DEL', done_list_key)
25-
26-
return removed_items_count
25+
return deleted

src/fetcher.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,6 @@ pub fn deserialize_with_meta<'a>(
197197
Some(idempotency_key_raw)
198198
};
199199

200-
dbg!(&idempotency_key);
201-
202200
let meta = meta_fields[9..]
203201
.chunks(2)
204202
.filter_map(|chunk| {

src/queries/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ mod list_queues;
33
mod list_tasks;
44
mod list_workers;
55
mod metrics;
6+
mod vacuum;
67
mod wait_for;

src/queries/vacuum.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
use apalis_core::backend::Vacuum;
2+
use apalis_core::backend::codec::Codec;
3+
use redis::aio::ConnectionLike;
4+
5+
use crate::RedisStorage;
6+
7+
impl<Args, Conn, C> Vacuum for RedisStorage<Args, Conn, C>
8+
where
9+
Args: Unpin + Send + Sync + 'static,
10+
Conn: ConnectionLike + Clone + Send + Sync + 'static,
11+
C: Codec<Args, Compact = Vec<u8>> + Unpin + Send + 'static,
12+
C::Error: std::error::Error + Send + Sync + 'static,
13+
{
14+
async fn vacuum(&mut self) -> Result<usize, Self::Error> {
15+
let vacuum_script = redis::Script::new(include_str!("../../lua/vacuum.lua"));
16+
vacuum_script
17+
.key(self.config.job_data_hash())
18+
.key(self.config.job_meta_hash())
19+
.invoke_async(&mut self.conn)
20+
.await
21+
}
22+
}

0 commit comments

Comments
 (0)