kevy_rt/runtime.rs
1//! The public entry point: configure and run the thread-per-core server.
2
3use crate::Commands;
4use crate::message::{Inbound, PubSubPatternReg, PubSubReg};
5use crate::shard::Shard;
6use kevy_map::KevyMap;
7use kevy_persist::{Aof, Fsync};
8use kevy_ring::{Consumer, Producer};
9use kevy_store::Store;
10use kevy_sys::{Poller, Waker, tcp_listen_reuseport, waker};
11use std::collections::{HashMap, VecDeque};
12use std::io;
13use std::path::PathBuf;
14use std::sync::atomic::{AtomicBool, AtomicU64};
15use std::sync::{Arc, RwLock};
16
17/// Default slots in each per-core-pair SPSC ring. A full ring spills
18/// to a local backlog (see [`Shard`]), so this only bounds the
19/// lock-free fast path, not capacity. Overridable via the
20/// `[advanced] ring_capacity` config field threaded through
21/// [`Runtime::with_advanced`].
22const DEFAULT_RING_CAPACITY: usize = 1024;
23
24/// The public entry point: configure and run the thread-per-core server.
25pub struct Runtime<C: Commands> {
26 pub(crate) ip: [u8; 4],
27 pub(crate) port: u16,
28 pub(crate) nshards: usize,
29 pub(crate) commands: C,
30 /// Directory for per-shard snapshot files (`dump-<id>.rdb`) and AOF logs.
31 pub(crate) data_dir: PathBuf,
32 /// Whether the append-only log is enabled.
33 pub(crate) enable_aof: bool,
34 /// fsync policy for the AOF. Default `EverySec` matches Redis.
35 pub(crate) appendfsync: Fsync,
36 /// auto-trigger BGREWRITEAOF when AOF grew this many % above the size
37 /// at the previous rewrite. `0` disables. Default `100` (matches Redis).
38 pub(crate) auto_aof_rewrite_pct: u32,
39 /// Floor below which auto-rewrite is skipped. Default `64 MiB`.
40 pub(crate) auto_aof_rewrite_min_size: u64,
41 /// Reactor SPSC ring slot count. See [`DEFAULT_RING_CAPACITY`].
42 pub(crate) ring_capacity: usize,
43 /// Reactor busy-poll iter limit before parking. Stored as `u32`
44 /// for the per-shard counter; the [`Shard`] field carries it
45 /// forward into the loop.
46 pub(crate) spin_limit: u32,
47 /// Reactor blocking-wait timeout in ms when parked.
48 pub(crate) park_timeout_ms: u32,
49 /// Wall-clock-read throttle for the tick check (TTL reaper / live
50 /// config refresh / auto-AOF-rewrite).
51 pub(crate) tick_check_every: u32,
52 /// `[slowlog].slower_than_micros`. Default: `-1` (OFF — zero
53 /// hot-path cost: every command would otherwise pay an
54 /// `Instant::now()` pair around dispatch). Set to `10_000` to match
55 /// Redis's default 10 ms threshold; see [`Self::with_slowlog`] /
56 /// `CONFIG SET slowlog-log-slower-than 10000`.
57 pub(crate) slowlog_slower_than_micros: i64,
58 /// `[slowlog].max_len`. Per-shard cap.
59 pub(crate) slowlog_max_len: u32,
60 /// Single-node cluster mode: slot-based key routing (CRC16 `{hashtag}`
61 /// → contiguous ranges) + one deterministic extra listener per shard at
62 /// `cluster_port_base + id`. `None` = off (default, zero change).
63 pub(crate) cluster_port_base: Option<u16>,
64 /// v3-cluster replication: when `true`, each shard runs a
65 /// `ReplicationSource` with `replication_buffer_size` byte budget;
66 /// every applied mutation is pushed to the backlog. The TCP
67 /// listener + streaming loop arrive in subsequent tasks (T1.12+);
68 /// this batch only wires the producer side. Default `false`.
69 pub(crate) enable_replication: bool,
70 /// Per-shard backlog byte budget when `enable_replication` is set.
71 /// Fed from `[replication] replication_buffer_size`. Default
72 /// `256 MiB` (matches the kevy-config default).
73 pub(crate) replication_buffer_size: u64,
74 /// v3-cluster replication listener: shard `i` binds at
75 /// `replication_port_base + i` (mirrors cluster listener pattern;
76 /// per Issue Ledger I2). `None` = no listener (producer side runs
77 /// without a network surface, backlog accumulates and evicts —
78 /// useful for benchmarks). Default `None`.
79 pub(crate) replication_port_base: Option<u16>,
80 /// Per-shard SlotTable reconnect-window in ms (T1.15). After a
81 /// streaming replica disconnects, its `(replica_id, sent_offset)`
82 /// is recorded in the shard's `slots` map; slots past this age
83 /// are reaped on the next shard tick. Default `60_000` (60 s)
84 /// matches the kevy-config default.
85 pub(crate) replication_reconnect_window_ms: u32,
86 /// Per-shard replica inboxes installed by
87 /// [`Self::with_replica_inboxes`]. Each entry is consumed
88 /// (via `Option::take`) when its shard is constructed, so the
89 /// receiver flows from this Vec to the matching `Shard.replica_inbox`.
90 /// Empty when no replica mode is configured.
91 pub(crate) replica_inboxes: Vec<Option<crate::replica_inbox::ReplicaInboxReceiver>>,
92}
93
94impl<C: Commands> Runtime<C> {
95 #[must_use]
96 pub fn new(ip: [u8; 4], port: u16, nshards: usize, commands: C) -> Self {
97 Runtime {
98 ip,
99 port,
100 nshards: nshards.max(1),
101 commands,
102 data_dir: PathBuf::from("."),
103 enable_aof: true,
104 appendfsync: Fsync::EverySec,
105 auto_aof_rewrite_pct: 100,
106 auto_aof_rewrite_min_size: 64 * 1024 * 1024,
107 ring_capacity: DEFAULT_RING_CAPACITY,
108 spin_limit: 256,
109 park_timeout_ms: 50,
110 tick_check_every: 256,
111 slowlog_slower_than_micros: -1,
112 slowlog_max_len: 128,
113 cluster_port_base: None,
114 enable_replication: false,
115 replica_inboxes: Vec::new(),
116 replication_buffer_size: 256 * 1024 * 1024,
117 replication_port_base: None,
118 replication_reconnect_window_ms: 60_000,
119 }
120 }
121
122
123 /// Spawn one thread per shard and run until `stop` is set.
124 pub fn run(mut self, stop: Arc<AtomicBool>) -> io::Result<()> {
125 let n = self.nshards;
126
127 // Cluster binds shard `i` at `port_base + i`; reject a range that
128 // overflows u16 up front (loud) instead of wrapping a listener onto
129 // a low/privileged port while CLUSTER SLOTS advertises 65536+.
130 if let Some(base) = self.cluster_port_base
131 && base as usize + n > u16::MAX as usize + 1
132 {
133 return Err(io::Error::new(
134 io::ErrorKind::InvalidInput,
135 format!(
136 "cluster port range {base}..={} exceeds 65535 ({n} shards)",
137 base as usize + n - 1
138 ),
139 ));
140 }
141
142 // Same overflow check for the replication port range
143 // (`base + 0 .. base + n`). See Issue Ledger I2 for the
144 // per-shard listener decision.
145 if let Some(base) = self.replication_port_base
146 && base as usize + n > u16::MAX as usize + 1
147 {
148 return Err(io::Error::new(
149 io::ErrorKind::InvalidInput,
150 format!(
151 "replication port range {base}..={} exceeds 65535 ({n} shards)",
152 base as usize + n - 1
153 ),
154 ));
155 }
156
157 // One lock-free SPSC ring per ordered core-pair (i→j): the producer goes
158 // to shard i's outbox[j], the consumer to shard j's inbox[i]. There is no
159 // self-ring — a shard runs its own commands inline, never over a ring.
160 let mut outboxes: Vec<Vec<Option<Producer<Inbound>>>> =
161 (0..n).map(|_| (0..n).map(|_| None).collect()).collect();
162 let mut inboxes: Vec<Vec<Option<Consumer<Inbound>>>> =
163 (0..n).map(|_| (0..n).map(|_| None).collect()).collect();
164 for i in 0..n {
165 for j in 0..n {
166 if i == j {
167 continue;
168 }
169 let (p, c) = kevy_ring::ring::<Inbound>(self.ring_capacity);
170 outboxes[i][j] = Some(p);
171 inboxes[j][i] = Some(c);
172 }
173 }
174
175 let mut wakers: Vec<Arc<Waker>> = Vec::with_capacity(n);
176 for _ in 0..n {
177 wakers.push(Arc::new(waker()?));
178 }
179 let parked: Vec<Arc<AtomicBool>> =
180 (0..n).map(|_| Arc::new(AtomicBool::new(false))).collect();
181 // Per-shard inbox-dirty bitmaps (one u64 bit per peer src).
182 // Senders OR a bit on the target's dirty word; the target's
183 // `drain_inbound_core` swaps and short-circuits when 0.
184 assert!(
185 n <= 64,
186 "kevy-rt: shard count {n} exceeds 64 — inbound_dirty bitmap holds one bit per peer in a u64. Reduce --threads or extend to a multi-word bitmap.",
187 );
188 let inbound_dirty: Vec<Arc<AtomicU64>> =
189 (0..n).map(|_| Arc::new(AtomicU64::new(0))).collect();
190
191 // Shared pub/sub channel registry (one per server, read on every PUBLISH).
192 let pubsub: PubSubReg = Arc::new(RwLock::new(HashMap::new()));
193 // Shared pub/sub pattern registry. Empty in steady state — the
194 // channel-only PUBLISH path skips the walk when so.
195 let pubsub_patterns: PubSubPatternReg = Arc::new(RwLock::new(Vec::new()));
196
197 // Reconcile the on-disk shard layout (count + routing) before any
198 // shard loads its files; a mismatch re-homes every key once, here.
199 // Skipped for a pure in-memory run against a dir with no kevy files.
200 // Cluster mode always records the layout even with AOF off and an
201 // empty dir: a later SAVE writes slot-distributed `dump-{i}.rdb`, and
202 // without a meta a non-cluster restart would read them as KevyHash
203 // and silently strand every key.
204 if self.enable_aof
205 || self.cluster_port_base.is_some()
206 || crate::reshard::has_kevy_files(&self.data_dir)
207 {
208 let routing = if self.cluster_port_base.is_some() {
209 kevy_persist::Routing::Slots
210 } else {
211 kevy_persist::Routing::KevyHash
212 };
213 crate::reshard::ensure_layout(&self.data_dir, n, routing, &self.commands)?;
214 }
215
216 // Advertised cluster topology (None = cluster off). A 0.0.0.0 bind
217 // advertises 127.0.0.1 — an unroutable redirect target would strand
218 // every cluster client (single-machine scope; no announce-ip knob).
219 let topo = self.cluster_port_base.map(|base| crate::cluster::ClusterTopo {
220 ip: if self.ip == [0, 0, 0, 0] { [127, 0, 0, 1] } else { self.ip },
221 port_base: base,
222 });
223
224 // Build every shard up front so a bind/open failure aborts before we spawn.
225 let mut shards = Vec::with_capacity(n);
226 for id in 0..n {
227 let listener = tcp_listen_reuseport(self.ip, self.port, 1024)?;
228 // Cluster mode: a second, deterministic per-shard listener at
229 // port_base + id (plain bind — exactly one owner per port).
230 let cluster_listener = match self.cluster_port_base {
231 Some(base) => Some(kevy_sys::tcp_listen(self.ip, base + id as u16, 1024)?),
232 None => None,
233 };
234 // Replication listener (per Issue Ledger I2): per-shard
235 // deterministic port, same `tcp_listen` (no SO_REUSEPORT)
236 // pattern as cluster. A replica's shard-aware client will
237 // connect to every `base + id` to mirror the full keyspace.
238 let replication_listener = match self.replication_port_base {
239 Some(base) => Some(kevy_sys::tcp_listen(self.ip, base + id as u16, 1024)?),
240 None => None,
241 };
242 let aof = if self.enable_aof {
243 Some(Aof::open(
244 &kevy_persist::layout::aof_path(&self.data_dir, id),
245 self.appendfsync,
246 )?)
247 } else {
248 None
249 };
250 let mut store = Store::new();
251 // The reactor loop refreshes the store clock once per batch, so
252 // lazy expiry can trust the cached clock (skip per-command
253 // `Instant::now()`).
254 store.set_cached_clock(true);
255 self.commands.on_shard_init(&mut store);
256 shards.push(Shard {
257 id,
258 nshards: n,
259 cluster: topo.clone(),
260 cluster_listener,
261 store,
262 commands: self.commands.clone(),
263 poller: Poller::new()?,
264 listener,
265 waker: wakers[id].clone(),
266 inboxes: std::mem::take(&mut inboxes[id]),
267 outboxes: std::mem::take(&mut outboxes[id]),
268 backlog: (0..n).map(|_| VecDeque::new()).collect(),
269 wakers: wakers.clone(),
270 conns: KevyMap::new(),
271 fd_to_conn: KevyMap::new(),
272 next_conn_id: 1,
273 events: Vec::with_capacity(1024),
274 read_buf: vec![0u8; 64 * 1024],
275 pending_wakes: 0,
276 backlog_nonempty: 0,
277 request_batch_nonempty: 0,
278 publish_batch_nonempty: 0,
279 parked: parked.clone(),
280 inbound_dirty: inbound_dirty.clone(),
281 data_dir: self.data_dir.clone(),
282 aof,
283 replicate: if self.enable_replication {
284 Some(kevy_replicate::source::ReplicationSource::new(
285 usize::try_from(self.replication_buffer_size)
286 .unwrap_or(usize::MAX),
287 ))
288 } else {
289 None
290 },
291 replication_listener,
292 replicas: Vec::new(),
293 slots: kevy_replicate::slot::SlotTable::new(),
294 replication_reconnect_window_ms: self.replication_reconnect_window_ms,
295 replication_epoch: std::time::Instant::now(),
296 replica_inbox: self.replica_inboxes.get_mut(id).and_then(Option::take),
297 replica_snapshot_buf: Vec::new(),
298 persist: crate::persist_worker::PersistWorker::new(),
299 auto_aof_rewrite_pct: self.auto_aof_rewrite_pct,
300 auto_aof_rewrite_min_size: self.auto_aof_rewrite_min_size,
301 dirty: Vec::new(),
302 pubsub: pubsub.clone(),
303 pubsub_patterns: pubsub_patterns.clone(),
304 psub_local: HashMap::new(),
305 publish_batch: (0..n).map(|_| Vec::new()).collect(),
306 request_batch: (0..n).map(|_| Vec::new()).collect(),
307 // Seed from the live config at construction, not default():
308 // these flags were otherwise blind until the first 100 ms
309 // shard tick, so a write landing before that never fired
310 // its keyspace notification (CI-visible flake; a real
311 // startup gap for any pre-configured notify_keyspace_events).
312 notify_flags: self
313 .commands
314 .live_runtime_config()
315 .notify_flags
316 .unwrap_or_default(),
317 spin_limit: self.spin_limit,
318 // `Poller::wait` takes the timeout as `i32` (POSIX
319 // poll/epoll convention). The config knob is `u32` —
320 // we clamp to i32::MAX, far above any sane park-timeout.
321 park_timeout_ms: self.park_timeout_ms.min(i32::MAX as u32) as i32,
322 tick_check_every: self.tick_check_every,
323 slowlog: crate::exec_slowlog::SlowlogState::new(
324 self.slowlog_slower_than_micros,
325 self.slowlog_max_len,
326 ),
327 blocked: crate::blocked::BlockedClients::new(),
328 origin_blocks: std::collections::HashMap::new(),
329 xwaiters: crate::block_xshard::XShardWaiters::default(),
330 reply_scratch: Vec::with_capacity(4096),
331 argv_pool: kevy_resp::ArgvPool::new(),
332 });
333 }
334
335 // Reactor selection on Linux:
336 // KEVY_IO_URING unset → auto: try io_uring, fall back to epoll if the
337 // host can't build the ring (probe below) — startup never fails.
338 // KEVY_IO_URING=0/off/no/false → force the epoll readiness reactor.
339 // KEVY_IO_URING=<anything else> → force io_uring (no fallback; a
340 // setup failure then surfaces loudly — for benchmarks / tests).
341 // The probe creates+drops a real ring with the run_uring parameters, so
342 // it catches a seccomp-blocked io_uring_setup (Docker's default profile)
343 // and pre-5.19 kernels before any shard loads data. (macOS = kqueue.)
344 #[cfg(target_os = "linux")]
345 let use_uring = match std::env::var("KEVY_IO_URING").ok().as_deref() {
346 Some("0") | Some("off") | Some("no") | Some("false") => false,
347 Some(_) => true,
348 None => {
349 let avail = crate::uring_reactor::io_uring_available();
350 eprintln!(
351 "kevy: reactor = {} (io_uring {})",
352 if avail { "io_uring" } else { "epoll" },
353 if avail { "available" } else { "unavailable — kernel <5.19 or seccomp; using epoll" },
354 );
355 avail
356 }
357 };
358
359 // v1.18.0: the replication listener + accept path is wired only
360 // through the epoll/kqueue reactor (`shard.run`); the io_uring
361 // T1.12.5: io_uring + replication is now supported. The
362 // replication-adjacent work (accept / read / write / pump /
363 // slot+view+watermark ticks) is poll-driven from the io_uring
364 // reactor's tick path (mostly per-tick @ 10 Hz, with
365 // `pump_replication` + `reap_closed_replicas` per-iter via
366 // their own early returns when nothing's live). Throughput
367 // path stays io_uring-native — only replica metadata uses
368 // polling. See `Shard::run_uring`.
369
370 let mut handles = Vec::with_capacity(n);
371 for shard in shards {
372 let stop = stop.clone();
373 let id = shard.id;
374 handles.push(std::thread::spawn(move || {
375 #[cfg(target_os = "linux")]
376 let res = if use_uring { shard.run_uring(stop) } else { shard.run(stop) };
377 #[cfg(not(target_os = "linux"))]
378 let res = shard.run(stop);
379 if let Err(e) = res {
380 eprintln!("kevy: shard {id} exited with error: {e}");
381 }
382 }));
383 }
384 for h in handles {
385 let _ = h.join();
386 }
387 Ok(())
388 }
389}