Skip to main content

minco_plan/
model.rs

1use crate::{DYNAMODB_AUDIT_TABLE_ACTIONS, cost::CostClass, sam_logical_id};
2use minco_contract::{ContractDocument, HttpMethod};
3use minco_core::{ApplicationGraph, ResourceKind};
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(rename_all = "snake_case")]
9pub enum Severity {
10    Error,
11    Warning,
12    Information,
13}
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16pub struct PlanDiagnostic {
17    pub code: String,
18    pub severity: Severity,
19    pub message: String,
20}
21
22/// Environment-owned deployment inputs. HTTP routes are deliberately absent: they are
23/// derived from the canonical `OpenAPI` contract.
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25pub struct DeploymentConfig {
26    pub schema_version: u32,
27    pub application: String,
28    pub environment: String,
29    pub region: String,
30    pub runtime: RuntimePlan,
31    pub ingress: IngressPlan,
32    pub auth: AuthPlan,
33    pub database: DatabaseDeployment,
34    pub functions: Vec<FunctionPlan>,
35    #[serde(default)]
36    pub queues: Vec<QueuePlan>,
37    #[serde(default)]
38    pub triggers: Vec<TriggerPlan>,
39    #[serde(default)]
40    pub scheduled_wakeups: Vec<String>,
41    #[serde(default)]
42    pub uses_nat_gateway: bool,
43    pub allowed_origins: Vec<String>,
44    #[serde(default = "default_allowed_headers")]
45    pub allowed_headers: Vec<String>,
46    #[serde(default = "default_log_retention_days")]
47    pub log_retention_days: u32,
48    #[serde(default)]
49    pub cost_policy: CostPolicy,
50    #[serde(default)]
51    pub performance_policy: PerformancePolicy,
52}
53
54impl DeploymentConfig {
55    #[must_use]
56    pub fn into_plan(self, contract: &ContractDocument) -> DeploymentPlan {
57        self.into_plan_with_graph(contract, ApplicationGraph::default())
58    }
59
60    #[must_use]
61    pub fn into_plan_with_graph(
62        self,
63        contract: &ContractDocument,
64        application_graph: ApplicationGraph,
65    ) -> DeploymentPlan {
66        let routes = contract
67            .operations
68            .iter()
69            .map(|operation| RoutePlan {
70                operation_id: operation.operation_id.clone(),
71                method: operation.method,
72                path: operation.path.clone(),
73                authenticated: operation.authenticated,
74            })
75            .collect();
76        let local_aws_services = local_aws_services(
77            &self.runtime,
78            &self.database,
79            &application_graph,
80            &self.queues,
81        );
82        let iam_intents = derive_iam_intents(
83            self.schema_version,
84            &self.runtime,
85            &self.database,
86            &application_graph,
87            &self.functions,
88            &self.triggers,
89        );
90        let mut allowed_headers = self
91            .allowed_headers
92            .into_iter()
93            .map(|configured| match configured.parse::<http::HeaderName>() {
94                Ok(header) => header.as_str().to_owned(),
95                Err(_) => configured,
96            })
97            .collect::<Vec<_>>();
98        allowed_headers.sort();
99        DeploymentPlan {
100            schema_version: self.schema_version,
101            application: self.application,
102            environment: self.environment,
103            region: self.region,
104            runtime: self.runtime,
105            ingress: self.ingress,
106            auth: self.auth,
107            database: self.database,
108            functions: self.functions,
109            queues: self.queues,
110            triggers: self.triggers,
111            iam_intents,
112            routes,
113            application_graph,
114            static_site: None,
115            realtime: None,
116            preview: None,
117            local_aws_services,
118            scheduled_wakeups: self.scheduled_wakeups,
119            uses_nat_gateway: self.uses_nat_gateway,
120            allowed_origins: self.allowed_origins,
121            allowed_headers,
122            exposed_headers: default_exposed_headers(),
123            log_retention_days: self.log_retention_days,
124            cost_policy: self.cost_policy,
125            performance_policy: self.performance_policy,
126        }
127    }
128}
129
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
131pub struct DeploymentPlan {
132    pub schema_version: u32,
133    pub application: String,
134    pub environment: String,
135    pub region: String,
136    pub runtime: RuntimePlan,
137    pub ingress: IngressPlan,
138    pub auth: AuthPlan,
139    pub database: DatabaseDeployment,
140    pub functions: Vec<FunctionPlan>,
141    #[serde(default, skip_serializing_if = "Vec::is_empty")]
142    pub queues: Vec<QueuePlan>,
143    #[serde(default, skip_serializing_if = "Vec::is_empty")]
144    pub triggers: Vec<TriggerPlan>,
145    #[serde(default, skip_serializing_if = "Vec::is_empty")]
146    pub iam_intents: Vec<IamIntent>,
147    pub routes: Vec<RoutePlan>,
148    #[serde(default)]
149    pub application_graph: ApplicationGraph,
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub static_site: Option<StaticSiteDeployment>,
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub realtime: Option<RealtimeDeployment>,
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub preview: Option<PreviewLifecyclePlan>,
156    #[serde(default)]
157    pub local_aws_services: Vec<String>,
158    pub scheduled_wakeups: Vec<String>,
159    pub uses_nat_gateway: bool,
160    pub allowed_origins: Vec<String>,
161    pub allowed_headers: Vec<String>,
162    #[serde(default = "default_exposed_headers")]
163    pub exposed_headers: Vec<String>,
164    pub log_retention_days: u32,
165    pub cost_policy: CostPolicy,
166    pub performance_policy: PerformancePolicy,
167}
168
169impl DeploymentPlan {
170    /// Returns the deterministic, physically separate audit table required by
171    /// the selected audit ledger capability for a `DynamoDB` deployment.
172    #[must_use]
173    pub fn dynamodb_audit_table(&self) -> Option<DynamoDbTablePlan> {
174        derive_dynamodb_audit_table(&self.database, &self.application_graph)
175    }
176}
177
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(rename_all = "snake_case")]
180pub enum PreviewResourceRetention {
181    Delete,
182    Retain,
183}
184
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(deny_unknown_fields)]
187pub struct PreviewResource {
188    pub logical_id: String,
189    pub resource_type: String,
190    pub retention: PreviewResourceRetention,
191    pub idle_cost_class: CostClass,
192}
193
194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
195#[serde(deny_unknown_fields)]
196pub struct PreviewCleanupSchedule {
197    pub expression: String,
198    pub action_after_completion: ScheduleCompletionAction,
199    pub residual_resources: Vec<String>,
200    pub manual_fallback: String,
201}
202
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204#[serde(deny_unknown_fields)]
205pub struct PreviewLifecyclePlan {
206    pub owner: String,
207    pub ttl_seconds: u32,
208    pub expected_account_id: String,
209    pub expected_region: String,
210    pub resources: Vec<PreviewResource>,
211    pub pricing_complete: bool,
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub cleanup_schedule: Option<PreviewCleanupSchedule>,
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217#[serde(deny_unknown_fields)]
218pub struct StaticSiteDeployment {
219    pub source_directory: String,
220    pub index_document: String,
221    pub spa_fallback: bool,
222    pub immutable_cache_seconds: u32,
223    pub html_cache_seconds: u32,
224    pub price_class: String,
225    pub ipv6_enabled: bool,
226    pub custom_domain: Option<String>,
227    pub manage_dns_alias: bool,
228}
229
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(deny_unknown_fields)]
232pub struct RealtimeDeployment {
233    pub namespace: String,
234    pub max_event_bytes: usize,
235    pub subscriber_claim: String,
236}
237
238impl RealtimeDeployment {
239    pub(crate) fn is_valid(&self) -> bool {
240        (1..=50).contains(&self.namespace.len())
241            && self
242                .namespace
243                .bytes()
244                .next()
245                .is_some_and(|byte| byte.is_ascii_alphanumeric())
246            && self
247                .namespace
248                .bytes()
249                .next_back()
250                .is_some_and(|byte| byte.is_ascii_alphanumeric())
251            && self
252                .namespace
253                .bytes()
254                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
255            && (256..=240 * 1024).contains(&self.max_event_bytes)
256            && (1..=128).contains(&self.subscriber_claim.len())
257            && self.subscriber_claim.bytes().all(|byte| {
258                byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':' | b'/')
259            })
260    }
261}
262
263impl StaticSiteDeployment {
264    fn is_valid(&self) -> bool {
265        let safe_path = |value: &str| {
266            let path = std::path::Path::new(value);
267            !value.is_empty()
268                && !value.chars().any(char::is_control)
269                && !path.is_absolute()
270                && path
271                    .components()
272                    .all(|component| matches!(component, std::path::Component::Normal(_)))
273        };
274        let domain_valid = self.custom_domain.as_deref().is_none_or(|domain| {
275            domain.len() <= 253
276                && !domain.starts_with('.')
277                && !domain.ends_with('.')
278                && domain.split('.').count() >= 2
279                && domain.split('.').all(|label| {
280                    !label.is_empty()
281                        && label.len() <= 63
282                        && !label.starts_with('-')
283                        && !label.ends_with('-')
284                        && label.bytes().all(|byte| {
285                            byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-'
286                        })
287                })
288        });
289        safe_path(&self.source_directory)
290            && safe_path(&self.index_document)
291            && self.immutable_cache_seconds <= 31_536_000
292            && self.html_cache_seconds <= 86_400
293            && matches!(
294                self.price_class.as_str(),
295                "PriceClass_100" | "PriceClass_200" | "PriceClass_All"
296            )
297            && (!self.manage_dns_alias || self.custom_domain.is_some())
298            && domain_valid
299    }
300}
301
302pub fn local_aws_services(
303    runtime: &RuntimePlan,
304    database: &DatabaseDeployment,
305    graph: &ApplicationGraph,
306    queues: &[QueuePlan],
307) -> Vec<String> {
308    let mut services = std::collections::BTreeSet::new();
309    if matches!(runtime, RuntimePlan::LambdaZipArm64) {
310        services.insert("sts".to_owned());
311        if matches!(
312            database,
313            DatabaseDeployment::NeonPostgres { .. }
314                | DatabaseDeployment::SelfHostedPostgres { .. }
315                | DatabaseDeployment::RdsPostgres { .. }
316                | DatabaseDeployment::AuroraServerlessV2 { .. }
317        ) {
318            services.insert("ssm".to_owned());
319        }
320    }
321    if matches!(database, DatabaseDeployment::DynamoDbOnDemand { .. }) {
322        services.insert("dynamodb".into());
323    }
324    if !queues.is_empty() {
325        services.insert("sqs".into());
326    }
327    for resource in graph.resources.values() {
328        match resource.kind {
329            ResourceKind::S3Bucket => {
330                services.insert("s3".into());
331            }
332            ResourceKind::SqsQueue => {
333                services.insert("sqs".into());
334            }
335            ResourceKind::SsmParameter => {
336                services.insert("ssm".into());
337            }
338            ResourceKind::DynamoDb => {
339                services.insert("dynamodb".into());
340            }
341            ResourceKind::Custom(ref kind) if kind == "realtime-event-api" => {
342                services.insert("appsync".into());
343            }
344            _ => {}
345        }
346    }
347    services.into_iter().collect()
348}
349
350impl DeploymentPlan {
351    #[must_use]
352    pub fn http_api_function_id(&self) -> Option<&str> {
353        if self.schema_version == 1 {
354            return self
355                .functions
356                .first()
357                .map(|function| function.name.as_str());
358        }
359        self.triggers.iter().find_map(|trigger| {
360            let TriggerPlan::HttpApi { function_id, .. } = trigger else {
361                return None;
362            };
363            Some(function_id.as_str())
364        })
365    }
366
367    #[must_use]
368    pub fn http_api_trigger_id(&self) -> Option<&str> {
369        (self.schema_version == 2)
370            .then(|| {
371                self.triggers.iter().find_map(|trigger| {
372                    let TriggerPlan::HttpApi { id, .. } = trigger else {
373                        return None;
374                    };
375                    Some(id.as_str())
376                })
377            })
378            .flatten()
379    }
380
381    #[must_use]
382    pub fn operation_function_id(&self, operation_id: &str) -> Option<&str> {
383        self.routes
384            .iter()
385            .any(|route| route.operation_id == operation_id)
386            .then(|| self.http_api_function_id())
387            .flatten()
388    }
389
390    /// Converts the legacy API-only schema into the explicit trigger schema.
391    ///
392    /// Legacy scheduled strings cannot be migrated safely because they do not
393    /// identify a function or carry enablement and purpose, so they fail with
394    /// a stable rejection instead of being guessed.
395    pub fn migrate_to_latest(mut self) -> Result<Self, PlanError> {
396        match self.schema_version {
397            2 => Ok(self),
398            1 => {
399                if !self.queues.is_empty()
400                    || !self.triggers.is_empty()
401                    || !self.scheduled_wakeups.is_empty()
402                {
403                    return Err(PlanError::SchemaMigration(
404                        "MINCO-PLAN-MIGRATE-001: schema 1 can migrate only an API-only plan \
405                         without queue, trigger, or scheduled-wakeup fields"
406                            .into(),
407                    ));
408                }
409                let [function] = self.functions.as_mut_slice() else {
410                    return Err(PlanError::SchemaMigration(
411                        "MINCO-PLAN-MIGRATE-002: schema 1 must contain exactly one API function"
412                            .into(),
413                    ));
414                };
415                if !matches!(function.role, FunctionRole::HttpApi) {
416                    return Err(PlanError::SchemaMigration(
417                        "MINCO-PLAN-MIGRATE-002: schema 1 must contain exactly one API function"
418                            .into(),
419                    ));
420                }
421                self.triggers.push(TriggerPlan::HttpApi {
422                    id: "http-api".into(),
423                    function_id: function.name.clone(),
424                });
425                self.schema_version = 2;
426                self.iam_intents = derive_iam_intents(
427                    self.schema_version,
428                    &self.runtime,
429                    &self.database,
430                    &self.application_graph,
431                    &self.functions,
432                    &self.triggers,
433                );
434                Ok(self)
435            }
436            version => Err(PlanError::SchemaMigration(format!(
437                "MINCO-PLAN-MIGRATE-003: unsupported source schema version {version}"
438            ))),
439        }
440    }
441
442    #[must_use]
443    pub fn validate(&self) -> Vec<PlanDiagnostic> {
444        let mut diagnostics = Vec::new();
445        if !matches!(self.schema_version, 1 | 2) {
446            diagnostics.push(error(
447                "MINCO-PLAN-001",
448                "unsupported deployment plan schema version",
449            ));
450        }
451        validate_runtime_ingress(self, &mut diagnostics);
452        let expected_local_services = local_aws_services(
453            &self.runtime,
454            &self.database,
455            &self.application_graph,
456            &self.queues,
457        );
458        if self.local_aws_services != expected_local_services {
459            diagnostics.push(error(
460                "MINCO-PLAN-003",
461                "local_aws_services does not match the configured application graph",
462            ));
463        }
464        if self
465            .static_site
466            .as_ref()
467            .is_some_and(|static_site| !static_site.is_valid())
468        {
469            diagnostics.push(error(
470                "MINCO-STATIC-001",
471                "static-site deployment intent is invalid",
472            ));
473        }
474        if let Some(realtime) = &self.realtime {
475            if !realtime.is_valid() {
476                diagnostics.push(error(
477                    "MINCO-REALTIME-001",
478                    "realtime deployment requires one portable namespace segment, a bounded subscriber claim name and a 256-byte to 240-KiB event limit",
479                ));
480            }
481            if !crate::realtime_oidc_auth_is_valid(&self.auth) {
482                diagnostics.push(error(
483                    "MINCO-REALTIME-002",
484                    "subscriber-only realtime requires a bounded HTTPS JWT issuer and at least one audience compatible with AppSync OIDC",
485                ));
486            }
487        }
488        if let Some(preview) = &self.preview {
489            let owner_valid = !preview.owner.trim().is_empty()
490                && preview.owner.len() <= 256
491                && !preview.owner.chars().any(char::is_control);
492            let account_valid = preview.expected_account_id.len() == 12
493                && preview
494                    .expected_account_id
495                    .bytes()
496                    .all(|byte| byte.is_ascii_digit());
497            let resource_identity_valid = preview.resources.iter().all(|resource| {
498                is_cloudformation_logical_id(&resource.logical_id)
499                    && !resource.resource_type.trim().is_empty()
500                    && !resource.resource_type.chars().any(char::is_control)
501            });
502            let resources_are_ordered = !preview.resources.is_empty()
503                && preview
504                    .resources
505                    .windows(2)
506                    .all(|resources| resources[0].logical_id < resources[1].logical_id);
507            if !owner_valid
508                || !(300..=2_592_000).contains(&preview.ttl_seconds)
509                || !account_valid
510                || preview.expected_region != self.region
511                || !resource_identity_valid
512                || !resources_are_ordered
513            {
514                diagnostics.push(error(
515                    "MINCO-PREVIEW-001",
516                    "preview lifecycle requires a bounded owner, TTL, exact target, and sorted unique resources",
517                ));
518            }
519            if self.environment != "preview" && !self.environment.starts_with("preview-") {
520                diagnostics.push(error(
521                    "MINCO-PREVIEW-002",
522                    "preview lifecycle is allowed only for an explicit preview environment",
523                ));
524            }
525            if let Some(cleanup) = &preview.cleanup_schedule {
526                let retained = preview
527                    .resources
528                    .iter()
529                    .filter(|resource| resource.retention == PreviewResourceRetention::Retain)
530                    .map(|resource| resource.logical_id.clone())
531                    .collect::<Vec<_>>();
532                if !cleanup.expression.starts_with("at(")
533                    || !is_schedule_expression(&cleanup.expression)
534                    || cleanup.residual_resources != retained
535                    || cleanup.manual_fallback.trim().is_empty()
536                    || cleanup.manual_fallback.chars().any(char::is_control)
537                {
538                    diagnostics.push(error(
539                        "MINCO-PREVIEW-003",
540                        "preview cleanup must be one-time, self-deleting, list exact retained resources, and keep a manual fallback",
541                    ));
542                }
543                if self.cost_policy.deny_scheduled_wakeups {
544                    diagnostics.push(error(
545                        "MINCO-PREVIEW-004",
546                        "preview cleanup scheduling requires explicit scheduled-wakeup permission",
547                    ));
548                }
549            }
550            if !preview.pricing_complete {
551                diagnostics.push(warning(
552                    "MINCO-PREVIEW-006",
553                    "preview pricing is incomplete; retained and provider-priced dimensions remain visible",
554                ));
555            }
556        }
557        if self.routes.iter().any(|route| route.authenticated)
558            && matches!(&self.auth, AuthPlan::None)
559        {
560            diagnostics.push(error("MINCO-AUTH-001", "the contract contains authenticated operations but no deployment authorizer is configured"));
561        }
562        if self.schema_version == 1 {
563            if self.functions.len() != 1 {
564                diagnostics.push(error(
565                    "MINCO-PLAN-002",
566                    "the initial Minco AWS profile requires exactly one API function",
567                ));
568            }
569            if !self.queues.is_empty() || !self.triggers.is_empty() || !self.iam_intents.is_empty()
570            {
571                diagnostics.push(error(
572                    "MINCO-PLAN-004",
573                    "queues, typed IAM intent, and structured triggers require schema version 2",
574                ));
575            }
576            if self
577                .functions
578                .iter()
579                .any(|function| !matches!(function.role, FunctionRole::HttpApi))
580            {
581                diagnostics.push(error(
582                    "MINCO-PLAN-005",
583                    "schema version 1 supports only its single HTTP API function",
584                ));
585            }
586        }
587        if self.schema_version == 2 {
588            if !self.scheduled_wakeups.is_empty() {
589                diagnostics.push(error(
590                    "MINCO-SCHEDULE-003",
591                    "schema version 2 rejects unstructured scheduled_wakeups; use a schedule trigger",
592                ));
593            }
594            validate_multi_runtime_topology(self, &mut diagnostics);
595            if self.iam_intents
596                != derive_iam_intents(
597                    self.schema_version,
598                    &self.runtime,
599                    &self.database,
600                    &self.application_graph,
601                    &self.functions,
602                    &self.triggers,
603                )
604            {
605                diagnostics.push(error(
606                    "MINCO-IAM-001",
607                    "iam_intents does not match the selected functions and triggers",
608                ));
609            }
610        }
611        if self.allowed_origins.is_empty() {
612            diagnostics.push(error(
613                "MINCO-HTTP-001",
614                "at least one exact CORS origin is required",
615            ));
616        }
617        if self.allowed_origins.iter().any(|origin| origin == "*") {
618            diagnostics.push(error("MINCO-HTTP-002", "wildcard CORS is forbidden"));
619        }
620        if self.allowed_headers.is_empty() {
621            diagnostics.push(error(
622                "MINCO-HTTP-003",
623                "at least one exact CORS request header is required",
624            ));
625        }
626        let mut seen_headers = std::collections::BTreeSet::new();
627        for configured in &self.allowed_headers {
628            let Ok(header) = configured.parse::<http::HeaderName>() else {
629                diagnostics.push(error(
630                    "MINCO-HTTP-004",
631                    &format!("invalid CORS request header: {configured}"),
632                ));
633                continue;
634            };
635            if header.as_str() == "*" {
636                diagnostics.push(error(
637                    "MINCO-HTTP-005",
638                    "wildcard CORS request headers are forbidden",
639                ));
640            } else if !seen_headers.insert(header.as_str().to_owned()) {
641                diagnostics.push(error(
642                    "MINCO-HTTP-006",
643                    &format!("duplicate CORS request header: {}", header.as_str()),
644                ));
645            }
646        }
647        if self.exposed_headers != default_exposed_headers() {
648            diagnostics.push(error(
649                "MINCO-HTTP-007",
650                "exposed CORS response headers must match the frontend-neutral HTTP boundary",
651            ));
652        }
653        if self.log_retention_days == 0 {
654            diagnostics.push(error(
655                "MINCO-COST-006",
656                "log retention must be explicit and greater than zero",
657            ));
658        }
659        if self.cost_policy.deny_nat_gateway && self.uses_nat_gateway {
660            diagnostics.push(error(
661                "MINCO-COST-001",
662                "minimal-idle profile forbids a NAT Gateway",
663            ));
664        }
665        let enabled_schedules = self
666            .triggers
667            .iter()
668            .filter(|trigger| matches!(trigger, TriggerPlan::Schedule { enabled: true, .. }))
669            .map(TriggerPlan::id)
670            .collect::<Vec<_>>();
671        if self.cost_policy.deny_scheduled_wakeups
672            && (!self.scheduled_wakeups.is_empty() || !enabled_schedules.is_empty())
673        {
674            diagnostics.push(error(
675                "MINCO-COST-002",
676                &if enabled_schedules.is_empty() {
677                    "minimal-idle profile forbids scheduled wakeups".to_owned()
678                } else {
679                    format!(
680                        "minimal-idle profile forbids enabled schedules: {}",
681                        enabled_schedules.join(", ")
682                    )
683                },
684            ));
685        } else if !self.cost_policy.deny_scheduled_wakeups {
686            for trigger in &self.triggers {
687                if let TriggerPlan::Schedule {
688                    id,
689                    function_id,
690                    expression,
691                    enabled: true,
692                    ..
693                } = trigger
694                {
695                    diagnostics.push(information(
696                        "MINCO-COST-009",
697                        &format!(
698                            "enabled schedule {id} invokes {function_id} with {expression}; it \
699                             is a request-based wake source and can wake a scale-to-zero database: {}",
700                            self.database.can_scale_to_zero()
701                        ),
702                    ));
703                }
704            }
705        }
706        if self.cost_policy.deny_fixed_compute && self.database.has_fixed_compute() {
707            diagnostics.push(error(
708                "MINCO-COST-007",
709                &format!(
710                    "database profile {} has fixed provisioned compute",
711                    self.database.kind_name()
712                ),
713            ));
714        }
715        for function in &self.functions {
716            if self.schema_version == 2
717                && (function.memory_mb == 0
718                    || function.timeout_seconds == 0
719                    || function.reserved_concurrency == 0)
720            {
721                diagnostics.push(error(
722                    "MINCO-PERF-004",
723                    &format!(
724                        "function {} requires non-zero memory, timeout, and reserved concurrency",
725                        function.name
726                    ),
727                ));
728            }
729            if function.provisioned_concurrency > function.reserved_concurrency {
730                diagnostics.push(error(
731                    "MINCO-COST-010",
732                    &format!(
733                        "function {} provisioned concurrency exceeds reserved concurrency",
734                        function.name
735                    ),
736                ));
737            }
738            if self.cost_policy.deny_provisioned_concurrency && function.provisioned_concurrency > 0
739            {
740                diagnostics.push(error(
741                    "MINCO-COST-003",
742                    &format!("function {} enables provisioned concurrency", function.name),
743                ));
744            }
745            if function.reserved_concurrency > self.cost_policy.max_reserved_concurrency {
746                diagnostics.push(error(
747                    "MINCO-COST-004",
748                    &format!(
749                        "function {} reserved concurrency {} exceeds {}",
750                        function.name,
751                        function.reserved_concurrency,
752                        self.cost_policy.max_reserved_concurrency
753                    ),
754                ));
755            }
756            if function.timeout_seconds > self.performance_policy.max_lambda_timeout_seconds {
757                diagnostics.push(error(
758                    "MINCO-PERF-001",
759                    &format!(
760                        "function {} timeout {}s exceeds {}s",
761                        function.name,
762                        function.timeout_seconds,
763                        self.performance_policy.max_lambda_timeout_seconds
764                    ),
765                ));
766            }
767            if function.memory_mb > self.performance_policy.max_lambda_memory_mb {
768                diagnostics.push(error(
769                    "MINCO-PERF-002",
770                    &format!(
771                        "function {} memory {}MB exceeds {}MB",
772                        function.name,
773                        function.memory_mb,
774                        self.performance_policy.max_lambda_memory_mb
775                    ),
776                ));
777            }
778        }
779        let possible_connections: u32 = self
780            .functions
781            .iter()
782            .map(|function| {
783                function
784                    .reserved_concurrency
785                    .saturating_mul(function.database_connections_per_instance)
786            })
787            .fold(0, u32::saturating_add);
788        if self.database.is_relational()
789            && possible_connections > self.cost_policy.max_database_connections
790        {
791            diagnostics.push(error(
792                "MINCO-COST-005",
793                &format!(
794                    "Lambda concurrency can create {possible_connections} database connections, exceeding {}",
795                    self.cost_policy.max_database_connections
796                ),
797            ));
798        }
799        if matches!(
800            &self.database,
801            DatabaseDeployment::SqliteLambdaMutable { .. }
802        ) {
803            diagnostics.push(error(
804                "MINCO-DB-001",
805                "mutable SQLite is not supported on Lambda ephemeral storage",
806            ));
807        }
808        if matches!(&self.database, DatabaseDeployment::DynamoDbOnDemand { .. }) {
809            diagnostics.push(information(
810                "MINCO-DB-002",
811                "DynamoDB is an alternate persistence model, not a transparent replacement for relational PostgreSQL adapters",
812            ));
813            validate_dynamodb_table(self, &mut diagnostics);
814        }
815        for field in self.database.invalid_numeric_inputs() {
816            diagnostics.push(error(
817                "MINCO-COST-008",
818                &format!("{field} has an invalid numeric value for its cost profile"),
819            ));
820        }
821        if let DatabaseDeployment::AuroraServerlessV2 {
822            minimum_acu,
823            auto_pause_seconds,
824            ..
825        } = &self.database
826        {
827            if *minimum_acu == 0.0 && auto_pause_seconds.is_none() {
828                diagnostics.push(warning(
829                    "MINCO-DB-003",
830                    "Aurora minimum ACU is zero but no auto-pause interval is recorded",
831                ));
832            }
833            if auto_pause_seconds
834                .is_some_and(|seconds| !(300..=86_400).contains(&seconds) || *minimum_acu != 0.0)
835            {
836                diagnostics.push(error(
837                    "MINCO-DB-004",
838                    "Aurora auto-pause must be 300 to 86400 seconds and requires minimum_acu = 0",
839                ));
840            }
841            if minimum_acu.is_finite()
842                && (*minimum_acu > 256.0 || (*minimum_acu * 2.0).fract() != 0.0)
843            {
844                diagnostics.push(error(
845                    "MINCO-DB-005",
846                    "Aurora minimum_acu must use 0.5 ACU increments and not exceed 256",
847                ));
848            }
849        }
850        diagnostics
851    }
852}
853
854fn validate_runtime_ingress(plan: &DeploymentPlan, diagnostics: &mut Vec<PlanDiagnostic>) {
855    match (&plan.runtime, &plan.ingress) {
856        (RuntimePlan::LambdaZipArm64, IngressPlan::ApiGatewayHttpApi)
857        | (RuntimePlan::LocalNative, IngressPlan::LocalTcp) => {}
858        (RuntimePlan::LambdaZipArm64, IngressPlan::LambdaFunctionUrl) => diagnostics.push(error(
859            "MINCO-PLAN-INGRESS-001",
860            "lambda_function_url is declared for explicit research and compatibility tracking but is not a supported deployment ingress",
861        )),
862        (runtime, ingress) => diagnostics.push(error(
863            "MINCO-PLAN-INGRESS-002",
864            &format!(
865                "runtime {} cannot use ingress {}",
866                runtime.kind_name(),
867                ingress.kind_name()
868            ),
869        )),
870    }
871}
872
873fn is_cloudformation_logical_id(value: &str) -> bool {
874    let mut bytes = value.bytes();
875    value.len() <= 255
876        && bytes.next().is_some_and(|byte| byte.is_ascii_alphabetic())
877        && bytes.all(|byte| byte.is_ascii_alphanumeric())
878}
879
880fn validate_multi_runtime_topology(plan: &DeploymentPlan, diagnostics: &mut Vec<PlanDiagnostic>) {
881    let mut functions = std::collections::BTreeMap::new();
882    for function in &plan.functions {
883        if !is_stable_id(&function.name) {
884            diagnostics.push(error(
885                "MINCO-PLAN-010",
886                &format!(
887                    "function {} does not use a stable identifier",
888                    function.name
889                ),
890            ));
891        }
892        if functions.insert(function.name.as_str(), function).is_some() {
893            diagnostics.push(error(
894                "MINCO-PLAN-011",
895                &format!("duplicate function identifier: {}", function.name),
896            ));
897        }
898    }
899    let api_functions = plan
900        .functions
901        .iter()
902        .filter(|function| matches!(function.role, FunctionRole::HttpApi))
903        .count();
904    if api_functions != 1 {
905        diagnostics.push(error(
906            "MINCO-PLAN-012",
907            "schema version 2 requires exactly one HTTP API function",
908        ));
909    }
910
911    let mut queues = std::collections::BTreeMap::new();
912    for queue in &plan.queues {
913        if !is_stable_id(&queue.id) {
914            diagnostics.push(error(
915                "MINCO-PLAN-010",
916                &format!("queue {} does not use a stable identifier", queue.id),
917            ));
918        }
919        if queues.insert(queue.id.as_str(), queue).is_some() {
920            diagnostics.push(error(
921                "MINCO-PLAN-013",
922                &format!("duplicate queue identifier: {}", queue.id),
923            ));
924        }
925        if queue.visibility_timeout_seconds > 43_200 {
926            diagnostics.push(error(
927                "MINCO-SQS-010",
928                &format!(
929                    "queue {} visibility timeout exceeds 43200 seconds",
930                    queue.id
931                ),
932            ));
933        }
934        if !(60..=1_209_600).contains(&queue.retention_seconds) {
935            diagnostics.push(error(
936                "MINCO-SQS-011",
937                &format!(
938                    "queue {} retention must be between 60 and 1209600 seconds",
939                    queue.id
940                ),
941            ));
942        }
943    }
944    for queue in &plan.queues {
945        match (&queue.dead_letter_queue_id, queue.max_receive_count) {
946            (Some(dead_letter_queue_id), Some(max_receive_count)) => {
947                if dead_letter_queue_id == &queue.id {
948                    diagnostics.push(error(
949                        "MINCO-SQS-004",
950                        &format!("queue {} cannot be its own dead-letter queue", queue.id),
951                    ));
952                }
953                match queues.get(dead_letter_queue_id.as_str()) {
954                    Some(dead_letter_queue) if dead_letter_queue.fifo != queue.fifo => {
955                        diagnostics.push(error(
956                            "MINCO-SQS-003",
957                            &format!(
958                                "queue {} and dead-letter queue {dead_letter_queue_id} must \
959                                 use the same FIFO setting",
960                                queue.id
961                            ),
962                        ));
963                    }
964                    Some(_) => {}
965                    None => diagnostics.push(error(
966                        "MINCO-PLAN-015",
967                        &format!(
968                            "queue {} references missing dead-letter queue \
969                             {dead_letter_queue_id}",
970                            queue.id
971                        ),
972                    )),
973                }
974                if !(1..=1_000).contains(&max_receive_count) {
975                    diagnostics.push(error(
976                        "MINCO-SQS-005",
977                        &format!(
978                            "queue {} max_receive_count must be between 1 and 1000",
979                            queue.id
980                        ),
981                    ));
982                }
983            }
984            (None, None) => {}
985            _ => diagnostics.push(error(
986                "MINCO-SQS-004",
987                &format!(
988                    "queue {} must configure dead_letter_queue_id and max_receive_count together",
989                    queue.id
990                ),
991            )),
992        }
993    }
994    if let Some(queue_id) = redrive_cycle_start(&queues) {
995        diagnostics.push(error(
996            "MINCO-SQS-006",
997            &format!("dead-letter queue references contain a cycle from {queue_id}"),
998        ));
999    }
1000
1001    let mut trigger_ids = std::collections::BTreeSet::new();
1002    let mut http_triggers = 0;
1003    for trigger in &plan.triggers {
1004        if !is_stable_id(trigger.id()) {
1005            diagnostics.push(error(
1006                "MINCO-PLAN-010",
1007                &format!("trigger {} does not use a stable identifier", trigger.id()),
1008            ));
1009        }
1010        if !trigger_ids.insert(trigger.id()) {
1011            diagnostics.push(error(
1012                "MINCO-PLAN-014",
1013                &format!("duplicate trigger identifier: {}", trigger.id()),
1014            ));
1015        }
1016        match trigger {
1017            TriggerPlan::HttpApi { function_id, .. } => {
1018                http_triggers += 1;
1019                match functions.get(function_id.as_str()) {
1020                    Some(function) if matches!(function.role, FunctionRole::HttpApi) => {}
1021                    Some(_) => diagnostics.push(error(
1022                        "MINCO-PLAN-016",
1023                        &format!(
1024                            "HTTP API trigger {} must target an HTTP API function",
1025                            trigger.id()
1026                        ),
1027                    )),
1028                    None => diagnostics.push(error(
1029                        "MINCO-PLAN-015",
1030                        &format!(
1031                            "trigger {} references missing function {function_id}",
1032                            trigger.id()
1033                        ),
1034                    )),
1035                }
1036            }
1037            TriggerPlan::Sqs {
1038                function_id,
1039                queue_id,
1040                batch_size,
1041                batching_window_seconds,
1042                report_batch_item_failures,
1043                maximum_concurrency,
1044                ..
1045            } => {
1046                let function = functions.get(function_id.as_str()).copied();
1047                match function {
1048                    Some(function) if matches!(function.role, FunctionRole::Worker) => {}
1049                    Some(_) => diagnostics.push(error(
1050                        "MINCO-PLAN-016",
1051                        &format!("SQS trigger {} must target a worker function", trigger.id()),
1052                    )),
1053                    None => diagnostics.push(error(
1054                        "MINCO-PLAN-015",
1055                        &format!(
1056                            "trigger {} references missing function {function_id}",
1057                            trigger.id()
1058                        ),
1059                    )),
1060                }
1061                let queue = queues.get(queue_id.as_str()).copied();
1062                if queue.is_none() {
1063                    diagnostics.push(error(
1064                        "MINCO-PLAN-015",
1065                        &format!(
1066                            "trigger {} references missing queue {queue_id}",
1067                            trigger.id()
1068                        ),
1069                    ));
1070                }
1071                if let (Some(function), Some(queue)) = (function, queue) {
1072                    let required_visibility = function
1073                        .timeout_seconds
1074                        .saturating_mul(6)
1075                        .saturating_add(*batching_window_seconds);
1076                    if queue.visibility_timeout_seconds < required_visibility {
1077                        diagnostics.push(error(
1078                            "MINCO-SQS-002",
1079                            &format!(
1080                                "queue {queue_id} visibility timeout must be at least \
1081                                 {required_visibility}s for trigger {}",
1082                                trigger.id()
1083                            ),
1084                        ));
1085                    }
1086                    if !(2..=1_000).contains(maximum_concurrency)
1087                        || *maximum_concurrency > function.reserved_concurrency
1088                        || *maximum_concurrency > plan.cost_policy.max_reserved_concurrency
1089                    {
1090                        diagnostics.push(error(
1091                            "MINCO-SQS-007",
1092                            &format!(
1093                                "SQS trigger {} maximum concurrency must be 2 to 1000 and \
1094                                 cannot exceed worker or cost-policy concurrency",
1095                                trigger.id()
1096                            ),
1097                        ));
1098                    }
1099                    let maximum_batch_size = if queue.fifo { 10 } else { 10_000 };
1100                    if !(1..=maximum_batch_size).contains(batch_size) {
1101                        diagnostics.push(error(
1102                            "MINCO-SQS-008",
1103                            &format!(
1104                                "SQS trigger {} batch size must be 1 to {maximum_batch_size}",
1105                                trigger.id()
1106                            ),
1107                        ));
1108                    }
1109                    if *batching_window_seconds > 300
1110                        || (queue.fifo && *batching_window_seconds != 0)
1111                        || (!queue.fifo && *batch_size > 10 && *batching_window_seconds == 0)
1112                    {
1113                        diagnostics.push(error(
1114                            "MINCO-SQS-009",
1115                            &format!(
1116                                "SQS trigger {} uses an invalid batching window",
1117                                trigger.id()
1118                            ),
1119                        ));
1120                    }
1121                }
1122                if !report_batch_item_failures {
1123                    diagnostics.push(error(
1124                        "MINCO-SQS-001",
1125                        &format!(
1126                            "SQS trigger {} must enable ReportBatchItemFailures",
1127                            trigger.id()
1128                        ),
1129                    ));
1130                }
1131            }
1132            TriggerPlan::Schedule {
1133                function_id,
1134                expression,
1135                purpose,
1136                cleanup,
1137                ..
1138            } => {
1139                if !functions.contains_key(function_id.as_str()) {
1140                    diagnostics.push(error(
1141                        "MINCO-PLAN-015",
1142                        &format!(
1143                            "trigger {} references missing function {function_id}",
1144                            trigger.id()
1145                        ),
1146                    ));
1147                }
1148                if purpose.trim().is_empty() {
1149                    diagnostics.push(error(
1150                        "MINCO-SCHEDULE-001",
1151                        &format!("schedule {} requires a reviewable purpose", trigger.id()),
1152                    ));
1153                }
1154                if !is_schedule_expression(expression) {
1155                    diagnostics.push(error(
1156                        "MINCO-SCHEDULE-002",
1157                        &format!(
1158                            "schedule {} must use an EventBridge at(...), rate(...), or \
1159                             cron(...) expression",
1160                            trigger.id()
1161                        ),
1162                    ));
1163                }
1164                if let Some(cleanup) = cleanup {
1165                    if !expression.starts_with("at(") {
1166                        diagnostics.push(error(
1167                            "MINCO-SCHEDULE-004",
1168                            &format!(
1169                                "schedule {} can delete itself after completion only when it \
1170                                 uses a one-time at(...) expression",
1171                                trigger.id()
1172                            ),
1173                        ));
1174                    }
1175                    if cleanup.residual_resources.is_empty()
1176                        || cleanup
1177                            .residual_resources
1178                            .iter()
1179                            .any(|resource| resource.trim().is_empty())
1180                    {
1181                        diagnostics.push(error(
1182                            "MINCO-SCHEDULE-005",
1183                            &format!(
1184                                "schedule {} cleanup must list residual resources explicitly",
1185                                trigger.id()
1186                            ),
1187                        ));
1188                    }
1189                    if cleanup.manual_fallback.trim().is_empty() {
1190                        diagnostics.push(error(
1191                            "MINCO-SCHEDULE-006",
1192                            &format!(
1193                                "schedule {} cleanup requires a reviewable manual fallback",
1194                                trigger.id()
1195                            ),
1196                        ));
1197                    }
1198                }
1199            }
1200        }
1201    }
1202    for function in plan
1203        .functions
1204        .iter()
1205        .filter(|function| matches!(function.role, FunctionRole::Worker))
1206    {
1207        let mapping_concurrency = plan
1208            .triggers
1209            .iter()
1210            .filter_map(|trigger| {
1211                let TriggerPlan::Sqs {
1212                    function_id,
1213                    maximum_concurrency,
1214                    ..
1215                } = trigger
1216                else {
1217                    return None;
1218                };
1219                (function_id == &function.name).then_some(*maximum_concurrency)
1220            })
1221            .fold(0, u32::saturating_add);
1222        if mapping_concurrency > function.reserved_concurrency {
1223            diagnostics.push(error(
1224                "MINCO-SQS-012",
1225                &format!(
1226                    "worker {} has aggregate SQS maximum concurrency {mapping_concurrency}, exceeding reserved concurrency {}",
1227                    function.name, function.reserved_concurrency
1228                ),
1229            ));
1230        }
1231    }
1232    if http_triggers != 1 {
1233        diagnostics.push(error(
1234            "MINCO-PLAN-017",
1235            "schema version 2 requires exactly one explicit HTTP API trigger",
1236        ));
1237    }
1238    validate_sam_resource_identifiers(plan, diagnostics);
1239}
1240
1241fn validate_sam_resource_identifiers(plan: &DeploymentPlan, diagnostics: &mut Vec<PlanDiagnostic>) {
1242    let mut resources = std::collections::BTreeMap::from([
1243        ("ApiFunction".to_owned(), "HTTP API function".to_owned()),
1244        ("ApiLogGroup".to_owned(), "HTTP API log group".to_owned()),
1245    ]);
1246    let mut insert_resource = |logical_id: String, owner: String| {
1247        if let Some(existing) = resources.insert(logical_id.clone(), owner.clone()) {
1248            diagnostics.push(error(
1249                "MINCO-PLAN-018",
1250                &format!(
1251                    "{owner} and {existing} collapse to the same SAM logical identifier {logical_id}"
1252                ),
1253            ));
1254        }
1255    };
1256    if let Some(table) = plan.database.dynamodb_table() {
1257        insert_resource(
1258            table.logical_id.clone(),
1259            "DynamoDB table contract".to_owned(),
1260        );
1261    }
1262    if let Some(table) = plan.dynamodb_audit_table() {
1263        insert_resource(table.logical_id, "DynamoDB audit table contract".to_owned());
1264    }
1265    for function in plan
1266        .functions
1267        .iter()
1268        .filter(|function| matches!(function.role, FunctionRole::Worker))
1269    {
1270        let prefix = sam_logical_id(&function.name);
1271        insert_resource(
1272            format!("{prefix}Function"),
1273            format!("worker function {}", function.name),
1274        );
1275        insert_resource(
1276            format!("{prefix}LogGroup"),
1277            format!("worker log group {}", function.name),
1278        );
1279    }
1280    for queue in &plan.queues {
1281        insert_resource(
1282            format!("{}Queue", sam_logical_id(&queue.id)),
1283            format!("queue {}", queue.id),
1284        );
1285    }
1286    let mut events = std::collections::BTreeMap::new();
1287    for route in &plan.routes {
1288        let event_id = format!("{}Event", sam_logical_id(&route.operation_id));
1289        let key = ("__http_api", event_id.clone());
1290        if let Some(existing) = events.insert(key, route.operation_id.as_str()) {
1291            diagnostics.push(error(
1292                "MINCO-PLAN-018",
1293                &format!(
1294                    "operations {} and {} collapse to the same SAM event identifier {event_id}",
1295                    route.operation_id, existing
1296                ),
1297            ));
1298        }
1299    }
1300    for trigger in &plan.triggers {
1301        let function_id = match trigger {
1302            TriggerPlan::Sqs { function_id, .. } | TriggerPlan::Schedule { function_id, .. } => {
1303                function_id
1304            }
1305            TriggerPlan::HttpApi { .. } => continue,
1306        };
1307        let event_id = format!("{}Event", sam_logical_id(trigger.id()));
1308        let key = (function_id.as_str(), event_id.clone());
1309        if let Some(existing) = events.insert(key, trigger.id()) {
1310            diagnostics.push(error(
1311                "MINCO-PLAN-018",
1312                &format!(
1313                    "triggers {} and {} on function {function_id} collapse to the same SAM event identifier {event_id}",
1314                    trigger.id(),
1315                    existing
1316                ),
1317            ));
1318        }
1319    }
1320
1321    if matches!(plan.runtime, RuntimePlan::LambdaZipArm64) {
1322        for function in &plan.functions {
1323            let name = if matches!(function.role, FunctionRole::HttpApi) {
1324                format!("{}-{}-api", plan.application, plan.environment)
1325            } else {
1326                format!(
1327                    "{}-{}-{}",
1328                    plan.application, plan.environment, function.name
1329                )
1330            };
1331            if !valid_lambda_function_name(&name) {
1332                diagnostics.push(error(
1333                    "MINCO-AWS-001",
1334                    &format!(
1335                        "function {} derives invalid Lambda FunctionName {name}",
1336                        function.name
1337                    ),
1338                ));
1339            }
1340        }
1341        for queue in &plan.queues {
1342            let suffix = if queue.fifo { ".fifo" } else { "" };
1343            let name = format!(
1344                "{}-{}-{}{}",
1345                plan.application, plan.environment, queue.id, suffix
1346            );
1347            if !valid_sqs_queue_name(&name, queue.fifo) {
1348                diagnostics.push(error(
1349                    "MINCO-AWS-002",
1350                    &format!("queue {} derives invalid SQS QueueName {name}", queue.id),
1351                ));
1352            }
1353        }
1354    }
1355}
1356
1357fn valid_lambda_function_name(value: &str) -> bool {
1358    (1..=64).contains(&value.len())
1359        && value
1360            .bytes()
1361            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
1362}
1363
1364fn valid_sqs_queue_name(value: &str, fifo: bool) -> bool {
1365    if !(1..=80).contains(&value.len()) {
1366        return false;
1367    }
1368    let body = if fifo {
1369        let Some(body) = value.strip_suffix(".fifo") else {
1370            return false;
1371        };
1372        body
1373    } else {
1374        value
1375    };
1376    !body.is_empty()
1377        && body
1378            .bytes()
1379            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
1380}
1381
1382fn validate_dynamodb_table(plan: &DeploymentPlan, diagnostics: &mut Vec<PlanDiagnostic>) {
1383    let Some(table) = plan.database.dynamodb_table() else {
1384        if plan
1385            .application_graph
1386            .capabilities
1387            .contains_key("audit.ledger")
1388        {
1389            diagnostics.push(error(
1390                "MINCO-DYNAMODB-013",
1391                "DynamoDB audit table requires an explicit operational table for atomic writes",
1392            ));
1393        }
1394        return;
1395    };
1396    validate_one_dynamodb_table(plan, table, diagnostics);
1397    let Some(audit) = plan.dynamodb_audit_table() else {
1398        return;
1399    };
1400    validate_one_dynamodb_table(plan, &audit, diagnostics);
1401    if table.logical_id == audit.logical_id {
1402        diagnostics.push(error(
1403            "MINCO-DYNAMODB-009",
1404            "DynamoDB operational and audit tables require distinct logical IDs",
1405        ));
1406    }
1407    if table.function_id != audit.function_id {
1408        diagnostics.push(error(
1409            "MINCO-DYNAMODB-010",
1410            "DynamoDB operational and audit tables must be owned by one function for atomic writes",
1411        ));
1412    }
1413    let valid_audit_schema = audit.partition_key.name == "pk"
1414        && audit.partition_key.scalar_type == DynamoDbScalarType::String
1415        && audit
1416            .sort_key
1417            .as_ref()
1418            .is_some_and(|key| key.name == "sk" && key.scalar_type == DynamoDbScalarType::String)
1419        && audit.global_secondary_indexes.is_empty();
1420    if !valid_audit_schema {
1421        diagnostics.push(error(
1422            "MINCO-DYNAMODB-011",
1423            "DynamoDB audit table requires string pk/sk keys and no global secondary indexes",
1424        ));
1425    }
1426    if !audit.point_in_time_recovery || audit.deletion_policy != DynamoDbDeletionPolicy::Retain {
1427        diagnostics.push(error(
1428            "MINCO-DYNAMODB-012",
1429            "DynamoDB audit table requires point-in-time recovery and retain deletion policy; SAM adds deletion protection",
1430        ));
1431    }
1432}
1433
1434fn validate_one_dynamodb_table(
1435    plan: &DeploymentPlan,
1436    table: &DynamoDbTablePlan,
1437    diagnostics: &mut Vec<PlanDiagnostic>,
1438) {
1439    if plan.schema_version != 2 {
1440        diagnostics.push(error(
1441            "MINCO-DYNAMODB-001",
1442            "an explicit DynamoDB table contract requires deployment schema version 2",
1443        ));
1444    }
1445    if !is_cloudformation_logical_id(&table.logical_id) {
1446        diagnostics.push(error(
1447            "MINCO-DYNAMODB-002",
1448            "DynamoDB logical_id must be a CloudFormation logical identifier",
1449        ));
1450    }
1451    if !plan
1452        .functions
1453        .iter()
1454        .any(|function| function.name == table.function_id)
1455    {
1456        diagnostics.push(error(
1457            "MINCO-DYNAMODB-003",
1458            "DynamoDB function_id must name one configured function",
1459        ));
1460    }
1461    if table.global_secondary_indexes.len() > 20 {
1462        diagnostics.push(error(
1463            "MINCO-DYNAMODB-004",
1464            "a DynamoDB table contract supports at most 20 global secondary indexes",
1465        ));
1466    }
1467
1468    let mut attributes = std::collections::BTreeMap::new();
1469    record_dynamodb_attribute(&table.partition_key, &mut attributes, diagnostics);
1470    if let Some(sort_key) = &table.sort_key {
1471        if sort_key.name == table.partition_key.name {
1472            diagnostics.push(error(
1473                "MINCO-DYNAMODB-007",
1474                "DynamoDB partition and sort keys must use different attributes",
1475            ));
1476        }
1477        record_dynamodb_attribute(sort_key, &mut attributes, diagnostics);
1478    }
1479
1480    let mut index_names = std::collections::BTreeSet::new();
1481    for index in &table.global_secondary_indexes {
1482        if !valid_dynamodb_index_name(&index.name) || !index_names.insert(index.name.as_str()) {
1483            diagnostics.push(error(
1484                "MINCO-DYNAMODB-008",
1485                "DynamoDB global secondary index names must be unique valid provider names",
1486            ));
1487        }
1488        record_dynamodb_attribute(&index.partition_key, &mut attributes, diagnostics);
1489        if let Some(sort_key) = &index.sort_key {
1490            if sort_key.name == index.partition_key.name {
1491                diagnostics.push(error(
1492                    "MINCO-DYNAMODB-007",
1493                    "DynamoDB partition and sort keys must use different attributes",
1494                ));
1495            }
1496            record_dynamodb_attribute(sort_key, &mut attributes, diagnostics);
1497        }
1498    }
1499}
1500
1501fn valid_dynamodb_attribute_name(value: &str) -> bool {
1502    (1..=255).contains(&value.len()) && !value.chars().any(char::is_control)
1503}
1504
1505fn record_dynamodb_attribute(
1506    attribute: &DynamoDbKeyAttribute,
1507    attributes: &mut std::collections::BTreeMap<String, DynamoDbScalarType>,
1508    diagnostics: &mut Vec<PlanDiagnostic>,
1509) {
1510    if !valid_dynamodb_attribute_name(&attribute.name) {
1511        diagnostics.push(error(
1512            "MINCO-DYNAMODB-005",
1513            "DynamoDB key attribute names must contain 1 to 255 visible bytes",
1514        ));
1515    }
1516    if attributes
1517        .insert(attribute.name.clone(), attribute.scalar_type)
1518        .is_some_and(|existing| existing != attribute.scalar_type)
1519    {
1520        diagnostics.push(error(
1521            "MINCO-DYNAMODB-006",
1522            "a DynamoDB key attribute must have one consistent scalar type",
1523        ));
1524    }
1525}
1526
1527fn valid_dynamodb_index_name(value: &str) -> bool {
1528    (3..=255).contains(&value.len())
1529        && value
1530            .bytes()
1531            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
1532}
1533
1534fn redrive_cycle_start<'a>(
1535    queues: &std::collections::BTreeMap<&'a str, &'a QueuePlan>,
1536) -> Option<&'a str> {
1537    for start in queues.keys().copied() {
1538        let mut visited = std::collections::BTreeSet::new();
1539        let mut current = start;
1540        loop {
1541            if !visited.insert(current) {
1542                return Some(start);
1543            }
1544            let next = queues
1545                .get(current)
1546                .and_then(|queue| queue.dead_letter_queue_id.as_deref());
1547            match next {
1548                Some(next) if queues.contains_key(next) => current = next,
1549                _ => break,
1550            }
1551        }
1552    }
1553    None
1554}
1555
1556pub fn is_stable_id(value: &str) -> bool {
1557    let mut characters = value.chars();
1558    matches!(characters.next(), Some(first) if first.is_ascii_lowercase())
1559        && characters.all(|character| {
1560            character.is_ascii_lowercase() || character.is_ascii_digit() || character == '-'
1561        })
1562}
1563
1564pub fn is_schedule_expression(value: &str) -> bool {
1565    (1..=256).contains(&value.len())
1566        && !value.contains(['\r', '\n'])
1567        && value.ends_with(')')
1568        && ["at(", "rate(", "cron("]
1569            .iter()
1570            .any(|prefix| value.starts_with(prefix) && value.len() > prefix.len() + 1)
1571}
1572
1573#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1574#[serde(tag = "kind", rename_all = "snake_case")]
1575pub enum AuthPlan {
1576    None,
1577    DevelopmentHeaders,
1578    Jwt {
1579        issuer: String,
1580        audiences: Vec<String>,
1581    },
1582}
1583
1584#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1585#[serde(rename_all = "snake_case")]
1586pub enum RuntimePlan {
1587    LambdaZipArm64,
1588    LocalNative,
1589}
1590
1591impl RuntimePlan {
1592    #[must_use]
1593    pub const fn kind_name(&self) -> &'static str {
1594        match self {
1595            Self::LambdaZipArm64 => "lambda_zip_arm64",
1596            Self::LocalNative => "local_native",
1597        }
1598    }
1599}
1600
1601#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1602#[serde(rename_all = "snake_case")]
1603pub enum IngressPlan {
1604    ApiGatewayHttpApi,
1605    LambdaFunctionUrl,
1606    LocalTcp,
1607}
1608
1609impl IngressPlan {
1610    #[must_use]
1611    pub const fn kind_name(&self) -> &'static str {
1612        match self {
1613            Self::ApiGatewayHttpApi => "api_gateway_http_api",
1614            Self::LambdaFunctionUrl => "lambda_function_url",
1615            Self::LocalTcp => "local_tcp",
1616        }
1617    }
1618}
1619
1620#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1621#[serde(rename_all = "snake_case")]
1622pub enum DynamoDbScalarType {
1623    String,
1624    Number,
1625    Binary,
1626}
1627
1628impl DynamoDbScalarType {
1629    #[must_use]
1630    pub const fn cloudformation_code(self) -> &'static str {
1631        match self {
1632            Self::String => "S",
1633            Self::Number => "N",
1634            Self::Binary => "B",
1635        }
1636    }
1637}
1638
1639#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1640#[serde(deny_unknown_fields)]
1641pub struct DynamoDbKeyAttribute {
1642    pub name: String,
1643    pub scalar_type: DynamoDbScalarType,
1644}
1645
1646#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1647#[serde(rename_all = "snake_case")]
1648pub enum DynamoDbProjection {
1649    All,
1650    KeysOnly,
1651}
1652
1653#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1654#[serde(deny_unknown_fields)]
1655pub struct DynamoDbGlobalSecondaryIndex {
1656    pub name: String,
1657    pub partition_key: DynamoDbKeyAttribute,
1658    #[serde(default, skip_serializing_if = "Option::is_none")]
1659    pub sort_key: Option<DynamoDbKeyAttribute>,
1660    pub projection: DynamoDbProjection,
1661}
1662
1663#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1664#[serde(rename_all = "snake_case")]
1665pub enum DynamoDbDeletionPolicy {
1666    Delete,
1667    Retain,
1668}
1669
1670#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1671#[serde(deny_unknown_fields)]
1672pub struct DynamoDbTablePlan {
1673    pub logical_id: String,
1674    pub function_id: String,
1675    pub partition_key: DynamoDbKeyAttribute,
1676    #[serde(default, skip_serializing_if = "Option::is_none")]
1677    pub sort_key: Option<DynamoDbKeyAttribute>,
1678    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1679    pub global_secondary_indexes: Vec<DynamoDbGlobalSecondaryIndex>,
1680    #[serde(default)]
1681    pub point_in_time_recovery: bool,
1682    pub deletion_policy: DynamoDbDeletionPolicy,
1683}
1684
1685#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1686#[serde(tag = "kind", rename_all = "snake_case")]
1687pub enum DatabaseDeployment {
1688    NeonPostgres {
1689        plan: NeonPlan,
1690        compute_unit_hours: f64,
1691        storage_gb_month: f64,
1692        history_storage_gb_month: f64,
1693    },
1694    SelfHostedPostgres {
1695        host_monthly_usd: f64,
1696        storage_gb_month: f64,
1697        storage_rate_usd: f64,
1698        backup_gb_month: f64,
1699        backup_rate_usd: f64,
1700        operations_monthly_usd: f64,
1701    },
1702    RdsPostgres {
1703        instance_hours: f64,
1704        instance_hour_rate_usd: Option<f64>,
1705        storage_gb_month: f64,
1706        storage_rate_usd: Option<f64>,
1707        backup_gb_month: f64,
1708        backup_rate_usd: Option<f64>,
1709        multi_az_multiplier: f64,
1710    },
1711    AuroraServerlessV2 {
1712        minimum_acu: f64,
1713        auto_pause_seconds: Option<u32>,
1714        acu_hours: f64,
1715        acu_hour_rate_usd: Option<f64>,
1716        storage_gb_month: f64,
1717        storage_rate_usd: Option<f64>,
1718        io_million: f64,
1719        io_million_rate_usd: Option<f64>,
1720    },
1721    DynamoDbOnDemand {
1722        read_request_units_million: f64,
1723        read_million_rate_usd: Option<f64>,
1724        write_request_units_million: f64,
1725        write_million_rate_usd: Option<f64>,
1726        storage_gb_month: f64,
1727        storage_rate_usd: Option<f64>,
1728        #[serde(default, skip_serializing_if = "Option::is_none")]
1729        table: Option<DynamoDbTablePlan>,
1730    },
1731    SqlitePersistentHost {
1732        host_monthly_usd: f64,
1733        backup_monthly_usd: f64,
1734    },
1735    SqliteLambdaMutable {
1736        expected_storage_gb: f64,
1737    },
1738}
1739
1740impl DatabaseDeployment {
1741    #[must_use]
1742    pub const fn dynamodb_table(&self) -> Option<&DynamoDbTablePlan> {
1743        match self {
1744            Self::DynamoDbOnDemand { table, .. } => table.as_ref(),
1745            _ => None,
1746        }
1747    }
1748
1749    #[must_use]
1750    pub const fn kind_name(&self) -> &'static str {
1751        match self {
1752            Self::NeonPostgres { .. } => "neon_postgres",
1753            Self::SelfHostedPostgres { .. } => "self_hosted_postgres",
1754            Self::RdsPostgres { .. } => "rds_postgres",
1755            Self::AuroraServerlessV2 { .. } => "aurora_serverless_v2",
1756            Self::DynamoDbOnDemand { .. } => "dynamodb_on_demand",
1757            Self::SqlitePersistentHost { .. } => "sqlite_persistent_host",
1758            Self::SqliteLambdaMutable { .. } => "sqlite_lambda_mutable",
1759        }
1760    }
1761
1762    #[must_use]
1763    pub fn has_fixed_compute(&self) -> bool {
1764        match self {
1765            Self::SelfHostedPostgres { .. }
1766            | Self::RdsPostgres { .. }
1767            | Self::SqlitePersistentHost { .. } => true,
1768            Self::AuroraServerlessV2 { minimum_acu, .. } => *minimum_acu > 0.0,
1769            Self::NeonPostgres { .. }
1770            | Self::DynamoDbOnDemand { .. }
1771            | Self::SqliteLambdaMutable { .. } => false,
1772        }
1773    }
1774
1775    #[must_use]
1776    pub const fn is_relational(&self) -> bool {
1777        !matches!(self, Self::DynamoDbOnDemand { .. })
1778    }
1779
1780    #[must_use]
1781    pub fn can_scale_to_zero(&self) -> bool {
1782        match self {
1783            Self::NeonPostgres { .. } | Self::DynamoDbOnDemand { .. } => true,
1784            Self::AuroraServerlessV2 {
1785                minimum_acu,
1786                auto_pause_seconds,
1787                ..
1788            } => *minimum_acu == 0.0 && auto_pause_seconds.is_some(),
1789            Self::SelfHostedPostgres { .. }
1790            | Self::RdsPostgres { .. }
1791            | Self::SqlitePersistentHost { .. }
1792            | Self::SqliteLambdaMutable { .. } => false,
1793        }
1794    }
1795
1796    pub(crate) fn invalid_numeric_inputs(&self) -> Vec<&'static str> {
1797        let mut invalid = Vec::new();
1798        match self {
1799            Self::NeonPostgres {
1800                compute_unit_hours,
1801                storage_gb_month,
1802                history_storage_gb_month,
1803                ..
1804            } => {
1805                check_non_negative(&mut invalid, "compute_unit_hours", *compute_unit_hours);
1806                check_non_negative(&mut invalid, "storage_gb_month", *storage_gb_month);
1807                check_non_negative(
1808                    &mut invalid,
1809                    "history_storage_gb_month",
1810                    *history_storage_gb_month,
1811                );
1812            }
1813            Self::SelfHostedPostgres {
1814                host_monthly_usd,
1815                storage_gb_month,
1816                storage_rate_usd,
1817                backup_gb_month,
1818                backup_rate_usd,
1819                operations_monthly_usd,
1820            } => {
1821                check_non_negative(&mut invalid, "host_monthly_usd", *host_monthly_usd);
1822                check_non_negative(&mut invalid, "storage_gb_month", *storage_gb_month);
1823                check_non_negative(&mut invalid, "storage_rate_usd", *storage_rate_usd);
1824                check_non_negative(&mut invalid, "backup_gb_month", *backup_gb_month);
1825                check_non_negative(&mut invalid, "backup_rate_usd", *backup_rate_usd);
1826                check_non_negative(
1827                    &mut invalid,
1828                    "operations_monthly_usd",
1829                    *operations_monthly_usd,
1830                );
1831            }
1832            Self::RdsPostgres {
1833                instance_hours,
1834                instance_hour_rate_usd,
1835                storage_gb_month,
1836                storage_rate_usd,
1837                backup_gb_month,
1838                backup_rate_usd,
1839                multi_az_multiplier,
1840            } => {
1841                check_non_negative(&mut invalid, "instance_hours", *instance_hours);
1842                check_optional_non_negative(
1843                    &mut invalid,
1844                    "instance_hour_rate_usd",
1845                    *instance_hour_rate_usd,
1846                );
1847                check_non_negative(&mut invalid, "storage_gb_month", *storage_gb_month);
1848                check_optional_non_negative(&mut invalid, "storage_rate_usd", *storage_rate_usd);
1849                check_non_negative(&mut invalid, "backup_gb_month", *backup_gb_month);
1850                check_optional_non_negative(&mut invalid, "backup_rate_usd", *backup_rate_usd);
1851                if !multi_az_multiplier.is_finite() || *multi_az_multiplier < 1.0 {
1852                    invalid.push("multi_az_multiplier");
1853                }
1854            }
1855            Self::AuroraServerlessV2 {
1856                minimum_acu,
1857                acu_hours,
1858                acu_hour_rate_usd,
1859                storage_gb_month,
1860                storage_rate_usd,
1861                io_million,
1862                io_million_rate_usd,
1863                ..
1864            } => {
1865                check_non_negative(&mut invalid, "minimum_acu", *minimum_acu);
1866                check_non_negative(&mut invalid, "acu_hours", *acu_hours);
1867                check_optional_non_negative(&mut invalid, "acu_hour_rate_usd", *acu_hour_rate_usd);
1868                check_non_negative(&mut invalid, "storage_gb_month", *storage_gb_month);
1869                check_optional_non_negative(&mut invalid, "storage_rate_usd", *storage_rate_usd);
1870                check_non_negative(&mut invalid, "io_million", *io_million);
1871                check_optional_non_negative(
1872                    &mut invalid,
1873                    "io_million_rate_usd",
1874                    *io_million_rate_usd,
1875                );
1876            }
1877            Self::DynamoDbOnDemand {
1878                read_request_units_million,
1879                read_million_rate_usd,
1880                write_request_units_million,
1881                write_million_rate_usd,
1882                storage_gb_month,
1883                storage_rate_usd,
1884                ..
1885            } => {
1886                check_non_negative(
1887                    &mut invalid,
1888                    "read_request_units_million",
1889                    *read_request_units_million,
1890                );
1891                check_optional_non_negative(
1892                    &mut invalid,
1893                    "read_million_rate_usd",
1894                    *read_million_rate_usd,
1895                );
1896                check_non_negative(
1897                    &mut invalid,
1898                    "write_request_units_million",
1899                    *write_request_units_million,
1900                );
1901                check_optional_non_negative(
1902                    &mut invalid,
1903                    "write_million_rate_usd",
1904                    *write_million_rate_usd,
1905                );
1906                check_non_negative(&mut invalid, "storage_gb_month", *storage_gb_month);
1907                check_optional_non_negative(&mut invalid, "storage_rate_usd", *storage_rate_usd);
1908            }
1909            Self::SqlitePersistentHost {
1910                host_monthly_usd,
1911                backup_monthly_usd,
1912            } => {
1913                check_non_negative(&mut invalid, "host_monthly_usd", *host_monthly_usd);
1914                check_non_negative(&mut invalid, "backup_monthly_usd", *backup_monthly_usd);
1915            }
1916            Self::SqliteLambdaMutable {
1917                expected_storage_gb,
1918            } => {
1919                check_non_negative(&mut invalid, "expected_storage_gb", *expected_storage_gb);
1920            }
1921        }
1922        invalid
1923    }
1924}
1925
1926fn check_non_negative(invalid: &mut Vec<&'static str>, field: &'static str, value: f64) {
1927    if !value.is_finite() || value < 0.0 {
1928        invalid.push(field);
1929    }
1930}
1931
1932fn check_optional_non_negative(
1933    invalid: &mut Vec<&'static str>,
1934    field: &'static str,
1935    value: Option<f64>,
1936) {
1937    if value.is_some_and(|value| !value.is_finite() || value < 0.0) {
1938        invalid.push(field);
1939    }
1940}
1941
1942#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1943#[serde(rename_all = "snake_case")]
1944pub enum NeonPlan {
1945    Free,
1946    Launch,
1947    Scale,
1948}
1949
1950#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1951pub struct FunctionPlan {
1952    pub name: String,
1953    #[serde(default, skip_serializing_if = "FunctionRole::is_http_api")]
1954    pub role: FunctionRole,
1955    pub artifact_path: String,
1956    pub memory_mb: u32,
1957    pub timeout_seconds: u32,
1958    pub reserved_concurrency: u32,
1959    pub provisioned_concurrency: u32,
1960    pub database_connections_per_instance: u32,
1961}
1962
1963#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1964#[serde(rename_all = "snake_case")]
1965pub enum FunctionRole {
1966    #[default]
1967    HttpApi,
1968    Worker,
1969}
1970
1971impl FunctionRole {
1972    // Serde's `skip_serializing_if` contract passes this field by reference.
1973    #[allow(clippy::trivially_copy_pass_by_ref)]
1974    const fn is_http_api(&self) -> bool {
1975        matches!(self, Self::HttpApi)
1976    }
1977}
1978
1979#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1980pub struct QueuePlan {
1981    pub id: String,
1982    pub fifo: bool,
1983    pub visibility_timeout_seconds: u32,
1984    pub retention_seconds: u32,
1985    #[serde(default, skip_serializing_if = "Option::is_none")]
1986    pub dead_letter_queue_id: Option<String>,
1987    #[serde(default, skip_serializing_if = "Option::is_none")]
1988    pub max_receive_count: Option<u32>,
1989}
1990
1991#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1992#[serde(rename_all = "snake_case")]
1993pub enum ScheduleCompletionAction {
1994    Delete,
1995}
1996
1997#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1998pub struct ScheduleCleanupPlan {
1999    pub action_after_completion: ScheduleCompletionAction,
2000    pub residual_resources: Vec<String>,
2001    pub manual_fallback: String,
2002}
2003
2004#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2005#[serde(tag = "kind", rename_all = "snake_case")]
2006pub enum TriggerPlan {
2007    HttpApi {
2008        id: String,
2009        function_id: String,
2010    },
2011    Sqs {
2012        id: String,
2013        function_id: String,
2014        queue_id: String,
2015        batch_size: u32,
2016        batching_window_seconds: u32,
2017        report_batch_item_failures: bool,
2018        maximum_concurrency: u32,
2019    },
2020    Schedule {
2021        id: String,
2022        function_id: String,
2023        expression: String,
2024        enabled: bool,
2025        purpose: String,
2026        #[serde(default, skip_serializing_if = "Option::is_none")]
2027        cleanup: Option<ScheduleCleanupPlan>,
2028    },
2029}
2030
2031#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2032pub struct IamIntent {
2033    pub function_id: String,
2034    pub actions: Vec<String>,
2035    pub resource: IamResource,
2036}
2037
2038#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2039#[serde(tag = "kind", rename_all = "snake_case")]
2040pub enum IamResource {
2041    DatabaseUrlParameter,
2042    DatabaseUrlKmsKey,
2043    DynamoDbTable { logical_id: String },
2044    Queue { queue_id: String },
2045    Function { function_id: String },
2046}
2047
2048pub fn derive_iam_intents(
2049    schema_version: u32,
2050    runtime: &RuntimePlan,
2051    database: &DatabaseDeployment,
2052    application_graph: &ApplicationGraph,
2053    functions: &[FunctionPlan],
2054    triggers: &[TriggerPlan],
2055) -> Vec<IamIntent> {
2056    if schema_version != 2 {
2057        return Vec::new();
2058    }
2059    let mut intents = Vec::new();
2060    if matches!(runtime, RuntimePlan::LambdaZipArm64)
2061        && let Some(table) = database.dynamodb_table()
2062    {
2063        intents.push(IamIntent {
2064            function_id: table.function_id.clone(),
2065            actions: [
2066                "dynamodb:DescribeTable",
2067                "dynamodb:GetItem",
2068                "dynamodb:Query",
2069                "dynamodb:TransactWriteItems",
2070                "dynamodb:UpdateItem",
2071            ]
2072            .into_iter()
2073            .map(str::to_owned)
2074            .collect(),
2075            resource: IamResource::DynamoDbTable {
2076                logical_id: table.logical_id.clone(),
2077            },
2078        });
2079    }
2080    if matches!(runtime, RuntimePlan::LambdaZipArm64)
2081        && let Some(table) = derive_dynamodb_audit_table(database, application_graph)
2082    {
2083        intents.push(IamIntent {
2084            function_id: table.function_id.clone(),
2085            actions: DYNAMODB_AUDIT_TABLE_ACTIONS
2086                .into_iter()
2087                .map(str::to_owned)
2088                .collect(),
2089            resource: IamResource::DynamoDbTable {
2090                logical_id: table.logical_id,
2091            },
2092        });
2093    }
2094    if matches!(runtime, RuntimePlan::LambdaZipArm64)
2095        && matches!(
2096            database,
2097            DatabaseDeployment::NeonPostgres { .. }
2098                | DatabaseDeployment::SelfHostedPostgres { .. }
2099                | DatabaseDeployment::RdsPostgres { .. }
2100                | DatabaseDeployment::AuroraServerlessV2 { .. }
2101        )
2102    {
2103        for function in functions
2104            .iter()
2105            .filter(|function| function.database_connections_per_instance > 0)
2106        {
2107            intents.push(IamIntent {
2108                function_id: function.name.clone(),
2109                actions: vec!["ssm:GetParameter".into()],
2110                resource: IamResource::DatabaseUrlParameter,
2111            });
2112            intents.push(IamIntent {
2113                function_id: function.name.clone(),
2114                actions: vec!["kms:Decrypt".into()],
2115                resource: IamResource::DatabaseUrlKmsKey,
2116            });
2117        }
2118    }
2119    for trigger in triggers {
2120        match trigger {
2121            TriggerPlan::Sqs {
2122                function_id,
2123                queue_id,
2124                ..
2125            } => {
2126                intents.push(IamIntent {
2127                    function_id: function_id.clone(),
2128                    actions: [
2129                        "sqs:ChangeMessageVisibility",
2130                        "sqs:DeleteMessage",
2131                        "sqs:GetQueueAttributes",
2132                        "sqs:ReceiveMessage",
2133                    ]
2134                    .into_iter()
2135                    .map(str::to_owned)
2136                    .collect(),
2137                    resource: IamResource::Queue {
2138                        queue_id: queue_id.clone(),
2139                    },
2140                });
2141            }
2142            TriggerPlan::Schedule { function_id, .. } => {
2143                intents.push(IamIntent {
2144                    function_id: function_id.clone(),
2145                    actions: vec!["lambda:InvokeFunction".into()],
2146                    resource: IamResource::Function {
2147                        function_id: function_id.clone(),
2148                    },
2149                });
2150            }
2151            TriggerPlan::HttpApi { .. } => {}
2152        }
2153    }
2154    intents.sort_by(|left, right| {
2155        left.function_id
2156            .cmp(&right.function_id)
2157            .then_with(|| iam_resource_key(&left.resource).cmp(&iam_resource_key(&right.resource)))
2158    });
2159    intents
2160}
2161
2162fn derive_dynamodb_audit_table(
2163    database: &DatabaseDeployment,
2164    application_graph: &ApplicationGraph,
2165) -> Option<DynamoDbTablePlan> {
2166    if !application_graph.capabilities.contains_key("audit.ledger") {
2167        return None;
2168    }
2169    let table = database.dynamodb_table()?;
2170    let logical_prefix = table
2171        .logical_id
2172        .strip_suffix("Table")
2173        .unwrap_or(&table.logical_id);
2174    Some(DynamoDbTablePlan {
2175        logical_id: format!("{logical_prefix}AuditTable"),
2176        function_id: table.function_id.clone(),
2177        partition_key: DynamoDbKeyAttribute {
2178            name: "pk".into(),
2179            scalar_type: DynamoDbScalarType::String,
2180        },
2181        sort_key: Some(DynamoDbKeyAttribute {
2182            name: "sk".into(),
2183            scalar_type: DynamoDbScalarType::String,
2184        }),
2185        global_secondary_indexes: Vec::new(),
2186        point_in_time_recovery: true,
2187        deletion_policy: DynamoDbDeletionPolicy::Retain,
2188    })
2189}
2190
2191fn iam_resource_key(resource: &IamResource) -> (&str, &str) {
2192    match resource {
2193        IamResource::DatabaseUrlParameter => ("database_url_parameter", ""),
2194        IamResource::DatabaseUrlKmsKey => ("database_url_kms_key", ""),
2195        IamResource::DynamoDbTable { logical_id } => ("dynamodb_table", logical_id),
2196        IamResource::Queue { queue_id } => ("queue", queue_id),
2197        IamResource::Function { function_id } => ("function", function_id),
2198    }
2199}
2200
2201impl TriggerPlan {
2202    fn id(&self) -> &str {
2203        match self {
2204            Self::HttpApi { id, .. } | Self::Sqs { id, .. } | Self::Schedule { id, .. } => id,
2205        }
2206    }
2207}
2208
2209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2210pub struct RoutePlan {
2211    pub operation_id: String,
2212    pub method: HttpMethod,
2213    pub path: String,
2214    pub authenticated: bool,
2215}
2216
2217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2218// Each independent switch is part of the serialized deployment-policy contract.
2219#[allow(clippy::struct_excessive_bools)]
2220pub struct CostPolicy {
2221    pub deny_fixed_compute: bool,
2222    pub deny_nat_gateway: bool,
2223    pub deny_provisioned_concurrency: bool,
2224    pub deny_scheduled_wakeups: bool,
2225    pub max_reserved_concurrency: u32,
2226    pub max_database_connections: u32,
2227}
2228
2229impl Default for CostPolicy {
2230    fn default() -> Self {
2231        Self {
2232            deny_fixed_compute: true,
2233            deny_nat_gateway: true,
2234            deny_provisioned_concurrency: true,
2235            deny_scheduled_wakeups: true,
2236            max_reserved_concurrency: 5,
2237            max_database_connections: 20,
2238        }
2239    }
2240}
2241
2242#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2243pub struct PerformancePolicy {
2244    pub max_lambda_timeout_seconds: u32,
2245    pub max_lambda_memory_mb: u32,
2246    pub max_request_body_bytes: u64,
2247    pub target_artifact_bytes: u64,
2248}
2249
2250impl Default for PerformancePolicy {
2251    fn default() -> Self {
2252        Self {
2253            max_lambda_timeout_seconds: 30,
2254            max_lambda_memory_mb: 1024,
2255            max_request_body_bytes: 1_048_576,
2256            target_artifact_bytes: 25 * 1024 * 1024,
2257        }
2258    }
2259}
2260
2261const fn default_log_retention_days() -> u32 {
2262    14
2263}
2264
2265fn default_allowed_headers() -> Vec<String> {
2266    [
2267        "authorization",
2268        "content-type",
2269        "idempotency-key",
2270        "if-match",
2271        "if-none-match",
2272        "x-request-id",
2273    ]
2274    .into_iter()
2275    .map(str::to_owned)
2276    .collect()
2277}
2278
2279fn default_exposed_headers() -> Vec<String> {
2280    [
2281        "deprecation",
2282        "etag",
2283        "link",
2284        "location",
2285        "retry-after",
2286        "sunset",
2287        "www-authenticate",
2288        "x-request-id",
2289    ]
2290    .into_iter()
2291    .map(str::to_owned)
2292    .collect()
2293}
2294
2295fn error(code: &str, message: &str) -> PlanDiagnostic {
2296    PlanDiagnostic {
2297        code: code.into(),
2298        severity: Severity::Error,
2299        message: message.into(),
2300    }
2301}
2302
2303fn warning(code: &str, message: &str) -> PlanDiagnostic {
2304    PlanDiagnostic {
2305        code: code.into(),
2306        severity: Severity::Warning,
2307        message: message.into(),
2308    }
2309}
2310
2311fn information(code: &str, message: &str) -> PlanDiagnostic {
2312    PlanDiagnostic {
2313        code: code.into(),
2314        severity: Severity::Information,
2315        message: message.into(),
2316    }
2317}
2318
2319#[derive(Debug, Error)]
2320pub enum PlanError {
2321    #[error("failed to serialize plan: {0}")]
2322    Json(#[from] serde_json::Error),
2323    #[error("unsupported SAM route method: {0}")]
2324    UnsupportedMethod(String),
2325    #[error("deployment plan has no API function")]
2326    MissingFunction,
2327    #[error("unsupported deployment combination: {0}")]
2328    UnsupportedDeployment(String),
2329    #[error("deployment plan schema migration failed: {0}")]
2330    SchemaMigration(String),
2331}
2332
2333#[cfg(test)]
2334mod tests {
2335    use super::*;
2336    use minco_contract::{ContractDocument, OwnedOperation};
2337    use minco_core::{
2338        GraphBuilder, IdleCostClass, PluginDescriptor, PluginId, ResourceIntent, ResourceKind,
2339    };
2340
2341    fn config(database: DatabaseDeployment) -> DeploymentConfig {
2342        DeploymentConfig {
2343            schema_version: 1,
2344            application: "example".into(),
2345            environment: "dev".into(),
2346            region: "ap-southeast-2".into(),
2347            runtime: RuntimePlan::LambdaZipArm64,
2348            ingress: IngressPlan::ApiGatewayHttpApi,
2349            auth: AuthPlan::Jwt {
2350                issuer: "https://issuer.example.invalid".into(),
2351                audiences: vec!["orders".into()],
2352            },
2353            database,
2354            functions: vec![FunctionPlan {
2355                name: "api".into(),
2356                role: FunctionRole::HttpApi,
2357                artifact_path: "target/lambda/orders-lambda/bootstrap.zip".into(),
2358                memory_mb: 512,
2359                timeout_seconds: 15,
2360                reserved_concurrency: 2,
2361                provisioned_concurrency: 0,
2362                database_connections_per_instance: 2,
2363            }],
2364            queues: Vec::new(),
2365            triggers: Vec::new(),
2366            scheduled_wakeups: Vec::new(),
2367            uses_nat_gateway: false,
2368            allowed_origins: vec!["https://app.example.invalid".into()],
2369            allowed_headers: default_allowed_headers(),
2370            log_retention_days: 14,
2371            cost_policy: CostPolicy::default(),
2372            performance_policy: PerformancePolicy::default(),
2373        }
2374    }
2375
2376    #[test]
2377    fn routes_are_derived_from_the_contract() {
2378        let contract = ContractDocument {
2379            source: "inline".into(),
2380            openapi_version: "3.1.0".into(),
2381            title: "test".into(),
2382            version: "1".into(),
2383            sha256: "hash".into(),
2384            operations: vec![OwnedOperation {
2385                operation_id: "getHealth".into(),
2386                method: HttpMethod::Get,
2387                path: "/health".into(),
2388                authenticated: false,
2389                idempotent: false,
2390            }],
2391            schema_names: Vec::new(),
2392            raw: serde_json::json!({}),
2393        };
2394        let plan = config(DatabaseDeployment::NeonPostgres {
2395            plan: NeonPlan::Free,
2396            compute_unit_hours: 1.0,
2397            storage_gb_month: 0.1,
2398            history_storage_gb_month: 0.0,
2399        })
2400        .into_plan(&contract);
2401        assert_eq!(plan.routes[0].operation_id, "getHealth");
2402    }
2403
2404    #[test]
2405    fn request_headers_are_normalized_and_sorted_in_the_plan() {
2406        let contract = ContractDocument {
2407            source: "inline".into(),
2408            openapi_version: "3.1.0".into(),
2409            title: "test".into(),
2410            version: "1".into(),
2411            sha256: "hash".into(),
2412            operations: Vec::new(),
2413            schema_names: Vec::new(),
2414            raw: serde_json::json!({}),
2415        };
2416        let mut deployment = config(DatabaseDeployment::NeonPostgres {
2417            plan: NeonPlan::Free,
2418            compute_unit_hours: 1.0,
2419            storage_gb_month: 0.1,
2420            history_storage_gb_month: 0.0,
2421        });
2422        deployment.allowed_headers = vec!["X-Request-ID".into(), "Authorization".into()];
2423        let plan = deployment.into_plan(&contract);
2424        assert_eq!(plan.allowed_headers, ["authorization", "x-request-id"]);
2425    }
2426
2427    #[test]
2428    fn default_request_headers_include_the_resource_preconditions() {
2429        assert_eq!(
2430            default_allowed_headers(),
2431            [
2432                "authorization",
2433                "content-type",
2434                "idempotency-key",
2435                "if-match",
2436                "if-none-match",
2437                "x-request-id",
2438            ]
2439        );
2440    }
2441
2442    #[test]
2443    fn plan_exposes_the_exact_frontend_neutral_response_headers() {
2444        let contract = ContractDocument {
2445            source: "inline".into(),
2446            openapi_version: "3.1.0".into(),
2447            title: "test".into(),
2448            version: "1".into(),
2449            sha256: "hash".into(),
2450            operations: Vec::new(),
2451            schema_names: Vec::new(),
2452            raw: serde_json::json!({}),
2453        };
2454        let plan = config(DatabaseDeployment::NeonPostgres {
2455            plan: NeonPlan::Free,
2456            compute_unit_hours: 1.0,
2457            storage_gb_month: 0.1,
2458            history_storage_gb_month: 0.0,
2459        })
2460        .into_plan(&contract);
2461
2462        assert_eq!(plan.exposed_headers, default_exposed_headers());
2463    }
2464
2465    #[test]
2466    fn plan_serializes_the_selected_graph_and_derives_local_aws_services() {
2467        let contract = ContractDocument {
2468            source: "inline".into(),
2469            openapi_version: "3.1.0".into(),
2470            title: "test".into(),
2471            version: "1".into(),
2472            sha256: "hash".into(),
2473            operations: Vec::new(),
2474            schema_names: Vec::new(),
2475            raw: serde_json::json!({}),
2476        };
2477        let mut descriptor = PluginDescriptor::new(
2478            PluginId::new("aws-provider").unwrap(),
2479            "1.0.0".parse().unwrap(),
2480            "AWS provider",
2481        );
2482        descriptor.resources.extend([
2483            ResourceIntent {
2484                id: "attachments".into(),
2485                kind: ResourceKind::S3Bucket,
2486                idle_cost: IdleCostClass::StorageOnly,
2487                wake_sources: Vec::new(),
2488                dependencies: Vec::new(),
2489            },
2490            ResourceIntent {
2491                id: "events".into(),
2492                kind: ResourceKind::SqsQueue,
2493                idle_cost: IdleCostClass::ZeroCompute,
2494                wake_sources: Vec::new(),
2495                dependencies: Vec::new(),
2496            },
2497        ]);
2498        let mut builder = GraphBuilder::default();
2499        builder.add_plugin(descriptor);
2500        let graph = builder.build().unwrap();
2501
2502        let plan = config(DatabaseDeployment::NeonPostgres {
2503            plan: NeonPlan::Free,
2504            compute_unit_hours: 1.0,
2505            storage_gb_month: 0.1,
2506            history_storage_gb_month: 0.0,
2507        })
2508        .into_plan_with_graph(&contract, graph);
2509
2510        assert_eq!(
2511            plan.application_graph.plugins[0].id.as_str(),
2512            "aws-provider"
2513        );
2514        assert_eq!(plan.local_aws_services, ["s3", "sqs", "ssm", "sts"]);
2515    }
2516
2517    #[test]
2518    fn plan_rejects_a_tampered_local_service_projection() {
2519        let contract = ContractDocument {
2520            source: "inline".into(),
2521            openapi_version: "3.1.0".into(),
2522            title: "test".into(),
2523            version: "1".into(),
2524            sha256: "hash".into(),
2525            operations: Vec::new(),
2526            schema_names: Vec::new(),
2527            raw: serde_json::json!({}),
2528        };
2529        let mut plan = config(DatabaseDeployment::NeonPostgres {
2530            plan: NeonPlan::Free,
2531            compute_unit_hours: 1.0,
2532            storage_gb_month: 0.1,
2533            history_storage_gb_month: 0.0,
2534        })
2535        .into_plan(&contract);
2536        plan.local_aws_services.push("s3".into());
2537
2538        assert!(
2539            plan.validate()
2540                .iter()
2541                .any(|diagnostic| diagnostic.code == "MINCO-PLAN-003")
2542        );
2543    }
2544
2545    #[test]
2546    fn function_url_is_declared_but_rejected_before_rendering() {
2547        let contract = ContractDocument {
2548            source: "inline".into(),
2549            openapi_version: "3.1.0".into(),
2550            title: "test".into(),
2551            version: "1".into(),
2552            sha256: "hash".into(),
2553            operations: Vec::new(),
2554            schema_names: Vec::new(),
2555            raw: serde_json::json!({}),
2556        };
2557        let mut deployment = config(DatabaseDeployment::NeonPostgres {
2558            plan: NeonPlan::Free,
2559            compute_unit_hours: 1.0,
2560            storage_gb_month: 0.1,
2561            history_storage_gb_month: 0.0,
2562        });
2563        deployment.ingress = IngressPlan::LambdaFunctionUrl;
2564        let plan = deployment.into_plan(&contract);
2565
2566        assert!(
2567            plan.validate()
2568                .iter()
2569                .any(|diagnostic| diagnostic.code == "MINCO-PLAN-INGRESS-001")
2570        );
2571    }
2572
2573    #[test]
2574    fn runtime_and_ingress_must_form_a_supported_topology() {
2575        let contract = ContractDocument {
2576            source: "inline".into(),
2577            openapi_version: "3.1.0".into(),
2578            title: "test".into(),
2579            version: "1".into(),
2580            sha256: "hash".into(),
2581            operations: Vec::new(),
2582            schema_names: Vec::new(),
2583            raw: serde_json::json!({}),
2584        };
2585        let mut deployment = config(DatabaseDeployment::NeonPostgres {
2586            plan: NeonPlan::Free,
2587            compute_unit_hours: 1.0,
2588            storage_gb_month: 0.1,
2589            history_storage_gb_month: 0.0,
2590        });
2591        deployment.runtime = RuntimePlan::LocalNative;
2592        let plan = deployment.into_plan(&contract);
2593
2594        assert!(
2595            plan.validate()
2596                .iter()
2597                .any(|diagnostic| diagnostic.code == "MINCO-PLAN-INGRESS-002")
2598        );
2599    }
2600
2601    #[test]
2602    fn fixed_compute_is_rejected_by_minimal_idle_policy() {
2603        let contract = ContractDocument {
2604            source: "inline".into(),
2605            openapi_version: "3.1.0".into(),
2606            title: "test".into(),
2607            version: "1".into(),
2608            sha256: "hash".into(),
2609            operations: Vec::new(),
2610            schema_names: Vec::new(),
2611            raw: serde_json::json!({}),
2612        };
2613        let plan = config(DatabaseDeployment::RdsPostgres {
2614            instance_hours: 730.0,
2615            instance_hour_rate_usd: Some(0.1),
2616            storage_gb_month: 20.0,
2617            storage_rate_usd: Some(0.1),
2618            backup_gb_month: 0.0,
2619            backup_rate_usd: Some(0.0),
2620            multi_az_multiplier: 1.0,
2621        })
2622        .into_plan(&contract);
2623        assert!(
2624            plan.validate()
2625                .iter()
2626                .any(|diagnostic| diagnostic.code == "MINCO-COST-007")
2627        );
2628    }
2629
2630    #[test]
2631    fn negative_cost_inputs_are_rejected() {
2632        let contract = ContractDocument {
2633            source: "inline".into(),
2634            openapi_version: "3.1.0".into(),
2635            title: "test".into(),
2636            version: "1".into(),
2637            sha256: "hash".into(),
2638            operations: Vec::new(),
2639            schema_names: Vec::new(),
2640            raw: serde_json::json!({}),
2641        };
2642        let plan = config(DatabaseDeployment::SelfHostedPostgres {
2643            host_monthly_usd: -1.0,
2644            storage_gb_month: 20.0,
2645            storage_rate_usd: 0.08,
2646            backup_gb_month: 20.0,
2647            backup_rate_usd: 0.05,
2648            operations_monthly_usd: 50.0,
2649        })
2650        .into_plan(&contract);
2651
2652        assert!(
2653            plan.validate()
2654                .iter()
2655                .any(|diagnostic| diagnostic.code == "MINCO-COST-008")
2656        );
2657    }
2658
2659    #[test]
2660    fn aurora_auto_pause_interval_must_match_zero_capacity() {
2661        let contract = ContractDocument {
2662            source: "inline".into(),
2663            openapi_version: "3.1.0".into(),
2664            title: "test".into(),
2665            version: "1".into(),
2666            sha256: "hash".into(),
2667            operations: Vec::new(),
2668            schema_names: Vec::new(),
2669            raw: serde_json::json!({}),
2670        };
2671        let invalid_timeout = config(DatabaseDeployment::AuroraServerlessV2 {
2672            minimum_acu: 0.0,
2673            auto_pause_seconds: Some(299),
2674            acu_hours: 1.0,
2675            acu_hour_rate_usd: Some(0.1),
2676            storage_gb_month: 1.0,
2677            storage_rate_usd: Some(0.1),
2678            io_million: 1.0,
2679            io_million_rate_usd: Some(0.1),
2680        })
2681        .into_plan(&contract);
2682        let nonzero_minimum = config(DatabaseDeployment::AuroraServerlessV2 {
2683            minimum_acu: 0.5,
2684            auto_pause_seconds: Some(300),
2685            acu_hours: 1.0,
2686            acu_hour_rate_usd: Some(0.1),
2687            storage_gb_month: 1.0,
2688            storage_rate_usd: Some(0.1),
2689            io_million: 1.0,
2690            io_million_rate_usd: Some(0.1),
2691        })
2692        .into_plan(&contract);
2693
2694        assert!(
2695            invalid_timeout
2696                .validate()
2697                .iter()
2698                .any(|diagnostic| diagnostic.code == "MINCO-DB-004")
2699        );
2700        assert!(
2701            nonzero_minimum
2702                .validate()
2703                .iter()
2704                .any(|diagnostic| diagnostic.code == "MINCO-DB-004")
2705        );
2706    }
2707}