Skip to content
Draft
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
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@
# for more info.
*.pb.go linguist-generated
*.mock.go linguist-generated
cmd/proxygenerator/interceptor.go -linguist-generated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

GitHub thinks this is a generated file.

internal/protojson/** linguist-vendored
internal/strcase/** linguist-vendored
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ gomodtidy:
# We need to ensure protos are up to date to test our UTF-8 post-processing
test: copy-helpers
go test -race -tags protolegacy ./...
go -C cmd/proxygenerator test -race ./...

##### Check #####

Expand Down
170 changes: 91 additions & 79 deletions cmd/proxygenerator/interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"go/format"
"go/types"
"os"
"slices"
"strings"
"text/template"

Expand Down Expand Up @@ -677,6 +678,7 @@ type TypeRecord struct {
Slice bool // The API refers to slices of this type
Map bool // The API refers to maps with this type as the value
Matches bool // We found methods on this type that can eventually lead to Payload(s)
children map[string]string
}

// isSlice returns true if a type is slice, false otherwise
Expand Down Expand Up @@ -756,87 +758,80 @@ func pruneRecords(input map[string]*TypeRecord) map[string]*TypeRecord {
return result
}

// isMatchingMessage returns true if the message descriptor is one of the target types
func isMatchingMessage(md protoreflect.MessageDescriptor, targetNames []string) bool {
fullName := string(md.FullName())
for _, targetName := range targetNames {
if fullName == targetName {
return true
// gatherMessagesContainingTargets walks all proto file descriptors in the registry
// and returns messages that transitively contain a target type, excluding the targets themselves.
func gatherMessagesContainingTargets(
protoFiles *protoregistry.Files,
targetMessages []string,
) ([]protoreflect.MessageDescriptor, error) {
referrers := make(map[protoreflect.FullName][]protoreflect.FullName)
indexed := make(map[protoreflect.FullName]bool)
var indexReferences func(protoreflect.MessageDescriptor)
indexReferences = func(message protoreflect.MessageDescriptor) {
name := message.FullName()
if indexed[name] {
return
}
indexed[name] = true

fields := message.Fields()
for i := 0; i < fields.Len(); i++ {
field := fields.Get(i)
// Only care about message-type fields.
if child := field.Message(); field.Kind() == protoreflect.MessageKind && child != nil {
referrers[child.FullName()] = append(referrers[child.FullName()], name)
indexReferences(child)
}
}
}
return false
}

// containsMessage recursively checks whether the given message descriptor (or any of its fields)
// contains (transitively) a target message.
func containsMessage(
md protoreflect.MessageDescriptor,
targetMessages []string,
memo map[protoreflect.FullName]bool,
) bool {
fullName := md.FullName()
// If we've already computed for this message, return the cached result.
if res, ok := memo[fullName]; ok {
return res
}
// Mark this message as not containing a payload to break cycles.
memo[fullName] = false

@stephanos stephanos Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Bug: This temporary false can become a stale result for another type.

If A visits B and B points back to A, B stays cached as having no payload even after A finds one.


// Check every field of this message.
for i := 0; i < md.Fields().Len(); i++ {
field := md.Fields().Get(i)
// Only care about message-type fields.
if field.Kind() == protoreflect.MessageKind && field.Message() != nil {
child := field.Message()
// If the field is directly a payload (or Any) then mark and return true.
if isMatchingMessage(child, targetMessages) {
memo[fullName] = true
return true
}
// Otherwise, recursively check if the field's message type contains a payload.
if containsMessage(child, targetMessages, memo) {
memo[fullName] = true
return true
}
var candidates []protoreflect.MessageDescriptor
var collectMessages func(protoreflect.MessageDescriptors)
collectMessages = func(messages protoreflect.MessageDescriptors) {
for i := 0; i < messages.Len(); i++ {
message := messages.Get(i)
candidates = append(candidates, message)
indexReferences(message)
collectMessages(message.Messages())
}
}
return false
}
protoFiles.RangeFiles(func(file protoreflect.FileDescriptor) bool {
collectMessages(file.Messages())
return true
})

// checkMessage examines the given message descriptor md and, if it (transitively) contains a
// payload, appends its result slice.
func checkMessage(md protoreflect.MessageDescriptor,
targetMessages []string,
memo map[protoreflect.FullName]bool,
result *[]protoreflect.MessageDescriptor,
) {
// Avoid reporting the target types directly
if !isMatchingMessage(md, targetMessages) && containsMessage(md, targetMessages, memo) {
*result = append(*result, md)
// Walk from the targets to every message that references them, marking each message once.
matches := make(map[protoreflect.FullName]bool)
pending := make([]protoreflect.FullName, 0, len(targetMessages))
for _, target := range targetMessages {
name := protoreflect.FullName(target)
if !matches[name] {
matches[name] = true
pending = append(pending, name)
}
}
nested := md.Messages()
for i := 0; i < nested.Len(); i++ {
checkMessage(nested.Get(i), targetMessages, memo, result)
for len(pending) > 0 {
name := pending[len(pending)-1]
pending = pending[:len(pending)-1]
for _, parent := range referrers[name] {
if !matches[parent] {
matches[parent] = true
pending = append(pending, parent)
}
}
}
}

// gatherMessagesContainingTargets walks all proto file descriptors in the registry,
// and returns a slice of full message names that (transitively) contain the target message types.
// The excludedPathPrefixes are used to skip files that match the given prefixes.
func gatherMessagesContainingTargets(
protoFiles *protoregistry.Files,
targetMessages []string,
) ([]protoreflect.MessageDescriptor, error) {
messagesWithPayload := make([]protoreflect.MessageDescriptor, 0)
memo := make(map[protoreflect.FullName]bool)
protoFiles.RangeFiles(func(fd protoreflect.FileDescriptor) bool {
msgs := fd.Messages()
for i := 0; i < msgs.Len(); i++ {
checkMessage(msgs.Get(i), targetMessages, memo, &messagesWithPayload)
// Avoid reporting the target types directly.
for _, target := range targetMessages {
delete(matches, protoreflect.FullName(target))
}
result := make([]protoreflect.MessageDescriptor, 0, len(matches))
for _, message := range candidates {
if matches[message.FullName()] {
result = append(result, message)
}
return true
})
return messagesWithPayload, nil
}
return result, nil
}

// getProtoRegistryFromDescriptor reads a file descriptor set from the given path and returns a proto registry.
Expand Down Expand Up @@ -914,6 +909,22 @@ func gatherMatchesToTypeRecords(
walk(targetTypes, directMatchTypes, types.NewPointer(t), &matchingRecords)
}
}
// Recursive getters may have been visited before their target was marked.
for changed := true; changed; {
changed = false
for _, record := range matchingRecords {
for method, child := range record.children {
if target := matchingRecords[child]; target != nil && target.Matches && !slices.Contains(record.Methods, method) {
record.Matches = true
record.Methods = append(record.Methods, method)
changed = true
}
}
}
}
for _, record := range matchingRecords {
slices.Sort(record.Methods)
}
matchingRecords = pruneRecords(matchingRecords)
return matchingRecords, nil
}
Expand All @@ -922,13 +933,12 @@ func gatherMatchesToTypeRecords(
// desired type(s). The return type for each method on this type is walked recursively to decide
// which methods can lead to the desired type.
func walk(desired []types.Type, directMatchTypes []types.Type, typ types.Type, records *map[string]*TypeRecord) bool {
typeName := typeName(typ)
name := typeName(typ)

// If this type is a slice then walk the underlying type and then make a note we need to encode slices of this type
if isSlice(typ) {
result := walk(desired, directMatchTypes, elemType(typ), records)
if result {
record := (*records)[typeName]
if record := (*records)[name]; record != nil {
record.Slice = true
}
return result
Expand All @@ -937,20 +947,19 @@ func walk(desired []types.Type, directMatchTypes []types.Type, typ types.Type, r
// If this type is a map then walk the underlying type and then make a note we need to encode maps with values of this type
if isMap(typ) {
result := walk(desired, directMatchTypes, elemType(typ), records)
if result {
record := (*records)[typeName]
if record := (*records)[name]; record != nil {
record.Map = true
}
return result
}

// If we've walked this type before, return the previous result
if record, ok := (*records)[typeName]; ok {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

A record is inserted before its getters are fully scanned. A recursive getter can read Matches == false from that unfinished record and get skipped, even if the target type later turns out to contain a payload.

if record, ok := (*records)[name]; ok {
return record.Matches
}

record := TypeRecord{}
(*records)[typeName] = &record
record := TypeRecord{children: map[string]string{}}
(*records)[name] = &record

// Look for all functions with this `typ` type
for _, meth := range typeutil.IntuitiveMethodSet(elemType(typ), nil) {
Expand Down Expand Up @@ -993,6 +1002,9 @@ func walk(desired []types.Type, directMatchTypes []types.Type, typ types.Type, r
record.Matches = true
record.Methods = append(record.Methods, methodName)
}
if !typeMatches(resultType, desired...) {
record.children[methodName] = typeName(resultType)
}
}

// Return whether this Type can (eventually) lead to Payload(s)
Expand Down
101 changes: 101 additions & 0 deletions cmd/proxygenerator/interceptor_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package main

import (
"slices"
"testing"

"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/descriptorpb"
)

// TestGatherMessagesContainingTargetsRecursive checks that the descriptor scan finds B's path to the target Payload message through A.
func TestGatherMessagesContainingTargetsRecursive(t *testing.T) {
field := func(name, typ string, number int32) *descriptorpb.FieldDescriptorProto {
return &descriptorpb.FieldDescriptorProto{
Name: proto.String(name),
Number: proto.Int32(number),
TypeName: proto.String(typ),
Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(),
Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
}
}
file, err := protodesc.NewFile(&descriptorpb.FileDescriptorProto{
Name: proto.String("recursive.proto"), Package: proto.String("recursive"), Syntax: proto.String("proto3"),
MessageType: []*descriptorpb.DescriptorProto{
{
Name: proto.String("A"),
Field: []*descriptorpb.FieldDescriptorProto{
field("b", ".recursive.B", 1),
field("payload", ".recursive.Payload", 2),
},
},
{
Name: proto.String("B"),
Field: []*descriptorpb.FieldDescriptorProto{
field("a", ".recursive.A", 1),
},
},
{
Name: proto.String("NoPayload"),
Field: []*descriptorpb.FieldDescriptorProto{
field("first", ".recursive.Leaf", 1),
field("second", ".recursive.Leaf", 2),
},
},
{Name: proto.String("Leaf")},
{Name: proto.String("Payload")},
},
}, nil)
if err != nil {
t.Fatal(err)
}

var files protoregistry.Files
if err := files.RegisterFile(file); err != nil {
t.Fatal(err)
}
matches, err := gatherMessagesContainingTargets(&files, []string{"recursive.Payload"})
if err != nil {
t.Fatal(err)
}

var names []protoreflect.Name
for _, match := range matches {
names = append(names, match.Name())
}
if want := []protoreflect.Name{"A", "B"}; !slices.Equal(names, want) {
t.Fatalf("messages containing a payload = %v, want %v", names, want)
}
}

// TestGatherMatchesKeepsRecursivePayloadGetter checks that the generator retains a recursive getter that can lead to a payload.
func TestGatherMatchesKeepsRecursivePayloadGetter(t *testing.T) {
payloads, err := lookupTypes("go.temporal.io/api/cmd/proxygenerator/testdata/recursive", []string{"Payload"})
if err != nil {
t.Fatal(err)
}

file, err := protodesc.NewFile(&descriptorpb.FileDescriptorProto{
Name: proto.String("recursive.proto"),
Package: proto.String("temporal.api.cmd.proxygenerator.testdata.recursive"),
MessageType: []*descriptorpb.DescriptorProto{
{Name: proto.String("Node")},
},
}, nil)
if err != nil {
t.Fatal(err)
}

records, err := gatherMatchesToTypeRecords([]protoreflect.MessageDescriptor{file.Messages().ByName("Node")}, payloads, payloads)
if err != nil {
t.Fatal(err)
}

record := records["*recursive.Node"]
if record == nil || !slices.Contains(record.Methods, "GetChild") {
t.Fatal("Node.GetChild should be visited because the child can contain a Payload")
}
}
16 changes: 16 additions & 0 deletions cmd/proxygenerator/testdata/recursive/getters.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package recursive

type Payload struct{}

type Node struct {
Child *Node
Payload *Payload
}

func (n *Node) GetChild() *Node {
return n.Child
}

func (n *Node) GetPayload() *Payload {
return n.Payload
}
Loading