@azure/storage-common 12.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +27 -0
  2. package/dist/browser/BufferScheduler-browser.d.mts.map +1 -0
  3. package/dist/browser/BufferScheduler-browser.mjs.map +1 -0
  4. package/dist/browser/BufferScheduler.d.ts +3 -0
  5. package/dist/browser/BufferScheduler.js +8 -0
  6. package/dist/browser/BuffersStream.d.ts +41 -0
  7. package/dist/browser/BuffersStream.d.ts.map +1 -0
  8. package/dist/browser/BuffersStream.js +83 -0
  9. package/dist/browser/BuffersStream.js.map +1 -0
  10. package/dist/browser/PooledBuffer.d.ts +63 -0
  11. package/dist/browser/PooledBuffer.d.ts.map +1 -0
  12. package/dist/browser/PooledBuffer.js +87 -0
  13. package/dist/browser/PooledBuffer.js.map +1 -0
  14. package/dist/browser/cache.d.ts +3 -0
  15. package/dist/browser/cache.d.ts.map +1 -0
  16. package/dist/browser/cache.js +11 -0
  17. package/dist/browser/cache.js.map +1 -0
  18. package/dist/browser/index.d.ts +3 -0
  19. package/dist/browser/index.d.ts.map +1 -0
  20. package/dist/browser/index.js +5 -0
  21. package/dist/browser/index.js.map +1 -0
  22. package/dist/browser/package.json +3 -0
  23. package/dist/commonjs/BufferScheduler.d.ts +157 -0
  24. package/dist/commonjs/BufferScheduler.d.ts.map +1 -0
  25. package/dist/commonjs/BufferScheduler.js +256 -0
  26. package/dist/commonjs/BufferScheduler.js.map +1 -0
  27. package/dist/commonjs/BuffersStream.d.ts +41 -0
  28. package/dist/commonjs/BuffersStream.d.ts.map +1 -0
  29. package/dist/commonjs/BuffersStream.js +87 -0
  30. package/dist/commonjs/BuffersStream.js.map +1 -0
  31. package/dist/commonjs/PooledBuffer.d.ts +63 -0
  32. package/dist/commonjs/PooledBuffer.d.ts.map +1 -0
  33. package/dist/commonjs/PooledBuffer.js +92 -0
  34. package/dist/commonjs/PooledBuffer.js.map +1 -0
  35. package/dist/commonjs/cache.d.ts +3 -0
  36. package/dist/commonjs/cache.d.ts.map +1 -0
  37. package/dist/commonjs/cache.js +14 -0
  38. package/dist/commonjs/cache.js.map +1 -0
  39. package/dist/commonjs/index.d.ts +3 -0
  40. package/dist/commonjs/index.d.ts.map +1 -0
  41. package/dist/commonjs/index.js +10 -0
  42. package/dist/commonjs/index.js.map +1 -0
  43. package/dist/commonjs/package.json +3 -0
  44. package/dist/commonjs/tsdoc-metadata.json +11 -0
  45. package/dist/esm/BufferScheduler.d.ts +157 -0
  46. package/dist/esm/BufferScheduler.d.ts.map +1 -0
  47. package/dist/esm/BufferScheduler.js +252 -0
  48. package/dist/esm/BufferScheduler.js.map +1 -0
  49. package/dist/esm/BuffersStream.d.ts +41 -0
  50. package/dist/esm/BuffersStream.d.ts.map +1 -0
  51. package/dist/esm/BuffersStream.js +83 -0
  52. package/dist/esm/BuffersStream.js.map +1 -0
  53. package/dist/esm/PooledBuffer.d.ts +63 -0
  54. package/dist/esm/PooledBuffer.d.ts.map +1 -0
  55. package/dist/esm/PooledBuffer.js +87 -0
  56. package/dist/esm/PooledBuffer.js.map +1 -0
  57. package/dist/esm/cache.d.ts +3 -0
  58. package/dist/esm/cache.d.ts.map +1 -0
  59. package/dist/esm/cache.js +11 -0
  60. package/dist/esm/cache.js.map +1 -0
  61. package/dist/esm/index.d.ts +3 -0
  62. package/dist/esm/index.d.ts.map +1 -0
  63. package/dist/esm/index.js +5 -0
  64. package/dist/esm/index.js.map +1 -0
  65. package/dist/esm/package.json +3 -0
  66. package/dist/react-native/BufferScheduler.d.ts +157 -0
  67. package/dist/react-native/BufferScheduler.d.ts.map +1 -0
  68. package/dist/react-native/BufferScheduler.js +252 -0
  69. package/dist/react-native/BufferScheduler.js.map +1 -0
  70. package/dist/react-native/BuffersStream.d.ts +41 -0
  71. package/dist/react-native/BuffersStream.d.ts.map +1 -0
  72. package/dist/react-native/BuffersStream.js +83 -0
  73. package/dist/react-native/BuffersStream.js.map +1 -0
  74. package/dist/react-native/PooledBuffer.d.ts +63 -0
  75. package/dist/react-native/PooledBuffer.d.ts.map +1 -0
  76. package/dist/react-native/PooledBuffer.js +87 -0
  77. package/dist/react-native/PooledBuffer.js.map +1 -0
  78. package/dist/react-native/cache.d.ts +3 -0
  79. package/dist/react-native/cache.d.ts.map +1 -0
  80. package/dist/react-native/cache.js +11 -0
  81. package/dist/react-native/cache.js.map +1 -0
  82. package/dist/react-native/index.d.ts +3 -0
  83. package/dist/react-native/index.d.ts.map +1 -0
  84. package/dist/react-native/index.js +5 -0
  85. package/dist/react-native/index.js.map +1 -0
  86. package/dist/react-native/package.json +3 -0
  87. package/package.json +104 -0
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT License.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.getCachedDefaultHttpClient = void 0;
6
+ const tslib_1 = require("tslib");
7
+ tslib_1.__exportStar(require("./BufferScheduler.js"), exports);
8
+ var cache_js_1 = require("./cache.js");
9
+ Object.defineProperty(exports, "getCachedDefaultHttpClient", { enumerable: true, get: function () { return cache_js_1.getCachedDefaultHttpClient; } });
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;;AAElC,+DAAqC;AACrC,uCAAwD;AAA/C,sHAAA,0BAA0B,OAAA","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport * from \"./BufferScheduler.js\";\nexport { getCachedDefaultHttpClient } from \"./cache.js\";\n"]}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,11 @@
1
+ // This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2
+ // It should be published with your NPM package. It should not be tracked by Git.
3
+ {
4
+ "tsdocVersion": "0.12",
5
+ "toolPackages": [
6
+ {
7
+ "packageName": "@microsoft/api-extractor",
8
+ "packageVersion": "7.52.8"
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * OutgoingHandler is an async function triggered by BufferScheduler.
3
+ */
4
+ export declare type OutgoingHandler = (body: () => NodeJS.ReadableStream, length: number, offset?: number) => Promise<any>;
5
+ /**
6
+ * This class accepts a Node.js Readable stream as input, and keeps reading data
7
+ * from the stream into the internal buffer structure, until it reaches maxBuffers.
8
+ * Every available buffer will try to trigger outgoingHandler.
9
+ *
10
+ * The internal buffer structure includes an incoming buffer array, and a outgoing
11
+ * buffer array. The incoming buffer array includes the "empty" buffers can be filled
12
+ * with new incoming data. The outgoing array includes the filled buffers to be
13
+ * handled by outgoingHandler. Every above buffer size is defined by parameter bufferSize.
14
+ *
15
+ * NUM_OF_ALL_BUFFERS = BUFFERS_IN_INCOMING + BUFFERS_IN_OUTGOING + BUFFERS_UNDER_HANDLING
16
+ *
17
+ * NUM_OF_ALL_BUFFERS lesser than or equal to maxBuffers
18
+ *
19
+ * PERFORMANCE IMPROVEMENT TIPS:
20
+ * 1. Input stream highWaterMark is better to set a same value with bufferSize
21
+ * parameter, which will avoid Buffer.concat() operations.
22
+ * 2. concurrency should set a smaller value than maxBuffers, which is helpful to
23
+ * reduce the possibility when a outgoing handler waits for the stream data.
24
+ * in this situation, outgoing handlers are blocked.
25
+ * Outgoing queue shouldn't be empty.
26
+ */
27
+ export declare class BufferScheduler {
28
+ /**
29
+ * Size of buffers in incoming and outgoing queues. This class will try to align
30
+ * data read from Readable stream into buffer chunks with bufferSize defined.
31
+ */
32
+ private readonly bufferSize;
33
+ /**
34
+ * How many buffers can be created or maintained.
35
+ */
36
+ private readonly maxBuffers;
37
+ /**
38
+ * A Node.js Readable stream.
39
+ */
40
+ private readonly readable;
41
+ /**
42
+ * OutgoingHandler is an async function triggered by BufferScheduler when there
43
+ * are available buffers in outgoing array.
44
+ */
45
+ private readonly outgoingHandler;
46
+ /**
47
+ * An internal event emitter.
48
+ */
49
+ private readonly emitter;
50
+ /**
51
+ * Concurrency of executing outgoingHandlers. (0 lesser than concurrency lesser than or equal to maxBuffers)
52
+ */
53
+ private readonly concurrency;
54
+ /**
55
+ * An internal offset marker to track data offset in bytes of next outgoingHandler.
56
+ */
57
+ private offset;
58
+ /**
59
+ * An internal marker to track whether stream is end.
60
+ */
61
+ private isStreamEnd;
62
+ /**
63
+ * An internal marker to track whether stream or outgoingHandler returns error.
64
+ */
65
+ private isError;
66
+ /**
67
+ * How many handlers are executing.
68
+ */
69
+ private executingOutgoingHandlers;
70
+ /**
71
+ * Encoding of the input Readable stream which has string data type instead of Buffer.
72
+ */
73
+ private encoding?;
74
+ /**
75
+ * How many buffers have been allocated.
76
+ */
77
+ private numBuffers;
78
+ /**
79
+ * Because this class doesn't know how much data every time stream pops, which
80
+ * is defined by highWaterMarker of the stream. So BufferScheduler will cache
81
+ * data received from the stream, when data in unresolvedDataArray exceeds the
82
+ * blockSize defined, it will try to concat a blockSize of buffer, fill into available
83
+ * buffers from incoming and push to outgoing array.
84
+ */
85
+ private unresolvedDataArray;
86
+ /**
87
+ * How much data consisted in unresolvedDataArray.
88
+ */
89
+ private unresolvedLength;
90
+ /**
91
+ * The array includes all the available buffers can be used to fill data from stream.
92
+ */
93
+ private incoming;
94
+ /**
95
+ * The array (queue) includes all the buffers filled from stream data.
96
+ */
97
+ private outgoing;
98
+ /**
99
+ * Creates an instance of BufferScheduler.
100
+ *
101
+ * @param readable - A Node.js Readable stream
102
+ * @param bufferSize - Buffer size of every maintained buffer
103
+ * @param maxBuffers - How many buffers can be allocated
104
+ * @param outgoingHandler - An async function scheduled to be
105
+ * triggered when a buffer fully filled
106
+ * with stream data
107
+ * @param concurrency - Concurrency of executing outgoingHandlers (&gt;0)
108
+ * @param encoding - [Optional] Encoding of Readable stream when it's a string stream
109
+ */
110
+ constructor(readable: NodeJS.ReadableStream, bufferSize: number, maxBuffers: number, outgoingHandler: OutgoingHandler, concurrency: number, encoding?: BufferEncoding);
111
+ /**
112
+ * Start the scheduler, will return error when stream of any of the outgoingHandlers
113
+ * returns error.
114
+ *
115
+ */
116
+ do(): Promise<void>;
117
+ /**
118
+ * Insert a new data into unresolved array.
119
+ *
120
+ * @param data -
121
+ */
122
+ private appendUnresolvedData;
123
+ /**
124
+ * Try to shift a buffer with size in blockSize. The buffer returned may be less
125
+ * than blockSize when data in unresolvedDataArray is less than bufferSize.
126
+ *
127
+ */
128
+ private shiftBufferFromUnresolvedDataArray;
129
+ /**
130
+ * Resolve data in unresolvedDataArray. For every buffer with size in blockSize
131
+ * shifted, it will try to get (or allocate a buffer) from incoming, and fill it,
132
+ * then push it into outgoing to be handled by outgoing handler.
133
+ *
134
+ * Return false when available buffers in incoming are not enough, else true.
135
+ *
136
+ * @returns Return false when buffers in incoming are not enough, else true.
137
+ */
138
+ private resolveData;
139
+ /**
140
+ * Try to trigger a outgoing handler for every buffer in outgoing. Stop when
141
+ * concurrency reaches.
142
+ */
143
+ private triggerOutgoingHandlers;
144
+ /**
145
+ * Trigger a outgoing handler for a buffer shifted from outgoing.
146
+ *
147
+ * @param buffer -
148
+ */
149
+ private triggerOutgoingHandler;
150
+ /**
151
+ * Return buffer used by outgoing handler into incoming.
152
+ *
153
+ * @param buffer -
154
+ */
155
+ private reuseBuffer;
156
+ }
157
+ //# sourceMappingURL=BufferScheduler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BufferScheduler.d.ts","sourceRoot":"","sources":["../../src/BufferScheduler.ts"],"names":[],"mappings":"AAMA;;GAEG;AACH,MAAM,CAAC,OAAO,MAAM,eAAe,GAAG,CACpC,IAAI,EAAE,MAAM,MAAM,CAAC,cAAc,EACjC,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,MAAM,KACZ,OAAO,CAAC,GAAG,CAAC,CAAC;AAElB;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,eAAe;IAC1B;;;OAGG;IACH,OAAO,C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;IACH,OAAO,CAAC,WAAW;CAMpB"}
@@ -0,0 +1,252 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import { EventEmitter } from "events";
4
+ import { PooledBuffer } from "./PooledBuffer.js";
5
+ /**
6
+ * This class accepts a Node.js Readable stream as input, and keeps reading data
7
+ * from the stream into the internal buffer structure, until it reaches maxBuffers.
8
+ * Every available buffer will try to trigger outgoingHandler.
9
+ *
10
+ * The internal buffer structure includes an incoming buffer array, and a outgoing
11
+ * buffer array. The incoming buffer array includes the "empty" buffers can be filled
12
+ * with new incoming data. The outgoing array includes the filled buffers to be
13
+ * handled by outgoingHandler. Every above buffer size is defined by parameter bufferSize.
14
+ *
15
+ * NUM_OF_ALL_BUFFERS = BUFFERS_IN_INCOMING + BUFFERS_IN_OUTGOING + BUFFERS_UNDER_HANDLING
16
+ *
17
+ * NUM_OF_ALL_BUFFERS lesser than or equal to maxBuffers
18
+ *
19
+ * PERFORMANCE IMPROVEMENT TIPS:
20
+ * 1. Input stream highWaterMark is better to set a same value with bufferSize
21
+ * parameter, which will avoid Buffer.concat() operations.
22
+ * 2. concurrency should set a smaller value than maxBuffers, which is helpful to
23
+ * reduce the possibility when a outgoing handler waits for the stream data.
24
+ * in this situation, outgoing handlers are blocked.
25
+ * Outgoing queue shouldn't be empty.
26
+ */
27
+ export class BufferScheduler {
28
+ /**
29
+ * Creates an instance of BufferScheduler.
30
+ *
31
+ * @param readable - A Node.js Readable stream
32
+ * @param bufferSize - Buffer size of every maintained buffer
33
+ * @param maxBuffers - How many buffers can be allocated
34
+ * @param outgoingHandler - An async function scheduled to be
35
+ * triggered when a buffer fully filled
36
+ * with stream data
37
+ * @param concurrency - Concurrency of executing outgoingHandlers (&gt;0)
38
+ * @param encoding - [Optional] Encoding of Readable stream when it's a string stream
39
+ */
40
+ constructor(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) {
41
+ /**
42
+ * An internal event emitter.
43
+ */
44
+ this.emitter = new EventEmitter();
45
+ /**
46
+ * An internal offset marker to track data offset in bytes of next outgoingHandler.
47
+ */
48
+ this.offset = 0;
49
+ /**
50
+ * An internal marker to track whether stream is end.
51
+ */
52
+ this.isStreamEnd = false;
53
+ /**
54
+ * An internal marker to track whether stream or outgoingHandler returns error.
55
+ */
56
+ this.isError = false;
57
+ /**
58
+ * How many handlers are executing.
59
+ */
60
+ this.executingOutgoingHandlers = 0;
61
+ /**
62
+ * How many buffers have been allocated.
63
+ */
64
+ this.numBuffers = 0;
65
+ /**
66
+ * Because this class doesn't know how much data every time stream pops, which
67
+ * is defined by highWaterMarker of the stream. So BufferScheduler will cache
68
+ * data received from the stream, when data in unresolvedDataArray exceeds the
69
+ * blockSize defined, it will try to concat a blockSize of buffer, fill into available
70
+ * buffers from incoming and push to outgoing array.
71
+ */
72
+ this.unresolvedDataArray = [];
73
+ /**
74
+ * How much data consisted in unresolvedDataArray.
75
+ */
76
+ this.unresolvedLength = 0;
77
+ /**
78
+ * The array includes all the available buffers can be used to fill data from stream.
79
+ */
80
+ this.incoming = [];
81
+ /**
82
+ * The array (queue) includes all the buffers filled from stream data.
83
+ */
84
+ this.outgoing = [];
85
+ if (bufferSize <= 0) {
86
+ throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`);
87
+ }
88
+ if (maxBuffers <= 0) {
89
+ throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`);
90
+ }
91
+ if (concurrency <= 0) {
92
+ throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`);
93
+ }
94
+ this.bufferSize = bufferSize;
95
+ this.maxBuffers = maxBuffers;
96
+ this.readable = readable;
97
+ this.outgoingHandler = outgoingHandler;
98
+ this.concurrency = concurrency;
99
+ this.encoding = encoding;
100
+ }
101
+ /**
102
+ * Start the scheduler, will return error when stream of any of the outgoingHandlers
103
+ * returns error.
104
+ *
105
+ */
106
+ async do() {
107
+ return new Promise((resolve, reject) => {
108
+ this.readable.on("data", (data) => {
109
+ data = typeof data === "string" ? Buffer.from(data, this.encoding) : data;
110
+ this.appendUnresolvedData(data);
111
+ if (!this.resolveData()) {
112
+ this.readable.pause();
113
+ }
114
+ });
115
+ this.readable.on("error", (err) => {
116
+ this.emitter.emit("error", err);
117
+ });
118
+ this.readable.on("end", () => {
119
+ this.isStreamEnd = true;
120
+ this.emitter.emit("checkEnd");
121
+ });
122
+ this.emitter.on("error", (err) => {
123
+ this.isError = true;
124
+ this.readable.pause();
125
+ reject(err);
126
+ });
127
+ this.emitter.on("checkEnd", () => {
128
+ if (this.outgoing.length > 0) {
129
+ this.triggerOutgoingHandlers();
130
+ return;
131
+ }
132
+ if (this.isStreamEnd && this.executingOutgoingHandlers === 0) {
133
+ if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) {
134
+ const buffer = this.shiftBufferFromUnresolvedDataArray();
135
+ this.outgoingHandler(() => buffer.getReadableStream(), buffer.size, this.offset)
136
+ .then(resolve)
137
+ .catch(reject);
138
+ }
139
+ else if (this.unresolvedLength >= this.bufferSize) {
140
+ return;
141
+ }
142
+ else {
143
+ resolve();
144
+ }
145
+ }
146
+ });
147
+ });
148
+ }
149
+ /**
150
+ * Insert a new data into unresolved array.
151
+ *
152
+ * @param data -
153
+ */
154
+ appendUnresolvedData(data) {
155
+ this.unresolvedDataArray.push(data);
156
+ this.unresolvedLength += data.length;
157
+ }
158
+ /**
159
+ * Try to shift a buffer with size in blockSize. The buffer returned may be less
160
+ * than blockSize when data in unresolvedDataArray is less than bufferSize.
161
+ *
162
+ */
163
+ shiftBufferFromUnresolvedDataArray(buffer) {
164
+ if (!buffer) {
165
+ buffer = new PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength);
166
+ }
167
+ else {
168
+ buffer.fill(this.unresolvedDataArray, this.unresolvedLength);
169
+ }
170
+ this.unresolvedLength -= buffer.size;
171
+ return buffer;
172
+ }
173
+ /**
174
+ * Resolve data in unresolvedDataArray. For every buffer with size in blockSize
175
+ * shifted, it will try to get (or allocate a buffer) from incoming, and fill it,
176
+ * then push it into outgoing to be handled by outgoing handler.
177
+ *
178
+ * Return false when available buffers in incoming are not enough, else true.
179
+ *
180
+ * @returns Return false when buffers in incoming are not enough, else true.
181
+ */
182
+ resolveData() {
183
+ while (this.unresolvedLength >= this.bufferSize) {
184
+ let buffer;
185
+ if (this.incoming.length > 0) {
186
+ buffer = this.incoming.shift();
187
+ this.shiftBufferFromUnresolvedDataArray(buffer);
188
+ }
189
+ else {
190
+ if (this.numBuffers < this.maxBuffers) {
191
+ buffer = this.shiftBufferFromUnresolvedDataArray();
192
+ this.numBuffers++;
193
+ }
194
+ else {
195
+ // No available buffer, wait for buffer returned
196
+ return false;
197
+ }
198
+ }
199
+ this.outgoing.push(buffer);
200
+ this.triggerOutgoingHandlers();
201
+ }
202
+ return true;
203
+ }
204
+ /**
205
+ * Try to trigger a outgoing handler for every buffer in outgoing. Stop when
206
+ * concurrency reaches.
207
+ */
208
+ async triggerOutgoingHandlers() {
209
+ let buffer;
210
+ do {
211
+ if (this.executingOutgoingHandlers >= this.concurrency) {
212
+ return;
213
+ }
214
+ buffer = this.outgoing.shift();
215
+ if (buffer) {
216
+ this.triggerOutgoingHandler(buffer);
217
+ }
218
+ } while (buffer);
219
+ }
220
+ /**
221
+ * Trigger a outgoing handler for a buffer shifted from outgoing.
222
+ *
223
+ * @param buffer -
224
+ */
225
+ async triggerOutgoingHandler(buffer) {
226
+ const bufferLength = buffer.size;
227
+ this.executingOutgoingHandlers++;
228
+ this.offset += bufferLength;
229
+ try {
230
+ await this.outgoingHandler(() => buffer.getReadableStream(), bufferLength, this.offset - bufferLength);
231
+ }
232
+ catch (err) {
233
+ this.emitter.emit("error", err);
234
+ return;
235
+ }
236
+ this.executingOutgoingHandlers--;
237
+ this.reuseBuffer(buffer);
238
+ this.emitter.emit("checkEnd");
239
+ }
240
+ /**
241
+ * Return buffer used by outgoing handler into incoming.
242
+ *
243
+ * @param buffer -
244
+ */
245
+ reuseBuffer(buffer) {
246
+ this.incoming.push(buffer);
247
+ if (!this.isError && this.resolveData() && !this.isStreamEnd) {
248
+ this.readable.resume();
249
+ }
250
+ }
251
+ }
252
+ //# sourceMappingURL=BufferScheduler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BufferScheduler.js","sourceRoot":"","sources":["../../src/BufferScheduler.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAWjD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,OAAO,eAAe;IAuF1B;;;;;;;;;;;OAWG;IACH,YACE,QAA+B,EAC/B,UAAkB,EAClB,UAAkB,EAClB,eAAgC,EAChC,WAAmB,EACnB,QAAyB;QAlF3B;;WAEG;QACc,YAAO,GAAiB,IAAI,YAAY,EAAE,CAAC;QAO5D;;WAEG;QACK,WAAM,GAAW,CAAC,CAAC;QAE3B;;WAEG;QACK,gBAAW,GAAY,KAAK,CAAC;QAErC;;WAEG;QACK,YAAO,GAAY,KAAK,CAAC;QAEjC;;WAEG;QACK,8BAAyB,GAAW,CAAC,CAAC;QAO9C;;WAEG;QACK,eAAU,GAAW,CAAC,CAAC;QAE/B;;;;;;WAMG;QACK,wBAAmB,GAAa,EAAE,CAAC;QAE3C;;WAEG;QACK,qBAAgB,GAAW,CAAC,CAAC;QAErC;;WAEG;QACK,aAAQ,GAAmB,EAAE,CAAC;QAEtC;;WAEG;QACK,aAAQ,GAAmB,EAAE,CAAC;QAsBpC,IAAI,UAAU,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,UAAU,CAAC,gDAAgD,UAAU,EAAE,CAAC,CAAC;QACrF,CAAC;QAED,IAAI,UAAU,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,UAAU,CAAC,gDAAgD,UAAU,EAAE,CAAC,CAAC;QACrF,CAAC;QAED,IAAI,WAAW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I,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QACzB,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { EventEmitter } from \"events\";\nimport { PooledBuffer } from \"./PooledBuffer.js\";\n\n/**\n * OutgoingHandler is an async function triggered by BufferScheduler.\n */\nexport declare type OutgoingHandler = (\n body: () => NodeJS.ReadableStream,\n length: number,\n offset?: number,\n) => Promise<any>;\n\n/**\n * This class accepts a Node.js Readable stream as input, and keeps reading data\n * from the stream into the internal buffer structure, until it reaches maxBuffers.\n * Every available buffer will try to trigger outgoingHandler.\n *\n * The internal buffer structure includes an incoming buffer array, and a outgoing\n * buffer array. The incoming buffer array includes the \"empty\" buffers can be filled\n * with new incoming data. The outgoing array includes the filled buffers to be\n * handled by outgoingHandler. Every above buffer size is defined by parameter bufferSize.\n *\n * NUM_OF_ALL_BUFFERS = BUFFERS_IN_INCOMING + BUFFERS_IN_OUTGOING + BUFFERS_UNDER_HANDLING\n *\n * NUM_OF_ALL_BUFFERS lesser than or equal to maxBuffers\n *\n * PERFORMANCE IMPROVEMENT TIPS:\n * 1. Input stream highWaterMark is better to set a same value with bufferSize\n * parameter, which will avoid Buffer.concat() operations.\n * 2. concurrency should set a smaller value than maxBuffers, which is helpful to\n * reduce the possibility when a outgoing handler waits for the stream data.\n * in this situation, outgoing handlers are blocked.\n * Outgoing queue shouldn't be empty.\n */\nexport class BufferScheduler {\n /**\n * Size of buffers in incoming and outgoing queues. This class will try to align\n * data read from Readable stream into buffer chunks with bufferSize defined.\n */\n private readonly bufferSize: number;\n\n /**\n * How many buffers can be created or maintained.\n */\n private readonly maxBuffers: number;\n\n /**\n * A Node.js Readable stream.\n */\n private readonly readable: NodeJS.ReadableStream;\n\n /**\n * OutgoingHandler is an async function triggered by BufferScheduler when there\n * are available buffers in outgoing array.\n */\n private readonly outgoingHandler: OutgoingHandler;\n\n /**\n * An internal event emitter.\n */\n private readonly emitter: EventEmitter = new EventEmitter();\n\n /**\n * Concurrency of executing outgoingHandlers. (0 lesser than concurrency lesser than or equal to maxBuffers)\n */\n private readonly concurrency: number;\n\n /**\n * An internal offset marker to track data offset in bytes of next outgoingHandler.\n */\n private offset: number = 0;\n\n /**\n * An internal marker to track whether stream is end.\n */\n private isStreamEnd: boolean = false;\n\n /**\n * An internal marker to track whether stream or outgoingHandler returns error.\n */\n private isError: boolean = false;\n\n /**\n * How many handlers are executing.\n */\n private executingOutgoingHandlers: number = 0;\n\n /**\n * Encoding of the input Readable stream which has string data type instead of Buffer.\n */\n private encoding?: BufferEncoding;\n\n /**\n * How many buffers have been allocated.\n */\n private numBuffers: number = 0;\n\n /**\n * Because this class doesn't know how much data every time stream pops, which\n * is defined by highWaterMarker of the stream. So BufferScheduler will cache\n * data received from the stream, when data in unresolvedDataArray exceeds the\n * blockSize defined, it will try to concat a blockSize of buffer, fill into available\n * buffers from incoming and push to outgoing array.\n */\n private unresolvedDataArray: Buffer[] = [];\n\n /**\n * How much data consisted in unresolvedDataArray.\n */\n private unresolvedLength: number = 0;\n\n /**\n * The array includes all the available buffers can be used to fill data from stream.\n */\n private incoming: PooledBuffer[] = [];\n\n /**\n * The array (queue) includes all the buffers filled from stream data.\n */\n private outgoing: PooledBuffer[] = [];\n\n /**\n * Creates an instance of BufferScheduler.\n *\n * @param readable - A Node.js Readable stream\n * @param bufferSize - Buffer size of every maintained buffer\n * @param maxBuffers - How many buffers can be allocated\n * @param outgoingHandler - An async function scheduled to be\n * triggered when a buffer fully filled\n * with stream data\n * @param concurrency - Concurrency of executing outgoingHandlers (&gt;0)\n * @param encoding - [Optional] Encoding of Readable stream when it's a string stream\n */\n constructor(\n readable: NodeJS.ReadableStream,\n bufferSize: number,\n maxBuffers: number,\n outgoingHandler: OutgoingHandler,\n concurrency: number,\n encoding?: BufferEncoding,\n ) {\n if (bufferSize <= 0) {\n throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`);\n }\n\n if (maxBuffers <= 0) {\n throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`);\n }\n\n if (concurrency <= 0) {\n throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`);\n }\n\n this.bufferSize = bufferSize;\n this.maxBuffers = maxBuffers;\n this.readable = readable;\n this.outgoingHandler = outgoingHandler;\n this.concurrency = concurrency;\n this.encoding = encoding;\n }\n\n /**\n * Start the scheduler, will return error when stream of any of the outgoingHandlers\n * returns error.\n *\n */\n public async do(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.readable.on(\"data\", (data) => {\n data = typeof data === \"string\" ? Buffer.from(data, this.encoding) : data;\n this.appendUnresolvedData(data);\n\n if (!this.resolveData()) {\n this.readable.pause();\n }\n });\n\n this.readable.on(\"error\", (err) => {\n this.emitter.emit(\"error\", err);\n });\n\n this.readable.on(\"end\", () => {\n this.isStreamEnd = true;\n this.emitter.emit(\"checkEnd\");\n });\n\n this.emitter.on(\"error\", (err) => {\n this.isError = true;\n this.readable.pause();\n reject(err);\n });\n\n this.emitter.on(\"checkEnd\", () => {\n if (this.outgoing.length > 0) {\n this.triggerOutgoingHandlers();\n return;\n }\n\n if (this.isStreamEnd && this.executingOutgoingHandlers === 0) {\n if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) {\n const buffer = this.shiftBufferFromUnresolvedDataArray();\n this.outgoingHandler(() => buffer.getReadableStream(), buffer.size, this.offset)\n .then(resolve)\n .catch(reject);\n } else if (this.unresolvedLength >= this.bufferSize) {\n return;\n } else {\n resolve();\n }\n }\n });\n });\n }\n\n /**\n * Insert a new data into unresolved array.\n *\n * @param data -\n */\n private appendUnresolvedData(data: Buffer): void {\n this.unresolvedDataArray.push(data);\n this.unresolvedLength += data.length;\n }\n\n /**\n * Try to shift a buffer with size in blockSize. The buffer returned may be less\n * than blockSize when data in unresolvedDataArray is less than bufferSize.\n *\n */\n private shiftBufferFromUnresolvedDataArray(buffer?: PooledBuffer): PooledBuffer {\n if (!buffer) {\n buffer = new PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength);\n } else {\n buffer.fill(this.unresolvedDataArray, this.unresolvedLength);\n }\n\n this.unresolvedLength -= buffer.size;\n return buffer;\n }\n\n /**\n * Resolve data in unresolvedDataArray. For every buffer with size in blockSize\n * shifted, it will try to get (or allocate a buffer) from incoming, and fill it,\n * then push it into outgoing to be handled by outgoing handler.\n *\n * Return false when available buffers in incoming are not enough, else true.\n *\n * @returns Return false when buffers in incoming are not enough, else true.\n */\n private resolveData(): boolean {\n while (this.unresolvedLength >= this.bufferSize) {\n let buffer: PooledBuffer;\n\n if (this.incoming.length > 0) {\n buffer = this.incoming.shift()!;\n this.shiftBufferFromUnresolvedDataArray(buffer);\n } else {\n if (this.numBuffers < this.maxBuffers) {\n buffer = this.shiftBufferFromUnresolvedDataArray();\n this.numBuffers++;\n } else {\n // No available buffer, wait for buffer returned\n return false;\n }\n }\n\n this.outgoing.push(buffer);\n this.triggerOutgoingHandlers();\n }\n return true;\n }\n\n /**\n * Try to trigger a outgoing handler for every buffer in outgoing. Stop when\n * concurrency reaches.\n */\n private async triggerOutgoingHandlers(): Promise<void> {\n let buffer: PooledBuffer | undefined;\n do {\n if (this.executingOutgoingHandlers >= this.concurrency) {\n return;\n }\n\n buffer = this.outgoing.shift();\n if (buffer) {\n this.triggerOutgoingHandler(buffer);\n }\n } while (buffer);\n }\n\n /**\n * Trigger a outgoing handler for a buffer shifted from outgoing.\n *\n * @param buffer -\n */\n private async triggerOutgoingHandler(buffer: PooledBuffer): Promise<any> {\n const bufferLength = buffer.size;\n\n this.executingOutgoingHandlers++;\n this.offset += bufferLength;\n\n try {\n await this.outgoingHandler(\n () => buffer.getReadableStream(),\n bufferLength,\n this.offset - bufferLength,\n );\n } catch (err: any) {\n this.emitter.emit(\"error\", err);\n return;\n }\n\n this.executingOutgoingHandlers--;\n this.reuseBuffer(buffer);\n this.emitter.emit(\"checkEnd\");\n }\n\n /**\n * Return buffer used by outgoing handler into incoming.\n *\n * @param buffer -\n */\n private reuseBuffer(buffer: PooledBuffer): void {\n this.incoming.push(buffer);\n if (!this.isError && this.resolveData() && !this.isStreamEnd) {\n this.readable.resume();\n }\n }\n}\n"]}
@@ -0,0 +1,41 @@
1
+ import type { ReadableOptions } from "node:stream";
2
+ import { Readable } from "node:stream";
3
+ /**
4
+ * Options to configure the BuffersStream.
5
+ */
6
+ export interface BuffersStreamOptions extends ReadableOptions {
7
+ }
8
+ /**
9
+ * This class generates a readable stream from the data in an array of buffers.
10
+ */
11
+ export declare class BuffersStream extends Readable {
12
+ private buffers;
13
+ private byteLength;
14
+ /**
15
+ * The offset of data to be read in the current buffer.
16
+ */
17
+ private byteOffsetInCurrentBuffer;
18
+ /**
19
+ * The index of buffer to be read in the array of buffers.
20
+ */
21
+ private bufferIndex;
22
+ /**
23
+ * The total length of data already read.
24
+ */
25
+ private pushedBytesLength;
26
+ /**
27
+ * Creates an instance of BuffersStream that will emit the data
28
+ * contained in the array of buffers.
29
+ *
30
+ * @param buffers - Array of buffers containing the data
31
+ * @param byteLength - The total length of data contained in the buffers
32
+ */
33
+ constructor(buffers: Buffer[], byteLength: number, options?: BuffersStreamOptions);
34
+ /**
35
+ * Internal _read() that will be called when the stream wants to pull more data in.
36
+ *
37
+ * @param size - Optional. The size of data to be read
38
+ */
39
+ _read(size?: number): void;
40
+ }
41
+ //# sourceMappingURL=BuffersStream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BuffersStream.d.ts","sourceRoot":"","sources":["../../src/BuffersStream.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC;;GAEG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAAG;AAEhE;;GAEG;AACH,qBAAa,aAAc,SAAQ,QAAQ;IAwBvC,OAAO,CAAC,OAAO;IACf,OAAO,CAAC,UAAU;IAxBpB;;OAEG;IACH,OAAO,CAAC,yBAAyB,CAAS;IAE1C;;OAEG;IACH,OAAO,CAAC,WAAW,CAAS;IAE5B;;OAEG;IACH,OAAO,CAAC,iBAAiB,CAAS;IAElC;;;;;;OAMG;gBAEO,OAAO,EAAE,MAAM,EAAE,EACjB,UAAU,EAAE,MAAM,EAC1B,OAAO,CAAC,EAAE,oBAAoB;IAiBhC;;;;OAIG;IACI,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI;CA+ClC"}
@@ -0,0 +1,83 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import { Readable } from "node:stream";
4
+ /**
5
+ * This class generates a readable stream from the data in an array of buffers.
6
+ */
7
+ export class BuffersStream extends Readable {
8
+ /**
9
+ * Creates an instance of BuffersStream that will emit the data
10
+ * contained in the array of buffers.
11
+ *
12
+ * @param buffers - Array of buffers containing the data
13
+ * @param byteLength - The total length of data contained in the buffers
14
+ */
15
+ constructor(buffers, byteLength, options) {
16
+ super(options);
17
+ this.buffers = buffers;
18
+ this.byteLength = byteLength;
19
+ this.byteOffsetInCurrentBuffer = 0;
20
+ this.bufferIndex = 0;
21
+ this.pushedBytesLength = 0;
22
+ // check byteLength is no larger than buffers[] total length
23
+ let buffersLength = 0;
24
+ for (const buf of this.buffers) {
25
+ buffersLength += buf.byteLength;
26
+ }
27
+ if (buffersLength < this.byteLength) {
28
+ throw new Error("Data size shouldn't be larger than the total length of buffers.");
29
+ }
30
+ }
31
+ /**
32
+ * Internal _read() that will be called when the stream wants to pull more data in.
33
+ *
34
+ * @param size - Optional. The size of data to be read
35
+ */
36
+ _read(size) {
37
+ if (this.pushedBytesLength >= this.byteLength) {
38
+ this.push(null);
39
+ }
40
+ if (!size) {
41
+ size = this.readableHighWaterMark;
42
+ }
43
+ const outBuffers = [];
44
+ let i = 0;
45
+ while (i < size && this.pushedBytesLength < this.byteLength) {
46
+ // The last buffer may be longer than the data it contains.
47
+ const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength;
48
+ const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer;
49
+ const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers);
50
+ if (remaining > size - i) {
51
+ // chunkSize = size - i
52
+ const end = this.byteOffsetInCurrentBuffer + size - i;
53
+ outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));
54
+ this.pushedBytesLength += size - i;
55
+ this.byteOffsetInCurrentBuffer = end;
56
+ i = size;
57
+ break;
58
+ }
59
+ else {
60
+ // chunkSize = remaining
61
+ const end = this.byteOffsetInCurrentBuffer + remaining;
62
+ outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));
63
+ if (remaining === remainingCapacityInThisBuffer) {
64
+ // this.buffers[this.bufferIndex] used up, shift to next one
65
+ this.byteOffsetInCurrentBuffer = 0;
66
+ this.bufferIndex++;
67
+ }
68
+ else {
69
+ this.byteOffsetInCurrentBuffer = end;
70
+ }
71
+ this.pushedBytesLength += remaining;
72
+ i += remaining;
73
+ }
74
+ }
75
+ if (outBuffers.length > 1) {
76
+ this.push(Buffer.concat(outBuffers));
77
+ }
78
+ else if (outBuffers.length === 1) {
79
+ this.push(outBuffers[0]);
80
+ }
81
+ }
82
+ }
83
+ //# sourceMappingURL=BuffersStream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BuffersStream.js","sourceRoot":"","sources":["../../src/BuffersStream.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAOvC;;GAEG;AACH,MAAM,OAAO,aAAc,SAAQ,QAAQ;IAgBzC;;;;;;OAMG;IACH,YACU,OAAiB,EACjB,UAAkB,EAC1B,OAA8B;QAE9B,KAAK,CAAC,OAAO,CAAC,CAAC;QAJP,YAAO,GAAP,OAAO,CAAU;QACjB,eAAU,GAAV,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AAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { ReadableOptions } from \"node:stream\";\nimport { Readable } from \"node:stream\";\n\n/**\n * Options to configure the BuffersStream.\n */\nexport interface BuffersStreamOptions extends ReadableOptions {}\n\n/**\n * This class generates a readable stream from the data in an array of buffers.\n */\nexport class BuffersStream extends Readable {\n /**\n * The offset of data to be read in the current buffer.\n */\n private byteOffsetInCurrentBuffer: number;\n\n /**\n * The index of buffer to be read in the array of buffers.\n */\n private bufferIndex: number;\n\n /**\n * The total length of data already read.\n */\n private pushedBytesLength: number;\n\n /**\n * Creates an instance of BuffersStream that will emit the data\n * contained in the array of buffers.\n *\n * @param buffers - Array of buffers containing the data\n * @param byteLength - The total length of data contained in the buffers\n */\n constructor(\n private buffers: Buffer[],\n private byteLength: number,\n options?: BuffersStreamOptions,\n ) {\n super(options);\n this.byteOffsetInCurrentBuffer = 0;\n this.bufferIndex = 0;\n this.pushedBytesLength = 0;\n\n // check byteLength is no larger than buffers[] total length\n let buffersLength = 0;\n for (const buf of this.buffers) {\n buffersLength += buf.byteLength;\n }\n if (buffersLength < this.byteLength) {\n throw new Error(\"Data size shouldn't be larger than the total length of buffers.\");\n }\n }\n\n /**\n * Internal _read() that will be called when the stream wants to pull more data in.\n *\n * @param size - Optional. The size of data to be read\n */\n public _read(size?: number): void {\n if (this.pushedBytesLength >= this.byteLength) {\n this.push(null);\n }\n\n if (!size) {\n size = this.readableHighWaterMark;\n }\n\n const outBuffers: Buffer[] = [];\n let i = 0;\n while (i < size && this.pushedBytesLength < this.byteLength) {\n // The last buffer may be longer than the data it contains.\n const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength;\n const remainingCapacityInThisBuffer =\n this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer;\n const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers);\n if (remaining > size - i) {\n // chunkSize = size - i\n const end = this.byteOffsetInCurrentBuffer + size - i;\n outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));\n this.pushedBytesLength += size - i;\n this.byteOffsetInCurrentBuffer = end;\n i = size;\n break;\n } else {\n // chunkSize = remaining\n const end = this.byteOffsetInCurrentBuffer + remaining;\n outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));\n if (remaining === remainingCapacityInThisBuffer) {\n // this.buffers[this.bufferIndex] used up, shift to next one\n this.byteOffsetInCurrentBuffer = 0;\n this.bufferIndex++;\n } else {\n this.byteOffsetInCurrentBuffer = end;\n }\n this.pushedBytesLength += remaining;\n i += remaining;\n }\n }\n\n if (outBuffers.length > 1) {\n this.push(Buffer.concat(outBuffers));\n } else if (outBuffers.length === 1) {\n this.push(outBuffers[0]);\n }\n }\n}\n"]}