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