forked from node-apn/node-apn
-
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathclient.js
More file actions
710 lines (633 loc) · 22.3 KB
/
client.js
File metadata and controls
710 lines (633 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
const VError = require('verror');
const tls = require('tls');
const extend = require('./util/extend');
const createProxySocket = require('./util/proxy');
module.exports = function (dependencies) {
// Used for routine logs such as HTTP status codes, etc.
const defaultLogger = dependencies.logger;
// Used for unexpected events that should be rare under normal circumstances,
// e.g. connection errors.
const defaultErrorLogger = dependencies.errorLogger || defaultLogger;
const { config, http2 } = dependencies;
const {
HTTP2_HEADER_STATUS,
HTTP2_HEADER_SCHEME,
HTTP2_HEADER_METHOD,
HTTP2_HEADER_AUTHORITY,
HTTP2_HEADER_PATH,
HTTP2_METHOD_POST,
HTTP2_METHOD_GET,
HTTP2_METHOD_DELETE,
NGHTTP2_CANCEL,
} = http2.constants;
const HTTPMethod = {
post: HTTP2_METHOD_POST,
get: HTTP2_METHOD_GET,
delete: HTTP2_METHOD_DELETE,
};
const TIMEOUT_STATUS = '(timeout)';
const ABORTED_STATUS = '(aborted)';
const ERROR_STATUS = '(error)';
function Client(options) {
this.isDestroyed = false;
this.config = config(options);
this.logger = defaultLogger;
this.errorLogger = defaultErrorLogger;
this.healthCheckInterval = setInterval(() => {
if (this.session && !this.session.closed && !this.session.destroyed && !this.isDestroyed) {
this.session.ping((error, duration) => {
if (error && this.errorLogger.enabled) {
this.errorLogger(
'No Ping response after ' + duration + ' ms with error:' + error.message
);
} else if (this.logger.enabled) {
this.logger('Ping response after ' + duration + ' ms');
}
});
}
}, this.config.heartBeat).unref();
this.manageChannelsHealthCheckInterval = setInterval(() => {
if (
this.manageChannelsSession &&
!this.manageChannelsSession.closed &&
!this.manageChannelsSession.destroyed &&
!this.isDestroyed
) {
this.manageChannelsSession.ping((error, duration) => {
if (error && this.errorLogger.enabled) {
this.errorLogger(
'ManageChannelsSession No Ping response after ' +
duration +
' ms with error:' +
error.message
);
} else if (this.logger.enabled) {
this.logger('ManageChannelsSession Ping response after ' + duration + ' ms');
}
});
}
}, this.config.heartBeat).unref();
}
// The respective session should always be passed.
Client.prototype.destroySession = function (session) {
if (!session) {
return;
}
if (!session.destroyed) {
session.destroy();
}
session = null;
};
// The respective session should always be passed.
Client.prototype.closeAndDestroySession = async function (session) {
if (!session) {
return;
}
if (!session.closed) {
await new Promise(resolve => {
session.close(() => {
resolve();
});
});
}
this.destroySession(session);
};
Client.prototype.makePath = function makePath(type, subDirectory) {
switch (type) {
case 'channels':
return `/1/apps/${subDirectory}/channels`;
case 'allChannels':
return `/1/apps/${subDirectory}/all-channels`;
case 'device':
return `/3/device/${subDirectory}`;
case 'broadcasts':
return `/4/broadcasts/apps/${subDirectory}`;
default:
return null;
}
};
Client.prototype.subDirectoryLabel = function subDirectoryLabel(type) {
switch (type) {
case 'device':
return 'device';
case 'channels':
case 'allChannels':
case 'broadcasts':
return 'bundleId';
default:
return null;
}
};
Client.prototype.makeSubDirectoryTypeObject = function makeSubDirectoryTypeObject(
label,
subDirectory
) {
const subDirectoryObject = {};
subDirectoryObject[label] = subDirectory;
return subDirectoryObject;
};
/**
* Determines if a request should be retried based on the error. This includes certain status codes, expired provider token, and transient write failures.
* @param {Object} error - An object representing the error which may include the following properties:
* @param {number} [error.status] - The HTTP status code returned from the APNs server.
* @param {VError} error.error - The error details which may include a message describing the error.
* @param {string} [error.error.message] - The error message which may indicate specific conditions such as 'ExpiredProviderToken' or transient write failures.
* @returns {boolean} - Returns true if the request is considered retryable based on the error, otherwise false.
*/
Client.isRequestRetryable = function isRequestRetryable(error) {
const isStatusCodeRetryable = [408, 429, 500, 502, 503, 504].includes(error.status);
const isProviderTokenExpired =
error.status === 403 && error.error?.message === 'ExpiredProviderToken';
// This can happen after the server initiates a goaway, and the client did not finish closing and destroying the session yet, so the client tries to send a request on a closing session.
const isTransientWriteFailure = !!error.error?.message?.startsWith('apn write failed');
return isStatusCodeRetryable || isProviderTokenExpired || isTransientWriteFailure;
};
Client.prototype.write = async function write(notification, subDirectory, type, method, count) {
const retryCount = count || 0;
const subDirectoryLabel = this.subDirectoryLabel(type) ?? type;
const subDirectoryInformation = this.makeSubDirectoryTypeObject(
subDirectoryLabel,
subDirectory
);
const path = this.makePath(type, subDirectory);
if (path == null) {
const error = {
...subDirectoryInformation,
error: new VError(`could not make a path for ${type} and ${subDirectory}`),
};
throw error;
}
const httpMethod = HTTPMethod[method];
if (httpMethod == null) {
const error = {
...subDirectoryInformation,
error: new VError(`invalid httpMethod "${method}"`),
};
throw error;
}
if (this.isDestroyed) {
const error = { ...subDirectoryInformation, error: new VError('client is destroyed') };
throw error;
}
if (path.includes('/1/apps/')) {
// Connect manageChannelsSession.
if (
!this.manageChannelsSession ||
this.manageChannelsSession.closed ||
this.manageChannelsSession.destroyed
) {
try {
await this.manageChannelsConnect();
} catch (error) {
if (this.errorLogger.enabled) {
// Proxy server that returned error doesn't have access to logger.
this.errorLogger(error.message);
}
const updatedError = { ...subDirectoryInformation, error };
throw updatedError;
}
}
try {
const sentRequest = await this.request(
this.manageChannelsSession,
this.config.manageChannelsAddress,
notification,
path,
httpMethod
);
return { ...subDirectoryInformation, ...sentRequest };
} catch (error) {
if (Client.isRequestRetryable(error)) {
try {
const resentRequest = await this.retryWrite(
error,
notification,
subDirectory,
type,
method,
retryCount
);
return { ...subDirectoryInformation, ...resentRequest };
} catch (error) {
if (error.status == 500) {
await this.closeAndDestroySession(this.manageChannelsSession);
}
delete error.retryAfter; // Never propagate retryAfter outside of client.
const updatedError = { ...subDirectoryInformation, ...error };
throw updatedError;
}
} else {
delete error.retryAfter; // Never propagate retryAfter outside of client.
throw { ...subDirectoryInformation, ...error };
}
}
} else {
// Connect to standard session.
if (!this.session || this.session.closed || this.session.destroyed) {
try {
await this.connect();
} catch (error) {
if (this.errorLogger.enabled) {
// Proxy server that returned error doesn't have access to logger.
this.errorLogger(error.message);
}
delete error.retryAfter; // Never propagate retryAfter outside of client.
const updatedError = { ...subDirectoryInformation, error };
throw updatedError;
}
}
try {
const sentRequest = await this.request(
this.session,
this.config.address,
notification,
path,
httpMethod
);
return { ...subDirectoryInformation, ...sentRequest };
} catch (error) {
if (Client.isRequestRetryable(error)) {
try {
const resentRequest = await this.retryWrite(
error,
notification,
subDirectory,
type,
method,
retryCount
);
return { ...subDirectoryInformation, ...resentRequest };
} catch (error) {
if (error.status == 500) {
await this.closeAndDestroySession(this.session);
}
delete error.retryAfter; // Never propagate retryAfter outside of client.
const updatedError = { ...subDirectoryInformation, ...error };
throw updatedError;
}
} else {
delete error.retryAfter; // Never propagate retryAfter outside of client.
throw { ...subDirectoryInformation, ...error };
}
}
}
};
Client.prototype.retryWrite = async function retryWrite(
error,
notification,
subDirectory,
type,
method,
retryCount
) {
if (retryCount >= this.config.connectionRetryLimit) {
throw error;
}
const delayInSeconds = parseInt(error.retryAfter || 0);
const delayPromise = new Promise(resolve => setTimeout(resolve, delayInSeconds * 1000));
await delayPromise;
// Retry write, which will handle reconnection if needed
return await this.write(notification, subDirectory, type, method, retryCount + 1);
};
Client.prototype.connect = function connect() {
if (this.sessionPromise) return this.sessionPromise;
const proxySocketPromise = this.config.proxy
? createProxySocket(this.config.proxy, {
host: this.config.address,
port: this.config.port,
})
: Promise.resolve();
this.sessionPromise = proxySocketPromise.then(socket => {
this.sessionPromise = null;
if (socket) {
this.config.createConnection = authority =>
authority.protocol === 'http:'
? socket
: authority.protocol === 'https:'
? tls.connect(+authority.port || 443, authority.hostname, {
socket,
servername: authority.hostname,
ALPNProtocols: ['h2'],
})
: null;
}
const session = (this.session = http2.connect(
this._mockOverrideUrl || `https://${this.config.address}`,
this.config
));
if (this.logger.enabled) {
this.session.on('connect', () => {
this.logger('Session connected');
});
}
this.session.on('close', () => {
if (this.errorLogger.enabled) {
this.errorLogger('Session closed');
}
this.destroySession(session);
});
this.session.on('error', error => {
if (this.errorLogger.enabled) {
this.errorLogger(`Session error: ${error}`);
}
this.closeAndDestroySession(session);
});
this.session.on('goaway', (errorCode, lastStreamId, opaqueData) => {
if (this.errorLogger.enabled) {
this.errorLogger(
`GOAWAY received: (errorCode ${errorCode}, lastStreamId: ${lastStreamId}, opaqueData: ${opaqueData})`
);
}
this.closeAndDestroySession(session);
});
this.session.on('frameError', (frameType, errorCode, streamId) => {
// This is a frame error not associate with any request(stream).
if (this.errorLogger.enabled) {
this.errorLogger(
`Frame error: (frameType: ${frameType}, errorCode ${errorCode}, streamId: ${streamId})`
);
}
this.closeAndDestroySession(session);
});
});
return this.sessionPromise;
};
Client.prototype.manageChannelsConnect = async function manageChannelsConnect() {
if (this.manageChannelsSessionPromise) return this.manageChannelsSessionPromise;
const proxySocketPromise = this.config.manageChannelsProxy
? createProxySocket(this.config.manageChannelsProxy, {
host: this.config.manageChannelsAddress,
port: this.config.manageChannelsPort,
})
: Promise.resolve();
this.manageChannelsSessionPromise = proxySocketPromise.then(socket => {
this.manageChannelsSessionPromise = null;
if (socket) {
this.config.createConnection = authority =>
authority.protocol === 'http:'
? socket
: authority.protocol === 'https:'
? tls.connect(+authority.port || this.config.manageChannelsPort, authority.hostname, {
socket,
servername: authority.hostname,
ALPNProtocols: ['h2'],
})
: null;
}
const config = { ...this.config }; // Only need a shallow copy.
// http2 will use this address and port.
config.address = config.manageChannelsAddress;
config.port = config.manageChannelsPort;
const session = (this.manageChannelsSession = http2.connect(
this._mockOverrideUrl || `https://${config.address}`,
config
));
if (this.logger.enabled) {
this.manageChannelsSession.on('connect', () => {
this.logger('ManageChannelsSession connected');
});
}
this.manageChannelsSession.on('close', () => {
if (this.errorLogger.enabled) {
this.errorLogger('ManageChannelsSession closed');
}
this.destroySession(session);
});
this.manageChannelsSession.on('socketError', error => {
if (this.errorLogger.enabled) {
this.errorLogger(`ManageChannelsSession Socket error: ${error}`);
}
this.closeAndDestroySession(session);
});
this.manageChannelsSession.on('error', error => {
if (this.errorLogger.enabled) {
this.errorLogger(`ManageChannelsSession error: ${error}`);
}
this.closeAndDestroySession(session);
});
this.manageChannelsSession.on('goaway', (errorCode, lastStreamId, opaqueData) => {
if (this.errorLogger.enabled) {
this.errorLogger(
`ManageChannelsSession GOAWAY received: (errorCode ${errorCode}, lastStreamId: ${lastStreamId}, opaqueData: ${opaqueData})`
);
}
this.closeAndDestroySession(session);
});
this.manageChannelsSession.on('frameError', (frameType, errorCode, streamId) => {
// This is a frame error not associate with any request(stream).
if (this.errorLogger.enabled) {
this.errorLogger(
`ManageChannelsSession Frame error: (frameType: ${frameType}, errorCode ${errorCode}, streamId: ${streamId})`
);
}
this.closeAndDestroySession(session);
});
});
return this.manageChannelsSessionPromise;
};
Client.prototype.createHeaderObject = function createHeaderObject(
uniqueId,
requestId,
channelId,
notificationId
) {
const header = {};
if (uniqueId) {
header['apns-unique-id'] = uniqueId;
}
if (requestId) {
header['apns-request-id'] = requestId;
}
if (channelId) {
header['apns-channel-id'] = channelId;
}
if (notificationId) {
header['apns-id'] = notificationId;
}
return header;
};
Client.prototype.request = async function request(
session,
address,
notification,
path,
httpMethod
) {
let tokenGeneration = null;
let status = null;
let retryAfter = null;
let uniqueId = null;
let requestId = null;
let channelId = null;
let notificationId = null;
let responseData = '';
const headers = extend(
{
[HTTP2_HEADER_SCHEME]: 'https',
[HTTP2_HEADER_METHOD]: httpMethod,
[HTTP2_HEADER_AUTHORITY]: address,
[HTTP2_HEADER_PATH]: path,
},
notification.headers
);
if (this.config.token) {
if (this.config.token.isExpired(3300)) {
this.config.token.regenerate(this.config.token.generation);
}
headers.authorization = `bearer ${this.config.token.current}`;
tokenGeneration = this.config.token.generation;
}
const request = session.request(headers);
request.setEncoding('utf8');
request.on('response', headers => {
status = headers[HTTP2_HEADER_STATUS];
retryAfter = headers['Retry-After'];
uniqueId = headers['apns-unique-id'];
requestId = headers['apns-request-id'];
channelId = headers['apns-channel-id'];
notificationId = headers['apns-id'];
});
request.on('data', data => {
responseData += data;
});
if (notification.body !== '{}') {
request.write(notification.body);
}
return new Promise((resolve, reject) => {
request.on('end', () => {
try {
if (this.logger.enabled) {
this.logger(`Request ended with status ${status} and responseData: ${responseData}`);
}
const headerObject = this.createHeaderObject(
uniqueId,
requestId,
channelId,
notificationId
);
if (status === 200 || status === 201 || status === 204) {
const body = responseData !== '' ? JSON.parse(responseData) : {};
resolve({ ...headerObject, ...body });
return;
} else if ([TIMEOUT_STATUS, ABORTED_STATUS, ERROR_STATUS].includes(status)) {
const error = {
status,
retryAfter,
error: new VError('Timeout, aborted, or other unknown error'),
};
reject({ ...headerObject, ...error });
return;
} else if (responseData !== '') {
const response = JSON.parse(responseData);
if (status === 403 && response.reason === 'ExpiredProviderToken') {
this.config.token.regenerate(tokenGeneration);
const error = {
status,
retryAfter,
error: new VError(response.reason),
};
reject({ ...headerObject, ...error });
return;
} else if (status === 500 && response.reason === 'InternalServerError') {
const error = {
status,
retryAfter,
error: new VError('Error 500, stream ended unexpectedly'),
};
reject({ ...headerObject, ...error });
return;
}
reject({ ...headerObject, status, retryAfter, response });
} else {
const error = {
error: new VError(`stream ended unexpectedly with status ${status} and empty body`),
};
reject({ ...headerObject, ...error });
}
} catch (e) {
const error = new VError(e, 'Unexpected error processing APNs response');
if (this.errorLogger.enabled) {
this.errorLogger(`Unexpected error processing APNs response: ${e.message}`);
}
reject({ error });
}
});
request.setTimeout(this.config.requestTimeout, () => {
if (this.errorLogger.enabled) {
this.errorLogger('Request timeout');
}
status = TIMEOUT_STATUS;
request.close(NGHTTP2_CANCEL);
const error = { error: new VError('apn write timeout') };
reject(error);
});
request.on('aborted', () => {
if (this.errorLogger.enabled) {
this.errorLogger('Request aborted');
}
status = ABORTED_STATUS;
const error = { error: new VError('apn write aborted') };
reject(error);
});
request.on('error', error => {
if (this.errorLogger.enabled) {
this.errorLogger(`Request error: ${error}`);
}
status = ERROR_STATUS;
if (typeof error === 'string') {
error = new VError('apn write failed: %s', error);
} else {
error = new VError(error, 'apn write failed');
}
reject({ error });
});
request.on('frameError', (frameType, errorCode, streamId) => {
const errorMessage = `Request frame error: (frameType: ${frameType}, errorCode ${errorCode}, streamId: ${streamId})`;
if (this.errorLogger.enabled) {
this.errorLogger(errorMessage);
}
const error = new VError(errorMessage);
reject({ error });
});
request.end();
});
};
Client.prototype.shutdown = async function shutdown(callback) {
if (this.isDestroyed) {
if (callback) {
callback();
}
return;
}
if (this.errorLogger.enabled) {
this.errorLogger('Called client.shutdown()');
}
this.isDestroyed = true;
if (this.healthCheckInterval) {
clearInterval(this.healthCheckInterval);
this.healthCheckInterval = null;
}
if (this.manageChannelsHealthCheckInterval) {
clearInterval(this.manageChannelsHealthCheckInterval);
this.manageChannelsHealthCheckInterval = null;
}
await this.closeAndDestroySession(this.session);
await this.closeAndDestroySession(this.manageChannelsSession);
if (callback) {
callback();
}
};
Client.prototype.setLogger = function (newLogger, newErrorLogger = null) {
if (typeof newLogger !== 'function') {
throw new Error(`Expected newLogger to be a function, got ${typeof newLogger}`);
}
if (newErrorLogger && typeof newErrorLogger !== 'function') {
throw new Error(
`Expected newErrorLogger to be a function or null, got ${typeof newErrorLogger}`
);
}
this.logger = newLogger;
this.errorLogger = newErrorLogger || newLogger;
};
return Client;
};