hpr_format/lib.rs
1//! The HPR open design format: a rocket design as one JSON document, with its JSON Schema.
2//!
3//! [The format's page][guide-format] says what a document holds, how it's versioned, and how it
4//! was checked. The format is version 0.2, a draft until FusionSpace HPR's first release, and a
5//! document of version 0.1 is migrated when it's read. The draft can change in place, so keep the
6//! source `.ork` too.
7//!
8//! A document is a [`DesignFile`]. It opens with a header naming the format ([`FORMAT`]), its
9//! version ([`VERSION`]) and where the design came from ([`Provenance`]). Then comes the design as
10//! [`hpr_io::ork`] reads it from a `.ork`. Last comes every other entry of that file's archive,
11//! such as an embedded thrust curve or a decal image.
12//!
13//! The design holds the rocket, every motor configuration, the recovery events and the
14//! simulations stored with it. What the source file holds that HPR Sim doesn't model is kept
15//! under a namespaced extension (`x-openrocket`). A `.ork` written from a document is the `.ork`
16//! HPR Sim writes from the file it was read from, byte for byte. That was checked on the 73
17//! designs HPR Sim's `.ork` checks read ([the format's decision record][adr-111]).
18//!
19//! [`to_json`] writes the canonical text: two-space indents, keys in the order the types declare
20//! them, and a final newline. So the same design always gives the same bytes, and a change shows
21//! as a small diff. [`from_json`] reads it back to the same value. It takes a document of an
22//! older version to the current one ([`migrate`]). It refuses one of another format or a newer
23//! version, with the reason. [`schema`] is the document's JSON Schema, committed as
24//! [`schema/format/hpr-design-0.2.schema.json`][schema-file] beside the older versions' schemas.
25//! A [`container`] (`.hprz`) carries a design with other files, such as its flight logs.
26//!
27//! TypeScript and Python programs read a document through types generated from the schema, under
28//! `schema/format/typescript/` and `schema/format/python/`. Each comes with a reader that checks a
29//! document against the schema ([the format page][format-page], [the milestone that added
30//! them][m3-3c]).
31//!
32//! ```
33//! use hpr_format::{DesignFile, Provenance, from_json, to_json};
34//!
35//! let bytes = include_bytes!("../../../validation/fixtures/ork/loft-demo/demo-stable.ork");
36//! let read = DesignFile::from_ork(bytes)?;
37//! let text = to_json(&read.value)?;
38//! assert!(text.starts_with("{\n \"format\": \"hpr-design\",\n \"version\": \"0.2\","));
39//! assert_eq!(from_json(&text)?, read.value);
40//! # Ok::<(), Box<dyn std::error::Error>>(())
41//! ```
42//!
43//! [guide-format]: https://hpr.fusionspace.co/format/hpr.html
44//! [adr-111]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-111-m33-the-hpr-design-format-its-extensions-versions-and-crate-2026-09-29
45//! [schema-file]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/schema/format/hpr-design-0.2.schema.json
46//! [m3-3c]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m3-3c
47//! [format-page]: https://hpr.fusionspace.co/format/hpr.html#typescript-and-python
48
49// Outside bytes reach casts here. An `as` cast of a length or count truncates silently where
50// `usize` is 32 bits (wasm32), and one from a float saturates: each cast is checked with
51// `try_from`, or its `allow` says why it is exact or meant.
52#![warn(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
53#![cfg_attr(
54 test,
55 allow(
56 clippy::cast_possible_truncation,
57 clippy::cast_sign_loss,
58 reason = "a test builds its own inputs, so it sets its casts' ranges"
59 )
60)]
61use std::collections::BTreeSet;
62use std::fmt;
63
64use base64::Engine as _;
65use base64::engine::general_purpose::STANDARD as BASE64;
66use hpr_design::Rocket;
67use hpr_io::ork::{
68 self, Attachment, Curve, Design, Extensions, Imported, Motors, OrkError, Recovery,
69 StoredSimulation,
70};
71use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
72use serde::{Deserialize, Serialize};
73use sha2::{Digest, Sha256};
74
75/// The format's name, the value of every document's `format` key.
76pub const FORMAT: &str = "hpr-design";
77
78/// The version this crate writes and reads.
79pub const VERSION: Version = Version { major: 0, minor: 2 };
80
81/// The extension of a design written as plain JSON ([ADR-111][adr-111]): `.hpr`.
82///
83/// [adr-111]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-111-m33-the-hpr-design-format-its-extensions-versions-and-crate-2026-09-29
84pub const EXTENSION: &str = "hpr";
85
86/// The extension of the zip container of a design and its attachments ([`container`]): `.hprz`.
87pub const CONTAINER_EXTENSION: &str = "hprz";
88
89/// The media type of a `.hpr` file, `application/vnd.fusionspace.hpr+json` ([ADR-199][adr-199]
90/// §4): FusionSpace's, in RFC 6838's vendor tree, with the `+json` suffix of a JSON document. Not
91/// registered with IANA. The extension ([`EXTENSION`]) and the format id ([`FORMAT`]) stay as
92/// they are.
93///
94/// [adr-199]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0199-the-2026-10-07-fusionspace-hpr.md
95pub const MEDIA_TYPE: &str = "application/vnd.fusionspace.hpr+json";
96
97/// A design as one document of the HPR design format.
98///
99/// The keys are written in this order. The design's own parts are those of [`hpr_io::ork::Design`],
100/// whose documentation says what each holds.
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
102#[serde(deny_unknown_fields)]
103#[non_exhaustive]
104#[schemars(
105 title = "HPR design",
106 description = "A rocket design in the HPR design format."
107)]
108pub struct DesignFile {
109 /// Always `hpr-design`.
110 pub format: Format,
111 /// The format's version, `major.minor`.
112 pub version: Version,
113 /// Which program wrote the document, and from what.
114 pub provenance: Provenance,
115 /// The rocket: its stages and their parts, with every configuration that flies.
116 pub rocket: Rocket,
117 /// Every motor configuration, flown or not, with why one is not.
118 pub motors: Motors,
119 /// When each parachute and streamer opens and each stage separates.
120 pub recovery: Recovery,
121 /// The simulations the source file stored, with their conditions and results.
122 pub simulations: Vec<StoredSimulation>,
123 /// What the source file holds that HPR Sim does not model, by namespace, kept for writing it
124 /// back.
125 pub extensions: Extensions,
126 /// The source file's other files, in the order it held them: a `.ork` archive's entries
127 /// besides the design, such as embedded thrust curves and decal images. Version 0.1 called
128 /// them `attachments`.
129 pub source_files: Vec<SourceFile>,
130}
131
132impl DesignFile {
133 /// The document of `design`, with its provenance and the source file's other files.
134 ///
135 /// `source_files` must hold each thrust curve the design's motors name as embedded
136 /// ([`Curve::Embedded`]): the file's own
137 /// [`OrkFile::attachments`](hpr_io::ork::OrkFile::attachments) do. Without one, [`to_json`]
138 /// refuses the document.
139 ///
140 /// A design read from a `.ork` should name, in its provenance's
141 /// [`Source::airframe_not_as_written`], why the file's airframe was not read exactly as written,
142 /// if it wasn't: without it, a program flies another motor in a rocket its `.ork` refuses.
143 /// [`DesignFile::from_ork`] sets it.
144 pub fn new(design: Design, provenance: Provenance, source_files: &[Attachment]) -> Self {
145 Self {
146 format: Format::HprDesign,
147 version: VERSION,
148 provenance,
149 rocket: design.rocket,
150 motors: design.motors,
151 recovery: design.recovery,
152 simulations: design.simulations,
153 extensions: design.extensions,
154 source_files: source_files.iter().map(SourceFile::of).collect(),
155 }
156 }
157
158 /// Reads a `.ork` file's bytes (zip, gzip or raw XML) into a document whose provenance names
159 /// this program, the file's SHA-256 and why its airframe was not read exactly as written, if
160 /// it wasn't, with the reader's warnings.
161 ///
162 /// The design is [`hpr_io::ork::design`]'s: a motor configuration flies with the curve the
163 /// file itself holds.
164 ///
165 /// # Errors
166 ///
167 /// [`OrkError`] when the bytes are not a `.ork` HPR Sim can read.
168 pub fn from_ork(bytes: &[u8]) -> Result<Imported<Self>, OrkError> {
169 let file = ork::read(bytes)?;
170 let design = ork::design(&file.value);
171 let mut warnings = file.warnings;
172 warnings.extend(design.warnings);
173 let mut source = Source::of(SourceFormat::Ork, bytes);
174 source.airframe_not_as_written = ork::airframe_not_as_written(&file.value);
175 let provenance = Provenance::hpr(Some(source));
176 Ok(Imported {
177 value: Self::new(design.value, provenance, &file.value.attachments),
178 warnings,
179 })
180 }
181
182 /// The document as this program writes it again: its provenance names this build, and
183 /// where the design came from is kept exactly as read ([`Provenance::rewritten`]). A
184 /// conversion writes a new file, so the program that wrote it is this one; the design's
185 /// source doesn't change.
186 #[must_use]
187 pub fn stamped(self) -> Self {
188 Self {
189 provenance: self.provenance.rewritten(),
190 ..self
191 }
192 }
193
194 /// The design the document holds, as [`hpr_io::ork`] would have read it.
195 pub fn design(&self) -> Design {
196 Design::new(
197 self.rocket.clone(),
198 self.motors.clone(),
199 self.recovery.clone(),
200 self.simulations.clone(),
201 self.extensions.clone(),
202 )
203 }
204
205 /// The source file's other files, as bytes.
206 ///
207 /// # Errors
208 ///
209 /// [`FormatError::Invalid`] when a file's base64 does not decode; [`from_json`] refuses such a
210 /// document, so only one built in code can hold one.
211 pub fn source_files(&self) -> Result<Vec<Attachment>, FormatError> {
212 self.source_files
213 .iter()
214 .map(|file| {
215 Ok(Attachment {
216 name: file.name.clone(),
217 bytes: file.bytes()?,
218 })
219 })
220 .collect()
221 }
222
223 /// The design written as a `.ork` ([`hpr_io::ork::export::write`]) with the source file's
224 /// other files, so it is the `.ork` HPR Sim writes from the source file itself.
225 ///
226 /// # Errors
227 ///
228 /// [`FormatError::Invalid`] for a source file that does not decode, and
229 /// [`FormatError::Ork`] when the archive cannot be written.
230 pub fn to_ork(&self) -> Result<Imported<Vec<u8>>, FormatError> {
231 ork::export::write(&self.design(), &self.source_files()?)
232 .map_err(|error| FormatError::Ork(error.to_string()))
233 }
234
235 /// What in a document read from JSON the types alone don't hold to: the source's SHA-256 has
236 /// the schema's pattern ([`Source::check`]); every source file decodes, has its own name, and
237 /// is a file a `.ork` can hold besides its design; and every thrust curve embedded in the
238 /// source file is among them.
239 fn check(&self) -> Result<(), FormatError> {
240 if let Some(source) = &self.provenance.source {
241 source.check()?;
242 }
243 let mut names = BTreeSet::new();
244 for file in &self.source_files {
245 file.bytes()?;
246 if !names.insert(file.name.as_str()) {
247 return Err(FormatError::Invalid(format!(
248 "two source files are named {:?}",
249 shortened(&file.name)
250 )));
251 }
252 // The design's own entry, and a directory's name, don't come back from a `.ork`.
253 if file.name.is_empty() || file.name == "rocket.ork" || file.name.ends_with(['/', '\\'])
254 {
255 return Err(FormatError::Invalid(format!(
256 "a source file is named {:?}, which a .ork can't hold besides its design",
257 shortened(&file.name)
258 )));
259 }
260 }
261 let entries = self
262 .motors
263 .configurations
264 .iter()
265 .flat_map(|configuration| &configuration.motors)
266 .filter_map(|motor| match &motor.curve {
267 Curve::Embedded { entry, .. } => Some(entry),
268 _ => None,
269 });
270 for entry in entries {
271 if !names.contains(entry.as_str()) {
272 return Err(FormatError::Invalid(format!(
273 "a motor's curve is embedded as {:?}, which the source files don't hold",
274 shortened(entry)
275 )));
276 }
277 }
278 Ok(())
279 }
280}
281
282/// One of the source file's other files: its name, and its contents as text where they are UTF-8,
283/// or else as base64 ([RFC 4648][rfc-4648], section 4).
284///
285/// Beyond the schema, the reader holds a document's source files to four rules: base64 decodes; no
286/// two share a name; each thrust curve a motor names as embedded is among them; and a name is not
287/// empty, not `rocket.ork` (the design's own entry) and not a directory's, ending in `/` or `\`.
288///
289/// [rfc-4648]: https://www.rfc-editor.org/rfc/rfc4648#section-4
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
291#[serde(deny_unknown_fields)]
292#[non_exhaustive]
293pub struct SourceFile {
294 /// Its name in the source file, such as `thrustcurves/<digest>.rse`.
295 pub name: String,
296 /// Its contents.
297 pub content: Content,
298}
299
300impl SourceFile {
301 /// `attachment`, an entry of the source file's archive, as text if it is UTF-8.
302 pub fn of(attachment: &Attachment) -> Self {
303 let content = match std::str::from_utf8(&attachment.bytes) {
304 Ok(text) => Content::Text(text.to_owned()),
305 Err(_) => Content::Base64(BASE64.encode(&attachment.bytes)),
306 };
307 Self {
308 name: attachment.name.clone(),
309 content,
310 }
311 }
312
313 /// Its bytes.
314 ///
315 /// # Errors
316 ///
317 /// [`FormatError::Invalid`] when its base64 does not decode.
318 pub fn bytes(&self) -> Result<Vec<u8>, FormatError> {
319 match &self.content {
320 Content::Text(text) => Ok(text.clone().into_bytes()),
321 Content::Base64(encoded) => BASE64.decode(encoded).map_err(|error| {
322 FormatError::Invalid(format!("source file {:?}: {error}", shortened(&self.name)))
323 }),
324 }
325 }
326}
327
328/// A file's contents: text, or base64 for bytes that are not UTF-8.
329#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
330#[serde(rename_all = "snake_case", deny_unknown_fields)]
331#[non_exhaustive]
332pub enum Content {
333 /// UTF-8 text, as the file holds it.
334 Text(String),
335 /// Any other bytes, in standard base64 with padding, which must decode.
336 Base64(String),
337}
338
339/// The format's name: a document holds only `hpr-design`.
340#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
341pub enum Format {
342 /// A rocket design.
343 #[serde(rename = "hpr-design")]
344 HprDesign,
345}
346
347/// A version of the format, written `major.minor` ([ADR-111][adr-111]).
348///
349/// While the major version is 0, every minor version may change the document in ways an older
350/// reader cannot follow, so a reader takes only its own version and those it can migrate from.
351///
352/// [adr-111]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-111-m33-the-hpr-design-format-its-extensions-versions-and-crate-2026-09-29
353#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
354#[serde(try_from = "String", into = "String")]
355pub struct Version {
356 /// The major version.
357 pub major: u32,
358 /// The minor version.
359 pub minor: u32,
360}
361
362impl fmt::Display for Version {
363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364 write!(f, "{}.{}", self.major, self.minor)
365 }
366}
367
368impl From<Version> for String {
369 fn from(version: Version) -> Self {
370 version.to_string()
371 }
372}
373
374impl TryFrom<String> for Version {
375 type Error = String;
376
377 fn try_from(text: String) -> Result<Self, Self::Error> {
378 let number = |part: &str| {
379 // Digits only: no sign, no spaces, no leading zero but a lone "0".
380 let plain = !part.is_empty()
381 && part.bytes().all(|byte| byte.is_ascii_digit())
382 && (part == "0" || !part.starts_with('0'));
383 plain.then(|| part.parse::<u32>().ok()).flatten()
384 };
385 text.split_once('.')
386 .and_then(|(major, minor)| Some((number(major)?, number(minor)?)))
387 .map(|(major, minor)| Self { major, minor })
388 .ok_or_else(|| format!("{text:?} is not a version: it is written major.minor, as 0.1"))
389 }
390}
391
392impl JsonSchema for Version {
393 fn schema_name() -> std::borrow::Cow<'static, str> {
394 "Version".into()
395 }
396
397 fn json_schema(_: &mut SchemaGenerator) -> Schema {
398 json_schema!({
399 "description": "A version of the format, `major.minor`.",
400 "type": "string",
401 "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$",
402 })
403 }
404}
405
406/// Which program wrote a document, and from what.
407#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
408#[serde(deny_unknown_fields)]
409#[non_exhaustive]
410pub struct Provenance {
411 /// The program, such as `FusionSpace HPR` (`hpr-sim` in a document an earlier build wrote).
412 pub tool: String,
413 /// Its version.
414 pub tool_version: String,
415 /// The program's designation in the FusionSpace product system, such as
416 /// `FS-ACHERNAR · SW · TOOL 001` (`FS · SW · TOOL 005` in a document an earlier build wrote);
417 /// absent in a document written before the first release, 0.1.
418 #[serde(default, skip_serializing_if = "Option::is_none")]
419 pub designation: Option<String>,
420 /// The file the design was read from, if it was read from one.
421 #[serde(default, skip_serializing_if = "Option::is_none")]
422 pub source: Option<Source>,
423}
424
425impl Provenance {
426 /// This program, at this version, reading `source`: [`hpr_core::tool::NAME`],
427 /// [`hpr_core::tool::VERSION`] and [`hpr_core::tool::DESIGNATION`].
428 pub fn hpr(source: Option<Source>) -> Self {
429 Self {
430 tool: hpr_core::tool::NAME.to_owned(),
431 tool_version: hpr_core::tool::VERSION.to_owned(),
432 designation: Some(hpr_core::tool::DESIGNATION.to_owned()),
433 source,
434 }
435 }
436
437 /// This provenance as a document this program writes again records it: the program fields
438 /// name this build ([`Provenance::hpr`]), and [`Provenance::source`] stays exactly as read.
439 /// A conversion writes a new file, so the program that wrote it is this one; where the
440 /// design came from doesn't change.
441 ///
442 /// ```
443 /// use hpr_format::{DesignFile, from_json, to_json};
444 ///
445 /// let bytes = include_bytes!("../../../validation/fixtures/ork/loft-demo/demo-stable.ork");
446 /// let mut read = DesignFile::from_ork(bytes)?.value;
447 /// read.provenance.tool_version = "0.0.1".to_owned();
448 /// read.provenance.designation = None;
449 ///
450 /// let rewritten = read.provenance.rewritten();
451 /// assert_eq!(rewritten.tool_version, hpr_core::tool::VERSION);
452 /// assert_eq!(rewritten.designation.as_deref(), Some(hpr_core::tool::DESIGNATION));
453 /// assert_eq!(rewritten.source, read.provenance.source);
454 /// # Ok::<(), Box<dyn std::error::Error>>(())
455 /// ```
456 #[must_use]
457 pub fn rewritten(&self) -> Self {
458 Self::hpr(self.source.clone())
459 }
460}
461
462/// The file a design was read from: its format and its SHA-256, which name it without its path,
463/// and whether its rocket was read exactly as written.
464#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
465#[serde(deny_unknown_fields)]
466#[non_exhaustive]
467pub struct Source {
468 /// The file's format.
469 pub format: SourceFormat,
470 /// The SHA-256 of the file's bytes, as 64 lowercase hexadecimal digits.
471 #[schemars(regex(pattern = "^[0-9a-f]{64}$"))]
472 pub sha256: String,
473 /// Why the file's airframe or a motor mount was not read exactly as written, if it wasn't: a
474 /// part left out, a value dropped or simplified, or something assumed
475 /// ([`hpr_io::ork::airframe_not_as_written`]). No configuration of such a rocket flies, and
476 /// `hpr sim` flies no other motor in it. Absent when the rocket was read as written. A document
477 /// migrated from 0.1 that doesn't show which holds exactly [`migrate::UNKNOWN`], a fixed text a
478 /// program can compare against.
479 #[serde(default, skip_serializing_if = "Option::is_none")]
480 pub airframe_not_as_written: Option<String>,
481}
482
483impl Source {
484 /// The schema's pattern for [`Source::sha256`], `^[0-9a-f]{64}$`, which a `String` alone
485 /// doesn't hold to: exactly 64 lowercase hexadecimal digits, so a document HPR Sim reads passes
486 /// the schema.
487 fn check(&self) -> Result<(), FormatError> {
488 let digits = self.sha256.len() == 64
489 && self
490 .sha256
491 .bytes()
492 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'));
493 if digits {
494 Ok(())
495 } else {
496 Err(FormatError::Invalid(format!(
497 "provenance.source.sha256 is {:?}, not 64 lowercase hexadecimal digits",
498 shortened(&self.sha256)
499 )))
500 }
501 }
502
503 /// The source `bytes` of `format`, its rocket read as written; set
504 /// [`Source::airframe_not_as_written`] when it wasn't.
505 pub fn of(format: SourceFormat, bytes: &[u8]) -> Self {
506 let digest = Sha256::digest(bytes);
507 let sha256 = digest
508 .iter()
509 .fold(String::with_capacity(64), |mut hex, byte| {
510 hex.push_str(&format!("{byte:02x}"));
511 hex
512 });
513 Self {
514 format,
515 sha256,
516 airframe_not_as_written: None,
517 }
518 }
519}
520
521/// The formats a design can be read from.
522#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
523#[serde(rename_all = "snake_case")]
524#[non_exhaustive]
525pub enum SourceFormat {
526 /// OpenRocket's `.ork`.
527 Ork,
528 /// A document of this format.
529 HprDesign,
530}
531
532/// Why a document could not be written or read.
533#[derive(Debug, Clone, PartialEq, thiserror::Error)]
534#[non_exhaustive]
535pub enum FormatError {
536 /// The text is not JSON.
537 #[error("not JSON: {0}")]
538 Json(String),
539 /// The JSON is not a document of this format: its `format` is missing or another.
540 #[error("not an HPR design: the document's \"format\" is {found}, not \"hpr-design\"")]
541 NotADesign {
542 /// What the document holds, as JSON, or `missing`.
543 found: String,
544 },
545 /// The document is of a version this reader neither takes nor migrates from.
546 #[error(
547 "the document is version {found}, and this reader takes version {supported}{}",
548 if found > supported {
549 ": it was written by a newer program".to_owned()
550 } else {
551 format!(" and migrates from {} on", migrate::OLDEST)
552 }
553 )]
554 Unsupported {
555 /// The document's version.
556 found: Version,
557 /// The version this reader takes and writes.
558 supported: Version,
559 },
560 /// The document names the format and version but does not follow the schema.
561 #[error("not a valid HPR design {VERSION}: {0}")]
562 Invalid(String),
563 /// The design holds a value JSON cannot carry exactly, such as a number that is not finite,
564 /// so the text would not read back as the same design.
565 #[error("the design does not read back the same from its JSON: {0}")]
566 NotRepresentable(String),
567 /// The `.ork` could not be written.
568 #[error("the .ork could not be written: {0}")]
569 Ork(String),
570 /// A `.hprz` container could not be read or written ([`container`]).
571 #[error("not a valid .hprz: {0}")]
572 Container(String),
573}
574
575/// The canonical JSON text of `document`: two-space indents, keys in declared order, a final
576/// newline.
577///
578/// # Errors
579///
580/// [`FormatError::Invalid`] for a document of another version, which this crate doesn't write;
581/// [`FormatError::NotRepresentable`] when the text would not read back as `document`,
582/// including when [`from_json`] would refuse it (a rule of [`SourceFile`]): every
583/// document written is read again and compared, so a value JSON cannot carry (a number that is
584/// not finite) is refused here rather than lost.
585pub fn to_json(document: &DesignFile) -> Result<String, FormatError> {
586 if document.version != VERSION {
587 return Err(FormatError::Invalid(format!(
588 "its \"version\" is {}, and this program writes only {VERSION}",
589 document.version
590 )));
591 }
592 let mut text = serde_json::to_string_pretty(document)
593 .map_err(|error| FormatError::NotRepresentable(error.to_string()))?;
594 text.push('\n');
595 match from_json(&text) {
596 Ok(back) if back == *document => Ok(text),
597 Ok(_) => Err(FormatError::NotRepresentable(
598 "a value reads back differently".to_owned(),
599 )),
600 Err(error) => Err(FormatError::NotRepresentable(error.to_string())),
601 }
602}
603
604/// Reads a document from its JSON text, taking one of an older version to the current one.
605///
606/// [`read_json`] with the version the text was written in dropped.
607///
608/// # Errors
609///
610/// [`FormatError`]: not JSON, not an HPR design, a version this reader doesn't take, or not
611/// valid.
612pub fn from_json(text: &str) -> Result<DesignFile, FormatError> {
613 read_json(text).map(|opened| opened.value)
614}
615
616/// A document read, and the version it was written in.
617#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
618#[non_exhaustive]
619pub struct Opened<T> {
620 /// What was read, in the current version.
621 pub value: T,
622 /// The version the text was written in: older than [`VERSION`] when it was migrated.
623 pub written_as: Version,
624}
625
626/// Reads a document from its JSON text, and says which version it was written in.
627///
628/// The format and version are checked first, so a file of another kind or version is refused with
629/// that reason rather than with the first field the reader does not know. A document of an older
630/// version this reader migrates from ([`migrate`]) is rewritten into the current version's shape
631/// and then read as one, so it is held to every rule a current document is.
632///
633/// A document this reader takes passes the [`schema`]: beyond the types, it refuses a source's
634/// SHA-256 that isn't 64 lowercase hexadecimal digits, and an array where the schema has an object
635/// (which serde alone reads as a struct's fields in order). It also refuses a few documents the
636/// schema takes, by the rules of [`SourceFile`].
637///
638/// # Errors
639///
640/// [`FormatError`]: not JSON, not an HPR design, a version this reader doesn't take, or not
641/// valid.
642pub fn read_json(text: &str) -> Result<Opened<DesignFile>, FormatError> {
643 // A byte-order mark, which some Windows editors write at the start of UTF-8, is not JSON.
644 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
645 let value: serde_json::Value =
646 serde_json::from_str(text).map_err(|error| FormatError::Json(error.to_string()))?;
647 let serde_json::Value::Object(mut object) = value else {
648 return Err(FormatError::NotADesign {
649 found: format!("absent: the JSON is {}, not an object", kind(&value)),
650 });
651 };
652 match object.get("format") {
653 Some(serde_json::Value::String(format)) if format == FORMAT => {}
654 Some(other) => {
655 return Err(FormatError::NotADesign {
656 found: shortened(&other.to_string()),
657 });
658 }
659 None => {
660 return Err(FormatError::NotADesign {
661 found: "missing".to_owned(),
662 });
663 }
664 }
665 let found = match object.get("version") {
666 Some(serde_json::Value::String(version)) => {
667 Version::try_from(shortened(version)).map_err(FormatError::Invalid)?
668 }
669 Some(other) => {
670 return Err(FormatError::Invalid(format!(
671 "its \"version\" is {}, not a string such as \"{VERSION}\"",
672 shortened(&other.to_string())
673 )));
674 }
675 None => return Err(FormatError::Invalid("it has no \"version\"".to_owned())),
676 };
677 let (document, read): (DesignFile, _) = if found == VERSION {
678 // Read from the text, not the value, so an error names its line and column.
679 let document =
680 serde_json::from_str(text).map_err(|error| FormatError::Invalid(error.to_string()))?;
681 (document, serde_json::Value::Object(object))
682 } else if migrate::migrates_from(found) {
683 migrate::migrate(&mut object, found).map_err(FormatError::Invalid)?;
684 let read = serde_json::Value::Object(object);
685 let document = DesignFile::deserialize(&read)
686 .map_err(|error| FormatError::Invalid(format!("migrated from {found}: {error}")))?;
687 (document, read)
688 } else {
689 return Err(FormatError::Unsupported {
690 found,
691 supported: VERSION,
692 });
693 };
694 no_array_for_an_object(&read, &document)?;
695 document.check()?;
696 Ok(Opened {
697 value: document,
698 written_as: found,
699 })
700}
701
702/// Refuses a document whose JSON holds an array where `document`, written back, holds an object.
703///
704/// serde reads a struct, or a variant of an enum tagged inside its object, from an array of its
705/// fields in order (`"provenance": ["FusionSpace HPR", "0.1.0"]`), and a struct whose fields all have
706/// defaults from `[]`. The schema wants an object there, so the reader refuses it too: every
707/// object HPR Sim writes is one in the text it reads.
708///
709/// # Errors
710///
711/// [`FormatError::Invalid`] naming the first such place, as a path such as
712/// `rocket.stages[0].components[2].motor_mount`.
713fn no_array_for_an_object(
714 read: &serde_json::Value,
715 document: &DesignFile,
716) -> Result<(), FormatError> {
717 let written =
718 serde_json::to_value(document).map_err(|error| FormatError::Invalid(error.to_string()))?;
719 let mut path = Vec::new();
720 if array_for_an_object(read, &written, &mut path) {
721 return Err(FormatError::Invalid(format!(
722 "{} is an array, where the schema has an object",
723 path_text(&path)
724 )));
725 }
726 Ok(())
727}
728
729/// A step from a JSON value into one it holds.
730enum Step<'a> {
731 /// The value under a key.
732 Key(&'a str),
733 /// An item of an array.
734 Index(usize),
735}
736
737/// Whether `read` holds an array where `written` holds an object, leaving `path` at the first
738/// such place. Only keys and items both hold are followed.
739fn array_for_an_object<'a>(
740 read: &'a serde_json::Value,
741 written: &serde_json::Value,
742 path: &mut Vec<Step<'a>>,
743) -> bool {
744 use serde_json::Value;
745 match (read, written) {
746 (Value::Array(_), Value::Object(_)) => true,
747 (Value::Object(read), Value::Object(written)) => {
748 for (key, value) in read {
749 if let Some(back) = written.get(key) {
750 path.push(Step::Key(key));
751 if array_for_an_object(value, back, path) {
752 return true;
753 }
754 path.pop();
755 }
756 }
757 false
758 }
759 (Value::Array(read), Value::Array(written)) => {
760 for (index, (value, back)) in read.iter().zip(written).enumerate() {
761 path.push(Step::Index(index));
762 if array_for_an_object(value, back, path) {
763 return true;
764 }
765 path.pop();
766 }
767 false
768 }
769 _ => false,
770 }
771}
772
773/// `path` as text, `rocket.stages[0].name`, each key [`shortened`] and the whole cut to its last
774/// 200 characters, so a file's long or deeply nested keys don't make a long message.
775fn path_text(path: &[Step]) -> String {
776 const MAX_CHARS: usize = 200;
777 if path.is_empty() {
778 return "the document".to_owned();
779 }
780 let mut text = String::new();
781 for step in path {
782 match step {
783 Step::Key(key) if text.is_empty() => text.push_str(&shortened(key)),
784 Step::Key(key) => {
785 text.push('.');
786 text.push_str(&shortened(key));
787 }
788 Step::Index(index) => text.push_str(&format!("[{index}]")),
789 }
790 }
791 let count = text.chars().count();
792 if count > MAX_CHARS {
793 let tail: String = text.chars().skip(count - MAX_CHARS).collect();
794 text = format!("…{tail}");
795 }
796 text
797}
798
799/// What kind of JSON value `value` is, in words.
800fn kind(value: &serde_json::Value) -> &'static str {
801 match value {
802 serde_json::Value::Null => "null",
803 serde_json::Value::Bool(_) => "a boolean",
804 serde_json::Value::Number(_) => "a number",
805 serde_json::Value::String(_) => "a string",
806 serde_json::Value::Array(_) => "an array",
807 serde_json::Value::Object(_) => "an object",
808 }
809}
810
811/// `text` cut to its first 40 characters, so a message quoting a file's value stays short.
812fn shortened(text: &str) -> String {
813 const MAX_CHARS: usize = 40;
814 match text.char_indices().nth(MAX_CHARS) {
815 Some((cut, _)) => format!("{}…", &text[..cut]),
816 None => text.to_owned(),
817 }
818}
819
820/// The document's JSON Schema (draft 2020-12), as committed under `schema/format/`.
821pub fn schema() -> serde_json::Value {
822 schemars::schema_for!(DesignFile).to_value()
823}
824
825/// [`schema`] as the canonical text committed: two-space indents and a final newline.
826pub fn schema_json() -> String {
827 let mut text = serde_json::to_string_pretty(&schema())
828 // A schema is a JSON value built from strings and maps, which always serializes.
829 .unwrap_or_default();
830 text.push('\n');
831 text
832}
833
834pub mod container;
835pub mod migrate;
836
837#[cfg(test)]
838mod tests;