Skip to main content

alien_core/
gateability.rs

1//! The single authority on which resources may carry an `.enabled()` gate.
2//!
3//! Both the compile-time check (`ResourceEnabledValidCheck`) and the setup
4//! generators consult this module, so a caller that renders without running
5//! preflights hits the same refusals. The rules live here rather than in the
6//! preflight crate because the generators must not depend on preflights, and
7//! duplicating the rules would let them drift.
8//!
9//! Extension resource types registered outside this crate are gateable by
10//! default (their ownership policy is `user_choice`), matching how the emitter
11//! registries treat them: the generic gating post-pass needs nothing from the
12//! emitter, so there is nothing for an extension to opt into.
13
14use crate::ownership_policy_for_resource_type;
15
16/// Reserved id of the deployment secrets vault.
17///
18/// `SecretsVaultMutation` links this vault to Live Workers and compute
19/// clusters after compile-time checks run, so its presence can never be
20/// optional. Owned here so the gating rules and the mutation agree on one
21/// constant.
22pub const SECRETS_VAULT_ID: &str = "secrets";
23
24/// Framework and auxiliary infrastructure Alien derives from the stack, the
25/// platform, or the deployment settings. A gate here is never a customer
26/// choice: `ServiceAccountMutation` inserts profile-derived "{profile}-sa"
27/// entries unconditionally, the Azure `default-*` resources are
28/// preflight-injected hosts other resources build on, and network presence is
29/// a StackSettings decision, not a stack-resource one. Both naming variants
30/// are listed where the ownership table accepts both.
31const STACK_DERIVED_TYPES: &[&str] = &[
32    "build",
33    "artifact-registry",
34    "service-account",
35    "compute-cluster",
36    "kubernetes-cluster",
37    "network",
38    "remote-stack-management",
39    "service_activation",
40    "service-activation",
41    "azure_resource_group",
42    "azure-resource-group",
43    "azure_storage_account",
44    "azure-storage-account",
45    "azure_container_apps_environment",
46    "azure-container-apps-environment",
47    "azure_service_bus_namespace",
48    "azure-service-bus-namespace",
49];
50
51/// Types whose setup emitters have not been proven under the generic gating
52/// post-pass yet. Emptied as each type's gated render is validated; the list
53/// exists so switching the mechanism cannot silently open gating for a type
54/// nobody has rendered gated before.
55const NOT_YET_GENERIC_TYPES: &[&str] = &[];
56
57/// Why a resource cannot carry an `.enabled()` gate.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum GateRefusal {
60    /// The reserved deployment secrets vault (`SECRETS_VAULT_ID`).
61    ReservedSecretsVault,
62    /// Framework infrastructure derived from the stack itself.
63    DerivedFromStack,
64    /// The type's gated setup render has not been validated yet.
65    NotYetGeneric,
66}
67
68impl GateRefusal {
69    /// The reason clause, phrased to follow "Resource 'x' is enabled by input
70    /// 'y', but ...". Callers compose the full message so the preflight and
71    /// the generators report identically.
72    pub fn reason(self) -> &'static str {
73        match self {
74            GateRefusal::ReservedSecretsVault => {
75                "it is the deployment secrets vault. Workers and compute clusters are wired to \
76                 it automatically after compile-time checks run, so a deployer who says no would \
77                 leave them resolving a binding for a vault that was never created. Its presence \
78                 cannot be optional. Give a vault you want to gate a different id"
79            }
80            GateRefusal::DerivedFromStack => {
81                "Alien derives this resource from the stack itself, so it cannot be optional"
82            }
83            GateRefusal::NotYetGeneric => {
84                "this resource type's conditional setup render has not been validated yet, so \
85                 the resource would be created regardless of the deployer's answer"
86            }
87        }
88    }
89}
90
91/// Whether a resource may carry an `.enabled()` gate at all. `None` means
92/// gateable. Lifecycle legality is not decided here — a lifecycle the type
93/// does not allow is refused by the lifecycle rules regardless of gating.
94pub fn gate_refusal(resource_type: &str, resource_id: &str) -> Option<GateRefusal> {
95    if resource_id == SECRETS_VAULT_ID {
96        return Some(GateRefusal::ReservedSecretsVault);
97    }
98    if STACK_DERIVED_TYPES.contains(&resource_type) {
99        return Some(GateRefusal::DerivedFromStack);
100    }
101    // Compute (worker, daemon, container) is deliberately gateable: declining
102    // a live workload rides the same removal path as deleting it from a
103    // release, and its provisioning baseline persists so acceptance can
104    // return. Pausing the sole consumer of an ungated queue is allowed by
105    // design — the queue's retention policy governs the backlog.
106    if NOT_YET_GENERIC_TYPES.contains(&resource_type) {
107        return Some(GateRefusal::NotYetGeneric);
108    }
109    None
110}
111
112/// Per-lifecycle gateability of one resource type, derived from the ownership
113/// table and the gate refusals. Serialized into the generated manifest the
114/// TypeScript SDK's surface test consumes.
115#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
116#[serde(rename_all = "camelCase")]
117pub struct TypeGateability {
118    /// The gate may appear on a Frozen entry of this type.
119    pub frozen: bool,
120    /// The gate may appear on a Live entry of this type.
121    pub live: bool,
122}
123
124/// Gateability of one built-in user resource type, keyed for the manifest.
125pub fn type_gateability(resource_type: &str) -> TypeGateability {
126    let policy = ownership_policy_for_resource_type(resource_type);
127    // The id-based rule cannot be evaluated per type; the manifest describes
128    // types, and the reserved vault id is refused per entry.
129    let gateable = gate_refusal(resource_type, "").is_none();
130    TypeGateability {
131        frozen: gateable && policy.allows_frozen(),
132        live: gateable && policy.allows_live(),
133    }
134}
135
136/// The built-in user resource types listed in the generated manifest. The SDK
137/// builder surface is asserted against exactly this set.
138pub const MANIFEST_TYPES: &[&str] = &[
139    "kv",
140    "storage",
141    "queue",
142    "vault",
143    "postgres",
144    "worker",
145    "daemon",
146    "container",
147    "email",
148    "experimental/aws-opensearch",
149];
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[test]
156    fn stores_are_gateable_in_both_lifecycles() {
157        for store in ["kv", "storage", "queue", "vault"] {
158            assert_eq!(gate_refusal(store, "analytics"), None, "{store}");
159            let gateability = type_gateability(store);
160            assert!(gateability.frozen && gateability.live, "{store}");
161        }
162    }
163
164    #[test]
165    fn postgres_is_live_gateable_only() {
166        assert_eq!(gate_refusal("postgres", "db"), None);
167        let gateability = type_gateability("postgres");
168        // Frozen postgres has no setup emitter today; the gate rule allows it
169        // and the missing emitter refuses the render, exactly as for an
170        // ungated frozen postgres.
171        assert!(gateability.live);
172    }
173
174    #[test]
175    fn compute_is_live_gateable() {
176        for compute in ["worker", "daemon", "container"] {
177            assert_eq!(gate_refusal(compute, "api"), None, "{compute}");
178            let gateability = type_gateability(compute);
179            assert!(!gateability.frozen, "{compute} cannot be frozen");
180            assert!(gateability.live, "{compute} gates as a live resource");
181        }
182    }
183
184    #[test]
185    fn stack_derived_types_are_refused() {
186        for framework in STACK_DERIVED_TYPES {
187            assert_eq!(
188                gate_refusal(framework, "x"),
189                Some(GateRefusal::DerivedFromStack),
190                "{framework}"
191            );
192        }
193    }
194
195    #[test]
196    fn the_reserved_secrets_vault_is_refused_by_id() {
197        assert_eq!(
198            gate_refusal("vault", SECRETS_VAULT_ID),
199            Some(GateRefusal::ReservedSecretsVault)
200        );
201        assert_eq!(gate_refusal("vault", "app-tokens"), None);
202    }
203
204    #[test]
205    fn email_and_opensearch_gate_as_frozen_resources() {
206        for setup_owned in ["email", "experimental/aws-opensearch"] {
207            assert_eq!(gate_refusal(setup_owned, "x"), None, "{setup_owned}");
208            let gateability = type_gateability(setup_owned);
209            assert!(gateability.frozen, "{setup_owned} gates at setup");
210            assert!(!gateability.live, "{setup_owned} has no runtime controller");
211        }
212    }
213
214    #[test]
215    fn extension_types_default_to_gateable() {
216        assert_eq!(gate_refusal("acme-widgets", "widgets"), None);
217        let gateability = type_gateability("acme-widgets");
218        assert!(gateability.frozen && gateability.live);
219    }
220}