All files / core Repo.ts

74.43% Statements 195/262
50% Branches 37/74
65.38% Functions 34/52
76.11% Lines 188/247
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708                                12x         12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x     12x               12x         12x 43x         43x 43x 43x             43x           43x           43x             43x 43x   43x     43x   43x   43x 12x             12x   31x   31x                         31x                 31x     43x           43x   15x     43x     43x 43x   4x 4x     4x 4x       4x 4x     4x       43x   43x   295x 350x 350x     295x     129x               12x 98x               12x             12x 882x     882x 882x             12x 540x                           12x             392x 392x 392x     392x 392x 208x 9x 23x   9x           199x 199x           184x 2x 3x   2x   182x 182x   392x 392x     184x   392x               12x               12x 33x 33x 5x               16x 16x 16x                   12x 92x 92x 92x 92x 92x             12x 535x                 400x           400x               400x 400x 400x         400x 400x           400x 400x       398x 398x       398x       398x 398x     400x 400x   400x               12x         11x     11x 11x 11x 11x 27x 27x 27x           11x 11x 11x         11x 11x       11x 11x       11x         11x 11x 11x       11x 27x 27x       11x                     12x 5x   5x 5x       5x   5x               5x 5x             12x                                 12x                                               12x                                               12x                                                               12x   410x 23x         387x         410x             12x             160x           160x         160x     12x 24x 24x       12x 5x 5x       12x                                                 12x                 1125x 604x 604x 602x   604x               12x         409x 409x 409x 409x                           12x 68x   12x  
/**
 * 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.
 */
 
import {
  generateWithValues,
  resolveDeferredValueSnapshot,
  resolveDeferredValueTree
} from './util/ServerValues';
import { nodeFromJSON } from './snap/nodeFromJSON';
import { Path } from './util/Path';
import { SparseSnapshotTree } from './SparseSnapshotTree';
import { SyncTree } from './SyncTree';
import { SnapshotHolder } from './SnapshotHolder';
import { stringify } from '@firebase/util';
import { beingCrawled, each, exceptionGuard, warn, log } from './util/util';
import { map, forEach, isEmpty } from '@firebase/util';
import { AuthTokenProvider } from './AuthTokenProvider';
import { StatsManager } from './stats/StatsManager';
import { StatsReporter } from './stats/StatsReporter';
import { StatsListener } from './stats/StatsListener';
import { EventQueue } from './view/EventQueue';
import { PersistentConnection } from './PersistentConnection';
import { ReadonlyRestClient } from './ReadonlyRestClient';
import { FirebaseApp } from '@firebase/app-types';
import { RepoInfo } from './RepoInfo';
import { Database } from '../api/Database';
import { ServerActions } from './ServerActions';
import { Query } from '../api/Query';
import { EventRegistration } from './view/EventRegistration';
import { StatsCollection } from './stats/StatsCollection';
import { Event } from './view/Event';
import { Node } from './snap/Node';
 
const INTERRUPT_REASON = 'repo_interrupt';
 
/**
 * A connection to a single data repository.
 */
export class Repo {
  dataUpdateCount = 0;
  private infoSyncTree_: SyncTree;
  private serverSyncTree_: SyncTree;
 
  private stats_: StatsCollection;
  private statsListener_: StatsListener | null = null;
  private eventQueue_ = new EventQueue();
  private nextWriteId_ = 1;
  private server_: ServerActions;
  private statsReporter_: StatsReporter;
  private transactions_init_: () => void;
  private infoData_: SnapshotHolder;
  private abortTransactions_: (path: Path) => Path;
  private rerunTransactions_: (changedPath: Path) => Path;
  private interceptServerDataCallback_:
    | ((a: string, b: any) => void)
    | null = null;
  private __database: Database;
 
  // A list of data pieces and paths to be set when this client disconnects.
  private onDisconnect_ = new SparseSnapshotTree();
 
  /**
   * TODO: This should be @private but it's used by test_access.js and internal.js
   * @type {?PersistentConnection}
   */
  persistentConnection_: PersistentConnection | null = null;
 
