1use 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#[allow(clippy::large_enum_variant)]
90#[non_exhaustive]
91#[derive(Debug, Clone, PartialEq)]
92pub enum ConfigAvailability {
93 NoApprovedConfig,
94 LastView(ConfigView),
95}
96
97#[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 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_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 pub fn refresh_project_config(&self, project_id: impl Into<String>) -> bool {
192 let session = &self.shared.config;
193 if session.declaration.get().is_none()
194 || self.is_closed()
195 || !self.daemon_supports(CONFIG_GATE_CAPABILITY)
196 {
197 return false;
198 }
199 session.enqueue_refresh(Some(project_id.into()));
200 true
201 }
202}
203
204pub(crate) fn start<H: ModuleHandler>(
205 handle: ModuleHandle,
206 handler: Arc<H>,
207 dispatcher: &RequestDispatcher,
208) {
209 let Some(declaration) = handle.shared.config.declaration.get().cloned() else {
210 return;
211 };
212 let session_handle = handle.clone();
213 dispatcher.spawn(async move {
214 tokio::select! {
215 () = session_handle.shared.config.stop.cancelled() => {},
216 () = run(handle, handler, declaration) => {},
217 }
218 });
219}
220
221async fn run<H: ModuleHandler>(
222 handle: ModuleHandle,
223 handler: Arc<H>,
224 declaration: ConfigDeclareRequest,
225) {
226 if !handle.daemon_supports(CONFIG_GATE_CAPABILITY) {
227 handler.config_files().await;
228 return;
229 }
230 let mut deliveries = BTreeMap::new();
231 let delivery = deliveries.entry(None).or_insert_with(Delivery::default);
232 match call(&handle, &declaration, CONFIG_DECLARE_OP).await {
235 Ok(_) => delivery.refresh(&handle, &*handler, None).await,
236 Err(error) => delivery.error(&*handler, None, error).await,
237 }
238 loop {
239 handle.shared.config.changed.notified().await;
240 let projects = std::mem::take(
241 &mut *handle
242 .shared
243 .config
244 .projects
245 .lock()
246 .unwrap_or_else(|p| p.into_inner()),
247 );
248 for project in projects {
249 deliveries
250 .entry(project.clone())
251 .or_insert_with(Delivery::default)
252 .refresh(&handle, &*handler, project)
253 .await;
254 }
255 }
256}
257
258pub(crate) fn changed(frame: &Frame, handle: &ModuleHandle) -> bool {
259 if !is_op(frame, CONFIG_CHANGED_OP) {
260 return false;
261 }
262 if handle.shared.config.declaration.get().is_some()
263 && handle.daemon_supports(CONFIG_GATE_CAPABILITY)
264 {
265 match serde_json::from_slice::<ConfigChanged>(&frame.body) {
266 Ok(hint) => handle.shared.config.enqueue_refresh(hint.project_id),
267 Err(error) => tracing::warn!(%error, "ignoring malformed config.changed"),
268 }
269 }
270 true
271}
272
273fn is_op(frame: &Frame, op: &str) -> bool {
274 serde_json::from_slice::<serde_json::Value>(&frame.body)
275 .ok()
276 .and_then(|value| {
277 value
278 .get("op")
279 .and_then(|value| value.as_str())
280 .map(|value| value == op)
281 })
282 == Some(true)
283}
284
285pub(crate) fn review<H: ModuleHandler>(
286 frame: &Frame,
287 egress: &tokio::sync::mpsc::Sender<Frame>,
288 handler: Arc<H>,
289 dispatcher: &RequestDispatcher,
290 handle: &ModuleHandle,
291) -> bool {
292 if !is_op(frame, CONFIG_REVIEW_OP) {
293 return false;
294 }
295 let frame = frame.clone();
296 let egress = egress.clone();
297 let opted_in = handle.shared.config.declaration.get().is_some()
298 && handle.daemon_supports(CONFIG_GATE_CAPABILITY);
299 let failure = dispatcher.clone();
300 dispatcher.spawn(async move {
301 let result = async {
302 let (ty, body) = if !opted_in {
303 (
304 FrameType::Error,
305 serde_json::to_vec(&ErrorBody::new(
306 "unsupported_op",
307 "module did not opt in to config.review",
308 )),
309 )
310 } else {
311 match serde_json::from_slice::<ConfigReviewRequest>(&frame.body) {
312 Ok(request) => (
313 FrameType::Response,
314 serde_json::to_vec(&handler.config_review(request).await),
315 ),
316 Err(_) => (
317 FrameType::Error,
318 serde_json::to_vec(&ErrorBody::new(
319 "invalid_request",
320 "invalid config.review snapshots",
321 )),
322 ),
323 }
324 };
325 let reply = Frame::build_with_version(
326 frame.header.ver,
327 ty,
328 crate::control_flags(),
329 0,
330 0,
331 frame.header.corr,
332 body.map_err(crate::SubcModuleError::Json)?,
333 )
334 .map_err(crate::SubcModuleError::FrameBuild)?;
335 crate::send_outbound(&egress, reply).await
336 }
337 .await;
338 if let Err(error) = result {
339 failure.fail(error);
340 }
341 });
342 true
343}
344
345#[derive(Default)]
346struct Delivery {
347 view: Option<ConfigView>,
348 report: Option<ConfigAppliedRequest>,
349}
350impl Delivery {
351 fn available(&self) -> ConfigAvailability {
352 self.view
353 .clone()
354 .map(ConfigAvailability::LastView)
355 .unwrap_or(ConfigAvailability::NoApprovedConfig)
356 }
357
358 async fn error<H: ModuleHandler>(
359 &self,
360 handler: &H,
361 project: Option<&str>,
362 error: ConfigError,
363 ) {
364 let state = match error {
365 ConfigError::Refused(refusal) if refusal.code == "config_gated" => {
366 ConfigState::ConfigGated {
367 view: self.available(),
368 refusal,
369 }
370 }
371 ConfigError::Refused(refusal) if refusal.code == "not_delivery_target" => {
372 ConfigState::NotDeliveryTarget {
373 view: self.available(),
374 refusal,
375 }
376 }
377 ConfigError::Refused(refusal) if refusal.code == "anchor_pending" => {
378 ConfigState::AnchorPending {
379 view: self.available(),
380 refusal,
381 }
382 }
383 error => {
384 match project {
385 Some(project) => {
386 handler
387 .on_project_config_error(project.to_owned(), error)
388 .await
389 }
390 None => handler.on_config_error(error).await,
391 }
392 return;
393 }
394 };
395 handler.on_config_state(state).await;
396 }
397
398 async fn report<H: ModuleHandler>(
399 &mut self,
400 handle: &ModuleHandle,
401 handler: &H,
402 project: Option<&str>,
403 ) -> bool {
404 let Some(report) = self.report.as_ref() else {
405 return true;
406 };
407 match call(handle, report, CONFIG_APPLIED_OP).await {
408 Ok(_) => {
409 if report.result.is_ack() {
410 if let Some(view) = self.view.as_mut() {
411 view.status = ConfigStatus::Active;
412 handler
413 .on_config_state(ConfigState::Active(view.clone()))
414 .await;
415 }
416 }
417 self.report = None;
418 true
419 }
420 Err(error) => {
421 if !matches!(&error, ConfigError::Refused(body) if body.code == "anchor_pending") {
426 self.report = None;
427 }
428 self.error(handler, project, error).await;
429 false
430 }
431 }
432 }
433
434 async fn refresh<H: ModuleHandler>(
435 &mut self,
436 handle: &ModuleHandle,
437 handler: &H,
438 project: Option<String>,
439 ) {
440 let project_id = project.as_deref();
441 if !self.report(handle, handler, project_id).await {
442 return;
443 }
444 let mut request = ConfigGetRequest::new();
445 request.project_id = project.clone();
446 let reply = match call(handle, &request, CONFIG_GET_OP)
447 .await
448 .and_then(decode::<ConfigGetReply>)
449 {
450 Ok(reply) => reply,
451 Err(error) => {
452 self.error(handler, project_id, error).await;
453 return;
454 }
455 };
456 let Some(mut view) = reply.pending.clone().or(reply.active.clone()) else {
457 self.error(
458 handler,
459 project_id,
460 ConfigError::Protocol("config.get returned no view".into()),
461 )
462 .await;
463 return;
464 };
465 view.declaration_pending = reply.declaration_pending.clone();
466 if view.project_id != project
467 || reply
468 .active
469 .as_ref()
470 .is_some_and(|active| active.project_id != project)
471 {
472 self.error(
473 handler,
474 project_id,
475 ConfigError::Protocol("config.get returned another project".into()),
476 )
477 .await;
478 return;
479 }
480 let recovery = reply
484 .active
485 .filter(|_| self.view.is_none() && reply.pending.is_some());
486 if recovery.as_ref().is_some_and(|active| {
487 active.status != ConfigStatus::Active
488 || active
489 .layers
490 .iter()
491 .any(|layer| layer.layer.known_layer().is_none())
492 }) {
493 self.error(
494 handler,
495 project_id,
496 ConfigError::Protocol("invalid recovery view".into()),
497 )
498 .await;
499 return;
500 }
501 if !matches!(
502 view.status,
503 ConfigStatus::Active | ConfigStatus::Pending | ConfigStatus::Unstamped
504 ) || view
505 .layers
506 .iter()
507 .any(|layer| layer.layer.known_layer().is_none())
508 {
509 self.error(
510 handler,
511 project_id,
512 ConfigError::Protocol("config.get returned an unknown status or layer".into()),
513 )
514 .await;
515 return;
516 }
517 let attempt = if reply.pending.is_some()
518 || (reply.declaration_pending.is_some() && view.attempt.is_some())
519 {
520 match view.attempt {
521 Some(attempt) => Some(attempt),
522 None => {
523 self.error(
524 handler,
525 project_id,
526 ConfigError::Protocol("pending view has no delivery attempt".into()),
527 )
528 .await;
529 return;
530 }
531 }
532 } else {
533 None
534 };
535 match handler.config_apply(view.clone()).await {
536 Ok(()) => {
537 self.view = Some(view.clone());
538 handler
539 .on_config_state(match view.status {
540 ConfigStatus::Unstamped => ConfigState::Unstamped(view.clone()),
541 ConfigStatus::Pending => ConfigState::Pending(view.clone()),
542 _ => ConfigState::Active(view.clone()),
543 })
544 .await;
545 if let Some(attempt) = attempt {
546 let mut report = ConfigAppliedRequest::new(
547 view.generation,
548 attempt,
549 ConfigApplyResult::Ack,
550 vec![],
551 );
552 report.project_id = view.project_id.clone();
553 self.report = Some(report);
554 }
555 }
556 Err(reasons) => {
557 let mut failure_reasons = reasons.clone();
558 if let Some(active) = recovery {
559 match handler.config_apply(active.clone()).await {
560 Ok(()) => {
561 self.view = Some(active.clone());
562 handler.on_config_state(ConfigState::Active(active)).await;
563 }
564 Err(recovery_reasons) => failure_reasons = recovery_reasons,
565 }
566 }
567 handler
568 .on_config_state(ConfigState::Failed {
569 view: self.available(),
570 reasons: failure_reasons,
571 })
572 .await;
573 if let Some(attempt) = attempt {
574 let mut report = ConfigAppliedRequest::new(
575 view.generation,
576 attempt,
577 ConfigApplyResult::Nack,
578 reasons,
579 );
580 report.project_id = view.project_id.clone();
581 self.report = Some(report);
582 }
583 }
584 }
585 self.report(handle, handler, project_id).await;
586 }
587}
588
589fn decode<T: DeserializeOwned>(body: serde_json::Value) -> Result<T, ConfigError> {
590 serde_json::from_value(body).map_err(|error| ConfigError::Protocol(error.to_string()))
591}
592
593async fn call(
594 handle: &ModuleHandle,
595 request: &impl Serialize,
596 op: &str,
597) -> Result<serde_json::Value, ConfigError> {
598 let body =
599 serde_json::to_vec(request).map_err(|error| ConfigError::Protocol(error.to_string()))?;
600 let (corr, writer, rx) = {
601 let mut inner = handle.shared.lock_inner();
602 let writer = inner.writer.clone().ok_or(ConfigError::ConnectionClosed)?;
603 let corr =
604 crate::next_module_control_corr(&mut inner).ok_or(ConfigError::ConnectionClosed)?;
605 let (tx, rx) = oneshot::channel();
606 inner.pending_config_calls.insert(corr, tx);
607 (corr, writer, rx)
608 };
609 let _guard = Waiter {
610 handle: handle.clone(),
611 corr,
612 };
613 let frame = Frame::build_with_version(
614 handle.shared.negotiated_ver,
615 FrameType::Request,
616 crate::control_flags(),
617 0,
618 0,
619 corr,
620 body,
621 )
622 .map_err(|error| ConfigError::Protocol(error.to_string()))?;
623 let reply = tokio::time::timeout(CATALOG_UPDATE_TIMEOUT, async {
624 writer
625 .send(frame)
626 .await
627 .map_err(|_| ConfigError::ConnectionClosed)?;
628 rx.await.map_err(|_| ConfigError::ConnectionClosed)
629 })
630 .await
631 .map_err(|_| ConfigError::Timeout)??;
632 if reply.header.ty == FrameType::Error {
633 return Err(ConfigError::Refused(
634 serde_json::from_slice(&reply.body)
635 .map_err(|error| ConfigError::Protocol(error.to_string()))?,
636 ));
637 }
638 let body: serde_json::Value = serde_json::from_slice(&reply.body)
639 .map_err(|error| ConfigError::Protocol(error.to_string()))?;
640 if body.get("op").and_then(|op| op.as_str()) != Some(op) {
641 return Err(ConfigError::Protocol(format!("unexpected reply to {op}")));
642 }
643 Ok(body)
644}
645struct Waiter {
646 handle: ModuleHandle,
647 corr: u64,
648}
649impl Drop for Waiter {
650 fn drop(&mut self) {
651 self.handle
652 .shared
653 .lock_inner()
654 .pending_config_calls
655 .remove(&self.corr);
656 }
657}
658
659#[cfg(test)]
660mod tests;