1use serde::{Deserialize, Serialize};
5use std::collections::BTreeMap;
6pub use subc_config::{ApprovalChannel, Digest, Generation, Plan};
7pub use subc_protocol::config::ConfigDeclarationPending;
8
9pub const CONFIG_GATE_CAPABILITY: &str = "config.gate";
10pub const CONFIG_SETTINGS_CAPABILITY: &str = "config.settings/v1";
11pub const CONFIG_SETTINGS_PROJECTS_CAPABILITY: &str = "config.settings.projects/v1";
12
13#[derive(Clone, Debug, PartialEq, Serialize)]
16pub struct ConfigEdit {
17 pub module_id: String,
18 pub layer: String,
19 #[serde(default, skip_serializing_if = "Option::is_none")]
20 pub workspace_id: Option<String>,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
22 pub project_id: Option<String>,
23 pub path: String,
24 #[serde(flatten)]
25 pub action: ConfigEditAction,
26}
27
28#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
29#[serde(untagged)]
30pub enum ConfigEditAction {
31 Set { set: serde_json::Value },
32 Remove { remove: bool },
33}
34
35impl<'de> Deserialize<'de> for ConfigEdit {
36 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
37 #[derive(Deserialize)]
38 #[serde(deny_unknown_fields)]
39 struct Wire {
40 module_id: String,
41 layer: String,
42 workspace_id: Option<String>,
43 project_id: Option<String>,
44 path: String,
45 #[serde(default, deserialize_with = "present_value")]
46 set: Option<serde_json::Value>,
47 remove: Option<bool>,
48 }
49 fn present_value<'de, D: serde::Deserializer<'de>>(
50 deserializer: D,
51 ) -> Result<Option<serde_json::Value>, D::Error> {
52 serde_json::Value::deserialize(deserializer).map(Some)
53 }
54 let wire = Wire::deserialize(deserializer)?;
55 let action = match (wire.set, wire.remove) {
56 (Some(set), None) => ConfigEditAction::Set { set },
57 (None, Some(true)) => ConfigEditAction::Remove { remove: true },
58 _ => return Err(serde::de::Error::custom("expected set or remove: true")),
59 };
60 Ok(Self {
61 module_id: wire.module_id,
62 layer: wire.layer,
63 workspace_id: wire.workspace_id,
64 project_id: wire.project_id,
65 path: wire.path,
66 action,
67 })
68 }
69}
70
71#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
73pub struct ConfigPlanRefusal {
74 pub module_id: String,
75 pub path: String,
76 pub code: String,
77 pub message: String,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub project_id: Option<String>,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub workspace_id: Option<String>,
82}
83
84#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
87#[serde(tag = "op", deny_unknown_fields)]
88#[non_exhaustive]
89pub enum ConfigControlRequest {
90 #[serde(rename = "config.status")]
91 Status {},
92 #[serde(rename = "config.modules")]
93 Modules {},
94 #[serde(rename = "config.schema")]
95 Schema { module_id: String },
96 #[serde(rename = "config.show")]
97 Show {
98 module_id: String,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
100 project_id: Option<String>,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
102 through: Option<ConfigThrough>,
103 },
104 #[serde(rename = "config.watch")]
105 Watch {
106 #[serde(default, skip_serializing_if = "Option::is_none")]
107 modules: Option<Vec<String>>,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
110 projects: Option<bool>,
111 },
112 #[serde(rename = "config.plan")]
113 Plan {
114 #[serde(default, skip_serializing_if = "Option::is_none")]
115 base_generations: Option<BTreeMap<String, u64>>,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
117 edits: Option<Vec<ConfigEdit>>,
118 },
119 #[serde(rename = "config.plan_get")]
120 PlanGet { digest: Digest },
121 #[serde(rename = "config.plan_discard")]
122 PlanDiscard { digest: Digest },
123 #[serde(rename = "config.apply")]
124 Apply { digest: Digest },
125 #[serde(rename = "config.stamp")]
126 Stamp {},
127 #[serde(rename = "config.unstamp")]
128 Unstamp {},
129 #[serde(rename = "config.history")]
130 History {},
131 #[serde(rename = "config.rollback")]
132 Rollback { generation: u64 },
133 #[serde(rename = "config.place_program")]
134 PlaceProgram {
135 module_id: String,
136 path: String,
137 sha256: Digest,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
140 manifest: Option<serde_json::Value>,
141 },
142}
143
144impl ConfigControlRequest {
145 pub fn op(&self) -> &'static str {
146 match self {
147 Self::Status {} => "config.status",
148 Self::Modules {} => "config.modules",
149 Self::Schema { .. } => "config.schema",
150 Self::Show { .. } => "config.show",
151 Self::Watch { .. } => "config.watch",
152 Self::Plan { .. } => "config.plan",
153 Self::PlanGet { .. } => "config.plan_get",
154 Self::PlanDiscard { .. } => "config.plan_discard",
155 Self::Apply { .. } => "config.apply",
156 Self::Stamp {} => "config.stamp",
157 Self::Unstamp {} => "config.unstamp",
158 Self::History {} => "config.history",
159 Self::Rollback { .. } => "config.rollback",
160 Self::PlaceProgram { .. } => "config.place_program",
161 }
162 }
163}
164
165#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
167#[serde(rename_all = "snake_case")]
168pub enum ConfigThrough {
169 Default,
170 User,
171 Workspace,
172}
173
174#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
176#[non_exhaustive]
177pub struct ConfigFileError {
178 pub code: String,
179 pub message: String,
180}
181
182impl ConfigFileError {
183 pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
184 Self {
185 code: code.into(),
186 message: message.into(),
187 }
188 }
189}
190
191#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
193#[non_exhaustive]
194pub struct ConfigModule {
195 #[serde(default, skip_serializing_if = "Option::is_none")]
196 pub declaration_pending: Option<ConfigDeclarationPending>,
197 pub module_id: String,
198 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub project_id: Option<String>,
200 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub workspace_id: Option<String>,
202 #[serde(default, skip_serializing_if = "Option::is_none")]
203 pub display_name: Option<String>,
204 pub gated: bool,
205 #[serde(default, skip_serializing_if = "Option::is_none")]
206 pub schema_digest: Option<Digest>,
207 pub status: String,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
209 pub status_reason: Option<String>,
210 #[serde(default, skip_serializing_if = "Option::is_none")]
211 pub file_error: Option<ConfigFileError>,
212 #[serde(default, skip_serializing_if = "Option::is_none")]
213 pub approved_generation: Option<u64>,
214 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub active_generation: Option<u64>,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
217 pub pending_plan: Option<Digest>,
218}
219
220#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
222#[non_exhaustive]
223pub struct ConfigSettingsLayer {
224 pub layer: subc_config::Layer,
225 #[serde(default, skip_serializing_if = "Option::is_none")]
226 pub workspace_id: Option<String>,
227 #[serde(default, skip_serializing_if = "Option::is_none")]
228 pub project_id: Option<String>,
229 pub document: serde_json::Value,
230}
231
232impl ConfigSettingsLayer {
233 pub fn new(layer: subc_config::Layer, document: serde_json::Value) -> Self {
234 Self {
235 layer,
236 workspace_id: None,
237 project_id: None,
238 document,
239 }
240 }
241}
242
243#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
246#[serde(tag = "event", rename_all = "snake_case")]
247#[non_exhaustive]
248#[allow(clippy::large_enum_variant)]
251pub enum ConfigWatchEvent {
252 Resync {
253 modules: Vec<ConfigModule>,
254 stamped: bool,
255 },
256 Change {
257 module_id: String,
258 #[serde(default, skip_serializing_if = "Option::is_none")]
259 project_id: Option<String>,
260 #[serde(default, skip_serializing_if = "Option::is_none")]
261 workspace_id: Option<String>,
262 #[serde(default, skip_serializing_if = "Option::is_none")]
263 declaration_pending: Option<ConfigDeclarationPending>,
264 #[serde(default, skip_serializing_if = "Option::is_none")]
265 approved_generation: Option<u64>,
266 #[serde(default, skip_serializing_if = "Option::is_none")]
267 active_generation: Option<u64>,
268 status: String,
269 #[serde(default, skip_serializing_if = "Option::is_none")]
270 status_reason: Option<String>,
271 #[serde(default, skip_serializing_if = "Option::is_none")]
272 file_error: Option<ConfigFileError>,
273 #[serde(default, skip_serializing_if = "Option::is_none")]
274 schema_digest: Option<Digest>,
275 #[serde(default, skip_serializing_if = "Option::is_none")]
276 pending_plan: Option<Digest>,
277 },
278}
279
280impl ConfigWatchEvent {
281 pub fn change(row: &ConfigModule) -> Self {
282 Self::Change {
283 module_id: row.module_id.clone(),
284 project_id: row.project_id.clone(),
285 workspace_id: row.workspace_id.clone(),
286 declaration_pending: row.declaration_pending.clone(),
287 approved_generation: row.approved_generation,
288 active_generation: row.active_generation,
289 status: row.status.clone(),
290 status_reason: row.status_reason.clone(),
291 file_error: row.file_error.clone(),
292 schema_digest: row.schema_digest.clone(),
293 pending_plan: row.pending_plan.clone(),
294 }
295 }
296}
297
298#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
299#[non_exhaustive]
300pub struct ConfigWatchResponse {
301 op: ConfigWatchOp,
302 #[serde(flatten)]
303 pub event: ConfigWatchEvent,
304}
305
306impl ConfigWatchResponse {
307 pub fn new(event: ConfigWatchEvent) -> Self {
308 Self {
309 op: ConfigWatchOp::Watch,
310 event,
311 }
312 }
313}
314
315#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
316enum ConfigWatchOp {
317 #[serde(rename = "config.watch")]
318 Watch,
319}
320
321#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
323#[non_exhaustive]
324pub struct ConfigPlanView {
325 pub digest: Digest,
326 pub base_revision: u64,
327 pub plan: Plan,
328 #[serde(default, skip_serializing_if = "Vec::is_empty")]
330 pub refusals: Vec<ConfigPlanRefusal>,
331 #[serde(default, skip_serializing_if = "Vec::is_empty")]
333 pub skipped: Vec<ConfigPlanRefusal>,
334}
335
336impl ConfigPlanView {
337 pub fn new(plan: Plan) -> Result<Self, subc_config::CanonicalError> {
338 Ok(Self {
339 digest: plan.digest()?,
340 base_revision: plan.base_revision,
341 plan,
342 refusals: Vec::new(),
343 skipped: Vec::new(),
344 })
345 }
346}
347
348#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
350#[non_exhaustive]
351pub struct ConfigApprovalRecord {
352 pub generation: u64,
353 pub channel: ApprovalChannel,
354}
355
356impl ConfigApprovalRecord {
357 pub fn new(generation: u64, channel: ApprovalChannel) -> Self {
358 Self {
359 generation,
360 channel,
361 }
362 }
363}
364
365#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
367#[non_exhaustive]
368pub struct ConfigStatus {
369 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
370 pub declaration_pending: BTreeMap<String, ConfigDeclarationPending>,
371 pub approval_channels: Vec<ConfigApprovalRecord>,
372 pub state: String,
373 pub integrity: String,
374 pub revision: u64,
375 pub base_revision: u64,
376 pub pending_proposals: u64,
377 pub anchor_pending: bool,
378 pub ungated_modules: Vec<String>,
379 pub ungated_inputs: Vec<String>,
380 pub gated_modules: Vec<String>,
381 pub interpreter_only_covered: Vec<String>,
382 pub approved_but_inactive: Vec<serde_json::Value>,
383 pub development_switches: Vec<String>,
384 pub missing_approval_surfaces: Vec<String>,
385 pub warnings: Vec<String>,
386 #[serde(default, skip_serializing_if = "ConfigRootIo::absent_or_idle")]
387 pub root_io: Option<ConfigRootIo>,
388}
389
390#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
392#[non_exhaustive]
393pub struct ConfigRootIo {
394 pub stuck_roots: Vec<String>,
396 pub charged_workers: u64,
398}
399
400impl ConfigRootIo {
401 fn absent_or_idle(root_io: &Option<Self>) -> bool {
402 root_io
403 .as_ref()
404 .is_none_or(|io| io.stuck_roots.is_empty() && io.charged_workers == 0)
405 }
406}
407
408#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
409#[serde(tag = "op")]
410#[non_exhaustive]
411pub enum ConfigControlResponse {
412 #[serde(rename = "config.status")]
413 Status { status: ConfigStatus },
414 #[serde(rename = "config.modules")]
415 Modules {
416 modules: Vec<ConfigModule>,
417 stamped: bool,
418 },
419 #[serde(rename = "config.schema")]
420 Schema {
421 module_id: String,
422 schema_digest: Digest,
423 schema: serde_json::Value,
424 },
425 #[serde(rename = "config.show")]
426 Show {
427 module_id: String,
428 #[serde(default, skip_serializing_if = "Option::is_none")]
429 project_id: Option<String>,
430 #[serde(default, skip_serializing_if = "Option::is_none")]
431 through: Option<ConfigThrough>,
432 stamped: bool,
433 base_generation: u64,
434 effective: serde_json::Value,
435 sources: std::collections::BTreeMap<String, subc_config::Layer>,
436 layers: Vec<ConfigSettingsLayer>,
437 #[serde(default, skip_serializing_if = "Option::is_none")]
438 file_error: Option<ConfigFileError>,
439 #[serde(default, skip_serializing_if = "Option::is_none")]
440 pending_plan: Option<Digest>,
441 #[serde(default, skip_serializing_if = "Option::is_none")]
442 declaration_pending: Option<ConfigDeclarationPending>,
443 },
444 #[serde(rename = "config.plan")]
445 Plan { view: ConfigPlanView },
446 #[serde(rename = "config.plan_get")]
447 PlanGet { view: ConfigPlanView },
448 #[serde(rename = "config.plan_discard")]
449 PlanDiscard {},
450 #[serde(rename = "config.stamp")]
451 Stamp { view: ConfigPlanView },
452 #[serde(rename = "config.unstamp")]
453 Unstamp { view: ConfigPlanView },
454 #[serde(rename = "config.rollback")]
455 Rollback { view: ConfigPlanView },
456 #[serde(rename = "config.apply")]
457 Applied {
458 generation: u64,
459 #[serde(default)]
460 restart_required: bool,
461 },
462 #[serde(rename = "config.history")]
463 History {
464 generations: Vec<Generation>,
465 pruned: Vec<serde_json::Value>,
466 },
467 #[serde(rename = "config.place_program")]
468 ProgramPlaced {
469 #[serde(default, skip_serializing_if = "Option::is_none")]
470 generation: Option<u64>,
471 },
472}
473
474#[cfg(test)]
475mod tests {
476 #[test]
477 fn config_wire_declaration_pending_reaches_settings_watch() {
478 use super::*;
479 let row = ConfigModule {
480 module_id: "sample".into(),
481 declaration_pending: Some(ConfigDeclarationPending::default()),
482 ..ConfigModule::default()
483 };
484 let event = ConfigWatchResponse::new(ConfigWatchEvent::change(&row));
485 let mut wire = serde_json::to_value(&event).unwrap();
486 assert_eq!(wire["declaration_pending"], serde_json::json!({}));
487 wire["declaration_pending"]["future_member"] = serde_json::json!(true);
488 assert_eq!(
489 serde_json::from_value::<ConfigWatchResponse>(wire).unwrap(),
490 event
491 );
492 }
493 #[test]
494 fn config_wire_existing_bodies_remain_byte_identical() {
495 const DIGEST: &str =
496 "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
497 for wire in [
498 r#"{"op":"config.status"}"#,
499 r#"{"op":"config.modules"}"#,
500 r#"{"op":"config.schema","module_id":"demo"}"#,
501 r#"{"op":"config.show","module_id":"demo"}"#,
502 r#"{"op":"config.show","module_id":"demo","through":"workspace"}"#,
503 r#"{"op":"config.watch"}"#,
504 r#"{"op":"config.watch","modules":["demo"]}"#,
505 r#"{"op":"config.plan"}"#,
506 r#"{"op":"config.plan","base_generations":{"demo":3},"edits":[{"module_id":"demo","layer":"user","path":"/limit","set":3}]}"#,
507 r#"{"op":"config.stamp"}"#,
508 r#"{"op":"config.unstamp"}"#,
509 r#"{"op":"config.history"}"#,
510 r#"{"op":"config.rollback","generation":3}"#,
511 ] {
512 assert_wire_bytes::<ConfigControlRequest>(wire);
513 }
514 for op in ["config.plan_get", "config.plan_discard", "config.apply"] {
515 assert_wire_bytes::<ConfigControlRequest>(&format!(
516 r#"{{"op":"{op}","digest":"{DIGEST}"}}"#
517 ));
518 }
519 assert_wire_bytes::<ConfigControlRequest>(&format!(
520 r#"{{"op":"config.place_program","module_id":"demo","path":"/bin/demo","sha256":"{DIGEST}"}}"#
521 ));
522
523 let row = r#"{"module_id":"demo","gated":true,"status":"adopted"}"#;
524 for wire in [
525 r#"{"op":"config.status","status":{"approval_channels":[],"state":"","integrity":"","revision":0,"base_revision":0,"pending_proposals":0,"anchor_pending":false,"ungated_modules":[],"ungated_inputs":[],"gated_modules":[],"interpreter_only_covered":[],"approved_but_inactive":[],"development_switches":[],"missing_approval_surfaces":[],"warnings":[]}}"#.to_owned(),
526 format!(r#"{{"op":"config.modules","modules":[{row}],"stamped":true}}"#),
527 format!(r#"{{"op":"config.schema","module_id":"demo","schema_digest":"{DIGEST}","schema":{{"type":"object"}}}}"#),
528 r#"{"op":"config.show","module_id":"demo","through":"workspace","stamped":true,"base_generation":3,"effective":{"limit":3},"sources":{"/limit":"user"},"layers":[{"layer":"user","document":{"limit":3}}]}"#.to_owned(),
529 r#"{"op":"config.plan_discard"}"#.to_owned(),
530 r#"{"op":"config.apply","generation":3,"restart_required":false}"#.to_owned(),
531 r#"{"op":"config.history","generations":[],"pruned":[]}"#.to_owned(),
532 r#"{"op":"config.place_program","generation":3}"#.to_owned(),
533 ] {
534 assert_wire_bytes::<ConfigControlResponse>(&wire);
535 }
536 let plan = r#"{"base_revision":7,"base_generation":3,"active_generations":{},"daemon_incarnation":"daemon","input_vector":{"inputs":{}},"changeset":{"fields":[],"affected_projects":[],"policy_changes":[],"launch_manifests":{},"apply_plan":null}}"#;
537 for op in [
538 "config.plan",
539 "config.plan_get",
540 "config.stamp",
541 "config.unstamp",
542 "config.rollback",
543 ] {
544 assert_wire_bytes::<ConfigControlResponse>(&format!(
545 r#"{{"op":"{op}","view":{{"digest":"{DIGEST}","base_revision":7,"plan":{plan}}}}}"#
546 ));
547 }
548 let refusal = r#"{"module_id":"demo","path":"/limit","code":"value_invalid","message":"invalid limit"}"#;
549 assert_wire_bytes::<ConfigControlResponse>(&format!(
550 r#"{{"op":"config.plan","view":{{"digest":"{DIGEST}","base_revision":7,"plan":{plan},"refusals":[{refusal}]}}}}"#
551 ));
552 assert_wire_bytes::<ConfigWatchResponse>(&format!(
553 r#"{{"op":"config.watch","event":"resync","modules":[{row}],"stamped":true}}"#
554 ));
555 assert_wire_bytes::<ConfigWatchResponse>(
556 r#"{"op":"config.watch","event":"change","module_id":"demo","status":"adopted"}"#,
557 );
558 }
559
560 fn assert_wire_bytes<T: serde::de::DeserializeOwned + Serialize>(wire: &str) {
561 let decoded: T =
562 serde_json::from_str(wire).unwrap_or_else(|error| panic!("{wire}: {error}"));
563 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
564 }
565
566 #[test]
567 fn config_wire_project_watch_round_trips_ids_and_opt_in() {
568 assert_eq!(
569 CONFIG_SETTINGS_PROJECTS_CAPABILITY,
570 "config.settings.projects/v1"
571 );
572 assert_wire_bytes::<ConfigControlRequest>(
573 r#"{"op":"config.watch","modules":["demo"],"projects":true}"#,
574 );
575 assert_wire_bytes::<ConfigControlRequest>(r#"{"op":"config.watch","projects":false}"#);
576 assert!(serde_json::from_str::<ConfigControlRequest>(
577 r#"{"op":"config.watch","projects":"true"}"#
578 )
579 .is_err());
580
581 let row = ConfigModule {
582 module_id: "demo".into(),
583 project_id: Some("p".into()),
584 workspace_id: Some("w".into()),
585 gated: true,
586 status: "adopted".into(),
587 ..ConfigModule::default()
588 };
589 let change = ConfigWatchResponse::new(ConfigWatchEvent::change(&row));
590 let wire = r#"{"op":"config.watch","event":"change","module_id":"demo","project_id":"p","workspace_id":"w","status":"adopted"}"#;
591 assert_eq!(serde_json::to_string(&change).unwrap(), wire);
592 assert_eq!(
593 serde_json::from_str::<ConfigWatchResponse>(wire).unwrap(),
594 change
595 );
596 assert_wire_bytes::<ConfigWatchResponse>(
597 r#"{"op":"config.watch","event":"resync","modules":[{"module_id":"demo","project_id":"p","workspace_id":"w","gated":true,"status":"adopted"}],"stamped":true}"#,
598 );
599 }
600
601 #[test]
602 fn config_wire_project_plan_keeps_skips_separate_from_refusals() {
603 let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
604 let mut view = ConfigPlanView::new(plan).unwrap();
605 view.refusals.push(ConfigPlanRefusal {
606 module_id: "demo".into(),
607 path: "/limit".into(),
608 code: "credential_layer_unsupported".into(),
609 message: "section is user-only".into(),
610 project_id: Some("p".into()),
611 workspace_id: None,
612 });
613 view.skipped.push(ConfigPlanRefusal {
614 module_id: "demo".into(),
615 path: ".cortexkit/demo.jsonc".into(),
616 code: "layer_symlink".into(),
617 message: "layer is a symlink".into(),
618 project_id: Some("q".into()),
619 workspace_id: Some("w".into()),
620 });
621 let response = ConfigControlResponse::Plan { view };
622 let wire = serde_json::to_value(&response).unwrap();
623 assert_eq!(
624 wire["view"]["refusals"],
625 json!([{
626 "module_id":"demo","path":"/limit","code":"credential_layer_unsupported",
627 "message":"section is user-only","project_id":"p"
628 }])
629 );
630 assert_eq!(
631 wire["view"]["skipped"],
632 json!([{
633 "module_id":"demo","path":".cortexkit/demo.jsonc","code":"layer_symlink",
634 "message":"layer is a symlink","project_id":"q","workspace_id":"w"
635 }])
636 );
637 assert_eq!(
638 serde_json::from_value::<ConfigControlResponse>(wire).unwrap(),
639 response
640 );
641 }
642
643 #[test]
644 fn config_wire_status_emits_only_non_idle_root_io_health() {
645 let mut status = ConfigStatus::default();
646 let legacy = serde_json::to_vec(&status).unwrap();
647 status.root_io = Some(ConfigRootIo::default());
648 assert_eq!(serde_json::to_vec(&status).unwrap(), legacy);
649
650 status.root_io = Some(ConfigRootIo {
651 stuck_roots: vec!["/roots/a".into(), "/roots/b".into()],
652 charged_workers: 2,
653 });
654 let response = ConfigControlResponse::Status { status };
655 let wire = serde_json::to_value(&response).unwrap();
656 assert_eq!(
657 wire["status"]["root_io"],
658 json!({
659 "stuck_roots":["/roots/a","/roots/b"],"charged_workers":2
660 })
661 );
662 assert_eq!(
663 serde_json::from_value::<ConfigControlResponse>(wire).unwrap(),
664 response
665 );
666 }
667
668 #[test]
669 fn config_wire_settings_status_is_open_and_selectors_are_strict() {
670 use super::*;
671 let module: ConfigModule = serde_json::from_value(
672 serde_json::json!({"module_id":"sample","gated":true,"status":"future_status"}),
673 )
674 .unwrap();
675 assert_eq!(module.status, "future_status");
676 assert!(serde_json::from_value::<ConfigControlRequest>(
677 serde_json::json!({"op":"config.show","module_id":"sample","through":"project"})
678 )
679 .is_err());
680 let event = ConfigWatchResponse::new(ConfigWatchEvent::Resync {
681 modules: vec![module],
682 stamped: false,
683 });
684 assert_eq!(
685 serde_json::from_slice::<ConfigWatchResponse>(&serde_json::to_vec(&event).unwrap())
686 .unwrap(),
687 event
688 );
689 }
690
691 #[test]
692 fn config_wire_file_errors_are_optional_and_tolerate_extensions() {
693 let legacy = json!({"module_id":"sample","gated":true,"status":"adopted"});
694 let mut row: ConfigModule = serde_json::from_value(legacy).unwrap();
695 assert!(row.file_error.is_none());
696 let error = ConfigFileError::new("value_invalid", "invalid settings");
697 row.file_error = Some(error.clone());
698 let change = ConfigWatchResponse::new(ConfigWatchEvent::change(&row));
699 let mut wire = serde_json::to_value(&change).unwrap();
700 assert_eq!(
701 wire["file_error"],
702 json!({"code":"value_invalid","message":"invalid settings"})
703 );
704 wire["file_error"]["future"] = json!(true);
705 assert_eq!(
706 serde_json::from_value::<ConfigWatchResponse>(wire).unwrap(),
707 change
708 );
709 let mut shown = json!({"op":"config.show","module_id":"sample","stamped":true,"base_generation":1,"effective":{},"sources":{},"layers":[]});
710 assert!(matches!(
711 serde_json::from_value::<ConfigControlResponse>(shown.clone()).unwrap(),
712 ConfigControlResponse::Show {
713 file_error: None,
714 ..
715 }
716 ));
717 shown["file_error"] = serde_json::to_value(&error).unwrap();
718 assert!(
719 matches!(serde_json::from_value::<ConfigControlResponse>(shown).unwrap(), ConfigControlResponse::Show {file_error:Some(found), ..} if found == error)
720 );
721 }
722
723 #[test]
724 fn config_wire_program_placement_names_and_optional_generation() {
725 use super::*;
726 let body = serde_json::json!({"op":"config.place_program","module_id":"demo","path":"/bin/demo","sha256":format!("sha256:{}", "a".repeat(64))});
727 let request: ConfigControlRequest = serde_json::from_value(body.clone()).unwrap();
728 assert_eq!(request.op(), "config.place_program");
729 assert_eq!(serde_json::to_value(request).unwrap(), body);
730 assert!(matches!(
731 serde_json::from_value::<ConfigControlResponse>(
732 serde_json::json!({"op":"config.place_program"})
733 )
734 .unwrap(),
735 ConfigControlResponse::ProgramPlaced { generation: None }
736 ));
737 let response = ConfigControlResponse::ProgramPlaced {
738 generation: Some(3),
739 };
740 assert_eq!(
741 serde_json::to_value(response).unwrap(),
742 serde_json::json!({"op":"config.place_program","generation":3})
743 );
744 }
745 #[test]
746 fn config_wire_applied_reports_restart_required_and_defaults_absent_to_false() {
747 use super::*;
748 let response = ConfigControlResponse::Applied {
749 generation: 7,
750 restart_required: true,
751 };
752 assert_eq!(
753 serde_json::to_value(response).unwrap(),
754 serde_json::json!({"op":"config.apply", "generation":7, "restart_required":true})
755 );
756 assert_eq!(
757 serde_json::from_value::<ConfigControlResponse>(
758 serde_json::json!({"op":"config.apply", "generation":7})
759 )
760 .unwrap(),
761 ConfigControlResponse::Applied {
762 generation: 7,
763 restart_required: false,
764 }
765 );
766 assert_eq!(
767 serde_json::to_value(ConfigControlResponse::Applied {
768 generation: 7,
769 restart_required: false,
770 })
771 .unwrap()["restart_required"],
772 false
773 );
774 }
775
776 #[test]
777 fn config_wire_status_and_history_preserve_unverified_approval_channel() {
778 use super::*;
779 let channel = ApprovalChannel::UnverifiedDevelopmentDesktop;
780 let mut status = ConfigStatus::default();
781 status
782 .approval_channels
783 .push(ConfigApprovalRecord::new(1, channel));
784 let generation = Generation::new(
785 1,
786 channel,
787 subc_config::raw_digest(b"plan"),
788 subc_config::InputVector::default(),
789 subc_config::Changeset::new(),
790 );
791 for response in [
792 ConfigControlResponse::Status { status },
793 ConfigControlResponse::History {
794 generations: vec![generation],
795 pruned: vec![],
796 },
797 ] {
798 let encoded = serde_json::to_string(&response).unwrap();
799 assert!(encoded.contains("unverified_development_desktop"));
800 assert_eq!(
801 serde_json::from_str::<ConfigControlResponse>(&encoded).unwrap(),
802 response
803 );
804 }
805 }
806 use super::*;
807 use serde_json::json;
808
809 #[test]
810 fn config_wire_requests_are_strict_and_round_trip() {
811 for body in [
812 json!({"op":"config.status"}),
813 json!({"op":"config.modules"}),
814 json!({"op":"config.schema","module_id":"sample-reader"}),
815 json!({"op":"config.show","module_id":"sample-reader"}),
816 json!({"op":"config.show","module_id":"sample-reader","project_id":"sample-project","through":"workspace"}),
817 json!({"op":"config.watch"}),
818 json!({"op":"config.watch","modules":["sample-reader"]}),
819 json!({"op":"config.plan"}),
820 json!({"op":"config.plan_get", "digest":subc_config::raw_digest(b"plan")}),
821 json!({"op":"config.plan_discard", "digest":subc_config::raw_digest(b"plan")}),
822 json!({"op":"config.apply", "digest":subc_config::raw_digest(b"plan")}),
823 json!({"op":"config.stamp"}),
824 json!({"op":"config.unstamp"}),
825 json!({"op":"config.history"}),
826 json!({"op":"config.rollback", "generation":4}),
827 ] {
828 let request: ConfigControlRequest = serde_json::from_value(body.clone()).unwrap();
829 assert_eq!(body["op"], request.op());
830 assert_eq!(serde_json::to_value(&request).unwrap(), body);
831 let mut claimed = body;
832 claimed["reviewed"] = json!(true);
833 assert!(serde_json::from_value::<ConfigControlRequest>(claimed).is_err());
834 }
835 assert!(
836 serde_json::from_value::<ConfigControlRequest>(json!({"op":"config.apply"})).is_err()
837 );
838 }
839
840 #[test]
841 fn config_wire_plan_view_and_status_tolerate_reply_extensions() {
842 let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
843 let view = ConfigPlanView::new(plan.clone()).unwrap();
844 assert_eq!(view.digest, plan.digest().unwrap());
845 let response = ConfigControlResponse::Stamp { view };
846 let mut body = serde_json::to_value(&response).unwrap();
847 body["future"] = json!(true);
848 assert_eq!(
849 serde_json::from_value::<ConfigControlResponse>(body).unwrap(),
850 response
851 );
852 let status = ConfigControlResponse::Status {
853 status: ConfigStatus::default(),
854 };
855 assert_eq!(
856 serde_json::from_value::<ConfigControlResponse>(serde_json::to_value(&status).unwrap())
857 .unwrap(),
858 status
859 );
860 }
861
862 #[test]
863 fn config_wire_edit_actions_are_exclusive_and_null_is_not_absence() {
864 let base = json!({"module_id":"demo","layer":"user","path":"/limit"});
865 for action in [
866 json!({"set":0}),
867 json!({"set":false}),
868 json!({"set":null}),
869 json!({"remove":true}),
870 ] {
871 let mut value = base.clone();
872 value
873 .as_object_mut()
874 .unwrap()
875 .extend(action.as_object().unwrap().clone());
876 let edit: ConfigEdit = serde_json::from_value(value.clone()).unwrap();
877 assert_eq!(serde_json::to_value(edit).unwrap(), value);
878 }
879 for action in [
880 json!({}),
881 json!({"set":1,"remove":true}),
882 json!({"remove":false}),
883 json!({"remove":true,"extra":1}),
884 ] {
885 let mut value = base.clone();
886 value
887 .as_object_mut()
888 .unwrap()
889 .extend(action.as_object().unwrap().clone());
890 assert!(serde_json::from_value::<ConfigEdit>(value).is_err());
891 }
892 let request: ConfigControlRequest =
893 serde_json::from_value(json!({"op":"config.plan"})).unwrap();
894 assert_eq!(
895 serde_json::to_vec(&request).unwrap(),
896 br#"{"op":"config.plan"}"#
897 );
898 }
899
900 #[test]
901 fn config_wire_empty_refusals_preserve_legacy_view_bytes() {
902 let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
903 let view = ConfigPlanView::new(plan.clone()).unwrap();
904 let legacy = json!({"digest":plan.digest().unwrap(),"base_revision":7,"plan":plan});
905 assert_eq!(serde_json::to_value(&view).unwrap(), legacy);
906 assert_eq!(
907 serde_json::from_value::<ConfigPlanView>(legacy).unwrap(),
908 view
909 );
910 assert_eq!(
911 serde_json::to_string(&ConfigControlResponse::PlanDiscard {}).unwrap(),
912 r#"{"op":"config.plan_discard"}"#
913 );
914 }
915}