Skip to main content

stackless_integrations/providers/turso/
database.rs

1//! `turso/database` 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-turso";
15
16#[derive(Debug, Serialize)]
17pub struct TursoDatabaseConfig {
18    pub location: String,
19    pub name: String,
20}
21
22impl CatalogService for TursoDatabaseConfig {
23    const REFERENCE: &'static str = "turso/database";
24}
25
26#[derive(Debug)]
27pub struct TursoDatabase;
28
29impl Hostable for TursoDatabase {
30    const PROVIDER: &'static str = "turso";
31    const HOSTING: IntegrationHosting = IntegrationHosting::Managed;
32    const CONFIG_SCOPE: ConfigScope = ConfigScope::GlobalOnly;
33    const RESOURCE_KIND: &'static str = RESOURCE_KIND;
34    const OUTPUTS: &'static [&'static str] = &["database_url", "auth_token"];
35}
36
37impl FamilyResource for TursoDatabase {
38    type Config = TursoDatabaseConfig;
39    const PROVIDER_PREFIX: &'static str = "TURSO";
40    const OUTPUT_FIELDS: &'static [(&'static str, &'static str, bool)] = &[
41        ("DATABASE_URL", "database_url", true),
42        ("AUTH_TOKEN", "auth_token", true),
43    ];
44
45    fn build_config(ctx: &ProvisionContext<'_>) -> Result<TursoDatabaseConfig, IntegrationError> {
46        let config = super::integration_config(ctx)?;
47        Ok(TursoDatabaseConfig {
48            location: super::interp_required(ctx, &config, "location")?,
49            name: super::interp_required(ctx, &config, "name")?,
50        })
51    }
52}
53
54pub fn validate_config(
55    name: &str,
56    config: &BTreeMap<String, toml::Value>,
57) -> Result<(), IntegrationError> {
58    registry::config_string(config, "location").map_err(|err| IntegrationError::ConfigInvalid {
59        location: format!("integrations.{name}.location"),
60        detail: err.to_string(),
61    })?;
62    registry::config_string(config, "name").map_err(|err| IntegrationError::ConfigInvalid {
63        location: format!("integrations.{name}.name"),
64        detail: err.to_string(),
65    })?;
66    let _ = (name, config);
67    Ok(())
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73    use crate::ProviderOps;
74    use crate::resource::ResourcePayload;
75    use stackless_core::def::StackDef;
76    use stackless_stripe_projects::stripe::StripeProjects;
77    use stackless_stripe_projects::test_support;
78
79    #[test]
80    fn config_matches_catalog() {
81        const FIXTURE: &str = include_str!(concat!(
82            env!("CARGO_MANIFEST_DIR"),
83            "/../stackless-stripe-projects/tests/fixtures/catalog.json"
84        ));
85        let catalog = stackless_stripe_projects::Catalog::from_json_envelope(FIXTURE).unwrap();
86        let failures = stackless_stripe_projects::verify_service(
87            &catalog,
88            &TursoDatabaseConfig {
89                location: "aws-us-east-1".into(),
90                name: "test-name".into(),
91            },
92        );
93        assert!(
94            failures.is_empty(),
95            "turso/database catalog gaps:\n{}",
96            failures.join("\n")
97        );
98    }
99
100    const CATALOG_ENVELOPE: &str = r##"{"ok":true,"command":"projects catalog","data":{"last_updated":"2026-07-11T00:00:00Z","services":[{"id":"prvsvc_database","object":"v2.provisioning.provider_service_detail","provider_id":"prvdr_turso","provider_name":"Turso","service_id":"database","categories":["database"],"kind":"deployable","scope":"project","availability":"available","development":false,"livemode":true,"pricing":{"type":"component"},"configuration_schema":{"properties":{"location":{"description":"Primary location (e.g. aws-us-east-1, aws-eu-west-1)","enum":["aws-us-east-1","aws-us-east-2","aws-us-west-2","aws-eu-west-1","aws-ap-south-1","aws-ap-northeast-1"],"type":"string"},"name":{"description":"Database name","type":"string"}},"required":["name","location"],"type":"object"}}]}}"##;
101
102    fn test_def() -> StackDef {
103        StackDef::parse(
104            r#"
105[stack]
106name = "atto"
107[stack.projects.stripe]
108project = "project_1"
109[integrations.res]
110provider = "turso"
111location = "aws-us-east-1"
112name = "test-name"
113[services.api]
114source = { repo = "r", ref = "main" }
115env = { OUT = "${integrations.res.database_url}" }
116health = { path = "/health" }
117[services.api.local]
118run = "true"
119"#,
120        )
121        .unwrap()
122    }
123
124    #[tokio::test]
125    async fn provision_records_outputs() {
126        let runner = test_support::provision_script(
127            CATALOG_ENVELOPE,
128            serde_json::json!({"TURSO_DATABASE_URL": "val_database_url", "TURSO_AUTH_TOKEN": "val_auth_token"}),
129            0,
130        );
131        let dir = tempfile::tempdir().unwrap();
132        std::fs::write(
133            dir.path().join("stackless.toml"),
134            "[stack]\nname=\"atto\"\n",
135        )
136        .unwrap();
137        let stripe = StripeProjects::new(&runner, dir.path());
138
139        let resource = TursoDatabase
140            .provision(
141                &stripe.as_dyn(),
142                &test_def(),
143                dir.path(),
144                "demo",
145                "res",
146                "local",
147                false,
148            )
149            .await
150            .unwrap();
151        assert_eq!(resource.resource_kind, "integration-turso");
152        let payload: ResourcePayload = serde_json::from_str(&resource.payload).unwrap();
153        assert_eq!(payload.outputs["database_url"], "val_database_url");
154    }
155}