Skip to main content

subc_daemon/control/
config_gate.rs

1use subc_control::config::{ConfigControlRequest, ConfigControlResponse};
2
3use super::*;
4mod admission;
5mod daemon_readers;
6pub(super) use daemon_readers::preview_approved_daemon;
7mod delivery_worker;
8mod phone;
9mod recovery;
10mod route_policy;
11mod settings;
12mod widening;
13
14/// Settings reads and user-layer edit plans are served together.
15pub(super) const CONFIG_SETTINGS_SURFACE_ENABLED: bool = true;
16
17/// Bound each immutable module review so an unanswered request cannot approve a plan.
18const CONFIG_REVIEW_TIMEOUT: Duration = Duration::from_secs(30);
19
20/// After a phone answer, lock waits and freshness work have thirty seconds to
21/// reach durable publication. Publication already started returns its real result.
22const CONFIG_APPROVAL_COMMIT_TIMEOUT: Duration = Duration::from_secs(30);
23use crate::config_gate::{
24    ApprovalChallenge, ApprovalFacts, ApprovalReply, GateError, PlanKind, PresenceDecision,
25};
26
27pub(super) fn is_config_op(op: &str) -> bool {
28    matches!(
29        op,
30        "config.status"
31            | "config.modules"
32            | "config.schema"
33            | "config.show"
34            | "config.watch"
35            | "config.plan"
36            | "config.plan_get"
37            | "config.plan_discard"
38            | "config.apply"
39            | "config.stamp"
40            | "config.unstamp"
41            | "config.history"
42            | "config.rollback"
43            | "config.place_program"
44    )
45}
46
47pub(super) fn is_module_config_op(op: &str) -> bool {
48    matches!(op, "config.declare" | "config.get" | "config.applied")
49}
50
51impl PrivilegedRequest for ConfigControlRequest {
52    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
53        // The config gate binds trusted review and presence to its digest. The
54        // generic operator prompt would run twice, and its log/shortcut modes
55        // cannot substitute for config approval.
56        match self {
57            Self::Status {} => None,
58            Self::Plan { .. } => None,
59            Self::Apply { .. } => None,
60            Self::Stamp {} => None,
61            Self::Unstamp {} => None,
62            Self::History {} => None,
63            Self::Rollback { .. } => None,
64            Self::PlaceProgram { .. } => None,
65            _ => None,
66        }
67    }
68}
69
70impl ControlHandler {
71    #[cfg(feature = "test-support")]
72    pub(crate) fn with_config_os_prompt_policy_for_tests(self) -> Self {
73        if let Some(owner) = self.config_runtime.as_ref() {
74            owner.set_os_prompt_policy_for_tests();
75        }
76        self
77    }
78    fn config_delivery_target_current(
79        &self,
80        module: &str,
81        connection: ConnectionId,
82        active: bool,
83        correlation: u64,
84    ) -> Result<bool, RouterError> {
85        if active {
86            Ok(self
87                .registry
88                .get_module(module)
89                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))?
90                .is_some_and(|target| target.connection_id == connection)
91                && self
92                    .forwarding
93                    .active_module_endpoint(module)
94                    .map_err(RouterError::Forwarding)?
95                    .is_some_and(|target| target.connection_id == connection))
96        } else {
97            Ok(self
98                .registry
99                .get_candidate(module)
100                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))?
101                .is_some_and(|target| target.connection_id == connection))
102        }
103    }
104
105    pub(crate) fn defers_config_approval(&self, frame: &Frame) -> bool {
106        frame.header.channel == 0
107            && frame.header.ty == FrameType::Request
108            && matches!(
109                serde_json::from_slice::<ConfigControlRequest>(&frame.body),
110                Ok(ConfigControlRequest::Apply { .. })
111            )
112    }
113
114    pub(crate) fn reserve_config_approval(
115        &self,
116        ctx: &RouteCtx,
117        frame: &Frame,
118    ) -> std::result::Result<Option<crate::config_gate::runtime::ApprovalRequestGuard>, GateError>
119    {
120        if self.defers_config_approval(frame) {
121            if let Some(owner) = &self.config_runtime {
122                return owner
123                    .reserve_approval_request(ctx.connection_id, frame.header.corr)
124                    .map(Some);
125            }
126        }
127        Ok(None)
128    }
129
130    pub(super) fn cancel_config_approval(&self, caller: ConnectionId, correlation: u64) -> bool {
131        use crate::config_gate::runtime::CancelApprovalRequest;
132        let Some(owner) = &self.config_runtime else {
133            return false;
134        };
135        match owner.cancel_approval_request_outcome(caller, correlation) {
136            CancelApprovalRequest::Unknown => false,
137            CancelApprovalRequest::Withdrawn | CancelApprovalRequest::AlreadyReported => true,
138            CancelApprovalRequest::TooLate => {
139                if let Some(activity) = &self.activity {
140                    activity.config_cancel_too_late(caller, correlation);
141                }
142                true
143            }
144        }
145    }
146
147    pub(super) async fn handle_module_config_request(
148        &self,
149        ctx: &RouteCtx,
150        frame: Frame,
151        op: &str,
152    ) -> Result<Vec<Frame>, RouterError> {
153        let Some(runtime) = self.config_runtime.clone() else {
154            return Ok(vec![control_error_frame(
155                &frame,
156                "config_gate_inactive",
157                "no config store configured",
158            )?]);
159        };
160        let registration = self
161            .registry
162            .get_module_by_connection(ctx.connection_id)
163            .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
164        let Some(registration) = registration else {
165            return Ok(vec![control_error_frame(
166                &frame,
167                "not_registered",
168                "module config operations require a registered connection",
169            )?]);
170        };
171        let module = registration.manifest.module_id.clone();
172        let gate = runtime
173            .module_gate(&module)
174            .map_err(|e| RouterError::backend(0, frame.header.corr, e.to_string()))?;
175        let _gate = gate.lock().await;
176        let active = self
177            .registry
178            .get_module(&module)
179            .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?
180            .is_some_and(|r| r.connection_id == ctx.connection_id)
181            && self
182                .forwarding
183                .active_module_endpoint(&module)
184                .map_err(RouterError::Forwarding)?
185                .is_some_and(|target| target.connection_id == ctx.connection_id);
186        let candidate = self
187            .registry
188            .get_candidate(&module)
189            .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?
190            .is_some_and(|r| r.connection_id == ctx.connection_id);
191        if !active && !candidate {
192            return Ok(vec![control_error_frame(
193                &frame,
194                "not_delivery_target",
195                "connection is no longer the active or candidate delivery target",
196            )?]);
197        }
198        let body = frame.body.clone();
199        let connection = ctx.connection_id;
200        let mut delivered_view = None;
201        let result = match op {
202            "config.declare" => {
203                let declaration = serde_json::from_slice(&body).map_err(|_| {
204                    GateError::new("invalid_control_body", "malformed config.declare request")
205                });
206                match declaration {
207                    Ok(declaration) => {
208                        config_work(runtime.clone(), ConfigWake::None, move |owner| {
209                            owner.declare(connection, &module, declaration, active)?;
210                            Ok(serde_json::json!({"op":"config.declare"}))
211                        })
212                        .await
213                    }
214                    Err(error) => Err(error),
215                }
216            }
217            "config.get" => {
218                let request = serde_json::from_slice(&body).map_err(|_| {
219                    GateError::new("invalid_control_body", "malformed config.get request")
220                });
221                match request {
222                    Ok(request) => {
223                        let module_id = module.clone();
224                        match config_work(runtime.clone(), ConfigWake::None, move |owner| {
225                            owner.module_get_for_rpc(connection, &module_id, request)
226                        })
227                        .await
228                        {
229                            Ok(reply) => {
230                                let encoded = serde_json::to_value(&reply).map_err(|_| {
231                                    GateError::new(
232                                        "config_unavailable",
233                                        "could not encode config view",
234                                    )
235                                });
236                                delivered_view = Some(reply);
237                                encoded
238                            }
239                            Err(error) => Err(error),
240                        }
241                    }
242                    Err(error) => Err(error),
243                }
244            }
245            "config.applied" => {
246                match serde_json::from_slice::<subc_protocol::config::ConfigAppliedRequest>(&body) {
247                    Ok(request) => {
248                        config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
249                            owner.module_applied(connection, &module, request)?;
250                            Ok(serde_json::json!({"op":"config.applied"}))
251                        })
252                        .await
253                    }
254                    Err(_) => Err(GateError::new(
255                        "invalid_control_body",
256                        "malformed config.applied request",
257                    )),
258                }
259            }
260            _ => Err(GateError::new(
261                "invalid_control_body",
262                "unsupported module configuration operation",
263            )),
264        };
265        match result {
266            Ok(response) => {
267                let response =
268                    control_response_body_frame(&frame, &response, "module config response")?;
269                if let Some(view) = delivered_view {
270                    use crate::config_gate::runtime::delivery::CONFIG_LIVE_ACK_TIMEOUT;
271                    let project = view
272                        .pending
273                        .as_ref()
274                        .or(view.active.as_ref())
275                        .and_then(|view| view.project_id.clone());
276                    let selected = view
277                        .pending
278                        .as_ref()
279                        .or(view
280                            .active
281                            .as_ref()
282                            .filter(|_| view.declaration_pending.is_some()))
283                        .and_then(|view| view.attempt.map(|attempt| (view.generation, attempt)));
284                    let writing_project = project.clone();
285                    let window = runtime
286                        .on_blocking(move |owner| {
287                            if active {
288                                if let Some((generation, attempt)) = selected {
289                                    owner.delivery_write_started_for(
290                                        connection,
291                                        writing_project.as_deref(),
292                                        generation,
293                                        attempt,
294                                        tokio::time::Instant::now(),
295                                    )?;
296                                }
297                            }
298                            owner.delivery_window_for(connection, writing_project.as_deref())
299                        })
300                        .await
301                        .map_err(|error| {
302                            RouterError::backend(0, frame.header.corr, error.to_string())
303                        })?;
304                    let write_deadline = window
305                        .filter(|window| selected == Some((window.generation, window.attempt)))
306                        .and_then(|window| window.deadline)
307                        .map_or(
308                            tokio::time::Instant::now() + CONFIG_LIVE_ACK_TIMEOUT,
309                            |deadline| {
310                                deadline.min(tokio::time::Instant::now() + CONFIG_LIVE_ACK_TIMEOUT)
311                            },
312                        );
313                    drop(_gate);
314                    let flushed =
315                        tokio::time::timeout_at(write_deadline, ctx.egress.send_flushed(response))
316                            .await;
317                    let flushed_at = tokio::time::Instant::now();
318                    let _gate = gate.lock().await;
319                    let current_project = project.clone();
320                    let current_window = runtime
321                        .on_blocking(move |owner| {
322                            owner.delivery_window_for(connection, current_project.as_deref())
323                        })
324                        .await
325                        .ok()
326                        .flatten();
327                    // A slow writer may finish after cutover or supersession.
328                    // Its receipt must not advance the replacement's attempt.
329                    if !self.config_delivery_target_current(
330                        &registration.manifest.module_id,
331                        connection,
332                        active,
333                        frame.header.corr,
334                    )? || selected.is_some_and(|selected| {
335                        current_window
336                            .is_none_or(|window| selected != (window.generation, window.attempt))
337                    }) {
338                        return Ok(vec![]);
339                    }
340                    match flushed {
341                        Ok(Ok(())) => {}
342                        failed => {
343                            if active {
344                                if let Some((generation, attempt)) = selected {
345                                    let module = registration.manifest.module_id.clone();
346                                    let _ = config_work(
347                                        runtime.clone(),
348                                        ConfigWake::Delivery,
349                                        move |owner| {
350                                            owner.delivery_timeout_for(
351                                                connection, &module, project, generation, attempt,
352                                            )
353                                        },
354                                    )
355                                    .await;
356                                }
357                            }
358                            return match failed {
359                                Ok(Err(error)) => Err(error),
360                                _ => Ok(vec![]),
361                            };
362                        }
363                    }
364                    let module = registration.manifest.module_id.clone();
365                    let delivered = config_work(runtime.clone(), ConfigWake::None, move |owner| {
366                        owner.module_view_delivered(connection, &module, &view, flushed_at, active)
367                    })
368                    .await;
369                    if let Err(error) = delivered {
370                        if matches!(
371                            error.code.as_str(),
372                            "delivery_superseded" | "not_delivery_target"
373                        ) {
374                            return Ok(vec![]);
375                        }
376                        if error.code == "delivery_expired" {
377                            if active {
378                                if let Some((generation, attempt)) = selected {
379                                    let module = registration.manifest.module_id.clone();
380                                    let _ = config_work(
381                                        runtime.clone(),
382                                        ConfigWake::Delivery,
383                                        move |owner| {
384                                            owner.delivery_timeout_for(
385                                                connection, &module, project, generation, attempt,
386                                            )
387                                        },
388                                    )
389                                    .await;
390                                }
391                            }
392                        } else {
393                            return Err(RouterError::backend(
394                                0,
395                                frame.header.corr,
396                                error.to_string(),
397                            ));
398                        }
399                    }
400                    Ok(vec![])
401                } else {
402                    Ok(vec![response])
403                }
404            }
405            Err(error) => {
406                if error.code == "anchor_pending" {
407                    let _ = config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
408                        owner.anchor_pending_served(connection)
409                    })
410                    .await;
411                }
412                Ok(vec![config_error_frame(&frame, error)?])
413            }
414        }
415    }
416    pub fn with_config_runtime(
417        mut self,
418        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
419    ) -> Self {
420        self.supervisor.install_binding_retirement(&runtime);
421        let _ = runtime.set_activity(self.activity.clone());
422        runtime.install_module_route_authority(Arc::new(route_policy::ModuleRouteAuthority(
423            self.clone(),
424            Arc::downgrade(&runtime),
425        )));
426        runtime.install_mark_publisher(Arc::new(caller_attestation::ControlMarkPublisher(
427            self.clone(),
428        )));
429        self.config_runtime = Some(runtime);
430        self
431    }
432
433    /// Only bootstrap's explicit store-root path advertises configuration authority.
434    pub(crate) fn with_explicit_config_store(
435        self,
436        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
437    ) -> Self {
438        let mut handler = self.with_config_runtime(runtime);
439        let capability = subc_protocol::config::CONFIG_GATE_CAPABILITY;
440        if !handler
441            .subc_capabilities
442            .iter()
443            .any(|present| present == capability)
444        {
445            let mut capabilities = handler.subc_capabilities.to_vec();
446            capabilities.push(capability.to_owned());
447            handler.subc_capabilities = capabilities.into();
448        }
449        handler
450    }
451
452    async fn config_desktop_identity(
453        &self,
454        connection: ConnectionId,
455    ) -> std::result::Result<bool, GateError> {
456        if !self.config_owner_connection(connection) {
457            return Ok(false);
458        }
459        #[cfg(feature = "dev-desktop-approval")]
460        {
461            // Requesting and receiving the complete immutable review is the
462            // development caller's desktop presentation, not app attestation.
463            Ok(self
464                .local_connections
465                .lock()
466                .unwrap_or_else(|p| p.into_inner())
467                .contains(&connection))
468        }
469        #[cfg(not(feature = "dev-desktop-approval"))]
470        {
471            Ok(self.has_current_config_desktop_stamp(connection).await)
472        }
473    }
474
475    pub(crate) fn config_desktop_review_request(&self, request: &Frame) -> bool {
476        self.config_runtime.is_some()
477            && request.header.ty == FrameType::Request
478            && serde_json::from_slice::<ControlOpProbe>(&request.body).is_ok_and(|probe| {
479                matches!(
480                    probe.op.as_str(),
481                    "config.plan" | "config.stamp" | "config.unstamp" | "config.rollback"
482                )
483            })
484    }
485
486    pub(crate) async fn config_desktop_review_response(
487        &self,
488        connection: ConnectionId,
489        response: &Frame,
490    ) -> Option<subc_control::config::ConfigPlanView> {
491        if self.config_runtime.is_none() || response.header.ty != FrameType::Response {
492            return None;
493        }
494        let probe: ControlOpProbe = serde_json::from_slice(&response.body).ok()?;
495        if !matches!(
496            probe.op.as_str(),
497            "config.plan"
498                | "config.plan_get"
499                | "config.stamp"
500                | "config.unstamp"
501                | "config.rollback"
502        ) || !matches!(self.config_desktop_identity(connection).await, Ok(true))
503        {
504            return None;
505        }
506        match serde_json::from_slice::<ConfigControlResponse>(&response.body).ok()? {
507            ConfigControlResponse::Plan { view }
508            | ConfigControlResponse::PlanGet { view }
509            | ConfigControlResponse::Stamp { view }
510            | ConfigControlResponse::Unstamp { view }
511            | ConfigControlResponse::Rollback { view } => Some(view),
512            _ => None,
513        }
514    }
515
516    pub(crate) async fn config_desktop_review_delivered(
517        &self,
518        connection: ConnectionId,
519        view: subc_control::config::ConfigPlanView,
520    ) {
521        if !matches!(self.config_desktop_identity(connection).await, Ok(true)) {
522            return;
523        }
524        let Some(runtime) = self.config_runtime.clone() else {
525            return;
526        };
527        let peers = self.captured_peers.clone();
528        let _ = config_work(runtime, ConfigWake::Delivery, move |owner| {
529            owner.desktop_view_delivered_when(connection, &view, || {
530                peers
531                    .lock()
532                    .unwrap_or_else(|p| p.into_inner())
533                    .contains_key(&connection)
534            })
535        })
536        .await;
537    }
538
539    pub(crate) async fn deliver_config_desktop_review(
540        &self,
541        ctx: &RouteCtx,
542        response: Frame,
543        view: subc_control::config::ConfigPlanView,
544    ) -> Result<(), RouterError> {
545        ctx.egress.send_flushed(response).await?;
546        self.config_desktop_review_delivered(ctx.connection_id, view)
547            .await;
548        Ok(())
549    }
550
551    pub fn with_config_review_admission(
552        mut self,
553        admission: Arc<dyn crate::config_gate::ReviewAdmission>,
554    ) -> Self {
555        self.config_review_admission = admission;
556        self.config_review_admission_is_default = false;
557        self
558    }
559
560    pub(super) fn review_admission(&self) -> Arc<dyn crate::config_gate::ReviewAdmission> {
561        if self.config_runtime.is_some() && self.config_review_admission_is_default {
562            Arc::new(admission::SupervisedReviewAdmission(self.clone()))
563        } else {
564            self.config_review_admission.clone()
565        }
566    }
567
568    /// Config operations are channel-0 only, so callers are unscoped. Scoped
569    /// access rules must be enforced if a scoped path to these operations is added.
570    pub(super) async fn handle_config_gate_request(
571        &self,
572        ctx: &RouteCtx,
573        frame: Frame,
574    ) -> Result<Vec<Frame>, RouterError> {
575        let request = match serde_json::from_slice::<ConfigControlRequest>(&frame.body) {
576            Ok(request) => request,
577            Err(error) => {
578                return Ok(vec![control_error_frame(
579                    &frame,
580                    "invalid_control_body",
581                    format!("malformed config control body: {error}"),
582                )?])
583            }
584        };
585        debug_assert!(privileged_operation(&request).is_none());
586        let Some(runtime) = self.config_runtime.clone() else {
587            return Ok(vec![control_error_frame(
588                &frame,
589                "config_gate_inactive",
590                "no config store configured",
591            )?]);
592        };
593        if !self.config_owner_connection(ctx.connection_id) {
594            return Ok(vec![control_error_frame(
595                &frame,
596                "owner_required",
597                "configuration control requires a kernel-observed owner-user connection",
598            )?]);
599        }
600        if let ConfigControlRequest::Watch { modules, .. } = request {
601            return self
602                .handle_config_settings_watch(ctx, frame, runtime, modules)
603                .await;
604        }
605        let result = self
606            .execute_config_request(ctx, &frame, runtime, request)
607            .await;
608        match result {
609            Ok(response) => Ok(vec![control_response_body_frame(
610                &frame,
611                &response,
612                "ConfigControlResponse",
613            )?]),
614            Err(error) => Ok(vec![config_error_frame(&frame, error)?]),
615        }
616    }
617
618    fn config_owner_connection(&self, connection: ConnectionId) -> bool {
619        let peers = self
620            .observed_peers
621            .lock()
622            .unwrap_or_else(|p| p.into_inner());
623        let Some(peer) = peers.get(&connection) else {
624            return false;
625        };
626        #[cfg(unix)]
627        {
628            peer.uid == Some(subc_os::effective_uid())
629        }
630        #[cfg(windows)]
631        {
632            subc_os::named_pipe::current_user_sid_string()
633                .ok()
634                .as_ref()
635                .is_some_and(|sid| peer.sid.as_ref() == Some(sid))
636        }
637        #[cfg(not(any(unix, windows)))]
638        {
639            let _ = peer;
640            false
641        }
642    }
643
644    async fn execute_config_request(
645        &self,
646        ctx: &RouteCtx,
647        frame: &Frame,
648        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
649        request: ConfigControlRequest,
650    ) -> std::result::Result<ConfigControlResponse, GateError> {
651        match request {
652            ConfigControlRequest::Modules {} => {
653                let known = self.config_settings_known_modules()?;
654                config_work(runtime, ConfigWake::None, move |owner| {
655                    owner.settings_modules(known)
656                })
657                .await
658            }
659            ConfigControlRequest::Schema { module_id } => {
660                let known = self.config_settings_known_modules()?;
661                config_work(runtime, ConfigWake::None, move |owner| {
662                    owner.settings_schema(known, module_id)
663                })
664                .await
665            }
666            ConfigControlRequest::Show {
667                module_id,
668                project_id,
669                through,
670            } => {
671                let known = self.config_settings_known_modules()?;
672                config_work(runtime, ConfigWake::None, move |owner| {
673                    owner.settings_show(known, module_id, project_id, through)
674                })
675                .await
676            }
677            ConfigControlRequest::PlanGet { digest } => {
678                let view = config_work(runtime, ConfigWake::None, move |owner| {
679                    owner.plan_get(&digest)
680                })
681                .await?;
682                Ok(ConfigControlResponse::PlanGet { view })
683            }
684            ConfigControlRequest::PlanDiscard { digest } => {
685                config_work(runtime, ConfigWake::Delivery, move |owner| {
686                    owner.plan_discard(&digest)
687                })
688                .await?;
689                Ok(ConfigControlResponse::PlanDiscard {})
690            }
691            ConfigControlRequest::PlaceProgram {
692                module_id,
693                path,
694                sha256,
695                manifest,
696            } => {
697                let gate = runtime.module_gate(&module_id)?;
698                let _guard = gate.lock().await;
699                let generation = config_work(runtime, ConfigWake::Delivery, move |owner| {
700                    owner.place_program_with_manifest(&module_id, &path, &sha256, manifest.as_ref())
701                })
702                .await?;
703                Ok(ConfigControlResponse::ProgramPlaced { generation })
704            }
705            ConfigControlRequest::Status {} => {
706                let snapshot = runtime.polled_snapshot()?;
707                let captured = snapshot.clone();
708                let mut status = runtime
709                    .on_blocking(move |owner| owner.polled_status_from(&captured))
710                    .await?;
711                let phone = self
712                    .config_phone_surface_checked(false, Some(&snapshot))
713                    .await;
714                let facts = self.config_approval_facts_with_phone(ctx, phone).await;
715                status
716                    .missing_approval_surfaces
717                    .extend(crate::config_gate::missing_surfaces(
718                        &facts,
719                        matches!(status.state.as_str(), "store_missing" | "store_unverified"),
720                    ));
721                self.report_daemon_configuration(&snapshot.approved_daemon, &mut status)
722                    .await?;
723                Ok(ConfigControlResponse::Status { status })
724            }
725            ConfigControlRequest::History {} => {
726                let (generations, pruned) =
727                    config_work(runtime, ConfigWake::None, |owner| owner.history()).await?;
728                Ok(ConfigControlResponse::History {
729                    generations,
730                    pruned,
731                })
732            }
733            ConfigControlRequest::Apply { digest } => {
734                let apply_digest = digest.clone();
735                if let Some(generation) = runtime.apply_control_edits(apply_digest).await? {
736                    return Ok(ConfigControlResponse::Applied {
737                        generation,
738                        restart_required: false,
739                    });
740                }
741                let connection = ctx.connection_id;
742                let corr = frame.header.corr;
743                #[cfg(all(test, unix))]
744                runtime.pause_approval_claim_for_test().await;
745                let request_guard = runtime.claim_approval_request(connection, corr)?;
746                if self.rescan.is_none() {
747                    return Err(GateError::new(
748                        "supervisor_reconcile_unavailable",
749                        "configuration commit requires the supervisor owner",
750                    ));
751                }
752                let facts = self.config_approval_facts(ctx).await;
753                let cancellation = request_guard.request.clone();
754                let (challenge, mut attempt_guard) =
755                    config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
756                        let challenge = owner.begin_approval_for_request(
757                            &digest,
758                            &facts,
759                            Some(&cancellation),
760                        )?;
761                        // The job owns slot cleanup even if its async caller drops
762                        // before this blocking result can be delivered.
763                        let guard = phone::ApprovalAttemptGuard::new(&owner, challenge.attempt());
764                        owner.track_reserved_approval_request(
765                            challenge.attempt(),
766                            connection,
767                            corr,
768                            &cancellation,
769                        )?;
770                        Ok((challenge, guard))
771                    })
772                    .await?;
773                request_guard.request.ensure_live()?;
774                let reply = match &challenge {
775                    ApprovalChallenge::Desktop { .. } | ApprovalChallenge::OsPrompt { .. } => {
776                        ApprovalReply::Presence(
777                            self.confirm_config_gate_presence(ctx, frame, &challenge)
778                                .await,
779                        )
780                    }
781                    ApprovalChallenge::Phone {
782                        attempt,
783                        connection,
784                        deadline,
785                        request,
786                    } => {
787                        self.config_phone_rpc(
788                            &runtime,
789                            *attempt,
790                            ConnectionId::new(*connection),
791                            *deadline,
792                            request,
793                        )
794                        .await?
795                    }
796                };
797                let attempt = challenge.attempt();
798                let window = matches!(challenge, ApprovalChallenge::Phone { .. }).then(|| {
799                    Arc::new(crate::config_gate::runtime::ApprovalCommitWindow::new(
800                        Instant::now() + CONFIG_APPROVAL_COMMIT_TIMEOUT,
801                    ))
802                });
803                attempt_guard.commit_window = window.clone();
804                let checked_phone = self.config_phone_surface().await;
805                let locks = async {
806                    // A registry root can keep its worker busy until the I/O
807                    // returns. Do not hold supervisor or module gates while
808                    // waiting for that registry check.
809                    let project_apply = runtime.recheck_capture_apply(attempt).await?;
810                    let operation = self.supervisor.operation_lock().lock_owned().await;
811                    let module_gates = runtime.approval_commit_gates(attempt).await?;
812                    let current_phone = self.config_phone_surface_snapshot().await;
813                    let phone = checked_phone.filter(|phone| Some(phone) == current_phone.as_ref());
814                    let facts = self.config_approval_facts_with_phone(ctx, phone).await;
815                    Ok::<_, GateError>((operation, module_gates, facts, project_apply))
816                };
817                let (operation, module_gates, facts, project_apply) = if let Some(window) = &window
818                {
819                    timeout_at(window.deadline, locks)
820                        .await
821                        .map_err(|_| GateError::commit_timeout())??
822                } else {
823                    locks.await?
824                };
825                let now = now_ms();
826                let publish_window = window.clone();
827                let publication_request = request_guard.request.clone();
828                let exit_runtime = runtime.clone();
829                let work = config_work(runtime, ConfigWake::Delivery, move |owner| {
830                    let _owned_gates = (operation, module_gates);
831                    let write_authority = project_apply.clone();
832                    let generation = owner.finish_approval_with_commit_window(
833                        attempt,
834                        &facts,
835                        reply,
836                        now,
837                        publish_window,
838                        publication_request,
839                        project_apply,
840                    )?;
841                    if let Some(authority) = write_authority {
842                        // The publication job can finish after the control
843                        // request disconnects. It still owns this write-back.
844                        tokio::spawn(async move {
845                            owner
846                                .write_approved_project_files(generation, authority)
847                                .await
848                        });
849                    }
850                    Ok(generation)
851                });
852                tokio::pin!(work);
853                let generation = if let Some(window) = window {
854                    tokio::select! {
855                        result = &mut work => result?,
856                        _ = tokio::time::sleep_until(window.deadline) => {
857                            if window.expire() { return Err(GateError::commit_timeout()); }
858                            work.await?
859                        }
860                    }
861                } else {
862                    work.await?
863                };
864                let approval_runtime = exit_runtime.clone();
865                if let Some(approval) =
866                    config_work(approval_runtime, ConfigWake::None, move |owner| {
867                        owner.development_approval(generation)
868                    })
869                    .await?
870                {
871                    self.publish_development_approval(&approval);
872                    return Ok(ConfigControlResponse::Applied {
873                        generation,
874                        restart_required: false,
875                    });
876                }
877                #[cfg(test)]
878                self.pause_before_apply_reconcile_for_test().await;
879                self.reconcile_authority_exit(exit_runtime.clone(), generation)
880                    .await?;
881                let restart_required = self
882                    .daemon_restart_required(&exit_runtime, generation)
883                    .await?;
884                Ok(ConfigControlResponse::Applied {
885                    generation,
886                    restart_required,
887                })
888            }
889            request => {
890                let (kind, edits) = match request {
891                    ConfigControlRequest::Plan {
892                        base_generations,
893                        edits,
894                    } => {
895                        if edits.is_none() && base_generations.is_some() {
896                            return Err(GateError::new(
897                                "invalid_params",
898                                "base_generations requires edits",
899                            ));
900                        }
901                        let edits = edits
902                            .map(|edits| {
903                                base_generations.map(|base| (base, edits)).ok_or_else(|| {
904                                    GateError::new(
905                                        "invalid_params",
906                                        "edits requires base_generations",
907                                    )
908                                })
909                            })
910                            .transpose()?;
911                        (PlanKind::Change, edits)
912                    }
913                    ConfigControlRequest::Stamp {} => (PlanKind::Stamp, None),
914                    ConfigControlRequest::Unstamp {} => (PlanKind::Unstamp, None),
915                    ConfigControlRequest::Rollback { generation } => {
916                        (PlanKind::Rollback(generation), None)
917                    }
918                    _ => {
919                        return Err(GateError::new(
920                            "unsupported_control_frame",
921                            "unknown configuration operation",
922                        ))
923                    }
924                };
925                let mut prepared = match edits {
926                    Some((base, edits)) => runtime.prepare_control_edits(base, edits).await?,
927                    None => {
928                        let prepared = runtime.prepare_capture(kind).await?;
929                        // Preparing a plan can record observations that delivery reads.
930                        runtime.notify_delivery_changed();
931                        prepared
932                    }
933                };
934                if prepared.capture_refused() {
935                    let view = config_work(runtime, ConfigWake::None, move |owner| {
936                        owner.capture_refusal(&prepared)?.ok_or_else(|| {
937                            GateError::new("module_review_invalid", "project refusal is absent")
938                        })
939                    })
940                    .await?;
941                    return Ok(ConfigControlResponse::Plan { view });
942                }
943                let mut fields = Vec::new();
944                let mut edit_refusals = Vec::new();
945                let mut unavailable_rereviews = Vec::new();
946                for (module, captured) in &prepared.candidate.modules {
947                    if !prepared.review_modules.contains(module) {
948                        continue;
949                    }
950                    let base = prepared.bases.get(module);
951                    let reply = self
952                        .review_config_tuple(&runtime, module, base, &captured.view)
953                        .await;
954                    let reply = match reply {
955                        Ok(reply) => reply,
956                        // A re-review the new program cannot answer now stays
957                        // pending in status; it does not hold up this plan.
958                        Err(_) if prepared.rereview_modules.contains(module) => {
959                            unavailable_rereviews.push(module.clone());
960                            continue;
961                        }
962                        Err(error) => return Err(error),
963                    };
964                    let reply: subc_protocol::config::ConfigReviewReply =
965                        serde_json::from_slice(&reply).map_err(|_| {
966                            GateError::new(
967                                "module_review_invalid",
968                                format!("{module}: malformed config.review reply"),
969                            )
970                        })?;
971                    if prepared.is_edit_plan() && !reply.refusals.is_empty() {
972                        let before = edit_refusals.len();
973                        for refusal in &reply.refusals {
974                            for path in refusal
975                                .paths
976                                .iter()
977                                .filter(|path| path.starts_with('/') && path.len() <= 1024)
978                            {
979                                edit_refusals.push(subc_control::config::ConfigPlanRefusal {
980                                    module_id: module.clone(),
981                                    path: path.clone(),
982                                    code: "module_review_refused".into(),
983                                    message: "the module refused this field".into(),
984                                    project_id: None,
985                                    workspace_id: None,
986                                });
987                            }
988                        }
989                        if edit_refusals.len() == before {
990                            edit_refusals.push(subc_control::config::ConfigPlanRefusal {
991                                module_id: module.clone(),
992                                path: String::new(),
993                                code: "module_review_refused".into(),
994                                message: "the module refused the edits".into(),
995                                project_id: None,
996                                workspace_id: None,
997                            });
998                        }
999                        fields.extend(prepared.refused_fields(module)?);
1000                        continue;
1001                    }
1002                    fields.extend(crate::config_gate::review::checked_fields(
1003                        module,
1004                        &captured.schema,
1005                        base,
1006                        prepared.base_schemas.get(module),
1007                        &captured.view,
1008                        reply,
1009                    )?);
1010                }
1011                for module in unavailable_rereviews {
1012                    prepared.review_modules.remove(&module);
1013                    prepared.rereview_modules.remove(&module);
1014                }
1015                let mut project_replies = Vec::new();
1016                for (tuple, review) in prepared.project_reviews() {
1017                    let bytes = self
1018                        .review_config_tuple(
1019                            &runtime,
1020                            &tuple.module,
1021                            review.base.as_ref(),
1022                            &review.approval.view,
1023                        )
1024                        .await?;
1025                    let reply: subc_protocol::config::ConfigReviewReply =
1026                        serde_json::from_slice(&bytes).map_err(|_| {
1027                            GateError::new(
1028                                "module_review_invalid",
1029                                format!("{}: malformed project config.review reply", tuple.module),
1030                            )
1031                        })?;
1032                    project_replies.push((tuple.clone(), reply));
1033                }
1034                for (tuple, reply) in project_replies {
1035                    if prepared.is_edit_plan() && !reply.refusals.is_empty() {
1036                        prepared.refuse_project_review(&tuple, &reply);
1037                    } else {
1038                        fields.extend(prepared.accept_project_review(&tuple, reply)?);
1039                    }
1040                }
1041                if prepared.capture_refused() {
1042                    let view = runtime
1043                        .on_blocking(move |owner| {
1044                            owner.capture_refusal(&prepared)?.ok_or_else(|| {
1045                                GateError::new("module_review_invalid", "project refusal is absent")
1046                            })
1047                        })
1048                        .await?;
1049                    return Ok(ConfigControlResponse::Plan { view });
1050                }
1051                prepared.add_edit_refusals(edit_refusals);
1052                let view = config_work(runtime, ConfigWake::Delivery, move |owner| {
1053                    owner.finish_plan(prepared, move |old, new| {
1054                        let mut changeset = crate::config_gate::runtime::daemon_review(old, new)?;
1055                        changeset.fields = fields;
1056                        let mut effects: std::collections::BTreeMap<String,std::collections::BTreeMap<String,Vec<String>>> = Default::default();
1057                        for field in changeset.fields.iter().filter(|field| field.project_id.is_none()) {
1058                            let kind = serde_json::to_value(field.apply).map_err(|_| GateError::new("schema_invalid", "could not encode apply kind"))?.as_str().ok_or_else(|| GateError::new("schema_invalid","apply kind is not a string"))?.to_owned();
1059                            effects.entry(field.module_id.clone()).or_default().entry(kind).or_default().push(field.path.clone());
1060                        }
1061                        if changeset.fields.iter().any(|field| field.project_id.is_none() && field.apply != subc_config::ApplyKind::Live) {
1062                            changeset.apply_plan = serde_json::json!({"daemon_effects":changeset.apply_plan,"modules":effects});
1063                        }
1064                        Ok(changeset)
1065                    })
1066                })
1067                .await?;
1068                Ok(match kind {
1069                    PlanKind::Change => ConfigControlResponse::Plan { view },
1070                    PlanKind::Stamp => ConfigControlResponse::Stamp { view },
1071                    PlanKind::Unstamp => ConfigControlResponse::Unstamp { view },
1072                    PlanKind::Rollback(_) => ConfigControlResponse::Rollback { view },
1073                })
1074            }
1075        }
1076    }
1077
1078    async fn review_config_tuple(
1079        &self,
1080        runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1081        module: &str,
1082        base: Option<&subc_protocol::config::ConfigView>,
1083        candidate: &subc_protocol::config::ConfigView,
1084    ) -> Result<Vec<u8>, GateError> {
1085        #[cfg(test)]
1086        if let Some(reply) = &self.config_review_test_reply {
1087            return serde_json::to_vec(reply).map_err(|_| {
1088                GateError::new(
1089                    "module_review_invalid",
1090                    "could not encode the fixture review",
1091                )
1092            });
1093        }
1094        let registration = self
1095            .registry
1096            .get_module(module)
1097            .map_err(|_| GateError::new("config_unavailable", "registry is unavailable"))?
1098            .ok_or_else(|| {
1099                GateError::new(
1100                    "module_review_unavailable",
1101                    format!("{module}: no active reviewer"),
1102                )
1103            })?;
1104        let admission = self.review_admission();
1105        let reviewer = registration.clone();
1106        config_work(runtime.clone(), ConfigWake::None, move |_| {
1107            admission.check(&reviewer)
1108        })
1109        .await?;
1110        if !registration
1111            .control_ops
1112            .iter()
1113            .any(|op| op == "config.review")
1114        {
1115            return Err(GateError::new(
1116                "module_review_unavailable",
1117                format!("{module}: config.review is not opted in"),
1118            ));
1119        }
1120        let request = subc_protocol::config::ConfigReviewRequest::new(
1121            base.map_or(0, |view| view.generation),
1122            candidate.layers.clone(),
1123            base.cloned(),
1124        );
1125        let bytes = serde_json::to_vec(&request).map_err(|_| {
1126            GateError::new("config_unavailable", "could not encode immutable review")
1127        })?;
1128        self.config_rpc(
1129            runtime,
1130            module,
1131            registration.connection_id,
1132            "config.review",
1133            bytes,
1134        )
1135        .await
1136    }
1137
1138    async fn config_approval_facts(&self, ctx: &RouteCtx) -> ApprovalFacts {
1139        let phone = self.config_phone_surface().await;
1140        self.config_approval_facts_with_phone(ctx, phone).await
1141    }
1142
1143    async fn config_approval_facts_with_phone(
1144        &self,
1145        ctx: &RouteCtx,
1146        phone: Option<crate::config_gate::PhoneSurface>,
1147    ) -> ApprovalFacts {
1148        let os_policy = crate::config_gate::os_prompt_policy_present();
1149        #[cfg(any(test, feature = "test-support"))]
1150        let os_policy = os_policy
1151            || self
1152                .config_runtime
1153                .as_ref()
1154                .is_some_and(|owner| owner.os_prompt_policy_for_tests());
1155        let desktop = self
1156            .config_desktop_identity(ctx.connection_id)
1157            .await
1158            .unwrap_or(false);
1159        ApprovalFacts {
1160            connection: ctx.connection_id.get(),
1161            owner_uid: self.config_owner_connection(ctx.connection_id),
1162            desktop_app: desktop,
1163            attested_operator_app: desktop && !cfg!(feature = "dev-desktop-approval"),
1164            os_prompt_available: config_os_prompt_available(
1165                self.forwarding.operator_confirms().config_gate_ready(),
1166                os_policy,
1167            ),
1168            phone,
1169            caller: self.resolve_caller(ctx.connection_id).await,
1170        }
1171    }
1172
1173    // The caller holds Callosum's module gate while allocating its RPC or
1174    // committing approval. This snapshot grants nothing until revalidated there.
1175    async fn config_phone_surface(&self) -> Option<crate::config_gate::PhoneSurface> {
1176        self.config_phone_surface_checked(true, None).await
1177    }
1178
1179    async fn config_phone_surface_snapshot(&self) -> Option<crate::config_gate::PhoneSurface> {
1180        self.config_phone_surface_checked(false, None).await
1181    }
1182
1183    async fn config_phone_surface_checked(
1184        &self,
1185        content: bool,
1186        publication: Option<&crate::config_gate::runtime::Published>,
1187    ) -> Option<crate::config_gate::PhoneSurface> {
1188        if self.config_runtime.as_ref().is_some_and(|owner| {
1189            publication.map_or_else(|| owner.is_recovering(), |view| view.is_recovering())
1190        }) {
1191            return None;
1192        }
1193        if !self.operator_app_policy.phone_enabled {
1194            return None;
1195        }
1196        let runtime = self.config_runtime.as_ref()?;
1197        let (_, registrations) = self.registry.list_modules_with_nonce_verification().ok()?;
1198        let (registration, verified) = registrations
1199            .into_iter()
1200            .find(|(registration, _)| registration.manifest.module_id == "callosum")?;
1201        if !verified
1202            || !registration.ready
1203            || !registration
1204                .control_ops
1205                .iter()
1206                .any(|op| op == subc_protocol::consent::CONSENT_V1)
1207        {
1208            return None;
1209        }
1210        let _spawn = self
1211            .supervisor
1212            .registration_spawn(registration.connection_id)?;
1213        if !self
1214            .forwarding
1215            .active_module_endpoint("callosum")
1216            .ok()
1217            .flatten()
1218            .is_some_and(|endpoint| endpoint.connection_id == registration.connection_id)
1219        {
1220            return None;
1221        }
1222        // Configuration approval requires a channel-bound phone launch.
1223        // Enabling configuration gating invalidates legacy launch nonces,
1224        // including an old registration whose process is still draining.
1225        let module = self.supervisor.get("callosum")?;
1226        let status = module.status().ok()?;
1227        let (spec, _) = module.configuration().ok()?;
1228        if !self.supervisor.registration_snapshot_is_current_live(
1229            &self.registry,
1230            "callosum",
1231            registration.connection_id,
1232            None,
1233        ) || !spec.reserved
1234            || !status.enabled
1235            || !status.process_alive
1236            || !status.registration_active
1237        {
1238            return None;
1239        }
1240        let connection = registration.connection_id;
1241        let approved = if content {
1242            runtime
1243                .on_blocking(move |owner| owner.approved_phone_entry(connection))
1244                .await
1245                .ok()??
1246        } else {
1247            if let Some(snapshot) = publication {
1248                runtime.polled_phone_entry_from(snapshot, connection)?
1249            } else {
1250                runtime.polled_phone_entry(connection)?
1251            }
1252        };
1253        if !approved.enabled || approved.module_spec() != spec {
1254            return None;
1255        }
1256        if content {
1257            let supervisor = self.supervisor.clone();
1258            let registry = self.registry.clone();
1259            if !runtime
1260                .on_blocking(move |_| {
1261                    Ok(supervisor
1262                        .registration_is_current_live(&registry, "callosum", connection, None))
1263                })
1264                .await
1265                .ok()?
1266            {
1267                return None;
1268            }
1269        }
1270        if !self.supervisor.registration_snapshot_is_current_live(
1271            &self.registry,
1272            "callosum",
1273            registration.connection_id,
1274            None,
1275        ) {
1276            return None;
1277        }
1278        Some(crate::config_gate::PhoneSurface {
1279            module_id: "callosum".into(),
1280            connection: connection.get(),
1281            spawn_generation: status.spawn_generation,
1282            enabled_by_policy: true,
1283            opted_in: true,
1284            approved_declaration: true,
1285            reserved: true,
1286            channel_registered: true,
1287            program_admitted: true,
1288            active_registration: true,
1289        })
1290    }
1291
1292    async fn config_rpc(
1293        &self,
1294        runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1295        module: &str,
1296        expected_connection: ConnectionId,
1297        op: &str,
1298        bytes: Vec<u8>,
1299    ) -> std::result::Result<Vec<u8>, GateError> {
1300        let gate = runtime.module_gate(module)?;
1301        let pending = {
1302            let _gate = gate.lock().await;
1303            let registration = self
1304                .registry
1305                .get_module(module)
1306                .map_err(|_| GateError::new("config_unavailable", "registry unavailable"))?
1307                .ok_or_else(|| {
1308                    GateError::new(
1309                        "module_review_unavailable",
1310                        format!("{module}: no active target"),
1311                    )
1312                })?;
1313            let pending = self
1314                .forwarding
1315                .begin_module_control_rpc_for(module, op, Instant::now() + CONFIG_REVIEW_TIMEOUT)
1316                .map_err(|_| {
1317                    GateError::new(
1318                        "module_review_unavailable",
1319                        format!("{module}: target unavailable"),
1320                    )
1321                })?;
1322            if pending.endpoint.connection_id != registration.connection_id
1323                || registration.connection_id != expected_connection
1324            {
1325                let _ = self
1326                    .forwarding
1327                    .cancel_module_control_rpc(pending.endpoint, pending.corr);
1328                return Err(GateError::new(
1329                    "not_delivery_target",
1330                    "registry and forwarding targets differ",
1331                ));
1332            }
1333            pending
1334        };
1335        let PendingModuleControlRpc {
1336            endpoint,
1337            module_sink,
1338            negotiated_ver,
1339            corr,
1340            receiver,
1341        } = pending;
1342        let mut guard = ModuleControlRpcGuard::new(self.forwarding.clone(), endpoint, corr);
1343        let deadline = Instant::now() + CONFIG_REVIEW_TIMEOUT;
1344        let frame = Frame::build_with_version(
1345            negotiated_ver,
1346            FrameType::Request,
1347            control_flags(),
1348            0,
1349            0,
1350            corr,
1351            bytes,
1352        )
1353        .map_err(|_| GateError::new("config_unavailable", "could not encode config request"))?;
1354        timeout_at(deadline, module_sink.send(frame))
1355            .await
1356            .map_err(|_| {
1357                GateError::new(
1358                    "config_review_timeout",
1359                    format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1360                )
1361            })?
1362            .map_err(|_| {
1363                GateError::new(
1364                    "module_review_unavailable",
1365                    format!("{module}: target disconnected"),
1366                )
1367            })?;
1368        let outcome = timeout_at(deadline, receiver)
1369            .await
1370            .map_err(|_| {
1371                GateError::new(
1372                    "config_review_timeout",
1373                    format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1374                )
1375            })?
1376            .map_err(|_| {
1377                GateError::new(
1378                    "module_review_unavailable",
1379                    format!("{module}: target disconnected"),
1380                )
1381            })?;
1382        guard.disarm();
1383        match outcome {
1384            ModuleControlRpcOutcome::RawResponse(bytes) => Ok(bytes),
1385            ModuleControlRpcOutcome::DeadlineElapsed => Err(GateError::new("config_review_timeout",format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"))),
1386            _ => Err(GateError::new(
1387                "module_review_unavailable",
1388                format!("{module}: config request was not answered"),
1389            )),
1390        }
1391    }
1392
1393    /// Execute only the presence part of an engine-selected challenge. The
1394    /// runtime owner still rechecks the inputs and surface before committing.
1395    pub async fn confirm_config_gate_presence(
1396        &self,
1397        ctx: &RouteCtx,
1398        frame: &Frame,
1399        challenge: &ApprovalChallenge,
1400    ) -> PresenceDecision {
1401        let Some(text) = challenge.prompt() else {
1402            return PresenceDecision::Unavailable;
1403        };
1404        let caller = self.resolve_caller(ctx.connection_id).await;
1405        let key = crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1406        // Neither privileged_operator_prompt nor operator-app shortcut policy
1407        // is consulted: every desktop gate review requires OS presence.
1408        let outcome = self
1409            .forwarding
1410            .operator_confirms()
1411            .approve_config_gate(ctx, frame, text.to_owned(), caller.description(), key)
1412            .await;
1413        PresenceDecision::from_operator_outcome(&outcome)
1414    }
1415}
1416
1417fn config_os_prompt_available(provider_ready: bool, policy_present: bool) -> bool {
1418    provider_ready && policy_present
1419}
1420
1421enum ConfigWake {
1422    None,
1423    Delivery,
1424}
1425
1426async fn config_work<T: Send + 'static>(
1427    runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1428    wake: ConfigWake,
1429    work: impl FnOnce(Arc<crate::config_gate::runtime::RuntimeOwner>) -> std::result::Result<T, GateError>
1430        + Send
1431        + 'static,
1432) -> std::result::Result<T, GateError> {
1433    runtime
1434        .on_blocking(move |owner| {
1435            let result = work(owner.clone());
1436            if matches!(wake, ConfigWake::Delivery) {
1437                owner.notify_delivery_changed();
1438            }
1439            result
1440        })
1441        .await
1442}
1443
1444pub(super) fn config_error_frame(frame: &Frame, error: GateError) -> Result<Frame, RouterError> {
1445    control_error_body_frame(
1446        frame,
1447        ErrorBody {
1448            code: error.code,
1449            message: error.detail,
1450            detail: None,
1451        },
1452    )
1453}
1454
1455fn now_ms() -> u64 {
1456    std::time::SystemTime::now()
1457        .duration_since(std::time::UNIX_EPOCH)
1458        .unwrap_or_default()
1459        .as_millis()
1460        .min(u128::from(u64::MAX)) as u64
1461}
1462
1463#[cfg(test)]
1464mod tests;
1465
1466#[cfg(test)]
1467mod desktop_tests;