Debian Codegraph @

closure-library/closure/goog/net/streams/pbjsonstreamparser.js

raw
1 // Copyright 2016 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview A stream parser of StreamBody message in Protobuf-JSON format.
17 *
18 * 1. StreamBody proto message is defined as following:
19 *
20 * message StreamBody {
21 * repeated bytes messages = 1;
22 * google.rpc.Status status = 2;
23 * }
24 *
25 * 2. In Protobuf-JSON format, StreamBody is represented as a JSON array:
26 *
27 * - [ [ message1, message2, ..., messageN ] ] (no status)
28 * - [ null, status ] (no message)
29 * - [ [ message1, message2, ..., messageN ] , status ]
30 *
31 * 3. All parsed messages and status will be delivered in a batch (array),
32 * with each constructed as {tag-id: content-string}.
33 */
34
35 goog.module('goog.net.streams.PbJsonStreamParser');
36
37 var JsonStreamParser = goog.require('goog.net.streams.JsonStreamParser');
38 var StreamParser = goog.require('goog.net.streams.StreamParser');
39 var asserts = goog.require('goog.asserts');
40 var utils = goog.require('goog.net.streams.utils');
41
42
43 /**
44 * A stream parser of StreamBody message in Protobuf-JSON format.
45 *
46 * @constructor
47 * @struct
48 * @implements {StreamParser}
49 * @final
50 */
51 var PbJsonStreamParser = function() {
52 /**
53 * Protobuf raw bytes stream parser
54 * @private {?JsonStreamParser}
55 */
56 this.jsonStreamParser_ = null;
57
58 /**
59 * The current error message, if any.
60 * @private {?string}
61 */
62 this.errorMessage_ = null;
63
64 /**
65 * The current position in the streamed data.
66 * @private {number}
67 */
68 this.streamPos_ = 0;
69
70 /**
71 * The current parser state.
72 * @private {!State}
73 */
74 this.state_ = State.INIT;
75
76 /**
77 * The currently buffered result (parsed JSON objects).
78 * @private {!Array<!Object>}
79 */
80 this.result_ = [];
81
82 /**
83 * Whether the status has been parsed.
84 * @private {boolean}
85 */
86 this.statusParsed_ = false;
87 };
88
89
90 /**
91 * The parser state.
92 * @enum {number}
93 */
94 var State = {
95 INIT: 0, // expecting the beginning "["
96 ARRAY_OPEN: 1, // expecting the message array or the msg-status separator
97 MESSAGES: 2, // expecting the message array
98 MESSAGES_DONE: 3, // expecting the msg-status separator or the ending "]"
99 STATUS: 4, // expecting the status
100 ARRAY_END: 5, // expecting NO more non-whitespace input
101 INVALID: 6 // the stream has become invalid
102 };
103
104
105 /** @override */
106 PbJsonStreamParser.prototype.isInputValid = function() {
107 return this.errorMessage_ === null;
108 };
109
110
111 /** @override */
112 PbJsonStreamParser.prototype.getErrorMessage = function() {
113 return this.errorMessage_;
114 };
115
116
117 /** @override */
118 PbJsonStreamParser.prototype.parse = function(input) {
119 asserts.assertString(input);
120
121 var parser = this;
122 var pos = 0;
123 while (pos < input.length) {
124 if (!readMore()) {
125 return null;
126 }
127
128 switch (parser.state_) {
129 case State.INVALID: {
130 reportError('stream already broken');
131 break;
132 }
133 case State.INIT: {
134 if (input[pos] === '[') {
135 parser.state_ = State.ARRAY_OPEN;
136 pos++;
137 parser.streamPos_++;
138 } else {
139 reportError('unexpected input token');
140 }
141 break;
142 }
143 case State.ARRAY_OPEN: {
144 if (input[pos] === '[') {
145 parser.state_ = State.MESSAGES;
146 resetJsonStreamParser();
147 // Feed the '[' again in the next loop.
148 } else if (input[pos] === ',' || input.substr(pos, 5) == 'null,') {
149 parser.state_ = State.MESSAGES_DONE;
150 // Feed the ',' again in the next loop.
151 } else if (input[pos] === ']') {
152 parser.state_ = State.ARRAY_END;
153 pos++;
154 parser.streamPos_++;
155 } else {
156 reportError('unexpected input token');
157 }
158 break;
159 }
160 case State.MESSAGES: {
161 var messages = parser.jsonStreamParser_.parse(input.substring(pos));
162 addResultMessages(messages);
163
164 if (!parser.jsonStreamParser_.done()) {
165 parser.streamPos_ += input.length - pos;
166 pos = input.length; // end the loop
167 } else {
168 parser.state_ = State.MESSAGES_DONE;
169 var extra = parser.jsonStreamParser_.getExtraInput();
170 parser.streamPos_ += input.length - pos - extra.length;
171 input = extra;
172 pos = 0;
173 }
174 break;
175 }
176 case State.MESSAGES_DONE: {
177 if (input[pos] === ',' || input.substr(pos, 5) == 'null,') {
178 parser.state_ = State.STATUS;
179 resetJsonStreamParser();
180 // Feed a dummy "[" to match the ending "]".
181 parser.jsonStreamParser_.parse('[');
182 pos += (input[pos] === ',' ? 1 : 5);
183 parser.streamPos_++;
184 } else if (input[pos] === ']') {
185 parser.state_ = State.ARRAY_END;
186 pos++;
187 parser.streamPos_++;
188 }
189 break;
190 }
191 case State.STATUS: {
192 var status = parser.jsonStreamParser_.parse(input.substring(pos));
193 addResultStatus(status);
194
195 if (!parser.jsonStreamParser_.done()) {
196 parser.streamPos_ += input.length - pos;
197 pos = input.length; // end the loop
198 } else {
199 parser.state_ = State.ARRAY_END;
200 var extra = parser.jsonStreamParser_.getExtraInput();
201 parser.streamPos_ += input.length - pos - extra.length;
202 input = extra;
203 pos = 0;
204 }
205 break;
206 }
207 case State.ARRAY_END: {
208 reportError('extra input after stream end');
209 break;
210 }
211 }
212 }
213
214 if (parser.result_.length > 0) {
215 var results = parser.result_;
216 parser.result_ = [];
217 return results;
218 }
219 return null;
220
221
222 /**
223 * @param {string} errorMessage Additional error message
224 * @throws {!Error} Throws an error indicating where the stream is broken
225 */
226 function reportError(errorMessage) {
227 parser.state_ = State.INVALID;
228 parser.errorMessage_ = 'The stream is broken @' + parser.streamPos_ + '/' +
229 pos + '. Error: ' + errorMessage + '. With input:\n';
230 throw new Error(parser.errorMessage_);
231 }
232
233
234 /**
235 * Advances to the first non-whitespace input character.
236 *
237 * @return {boolean} return false if no more non-whitespace input character
238 */
239 function readMore() {
240 while (pos < input.length) {
241 if (!utils.isJsonWhitespace(input[pos])) {
242 return true;
243 }
244 pos++;
245 parser.streamPos_++;
246 }
247 return false;
248 }
249
250 function resetJsonStreamParser() {
251 parser.jsonStreamParser_ = new JsonStreamParser({
252 'allowCompactJsonArrayFormat': true,
253 'deliverMessageAsRawString': true
254 });
255 }
256
257 /** @param {?Array<string>} messages Parsed messages */
258 function addResultMessages(messages) {
259 if (messages) {
260 for (var i = 0; i < messages.length; i++) {
261 var tagged = {};
262 tagged[1] = messages[i];
263 parser.result_.push(tagged);
264 }
265 }
266 }
267
268 /** @param {?Array<string>} status Parsed status */
269 function addResultStatus(status) {
270 if (status) {
271 if (parser.statusParsed_ || status.length > 1) {
272 reportError('extra status: ' + status);
273 }
274 parser.statusParsed_ = true;
275
276 var tagged = {};
277 tagged[2] = status[0];
278 parser.result_.push(tagged);
279 }
280 }
281 };
282
283
284 exports = PbJsonStreamParser;