Skip to main content

stackless_integrations/providers/upstash/
redis.rs

1//! `upstash/redis` 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};
12
13pub const RESOURCE_KIND: &str = "integration-upstash-redis";
14
15#[derive(Debug, Serialize)]
16pub struct UpstashRedisConfig {
17    #[serde(skip_serializing_if = "Option::is_none")]
18    pub eviction: Option<String>,
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub name: Option<String>,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub price: Option<String>,
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub prod_pack: Option<String>,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub read_regions: Option<String>,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub region: Option<String>,
29}
30
31impl CatalogService for UpstashRedisConfig {
32    const REFERENCE: &'static str = "upstash/redis";
33}
34
35#[derive(Debug)]
36pub struct UpstashRedis;
37
38impl Hostable for UpstashRedis {
39    const PROVIDER: &'static str = "upstash-redis";
40    const HOSTING: IntegrationHosting = IntegrationHosting::Managed;
41    const CONFIG_SCOPE: ConfigScope = ConfigScope::GlobalOnly;
42    const RESOURCE_KIND: &'static str = RESOURCE_KIND;
43    const OUTPUTS: &'static [&'static str] = &["redis_url", "rest_token"];
44}
45
46impl FamilyResource for UpstashRedis {
47    type Config = UpstashRedisConfig;
48    const PROVIDER_PREFIX: &'static str = "UPSTASH";
49    // Provisional until pinned by `mise run discover upstash/redis`.
50    const OUTPUT_FIELDS: &'static [(&'static str, &'static str, bool)] = &[
51        ("REDIS_URL", "redis_url", true),
52        ("REST_TOKEN", "rest_token", false),
53    ];
54
55    fn build_config(ctx: &ProvisionContext<'_>) -> Result<UpstashRedisConfig, IntegrationError> {
56        let config = super::integration_config(ctx)?;
57        Ok(UpstashRedisConfig {
58            eviction: super::interp_optional(ctx, &config, "eviction")?,
59            name: super::interp_optional(ctx, &config, "name")?,
60            price: super::interp_optional(ctx, &config, "price")?,
61            prod_pack: super::interp_optional(ctx, &config, "prod_pack")?,
62            read_regions: super::interp_optional(ctx, &config, "read_regions")?,
63            region: super::interp_optional(ctx, &config, "region")?,
64        })
65    }
66}
67
68pub fn validate_config(
69    name: &str,
70    config: &BTreeMap<String, toml::Value>,
71) -> Result<(), IntegrationError> {
72    let _ = (name, config);
73    Ok(())
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79    use crate::ProviderOps;
80    use crate::resource::ResourcePayload;
81    use stackless_core::def::StackDef;
82    use stackless_stripe_projects::stripe::StripeProjects;
83    use stackless_stripe_projects::test_support;
84
85    #[test]
86    fn config_matches_catalog() {
87        const FIXTURE: &str = include_str!(concat!(
88            env!("CARGO_MANIFEST_DIR"),
89            "/../stackless-stripe-projects/tests/fixtures/catalog.json"
90        ));
91        let catalog = stackless_stripe_projects::Catalog::from_json_envelope(FIXTURE).unwrap();
92        let failures = stackless_stripe_projects::verify_service(
93            &catalog,
94            &UpstashRedisConfig {
95                eviction: None,
96                name: None,
97                price: None,
98                prod_pack: None,
99                read_regions: None,
100                region: None,
101            },
102        );
103        assert!(
104            failures.is_empty(),
105            "upstash/redis catalog gaps:\n{}",
106            failures.join("\n")
107        );
108    }
109
110    const CATALOG_ENVELOPE: &str = r##"{"ok":true,"command":"projects catalog","data":{"last_updated":"2026-07-11T00:00:00Z","services":[{"id":"prvsvc_redis","object":"v2.provisioning.provider_service_detail","provider_id":"prvdr_upstash","provider_name":"Upstash","service_id":"redis","categories":["database"],"kind":"deployable","scope":"project","availability":"available","development":false,"livemode":true,"pricing":{"type":"paid"},"configuration_schema":{"properties":{"eviction":{"description":"Enable eviction when data size limit is reached (on or off)","enum":["on","off"],"type":"string"},"name":{"description":"Database name","maxLength":40,"minLength":1,"type":"string"},"price":{"default":"payg","description":"Pricing tier. 'free' provisions on the free plan (subject to free-tier limits and one-per-account). 'payg' provisions pay-as-you-go. Defaults to 'payg'.","enum":["free","payg"],"type":"string"},"prod_pack":{"description":"Enable Production Pack ($200/mo) for enhanced SLA, higher limits, and multi-zone replication. Requires price=payg.","enum":["on","off"],"type":"string"},"read_regions":{"description":"Comma-separated list of read replica regions for global databases (e.g. \"eu-west-1,ap-southeast-1\"). Leave empty for single-region. Allowed values: us-east-1, us-west-1, us-west-2, us-east-2, eu-west-1, eu-west-2, eu-central-1, ap-southeast-1, ap-southeast-2, ap-northeast-1, ap-south-1, af-south-1, sa-east-1, ca-central-1, us-central1, europe-west1, asia-northeast1, us-east4","type":"string"},"region":{"description":"AWS/GCP region for the database","enum":["us-east-1","us-west-1","us-west-2","us-east-2","eu-west-1","eu-west-2","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-south-1","af-south-1","sa-east-1","ca-central-1","us-central1","europe-west1","asia-northeast1","us-east4"],"type":"string"}},"type":"object"}}]}}"##;
111
112    fn test_def() -> StackDef {
113        StackDef::parse(
114            r#"
115[stack]
116name = "atto"
117[stack.projects.stripe]
118project = "project_1"
119[integrations.res]
120provider = "upstash-redis"
121[services.api]
122source = { repo = "r", ref = "main" }
123env = { OUT = "${integrations.res.redis_url}" }
124health = { path = "/health" }
125[services.api.local]
126run = "true"
127"#,
128        )
129        .unwrap()
130    }
131
132    #[tokio::test]
133    async fn provision_records_outputs() {
134        let runner = test_support::provision_script(
135            CATALOG_ENVELOPE,
136            serde_json::json!({"UPSTASH_REDIS_URL": "val_redis_url", "UPSTASH_REST_TOKEN": "val_rest_token"}),
137            0,
138        );
139        let dir = tempfile::tempdir().unwrap();
140        std::fs::write(
141            dir.path().join("stackless.toml"),
142            "[stack]\nname=\"atto\"\n",
143        )
144        .unwrap();
145        let stripe = StripeProjects::new(&runner, dir.path());
146
147        let resource = UpstashRedis
148            .provision(
149                &stripe.as_dyn(),
150                &test_def(),
151                dir.path(),
152                "demo",
153                "res",
154                "local",
155                false,
156            )
157            .await
158            .unwrap();
159        assert_eq!(resource.resource_kind, "integration-upstash-redis");
160        let payload: ResourcePayload = serde_json::from_str(&resource.payload).unwrap();
161        assert_eq!(payload.outputs["redis_url"], "val_redis_url");
162    }
163}