Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub mod ledger;
pub mod policy;
pub mod progenitor_operation_retry;
pub mod resolvable_files;
pub mod snake_case_option_result;
pub mod snake_case_result;
pub mod update;
pub mod vlan;
Expand Down
115 changes: 115 additions & 0 deletions common/src/snake_case_option_result.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! A serializable `Option<Result>` that plays nicely with OpenAPI lints.

use crate::snake_case_result::SnakeCaseResult;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(rename = "OptionResult{T}Or{E}")]
#[serde(untagged)]
pub enum SnakeCaseOptionResult<T, E> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oof, sorry, I didn't realize proposing Option<Result<_, _>> would lead to this.

Would it be cleaner to squish this down into an enum of our own? Something like

enum HealthMonitorResult<T> {
    NotYetKnown,
    Ok(T),
    Err(String),
}

? (I don't have strong feelings either way.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, the code is cleaner yes, but the OpenAPI linter forces me to use tags and the result of this ends up being a somewhat weird looking API 😄

I tried out how the API would look using the enum with services in maintenance and the Option<Result<T>> with the unhealthy zpools, and I think the API is much cleaner when using the Option<Result<T>> :

$ curl -H "api-version: 18.0.0"  http://[::1]:55444/inventory | jq .health_monitor
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 21757  100 21757    0     0  8901k      0 --:--:-- --:--:-- --:--:-- 10.3M
{
  "smf_services_in_maintenance": {
    "result": "ok",
    "value": {
      "services": [
        {
          "fmri": "svc:/site/fake-service2:default",
          "zone": "global"
        },
        {
          "fmri": "svc:/site/fake-service:default",
          "zone": "global"
        }
      ],
      "errors": [],
      "time_of_status": "2026-02-03T03:56:03.594752466Z"
    }
  },
  "unhealthy_zpools": {
    "ok": {
      "zpools": [
        {
          "zpool": "fakepool1",
          "state": "degraded"
        },
        {
          "zpool": "fakepool2",
          "state": "degraded"
        }
      ],
      "errors": [],
      "time_of_status": "2026-02-03T03:56:03.560975738Z"
    }
  }
}

If it's not super important, perhaps we can keep it as is?

Some(SnakeCaseResult<T, E>),
None,
}

impl<T, E> JsonSchema for SnakeCaseOptionResult<T, E>
where
T: JsonSchema,
E: JsonSchema,
{
fn schema_name() -> String {
format!("OptionResult{}Or{}", T::schema_name(), E::schema_name())
}

fn json_schema(
generator: &mut schemars::r#gen::SchemaGenerator,
) -> schemars::schema::Schema {
let mut ok_schema = schemars::schema::SchemaObject {
instance_type: Some(schemars::schema::InstanceType::Object.into()),
..Default::default()
};
let obj = ok_schema.object();
obj.required.insert("ok".to_owned());
obj.properties.insert("ok".to_owned(), generator.subschema_for::<T>());

let mut err_schema = schemars::schema::SchemaObject {
instance_type: Some(schemars::schema::InstanceType::Object.into()),
..Default::default()
};
let obj = err_schema.object();
obj.required.insert("err".to_owned());
obj.properties.insert("err".to_owned(), generator.subschema_for::<E>());

let mut schema = schemars::schema::SchemaObject::default();
schema.subschemas().one_of =
Some(vec![ok_schema.into(), err_schema.into()]);

schema
.extensions
.insert(String::from("nullable"), serde_json::json!(true));
schema.extensions.insert(
String::from("x-rust-type"),
serde_json::json!({
"crate": "std",
"version": "*",
"path": "::std::result::Result",
"parameters": [
generator.subschema_for::<T>(),
generator.subschema_for::<E>(),
],
}),
);
schema.into()
}
}

/// Serialize an Option<Result<T, E>> as a `SnakeCaseOptionResult`.
pub fn serialize<S, T, E>(
value: &Option<Result<T, E>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
T: Serialize,
E: Serialize,
{
match value {
None => serializer.serialize_none(),
Some(Ok(val)) => {
SnakeCaseOptionResult::<&T, &E>::Some(SnakeCaseResult::Ok(val))
.serialize(serializer)
}
Some(Err(err)) => {
SnakeCaseOptionResult::<&T, &E>::Some(SnakeCaseResult::Err(err))
.serialize(serializer)
}
}
}

/// Deserialize a `SnakeCaseOptionResult` into an `Option<Result>`.
pub fn deserialize<'de, D, T, E>(
deserializer: D,
) -> Result<Option<Result<T, E>>, D::Error>
where
D: serde::Deserializer<'de>,
T: Deserialize<'de>,
E: Deserialize<'de>,
{
SnakeCaseOptionResult::<T, E>::deserialize(deserializer).map(|snek| {
match snek {
SnakeCaseOptionResult::Some(SnakeCaseResult::Ok(val)) => {
Some(Ok(val))
}
SnakeCaseOptionResult::Some(SnakeCaseResult::Err(err)) => {
Some(Err(err))
}
SnakeCaseOptionResult::None => None,
}
})
}
2 changes: 1 addition & 1 deletion illumos-utils/src/svcs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ impl SvcsInMaintenanceResult {
));
error!(
log,
"unable to parse; output line missing zone:";
"unable to parse; output line missing zone";
"line" => line,
);
continue;
Expand Down
Loading
Loading