Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically validate deserialized structs #177

Closed
ggutoski opened this issue Oct 5, 2021 · 3 comments
Closed

Automatically validate deserialized structs #177

ggutoski opened this issue Oct 5, 2021 · 3 comments

Comments

@ggutoski
Copy link
Contributor

ggutoski commented Oct 5, 2021

Serde does not automatically validate deserialized structs. This is annoying because a struct instance that is otherwise guaranteed to be valid by construction can be made invalid via serde round trip. Examples in tofn include GroupPublicInfo and SharePublicInfo.

I spent a long time digging for ergonomic ways to validate serde-deserialized data. 😞 Seems like the best solution is to use deserialize_with as described here serde-rs/serde#1858 (review). Documentation on deserialize_with is sparse---this is all I could find: Field attributes · Serde

If we do go this route then presumably the clean way to do it is for each struct would have a validate() method that is called in two places:

  1. at initial construction (eg. in new())
  2. in deserialize_with

That's a pretty generic pattern---might even be worth a Validator trait or something. Note that this crate exists https://github.com/Keats/validator but at first glance it doesn't seem to meet our needs.

Not sure yet whether we have a strong need for this fix but I can envision a time when we do.

@tarcieri
Copy link

tarcieri commented Oct 5, 2021

A pattern I'd recommend for this is having a separate "serde type" where you derive Serialize/Deserialize, and then impl TryFrom to convert from the "serde type" to a validated struct. You can then have deserialize_with decode to the "serde type" and then call TryFrom

@ggutoski
Copy link
Contributor Author

ggutoski commented Oct 5, 2021

A pattern I'd recommend for this is having a separate "serde type" ...

Thanks for the suggestion! This pattern is described in detail at serde-rs/serde#642 (comment)

@tarcieri
Copy link

tarcieri commented Oct 5, 2021

TIL:

#[serde(try_from = "MyTypeShadow")]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants