kividb 1.2.1

A fast RedisĀ®-compatible in-memory store written 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
// src/lib.rs
//! The internals of the KiviDB server, a Redis-compatible in-memory database.
//!
//! This crate is published so that `cargo install kividb` can build the
//! `kividb` server. The server binary is not built from this library:
//! `src/main.rs` declares its own modules and its own global allocator. The
//! library is built from the same sources so the integration tests can use
//! them; it is not a public API. It is not a client or an embeddable
//! database, and any release may change or remove any of it. It sets a
//! global allocator too, so a crate that depended on it would get that one.
//! To talk to KiviDB from Rust, use a Redis client such as the `redis` crate.
//!
//! Documentation for running the server: <https://github.com/kividbio/kividb>.

// First, so its logging macros are in scope in every module after it.
#[macro_use]
pub mod loglevel;
pub mod acl;
pub mod aof;
pub mod cluster;
pub mod cmdstats;
pub mod command_gate;
pub mod commands;
pub mod compaction;
pub mod config;
pub mod eviction;
pub mod expiry;
pub mod field_expiry;
pub mod key_bytes;
pub mod key_moves;
pub mod latency;
pub mod lazyfree;
pub mod listen;
#[cfg(feature = "lua")]
mod lua_vm_blocking;
pub mod member_set;
pub mod memory_use;
pub mod monitor;
pub mod node_tls;
pub mod pause;
pub mod protected_mode;
pub mod pubsub;
pub mod redis_settings;
pub mod replication;
pub mod resp;
pub mod script_clock;
pub mod server;
pub mod shared_bytes;
pub mod shutdown;
pub mod slowlog;
pub mod snapshot;
pub mod stats;
pub mod store;
pub mod tag_locks;
#[cfg(test)]
pub(crate) mod test_hooks;
pub mod tracking;
pub mod types;
pub mod update_check;
pub mod value_slab;
pub mod vector;
pub mod wait_table;
pub mod watch;
pub mod write_gate;
pub mod write_order;
use crate::replication::{ReplState, start_hub};
pub mod client_registry;
pub mod keyspace_events;
pub mod keyspec;

#[cfg(feature = "tls")]
mod tls;

#[cfg(target_os = "linux")]
pub mod server_uring;

/// Counts what it allocates: `maxmemory` is measured against that. See
/// `memory_use`.
#[global_allocator]
static ALLOCATOR: memory_use::Counting = memory_use::Counting;

pub static RUNTIME_MAXMEMORY: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);
/// Entry point for integration tests — starts a tokio server on the given
/// config and blocks the calling thread. Meant to run inside a thread::spawn.
pub fn run_for_test(config: config::Config) {
    let cfg = std::sync::Arc::new(config);
    crate::RUNTIME_MAXMEMORY.store(cfg.maxmemory, std::sync::atomic::Ordering::Relaxed);
    // Only ever switched on here: the servers of one test process share it.
    if cfg!(feature = "lua") && cfg.lua_parallel_scripts {
        crate::tag_locks::set_enabled(true);
    }
    crate::eviction::configure(&cfg);
    crate::compaction::configure(&cfg);
    // Only ever raised here, as the servers of one test process share it.
    crate::snapshot::SNAPSHOT_DATABASES
        .fetch_max(cfg.databases, std::sync::atomic::Ordering::Relaxed);
    if let Err(e) = crate::node_tls::init(&cfg) {
        panic!("TLS between nodes: {e}");
    }
    crate::protected_mode::set(cfg.protected_mode);
    crate::stats::record_save();
    crate::commands::memory::note_startup();
    let started_at = std::time::Instant::now();

    tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .enable_all()
        .build()
        .unwrap()
        .block_on(crate::server_tokio(cfg, started_at))
        .unwrap();
}

