Skip to main content

core_api/
extension_preview.rs

1//! Complete development material. Provider values travel separately and never enter the snapshot.
2use crate::extension_sources::{IntegrationSource, PackageType, SnapshotId, SourceReadResponse};
3use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5use std::collections::BTreeMap;
6
7pub const APPLY_TARGET: &str = "/app/integration/preview/apply";
8pub const STATUS_TARGET: &str = "/app/integration/preview/status";
9pub const ENV_READ_ROUTE: &str = "/dispatch/integration/preview/env/read";
10pub const MAX_PACKAGE_BYTES: usize = 16 * 1024 * 1024;
11pub const MAX_CONFIGURATION_BYTES: usize = 64 * 1024;
12
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "camelCase", deny_unknown_fields)]
15pub struct PreviewManifest {
16    pub format_version: u32,
17    pub integration_id: String,
18    pub schemas: BTreeMap<String, String>,
19    pub i18n: BTreeMap<String, String>,
20    pub scripts: BTreeMap<String, script_api::ScriptArtifact>,
21}
22
23impl PreviewManifest {
24    pub fn material(&self) -> Result<SourceReadResponse, &'static str> {
25        if self.format_version != 1 || self.scripts.len() > 100 {
26            return Err("Unsupported Preview package format");
27        }
28        let encoded = serde_json::to_vec(self).map_err(|_| "Invalid Preview package")?;
29        if encoded.len() > MAX_PACKAGE_BYTES {
30            return Err("Preview package exceeds the size limit");
31        }
32        let snapshot: SnapshotId = format!("{:x}", Sha256::digest(encoded)).parse()?;
33        let material = SourceReadResponse {
34            source: IntegrationSource {
35                integration_id: self.integration_id.clone(),
36                version: None,
37                package_type: PackageType::Standard,
38                snapshot: Some(snapshot),
39            },
40            schemas: self.schemas.clone(),
41            i18n: self.i18n.clone(),
42            script_digests: self
43                .scripts
44                .iter()
45                .map(|(name, script)| (name.clone(), script.sha256.clone()))
46                .collect(),
47        };
48        material.validate()?;
49        for (function, script) in &self.scripts {
50            let reference = script_api::ScriptRef::IntegrationPreview {
51                package_id: self.integration_id.clone(),
52                snapshot: snapshot.to_string(),
53                function: function.clone(),
54                sha256: script.sha256.clone(),
55            };
56            script
57                .validate_for(&reference)
58                .map_err(|_| "Invalid Preview script metadata")?;
59        }
60        Ok(material)
61    }
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
65#[serde(rename_all = "camelCase", deny_unknown_fields)]
66pub struct ApplyPreviewRequest {
67    pub material: crate::resource_transfer::TextPayload,
68    pub scripts: BTreeMap<String, crate::resource_transfer::TextPayload>,
69    /// Missing preserves previous values; null removes an explicitly named value.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub configuration: Option<BTreeMap<String, serde_json::Value>>,
72}
73
74impl ApplyPreviewRequest {
75    pub fn validate(&self) -> Result<(), &'static str> {
76        if self.scripts.len() > 100
77            || serde_json::to_vec(self)
78                .map_err(|_| "Invalid Preview request")?
79                .len()
80                > 1024 * 1024
81        {
82            return Err("Preview request exceeds the inline size limit");
83        }
84        if let Some(configuration) = &self.configuration {
85            if configuration.len() > 1000
86                || serde_json::to_vec(configuration)
87                    .map_err(|_| "Invalid Preview configuration")?
88                    .len()
89                    > MAX_CONFIGURATION_BYTES
90            {
91                return Err("Preview configuration exceeds the size limit");
92            }
93        }
94        Ok(())
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    fn manifest() -> PreviewManifest {
102        PreviewManifest {
103            format_version: 1,
104            integration_id: "garden.device".into(),
105            schemas: BTreeMap::from([(
106                "root.yml".into(),
107                "integration:\n  domain: garden\n  entity: device\n".into(),
108            )]),
109            i18n: BTreeMap::new(),
110            scripts: BTreeMap::new(),
111        }
112    }
113    #[test]
114    fn content_identity_changes_without_a_release_version_and_ignores_provider_values() {
115        let mut value = manifest();
116        let original = value.material().unwrap();
117        assert!(original.source.version.is_none());
118        assert!(original.source.snapshot.is_some());
119        assert_eq!(
120            original,
121            serde_json::from_value::<PreviewManifest>(serde_json::to_value(&value).unwrap())
122                .unwrap()
123                .material()
124                .unwrap()
125        );
126        value
127            .schemas
128            .get_mut("root.yml")
129            .unwrap()
130            .push_str("# changed\n");
131        assert_ne!(
132            original.source.snapshot,
133            value.material().unwrap().source.snapshot
134        );
135        let mut raw = serde_json::to_value(&value).unwrap();
136        raw["configuration"] = serde_json::json!({"token":"private"});
137        assert!(serde_json::from_value::<PreviewManifest>(raw).is_err());
138    }
139    #[test]
140    fn invalid_inventory_paths_metadata_and_inline_limits_are_rejected() {
141        let mut value = manifest();
142        value
143            .schemas
144            .insert("../outside.yml".into(), "outside".into());
145        assert!(value.material().is_err());
146        let mut value = manifest();
147        let artifact = script_api::ScriptArtifact {
148            format: script_api::ArtifactFormat::JavascriptEsm,
149            sha256: "a".repeat(64),
150            size: 1024,
151            sdk_version: "0.2.0".into(),
152            contract: None,
153        };
154        value.scripts.insert("../escape".into(), artifact);
155        assert!(value.material().is_err());
156        let request = ApplyPreviewRequest {
157            material: crate::resource_transfer::TextPayload::Inline {
158                text: "x".repeat(1024 * 1024),
159            },
160            scripts: BTreeMap::new(),
161            configuration: None,
162        };
163        assert!(request.validate().is_err());
164    }
165}