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]
270#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
271pub struct ConfigReviewRequest {
272 op: ReviewOp,
273 pub base_generation: u64,
274 pub layers: Vec<ConfigLayerSnapshot>,
275 pub base: Option<ConfigView>,
276}
277impl ConfigReviewRequest {
278 pub fn new(
279 base_generation: u64,
280 layers: Vec<ConfigLayerSnapshot>,
281 base: Option<ConfigView>,
282 ) -> Self {
283 Self {
284 op: ReviewOp::Op,
285 base_generation,
286 layers,
287 base,
288 }
289 }
290}
291
292#[non_exhaustive]
295#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
296pub struct ConfigReviewRefusal {
297 pub code: String,
298 pub paths: Vec<String>,
299 #[serde(default, skip_serializing_if = "Option::is_none")]
300 pub project_id: Option<String>,
301 pub reasons: Vec<String>,
302}
303impl ConfigReviewRefusal {
304 pub fn new(code: impl Into<String>, paths: Vec<String>, reasons: Vec<String>) -> Self {
305 Self {
306 code: code.into(),
307 paths,
308 project_id: None,
309 reasons,
310 }
311 }
312}
313
314#[non_exhaustive]
318#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
319pub struct ConfigReviewReply {
320 op: ReviewOp,
321 pub fields: Vec<FieldChange>,
322 pub refusals: Vec<ConfigReviewRefusal>,
323}
324impl ConfigReviewReply {
325 pub fn new(fields: Vec<FieldChange>, refusals: Vec<ConfigReviewRefusal>) -> Self {
326 Self {
327 op: ReviewOp::Op,
328 fields,
329 refusals,
330 }
331 }
332}
333
334#[non_exhaustive]
339#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
340pub struct ConfigDeclareRequest {
341 op: DeclareOp,
342 pub schema: Value,
343 pub user_file: String,
344 pub project_dirs: Vec<String>,
345}
346impl ConfigDeclareRequest {
347 pub fn new(schema: Value, user_file: impl Into<String>, project_dirs: Vec<String>) -> Self {
348 Self {
349 op: DeclareOp::Op,
350 schema,
351 user_file: user_file.into(),
352 project_dirs,
353 }
354 }
355}
356
357#[non_exhaustive]
360#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
361pub struct ConfigGetRequest {
362 op: GetOp,
363 #[serde(default, skip_serializing_if = "Option::is_none")]
364 pub project_id: Option<String>,
365 #[serde(default, skip_serializing_if = "Option::is_none")]
366 pub generation: Option<u64>,
367 #[serde(default, skip_serializing_if = "Option::is_none")]
368 pub attempt: Option<u64>,
369}
370impl ConfigGetRequest {
371 pub fn new() -> Self {
372 Self {
373 op: GetOp::Op,
374 project_id: None,
375 generation: None,
376 attempt: None,
377 }
378 }
379}
380impl Default for ConfigGetRequest {
381 fn default() -> Self {
382 Self::new()
383 }
384}
385
386#[non_exhaustive]
391#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
392pub struct ConfigGetReply {
393 op: GetOp,
394 pub active: Option<ConfigView>,
395 #[serde(default, skip_serializing_if = "Option::is_none")]
396 pub pending: Option<ConfigView>,
397}
398impl ConfigGetReply {
399 pub fn new(active: Option<ConfigView>, pending: Option<ConfigView>) -> Self {
400 Self {
401 op: GetOp::Op,
402 active,
403 pending,
404 }
405 }
406}
407
408#[non_exhaustive]
412#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
413pub struct ConfigAppliedRequest {
414 op: AppliedOp,
415 pub generation: u64,
416 pub attempt: u64,
417 #[serde(default, skip_serializing_if = "Option::is_none")]
418 pub project_id: Option<String>,
419 pub result: ConfigApplyResult,
420 pub reasons: Vec<String>,
421}
422impl ConfigAppliedRequest {
423 pub fn new(
424 generation: u64,
425 attempt: u64,
426 result: ConfigApplyResult,
427 reasons: Vec<String>,
428 ) -> Self {
429 Self {
430 op: AppliedOp::Op,
431 generation,
432 attempt,
433 project_id: None,
434 result,
435 reasons,
436 }
437 }
438}
439
440#[non_exhaustive]
443#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
444pub struct ConfigChanged {
445 op: ChangedOp,
446 pub generation: u64,
447 #[serde(default, skip_serializing_if = "Option::is_none")]
448 pub project_id: Option<String>,
449 pub fields: Vec<String>,
451}
452impl ConfigChanged {
453 pub fn new(generation: u64, fields: Vec<String>) -> Self {
454 Self {
455 op: ChangedOp::Op,
456 generation,
457 project_id: None,
458 fields,
459 }
460 }
461}
462
463macro_rules! empty_reply {
464 ($(#[$meta:meta])* $name:ident, $tag:ident) => {
465 $(#[$meta])*
466 #[non_exhaustive]
467 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
468 pub struct $name { op: $tag }
469 impl $name { pub fn new() -> Self { Self { op: $tag::Op } } }
470 impl Default for $name { fn default() -> Self { Self::new() } }
471 };
472}
473empty_reply! {
474 ConfigDeclareReply, DeclareOp
476}
477empty_reply! {
478 ConfigAppliedReply, AppliedOp
480}