Skip to content

Make SyncEngine an interface. #3283

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 26, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions packages/firestore/src/core/component_provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ import {
newLocalStore,
newMultiTabLocalStore
} from '../local/local_store';
import { MultiTabSyncEngine, SyncEngine } from './sync_engine';
import {
MultiTabSyncEngine,
newMultiTabSyncEngine,
newSyncEngine,
SyncEngine
} from './sync_engine';
import { RemoteStore } from '../remote/remote_store';
import { EventManager } from './event_manager';
import { AsyncQueue } from '../util/async_queue';
Expand Down Expand Up @@ -167,7 +172,7 @@ export class MemoryComponentProvider implements ComponentProvider {
}

createSyncEngine(cfg: ComponentConfiguration): SyncEngine {
return new SyncEngine(
return newSyncEngine(
this.localStore,
this.remoteStore,
cfg.datastore,
Expand Down Expand Up @@ -225,7 +230,7 @@ export class IndexedDbComponentProvider extends MemoryComponentProvider {
}

createSyncEngine(cfg: ComponentConfiguration): SyncEngine {
const syncEngine = new MultiTabSyncEngine(
const syncEngine = newMultiTabSyncEngine(
this.localStore,
this.remoteStore,
cfg.datastore,
Expand Down
188 changes: 142 additions & 46 deletions packages/firestore/src/core/sync_engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,94 @@ export interface SyncEngineListener {
* The SyncEngine’s methods should only ever be called by methods running in the
* global async queue.
*/
export class SyncEngine implements RemoteSyncer {
export interface SyncEngine extends RemoteSyncer {
isPrimaryClient: boolean;

/** Subscribes to SyncEngine notifications. Has to be called exactly once. */
subscribe(syncEngineListener: SyncEngineListener): void;

/**
* Initiates the new listen, resolves promise when listen enqueued to the
* server. All the subsequent view snapshots or errors are sent to the
* subscribed handlers. Returns the initial snapshot.
*/
listen(query: Query): Promise<ViewSnapshot>;

/** Stops listening to the query. */
unlisten(query: Query): Promise<void>;

/**
* Initiates the write of local mutation batch which involves adding the
* writes to the mutation queue, notifying the remote store about new
* mutations and raising events for any changes this write caused.
*
* The promise returned by this call is resolved when the above steps
* have completed, *not* when the write was acked by the backend. The
* userCallback is resolved once the write was acked/rejected by the
* backend (or failed locally for any other reason).
*/
write(batch: Mutation[], userCallback: Deferred<void>): Promise<void>;

/**
* Takes an updateFunction in which a set of reads and writes can be performed
* atomically. In the updateFunction, the client can read and write values
* using the supplied transaction object. After the updateFunction, all
* changes will be committed. If a retryable error occurs (ex: some other
* client has changed any of the data referenced), then the updateFunction
* will be called again after a backoff. If the updateFunction still fails
* after all retries, then the transaction will be rejected.
*
* The transaction object passed to the updateFunction contains methods for
* accessing documents and collections. Unlike other datastore access, data
* accessed with the transaction will not reflect local changes that have not
* been committed. For this reason, it is required that all reads are
* performed before any writes. Transactions must be performed while online.
*
* The Deferred input is resolved when the transaction is fully committed.
*/
runTransaction<T>(
asyncQueue: AsyncQueue,
updateFunction: (transaction: Transaction) => Promise<T>,
deferred: Deferred<T>
): void;

/**
* Applies an OnlineState change to the sync engine and notifies any views of
* the change.
*/
applyOnlineStateChange(
onlineState: OnlineState,
source: OnlineStateSource
): void;

/**
* Registers a user callback that resolves when all pending mutations at the moment of calling
* are acknowledged .
*/
registerPendingWritesCallback(callback: Deferred<void>): Promise<void>;

activeLimboDocumentResolutions(): SortedMap<DocumentKey, TargetId>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add // Visible for testing

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.


enqueuedLimboDocumentResolutions(): DocumentKey[];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add // Visible for testing

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.


handleCredentialChange(user: User): Promise<void>;

enableNetwork(): Promise<void>;

disableNetwork(): Promise<void>;

getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet;
}

/**
* An implementation of `SyncEngine` coordinating with other parts of SDK.
*
* Note: some field defined in this class might have public access level, but
* the class is not exported so they are only accessible from this module.
* This is useful to implement optional features (like bundles) in free
* functions, such that they are tree-shakeable.
*/
class SyncEngineImpl implements SyncEngine {
protected syncEngineListener: SyncEngineListener | null = null;

protected queryViewsByQuery = new ObjectMap<Query, QueryView>(
Expand Down Expand Up @@ -198,7 +285,6 @@ export class SyncEngine implements RemoteSyncer {
return true;
}

/** Subscribes to SyncEngine notifications. Has to be called exactly once. */
subscribe(syncEngineListener: SyncEngineListener): void {
debugAssert(
syncEngineListener !== null,
Expand All @@ -212,11 +298,6 @@ export class SyncEngine implements RemoteSyncer {
this.syncEngineListener = syncEngineListener;
}

/**
* Initiates the new listen, resolves promise when listen enqueued to the
* server. All the subsequent view snapshots or errors are sent to the
* subscribed handlers. Returns the initial snapshot.
*/
async listen(query: Query): Promise<ViewSnapshot> {
this.assertSubscribed('listen()');

Expand Down Expand Up @@ -295,7 +376,6 @@ export class SyncEngine implements RemoteSyncer {
return viewChange.snapshot!;
}

/** Stops listening to the query. */
async unlisten(query: Query): Promise<void> {
this.assertSubscribed('unlisten()');

Expand Down Expand Up @@ -342,16 +422,6 @@ export class SyncEngine implements RemoteSyncer {
}
}

/**
* Initiates the write of local mutation batch which involves adding the
* writes to the mutation queue, notifying the remote store about new
* mutations and raising events for any changes this write caused.
*
* The promise returned by this call is resolved when the above steps
* have completed, *not* when the write was acked by the backend. The
* userCallback is resolved once the write was acked/rejected by the
* backend (or failed locally for any other reason).
*/
async write(batch: Mutation[], userCallback: Deferred<void>): Promise<void> {
this.assertSubscribed('write()');

Expand All @@ -369,23 +439,6 @@ export class SyncEngine implements RemoteSyncer {
}
}

/**
* Takes an updateFunction in which a set of reads and writes can be performed
* atomically. In the updateFunction, the client can read and write values
* using the supplied transaction object. After the updateFunction, all
* changes will be committed. If a retryable error occurs (ex: some other
* client has changed any of the data referenced), then the updateFunction
* will be called again after a backoff. If the updateFunction still fails
* after all retries, then the transaction will be rejected.
*
* The transaction object passed to the updateFunction contains methods for
* accessing documents and collections. Unlike other datastore access, data
* accessed with the transaction will not reflect local changes that have not
* been committed. For this reason, it is required that all reads are
* performed before any writes. Transactions must be performed while online.
*
* The Deferred input is resolved when the transaction is fully committed.
*/
runTransaction<T>(
asyncQueue: AsyncQueue,
updateFunction: (transaction: Transaction) => Promise<T>,
Expand Down Expand Up @@ -442,10 +495,6 @@ export class SyncEngine implements RemoteSyncer {
}
}

/**
* Applies an OnlineState change to the sync engine and notifies any views of
* the change.
*/
applyOnlineStateChange(
onlineState: OnlineState,
source: OnlineStateSource
Expand Down Expand Up @@ -568,10 +617,6 @@ export class SyncEngine implements RemoteSyncer {
}
}

/**
* Registers a user callback that resolves when all pending mutations at the moment of calling
* are acknowledged .
*/
async registerPendingWritesCallback(callback: Deferred<void>): Promise<void> {
if (!this.remoteStore.canUseNetwork()) {
logDebug(
Expand Down Expand Up @@ -912,13 +957,46 @@ export class SyncEngine implements RemoteSyncer {
}
}

export function newSyncEngine(
localStore: LocalStore,
remoteStore: RemoteStore,
datastore: Datastore,
// PORTING NOTE: Manages state synchronization in multi-tab environments.
sharedClientState: SharedClientState,
currentUser: User,
maxConcurrentLimboResolutions: number
): SyncEngine {
return new SyncEngineImpl(
localStore,
remoteStore,
datastore,
sharedClientState,
currentUser,
maxConcurrentLimboResolutions
);
}

/**
* An impplementation of SyncEngine that implement SharedClientStateSyncer for
* An extension of SyncEngine that also include SharedClientStateSyncer for
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/include/includes

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

* Multi-Tab synchronization.
*/
// PORTING NOTE: Web only
export class MultiTabSyncEngine extends SyncEngine
implements SharedClientStateSyncer {
export interface MultiTabSyncEngine
extends SharedClientStateSyncer,
SyncEngine {
applyPrimaryState(isPrimary: boolean): Promise<void>;
}

/**
* An implementation of `SyncEngineImpl` providing multi-tab synchronization on
* top of `SyncEngineImpl`.
*
* Note: some field defined in this class might have public access level, but
* the class is not exported so they are only accessible from this module.
* This is useful to implement optional features (like bundles) in free
* functions, such that they are tree-shakeable.
*/
class MultiTabSyncEngineImpl extends SyncEngineImpl {
// The primary state is set to `true` or `false` immediately after Firestore
// startup. In the interim, a client should only be considered primary if
// `isPrimary` is true.
Expand Down Expand Up @@ -1273,3 +1351,21 @@ export class MultiTabSyncEngine extends SyncEngine
}
}
}

export function newMultiTabSyncEngine(
localStore: MultiTabLocalStore,
remoteStore: RemoteStore,
datastore: Datastore,
sharedClientState: SharedClientState,
currentUser: User,
maxConcurrentLimboResolutions: number
): MultiTabSyncEngine {
return new MultiTabSyncEngineImpl(
localStore,
remoteStore,
datastore,
sharedClientState,
currentUser,
maxConcurrentLimboResolutions
);
}