Skip to main content

stackless_integrations/providers/cloudflare/
r2.rs

1//! Cloudflare R2 object storage (`cloudflare/r2:bucket`).
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::CloudflareResource;
10use crate::error::IntegrationError;
11use crate::hostable::{ConfigScope, Hostable, IntegrationHosting};
12use crate::registry;
13
14pub const RESOURCE_KIND: &str = "integration-cloudflare-r2";
15
16/// The typed `cloudflare/r2:bucket` `--config`. Field names ARE the catalog
17/// contract; the gap test pins them against the live `configuration_schema`.
18#[derive(Debug, Serialize)]
19pub struct R2Config {
20    pub name: String,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub location_hint: Option<String>,
23}
24
25impl CatalogService for R2Config {
26    const REFERENCE: &'static str = "cloudflare/r2:bucket";
27}
28
29#[derive(Debug)]
30pub struct CloudflareR2;
31
32impl Hostable for CloudflareR2 {
33    const PROVIDER: &'static str = "cloudflare-r2";
34    /// R2 runs on Cloudflare's edge — not on the stack's `--on` host.
35    const HOSTING: IntegrationHosting = IntegrationHosting::Managed;
36    const CONFIG_SCOPE: ConfigScope = ConfigScope::GlobalOnly;
37    const RESOURCE_KIND: &'static str = RESOURCE_KIND;
38    /// Bucket coordinates usable from any substrate's service env.
39    const OUTPUTS: &'static [&'static str] = &["account_id", "bucket", "endpoint", "dashboard_url"];
40}
41
42impl CloudflareResource for CloudflareR2 {
43    type Config = R2Config;
44    const PROVIDER_PREFIX: &'static str = "CLOUDFLARE";
45    // Confirmed by the live smoke 2026-06-16. No S3 access/secret keys — Stripe's
46    // R2 provisioning returns the account/bucket/endpoint, not API tokens.
47    const OUTPUT_FIELDS: &'static [(&'static str, &'static str, bool)] = &[
48        ("ACCOUNT_ID", "account_id", true),
49        ("BUCKET_NAME", "bucket", true),
50        ("ENDPOINT", "endpoint", true),
51        ("DASHBOARD_URL", "dashboard_url", false),
52    ];
53
54    fn build_config(ctx: &ProvisionContext<'_>) -> Result<R2Config, IntegrationError> {
55        let config = super::integration_config(ctx)?;
56        Ok(R2Config {
57            name: super::interp_required(ctx, &config, "name")?,
58            location_hint: super::interp_optional(ctx, &config, "location_hint")?,
59        })
60    }
61}
62
63pub fn validate_config(
64    name: &str,
65    config: &BTreeMap<String, toml::Value>,
66) -> Result<(), IntegrationError> {
67    // `name` is required; `location_hint` is optional and enum-checked against
68    // the catalog schema at provision.
69    registry::config_string(config, "name").map_err(|err| IntegrationError::ConfigInvalid {
70        location: format!("integrations.{name}.name"),
71        detail: err.to_string(),
72    })?;
73    Ok(())
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79    use crate::ProviderOps;
80    use crate::resource::ResourcePayload as CloudflarePayload;
81    use stackless_core::def::StackDef;
82    use stackless_provider_sdk::IntegrationObservation;
83    use stackless_stripe_projects::stripe::{CommandOutput, StripeProjects};
84    use stackless_stripe_projects::test_support::ScriptedRunner;
85
86    fn out(stdout: &str) -> CommandOutput {
87        CommandOutput {
88            status: 0,
89            stdout: stdout.to_owned(),
90            stderr: String::new(),
91        }
92    }
93
94    /// Catalog gap check: `R2Config` must validate against the live
95    /// `cloudflare/r2:bucket` schema in the committed catalog fixture.
96    #[test]
97    fn r2_config_matches_catalog() {
98        const FIXTURE: &str = include_str!(concat!(
99            env!("CARGO_MANIFEST_DIR"),
100            "/../stackless-stripe-projects/tests/fixtures/catalog.json"
101        ));
102        let catalog = stackless_stripe_projects::Catalog::from_json_envelope(FIXTURE).unwrap();
103        let failures = stackless_stripe_projects::verify_service(
104            &catalog,
105            &R2Config {
106                name: "stackless-assets".into(),
107                location_hint: Some("wnam".into()),
108            },
109        );
110        assert!(
111            failures.is_empty(),
112            "cloudflare/r2:bucket catalog gaps:\n{}",
113            failures.join("\n")
114        );
115    }
116
117    /// A minimal `stripe projects catalog --json` envelope carrying
118    /// `cloudflare/r2:bucket` as a paid service (so `--confirm-paid-service` fires).
119    const R2_CATALOG_ENVELOPE: &str = r#"{"ok":true,"command":"projects catalog","data":{
120        "last_updated":"2026-06-16T00:00:00Z","services":[{
121            "id":"prvsvc_r2","object":"v2.provisioning.provider_service_detail",
122            "provider_id":"prvdr_cloudflare","provider_name":"Cloudflare","service_id":"r2:bucket",
123            "categories":["storage"],"kind":"deployable","scope":"project","availability":"available",
124            "development":false,"livemode":true,
125            "pricing":{"type":"paid","paid_pricing":[{"type":"freeform","freeform":"usage-based"}]},
126            "configuration_schema":{"type":"object","required":["name"],"additionalProperties":false,
127                "properties":{"name":{"type":"string"},
128                    "location_hint":{"type":"string","enum":["wnam","enam","weur","eeur","apac","oc"]}}}
129        }]}}"#;
130
131    fn test_def() -> StackDef {
132        StackDef::parse(
133            r#"
134[stack]
135name = "atto"
136[stack.projects.stripe]
137project = "project_1"
138
139[integrations.bucket]
140provider = "cloudflare-r2"
141name = "${stack.name}-${instance.name}-assets"
142
143[services.api]
144source = { repo = "r", ref = "main" }
145env = { R2_ENDPOINT = "${integrations.bucket.endpoint}" }
146health = { path = "/health" }
147[services.api.local]
148run = "true"
149"#,
150        )
151        .unwrap()
152    }
153
154    #[tokio::test]
155    async fn provision_r2_adds_paid_resource_and_records_outputs() {
156        // Stripe returns the R2 coordinates as distinct env vars in the add
157        // response (the real envelope, confirmed by the live smoke).
158        let runner = ScriptedRunner::new(vec![
159            out(R2_CATALOG_ENVELOPE),
160            out(r#"{"ok":true,"data":{"project":{"id":"project_1"}}}"#),
161            out(r#"{"ok":true,"data":{"environments":[{"name":"demo"}]}}"#),
162            out(r#"{"ok":true,"data":null}"#),
163            out(r#"{"ok":true,"data":{"services":[]}}"#),
164            out(&serde_json::json!({
165                "ok": true,
166                "data": { "variables": {
167                    "CLOUDFLARE_ACCOUNT_ID": "acc_123",
168                    "CLOUDFLARE_BUCKET_NAME": "atto-demo-assets",
169                    "CLOUDFLARE_ENDPOINT": "https://acc_123.r2.cloudflarestorage.com",
170                    "CLOUDFLARE_DASHBOARD_URL": "https://dash.cloudflare.com/acc_123/r2/atto-demo-assets"
171                }}
172            })
173            .to_string()),
174            out(r#"{"ok":true,"data":null}"#),
175            // env --pull --refresh for the resource-prefixed candidate keys
176            out(r#"{"ok":true,"data":null}"#),
177        ]);
178        let dir = tempfile::tempdir().unwrap();
179        std::fs::write(
180            dir.path().join("stackless.toml"),
181            "[stack]\nname=\"atto\"\n",
182        )
183        .unwrap();
184        let stripe = StripeProjects::new(&runner, dir.path());
185
186        let resource = CloudflareR2
187            .provision(
188                &stripe.as_dyn(),
189                &test_def(),
190                dir.path(),
191                "demo",
192                "bucket",
193                "local",
194                false,
195            )
196            .await
197            .unwrap();
198
199        assert_eq!(resource.resource_kind, "integration-cloudflare-r2");
200        assert_eq!(resource.resource_id, "demo-bucket");
201        let payload: CloudflarePayload = serde_json::from_str(&resource.payload).unwrap();
202        assert_eq!(payload.outputs["bucket"], "atto-demo-assets");
203        assert_eq!(payload.outputs["account_id"], "acc_123");
204        assert_eq!(
205            payload.outputs["endpoint"],
206            "https://acc_123.r2.cloudflarestorage.com"
207        );
208
209        let calls = runner.calls();
210        let add = calls
211            .iter()
212            .find(|call| call.first().map(String::as_str) == Some("add"))
213            .expect("an add call");
214        assert_eq!(add[1], "cloudflare/r2:bucket");
215        assert!(add.contains(&"--name".to_owned()) && add.contains(&"demo-bucket".to_owned()));
216        // R2 is paid → the catalog tier drives `--confirm-paid-service`.
217        assert!(add.contains(&"--confirm-paid-service".to_owned()));
218    }
219
220    #[tokio::test]
221    async fn observe_and_destroy_use_stripe_resource_from_payload() {
222        let payload = serde_json::to_string(&CloudflarePayload {
223            stripe_resource: "demo-bucket".into(),
224            outputs: BTreeMap::new(),
225        })
226        .unwrap();
227        let runner = ScriptedRunner::new(vec![
228            out(r#"{"ok":true,"data":{"services":[{"name":"demo-bucket"}]}}"#),
229            out(r#"{"ok":true,"data":{"services":[{"name":"demo-bucket"}]}}"#),
230            out(r#"{"ok":true,"data":null}"#),
231        ]);
232        let stripe = StripeProjects::new(&runner, std::env::temp_dir());
233
234        assert_eq!(
235            crate::resource::observe_resource(&stripe.as_dyn(), &payload, "fallback")
236                .await
237                .unwrap(),
238            IntegrationObservation::Present { drift: vec![] }
239        );
240        crate::resource::destroy_resource(&stripe.as_dyn(), &payload, "fallback")
241            .await
242            .unwrap();
243        let calls = runner.calls();
244        assert!(
245            calls
246                .iter()
247                .any(|call| call.starts_with(&["remove".to_owned(), "demo-bucket".to_owned()]))
248        );
249    }
250}