  /**
   * @param {!RepoInfo} repoInfo_
   * @param {boolean} forceRestClient
   * @param {!FirebaseApp} app
   */
  constructor(
    public repoInfo_: RepoInfo,
    forceRestClient: boolean,
    public app: FirebaseApp
  ) {
    /** @type {!AuthTokenProvider} */
    const authTokenProvider = new AuthTokenProvider(app);
 
    this.stats_ = StatsManager.getCollection(repoInfo_);
 
    if (forceRestClient || beingCrawled()) {
      this.server_ = new ReadonlyRestClient(
        this.repoInfo_,
        this.onDataUpdate_.bind(this),
        authTokenProvider
      );
 
      // Minor hack: Fire onConnect immediately, since there's no actual connection.
      setTimeout(this.onConnectStatus_.bind(this, true), 0);
    } else {
      const authOverride = app.options['databaseAuthVariableOverride'];
      // Validate authOverride
      Iif (typeof authOverride !== 'undefined' && authOverride !== null) {
        if (typeof authOverride !== 'object') {
          throw new Error(
            'Only objects are supported for option databaseAuthVariableOverride'
          );
        }
        try {
          stringify(authOverride);
        } catch (e) {
          throw new Error('Invalid authOverride provided: ' + e);
        }
      }
 
      this.persistentConnection_ = new PersistentConnection(
        this.repoInfo_,
        this.onDataUpdate_.bind(this),
        this.onConnectStatus_.bind(this),
        this.onServerInfoUpdate_.bind(this),
        authTokenProvider,
        authOverride
      );
 
      this.server_ = this.persistentConnection_;
    }
 
    authTokenProvider.addTokenChangeListener(token => {
      this.server_.refreshAuthToken(token);
    });
 
    // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
    // we only want to create one StatsReporter.  As such, we'll report stats over the first Repo created.
    this.statsReporter_ = StatsManager.getOrCreateReporter(
      repoInfo_,
      () => new StatsReporter(this.stats_, this.server_)
    );
 
    this.transactions_init_();
 
    // Used for .info.
    this.infoData_ = new SnapshotHolder();
    this.infoSyncTree_ = new SyncTree({
      startListening: (query, tag, currentHashFn, onComplete) => {
        let infoEvents: Event[] = [];
        const node = this.infoData_.getNode(query.path);
        // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
        // on initial data...
        Eif (!node.isEmpty()) {
          infoEvents = this.infoSyncTree_.applyServerOverwrite(
            query.path,
            node
          );
          setTimeout(() => {
            onComplete('ok');
          }, 0);
        }
        return infoEvents;
      },
      stopListening: () => {}
    });
    this.updateInfo_('connected', false);
 
    this.serverSyncTree_ = new SyncTree({
      startListening: (query, tag, currentHashFn, onComplete) => {
        this.server_.listen(query, currentHashFn, tag, (status, data) => {
          const events = onComplete(status, data);
          this.eventQueue_.raiseEventsForChangedPath(query.path, events);
        });
        // No synchronous events for network-backed sync trees
        return [];
      },
      stopListening: (query, tag) => {
        this.server_.unlisten(query, tag);
      }
    });
  }
 
  /**
   * @return {string}  The URL corresponding to the root of this Firebase.
   */
  toString(): string {
    return (
      (this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host
    );
  }
 
  /**
   * @return {!string} The namespace represented by the repo.
   */
  name(): string {
    return this.repoInfo_.namespace;
  }
 
  /**
   * @return {!number} The time in milliseconds, taking the server offset into account if we have one.
   */
  serverTime(): number {
    const offsetNode = this.infoData_.getNode(
      new Path('.info/serverTimeOffset')
    );
    const offset = (offsetNode.val() as number) || 0;
    return new Date().getTime() + offset;
  }
 
  /**
   * Generate ServerValues using some variables from the repo object.
   * @return {!Object}
   */
  generateServerValues(): Object {
    return generateWithValues({
      timestamp: this.serverTime()
    });
  }
 
  /**
   * Called by realtime when we get new messages from the server.
   *
   * @private
   * @param {string} pathString
   * @param {*} data
   * @param {boolean} isMerge
   * @param {?number} tag
   */
  private onDataUpdate_(
    pathString: string,
    data: any,
    isMerge: boolean,
    tag: number | null
  ) {
    // For testing.
    this.dataUpdateCount++;
    const path = new Path(pathString);
    data = this.interceptServerDataCallback_
      ? this.interceptServerDataCallback_(pathString, data)
      : data;
    let events = [];
    if (tag) {
      if (isMerge) {
        const taggedChildren = map(data as { [k: string]: any }, (raw: any) =>
          nodeFromJSON(raw)
        );
        events = this.serverSyncTree_.applyTaggedQueryMerge(
          path,
          taggedChildren,
          tag
        );
      } else {
        const taggedSnap = nodeFromJSON(data);
        events = this.serverSyncTree_.applyTaggedQueryOverwrite(
          path,
          taggedSnap,
          tag
        );
      }
    } else if (isMerge) {
      const changedChildren = map(data as { [k: string]: any }, (raw: any) =>
        nodeFromJSON(raw)
      );
      events = this.serverSyncTree_.applyServerMerge(path, changedChildren);
    } else {
      const snap = nodeFromJSON(data);
      events = this.serverSyncTree_.applyServerOverwrite(path, snap);
    }
    let affectedPath = path;
    if (events.length > 0) {
      // Since we have a listener outstanding for each transaction, receiving any events
      // is a proxy for some change having occurred.
      affectedPath = this.rerunTransactions_(path);
    }
    this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);
  }
 
