Debian Codegraph @

v2/proto_json_stream.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright 2022, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
•30 //go:build !go1.27
31
32 package gax
33
34 import (
35 "encoding/json"
36 "errors"
37 "io"
38
39 "google.golang.org/protobuf/encoding/protojson"
40 "google.golang.org/protobuf/proto"
41 "google.golang.org/protobuf/reflect/protoreflect"
42 )
43
44 var (
45 arrayOpen = json.Delim('[')
46 arrayClose = json.Delim(']')
47 errBadOpening = errors.New("unexpected opening token, expected '['")
48 )
49
50 // ProtoJSONStream represents a wrapper for consuming a stream of protobuf
51 // messages encoded using protobuf-JSON format. More information on this format
52 // can be found at https://developers.google.com/protocol-buffers/docs/proto3#json.
53 // The stream must appear as a comma-delimited, JSON array of obbjects with
54 // opening and closing square braces.
55 //
56 // This is for internal use only.
57 type ProtoJSONStream struct {
58 first, closed bool
59 reader io.ReadCloser
60 stream *json.Decoder
61 typ protoreflect.MessageType
62 }
63
64 // NewProtoJSONStreamReader accepts a stream of bytes via an io.ReadCloser that are
65 // protobuf-JSON encoded protobuf messages of the given type. The ProtoJSONStream
66 // must be closed when done.
67 //
68 // This is for internal use only.
69 func NewProtoJSONStreamReader(rc io.ReadCloser, typ protoreflect.MessageType) *ProtoJSONStream {
70 return &ProtoJSONStream{
71 first: true,
72 reader: rc,
73 stream: json.NewDecoder(rc),
74 typ: typ,
75 }
76 }
77
78 // Recv decodes the next protobuf message in the stream or returns io.EOF if
79 // the stream is done. It is not safe to call Recv on the same stream from
80 // different goroutines, just like it is not safe to do so with a single gRPC
81 // stream. Type-cast the protobuf message returned to the type provided at
82 // ProtoJSONStream creation.
83 // Calls to Recv after calling Close will produce io.EOF.
84 func (s *ProtoJSONStream) Recv() (proto.Message, error) {
85 if s.closed {
86 return nil, io.EOF
87 }
88 if s.first {
89 s.first = false
90
91 // Consume the opening '[' so Decode gets one object at a time.
92 if t, err := s.stream.Token(); err != nil {
93 return nil, err
94 } else if t != arrayOpen {
95 return nil, errBadOpening
96 }
97 }
98
99 // Capture the next block of data for the item (a JSON object) in the stream.
100 var raw json.RawMessage
101 if err := s.stream.Decode(&raw); err != nil {
102 e := err
103 // To avoid checking the first token of each stream, just attempt to
104 // Decode the next blob and if that fails, double check if it is just
105 // the closing token ']'. If it is the closing, return io.EOF. If it
106 // isn't, return the original error.
107 if t, _ := s.stream.Token(); t == arrayClose {
108 e = io.EOF
109 }
110 return nil, e
111 }
112
113 // Initialize a new instance of the protobuf message to unmarshal the
114 // raw data into.
115 m := s.typ.New().Interface()
116 unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
117 err := unm.Unmarshal(raw, m)
118
119 return m, err
120 }
121
122 // Close closes the stream so that resources are cleaned up.
123 func (s *ProtoJSONStream) Close() error {
124 // Dereference the *json.Decoder so that the memory is gc'd.
125 s.stream = nil
126 s.closed = true
127
128 return s.reader.Close()
129 }