a3s-runtime 0.2.0

Provider-neutral execution contract and client for A3S runtimes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use super::{
    ArtifactRef, IsolationLevel, ResourceLimits, RuntimeNetworkSpec, RuntimeProcessSpec,
    SecretReference,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RuntimeUnitClass {
    Task,
    Service,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MountKind {
    Artifact,
    Volume,
    Tmpfs,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum RuntimeMountSource {
    Artifact { artifact: ArtifactRef },
    Volume { volume_id: String },
    Tmpfs { size_bytes: u64 },
}

impl RuntimeMountSource {
    pub fn kind(&self) -> MountKind {
        match self {
            Self::Artifact { .. } => MountKind::Artifact,
            Self::Volume { .. } => MountKind::Volume,
            Self::Tmpfs { .. } => MountKind::Tmpfs,
        }
    }

    fn validate(&self) -> Result<(), String> {
        match self {
            Self::Artifact { artifact } => artifact.validate(),
            Self::Volume { volume_id } => super::validate_id("volume_id", volume_id, 255),
            Self::Tmpfs { size_bytes } if *size_bytes == 0 => {
                Err("tmpfs size_bytes must be positive".into())
            }
            Self::Tmpfs { .. } => Ok(()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RuntimeMount {
    pub name: String,
    pub source: RuntimeMountSource,
    pub target: String,
    pub read_only: bool,
}

impl RuntimeMount {
    fn validate(&self) -> Result<(), String> {
        super::validate_name("mount name", &self.name)?;
        super::validate_absolute_path("mount target", &self.target)?;
        self.source.validate()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HealthCheckKind {
    Http,
    Tcp,
    Command,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum HealthProbe {
    Http {
        port: String,
        path: String,
        expected_statuses: Vec<u16>,
    },
    Tcp {
        port: String,
    },
    Command {
        command: Vec<String>,
    },
}

impl HealthProbe {
    pub fn kind(&self) -> HealthCheckKind {
        match self {
            Self::Http { .. } => HealthCheckKind::Http,
            Self::Tcp { .. } => HealthCheckKind::Tcp,
            Self::Command { .. } => HealthCheckKind::Command,
        }
    }

    fn validate(&self, network: &RuntimeNetworkSpec) -> Result<(), String> {
        match self {
            Self::Http {
                port,
                path,
                expected_statuses,
            } => {
                super::validate_name("health port", port)?;
                if !network.has_port(port) {
                    return Err(format!(
                        "HTTP health check references unknown port {port:?}"
                    ));
                }
                if !path.starts_with('/') || path.len() > 2048 || path.contains(['\0', '\r', '\n'])
                {
                    return Err("HTTP health path must be a bounded absolute request path".into());
                }
                if expected_statuses.is_empty()
                    || expected_statuses.len() > 32
                    || expected_statuses
                        .iter()
                        .any(|status| !(100..=599).contains(status))
                {
                    return Err("HTTP health expected_statuses are invalid".into());
                }
                Ok(())
            }
            Self::Tcp { port } => {
                super::validate_name("health port", port)?;
                if !network.has_port(port) {
                    return Err(format!("TCP health check references unknown port {port:?}"));
                }
                Ok(())
            }
            Self::Command { command } => {
                if command.is_empty() || command.len() > 64 {
                    return Err("command health check requires 1 to 64 arguments".into());
                }
                for value in command {
                    if value.is_empty() || value.len() > 32 * 1024 || value.contains('\0') {
                        return Err("command health check contains an invalid argument".into());
                    }
                }
                Ok(())
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RuntimeHealthCheck {
    pub probe: HealthProbe,
    pub interval_ms: u64,
    pub timeout_ms: u64,
    pub start_period_ms: u64,
    pub success_threshold: u32,
    pub failure_threshold: u32,
}

impl RuntimeHealthCheck {
    fn validate(&self, network: &RuntimeNetworkSpec) -> Result<(), String> {
        if self.interval_ms == 0
            || self.timeout_ms == 0
            || self.timeout_ms > self.interval_ms
            || self.success_threshold == 0
            || self.failure_threshold == 0
        {
            return Err("health timing and threshold values are invalid".into());
        }
        self.probe.validate(network)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum RestartPolicy {
    Never,
    OnFailure { max_retries: u32 },
    Always,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RuntimeOutputSpec {
    pub name: String,
    pub path: String,
    pub media_type: String,
    pub max_bytes: u64,
}

impl RuntimeOutputSpec {
    fn validate(&self) -> Result<(), String> {
        super::validate_name("output name", &self.name)?;
        super::validate_absolute_path("output path", &self.path)?;
        super::validate_nonempty("output media_type", &self.media_type, 255)?;
        if self.max_bytes == 0 {
            return Err("output max_bytes must be positive".into());
        }
        Ok(())
    }
}

/// Immutable provider-neutral definition of one finite Task or long-running
/// Service generation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RuntimeUnitSpec {
    pub schema: String,
    pub unit_id: String,
    pub generation: u64,
    pub class: RuntimeUnitClass,
    pub artifact: ArtifactRef,
    pub process: RuntimeProcessSpec,
    pub mounts: Vec<RuntimeMount>,
    pub secrets: Vec<SecretReference>,
    pub network: RuntimeNetworkSpec,
    pub resources: ResourceLimits,
    pub isolation: IsolationLevel,
    pub health: Option<RuntimeHealthCheck>,
    pub restart: RestartPolicy,
    pub outputs: Vec<RuntimeOutputSpec>,
    pub semantics_profile_digest: Option<String>,
}

impl RuntimeUnitSpec {
    pub const SCHEMA: &'static str = "a3s.runtime.unit-spec.v2";

    pub fn validate(&self) -> Result<(), String> {
        if self.schema != Self::SCHEMA {
            return Err(format!("unsupported Runtime unit schema {:?}", self.schema));
        }
        super::validate_id("unit_id", &self.unit_id, 512)?;
        if self.generation == 0 {
            return Err("Runtime unit generation must be positive".into());
        }
        self.artifact.validate()?;
        self.process.validate()?;
        self.network.validate()?;
        self.resources.validate()?;
        if self.mounts.len() > 128 || self.secrets.len() > 128 || self.outputs.len() > 128 {
            return Err("Runtime unit input or output count exceeds protocol limits".into());
        }

        let mut mount_names = BTreeSet::new();
        let mut mount_targets = BTreeSet::new();
        for mount in &self.mounts {
            mount.validate()?;
            if !mount_names.insert(&mount.name) || !mount_targets.insert(&mount.target) {
                return Err("Runtime mount names and targets must be unique".into());
            }
        }

        let mut secret_names = BTreeSet::new();
        let mut secret_targets = BTreeSet::new();
        for secret in &self.secrets {
            secret.validate()?;
            let target = serde_json::to_string(&secret.target)
                .map_err(|error| format!("could not encode secret target: {error}"))?;
            if !secret_names.insert(&secret.name) || !secret_targets.insert(target) {
                return Err("Runtime secret names and targets must be unique".into());
            }
        }

        let mut output_names = BTreeSet::new();
        let mut output_paths = BTreeSet::new();
        for output in &self.outputs {
            output.validate()?;
            if !output_names.insert(&output.name) || !output_paths.insert(&output.path) {
                return Err("Runtime output names and paths must be unique".into());
            }
        }

        if let Some(digest) = &self.semantics_profile_digest {
            super::validate_digest(digest)?;
        }

        match self.class {
            RuntimeUnitClass::Task => {
                if self.resources.execution_timeout_ms.is_none() {
                    return Err("Task requires execution_timeout_ms".into());
                }
                if self.health.is_some() || matches!(self.restart, RestartPolicy::Always) {
                    return Err("Task cannot use health checks or an always restart policy".into());
                }
            }
            RuntimeUnitClass::Service => {
                if self.resources.execution_timeout_ms.is_some() || !self.outputs.is_empty() {
                    return Err("Service cannot use an execution timeout or Task outputs".into());
                }
                if let Some(health) = &self.health {
                    health.validate(&self.network)?;
                }
            }
        }
        Ok(())
    }

    pub fn digest(&self) -> Result<String, String> {
        self.validate()?;
        let bytes = serde_json::to_vec(self)
            .map_err(|error| format!("could not encode Runtime unit spec: {error}"))?;
        Ok(format!("sha256:{:x}", Sha256::digest(bytes)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;

    fn artifact() -> ArtifactRef {
        ArtifactRef {
            uri: format!("oci://registry.example/a3s/demo@sha256:{}", "a".repeat(64)),
            digest: format!("sha256:{}", "a".repeat(64)),
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
        }
    }

    fn resources(timeout: Option<u64>) -> ResourceLimits {
        ResourceLimits {
            cpu_millis: 500,
            memory_bytes: 128 * 1024 * 1024,
            pids: 128,
            ephemeral_storage_bytes: Some(1024 * 1024 * 1024),
            execution_timeout_ms: timeout,
        }
    }

    fn task() -> RuntimeUnitSpec {
        RuntimeUnitSpec {
            schema: RuntimeUnitSpec::SCHEMA.into(),
            unit_id: "build-1".into(),
            generation: 1,
            class: RuntimeUnitClass::Task,
            artifact: artifact(),
            process: RuntimeProcessSpec {
                command: vec!["/bin/build".into()],
                args: vec![],
                working_directory: Some("/workspace".into()),
                environment: BTreeMap::new(),
            },
            mounts: vec![],
            secrets: vec![],
            network: RuntimeNetworkSpec {
                mode: super::super::NetworkMode::Outbound,
                ports: vec![],
            },
            resources: resources(Some(60_000)),
            isolation: IsolationLevel::Container,
            health: None,
            restart: RestartPolicy::OnFailure { max_retries: 1 },
            outputs: vec![RuntimeOutputSpec {
                name: "image".into(),
                path: "/outputs/image.json".into(),
                media_type: "application/json".into(),
                max_bytes: 1024,
            }],
            semantics_profile_digest: None,
        }
    }

    fn service() -> RuntimeUnitSpec {
        let mut spec = task();
        spec.unit_id = "service-1".into();
        spec.class = RuntimeUnitClass::Service;
        spec.resources = resources(None);
        spec.outputs.clear();
        spec.restart = RestartPolicy::Always;
        spec.network = RuntimeNetworkSpec {
            mode: super::super::NetworkMode::Service,
            ports: vec![super::super::RuntimePort {
                name: "http".into(),
                container_port: 8080,
                protocol: super::super::TransportProtocol::Tcp,
            }],
        };
        spec.health = Some(RuntimeHealthCheck {
            probe: HealthProbe::Http {
                port: "http".into(),
                path: "/health".into(),
                expected_statuses: vec![200],
            },
            interval_ms: 5_000,
            timeout_ms: 1_000,
            start_period_ms: 10_000,
            success_threshold: 1,
            failure_threshold: 3,
        });
        spec
    }

    #[test]
    fn task_and_service_specs_are_general_and_digest_stable() {
        let task = task();
        let service = service();
        task.validate().unwrap();
        service.validate().unwrap();
        assert_eq!(task.digest().unwrap(), task.digest().unwrap());
        assert_ne!(task.digest().unwrap(), service.digest().unwrap());
    }

    #[test]
    fn lifecycle_specific_fields_fail_closed() {
        let mut task = task();
        task.resources.execution_timeout_ms = None;
        assert!(task.validate().is_err());

        let mut service = service();
        service.outputs.push(RuntimeOutputSpec {
            name: "invalid".into(),
            path: "/output".into(),
            media_type: "text/plain".into(),
            max_bytes: 1,
        });
        assert!(service.validate().is_err());
    }

    #[test]
    fn health_checks_reference_declared_ports() {
        let mut service = service();
        let health = service.health.as_mut().unwrap();
        health.probe = HealthProbe::Tcp {
            port: "missing".into(),
        };
        assert!(service.validate().is_err());
    }
}