From e72954e1e66b99258a65066a96826cfdaf5b4231 Mon Sep 17 00:00:00 2001 From: Matthieu Vachon Date: Fri, 4 Dec 2026 13:38:01 -0500 Subject: [PATCH 1/3] Add WalkUnknownFields iterator --- CHANGELOG.md | 1 + README.md | 10 +++ unknown.go | 77 +++++++++++++++++++++ unknown_test.go | 178 ++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 266 insertions(+) create mode 100644 unknown.go create mode 100644 unknown_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b4ad61..15436af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ - `WalkMessageDescriptors`: depth-first walk of a message descriptor tree with cycle detection - `WalkMessageFields`: iterator-based depth-first walk of all fields in a message hierarchy, with optional field filter - `WalkMessageInstanceFields`: iterator-based depth-first walk of all fields in a proto message **instance** (not just descriptors), recursing into sub-messages and repeated message elements; skips `google.protobuf.*` well-known types and prevents infinite recursion via DFS type-stack +- `WalkUnknownFields`: iterator over unknown protobuf field numbers in a message instance, recursing into sub-messages, lists and maps - `DynamicAsTimestamppb` / `DynamicAsTimestampTime` / `DynamicAsTimestampParts`: convert dynamic `google.protobuf.Timestamp` messages to Go types - `IsWellKnownTimestampField` / `IsWellKnownGoogleField`: helpers to identify well-known `google.protobuf.*` fields - `EnumValueToString` / `EnumKnownValuesDebugString`: enum value utilities diff --git a/README.md b/README.md index 31483bd..8a80d86 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,16 @@ for field := range protox.WalkMessageFields(root, func(f protoreflect.FieldDescr } ``` +**`WalkUnknownFields`** — iterator over unknown protobuf fields in a message **instance**, recursing into +sub-messages, list elements and map values. Yields `(message, field number)` once per distinct unknown +number per message. Stops early if the consumer breaks. + +```go +for msg, number := range protox.WalkUnknownFields(block.ProtoReflect()) { + fmt.Printf("%s has unknown field %d\n", msg.Descriptor().FullName(), number) +} +``` + ### Dynamic Timestamp helpers Utilities for converting a dynamically-typed `google.protobuf.Timestamp` message (obtained via diff --git a/unknown.go b/unknown.go new file mode 100644 index 0000000..07cd3c6 --- /dev/null +++ b/unknown.go @@ -0,0 +1,77 @@ +package protox + +import ( + "iter" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/reflect/protoreflect" +) + +// WalkUnknownFields walks msg recursively and yields (message, field number) for every +// unknown field found in the tree, including inside populated message fields, list +// elements and map values. +// +// A message holding unknown bytes yields each distinct unknown field number once, in +// order of first appearance, even when that number occurs several times in the bytes. +// Unknown bytes that cannot be parsed stop the scan of that message; numbers parsed +// before the malformed bytes are still yielded. A message's own unknown fields are +// yielded before those of its sub-messages. +// +// A nil or invalid message yields nothing. Iteration stops as soon as the consumer +// stops, including from inside the recursion. +func WalkUnknownFields(msg protoreflect.Message) iter.Seq2[protoreflect.Message, protowire.Number] { + return func(yield func(protoreflect.Message, protowire.Number) bool) { + walkUnknownFields(msg, yield) + } +} + +func walkUnknownFields(msg protoreflect.Message, yield func(protoreflect.Message, protowire.Number) bool) bool { + if msg == nil || !msg.IsValid() { + return true + } + + var seen map[protowire.Number]struct{} + unknown := msg.GetUnknown() + for len(unknown) > 0 { + number, _, n := protowire.ConsumeField(unknown) + if n < 0 { + break + } + unknown = unknown[n:] + + if _, ok := seen[number]; ok { + continue + } + if seen == nil { + seen = map[protowire.Number]struct{}{} + } + seen[number] = struct{}{} + + if !yield(msg, number) { + return false + } + } + + cont := true + msg.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + switch { + case fd.IsList() && fd.Message() != nil: + list := v.List() + for i := range list.Len() { + if cont = walkUnknownFields(list.Get(i).Message(), yield); !cont { + break + } + } + case fd.IsMap() && fd.MapValue().Message() != nil: + v.Map().Range(func(_ protoreflect.MapKey, mv protoreflect.Value) bool { + cont = walkUnknownFields(mv.Message(), yield) + return cont + }) + case fd.Message() != nil && !fd.IsList() && !fd.IsMap(): + cont = walkUnknownFields(v.Message(), yield) + } + return cont + }) + + return cont +} diff --git a/unknown_test.go b/unknown_test.go new file mode 100644 index 0000000..291830a --- /dev/null +++ b/unknown_test.go @@ -0,0 +1,178 @@ +package protox_test + +import ( + "fmt" + "testing" + + "github.com/streamingfast/protox" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/descriptorpb" + "google.golang.org/protobuf/types/dynamicpb" +) + +func TestWalkUnknownFields_none(t *testing.T) { + root, _ := unknownTestMessages(t) + assert.Empty(t, collectUnknown(root)) +} + +func TestWalkUnknownFields_nilAndInvalid(t *testing.T) { + assert.Empty(t, collectUnknown(nil)) + + root, _ := unknownTestMessages(t) + var invalid protoreflect.Message = root.Get(root.Descriptor().Fields().ByName("child")).Message() + require.False(t, invalid.IsValid()) + assert.Empty(t, collectUnknown(invalid)) +} + +func TestWalkUnknownFields_topLevel(t *testing.T) { + root, _ := unknownTestMessages(t) + root.SetUnknown(unknownBytes(100)) + + assert.Equal(t, []string{"test.Root:100"}, collectUnknown(root)) +} + +func TestWalkUnknownFields_severalNumbersAndRepeats(t *testing.T) { + root, _ := unknownTestMessages(t) + root.SetUnknown(unknownBytes(100, 101, 100, 102, 101)) + + assert.Equal(t, []string{"test.Root:100", "test.Root:101", "test.Root:102"}, collectUnknown(root)) +} + +func TestWalkUnknownFields_nested(t *testing.T) { + root, newChild := unknownTestMessages(t) + child := newChild() + child.SetUnknown(unknownBytes(200)) + root.Set(root.Descriptor().Fields().ByName("child"), protoreflect.ValueOfMessage(child)) + + assert.Equal(t, []string{"test.Child:200"}, collectUnknown(root)) +} + +func TestWalkUnknownFields_list(t *testing.T) { + root, newChild := unknownTestMessages(t) + list := root.Mutable(root.Descriptor().Fields().ByName("items")).List() + for _, n := range []protowire.Number{300, 301} { + c := newChild() + c.SetUnknown(unknownBytes(n)) + list.Append(protoreflect.ValueOfMessage(c)) + } + + assert.Equal(t, []string{"test.Child:300", "test.Child:301"}, collectUnknown(root)) +} + +func TestWalkUnknownFields_map(t *testing.T) { + root, newChild := unknownTestMessages(t) + m := root.Mutable(root.Descriptor().Fields().ByName("by_name")).Map() + c := newChild() + c.SetUnknown(unknownBytes(400)) + m.Set(protoreflect.ValueOfString("a").MapKey(), protoreflect.ValueOfMessage(c)) + + assert.Equal(t, []string{"test.Child:400"}, collectUnknown(root)) +} + +func TestWalkUnknownFields_earlyBreak(t *testing.T) { + root, newChild := unknownTestMessages(t) + root.SetUnknown(unknownBytes(100, 101)) + list := root.Mutable(root.Descriptor().Fields().ByName("items")).List() + for _, n := range []protowire.Number{300, 301} { + c := newChild() + c.SetUnknown(unknownBytes(n)) + list.Append(protoreflect.ValueOfMessage(c)) + } + + // Break on the first yielded value. + count := 0 + for range protox.WalkUnknownFields(root) { + count++ + break + } + assert.Equal(t, 1, count) + + // Break while inside the recursion. + var got []string + for msg, n := range protox.WalkUnknownFields(root) { + got = append(got, unknownKey(msg, n)) + if n == 300 { + break + } + } + assert.Equal(t, []string{"test.Root:100", "test.Root:101", "test.Child:300"}, got) +} + +func collectUnknown(msg protoreflect.Message) (out []string) { + for m, n := range protox.WalkUnknownFields(msg) { + out = append(out, unknownKey(m, n)) + } + return out +} + +func unknownKey(m protoreflect.Message, n protowire.Number) string { + return fmt.Sprintf("%s:%d", m.Descriptor().FullName(), n) +} + +func unknownBytes(numbers ...protowire.Number) []byte { + var b []byte + for _, n := range numbers { + b = protowire.AppendTag(b, n, protowire.VarintType) + b = protowire.AppendVarint(b, 1) + } + return b +} + +// unknownTestMessages returns an empty test.Root message and a constructor of test.Child. +// +// message Child { string name = 1; } +// message Root { Child child = 1; repeated Child items = 2; map by_name = 3; } +func unknownTestMessages(t *testing.T) (protoreflect.Message, func() protoreflect.Message) { + t.Helper() + + opt := descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum() + rep := descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum() + msgType := descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum() + strType := descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum() + + files, err := protodesc.NewFiles(&descriptorpb.FileDescriptorSet{ + File: []*descriptorpb.FileDescriptorProto{{ + Name: proto.String("unknown_test.proto"), + Package: proto.String("test"), + Syntax: proto.String("proto3"), + MessageType: []*descriptorpb.DescriptorProto{ + { + Name: proto.String("Child"), + Field: []*descriptorpb.FieldDescriptorProto{{Name: proto.String("name"), JsonName: proto.String("name"), Number: proto.Int32(1), Label: opt, Type: strType}}, + }, + { + Name: proto.String("Root"), + Field: []*descriptorpb.FieldDescriptorProto{ + {Name: proto.String("child"), JsonName: proto.String("child"), Number: proto.Int32(1), Label: opt, Type: msgType, TypeName: proto.String(".test.Child")}, + {Name: proto.String("items"), JsonName: proto.String("items"), Number: proto.Int32(2), Label: rep, Type: msgType, TypeName: proto.String(".test.Child")}, + {Name: proto.String("by_name"), JsonName: proto.String("byName"), Number: proto.Int32(3), Label: rep, Type: msgType, TypeName: proto.String(".test.Root.ByNameEntry")}, + }, + NestedType: []*descriptorpb.DescriptorProto{{ + Name: proto.String("ByNameEntry"), + Options: &descriptorpb.MessageOptions{MapEntry: proto.Bool(true)}, + Field: []*descriptorpb.FieldDescriptorProto{ + {Name: proto.String("key"), JsonName: proto.String("key"), Number: proto.Int32(1), Label: opt, Type: strType}, + {Name: proto.String("value"), JsonName: proto.String("value"), Number: proto.Int32(2), Label: opt, Type: msgType, TypeName: proto.String(".test.Child")}, + }, + }}, + }, + }, + }}, + }) + require.NoError(t, err) + + rootDesc, err := files.FindDescriptorByName("test.Root") + require.NoError(t, err) + childDesc, err := files.FindDescriptorByName("test.Child") + require.NoError(t, err) + + return dynamicpb.NewMessage(rootDesc.(protoreflect.MessageDescriptor)).ProtoReflect(), + func() protoreflect.Message { + return dynamicpb.NewMessage(childDesc.(protoreflect.MessageDescriptor)) + } +} From 84ffd950d704eaf617011cac99101a576fa92935 Mon Sep 17 00:00:00 2001 From: Matthieu Vachon Date: Fri, 4 Dec 2026 14:15:05 -0500 Subject: [PATCH 2/3] Add sfreleaser configuration and release workflows --- .github/workflows/draft-release.yml | 38 ++++++++++++++++++++++ .github/workflows/publish-release.yml | 47 +++++++++++++++++++++++++++ .sfreleaser | 3 ++ 3 files changed, 88 insertions(+) create mode 100644 .github/workflows/draft-release.yml create mode 100644 .github/workflows/publish-release.yml create mode 100644 .sfreleaser diff --git a/.github/workflows/draft-release.yml b/.github/workflows/draft-release.yml new file mode 100644 index 0000000..a4aa278 --- /dev/null +++ b/.github/workflows/draft-release.yml @@ -0,0 +1,38 @@ +name: Draft release + +on: + pull_request: + branches: + - "master" + paths: + - "CHANGELOG.md" + workflow_dispatch: + +permissions: + contents: write + pull-requests: write + +concurrency: + group: draft-release-${{ github.event.pull_request.number || github.ref_name }} + cancel-in-progress: true + +jobs: + draft-release: + if: github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-24.04 + steps: + - name: Checkout repository + uses: actions/checkout@v7 + with: + ref: ${{ github.head_ref || github.ref_name }} + fetch-depth: 0 + + - name: Detect release PR + id: detect + uses: streamingfast/actions/sfreleaser/detect@v1 + + - name: Prepare release + if: steps.detect.outputs.is_release_pr + uses: streamingfast/actions/sfreleaser/prepare@v1 + with: + version: ${{ steps.detect.outputs.version }} diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml new file mode 100644 index 0000000..7af9f3e --- /dev/null +++ b/.github/workflows/publish-release.yml @@ -0,0 +1,47 @@ +name: Publish release + +on: + pull_request: + types: + - closed + branches: + - "master" + paths: + - "CHANGELOG.md" + workflow_dispatch: + inputs: + tag: + description: "Release tag to run the publish steps for again, e.g. v1.2.3" + required: true + +permissions: + actions: write + contents: write + +concurrency: + group: publish-release-${{ github.event.pull_request.number || inputs.tag }} + cancel-in-progress: false + +jobs: + publish: + if: github.event_name == 'workflow_dispatch' || (github.event.pull_request.merged && github.event.pull_request.head.repo.full_name == github.repository) + runs-on: ubuntu-24.04 + steps: + - name: Checkout repository + uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.merge_commit_sha || inputs.tag }} + fetch-depth: 0 + + - name: Detect release PR + id: detect + if: github.event_name == 'pull_request' + uses: streamingfast/actions/sfreleaser/detect@v1 + with: + before: ${{ github.event.pull_request.merge_commit_sha }}^1 + + - name: Publish release + if: steps.detect.outputs.is_release_pr || github.event_name == 'workflow_dispatch' + uses: streamingfast/actions/sfreleaser/publish@v1 + with: + version: ${{ steps.detect.outputs.version || inputs.tag }} diff --git a/.sfreleaser b/.sfreleaser new file mode 100644 index 0000000..07033da --- /dev/null +++ b/.sfreleaser @@ -0,0 +1,3 @@ +global: + language: golang + kind: library From 6dffad676adfa8b0eea50c8f854f9175cab4dc13 Mon Sep 17 00:00:00 2001 From: Matthieu Vachon Date: Fri, 4 Dec 2026 14:15:47 -0500 Subject: [PATCH 3/3] Release v0.1.0 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 15436af..a27ad95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -## Unreleased +## v0.1.0 ### Added