Skip to main content

stackless_integrations/providers/planetscale/
mysql.rs

1//! `planetscale/mysql` 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};
12use crate::registry;
13
14pub const RESOURCE_KIND: &str = "integration-planetscale-mysql";
15
16#[derive(Debug, Serialize)]
17pub struct PlanetScaleMysqlConfig {
18    pub cluster: String,
19    pub name: String,
20    pub region: String,
21}
22
23impl CatalogService for PlanetScaleMysqlConfig {
24    const REFERENCE: &'static str = "planetscale/mysql";
25}
26
27#[derive(Debug)]
28pub struct PlanetScaleMysql;
29
30impl Hostable for PlanetScaleMysql {
31    const PROVIDER: &'static str = "planetscale-mysql";
32    const HOSTING: IntegrationHosting = IntegrationHosting::Managed;
33    const CONFIG_SCOPE: ConfigScope = ConfigScope::GlobalOnly;
34    const RESOURCE_KIND: &'static str = RESOURCE_KIND;
35    const OUTPUTS: &'static [&'static str] = &["url", "host", "database", "username", "password"];
36}
37
38impl FamilyResource for PlanetScaleMysql {
39    type Config = PlanetScaleMysqlConfig;
40    const PROVIDER_PREFIX: &'static str = "PLANETSCALE";
41    const OUTPUT_FIELDS: &'static [(&'static str, &'static str, bool)] = &[
42        ("URL", "url", true),
43        ("HOST", "host", false),
44        ("DATABASE", "database", true),
45        ("USERNAME", "username", true),
46        ("PASSWORD", "password", true),
47    ];
48
49    fn build_config(
50        ctx: &ProvisionContext<'_>,
51    ) -> Result<PlanetScaleMysqlConfig, IntegrationError> {
52        let config = super::integration_config(ctx)?;
53        Ok(PlanetScaleMysqlConfig {
54            cluster: super::interp_required(ctx, &config, "cluster")?,
55            name: super::interp_required(ctx, &config, "name")?,
56            region: super::interp_required(ctx, &config, "region")?,
57        })
58    }
59}
60
61pub fn validate_config(
62    name: &str,
63    config: &BTreeMap<String, toml::Value>,
64) -> Result<(), IntegrationError> {
65    registry::config_string(config, "cluster").map_err(|err| IntegrationError::ConfigInvalid {
66        location: format!("integrations.{name}.cluster"),
67        detail: err.to_string(),
68    })?;
69    registry::config_string(config, "name").map_err(|err| IntegrationError::ConfigInvalid {
70        location: format!("integrations.{name}.name"),
71        detail: err.to_string(),
72    })?;
73    registry::config_string(config, "region").map_err(|err| IntegrationError::ConfigInvalid {
74        location: format!("integrations.{name}.region"),
75        detail: err.to_string(),
76    })?;
77    let _ = (name, config);
78    Ok(())
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84    use crate::ProviderOps;
85    use crate::resource::ResourcePayload;
86    use stackless_core::def::StackDef;
87    use stackless_stripe_projects::stripe::StripeProjects;
88    use stackless_stripe_projects::test_support;
89
90    #[test]
91    fn config_matches_catalog() {
92        const FIXTURE: &str = include_str!(concat!(
93            env!("CARGO_MANIFEST_DIR"),
94            "/../stackless-stripe-projects/tests/fixtures/catalog.json"
95        ));
96        let catalog = stackless_stripe_projects::Catalog::from_json_envelope(FIXTURE).unwrap();
97        let failures = stackless_stripe_projects::verify_service(
98            &catalog,
99            &PlanetScaleMysqlConfig {
100                cluster: "PS-10".into(),
101                name: "test-name".into(),
102                region: "aws-ap-northeast".into(),
103            },
104        );
105        assert!(
106            failures.is_empty(),
107            "planetscale/mysql catalog gaps:\n{}",
108            failures.join("\n")
109        );
110    }
111
112    const CATALOG_ENVELOPE: &str = r##"{"ok":true,"command":"projects catalog","data":{"last_updated":"2026-07-11T00:00:00Z","services":[{"id":"prvsvc_mysql","object":"v2.provisioning.provider_service_detail","provider_id":"prvdr_planetscale","provider_name":"PlanetScale","service_id":"mysql","categories":["database"],"kind":"deployable","scope":"project","availability":"available","development":false,"livemode":true,"pricing":{"type":"paid"},"configuration_schema":{"properties":{"cluster":{"description":"Cluster size","enum":["PS-10","PS-20","PS-40","PS-80","PS-160","PS-320"],"type":"string"},"name":{"description":"Database name.","maxLength":63,"minLength":2,"pattern":"^[a-z0-9][a-z0-9_-]*[a-z0-9]$","type":"string"},"region":{"description":"Deployment region (prefixed with cloud provider, e.g., aws-us-east, gcp-us-central1)","enum":["aws-ap-northeast","aws-ap-south","aws-ap-southeast","aws-ap-southeast-2","aws-ca-central-1","aws-eu-central","aws-eu-west","aws-eu-west-2","aws-sa-east-1","aws-us-east","aws-us-east-2","aws-us-west","gcp-asia-northeast3","gcp-europe-west1","gcp-europe-west4","gcp-northamerica-northeast1","gcp-us-central1","gcp-us-east1","gcp-us-east4"],"type":"string"}},"required":["name","cluster","region"],"type":"object"}}]}}"##;
113
114    fn test_def() -> StackDef {
115        StackDef::parse(
116            r#"
117[stack]
118name = "atto"
119[stack.projects.stripe]
120project = "project_1"
121[integrations.res]
122provider = "planetscale-mysql"
123cluster = "PS-10"
124name = "test-name"
125region = "aws-ap-northeast"
126[services.api]
127source = { repo = "r", ref = "main" }
128env = { OUT = "${integrations.res.url}" }
129health = { path = "/health" }
130[services.api.local]
131run = "true"
132"#,
133        )
134        .unwrap()
135    }
136
137    #[tokio::test]
138    async fn provision_records_outputs() {
139        let runner = test_support::provision_script(
140            CATALOG_ENVELOPE,
141            serde_json::json!({"PLANETSCALE_URL": "val_url", "PLANETSCALE_HOST": "val_host", "PLANETSCALE_DATABASE": "val_database", "PLANETSCALE_USERNAME": "val_username", "PLANETSCALE_PASSWORD": "val_password"}),
142            0,
143        );
144        let dir = tempfile::tempdir().unwrap();
145        std::fs::write(
146            dir.path().join("stackless.toml"),
147            "[stack]\nname=\"atto\"\n",
148        )
149        .unwrap();
150        let stripe = StripeProjects::new(&runner, dir.path());
151
152        let resource = PlanetScaleMysql
153            .provision(
154                &stripe.as_dyn(),
155                &test_def(),
156                dir.path(),
157                "demo",
158                "res",
159                "local",
160                false,
161            )
162            .await
163            .unwrap();
164        assert_eq!(resource.resource_kind, "integration-planetscale-mysql");
165        let payload: ResourcePayload = serde_json::from_str(&resource.payload).unwrap();
166        assert_eq!(payload.outputs["url"], "val_url");
167    }
168}