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

feat(performance): AngularFire Performance Monitoring #2064

Merged
merged 14 commits into from
May 24, 2019
Merged
Show file tree
Hide file tree
Changes from 7 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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ Firebase offers two cloud-based, client-accessible database solutions that suppo
### Send push notifications
- [Getting started with Firebase Messaging](docs/messaging/messaging.md)

### Monitor your application performance in production

- [Getting started with Performance Monitoring](docs/performance/getting-started.md)

### Directly call Cloud Functions
- [Getting started with Callable Functions](docs/functions/functions.md)

Expand Down
73 changes: 73 additions & 0 deletions docs/performance/getting-started.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Getting started with Performance Monitoring

## Basic usage

**TBD** basic explainer
jamesdaniels marked this conversation as resolved.
Show resolved Hide resolved

```ts
constructor(private afp: AngularFirePerformance, private afs: AngularFirestore) {}

ngOnInit() {
this.articles = afs.collection('articles')
.collection('articles', ref => ref.orderBy('publishedAt', 'desc'))
.snapshotChanges()
.pipe(
this.afp.trace('getArticles'),
jamesdaniels marked this conversation as resolved.
Show resolved Hide resolved
map(articles => ...)
);
}
```

`trace(name:string)` will trace the time it takes for your observable to either complete or emit it's first value. Beyond the basic trace there are three other operators:
jamesdaniels marked this conversation as resolved.
Show resolved Hide resolved
jamesdaniels marked this conversation as resolved.
Show resolved Hide resolved

### `traceComplete(name:string)`
jamesdaniels marked this conversation as resolved.
Show resolved Hide resolved

Traces the observable until the completion.

### `traceUntil(name:string, test: (T) => Boolean)`

Traces the observable until the first emission that passes the provided test.

### `traceFirst(name: string)`

Traces the observable until the first emission or the first emission that matches the provided test.

## Advanced usage

### `trace$(...) => Observable<void>`

`(name:string)`
`(name:string, options: TraceOptions)`

Observable version of `firebase/perf`'s `.trace` method; the basis for `AngularFirePerfomance`'s pipes.

`.subscribe()` is equivalent to calling `.start()`
`.unsubscribe()` is equivalent to calling `.stop()`

### `TraceOptions`

**TBD explain how each option is used by `.trace$`**
jamesdaniels marked this conversation as resolved.
Show resolved Hide resolved

```ts
export const gameUpdate = (state: State, input: Input): State => (
afp.traceComplete('game', {
pluckMetrics: ['score'],
attribute$: { user: this.afAuth.user }
}),
whileNotGameOver(state, input),
processInput(state, input),
updateState(state)
);
```

```ts
export type TraceOptions = {
pluckMetrics?: [string],
pluckAttributes?: [string],
metrics?: { [key:string]: number },
attributes?: { [key:string]: string },
attribute$?: { [key:string]: Observable<string> },
incrementMetric$: { [key:string]: Observable<number|void|null|undefined> },
metric$?: { [key:string]: Observable<number> }
};
```
2 changes: 2 additions & 0 deletions karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,15 @@ module.exports = function(config) {
'node_modules/firebase/firebase-database.js',
'node_modules/firebase/firebase-firestore.js',
'node_modules/firebase/firebase-functions.js',
'node_modules/firebase/firebase-performance.js',
'node_modules/firebase/firebase-storage.js',
'dist/packages-dist/bundles/core.umd.{js,map}',
'dist/packages-dist/bundles/auth.umd.{js,map}',
'dist/packages-dist/bundles/database.umd.{js,map}',
'dist/packages-dist/bundles/firestore.umd.{js,map}',
'dist/packages-dist/bundles/functions.umd.{js,map}',
'dist/packages-dist/bundles/storage.umd.{js,map}',
'dist/packages-dist/bundles/performance.umd.{js,map}',
'dist/packages-dist/bundles/database-deprecated.umd.{js,map}',
'dist/packages-dist/bundles/test.umd.{js,map}',
],
Expand Down
1 change: 1 addition & 0 deletions src/core/firebase.app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export class FirebaseApp {
auth: () => FirebaseAuth;
database: (databaseURL?: string) => FirebaseDatabase;
messaging: () => FirebaseMessaging;
performance: () => any; // SEMVER: once >= 6 import performance.Performance
storage: (storageBucket?: string) => FirebaseStorage;
delete: () => Promise<void>;
firestore: () => FirebaseFirestore;
Expand Down
1 change: 1 addition & 0 deletions src/performance/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './performance.spec';
1 change: 1 addition & 0 deletions src/performance/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './public_api';
30 changes: 30 additions & 0 deletions src/performance/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "@angular/fire/performance",
"version": "ANGULARFIRE2_VERSION",
"description": "The performance monitoring module",
"main": "../bundles/performance.umd.js",
"module": "index.js",
"es2015": "./es2015/index.js",
"keywords": [
"angular",
"firebase",
"rxjs"
],
"repository": {
"type": "git",
"url": "git+https://github.com/angular/angularfire2.git"
},
"author": "angular,firebase",
"license": "MIT",
"peerDependencies": {
"@angular/fire": "ANGULARFIRE2_VERSION",
"@angular/common": "ANGULAR_VERSION",
"@angular/core": "ANGULAR_VERSION",
"@angular/platform-browser": "ANGULAR_VERSION",
"@angular/platform-browser-dynamic": "ANGULAR_VERSION",
"firebase": "FIREBASE_VERSION",
"rxjs": "RXJS_VERSION",
"zone.js": "ZONEJS_VERSION"
},
"typings": "index.d.ts"
}
9 changes: 9 additions & 0 deletions src/performance/performance.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { NgModule } from '@angular/core';
import { AngularFirePerformance } from './performance';

