Hi! Is there a way to produce proto files from @serialzable kotlin classes? (if possible handling up...
g
Hi! Is there a way to produce proto files from @serialzable kotlin classes? (if possible handling upgrades from previous proto files)
l
You can use the
kotlinx.serialization.protobuf
library to serialize your data to a Byte array, then combine it with something like okio to write to files.
In terms of upgrading, you'll want your serialization to be lenient, such as adding deprecated fields matching the old ones, nullable fields, etc. When you re-encode the data, it should use the 'new' format.
g
I should have been more precise sorry. I'm using the protobuf library to produce ByteArray already, but as I need to maintain both proto files for other services (not always Kotlin) and Kotlin classes for my KMP project, I'm interested to generate the proto files from my data classes. In my dreams, this tool would read proto files and my kotlin class, and update the proto files accordingly to ensure consistency. Does it make sense?
s
Looks like that feature was merged a while ago: https://github.com/Kotlin/kotlinx.serialization/pull/1255
That is, use
ProtoBufSchemaGenerator.generateSchemaText()
.
g
I missed this class, exactly what I was looking for, thank you! (A bit unfortunate that it's not handling proto3 tho, but probably easier to do the changes on files after this generator.)
Oh and
value class
are serialized with the internal type but the generated schema produce a dedicated
message
for it. Is it expected? The byte array produced by a value class is exactly the same than when using the internal type. I'd expect some additional headers in proto format if I add an additional message (also when replacing
value
by
data
it's producing the same schema but a different byte arrays). Feels like it's still a bit experimental, so if anyone reading this has more experience with it, thanks for sharing đŸ™‚