Skip to main content

khive_runtime/
daemon.rs

1//! khived daemon server — persistent warm runtime over a Unix socket.
2//!
3//! The daemon binds `~/.khive/khived.sock`, accepts length-prefixed request
4//! frames, dispatches them through a [`DaemonDispatch`] implementor, and serves
5//! results back. It is transport-agnostic: the MCP crate provides the dispatch
6//! impl, but any future client (CLI, HTTP gateway) can reuse this server.
7//!
8//! The client side (forwarding, auto-spawn) lives in the transport crate
9//! (e.g. `khive-mcp`), not here.
10
11use std::sync::Arc;
12
13mod boot_guard;
14mod connection;
15mod dispatch_trait;
16mod locks;
17mod process_files;
18mod run_daemon;
19
20pub use dispatch_trait::*;
21
22#[cfg(all(unix, feature = "fault-injection"))]
23pub use connection::handle_conn_for_test;
24#[cfg(unix)]
25use connection::*;
26
27#[cfg(unix)]
28pub use run_daemon::*;
29
30#[cfg(unix)]
31pub use boot_guard::*;
32
33#[cfg(all(test, unix))]
34use locks::open_lock_file;
35#[cfg(unix)]
36pub use locks::{
37    acquire_daemon_boot_guard, acquire_recovery_lock, open_mutating_daemon_lock,
38    try_acquire_daemon_boot_guard_until, try_acquire_recoverer_lock_until, DaemonBootGuard,
39};
40#[cfg(unix)]
41pub(crate) use locks::{peer_uid, uid_is_permitted};
42#[cfg(unix)]
43use locks::{socket_identity, SocketIdentity};
44pub use process_files::*;
45
46mod store_guard;
47mod store_identity;
48#[cfg(unix)]
49use store_guard::ensure_claimed_parent_identity;
50#[cfg(unix)]
51pub use store_guard::{acquire_daemon_store_guards, bind_daemon_store_files, claim_stores};
52pub use store_guard::{assert_daemon_store_identities, DaemonStoreGuard};
53#[cfg(unix)]
54pub use store_identity::claimed_daemon_store_identity;
55mod supervisor_marker;
56#[cfg(unix)]
57pub use supervisor_marker::supervisor_marker_path;
58
59#[cfg(unix)]
60use std::io::Write as _;
61#[cfg(unix)]
62use std::os::unix::fs::{MetadataExt, PermissionsExt};
63#[cfg(unix)]
64use std::os::unix::io::AsRawFd;
65#[cfg(all(test, unix))]
66use std::path::PathBuf;
67
68#[cfg(unix)]
69use async_trait::async_trait;
70#[cfg(unix)]
71use libc;
72#[cfg(unix)]
73use serde::Deserialize;
74#[cfg(unix)]
75use tokio::io::AsyncReadExt;
76#[cfg(all(test, unix))]
77use tokio::io::AsyncWriteExt;
78#[cfg(unix)]
79use tokio::net::{UnixListener, UnixStream};
80
81#[cfg(unix)]
82use crate::pack::RequestIdentity;
83#[cfg(unix)]
84use khive_db::{run_checkpoint_task, CheckpointConfig, CheckpointLifecycleOwner, ConnectionPool};
85
86// Unix-only: gated inside the file, because the error-constructor census
87// admits only attribute-free submodule declarations.
88mod exit_record;
89mod lifecycle;
90#[cfg(unix)]
91use lifecycle::khive_dir;
92#[cfg(test)]
93use lifecycle::khive_root_from;
94#[cfg(unix)]
95use lifecycle::{
96    current_supervisor_claim, default_socket_path, ensure_rendezvous_overrides_paired,
97    read_supervisor_marker_claim, DaemonLifecycle, PID_PATH_ENV, SOCKET_PATH_ENV,
98};
99pub use lifecycle::{
100    lock_path, volume_lock_dir, DaemonLifecyclePhase, DaemonLifecycleSnapshot, DaemonLifetime,
101    DaemonOptions, DaemonShutdownReason, DaemonStartupReport, DEFAULT_DEMAND_IDLE_SECS,
102};
103#[cfg(unix)]
104pub use lifecycle::{
105    pid_path, recoverer_lock_path, rendezvous_split, socket_path, RendezvousSplit,
106    SUPERVISOR_CLAIM_ENV,
107};
108
109mod load_limits;
110#[cfg(unix)]
111use load_limits::{admit_or_refuse_busy, ConnectionAdmission};
112pub use load_limits::{
113    recall_ledger_snapshot, track_recall_ledger_task, ConnectionCapSnapshot, RecallLedgerSnapshot,
114};
115
116/// Maximum frame size accepted in either direction.
117pub const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
118
119/// Wire protocol version for the daemon IPC framing.
120///
121/// Increment this constant whenever the request or response frame shape
122/// changes in a backward-incompatible way. The client sends its version
123/// in every request; the daemon rejects mismatches with an explicit error
124/// that names both sides so the operator knows exactly what to do
125/// (`make local` rebuilds the client binary).
126/// See `docs/api/daemon.md#protocol_version` for the version-by-version history.
127pub const PROTOCOL_VERSION: u32 = 8;
128
129/// Internal signal carried in a dispatch result until the daemon moves it to
130/// response-frame metadata. It must never be sent in `result`: older v8
131/// clients publish that string without inspecting its contents.
132#[doc(hidden)]
133pub const DAEMON_LEXICAL_TIMEOUT_MARKER: &str = "__khive_daemon_lexical_timeout";
134
135const DEFAULT_DRAIN_TIMEOUT_SECS: u64 = 10;
136/// An accepted local socket must finish its first frame within this window.
137/// Dispatch deadlines start only after decoding, so they cannot reap peers
138/// that connect and then stop sending request bytes.
139#[cfg(unix)]
140const INITIAL_FRAME_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
141
142#[cfg(unix)]
143fn next_accept_error_backoff(previous: Option<std::time::Duration>) -> std::time::Duration {
144    previous
145        .map(|delay| delay.saturating_mul(2))
146        .unwrap_or_else(|| std::time::Duration::from_millis(10))
147        .min(std::time::Duration::from_secs(1))
148}
149
150// ── wire types ────────────────────────────────────────────────────────────────
151
152mod config_id;
153#[cfg(test)]
154use config_id::parse_config_id;
155pub use config_id::{
156    config_id_extra_embedder_exclusions, config_ids_compatible, first_config_mismatch_field,
157    no_receipt_ring_fingerprint, visibility_receipt_policy_fingerprint,
158};
159
160mod wire_frames;
161pub use wire_frames::{
162    drop_error_detail_iteratively, error_detail_value_within_limit, CheckpointStoreMetrics,
163    DaemonDispatchError, DaemonRequestFrame, DaemonResponseFrame, MetricsSnapshot,
164    ERROR_DETAIL_NESTING_DEPTH_LIMIT,
165};
166#[cfg(unix)]
167pub use wire_frames::{read_frame, write_frame};
168#[cfg(unix)]
169use wire_frames::{read_initial_frame, take_daemon_lexical_timeout_marker};
170
171/// Returns `true` for non-empty env values that are not `"0"` or `"false"`.
172#[cfg(unix)]
173pub fn env_truthy(key: &str) -> bool {
174    std::env::var(key)
175        .map(|v| {
176            let v = v.trim();
177            !v.is_empty() && v != "0" && !v.eq_ignore_ascii_case("false")
178        })
179        .unwrap_or(false)
180}
181
182include!("daemon_khive_root_tests.rs");
183
184/// Serve one already-admitted test connection through the production frame handler.
185///
186/// This seam owns no socket path, PID, boot guard, background components, or
187/// process-wide shutdown state. The caller owns and joins the connection task.
188/// It deliberately does not exercise listener admission or daemon lifecycle.
189#[cfg(all(unix, any(test, feature = "test-internals")))]
190#[doc(hidden)]
191pub async fn serve_connection_for_test<D: DaemonDispatch>(stream: UnixStream, dispatcher: D) {
192    handle_conn_with_shutdown(
193        stream,
194        dispatcher,
195        None,
196        tokio::time::Instant::now() + INITIAL_FRAME_READ_TIMEOUT,
197    )
198    .await;
199}
200
201#[cfg(all(test, unix))]
202#[path = "daemon_tests.rs"]
203mod tests;