effindom_native_packaging/
runtime_release.rs1use crate::{Error, Result};
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeSet;
4use std::path::{Component, Path};
5
6pub const NATIVE_RUNTIME_MANIFEST_SCHEMA_VERSION: u32 = 1;
7
8#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord)]
9#[serde(rename_all = "kebab-case")]
10pub enum NativeRuntimeTarget {
11 MacosArm64,
12 MacosX64,
13 WindowsArm64,
14 WindowsX64,
15 LinuxArm64,
16 LinuxX64,
17}
18
19pub const REQUIRED_NATIVE_RUNTIME_TARGETS: [NativeRuntimeTarget; 6] = [
20 NativeRuntimeTarget::LinuxArm64,
21 NativeRuntimeTarget::LinuxX64,
22 NativeRuntimeTarget::MacosArm64,
23 NativeRuntimeTarget::MacosX64,
24 NativeRuntimeTarget::WindowsArm64,
25 NativeRuntimeTarget::WindowsX64,
26];
27
28impl NativeRuntimeTarget {
29 pub const fn as_str(self) -> &'static str {
30 match self {
31 Self::MacosArm64 => "macos-arm64",
32 Self::MacosX64 => "macos-x64",
33 Self::WindowsArm64 => "windows-arm64",
34 Self::WindowsX64 => "windows-x64",
35 Self::LinuxArm64 => "linux-arm64",
36 Self::LinuxX64 => "linux-x64",
37 }
38 }
39
40 pub const fn archive_format(self) -> NativeRuntimeArchiveFormat {
41 match self {
42 Self::WindowsArm64 | Self::WindowsX64 => NativeRuntimeArchiveFormat::Zip,
43 _ => NativeRuntimeArchiveFormat::TarZstd,
44 }
45 }
46
47 pub fn archive_name(self) -> String {
48 format!(
49 "effindom-native-{}.{}",
50 self.as_str(),
51 self.archive_format().extension()
52 )
53 }
54}
55
56#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
57#[serde(rename_all = "kebab-case")]
58pub enum NativeRuntimeArchiveFormat {
59 TarZstd,
60 Zip,
61}
62
63impl NativeRuntimeArchiveFormat {
64 pub const fn extension(self) -> &'static str {
65 match self {
66 Self::TarZstd => "tar.zst",
67 Self::Zip => "zip",
68 }
69 }
70}
71
72#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord)]
73#[serde(rename_all = "kebab-case")]
74pub enum NativeRuntimeFileRole {
75 HostLibrary,
76 Launcher,
77 LinkMetadata,
78 Packager,
79 RuntimeAsset,
80 RuntimeLibrary,
81}
82
83#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
84#[serde(deny_unknown_fields, rename_all = "camelCase")]
85pub struct NativeRuntimeMinimumOs {
86 pub family: String,
87 pub version: String,
88}
89
90#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
91#[serde(deny_unknown_fields, rename_all = "camelCase")]
92pub struct NativeRuntimeFile {
93 pub path: String,
94 pub bytes: u64,
95 pub sha256: String,
96 pub role: NativeRuntimeFileRole,
97 #[serde(default, skip_serializing_if = "is_false")]
98 pub executable: bool,
99}
100
101#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
102#[serde(deny_unknown_fields, rename_all = "camelCase")]
103pub struct NativeRuntimeBundleManifest {
104 pub schema_version: u32,
105 pub source_commit: String,
106 pub target: NativeRuntimeTarget,
107 pub core_abi: u32,
108 pub ui_abi: u32,
109 pub minimum_os: NativeRuntimeMinimumOs,
110 pub files: Vec<NativeRuntimeFile>,
111}
112
113#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
114#[serde(deny_unknown_fields, rename_all = "camelCase")]
115pub struct NativeRuntimeArtifact {
116 pub target: NativeRuntimeTarget,
117 pub archive: String,
118 pub archive_format: NativeRuntimeArchiveFormat,
119 pub archive_bytes: u64,
120 pub archive_sha256: String,
121 pub bundle_manifest_sha256: String,
122 pub core_abi: u32,
123 pub ui_abi: u32,
124 pub minimum_os: NativeRuntimeMinimumOs,
125 pub files: Vec<NativeRuntimeFile>,
126}
127
128#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
129#[serde(deny_unknown_fields, rename_all = "camelCase")]
130pub struct NativeRuntimeReleaseManifest {
131 pub schema_version: u32,
132 pub release: String,
133 pub source_commit: String,
134 pub artifacts: Vec<NativeRuntimeArtifact>,
135}
136
137impl NativeRuntimeBundleManifest {
138 pub fn validate(&self) -> Result<()> {
139 validate_schema(self.schema_version)?;
140 validate_commit(&self.source_commit)?;
141 validate_abi(self.core_abi, self.ui_abi)?;
142 validate_minimum_os(self.target, &self.minimum_os)?;
143 validate_files(&self.files)
144 }
145
146 fn canonicalized(mut self) -> Result<Self> {
147 self.validate()?;
148 self.files.sort_by(|left, right| left.path.cmp(&right.path));
149 Ok(self)
150 }
151}
152
153impl NativeRuntimeReleaseManifest {
154 pub fn validate(&self) -> Result<()> {
155 validate_schema(self.schema_version)?;
156 semver::Version::parse(&self.release).map_err(|source| {
157 invalid(format!(
158 "release {:?} is not semantic versioning: {source}",
159 self.release
160 ))
161 })?;
162 validate_commit(&self.source_commit)?;
163 if self.artifacts.len() != REQUIRED_NATIVE_RUNTIME_TARGETS.len() {
164 return Err(invalid(format!(
165 "release must contain exactly {} target artifacts, found {}",
166 REQUIRED_NATIVE_RUNTIME_TARGETS.len(),
167 self.artifacts.len()
168 )));
169 }
170 let mut targets = BTreeSet::new();
171 let mut archives = BTreeSet::new();
172 for artifact in &self.artifacts {
173 if !targets.insert(artifact.target) {
174 return Err(invalid(format!(
175 "target {} appears more than once",
176 artifact.target.as_str()
177 )));
178 }
179 if !archives.insert(&artifact.archive) {
180 return Err(invalid(format!(
181 "archive {:?} appears more than once",
182 artifact.archive
183 )));
184 }
185 validate_artifact(artifact)?;
186 }
187 let required = REQUIRED_NATIVE_RUNTIME_TARGETS
188 .into_iter()
189 .collect::<BTreeSet<_>>();
190 if targets != required {
191 return Err(invalid("release target set is incomplete"));
192 }
193 Ok(())
194 }
195
196 pub fn artifact(&self, target: NativeRuntimeTarget) -> Option<&NativeRuntimeArtifact> {
197 self.artifacts
198 .iter()
199 .find(|artifact| artifact.target == target)
200 }
201
202 fn canonicalized(mut self) -> Result<Self> {
203 self.validate()?;
204 self.artifacts
205 .sort_by_key(|artifact| artifact.target.as_str());
206 for artifact in &mut self.artifacts {
207 artifact
208 .files
209 .sort_by(|left, right| left.path.cmp(&right.path));
210 }
211 Ok(self)
212 }
213}
214
215pub fn encode_native_runtime_bundle_manifest(
216 manifest: &NativeRuntimeBundleManifest,
217) -> Result<Vec<u8>> {
218 encode(&manifest.clone().canonicalized()?)
219}
220
221pub fn decode_native_runtime_bundle_manifest(bytes: &[u8]) -> Result<NativeRuntimeBundleManifest> {
222 let manifest: NativeRuntimeBundleManifest =
223 serde_json::from_slice(bytes).map_err(Error::ParseNativeRuntimeManifest)?;
224 manifest.validate()?;
225 Ok(manifest)
226}
227
228pub fn encode_native_runtime_release_manifest(
229 manifest: &NativeRuntimeReleaseManifest,
230) -> Result<Vec<u8>> {
231 encode(&manifest.clone().canonicalized()?)
232}
233
234pub fn decode_native_runtime_release_manifest(
235 bytes: &[u8],
236) -> Result<NativeRuntimeReleaseManifest> {
237 let manifest: NativeRuntimeReleaseManifest =
238 serde_json::from_slice(bytes).map_err(Error::ParseNativeRuntimeManifest)?;
239 manifest.validate()?;
240 Ok(manifest)
241}
242
243fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>> {
244 let mut bytes =
245 serde_json::to_vec_pretty(value).map_err(Error::SerializeNativeRuntimeManifest)?;
246 bytes.push(b'\n');
247 Ok(bytes)
248}
249
250fn validate_artifact(artifact: &NativeRuntimeArtifact) -> Result<()> {
251 if artifact.archive != artifact.target.archive_name() {
252 return Err(invalid(format!(
253 "target {} must use archive {:?}",
254 artifact.target.as_str(),
255 artifact.target.archive_name()
256 )));
257 }
258 if artifact.archive_format != artifact.target.archive_format() {
259 return Err(invalid(format!(
260 "target {} uses the wrong archive format",
261 artifact.target.as_str()
262 )));
263 }
264 if artifact.archive_bytes == 0 {
265 return Err(invalid(format!("archive {:?} is empty", artifact.archive)));
266 }
267 validate_sha256("archive", &artifact.archive_sha256)?;
268 validate_sha256("bundle manifest", &artifact.bundle_manifest_sha256)?;
269 validate_abi(artifact.core_abi, artifact.ui_abi)?;
270 validate_minimum_os(artifact.target, &artifact.minimum_os)?;
271 validate_files(&artifact.files)
272}
273
274fn validate_files(files: &[NativeRuntimeFile]) -> Result<()> {
275 if files.is_empty() {
276 return Err(invalid("runtime artifact contains no files"));
277 }
278 let mut paths = BTreeSet::new();
279 for file in files {
280 let path = Path::new(&file.path);
281 if file.path.is_empty()
282 || path.is_absolute()
283 || path.components().any(|component| {
284 matches!(
285 component,
286 Component::ParentDir | Component::RootDir | Component::Prefix(_)
287 )
288 })
289 {
290 return Err(invalid(format!(
291 "runtime file path {:?} must be safe and relative",
292 file.path
293 )));
294 }
295 if !paths.insert(&file.path) {
296 return Err(invalid(format!(
297 "runtime file path {:?} appears more than once",
298 file.path
299 )));
300 }
301 validate_sha256(&format!("runtime file {:?}", file.path), &file.sha256)?;
302 }
303 Ok(())
304}
305
306fn validate_schema(schema: u32) -> Result<()> {
307 if schema != NATIVE_RUNTIME_MANIFEST_SCHEMA_VERSION {
308 return Err(invalid(format!(
309 "schema {schema} is unsupported; expected {NATIVE_RUNTIME_MANIFEST_SCHEMA_VERSION}"
310 )));
311 }
312 Ok(())
313}
314
315fn validate_commit(commit: &str) -> Result<()> {
316 if !matches!(commit.len(), 40 | 64)
317 || !commit
318 .bytes()
319 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
320 {
321 return Err(invalid(format!(
322 "source commit {commit:?} must be a lowercase 40- or 64-character hexadecimal digest"
323 )));
324 }
325 Ok(())
326}
327
328fn validate_sha256(name: &str, value: &str) -> Result<()> {
329 if value.len() != 64
330 || !value
331 .bytes()
332 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
333 {
334 return Err(invalid(format!(
335 "{name} SHA-256 {value:?} must be 64 lowercase hexadecimal characters"
336 )));
337 }
338 Ok(())
339}
340
341fn validate_abi(core: u32, ui: u32) -> Result<()> {
342 if core == 0 || ui == 0 {
343 return Err(invalid("Core and UI ABI versions must be non-zero"));
344 }
345 Ok(())
346}
347
348fn validate_minimum_os(
349 target: NativeRuntimeTarget,
350 minimum: &NativeRuntimeMinimumOs,
351) -> Result<()> {
352 let expected = match target {
353 NativeRuntimeTarget::MacosArm64 | NativeRuntimeTarget::MacosX64 => "macos",
354 NativeRuntimeTarget::WindowsArm64 | NativeRuntimeTarget::WindowsX64 => "windows",
355 NativeRuntimeTarget::LinuxArm64 | NativeRuntimeTarget::LinuxX64 => "glibc",
356 };
357 if minimum.family != expected || minimum.version.trim().is_empty() {
358 return Err(invalid(format!(
359 "target {} requires non-empty minimum OS family {expected:?}",
360 target.as_str()
361 )));
362 }
363 Ok(())
364}
365
366fn invalid(message: impl Into<String>) -> Error {
367 Error::InvalidNativeRuntimeManifest(message.into())
368}
369
370fn is_false(value: &bool) -> bool {
371 !*value
372}