Skip to content

Initialize transport service in Performance Monitoring when performance() is called. #2506

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 4 commits into from
Jan 9, 2020
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
2 changes: 2 additions & 0 deletions packages/performance/src/controllers/perf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ import { Api } from '../services/api_service';
import { FirebaseApp } from '@firebase/app-types';
import { FirebasePerformance } from '@firebase/performance-types';
import { consoleLogger } from '../utils/console_logger';
import { setupTransportService } from '../services/transport_service';

export class PerformanceController implements FirebasePerformance {
constructor(readonly app: FirebaseApp) {
if (Api.getInstance().requiredApisAvailable()) {
setupTransportService();
getInitializationPromise().then(setupOobResources, setupOobResources);
} else {
consoleLogger.info(
Expand Down
82 changes: 0 additions & 82 deletions packages/performance/src/services/cc_service.test.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ describe('Firebase Performance > oob_resources_service', () => {
it('waits for first input delay if polyfill is available', () => {
getIidStub.returns(MOCK_ID);
const api = Api.getInstance();
//@ts-ignore Assignment to read-only property.
api.onFirstInputDelay = stub();
setupOobResources();
clock.tick(1);
Expand All @@ -170,6 +171,7 @@ describe('Firebase Performance > oob_resources_service', () => {
// Underscore is to avoid compiler comlaining about variable being declared but not used.
type FirstInputDelayCallback = (firstInputDelay: number) => void;
let firstInputDelayCallback: FirstInputDelayCallback = (): void => {};
//@ts-ignore Assignment to read-only property.
api.onFirstInputDelay = (cb: FirstInputDelayCallback) => {
firstInputDelayCallback = cb;
};
Expand Down
6 changes: 3 additions & 3 deletions packages/performance/src/services/perf_logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

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

function mockCcHandler(
function mockTransportHandler(
serializer: (...args: any[]) => string
): (...args: any[]) => void {
return (...args) => {
Expand All @@ -65,7 +65,7 @@ describe('Performance Monitoring > perf_logger', () => {
beforeEach(() => {
getIidStub = stub(iidService, 'getIid');
addToQueueStub = stub();
stub(ccService, 'ccHandler').callsFake(mockCcHandler);
stub(transportService, 'transportHandler').callsFake(mockTransportHandler);
stub(Api.prototype, 'getUrl').returns(PAGE_URL);
stub(Api.prototype, 'getTimeOrigin').returns(TIME_ORIGIN);
stub(initializationService, 'isPerfInitialized').returns(true);
Expand Down
4 changes: 2 additions & 2 deletions packages/performance/src/services/perf_logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
isPerfInitialized,
getInitializationPromise
} from './initialization_service';
import { ccHandler } from './cc_service';
import { transportHandler } from './transport_service';
import { SDK_VERSION } from '../constants';

const enum ResourceType {
Expand Down Expand Up @@ -95,7 +95,7 @@ function sendLog(
resourceType: ResourceType
): void {
if (!logger) {
logger = ccHandler(serializer);
logger = transportHandler(serializer);
}
logger(resource, resourceType);
}
Expand Down
74 changes: 74 additions & 0 deletions packages/performance/src/services/transport_service.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @license
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { stub, useFakeTimers, SinonStub, SinonFakeTimers } from 'sinon';
import { use, expect } from 'chai';
import * as sinonChai from 'sinon-chai';
import { transportHandler, setupTransportService } from './transport_service';

use(sinonChai);

describe('Firebase Performance > transport_service', () => {
let fetchStub: SinonStub<[RequestInfo, RequestInit?], Promise<Response>>;
const INITIAL_SEND_TIME_DELAY_MS = 5.5 * 1000;
const DEFAULT_SEND_INTERVAL_MS = 10 * 1000;
// Starts date at timestamp 1 instead of 0, otherwise it causes validation errors.
const clock: SinonFakeTimers = useFakeTimers(1);
setupTransportService();
const testTransportHandler = transportHandler((...args) => {
return args[0];
});

beforeEach(() => {
fetchStub = stub(window, 'fetch');
});

afterEach(() => {
fetchStub.restore();
});

it('throws an error when logging an empty message', () => {
expect(() => {
testTransportHandler('');
}).to.throw;
});

it('does not attempt to log an event to clearcut after INITIAL_SEND_TIME_DELAY_MS if queue is empty', () => {
fetchStub.resolves(
new Response('', {
status: 200,
headers: { 'Content-type': 'application/json' }
})
);

clock.tick(INITIAL_SEND_TIME_DELAY_MS);
expect(fetchStub).to.not.have.been.called;
});

it('attempts to log an event to clearcut after DEFAULT_SEND_INTERVAL_MS if queue not empty', () => {
fetchStub.resolves(
new Response('', {
status: 200,
headers: { 'Content-type': 'application/json' }
})
);

testTransportHandler('someEvent');
clock.tick(DEFAULT_SEND_INTERVAL_MS);
expect(fetchStub).to.have.been.calledOnce;
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ interface Log {

let queue: BatchEvent[] = [];

let isTransportSetup: boolean = false;

export function setupTransportService(): void {
if (!isTransportSetup) {
processQueue(INITIAL_SEND_TIME_DELAY_MS);
isTransportSetup = true;
}
}

function processQueue(timeOffset: number): void {
setTimeout(() => {
// If there is no remainingTries left, stop retrying.
Expand Down Expand Up @@ -120,8 +129,6 @@ function processQueue(timeOffset: number): void {
}, timeOffset);
}

processQueue(INITIAL_SEND_TIME_DELAY_MS);

function addToQueue(evt: BatchEvent): void {
if (!evt.eventTime || !evt.message) {
throw ERROR_FACTORY.create(ErrorCode.INVALID_CC_LOG);
Expand All @@ -131,7 +138,7 @@ function addToQueue(evt: BatchEvent): void {
}

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