GREsau / schemars

Generate JSON Schema documents from Rust code
https://graham.cool/schemars/
MIT License
826 stars 229 forks source link

Use full path in json definition generation #177

Closed jawoznia closed 2 months ago

jawoznia commented 2 years ago

Consider example below which I encountered while working on some project.

mod msg1 {
    #[derive(
        serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq, schemars::JsonSchema,
    )]
    #[serde(rename_all = "snake_case")]
    pub enum Msg {
        SomeVariant {},
    }
}

mod msg2 {
    #[derive(
        serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq, schemars::JsonSchema,
    )]
    #[serde(rename_all = "snake_case")]
    pub enum Msg {
        AnotherVariant {},
    }
}

#[derive(
    serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case", untagged)]
pub enum WrapperMsg {
    // Switch order of variants and run tests
    // Notice that only the upper definition is present in println
    Msg1(msg1::Msg),
    Msg2(msg2::Msg),
}

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

    #[test]
    fn call_schema_for() {
        let schema = schemars::schema_for!(WrapperMsg);
        println!("{}", serde_json::to_string_pretty(&schema).unwrap());
    }
}

Example output for above code is

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "WrapperMsg",
  "anyOf": [
    {
      "$ref": "#/definitions/Msg"
    },
    {
      "$ref": "#/definitions/Msg"
    }
  ],
  "definitions": {
    "Msg": {
      "oneOf": [
        {
          "type": "object",
          "required": [
            "some_variant"
          ],
          "properties": {
            "some_variant": {
              "type": "object"
            }
          },
          "additionalProperties": false
        }
      ]
    }
  }
}

It seems that there is no support for colliding variant names from different modules. It would be nice if full path was considered for definition generation as colliding names can occur between modules.

miraclx commented 2 years ago

Was just about to submit a ticket for this. This is really relevant. We can probably come up with a different key discriminant than the type name here:

https://github.com/GREsau/schemars/blob/5268080b014152912a910e3fe8524c4c876407de/schemars/src/gen.rs#L225-L227

Perhaps a Hash of std::any::TypeId?

ewoolsey commented 1 year ago

Commenting here to mention that I have also run into this problem. Would love to see a fix for this, Should be fairly straightforward I imagine.

miraclx commented 1 year ago

Hi @ewoolsey, https://github.com/GREsau/schemars/pull/178 is a potential fix. Although, as highlighted in there, I believe a different approach should be considered. An approach that, in-turn, won't be a simple fix.

ewoolsey commented 1 year ago

Hi @ewoolsey, #178 is a potential fix. Although, as highlighted in there, I believe a different approach should be considered. An approach that, in-turn, won't be a simple fix.

Haha things are never as straightforward as they first seem. @miraclx any Idea when we can expect either of these solutions to be implemented? I'm working on an interactive parser built on top of schemers and serde to generate complex types from user input. Using it to build some cool development tools. Should I proceed with a workaround or wait it out?

miraclx commented 1 year ago

@ewoolsey, depending on your use case, #178 should suffice for schema generation.

For schema consumption, however, clients have to read the title field for type names. Which, unless you're writing your own jsonschema consumer, probably won't use.

But if you are, it should work perfectly.

One last thing to note is that PR aids exhaustive schema generation.

But you should be careful about espousing reductionism when consuming it.

Effectively, you need to be careful not to remap it to {TypeName: TypeSchema}.

Avoiding these classes of errors both when generating and consuming the schema will require a different approach for encoding information in the jsonschema that helps clients further disambiguate types. Module paths might be an option. But that's tricky to extract from macros.

ewoolsey commented 1 year ago

Unfortunately because I'm dealing with a large library that implements JsonSchema on all its types, I'll have to wait for a new release on crates.io :/ Really appreciate the info though! And good luck finding a more robust solution!

karelispanagiotis commented 1 year ago

I encountered the same issue with structs having the same name in different mods.

GREsau commented 2 months ago

This has been fixed since schemars 0.8.14

In the latest version (1.0.0-alpha.3), the output from the code in the original issue is:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "WrapperMsg",
  "anyOf": [
    {
      "$ref": "#/$defs/Msg"
    },
    {
      "$ref": "#/$defs/Msg2"
    }
  ],
  "$defs": {
    "Msg": {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "some_variant": {
              "type": "object"
            }
          },
          "additionalProperties": false,
          "required": [
            "some_variant"
          ]
        }
      ]
    },
    "Msg2": {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "another_variant": {
              "type": "object"
            }
          },
          "additionalProperties": false,
          "required": [
            "another_variant"
          ]
        }
      ]
    }
  }
}