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