@fluidframework/driver-utils 2.0.0-dev.2.3.0.115467 → 2.0.0-dev.4.1.0.148229

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 (180) hide show
  1. package/.eslintrc.js +17 -19
  2. package/.mocharc.js +2 -2
  3. package/api-extractor.json +2 -2
  4. package/dist/buildSnapshotTree.d.ts.map +1 -1
  5. package/dist/buildSnapshotTree.js.map +1 -1
  6. package/dist/documentStorageServiceProxy.d.ts.map +1 -1
  7. package/dist/documentStorageServiceProxy.js.map +1 -1
  8. package/dist/error.d.ts.map +1 -1
  9. package/dist/error.js.map +1 -1
  10. package/dist/fluidResolvedUrl.d.ts +8 -0
  11. package/dist/fluidResolvedUrl.d.ts.map +1 -1
  12. package/dist/fluidResolvedUrl.js +8 -0
  13. package/dist/fluidResolvedUrl.js.map +1 -1
  14. package/dist/index.d.ts +4 -10
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +2 -19
  17. package/dist/index.js.map +1 -1
  18. package/dist/insecureUrlResolver.d.ts.map +1 -1
  19. package/dist/insecureUrlResolver.js +2 -1
  20. package/dist/insecureUrlResolver.js.map +1 -1
  21. package/dist/messageRecognition.d.ts +0 -20
  22. package/dist/messageRecognition.d.ts.map +1 -1
  23. package/dist/messageRecognition.js +1 -37
  24. package/dist/messageRecognition.js.map +1 -1
  25. package/dist/network.d.ts +0 -15
  26. package/dist/network.d.ts.map +1 -1
  27. package/dist/network.js +4 -3
  28. package/dist/network.js.map +1 -1
  29. package/dist/networkUtils.d.ts +0 -10
  30. package/dist/networkUtils.d.ts.map +1 -1
  31. package/dist/networkUtils.js +3 -35
  32. package/dist/networkUtils.js.map +1 -1
  33. package/dist/packageVersion.d.ts +1 -1
  34. package/dist/packageVersion.js +1 -1
  35. package/dist/packageVersion.js.map +1 -1
  36. package/dist/parallelRequests.d.ts.map +1 -1
  37. package/dist/parallelRequests.js +52 -23
  38. package/dist/parallelRequests.js.map +1 -1
  39. package/dist/prefetchDocumentStorageService.d.ts.map +1 -1
  40. package/dist/prefetchDocumentStorageService.js.map +1 -1
  41. package/dist/rateLimiter.d.ts.map +1 -1
  42. package/dist/rateLimiter.js.map +1 -1
  43. package/dist/readAndParse.d.ts.map +1 -1
  44. package/dist/readAndParse.js.map +1 -1
  45. package/dist/runWithRetry.d.ts.map +1 -1
  46. package/dist/runWithRetry.js +10 -0
  47. package/dist/runWithRetry.js.map +1 -1
  48. package/dist/summaryForCreateNew.d.ts +21 -1
  49. package/dist/summaryForCreateNew.d.ts.map +1 -1
  50. package/dist/summaryForCreateNew.js +26 -1
  51. package/dist/summaryForCreateNew.js.map +1 -1
  52. package/dist/treeConversions.d.ts.map +1 -1
  53. package/dist/treeConversions.js +6 -10
  54. package/dist/treeConversions.js.map +1 -1
  55. package/lib/buildSnapshotTree.d.ts.map +1 -1
  56. package/lib/buildSnapshotTree.js.map +1 -1
  57. package/lib/documentStorageServiceProxy.d.ts.map +1 -1
  58. package/lib/documentStorageServiceProxy.js.map +1 -1
  59. package/lib/error.d.ts.map +1 -1
  60. package/lib/error.js.map +1 -1
  61. package/lib/fluidResolvedUrl.d.ts +8 -0
  62. package/lib/fluidResolvedUrl.d.ts.map +1 -1
  63. package/lib/fluidResolvedUrl.js +8 -0
  64. package/lib/fluidResolvedUrl.js.map +1 -1
  65. package/lib/index.d.ts +4 -10
  66. package/lib/index.d.ts.map +1 -1
  67. package/lib/index.js +3 -9
  68. package/lib/index.js.map +1 -1
  69. package/lib/insecureUrlResolver.d.ts.map +1 -1
  70. package/lib/insecureUrlResolver.js +2 -1
  71. package/lib/insecureUrlResolver.js.map +1 -1
  72. package/lib/messageRecognition.d.ts +0 -20
  73. package/lib/messageRecognition.d.ts.map +1 -1
  74. package/lib/messageRecognition.js +1 -36
  75. package/lib/messageRecognition.js.map +1 -1
  76. package/lib/network.d.ts +0 -15
  77. package/lib/network.d.ts.map +1 -1
  78. package/lib/network.js +4 -3
  79. package/lib/network.js.map +1 -1
  80. package/lib/networkUtils.d.ts +0 -10
  81. package/lib/networkUtils.d.ts.map +1 -1
  82. package/lib/networkUtils.js +2 -33
  83. package/lib/networkUtils.js.map +1 -1
  84. package/lib/packageVersion.d.ts +1 -1
  85. package/lib/packageVersion.js +1 -1
  86. package/lib/packageVersion.js.map +1 -1
  87. package/lib/parallelRequests.d.ts.map +1 -1
  88. package/lib/parallelRequests.js +53 -24
  89. package/lib/parallelRequests.js.map +1 -1
  90. package/lib/prefetchDocumentStorageService.d.ts.map +1 -1
  91. package/lib/prefetchDocumentStorageService.js.map +1 -1
  92. package/lib/rateLimiter.d.ts.map +1 -1
  93. package/lib/rateLimiter.js.map +1 -1
  94. package/lib/readAndParse.d.ts.map +1 -1
  95. package/lib/readAndParse.js.map +1 -1
  96. package/lib/runWithRetry.d.ts.map +1 -1
  97. package/lib/runWithRetry.js +10 -0
  98. package/lib/runWithRetry.js.map +1 -1
  99. package/lib/summaryForCreateNew.d.ts +21 -1
  100. package/lib/summaryForCreateNew.d.ts.map +1 -1
  101. package/lib/summaryForCreateNew.js +24 -0
  102. package/lib/summaryForCreateNew.js.map +1 -1
  103. package/lib/treeConversions.d.ts.map +1 -1
  104. package/lib/treeConversions.js +9 -13
  105. package/lib/treeConversions.js.map +1 -1
  106. package/package.json +54 -52
  107. package/prettier.config.cjs +1 -1
  108. package/src/buildSnapshotTree.ts +54 -51
  109. package/src/documentStorageServiceProxy.ts +49 -43
  110. package/src/error.ts +5 -7
  111. package/src/fluidResolvedUrl.ts +17 -6
  112. package/src/index.ts +4 -14
  113. package/src/insecureUrlResolver.ts +127 -116
  114. package/src/messageRecognition.ts +14 -44
  115. package/src/network.ts +112 -126
  116. package/src/networkUtils.ts +19 -48
  117. package/src/packageVersion.ts +1 -1
  118. package/src/parallelRequests.ts +591 -510
  119. package/src/prefetchDocumentStorageService.ts +76 -74
  120. package/src/rateLimiter.ts +29 -29
  121. package/src/readAndParse.ts +7 -4
  122. package/src/runWithRetry.ts +106 -84
  123. package/src/summaryForCreateNew.ts +74 -25
  124. package/src/treeConversions.ts +47 -70
  125. package/tsconfig.esnext.json +6 -6
  126. package/tsconfig.json +8 -12
  127. package/dist/blobAggregationStorage.d.ts +0 -43
  128. package/dist/blobAggregationStorage.d.ts.map +0 -1
  129. package/dist/blobAggregationStorage.js +0 -318
  130. package/dist/blobAggregationStorage.js.map +0 -1
  131. package/dist/blobCacheStorageService.d.ts +0 -16
  132. package/dist/blobCacheStorageService.d.ts.map +0 -1
  133. package/dist/blobCacheStorageService.js +0 -29
  134. package/dist/blobCacheStorageService.js.map +0 -1
  135. package/dist/emptyDocumentDeltaStorageService.d.ts +0 -13
  136. package/dist/emptyDocumentDeltaStorageService.d.ts.map +0 -1
  137. package/dist/emptyDocumentDeltaStorageService.js +0 -20
  138. package/dist/emptyDocumentDeltaStorageService.js.map +0 -1
  139. package/dist/multiDocumentServiceFactory.d.ts +0 -16
  140. package/dist/multiDocumentServiceFactory.d.ts.map +0 -1
  141. package/dist/multiDocumentServiceFactory.js +0 -63
  142. package/dist/multiDocumentServiceFactory.js.map +0 -1
  143. package/dist/multiUrlResolver.d.ts +0 -20
  144. package/dist/multiUrlResolver.d.ts.map +0 -1
  145. package/dist/multiUrlResolver.js +0 -45
  146. package/dist/multiUrlResolver.js.map +0 -1
  147. package/dist/treeUtils.d.ts +0 -51
  148. package/dist/treeUtils.d.ts.map +0 -1
  149. package/dist/treeUtils.js +0 -85
  150. package/dist/treeUtils.js.map +0 -1
  151. package/lib/blobAggregationStorage.d.ts +0 -43
  152. package/lib/blobAggregationStorage.d.ts.map +0 -1
  153. package/lib/blobAggregationStorage.js +0 -313
  154. package/lib/blobAggregationStorage.js.map +0 -1
  155. package/lib/blobCacheStorageService.d.ts +0 -16
  156. package/lib/blobCacheStorageService.d.ts.map +0 -1
  157. package/lib/blobCacheStorageService.js +0 -25
  158. package/lib/blobCacheStorageService.js.map +0 -1
  159. package/lib/emptyDocumentDeltaStorageService.d.ts +0 -13
  160. package/lib/emptyDocumentDeltaStorageService.d.ts.map +0 -1
  161. package/lib/emptyDocumentDeltaStorageService.js +0 -16
  162. package/lib/emptyDocumentDeltaStorageService.js.map +0 -1
  163. package/lib/multiDocumentServiceFactory.d.ts +0 -16
  164. package/lib/multiDocumentServiceFactory.d.ts.map +0 -1
  165. package/lib/multiDocumentServiceFactory.js +0 -59
  166. package/lib/multiDocumentServiceFactory.js.map +0 -1
  167. package/lib/multiUrlResolver.d.ts +0 -20
  168. package/lib/multiUrlResolver.d.ts.map +0 -1
  169. package/lib/multiUrlResolver.js +0 -40
  170. package/lib/multiUrlResolver.js.map +0 -1
  171. package/lib/treeUtils.d.ts +0 -51
  172. package/lib/treeUtils.d.ts.map +0 -1
  173. package/lib/treeUtils.js +0 -80
  174. package/lib/treeUtils.js.map +0 -1
  175. package/src/blobAggregationStorage.ts +0 -374
  176. package/src/blobCacheStorageService.ts +0 -32
  177. package/src/emptyDocumentDeltaStorageService.ts +0 -24
  178. package/src/multiDocumentServiceFactory.ts +0 -80
  179. package/src/multiUrlResolver.ts +0 -51
  180. package/src/treeUtils.ts +0 -111