import 'firebase/performance';

@NgModule({
providers: [ AngularFirePerformance ]
})
export class AngularFirePerformanceModule { }
36 changes: 36 additions & 0 deletions src/performance/performance.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { TestBed, inject } from '@angular/core/testing';
import { FirebaseApp, AngularFireModule } from '@angular/fire';
import { AngularFirePerformance, AngularFirePerformanceModule } from '@angular/fire/performance';
import { COMMON_CONFIG } from './test-config';

describe('AngularFirePerformance', () => {
let app: FirebaseApp;
let afp: AngularFirePerformance;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [
AngularFireModule.initializeApp(COMMON_CONFIG),
AngularFirePerformanceModule
]
});
inject([FirebaseApp, AngularFirePerformance], (app_: FirebaseApp, _perf: AngularFirePerformance) => {
app = app_;
afp = _perf;
})();
});

afterEach(done => {
app.delete();
done();
});

it('should be exist', () => {
expect(afp instanceof AngularFirePerformance).toBe(true);
});

it('should have the Performance instance', () => {
expect(afp.performance).toBeDefined();
});

});
98 changes: 98 additions & 0 deletions src/performance/performance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { Injectable, NgZone, ApplicationRef, InjectionToken, Inject, Optional } from '@angular/core';
import { Observable } from 'rxjs';
import { first, tap } from 'rxjs/operators';
import { performance } from 'firebase/app';

export const AUTOMATICALLY_TRACE_CORE_NG_METRICS = new InjectionToken<boolean>('angularfire2.performance.auto_trace');

export type TraceOptions = {
metrics: {[key:string]: number},
attributes?:{[key:string]:string},
attribute$?:{[key:string]:Observable<string>},
incrementMetric$:{[key:string]: Observable<number|void|null|undefined>},
metric$?:{[key:string]: Observable<number>}
};

