/
indexeddb_persistence.ts
1342 lines (1235 loc) · 44.8 KB
/
indexeddb_persistence.ts
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* 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 { User } from '../auth/user';
import { DatabaseInfo } from '../core/database_info';
import { ListenSequence, SequenceNumberSyncer } from '../core/listen_sequence';
import { ListenSequenceNumber, TargetId } from '../core/types';
import { DocumentKey } from '../model/document_key';
import { Platform } from '../platform/platform';
import { JsonProtoSerializer } from '../remote/serializer';
import { assert, fail } from '../util/assert';
import { AsyncQueue, TimerId } from '../util/async_queue';
import { Code, FirestoreError } from '../util/error';
import * as log from '../util/log';
import { CancelablePromise } from '../util/promise';
import { decode, encode, EncodedResourcePath } from './encoded_resource_path';
import {
IndexedDbMutationQueue,
mutationQueuesContainKey
} from './indexeddb_mutation_queue';
import {
documentTargetStore,
getHighestListenSequenceNumber,
IndexedDbQueryCache
} from './indexeddb_query_cache';
import { IndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';
import {
ALL_STORES,
DbClientMetadata,
DbClientMetadataKey,
DbPrimaryClient,
DbPrimaryClientKey,
DbTargetDocument,
DbTargetGlobal,
SCHEMA_VERSION,
SchemaConverter
} from './indexeddb_schema';
import { LocalSerializer } from './local_serializer';
import {
ActiveTargets,
LruDelegate,
LruGarbageCollector,
LruParams
} from './lru_garbage_collector';
import { MutationQueue } from './mutation_queue';
import {
Persistence,
PersistenceTransaction,
PrimaryStateListener,
ReferenceDelegate
} from './persistence';
import { PersistencePromise } from './persistence_promise';
import { QueryData } from './query_data';
import { ReferenceSet } from './reference_set';
import { ClientId } from './shared_client_state';
import { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';
const LOG_TAG = 'IndexedDbPersistence';
/**
* Oldest acceptable age in milliseconds for client metadata before the client
* is considered inactive and its associated data (such as the remote document
* cache changelog) is garbage collected.
*/
const MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes
/**
* Oldest acceptable metadata age for clients that may participate in the
* primary lease election. Clients that have not updated their client metadata
* within 5 seconds are not eligible to receive a primary lease.
*/
const MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;
/**
* The interval at which clients will update their metadata, including
* refreshing their primary lease if held or potentially trying to acquire it if
* not held.
*
* Primary clients may opportunistically refresh their metadata earlier
* if they're already performing an IndexedDB operation.
*/
const CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;
/** User-facing error when the primary lease is required but not available. */
const PRIMARY_LEASE_LOST_ERROR_MSG =
'The current tab is not in the required state to perform this operation. ' +
'It might be necessary to refresh the browser tab.';
const PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG =
'Another tab has exclusive access to the persistence layer. ' +
'To allow shared access, make sure to invoke ' +
'`enablePersistence()` with `experimentalTabSynchronization:true` in all tabs.';
const UNSUPPORTED_PLATFORM_ERROR_MSG =
'This platform is either missing' +
' IndexedDB or is known to have an incomplete implementation. Offline' +
' persistence has been disabled.';
// The format of the LocalStorage key that stores zombied client is:
// firestore_zombie_<persistence_prefix>_<instance_key>
const ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';
export class IndexedDbTransaction extends PersistenceTransaction {
constructor(
readonly simpleDbTransaction: SimpleDbTransaction,
readonly currentSequenceNumber
) {
super();
}
}
/**
* An IndexedDB-backed instance of Persistence. Data is stored persistently
* across sessions.
*
* On Web only, the Firestore SDKs support shared access to its persistence
* layer. This allows multiple browser tabs to read and write to IndexedDb and
* to synchronize state even without network connectivity. Shared access is
* currently optional and not enabled unless all clients invoke
* `enablePersistence()` with `{experimentalTabSynchronization:true}`.
*
* In multi-tab mode, if multiple clients are active at the same time, the SDK
* will designate one client as the “primary client”. An effort is made to pick
* a visible, network-connected and active client, and this client is
* responsible for letting other clients know about its presence. The primary
* client writes a unique client-generated identifier (the client ID) to
* IndexedDb’s “owner” store every 4 seconds. If the primary client fails to
* update this entry, another client can acquire the lease and take over as
* primary.
*
* Some persistence operations in the SDK are designated as primary-client only
* operations. This includes the acknowledgment of mutations and all updates of
* remote documents. The effects of these operations are written to persistence
* and then broadcast to other tabs via LocalStorage (see
* `WebStorageSharedClientState`), which then refresh their state from
* persistence.
*
* Similarly, the primary client listens to notifications sent by secondary
* clients to discover persistence changes written by secondary clients, such as
* the addition of new mutations and query targets.
*
* If multi-tab is not enabled and another tab already obtained the primary
* lease, IndexedDbPersistence enters a failed state and all subsequent
* operations will automatically fail.
*
* Additionally, there is an optimization so that when a tab is closed, the
* primary lease is released immediately (this is especially important to make
* sure that a refreshed tab is able to immediately re-acquire the primary
* lease). Unfortunately, IndexedDB cannot be reliably used in window.unload
* since it is an asynchronous API. So in addition to attempting to give up the
* lease, the leaseholder writes its client ID to a "zombiedClient" entry in
* LocalStorage which acts as an indicator that another tab should go ahead and
* take the primary lease immediately regardless of the current lease timestamp.
*
* TODO(b/114226234): Remove `experimentalTabSynchronization` section when
* multi-tab is no longer optional.
*/
export type MultiClientParams = {
sequenceNumberSyncer: SequenceNumberSyncer;
};
export class IndexedDbPersistence implements Persistence {
static getStore<Key extends IDBValidKey, Value>(
txn: PersistenceTransaction,
store: string
): SimpleDbStore<Key, Value> {
if (txn instanceof IndexedDbTransaction) {
return SimpleDb.getStore<Key, Value>(txn.simpleDbTransaction, store);
} else {
throw fail(
'IndexedDbPersistence must use instances of IndexedDbTransaction'
);
}
}
/**
* The name of the main (and currently only) IndexedDB database. this name is
* appended to the prefix provided to the IndexedDbPersistence constructor.
*/
static MAIN_DATABASE = 'main';
static async createIndexedDbPersistence(
persistenceKey: string,
clientId: ClientId,
platform: Platform,
queue: AsyncQueue,
serializer: JsonProtoSerializer,
lruParams: LruParams
): Promise<IndexedDbPersistence> {
const persistence = new IndexedDbPersistence(
persistenceKey,
clientId,
platform,
queue,
serializer,
lruParams
);
await persistence.start();
return persistence;
}
static async createMultiClientIndexedDbPersistence(
persistenceKey: string,
clientId: ClientId,
platform: Platform,
queue: AsyncQueue,
serializer: JsonProtoSerializer,
lruParams: LruParams,
multiClientParams: MultiClientParams
): Promise<IndexedDbPersistence> {
const persistence = new IndexedDbPersistence(
persistenceKey,
clientId,
platform,
queue,
serializer,
lruParams,
multiClientParams
);
await persistence.start();
return persistence;
}
private readonly document: Document | null;
private readonly window: Window;
private simpleDb: SimpleDb;
private _started = false;
private isPrimary = false;
private networkEnabled = true;
private dbName: string;
/** Our window.unload handler, if registered. */
private windowUnloadHandler: (() => void) | null;
private inForeground = false;
private serializer: LocalSerializer;
/** Our 'visibilitychange' listener if registered. */
private documentVisibilityHandler: ((e?: Event) => void) | null;
/** The client metadata refresh task. */
private clientMetadataRefresher: CancelablePromise<void>;
/** The last time we garbage collected the Remote Document Changelog. */
private lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;
/** Whether to allow shared multi-tab access to the persistence layer. */
private allowTabSynchronization: boolean;
/** A listener to notify on primary state changes. */
private primaryStateListener: PrimaryStateListener = _ => Promise.resolve();
private readonly queryCache: IndexedDbQueryCache;
private readonly remoteDocumentCache: IndexedDbRemoteDocumentCache;
private readonly webStorage: Storage;
private listenSequence: ListenSequence;
readonly referenceDelegate: IndexedDbLruDelegate;
// Note that `multiClientParams` must be present to enable multi-client support while multi-tab
// is still experimental. When multi-client is switched to always on, `multiClientParams` will
// no longer be optional.
private constructor(
private readonly persistenceKey: string,
private readonly clientId: ClientId,
platform: Platform,
private readonly queue: AsyncQueue,
serializer: JsonProtoSerializer,
lruParams: LruParams,
private readonly multiClientParams?: MultiClientParams
) {
if (!IndexedDbPersistence.isAvailable()) {
throw new FirestoreError(
Code.UNIMPLEMENTED,
UNSUPPORTED_PLATFORM_ERROR_MSG
);
}
this.referenceDelegate = new IndexedDbLruDelegate(this, lruParams);
this.dbName = persistenceKey + IndexedDbPersistence.MAIN_DATABASE;
this.serializer = new LocalSerializer(serializer);
this.document = platform.document;
this.allowTabSynchronization = multiClientParams !== undefined;
this.queryCache = new IndexedDbQueryCache(
this.referenceDelegate,
this.serializer
);
this.remoteDocumentCache = new IndexedDbRemoteDocumentCache(
this.serializer,
/*keepDocumentChangeLog=*/ this.allowTabSynchronization
);
if (platform.window && platform.window.localStorage) {
this.window = platform.window;
this.webStorage = this.window.localStorage;
} else {
throw new FirestoreError(
Code.UNIMPLEMENTED,
'IndexedDB persistence is only available on platforms that support LocalStorage.'
);
}
}
/**
* Attempt to start IndexedDb persistence.
*
* @return {Promise<void>} Whether persistence was enabled.
*/
private start(): Promise<void> {
assert(!this.started, 'IndexedDbPersistence double-started!');
assert(this.window !== null, "Expected 'window' to be defined");
return SimpleDb.openOrCreate(
this.dbName,
SCHEMA_VERSION,
new SchemaConverter(this.serializer)
)
.then(db => {
this.simpleDb = db;
// NOTE: This is expected to fail sometimes (in the case of another tab already
// having the persistence lock), so it's the first thing we should do.
return this.updateClientMetadataAndTryBecomePrimary();
})
.then(() => {
this.attachVisibilityHandler();
this.attachWindowUnloadHook();
this.scheduleClientMetadataAndPrimaryLeaseRefreshes();
return this.startRemoteDocumentCache();
})
.then(() => {
return this.simpleDb.runTransaction(
'readonly',
[DbTargetGlobal.store],
txn => {
return getHighestListenSequenceNumber(txn).next(
highestListenSequenceNumber => {
const sequenceNumberSyncer = this.multiClientParams
? this.multiClientParams.sequenceNumberSyncer
: undefined;
this.listenSequence = new ListenSequence(
highestListenSequenceNumber,
sequenceNumberSyncer
);
}
);
}
);
})
.then(() => {
this._started = true;
})
.catch(reason => {
this.simpleDb && this.simpleDb.close();
return Promise.reject(reason);
});
}
private startRemoteDocumentCache(): Promise<void> {
return this.simpleDb.runTransaction('readonly', ALL_STORES, txn =>
this.remoteDocumentCache.start(txn)
);
}
setPrimaryStateListener(
primaryStateListener: PrimaryStateListener
): Promise<void> {
this.primaryStateListener = async primaryState => {
if (this.started) {
return primaryStateListener(primaryState);
}
};
return primaryStateListener(this.isPrimary);
}
setNetworkEnabled(networkEnabled: boolean): void {
if (this.networkEnabled !== networkEnabled) {
this.networkEnabled = networkEnabled;
// Schedule a primary lease refresh for immediate execution. The eventual
// lease update will be propagated via `primaryStateListener`.
this.queue.enqueueAndForget(async () => {
if (this.started) {
await this.updateClientMetadataAndTryBecomePrimary();
}
});
}
}
/**
* Updates the client metadata in IndexedDb and attempts to either obtain or
* extend the primary lease for the local client. Asynchronously notifies the
* primary state listener if the client either newly obtained or released its
* primary lease.
*/
private updateClientMetadataAndTryBecomePrimary(): Promise<void> {
return this.simpleDb.runTransaction('readwrite', ALL_STORES, txn => {
const metadataStore = clientMetadataStore(txn);
return metadataStore
.put(
new DbClientMetadata(
this.clientId,
Date.now(),
this.networkEnabled,
this.inForeground,
this.remoteDocumentCache.lastProcessedDocumentChangeId
)
)
.next(() => {
if (this.isPrimary) {
return this.verifyPrimaryLease(txn).next(success => {
if (!success) {
this.isPrimary = false;
this.queue.enqueueAndForget(() =>
this.primaryStateListener(false)
);
}
});
}
})
.next(() => this.canActAsPrimary(txn))
.next(canActAsPrimary => {
const wasPrimary = this.isPrimary;
this.isPrimary = canActAsPrimary;
if (wasPrimary !== this.isPrimary) {
this.queue.enqueueAndForget(() =>
this.primaryStateListener(this.isPrimary)
);
}
if (wasPrimary && !this.isPrimary) {
return this.releasePrimaryLeaseIfHeld(txn);
} else if (this.isPrimary) {
return this.acquireOrExtendPrimaryLease(txn);
}
});
});
}
private verifyPrimaryLease(
txn: SimpleDbTransaction
): PersistencePromise<boolean> {
const store = primaryClientStore(txn);
return store.get(DbPrimaryClient.key).next(primaryClient => {
return PersistencePromise.resolve(this.isLocalClient(primaryClient));
});
}
private removeClientMetadata(
txn: SimpleDbTransaction
): PersistencePromise<void> {
const metadataStore = clientMetadataStore(txn);
return metadataStore.delete(this.clientId);
}
/**
* If the garbage collection threshold has passed, prunes the
* RemoteDocumentChanges and the ClientMetadata store based on the last update
* time of all clients.
*/
private async maybeGarbageCollectMultiClientState(): Promise<void> {
if (
this.isPrimary &&
!this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)
) {
this.lastGarbageCollectionTime = Date.now();
let activeClients: DbClientMetadata[];
let inactiveClients: DbClientMetadata[] = [];
await this.runTransaction(
'maybeGarbageCollectMultiClientState',
'readwrite-primary',
txn => {
const metadataStore = IndexedDbPersistence.getStore<
DbClientMetadataKey,
DbClientMetadata
>(txn, DbClientMetadata.store);
return metadataStore
.loadAll()
.next(existingClients => {
activeClients = this.filterActiveClients(
existingClients,
MAX_CLIENT_AGE_MS
);
inactiveClients = existingClients.filter(
client => activeClients.indexOf(client) === -1
);
})
.next(() =>
// Delete metadata for clients that are no longer considered active.
PersistencePromise.forEach(inactiveClients, inactiveClient =>
metadataStore.delete(inactiveClient.clientId)
)
)
.next(() => {
// Retrieve the minimum change ID from the set of active clients.
// The primary client doesn't read from the document change log,
// and hence we exclude it when we determine the minimum
// `lastProcessedDocumentChangeId`.
activeClients = activeClients.filter(
client => client.clientId !== this.clientId
);
if (activeClients.length > 0) {
const processedChangeIds = activeClients.map(
client => client.lastProcessedDocumentChangeId || 0
);
const oldestChangeId = Math.min(...processedChangeIds);
return this.remoteDocumentCache.removeDocumentChangesThroughChangeId(
txn,
oldestChangeId
);
}
});
}
);
// Delete potential leftover entries that may continue to mark the
// inactive clients as zombied in LocalStorage.
// Ideally we'd delete the IndexedDb and LocalStorage zombie entries for
// the client atomically, but we can't. So we opt to delete the IndexedDb
// entries first to avoid potentially reviving a zombied client.
inactiveClients.forEach(inactiveClient => {
this.window.localStorage.removeItem(
this.zombiedClientLocalStorageKey(inactiveClient.clientId)
);
});
}
}
/**
* Schedules a recurring timer to update the client metadata and to either
* extend or acquire the primary lease if the client is eligible.
*/
private scheduleClientMetadataAndPrimaryLeaseRefreshes(): void {
this.clientMetadataRefresher = this.queue.enqueueAfterDelay(
TimerId.ClientMetadataRefresh,
CLIENT_METADATA_REFRESH_INTERVAL_MS,
() => {
return this.updateClientMetadataAndTryBecomePrimary()
.then(() => this.maybeGarbageCollectMultiClientState())
.then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes());
}
);
}
/** Checks whether `client` is the local client. */
private isLocalClient(client: DbPrimaryClient | null): boolean {
return client ? client.ownerId === this.clientId : false;
}
/**
* Evaluate the state of all active clients and determine whether the local
* client is or can act as the holder of the primary lease. Returns whether
* the client is eligible for the lease, but does not actually acquire it.
* May return 'false' even if there is no active leaseholder and another
* (foreground) client should become leaseholder instead.
*/
private canActAsPrimary(
txn: SimpleDbTransaction
): PersistencePromise<boolean> {
const store = primaryClientStore(txn);
return store
.get(DbPrimaryClient.key)
.next(currentPrimary => {
const currentLeaseIsValid =
currentPrimary !== null &&
this.isWithinAge(
currentPrimary.leaseTimestampMs,
MAX_PRIMARY_ELIGIBLE_AGE_MS
) &&
!this.isClientZombied(currentPrimary.ownerId);
// A client is eligible for the primary lease if:
// - its network is enabled and the client's tab is in the foreground.
// - its network is enabled and no other client's tab is in the
// foreground.
// - every clients network is disabled and the client's tab is in the
// foreground.
// - every clients network is disabled and no other client's tab is in
// the foreground.
if (currentLeaseIsValid) {
if (this.isLocalClient(currentPrimary) && this.networkEnabled) {
return true;
}
if (!this.isLocalClient(currentPrimary)) {
if (!currentPrimary!.allowTabSynchronization) {
// Fail the `canActAsPrimary` check if the current leaseholder has
// not opted into multi-tab synchronization. If this happens at
// client startup, we reject the Promise returned by
// `enablePersistence()` and the user can continue to use Firestore
// with in-memory persistence.
// If this fails during a lease refresh, we will instead block the
// AsyncQueue from executing further operations. Note that this is
// acceptable since mixing & matching different `synchronizeTabs`
// settings is not supported.
//
// TODO(b/114226234): Remove this check when `synchronizeTabs` can
// no longer be turned off.
throw new FirestoreError(
Code.FAILED_PRECONDITION,
PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG
);
}
return false;
}
}
if (this.networkEnabled && this.inForeground) {
return true;
}
return clientMetadataStore(txn)
.loadAll()
.next(existingClients => {
// Process all existing clients and determine whether at least one of
// them is better suited to obtain the primary lease.
const preferredCandidate = this.filterActiveClients(
existingClients,
MAX_PRIMARY_ELIGIBLE_AGE_MS
).find(otherClient => {
if (this.clientId !== otherClient.clientId) {
const otherClientHasBetterNetworkState =
!this.networkEnabled && otherClient.networkEnabled;
const otherClientHasBetterVisibility =
!this.inForeground && otherClient.inForeground;
const otherClientHasSameNetworkState =
this.networkEnabled === otherClient.networkEnabled;
if (
otherClientHasBetterNetworkState ||
(otherClientHasBetterVisibility &&
otherClientHasSameNetworkState)
) {
return true;
}
}
return false;
});
return preferredCandidate === undefined;
});
})
.next(canActAsPrimary => {
if (this.isPrimary !== canActAsPrimary) {
log.debug(
LOG_TAG,
`Client ${
canActAsPrimary ? 'is' : 'is not'
} eligible for a primary lease.`
);
}
return canActAsPrimary;
});
}
async shutdown(deleteData?: boolean): Promise<void> {
// The shutdown() operations are idempotent and can be called even when
// start() aborted (e.g. because it couldn't acquire the persistence lease).
this._started = false;
this.markClientZombied();
if (this.clientMetadataRefresher) {
this.clientMetadataRefresher.cancel();
}
this.detachVisibilityHandler();
this.detachWindowUnloadHook();
await this.simpleDb.runTransaction(
'readwrite',
[DbPrimaryClient.store, DbClientMetadata.store],
txn => {
return this.releasePrimaryLeaseIfHeld(txn).next(() =>
this.removeClientMetadata(txn)
);
}
);
this.simpleDb.close();
// Remove the entry marking the client as zombied from LocalStorage since
// we successfully deleted its metadata from IndexedDb.
this.removeClientZombiedEntry();
if (deleteData) {
await SimpleDb.delete(this.dbName);
}
}
/**
* Returns clients that are not zombied and have an updateTime within the
* provided threshold.
*/
private filterActiveClients(
clients: DbClientMetadata[],
activityThresholdMs: number
): DbClientMetadata[] {
return clients.filter(
client =>
this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&
!this.isClientZombied(client.clientId)
);
}
getActiveClients(): Promise<ClientId[]> {
return this.simpleDb.runTransaction(
'readonly',
[DbClientMetadata.store],
txn => {
return clientMetadataStore(txn)
.loadAll()
.next(clients =>
this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(
clientMetadata => clientMetadata.clientId
)
);
}
);
}
get started(): boolean {
return this._started;
}
getMutationQueue(user: User): MutationQueue {
assert(
this.started,
'Cannot initialize MutationQueue before persistence is started.'
);
return IndexedDbMutationQueue.forUser(
user,
this.serializer,
this.referenceDelegate
);
}
getQueryCache(): IndexedDbQueryCache {
assert(
this.started,
'Cannot initialize QueryCache before persistence is started.'
);
return this.queryCache;
}
getRemoteDocumentCache(): IndexedDbRemoteDocumentCache {
assert(
this.started,
'Cannot initialize RemoteDocumentCache before persistence is started.'
);
return this.remoteDocumentCache;
}
runTransaction<T>(
action: string,
mode: 'readonly' | 'readwrite' | 'readwrite-primary',
transactionOperation: (
transaction: PersistenceTransaction
) => PersistencePromise<T>
): Promise<T> {
log.debug(LOG_TAG, 'Starting transaction:', action);
// Do all transactions as readwrite against all object stores, since we
// are the only reader/writer.
return this.simpleDb.runTransaction(
mode === 'readonly' ? 'readonly' : 'readwrite',
ALL_STORES,
simpleDbTxn => {
if (mode === 'readwrite-primary') {
// While we merely verify that we have (or can acquire) the lease
// immediately, we wait to extend the primary lease until after
// executing transactionOperation(). This ensures that even if the
// transactionOperation takes a long time, we'll use a recent
// leaseTimestampMs in the extended (or newly acquired) lease.
return this.verifyPrimaryLease(simpleDbTxn)
.next(success => {
if (!success) {
log.error(
`Failed to obtain primary lease for action '${action}'.`
);
this.isPrimary = false;
this.queue.enqueueAndForget(() =>
this.primaryStateListener(false)
);
throw new FirestoreError(
Code.FAILED_PRECONDITION,
PRIMARY_LEASE_LOST_ERROR_MSG
);
}
return transactionOperation(
new IndexedDbTransaction(
simpleDbTxn,
this.listenSequence.next()
)
);
})
.next(result => {
return this.acquireOrExtendPrimaryLease(simpleDbTxn).next(
() => result
);
});
} else {
return this.verifyAllowTabSynchronization(simpleDbTxn).next(() =>
transactionOperation(
new IndexedDbTransaction(simpleDbTxn, this.listenSequence.next())
)
);
}
}
);
}
/**
* Verifies that the current tab is the primary leaseholder or alternatively
* that the leaseholder has opted into multi-tab synchronization.
*/
// TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
// be turned off.
private verifyAllowTabSynchronization(
txn: SimpleDbTransaction
): PersistencePromise<void> {
const store = primaryClientStore(txn);
return store.get(DbPrimaryClient.key).next(currentPrimary => {
const currentLeaseIsValid =
currentPrimary !== null &&
this.isWithinAge(
currentPrimary.leaseTimestampMs,
MAX_PRIMARY_ELIGIBLE_AGE_MS
) &&
!this.isClientZombied(currentPrimary.ownerId);
if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) {
if (!currentPrimary!.allowTabSynchronization) {
throw new FirestoreError(
Code.FAILED_PRECONDITION,
PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG
);
}
}
});
}
/**
* Obtains or extends the new primary lease for the local client. This
* method does not verify that the client is eligible for this lease.
*/
private acquireOrExtendPrimaryLease(txn): PersistencePromise<void> {
const newPrimary = new DbPrimaryClient(
this.clientId,
this.allowTabSynchronization,
Date.now()
);
return primaryClientStore(txn).put(DbPrimaryClient.key, newPrimary);
}
static isAvailable(): boolean {
return SimpleDb.isAvailable();
}
/**
* Generates a string used as a prefix when storing data in IndexedDB and
* LocalStorage.
*/
static buildStoragePrefix(databaseInfo: DatabaseInfo): string {
// Use two different prefix formats:
//
// * firestore / persistenceKey / projectID . databaseID / ...
// * firestore / persistenceKey / projectID / ...
//
// projectIDs are DNS-compatible names and cannot contain dots
// so there's no danger of collisions.
let database = databaseInfo.databaseId.projectId;
if (!databaseInfo.databaseId.isDefaultDatabase) {
database += '.' + databaseInfo.databaseId.database;
}
return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';
}
/** Checks the primary lease and removes it if we are the current primary. */
private releasePrimaryLeaseIfHeld(
txn: SimpleDbTransaction
): PersistencePromise<void> {
const store = primaryClientStore(txn);
return store.get(DbPrimaryClient.key).next(primaryClient => {
if (this.isLocalClient(primaryClient)) {
log.debug(LOG_TAG, 'Releasing primary lease.');
return store.delete(DbPrimaryClient.key);
} else {
return PersistencePromise.resolve();
}
});
}
/** Verifies that `updateTimeMs` is within `maxAgeMs`. */
private isWithinAge(updateTimeMs: number, maxAgeMs: number): boolean {
const now = Date.now();
const minAcceptable = now - maxAgeMs;
const maxAcceptable = now;
if (updateTimeMs < minAcceptable) {
return false;
} else if (updateTimeMs > maxAcceptable) {
log.error(
`Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`
);
return false;
}
return true;
}
private attachVisibilityHandler(): void {
if (
this.document !== null &&
typeof this.document.addEventListener === 'function'
) {
this.documentVisibilityHandler = () => {
this.queue.enqueueAndForget(() => {
this.inForeground = this.document!.visibilityState === 'visible';
return this.updateClientMetadataAndTryBecomePrimary();
});
};
this.document.addEventListener(
'visibilitychange',
this.documentVisibilityHandler
);
this.inForeground = this.document.visibilityState === 'visible';
}
}
private detachVisibilityHandler(): void {
if (this.documentVisibilityHandler) {
assert(
this.document !== null &&
typeof this.document.addEventListener === 'function',
"Expected 'document.addEventListener' to be a function"
);
this.document!.removeEventListener(
'visibilitychange',
this.documentVisibilityHandler
);
this.documentVisibilityHandler = null;
}
}
/**
* Attaches a window.unload handler that will synchronously write our
* clientId to a "zombie client id" location in LocalStorage. This can be used
* by tabs trying to acquire the primary lease to determine that the lease
* is no longer valid even if the timestamp is recent. This is particularly
* important for the refresh case (so the tab correctly re-acquires the
* primary lease). LocalStorage is used for this rather than IndexedDb because
* it is a synchronous API and so can be used reliably from an unload
* handler.
*/
private attachWindowUnloadHook(): void {
if (typeof this.window.addEventListener === 'function') {
this.windowUnloadHandler = () => {
// Note: In theory, this should be scheduled on the AsyncQueue since it
// accesses internal state. We execute this code directly during shutdown
// to make sure it gets a chance to run.
this.markClientZombied();
this.queue.enqueueAndForget(() => {
// Attempt graceful shutdown (including releasing our primary lease),
// but there's no guarantee it will complete.
return this.shutdown();
});
};
this.window.addEventListener('unload', this.windowUnloadHandler);
}
}
private detachWindowUnloadHook(): void {
if (this.windowUnloadHandler) {
assert(
typeof this.window.removeEventListener === 'function',
"Expected 'window.removeEventListener' to be a function"
);
this.window.removeEventListener('unload', this.windowUnloadHandler);
this.windowUnloadHandler = null;
}
}
/**
* Returns whether a client is "zombied" based on its LocalStorage entry.
* Clients become zombied when their tab closes without running all of the
* cleanup logic in `shutdown()`.
*/