Skip to content

Commit 9c28e7b

Browse files
authored
Initialize transport service in Performance Monitoring when performance() is called. (#2506)
* Initialize transport service after performance() is called. * Run transport service setup only once. * Add @ts-ignore and update naming of transportHandler. * Remove done() and start transport timer right after component API instance is ready.
1 parent 689f035 commit 9c28e7b

File tree

7 files changed

+93
-90
lines changed

7 files changed

+93
-90
lines changed

packages/performance/src/controllers/perf.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,12 @@ import { Api } from '../services/api_service';
2222
import { FirebaseApp } from '@firebase/app-types';
2323
import { FirebasePerformance } from '@firebase/performance-types';
2424
import { consoleLogger } from '../utils/console_logger';
25+
import { setupTransportService } from '../services/transport_service';
2526

2627
export class PerformanceController implements FirebasePerformance {
2728
constructor(readonly app: FirebaseApp) {
2829
if (Api.getInstance().requiredApisAvailable()) {
30+
setupTransportService();
2931
getInitializationPromise().then(setupOobResources, setupOobResources);
3032
} else {
3133
consoleLogger.info(

packages/performance/src/services/cc_service.test.ts

Lines changed: 0 additions & 82 deletions
This file was deleted.

packages/performance/src/services/oob_resources_service.test.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ describe('Firebase Performance > oob_resources_service', () => {
150150
it('waits for first input delay if polyfill is available', () => {
151151
getIidStub.returns(MOCK_ID);
152152
const api = Api.getInstance();
153+
//@ts-ignore Assignment to read-only property.
153154
api.onFirstInputDelay = stub();
154155
setupOobResources();
155156
clock.tick(1);
@@ -170,6 +171,7 @@ describe('Firebase Performance > oob_resources_service', () => {
170171
// Underscore is to avoid compiler comlaining about variable being declared but not used.
171172
type FirstInputDelayCallback = (firstInputDelay: number) => void;
172173
let firstInputDelayCallback: FirstInputDelayCallback = (): void => {};
174+
//@ts-ignore Assignment to read-only property.
173175
api.onFirstInputDelay = (cb: FirstInputDelayCallback) => {
174176
firstInputDelayCallback = cb;
175177
};

packages/performance/src/services/perf_logger.test.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
import { stub, SinonStub, useFakeTimers, SinonFakeTimers } from 'sinon';
1919
import { Trace } from '../resources/trace';
20-
import * as ccService from './cc_service';
20+
import * as transportService from './transport_service';
2121
import * as iidService from './iid_service';
2222
import { expect } from 'chai';
2323
import { Api, setupApi } from './api_service';
@@ -48,7 +48,7 @@ describe('Performance Monitoring > perf_logger', () => {
4848
let getIidStub: SinonStub<[], string | undefined>;
4949
let clock: SinonFakeTimers;
5050

51-
function mockCcHandler(
51+
function mockTransportHandler(
5252
serializer: (...args: any[]) => string
5353
): (...args: any[]) => void {
5454
return (...args) => {
@@ -65,7 +65,7 @@ describe('Performance Monitoring > perf_logger', () => {
6565
beforeEach(() => {
6666
getIidStub = stub(iidService, 'getIid');
6767
addToQueueStub = stub();
68-
stub(ccService, 'ccHandler').callsFake(mockCcHandler);
68+
stub(transportService, 'transportHandler').callsFake(mockTransportHandler);
6969
stub(Api.prototype, 'getUrl').returns(PAGE_URL);
7070
stub(Api.prototype, 'getTimeOrigin').returns(TIME_ORIGIN);
7171
stub(initializationService, 'isPerfInitialized').returns(true);

packages/performance/src/services/perf_logger.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import {
3030
isPerfInitialized,
3131
getInitializationPromise
3232
} from './initialization_service';
33-
import { ccHandler } from './cc_service';
33+
import { transportHandler } from './transport_service';
3434
import { SDK_VERSION } from '../constants';
3535

3636
const enum ResourceType {
@@ -95,7 +95,7 @@ function sendLog(
9595
resourceType: ResourceType
9696
): void {
9797
if (!logger) {
98-
logger = ccHandler(serializer);
98+
logger = transportHandler(serializer);
9999
}
100100
logger(resource, resourceType);
101101
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/**
2+
* @license
3+
* Copyright 2019 Google Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
import { stub, useFakeTimers, SinonStub, SinonFakeTimers } from 'sinon';
19+
import { use, expect } from 'chai';
20+
import * as sinonChai from 'sinon-chai';
21+
import { transportHandler, setupTransportService } from './transport_service';
22+
23+
use(sinonChai);
24+
25+
describe('Firebase Performance > transport_service', () => {
26+
let fetchStub: SinonStub<[RequestInfo, RequestInit?], Promise<Response>>;
27+
const INITIAL_SEND_TIME_DELAY_MS = 5.5 * 1000;
28+
const DEFAULT_SEND_INTERVAL_MS = 10 * 1000;
29+
// Starts date at timestamp 1 instead of 0, otherwise it causes validation errors.
30+
const clock: SinonFakeTimers = useFakeTimers(1);
31+
setupTransportService();
32+
const testTransportHandler = transportHandler((...args) => {
33+
return args[0];
34+
});
35+
36+
beforeEach(() => {
37+
fetchStub = stub(window, 'fetch');
38+
});
39+
40+
afterEach(() => {
41+
fetchStub.restore();
42+
});
43+
44+
it('throws an error when logging an empty message', () => {
45+
expect(() => {
46+
testTransportHandler('');
47+
}).to.throw;
48+
});
49+
50+
it('does not attempt to log an event to clearcut after INITIAL_SEND_TIME_DELAY_MS if queue is empty', () => {
51+
fetchStub.resolves(
52+
new Response('', {
53+
status: 200,
54+
headers: { 'Content-type': 'application/json' }
55+
})
56+
);
57+
58+
clock.tick(INITIAL_SEND_TIME_DELAY_MS);
59+
expect(fetchStub).to.not.have.been.called;
60+
});
61+
62+
it('attempts to log an event to clearcut after DEFAULT_SEND_INTERVAL_MS if queue not empty', () => {
63+
fetchStub.resolves(
64+
new Response('', {
65+
status: 200,
66+
headers: { 'Content-type': 'application/json' }
67+
})
68+
);
69+
70+
testTransportHandler('someEvent');
71+
clock.tick(DEFAULT_SEND_INTERVAL_MS);
72+
expect(fetchStub).to.have.been.calledOnce;
73+
});
74+
});

packages/performance/src/services/cc_service.ts renamed to packages/performance/src/services/transport_service.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,15 @@ interface Log {
5252

5353
let queue: BatchEvent[] = [];
5454

55+
let isTransportSetup: boolean = false;
56+
57+
export function setupTransportService(): void {
58+
if (!isTransportSetup) {
59+
processQueue(INITIAL_SEND_TIME_DELAY_MS);
60+
isTransportSetup = true;
61+
}
62+
}
63+
5564
function processQueue(timeOffset: number): void {
5665
setTimeout(() => {
5766
// If there is no remainingTries left, stop retrying.
@@ -120,8 +129,6 @@ function processQueue(timeOffset: number): void {
120129
}, timeOffset);
121130
}
122131

123-
processQueue(INITIAL_SEND_TIME_DELAY_MS);
124-
125132
function addToQueue(evt: BatchEvent): void {
126133
if (!evt.eventTime || !evt.message) {
127134
throw ERROR_FACTORY.create(ErrorCode.INVALID_CC_LOG);
@@ -131,7 +138,7 @@ function addToQueue(evt: BatchEvent): void {
131138
}
132139

133140
/** Log handler for cc service to send the performance logs to the server. */
134-
export function ccHandler(
141+
export function transportHandler(
135142
// eslint-disable-next-line @typescript-eslint/no-explicit-any
136143
serializer: (...args: any[]) => string
137144
): (...args: unknown[]) => void {

0 commit comments

Comments
 (0)