@@ -8,7 +8,7 @@ import { PerformanceEvent } from "@fluidframework/telemetry-utils";
8
8
  import { ISequencedDocumentMessage } from "@fluidframework/protocol-definitions";
9
9
  import { IDeltasFetchResult, IStream, IStreamResult } from "@fluidframework/driver-definitions";
10
10
  import { getRetryDelayFromError, canRetryOnError, createGenericNetworkError } from "./network";
11
- import { waitForConnectedState, logNetworkFailure } from "./networkUtils";
11
+ import { logNetworkFailure } from "./networkUtils";
12
12
  // For now, this package is versioned and released in unison with the specific drivers
13
13
  import { pkgVersion as driverVersion } from "./packageVersion";
14
14
 
@@ -30,274 +30,307 @@ type WorkingState = "working" | "done" | "canceled";
30
30
  * @returns - Queue that can be used to retrieve data
31
31
  */
32
32
  export class ParallelRequests<T> {
33
- private latestRequested: number;
34
- private nextToDeliver: number;
35
- private readonly results: Map<number, T[]> = new Map();
36
- private workingState: WorkingState = "working";
37
- private requestsInFlight = 0;
38
- private readonly endEvent = new Deferred<void>();
39
- private requests = 0;
40
- private readonly knewTo: boolean;
41
-
42
- private get working() { return this.workingState === "working"; }
43
- public get canceled() { return this.workingState === "canceled"; }
44
-
45
- constructor(
46
- from: number,
47
- private to: number | undefined,
48
- private readonly payloadSize: number,
49
- private readonly logger: ITelemetryLogger,
50
- private readonly requestCallback: (
51
- request: number,
52
- from: number,
53
- to: number,
54
- strongTo: boolean,
55
- props: ITelemetryProperties) => Promise<{ partial: boolean; cancel: boolean; payload: T[]; }>,
56
- private readonly responseCallback: (payload: T[]) => void) {
57
- this.latestRequested = from;
58
- this.nextToDeliver = from;
59
- this.knewTo = (to !== undefined);
60
- }
61
-
62
- public cancel() {
63
- if (this.working) {
64
- this.workingState = "canceled";
65
- this.endEvent.resolve();
66
- }
67
- }
68
-
69
- public async run(concurrency: number) {
70
- assert(concurrency > 0, 0x102 /* "invalid level of concurrency" */);
71
- assert(this.working, 0x103 /* "trying to parallel run while not working" */);
72
-
73
- let c = concurrency;
74
- while (c > 0) {
75
- c--;
76
- this.addRequest();
77
- }
78
- this.dispatch();// will recalculate and trigger this.endEvent if needed
79
- return this.endEvent.promise;
80
- }
81
-
82
- private done() {
83
- // We should satisfy request fully.
84
- assert(this.to !== undefined, 0x104 /* "undefined end point for parallel fetch" */);
85
- assert(this.nextToDeliver >= this.to, 0x105 /* "unexpected end point for parallel fetch" */);
86
- if (this.working) {
87
- this.workingState = "done";
88
- this.endEvent.resolve();
89
- }
90
- }
91
-
92
- private fail(error) {
93
- if (this.working) {
94
- this.workingState = "done";
95
- this.endEvent.reject(error);
96
- }
97
- }
98
-
99
- private dispatch() {
100
- while (this.working) {
101
- const value = this.results.get(this.nextToDeliver);
102
- if (value === undefined) {
103
- break;
104
- }
105
- this.results.delete(this.nextToDeliver);
106
- assert(value.length <= this.payloadSize, 0x1d9 /* "addRequestCore() should break into smaller chunks" */);
107
- this.nextToDeliver += value.length;
108
- this.responseCallback(value);
109
- }
110
-
111
- // Account for cancellation - state might be not in consistent state on cancelling operation
112
- if (this.working) {
113
- if (this.requestsInFlight === 0) {
114
- // we should have dispatched everything, no matter whether we knew about the end or not.
115
- // see comment in addRequestCore() around throwing away chunk if it's above this.to
116
- assert(this.results.size === 0,
117
- 0x107 /* "ending dispatch with remaining results to be sent" */);
118
- this.done();
119
- } else if (this.to !== undefined && this.nextToDeliver >= this.to) {
120
- // Learned about the end and dispatched all the ops up to it.
121
- // Ignore all the in-flight requests above boundary - unblock caller sooner.
122
- assert(!this.knewTo, 0x108 /* "ending results dispatch but knew in advance about more requests" */);
123
- this.done();
124
- }
125
- }
126
- }
127
-
128
- private getNextChunk() {
129
- if (!this.working) {
130
- return undefined;
131
- }
132
-
133
- const from = this.latestRequested;
134
- if (this.to !== undefined) {
135
- if (this.to <= from) {
136
- return undefined;
137
- }
138
- }
139
-
140
- // this.latestRequested
141
- // inclusive on the right side! Exclusive on the left.
142
- this.latestRequested += this.payloadSize;
143
-
144
- if (this.to !== undefined) {
145
- this.latestRequested = Math.min(this.to, this.latestRequested);
146
- }
147
-
148
- assert(from < this.latestRequested, 0x109 /* "unexpected next chunk position" */);
149
-
150
- return { from, to: this.latestRequested };
151
- }
152
-
153
- private addRequest() {
154
- const chunk = this.getNextChunk();
155
- if (chunk === undefined) {
156
- return;
157
- }
158
- this.addRequestCore(chunk.from, chunk.to).catch(this.fail.bind(this));
159
- }
160
-
161
- private async addRequestCore(fromArg: number, toArg: number) {
162
- assert(this.working, 0x10a /* "cannot add parallel request while not working" */);
163
-
164
- let from = fromArg;
165
- let to = toArg;
166
-
167
- // to & from are exclusive
168
- this.requestsInFlight++;
169
- while (this.working) {
170
- const requestedLength = to - from;
171
- assert(requestedLength > 0, 0x10b /* "invalid parallel request range" */);
172
-
173
- // We should not be wasting time asking for something useless.
174
- if (this.to !== undefined) {
175
- assert(from < this.to, 0x10c /* "invalid parallel request start point" */);
176
- assert(to <= this.to, 0x10d /* "invalid parallel request end point" */);
177
- }
178
-
179
- this.requests++;
180
-
181
- const promise = this.requestCallback(this.requests, from, to, this.to !== undefined, {});
182
-
183
- // dispatch any prior received data
184
- this.dispatch();
185
-
186
- const { payload, cancel, partial } = await promise;
187
-
188
- if (cancel) {
189
- this.cancel();
190
- }
191
-
192
- if (this.to !== undefined && from >= this.to) {
193
- // while we were waiting for response, we learned on what is the boundary
194
- // We can get here (with actual result!) if situation changed while this request was in
195
- // flight, i.e. the end was extended over what we learn in some other request
196
- // While it's useful not to throw this result, this is very corner cases and makes logic
197
- // (including consistency checks) much harder to write correctly.
198
- // So for now, we are throwing this result out the window.
199
- assert(!this.knewTo, 0x10e /* "should not throw result if we knew about boundary in advance" */);
200
- // Learn how often it happens and if it's too wasteful to throw these chunks.
201
- // If it pops into our view a lot, we would need to reconsider how we approach it.
202
- // Note that this is not visible to user other than potentially not hitting 100% of
203
- // what we can in perf domain.
204
- if (payload.length !== 0) {
205
- this.logger.sendErrorEvent({
206
- eventName: "ParallelRequests_GotExtra",
207
- from,
208
- to,
209
- end: this.to,
210
- length: payload.length,
211
- });
212
- }
213
-
214
- break;
215
- }
216
-
217
- if (this.working) {
218
- const fromOrig = from;
219
- const length = payload.length;
220
- let fullChunk = (requestedLength <= length); // we can possible get more than we asked.
221
-
222
- if (length !== 0) {
223
- // We can get more than we asked for!
224
- // This can screw up logic in dispatch!
225
- // So push only batch size, and keep the rest for later - if conditions are favorable, we
226
- // will be able to use it. If not (parallel request overlapping these ops), it's easier to
227
- // discard them and wait for another (overlapping) request to come in later.
228
- if (requestedLength < length) {
229
- // This is error in a sense that it's not expected and likely points bug in other layer.
230
- // This layer copes with this situation just fine.
231
- this.logger.sendTelemetryEvent({
232
- eventName: "ParallelRequests_Over",
233
- from,
234
- to,
235
- length,
236
- });
237
- }
238
- const data = payload.splice(0, requestedLength);
239
- this.results.set(from, data);
240
- from += data.length;
241
- } else {
242
- // 1. empty (partial) chunks should not be returned by various caching / adapter layers -
243
- // they should fall back to next layer. This might be important invariant to hold to ensure
244
- // that we are less likely have bugs where such layer would keep returning empty partial
245
- // result on each call.
246
- // 2. Current invariant is that callback does retries until it gets something,
247
- // with the goal of failing if zero data is retrieved in given amount of time.
248
- // This is very specific property of storage / ops, so this logic is not here, but given only
249
- // one user of this class, we assert that to catch issues earlier.
250
- // These invariant can be relaxed if needed.
251
- assert(!partial, 0x10f /* "empty/partial chunks should not be returned by caching" */);
252
- assert(!this.knewTo,
253
- 0x110 /* "callback should retry until valid fetch before it learns new boundary" */);
254
- }
255
-
256
- if (!partial && !fullChunk) {
257
- if (!this.knewTo) {
258
- if (this.to === undefined || this.to > from) {
259
- // The END
260
- this.to = from;
261
- }
262
- break;
263
- }
264
- // We know that there are more items to be retrieved
265
- // Can we get partial chunk? Ideally storage indicates that's not a full chunk
266
- // Note that it's possible that not all ops hit storage yet.
267
- // We will come back to request more, and if we can't get any more ops soon, it's
268
- // catastrophic failure (see comment above on responsibility of callback to return something)
269
- // This layer will just keep trying until it gets full set.
270
- this.logger.sendPerformanceEvent({
271
- eventName: "ParallelRequests_Partial",
272
- from: fromOrig,
273
- to,
274
- length,
275
- });
276
- }
277
-
278
- if (to === this.latestRequested) {
279
- // we can go after full chunk at the end if we received partial chunk, or more than asked
280
- // Also if we got more than we asked to, we can actually use those ops!
281
- if (payload.length !== 0) {
282
- this.results.set(from, payload);
283
- from += payload.length;
284
- }
285
-
286
- this.latestRequested = from;
287
- fullChunk = true;
288
- }
289
-
290
- if (fullChunk) {
291
- const chunk = this.getNextChunk();
292
- if (chunk === undefined) { break; }
293
- from = chunk.from;
294
- to = chunk.to;
295
- }
296
- }
297
- }
298
- this.requestsInFlight--;
299
- this.dispatch();
300
- }
33
+ private latestRequested: number;
34
+ private nextToDeliver: number;
35
+ private readonly results: Map<number, T[]> = new Map();
36
+ private workingState: WorkingState = "working";
37
+ private requestsInFlight = 0;
38
+ private readonly endEvent = new Deferred<void>();
39
+ private requests = 0;
40
+ private readonly knewTo: boolean;
41
+
42
+ private get working() {
43
+ return this.workingState === "working";
44
+ }
45
+ public get canceled() {
46
+ return this.workingState === "canceled";
47
+ }
48
+
49
+ constructor(
50
+ from: number,
51
+ private to: number | undefined,
52
+ private readonly payloadSize: number,
53
+ private readonly logger: ITelemetryLogger,
54
+ private readonly requestCallback: (
55
+ request: number,
56
+ from: number,
57
+ to: number,
58
+ strongTo: boolean,
59
+ props: ITelemetryProperties,
60
+ ) => Promise<{ partial: boolean; cancel: boolean; payload: T[] }>,
61
+ private readonly responseCallback: (payload: T[]) => void,
62
+ ) {
63
+ this.latestRequested = from;
64
+ this.nextToDeliver = from;
65
+ this.knewTo = to !== undefined;
66
+ }
67
+
68
+ public cancel() {
69
+ if (this.working) {
70
+ this.workingState = "canceled";
71
+ this.endEvent.resolve();
72
+ }
73
+ }
74
+
75
+ public async run(concurrency: number) {
76
+ assert(concurrency > 0, 0x102 /* "invalid level of concurrency" */);
77
+ assert(this.working, 0x103 /* "trying to parallel run while not working" */);
78
+
79
+ let c = concurrency;
80
+ while (c > 0) {
81
+ c--;
82
+ this.addRequest();
83
+ }
84
+ this.dispatch(); // will recalculate and trigger this.endEvent if needed
85
+ return this.endEvent.promise;
86
+ }
87
+
88
+ private done() {
89
+ // We should satisfy request fully.
90
+ assert(this.to !== undefined, 0x104 /* "undefined end point for parallel fetch" */);
91
+ assert(
92
+ this.nextToDeliver >= this.to,
93
+ 0x105 /* "unexpected end point for parallel fetch" */,
94
+ );
95
+ if (this.working) {
96
+ this.workingState = "done";
97
+ this.endEvent.resolve();
98
+ }
99
+ }
100
+
101
+ private fail(error) {
102
+ if (this.working) {
103
+ this.workingState = "done";
104
+ this.endEvent.reject(error);
105
+ }
106
+ }
107
+
108
+ private dispatch() {
109
+ while (this.working) {
110
+ const value = this.results.get(this.nextToDeliver);
111
+ if (value === undefined) {
112
+ break;
113
+ }
114
+ this.results.delete(this.nextToDeliver);
115
+ assert(
116
+ value.length <= this.payloadSize,
117
+ 0x1d9 /* "addRequestCore() should break into smaller chunks" */,
118
+ );
119
+ this.nextToDeliver += value.length;
120
+ this.responseCallback(value);
121
+ }
122
+
123
+ // Account for cancellation - state might be not in consistent state on cancelling operation
124
+ if (this.working) {
125
+ if (this.requestsInFlight === 0) {
126
+ // we should have dispatched everything, no matter whether we knew about the end or not.
127
+ // see comment in addRequestCore() around throwing away chunk if it's above this.to
128
+ assert(
129
+ this.results.size === 0,
130
+ 0x107 /* "ending dispatch with remaining results to be sent" */,
131
+ );
132
+ this.done();
133
+ } else if (this.to !== undefined && this.nextToDeliver >= this.to) {
134
+ // Learned about the end and dispatched all the ops up to it.
135
+ // Ignore all the in-flight requests above boundary - unblock caller sooner.
136
+ assert(
137
+ !this.knewTo,
138
+ 0x108 /* "ending results dispatch but knew in advance about more requests" */,
139
+ );
140
+ this.done();
141
+ }
142
+ }
143
+ }
144
+
145
+ private getNextChunk() {
146
+ if (!this.working) {
147
+ return undefined;
148
+ }
149
+
150
+ const from = this.latestRequested;
151
+ if (this.to !== undefined) {
152
+ if (this.to <= from) {
153
+ return undefined;
154
+ }
155
+ }
156
+
157
+ // this.latestRequested
158
+ // inclusive on the right side! Exclusive on the left.
159
+ this.latestRequested += this.payloadSize;
160
+
161
+ if (this.to !== undefined) {
162
+ this.latestRequested = Math.min(this.to, this.latestRequested);
163
+ }
164
+
165
+ assert(from < this.latestRequested, 0x109 /* "unexpected next chunk position" */);
166
+
167
+ return { from, to: this.latestRequested };
168
+ }
169
+
170
+ private addRequest() {
171
+ const chunk = this.getNextChunk();
172
+ if (chunk === undefined) {
173
+ return;
174
+ }
175
+ this.addRequestCore(chunk.from, chunk.to).catch(this.fail.bind(this));
176
+ }
177
+
178
+ private async addRequestCore(fromArg: number, toArg: number) {
179
+ assert(this.working, 0x10a /* "cannot add parallel request while not working" */);
180
+
181
+ let from = fromArg;
182
+ let to = toArg;
183
+
184
+ // to & from are exclusive
185
+ this.requestsInFlight++;
186
+ while (this.working) {
187
+ const requestedLength = to - from;
188
+ assert(requestedLength > 0, 0x10b /* "invalid parallel request range" */);
189
+
190
+ // We should not be wasting time asking for something useless.
191
+ if (this.to !== undefined) {
192
+ assert(from < this.to, 0x10c /* "invalid parallel request start point" */);
193
+ assert(to <= this.to, 0x10d /* "invalid parallel request end point" */);
194
+ }
195
+
196
+ this.requests++;
197
+
198
+ const promise = this.requestCallback(
199
+ this.requests,
200
+ from,
201
+ to,
202
+ this.to !== undefined,
203
+ {},
204
+ );
205
+
206
+ // dispatch any prior received data
207
+ this.dispatch();
208
+
209
+ const { payload, cancel, partial } = await promise;
210
+
211
+ if (cancel) {
212
+ this.cancel();
213
+ }
214
+
215
+ if (this.to !== undefined && from >= this.to) {
216
+ // while we were waiting for response, we learned on what is the boundary
217
+ // We can get here (with actual result!) if situation changed while this request was in
218
+ // flight, i.e. the end was extended over what we learn in some other request
219
+ // While it's useful not to throw this result, this is very corner cases and makes logic
220
+ // (including consistency checks) much harder to write correctly.
221
+ // So for now, we are throwing this result out the window.
222
+ assert(
223
+ !this.knewTo,
224
+ 0x10e /* "should not throw result if we knew about boundary in advance" */,
225
+ );
226
+ // Learn how often it happens and if it's too wasteful to throw these chunks.
227
+ // If it pops into our view a lot, we would need to reconsider how we approach it.
228
+ // Note that this is not visible to user other than potentially not hitting 100% of
229
+ // what we can in perf domain.
230
+ if (payload.length !== 0) {
231
+ this.logger.sendErrorEvent({
232
+ eventName: "ParallelRequests_GotExtra",
233
+ from,
234
+ to,
235
+ end: this.to,
236
+ length: payload.length,
237
+ });
238
+ }
239
+
240
+ break;
241
+ }
242
+
243
+ if (this.working) {
244
+ const fromOrig = from;
245
+ const length = payload.length;
246
+ let fullChunk = requestedLength <= length; // we can possible get more than we asked.
247
+
248
+ if (length !== 0) {
249
+ // We can get more than we asked for!
250
+ // This can screw up logic in dispatch!
251
+ // So push only batch size, and keep the rest for later - if conditions are favorable, we
252
+ // will be able to use it. If not (parallel request overlapping these ops), it's easier to
253
+ // discard them and wait for another (overlapping) request to come in later.
254
+ if (requestedLength < length) {
255
+ // This is error in a sense that it's not expected and likely points bug in other layer.
256
+ // This layer copes with this situation just fine.
257
+ this.logger.sendTelemetryEvent({
258
+ eventName: "ParallelRequests_Over",
259
+ from,
260
+ to,
261
+ length,
262
+ });
263
+ }
264
+ const data = payload.splice(0, requestedLength);
265
+ this.results.set(from, data);
266
+ from += data.length;
267
+ } else {
268
+ // 1. empty (partial) chunks should not be returned by various caching / adapter layers -
269
+ // they should fall back to next layer. This might be important invariant to hold to ensure
270
+ // that we are less likely have bugs where such layer would keep returning empty partial
271
+ // result on each call.
272
+ // 2. Current invariant is that callback does retries until it gets something,
273
+ // with the goal of failing if zero data is retrieved in given amount of time.
274
+ // This is very specific property of storage / ops, so this logic is not here, but given only
275
+ // one user of this class, we assert that to catch issues earlier.
276
+ // These invariant can be relaxed if needed.
277
+ assert(
278
+ !partial,
279
+ 0x10f /* "empty/partial chunks should not be returned by caching" */,
280
+ );
281
+ assert(
282
+ !this.knewTo,
283
+ 0x110 /* "callback should retry until valid fetch before it learns new boundary" */,
284
+ );
285
+ }
286
+
287
+ if (!partial && !fullChunk) {
288
+ if (!this.knewTo) {
289
+ if (this.to === undefined || this.to > from) {
290
+ // The END
291
+ this.to = from;
292
+ }
293
+ break;
294
+ }
295
+ // We know that there are more items to be retrieved
296
+ // Can we get partial chunk? Ideally storage indicates that's not a full chunk
297
+ // Note that it's possible that not all ops hit storage yet.
298
+ // We will come back to request more, and if we can't get any more ops soon, it's
299
+ // catastrophic failure (see comment above on responsibility of callback to return something)
300
+ // This layer will just keep trying until it gets full set.
301
+ this.logger.sendPerformanceEvent({
302
+ eventName: "ParallelRequests_Partial",
303
+ from: fromOrig,
304
+ to,
305
+ length,
306
+ });
307
+ }
308
+
309
+ if (to === this.latestRequested) {
310
+ // we can go after full chunk at the end if we received partial chunk, or more than asked
311
+ // Also if we got more than we asked to, we can actually use those ops!
312
+ if (payload.length !== 0) {
313
+ this.results.set(from, payload);
314
+ from += payload.length;
315
+ }
316
+
317
+ this.latestRequested = from;
318
+ fullChunk = true;
319
+ }
320
+
321
+ if (fullChunk) {
322
+ const chunk = this.getNextChunk();
323
+ if (chunk === undefined) {
324
+ break;
325
+ }
326
+ from = chunk.from;
327
+ to = chunk.to;
328
+ }
329
+ }
330
+ }
331
+ this.requestsInFlight--;
332
+ this.dispatch();
333
+ }
301
334
  }
