Skip to main content

stackless_integrations/providers/blaxel/
sandbox.rs

1//! `blaxel/sandbox` integration.
2
3use std::collections::BTreeMap;
4
5use serde::Serialize;
6use stackless_stripe_projects::catalog::verify::CatalogService;
7use stackless_stripe_projects::provision::ProvisionContext;
8
9use super::FamilyResource;
10use crate::error::IntegrationError;
11use crate::hostable::{ConfigScope, Hostable, IntegrationHosting};
12
13pub const RESOURCE_KIND: &str = "integration-blaxel-sandbox";
14
15#[derive(Debug, Serialize)]
16pub struct BlaxelSandboxConfig {
17    #[serde(skip_serializing_if = "Option::is_none")]
18    pub display_name: Option<String>,
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub image: Option<String>,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub memory: Option<i64>,
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub region: Option<String>,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub ttl: Option<String>,
27}
28
29impl CatalogService for BlaxelSandboxConfig {
30    const REFERENCE: &'static str = "blaxel/sandbox";
31}
32
33#[derive(Debug)]
34pub struct BlaxelSandbox;
35
36impl Hostable for BlaxelSandbox {
37    const PROVIDER: &'static str = "blaxel-sandbox";
38    const HOSTING: IntegrationHosting = IntegrationHosting::Managed;
39    const CONFIG_SCOPE: ConfigScope = ConfigScope::GlobalOnly;
40    const RESOURCE_KIND: &'static str = RESOURCE_KIND;
41    const OUTPUTS: &'static [&'static str] = &[
42        "api_key",
43        "resource_name",
44        "service_account_client_id",
45        "workspace",
46    ];
47}
48
49impl FamilyResource for BlaxelSandbox {
50    type Config = BlaxelSandboxConfig;
51    const PROVIDER_PREFIX: &'static str = "BLAXEL";
52    const OUTPUT_FIELDS: &'static [(&'static str, &'static str, bool)] = &[
53        ("API_KEY", "api_key", true),
54        ("RESOURCE_NAME", "resource_name", true),
55        (
56            "SERVICE_ACCOUNT_CLIENT_ID",
57            "service_account_client_id",
58            true,
59        ),
60        ("WORKSPACE", "workspace", true),
61    ];
62
63    fn build_config(ctx: &ProvisionContext<'_>) -> Result<BlaxelSandboxConfig, IntegrationError> {
64        let config = super::integration_config(ctx)?;
65        Ok(BlaxelSandboxConfig {
66            display_name: super::interp_optional(ctx, &config, "display_name")?,
67            image: super::interp_optional(ctx, &config, "image")?,
68            memory: super::int_optional(ctx, &config, "memory")?,
69            region: super::interp_optional(ctx, &config, "region")?,
70            ttl: super::interp_optional(ctx, &config, "ttl")?,
71        })
72    }
73}
74
75pub fn validate_config(
76    name: &str,
77    config: &BTreeMap<String, toml::Value>,
78) -> Result<(), IntegrationError> {
79    let _ = (name, config);
80    Ok(())
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use crate::ProviderOps;
87    use crate::resource::ResourcePayload;
88    use stackless_core::def::StackDef;
89    use stackless_stripe_projects::stripe::StripeProjects;
90    use stackless_stripe_projects::test_support;
91
92    #[test]
93    fn config_matches_catalog() {
94        const FIXTURE: &str = include_str!(concat!(
95            env!("CARGO_MANIFEST_DIR"),
96            "/../stackless-stripe-projects/tests/fixtures/catalog.json"
97        ));
98        let catalog = stackless_stripe_projects::Catalog::from_json_envelope(FIXTURE).unwrap();
99        let failures = stackless_stripe_projects::verify_service(
100            &catalog,
101            &BlaxelSandboxConfig {
102                display_name: None,
103                image: None,
104                memory: None,
105                region: None,
106                ttl: None,
107            },
108        );
109        assert!(
110            failures.is_empty(),
111            "blaxel/sandbox catalog gaps:\n{}",
112            failures.join("\n")
113        );
114    }
115
116    const CATALOG_ENVELOPE: &str = r##"{"ok":true,"command":"projects catalog","data":{"last_updated":"2026-07-11T00:00:00Z","services":[{"id":"prvsvc_sandbox","object":"v2.provisioning.provider_service_detail","provider_id":"prvdr_blaxel","provider_name":"Blaxel","service_id":"sandbox","categories":["database"],"kind":"deployable","scope":"project","availability":"available","development":false,"livemode":true,"pricing":{"type":"free"},"configuration_schema":{"additionalProperties":false,"properties":{"display_name":{"description":"Human-readable display name shown in the Blaxel dashboard.","type":"string"},"image":{"description":"Base image for the sandbox.","enum":["blaxel/base-image:latest","blaxel/ts-app:latest","blaxel/node:latest","blaxel/py-app:latest","blaxel/nextjs:latest","blaxel/vite:latest","blaxel/expo:latest"],"type":"string"},"memory":{"description":"Memory in MB. CPU is derived automatically.","enum":[1024,2048,4096,8192,16384],"type":"integer"},"region":{"description":"Region where the sandbox runs.","enum":["us-pdx-1","us-was-1","eu-lon-1","eu-fra-1"],"type":"string"},"ttl":{"description":"Max-age TTL from creation. Sandbox is deleted after this duration.","enum":["24h","7d","30d"],"type":"string"}},"required":[],"type":"object"}}]}}"##;
117
118    fn test_def() -> StackDef {
119        StackDef::parse(
120            r#"
121[stack]
122name = "atto"
123[stack.projects.stripe]
124project = "project_1"
125[integrations.res]
126provider = "blaxel-sandbox"
127[services.api]
128source = { repo = "r", ref = "main" }
129env = { OUT = "${integrations.res.api_key}" }
130health = { path = "/health" }
131[services.api.local]
132run = "true"
133"#,
134        )
135        .unwrap()
136    }
137
138    #[tokio::test]
139    async fn provision_records_outputs() {
140        let runner = test_support::provision_script(
141            CATALOG_ENVELOPE,
142            serde_json::json!({
143                "BLAXEL_API_KEY": "val_api_key",
144                "BLAXEL_RESOURCE_NAME": "val_resource_name",
145                "BLAXEL_SERVICE_ACCOUNT_CLIENT_ID": "val_service_account_client_id",
146                "BLAXEL_WORKSPACE": "val_workspace"
147            }),
148            0,
149        );
150        let dir = tempfile::tempdir().unwrap();
151        std::fs::write(
152            dir.path().join("stackless.toml"),
153            "[stack]\nname=\"atto\"\n",
154        )
155        .unwrap();
156        let stripe = StripeProjects::new(&runner, dir.path());
157
158        let resource = BlaxelSandbox
159            .provision(
160                &stripe.as_dyn(),
161                &test_def(),
162                dir.path(),
163                "demo",
164                "res",
165                "local",
166                false,
167            )
168            .await
169            .unwrap();
170        assert_eq!(resource.resource_kind, "integration-blaxel-sandbox");
171        let payload: ResourcePayload = serde_json::from_str(&resource.payload).unwrap();
172        assert_eq!(payload.outputs["api_key"], "val_api_key");
173        assert_eq!(payload.outputs["resource_name"], "val_resource_name");
174        assert_eq!(
175            payload.outputs["service_account_client_id"],
176            "val_service_account_client_id"
177        );
178        assert_eq!(payload.outputs["workspace"], "val_workspace");
179    }
180}