valkey-module 0.1.14

A toolkit for building valkey modules in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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
142
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use anyhow::{Context, Result};

use redis::Connection;
use redis::RedisResult;
use std::fs;
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;
use std::process::Command;
use std::time::{Duration, Instant};
use tempfile::TempDir;

const SHUTDOWN_CONNECTION_TIMEOUT: Duration = Duration::from_millis(250);
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
const SHUTDOWN_POLL_INTERVAL: Duration = Duration::from_millis(10);
const EVENT_WAIT_TIMEOUT: Duration = Duration::from_secs(10);
const EVENT_POLL_INTERVAL: Duration = Duration::from_millis(50);

/// Owns a Valkey test process and the connection used to communicate with it.
pub(super) struct TestServer {
    pub(super) port: u16,
    _guard: ChildGuard,
    connection: Connection,
}

// Allows TestServer to be used where an immutable Redis connection is expected.
impl Deref for TestServer {
    type Target = Connection;

    fn deref(&self) -> &Self::Target {
        &self.connection
    }
}

// Allows TestServer to be used where a mutable Redis connection is expected.
impl DerefMut for TestServer {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.connection
    }
}

// Exposes only the lifecycle operations that integration tests need.
impl TestServer {
    pub(super) fn data_dir(&self) -> &std::path::Path {
        self._guard.data_dir()
    }

    pub(super) fn into_parts(self) -> (ChildGuard, Connection) {
        (self._guard, self.connection)
    }
}

/// Shuts down the child Valkey process and removes its temporary data directory on drop.
pub(super) struct ChildGuard {
    name: &'static str,
    port: u16,
    data_dir: TempDir,
    child: std::process::Child,
}

// Gracefully stops the child process before its isolated data directory is removed.
impl Drop for ChildGuard {
    fn drop(&mut self) {
        let client = redis::Client::open(format!("redis://127.0.0.1:{}/", self.port));
        if let Ok(client) = client {
            if let Ok(mut connection) =
                client.get_connection_with_timeout(SHUTDOWN_CONNECTION_TIMEOUT)
            {
                let _: RedisResult<()> =
                    redis::cmd("SHUTDOWN").arg("NOSAVE").query(&mut connection);
            }
        }

        let shutdown_deadline = Instant::now() + SHUTDOWN_TIMEOUT;
        loop {
            match self.child.try_wait() {
                Ok(Some(_)) => {
                    return;
                }
                Ok(None) if Instant::now() < shutdown_deadline => {
                    std::thread::sleep(SHUTDOWN_POLL_INTERVAL);
                }
                Ok(None) => {
                    if let Err(e) = self.child.kill() {
                        println!("Could not kill {} after shutdown timeout: {e}", self.name);
                    }
                    if let Err(e) = self.child.wait() {
                        println!(
                            "Could not wait for {} after shutdown timeout: {e}",
                            self.name
                        );
                    }
                    return;
                }
                Err(e) => {
                    println!("Could not check whether {} exited: {e}", self.name);
                    return;
                }
            }
        }
    }
}

// Contains cleanup behavior used by the child process lifecycle.
impl ChildGuard {
    fn data_dir(&self) -> &std::path::Path {
        self.data_dir.path()
    }
}

pub(super) fn start_server_w_module_get_connection(module_name: &str) -> Result<TestServer> {
    let port = get_available_port()?;
    let guard = start_valkey_server_with_module(module_name, port)
        .with_context(|| "failed to start valkey server")?;
    let connection =
        get_valkey_connection(port).with_context(|| "failed to connect to valkey server")?;

    Ok(TestServer {
        port,
        _guard: guard,
        connection,
    })
}

fn start_valkey_server_with_module(module_name: &str, port: u16) -> Result<ChildGuard> {
    let module_path = get_module_path(module_name)?;
    let data_dir = create_data_dir()?;
    let port_arg = port.to_string();
    let data_dir_arg = data_dir
        .path()
        .to_str()
        .context("Valkey data directory is not valid UTF-8")?;

    let args = &[
        "--port",
        port_arg.as_str(),
        "--dir",
        data_dir_arg,
        "--dbfilename",
        "dump.rdb",
        "--loadmodule",
        module_path.as_str(),
        "--enable-debug-command",
        "yes",
        "--enable-module-command",
        "yes",
    ];

    let child = Command::new("valkey-server")
        .args(args)
        .current_dir(data_dir.path())
        .spawn();
    let child = match child {
        Ok(child) => child,
        Err(error) => return Err(error.into()),
    };

    Ok(ChildGuard {
        name: "server",
        port,
        data_dir,
        child,
    })
}

