Skip to content

Commit

Permalink
Add websocket.UnknownMessage (#1065)
Browse files Browse the repository at this point in the history
Instead of always skipping structured messages of an unknonw type with a
generic log message, the websocket client will provide them to the configured
handler in the Unknown field of the IncomingMessage type.

Existing message handlers already defensively handle unexpected message types
by explicitly checking for msg.WebhookEvent or msg.RequestLogEvent.
  • Loading branch information
bernerd-stripe authored May 1, 2023
1 parent fad8622 commit fdf8276
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
30 changes: 20 additions & 10 deletions pkg/websocket/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,26 @@ package websocket

import (
"encoding/json"
"fmt"
)

// IncomingMessage represents any incoming message sent by Stripe.
type IncomingMessage struct {
*WebhookEvent
*RequestLogEvent

// Unknown will be present if the incoming message type does not match the
// list known to the CLI.
Unknown *UnknownMessage
}

// UnknownMessage represents an incoming message with a type that's unknown
// to the CLI, and therefore cannot be deserialized into a structured type.
type UnknownMessage struct {
// Type is the value of the type field in the message's data.
Type string

// Data contains the raw data of the message.
Data []byte
}

// UnmarshalJSON deserializes incoming messages sent by Stripe into the
Expand All @@ -23,21 +36,18 @@ func (m *IncomingMessage) UnmarshalJSON(data []byte) error {

switch incomingMessageTypeOnly.Type {
case "webhook_event":
var evt WebhookEvent
if err := json.Unmarshal(data, &evt); err != nil {
if err := json.Unmarshal(data, &m.WebhookEvent); err != nil {
return err
}

m.WebhookEvent = &evt
case "request_log_event":
var evt RequestLogEvent
if err := json.Unmarshal(data, &evt); err != nil {
if err := json.Unmarshal(data, &m.RequestLogEvent); err != nil {
return err
}

m.RequestLogEvent = &evt
default:
return fmt.Errorf("Unexpected message type: %s", incomingMessageTypeOnly.Type)
m.Unknown = &UnknownMessage{
Type: incomingMessageTypeOnly.Type,
Data: data,
}
}

return nil
Expand Down
4 changes: 3 additions & 1 deletion pkg/websocket/messages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ func TestUnmarshalUnknownIncomingMsg(t *testing.T) {

var msg IncomingMessage
err := json.Unmarshal([]byte(data), &msg)
require.EqualError(t, err, "Unexpected message type: unknown_type")
require.NoError(t, err)
require.Equal(t, "unknown_type", msg.Unknown.Type)
require.Equal(t, data, string(msg.Unknown.Data))
}

func TestMarshalWebhookEventAck(t *testing.T) {
Expand Down

0 comments on commit fdf8276

Please sign in to comment.