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 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
185 changes: 185 additions & 0 deletions common/nexus/payload_serializer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
// 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"
"maps"
"mime"

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

type payloadSerializer struct{}
Copy link
Member

Choose a reason for hiding this comment

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

What is the purpose of this type? Not that it's wrong, but you check that it implements an interface and everything but nothing uses it and it's not exported

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 still don't know if I want to export it but I'm going to use it in a bit when I implement the Nexus Handler in this code base.

Copy link
Member

@cretz cretz Nov 17, 2023

Choose a reason for hiding this comment

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

Would be willing to wait until then to review since how it is used affects how it is written (or at least set a reminder to go review this already-merged piece if it does get merged before the usage of it is done)


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

// Deserialize implements nexus.Serializer.
func (payloadSerializer) Deserialize(content *nexus.Content, v any) error {
Copy link
Member

Choose a reason for hiding this comment

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

To me this reads clearer as a future maintainer, but don't have to accept it (just typed real quick, so probably some typos):

// Deserialize implements nexus.Serializer.
func (payloadSerializer) Deserialize(content *nexus.Content, v any) error {
	payloadRef, ok := v.(**commonpb.Payload)
	if !ok {
		return fmt.Errorf("cannot deserialize into %v", v)
	}
	payload := &commonpb.Payload{Metadata: map[string][]byte{}, Data: content.Data}
	*payloadRef = payload

	// Absent content type with no data means null, with data is just binary
	if contentType := content.Header["type"]; contentType == "" {
		if len(content.Data) == 0 {
			payload.Metadata["encoding"] = []byte("binary/null")
		} else {
			payload.Metadata["encoding"] = []byte("binary/plain")
		}
		return nil
	}

	// Different content types make different payloads
	if mediaType, params, err := mime.ParseMediaType(contentType); err == nil {
		switch mediaType {
		case "application/x-temporal-payload":
			if err := payload.Unmarshal(content.Data); err != nil {
				return fmt.Errorf("failed to unmarshal payload: %w", err)
			}
			return nil
		case "application/json":
			if protoMessageType := params["protobuf-message-type"]; protoMessageType != "" {
				payload.Metadata["encoding"] = []byte("json/protobuf")
				payload.Metadata["messageType"] = []byte(protoMessageType)
			} else {
				payload.Metadata["encoding"] = []byte("json/plain")
			}
			return nil
		case "application/x-protobuf":
			if protoMessageType := params["protobuf-message-type"]; protoMessageType != "" {
				payload.Metadata["encoding"] = []byte("binary/protobuf")
				payload.Metadata["messageType"] = []byte(protoMessageType)
				return nil
			}
			return fmt.Errorf("protobuf message type required for application/x-protobuf content type")
		case "application/octet-stream":
			payload.Metadata["encoding"] = []byte("binary/plain")
			return nil
		}
	}

	// Unknown or bad content type
	payload.Metadata["encoding"] = "binary/unknown-nexus"
	for k, v := range content.Header {
		// Don't want length or encoding
		if k != "length" && k != "encoding" {
			payload.Metadata[k] = []byte(v)
		}
	}
	return nil
}

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 prefer my stricter non-lossy version.

Copy link
Member Author

Choose a reason for hiding this comment

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

Thanks for the suggestion though.

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

h := maps.Clone(content.Header)
// 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")
Comment on lines +52 to +55
Copy link
Member

Choose a reason for hiding this comment

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

Why remove these here when you can just filter and not set them in the one place you actually copy headers, the setUnknownNexusContent call?

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 is mostly to simplify the logic below and sanitize any irrelevant fields.


if len(h) > 1 {
Copy link
Member

Choose a reason for hiding this comment

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

Why do you care what the rest of the headers are so long as the content type is correct? I think you're overthinking here and can just remove this conditional

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 don't want to lose information in the conversion

setUnknownNexusContent(h, payload.Metadata)
return nil
}

contentType := h.Get("type")
if contentType == "" {
bergundy marked this conversation as resolved.
Show resolved Hide resolved
if len(h) == 0 && len(content.Data) == 0 {
payload.Metadata["encoding"] = []byte("binary/null")
} else {
setUnknownNexusContent(h, payload.Metadata)
Copy link
Member

Choose a reason for hiding this comment

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

I still think this should be 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.

This could also be content header that's not type, and I'd rather not lose this information.

}
return nil
}

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

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

Choose a reason for hiding this comment

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

I think you're being overly strict on the mime type params. If it's our content type, we can ignore params we don't care about

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'd rather not lose this information. Either you're sticking to the standard or you're a custom nexus payload.

payload.Metadata["encoding"] = []byte("json/protobuf")
payload.Metadata["messageType"] = []byte(params["message-type"])
} else {
setUnknownNexusContent(h, payload.Metadata)
}
case "application/x-protobuf":
if len(params) == 1 && params["message-type"] != "" {
payload.Metadata["encoding"] = []byte("binary/protobuf")
payload.Metadata["messageType"] = []byte(params["message-type"])
} else {
setUnknownNexusContent(h, payload.Metadata)
}
case "application/octet-stream":
if len(params) == 0 {
payload.Metadata["encoding"] = []byte("binary/plain")
} else {
setUnknownNexusContent(h, payload.Metadata)
}
default:
setUnknownNexusContent(h, payload.Metadata)
}
return nil
}

func setUnknownNexusContent(nexusHeader nexus.Header, payloadMetadata map[string][]byte) {
for k, v := range nexusHeader {
payloadMetadata[k] = []byte(v)
}
payloadMetadata["encoding"] = []byte("unknown/nexus-content")
}

// Serialize implements nexus.Serializer.
func (payloadSerializer) Serialize(v any) (*nexus.Content, error) {
payload, ok := v.(*commonpb.Payload)
if !ok {
return nil, fmt.Errorf("%w: cannot serialize %v", errSerializer, v)
}

if payload == nil {
return &nexus.Content{}, nil
}

if payload.GetMetadata() == nil {
return xTemporalPayload(payload)
}

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":
if len(payload.Metadata) != 2 || 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 think, like with the code in deserialize, you're being overly strict on the metadata. If it's our encoding, we can choose to ignore other metadata

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 don't think you're right here.
If a user customizes serialization to add more information, we should treat their payload as opaque and non standard and avoid losing metadata during the conversion.

return xTemporalPayload(payload)
}
content.Header["type"] = fmt.Sprintf("application/json; format=protobuf; message-type=%q", messageType)
case "binary/protobuf":
if len(payload.Metadata) != 2 || messageType == "" {
return xTemporalPayload(payload)
}
content.Header["type"] = fmt.Sprintf("application/x-protobuf; message-type=%q", messageType)
case "json/plain":
content.Header["type"] = "application/json"
case "binary/null":
if len(payload.Metadata) != 1 {
return xTemporalPayload(payload)
}
// type is unset
case "binary/plain":
if len(payload.Metadata) != 1 {
return xTemporalPayload(payload)
}
content.Header["type"] = "application/octet-stream"
default:
return xTemporalPayload(payload)
}

return &content, nil
}

func xTemporalPayload(payload *commonpb.Payload) (*nexus.Content, error) {
data, err := payload.Marshal()
if err != nil {
return nil, fmt.Errorf("%w: payload marshal error: %w", errSerializer, err)
}
return &nexus.Content{
Header: nexus.Header{"type": "application/x-temporal-payload"},
Data: data,
}, nil
}

var _ nexus.Serializer = payloadSerializer{}
Loading
Loading