Skip to main content

kevy_rt/
lib.rs

1//! kevy-rt — shared-nothing, thread-per-core runtime.
2//!
3//! Each core runs its own reactor (kqueue/epoll) and owns one **shard** of the
4//! keyspace (`hash(key) % nshards`). There is no shared mutable state and no
5//! lock on the hot path — cores communicate only by message passing over
6//! channels, woken via a self-pipe ([`kevy_sys::Waker`]). Connections are spread
7//! across cores by `SO_REUSEPORT`; a command whose key lives on another core is
8//! forwarded to that core, executed there, and the reply routed back to the
9//! originating connection.
10//!
11//! Per-connection reply ordering is preserved (RESP is pipelined): each command
12//! gets a monotonic seq; replies are emitted only in contiguous seq order, so an
13//! async cross-core reply never overtakes an earlier one.
14//!
15//! The cross-core channel currently uses `std::sync::mpsc` (pure Rust, zero
16//! deps); swapping in a lock-free SPSC/MPSC ring is a perf-polish item.
17//! Command semantics are injected via the [`Commands`] trait, keeping the
18//! runtime independent of the concrete command set. Part of the [kevy] server.
19//!
20//! [kevy]: https://crates.io/crates/kevy
21//!
22//! # Module map
23//!
24//! - [`Runtime`] (in `runtime`) — public entry point; spawns one `shard` per core.
25//! - `shard` — the per-core reactor: sockets, the inbound queue, reply flushing.
26//! - `exec` — command semantics: routing, execution, and result reduction.
27//! - `message` — internal cross-core work/result types.
28//! - `conn` — per-connection state (input/output, seq ring, subscriptions).
29//! - `reduce` — reply reduction (`materialize`) and pure helpers (set algebra,
30//!   shard hashing, pub/sub framing).
31//!
32//! # Example
33//!
34//! Implement [`Commands`] for your command set and run it. ([`Store`] is
35//! re-exported so you don't need a separate dependency.)
36//!
37//! ```no_run
38//! use kevy_rt::{ArgvView, Commands, Route, Runtime, Store, TxnKind};
39//! use std::sync::Arc;
40//! use std::sync::atomic::AtomicBool;
41//!
42//! #[derive(Clone)]
43//! struct MyCommands;
44//! impl Commands for MyCommands {
45//!     fn route<A: ArgvView + ?Sized>(&self, args: &A) -> Route {
46//!         if args.len() >= 2 { Route::Single(1) } else { Route::Local }
47//!     }
48//!     fn dispatch<A: ArgvView + ?Sized>(&self, _store: &mut Store, _args: &A) -> Vec<u8> {
49//!         b"+OK\r\n".to_vec()
50//!     }
51//!     fn is_quit<A: ArgvView + ?Sized>(&self, args: &A) -> bool {
52//!         args.first().is_some_and(|c| c.eq_ignore_ascii_case(b"QUIT"))
53//!     }
54//!     fn is_write<A: ArgvView + ?Sized>(&self, _args: &A) -> bool { false }
55//!     fn txn_kind<A: ArgvView + ?Sized>(&self, _args: &A) -> TxnKind { TxnKind::Other }
56//! }
57//!
58//! // One shard per core, listening on 127.0.0.1:6379, until `stop` is set.
59//! let rt = Runtime::new([127, 0, 0, 1], 6379, 4, MyCommands);
60//! rt.run(Arc::new(AtomicBool::new(false))).unwrap();
61//! ```
62// Almost entirely safe: the only `unsafe` is in `uring_reactor` (Linux io_uring),
63// which needs raw buffer pointers for zero-allocation completion I/O — on the hot
64// path toward kevy's disk-I/O-ceiling goal, where a buffer-ownership safe wrapper
65// would add per-op cost. Each such block documents its invariant; the
66// epoll/kqueue path and every other module stay safe, and all libc lives in
67// kevy-sys.
68#![deny(unsafe_op_in_unsafe_fn)]
69
70mod block_xshard;
71mod blocked;
72mod cluster;
73mod conn;
74mod exec;
75mod exec_build;
76mod exec_dispatch;
77mod exec_notify;
78mod exec_op;
79mod exec_pubsub;
80mod exec_pubsub_pattern;
81mod exec_rename;
82mod exec_slowlog;
83mod exec_watch;
84mod inbox;
85mod persist_worker;
86mod message;
87mod reduce;
88mod replica_inbox;
89mod replication;
90mod replication_apply;
91mod replication_gate;
92mod replication_io;
93mod replication_pump;
94mod reshard;
95mod route;
96mod runtime;
97mod runtime_builders;
98mod shard;
99mod shard_flush;
100mod shard_lifecycle;
101mod shard_tick;
102#[cfg(target_os = "linux")]
103mod uring_conn;
104#[cfg(target_os = "linux")]
105mod uring_inbox;
106#[cfg(target_os = "linux")]
107mod uring_park;
108#[cfg(target_os = "linux")]
109mod uring_reactor;
110
111pub use blocked::{BlockHint, BlockKind};
112pub use cluster::shard_slot_range;
113pub use exec_slowlog::{SlowlogSub, parse_slowlog_sub};
114pub use kevy_config::NotificationFlags;
115pub use kevy_persist::Fsync;
116pub use kevy_resp::{Argv, ArgvBorrowed, ArgvView, RespVersion};
117pub use kevy_store::Store;
118pub use replica_inbox::{ReplicaApply, ReplicaInboxReceiver, ReplicaInboxSender, replica_inbox_pair};
119pub use replication_gate::ReplicatedApplyGuard;
120pub use route::{Route, XGroupCtx};
121pub use runtime::Runtime;
122
123/// Command-set semantics injected into the runtime. Cloned to every core, so it
124/// must be cheap/stateless to clone.
125pub trait Commands: Clone + Send + 'static {
126    /// Classify how a command is routed across shards.
127    fn route<A: ArgvView + ?Sized>(&self, args: &A) -> Route;
128    /// Execute a full command against one shard's store, returning RESP bytes.
129    fn dispatch<A: ArgvView + ?Sized>(&self, store: &mut Store, args: &A) -> Vec<u8>;
130    /// RESP3 variant of [`Self::dispatch`] — called when the connection
131    /// has negotiated `HELLO 3`. Default: delegate to the RESP2 path
132    /// (the cross-shard forward carries a per-cmd `RespVersion`
133    /// so a V2 client and a V3 client can share the owning shard).
134    fn dispatch_resp3<A: ArgvView + ?Sized>(&self, store: &mut Store, args: &A) -> Vec<u8> {
135        self.dispatch(store, args)
136    }
137    /// Execute a command, appending the RESP reply to `out`. The in-order local
138    /// fast path uses this to write straight into the connection's output buffer
139    /// (no per-command reply `Vec`). Default: delegate to [`dispatch`](Self::dispatch).
140    fn dispatch_into<A: ArgvView + ?Sized>(&self, store: &mut Store, args: &A, out: &mut Vec<u8>) {
141        out.extend_from_slice(&self.dispatch(store, args));
142    }
143    /// RESP3 variant of [`Self::dispatch_into`] — called when the
144    /// connection has negotiated `HELLO 3`. Default: delegate to the
145    /// RESP2 path (so a server that hasn't migrated any replies still
146    /// works correctly with a RESP3 client, per spec). Override per
147    /// command to emit RESP3 shapes (Map / Set / Double / …).
148    fn dispatch_into_resp3<A: ArgvView + ?Sized>(
149        &self,
150        store: &mut Store,
151        args: &A,
152        out: &mut Vec<u8>,
153    ) {
154        self.dispatch_into(store, args, out);
155    }
156    /// Classify a command for keyspace notifications. Returns `Some`
157    /// for write commands that should fire a notification when the
158    /// corresponding flag is enabled; `None` for read-only / no-op /
159    /// not-yet-classified commands (those never publish). Default
160    /// `None` so non-kevy embedders pay nothing.
161    fn notify_class<A: ArgvView + ?Sized>(&self, _args: &A) -> Option<NotifyClass> {
162        None
163    }
164
165    /// Handle `HELLO` — return the new connection protocol version + the
166    /// reply bytes. The runtime applies the new version to the conn
167    /// before scheduling the reply, so a `HELLO 3` ack itself comes out
168    /// shaped as a RESP3 Map (the new protocol is in effect for its own
169    /// reply).
170    ///
171    /// Default: ignore the args, keep `current_proto`, emit a minimal
172    /// RESP2 +OK so embedders that don't care still see a sane reply.
173    /// kevy's own impl in `kevy::KevyCommands` parses the optional
174    /// protover and emits the full server-info shape.
175    fn hello_reply<A: ArgvView + ?Sized>(
176        &self,
177        _args: &A,
178        current_proto: RespVersion,
179    ) -> (RespVersion, Vec<u8>) {
180        (current_proto, b"+OK\r\n".to_vec())
181    }
182    /// Whether this command should close the connection (QUIT).
183    fn is_quit<A: ArgvView + ?Sized>(&self, args: &A) -> bool;
184    /// Whether this command mutates the keyspace (so it must be logged to the AOF).
185    fn is_write<A: ArgvView + ?Sized>(&self, args: &A) -> bool;
186    /// Transaction-control classification (MULTI/EXEC/DISCARD vs anything else).
187    fn txn_kind<A: ArgvView + ?Sized>(&self, args: &A) -> TxnKind;
188    /// Called once per shard, immediately after [`Store::new`], before the
189    /// reactor enters its event loop. Implementations install per-shard
190    /// configuration that the runtime doesn't know about — currently the
191    /// `maxmemory` + eviction-policy pair, which kevy ships via its own
192    /// process-wide config snapshot. Default: no-op so non-kevy embedders
193    /// aren't forced to override.
194    fn on_shard_init(&self, _store: &mut Store) {}
195
196    /// Called once on the shard's own thread, first thing in the reactor
197    /// entry (both reactors), before restore/replay. Implementations that
198    /// need per-shard identity at dispatch time (e.g. kevy's `CLUSTER MYID`
199    /// / `CLUSTER NODES` `myself` flag) stash `shard` in a thread-local here
200    /// — in a thread-per-core runtime the current thread *is* the shard.
201    /// Default: no-op.
202    fn on_shard_start(&self, _shard: usize) {}
203
204    /// Per-tick persistence-stats publication: whether this shard has a
205    /// background save/rewrite in flight and how many AOF rewrites have
206    /// completed since open. Command layers that serve `INFO persistence`
207    /// stash these in a thread-local (thread-per-core: the answering
208    /// thread *is* the shard, same pattern as [`Self::on_shard_start`]).
209    /// Default: no-op.
210    fn on_persist_stats(&self, _in_flight: bool, _aof_rewrites_total: u64) {}
211
212    /// Per-tick replication-view publication: the answering shard's
213    /// current `master_repl_offset` (== `ReplicationSource::next_offset()`)
214    /// plus the per-replica `(ipv4, port, sent_offset)` triple for
215    /// every handshake-complete replica (in `AckSent`, `Streaming`,
216    /// or `SnapshotShipping`). `connected_slaves` for `INFO` /
217    /// `ROLE` is derived as `replicas.len()`.
218    /// Only called when this shard has a `ReplicationSource`
219    /// installed (i.e. `Runtime::with_replication(true, ...)` was
220    /// requested); standalone setups pay nothing. Command layers
221    /// that serve `ROLE` / `INFO replication` stash the values in a
222    /// thread-local (thread-per-core: the answering thread *is* the
223    /// shard, same pattern as [`Self::on_persist_stats`]). Default
224    /// no-op.
225    fn on_replication_view(
226        &self,
227        _master_repl_offset: u64,
228        _replicas: Vec<(std::net::Ipv4Addr, u16, u64)>,
229    ) {}
230
231    /// Periodic shard housekeeping (the equivalent of Redis's `serverCron`).
232    /// kevy uses this to run [`Store::tick_expire`] at the configured
233    /// `[expiry].hz`. Default no-op so non-kevy embedders / runtimes can
234    /// ignore it.
235    fn on_shard_tick(&self, _store: &mut Store) {}
236
237    /// Called once per client command at dispatch entry (before routing /
238    /// fan-out, so a multi-key command counts once). kevy uses it for
239    /// `INFO stats: total_commands_processed`. Hot path — keep it to a single
240    /// thread-local bump. Default no-op so non-kevy embedders pay nothing.
241    fn on_command(&self) {}
242
243    /// Called once per accepted client connection. kevy uses it for
244    /// `INFO stats: total_connections_received`. Default no-op.
245    fn on_connection(&self) {}
246
247    /// Interval between [`Self::on_shard_tick`] calls. Default 100 ms
248    /// (matching Redis's `hz = 10`). `0` disables ticking entirely.
249    fn shard_tick_interval_ms(&self) -> u64 {
250        100
251    }
252
253    /// Snapshot of the runtime-owned knobs that can be hot-modified
254    /// (the kevy server wires this to `CONFIG SET`). Called once per
255    /// shard tick — each `Some` value is applied to the shard's live
256    /// state; each `None` keeps the existing setting untouched.
257    ///
258    /// Default returns all-None so embedders that never hot-swap config
259    /// pay nothing beyond one struct-build per tick. The cost lives in
260    /// the impl's read of its own config source.
261    fn live_runtime_config(&self) -> LiveRuntimeConfig {
262        LiveRuntimeConfig::default()
263    }
264
265    /// Index into `args` of the key whose write may wake a blocked waiter
266    /// (`LPUSH` / `RPUSH` feed `BLPOP` / `BRPOP`; `XADD` feeds the stream
267    /// blocks). `Some(1)` for those verbs, `None` for everything else. The
268    /// in-shard fast path reads this off [`ResolvedCmd::wake_idx`]; the
269    /// cross-shard write path (`exec_op`, where a forwarded write
270    /// lands on the key's owning shard) re-derives it via this method since
271    /// the forwarded envelope doesn't carry the resolved hint. Default
272    /// `None` so non-blocking embedders pay nothing.
273    fn wake_idx<A: ArgvView + ?Sized>(&self, _args: &A) -> Option<u8> {
274        None
275    }
276
277    /// Classify a command for blocking semantics. `BlockHint::None`
278    /// (default) is the zero-cost answer for every non-blocking verb;
279    /// the dispatcher only registers a waiter when this returns
280    /// `BlockHint::Block` *and* the command's `dispatch_into` produced no
281    /// reply (i.e. it could not satisfy itself immediately — e.g. BLPOP
282    /// on an empty list). Concrete impls should fold this into their
283    /// override of [`Self::resolve`] so the verb-table lookup happens
284    /// once per command.
285    fn block_hint<A: ArgvView + ?Sized>(&self, _args: &A) -> BlockHint {
286        BlockHint::None
287    }
288
289    /// Rewrite `args` into the owned [`Argv`] that the dispatcher will
290    /// store as the parked waiter's command and replay on wake. Lets a
291    /// command set normalise positional ID / cursor arguments that would
292    /// otherwise re-resolve to a different value on retry — most notably
293    /// `XREAD BLOCK ... STREAMS k $`, where leaving `$` literal in the
294    /// retried argv causes a fresh re-resolve to the post-`XADD` last_id
295    /// and zero matching entries (the wake hangs).
296    ///
297    /// Default: just materialise the argv unchanged. Concrete impls only
298    /// need to override when a registered command carries an arg whose
299    /// meaning depends on store state at park time (`XREAD $`, the
300    /// classic case).
301    ///
302    /// For the cross-shard arbiter this runs on the **target** shard (the
303    /// one that owns the key) when the waiter is armed, so `$` snapshots
304    /// the target's real `last_id` — not the origin shard's (which may not
305    /// hold the stream at all).
306    fn resolve_block_argv<A: ArgvView + ?Sized>(
307        &self,
308        _store: &mut Store,
309        args: &A,
310        _kind: BlockKind,
311    ) -> Argv {
312        args.to_argv()
313    }
314
315    /// Build the **single-key** command the dispatcher will replay to
316    /// satisfy one watched `key` of a (possibly multi-key) blocking
317    /// command. `args` is the original command; `key` is one of its
318    /// watched keys. Returns an [`Argv`] that, when dispatched, pops /
319    /// reads only `key` — e.g. `BLPOP k1 k2 0` watching `k2` yields
320    /// `BLPOP k2 0`; `XREAD … STREAMS s1 s2 id1 id2` watching `s2`
321    /// yields `XREAD … STREAMS s2 id2`.
322    ///
323    /// Any state-dependent positional arg (`$`) is left **literal** here —
324    /// it's frozen later by [`Self::resolve_block_argv`] on the key's
325    /// owning shard. No store access needed (pure argv slicing). Default:
326    /// the unchanged argv (single-key blocking commands need no rewrite).
327    fn block_serve_argv<A: ArgvView + ?Sized>(
328        &self,
329        args: &A,
330        _kind: BlockKind,
331        _key: &[u8],
332    ) -> Argv {
333        args.to_argv()
334    }
335
336    /// Non-destructive readiness peek for a parked waiter: would replaying
337    /// `serve_argv` (built by [`Self::block_serve_argv`], `$` already
338    /// frozen) produce a reply right now? Runs on the key's owning shard
339    /// when arming and is the gate for emitting a cross-shard wake. Must
340    /// NOT mutate the store (no pop / no group-cursor advance). Default
341    /// `false` so non-blocking embedders never spuriously wake.
342    fn block_ready<A: ArgvView + ?Sized>(
343        &self,
344        _store: &mut Store,
345        _serve_argv: &A,
346        _kind: BlockKind,
347    ) -> bool {
348        false
349    }
350
351    /// Resolve all verb-dependent attributes in **one** verb-table lookup.
352    /// The default implementation calls the per-attribute methods above
353    /// (five upper_verb scans + matches); concrete impls SHOULD override
354    /// this with a single match so the reactor's hot path pays the verb-
355    /// resolution cost only once per command.
356    fn resolve<A: ArgvView + ?Sized>(&self, args: &A) -> ResolvedCmd {
357        ResolvedCmd {
358            txn_kind: self.txn_kind(args),
359            route: self.route(args),
360            is_quit: self.is_quit(args),
361            is_write: self.is_write(args),
362            block_hint: self.block_hint(args),
363            wake_idx: None,
364        }
365    }
366}
367
368/// Per-command verb-resolution result. Produced once by [`Commands::resolve`]
369/// in the reactor's parse-then-dispatch loop, reused for routing decisions,
370/// AOF logging, and the QUIT branch — so the per-cmd `upper_verb` cost goes
371/// from 4× down to 1×.
372pub struct ResolvedCmd {
373    pub txn_kind: TxnKind,
374    pub route: Route,
375    pub is_quit: bool,
376    pub is_write: bool,
377    /// Blocking-command classification (see [`Commands::block_hint`]).
378    /// `BlockHint::None` for every non-blocking verb.
379    pub block_hint: BlockHint,
380    /// Index into `args` whose write may wake a `BLPOP` / `XREAD BLOCK`
381    /// waiter parked on that key — `Some(1)` for `LPUSH` / `RPUSH` /
382    /// `XADD`, `None` for every other command (including reads). The
383    /// dispatcher's wake hook is gated on both this being `Some` *and*
384    /// the per-shard `BlockedClients` registry being non-empty, so the
385    /// steady-state cost when nobody is parked is one `is_empty()` check.
386    pub wake_idx: Option<u8>,
387}
388
389/// Keyspace-notification event class — what category a write command
390/// belongs to, so the runtime can match it against the per-conn
391/// notify_keyspace_events flags before publishing.
392#[derive(Debug, Clone, Copy, PartialEq, Eq)]
393pub enum NotifyClass {
394    /// `g` — generic key commands (DEL / EXPIRE / PERSIST / RENAME / TYPE).
395    Generic,
396    /// `$` — string commands (SET / GETSET / INCR / APPEND / MSET).
397    String,
398    /// `l` — list commands (LPUSH / RPUSH / LPOP / LREM / LTRIM / …).
399    List,
400    /// `s` — set commands (SADD / SREM / SPOP / …).
401    Set,
402    /// `h` — hash commands (HSET / HDEL / HINCRBY / …).
403    Hash,
404    /// `z` — sorted-set commands (ZADD / ZREM / ZINCRBY / …).
405    Zset,
406    /// `t` — stream commands (XADD / XDEL / XTRIM / XGROUP / XACK /
407    /// XCLAIM / XREADGROUP / …). Matches Redis's `t` class.
408    Stream,
409}
410
411impl NotifyClass {
412    /// Whether `flags` enables this event class.
413    #[inline]
414    pub fn enabled_in(self, flags: &NotificationFlags) -> bool {
415        match self {
416            NotifyClass::Generic => flags.generic,
417            NotifyClass::String => flags.string,
418            NotifyClass::List => flags.list,
419            NotifyClass::Set => flags.set,
420            NotifyClass::Hash => flags.hash,
421            NotifyClass::Zset => flags.zset,
422            NotifyClass::Stream => flags.stream,
423        }
424    }
425}
426
427/// Transaction-control classification for a command.
428pub enum TxnKind {
429    Multi,
430    Exec,
431    Discard,
432    /// `WATCH` — outside MULTI runs the fan-out; inside MULTI is rejected
433    /// with an error (Redis semantics: `WATCH inside MULTI is not allowed`).
434    /// `UNWATCH` is plain [`Self::Other`] — outside MULTI it routes to
435    /// [`Route::Unwatch`] (clear + OK); inside MULTI it queues as a no-op
436    /// that dispatch resolves to +OK at EXEC time.
437    Watch,
438    Other,
439}
440
441/// Live snapshot of the runtime-owned knobs that may have been changed
442/// since this shard's last tick. Built by the [`Commands`] impl from
443/// its own config source (e.g. kevy reads `config_global`). Each
444/// `Some(_)` is applied to the shard; each `None` leaves the existing
445/// setting alone.
446///
447/// One snapshot is built per tick (every 100 ms by default), so its
448/// cost is amortised across thousands of commands.
449#[derive(Debug, Default, Clone, Copy)]
450pub struct LiveRuntimeConfig {
451    /// AOF fsync policy. Applied via `Aof::set_fsync` — switching to
452    /// `Always` mid-flight also flushes any buffered bytes so the new
453    /// "every write is on disk before reply" contract is honoured from
454    /// the next append onward.
455    pub appendfsync: Option<Fsync>,
456    /// `auto_aof_rewrite_percentage`. `0` disables the auto-trigger.
457    pub auto_aof_rewrite_pct: Option<u32>,
458    /// `auto_aof_rewrite_min_size` in bytes.
459    pub auto_aof_rewrite_min_size: Option<u64>,
460    /// New tick interval in ms (`1000/hz`). `0` disables ticking
461    /// entirely — note that disabling also turns off active TTL
462    /// expiry and the auto-rewrite tick path. Lazy expiry on access
463    /// always still works.
464    pub tick_interval_ms: Option<u64>,
465    /// `notify_keyspace_events` flags. Parsed by the [`Commands`]
466    /// impl from its config source (e.g. kevy reads
467    /// `config_global` + [`kevy_config::parse_notification_flags`]).
468    /// Default-empty flags mean OFF — writes pay one bool-OR check
469    /// and skip every per-key keyspace notification publish.
470    pub notify_flags: Option<NotificationFlags>,
471    /// `[slowlog].slower_than_micros` — `-1` disables, `0` records all,
472    /// `>0` is the strict micros threshold. `None` keeps the existing
473    /// shard setting (set by the [`Runtime`] builder at startup).
474    pub slowlog_slower_than_micros: Option<i64>,
475    /// `[slowlog].max_len` — ring cap per shard. Shrinking trims the
476    /// oldest entries on the next tick application.
477    pub slowlog_max_len: Option<u32>,
478}