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] = &[
44        "endpoint",
45        "password",
46        "port",
47        "rest_url",
48        "rest_token",
49        "read_only_rest_token",
50    ];
51}
52
53impl FamilyResource for UpstashRedis {
54    type Config = UpstashRedisConfig;
55    const PROVIDER_PREFIX: &'static str = "UPSTASH";
56    const OUTPUT_FIELDS: &'static [(&'static str, &'static str, bool)] = &[
57        ("ENDPOINT", "endpoint", true),
58        ("PASSWORD", "password", true),
59        ("PORT", "port", false),
60        ("REST_URL", "rest_url", false),
61        ("REST_TOKEN", "rest_token", false),
62        ("READ_ONLY_REST_TOKEN", "read_only_rest_token", false),
63    ];
64
65    fn build_config(ctx: &ProvisionContext<'_>) -> Result<UpstashRedisConfig, IntegrationError> {
66        let config = super::integration_config(ctx)?;
67        Ok(UpstashRedisConfig {
68            eviction: super::interp_optional(ctx, &config, "eviction")?,
69            name: super::interp_optional(ctx, &config, "name")?,
70            price: super::interp_optional(ctx, &config, "price")?,
71            prod_pack: super::interp_optional(ctx, &config, "prod_pack")?,
72            read_regions: super::interp_optional(ctx, &config, "read_regions")?,
73            region: super::interp_optional(ctx, &config, "region")?,
74        })
75    }
76}
77
78pub fn validate_config(
79    name: &str,
80    config: &BTreeMap<String, toml::Value>,
81) -> Result<(), IntegrationError> {
82    let _ = (name, config);
83    Ok(())
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89    use crate::ProviderOps;
90    use crate::resource::ResourcePayload;
91    use stackless_core::def::StackDef;
92    use stackless_stripe_projects::stripe::StripeProjects;
93    use stackless_stripe_projects::test_support;
94
95    #[test]
96    fn config_matches_catalog() {
97        const FIXTURE: &str = include_str!(concat!(
98            env!("CARGO_MANIFEST_DIR"),
99            "/../stackless-stripe-projects/tests/fixtures/catalog.json"
100        ));
101        let catalog = stackless_stripe_projects::Catalog::from_json_envelope(FIXTURE).unwrap();
102        let failures = stackless_stripe_projects::verify_service(
103            &catalog,
104            &UpstashRedisConfig {
105                eviction: None,
106                name: None,
107                price: None,
108                prod_pack: None,
109                read_regions: None,
110                region: None,
111            },
112        );
113        assert!(
114            failures.is_empty(),
115            "upstash/redis catalog gaps:\n{}",
116            failures.join("\n")
117        );
118    }
119
120    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"}}]}}"##;
121
122    fn test_def() -> StackDef {
123        StackDef::parse(
124            r#"
125[stack]
126name = "atto"
127[stack.projects.stripe]
128project = "project_1"
129[integrations.res]
130provider = "upstash-redis"
131[services.api]
132source = { repo = "r", ref = "main" }
133env = { OUT = "${integrations.res.endpoint}" }
134health = { path = "/health" }
135[services.api.local]
136run = "true"
137"#,
138        )
139        .unwrap()
140    }
141
142    #[tokio::test]
143    async fn provision_records_outputs() {
144        let runner = test_support::provision_script(
145            CATALOG_ENVELOPE,
146            serde_json::json!({"UPSTASH_ENDPOINT": "val_endpoint", "UPSTASH_PASSWORD": "val_password", "UPSTASH_PORT": "val_port", "UPSTASH_REST_URL": "val_rest_url", "UPSTASH_REST_TOKEN": "val_rest_token", "UPSTASH_READ_ONLY_REST_TOKEN": "val_read_only_rest_token"}),
147            0,
148        );
149        let dir = tempfile::tempdir().unwrap();
150        std::fs::write(
151            dir.path().join("stackless.toml"),
152            "[stack]\nname=\"atto\"\n",
153        )
154        .unwrap();
155        let stripe = StripeProjects::new(&runner, dir.path());
156
157        let resource = UpstashRedis
158            .provision(
159                &stripe.as_dyn(),
160                &test_def(),
161                dir.path(),
162                "demo",
163                "res",
164                "local",
165                false,
166            )
167            .await
168            .unwrap();
169        assert_eq!(resource.resource_kind, "integration-upstash-redis");
170        let payload: ResourcePayload = serde_json::from_str(&resource.payload).unwrap();
171        assert_eq!(payload.outputs["endpoint"], "val_endpoint");
172    }
173}