async fn server_tokio(
    config: std::sync::Arc<config::Config>,
    started_at: std::time::Instant,
) -> Result<(), Box<dyn std::error::Error>> {
    use parking_lot::RwLock;
    use std::net::SocketAddr;
    use std::sync::Arc;
    use tokio::net::TcpListener;
    use tokio::sync::mpsc;

    let store = store::new_store(config.databases);
    let index_store = vector::new_index_store();
    let lastsave = Arc::new(RwLock::new(0i64));
    let aof_enabled = config.aof;
    let started_at = Arc::new(started_at);
    let wait_table = Arc::new(crate::wait_table::WaitTable::new());
    let dict_store = vector::new_dict_store();
    vector::register_dict_store(&index_store, &dict_store);
    let ts_index = store::new_ts_index();
    let pubsub = pubsub::PubSubHub::new();
    // Unbounded: a bounded AOF queue drops durability records under load.
    let (aof_tx, aof_rx) = mpsc::unbounded_channel();
    // Reachable from the replication applier, which is built too deep to be
    // handed this channel directly. See `aof::install_global_aof_sender`.
    aof::install_global_aof_sender(Box::new(aof_tx.clone()));
    let repl_state = Arc::new(ReplState::from_config(&config));
    let hub_tx = start_hub(Arc::clone(&repl_state));
    crate::stats::spawn_instantaneous_ops_sampler();
    let latency = crate::latency::new_latency_tracker();
    crate::commands::helpers::spawn_active_expire_task(
        Arc::clone(&store),
        Arc::clone(&index_store),
        pubsub.clone(),
        Arc::clone(&latency),
        &repl_state,
        &hub_tx,
    );
    crate::compaction::spawn(Arc::clone(&store));
    let watch_registry = crate::watch::new_watch_registry();
    crate::watch::register_for(&store, &watch_registry);
    let client_registry = crate::client_registry::new_client_registry();
    let acl_store = acl::new_acl_store(&config.requirepass);
    let acl_log = acl::new_acl_log();
    acl_log.set_max_len(config.acllog_max_len);
    let slowlog = crate::slowlog::new_slowlog_from_config(&config);
    let cluster_state = std::sync::Arc::new(
        crate::cluster::ClusterState::from_config(&config).expect("cluster config file"),
    );
    let tracking_table = crate::tracking::new_tracking_table();
    crate::tracking::register_for(&store, &tracking_table, &client_registry, &acl_store);

    // HNSW compaction worker — drains background rebuild requests.
    // Single OS thread; no tokio runtime needed.
    let (compaction_tx, compaction_rx) = vector::new_compaction_channel();
    {
        let index_store_for_compaction = Arc::clone(&index_store);
        let store_for_compaction = Arc::clone(&store);
        vector::spawn_compaction_worker(
            index_store_for_compaction,
            store_for_compaction,
            compaction_rx,
        );
    }

    if !config.aclfile.is_empty() {
        match acl::load_acl_file(&config.aclfile, &acl_store, &config.requirepass) {
            Ok(_) => log_info!("ACL file loaded: {}", config.aclfile),
            Err(e) => {
                log_fatal!(
                    "Can't load the ACL file '{}': {e}. Fix the line named, or start \
                     without aclfile",
                    config.aclfile
                );
                // Fatal — misconfigured ACL file should not silently proceed
                std::process::exit(1);
            }
        }
    }
    // The AOF writer gets a dedicated single-thread runtime rather than a task on
    // the shared one. `rewrite_aof` quiesces by holding every shard lock and then
    // waits for the writer to perform the swap; if the writer were a task here,
    // enough connection tasks blocking synchronously on those same locks could
    // occupy every worker thread and the writer would never be polled -- the
    // server would hang holding all locks. A dedicated runtime makes that
    // impossible. (The io_uring path already does this for its own reasons.)
    let aof_writer = aof::start_aof_writer(aof_rx);
    std::thread::spawn(move || {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(aof_writer)
    });

    // One monitor registry for the whole server. Each connection used to be
    // handed a registry of its own, so `MONITOR` on one connection could never
    // see commands run on another.
    let monitor_registry = crate::monitor::new_monitor_registry();

    // Replica client — runs on its own thread and runtime (see
    // `ReplicaStarter::start`).
    let replica_starter = crate::replication::replica_client::ReplicaStarter {
        store: Arc::clone(&store),
        index_store: Arc::clone(&index_store),
        dict_store: Arc::clone(&dict_store),
        wait_table: Arc::clone(&wait_table),
        ts_index: Arc::clone(&ts_index),
        config: Arc::clone(&config),
        compaction_tx: compaction_tx.clone(),
        repl_state: Arc::clone(&repl_state),
        hub_tx: hub_tx.clone(),
        pubsub: pubsub.clone(),
        client_registry: Arc::clone(&client_registry),
        tracking_table: Arc::clone(&tracking_table),
        monitor_registry: Arc::clone(&monitor_registry),
    };
    cluster_state.start(
        &config,
        crate::cluster::ClusterHooks {
            replica_starter: replica_starter.clone(),
            pubsub: pubsub.clone(),
        },
    );
    if let Some((host, port)) = config.replicaof_addr() {
        replica_starter.start(host, port);
    } else if let Some(master_id) = cluster_state.my_master_id() {
        // A cluster replica restarting: resume following its master.
        let addr = cluster_state
            .nodes
            .read()
            .get(&master_id)
            .map(|m| (m.ip.clone(), m.client_port));
        if let Some((ip, port)) = addr {
            replica_starter.start(ip, port);
        }
    }

    let addr: SocketAddr = config.addr().parse()?;
    // Port 0: no plaintext port, until `CONFIG SET port` opens one.
    let listener = if addr.port() == 0 {
        None
    } else {
        Some(TcpListener::bind(addr).await?)
    };

    // Also with no TLS port: `CONFIG SET tls-port` opens one.
    #[cfg(feature = "tls")]
    {
        use crate::tls::acceptor;

        let mut tls_listener = match acceptor::listener(&config) {
            Ok(listener) => listener,
            Err(e) => {
                log_fatal!("TLS: {e}");
                std::process::exit(1);
            }
        };

        let tls_config = Arc::clone(&config);
        let tls_store = Arc::clone(&store);
        let tls_lastsave = Arc::clone(&lastsave);
        let tls_aof_tx = aof_tx.clone();
        let tls_started_at = Arc::clone(&started_at);
        let tls_index_store = Arc::clone(&index_store);
        let tls_wait_table = Arc::clone(&wait_table);
        let tls_dict_store = dict_store.clone();
        let tls_ts_index = ts_index.clone();
        let tls_pubsub = pubsub.clone();
        let tls_hub_tx = hub_tx.clone();
        let tls_repl_state = Arc::clone(&repl_state);
        let tls_watch_registry = Arc::clone(&watch_registry);
        let tls_client_registry = Arc::clone(&client_registry);
        let tls_acl_store = Arc::clone(&acl_store);
        let tls_acl_log = Arc::clone(&acl_log);
        let tls_slowlog = Arc::clone(&slowlog);
        let tls_latency = Arc::clone(&latency);
        let tls_compaction_tx = compaction_tx.clone();
        let tls_cluster_state = Arc::clone(&cluster_state);
        let tls_monitor_registry = Arc::clone(&monitor_registry);
        let tls_tracking_table = Arc::clone(&tracking_table);

        let server = crate::listen::server_of(&config);
        tokio::spawn(async move {
            loop {
                let (tcp_stream, peer_addr) = match tls_listener.accept().await {
                    Ok(pair) => pair,
                    Err(e) => {
                        log_warn!("TLS: accept error: {e}");
                        // Out of file descriptors, it would otherwise spin.
                        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                        continue;
                    }
                };

                // Installed before the port is opened.
                let Some(acceptor) = acceptor::current(server) else {
                    continue;
                };
                let Some(slot) = crate::client_registry::admit(&tls_client_registry) else {
                    continue;
                };
                let store = Arc::clone(&tls_store);
                let lastsave = Arc::clone(&tls_lastsave);
                let aof_tx = tls_aof_tx.clone();
                let config = Arc::clone(&tls_config);
                let started_at = Arc::clone(&tls_started_at);
                let index_store = Arc::clone(&tls_index_store);
                let wait_table = Arc::clone(&tls_wait_table);
                let dict_store = tls_dict_store.clone();
                let ts_index = tls_ts_index.clone();
                let pubsub = tls_pubsub.clone();
                let hub_tx = tls_hub_tx.clone();
                let repl_state = Arc::clone(&tls_repl_state);
                let watch_registry = Arc::clone(&tls_watch_registry);
                let client_registry = Arc::clone(&tls_client_registry);
                let acl_store = Arc::clone(&tls_acl_store);
                let acl_log = Arc::clone(&tls_acl_log);
                let slowlog = Arc::clone(&tls_slowlog);
                let latency = Arc::clone(&tls_latency);
                let compaction_tx = tls_compaction_tx.clone();
                let cluster_state = Arc::clone(&tls_cluster_state);
                let monitor_registry = Arc::clone(&tls_monitor_registry);
                let tracking_table = Arc::clone(&tls_tracking_table);

                tokio::spawn(async move {
                    let Some((tls_stream, _slot)) =
                        acceptor::handshake(&acceptor, tcp_stream, peer_addr, slot).await
                    else {
                        return;
                    };
                    crate::stats::TOTAL_CONNECTIONS_RECEIVED
                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    let peer_addr_str = peer_addr.to_string();

                    let _ = server::handle_client(
                        tls_stream,
                        store,
                        lastsave,
                        aof_tx,
                        aof_enabled,
                        config,
                        started_at,
                        index_store,
                        dict_store,
                        wait_table,
                        ts_index,
                        pubsub,
                        hub_tx,
                        repl_state,
                        watch_registry,
                        client_registry,
                        peer_addr_str,
                        acl_store,
                        acl_log,
                        slowlog,
                        latency,
                        compaction_tx,
                        cluster_state,
                        monitor_registry,
                        tracking_table,
                    )
                    .await;
                });
            }
        });
    }

    let mut listener = crate::listen::Listener::new(
        listener,
        addr,
        crate::listen::server_of(&config),
        crate::listen::Kind::Plain,
    );
    loop {
        let (socket, peer_addr) = match listener.accept().await {
            Ok(v) => v,
            Err(_) => continue,
        };
        let Some(slot) = crate::client_registry::admit(&client_registry) else {
            crate::client_registry::turn_away(socket);
            continue;
        };
        crate::stats::TOTAL_CONNECTIONS_RECEIVED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let peer_addr_str = peer_addr.to_string();
        let store = Arc::clone(&store);
        let index_store = Arc::clone(&index_store);
        let lastsave = Arc::clone(&lastsave);
        let aof_tx = aof_tx.clone();
        let config = Arc::clone(&config);
        let started_at = Arc::clone(&started_at);
        let wait_table = Arc::clone(&wait_table);
        let dict_store = Arc::clone(&dict_store);
        let ts_index = Arc::clone(&ts_index);
        let pubsub = pubsub.clone();
        let hub_tx = hub_tx.clone();
        let repl_state = Arc::clone(&repl_state);
        let watch_registry = Arc::clone(&watch_registry);
        let client_registry = Arc::clone(&client_registry);
        let acl_store = Arc::clone(&acl_store);
        let acl_log = Arc::clone(&acl_log);
        let slowlog = Arc::clone(&slowlog);
        let latency = Arc::clone(&latency);
        let compaction_tx = compaction_tx.clone();
        let cluster_state = Arc::clone(&cluster_state);
        let monitor_registry = Arc::clone(&monitor_registry);
        let tracking_table = Arc::clone(&tracking_table);
        tokio::spawn(async move {
            let _slot = slot;
            let _ = server::handle_client(
                socket,
                store,
                lastsave,
                aof_tx,
                aof_enabled,
                config,
                started_at,
                index_store,
                dict_store,
                wait_table,
                ts_index,
                pubsub,
                hub_tx,
                repl_state,
                watch_registry,
                client_registry,
                peer_addr_str,
                acl_store,
                acl_log,
                slowlog,
                latency,
                compaction_tx,
                cluster_state,
                monitor_registry,
                tracking_table,
            )
            .await;
        });
    }
}