302
335
 
303
336
  /**
@@ -305,47 +338,60 @@ export class ParallelRequests<T> {
305
338
  * It's essentially a pipe allowing multiple writers, and single reader
306
339
  */
307
340
  export class Queue<T> implements IStream<T> {
308
- private readonly queue: Promise<IStreamResult<T>>[] = [];
309
- private deferred: Deferred<IStreamResult<T>> | undefined;
310
- private done = false;
311
-
312
- public pushValue(value: T) {
313
- this.pushCore(Promise.resolve({ done: false, value }));
314
- }
315
-
316
- public pushError(error: any) {
317
- this.pushCore(Promise.reject(error));
318
- this.done = true;
319
- }
320
-
321
- public pushDone() {
322
- this.pushCore(Promise.resolve({ done: true }));
323
- this.done = true;
324
- }
325
-
326
- protected pushCore(value: Promise<IStreamResult<T>>) {
327
- assert(!this.done, 0x112 /* "cannot push onto queue if done" */);
328
- if (this.deferred) {
329
- assert(this.queue.length === 0, 0x113 /* "deferred queue should be empty" */);
330
- this.deferred.resolve(value);
331
- this.deferred = undefined;
332
- } else {
333
- this.queue.push(value);
334
- }
335
- }
336
-
337
- public async read(): Promise<IStreamResult<T>> {
338
- assert(this.deferred === undefined, 0x114 /* "cannot pop if deferred" */);
339
- const value = this.queue.shift();
340
- if (value !== undefined) {
341
- return value;
342
- }
343
- assert(!this.done, 0x115 /* "queue should not be done during pop" */);
344
- this.deferred = new Deferred<IStreamResult<T>>();
345
- return this.deferred.promise;
346
- }
341
+ private readonly queue: Promise<IStreamResult<T>>[] = [];
342
+ private deferred: Deferred<IStreamResult<T>> | undefined;
343
+ private done = false;
344
+
345
+ public pushValue(value: T) {
346
+ this.pushCore(Promise.resolve({ done: false, value }));
347
+ }
348
+
349
+ public pushError(error: any) {
350
+ this.pushCore(Promise.reject(error));
351
+ this.done = true;
352
+ }
353
+
354
+ public pushDone() {
355
+ this.pushCore(Promise.resolve({ done: true }));
356
+ this.done = true;
357
+ }
358
+
359
+ protected pushCore(value: Promise<IStreamResult<T>>) {
360
+ assert(!this.done, 0x112 /* "cannot push onto queue if done" */);
361
+ if (this.deferred) {
362
+ assert(this.queue.length === 0, 0x113 /* "deferred queue should be empty" */);
363
+ this.deferred.resolve(value);
364
+ this.deferred = undefined;
365
+ } else {
366
+ this.queue.push(value);
367
+ }
368
+ }
369
+
370
+ public async read(): Promise<IStreamResult<T>> {
371
+ assert(this.deferred === undefined, 0x114 /* "cannot pop if deferred" */);
372
+ const value = this.queue.shift();
373
+ if (value !== undefined) {
374
+ return value;
375
+ }
376
+ assert(!this.done, 0x115 /* "queue should not be done during pop" */);
377
+ this.deferred = new Deferred<IStreamResult<T>>();
378
+ return this.deferred.promise;
379
+ }
347
380
  }
