Skip to main content

subc_client_rs/
config.rs

1//! Opt-in module configuration delivery. See [`ModuleHandler`] for lifecycle hooks.
2//!
3//! Only an absent `config.gate` capability permits the existing file reader.
4//! Refusals retain the last applied view; no approved view is represented without
5//! inventing empty configuration bytes. Anchor-pending reports retry on the next
6//! `config.changed` hint. Review and apply hooks never occupy the frame reader.
7//!
8//! # A small module adopting the gate
9//!
10//! The hooks below are the entire adoption; an existing `handle` is unchanged.
11//! The declaration's user path is provided by the module's startup configuration.
12//! The review function uses only supplied bytes and the supplied old view.
13//!
14//! ```no_run
15//! use async_trait::async_trait;
16//! use serde_json::json;
17//! use std::sync::Mutex;
18//! use subc_client_rs::{ModuleHandler, RequestCtx, HandlerOutcome, config::*};
19//!
20//! struct Counter { user_file: String, value: Mutex<serde_json::Value> }
21//! fn schema() -> serde_json::Value {
22//!     json!({"$schema":"https://json-schema.org/draft/2020-12/schema",
23//!       "type":"object","unevaluatedProperties":false,"properties":{"count":{"type":"integer",
24//!       "description":"Counter value","default":0,"x-ck-apply":"live",
25//!       "x-ck-layers":["user"]}}})
26//! }
27//! fn review(request: ConfigReviewRequest) -> Result<ConfigReviewReply, String> {
28//!     let schema = Schema::new(schema()).map_err(|e| format!("{e:?}"))?;
29//!     let layers = request.layers.iter().filter_map(|l| l.bytes.as_ref().map(|b| (l,b)))
30//!         .map(|(l,b)| Ok(LayerValue::new(l.layer.known_layer().ok_or("unknown layer")?,
31//!             serde_json::from_slice(b).map_err(|_| "invalid JSON")?)))
32//!         .collect::<Result<Vec<_>, &str>>().map_err(str::to_owned)?;
33//!     let tuple = schema.review_tuple(&layers, &ValidationContext::new("counter", None))
34//!         .map_err(|_| "invalid counter configuration")?;
35//!     let old = request.base.as_ref().map(|v| v.effective.clone()).unwrap_or(json!({"count":null}));
36//!     let old_source = request.base.as_ref().and_then(|v| v.sources.get("/count")).copied().unwrap_or(Layer::Default);
37//!     if old["count"] == tuple.effective["count"] && old_source == tuple.sources["/count"] {
38//!         return Ok(ConfigReviewReply::new(vec![], vec![]));
39//!     }
40//!     let mut field = FieldChange::new("counter", "/count", RecordedValue::new(old["count"].clone()),
41//!         RecordedValue::new(tuple.effective["count"].clone()), ApplyKind::Live);
42//!     field.old_source = old_source;
43//!     field.new_source = tuple.sources["/count"];
44//!     Ok(ConfigReviewReply::new(vec![field], vec![]))
45//! }
46//! #[async_trait]
47//! impl ModuleHandler for Counter {
48//!     async fn handle(&self, _: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
49//!         HandlerOutcome::Response(body)
50//!     }
51//!     fn config_declaration(&self) -> Option<ConfigDeclareRequest> {
52//!         Some(ConfigDeclareRequest::new(schema(), &self.user_file, vec![]))
53//!     }
54//!     async fn config_review(&self, request: ConfigReviewRequest) -> ConfigReviewReply {
55//!         review(request).unwrap_or_else(|reason| ConfigReviewReply::new(vec![],
56//!             vec![ConfigReviewRefusal::new("value_invalid", vec!["/count".into()], vec![reason])]))
57//!     }
58//!     async fn config_apply(&self, view: ConfigView) -> Result<(), Vec<String>> {
59//!         *self.value.lock().unwrap() = view.effective; Ok(())
60//!     }
61//!     async fn config_files(&self) {
62//!         // This path is used only with an older daemon, never on a refusal.
63//!         if let Ok(bytes) = std::fs::read(&self.user_file) {
64//!             if let Ok(value) = serde_json::from_slice(&bytes) { *self.value.lock().unwrap() = value; }
65//!         }
66//!     }
67//!     async fn on_config_state(&self, state: ConfigState) { eprintln!("{}", state.as_str()); }
68//! }
69//! # let _ = Counter { user_file: "counter.json".into(), value: Mutex::new(json!({"count":0})) };
70//! ```
71
72use std::{
73    collections::{BTreeMap, BTreeSet},
74    error::Error,
75    fmt,
76    sync::{Arc, OnceLock},
77};
78
79use serde::{de::DeserializeOwned, Serialize};
80use subc_protocol::{ErrorBody, Frame, FrameType};
81use tokio::sync::{oneshot, Notify};
82
83use crate::{ModuleHandle, ModuleHandler, RequestDispatcher, CATALOG_UPDATE_TIMEOUT};
84pub use subc_config::{ApplyKind, LayerValue, RecordedValue, Schema, ValidationContext};
85pub use subc_protocol::config::*;
86
87/// The bytes available after a refusal. Absence is not permission to read files.
88// The view is held inline: boxing it would change this published variant's type.
89#[allow(clippy::large_enum_variant)]
90#[non_exhaustive]
91#[derive(Debug, Clone, PartialEq)]
92pub enum ConfigAvailability {
93    NoApprovedConfig,
94    LastView(ConfigView),
95}
96
97/// Wire status or refusal, with the module's retained view where applicable.
98/// `ConfigGated` with `NoApprovedConfig` carries the original refusal but no bytes.
99#[non_exhaustive]
100#[derive(Debug, Clone)]
101pub enum ConfigState {
102    Unstamped(ConfigView),
103    Pending(ConfigView),
104    Active(ConfigView),
105    Failed {
106        view: ConfigAvailability,
107        reasons: Vec<String>,
108    },
109    ConfigGated {
110        view: ConfigAvailability,
111        refusal: ErrorBody,
112    },
113    NotDeliveryTarget {
114        view: ConfigAvailability,
115        refusal: ErrorBody,
116    },
117    AnchorPending {
118        view: ConfigAvailability,
119        refusal: ErrorBody,
120    },
121}
122
123impl ConfigState {
124    /// The daemon's status or refusal spelling, without configuration values.
125    pub fn as_str(&self) -> &'static str {
126        match self {
127            Self::Unstamped(_) => "unstamped",
128            Self::Pending(_) => "pending",
129            Self::Active(_) => "active",
130            Self::Failed { .. } => "failed",
131            Self::ConfigGated { .. } => "config_gated",
132            Self::NotDeliveryTarget { .. } => "not_delivery_target",
133            Self::AnchorPending { .. } => "anchor_pending",
134        }
135    }
136}
137
138/// Non-status errors never authorize a fallback. Refusals preserve extension data.
139#[non_exhaustive]
140#[derive(Debug)]
141pub enum ConfigError {
142    Refused(ErrorBody),
143    Protocol(String),
144    Timeout,
145    ConnectionClosed,
146}
147impl fmt::Display for ConfigError {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        match self {
150            Self::Refused(body) => write!(f, "{}: {}", body.code, body.message),
151            Self::Protocol(message) => f.write_str(message),
152            Self::Timeout => f.write_str("config request timed out"),
153            Self::ConnectionClosed => f.write_str("config connection closed"),
154        }
155    }
156}
157impl Error for ConfigError {}
158
159#[derive(Default)]
160pub(crate) struct Session {
161    pub(crate) declaration: OnceLock<ConfigDeclareRequest>,
162    changed: Notify,
163    projects: std::sync::Mutex<BTreeSet<Option<String>>>,
164    pub(crate) stop: tokio_util::sync::CancellationToken,
165}
166
167impl Session {
168    fn enqueue_refresh(&self, project_id: Option<String>) {
169        self.projects
170            .lock()
171            .unwrap_or_else(|p| p.into_inner())
172            .insert(project_id);
173        self.changed.notify_one();
174    }
175}
176
177impl ModuleHandle {
178    /// Queue a configuration refresh for a named project on this connection.
179    ///
180    /// Returns `false` if the module has no config declaration, the connection
181    /// is closed, or the daemon did not advertise `config.gate`. `true` means
182    /// queued, not fetched or applied. Queued refreshes for the same project
183    /// coalesce, including those triggered by `config.changed`.
184    ///
185    /// Errors arrive through [`ModuleHandler::on_project_config_error`]. The
186    /// `config_gated`, `not_delivery_target`, and `anchor_pending` refusals
187    /// instead go to [`ModuleHandler::on_config_state`].
188    ///
189    /// This does not check project support before sending `config.get`; use
190    /// [`Self::daemon_supports`] to check capabilities advertised in HELLO_ACK.
191    pub fn refresh_project_config(&self, project_id: impl Into<String>) -> bool {
192        self.enqueue_config_refresh(Some(project_id.into()))
193    }
194
195    /// Queue a refresh of the module's default config view. Returns `false`
196    /// if config is unavailable or the connection is fenced for a daemon upgrade.
197    pub fn refresh_config(&self) -> bool {
198        self.enqueue_config_refresh(None)
199    }
200
201    fn enqueue_config_refresh(&self, project_id: Option<String>) -> bool {
202        let shared = self.shared();
203        let session = &shared.config;
204        let state = shared.lock_inner();
205        if session.declaration.get().is_none()
206            || state.closed
207            || state.upgrade.fenced()
208            || !shared
209                .daemon_capabilities
210                .iter()
211                .any(|capability| capability == CONFIG_GATE_CAPABILITY)
212        {
213            return false;
214        }
215        session.enqueue_refresh(project_id);
216        true
217    }
218}
219
220pub(crate) fn start<H: ModuleHandler>(
221    handle: ModuleHandle,
222    handler: Arc<H>,
223    dispatcher: &RequestDispatcher,
224) {
225    let shared = handle.shared();
226    let Some(declaration) = shared.config.declaration.get().cloned() else {
227        return;
228    };
229    dispatcher.spawn(async move {
230        tokio::select! {
231            () = shared.config.stop.cancelled() => {},
232            () = run(handle, handler, declaration) => {},
233        }
234    });
235}
236
237async fn run<H: ModuleHandler>(
238    handle: ModuleHandle,
239    handler: Arc<H>,
240    declaration: ConfigDeclareRequest,
241) {
242    let shared = handle.shared();
243    if !handle.daemon_supports(CONFIG_GATE_CAPABILITY) {
244        handler.config_files().await;
245        return;
246    }
247    let mut deliveries = BTreeMap::new();
248    let delivery = deliveries.entry(None).or_insert_with(Delivery::default);
249    // A declaration refusal still consumes the one declaration on this
250    // connection. Future hints fetch again, never declare a second time.
251    match call(&handle, &declaration, CONFIG_DECLARE_OP).await {
252        Ok(_) => delivery.refresh(&handle, &*handler, None).await,
253        Err(error) => delivery.error(&*handler, None, error).await,
254    }
255    loop {
256        shared.config.changed.notified().await;
257        let projects = std::mem::take(
258            &mut *shared
259                .config
260                .projects
261                .lock()
262                .unwrap_or_else(|p| p.into_inner()),
263        );
264        for project in projects {
265            deliveries
266                .entry(project.clone())
267                .or_insert_with(Delivery::default)
268                .refresh(&handle, &*handler, project)
269                .await;
270        }
271    }
272}
273
274pub(crate) fn changed(frame: &Frame, handle: &ModuleHandle) -> bool {
275    if !is_op(frame, CONFIG_CHANGED_OP) {
276        return false;
277    }
278    let shared = handle.shared();
279    if shared.config.declaration.get().is_some()
280        && !shared.lock_inner().upgrade.fenced()
281        && handle.daemon_supports(CONFIG_GATE_CAPABILITY)
282    {
283        match serde_json::from_slice::<ConfigChanged>(&frame.body) {
284            Ok(hint) => shared.config.enqueue_refresh(hint.project_id),
285            Err(error) => tracing::warn!(%error, "ignoring malformed config.changed"),
286        }
287    }
288    true
289}
290
291fn is_op(frame: &Frame, op: &str) -> bool {
292    serde_json::from_slice::<serde_json::Value>(&frame.body)
293        .ok()
294        .and_then(|value| {
295            value
296                .get("op")
297                .and_then(|value| value.as_str())
298                .map(|value| value == op)
299        })
300        == Some(true)
301}
302
303pub(crate) fn review<H: ModuleHandler>(
304    frame: &Frame,
305    egress: &tokio::sync::mpsc::Sender<Frame>,
306    handler: Arc<H>,
307    dispatcher: &RequestDispatcher,
308    handle: &ModuleHandle,
309) -> bool {
310    if !is_op(frame, CONFIG_REVIEW_OP) {
311        return false;
312    }
313    let frame = frame.clone();
314    let egress = egress.clone();
315    let opted_in = handle.shared().config.declaration.get().is_some()
316        && handle.daemon_supports(CONFIG_GATE_CAPABILITY);
317    let failure = dispatcher.clone();
318    dispatcher.spawn(async move {
319        let result = async {
320            let (ty, body) = if !opted_in {
321                (
322                    FrameType::Error,
323                    serde_json::to_vec(&ErrorBody::new(
324                        "unsupported_op",
325                        "module did not opt in to config.review",
326                    )),
327                )
328            } else {
329                match serde_json::from_slice::<ConfigReviewRequest>(&frame.body) {
330                    Ok(request) => (
331                        FrameType::Response,
332                        serde_json::to_vec(&handler.config_review(request).await),
333                    ),
334                    Err(_) => (
335                        FrameType::Error,
336                        serde_json::to_vec(&ErrorBody::new(
337                            "invalid_request",
338                            "invalid config.review snapshots",
339                        )),
340                    ),
341                }
342            };
343            let reply = Frame::build_with_version(
344                frame.header.ver,
345                ty,
346                crate::control_flags(),
347                0,
348                0,
349                frame.header.corr,
350                body.map_err(crate::SubcModuleError::Json)?,
351            )
352            .map_err(crate::SubcModuleError::FrameBuild)?;
353            crate::send_outbound(&egress, reply).await
354        }
355        .await;
356        if let Err(error) = result {
357            failure.fail(error);
358        }
359    });
360    true
361}
362
363#[derive(Default)]
364struct Delivery {
365    view: Option<ConfigView>,
366    report: Option<ConfigAppliedRequest>,
367}
368impl Delivery {
369    fn available(&self) -> ConfigAvailability {
370        self.view
371            .clone()
372            .map(ConfigAvailability::LastView)
373            .unwrap_or(ConfigAvailability::NoApprovedConfig)
374    }
375
376    async fn error<H: ModuleHandler>(
377        &self,
378        handler: &H,
379        project: Option<&str>,
380        error: ConfigError,
381    ) {
382        let state = match error {
383            ConfigError::Refused(refusal) if refusal.code == "config_gated" => {
384                ConfigState::ConfigGated {
385                    view: self.available(),
386                    refusal,
387                }
388            }
389            ConfigError::Refused(refusal) if refusal.code == "not_delivery_target" => {
390                ConfigState::NotDeliveryTarget {
391                    view: self.available(),
392                    refusal,
393                }
394            }
395            ConfigError::Refused(refusal) if refusal.code == "anchor_pending" => {
396                ConfigState::AnchorPending {
397                    view: self.available(),
398                    refusal,
399                }
400            }
401            error => {
402                match project {
403                    Some(project) => {
404                        handler
405                            .on_project_config_error(project.to_owned(), error)
406                            .await
407                    }
408                    None => handler.on_config_error(error).await,
409                }
410                return;
411            }
412        };
413        handler.on_config_state(state).await;
414    }
415
416    async fn report<H: ModuleHandler>(
417        &mut self,
418        handle: &ModuleHandle,
419        handler: &H,
420        project: Option<&str>,
421    ) -> bool {
422        let Some(report) = self.report.as_ref() else {
423            return true;
424        };
425        match call(handle, report, CONFIG_APPLIED_OP).await {
426            Ok(_) => {
427                if report.result.is_ack() {
428                    if let Some(view) = self.view.as_mut() {
429                        view.status = ConfigStatus::Active;
430                        handler
431                            .on_config_state(ConfigState::Active(view.clone()))
432                            .await;
433                    }
434                }
435                self.report = None;
436                true
437            }
438            Err(error) => {
439                // Only anchor_pending explicitly permits replaying the report.
440                // During a module swap, a not-yet-promoted or replaced connection
441                // is not the delivery target. It must wait for config.changed to
442                // announce promotion, then fetch the newly assigned attempt.
443                if !matches!(&error, ConfigError::Refused(body) if body.code == "anchor_pending") {
444                    self.report = None;
445                }
446                self.error(handler, project, error).await;
447                false
448            }
449        }
450    }
451
452    async fn refresh<H: ModuleHandler>(
453        &mut self,
454        handle: &ModuleHandle,
455        handler: &H,
456        project: Option<String>,
457    ) {
458        let project_id = project.as_deref();
459        if !self.report(handle, handler, project_id).await {
460            return;
461        }
462        let mut request = ConfigGetRequest::new();
463        request.project_id = project.clone();
464        let reply = match call(handle, &request, CONFIG_GET_OP)
465            .await
466            .and_then(decode::<ConfigGetReply>)
467        {
468            Ok(reply) => reply,
469            Err(error) => {
470                self.error(handler, project_id, error).await;
471                return;
472            }
473        };
474        let Some(mut view) = reply.pending.clone().or(reply.active.clone()) else {
475            self.error(
476                handler,
477                project_id,
478                ConfigError::Protocol("config.get returned no view".into()),
479            )
480            .await;
481            return;
482        };
483        view.declaration_pending = reply.declaration_pending.clone();
484        if view.project_id != project
485            || reply
486                .active
487                .as_ref()
488                .is_some_and(|active| active.project_id != project)
489        {
490            self.error(
491                handler,
492                project_id,
493                ConfigError::Protocol("config.get returned another project".into()),
494            )
495            .await;
496            return;
497        }
498        // A module that boots on its first apply must boot once, on the view it
499        // will keep. Try pending first, but keep active for recovery so a refused
500        // delivery does not leave a fresh process without settings.
501        let recovery = reply
502            .active
503            .filter(|_| self.view.is_none() && reply.pending.is_some());
504        if recovery.as_ref().is_some_and(|active| {
505            active.status != ConfigStatus::Active
506                || active
507                    .layers
508                    .iter()
509                    .any(|layer| layer.layer.known_layer().is_none())
510        }) {
511            self.error(
512                handler,
513                project_id,
514                ConfigError::Protocol("invalid recovery view".into()),
515            )
516            .await;
517            return;
518        }
519        if !matches!(
520            view.status,
521            ConfigStatus::Active | ConfigStatus::Pending | ConfigStatus::Unstamped
522        ) || view
523            .layers
524            .iter()
525            .any(|layer| layer.layer.known_layer().is_none())
526        {
527            self.error(
528                handler,
529                project_id,
530                ConfigError::Protocol("config.get returned an unknown status or layer".into()),
531            )
532            .await;
533            return;
534        }
535        let attempt = if reply.pending.is_some()
536            || (reply.declaration_pending.is_some() && view.attempt.is_some())
537        {
538            match view.attempt {
539                Some(attempt) => Some(attempt),
540                None => {
541                    self.error(
542                        handler,
543                        project_id,
544                        ConfigError::Protocol("pending view has no delivery attempt".into()),
545                    )
546                    .await;
547                    return;
548                }
549            }
550        } else {
551            None
552        };
553        match handler.config_apply(view.clone()).await {
554            Ok(()) => {
555                self.view = Some(view.clone());
556                handler
557                    .on_config_state(match view.status {
558                        ConfigStatus::Unstamped => ConfigState::Unstamped(view.clone()),
559                        ConfigStatus::Pending => ConfigState::Pending(view.clone()),
560                        _ => ConfigState::Active(view.clone()),
561                    })
562                    .await;
563                if let Some(attempt) = attempt {
564                    let mut report = ConfigAppliedRequest::new(
565                        view.generation,
566                        attempt,
567                        ConfigApplyResult::Ack,
568                        vec![],
569                    );
570                    report.project_id = view.project_id.clone();
571                    self.report = Some(report);
572                }
573            }
574            Err(reasons) => {
575                let mut failure_reasons = reasons.clone();
576                if let Some(active) = recovery {
577                    match handler.config_apply(active.clone()).await {
578                        Ok(()) => {
579                            self.view = Some(active.clone());
580                            handler.on_config_state(ConfigState::Active(active)).await;
581                        }
582                        Err(recovery_reasons) => failure_reasons = recovery_reasons,
583                    }
584                }
585                handler
586                    .on_config_state(ConfigState::Failed {
587                        view: self.available(),
588                        reasons: failure_reasons,
589                    })
590                    .await;
591                if let Some(attempt) = attempt {
592                    let mut report = ConfigAppliedRequest::new(
593                        view.generation,
594                        attempt,
595                        ConfigApplyResult::Nack,
596                        reasons,
597                    );
598                    report.project_id = view.project_id.clone();
599                    self.report = Some(report);
600                }
601            }
602        }
603        self.report(handle, handler, project_id).await;
604    }
605}
606
607fn decode<T: DeserializeOwned>(body: serde_json::Value) -> Result<T, ConfigError> {
608    serde_json::from_value(body).map_err(|error| ConfigError::Protocol(error.to_string()))
609}
610
611async fn call(
612    handle: &ModuleHandle,
613    request: &impl Serialize,
614    op: &str,
615) -> Result<serde_json::Value, ConfigError> {
616    let shared = handle.shared();
617    let body =
618        serde_json::to_vec(request).map_err(|error| ConfigError::Protocol(error.to_string()))?;
619    let (corr, writer, rx) = {
620        let mut inner = shared.lock_inner();
621        if inner.upgrade.fenced() {
622            return Err(ConfigError::Refused(crate::live_upgrade::upgrade_refusal()));
623        }
624        let writer = inner.writer.clone().ok_or(ConfigError::ConnectionClosed)?;
625        let corr =
626            crate::next_module_control_corr(&mut inner).ok_or(ConfigError::ConnectionClosed)?;
627        let (tx, rx) = oneshot::channel();
628        inner.pending_config_calls.insert(corr, tx);
629        (corr, writer, rx)
630    };
631    let _guard = Waiter {
632        shared: shared.clone(),
633        corr,
634    };
635    let frame = Frame::build_with_version(
636        shared.negotiated_ver,
637        FrameType::Request,
638        crate::control_flags(),
639        0,
640        0,
641        corr,
642        body,
643    )
644    .map_err(|error| ConfigError::Protocol(error.to_string()))?;
645    let reply = tokio::time::timeout(CATALOG_UPDATE_TIMEOUT, async {
646        shared
647            .queue_request(&writer, frame)
648            .await
649            .map_err(|err| match err {
650                crate::CatalogUpdateError::Rejected(body) => ConfigError::Refused(body),
651                _ => ConfigError::ConnectionClosed,
652            })?;
653        rx.await.map_err(|_| ConfigError::ConnectionClosed)
654    })
655    .await
656    .map_err(|_| ConfigError::Timeout)??;
657    if reply.header.ty == FrameType::Error {
658        return Err(ConfigError::Refused(
659            serde_json::from_slice(&reply.body)
660                .map_err(|error| ConfigError::Protocol(error.to_string()))?,
661        ));
662    }
663    let body: serde_json::Value = serde_json::from_slice(&reply.body)
664        .map_err(|error| ConfigError::Protocol(error.to_string()))?;
665    if body.get("op").and_then(|op| op.as_str()) != Some(op) {
666        return Err(ConfigError::Protocol(format!("unexpected reply to {op}")));
667    }
668    Ok(body)
669}
670struct Waiter {
671    shared: Arc<crate::ModuleHandleShared>,
672    corr: u64,
673}
674impl Drop for Waiter {
675    fn drop(&mut self) {
676        self.shared
677            .lock_inner()
678            .pending_config_calls
679            .remove(&self.corr);
680    }
681}
682
683#[cfg(test)]
684mod tests;