Skip to content

Create a logging service with flagsetDeliveryMetricsExportedToBigQueryEnabled to enable/disable #5139

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 16 commits into from
Aug 17, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
5 changes: 5 additions & 0 deletions .changeset/bright-clouds-pretend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@firebase/messaging': minor
---

Allows retrieval of `messageId` from `MessagePayload`.
6 changes: 6 additions & 0 deletions .changeset/quiet-moles-grab.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@firebase/messaging-exp': minor
---

Allows retrieval of `messageId` from `MessagePayload`.
Add `setDeliveryMetricsExportedToBigQueryEnabled` to enable/disable Firebase Messaging Big Query Export.
4 changes: 1 addition & 3 deletions common/api-review/messaging-exp.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@ export interface FcmOptions {
export interface FirebaseMessaging {
}

// @internal (undocumented)
export type _FirebaseMessagingName = 'messaging';

// @public
export function getMessaging(app?: FirebaseApp): FirebaseMessaging;

Expand All @@ -48,6 +45,7 @@ export interface MessagePayload {
};
fcmOptions?: FcmOptions;
from: string;
messageId: string;
notification?: NotificationPayload;
}

Expand Down
20 changes: 20 additions & 0 deletions packages-exp/messaging-exp/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { deleteToken as _deleteToken } from './api/deleteToken';
import { getToken as _getToken } from './api/getToken';
import { onBackgroundMessage as _onBackgroundMessage } from './api/onBackgroundMessage';
import { onMessage as _onMessage } from './api/onMessage';
import { _setDeliveryMetricsExportedToBigQueryEnabled } from './api/setDeliveryMetricsExportedToBigQueryEnabled';

/**
* Retrieves a Firebase Cloud Messaging instance.
Expand Down Expand Up @@ -141,3 +142,22 @@ export function onBackgroundMessage(
messaging = getModularInstance(messaging);
return _onBackgroundMessage(messaging as MessagingService, nextOrObserver);
}

/**
* Enables or disables Firebase Cloud Messaging message delivery metrics export to BigQuery. By
* default, message delivery metrics are not exported to BigQuery. Use this method to enable or
* disable the export at runtime.
*
* @param messaging - The `FirebaseMessaging` instance.
* @param enable - Whether Firebase Cloud Messaging should export message delivery metrics to
* BigQuery.
*
* @public
*/
export function setDeliveryMetricsExportedToBigQueryEnabled(
messaging: FirebaseMessaging,
enable: boolean
): void {
messaging = getModularInstance(messaging);
return _setDeliveryMetricsExportedToBigQueryEnabled(messaging, enable);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @license
* Copyright 2020 Google LLC
*
* 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 { FirebaseMessaging } from '../interfaces/public-types';
import { MessagingService } from '../messaging-service';

export function _setDeliveryMetricsExportedToBigQueryEnabled(
messaging: FirebaseMessaging,
enable: boolean
): void {
(messaging as MessagingService).deliveryMetricsExportedToBigQueryEnabled = enable;
}
21 changes: 15 additions & 6 deletions packages-exp/messaging-exp/src/helpers/externalizePayload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,16 @@ describe('externalizePayload', () => {
},
from: 'from',
// eslint-disable-next-line camelcase
collapse_key: 'collapse'
collapse_key: 'collapse',
// eslint-disable-next-line camelcase
exposed_message_id: 'mid'
};

const payload: MessagePayload = {
notification: { title: 'title', body: 'body', image: 'image' },
from: 'from',
collapseKey: 'collapse'
collapseKey: 'collapse',
messageId: 'mid'
};
expect(externalizePayload(internalPayload)).to.deep.equal(payload);
});
Expand All @@ -50,13 +53,16 @@ describe('externalizePayload', () => {
},
from: 'from',
// eslint-disable-next-line camelcase
collapse_key: 'collapse'
collapse_key: 'collapse',
// eslint-disable-next-line camelcase
exposed_message_id: 'mid'
};

const payload: MessagePayload = {
data: { foo: 'foo', bar: 'bar', baz: 'baz' },
from: 'from',
collapseKey: 'collapse'
collapseKey: 'collapse',
messageId: 'mid'
};
expect(externalizePayload(internalPayload)).to.deep.equal(payload);
});
Expand All @@ -80,7 +86,9 @@ describe('externalizePayload', () => {
},
from: 'from',
// eslint-disable-next-line camelcase
collapse_key: 'collapse'
collapse_key: 'collapse',
// eslint-disable-next-line camelcase
exposed_message_id: 'mid'
};