348
381
 
382
+ const waitForOnline = async (): Promise<void> => {
383
+ // Only wait if we have a strong signal that we're offline - otherwise assume we're online.
384
+ if (globalThis.navigator?.onLine === false && globalThis.addEventListener !== undefined) {
385
+ return new Promise<void>((resolve) => {
386
+ const resolveAndRemoveListener = () => {
387
+ resolve();
388
+ globalThis.removeEventListener("online", resolveAndRemoveListener);
389
+ };
390
+ globalThis.addEventListener("online", resolveAndRemoveListener);
391
+ });
392
+ }
393
+ };
394
+
349
395
  /**
350
396
  * Retrieve single batch of ops
351
397
  * @param request - request index
@@ -360,93 +406,100 @@ export class Queue<T> implements IStream<T> {
360
406
  * @returns - an object with resulting ops and cancellation / partial result flags
361
407
  */
362
408
  async function getSingleOpBatch(
363
- get: (telemetryProps: ITelemetryProperties) => Promise<IDeltasFetchResult>,
364
- props: ITelemetryProperties,
365
- strongTo: boolean,
366
- logger: ITelemetryLogger,
367
- signal?: AbortSignal,
368
- scenarioName?: string):
369
- Promise<{ partial: boolean; cancel: boolean; payload: ISequencedDocumentMessage[]; }> {
370
- let lastSuccessTime: number | undefined;
371
-
372
- let retry: number = 0;
373
- const deltas: ISequencedDocumentMessage[] = [];
374
- const nothing = { partial: false, cancel: true, payload: [] };
375
-
376
- while (signal?.aborted !== true) {
377
- retry++;
378
- let delay = Math.min(MaxFetchDelayInMs, MissingFetchDelayInMs * Math.pow(2, retry));
379
- const startTime = performance.now();
380
-
381
- try {
382
- // Issue async request for deltas - limit the number fetched to MaxBatchDeltas
383
- const deltasP = get({ ...props, retry } /* telemetry props */);
384
-
385
- const { messages, partialResult } = await deltasP;
386
- deltas.push(...messages);
387
-
388
- const deltasRetrievedLast = messages.length;
389
-
390
- if (deltasRetrievedLast !== 0 || !strongTo) {
391
- return { payload: deltas, cancel: false, partial: partialResult };
392
- }
393
-
394
- // Storage does not have ops we need.
395
- // Attempt to fetch more deltas. If we didn't receive any in the previous call we up our retry
396
- // count since something prevented us from seeing those deltas
397
-
398
- if (lastSuccessTime === undefined) {
399
- lastSuccessTime = performance.now();
400
- } else if (performance.now() - lastSuccessTime > 30000) {
401
- // If we are connected and receiving proper responses from server, but can't get any ops back,
402
- // then give up after some time. This likely indicates the issue with ordering service not flushing
403
- // ops to storage quick enough, and possibly waiting for summaries, while summarizer can't get
404
- // current as it can't get ops.
405
- throw createGenericNetworkError(
406
- // pre-0.58 error message: failedToRetrieveOpsFromStorage:TooManyRetries
407
- "Failed to retrieve ops from storage (Too Many Retries)",
408
- { canRetry: false },
409
- {
410
- retry,
411
- driverVersion,
412
- ...props,
413
- },
414
- );
415
- }
416
- } catch (error) {
417
- const canRetry = canRetryOnError(error);
418
-
419
- lastSuccessTime = undefined;
420
-
421
- const retryAfter = getRetryDelayFromError(error);
422
-
423
- // This will log to error table only if the error is non-retryable
424
- logNetworkFailure(
425
- logger,
426
- {
427
- eventName: "GetDeltas_Error",
428
- ...props,
429
- retry,
430
- duration: performance.now() - startTime,
431
- retryAfter,
432
- reason: scenarioName,
433
- },
434
- error);
435
-
436
- if (!canRetry) {
437
- // It's game over scenario.
438
- throw error;
439
- }
440
-
441
- if (retryAfter !== undefined && retryAfter >= 0) {
442
- delay = retryAfter;
443
- }
444
- }
445
-
446
- await waitForConnectedState(delay);
447
- }
448
-
449
- return nothing;
409
+ get: (telemetryProps: ITelemetryProperties) => Promise<IDeltasFetchResult>,
410
+ props: ITelemetryProperties,
411
+ strongTo: boolean,
412
+ logger: ITelemetryLogger,
413
+ signal?: AbortSignal,
414
+ scenarioName?: string,
415
+ ): Promise<{ partial: boolean; cancel: boolean; payload: ISequencedDocumentMessage[] }> {
416
+ let lastSuccessTime: number | undefined;
417
+
418
+ let retry: number = 0;
419
+ const nothing = { partial: false, cancel: true, payload: [] };
420
+
421
+ while (signal?.aborted !== true) {
422
+ retry++;
423
+ let delay = Math.min(MaxFetchDelayInMs, MissingFetchDelayInMs * Math.pow(2, retry));
424
+ const startTime = performance.now();
425
+
426
+ try {
427
+ // Issue async request for deltas
428
+ const { messages, partialResult } = await get(
429
+ { ...props, retry } /* telemetry props */,
430
+ );
431
+
432
+ // If we got messages back, return them. Return regardless of whether we got messages back if we didn't
433
+ // specify a "to", since we don't have an expectation of how many to receive.
434
+ if (messages.length !== 0 || !strongTo) {
435
+ return { payload: messages, cancel: false, partial: partialResult };
436
+ }
437
+
438
+ // Otherwise, the storage gave us back an empty set of ops but we were expecting a non-empty set.
439
+
440
+ if (lastSuccessTime === undefined) {
441
+ // Take timestamp of the first time server responded successfully, even though it wasn't with the ops we asked for.
442
+ // If we keep getting empty responses we'll eventually fail out below.
443
+ lastSuccessTime = performance.now();
444
+ } else if (performance.now() - lastSuccessTime > 30000) {
445
+ // If we are connected and receiving proper responses from server, but can't get any ops back,
446
+ // then give up after some time. This likely indicates the issue with ordering service not flushing
447
+ // ops to storage quick enough, and possibly waiting for summaries, while summarizer can't get
448
+ // current as it can't get ops.
449
+ throw createGenericNetworkError(
450
+ // pre-0.58 error message: failedToRetrieveOpsFromStorage:TooManyRetries
451
+ "Failed to retrieve ops from storage (Too Many Retries)",
452
+ { canRetry: false },
453
+ {
454
+ retry,
455
+ driverVersion,
456
+ ...props,
457
+ },
458
+ );
459
+ }
460
+ } catch (error) {
461
+ const canRetry = canRetryOnError(error);
462
+
463
+ const retryAfter = getRetryDelayFromError(error);
464
+
465
+ // This will log to error table only if the error is non-retryable
466
+ logNetworkFailure(
467
+ logger,
468
+ {
469
+ eventName: "GetDeltas_Error",
470
+ ...props,
471
+ retry,
472
+ duration: performance.now() - startTime,
473
+ retryAfter,
474
+ reason: scenarioName,
475
+ },
476
+ error,
477
+ );
478
+
479
+ if (!canRetry) {
480
+ // It's game over scenario.
481
+ throw error;
482
+ }
483
+
484
+ if (retryAfter !== undefined) {
485
+ // If the error told us to wait, then we will wait for that specific amount rather than the default.
486
+ delay = retryAfter;
487
+ }
488
+ }
489
+
490
+ // If we get here something has gone wrong - either got an unexpected empty set of messages back or a real error.
491
+ // Either way we will wait a little bit before retrying.
492
+ await new Promise<void>((resolve) => {
493
+ setTimeout(resolve, delay);
494
+ });
495
+
496
+ // If we believe we're offline, we assume there's no point in trying until we at least think we're online.
497
+ // NOTE: This isn't strictly true for drivers that don't require network (e.g. local driver). Really this logic
498
+ // should probably live in the driver.
499
+ await waitForOnline();
500
+ }
501
+
502
+ return nothing;
450
503
  }
