/
proto.go
275 lines (237 loc) · 7.61 KB
/
proto.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// Copyright 2015 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pubsubprotocol
import (
"bytes"
"compress/zlib"
"errors"
"fmt"
"io"
"github.com/golang/protobuf/proto"
"go.chromium.org/luci/common/data/recordio"
"go.chromium.org/luci/logdog/api/logpb"
"go.chromium.org/luci/logdog/common/types"
)
const (
// DefaultCompressThreshold is the byte size threshold for compressing message
// data. Messages whose byte count is less than or equal to this threshold
// will not be compressed.
//
// This is the value used by Akamai for its compression threshold:
// "The reasons 860 bytes is the minimum size for compression is twofold:
// (1) The overhead of compressing an object under 860 bytes outweighs
// performance gain. (2) Objects under 860 bytes can be transmitted via a
// single packet anyway, so there isn't a compelling reason to compress them."
DefaultCompressThreshold = 860
)
// protoBase is the base type of protocol reader/writer objects.
type protoBase struct {
// maxSize is the maximum Butler protocol data size. By default, it is
// types.MaxButlerLogBundleSize. However, it can be overridden for testing
// here.
maxSize int64
}
func (p *protoBase) getMaxSize() int64 {
if p.maxSize == 0 {
return types.MaxButlerLogBundleSize
}
return p.maxSize
}
// Reader is a protocol reader instance.
type Reader struct {
protoBase
// Metadata is the unpacked ButlerMetadata. It is populated when the
// metadata has been read.
Metadata *logpb.ButlerMetadata
// Bundle is the unpacked ButlerLogBundle. It is populated when the
// protocol data has been read and the Metadata indicates a ButlerLogBundle
// type.
Bundle *logpb.ButlerLogBundle
}
// ReadMetadata reads the metadata header frame.
func (r *Reader) readMetadata(fr recordio.Reader) error {
data, err := fr.ReadFrameAll()
if err != nil {
return err
}
md := logpb.ButlerMetadata{}
if err := proto.Unmarshal(data, &md); err != nil {
return fmt.Errorf("butlerproto: failed to unmarshal Metadata frame: %s", err)
}
r.Metadata = &md
return nil
}
func (r *Reader) readData(fr recordio.Reader) ([]byte, error) {
var br io.Reader
size, br, err := fr.ReadFrame()
if err != nil {
return nil, fmt.Errorf("failed to read bundle frame: %s", err)
}
// Read the frame through a zlib reader.
switch r.Metadata.Compression {
case logpb.ButlerMetadata_NONE:
break
case logpb.ButlerMetadata_ZLIB:
br, err = zlib.NewReader(br)
if err != nil {
return nil, fmt.Errorf("failed to initialize zlib reader: %s", err)
}
default:
return nil, fmt.Errorf("unknown compression type: %v", r.Metadata.Compression)
}
// Wrap our reader in a limitErrorReader so we don't pull data beyond our
// soft maximum.
br = &limitErrorReader{
Reader: br,
limit: r.getMaxSize(),
}
buf := bytes.Buffer{}
buf.Grow(int(size))
_, err = buf.ReadFrom(br)
if err != nil {
return nil, fmt.Errorf("butlerproto: failed to buffer bundle frame: %s", err)
}
return buf.Bytes(), nil
}
func (r *Reader) Read(ir io.Reader) error {
fr := recordio.NewReader(ir, r.getMaxSize())
// Ensure that we have our Metadata.
if err := r.readMetadata(fr); err != nil {
return err
}
switch r.Metadata.Type {
case logpb.ButlerMetadata_ButlerLogBundle:
data, err := r.readData(fr)
if err != nil {
return fmt.Errorf("butlerproto: failed to read Bundle data: %s", err)
}
if r.Metadata.ProtoVersion == logpb.Version {
bundle := logpb.ButlerLogBundle{}
if err := proto.Unmarshal(data, &bundle); err != nil {
return fmt.Errorf("butlerproto: failed to unmarshal Bundle frame: %s", err)
}
r.Bundle = &bundle
}
return nil
default:
return fmt.Errorf("butlerproto: unknown data type: %s", r.Metadata.Type)
}
}
// limitErrorReader is similar to io.LimitReader, except that it returns
// a custom error instead of io.EOF.
//
// This is important, as it allows us to distinguish between the end of
// the compressed reader's data and a limit being hit.
type limitErrorReader struct {
io.Reader // underlying reader
limit int64 // max bytes remaining
}
func (r *limitErrorReader) Read(p []byte) (int, error) {
if r.limit <= 0 {
return 0, errors.New("limit exceeded")
}
if int64(len(p)) > r.limit {
p = p[0:r.limit]
}
n, err := r.Reader.Read(p)
r.limit -= int64(n)
return n, err
}
// Writer writes Butler messages that the Reader can read.
type Writer struct {
protoBase
// ProtoVersion is the protocol version string to use. If empty, the current
// ProtoVersion will be used.
ProtoVersion string
// Compress, if true, allows the Writer to choose to compress data when
// applicable.
Compress bool
// CompressThreshold is the minimum size that data must be in order to
CompressThreshold int
compressBuf bytes.Buffer
compressWriter *zlib.Writer
}
func (w *Writer) writeData(fw recordio.Writer, t logpb.ButlerMetadata_ContentType, data []byte) error {
if int64(len(data)) > w.getMaxSize() {
return fmt.Errorf("butlerproto: serialized size exceeds soft cap (%d > %d)", len(data), w.getMaxSize())
}
pv := w.ProtoVersion
if pv == "" {
pv = logpb.Version
}
md := logpb.ButlerMetadata{
Type: t,
ProtoVersion: pv,
}
// If we're configured to compress and the data is below our threshold,
// compress.
if w.Compress && len(data) >= w.CompressThreshold {
w.compressBuf.Reset()
if w.compressWriter == nil {
w.compressWriter = zlib.NewWriter(&w.compressBuf)
} else {
w.compressWriter.Reset(&w.compressBuf)
}
if _, err := w.compressWriter.Write(data); err != nil {
return err
}
if err := w.compressWriter.Close(); err != nil {
return err
}
compressed := true
if compressed {
md.Compression = logpb.ButlerMetadata_ZLIB
}
data = w.compressBuf.Bytes()
}
// Write metadata frame.
mdData, err := proto.Marshal(&md)
if err != nil {
return fmt.Errorf("butlerproto: failed to marshal Metadata: %s", err)
}
_, err = fw.Write(mdData)
if err != nil {
return fmt.Errorf("butlerproto: failed to write Metadata frame: %s", err)
}
if err := fw.Flush(); err != nil {
return fmt.Errorf("butlerproto: failed to flush Metadata frame: %s", err)
}
// Write data frame.
_, err = fw.Write(data)
if err != nil {
return fmt.Errorf("butlerproto: failed to write data frame: %s", err)
}
if err := fw.Flush(); err != nil {
return fmt.Errorf("butlerproto: failed to flush data frame: %s", err)
}
return nil
}
// WriteWith writes a ButlerLogBundle to the supplied Writer.
func (w *Writer) Write(iw io.Writer, b *logpb.ButlerLogBundle) error {
return w.WriteWith(recordio.NewWriter(iw), b)
}
// WriteWith writes a ButlerLogBundle to the supplied recordio.Writer.
func (w *Writer) WriteWith(fw recordio.Writer, b *logpb.ButlerLogBundle) error {
data, err := proto.Marshal(b)
if err != nil {
entries := b.GetEntries()
// TODO(tandrii, hinoka): leave just error after crbug.com/859995 is fixed.
if len(entries) > 100 {
return fmt.Errorf("butlerproto: failed to marshal Bundle of len %d with first 100 entries %s: %s",
len(entries), entries[:100], err)
}
return fmt.Errorf("butlerproto: failed to marshal Bundle %s: %s", entries, err)
}
return w.writeData(fw, logpb.ButlerMetadata_ButlerLogBundle, data)
}