Skip to content
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
38 changes: 38 additions & 0 deletions .github/workflows/draft-release.yml
Original file line number Diff line number Diff line change
@@ -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 }}
47 changes: 47 additions & 0 deletions .github/workflows/publish-release.yml
Original file line number Diff line number Diff line change
@@ -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 }}
3 changes: 3 additions & 0 deletions .sfreleaser
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
global:
language: golang
kind: library
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
## Unreleased
## v0.1.0

### Added

Expand All @@ -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
Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
77 changes: 77 additions & 0 deletions unknown.go
Original file line number Diff line number Diff line change
@@ -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
}
178 changes: 178 additions & 0 deletions unknown_test.go
Original file line number Diff line number Diff line change
@@ -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<string, Child> 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))
}
}