451
504
 
452
505
  /**
@@ -462,127 +515,155 @@ async function getSingleOpBatch(
462
515
  * @returns - Messages fetched
463
516
  */
464
517
  export function requestOps(
465
- get: (from: number, to: number, telemetryProps: ITelemetryProperties) => Promise<IDeltasFetchResult>,
466
- concurrency: number,
467
- fromTotal: number,
468
- toTotal: number | undefined,
469
- payloadSize: number,
470
- logger: ITelemetryLogger,
471
- signal?: AbortSignal,
472
- scenarioName?: string,
518
+ get: (
519
+ from: number,
520
+ to: number,
521
+ telemetryProps: ITelemetryProperties,
522
+ ) => Promise<IDeltasFetchResult>,
523
+ concurrency: number,
524
+ fromTotal: number,
525
+ toTotal: number | undefined,
526
+ payloadSize: number,
527
+ logger: ITelemetryLogger,
528
+ signal?: AbortSignal,
529
+ scenarioName?: string,
473
530
  ): IStream<ISequencedDocumentMessage[]> {
474
- let requests = 0;
475
- let lastFetch: number | undefined;
476
- let length = 0;
477
- const queue = new Queue<ISequencedDocumentMessage[]>();
478
-
479
- const propsTotal: ITelemetryProperties = {
480
- fromTotal,
481
- toTotal,
482
- };
483
-
484
- const telemetryEvent = PerformanceEvent.start(logger, {
485
- eventName: "GetDeltas",
486
- ...propsTotal,
487
- reason: scenarioName,
488
- });
489
-
490
- const manager = new ParallelRequests<ISequencedDocumentMessage>(
491
- fromTotal,
492
- toTotal,
493
- payloadSize,
494
- logger,
495
- async (request: number, from: number, to: number, strongTo: boolean, propsPerRequest: ITelemetryProperties) => {
496
- requests++;
497
- return getSingleOpBatch(
498
- async (propsAll) => get(from, to, propsAll),
499
- { request, from, to, ...propsTotal, ...propsPerRequest },
500
- strongTo,
501
- logger,
502
- signal,
503
- scenarioName,
504
- );
505
- },
506
- (deltas: ISequencedDocumentMessage[]) => {
507
- // Assert continuing and right start.
508
- if (lastFetch === undefined) {
509
- assert(deltas[0].sequenceNumber === fromTotal, 0x26d /* "wrong start" */);
510
- } else {
511
- assert(deltas[0].sequenceNumber === lastFetch + 1, 0x26e /* "wrong start" */);
512
- }
513
- lastFetch = deltas[deltas.length - 1].sequenceNumber;
514
- assert(lastFetch - deltas[0].sequenceNumber + 1 === deltas.length,
515
- 0x26f /* "continuous and no duplicates" */);
516
- length += deltas.length;
517
- queue.pushValue(deltas);
518
- });
519
-
520
- // Implement faster cancellation. getSingleOpBatch() checks signal, but only in between
521
- // waits (up to 10 seconds) and fetches (can take infinite amount of time).
522
- // While every such case should be improved and take into account signal (and thus cancel immediately),
523
- // it is beneficial to have catch-all
524
- const listener = (event: Event) => { manager.cancel(); };
525
- if (signal !== undefined) {
526
- signal.addEventListener("abort", listener);
527
- }
528
-
529
- manager.run(concurrency)
530
- .finally(() => {
531
- if (signal !== undefined) {
532
- signal.removeEventListener("abort", listener);
533
- }
534
- }).then(() => {
535
- const props = {
536
- lastFetch,
537
- length,
538
- requests,
539
- };
540
- if (manager.canceled) {
541
- telemetryEvent.cancel({ ...props, error: "ops request cancelled by client" });
542
- } else {
543
- assert(toTotal === undefined || lastFetch !== undefined && lastFetch >= toTotal - 1,
544
- 0x270 /* "All requested ops fetched" */);
545
- telemetryEvent.end(props);
546
- }
547
- queue.pushDone();
548
- })
549
- .catch((error) => {
550
- telemetryEvent.cancel({
551
- lastFetch,
552
- length,
553
- requests,
554
- }, error);
555
- queue.pushError(error);
556
- });
557
-
558
- return queue;
531
+ let requests = 0;
532
+ let lastFetch: number | undefined;
533
+ let length = 0;
534
+ const queue = new Queue<ISequencedDocumentMessage[]>();
535
+
536
+ const propsTotal: ITelemetryProperties = {
537
+ fromTotal,
538
+ toTotal,
539
+ };
540
+
541
+ const telemetryEvent = PerformanceEvent.start(logger, {
542
+ eventName: "GetDeltas",
543
+ ...propsTotal,
544
+ reason: scenarioName,
545
+ });
546
+
547
+ const manager = new ParallelRequests<ISequencedDocumentMessage>(
548
+ fromTotal,
549
+ toTotal,
550
+ payloadSize,
551
+ logger,
552
+ async (
553
+ request: number,
554
+ from: number,
555
+ to: number,
556
+ strongTo: boolean,
557
+ propsPerRequest: ITelemetryProperties,
558
+ ) => {
559
+ requests++;
560
+ return getSingleOpBatch(
561
+ async (propsAll) => get(from, to, propsAll),
562
+ { request, from, to, ...propsTotal, ...propsPerRequest },
563
+ strongTo,
564
+ logger,
565
+ signal,
566
+ scenarioName,
567
+ );
568
+ },
569
+ (deltas: ISequencedDocumentMessage[]) => {
570
+ // Assert continuing and right start.
571
+ if (lastFetch === undefined) {
572
+ assert(deltas[0].sequenceNumber === fromTotal, 0x26d /* "wrong start" */);
573
+ } else {
574
+ assert(deltas[0].sequenceNumber === lastFetch + 1, 0x26e /* "wrong start" */);
575
+ }
576
+ lastFetch = deltas[deltas.length - 1].sequenceNumber;
577
+ assert(
578
+ lastFetch - deltas[0].sequenceNumber + 1 === deltas.length,
579
+ 0x26f /* "continuous and no duplicates" */,
580
+ );
581
+ length += deltas.length;
582
+ queue.pushValue(deltas);
583
+ },
584
+ );
585
+
586
+ // Implement faster cancellation. getSingleOpBatch() checks signal, but only in between
587
+ // waits (up to 10 seconds) and fetches (can take infinite amount of time).
588
+ // While every such case should be improved and take into account signal (and thus cancel immediately),
589
+ // it is beneficial to have catch-all
590
+ const listener = (event: Event) => {
591
+ manager.cancel();
592
+ };
593
+ if (signal !== undefined) {
594
+ signal.addEventListener("abort", listener);
595
+ }
596
+
597
+ manager
598
+ .run(concurrency)
599
+ .finally(() => {
600
+ if (signal !== undefined) {
601
+ signal.removeEventListener("abort", listener);
602
+ }
603
+ })
604
+ .then(() => {
605
+ const props = {
606
+ lastFetch,
607
+ length,
608
+ requests,
609
+ };
610
+ if (manager.canceled) {
611
+ telemetryEvent.cancel({ ...props, error: "ops request cancelled by client" });
612
+ } else {
613
+ assert(
614
+ toTotal === undefined || (lastFetch !== undefined && lastFetch >= toTotal - 1),
615
+ 0x270 /* "All requested ops fetched" */,
616
+ );
617
+ telemetryEvent.end(props);
618
+ }
619
+ queue.pushDone();
620
+ })
621
+ .catch((error) => {
622
+ telemetryEvent.cancel(
623
+ {
624
+ lastFetch,
625
+ length,
626
+ requests,
627
+ },
628
+ error,
629
+ );
630
+ queue.pushError(error);
631
+ });
632
+
633
+ return queue;
559
634
  }
