1use std::collections::BTreeMap;
14
15use base64::{engine::general_purpose::STANDARD, Engine as _};
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18pub use subc_config::{Digest, FieldChange, Layer};
19
20pub const CONFIG_GATE_CAPABILITY: &str = "config.gate";
21pub const CONFIG_REVIEW_OP: &str = "config.review";
22pub const CONFIG_DECLARE_OP: &str = "config.declare";
23pub const CONFIG_GET_OP: &str = "config.get";
24pub const CONFIG_APPLIED_OP: &str = "config.applied";
25pub const CONFIG_CHANGED_OP: &str = "config.changed";
26
27macro_rules! op_tag {
28 ($name:ident, $wire:literal) => {
29 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30 enum $name {
31 #[serde(rename = $wire)]
32 Op,
33 }
34 };
35}
36op_tag!(ReviewOp, "config.review");
37op_tag!(DeclareOp, "config.declare");
38op_tag!(GetOp, "config.get");
39op_tag!(AppliedOp, "config.applied");
40op_tag!(ChangedOp, "config.changed");
41
42macro_rules! open_string_enum {
43 ($(#[$meta:meta])* $name:ident { $($variant:ident => $wire:literal),+ $(,)? }) => {
44 $(#[$meta])*
45 #[non_exhaustive]
46 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47 #[serde(from = "String", into = "String")]
48 pub enum $name {
49 $($variant,)+
50 Unknown(String),
52 }
53 impl $name {
54 pub fn as_str(&self) -> &str {
55 match self {
56 $(Self::$variant => $wire,)+
57 Self::Unknown(value) => value,
58 }
59 }
60 }
61 impl From<String> for $name {
62 fn from(value: String) -> Self {
63 match value.as_str() {
64 $($wire => Self::$variant,)+
65 _ => Self::Unknown(value),
66 }
67 }
68 }
69 impl From<$name> for String {
70 fn from(value: $name) -> Self { value.as_str().to_owned() }
71 }
72 };
73}
74pub(crate) use open_string_enum;
75
76open_string_enum! {
77 ConfigLayer {
79 Default => "default", User => "user", Workspace => "workspace", Project => "project"
80 }
81}
82impl ConfigLayer {
83 pub fn known_layer(&self) -> Option<Layer> {
84 match self {
85 Self::Default => Some(Layer::Default),
86 Self::User => Some(Layer::User),
87 Self::Workspace => Some(Layer::Workspace),
88 Self::Project => Some(Layer::Project),
89 Self::Unknown(_) => None,
90 }
91 }
92}
93
94open_string_enum! {
95 ConfigStatus {
97 Unstamped => "unstamped", Pending => "pending", Active => "active",
98 Failed => "failed", Gated => "gated"
99 }
100}
101impl ConfigStatus {
102 pub fn is_active(&self) -> bool {
103 matches!(self, Self::Active)
104 }
105}
106
107open_string_enum! {
108 ConfigApplyResult { Ack => "ack", Nack => "nack" }
110}
111impl ConfigApplyResult {
112 pub fn is_ack(&self) -> bool {
114 matches!(self, Self::Ack)
115 }
116}
117
118#[non_exhaustive]
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127#[serde(try_from = "SnapshotWire")]
128pub struct ConfigLayerSnapshot {
129 pub module_id: String,
130 #[serde(skip_serializing_if = "Option::is_none")]
131 pub project_id: Option<String>,
132 #[serde(skip_serializing_if = "Option::is_none")]
133 pub workspace_id: Option<String>,
134 pub layer: ConfigLayer,
135 #[serde(skip_serializing_if = "Option::is_none")]
136 pub path: Option<String>,
137 #[serde(skip_serializing_if = "Option::is_none")]
138 pub proposal_id: Option<String>,
139 #[serde(
140 serialize_with = "serialize_bytes",
141 skip_serializing_if = "Option::is_none"
142 )]
143 pub bytes: Option<Vec<u8>>,
144 #[serde(skip_serializing_if = "Option::is_none")]
145 pub digest: Option<Digest>,
146}
147
148impl ConfigLayerSnapshot {
149 pub fn file(
151 module_id: impl Into<String>,
152 layer: ConfigLayer,
153 path: impl Into<String>,
154 bytes: Option<Vec<u8>>,
155 ) -> Self {
156 let digest = bytes.as_deref().map(subc_config::raw_digest);
157 Self {
158 module_id: module_id.into(),
159 project_id: None,
160 workspace_id: None,
161 layer,
162 path: Some(path.into()),
163 proposal_id: None,
164 bytes,
165 digest,
166 }
167 }
168}
169
170fn serialize_bytes<S: serde::Serializer>(
171 bytes: &Option<Vec<u8>>,
172 serializer: S,
173) -> Result<S::Ok, S::Error> {
174 bytes
175 .as_ref()
176 .map(|bytes| STANDARD.encode(bytes))
177 .serialize(serializer)
178}
179
180#[derive(Deserialize)]
181struct SnapshotWire {
182 module_id: String,
183 project_id: Option<String>,
184 workspace_id: Option<String>,
185 layer: ConfigLayer,
186 path: Option<String>,
187 proposal_id: Option<String>,
188 bytes: Option<String>,
189 digest: Option<Digest>,
190}
191
192impl TryFrom<SnapshotWire> for ConfigLayerSnapshot {
193 type Error = String;
194 fn try_from(wire: SnapshotWire) -> Result<Self, Self::Error> {
195 let bytes = wire
196 .bytes
197 .map(|encoded| {
198 let bytes = STANDARD
199 .decode(&encoded)
200 .map_err(|_| "bytes: invalid canonical base64")?;
201 if STANDARD.encode(&bytes) != encoded {
202 return Err("bytes: non-canonical base64");
203 }
204 Ok(bytes)
205 })
206 .transpose()
207 .map_err(str::to_owned)?;
208 match (&bytes, &wire.digest) {
209 (Some(bytes), Some(digest)) if subc_config::raw_digest(bytes) != *digest => {
210 return Err("digest: does not match bytes".into())
211 }
212 (Some(_), None) => return Err("digest: required with bytes".into()),
213 (None, Some(_)) => return Err("bytes: required with digest".into()),
214 _ => {}
215 }
216 Ok(Self {
217 module_id: wire.module_id,
218 project_id: wire.project_id,
219 workspace_id: wire.workspace_id,
220 layer: wire.layer,
221 path: wire.path,
222 proposal_id: wire.proposal_id,
223 bytes,
224 digest: wire.digest,
225 })
226 }
227}
228
229#[non_exhaustive]
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234pub struct ConfigView {
235 #[serde(skip)]
238 pub declaration_pending: Option<ConfigDeclarationPending>,
239 pub generation: u64,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub attempt: Option<u64>,
242 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub project_id: Option<String>,
244 pub effective: Value,
245 pub sources: BTreeMap<String, Layer>,
247 pub layers: Vec<ConfigLayerSnapshot>,
248 pub status: ConfigStatus,
249}
250impl ConfigView {
251 pub fn new(
252 generation: u64,
253 effective: Value,
254 sources: BTreeMap<String, Layer>,
255 layers: Vec<ConfigLayerSnapshot>,
256 status: ConfigStatus,
257 ) -> Self {
258 Self {
259 generation,
260 declaration_pending: None,
261 attempt: None,
262 project_id: None,
263 effective,
264 sources,
265 layers,
266 status,
267 }
268 }
269}
270
271#[non_exhaustive]
277#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
278pub struct ConfigReviewRequest {
279 op: ReviewOp,
280 pub base_generation: u64,
281 pub layers: Vec<ConfigLayerSnapshot>,
282 pub base: Option<ConfigView>,
283}
284impl ConfigReviewRequest {
285 pub fn new(
286 base_generation: u64,
287 layers: Vec<ConfigLayerSnapshot>,
288 base: Option<ConfigView>,
289 ) -> Self {
290 Self {
291 op: ReviewOp::Op,
292 base_generation,
293 layers,
294 base,
295 }
296 }
297}
298
299#[non_exhaustive]
302#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
303pub struct ConfigReviewRefusal {
304 pub code: String,
305 pub paths: Vec<String>,
306 #[serde(default, skip_serializing_if = "Option::is_none")]
307 pub project_id: Option<String>,
308 pub reasons: Vec<String>,
309}
310impl ConfigReviewRefusal {
311 pub fn new(code: impl Into<String>, paths: Vec<String>, reasons: Vec<String>) -> Self {
312 Self {
313 code: code.into(),
314 paths,
315 project_id: None,
316 reasons,
317 }
318 }
319}
320
321#[non_exhaustive]
325#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
326pub struct ConfigReviewReply {
327 op: ReviewOp,
328 pub fields: Vec<FieldChange>,
329 pub refusals: Vec<ConfigReviewRefusal>,
330}
331impl ConfigReviewReply {
332 pub fn new(fields: Vec<FieldChange>, refusals: Vec<ConfigReviewRefusal>) -> Self {
333 Self {
334 op: ReviewOp::Op,
335 fields,
336 refusals,
337 }
338 }
339}
340
341#[non_exhaustive]
346#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
347pub struct ConfigDeclareRequest {
348 op: DeclareOp,
349 pub schema: Value,
350 pub user_file: String,
351 pub project_dirs: Vec<String>,
352}
353impl ConfigDeclareRequest {
354 pub fn new(schema: Value, user_file: impl Into<String>, project_dirs: Vec<String>) -> Self {
355 Self {
356 op: DeclareOp::Op,
357 schema,
358 user_file: user_file.into(),
359 project_dirs,
360 }
361 }
362}
363
364#[non_exhaustive]
367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
368pub struct ConfigGetRequest {
369 op: GetOp,
370 #[serde(default, skip_serializing_if = "Option::is_none")]
371 pub project_id: Option<String>,
372 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub generation: Option<u64>,
374 #[serde(default, skip_serializing_if = "Option::is_none")]
375 pub attempt: Option<u64>,
376}
377impl ConfigGetRequest {
378 pub fn new() -> Self {
379 Self {
380 op: GetOp::Op,
381 project_id: None,
382 generation: None,
383 attempt: None,
384 }
385 }
386}
387impl Default for ConfigGetRequest {
388 fn default() -> Self {
389 Self::new()
390 }
391}
392
393#[non_exhaustive]
400#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
401pub struct ConfigGetReply {
402 #[serde(default, skip_serializing_if = "Option::is_none")]
403 pub declaration_pending: Option<ConfigDeclarationPending>,
404 op: GetOp,
405 pub active: Option<ConfigView>,
406 #[serde(default, skip_serializing_if = "Option::is_none")]
407 pub pending: Option<ConfigView>,
408}
409impl ConfigGetReply {
410 pub fn new(active: Option<ConfigView>, pending: Option<ConfigView>) -> Self {
411 Self {
412 declaration_pending: None,
413 op: GetOp::Op,
414 active,
415 pending,
416 }
417 }
418}
419
420#[non_exhaustive]
423#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
424pub struct ConfigDeclarationPending {
425 #[serde(default, skip_serializing_if = "Option::is_none")]
426 pub plan_digest: Option<subc_config::Digest>,
427}
428
429#[non_exhaustive]
433#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
434pub struct ConfigAppliedRequest {
435 op: AppliedOp,
436 pub generation: u64,
437 pub attempt: u64,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
439 pub project_id: Option<String>,
440 pub result: ConfigApplyResult,
441 pub reasons: Vec<String>,
442}
443impl ConfigAppliedRequest {
444 pub fn new(
445 generation: u64,
446 attempt: u64,
447 result: ConfigApplyResult,
448 reasons: Vec<String>,
449 ) -> Self {
450 Self {
451 op: AppliedOp::Op,
452 generation,
453 attempt,
454 project_id: None,
455 result,
456 reasons,
457 }
458 }
459}
460
461#[non_exhaustive]
464#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
465pub struct ConfigChanged {
466 op: ChangedOp,
467 pub generation: u64,
468 #[serde(default, skip_serializing_if = "Option::is_none")]
469 pub project_id: Option<String>,
470 pub fields: Vec<String>,
472}
473impl ConfigChanged {
474 pub fn new(generation: u64, fields: Vec<String>) -> Self {
475 Self {
476 op: ChangedOp::Op,
477 generation,
478 project_id: None,
479 fields,
480 }
481 }
482}
483
484macro_rules! empty_reply {
485 ($(#[$meta:meta])* $name:ident, $tag:ident) => {
486 $(#[$meta])*
487 #[non_exhaustive]
488 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
489 pub struct $name { op: $tag }
490 impl $name { pub fn new() -> Self { Self { op: $tag::Op } } }
491 impl Default for $name { fn default() -> Self { Self::new() } }
492 };
493}
494empty_reply! {
495 ConfigDeclareReply, DeclareOp
497}
498empty_reply! {
499 ConfigAppliedReply, AppliedOp
501}