const payload: MessagePayload = {
Expand All @@ -99,7 +107,8 @@ describe('externalizePayload', () => {
analyticsLabel: 'label'
},
from: 'from',
collapseKey: 'collapse'
collapseKey: 'collapse',
messageId: 'mid'
};
expect(externalizePayload(internalPayload)).to.deep.equal(payload);
});
Expand Down
4 changes: 3 additions & 1 deletion packages-exp/messaging-exp/src/helpers/externalizePayload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ export function externalizePayload(
const payload: MessagePayload = {
from: internalPayload.from,
// eslint-disable-next-line camelcase
collapseKey: internalPayload.collapse_key
collapseKey: internalPayload.collapse_key,
// eslint-disable-next-line camelcase
messageId: internalPayload.exposed_message_id
} as MessagePayload;

propagateNotificationPayload(payload, internalPayload);
Expand Down
173 changes: 173 additions & 0 deletions packages-exp/messaging-exp/src/helpers/logToFirelog.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
/**
* @license
* Copyright 2019 Google LLC
*
* 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 * as LogModule from './logToFirelog';
import * as chaiAsPromised from 'chai-as-promised';
import * as sinonChai from 'sinon-chai';

import { expect, use } from 'chai';
import {
getFakeLogEvent,
getSuccessResponse
} from '../testing/fakes/logging-object';
import { restore, stub } from 'sinon';

import { MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST } from '../util/constants';
import { MessagingService } from '../messaging-service';
import { Stub } from '../testing/sinon-types';
import { getFakeMessagingService } from '../testing/fakes/messaging-service';

const FIRELOG_ENDPOINT = LogModule._mergeStrings(
'hts/frbslgigp.ogepscmv/ieo/eaylg',
'tp:/ieaeogn-agolai.o/1frlglgc/o'
);

const FCM_TRANSPORT_KEY = LogModule._mergeStrings(
'AzSCbw63g1R0nCw85jG8',
'Iaya3yLKwmgvh7cF0q4'
);

use(chaiAsPromised);
use(sinonChai);

describe('logToFirelog', () => {
let fetchStub: Stub<typeof fetch>;
let messaging: MessagingService;

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

afterEach(async () => {
restore();
});

describe('_dispatchLogEvents', () => {
it('dispatches queue successfully ', async () => {
// set up
fetchStub.resolves(new Response(JSON.stringify(getSuccessResponse())));
messaging.logEvents.push(getFakeLogEvent());

// call
await LogModule._dispatchLogEvents(messaging);

// assert
expect(fetchStub).to.be.calledOnceWith(
FIRELOG_ENDPOINT.concat('?key=', FCM_TRANSPORT_KEY),
{
method: 'POST',
body: JSON.stringify(LogModule._createLogRequest([getFakeLogEvent()]))
}
);
expect(messaging.logEvents).to.be.empty;
});

it('Retries at most max retries times', async () => {
// set up
fetchStub.rejects(new Error('err'));
messaging.logEvents.push(getFakeLogEvent());

// call
await LogModule._dispatchLogEvents(messaging);

//assert
expect(fetchStub).to.be.calledThrice;
expect(messaging.logEvents).to.be.empty;
});

it('Reject 1st request, Pass 2nd request', async () => {
// set up
fetchStub
.onFirstCall()
.rejects(new Error('reject 1st time. 2 retry remain'))
.onSecondCall()
.resolves(new Response(JSON.stringify(getSuccessResponse())));
messaging.logEvents.push(getFakeLogEvent());

// call
await LogModule._dispatchLogEvents(messaging);

//assert
expect(fetchStub).to.be.calledTwice;
expect(messaging.logEvents).to.be.empty;
});

it('Slices logEvents based on max events per request', async () => {
// set up
fetchStub.resolves(new Response(JSON.stringify(getSuccessResponse())));
for (let i = 0; i < MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST * 3; i++) {
messaging.logEvents.push(getFakeLogEvent());
}

// call
await LogModule._dispatchLogEvents(messaging);

//assert
expect(fetchStub).to.be.calledThrice;
expect(messaging.logEvents).to.be.empty;
});

it('Empty queue', async () => {
// set up
fetchStub.resolves(new Response(JSON.stringify(getSuccessResponse())));
messaging.logEvents = [];

// call
await LogModule._dispatchLogEvents(messaging);

//assert
expect(fetchStub).to.not.have.been.called;
expect(messaging.logEvents).to.be.empty;
});
});

describe('_processQueue', () => {
it('clears log events if no user logging permission', done => {
// set up
messaging = getFakeMessagingService();
messaging.logEvents.push(getFakeLogEvent());
messaging.deliveryMetricsExportedToBigQueryEnabled = false;

// call
LogModule._processQueue(messaging, /** offsetInMs= */ 100);

// assert
setTimeout(() => {
expect(messaging.logEvents.length).to.equal(0);
expect(messaging.isLogServiceStarted).to.be.false;
done();
}, 1000);
});

it('clears log events if no user logging permission', done => {
// set up
messaging = getFakeMessagingService();
messaging.logEvents.push(getFakeLogEvent());
messaging.deliveryMetricsExportedToBigQueryEnabled = true;

// call
LogModule._processQueue(messaging, /** offsetInMs= */ 100);

// assert
setTimeout(() => {
expect(messaging.logEvents.length).to.equal(0);
done();
}, 1000);
});
});
});
Loading