|
| 1 | +/* |
| 2 | +Copyright 2025 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package protobuf |
| 18 | + |
| 19 | +import ( |
| 20 | + "errors" |
| 21 | + "io" |
| 22 | + "math/bits" |
| 23 | + |
| 24 | + "github.com/gogo/protobuf/proto" |
| 25 | + |
| 26 | + "k8s.io/apimachinery/pkg/api/meta" |
| 27 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 28 | + "k8s.io/apimachinery/pkg/conversion" |
| 29 | + "k8s.io/apimachinery/pkg/runtime" |
| 30 | +) |
| 31 | + |
| 32 | +var ( |
| 33 | + errFieldCount = errors.New("expected ListType to have 3 fields") |
| 34 | + errTypeMetaField = errors.New("expected TypeMeta field to have TypeMeta type") |
| 35 | + errTypeMetaProtobufTag = errors.New(`expected TypeMeta protobuf field tag to be ""`) |
| 36 | + errListMetaField = errors.New("expected ListMeta field to have ListMeta type") |
| 37 | + errListMetaProtobufTag = errors.New(`expected ListMeta protobuf field tag to be "bytes,1,opt,name=metadata"`) |
| 38 | + errItemsProtobufTag = errors.New(`expected Items protobuf field tag to be "bytes,2,rep,name=items"`) |
| 39 | + errItemsSizer = errors.New(`expected Items elements to implement proto.Sizer`) |
| 40 | +) |
| 41 | + |
| 42 | +// getStreamingListData implements list extraction logic for protobuf stream serialization. |
| 43 | +// |
| 44 | +// Reason for a custom logic instead of reusing accessors from meta package: |
| 45 | +// * Validate proto tags to prevent incompatibility with proto standard package. |
| 46 | +// * ListMetaAccessor doesn't distinguish empty from nil value. |
| 47 | +// * TypeAccessor reparsing "apiVersion" and serializing it with "{group}/{version}" |
| 48 | +func getStreamingListData(list runtime.Object) (data streamingListData, err error) { |
| 49 | + listValue, err := conversion.EnforcePtr(list) |
| 50 | + if err != nil { |
| 51 | + return data, err |
| 52 | + } |
| 53 | + listType := listValue.Type() |
| 54 | + if listType.NumField() != 3 { |
| 55 | + return data, errFieldCount |
| 56 | + } |
| 57 | + // TypeMeta: validated, but not returned as is not serialized. |
| 58 | + _, ok := listValue.Field(0).Interface().(metav1.TypeMeta) |
| 59 | + if !ok { |
| 60 | + return data, errTypeMetaField |
| 61 | + } |
| 62 | + if listType.Field(0).Tag.Get("protobuf") != "" { |
| 63 | + return data, errTypeMetaProtobufTag |
| 64 | + } |
| 65 | + // ListMeta |
| 66 | + listMeta, ok := listValue.Field(1).Interface().(metav1.ListMeta) |
| 67 | + if !ok { |
| 68 | + return data, errListMetaField |
| 69 | + } |
| 70 | + // if we were ever to relax the protobuf tag check we should update the hardcoded `0xa` below when writing ListMeta. |
| 71 | + if listType.Field(1).Tag.Get("protobuf") != "bytes,1,opt,name=metadata" { |
| 72 | + return data, errListMetaProtobufTag |
| 73 | + } |
| 74 | + data.listMeta = listMeta |
| 75 | + // Items; if we were ever to relax the protobuf tag check we should update the hardcoded `0x12` below when writing Items. |
| 76 | + if listType.Field(2).Tag.Get("protobuf") != "bytes,2,rep,name=items" { |
| 77 | + return data, errItemsProtobufTag |
| 78 | + } |
| 79 | + items, err := meta.ExtractList(list) |
| 80 | + if err != nil { |
| 81 | + return data, err |
| 82 | + } |
| 83 | + data.items = items |
| 84 | + data.totalSize, data.listMetaSize, data.itemsSizes, err = listSize(listMeta, items) |
| 85 | + return data, err |
| 86 | +} |
| 87 | + |
| 88 | +type streamingListData struct { |
| 89 | + // totalSize is the total size of the serialized List object, including their proto headers/size bytes |
| 90 | + totalSize int |
| 91 | + |
| 92 | + // listMetaSize caches results from .Size() call to listMeta, doesn't include header bytes (field identifier, size) |
| 93 | + listMetaSize int |
| 94 | + listMeta metav1.ListMeta |
| 95 | + |
| 96 | + // itemsSizes caches results from .Size() call to items, doesn't include header bytes (field identifier, size) |
| 97 | + itemsSizes []int |
| 98 | + items []runtime.Object |
| 99 | +} |
| 100 | + |
| 101 | +// listSize return size of ListMeta and items to be later used for preallocations. |
| 102 | +// listMetaSize and itemSizes do not include header bytes (field identifier, size). |
| 103 | +func listSize(listMeta metav1.ListMeta, items []runtime.Object) (totalSize, listMetaSize int, itemSizes []int, err error) { |
| 104 | + // ListMeta |
| 105 | + listMetaSize = listMeta.Size() |
| 106 | + totalSize += 1 + sovGenerated(uint64(listMetaSize)) + listMetaSize |
| 107 | + // Items |
| 108 | + itemSizes = make([]int, len(items)) |
| 109 | + for i, item := range items { |
| 110 | + sizer, ok := item.(proto.Sizer) |
| 111 | + if !ok { |
| 112 | + return totalSize, listMetaSize, nil, errItemsSizer |
| 113 | + } |
| 114 | + n := sizer.Size() |
| 115 | + itemSizes[i] = n |
| 116 | + totalSize += 1 + sovGenerated(uint64(n)) + n |
| 117 | + } |
| 118 | + return totalSize, listMetaSize, itemSizes, nil |
| 119 | +} |
| 120 | + |
| 121 | +func streamingEncodeUnknownList(w io.Writer, unk runtime.Unknown, listData streamingListData, memAlloc runtime.MemoryAllocator) error { |
| 122 | + _, err := w.Write(protoEncodingPrefix) |
| 123 | + if err != nil { |
| 124 | + return err |
| 125 | + } |
| 126 | + // encodeList is responsible for encoding the List into the unknown Raw. |
| 127 | + encodeList := func(writer io.Writer) (int, error) { |
| 128 | + return streamingEncodeList(writer, listData, memAlloc) |
| 129 | + } |
| 130 | + _, err = unk.MarshalToWriter(w, listData.totalSize, encodeList) |
| 131 | + return err |
| 132 | +} |
| 133 | + |
| 134 | +func streamingEncodeList(w io.Writer, listData streamingListData, memAlloc runtime.MemoryAllocator) (size int, err error) { |
| 135 | + // ListMeta; 0xa = (1 << 3) | 2; field number: 1, type: 2 (LEN). https://protobuf.dev/programming-guides/encoding/#structure |
| 136 | + n, err := doEncodeWithHeader(&listData.listMeta, w, 0xa, listData.listMetaSize, memAlloc) |
| 137 | + size += n |
| 138 | + if err != nil { |
| 139 | + return size, err |
| 140 | + } |
| 141 | + // Items; 0x12 = (2 << 3) | 2; field number: 2, type: 2 (LEN). https://protobuf.dev/programming-guides/encoding/#structure |
| 142 | + for i, item := range listData.items { |
| 143 | + n, err := doEncodeWithHeader(item, w, 0x12, listData.itemsSizes[i], memAlloc) |
| 144 | + size += n |
| 145 | + if err != nil { |
| 146 | + return size, err |
| 147 | + } |
| 148 | + } |
| 149 | + return size, nil |
| 150 | +} |
| 151 | + |
| 152 | +func writeVarintGenerated(w io.Writer, v int) (int, error) { |
| 153 | + buf := make([]byte, sovGenerated(uint64(v))) |
| 154 | + encodeVarintGenerated(buf, len(buf), uint64(v)) |
| 155 | + return w.Write(buf) |
| 156 | +} |
| 157 | + |
| 158 | +// sovGenerated is copied from `generated.pb.go` returns size of varint. |
| 159 | +func sovGenerated(v uint64) int { |
| 160 | + return (bits.Len64(v|1) + 6) / 7 |
| 161 | +} |
| 162 | + |
| 163 | +// encodeVarintGenerated is copied from `generated.pb.go` encodes varint. |
| 164 | +func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { |
| 165 | + offset -= sovGenerated(v) |
| 166 | + base := offset |
| 167 | + for v >= 1<<7 { |
| 168 | + dAtA[offset] = uint8(v&0x7f | 0x80) |
| 169 | + v >>= 7 |
| 170 | + offset++ |
| 171 | + } |
| 172 | + dAtA[offset] = uint8(v) |
| 173 | + return base |
| 174 | +} |
0 commit comments