1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 | 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 32x 22x 22x 22x 22x 22x 22x 22x 22x 22x 1x 1x 1x 1x 1x 22x 22x 22x 22x 22x 22x 3x 3x 3x 3x 22x 3x 27x 27x 27x 6x 3x 3x 3x 3x 21x 27x 27x 27x 18x 18x 7x 7x 2x 2x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 3x 3x 3x 3x 3x 21x 21x 14x 14x 14x 14x 6x 6x 6x 6x 3x 9x 9x 9x 9x 3x 28x 28x 7x 7x 7x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 7x 7x 7x 7x 1x 1x 1x 7x 7x 7x 3x 3x 3x 3x 3x 34x 34x 3x 34x 38x 38x 23x 1x 26x 26x 26x 18x 18x 15x 3x 3x 3x 3x 2x 1x 2x 26x 26x 20x 20x 5x 15x 15x 15x 2x 20x 3x 2x 1x 20x 20x 20x 5x 15x 3x 2x 3x 3x 15x 15x 3x 2x 28x 28x 28x 28x 41x 3x 28x 28x 28x 7x 7x 8x 8x 8x 13x 13x 28x 15x 15x 3x 56x 56x 43x 24x 43x 10x 7x 10x 3x 3x 3x 3x 3x 2x 2x 2x 2x 3x 3x 2x 2x 2x 2x 3x 8x 7x 7x 7x 7x 3x | /** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Defines types for interacting with blob transfer tasks. */ import { AuthWrapper } from './implementation/authwrapper'; import { FbsBlob } from './implementation/blob'; import { FirebaseStorageError } from './implementation/error'; import { InternalTaskState } from './implementation/taskenums'; import { Metadata } from './metadata'; import { NextFn, ErrorFn, CompleteFn, Unsubscribe, Observer } from './implementation/observer'; import { Request } from './implementation/request'; import * as RequestExports from './implementation/request'; import { Subscribe } from './implementation/observer'; import { TaskEvent, TaskState } from './implementation/taskenums'; import { UploadTaskSnapshot } from './tasksnapshot'; import * as fbsArgs from './implementation/args'; import { ArgSpec } from './implementation/args'; import * as fbsArray from './implementation/array'; import { async as fbsAsync } from './implementation/async'; import { errors as fbsErrors } from './implementation/error'; import * as errors from './implementation/error'; import { Location } from './implementation/location'; import * as fbsMetadata from './implementation/metadata'; import * as fbsPromiseimpl from './implementation/promise_external'; import { RequestInfo } from './implementation/requestinfo'; import * as fbsRequests from './implementation/requests'; import * as fbsTaskEnums from './implementation/taskenums'; import * as typeUtils from './implementation/type'; import { Reference } from './reference'; /** * Represents a blob being uploaded. Can be used to pause/resume/cancel the * upload and manage callbacks for various events. */ export class UploadTask { private ref_: Reference; private authWrapper_: AuthWrapper; private location_: Location; private blob_: FbsBlob; private metadata_: Metadata | null; private mappings_: fbsMetadata.Mappings; private transferred_: number = 0; private needToFetchStatus_: boolean = false; private needToFetchMetadata_: boolean = false; private observers_: Observer<UploadTaskSnapshot>[] = []; private resumable_: boolean; private state_: InternalTaskState; private error_: Error | null = null; private uploadUrl_: string | null = null; private request_: Request<any> | null = null; private chunkMultiplier_: number = 1; private errorHandler_: (p1: FirebaseStorageError) => void; private metadataErrorHandler_: (p1: FirebaseStorageError) => void; private resolve_: ((p1: UploadTaskSnapshot) => void) | null = null; private reject_: ((p1: Error) => void) | null = null; private promise_: Promise<UploadTaskSnapshot>; /** * @param ref The firebaseStorage.Reference object this task came * from, untyped to avoid cyclic dependencies. * @param blob The blob to upload. */ constructor( ref: Reference, authWrapper: AuthWrapper, location: Location, mappings: fbsMetadata.Mappings, blob: FbsBlob, metadata: Metadata | null = null ) { this.ref_ = ref; this.authWrapper_ = authWrapper; this.location_ = location; this.blob_ = blob; this.metadata_ = metadata; this.mappings_ = mappings; this.resumable_ = this.shouldDoResumable_(this.blob_); this.state_ = InternalTaskState.RUNNING; this.errorHandler_ = error => { this.request_ = null; this.chunkMultiplier_ = 1; Iif (error.codeEquals(errors.Code.CANCELED)) { this.needToFetchStatus_ = true; this.completeTransitions_(); } else { this.error_ = error; this.transition_(InternalTaskState.ERROR); } }; this.metadataErrorHandler_ = error => { this.request_ = null; if (error.codeEquals(errors.Code.CANCELED)) { this.completeTransitions_(); } else { this.error_ = error; this.transition_(InternalTaskState.ERROR); } }; this.promise_ = fbsPromiseimpl.make((resolve, reject) => { this.resolve_ = resolve; this.reject_ = reject; this.start_(); }); // Prevent uncaught rejections on the internal promise from bubbling out // to the top level with a dummy handler. this.promise_.then(null, () => {}); } private makeProgressCallback_(): (p1: number, p2: number) => void { const sizeBefore = this.transferred_; return (loaded, total) => { this.updateProgress_(sizeBefore + loaded); }; } private shouldDoResumable_(blob: FbsBlob): boolean { return blob.size() > 256 * 1024; } private start_() { Iif (this.state_ !== InternalTaskState.RUNNING) { // This can happen if someone pauses us in a resume callback, for example. return; } Iif (this.request_ !== null) { return; } if (this.resumable_) { if (this.uploadUrl_ === null) { this.createResumable_(); } else { Iif (this.needToFetchStatus_) { this.fetchStatus_(); } else { Iif (this.needToFetchMetadata_) { // Happens if we miss the metadata on upload completion. this.fetchMetadata_(); } else { this.continueUpload_(); } } } } else { this.oneShotUpload_(); } } private resolveToken_(callback: (p1: string | null) => void) { this.authWrapper_.getAuthToken().then(authToken => { switch (this.state_) { case InternalTaskState.RUNNING: callback(authToken); break; case InternalTaskState.CANCELING: this.transition_(InternalTaskState.CANCELED); break; case InternalTaskState.PAUSING: this.transition_(InternalTaskState.PAUSED); break; default: } }); } // TODO(andysoto): assert false private createResumable_() { this.resolveToken_(authToken => { const requestInfo = fbsRequests.createResumableUpload( this.authWrapper_, this.location_, this.mappings_, this.blob_, this.metadata_ ); const createRequest = this.authWrapper_.makeRequest( requestInfo, authToken ); this.request_ = createRequest; createRequest.getPromise().then((url: string) => { this.request_ = null; this.uploadUrl_ = url; this.needToFetchStatus_ = false; this.completeTransitions_(); }, this.errorHandler_); }); } private fetchStatus_() { // TODO(andysoto): assert(this.uploadUrl_ !== null); const url = this.uploadUrl_ as string; this.resolveToken_(authToken => { const requestInfo = fbsRequests.getResumableUploadStatus( this.authWrapper_, this.location_, url, this.blob_ ); const statusRequest = this.authWrapper_.makeRequest( requestInfo, authToken ); this.request_ = statusRequest; statusRequest.getPromise().then(status => { status = status as fbsRequests.ResumableUploadStatus; this.request_ = null; this.updateProgress_(status.current); this.needToFetchStatus_ = false; if (status.finalized) { this.needToFetchMetadata_ = true; } this.completeTransitions_(); }, this.errorHandler_); }); } private continueUpload_() { const chunkSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_; const status = new fbsRequests.ResumableUploadStatus( this.transferred_, this.blob_.size() ); // TODO(andysoto): assert(this.uploadUrl_ !== null); const url = this.uploadUrl_ as string; this.resolveToken_(authToken => { let requestInfo; try { requestInfo = fbsRequests.continueResumableUpload( this.location_, this.authWrapper_, url, this.blob_, chunkSize, this.mappings_, status, this.makeProgressCallback_() ); } catch (e) { this.error_ = e; this.transition_(InternalTaskState.ERROR); return; } const uploadRequest = this.authWrapper_.makeRequest( requestInfo, authToken ); this.request_ = uploadRequest; uploadRequest .getPromise() .then((newStatus: fbsRequests.ResumableUploadStatus) => { this.increaseMultiplier_(); this.request_ = null; this.updateProgress_(newStatus.current); if (newStatus.finalized) { this.metadata_ = newStatus.metadata; this.transition_(InternalTaskState.SUCCESS); } else { this.completeTransitions_(); } }, this.errorHandler_); }); } private increaseMultiplier_() { const currentSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_; // Max chunk size is 32M. Eif (currentSize < 32 * 1024 * 1024) { this.chunkMultiplier_ *= 2; } } private fetchMetadata_() { this.resolveToken_(authToken => { const requestInfo = fbsRequests.getMetadata( this.authWrapper_, this.location_, this.mappings_ ); const metadataRequest = this.authWrapper_.makeRequest( requestInfo, authToken ); this.request_ = metadataRequest; metadataRequest.getPromise().then(metadata => { this.request_ = null; this.metadata_ = metadata; this.transition_(InternalTaskState.SUCCESS); }, this.metadataErrorHandler_); }); } private oneShotUpload_() { this.resolveToken_(authToken => { const requestInfo = fbsRequests.multipartUpload( this.authWrapper_, this.location_, this.mappings_, this.blob_, this.metadata_ ); const multipartRequest = this.authWrapper_.makeRequest( requestInfo, authToken ); this.request_ = multipartRequest; multipartRequest.getPromise().then(metadata => { this.request_ = null; this.metadata_ = metadata; this.updateProgress_(this.blob_.size()); this.transition_(InternalTaskState.SUCCESS); }, this.errorHandler_); }); } private updateProgress_(transferred: number) { const old = this.transferred_; this.transferred_ = transferred; // A progress update can make the "transferred" value smaller (e.g. a // partial upload not completed by server, after which the "transferred" // value may reset to the value at the beginning of the request). Eif (this.transferred_ !== old) { this.notifyObservers_(); } } private transition_(state: InternalTaskState) { Iif (this.state_ === state) { return; } switch (state) { case InternalTaskState.CANCELING: // TODO(andysoto): // assert(this.state_ === InternalTaskState.RUNNING || // this.state_ === InternalTaskState.PAUSING); this.state_ = state; Iif (this.request_ !== null) { this.request_.cancel(); } break; case InternalTaskState.PAUSING: // TODO(andysoto): // assert(this.state_ === InternalTaskState.RUNNING); this.state_ = state; Iif (this.request_ !== null) { this.request_.cancel(); } break; case InternalTaskState.RUNNING: // TODO(andysoto): // assert(this.state_ === InternalTaskState.PAUSED || // this.state_ === InternalTaskState.PAUSING); const wasPaused = this.state_ === InternalTaskState.PAUSED; this.state_ = state; Eif (wasPaused) { this.notifyObservers_(); this.start_(); } break; case InternalTaskState.PAUSED: // TODO(andysoto): // assert(this.state_ === InternalTaskState.PAUSING); this.state_ = state; this.notifyObservers_(); break; case InternalTaskState.CANCELED: // TODO(andysoto): // assert(this.state_ === InternalTaskState.PAUSED || // this.state_ === InternalTaskState.CANCELING); this.error_ = errors.canceled(); this.state_ = state; this.notifyObservers_(); break; case InternalTaskState.ERROR: // TODO(andysoto): // assert(this.state_ === InternalTaskState.RUNNING || // this.state_ === InternalTaskState.PAUSING || // this.state_ === InternalTaskState.CANCELING); this.state_ = state; this.notifyObservers_(); break; case InternalTaskState.SUCCESS: // TODO(andysoto): // assert(this.state_ === InternalTaskState.RUNNING || // this.state_ === InternalTaskState.PAUSING || // this.state_ === InternalTaskState.CANCELING); this.state_ = state; this.notifyObservers_(); break; } } private completeTransitions_() { switch (this.state_) { case InternalTaskState.PAUSING: this.transition_(InternalTaskState.PAUSED); break; case InternalTaskState.CANCELING: this.transition_(InternalTaskState.CANCELED); break; case InternalTaskState.RUNNING: this.start_(); break; default: // TODO(andysoto): assert(false); break; } } get snapshot(): UploadTaskSnapshot { const externalState = fbsTaskEnums.taskStateFromInternalTaskState( this.state_ ); return new UploadTaskSnapshot( this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_ ); } /** * Adds a callback for an event. * @param type The type of event to listen for. */ on( type: TaskEvent, nextOrObserver = undefined, error = undefined, completed = undefined ): Unsubscribe | Subscribe<UploadTaskSnapshot> { function typeValidator(_p: any) { if (type !== TaskEvent.STATE_CHANGED) { throw `Expected one of the event types: [${TaskEvent.STATE_CHANGED}].`; } } const nextOrObserverMessage = 'Expected a function or an Object with one of ' + '`next`, `error`, `complete` properties.'; const nextValidator = fbsArgs.nullFunctionSpec(true).validator; const observerValidator = fbsArgs.looseObjectSpec(null, true).validator; function nextOrObserverValidator(p: any) { try { nextValidator(p); return; } catch (e) {} try { observerValidator(p); const anyDefined = typeUtils.isJustDef(p['next']) || typeUtils.isJustDef(p['error']) || typeUtils.isJustDef(p['complete']); if (!anyDefined) { throw ''; } return; } catch (e) { throw nextOrObserverMessage; } } const specs = [ fbsArgs.stringSpec(typeValidator), fbsArgs.looseObjectSpec(nextOrObserverValidator, true), fbsArgs.nullFunctionSpec(true), fbsArgs.nullFunctionSpec(true) ]; fbsArgs.validate('on', specs, arguments); const self = this; function makeBinder( specs: ArgSpec[] | null ): Subscribe<UploadTaskSnapshot> { function binder( nextOrObserver: | NextFn<UploadTaskSnapshot> | { [name: string]: string | null } | null, error?: ErrorFn | null, opt_complete?: CompleteFn | null ) { if (specs !== null) { fbsArgs.validate('on', specs, arguments); } const observer = new Observer(nextOrObserver, error, completed); self.addObserver_(observer); return () => { self.removeObserver_(observer); }; } return binder; } function binderNextOrObserverValidator(p: any) { if (p === null) { throw nextOrObserverMessage; } nextOrObserverValidator(p); } const binderSpecs = [ fbsArgs.looseObjectSpec(binderNextOrObserverValidator), fbsArgs.nullFunctionSpec(true), fbsArgs.nullFunctionSpec(true) ]; const typeOnly = !( typeUtils.isJustDef(nextOrObserver) || typeUtils.isJustDef(error) || typeUtils.isJustDef(completed) ); if (typeOnly) { return makeBinder(binderSpecs); } else { return makeBinder(null)(nextOrObserver, error, completed); } } /** * This object behaves like a Promise, and resolves with its snapshot data * when the upload completes. * @param onFulfilled The fulfillment callback. Promise chaining works as normal. * @param onRejected The rejection callback. */ then<U>( onFulfilled?: ((value: UploadTaskSnapshot) => U | Promise<U>) | null, onRejected?: ((error: any) => U | Promise<U>) | null ): Promise<U> { // These casts are needed so that TypeScript can infer the types of the // resulting Promise. return this.promise_.then<U>( onFulfilled as (value: UploadTaskSnapshot) => U | Promise<U>, onRejected as ((error: any) => Promise<never>) | null ); } /** * Equivalent to calling `then(null, onRejected)`. */ catch<T>(onRejected: (p1: Error) => T | Promise<T>): Promise<T> { return this.then(null, onRejected); } /** * Adds the given observer. */ private addObserver_(observer: Observer<UploadTaskSnapshot>) { this.observers_.push(observer); this.notifyObserver_(observer); } /** * Removes the given observer. */ private removeObserver_(observer: Observer<UploadTaskSnapshot>) { fbsArray.remove(this.observers_, observer); } private notifyObservers_() { this.finishPromise_(); const observers = fbsArray.clone(this.observers_); observers.forEach(observer => { this.notifyObserver_(observer); }); } private finishPromise_() { Eif (this.resolve_ !== null) { let triggered = true; switch (fbsTaskEnums.taskStateFromInternalTaskState(this.state_)) { case TaskState.SUCCESS: fbsAsync(this.resolve_.bind(null, this.snapshot))(); break; case TaskState.CANCELED: case TaskState.ERROR: const toCall = this.reject_ as ((p1: Error) => void); fbsAsync(toCall.bind(null, this.error_ as Error))(); break; default: triggered = false; break; } if (triggered) { this.resolve_ = null; this.reject_ = null; } } } private notifyObserver_(observer: Observer<UploadTaskSnapshot>) { const externalState = fbsTaskEnums.taskStateFromInternalTaskState( this.state_ ); switch (externalState) { case TaskState.RUNNING: case TaskState.PAUSED: if (observer.next !== null) { fbsAsync(observer.next.bind(observer, this.snapshot))(); } break; case TaskState.SUCCESS: if (observer.complete !== null) { fbsAsync(observer.complete.bind(observer))(); } break; case TaskState.CANCELED: case TaskState.ERROR: Eif (observer.error !== null) { fbsAsync(observer.error.bind(observer, this.error_ as Error))(); } break; default: // TODO(andysoto): assert(false); if (observer.error !== null) { fbsAsync(observer.error.bind(observer, this.error_ as Error))(); } } } /** * Resumes a paused task. Has no effect on a currently running or failed task. * @return True if the operation took effect, false if ignored. */ resume(): boolean { fbsArgs.validate('resume', [], arguments); const valid = this.state_ === InternalTaskState.PAUSED || this.state_ === InternalTaskState.PAUSING; Eif (valid) { this.transition_(InternalTaskState.RUNNING); } return valid; } /** * Pauses a currently running task. Has no effect on a paused or failed task. * @return True if the operation took effect, false if ignored. */ pause(): boolean { fbsArgs.validate('pause', [], arguments); const valid = this.state_ === InternalTaskState.RUNNING; Eif (valid) { this.transition_(InternalTaskState.PAUSING); } return valid; } /** * Cancels a currently running or paused task. Has no effect on a complete or * failed task. * @return True if the operation took effect, false if ignored. */ cancel(): boolean { fbsArgs.validate('cancel', [], arguments); const valid = this.state_ === InternalTaskState.RUNNING || this.state_ === InternalTaskState.PAUSING; Eif (valid) { this.transition_(InternalTaskState.CANCELING); } return valid; } } |