Skip to content

Commit

Permalink
Rewrite Event.DeserializationStrategy (#923)
Browse files Browse the repository at this point in the history
When deserializing Events, Event.DeserializationStrategy assumed that
the d field [1] was the last field to be observed. If it wasn't the last
field, the deserialization could fail in two ways:

 * the t and s fields were ignored if they came after the d field

 * an exception was thrown if the op field came after the d field

To fix these possible failure cases, the deserialization logic has been
changed to work in two steps:

 1. decode all fields regardless of order, treating the d field as a
    plain JsonElement

 2. after all fields have been decoded, construct an Event from the
    JsonElement, depending on the values of the op, t and s fields

The supertype of Event.DeserializationStrategy has also been changed
from DeserializationStrategy<Event?> to DeserializationStrategy<Event> -
deserialize no longer returns null in some cases of illegal event
payloads, but throws exceptions instead.

Fixes #922

[1] https://discord.com/developers/docs/topics/gateway-events#payload-structure

Co-authored-by: Michael Rittmeister <[email protected]>
  • Loading branch information
lukellmann and DRSchlaubi authored Mar 16, 2024
1 parent 5f9294c commit d1651a7
Show file tree
Hide file tree
Showing 7 changed files with 1,202 additions and 228 deletions.
2 changes: 1 addition & 1 deletion gateway/src/commonMain/kotlin/DefaultGateway.kt
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ public class DefaultGateway(private val data: DefaultGatewayData) : Gateway {

try {
defaultGatewayLogger.trace { "Gateway <<< $json" }
val event = jsonParser.decodeFromString(Event.DeserializationStrategy, json) ?: return
val event = jsonParser.decodeFromString(Event.DeserializationStrategy, json)
data.eventFlow.emit(event)
} catch (exception: Exception) {
defaultGatewayLogger.error(exception) { "" }
Expand Down
360 changes: 133 additions & 227 deletions gateway/src/commonMain/kotlin/Event.kt

Large diffs are not rendered by default.

Loading

0 comments on commit d1651a7

Please sign in to comment.