-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathresponder.js
More file actions
1273 lines (1096 loc) · 36.9 KB
/
Copy pathresponder.js
File metadata and controls
1273 lines (1096 loc) · 36.9 KB
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2015-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
*/
'use strict';
const concatStream = require('concat-stream');
const jsonParser = require('json-text-sequence').Parser;
const Dicer = require('@fastify/busboy/deps/dicer/lib/Dicer');
const through2 = require('through2');
const mlutil = require('./mlutil.js');
const requester = require('./requester');
const {createGunzip} = require('zlib');
/**
* Handle response from the REST API based on response and operation
* @param {http.IncomingMessage} response - An HTTP response
*
* The following dispatch methods are available:
*
* BodyDispatcher.emptyPromise()
* BodyDispatcher.emptyStream()
* BodyDispatcher.promise()
* BodyDispatcher.chunkedStream()
* BodyDispatcher.objectStream()
* MultipartDispatcher.emptyPromise()
* MultipartDispatcher.emptyStream()
* MultipartDispatcher.promise()
* MultipartDispatcher.chunkedStream()
* MultipartDispatcher.objectStream()
*
* @ignore
*/
function responseDispatcher(response) {
/*jshint validthis:true */
const operation = this;
if (!isResponseStatusOkay.call(operation, response)) {
return;
}
const outputMode = operation.outputMode;
if (outputMode === 'none') {
return;
}
const responseType = response.headers['content-type'];
const responseTypeLen = (!responseType) ? 0 : responseType.length;
let responseBoundary = null;
if (15 <= responseTypeLen && responseType.substr(0, 15) === 'multipart/mixed') {
responseBoundary = responseType.replace(
/^multipart.mixed\s*;\s*boundary\s*=\s*([^\s;]+)([\s;].*)?$/, '$1'
);
if (responseBoundary.length === responseTypeLen) {
operation.errorListener('multipart/mixed response without boundary');
return;
}
if (responseBoundary !== mlutil.multipartBoundary) {
operation.logger.debug(
'expected '+mlutil.multipartBoundary+
' but received '+responseBoundary+' multipart/mixed boundary'
);
}
}
const isMultipart = (responseBoundary != null);
// inputHeader may be boundary (for multipart) or content type (for body)
// Allows dispatch function signatures to remain consistent
const inputHeader = isMultipart ? responseBoundary : responseType;
const responseLength = response.headers['content-length'];
const isEmpty = ((responseLength != null) && responseLength === '0');
const expectedType = operation.responseType;
// point-in-time operations: if timestamp unset, set with header value
if (operation.timestamp !== undefined && operation.timestamp !== null) {
if (operation.timestamp.value === null &&
response.headers['ml-effective-timestamp']) {
operation.timestamp.value = response.headers['ml-effective-timestamp'];
}
}
let dispatcher = null;
if (isMultipart) {
if (expectedType !== 'multipart') {
operation.logger.debug('expected body but received multipart');
}
if (operation.onMultipart){
operation.onMultipart(response.headers);
}
dispatcher = new MultipartDispatcher(operation);
} else if (20 <= responseTypeLen && responseType && responseType.substr(0, 20) === 'application/json-seq') {
dispatcher = new JSONSeqDispatcher(operation);
} else if (8 <= responseTypeLen && responseType && responseType.substr(0, 8) === 'text/csv') {
dispatcher = new CSVDispatcher(operation);
} else {
if (expectedType === 'multipart') {
operation.logger.debug('expected multipart but received body');
}
dispatcher = new BodyDispatcher(operation);
}
response.on('error', operation.errorListener);
if (isEmpty) {
if (expectedType !== 'empty') {
operation.logger.debug('expected body or multipart but received empty response');
}
if (outputMode === 'promise') {
dispatcher.emptyPromise(response);
} else {
dispatcher.emptyStream(response);
}
} else {
if (expectedType === 'empty') {
operation.logger.debug('expected empty response but received body or multipart');
}
switch(outputMode) {
case 'promise':
dispatcher.promise(inputHeader, response);
break;
case 'chunkedStream':
dispatcher.chunkedStream(inputHeader, response);
break;
case 'objectStream':
dispatcher.objectStream(inputHeader, response);
break;
case 'sequenceStream':
dispatcher.sequenceStream(inputHeader, response);
break;
default:
operation.errorListener('unknown output mode '+outputMode);
break;
}
}
}
function CSVDispatcher(operation) {
if (!(this instanceof CSVDispatcher)) {
return new CSVDispatcher(operation);
}
this.operation = operation;
}
CSVDispatcher.prototype.promise = function dispatchCSVPromise(
contentType, response
) {
const operation = this.operation;
operation.logger.debug('csv promise');
const collectObject = function collectPromiseBodyObject(data) {
operation.data = data;
resolvedPromise(operation, operation.resolve);
};
const isString = operation.copyResponseHeaders(response);
if(isResponseGzipped(response.headers)) {
response.pipe(createGunzip()).pipe(concatStream(
{encoding: (isString ? 'string' : 'buffer')},
collectObject
));
} else {
response.pipe(concatStream(
{encoding: (isString ? 'string' : 'buffer')},
collectObject
));
}
};
CSVDispatcher.prototype.chunkedStream = function dispatchCSVChunkedStream(
contentType, response
) {
const operation = this.operation;
operation.logger.debug('csv chunked stream');
// HTTP response gives a chunked stream to begin with
// .stream('chunked') creates through2 stream (writable and readable)
// Simply pipe HTTP response to the through2 stream
if(isResponseGzipped(response.headers)) {
response.pipe(createGunzip()).pipe(operation.outputStream);
} else {
response.pipe(operation.outputStream);
}
};
function JSONSeqDispatcher(operation) {
if (!(this instanceof JSONSeqDispatcher)) {
return new JSONSeqDispatcher(operation);
}
this.operation = operation;
}
JSONSeqDispatcher.prototype.promise = function dispatchJSONSeqPromise(
contentType, response
) {
const operation = this.operation;
const errorListener = operation.errorListener;
let objectQueue = new FifoQueue(2);
let parsedObjects = 0;
operation.logger.debug('json sequence promise');
let dataListener = function JSONSeqDataListener(object) {
parsedObjects++;
operation.logger.debug('json-seq parsing object %d', parsedObjects);
objectQueue.addLast(object);
};
let finishListener = function JSONSeqFinishListener() {
operation.logger.debug('json-seq finished parsing %d objects', parsedObjects);
operation.data = objectQueue.getQueue();
resolvedPromise(operation, operation.resolve);
dataListener = null;
finishListener = null;
parser = null;
objectQueue = null;
};
var parser = new jsonParser()
.on('data', dataListener)
.on('truncated', function(buf) {
throw new Error('json-seq truncated data encountered: ' + buf);
})
.on('invalid', errorListener)
.on('finish', finishListener);
if(isResponseGzipped(response.headers)) {
response.pipe(createGunzip()).pipe(parser);
} else {
response.pipe(parser);
}
};
JSONSeqDispatcher.prototype.sequenceStream = function dispatchJSONSeqSequenceStream(
contentType, response
) {
this.stream('sequence', response);
};
JSONSeqDispatcher.prototype.objectStream = function dispatchJSONSeqObjectStream(
contentType, response
) {
this.stream('object', response);
};
JSONSeqDispatcher.prototype.stream = function dispatchJSONSeqStream(
streamMode, response
) {
const operation = this.operation;
const errorListener = operation.errorListener;
const outputStream = operation.outputStream;
let parsedObjects = 0;
let hasParsed = false;
let hasEnded = false;
operation.logger.debug('json sequence stream ' + streamMode);
let dataListener = function JSONSeqDataListener(object) {
parsedObjects++;
operation.logger.debug('parsing object %d', parsedObjects);
operation.logger.debug(object);
let writeResult = null;
if (object !== null && object !== undefined) {
if (streamMode === 'object') {
writeResult = outputStream.write(object);
} else if (streamMode === 'sequence') {
writeResult = outputStream.write('\x1e' + JSON.stringify(object) + '\n');
} else {
writeResult = outputStream.write(JSON.stringify(object));
}
}
// Manage backpressure
if (writeResult === false) {
// Only pause resp stream if resp hasn't ended
if (!hasEnded) {
response.pause();
}
return;
}
};
let responseFinisher = function JSONSeqFinishListener() {
if (hasParsed && hasEnded) {
operation.logger.debug('finished parsing %d objects', parsedObjects);
dataListener = null;
responseFinisher = null;
parseFinishListener = null;
responseEndListener = null;
drainListener = null;
parser = null;
outputStream.end();
}
};
var parseFinishListener = function objectParseFinishListener() {
hasParsed = true;
responseFinisher();
};
var responseEndListener = function objectResponseEndListener() {
hasEnded = true;
responseFinisher();
};
var drainListener = function objectDrainListener() {
if (!hasEnded) {
response.resume();
}
};
var parser = new jsonParser()
.on('data', dataListener)
.on('truncated', function(buf) {
throw new Error('truncated data encountered: ' + buf);
})
.on('invalid', errorListener)
.on('finish', parseFinishListener);
response.on('end', responseEndListener);
outputStream.on('drain', drainListener);
if(isResponseGzipped(response.headers)) {
response.pipe(createGunzip()).pipe(parser);
} else {
response.pipe(parser);
}
};
function BodyDispatcher(operation) {
if (!(this instanceof BodyDispatcher)) {
return new BodyDispatcher(operation);
}
this.operation = operation;
}
BodyDispatcher.prototype.emptyPromise = function dispatchBodyEmptyPromise(response) {
const operation = this.operation;
operation.logger.debug('empty body promise');
operation.data = operation.emptyHeaderData(response);
resolvedPromise(operation, operation.resolve);
};
BodyDispatcher.prototype.emptyStream = function dispatchBodyEmptyStream(response) {
const operation = this.operation;
const data = operation.emptyHeaderData(response);
operation.logger.debug('empty body stream');
const outputStream = operation.outputStream;
if (data != null) {
if (operation.outputStreamMode === 'chunked') {
outputStream.write(JSON.stringify(data));
} else {
outputStream.write(data);
}
}
outputStream.end();
};
BodyDispatcher.prototype.promise = function dispatchBodyPromise(
contentType, response
) {
const operation = this.operation;
operation.logger.debug('body promise');
const collectObject = function collectPromiseBodyObject(data) {
// turn collected data into something usable
// e.g., if JSON, parse as JS object
operation.data = operation.collectBodyObject(data);
resolvedPromise(operation, operation.resolve);
};
const isString = operation.copyResponseHeaders(response);
if(isResponseGzipped(response.headers)) {
const gunzip = createGunzip();
response.pipe(gunzip).pipe(concatStream(
{encoding: (isString ? 'string' : 'buffer')},
collectObject
));
} else {
// concatStream accumulates response with callback
response.pipe(concatStream(
{encoding: (isString ? 'string' : 'buffer')},
collectObject
));
}
};
BodyDispatcher.prototype.chunkedStream = function dispatchBodyChunkedStream(
contentType, response
) {
const operation = this.operation;
operation.logger.debug('body chunked stream');
// HTTP response gives a chunked stream to begin with
// .stream('chunked') creates through2 stream (writable and readable)
// Simply pipe HTTP response to the through2 stream
if(isResponseGzipped(response.headers)) {
response.pipe(createGunzip()).pipe(operation.outputStream);
} else {
response.pipe(operation.outputStream);
}
};
BodyDispatcher.prototype.objectStream = function dispatchBodyObjectStream(
contentType, response
) {
const operation = this.operation;
operation.logger.debug('body object stream');
// outputStream is a through2 stream in object mode
const outputStream = operation.outputStream;
const collectObject = function collectStreamBodyObject(data) {
// similar to promise body case, but write to through2
const writableObject = operation.collectBodyObject(data);
if (writableObject != null) {
outputStream.write(writableObject);
}
outputStream.end();
};
const isString = operation.copyResponseHeaders(response);
if(isResponseGzipped(response.headers)) {
response.pipe(createGunzip()).pipe(concatStream(
{encoding: (isString ? 'string' : 'buffer')},
collectObject
));
} else {
response.pipe(concatStream(
{encoding: (isString ? 'string' : 'buffer')},
collectObject
));
}
};
// Multipart cases similar to the above, but with multiple objects
// Promise case: Accumulate an array of objects
// Chunked case: Send chunks (but filter out multipart bits -- e.g., headers)
// Object stream case: Write multiple objects instead of single object
function MultipartDispatcher(operation) {
if (!(this instanceof MultipartDispatcher)) {
return new MultipartDispatcher(operation);
}
this.operation = operation;
}
MultipartDispatcher.prototype.emptyPromise = function dispatchMultipartEmptyPromise(response) {
const operation = this.operation;
const data = operation.emptyHeaderData(response);
operation.logger.debug('empty multipart promise');
operation.data = (data == null) ? [] : [data];
resolvedPromise(operation, operation.resolve);
};
MultipartDispatcher.prototype.emptyStream = function dispatchMultipartEmptyStream(response) {
const operation = this.operation;
const data = operation.emptyHeaderData(response);
operation.logger.debug('empty multipart stream');
const outputStream = operation.outputStream;
if (data != null) {
if (operation.outputStreamMode === 'chunked') {
outputStream.write(JSON.stringify(data));
} else {
outputStream.write(data);
}
}
outputStream.end();
};
/* Note: the following events can occur in any order:
* 'end' on the readable stream for the last part
* 'finish' on the Dicer parser
* 'end' on the reponse
*/
MultipartDispatcher.prototype.promise = function dispatchMultipartPromise(
boundary, response
) {
const operation = this.operation;
operation.logger.debug('multipart promise');
const errorListenerCheck = (operation.options.headers.Accept === 'application/json' && (operation.name.includes('rows') || operation.name.includes('query') || operation.name.includes('/v1/rows')));
if(errorListenerCheck) {
if(response.headers['content-encoding']!=='gzip'){
response.setEncoding('utf8');
}
const multipartResponse = (isResponseGzipped(response.headers))?response.pipe(createGunzip()):response;
let chunks = '';
multipartResponse.on('data', function(data) {
chunks += data;
});
multipartResponse.on('end', function() {
response.pipe(concatStream(
{encoding: 'json'},
() => {
const data = JSON.parse(chunks);
operation.data = data;
resolvedPromise(operation, operation.resolve);
}
));
});
return;
}
const errorListener = operation.errorListener;
let rawHeaderQueue = new FifoQueue(2);
let objectQueue = new FifoQueue(2);
let partReaderQueue = new FifoQueue(3);
let parsingParts = 0;
let parsedParts = 0;
let hasParsed = false;
let hasEnded = false;
let responseFinisher = function promiseResponseFinisher() {
// If there is metadata left in the buffer, add it to queue
if (operation.nextMetadataBuffer !== null) {
const metadataHeaders = operation.nextMetadataBuffer[0];
mlutil.copyProperties(operation.nextMetadataBuffer[1], metadataHeaders);
objectQueue.addLast(metadataHeaders);
}
operation.logger.debug('ending multipart promise');
operation.data = objectQueue.getQueue();
resolvedPromise(operation, operation.resolve);
partFinisher = null;
partHeadersListener = null;
partListener = null;
parseFinishListener = null;
responseEndListener = null;
parser = null;
rawHeaderQueue = null;
objectQueue = null;
partReaderQueue = null;
responseFinisher = null;
};
var partFinisher = function promisePartFinisher(data) {
parsedParts++;
operation.logger.debug('parsed part %d', parsedParts);
partReaderQueue.removeFirst();
const madeObject = operation.makeObject(
(data.length === 0) ? null : data, rawHeaderQueue
);
if (madeObject !== null && madeObject !== undefined) {
objectQueue.addLast(madeObject);
}
if (partReaderQueue.hasItem()) {
const partConcatenator = concatStream(partFinisher);
partConcatenator.on('error', errorListener);
const partReadStream = partReaderQueue.getFirst();
partReadStream.pipe(partConcatenator);
} else if (hasParsed) {
responseFinisher();
}
};
var partHeadersListener = function promisePartHeadersListener(headers) {
operation.logger.debug('queued header %d %j', parsingParts, headers);
rawHeaderQueue.addLast(headers);
};
var partListener = function promisePartListener(partReadStream) {
parsingParts++;
operation.logger.debug('parsing part %d', parsingParts);
partReadStream.on('header', partHeadersListener);
partReadStream.on('error', errorListener);
partReaderQueue.addLast(partReadStream);
if (partReaderQueue.isLast()) {
const partConcatenator = concatStream(partFinisher);
partConcatenator.on('error', errorListener);
partReadStream.pipe(partConcatenator);
}
};
var parseFinishListener = function promiseParseFinishListener() {
operation.logger.debug('parse finished at part %d of %d', parsedParts, parsingParts);
hasParsed = true;
if (!partReaderQueue.hasItem()) {
responseFinisher();
}
};
var responseEndListener = function promiseResponseEndListener() {
hasEnded = true;
};
var parser = new Dicer({boundary: boundary});
parser.on('part', partListener);
parser.on('error', errorListener);
parser.on('finish', parseFinishListener);
response.on('end', responseEndListener);
if(isResponseGzipped(response.headers)) {
response.pipe(createGunzip()).pipe(parser);
} else {
response.pipe(parser);
}
};
MultipartDispatcher.prototype.chunkedStream = function dispatchMultipartChunkedStream(
boundary, response
) {
const operation = this.operation;
operation.logger.debug('multipart chunked stream');
const errorListener = operation.errorListener;
let outputStream = operation.outputStream;
const partReaderQueue = new FifoQueue(3);
let hasParsed = false;
let hasEnded = false;
let responseFinisher = function chunkedResponseFinisher() {
outputStream.end();
outputStream = null;
partEndListener = null;
partListener = null;
parser = null;
parseFinishListener = null;
responseEndListener = null;
responseFinisher = null;
};
var partEndListener = function chunkedPartEndListener() {
partReaderQueue.removeFirst();
if (partReaderQueue.hasItem()) {
const partReadStream = partReaderQueue.getFirst();
partReadStream.pipe(outputStream, {end: false});
} else if (hasParsed) {
responseFinisher();
}
};
var partListener = function chunkedPartListener(partReadStream) {
partReadStream.on('error', errorListener);
partReadStream.on('end', partEndListener);
partReaderQueue.addLast(partReadStream);
if (partReaderQueue.isLast()) {
partReadStream.pipe(outputStream, {end: false});
}
};
var parseFinishListener = function chunkedParseFinishListener() {
operation.logger.debug('parse finished');
hasParsed = true;
if (!partReaderQueue.hasItem()) {
responseFinisher();
}
};
var responseEndListener = function chunkedResponseEndListener() {
hasEnded = true;
};
var parser = new Dicer({boundary: boundary});
parser.on('part', partListener);
parser.on('error', errorListener);
parser.on('finish', parseFinishListener);
response.on('end', responseEndListener);
if(isResponseGzipped(response.headers)) {
response.pipe(createGunzip()).pipe(parser);
} else {
response.pipe(parser);
}
};
MultipartDispatcher.prototype.objectStream = function dispatchMultipartObjectStream(
boundary, response
) {
const operation = this.operation;
operation.logger.debug('multipart object stream');
const errorListener = operation.errorListener;
let rawHeaderQueue = new FifoQueue(5);
const partReaderQueue = new FifoQueue(3);
// For referenced attachments case
let partBuffer = null;
let parsingParts = 0;
let parsedParts = 0;
let hasParsed = false;
let hasEnded = false;
let isConcatenating = false;
const responseFinisher = function objectResponseFinisher() {
if (!partReaderQueue.hasItem() && hasParsed && hasEnded) {
// Handle multipart with reference attachments (rows)
if (operation.complexValues === 'reference') {
// If there is a part left in the buffer, write it
if (partBuffer !== null) {
operation.outputStream.write(partBuffer);
partBuffer = null;
}
}
// All other cases
else {
// If there is metadata left in the buffer, write it
if (operation.nextMetadataBuffer !== null) {
const metadataHeaders = operation.nextMetadataBuffer[0];
mlutil.copyProperties(operation.nextMetadataBuffer[1], metadataHeaders);
operation.outputStream.write(metadataHeaders);
operation.nextMetadataBuffer = null;
}
}
rawHeaderQueue = null;
parser = null;
partHeadersListener = null;
partListener = null;
parseFinishListener = null;
responseEndListener = null;
operation.outputStream.end();
}
};
const partFinisher = function objectPartFinisher(data) {
parsedParts++;
operation.logger.debug('parsed part %d', parsedParts);
const madeObject = operation.makeObject(
(data.length === 0) ? null : data, rawHeaderQueue
);
// Handle multipart with reference attachments (rows)
let writeResult = null;
if (operation.complexValues === 'reference') {
if (madeObject !== null && madeObject !== undefined) {
// Columns object
if (madeObject.kind === 'columns') {
writeResult = operation.outputStream.write(madeObject);
}
// Row object
else if (madeObject.kind === 'row') {
// First
if (partBuffer === null) {
partBuffer = madeObject;
}
// Subsequent
else {
writeResult = operation.outputStream.write(partBuffer);
partBuffer = madeObject;
}
}
// Attachment object
else {
// Remove '[n]' to get column name
const columnName = madeObject.contentId
.slice(0, madeObject.contentId.lastIndexOf('['));
// Put attachment into currently cached part
partBuffer.content[columnName] = {
contentType: madeObject.contentType,
format: madeObject.format,
content: madeObject.content
};
}
}
}
// All other cases
else {
if (madeObject !== null && madeObject !== undefined) {
writeResult = operation.outputStream.write(madeObject);
}
}
// Manage backpressure
if (writeResult === false) {
// Only pause resp stream if not all parsed and resp hasn't ended
if (hasParsed && !partReaderQueue.hasItem()) {
responseFinisher();
} else if (!hasEnded) {
response.pause();
}
return;
}
partReaderQueue.removeFirst();
isConcatenating = false;
// If item avail, concat-stream it with callback to finisher
if (partReaderQueue.hasItem()) {
isConcatenating = true;
const partRead = concatStream(partFinisher);
partRead.on('error', errorListener);
const partReadStream = partReaderQueue.getFirst();
partReadStream.pipe(partRead);
} else if (hasParsed) {
responseFinisher();
}
};
var partHeadersListener = function objectPartHeadersListener(headers) {
operation.logger.debug('queued header');
rawHeaderQueue.addLast(headers);
};
var partListener = function objectPartListener(partReadStream) {
parsingParts++;
operation.logger.debug('parsing part %d', parsingParts);
partReadStream.on('header', partHeadersListener);
partReadStream.on('error', errorListener);
partReaderQueue.addLast(partReadStream);
if (partReaderQueue.isLast()) {
isConcatenating = true;
const partRead = concatStream(partFinisher);
partRead.on('error', errorListener);
partReadStream.pipe(partRead);
}
};
var parseFinishListener = function objectParseFinishListener() {
hasParsed = true;
responseFinisher();
};
var responseEndListener = function objectResponseEndListener() {
hasEnded = true;
responseFinisher();
};
const drainListener = function objectDrainListener() {
if (!hasEnded) {
response.resume();
// Don't read if concat in progress to avoid double processing
if (partReaderQueue.hasItem() && !isConcatenating) {
isConcatenating = true;
const partRead = concatStream(partFinisher);
partRead.on('error', errorListener);
const partReadStream = partReaderQueue.getFirst();
partReadStream.pipe(partRead);
}
}
};
var parser = new Dicer({boundary: boundary});
parser.on('part', partListener);
parser.on('error', errorListener);
parser.on('finish', parseFinishListener);
response.on('end', responseEndListener);
operation.outputStream.on('drain', drainListener);
if(isResponseGzipped(response.headers)) {
response.pipe(createGunzip()).pipe(parser);
} else {
response.pipe(parser);
}
};
/* Note: Dicer appears to read ahead.
+ each type of event (such as header or end) fires in part order; however
+ for typical MarkLogic documents, part streams become available in batches
+ the header event fires when each part stream becomes available
+ if parts are piped as soon as available, the end event for one pipe
can fire after the next pipe starts reading
+ thus, if parts are piped as soon as available, different types of events
can interleave, as in:
part reader 1
header event 1
part reader 2
header event 2
part data 1
part data 2
part end 1
part end 2
finish
*/
function FifoQueue(min) {
if (!(this instanceof FifoQueue)) {
return new FifoQueue(min);
}
this.queue = (min > 0) ? new Array(min) : [];
this.first = -1;
this.last = -1;
this.total = 0;
}
FifoQueue.prototype.addLast = function fifoAddLast(item) {
this.last++;
this.total++;
if (this.first === -1) {
this.first = this.last;
}
if (this.last < this.queue.length) {
this.queue[this.last] = item;
} else {
this.queue.push(item);
}
};
FifoQueue.prototype.hasItem = function fifoHasItem() {
return (this.first >= 0);
};
FifoQueue.prototype.isLast = function fifoIsLast() {
return (this.first >= 0 && this.first === this.last);
};
FifoQueue.prototype.getFirst = function fifoGetFirst() {
return (this.first >= 0) ? this.queue[this.first] : undefined;
};
FifoQueue.prototype.removeFirst = function fifoRemoveFirst() {
if (this.first >= 0) {
this.queue[this.first] = undefined;
if (this.first === this.last) {
this.first = -1;
this.last = -1;
} else {
this.first++;
}
}
};
FifoQueue.prototype.pollFirst = function fifoPollFirst() {
const item = this.getFirst();
if (item !== undefined) {
this.removeFirst();
}
return item;
};
FifoQueue.prototype.getQueue = function fifoGetQueue() {
return (this.first === 0 && this.last === this.queue.length) ?
this.queue : this.queue.slice(this.first, this.last + 1);
};
/*
FifoQueue.prototype.getLast = function fifoGetLast() {
return (this.first >= 0) ? this.queue[this.last] : undefined;
};
FifoQueue.prototype.getTotal = function fifoGetTotal() {
return this.total;
};
FifoQueue.prototype.length = function fifoLength() {
return (this.first >= 0) ? (this.last - this.first) + 1 : 0;
};
FifoQueue.prototype.at = function fifoAt(i) {
return this.queue[this.first + i];
};
FifoQueue.prototype.replaceLast = function fifoReplaceLast(item) {
if (this.first >= 0) {
this.queue[this.last] = item;
}
};
FifoQueue.prototype.compact = function fifoCompact() {
if (this.first > 0) {
var last = (this.last - this.first);
var next = 0;
var i = 0;
for (; i <= last; i++) {
next = this.first + i;
this.queue[i] = this.queue[next];
this.queue[next] = null;
}
this.first = 0;
this.last = last;
}
};
*/
function isResponseStatusOkay(response) {
/*jshint validthis:true */
const operation = this;