@Injectable()
export class AngularFirePerformance {

performance: performance.Performance;

constructor(
@Optional() @Inject(AUTOMATICALLY_TRACE_CORE_NG_METRICS) automaticallyTraceCoreNgMetrics:boolean|null,
appRef: ApplicationRef,
private zone: NgZone
) {

this.performance = zone.runOutsideAngular(() => performance());
jamesdaniels marked this conversation as resolved.
Show resolved Hide resolved

if (automaticallyTraceCoreNgMetrics != false) {

// TODO detirmine more built in metrics
appRef.isStable.pipe(
this.traceComplete('isStable'),
first(it => it)
).subscribe();

}

}

trace$ = (name:string, options?: TraceOptions) => new Observable<void>(emitter =>
this.zone.runOutsideAngular(() => {
const trace = this.performance.trace(name);
options && options.metrics && Object.keys(options.metrics).forEach(metric => {
trace.putMetric(metric, options!.metrics![metric])
});
options && options.attributes && Object.keys(options.attributes).forEach(attribute => {
trace.putAttribute(attribute, options!.attributes![attribute])
});
const attributeSubscriptions = options && options.attribute$ ? Object.keys(options.attribute$).map(attribute =>
options!.attribute$![attribute].subscribe(next => trace.putAttribute(attribute, next))
) : [];
const metricSubscriptions = options && options.metric$ ? Object.keys(options.metric$).map(metric =>
options!.metric$![metric].subscribe(next => trace.putMetric(metric, next))
) : [];
const incrementOnSubscriptions = options && options.incrementMetric$ ? Object.keys(options.incrementMetric$).map(metric =>
options!.incrementMetric$![metric].subscribe(next => trace.incrementMetric(metric, next || undefined))
) : [];
emitter.next(trace.start());
return { unsubscribe: () => {
trace.stop();
metricSubscriptions.forEach(m => m.unsubscribe());
incrementOnSubscriptions.forEach(m => m.unsubscribe());
attributeSubscriptions.forEach(m => m.unsubscribe());
}};
})
);

traceUntil = <T=any>(name:string, test: (a:T) => boolean, options?: TraceOptions) => (source$: Observable<T>) => {
const traceSubscription = this.trace$(name, options).subscribe();
return source$.pipe(
tap(a => { if (test(a)) { traceSubscription.unsubscribe() }})
)
};

traceComplete = <T=any>(name:string, options?: TraceOptions) => (source$: Observable<T>) => {
const traceSubscription = this.trace$(name, options).subscribe();
return source$.pipe(
tap(
() => {},
() => {},
() => traceSubscription.unsubscribe()
)
)
};

trace = <T=any>(name:string, options?: TraceOptions) => (source$: Observable<T>) => {
const traceSubscription = this.trace$(name, options).subscribe();
return source$.pipe(
tap(
() => traceSubscription.unsubscribe(),
() => {},
() => traceSubscription.unsubscribe()
)
)
};

}
2 changes: 2 additions & 0 deletions src/performance/public_api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './performance';
export * from './performance.module';
10 changes: 10 additions & 0 deletions src/performance/test-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

export const COMMON_CONFIG = {
apiKey: "AIzaSyBVSy3YpkVGiKXbbxeK0qBnu3-MNZ9UIjA",
authDomain: "angularfire2-test.firebaseapp.com",
databaseURL: "https://angularfire2-test.firebaseio.com",
projectId: "angularfire2-test",
storageBucket: "angularfire2-test.appspot.com",
messagingSenderId: "920323787688",
appId: "1:920323787688:web:2253a0e5eb5b9a8b"
};
33 changes: 33 additions & 0 deletions src/performance/tsconfig-build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"compilerOptions": {
"baseUrl": ".",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"module": "es2015",
"target": "es2015",
"noImplicitAny": false,
"outDir": "../../dist/packages-dist/performance/es2015",
"rootDir": ".",
"sourceMap": true,
"inlineSources": true,
"declaration": false,
"removeComments": true,
"strictNullChecks": true,
"lib": ["es2015", "dom", "es2015.promise", "es2015.collection", "es2015.iterable"],
"skipLibCheck": true,
"moduleResolution": "node",
"paths": {
"@angular/fire": ["../../dist/packages-dist"]
}
},
"files": [
"index.ts",
"../../node_modules/zone.js/dist/zone.js.d.ts"
],
"angularCompilerOptions": {
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"enableSummariesForJit": false
}
}

19 changes: 19 additions & 0 deletions src/performance/tsconfig-esm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"extends": "./tsconfig-build.json",
"compilerOptions": {
"target": "es5",
"outDir": "../../dist/packages-dist/performance",
"declaration": true
},
"files": [
"public_api.ts",
"../../node_modules/zone.js/dist/zone.js.d.ts"
],
"angularCompilerOptions": {
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"enableSummariesForJit": false,
"flatModuleOutFile": "index.js",
"flatModuleId": "@angular/fire/performance"
}
}
13 changes: 13 additions & 0 deletions src/performance/tsconfig-test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "./tsconfig-esm.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@angular/fire": ["../../dist/packages-dist"]
}
},
"files": [
"index.spec.ts",
"../../node_modules/zone.js/dist/zone.js.d.ts"
]
}
1 change: 1 addition & 0 deletions src/root.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export * from './packages-dist/database/list/snapshot-changes.spec';
export * from './packages-dist/database/list/state-changes.spec';
export * from './packages-dist/database/list/audit-trail.spec';
export * from './packages-dist/storage/storage.spec';
export * from './packages-dist/performance/performance.spec';
//export * from './packages-dist/messaging/messaging.spec';

// // Since this a deprecated API, we run on it on manual tests only
Expand Down
1 change: 1 addition & 0 deletions src/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"@angular/fire/functions": ["./functions"],
"@angular/fire/storage": ["./storage"],
"@angular/fire/messaging": ["./messaging"],
"@angular/fire/performance": ["./performance"],
"@angular/fire/database-deprecated": ["./database-deprecated"]
},
"rootDir": ".",
Expand Down
Loading