fn create_data_dir() -> Result<TempDir> {
    tempfile::Builder::new()
        .prefix("valkeymodule-rs-")
        .tempdir()
        .context("failed to create Valkey data directory")
}

fn get_available_port() -> Result<u16> {
    let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
    Ok(listener.local_addr()?.port())
}

pub(super) fn get_module_path(module_name: &str) -> Result<String> {
    let extension = if cfg!(target_os = "macos") {
        "dylib"
    } else {
        "so"
    };

    let profile = if cfg!(not(debug_assertions)) {
        "release"
    } else {
        "debug"
    };

    let module_path: PathBuf = [
        std::env::current_dir()?,
        PathBuf::from(format!(
            "target/{profile}/examples/lib{module_name}.{extension}"
        )),
    ]
    .iter()
    .collect();

    assert!(fs::metadata(&module_path)
        .with_context(|| format!("Loading valkey module: {}", module_path.display()))?
        .is_file());

    let module_path = format!("{}", module_path.display());
    Ok(module_path)
}

// Get connection to Redis
pub(super) fn get_valkey_connection(port: u16) -> Result<Connection> {
    let client = redis::Client::open(format!("redis://127.0.0.1:{port}/"))?;
    loop {
        let res = client.get_connection();
        match res {
            Ok(con) => return Ok(con),
            Err(e) => {
                if e.is_connection_refusal() {
                    // Valkey not ready yet, sleep and retry
                    std::thread::sleep(Duration::from_millis(50));
                } else {
                    return Err(e.into());
                }
            }
        }
    }
}

#[derive(Debug)]
pub(super) enum AuthExpectedResult {
    Success,
    Denied,
    EngineDenied,
    Aborted,
}

// Helper function to validate the authentication
pub(super) fn check_auth(
    con: &mut redis::Connection,
    username: &str,
    password: &str,
    expected_result: AuthExpectedResult,
) -> Result<()> {
    let response: RedisResult<String> = redis::cmd("AUTH").arg(&[username, password]).query(con);

    match expected_result {
        AuthExpectedResult::Success => {
            let res =
                response.with_context(|| format!("failed to authenticate {username} user"))?;
            assert_eq!(res, "OK");
        }
        AuthExpectedResult::Denied => {
            let err = response
                .expect_err("authentication should be denied")
                .to_string();
            assert!(
                err.contains("DENIED: Authentication credentials mismatch"),
                "Unexpected error message: {}",
                err
            );
        }
        AuthExpectedResult::EngineDenied => {
            let err = response
                .expect_err("authentication engine should deny the request")
                .to_string();
            assert!(
                err.contains("WRONGPASS: invalid username-password pair or user is disabled"),
                "Unexpected error message: {}",
                err
            );
        }
        AuthExpectedResult::Aborted => {
            let err = response
                .expect_err("authentication should be aborted by the server")
                .to_string();
            assert!(
                err.contains("ABORT: Authentication aborted by server"),
                "Unexpected error message: {}",
                err
            );
        }
    }
    Ok(())
}

pub(super) fn setup_acl_users(
    con: &mut redis::Connection,
    users: &[(&str, Option<&str>)],
) -> Result<()> {
    for (user, maybe_pass) in users {
        let res: String = if let Some(pass) = maybe_pass {
            redis::cmd("ACL")
                .arg(&["SETUSER", user, "on", &format!(">{}", pass), "~*", "+@all"])
                .query(con)?
        } else {
            redis::cmd("ACL")
                .arg(&["SETUSER", user, "on", "nopass", "~*", "+@all"])
                .query(con)?
        };
        assert_eq!(&res, "OK");
    }
    Ok(())
}

pub(super) fn check_blocked_clients(con: &mut redis::Connection) -> Result<i32> {
    let info: String = redis::cmd("INFO").arg("clients").query(con)?;

    let blocked_clients = info
        .lines()
        .find(|line| line.starts_with("blocked_clients:"))
        .and_then(|line| line.split(':').nth(1))
        .and_then(|count| count.trim().parse::<i32>().ok())
        .unwrap_or(0);

    Ok(blocked_clients)
}

pub(super) fn wait_for_blocked_clients(con: &mut redis::Connection) -> Result<()> {
    wait_for_blocked_client_count(con, |count| count > 0, "at least one blocked client")
}

