optimization_job_api/
spec.rs1use crate::{Result, coded, legacy, storage};
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use std::{
8 collections::BTreeSet,
9 fs,
10 path::{Component, Path},
11};
12
13pub const SCHEMA: &str = "optimization.job/0.1";
16pub const PROTOCOL: &str = "optimization.worker/0.2";
20pub const PROTOCOLS: [&str; 2] = ["optimization.worker/0.1", PROTOCOL];
24pub fn protocol_supported(protocol: &Value) -> bool {
26 protocol.as_str().is_some_and(|p| PROTOCOLS.contains(&p))
27}
28pub const MAX_INPUT_BYTES: u64 = 64 * 1024 * 1024;
30
31#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
34#[serde(deny_unknown_fields)]
35pub struct Resources {
36 pub cpu_slots: usize,
38 pub outer_workers: usize,
40 pub inner_threads: usize,
42}
43#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
45#[serde(deny_unknown_fields)]
46pub struct Limits {
47 pub wall_time_seconds: f64,
50 pub grace_seconds: f64,
53}
54#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
56#[serde(deny_unknown_fields)]
57pub struct Input {
58 pub name: String,
61 pub file: String,
64 pub sha256: String,
66}
67#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
69#[serde(deny_unknown_fields)]
70pub struct JobSpec {
71 pub schema_version: String,
73 pub request_key: String,
76 pub worker: String,
78 pub payload_schema: String,
80 pub payload: Value,
83 pub resources: Resources,
85 pub limits: Limits,
87 #[serde(default)]
89 pub inputs: Vec<Input>,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub task_count: Option<usize>,
93}
94pub fn safe_name(s: &str) -> bool {
98 !s.is_empty()
99 && s.len() <= 80
100 && s.bytes()
101 .all(|c| c.is_ascii_alphanumeric() || b"-_.".contains(&c))
102 && s != "."
103 && s != ".."
104}
105impl JobSpec {
106 pub fn validate(&self) -> Result<()> {
112 if self.schema_version != SCHEMA
113 || self.request_key.is_empty()
114 || self.request_key.len() > 200
115 || !safe_name(&self.worker)
116 || self.payload_schema.is_empty()
117 || !self.payload.is_object()
118 {
119 return Err("invalid job envelope, schema, request_key or worker".into());
120 }
121 let r = &self.resources;
122 if r.cpu_slots == 0
123 || r.cpu_slots > 1024
124 || r.outer_workers == 0
125 || r.inner_threads == 0
126 || r.outer_workers
127 .checked_mul(r.inner_threads)
128 .is_none_or(|n| n > r.cpu_slots)
129 {
130 return Err(
131 "resources require 1 <= outer_workers * inner_threads <= cpu_slots <= 1024".into(),
132 );
133 }
134 if !self.limits.wall_time_seconds.is_finite()
135 || !(0.0..=31_536_000.0).contains(&self.limits.wall_time_seconds)
136 || self.limits.wall_time_seconds == 0.0
137 || !self.limits.grace_seconds.is_finite()
138 || !(0.0..=86400.0).contains(&self.limits.grace_seconds)
139 {
140 return Err("invalid wall time or grace".into());
141 }
142 if self.task_count.is_some_and(|n| n == 0 || n > 1_000_000) || self.inputs.len() > 16 {
143 return Err("invalid task/input count".into());
144 }
145 let mut names = BTreeSet::new();
146 for i in &self.inputs {
147 if !safe_name(&i.name)
148 || !names.insert(&i.name)
149 || i.sha256.len() != 64
150 || !i
151 .sha256
152 .bytes()
153 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
154 || i.file.is_empty()
155 || Path::new(&i.file)
156 .components()
157 .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir))
158 || !Path::new(&i.file)
159 .components()
160 .any(|c| matches!(c, Component::Normal(_)))
161 {
162 return Err("input requires unique safe name, relative contained path and lowercase SHA-256".into());
163 }
164 }
165 Ok(())
166 }
167 pub fn digest(&self) -> Result<String> {
170 let mut v = serde_json::to_value(self)?;
171 v.as_object_mut().unwrap().remove("request_key");
172 Ok(storage::digest(&serde_json::to_vec(&v)?))
173 }
174 pub fn input_bytes(&self, base: &Path, name: &str) -> Result<Vec<u8>> {
177 let input = self
178 .inputs
179 .iter()
180 .find(|i| i.name == name)
181 .ok_or("missing model input")?;
182 checked_input(base, input)
183 }
184}
185pub fn checked_input(base: &Path, input: &Input) -> Result<Vec<u8>> {
189 let base = fs::canonicalize(base)?;
190 let path = fs::canonicalize(base.join(&input.file))?;
191 if !path.starts_with(&base) || !path.is_file() || fs::metadata(&path)?.len() > MAX_INPUT_BYTES {
192 return Err("input escapes directory or exceeds 64 MiB".into());
193 }
194 use std::io::Read;
196 let mut bytes = Vec::new();
197 fs::File::open(path)?
198 .take(MAX_INPUT_BYTES + 1)
199 .read_to_end(&mut bytes)?;
200 if bytes.len() as u64 > MAX_INPUT_BYTES || storage::digest(&bytes) != input.sha256 {
201 return Err("input SHA-256 mismatch or oversized input".into());
202 }
203 Ok(bytes)
204}
205pub fn stage_inputs(s: &mut JobSpec, from: &Path, to: &Path) -> Result<()> {
208 fs::create_dir_all(to.join("inputs"))?;
209 for i in &mut s.inputs {
210 let bytes = checked_input(from, i)?;
211 i.file = format!("inputs/{}", i.name);
212 let path = to.join(&i.file);
213 fs::write(&path, bytes)?;
214 fs::File::open(path)?.sync_all()?;
215 }
216 fs::File::open(to.join("inputs"))?.sync_all()?;
217 Ok(())
218}
219#[derive(Clone, Debug, Serialize)]
221#[serde(untagged)]
222pub enum Request {
223 Legacy(legacy::JobSpec),
225 Job(JobSpec),
227}
228impl Request {
229 pub fn parse(bytes: &[u8]) -> Result<Self> {
231 Self::parse_unchecked(bytes).map_err(|e| coded("invalid_job", e.to_string()))
232 }
233 fn parse_unchecked(bytes: &[u8]) -> Result<Self> {
234 let v: Value = serde_json::from_slice(bytes)?;
235 match v["schema_version"].as_str() {
236 Some("fcmaes.job/0.1") => Ok(Self::Legacy(
237 serde_json::from_value::<legacy::JobSpec>(v)?.resolve()?,
238 )),
239 Some(SCHEMA) => {
240 let s: JobSpec = serde_json::from_value(v)?;
241 s.validate()?;
242 Ok(Self::Job(s))
243 }
244 _ => Err("unsupported job schema".into()),
245 }
246 }
247 pub fn request_key(&self) -> &str {
249 match self {
250 Self::Legacy(s) => &s.request_key,
251 Self::Job(s) => &s.request_key,
252 }
253 }
254 pub fn worker(&self) -> &str {
256 match self {
257 Self::Legacy(_) => "native",
258 Self::Job(s) => &s.worker,
259 }
260 }
261 pub fn slots(&self) -> usize {
264 match self {
265 Self::Legacy(s) => s.execution.workers,
266 Self::Job(s) => s.resources.cpu_slots,
267 }
268 }
269 pub fn wall(&self) -> f64 {
271 match self {
272 Self::Legacy(s) => s.budget.wall_time_seconds,
273 Self::Job(s) => s.limits.wall_time_seconds,
274 }
275 }
276 pub fn grace(&self) -> f64 {
278 match self {
279 Self::Legacy(s) => s.budget.grace_seconds,
280 Self::Job(s) => s.limits.grace_seconds,
281 }
282 }
283 pub fn digest(&self) -> Result<String> {
285 match self {
286 Self::Legacy(s) => s.digest(),
287 Self::Job(s) => s.digest(),
288 }
289 }
290 pub fn save(&self, path: &Path) -> Result<()> {
292 Ok(storage::write_atomic_json(path, self)?)
293 }
294}