560
635
 
561
636
  export const emptyMessageStream: IStream<ISequencedDocumentMessage[]> = {
562
- read: async () => { return { done: true }; },
637
+ read: async () => {
638
+ return { done: true };
639
+ },
563
640
  };
564
641
 
565
- export function streamFromMessages(messagesArg: Promise<ISequencedDocumentMessage[]>):
566
- IStream<ISequencedDocumentMessage[]> {
567
- let messages: Promise<ISequencedDocumentMessage[]> | undefined = messagesArg;
568
- return {
569
- read: async () => {
570
- if (messages === undefined) {
571
- return { done: true };
572
- }
573
- const value = await messages;
574
- messages = undefined;
575
- return value.length === 0 ? { done: true } : { done: false, value };
576
- },
577
- };
642
+ export function streamFromMessages(
643
+ messagesArg: Promise<ISequencedDocumentMessage[]>,
644
+ ): IStream<ISequencedDocumentMessage[]> {
645
+ let messages: Promise<ISequencedDocumentMessage[]> | undefined = messagesArg;
646
+ return {
647
+ read: async () => {
648
+ if (messages === undefined) {
649
+ return { done: true };
650
+ }
651
+ const value = await messages;
652
+ messages = undefined;
653
+ return value.length === 0 ? { done: true } : { done: false, value };
654
+ },
655
+ };
578
656
  }
579
657
 
580
- export function streamObserver<T>(stream: IStream<T>, handler: (value: IStreamResult<T>) => void): IStream<T> {
581
- return {
582
- read: async () => {
583
- const value = await stream.read();
584
- handler(value);
585
- return value;
586
- },
587
- };
658
+ export function streamObserver<T>(
659
+ stream: IStream<T>,
660
+ handler: (value: IStreamResult<T>) => void,
661
+ ): IStream<T> {
662
+ return {
663
+ read: async () => {
664
+ const value = await stream.read();
665
+ handler(value);
666
+ return value;
667
+ },
668
+ };
588
669
  }