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 pub generation: u64,
236 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub attempt: Option<u64>,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub project_id: Option<String>,
240 pub effective: Value,
241 pub sources: BTreeMap<String, Layer>,
243 pub layers: Vec<ConfigLayerSnapshot>,
244 pub status: ConfigStatus,
245}
246impl ConfigView {
247 pub fn new(
248 generation: u64,
249 effective: Value,
250 sources: BTreeMap<String, Layer>,
251 layers: Vec<ConfigLayerSnapshot>,
252 status: ConfigStatus,
253 ) -> Self {
254 Self {
255 generation,
256 attempt: None,
257 project_id: None,
258 effective,
259 sources,
260 layers,
261 status,
262 }
263 }
264}
265
266#[non_exhaustive]
272#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
273pub struct ConfigReviewRequest {
274 op: ReviewOp,
275 pub base_generation: u64,
276 pub layers: Vec<ConfigLayerSnapshot>,
277 pub base: Option<ConfigView>,
278}
279impl ConfigReviewRequest {
280 pub fn new(
281 base_generation: u64,
282 layers: Vec<ConfigLayerSnapshot>,
283 base: Option<ConfigView>,
284 ) -> Self {
285 Self {
286 op: ReviewOp::Op,
287 base_generation,
288 layers,
289 base,
290 }
291 }
292}
293
294#[non_exhaustive]
297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298pub struct ConfigReviewRefusal {
299 pub code: String,
300 pub paths: Vec<String>,
301 #[serde(default, skip_serializing_if = "Option::is_none")]
302 pub project_id: Option<String>,
303 pub reasons: Vec<String>,
304}
305impl ConfigReviewRefusal {
306 pub fn new(code: impl Into<String>, paths: Vec<String>, reasons: Vec<String>) -> Self {
307 Self {
308 code: code.into(),
309 paths,
310 project_id: None,
311 reasons,
312 }
313 }
314}
315
316#[non_exhaustive]
320#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
321pub struct ConfigReviewReply {
322 op: ReviewOp,
323 pub fields: Vec<FieldChange>,
324 pub refusals: Vec<ConfigReviewRefusal>,
325}
326impl ConfigReviewReply {
327 pub fn new(fields: Vec<FieldChange>, refusals: Vec<ConfigReviewRefusal>) -> Self {
328 Self {
329 op: ReviewOp::Op,
330 fields,
331 refusals,
332 }
333 }
334}
335
336#[non_exhaustive]
341#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
342pub struct ConfigDeclareRequest {
343 op: DeclareOp,
344 pub schema: Value,
345 pub user_file: String,
346 pub project_dirs: Vec<String>,
347}
348impl ConfigDeclareRequest {
349 pub fn new(schema: Value, user_file: impl Into<String>, project_dirs: Vec<String>) -> Self {
350 Self {
351 op: DeclareOp::Op,
352 schema,
353 user_file: user_file.into(),
354 project_dirs,
355 }
356 }
357}
358
359#[non_exhaustive]
362#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
363pub struct ConfigGetRequest {
364 op: GetOp,
365 #[serde(default, skip_serializing_if = "Option::is_none")]
366 pub project_id: Option<String>,
367 #[serde(default, skip_serializing_if = "Option::is_none")]
368 pub generation: Option<u64>,
369 #[serde(default, skip_serializing_if = "Option::is_none")]
370 pub attempt: Option<u64>,
371}
372impl ConfigGetRequest {
373 pub fn new() -> Self {
374 Self {
375 op: GetOp::Op,
376 project_id: None,
377 generation: None,
378 attempt: None,
379 }
380 }
381}
382impl Default for ConfigGetRequest {
383 fn default() -> Self {
384 Self::new()
385 }
386}
387
388#[non_exhaustive]
393#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
394pub struct ConfigGetReply {
395 op: GetOp,
396 pub active: Option<ConfigView>,
397 #[serde(default, skip_serializing_if = "Option::is_none")]
398 pub pending: Option<ConfigView>,
399}
400impl ConfigGetReply {
401 pub fn new(active: Option<ConfigView>, pending: Option<ConfigView>) -> Self {
402 Self {
403 op: GetOp::Op,
404 active,
405 pending,
406 }
407 }
408}
409
410#[non_exhaustive]
414#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
415pub struct ConfigAppliedRequest {
416 op: AppliedOp,
417 pub generation: u64,
418 pub attempt: u64,
419 #[serde(default, skip_serializing_if = "Option::is_none")]
420 pub project_id: Option<String>,
421 pub result: ConfigApplyResult,
422 pub reasons: Vec<String>,
423}
424impl ConfigAppliedRequest {
425 pub fn new(
426 generation: u64,
427 attempt: u64,
428 result: ConfigApplyResult,
429 reasons: Vec<String>,
430 ) -> Self {
431 Self {
432 op: AppliedOp::Op,
433 generation,
434 attempt,
435 project_id: None,
436 result,
437 reasons,
438 }
439 }
440}
441
442#[non_exhaustive]
445#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
446pub struct ConfigChanged {
447 op: ChangedOp,
448 pub generation: u64,
449 #[serde(default, skip_serializing_if = "Option::is_none")]
450 pub project_id: Option<String>,
451 pub fields: Vec<String>,
453}
454impl ConfigChanged {
455 pub fn new(generation: u64, fields: Vec<String>) -> Self {
456 Self {
457 op: ChangedOp::Op,
458 generation,
459 project_id: None,
460 fields,
461 }
462 }
463}
464
465macro_rules! empty_reply {
466 ($(#[$meta:meta])* $name:ident, $tag:ident) => {
467 $(#[$meta])*
468 #[non_exhaustive]
469 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
470 pub struct $name { op: $tag }
471 impl $name { pub fn new() -> Self { Self { op: $tag::Op } } }
472 impl Default for $name { fn default() -> Self { Self::new() } }
473 };
474}
475empty_reply! {
476 ConfigDeclareReply, DeclareOp
478}
479empty_reply! {
480 ConfigAppliedReply, AppliedOp
482}