Trim SSE event names. (#9342)

* Trim SSE event names.

When sending SSE events the event name contains trailing whitespace.
This patch removes the whitespace before processing the event, ensuring
it is easily parsed by clients.

* Separate test.

* Test receiveEvents, not writeEvent.

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: Radosław Kapka <rkapka@wp.pl>
Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
This commit is contained in:
Jim McDonald
2021-08-12 00:00:39 +01:00
committed by GitHub
parent 225f9a74f6
commit 5256751e8b
2 changed files with 40 additions and 2 deletions

View File

@@ -185,7 +185,11 @@ func receiveEvents(eventChan <-chan *sse.Event, w http.ResponseWriter, req *http
case msg := <-eventChan:
var data interface{}
switch strings.TrimSpace(string(msg.Event)) {
// The message's event comes to us with trailing whitespace. Remove it here for
// ease of future procesing.
msg.Event = bytes.TrimSpace(msg.Event)
switch string(msg.Event) {
case events.HeadTopic:
data = &eventHeadJson{}
case events.BlockTopic:
@@ -215,7 +219,7 @@ func receiveEvents(eventChan <-chan *sse.Event, w http.ResponseWriter, req *http
data = &eventErrorJson{}
default:
return &gateway.DefaultErrorJson{
Message: fmt.Sprintf("Event type '%s' not supported", strings.TrimSpace(string(msg.Event))),
Message: fmt.Sprintf("Event type '%s' not supported", string(msg.Event)),
Code: http.StatusInternalServerError,
}
}

View File

@@ -191,6 +191,40 @@ func TestReceiveEvents_EventNotSupported(t *testing.T) {
assert.Equal(t, "Event type 'not_supported' not supported", errJson.Msg())
}
func TestReceiveEvents_TrailingSpace(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan *sse.Event)
w := httptest.NewRecorder()
w.Body = &bytes.Buffer{}
req := httptest.NewRequest("GET", "http://foo.example", &bytes.Buffer{})
req = req.WithContext(ctx)
go func() {
base64Val := "Zm9v"
data := &eventFinalizedCheckpointJson{
Block: base64Val,
State: base64Val,
Epoch: "1",
}
bData, err := json.Marshal(data)
require.NoError(t, err)
msg := &sse.Event{
Data: bData,
Event: []byte("finalized_checkpoint "),
}
ch <- msg
time.Sleep(time.Second)
cancel()
}()
errJson := receiveEvents(ch, w, req)
assert.Equal(t, true, errJson == nil)
assert.Equal(t, `event: finalized_checkpoint
data: {"block":"0x666f6f","state":"0x666f6f","epoch":"1"}
`, w.Body.String())
}
func TestWriteEvent(t *testing.T) {
base64Val := "Zm9v"
data := &eventFinalizedCheckpointJson{