Skip to content

Commit 42f6333

Browse files
author
Dmitry Polyakovsky
committed
valkey module rust SDK updates
1 parent 392a849 commit 42f6333

File tree

1 file changed

+273
-0
lines changed

1 file changed

+273
-0
lines changed
Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
+++
2+
title= "Valkey Modules Rust SDK updates"
3+
date= 2025-04-27 01:01:01
4+
description= "Extending Valkey using Rust SDK."
5+
authors= ["dmitrypol"]
6+
categories= "modules"
7+
+++
8+
9+
## What are Valkey modules?
10+
11+
In an earlier [article](/blog/modules-101/) we discussed the process of building Valkey Modules.
12+
Modules allow adding extra features (such as new commands and data types) to Valkey without making changes to the core code.
13+
We briefly touched on how to use [Valkey Modules Rust SDK](https://github.com/valkey-io/valkeymodule-rs) to build a simple module.
14+
In this article we will expand on this topic and discuss some of the new features added to the SDK over the last year.
15+
SDK itself also provides examples on how to use these new features but this article summarizes them below.
16+
17+
## What is Valkey Modules Rust SDK?
18+
19+
The SDK is based on [Redis Modules Rust SDK](https://github.com/RedisLabsModules/redismodule-rs) and provides abstraction APIs on top of Valkey Modules own API.
20+
For those familiar with Rust development the SDK is a regular Rust crate that can be added to Cargo.toml file like any other Rust dependency.
21+
It requires functionality to be present in the underlying Valkey version but allows writing Valkey modules in Rust, without needing to use raw pointers or unsafe code.
22+
Recently released [Bloom Filers module](/blog/introducing-bloom-filters/) is built using this crate and several of the developers who worked on the module contributed to the SDK.
23+
Let's deep dive into to new features.
24+
25+
## Client
26+
27+
`Context` struct now has several new functions to get information about the client.
28+
It provides Rust wrappers around `Module_GetClient*` functions in the underlying Valkey Module API.
29+
Most new functions return `ValkeyResult` so the module developer can handle the error appropriately.
30+
The functions can be called for the current client or by specifying `client_id`.
31+
32+
```rust
33+
fn my_client_cmd(ctx: &Context, _args: Vec<ValkeyString>) -> ValkeyResult {
34+
let client_id = ctx.get_client_id();
35+
let username = ctx.get_client_username_by_id(client_id);
36+
Ok(ValkeyValue::from(username.to_string()))
37+
}
38+
valkey_module! {
39+
...
40+
commands: [
41+
["my_client_cmd", my_client_cmd, "", 0, 0, 0],
42+
]
43+
}
44+
45+
```
46+
47+
## Auth callback
48+
49+
Valkey 7.2 introduced support for callbacks after authentication.
50+
Now it can be leveraged via modules.
51+
52+
```rust
53+
fn auth_callback(
54+
ctx: &Context,
55+
username: ValkeyString,
56+
_password: ValkeyString,
57+
) -> Result<c_int, ValkeyError> {
58+
if ctx.authenticate_client_with_acl_user(&username) == Status::Ok {
59+
// can be combined with ctx.get_client_ip to control access by IP address
60+
let _client_ip = ctx.get_client_ip()?;
61+
...
62+
return Ok(AUTH_HANDLED);
63+
}
64+
Ok(AUTH_NOT_HANDLED)
65+
}
66+
valkey_module! {
67+
...
68+
auth: [auth_callback],
69+
}
70+
```
71+
72+
## Preload validation
73+
74+
`valkey_module!` macro already provided `init` callback that can be used to execute custom code during module load.
75+
However, `init` executes at the very end of module load after new commands and data types are created.
76+
That can be use useful but what if we wanted to stop module load before any of that happens?
77+
For example, we might need to restrict module to be loaded only on specific version of Valkey.
78+
That's where the optional `preload` can be used.
79+
80+
```rust
81+
fn preload_fn(ctx: &Context, _args: &[ValkeyString]) -> Status {
82+
let _version = ctx.get_server_version().unwrap();
83+
// respond with Status::Ok or Status::Err to prevent loading
84+
Status::Ok
85+
}
86+
valkey_module! {
87+
...
88+
preload: preload_fn,
89+
commands: [],
90+
}
91+
```
92+
93+
## Filters
94+
95+
To execute custom code before specific Valkey commands we can use command filters. This can be leveraged to replace default commands with custom comands or modify arguments.
96+
Thanks to the abstractions provided by the SDK we simply need to create a Rust function and register it in the `valkey_module!` macro.
97+
Note of caution - since filters are executed before every command this code needs to be optimized.
98+
99+
```rust
100+
fn my_filter_fn(_ctx: *mut RedisModuleCommandFilterCtx) {
101+
let cf_ctx = CommandFilterCtx::new(ctx);
102+
// check the number of arguments
103+
if cf_ctx.args_count() != 3 {
104+
return;
105+
}
106+
// get which command is being executed
107+
let _cmd = cf_ctx.cmd_get_try_as_str().unwrap();
108+
// grab various args passed to the command
109+
let _all_args = cf_ctx.get_all_args_wo_cmd();
110+
// replace command
111+
cf_ctx.arg_replace(0, "custom_cmd");
112+
}
113+
valkey_module! {
114+
...
115+
filters: [
116+
[my_filter_fn, VALKEYMODULE_CMDFILTER_NOSELF],
117+
]
118+
}
119+
```
120+
121+
## New event handlers
122+
123+
SDK now supports more server events. We can use this to execute our own code on client connect/disconnect, server shutdown or specific key events.
124+
125+
```rust
126+
#[client_changed_event_handler]
127+
fn client_changed_event_handler(_ctx: &Context, client_event: ClientChangeSubevent) {
128+
match client_event {
129+
ClientChangeSubevent::Connected => {}
130+
ClientChangeSubevent::Disconnected => {}
131+
}
132+
}
133+
#[shutdown_event_handler]
134+
fn shutdown_event_handler(_ctx: &Context, _event: u64) {
135+
...
136+
}
137+
#[key_event_handler]
138+
fn key_event_handler(ctx: &Context, key_event: KeyChangeSubevent) {
139+
match key_event {
140+
KeyChangeSubevent::Deleted => {}
141+
KeyChangeSubevent::Evicted => {}
142+
KeyChangeSubevent::Overwritten => {}
143+
KeyChangeSubevent::Expired => {}
144+
}
145+
}
146+
```
147+
148+
## Custom ACL categories support
149+
150+
Valkey 8 introduced support for custom ACL categories. To implement that we need to enable `required-features = ["min-valkey-compatibility-version-8-0"]` in `Cargo.toml` and register new categories in `valkey_module!` macro. Then we can restrict our custom commands to these ACL categories.
151+
152+
```rust
153+
valkey_module! {
154+
...
155+
acl_categories: [
156+
"acl_one",
157+
"acl_two"
158+
]
159+
commands: [
160+
["cmd1", cmd1, "write", 0, 0, 0, "acl_one"],
161+
["cmd2", cmd2, "", 0, 0, 0, "acl_one acl_two"],
162+
]
163+
```
164+
165+
## Validating / Rejecting CONFIG SET
166+
167+
SDK now supports specifying optional callback functions to validate or reject custom configuations. This is available for String, i64, bool and enum configs. Here is an example of validation for i64 custom config.
168+
169+
```rust
170+
lazy_static! {
171+
static ref CONFIG_I64: ValkeyGILGuard<i64> = ValkeyGILGuard::default();
172+
}
173+
fn on_i64_config_set<G, T: ConfigurationValue<i64>>(
174+
config_ctx: &ConfigurationContext,
175+
_name: &str,
176+
val: &'static T,
177+
) -> Result<(), ValkeyError> {
178+
if val.get(config_ctx) == custom_logic_here {
179+
log_notice("log message here");
180+
Err(ValkeyError::Str("error message here "))
181+
} else {
182+
Ok(())
183+
}
184+
}
185+
valkey_module! {
186+
configurations: [
187+
i64: [
188+
["my_i64", &*CONFIG_I64, 10, 0, 1000, ConfigurationFlags::DEFAULT, Some(Box::new(on_configuration_changed)), Some(Box::new(on_i64_config_set::<ValkeyString, ValkeyGILGuard<i64>>))],
189+
],
190+
...
191+
]
192+
}
193+
```
194+
195+
## Defrag
196+
197+
There is a new `Defrag` struct abstracting away the raw C FFI calls to implement defrag for custom data types.
198+
199+
```rust
200+
static MY_VALKEY_TYPE: ValkeyType = ValkeyType::new(
201+
"mytype123",
202+
0,
203+
raw::RedisModuleTypeMethods {
204+
...
205+
defrag: Some(defrag),
206+
},
207+
);
208+
unsafe extern "C" fn defrag(
209+
defrag_ctx: *mut raw::RedisModuleDefragCtx,
210+
_from_key: *mut RedisModuleString,
211+
value: *mut *mut c_void,
212+
) -> i32 {
213+
let defrag = Defrag::new(defrag_ctx);
214+
...
215+
0
216+
}
217+
valkey_module! {
218+
...
219+
data_types: [
220+
MY_VALKEY_TYPE,
221+
],
222+
...
223+
}
224+
```
225+
226+
## Redis support
227+
228+
There is a new feature flag in case module needs to run on Valkey and Redis. Specify `use-redismodule-api` so that module used RedisModule API Initialization for backwards compatibility.
229+
230+
```rust
231+
[features]
232+
use-redismodule-api = ["valkey-module/use-redismodule-api"]
233+
default = []
234+
235+
cargo build --release --features use-redismodule-api
236+
```
237+
238+
## Unit tests and memory allocation
239+
240+
This feature flag supports running unit tests outside of Valkey or Redis. As the result it cannot use Vakey Allocator and instead relies on the System Allocator instead. The core logis is present in `alloc.rs` but developers only need to specify this in the module Cargo.toml.
241+
242+
```rust
243+
[features]
244+
enable-system-alloc = ["valkey-module/system-alloc"]
245+
246+
cargo test --features enable-system-alloc
247+
```
248+
249+
## Ideas for future development
250+
251+
* Mock Context for unit testing - enable unit testing functions that require `&ctx`
252+
* Context in Filters - enable more operations to be done in filters.
253+
* Environment specific config support - during development or unit testing it is useful to have different config settings.
254+
* Crontab - `cron_event_handler` uses `serverCron` (10 times per second by default) but it can be extended to run custom code on pre-determined schedule and configured via custom commands.
255+
* And more. Please stay tuned.
256+
257+
## List of contributors
258+
259+
Below are the Github handles of the developers who contibuted to the SDK in the past year
260+
261+
* KarthikSubbarao
262+
* sachinvmurthy
263+
* zackcam
264+
* YueTang-Vanessa
265+
* hahnandrew
266+
* Mkmkme
267+
* dmitrypol
268+
269+
## Usefull links
270+
271+
* [Valkey repo](https://github.com/valkey-io/valkey)
272+
* [Valkey Modules Rust SDK](https://github.com/valkey-io/valkeymodule-rs)
273+
* [Rust in VS Code](https://code.visualstudio.com/docs/languages/rust)

0 commit comments

Comments
 (0)