Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add
serde
support for ConvexValue
to help with serializing system…
… metadata (#22841) It's very tedious to manually write the conversions between our in-memory structs (like `TableMetadata`) and `ConvexValue`. This change uses Serde to automate some parts of this conversion. Let's use `TableMetadata` as our running example: ```rust pub struct TableMetadata { pub name: TableName, pub number: TableNumber, pub state: TableState, } pub enum TableState { Active, Hidden, Deleting, } ``` To start, the developer defines two `Serialized*` types in Rust that define the serialization format they'd like for this in-memory structure. Think of these definitions in Rust as similar to a Protobuf definition. ```rust #[derive(Serialize, Deserialize)] pub struct SerializedTableMetadata { pub name: String, pub number: i64, pub state: SerializedTableState, } #[derive(Serialize, Deserialize)] #[serde(tag = "type")] pub enum SerializedTableState { Active {}, Hidden {}, Deleting {}, } ``` The developer may have the `Serialized*` structs diverge from the in-memory one to, say, implement backwards compatibility. Note that we're using an empty struct variant for the enum to tell serde to serialize the enum as an object with its variant tagged in the `type` field. Then, implement `TryFrom` conversions both ways. Since this is going between two Rust data types, this should be easier than implementing conversions to and from `ConvexObject`: ```rust impl TryFrom<TableMetadata> for SerializedTableMetadata { type Error = anyhow::Error; ... } impl TryFrom<SerializedTableMetadata> for TableMetadata { type Error = anyhow::Error; ... } impl TryFrom<TableState> for SerializedTableState { type Error = anyhow::Error; ... } impl TryFrom<SerializedTableState> for TableState { type Error = anyhow::Error; ... } ``` Finally, connect the two types together with the `codegen_convex_serialization!` macro. This macro generates conversions to and from `ConvexValue` and `ConvexObject`, and it also defines a roundtrips proptest. ```rust codegen_convex_serialization!(TableMetadata, SerializedTableMetadata); ``` I've ported over all of `bootstrap_model` to this new approach, and I think it cleans stuff up a lot! GitOrigin-RevId: ede5e8a87d608bb72a7007948c91b28472ca4aca
- Loading branch information