pub(super) fn wait_for_no_blocked_clients(con: &mut redis::Connection) -> Result<()> {
    wait_for_blocked_client_count(con, |count| count == 0, "no blocked clients")
}

pub(super) fn wait_for_client_connection_count(
    con: &mut redis::Connection,
    expected: i64,
) -> Result<()> {
    let start = Instant::now();

    loop {
        let actual: i64 = redis::cmd("num_connects").query(con)?;
        if actual == expected {
            return Ok(());
        }
        if start.elapsed() >= EVENT_WAIT_TIMEOUT {
            anyhow::bail!(
                "timed out waiting for {expected} connected clients; last observed {actual}"
            );
        }

        std::thread::sleep(EVENT_POLL_INTERVAL);
    }
}

fn wait_for_blocked_client_count(
    con: &mut redis::Connection,
    predicate: impl Fn(i32) -> bool,
    expected: &str,
) -> Result<()> {
    let start = Instant::now();

    loop {
        let blocked_clients = check_blocked_clients(con)?;
        if predicate(blocked_clients) {
            return Ok(());
        }
        if start.elapsed() >= EVENT_WAIT_TIMEOUT {
            anyhow::bail!(
                "timed out waiting for {expected}; last observed {blocked_clients} blocked clients"
            );
        }

        std::thread::sleep(EVENT_POLL_INTERVAL);
    }
}

pub(super) fn wait_for_replica_change_events(
    con: &mut redis::Connection,
    expected: i64,
) -> Result<()> {
    wait_for_event_count(con, "num_replica_change_events", expected)
}

pub(super) fn wait_for_repl_async_load_events(
    con: &mut redis::Connection,
    expected: i64,
) -> Result<()> {
    wait_for_event_count(con, "num_repl_async_load_events", expected)
}

pub(super) fn wait_for_master_link_state(
    con: &mut redis::Connection,
    expected_up: bool,
    minimum_events: i64,
) -> Result<()> {
    let start = Instant::now();

    loop {
        let event_count: i64 = redis::cmd("num_master_link_change_events").query(con)?;
        let is_up: bool = redis::cmd("is_master_link_up").query(con)?;
        if is_up == expected_up && event_count >= minimum_events {
            return Ok(());
        }
        if start.elapsed() >= EVENT_WAIT_TIMEOUT {
            anyhow::bail!(
                "timed out waiting for master link up={expected_up} with at least {minimum_events} \
                 events; last observed up={is_up}, events={event_count}"
            );
        }

        std::thread::sleep(EVENT_POLL_INTERVAL);
    }
}

pub(super) fn wait_for_event_count(
    con: &mut redis::Connection,
    command: &str,
    expected: i64,
) -> Result<()> {
    let start = Instant::now();

    loop {
        let actual: i64 = redis::cmd(command).query(con)?;
        if actual == expected {
            return Ok(());
        }
        if actual > expected {
            anyhow::bail!("expected {expected} events from {command}, but observed {actual}");
        }
        if start.elapsed() >= EVENT_WAIT_TIMEOUT {
            anyhow::bail!(
                "timed out waiting for {expected} events from {command}; last observed {actual}"
            );
        }

        std::thread::sleep(EVENT_POLL_INTERVAL);
    }
}

pub(super) fn wait_for_event_count_greater_than(
    con: &mut redis::Connection,
    command: &str,
    previous: i64,
) -> Result<()> {
    let start = Instant::now();

    loop {
        let actual: i64 = redis::cmd(command).query(con)?;
        if actual > previous {
            return Ok(());
        }
        if start.elapsed() >= EVENT_WAIT_TIMEOUT {
            anyhow::bail!(
                "timed out waiting for {command} to exceed {previous}; last observed {actual}"
            );
        }

        std::thread::sleep(EVENT_POLL_INTERVAL);
    }
}

pub(super) fn wait_for_file_contents(path: &std::path::Path, expected: &[&str]) -> Result<()> {
    let start = Instant::now();

    loop {
        match fs::read_to_string(path) {
            Ok(contents) if expected.iter().all(|expected| contents.contains(expected)) => {
                return Ok(())
            }
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => return Err(e).with_context(|| format!("failed to read {}", path.display())),
        }
        if start.elapsed() >= EVENT_WAIT_TIMEOUT {
            anyhow::bail!(
                "timed out waiting for expected contents in {}",
                path.display()
            );
        }

        std::thread::sleep(EVENT_POLL_INTERVAL);
    }
}