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

Implement Nexus Serializer for Temporal Payloads #5126

Merged
merged 5 commits into from
Nov 17, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
219 changes: 219 additions & 0 deletions common/nexus/payload_serializer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
// The MIT License
//
// Copyright (c) 2023 Temporal Technologies Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package nexus

import (
"errors"
"fmt"
"mime"

"github.com/nexus-rpc/sdk-go/nexus"
commonpb "go.temporal.io/api/common/v1"
)

type nexusPayloadSerializer struct{}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm going to rename this to payloadSerializer and avoid the stuttering.


var errSerializer = errors.New("serializer error")
tdeebswihart marked this conversation as resolved.
Show resolved Hide resolved

// Deserialize implements nexus.Serializer.
func (nexusPayloadSerializer) Deserialize(content *nexus.Content, v any) error {
payloadRef, ok := v.(**commonpb.Payload)
if !ok {
return fmt.Errorf("%w: cannot deserialize into %v", errSerializer, v)
bergundy marked this conversation as resolved.
Show resolved Hide resolved
}

payload := &commonpb.Payload{}
*payloadRef = payload
payload.Metadata = make(map[string][]byte)
payload.Data = content.Data

if !isStandardNexusContent(content) {
for k, v := range content.Header {
payload.Metadata[k] = []byte(v)
}
payload.Metadata["encoding"] = []byte("unknown/nexus-content")
return nil
}

contentType := content.Header.Get("type")
if contentType == "" {
bergundy marked this conversation as resolved.
Show resolved Hide resolved
payload.Metadata["encoding"] = []byte("binary/null")
return nil
}

mediaType, params, err := mime.ParseMediaType(contentType)
if err != nil {
return err
}

switch mediaType {
case "application/x-temporal-payload":
err := payload.Unmarshal(content.Data)
if err != nil {
return err
}
return nil
case "application/json":
if params["format"] == "protobuf" {
payload.Metadata["encoding"] = []byte("json/protobuf")
messageType := params["message-type"]
if messageType != "" {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should allow proto without message type. It's not very useful over normal JSON and message-type-less protos in Temporal are only supported on older SDKs. Arguably you don't need format and message-type as separate params, just a single protobuf-message-type param is good enough to be seen as proto JSON.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm fine considering protos without message-type non-standard.
I'll also consider merging into a single param.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, more and more the single param sounds good.

payload.Metadata["messageType"] = []byte(messageType)
}
} else {
payload.Metadata["encoding"] = []byte("json/plain")
}
case "application/x-protobuf":
payload.Metadata["encoding"] = []byte("binary/protobuf")
messageType := params["message-type"]
if messageType != "" {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, we should not allow message-type-less proto binary

payload.Metadata["messageType"] = []byte(messageType)
}
case "application/octet-stream":
payload.Metadata["encoding"] = []byte("binary/plain")
default:
return fmt.Errorf("%w: standard content detection failed", errSerializer)
}
return nil
}

func isStandardNexusContent(content *nexus.Content) bool {
h := content.Header
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was supposed to clone the map, I missed that.

// We assume that encoding is handled by the transport layer and the content is decoded.
delete(h, "encoding")
// Length can safely be ignored.
delete(h, "length")

if len(h) > 1 {
return false
}
contentType := h.Get("type")
if contentType == "" {
return len(h) == 0 && len(content.Data) == 0
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So it was confusing to follow this logic down to here, but I think an absent content type with data should be a binary/plain.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I considered that but it would make this conversion asymmetric. Because we can't interpret the intent I think it may be better that this becomes encoding: unknown/nexus-content so then if it's turned into a content object again it doesn't get an application/octet-stream content type.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An absent content type + data is always asymmetric because it's more loosely defined inbound but we want to explicitly set content type outbound when data is present. So discussion of absent content-type + data only applies in one direction.

}
mediaType, params, err := mime.ParseMediaType(contentType)
if err != nil {
return false
}

switch mediaType {
case "application/octet-stream",
"application/x-temporal-payload":
return len(params) == 0
case "application/json":
if params["format"] == "protobuf" {
if params["message-type"] != "" {
return len(params) == 2
}
return len(params) == 1
}
return len(params) == 0
case "application/x-protobuf":
if params["message-type"] != "" {
return len(params) == 1
}
return len(params) == 0
tdeebswihart marked this conversation as resolved.
Show resolved Hide resolved
}
return false
}

// Serialize implements nexus.Serializer.
func (nexusPayloadSerializer) Serialize(v any) (*nexus.Content, error) {
tdeebswihart marked this conversation as resolved.
Show resolved Hide resolved
payload, ok := v.(*commonpb.Payload)
if !ok {
return nil, fmt.Errorf("%w: cannot serialize %v", errSerializer, v)
}

if payload == nil {
return &nexus.Content{Header: nexus.Header{}}, nil
bergundy marked this conversation as resolved.
Show resolved Hide resolved
}

if !isStandardPayload(payload) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is confusing too, can you just make this stuff part of the switch below? You can set data in each arm of the switch, there's not that much code reuse here. Just handle each type specifically. I can suggest exact rewrite if it helps.

data, err := payload.Marshal()
if err != nil {
return nil, fmt.Errorf("%w: payload marshal error: %w", errSerializer, err)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You may as well just have errSerializer be a string prefix; it doesn't look like we gain anything by wrapping it into the error tree

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly did this to satisfy our linter.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would avoid a double %w, there's only one true cause. In fact, would avoid errSerializer altogether, it has no value from what I see (but I understand server has a bit of a history with hard to read code by precreating errors often unnecessarily regardless of some opinions about performance or attempting to predict future uses)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, I could make a linter exception here. I was just "following the rules".

}
return &nexus.Content{
Header: nexus.Header{"type": "application/x-temporal-payload"},
Data: data,
}, nil
}

content := nexus.Content{Header: nexus.Header{}, Data: payload.Data}
encoding := string(payload.Metadata["encoding"])
messageType := string(payload.Metadata["messageType"])

switch encoding {
case "unknown/nexus-content":
for k, v := range payload.Metadata {
if k != "encoding" {
content.Header[k] = string(v)
}
}
case "json/protobuf":
content.Header["type"] = fmt.Sprintf("application/json; format=protobuf")
if messageType != "" {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think any SDKs leave this off anymore and haven't for a while, I think we can require usage of a somewhat modern SDK version for use with Nexus protos

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm fine with that.

content.Header["type"] += fmt.Sprintf("; message-type=%q", messageType)
}
case "binary/protobuf":
content.Header["type"] = fmt.Sprintf("application/x-protobuf")
if messageType != "" {
content.Header["type"] += fmt.Sprintf("; message-type=%q", messageType)
}
case "json/plain":
content.Header["type"] = "application/json"
case "binary/null":
// type is unset
case "binary/plain":
content.Header["type"] = "application/octet-stream"
default:
return nil, fmt.Errorf("%w: standard payload detection failed", errSerializer)
tdeebswihart marked this conversation as resolved.
Show resolved Hide resolved
}

return &content, nil
}

var _ nexus.Serializer = nexusPayloadSerializer{}

func isStandardPayload(payload *commonpb.Payload) bool {
if payload.GetMetadata() == nil {
return false
}

encoding := string(payload.Metadata["encoding"])
switch encoding {
case "unknown/nexus-content":
return true
case "json/protobuf",
"binary/protobuf":
if _, ok := payload.Metadata["messageType"]; ok {
return len(payload.Metadata) == 2
}
return len(payload.Metadata) == 1
case "json/plain",
"binary/null",
"binary/plain":
return len(payload.Metadata) == 1
}
return false
}
Loading
Loading