  /**
   * TODO: This should be @private but it's used by test_access.js and internal.js
   * @param {?function(!string, *):*} callback
   * @private
   */
  interceptServerData_(callback: ((a: string, b: any) => any) | null) {
    this.interceptServerDataCallback_ = callback;
  }
 
  /**
   * @param {!boolean} connectStatus
   * @private
   */
  private onConnectStatus_(connectStatus: boolean) {
    this.updateInfo_('connected', connectStatus);
    if (connectStatus === false) {
      this.runOnDisconnectEvents_();
    }
  }
 
  /**
   * @param {!Object} updates
   * @private
   */
  private onServerInfoUpdate_(updates: Object) {
    each(updates, (value: any, key: string) => {
      this.updateInfo_(key, value);
    });
  }
 
  /**
   *
   * @param {!string} pathString
   * @param {*} value
   * @private
   */
  private updateInfo_(pathString: string, value: any) {
    const path = new Path('/.info/' + pathString);
    const newNode = nodeFromJSON(value);
    this.infoData_.updateSnapshot(path, newNode);
    const events = this.infoSyncTree_.applyServerOverwrite(path, newNode);
    this.eventQueue_.raiseEventsForChangedPath(path, events);
  }
 
  /**
   * @return {!number}
   * @private
   */
  private getNextWriteId_(): number {
    return this.nextWriteId_++;
  }
 
