Skip to content
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

Emulator Idempotency: Firestore #8780

Merged
merged 8 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions common/api-review/firestore-lite.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -494,4 +494,5 @@ export class WriteBatch {
// @public
export function writeBatch(firestore: Firestore): WriteBatch;


Copy link
Contributor

Choose a reason for hiding this comment

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

i did not see this API proposal 😮

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It was a blank document. :)

```
30 changes: 25 additions & 5 deletions packages/firestore/src/lite-api/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
} from '@firebase/app';
import {
createMockUserToken,
deepEqual,
EmulatorMockTokenOptions,
getDefaultEmulatorHostnameAndPort
} from '@firebase/util';
Expand Down Expand Up @@ -71,6 +72,9 @@ export class Firestore implements FirestoreService {

private _settings = new FirestoreSettingsImpl({});
private _settingsFrozen = false;
private _emulatorOptions: {
mockUserToken?: EmulatorMockTokenOptions | string;
} = {};

// A task that is assigned when the terminate() is invoked and resolved when
// all components have shut down. Otherwise, Firestore is not terminated,
Expand Down Expand Up @@ -119,6 +123,8 @@ export class Firestore implements FirestoreService {
);
}
this._settings = new FirestoreSettingsImpl(settings);
this._emulatorOptions = settings.emulatorOptions || {};

if (settings.credentials !== undefined) {
this._authCredentials = makeAuthCredentialsProvider(settings.credentials);
}
Expand All @@ -128,6 +134,10 @@ export class Firestore implements FirestoreService {
return this._settings;
}

_getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {
return this._emulatorOptions;
}

_freezeSettings(): FirestoreSettingsImpl {
this._settingsFrozen = true;
return this._settings;
Expand Down Expand Up @@ -316,20 +326,30 @@ export function connectFirestoreEmulator(
): void {
firestore = cast(firestore, Firestore);
const settings = firestore._getSettings();
const existingConfig = {
...settings,
emulatorOptions: firestore._getEmulatorOptions()
};
const newHostSetting = `${host}:${port}`;

if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {
logWarn(
'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +
'will be used.'
);
}

firestore._setSettings({
const newConfig = {
...settings,
host: newHostSetting,
ssl: false
});
ssl: false,
emulatorOptions: options
};
// No-op if the new configuration matches the current configuration. This supports SSR
// enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.
if (deepEqual(newConfig, existingConfig)) {
return;
}

firestore._setSettings(newConfig);

if (options.mockUserToken) {
let token: string;
Expand Down
3 changes: 3 additions & 0 deletions packages/firestore/src/lite-api/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
* limitations under the License.
*/

import { EmulatorMockTokenOptions } from '@firebase/util';

import { FirestoreLocalCache } from '../api/cache_config';
import { CredentialsSettings } from '../api/credentials';
import {
Expand Down Expand Up @@ -80,6 +82,7 @@ export interface PrivateSettings extends FirestoreSettings {
experimentalAutoDetectLongPolling?: boolean;
experimentalLongPollingOptions?: ExperimentalLongPollingOptions;
useFetchStreams?: boolean;
emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };

localCache?: FirestoreLocalCache;
}
Expand Down
52 changes: 43 additions & 9 deletions packages/firestore/test/integration/api/validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ import {
import {
ALT_PROJECT_ID,
DEFAULT_PROJECT_ID,
TARGET_DB_ID
TARGET_DB_ID,
USE_EMULATOR,
getEmulatorPort
} from '../util/settings';

// We're using 'as any' to pass invalid values to APIs for testing purposes.
Expand Down Expand Up @@ -179,7 +181,19 @@ apiDescribe('Validation:', persistence => {

validationIt(
persistence,
'disallows calling connectFirestoreEmulator() after use',
'connectFirestoreEmulator() can set mockUserToken object',
() => {
const db = newTestFirestore(newTestApp('test-project'));
// Verify that this doesn't throw.
connectFirestoreEmulator(db, '127.0.0.1', 9000, {
mockUserToken: { sub: 'foo' }
});
}
);

validationIt(
persistence,
'disallows calling connectFirestoreEmulator() for first time after use',
async db => {
const errorMsg =
'Firestore has already been started and its settings can no longer be changed.';
Expand All @@ -193,13 +207,33 @@ apiDescribe('Validation:', persistence => {

validationIt(
persistence,
'connectFirestoreEmulator() can set mockUserToken object',
() => {
const db = newTestFirestore(newTestApp('test-project'));
// Verify that this doesn't throw.
connectFirestoreEmulator(db, '127.0.0.1', 9000, {
mockUserToken: { sub: 'foo' }
});
'allows calling connectFirestoreEmulator() after use with same config',
async db => {
if (USE_EMULATOR) {
const port = getEmulatorPort();
connectFirestoreEmulator(db, '127.0.0.1', port);
await setDoc(doc(db, 'foo/bar'), {});
expect(() =>
connectFirestoreEmulator(db, '127.0.0.1', port)
).to.not.throw();
}
}
);

validationIt(
persistence,
'disallows calling connectFirestoreEmulator() after use with different config',
async db => {
if (USE_EMULATOR) {
const errorMsg =
'Firestore has already been started and its settings can no longer be changed.';
const port = getEmulatorPort();
connectFirestoreEmulator(db, '127.0.0.1', port);
await setDoc(doc(db, 'foo/bar'), {});
expect(() =>
connectFirestoreEmulator(db, '127.0.0.1', port + 1)
).to.throw(errorMsg);
}
}
);

Expand Down
4 changes: 4 additions & 0 deletions packages/firestore/test/integration/util/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ function getFirestoreHost(targetBackend: TargetBackend): string {
}
}

export function getEmulatorPort(): number {
return parseInt(process.env.FIRESTORE_EMULATOR_PORT || '8080', 10);
}

function getSslEnabled(targetBackend: TargetBackend): boolean {
return targetBackend !== TargetBackend.EMULATOR;
}
Expand Down
11 changes: 11 additions & 0 deletions packages/firestore/test/unit/api/database.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,17 @@ describe('Settings', () => {
expect(db._getSettings().ssl).to.be.false;
});

it('gets privateSettings from useEmulator', () => {
// Use a new instance of Firestore in order to configure settings.
const db = newTestFirestore();
const emulatorOptions = { mockUserToken: 'test' };
connectFirestoreEmulator(db, '127.0.0.1', 9000, emulatorOptions);

expect(db._getSettings().host).to.exist.and.to.equal('127.0.0.1:9000');
expect(db._getSettings().ssl).to.exist.and.to.be.false;
expect(db._getEmulatorOptions()).to.equal(emulatorOptions);
});

it('prefers host from useEmulator to host from settings', () => {
// Use a new instance of Firestore in order to configure settings.
const db = newTestFirestore();
Expand Down
Loading