Skip to main content

alpha2_eval/edit/
json.rs

1//! The operations over JSON text, which every binding calls, so each answers the same bytes.
2
3use alpha2_model::{Project, ProjectWriteError};
4
5use super::{EditError, EditRequest, apply};
6
7/// An operation's result as canonical JSON text.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct EditedJson {
10    /// The edited project document.
11    pub project: String,
12    /// The [`super::EditReport`].
13    pub report: String,
14}
15
16/// Why [`apply_json`] gave no result.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct EditFailure {
19    /// `INVALID_INPUT`, or `INTERNAL` for an edited project that fails validation.
20    pub code: &'static str,
21    /// The reason in snake case, `invalid_project`, `invalid_request`, `result_too_large` or an
22    /// [`EditError::kind`].
23    pub refusal: &'static str,
24    /// What went wrong.
25    pub message: String,
26}
27
28impl std::fmt::Display for EditFailure {
29    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        formatter.write_str(&self.message)
31    }
32}
33
34impl std::error::Error for EditFailure {}
35
36impl From<EditError> for EditFailure {
37    fn from(error: EditError) -> Self {
38        Self {
39            code: if matches!(error, EditError::InvalidResult(_)) {
40                "INTERNAL"
41            } else {
42                "INVALID_INPUT"
43            },
44            refusal: error.kind(),
45            message: error.to_string(),
46        }
47    }
48}
49
50/// Applies the request `request_json` to the project `project_json`.
51///
52/// # Errors
53/// [`EditFailure`] for an invalid project or request, for every [`EditError`], and for an edited
54/// project longer than a project document may be (`result_too_large`).
55pub fn apply_json(project_json: &str, request_json: &str) -> Result<EditedJson, EditFailure> {
56    let project = Project::from_json(project_json).map_err(|error| EditFailure {
57        code: "INVALID_INPUT",
58        refusal: "invalid_project",
59        message: format!("invalid project: {error}"),
60    })?;
61    let request: EditRequest = serde_json::from_str(request_json).map_err(|error| EditFailure {
62        code: "INVALID_INPUT",
63        refusal: "invalid_request",
64        message: format!("invalid edit request: {error}"),
65    })?;
66    let (edited, report) = apply(&project, &request)?;
67    let text = |value: Result<String, serde_json::Error>| {
68        value.map_err(|error| EditFailure {
69            code: "INTERNAL",
70            refusal: "invalid_result",
71            message: error.to_string(),
72        })
73    };
74    let project = edited.to_json().map_err(|error| match error {
75        ProjectWriteError::TooLarge { .. } => EditFailure {
76            code: "INVALID_INPUT",
77            refusal: "result_too_large",
78            message: format!("the edit is refused: {error}"),
79        },
80        error => EditFailure {
81            code: "INTERNAL",
82            refusal: "invalid_result",
83            message: error.to_string(),
84        },
85    })?;
86    Ok(EditedJson {
87        project,
88        report: text(serde_json::to_string(&report))?,
89    })
90}