Skip to content

Migrate Database to component framework #2327

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 2 commits into from
Nov 5, 2019
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
78 changes: 60 additions & 18 deletions packages/database/index.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*/

import { FirebaseNamespace, FirebaseApp } from '@firebase/app-types';
import { _FirebaseNamespace } from '@firebase/app-types/private';
import { _FirebaseNamespace, _FirebaseApp } from '@firebase/app-types/private';
import { Database } from './src/api/Database';
import { DataSnapshot } from './src/api/DataSnapshot';
import { Query } from './src/api/Query';
Expand All @@ -30,6 +30,13 @@ import { setSDKVersion } from './src/core/version';
import { CONSTANTS, isNodeSdk } from '@firebase/util';
import { setWebSocketImpl } from './src/realtime/WebSocketConnection';
import { Client } from 'faye-websocket';
import {
Component,
ComponentType,
Provider,
ComponentContainer
} from '@firebase/component';
import { FirebaseAuthInternal } from '@firebase/auth-interop-types';

setWebSocketImpl(Client);

Expand All @@ -51,8 +58,28 @@ export function initStandalone(app: FirebaseApp, url: string, version: string) {
CONSTANTS.NODE_ADMIN = true;
setSDKVersion(version);

/**
* Create a 'auth-internal' component using firebase-admin-node's implementation
* that implements FirebaseAuthInternal.
* ComponentContainer('database-admin') is just a placeholder that doesn't perform
* any actual function.
*/
const authProvider = new Provider<FirebaseAuthInternal>(
'auth-internal',
new ComponentContainer('database-admin')
);
authProvider.setComponent(
new Component(
'auth-internal',
// firebase-admin-node's app.INTERNAL implements FirebaseAuthInternal interface
// eslint-disable-next-line @eslint-tslint/no-explicit-any
() => (app as any).INTERNAL,
ComponentType.PRIVATE
)
);

return {
instance: RepoManager.getInstance().databaseFromApp(app, url),
instance: RepoManager.getInstance().databaseFromApp(app, authProvider, url),
namespace: {
Reference,
Query,
Expand All @@ -71,22 +98,37 @@ export function registerDatabase(instance: FirebaseNamespace) {
setSDKVersion(instance.SDK_VERSION);

// Register the Database Service with the 'firebase' namespace.
const namespace = (instance as _FirebaseNamespace).INTERNAL.registerService(
'database',
(app, unused, url) => RepoManager.getInstance().databaseFromApp(app, url),
// firebase.database namespace properties
{
Reference,
Query,
Database,
DataSnapshot,
enableLogging,
INTERNAL,
ServerValue,
TEST_ACCESS
},
null,
true
const namespace = (instance as _FirebaseNamespace).INTERNAL.registerComponent(
new Component(
'database',
(container, url) => {
/* Dependencies */
// getImmediate for FirebaseApp will always succeed
const app = container.getProvider('app').getImmediate();
const authProvider = container.getProvider('auth-internal');

return RepoManager.getInstance().databaseFromApp(
app,
authProvider,
url
);
},
ComponentType.PUBLIC
)
.setServiceProps(
// firebase.database namespace properties
{
Reference,
Query,
Database,
DataSnapshot,
enableLogging,
INTERNAL,
ServerValue,
TEST_ACCESS
}
)
.setMultipleInstances(true)
);

if (isNodeSdk()) {
Expand Down
48 changes: 32 additions & 16 deletions packages/database/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import * as TEST_ACCESS from './src/api/test_access';
import { isNodeSdk } from '@firebase/util';
import * as types from '@firebase/database-types';
import { setSDKVersion } from './src/core/version';
import { Component, ComponentType } from '@firebase/component';

const ServerValue = Database.ServerValue;

Expand All @@ -37,22 +38,37 @@ export function registerDatabase(instance: FirebaseNamespace) {
setSDKVersion(instance.SDK_VERSION);

// Register the Database Service with the 'firebase' namespace.
const namespace = (instance as _FirebaseNamespace).INTERNAL.registerService(
'database',
(app, unused, url) => RepoManager.getInstance().databaseFromApp(app, url),
// firebase.database namespace properties
{
Reference,
Query,
Database,
DataSnapshot,
enableLogging,
INTERNAL,
ServerValue,
TEST_ACCESS
},
null,
true
const namespace = (instance as _FirebaseNamespace).INTERNAL.registerComponent(
new Component(
'database',
(container, url) => {
/* Dependencies */
// getImmediate for FirebaseApp will always succeed
const app = container.getProvider('app').getImmediate();
const authProvider = container.getProvider('auth-internal');

return RepoManager.getInstance().databaseFromApp(
app,
authProvider,
url
);
},
ComponentType.PUBLIC
)
.setServiceProps(
// firebase.database namespace properties
{
Reference,
Query,
Database,
DataSnapshot,
enableLogging,
INTERNAL,
ServerValue,
TEST_ACCESS
}
)
.setMultipleInstances(true)
);

if (isNodeSdk()) {
Expand Down
2 changes: 1 addition & 1 deletion packages/database/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"test": "yarn test:emulator",
"test:all": "run-p test:browser test:node",
"test:browser": "karma start --single-run",
"test:node": "TS_NODE_CACHE=NO TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' nyc --reporter lcovonly -- mocha 'test/{,!(browser)/**/}*.test.ts' --file index.node.ts --opts ../../config/mocha.node.opts",
"test:node": "TS_NODE_FILES=true TS_NODE_CACHE=NO TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' nyc --reporter lcovonly -- mocha 'test/{,!(browser)/**/}*.test.ts' --file index.node.ts --opts ../../config/mocha.node.opts",
"test:emulator": "ts-node --compiler-options='{\"module\":\"commonjs\"}' ../../scripts/emulator-testing/database-test-runner.ts",
"prepare": "yarn build"
},
Expand Down
57 changes: 37 additions & 20 deletions packages/database/src/core/AuthTokenProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,48 +15,65 @@
* limitations under the License.
*/

import { FirebaseApp } from '@firebase/app-types';
import { FirebaseAuthTokenData } from '@firebase/app-types/private';
import { FirebaseAuthInternal } from '@firebase/auth-interop-types';
import { Provider } from '@firebase/component';
import { log, warn } from './util/util';
import { FirebaseApp } from '@firebase/app-types';

/**
* Abstraction around FirebaseApp's token fetching capabilities.
*/
export class AuthTokenProvider {
/**
* @param {!FirebaseApp} app_
*/
constructor(private app_: FirebaseApp) {}
private auth_: FirebaseAuthInternal | null = null;
constructor(
private app_: FirebaseApp,
private authProvider_: Provider<FirebaseAuthInternal>
) {
this.auth_ = authProvider_.getImmediate({ optional: true });
if (!this.auth_) {
authProvider_.get().then(auth => (this.auth_ = auth));
}
}

/**
* @param {boolean} forceRefresh
* @return {!Promise<FirebaseAuthTokenData>}
*/
getToken(forceRefresh: boolean): Promise<FirebaseAuthTokenData> {
return this.app_['INTERNAL']['getToken'](forceRefresh).then(
null,
// .catch
function(error) {
// TODO: Need to figure out all the cases this is raised and whether
// this makes sense.
if (error && error.code === 'auth/token-not-initialized') {
log('Got auth/token-not-initialized error. Treating as null token.');
return null;
} else {
return Promise.reject(error);
}
if (!this.auth_) {
return Promise.resolve(null);
}

return this.auth_.getToken(forceRefresh).catch(function(error) {
// TODO: Need to figure out all the cases this is raised and whether
// this makes sense.
if (error && error.code === 'auth/token-not-initialized') {
log('Got auth/token-not-initialized error. Treating as null token.');
return null;
} else {
return Promise.reject(error);
}
);
});
}

addTokenChangeListener(listener: (token: string | null) => void) {
// TODO: We might want to wrap the listener and call it with no args to
// avoid a leaky abstraction, but that makes removing the listener harder.
this.app_['INTERNAL']['addAuthTokenListener'](listener);
if (this.auth_) {
this.auth_.addAuthTokenListener(listener);
} else {
setTimeout(() => listener(null), 0);
this.authProvider_
.get()
.then(auth => auth.addAuthTokenListener(listener));
}
}

removeTokenChangeListener(listener: (token: string | null) => void) {
this.app_['INTERNAL']['removeAuthTokenListener'](listener);
this.authProvider_
.get()
.then(auth => auth.removeAuthTokenListener(listener));
}

notifyForInvalidToken() {
Expand Down
7 changes: 5 additions & 2 deletions packages/database/src/core/Repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ import { EventRegistration } from './view/EventRegistration';
import { StatsCollection } from './stats/StatsCollection';
import { Event } from './view/Event';
import { Node } from './snap/Node';
import { FirebaseAuthInternal } from '@firebase/auth-interop-types';
import { Provider } from '@firebase/component';

const INTERRUPT_REASON = 'repo_interrupt';

Expand Down Expand Up @@ -79,9 +81,10 @@ export class Repo {
constructor(
public repoInfo_: RepoInfo,
forceRestClient: boolean,
public app: FirebaseApp
public app: FirebaseApp,
authProvider: Provider<FirebaseAuthInternal>
) {
const authTokenProvider = new AuthTokenProvider(app);
const authTokenProvider = new AuthTokenProvider(app, authProvider);

this.stats_ = StatsManager.getCollection(repoInfo_);

Expand Down
18 changes: 14 additions & 4 deletions packages/database/src/core/RepoManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import { validateUrl } from './util/validation';
import './Repo_transaction';
import { Database } from '../api/Database';
import { RepoInfo } from './RepoInfo';
import { FirebaseAuthInternal } from '@firebase/auth-interop-types';
import { Provider } from '@firebase/component';

/** @const {string} */
const DATABASE_URL_OPTION = 'databaseURL';
Expand Down Expand Up @@ -89,7 +91,11 @@ export class RepoManager {
* @param {!FirebaseApp} app
* @return {!Database}
*/
databaseFromApp(app: FirebaseApp, url?: string): Database {
databaseFromApp(
app: FirebaseApp,
authProvider: Provider<FirebaseAuthInternal>,
url?: string
): Database {
let dbUrl: string | undefined = url || app.options[DATABASE_URL_OPTION];
if (dbUrl === undefined) {
fatal(
Expand Down Expand Up @@ -120,7 +126,7 @@ export class RepoManager {
);
}

const repo = this.createRepo(repoInfo, app);
const repo = this.createRepo(repoInfo, app, authProvider);

return repo.database;
}
Expand Down Expand Up @@ -150,7 +156,11 @@ export class RepoManager {
* @param {!FirebaseApp} app
* @return {!Repo} The Repo object for the specified server / repoName.
*/
createRepo(repoInfo: RepoInfo, app: FirebaseApp): Repo {
createRepo(
repoInfo: RepoInfo,
app: FirebaseApp,
authProvider: Provider<FirebaseAuthInternal>
): Repo {
let appRepos = safeGet(this.repos_, app.name);

if (!appRepos) {
Expand All @@ -164,7 +174,7 @@ export class RepoManager {
'Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'
);
}
repo = new Repo(repoInfo, this.useRestClient_, app);
repo = new Repo(repoInfo, this.useRestClient_, app, authProvider);
appRepos[repoInfo.toURLString()] = repo;

return repo;
Expand Down
13 changes: 1 addition & 12 deletions packages/database/test/browser/crawler_support.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,13 @@
import { expect } from 'chai';
import { forceRestClient } from '../../src/api/test_access';

import {
getRandomNode,
testAuthTokenProvider,
getFreshRepoFromReference
} from '../helpers/util';
import { getRandomNode, getFreshRepoFromReference } from '../helpers/util';

// Some sanity checks for the ReadonlyRestClient crawler support.
describe('Crawler Support', function() {
let initialData;
let normalRef;
let restRef;
let tokenProvider;

beforeEach(function(done) {
normalRef = getRandomNode();
Expand All @@ -38,15 +33,9 @@ describe('Crawler Support', function() {
restRef = getFreshRepoFromReference(normalRef);
forceRestClient(false);

tokenProvider = testAuthTokenProvider(restRef.database.app);

setInitialData(done);
});

afterEach(function() {
tokenProvider.setToken(null);
});

function setInitialData(done) {
// Set some initial data.
initialData = {
Expand Down
Loading