Skip to main content

stackless_integrations/providers/planetscale/
postgresql.rs

1//! `planetscale/postgresql` 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-postgresql";
15
16#[derive(Debug, Serialize)]
17pub struct PlanetScalePostgresqlConfig {
18    pub cluster: String,
19    pub name: String,
20    pub region: String,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub replicas: Option<i64>,
23}
24
25impl CatalogService for PlanetScalePostgresqlConfig {
26    const REFERENCE: &'static str = "planetscale/postgresql";
27}
28
29#[derive(Debug)]
30pub struct PlanetScalePostgresql;
31
32impl Hostable for PlanetScalePostgresql {
33    const PROVIDER: &'static str = "planetscale-postgresql";
34    const HOSTING: IntegrationHosting = IntegrationHosting::Managed;
35    const CONFIG_SCOPE: ConfigScope = ConfigScope::GlobalOnly;
36    const RESOURCE_KIND: &'static str = RESOURCE_KIND;
37    const OUTPUTS: &'static [&'static str] = &["database_url"];
38}
39
40impl FamilyResource for PlanetScalePostgresql {
41    type Config = PlanetScalePostgresqlConfig;
42    const PROVIDER_PREFIX: &'static str = "PLANETSCALE";
43    // Provisional until pinned by `mise run discover planetscale/postgresql`.
44    const OUTPUT_FIELDS: &'static [(&'static str, &'static str, bool)] =
45        &[("DATABASE_URL", "database_url", true)];
46
47    fn build_config(
48        ctx: &ProvisionContext<'_>,
49    ) -> Result<PlanetScalePostgresqlConfig, IntegrationError> {
50        let config = super::integration_config(ctx)?;
51        Ok(PlanetScalePostgresqlConfig {
52            cluster: super::interp_required(ctx, &config, "cluster")?,
53            name: super::interp_required(ctx, &config, "name")?,
54            region: super::interp_required(ctx, &config, "region")?,
55            replicas: super::int_optional(ctx, &config, "replicas")?,
56        })
57    }
58}
59
60pub fn validate_config(
61    name: &str,
62    config: &BTreeMap<String, toml::Value>,
63) -> Result<(), IntegrationError> {
64    registry::config_string(config, "cluster").map_err(|err| IntegrationError::ConfigInvalid {
65        location: format!("integrations.{name}.cluster"),
66        detail: err.to_string(),
67    })?;
68    registry::config_string(config, "name").map_err(|err| IntegrationError::ConfigInvalid {
69        location: format!("integrations.{name}.name"),
70        detail: err.to_string(),
71    })?;
72    registry::config_string(config, "region").map_err(|err| IntegrationError::ConfigInvalid {
73        location: format!("integrations.{name}.region"),
74        detail: err.to_string(),
75    })?;
76    let _ = (name, config);
77    Ok(())
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83    use crate::ProviderOps;
84    use crate::resource::ResourcePayload;
85    use stackless_core::def::StackDef;
86    use stackless_stripe_projects::stripe::StripeProjects;
87    use stackless_stripe_projects::test_support;
88
89    #[test]
90    fn config_matches_catalog() {
91        const FIXTURE: &str = include_str!(concat!(
92            env!("CARGO_MANIFEST_DIR"),
93            "/../stackless-stripe-projects/tests/fixtures/catalog.json"
94        ));
95        let catalog = stackless_stripe_projects::Catalog::from_json_envelope(FIXTURE).unwrap();
96        let failures = stackless_stripe_projects::verify_service(
97            &catalog,
98            &PlanetScalePostgresqlConfig {
99                cluster: "PS-5".into(),
100                name: "test-name".into(),
101                region: "aws-ap-northeast".into(),
102                replicas: None,
103            },
104        );
105        assert!(
106            failures.is_empty(),
107            "planetscale/postgresql 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_postgresql","object":"v2.provisioning.provider_service_detail","provider_id":"prvdr_planetscale","provider_name":"PlanetScale","service_id":"postgresql","categories":["database"],"kind":"deployable","scope":"project","availability":"available","development":false,"livemode":true,"pricing":{"type":"paid"},"configuration_schema":{"properties":{"cluster":{"description":"Cluster size","enum":["PS-5","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"},"replicas":{"default":0,"description":"Number of replicas (0 for single node, 2+ for high availability)","maximum":9,"minimum":0,"type":"integer"}},"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-postgresql"
123cluster = "PS-5"
124name = "test-name"
125region = "aws-ap-northeast"
126[services.api]
127source = { repo = "r", ref = "main" }
128env = { OUT = "${integrations.res.database_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_DATABASE_URL": "val_database_url"}),
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 = PlanetScalePostgresql
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-postgresql");
165        let payload: ResourcePayload = serde_json::from_str(&resource.payload).unwrap();
166        assert_eq!(payload.outputs["database_url"], "val_database_url");
167    }
168}