OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library async.stream_events; |
| 6 |
| 7 import 'dart:async'; |
| 8 import 'dart:collection'; |
| 9 |
| 10 import "subscription_stream.dart"; |
| 11 import "stream_completer.dart"; |
| 12 import "../result.dart"; |
| 13 |
| 14 /// An asynchronous pull-based interface for accessing stream events. |
| 15 /// |
| 16 /// Wraps a stream and makes individual events available on request. |
| 17 /// |
| 18 /// You can request (and reserve) one or more events from the stream, |
| 19 /// and after all previous requests have been fulfilled, stream events |
| 20 /// go towards fulfilling your request. |
| 21 /// |
| 22 /// For example, if you ask for [next] two times, the returned futures |
| 23 /// will be completed by the next two unrequested events from the stream. |
| 24 /// |
| 25 /// The stream subscription is paused when there are no active |
| 26 /// requests. |
| 27 /// |
| 28 /// Some streams, including broadcast streams, will buffer |
| 29 /// events while paused, so waiting too long between requests may |
| 30 /// cause memory bloat somewhere else. |
| 31 /// |
| 32 /// This is similar to, but more convenient than, a [StreamIterator]. |
| 33 /// A `StreamIterator` requires you to manually check when a new event is |
| 34 /// available and you can only access the value of that event until you |
| 35 /// check for the next one. A `StreamQueue` allows you to request, for example, |
| 36 /// three events at a time, either individually, as a group using [take] |
| 37 /// or [skip], or in any combination. |
| 38 /// |
| 39 /// You can also ask to have the [rest] of the stream provided as |
| 40 /// a new stream. This allows, for example, taking the first event |
| 41 /// out of a stream and continuing to use the rest of the stream as a stream. |
| 42 /// |
| 43 /// Example: |
| 44 /// |
| 45 /// var events = new StreamQueue<String>(someStreamOfLines); |
| 46 /// var first = await events.next; |
| 47 /// while (first.startsWith('#')) { |
| 48 /// // Skip comments. |
| 49 /// first = await events.next; |
| 50 /// } |
| 51 /// |
| 52 /// if (first.startsWith(MAGIC_MARKER)) { |
| 53 /// var headerCount = |
| 54 /// first.parseInt(first.substring(MAGIC_MARKER.length + 1)); |
| 55 /// handleMessage(headers: await events.take(headerCount), |
| 56 /// body: events.rest); |
| 57 /// return; |
| 58 /// } |
| 59 /// // Error handling. |
| 60 /// |
| 61 /// When you need no further events the `StreamQueue` should be closed |
| 62 /// using [cancel]. This releases the underlying stream subscription. |
| 63 class StreamQueue<T> { |
| 64 // This class maintains two queues: one of events and one of requests. |
| 65 // The active request (the one in front of the queue) is called with |
| 66 // the current event queue when it becomes active. |
| 67 // |
| 68 // If the request returns true, it's complete and will be removed from the |
| 69 // request queue. |
| 70 // If the request returns false, it needs more events, and will be called |
| 71 // again when new events are available. |
| 72 // The request can remove events that it uses, or keep them in the event |
| 73 // queue until it has all that it needs. |
| 74 // |
| 75 // This model is very flexible and easily extensible. |
| 76 // It allows requests that don't consume events (like [hasNext]) or |
| 77 // potentially a request that takes either five or zero events, determined |
| 78 // by the content of the fifth event. |
| 79 |
| 80 /// Source of events. |
| 81 final Stream _sourceStream; |
| 82 |
| 83 /// Subscription on [_sourceStream] while listening for events. |
| 84 /// |
| 85 /// Set to subscription when listening, and set to `null` when the |
| 86 /// subscription is done (and [_isDone] is set to true). |
| 87 StreamSubscription _subscription; |
| 88 |
| 89 /// Whether we have listened on [_sourceStream] and the subscription is done. |
| 90 bool _isDone = false; |
| 91 |
| 92 /// Whether a closing operation has been performed on the stream queue. |
| 93 /// |
| 94 /// Closing operations are [cancel] and [rest]. |
| 95 bool _isClosed = false; |
| 96 |
| 97 /// Queue of events not used by a request yet. |
| 98 final Queue<Result> _eventQueue = new Queue(); |
| 99 |
| 100 /// Queue of pending requests. |
| 101 /// |
| 102 /// Access through methods below to ensure consistency. |
| 103 final Queue<_EventRequest> _requestQueue = new Queue(); |
| 104 |
| 105 /// Create a `StreamQueue` of the events of [source]. |
| 106 StreamQueue(Stream source) |
| 107 : _sourceStream = source; |
| 108 |
| 109 /// Asks if the stream has any more events. |
| 110 /// |
| 111 /// Returns a future that completes with `true` if the stream has any |
| 112 /// more events, whether data or error. |
| 113 /// If the stream closes without producing any more events, the returned |
| 114 /// future completes with `false`. |
| 115 /// |
| 116 /// Can be used before using [next] to avoid getting an error in the |
| 117 /// future returned by `next` in the case where there are no more events. |
| 118 Future<bool> get hasNext { |
| 119 if (!_isClosed) { |
| 120 var hasNextRequest = new _HasNextRequest(); |
| 121 _addRequest(hasNextRequest); |
| 122 return hasNextRequest.future; |
| 123 } |
| 124 throw _failClosed(); |
| 125 } |
| 126 |
| 127 /// Requests the next (yet unrequested) event from the stream. |
| 128 /// |
| 129 /// When the requested event arrives, the returned future is completed with |
| 130 /// the event. |
| 131 /// If the event is a data event, the returned future completes |
| 132 /// with its value. |
| 133 /// If the event is an error event, the returned future completes with |
| 134 /// its error and stack trace. |
| 135 /// If the stream closes before an event arrives, the returned future |
| 136 /// completes with a [StateError]. |
| 137 /// |
| 138 /// It's possible to have several pending [next] calls (or other requests), |
| 139 /// and they will be completed in the order they were requested, by the |
| 140 /// first events that were not consumed by previous requeusts. |
| 141 Future<T> get next { |
| 142 if (!_isClosed) { |
| 143 var nextRequest = new _NextRequest<T>(); |
| 144 _addRequest(nextRequest); |
| 145 return nextRequest.future; |
| 146 } |
| 147 throw _failClosed(); |
| 148 } |
| 149 |
| 150 /// Returns a stream of all the remaning events of the source stream. |
| 151 /// |
| 152 /// All requested [next], [skip] or [take] operations are completed |
| 153 /// first, and then any remaining events are provided as events of |
| 154 /// the returned stream. |
| 155 /// |
| 156 /// Using `rest` closes this stream queue. After getting the |
| 157 /// `rest` the caller may no longer request other events, like |
| 158 /// after calling [cancel]. |
| 159 Stream<T> get rest { |
| 160 if (_isClosed) { |
| 161 throw _failClosed(); |
| 162 } |
| 163 var request = new _RestRequest<T>(this); |
| 164 _isClosed = true; |
| 165 _addRequest(request); |
| 166 return request.stream; |
| 167 } |
| 168 |
| 169 /// Skips the next [count] *data* events. |
| 170 /// |
| 171 /// The [count] must be non-negative. |
| 172 /// |
| 173 /// When successful, this is equivalent to using [take] |
| 174 /// and ignoring the result. |
| 175 /// |
| 176 /// If an error occurs before `count` data events have been skipped, |
| 177 /// the returned future completes with that error instead. |
| 178 /// |
| 179 /// If the stream closes before `count` data events, |
| 180 /// the remaining unskipped event count is returned. |
| 181 /// If the returned future completes with the integer `0`, |
| 182 /// then all events were succssfully skipped. If the value |
| 183 /// is greater than zero then the stream ended early. |
| 184 Future<int> skip(int count) { |
| 185 if (count < 0) throw new RangeError.range(count, 0, null, "count"); |
| 186 if (!_isClosed) { |
| 187 var request = new _SkipRequest(count); |
| 188 _addRequest(request); |
| 189 return request.future; |
| 190 } |
| 191 throw _failClosed(); |
| 192 } |
| 193 |
| 194 /// Requests the next [count] data events as a list. |
| 195 /// |
| 196 /// The [count] must be non-negative. |
| 197 /// |
| 198 /// Equivalent to calling [next] `count` times and |
| 199 /// storing the data values in a list. |
| 200 /// |
| 201 /// If an error occurs before `count` data events has |
| 202 /// been collected, the returned future completes with |
| 203 /// that error instead. |
| 204 /// |
| 205 /// If the stream closes before `count` data events, |
| 206 /// the returned future completes with the list |
| 207 /// of data collected so far. That is, the returned |
| 208 /// list may have fewer than [count] elements. |
| 209 Future<List<T>> take(int count) { |
| 210 if (count < 0) throw new RangeError.range(count, 0, null, "count"); |
| 211 if (!_isClosed) { |
| 212 var request = new _TakeRequest<T>(count); |
| 213 _addRequest(request); |
| 214 return request.future; |
| 215 } |
| 216 throw _failClosed(); |
| 217 } |
| 218 |
| 219 /// Cancels the underlying stream subscription. |
| 220 /// |
| 221 /// If [immediate] is `false` (the default), the cancel operation waits until |
| 222 /// all previously requested events have been processed, then it cancels the |
| 223 /// subscription providing the events. |
| 224 /// |
| 225 /// If [immediate] is `true`, the subscription is instead canceled |
| 226 /// immediately. Any pending events complete with a 'closed'-event, as though |
| 227 /// the stream had closed by itself. |
| 228 /// |
| 229 /// The returned future completes with the result of calling |
| 230 /// `cancel`. |
| 231 /// |
| 232 /// After calling `cancel`, no further events can be requested. |
| 233 /// None of [next], [rest], [skip], [take] or [cancel] may be |
| 234 /// called again. |
| 235 Future cancel({bool immediate: false}) { |
| 236 if (_isClosed) throw _failClosed(); |
| 237 _isClosed = true; |
| 238 |
| 239 if (!immediate) { |
| 240 var request = new _CancelRequest(this); |
| 241 _addRequest(request); |
| 242 return request.future; |
| 243 } |
| 244 |
| 245 if (_isDone) return new Future.value(); |
| 246 if (_subscription == null) _subscription = _sourceStream.listen(null); |
| 247 var future = _subscription.cancel(); |
| 248 _onDone(); |
| 249 return future; |
| 250 } |
| 251 |
| 252 /// Returns an error for when a request is made after cancel. |
| 253 /// |
| 254 /// Returns a [StateError] with a message saying that either |
| 255 /// [cancel] or [rest] have already been called. |
| 256 Error _failClosed() { |
| 257 return new StateError("Already cancelled"); |
| 258 } |
| 259 |
| 260 // Callbacks receiving the events of the source stream. |
| 261 |
| 262 void _onData(T data) { |
| 263 _eventQueue.add(new Result.value(data)); |
| 264 _checkQueues(); |
| 265 } |
| 266 |
| 267 void _onError(error, StackTrace stack) { |
| 268 _eventQueue.add(new Result.error(error, stack)); |
| 269 _checkQueues(); |
| 270 } |
| 271 |
| 272 void _onDone() { |
| 273 _subscription = null; |
| 274 _isDone = true; |
| 275 _closeAllRequests(); |
| 276 } |
| 277 |
| 278 // Request queue management. |
| 279 |
| 280 /// Adds a new request to the queue. |
| 281 void _addRequest(_EventRequest request) { |
| 282 if (_isDone) { |
| 283 assert(_requestQueue.isEmpty); |
| 284 if (!request.addEvents(_eventQueue)) { |
| 285 request.close(_eventQueue); |
| 286 } |
| 287 return; |
| 288 } |
| 289 if (_requestQueue.isEmpty) { |
| 290 if (request.addEvents(_eventQueue)) return; |
| 291 _ensureListening(); |
| 292 } |
| 293 _requestQueue.add(request); |
| 294 } |
| 295 |
| 296 /// Ensures that we are listening on events from [_sourceStream]. |
| 297 /// |
| 298 /// Resumes subscription on [_sourceStream], or creates it if necessary. |
| 299 void _ensureListening() { |
| 300 assert(!_isDone); |
| 301 if (_subscription == null) { |
| 302 _subscription = |
| 303 _sourceStream.listen(_onData, onError: _onError, onDone: _onDone); |
| 304 } else { |
| 305 _subscription.resume(); |
| 306 } |
| 307 } |
| 308 |
| 309 /// Removes all requests and closes them. |
| 310 /// |
| 311 /// Used when the source stream is done. |
| 312 /// After this, no further requests will be added to the queue, |
| 313 /// requests are immediately served entirely by events already in the event |
| 314 /// queue, if any. |
| 315 void _closeAllRequests() { |
| 316 assert(_isDone); |
| 317 while (_requestQueue.isNotEmpty) { |
| 318 var request = _requestQueue.removeFirst(); |
| 319 if (!request.addEvents(_eventQueue)) { |
| 320 request.close(_eventQueue); |
| 321 } |
| 322 } |
| 323 } |
| 324 |
| 325 /// Matches events with requests. |
| 326 /// |
| 327 /// Called after receiving an event. |
| 328 void _checkQueues() { |
| 329 while (_requestQueue.isNotEmpty) { |
| 330 if (_requestQueue.first.addEvents(_eventQueue)) { |
| 331 _requestQueue.removeFirst(); |
| 332 } else { |
| 333 return; |
| 334 } |
| 335 } |
| 336 if (!_isDone) { |
| 337 _subscription.pause(); |
| 338 } |
| 339 } |
| 340 |
| 341 /// Extracts the subscription and makes this stream queue unusable. |
| 342 /// |
| 343 /// Can only be used by the very last request. |
| 344 StreamSubscription _dispose() { |
| 345 assert(_isClosed); |
| 346 var subscription = _subscription; |
| 347 _subscription = null; |
| 348 _isDone = true; |
| 349 return subscription; |
| 350 } |
| 351 } |
| 352 |
| 353 /// Request object that receives events when they arrive, until fulfilled. |
| 354 /// |
| 355 /// Each request that cannot be fulfilled immediately is represented by |
| 356 /// an `_EventRequest` object in the request queue. |
| 357 /// |
| 358 /// Events from the source stream are sent to the first request in the |
| 359 /// queue until it reports itself as [isComplete]. |
| 360 /// |
| 361 /// When the first request in the queue `isComplete`, either when becoming |
| 362 /// the first request or after receiving an event, its [close] methods is |
| 363 /// called. |
| 364 /// |
| 365 /// The [close] method is also called immediately when the source stream |
| 366 /// is done. |
| 367 abstract class _EventRequest { |
| 368 /// Handle available events. |
| 369 /// |
| 370 /// The available events are provided as a queue. The `addEvents` function |
| 371 /// should only remove events from the front of the event queue, e.g., |
| 372 /// using [removeFirst]. |
| 373 /// |
| 374 /// Returns `true` if the request is completed, or `false` if it needs |
| 375 /// more events. |
| 376 /// The call may keep events in the queue until the requeust is complete, |
| 377 /// or it may remove them immediately. |
| 378 /// |
| 379 /// If the method returns true, the request is considered fulfilled, and |
| 380 /// will never be called again. |
| 381 /// |
| 382 /// This method is called when a request reaches the front of the request |
| 383 /// queue, and if it returns `false`, it's called again every time a new event |
| 384 /// becomes available, or when the stream closes. |
| 385 bool addEvents(Queue<Result> events); |
| 386 |
| 387 /// Complete the request. |
| 388 /// |
| 389 /// This is called when the source stream is done before the request |
| 390 /// had a chance to receive all its events. That is, after a call |
| 391 /// to [addEvents] has returned `false`. |
| 392 /// If there are any unused events available, they are in the [events] queue. |
| 393 /// No further events will become available. |
| 394 /// |
| 395 /// The queue should only remove events from the front of the event queue, |
| 396 /// e.g., using [removeFirst]. |
| 397 /// |
| 398 /// If the request kept events in the queue after an [addEvents] call, |
| 399 /// this is the last chance to use them. |
| 400 void close(Queue<Result> events); |
| 401 } |
| 402 |
| 403 /// Request for a [StreamQueue.next] call. |
| 404 /// |
| 405 /// Completes the returned future when receiving the first event, |
| 406 /// and is then complete. |
| 407 class _NextRequest<T> implements _EventRequest { |
| 408 /// Completer for the future returned by [StreamQueue.next]. |
| 409 final Completer _completer; |
| 410 |
| 411 _NextRequest() : _completer = new Completer<T>(); |
| 412 |
| 413 Future<T> get future => _completer.future; |
| 414 |
| 415 bool addEvents(Queue<Result> events) { |
| 416 if (events.isEmpty) return false; |
| 417 events.removeFirst().complete(_completer); |
| 418 return true; |
| 419 } |
| 420 |
| 421 void close(Queue<Result> events) { |
| 422 var errorFuture = |
| 423 new Future.sync(() => throw new StateError("No elements")); |
| 424 _completer.complete(errorFuture); |
| 425 } |
| 426 } |
| 427 |
| 428 /// Request for a [StreamQueue.skip] call. |
| 429 class _SkipRequest implements _EventRequest { |
| 430 /// Completer for the future returned by the skip call. |
| 431 final Completer _completer = new Completer<int>(); |
| 432 |
| 433 /// Number of remaining events to skip. |
| 434 /// |
| 435 /// The request [isComplete] when the values reaches zero. |
| 436 /// |
| 437 /// Decremented when an event is seen. |
| 438 /// Set to zero when an error is seen since errors abort the skip request. |
| 439 int _eventsToSkip; |
| 440 |
| 441 _SkipRequest(this._eventsToSkip); |
| 442 |
| 443 /// The future completed when the correct number of events have been skipped. |
| 444 Future get future => _completer.future; |
| 445 |
| 446 bool addEvents(Queue<Result> events) { |
| 447 while (_eventsToSkip > 0) { |
| 448 if (events.isEmpty) return false; |
| 449 _eventsToSkip--; |
| 450 var event = events.removeFirst(); |
| 451 if (event.isError) { |
| 452 event.complete(_completer); |
| 453 return true; |
| 454 } |
| 455 } |
| 456 _completer.complete(0); |
| 457 return true; |
| 458 } |
| 459 |
| 460 void close(Queue<Result> events) { |
| 461 _completer.complete(_eventsToSkip); |
| 462 } |
| 463 } |
| 464 |
| 465 /// Request for a [StreamQueue.take] call. |
| 466 class _TakeRequest<T> implements _EventRequest { |
| 467 /// Completer for the future returned by the take call. |
| 468 final Completer _completer; |
| 469 |
| 470 /// List collecting events until enough have been seen. |
| 471 final List _list = <T>[]; |
| 472 |
| 473 /// Number of events to capture. |
| 474 /// |
| 475 /// The request [isComplete] when the length of [_list] reaches |
| 476 /// this value. |
| 477 final int _eventsToTake; |
| 478 |
| 479 _TakeRequest(this._eventsToTake) : _completer = new Completer<List<T>>(); |
| 480 |
| 481 /// The future completed when the correct number of events have been captured. |
| 482 Future get future => _completer.future; |
| 483 |
| 484 bool addEvents(Queue<Result> events) { |
| 485 while (_list.length < _eventsToTake) { |
| 486 if (events.isEmpty) return false; |
| 487 var result = events.removeFirst(); |
| 488 if (result.isError) { |
| 489 result.complete(_completer); |
| 490 return true; |
| 491 } |
| 492 _list.add(result.asValue.value); |
| 493 } |
| 494 _completer.complete(_list); |
| 495 return true; |
| 496 } |
| 497 |
| 498 void close(Queue<Result> events) { |
| 499 _completer.complete(_list); |
| 500 } |
| 501 } |
| 502 |
| 503 /// Request for a [StreamQueue.cancel] call. |
| 504 /// |
| 505 /// The request needs no events, it just waits in the request queue |
| 506 /// until all previous events are fulfilled, then it cancels the stream queue |
| 507 /// source subscription. |
| 508 class _CancelRequest implements _EventRequest { |
| 509 /// Completer for the future returned by the `cancel` call. |
| 510 final Completer _completer = new Completer(); |
| 511 |
| 512 /// The [StreamQueue] object that has this request queued. |
| 513 /// |
| 514 /// When the event is completed, it needs to cancel the active subscription |
| 515 /// of the `StreamQueue` object, if any. |
| 516 final StreamQueue _streamQueue; |
| 517 |
| 518 _CancelRequest(this._streamQueue); |
| 519 |
| 520 /// The future completed when the cancel request is completed. |
| 521 Future get future => _completer.future; |
| 522 |
| 523 bool addEvents(Queue<Result> events) { |
| 524 _shutdown(); |
| 525 return true; |
| 526 } |
| 527 |
| 528 void close(_) { |
| 529 _shutdown(); |
| 530 } |
| 531 |
| 532 void _shutdown() { |
| 533 if (_streamQueue._isDone) { |
| 534 _completer.complete(); |
| 535 } else { |
| 536 _streamQueue._ensureListening(); |
| 537 _completer.complete(_streamQueue._dispose().cancel()); |
| 538 } |
| 539 } |
| 540 } |
| 541 |
| 542 /// Request for a [StreamQueue.rest] call. |
| 543 /// |
| 544 /// The request is always complete, it just waits in the request queue |
| 545 /// until all previous events are fulfilled, then it takes over the |
| 546 /// stream events subscription and creates a stream from it. |
| 547 class _RestRequest<T> implements _EventRequest { |
| 548 /// Completer for the stream returned by the `rest` call. |
| 549 final StreamCompleter _completer = new StreamCompleter<T>(); |
| 550 |
| 551 /// The [StreamQueue] object that has this request queued. |
| 552 /// |
| 553 /// When the event is completed, it needs to cancel the active subscription |
| 554 /// of the `StreamQueue` object, if any. |
| 555 final StreamQueue _streamQueue; |
| 556 |
| 557 _RestRequest(this._streamQueue); |
| 558 |
| 559 /// The stream which will contain the remaining events of [_streamQueue]. |
| 560 Stream<T> get stream => _completer.stream; |
| 561 |
| 562 bool addEvents(Queue<Result> events) { |
| 563 _completeStream(events); |
| 564 return true; |
| 565 } |
| 566 |
| 567 void close(Queue<Result> events) { |
| 568 _completeStream(events); |
| 569 } |
| 570 |
| 571 void _completeStream(Queue<Result> events) { |
| 572 if (events.isEmpty) { |
| 573 if (_streamQueue._isDone) { |
| 574 _completer.setEmpty(); |
| 575 } else { |
| 576 _completer.setSourceStream(_getRestStream()); |
| 577 } |
| 578 } else { |
| 579 // There are prefetched events which needs to be added before the |
| 580 // remaining stream. |
| 581 var controller = new StreamController<T>(); |
| 582 for (var event in events) { |
| 583 event.addTo(controller); |
| 584 } |
| 585 controller.addStream(_getRestStream(), cancelOnError: false) |
| 586 .whenComplete(controller.close); |
| 587 _completer.setSourceStream(controller.stream); |
| 588 } |
| 589 } |
| 590 |
| 591 /// Create a stream from the rest of [_streamQueue]'s subscription. |
| 592 Stream _getRestStream() { |
| 593 if (_streamQueue._isDone) { |
| 594 var controller = new StreamController<T>()..close(); |
| 595 return controller.stream; |
| 596 // TODO(lrn). Use the following when 1.11 is released. |
| 597 // return new Stream<T>.empty(); |
| 598 } |
| 599 if (_streamQueue._subscription == null) { |
| 600 return _streamQueue._sourceStream; |
| 601 } |
| 602 var subscription = _streamQueue._dispose(); |
| 603 subscription.resume(); |
| 604 return new SubscriptionStream<T>(subscription); |
| 605 } |
| 606 } |
| 607 |
| 608 /// Request for a [StreamQueue.hasNext] call. |
| 609 /// |
| 610 /// Completes the [future] with `true` if it sees any event, |
| 611 /// but doesn't consume the event. |
| 612 /// If the request is closed without seeing an event, then |
| 613 /// the [future] is completed with `false`. |
| 614 class _HasNextRequest<T> implements _EventRequest { |
| 615 final Completer _completer = new Completer<bool>(); |
| 616 |
| 617 Future<bool> get future => _completer.future; |
| 618 |
| 619 bool addEvents(Queue<Result> events) { |
| 620 if (events.isNotEmpty) { |
| 621 _completer.complete(true); |
| 622 return true; |
| 623 } |
| 624 return false; |
| 625 } |
| 626 |
| 627 void close(_) { |
| 628 _completer.complete(false); |
| 629 } |
| 630 } |
OLD | NEW |