1use std::collections::{BTreeMap, BTreeSet};
11
12use serde::{Deserialize, Serialize};
13
14use super::error::DefError;
15use crate::types::{DnsName, HttpStatus};
16
17#[derive(Debug, Clone, Deserialize, Serialize)]
20#[serde(deny_unknown_fields)]
21pub struct StackDef {
22 pub stack: Stack,
23 #[serde(default)]
24 pub secrets: SecretsSpec,
25 #[serde(default, alias = "resources")]
26 pub integrations: BTreeMap<String, Integration>,
27 #[serde(default, alias = "workloads")]
28 pub services: BTreeMap<String, Service>,
29 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
30 pub jobs: BTreeMap<String, Service>,
31 #[serde(default)]
32 pub endpoints: BTreeMap<String, Endpoint>,
33 #[serde(skip)]
38 pub legacy_datastores: BTreeSet<String>,
39}
40
41#[derive(Debug, Clone, Deserialize, Serialize)]
42pub struct Stack {
43 pub name: DnsName,
44 #[serde(default)]
45 pub projects: ProjectsSpec,
46 pub verify: Option<VerifyRoot>,
47 #[serde(flatten)]
50 pub substrates: BTreeMap<String, toml::Value>,
51}
52
53#[derive(Debug, Clone, Default, Deserialize, Serialize)]
54#[serde(deny_unknown_fields)]
55pub struct ProjectsSpec {
56 pub stripe: Option<StripeProjectSpec>,
57}
58
59#[derive(Debug, Clone, Deserialize, Serialize)]
60#[serde(deny_unknown_fields)]
61pub struct StripeProjectSpec {
62 pub project: Option<String>,
63}
64
65#[derive(Debug, Clone, Deserialize, Serialize)]
67#[serde(deny_unknown_fields)]
68pub struct VerifySpec {
69 pub run: String,
70 #[serde(default)]
71 pub env: BTreeMap<String, String>,
72 #[serde(default = "default_job_timeout")]
73 pub timeout_secs: u64,
74}
75
76#[derive(Debug, Clone, Deserialize, Serialize)]
78#[serde(deny_unknown_fields)]
79pub struct VerifyRoot {
80 pub run: Option<String>,
81 #[serde(default)]
82 pub env: BTreeMap<String, String>,
83 #[serde(default = "default_job_timeout")]
84 pub timeout_secs: u64,
85 #[serde(default)]
86 pub tiers: BTreeMap<String, VerifySpec>,
87}
88
89impl Default for VerifyRoot {
90 fn default() -> Self {
91 Self {
92 run: None,
93 env: BTreeMap::new(),
94 timeout_secs: default_job_timeout(),
95 tiers: BTreeMap::new(),
96 }
97 }
98}
99
100impl VerifyRoot {
101 pub fn is_declared(&self) -> bool {
102 self.run.is_some() || !self.tiers.is_empty()
103 }
104
105 pub fn resolve(&self, tier: Option<&str>) -> Option<VerifySpec> {
106 match tier {
107 None | Some("default") => self.run.as_ref().map(|run| VerifySpec {
108 run: run.clone(),
109 env: self.env.clone(),
110 timeout_secs: self.timeout_secs,
111 }),
112 Some(name) => self.tiers.get(name).cloned(),
113 }
114 }
115}
116
117#[derive(Debug, Clone, Default, Deserialize, Serialize)]
118#[serde(deny_unknown_fields)]
119pub struct SecretsSpec {
120 #[serde(default)]
121 pub required: Vec<String>,
122}
123
124#[derive(Debug, Clone, Deserialize, Serialize)]
125pub struct Integration {
126 pub provider: String,
128 pub on: Option<String>,
130 #[serde(flatten)]
134 pub fields: BTreeMap<String, toml::Value>,
135}
136
137impl Integration {
138 pub fn config_fields(&self, known_substrates: &[&str]) -> BTreeMap<String, toml::Value> {
142 self.fields
143 .iter()
144 .filter(|(key, _)| !known_substrates.contains(&key.as_str()))
145 .map(|(key, value)| (key.clone(), value.clone()))
146 .collect()
147 }
148
149 pub fn host_block(&self, host: &str) -> Option<&toml::Table> {
150 self.fields.get(host).and_then(toml::Value::as_table)
151 }
152
153 pub fn effective_config(
155 &self,
156 host: &str,
157 known_substrates: &[&str],
158 ) -> BTreeMap<String, toml::Value> {
159 let mut out = self.config_fields(known_substrates);
160 if let Some(override_table) = self.host_block(host) {
161 for (key, value) in override_table {
162 out.insert(key.clone(), value.clone());
163 }
164 }
165 out
166 }
167
168 pub fn host_blocks(&self, known_substrates: &[&str]) -> BTreeMap<String, &toml::Table> {
170 self.fields
171 .iter()
172 .filter_map(|(key, value)| {
173 if !known_substrates.contains(&key.as_str()) {
174 return None;
175 }
176 Some((key.clone(), value.as_table()?))
177 })
178 .collect()
179 }
180}
181
182#[derive(Debug, Clone, Deserialize, Serialize)]
183pub struct Service {
184 pub image: Option<String>,
186 #[serde(default)]
187 pub source: Source,
188 #[serde(default)]
189 pub kind: WorkloadKind,
190 pub run: Option<String>,
191 pub on: Option<String>,
192 #[serde(default)]
193 pub depends_on: BTreeMap<String, DependencyCondition>,
194 #[serde(default = "default_job_timeout")]
195 pub timeout_secs: u64,
196 pub setup: Option<String>,
198 pub prepare: Option<String>,
200 #[serde(default)]
202 pub secrets: Vec<String>,
203 #[serde(default)]
204 pub env: BTreeMap<String, String>,
205 pub health: Option<Health>,
207 #[serde(default)]
209 pub root_origin: bool,
210 #[serde(flatten)]
212 pub substrates: BTreeMap<String, toml::Value>,
213}
214
215#[derive(Debug, Clone, Deserialize, Serialize)]
217#[serde(deny_unknown_fields)]
218pub struct Source {
219 #[serde(default)]
220 pub repo: String,
221 #[serde(rename = "ref", default = "default_source_ref")]
222 pub reference: String,
223 pub path: Option<String>,
224 pub root: Option<String>,
225}
226
227impl Default for Source {
228 fn default() -> Self {
229 Self {
230 repo: String::new(),
231 reference: default_source_ref(),
232 path: None,
233 root: None,
234 }
235 }
236}
237
238fn default_source_ref() -> String {
239 "HEAD".into()
240}
241fn default_job_timeout() -> u64 {
242 300
243}
244
245#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
246#[serde(rename_all = "snake_case")]
247pub enum WorkloadKind {
248 #[default]
249 Service,
250 Worker,
251 Job,
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
255#[serde(rename_all = "snake_case")]
256pub enum DependencyCondition {
257 Started,
258 Ready,
259 Completed,
260}
261
262#[derive(Debug, Clone, Deserialize, Serialize)]
263#[serde(deny_unknown_fields)]
264pub struct Endpoint {
265 pub workload: String,
266 pub url: Option<String>,
268}
269
270#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
271#[serde(rename_all = "snake_case")]
272pub enum EndpointSource {
273 Provider,
274 Declared,
275}
276
277#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
279pub struct ResolvedEndpoint {
280 pub workload: String,
281 pub url: String,
282 pub source: EndpointSource,
283}
284
285impl StackDef {
286 pub fn resolve_endpoints(
287 &self,
288 origins: &BTreeMap<String, String>,
289 ) -> BTreeMap<String, ResolvedEndpoint> {
290 self.endpoints
291 .iter()
292 .filter_map(|(name, endpoint)| {
293 let (url, source) = if let Some(url) = &endpoint.url {
294 (url, EndpointSource::Declared)
295 } else {
296 (origins.get(&endpoint.workload)?, EndpointSource::Provider)
297 };
298 (!url.is_empty()).then(|| {
299 (
300 name.clone(),
301 ResolvedEndpoint {
302 workload: endpoint.workload.clone(),
303 url: url.clone(),
304 source,
305 },
306 )
307 })
308 })
309 .collect()
310 }
311}
312
313#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
314#[serde(rename_all = "snake_case")]
315pub enum HealthProtocol {
316 #[default]
317 Http,
318 Tcp,
319}
320
321impl HealthProtocol {
322 fn is_http(&self) -> bool {
323 *self == Self::Http
324 }
325}
326
327#[derive(Debug, Clone, Deserialize, Serialize)]
329#[serde(deny_unknown_fields)]
330pub struct Health {
331 #[serde(default, skip_serializing_if = "HealthProtocol::is_http")]
332 pub protocol: HealthProtocol,
333 #[serde(default)]
334 pub path: String,
335 #[serde(default = "default_health_status")]
336 pub status: HttpStatus,
337 pub contains: Option<String>,
338}
339
340impl Health {
341 pub fn is_tcp(&self) -> bool {
342 self.protocol == HealthProtocol::Tcp
343 }
344
345 pub fn validate(&self, workload: &str) -> Result<(), DefError> {
346 let invalid = if self.is_tcp() {
347 !self.path.is_empty() || self.status != HttpStatus::OK || self.contains.is_some()
348 } else {
349 !self.path.starts_with('/') || self.path.chars().any(char::is_control)
350 };
351 if invalid {
352 return Err(DefError::Schema {
353 message: format!(
354 "services.{workload}.health requires an HTTP path starting with /, or protocol = 'tcp' without HTTP assertions"
355 ),
356 });
357 }
358 Ok(())
359 }
360}
361
362fn default_health_status() -> HttpStatus {
363 HttpStatus::OK
364}
365
366impl Service {
367 pub fn source_root(&self, service: &str, provider: &str) -> Result<Option<String>, DefError> {
369 let normalize = |raw: &str, location: &str| -> Result<String, DefError> {
370 use std::path::Component;
371 let invalid = || DefError::Schema {
372 message: format!(
373 "{location} must name a relative directory inside the source tree"
374 ),
375 };
376 if raw.trim().is_empty() || raw.contains('\\') || raw.chars().any(char::is_control) {
377 return Err(invalid());
378 }
379 let mut parts = Vec::new();
380 for part in std::path::Path::new(raw).components() {
381 match part {
382 Component::CurDir => (),
383 Component::Normal(part) => {
384 let part = part.to_str().ok_or_else(invalid)?;
385 if crate::source_archive::excluded(part) {
386 return Err(invalid());
387 }
388 parts.push(part);
389 }
390 _ => return Err(invalid()),
391 }
392 }
393 Ok(if parts.is_empty() {
394 ".".into()
395 } else {
396 parts.join("/")
397 })
398 };
399 let common = self
400 .source
401 .root
402 .as_deref()
403 .map(|root| normalize(root, &format!("services.{service}.source.root")))
404 .transpose()?;
405 let provider_root = self
406 .substrates
407 .get(provider)
408 .and_then(|block| block.get("root"))
409 .map(|root| {
410 let location = format!("services.{service}.{provider}.root");
411 let root = root.as_str().ok_or_else(|| DefError::Schema {
412 message: format!("{location} must be a string"),
413 })?;
414 normalize(root, &location)
415 })
416 .transpose()?;
417 if common
418 .as_ref()
419 .zip(provider_root.as_ref())
420 .is_some_and(|(a, b)| a != b)
421 {
422 return Err(DefError::Schema {
423 message: format!(
424 "services.{service}.source.root conflicts with services.{service}.{provider}.root"
425 ),
426 });
427 }
428 Ok(common.or(provider_root))
429 }
430
431 pub fn substrate_env(
437 &self,
438 service_name: &str,
439 substrate: &str,
440 ) -> Result<BTreeMap<String, String>, DefError> {
441 let Some(block) = self.substrates.get(substrate) else {
442 return Ok(BTreeMap::new());
443 };
444 let location = format!("services.{service_name}.{substrate}.env");
445 let Some(table) = block.as_table() else {
446 return Ok(BTreeMap::new());
449 };
450 let Some(env) = table.get("env") else {
451 return Ok(BTreeMap::new());
452 };
453 let Some(env) = env.as_table() else {
454 return Err(DefError::EnvNotStrings { location });
455 };
456 let mut out = BTreeMap::new();
457 for (key, value) in env {
458 let Some(value) = value.as_str() else {
459 return Err(DefError::EnvNotStrings { location });
460 };
461 out.insert(key.clone(), value.to_owned());
462 }
463 Ok(out)
464 }
465
466 pub fn effective_env(
468 &self,
469 service_name: &str,
470 substrate: &str,
471 ) -> Result<BTreeMap<String, String>, DefError> {
472 let overlay = self.substrate_env(service_name, substrate)?;
473 if overlay.is_empty() {
474 return Ok(self.env.clone());
475 }
476 let mut env = self.env.clone();
477 env.extend(overlay);
478 Ok(env)
479 }
480}