com-lihaoyi / upickle

uPickle: a simple, fast, dependency-free JSON & Binary (MessagePack) serialization library for Scala
https://com-lihaoyi.github.io/upickle
MIT License
707 stars 158 forks source link

Shorten `$type` tag used for discriminating `sealed trait` cases #596

Open lihaoyi opened 6 days ago

lihaoyi commented 6 days ago

Fixes https://github.com/com-lihaoyi/upickle/issues/527

This PR shortens the "$type": "foo.bar.Qux" tag that uPickle uses to distinguish between cases of a sealed trait, down to "$type": "Qux" or "$type": "bar.Qux". Because the trait is sealed, upickle is able to look at all the other cases, and picks the shortest partially-qualified name that is enough to distinguish all the different cases. As mentioned in the original issue, this makes the serialization format more compact, more robust against code changes (e.g. changes in package name), and it homogenizes the serialization format of sealed trait hierarchies and Scala 3 enums (which already use a short partially-qualified name as the $type tag)

Despite being binary compatible at the JVM level, this is a backwards incompatible change that will need to go into uPickle 4.x. To ease the rollout, the implementation is able to read both old-style fully qualified $type tags as well as new-style partially-qualified $type-tags, and whether new-style output or old-style output is generated during serialization is controlled by a objectTypeKeyWriteFullyQualified flag.

Someone migrating to uPickle 4.x from upickle 3.x can preserve the existing read/write behavior by replacing upickle.default with a CustomPickler with objectTypeKeyWriteFullyQualified = true, roll it out across their system so their entire system can read both old-style and new-style $type tags, and then flip individual components to objectTypeKeyWriteFullyQualified = false (or back to upickle.default). The system will work correctly with a mix of old-style and new-style $type tags being generated, until everything is on new-style $type tags.