Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rpc/handler: do not append null to stream when json may be valid #10390

Merged
merged 2 commits into from
May 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions rpc/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -578,9 +578,28 @@ func writeNilIfNotPresent(stream *jsoniter.Stream) {
} else {
hasNil = false
}
if !hasNil {
stream.WriteNil()
if hasNil {
// not needed
return
}

var validJsonEnd bool
if len(b) > 0 {
// assumption is that api call handlers would write valid json in case of errors
// we are not guaranteed that they did write valid json if last elem is "}" or "]"
// since we don't check json nested-ness
// however appending "null" after "}" or "]" does not help much either
lastIdx := len(b) - 1
validJsonEnd = b[lastIdx] == '}' || b[lastIdx] == ']'
}
if validJsonEnd {
// not needed
return
}

// does not have nil ending
// does not have valid json
stream.WriteNil()
}

// unsubscribe is the callback function for all *_unsubscribe calls.
Expand Down
16 changes: 15 additions & 1 deletion rpc/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ func TestHandlerDoesNotDoubleWriteNull(t *testing.T) {
params: []byte("[3]"),
expected: `{"jsonrpc":"2.0","id":1,"result":{}}`,
},
"err_with_valid_json": {
params: []byte("[4]"),
expected: `{"jsonrpc":"2.0","id":1,"result":{"structLogs":[]},"error":{"code":-32000,"message":"id 4"}}`,
},
}

for name, testParams := range tests {
Expand All @@ -50,7 +54,17 @@ func TestHandlerDoesNotDoubleWriteNull(t *testing.T) {
if id == 2 {
return fmt.Errorf("id 2")
}
stream.WriteEmptyObject()
if id == 3 {
stream.WriteEmptyObject()
return nil
}
if id == 4 {
stream.WriteObjectStart()
stream.WriteObjectField("structLogs")
stream.WriteEmptyArray()
stream.WriteObjectEnd()
return fmt.Errorf("id 4")
}
return nil
}

Expand Down
Loading