  /**
   * @param {!Path} path
   * @param {*} newVal
   * @param {number|string|null} newPriority
   * @param {?function(?Error, *=)} onComplete
   */
  setWithPriority(
    path: Path,
    newVal: any,
    newPriority: number | string | null,
    onComplete: ((status: Error | null, errorReason?: string) => void) | null
  ) {
    this.log_('set', {
      path: path.toString(),
      value: newVal,
      priority: newPriority
    });
 
    // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
    // (b) store unresolved paths on JSON parse
    const serverValues = this.generateServerValues();
    const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
    const newNode = resolveDeferredValueSnapshot(
      newNodeUnresolved,
      serverValues
    );
 
    const writeId = this.getNextWriteId_();
    const events = this.serverSyncTree_.applyUserOverwrite(
      path,
      newNode,
      writeId,
      true
    );
    this.eventQueue_.queueEvents(events);
    this.server_.put(
      path.toString(),
      newNodeUnresolved.val(/*export=*/ true),
      (status, errorReason) => {
        const success = status === 'ok';
        Iif (!success) {
          warn('set at ' + path + ' failed: ' + status);
        }
 
        const clearEvents = this.serverSyncTree_.ackUserWrite(
          writeId,
          !success
        );
        this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);
        this.callOnCompleteCallback(onComplete, status, errorReason);
      }
    );
    const affectedPath = this.abortTransactions_(path);
    this.rerunTransactions_(affectedPath);
    // We queued the events above, so just flush the queue here
    this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);
  }
 
  /**
   * @param {!Path} path
   * @param {!Object} childrenToMerge
   * @param {?function(?Error, *=)} onComplete
   */
  update(
    path: Path,
    childrenToMerge: { [k: string]: any },
    onComplete: ((status: Error | null, errorReason?: string) => void) | null
  ) {
    this.log_('update', { path: path.toString(), value: childrenToMerge });
 
    // Start with our existing data and merge each child into it.
    let empty = true;
    const serverValues = this.generateServerValues();
    const changedChildren: { [k: string]: Node } = {};
    forEach(childrenToMerge, (changedKey: string, changedValue: any) => {
      empty = false;
      const newNodeUnresolved = nodeFromJSON(changedValue);
      changedChildren[changedKey] = resolveDeferredValueSnapshot(
        newNodeUnresolved,
        serverValues
      );
    });
 
    Eif (!empty) {
      const writeId = this.getNextWriteId_();
      const events = this.serverSyncTree_.applyUserMerge(
        path,
        changedChildren,
        writeId
      );
      this.eventQueue_.queueEvents(events);
      this.server_.merge(
        path.toString(),
        childrenToMerge,
        (status, errorReason) => {
          const success = status === 'ok';
          Iif (!success) {
            warn('update at ' + path + ' failed: ' + status);
          }
 
          const clearEvents = this.serverSyncTree_.ackUserWrite(
            writeId,
            !success
          );
          const affectedPath =
            clearEvents.length > 0 ? this.rerunTransactions_(path) : path;
          this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);
          this.callOnCompleteCallback(onComplete, status, errorReason);
        }
      );
 
      forEach(childrenToMerge, (changedPath: string) => {
        const affectedPath = this.abortTransactions_(path.child(changedPath));
        this.rerunTransactions_(affectedPath);
      });
 
      // We queued the events above, so just flush the queue here
      this.eventQueue_.raiseEventsForChangedPath(path, []);
    } else {
      log("update() called with empty data.  Don't do anything.");
      this.callOnCompleteCallback(onComplete, 'ok');
    }
  }
 
  /**
   * Applies all of the changes stored up in the onDisconnect_ tree.
   * @private
   */
  private runOnDisconnectEvents_() {
    this.log_('onDisconnectEvents');
 
    const serverValues = this.generateServerValues();
    const resolvedOnDisconnectTree = resolveDeferredValueTree(
      this.onDisconnect_,
      serverValues
    );
    let events: Event[] = [];
 
    resolvedOnDisconnectTree.forEachTree(Path.Empty, (path, snap) => {
      events = events.concat(
        this.serverSyncTree_.applyServerOverwrite(path, snap)
      );
      const affectedPath = this.abortTransactions_(path);
      this.rerunTransactions_(affectedPath);
    });
 
    this.onDisconnect_ = new SparseSnapshotTree();
    this.eventQueue_.raiseEventsForChangedPath(Path.Empty, events);
  }
 
  /**
   * @param {!Path} path
   * @param {?function(?Error, *=)} onComplete
   */
  onDisconnectCancel(
    path: Path,
    onComplete: ((status: Error | null, errorReason?: string) => void) | null
  ) {
    this.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
      if (status === 'ok') {
        this.onDisconnect_.forget(path);
      }
      this.callOnCompleteCallback(onComplete, status, errorReason);
    });
  }
 
  /**
   * @param {!Path} path
   * @param {*} value
   * @param {?function(?Error, *=)} onComplete
   */
  onDisconnectSet(
    path: Path,
    value: any,
    onComplete: ((status: Error | null, errorReason?: string) => void) | null
  ) {
    const newNode = nodeFromJSON(value);
    this.server_.onDisconnectPut(
      path.toString(),
      newNode.val(/*export=*/ true),
      (status, errorReason) => {
        if (status === 'ok') {
          this.onDisconnect_.remember(path, newNode);
        }
        this.callOnCompleteCallback(onComplete, status, errorReason);
      }
    );
  }
 
  /**
   * @param {!Path} path
   * @param {*} value
   * @param {*} priority
   * @param {?function(?Error, *=)} onComplete
   */
  onDisconnectSetWithPriority(
    path: Path,
    value: any,
    priority: any,
    onComplete: ((status: Error | null, errorReason?: string) => void) | null
  ) {
    const newNode = nodeFromJSON(value, priority);
    this.server_.onDisconnectPut(
      path.toString(),
      newNode.val(/*export=*/ true),
      (status, errorReason) => {
        if (status === 'ok') {
          this.onDisconnect_.remember(path, newNode);
        }
        this.callOnCompleteCallback(onComplete, status, errorReason);
      }
    );
  }
 
  /**
   * @param {!Path} path
   * @param {*} childrenToMerge
   * @param {?function(?Error, *=)} onComplete
   */
  onDisconnectUpdate(
    path: Path,
    childrenToMerge: { [k: string]: any },
    onComplete: ((status: Error | null, errorReason?: string) => void) | null
  ) {
    if (isEmpty(childrenToMerge)) {
      log(
        "onDisconnect().update() called with empty data.  Don't do anything."
      );
      this.callOnCompleteCallback(onComplete, 'ok');
      return;
    }
 
    this.server_.onDisconnectMerge(
      path.toString(),
      childrenToMerge,
      (status, errorReason) => {
        if (status === 'ok') {
          forEach(childrenToMerge, (childName: string, childNode: any) => {
            const newChildNode = nodeFromJSON(childNode);
            this.onDisconnect_.remember(path.child(childName), newChildNode);
          });
        }
        this.callOnCompleteCallback(onComplete, status, errorReason);
      }
    );
  }
 
  /**
   * @param {!Query} query
   * @param {!EventRegistration} eventRegistration
   */
  addEventCallbackForQuery(query: Query, eventRegistration: EventRegistration) {
    let events;
    if (query.path.getFront() === '.info') {
      events = this.infoSyncTree_.addEventRegistration(
        query,
        eventRegistration
      );
    } else {
      events = this.serverSyncTree_.addEventRegistration(
        query,
        eventRegistration
      );
    }
    this.eventQueue_.raiseEventsAtPath(query.path, events);
  }
 
  /**
   * @param {!Query} query
   * @param {?EventRegistration} eventRegistration
   */
  removeEventCallbackForQuery(
    query: Query,
    eventRegistration: EventRegistration
  ) {
    // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
    // a little bit by handling the return values anyways.
    let events;
    Iif (query.path.getFront() === '.info') {
      events = this.infoSyncTree_.removeEventRegistration(
        query,
        eventRegistration
      );
    } else {
      events = this.serverSyncTree_.removeEventRegistration(
        query,
        eventRegistration
      );
    }
    this.eventQueue_.raiseEventsAtPath(query.path, events);
  }
 
  interrupt() {
    Eif (this.persistentConnection_) {
      this.persistentConnection_.interrupt(INTERRUPT_REASON);
    }
  }
 
  resume() {
    Eif (this.persistentConnection_) {
      this.persistentConnection_.resume(INTERRUPT_REASON);
    }
  }
 
  stats(showDelta: boolean = false) {
    if (typeof console === 'undefined') return;
 
    let stats: { [k: string]: any };
    if (showDelta) {
      if (!this.statsListener_)
        this.statsListener_ = new StatsListener(this.stats_);
      stats = this.statsListener_.get();
    } else {
      stats = this.stats_.get();
    }
 
    const longestName = Object.keys(stats).reduce(
      (previousValue, currentValue) =>
        Math.max(currentValue.length, previousValue),
      0
    );
 
    forEach(stats, (stat: string, value: any) => {
      // pad stat names to be the same length (plus 2 extra spaces).
      for (let i = stat.length; i < longestName + 2; i++) stat += ' ';
      console.log(stat + value);
    });
  }
 
  statsIncrementCounter(metric: string) {
    this.stats_.incrementCounter(metric);
    this.statsReporter_.includeStat(metric);
  }
 
  /**
   * @param {...*} var_args
   * @private
   */
  private log_(...var_args: any[]) {
    let prefix = '';
    if (this.persistentConnection_) {
      prefix = this.persistentConnection_.id + ':';
    }
    log(prefix, ...var_args);
  }
 
  /**
   * @param {?function(?Error, *=)} callback
   * @param {!string} status
   * @param {?string=} errorReason
   */
  callOnCompleteCallback(
    callback: ((status: Error | null, errorReason?: string) => void) | null,
    status: string,
    errorReason?: string | null
  ) {
    Eif (callback) {
      exceptionGuard(function() {
        Eif (status == 'ok') {
          callback(null);
        } else {
          const code = (status || 'error').toUpperCase();
          let message = code;
          if (errorReason) message += ': ' + errorReason;
 
          const error = new Error(message);
          (error as any).code = code;
          callback(error);
        }
      });
    }
  }
 
  get database(): Database {
    return this.__database || (this.__database = new Database(this));
  }
}