Skip to content

Commit b5f9bf8

Browse files
authored
Implementing FCM sendAll() API (#453)
* Initial implementation for batch send * Unit tests for BatchRequestClient * Finished sendAll() implementation * Fixed some lint errors * Fixed messaging test imports * Adding more tests * Increased test coverage * Updated tests * Implemented multipart parsing with dicer for performance * Increased test coverage for HttpClient * Added a test case for zlib * Removed http-message-parser frm required dependencies * Added some documentation * Updated comments * Trigger CI * Fixed some typos; Reduced batch size limit to 100 * More documentation and clean up * Updated docs; Other code review feedback * Handling malformed responses in parseHttpResponse() * Implementing the sendMulticast() API for FCM (#473) * Implementing sendMulticast() API * Added integration test * Fixed a comment * Readability improvement in the copy operation
1 parent 1e8b553 commit b5f9bf8

15 files changed

+2414
-663
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Unreleased
22

3+
- [added] A new `messaging.sendAll()` API for sending multiple messages as a
4+
single batch.
5+
- [added] A new `messaging.sendMulticast()` API for sending a message to
6+
multiple device registration tokens.
37
- [fixed] Improved typings of `UpdateRequest` interface to support deletion of
48
properties.
59

package-lock.json

Lines changed: 67 additions & 11 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
"@firebase/app": "^0.3.4",
5757
"@firebase/database": "^0.3.6",
5858
"@types/node": "^8.0.53",
59+
"dicer": "^0.3.0",
5960
"jsonwebtoken": "8.1.0",
6061
"node-forge": "0.7.4"
6162
},
@@ -90,6 +91,7 @@
9091
"gulp-header": "^1.8.8",
9192
"gulp-replace": "^0.5.4",
9293
"gulp-typescript": "^3.2.4",
94+
"http-message-parser": "^0.0.34",
9395
"lodash": "^4.17.5",
9496
"merge2": "^1.2.1",
9597
"minimist": "^1.2.0",

src/index.d.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,10 @@ interface ConditionMessage extends BaseMessage {
412412
declare namespace admin.messaging {
413413
type Message = TokenMessage | TopicMessage | ConditionMessage;
414414

415+
interface MulticastMessage extends BaseMessage {
416+
tokens: string[];
417+
}
418+
415419
type AndroidConfig = {
416420
collapseKey?: string;
417421
priority?: ('high'|'normal');
@@ -586,10 +590,30 @@ declare namespace admin.messaging {
586590
errors: admin.FirebaseArrayIndexError[];
587591
};
588592

593+
type BatchResponse = {
594+
responses: admin.messaging.SendResponse[];
595+
successCount: number;
596+
failureCount: number;
597+
}
598+
599+
type SendResponse = {
600+
success: boolean;
601+
messageId?: string;
602+
error?: admin.FirebaseError;
603+
};
604+
589605
interface Messaging {
590606
app: admin.app.App;
591607

592608
send(message: admin.messaging.Message, dryRun?: boolean): Promise<string>;
609+
sendAll(
610+
messages: Array<admin.messaging.Message>,
611+
dryRun?: boolean
612+
): Promise<admin.messaging.BatchResponse>;
613+
sendMulticast(
614+
message: admin.messaging.MulticastMessage,
615+
dryRun?: boolean
616+
): Promise<admin.messaging.BatchResponse>;
593617
sendToDevice(
594618
registrationToken: string | string[],
595619
payload: admin.messaging.MessagingPayload,

src/messaging/batch-request.ts

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
/*!
2+
* Copyright 2019 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import {
18+
HttpClient, HttpRequestConfig, HttpResponse, parseHttpResponse,
19+
} from '../utils/api-request';
20+
21+
const PART_BOUNDARY: string = '__END_OF_PART__';
22+
const TEN_SECONDS_IN_MILLIS = 10000;
23+
24+
/**
25+
* Represents a request that can be sent as part of an HTTP batch request.
26+
*/
27+
export interface SubRequest {
28+
url: string;
29+
body: object;
30+
headers?: {[key: string]: any};
31+
}
32+
33+
/**
34+
* An HTTP client that can be used to make batch requests. This client is not tied to any service
35+
* (FCM or otherwise). Therefore it can be used to make batch requests to any service that allows
36+
* it. If this requirement ever arises we can move this implementation to the utils module
37+
* where it can be easily shared among other modules.
38+
*/
39+
export class BatchRequestClient {
40+
41+
/**
42+
* @param {HttpClient} httpClient The client that will be used to make HTTP calls.
43+
* @param {string} batchUrl The URL that accepts batch requests.
44+
* @param {object=} commonHeaders Optional headers that will be included in all requests.
45+
*
46+
* @constructor
47+
*/
48+
constructor(
49+
private readonly httpClient: HttpClient,
50+
private readonly batchUrl: string,
51+
private readonly commonHeaders?: object) {
52+
}
53+
54+
/**
55+
* Sends the given array of sub requests as a single batch, and parses the results into an array
56+
* of HttpResponse objects.
57+
*
58+
* @param {SubRequest[]} requests An array of sub requests to send.
59+
* @return {Promise<HttpResponse[]>} A promise that resolves when the send operation is complete.
60+
*/
61+
public send(requests: SubRequest[]): Promise<HttpResponse[]> {
62+
const requestHeaders = {
63+
'Content-Type': `multipart/mixed; boundary=${PART_BOUNDARY}`,
64+
};
65+
const request: HttpRequestConfig = {
66+
method: 'POST',
67+
url: this.batchUrl,
68+
data: this.getMultipartPayload(requests),
69+
headers: Object.assign({}, this.commonHeaders, requestHeaders),
70+
timeout: TEN_SECONDS_IN_MILLIS,
71+
};
72+
return this.httpClient.send(request).then((response) => {
73+
return response.multipart.map((buff) => {
74+
return parseHttpResponse(buff, request);
75+
});
76+
});
77+
}
78+
79+
private getMultipartPayload(requests: SubRequest[]): Buffer {
80+
let buffer: string = '';
81+
requests.forEach((request: SubRequest, idx: number) => {
82+
buffer += createPart(request, PART_BOUNDARY, idx);
83+
});
84+
buffer += `--${PART_BOUNDARY}--\r\n`;
85+
return Buffer.from(buffer, 'utf-8');
86+
}
87+
}
88+
89+
/**
90+
* Creates a single part in a multipart HTTP request body. The part consists of several headers
91+
* followed by the serialized sub request as the body. As per the requirements of the FCM batch
92+
* API, sets the content-type header to application/http, and the content-transfer-encoding to
93+
* binary.
94+
*
95+
* @param {SubRequest} request A sub request that will be used to populate the part.
96+
* @param {string} boundary Multipart boundary string.
97+
* @param {number} idx An index number that is used to set the content-id header.
98+
* @return {string} The part as a string that can be included in the HTTP body.
99+
*/
100+
function createPart(request: SubRequest, boundary: string, idx: number): string {
101+
const serializedRequest: string = serializeSubRequest(request);
102+
let part: string = `--${boundary}\r\n`;
103+
part += `Content-Length: ${serializedRequest.length}\r\n`;
104+
part += 'Content-Type: application/http\r\n';
105+
part += `content-id: ${idx + 1}\r\n`;
106+
part += 'content-transfer-encoding: binary\r\n';
107+
part += '\r\n';
108+
part += `${serializedRequest}\r\n`;
109+
return part;
110+
}
111+
112+
/**
113+
* Serializes a sub request into a string that can be embedded in a multipart HTTP request. The
114+
* format of the string is the wire format of a typical HTTP request, consisting of a header and a
115+
* body.
116+
*
117+
* @param request {SubRequest} The sub request to be serialized.
118+
* @return {string} String representation of the SubRequest.
119+
*/
120+
function serializeSubRequest(request: SubRequest): string {
121+
const requestBody: string = JSON.stringify(request.body);
122+
let messagePayload: string = `POST ${request.url} HTTP/1.1\r\n`;
123+
messagePayload += `Content-Length: ${requestBody.length}\r\n`;
124+
messagePayload += 'Content-Type: application/json; charset=UTF-8\r\n';
125+
if (request.headers) {
126+
Object.keys(request.headers).forEach((key) => {
127+
messagePayload += `${key}: ${request.headers[key]}\r\n`;
128+
});
129+
}
130+
messagePayload += '\r\n';
131+
messagePayload += requestBody;
132+
return messagePayload;
133+
}

0 commit comments

Comments
 (0)