stackless_integrations/providers/cloudflare/
d1.rs1use std::collections::BTreeMap;
4
5use serde::Serialize;
6use stackless_stripe_projects::catalog::verify::CatalogService;
7use stackless_stripe_projects::provision::ProvisionContext;
8
9use super::CloudflareResource;
10use crate::error::IntegrationError;
11use crate::hostable::{ConfigScope, Hostable, IntegrationHosting};
12use crate::registry;
13
14pub const RESOURCE_KIND: &str = "integration-cloudflare-d1";
15
16#[derive(Debug, Serialize)]
17pub struct D1Config {
18 pub name: String,
19 #[serde(skip_serializing_if = "Option::is_none")]
20 pub primary_location_hint: Option<String>,
21}
22
23impl CatalogService for D1Config {
24 const REFERENCE: &'static str = "cloudflare/d1";
25}
26
27#[derive(Debug)]
28pub struct CloudflareD1;
29
30impl Hostable for CloudflareD1 {
31 const PROVIDER: &'static str = "cloudflare-d1";
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] = &["database_id", "name", "account_id"];
36}
37
38impl CloudflareResource for CloudflareD1 {
39 type Config = D1Config;
40 const PROVIDER_PREFIX: &'static str = "CLOUDFLARE";
41 const OUTPUT_FIELDS: &'static [(&'static str, &'static str, bool)] = &[
43 ("DATABASE_ID", "database_id", true),
44 ("NAME", "name", false),
45 ("ACCOUNT_ID", "account_id", false),
46 ];
47
48 fn build_config(ctx: &ProvisionContext<'_>) -> Result<D1Config, IntegrationError> {
49 let config = super::integration_config(ctx)?;
50 Ok(D1Config {
51 name: super::interp_required(ctx, &config, "name")?,
52 primary_location_hint: super::interp_optional(ctx, &config, "primary_location_hint")?,
53 })
54 }
55}
56
57pub fn validate_config(
58 name: &str,
59 config: &BTreeMap<String, toml::Value>,
60) -> Result<(), IntegrationError> {
61 registry::config_string(config, "name").map_err(|err| IntegrationError::ConfigInvalid {
62 location: format!("integrations.{name}.name"),
63 detail: err.to_string(),
64 })?;
65 Ok(())
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71 use crate::ProviderOps;
72 use crate::resource::ResourcePayload as CloudflarePayload;
73 use stackless_core::def::StackDef;
74 use stackless_stripe_projects::stripe::StripeProjects;
75 use stackless_stripe_projects::test_support;
76
77 #[test]
78 fn d1_config_matches_catalog() {
79 const FIXTURE: &str = include_str!(concat!(
80 env!("CARGO_MANIFEST_DIR"),
81 "/../stackless-stripe-projects/tests/fixtures/catalog.json"
82 ));
83 let catalog = stackless_stripe_projects::Catalog::from_json_envelope(FIXTURE).unwrap();
84 let failures = stackless_stripe_projects::verify_service(
85 &catalog,
86 &D1Config {
87 name: "stackless-db".into(),
88 primary_location_hint: Some("wnam".into()),
89 },
90 );
91 assert!(
92 failures.is_empty(),
93 "cloudflare/d1 catalog gaps:\n{}",
94 failures.join("\n")
95 );
96 }
97
98 const D1_CATALOG_ENVELOPE: &str = r#"{"ok":true,"command":"projects catalog","data":{
99 "last_updated":"2026-06-16T00:00:00Z","services":[{
100 "id":"prvsvc_d1","object":"v2.provisioning.provider_service_detail",
101 "provider_id":"prvdr_cloudflare","provider_name":"Cloudflare","service_id":"d1",
102 "categories":["database"],"kind":"deployable","scope":"project","availability":"available",
103 "development":false,"livemode":true,"pricing":{"type":"component"},
104 "configuration_schema":{"type":"object","required":["name"],"additionalProperties":false,
105 "properties":{"name":{"type":"string"},
106 "primary_location_hint":{"type":"string","enum":["wnam","enam","weur","eeur","apac","oc"]}}}
107 }]}}"#;
108
109 fn test_def() -> StackDef {
110 StackDef::parse(
111 r#"
112[stack]
113name = "atto"
114[stack.projects.stripe]
115project = "project_1"
116[integrations.db]
117provider = "cloudflare-d1"
118name = "${stack.name}-db"
119[services.api]
120source = { repo = "r", ref = "main" }
121env = { D1_ID = "${integrations.db.database_id}" }
122health = { path = "/health" }
123[services.api.local]
124run = "true"
125"#,
126 )
127 .unwrap()
128 }
129
130 #[tokio::test]
131 async fn provision_d1_records_outputs() {
132 let runner = test_support::provision_script(
133 D1_CATALOG_ENVELOPE,
134 serde_json::json!({
135 "CLOUDFLARE_DATABASE_ID": "db_123",
136 "CLOUDFLARE_NAME": "atto-db",
137 "CLOUDFLARE_ACCOUNT_ID": "acc_1"
138 }),
139 0,
140 );
141 let dir = tempfile::tempdir().unwrap();
142 std::fs::write(
143 dir.path().join("stackless.toml"),
144 "[stack]\nname=\"atto\"\n",
145 )
146 .unwrap();
147 let stripe = StripeProjects::new(&runner, dir.path());
148
149 let resource = CloudflareD1
150 .provision(
151 &stripe.as_dyn(),
152 &test_def(),
153 dir.path(),
154 "demo",
155 "db",
156 "local",
157 false,
158 )
159 .await
160 .unwrap();
161 assert_eq!(resource.resource_kind, "integration-cloudflare-d1");
162 let payload: CloudflarePayload = serde_json::from_str(&resource.payload).unwrap();
163 assert_eq!(payload.outputs["database_id"], "db_123");
164 assert_eq!(payload.outputs["name"], "atto-db");
165 assert_eq!(payload.outputs["account_id"], "acc_1");
166 }
167}