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
2840 lines (2687 loc) · 107 KB
/
client.js
File metadata and controls
2840 lines (2687 loc) · 107 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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const VError = require('verror');
const net = require('net');
const http2 = require('http2');
const { HTTP2_METHOD_POST, HTTP2_METHOD_GET, HTTP2_METHOD_DELETE } = http2.constants;
const debug = require('debug')('apn');
const credentials = require('../lib/credentials')({
logger: debug,
});
const TEST_PORT = 30939;
const CLIENT_TEST_PORT = TEST_PORT + 1;
const LOAD_TEST_BATCH_SIZE = 2000;
const config = require('../lib/config')({
logger: debug,
prepareCertificate: () => ({}), // credentials.certificate,
prepareToken: credentials.token,
prepareCA: credentials.ca,
});
const Client = require('../lib/client')({
logger: debug,
config,
http2,
});
debug.log = console.log.bind(console);
// function builtNotification() {
// return {
// headers: {},
// body: JSON.stringify({ aps: { badge: 1 } }),
// };
// }
// function FakeStream(deviceId, statusCode, response) {
// const fakeStream = new stream.Transform({
// transform: sinon.spy(function(chunk, encoding, callback) {
// expect(this.headers).to.be.calledOnce;
//
// const headers = this.headers.firstCall.args[0];
// expect(headers[":path"].substring(10)).to.equal(deviceId);
//
// this.emit("headers", {
// ":status": statusCode
// });
// callback(null, Buffer.from(JSON.stringify(response) || ""));
// })
// });
// fakeStream.headers = sinon.stub();
//
// return fakeStream;
// }
// XXX these may be flaky in CI due to being sensitive to timing,
// and if a test case crashes, then others may get stuck.
//
// Try to fix this if any issues come up.
describe('Client', () => {
let server;
let client;
const MOCK_BODY = '{"mock-key":"mock-value"}';
const MOCK_DEVICE_TOKEN = 'abcf0123abcf0123abcf0123abcf0123abcf0123abcf0123abcf0123abcf0123';
const BUNDLE_ID = 'com.node.apn';
const PATH_DEVICE = `/3/device/${MOCK_DEVICE_TOKEN}`;
const PATH_BROADCASTS = `/4/broadcasts/apps/${BUNDLE_ID}`;
// Create an insecure http2 client for unit testing.
// (APNS would use https://, not http://)
// (It's probably possible to allow accepting invalid certificates instead,
// but that's not the most important point of these tests)
const createClient = (port, timeout = 500, heartBeat = 6000) => {
const c = new Client({
port: TEST_PORT,
address: '127.0.0.1',
heartBeat: heartBeat,
requestTimeout: timeout,
});
c._mockOverrideUrl = `http://127.0.0.1:${port}`;
return c;
};
// Create an insecure server for unit testing.
const createAndStartMockServer = (port, cb) => {
server = http2.createServer((req, res) => {
const buffers = [];
req.on('data', data => buffers.push(data));
req.on('end', () => {
const requestBody = Buffer.concat(buffers).toString('utf-8');
cb(req, res, requestBody);
});
});
server.listen(port);
server.on('error', err => {
expect.fail(`unexpected error ${err}`);
});
// Don't block the tests if this server doesn't shut down properly
server.unref();
return server;
};
const createAndStartMockLowLevelServer = (port, cb) => {
server = http2.createServer();
server.on('stream', cb);
server.listen(port);
server.on('error', err => {
expect.fail(`unexpected error ${err}`);
});
// Don't block the tests if this server doesn't shut down properly
server.unref();
return server;
};
afterEach(async () => {
const closeServer = async () => {
if (server) {
await new Promise(resolve => {
server.close(() => {
resolve();
});
});
server = null;
}
};
if (client) {
await client.shutdown();
client = null;
}
await closeServer();
});
it('Treats HTTP 200 responses as successful for device', async () => {
let didRequest = false;
let establishedConnections = 0;
let requestsServed = 0;
const method = HTTP2_METHOD_POST;
const path = PATH_DEVICE;
server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
expect(req.headers).to.deep.equal({
':authority': '127.0.0.1',
':method': method,
':path': path,
':scheme': 'https',
'apns-someheader': 'somevalue',
});
expect(requestBody).to.equal(MOCK_BODY);
// res.setHeader('X-Foo', 'bar');
// res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.writeHead(200);
res.end('');
requestsServed += 1;
didRequest = true;
});
server.on('connection', () => (establishedConnections += 1));
await new Promise(resolve => server.on('listening', resolve));
client = createClient(CLIENT_TEST_PORT);
const runSuccessfulRequest = async () => {
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const device = MOCK_DEVICE_TOKEN;
const result = await client.write(mockNotification, device, 'device', 'post');
expect(result).to.deep.equal({ device });
expect(didRequest).to.be.true;
};
expect(establishedConnections).to.equal(0); // should not establish a connection until it's needed
// Validate that when multiple valid requests arrive concurrently,
// only one HTTP/2 connection gets established
await Promise.all([
runSuccessfulRequest(),
runSuccessfulRequest(),
runSuccessfulRequest(),
runSuccessfulRequest(),
runSuccessfulRequest(),
]);
didRequest = false;
client.destroySession(); // Don't pass in session to destroy, should not force a disconnection.
await runSuccessfulRequest();
expect(establishedConnections).to.equal(1); // should establish a connection to the server and reuse it
expect(requestsServed).to.equal(6);
});
it('Treats HTTP 200 responses as successful for broadcasts', async () => {
let didRequest = false;
let establishedConnections = 0;
let requestsServed = 0;
const method = HTTP2_METHOD_POST;
const path = PATH_BROADCASTS;
server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
expect(req.headers).to.deep.equal({
':authority': '127.0.0.1',
':method': method,
':path': path,
':scheme': 'https',
'apns-someheader': 'somevalue',
});
expect(requestBody).to.equal(MOCK_BODY);
// res.setHeader('X-Foo', 'bar');
// res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.writeHead(200);
res.end('');
requestsServed += 1;
didRequest = true;
});
server.on('connection', () => (establishedConnections += 1));
await new Promise(resolve => server.on('listening', resolve));
client = createClient(CLIENT_TEST_PORT);
const runSuccessfulRequest = async () => {
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const bundleId = BUNDLE_ID;
const result = await client.write(mockNotification, bundleId, 'broadcasts', 'post');
expect(result).to.deep.equal({ bundleId });
expect(didRequest).to.be.true;
};
expect(establishedConnections).to.equal(0); // should not establish a connection until it's needed
// Validate that when multiple valid requests arrive concurrently,
// only one HTTP/2 connection gets established
await Promise.all([
runSuccessfulRequest(),
runSuccessfulRequest(),
runSuccessfulRequest(),
runSuccessfulRequest(),
runSuccessfulRequest(),
]);
didRequest = false;
await runSuccessfulRequest();
expect(establishedConnections).to.equal(1); // should establish a connection to the server and reuse it
expect(requestsServed).to.equal(6);
});
// Assert that this doesn't crash when a large batch of requests are requested simultaneously
it('Treats HTTP 200 responses as successful (load test for a batch of requests)', async function () {
this.timeout(10000);
let establishedConnections = 0;
let requestsServed = 0;
const method = HTTP2_METHOD_POST;
const path = PATH_DEVICE;
server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
expect(req.headers).to.deep.equal({
':authority': '127.0.0.1',
':method': method,
':path': path,
':scheme': 'https',
'apns-someheader': 'somevalue',
});
expect(requestBody).to.equal(MOCK_BODY);
// Set a timeout of 100 to simulate latency to a remote server.
setTimeout(() => {
res.writeHead(200);
res.end('');
requestsServed += 1;
}, 100);
});
server.on('connection', () => (establishedConnections += 1));
await new Promise(resolve => server.on('listening', resolve));
client = createClient(CLIENT_TEST_PORT, 1500);
const runSuccessfulRequest = async () => {
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const device = MOCK_DEVICE_TOKEN;
const result = await client.write(mockNotification, device, 'device', 'post');
expect(result).to.deep.equal({ device });
};
expect(establishedConnections).to.equal(0); // should not establish a connection until it's needed
// Validate that when multiple valid requests arrive concurrently,
// only one HTTP/2 connection gets established
const promises = [];
for (let i = 0; i < LOAD_TEST_BATCH_SIZE; i++) {
promises.push(runSuccessfulRequest());
}
await Promise.all(promises);
expect(establishedConnections).to.equal(1); // should establish a connection to the server and reuse it
expect(requestsServed).to.equal(LOAD_TEST_BATCH_SIZE);
});
it('Log pings for session', async () => {
let establishedConnections = 0;
let requestsServed = 0;
const method = HTTP2_METHOD_POST;
const path = PATH_DEVICE;
const pingDelay = 50;
const responseDelay = pingDelay * 2;
server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
expect(req.headers).to.deep.equal({
':authority': '127.0.0.1',
':method': method,
':path': path,
':scheme': 'https',
'apns-someheader': 'somevalue',
});
expect(requestBody).to.equal(MOCK_BODY);
// Set a timeout of responseDelay to simulate latency to a remote server.
setTimeout(() => {
res.writeHead(200);
res.end('');
requestsServed += 1;
}, responseDelay);
});
server.on('connection', () => (establishedConnections += 1));
await new Promise(resolve => server.on('listening', resolve));
client = createClient(CLIENT_TEST_PORT, 500, pingDelay);
// Setup logger.
const infoMessages = [];
const errorMessages = [];
const mockInfoLogger = message => {
infoMessages.push(message);
};
const mockErrorLogger = message => {
errorMessages.push(message);
};
mockInfoLogger.enabled = true;
mockErrorLogger.enabled = true;
client.setLogger(mockInfoLogger, mockErrorLogger);
const runSuccessfulRequest = async () => {
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const device = MOCK_DEVICE_TOKEN;
const result = await client.write(mockNotification, device, 'device', 'post');
expect(result).to.deep.equal({ device });
};
expect(establishedConnections).to.equal(0); // should not establish a connection until it's needed
await runSuccessfulRequest();
expect(establishedConnections).to.equal(1); // should establish a connection to the server and reuse it
expect(requestsServed).to.equal(1);
expect(infoMessages).to.not.be.empty;
let infoMessagesContainsPing = false;
// Search for message, in older node, may be in random order.
for (const message of infoMessages) {
if (message.includes('Ping response')) {
infoMessagesContainsPing = true;
break;
}
}
expect(infoMessagesContainsPing).to.be.true;
expect(errorMessages).to.be.empty;
});
it('Returns APNs notification ID in responses', async () => {
const notificationId = '7dc35f9f-58d4-40dd-8c08-38ab811f57df';
server = createAndStartMockServer(TEST_PORT, (req, res) => {
res.writeHead(200, { 'apns-id': notificationId });
res.end('');
});
await new Promise(resolve => server.on('listening', resolve));
client = createClient(CLIENT_TEST_PORT);
const mockNotification = {
headers: { 'apns-someheader': 'somevalue' },
body: MOCK_BODY,
};
const device = MOCK_DEVICE_TOKEN;
const result = await client.write(mockNotification, device, 'device', 'post');
expect(result).to.deep.equal({ 'apns-id': notificationId, device });
});
// https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/handling_notification_responses_from_apns
it('JSON decodes HTTP 400 responses', async () => {
let didRequest = false;
let establishedConnections = 0;
server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
expect(requestBody).to.equal(MOCK_BODY);
// res.setHeader('X-Foo', 'bar');
// res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.writeHead(400);
res.end('{"reason": "BadDeviceToken"}');
didRequest = true;
});
server.on('connection', () => (establishedConnections += 1));
await new Promise(resolve => server.on('listening', resolve));
client = createClient(CLIENT_TEST_PORT);
const infoMessages = [];
const errorMessages = [];
const mockInfoLogger = message => {
infoMessages.push(message);
};
const mockErrorLogger = message => {
errorMessages.push(message);
};
mockInfoLogger.enabled = true;
mockErrorLogger.enabled = true;
client.setLogger(mockInfoLogger, mockErrorLogger);
const runRequestWithBadDeviceToken = async () => {
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const device = MOCK_DEVICE_TOKEN;
let receivedError;
try {
await client.write(mockNotification, device, 'device', 'post');
} catch (e) {
receivedError = e;
}
expect(receivedError).to.exist;
expect(receivedError).to.deep.equal({
device,
response: {
reason: 'BadDeviceToken',
},
status: 400,
});
expect(didRequest).to.be.true;
didRequest = false;
};
await runRequestWithBadDeviceToken();
await runRequestWithBadDeviceToken();
expect(establishedConnections).to.equal(1); // should establish a connection to the server and reuse it
expect(infoMessages).to.deep.equal([
'Session connected',
'Request ended with status 400 and responseData: {"reason": "BadDeviceToken"}',
'Request ended with status 400 and responseData: {"reason": "BadDeviceToken"}',
]);
expect(errorMessages).to.be.empty;
});
it('Attempts to regenerate token when HTTP 403 responses are received', async () => {
let establishedConnections = 0;
const responseDelay = 50;
server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
// Wait 50ms before sending the responses in parallel
setTimeout(() => {
expect(requestBody).to.equal(MOCK_BODY);
res.writeHead(403);
res.end('{"reason": "ExpiredProviderToken"}');
}, responseDelay);
});
server.on('connection', () => (establishedConnections += 1));
await new Promise(resolve => server.on('listening', resolve));
client = createClient(CLIENT_TEST_PORT);
// Setup logger.
const infoMessages = [];
const errorMessages = [];
const mockInfoLogger = message => {
infoMessages.push(message);
};
const mockErrorLogger = message => {
errorMessages.push(message);
};
mockInfoLogger.enabled = true;
mockErrorLogger.enabled = true;
client.setLogger(mockInfoLogger, mockErrorLogger);
const runRequestWithExpiredProviderToken = async () => {
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const device = MOCK_DEVICE_TOKEN;
let receivedError;
try {
await client.write(mockNotification, device, 'device', 'post');
} catch (e) {
receivedError = e;
}
expect(receivedError).to.exist;
expect(receivedError.device).to.equal(device);
expect(receivedError.error).to.be.an.instanceof(VError);
expect(receivedError.error.message).to.have.string('APNs response');
};
await runRequestWithExpiredProviderToken();
await runRequestWithExpiredProviderToken();
await runRequestWithExpiredProviderToken();
expect(establishedConnections).to.equal(1);
await Promise.allSettled([
runRequestWithExpiredProviderToken(),
runRequestWithExpiredProviderToken(),
runRequestWithExpiredProviderToken(),
runRequestWithExpiredProviderToken(),
]);
expect(establishedConnections).to.equal(1); // should close and establish new connections on http 500
expect(errorMessages).to.not.be.empty;
let errorMessagesContainsAPN = false;
// Search for message, in older node, may be in random order.
for (const message of errorMessages) {
if (message.includes('APNs response')) {
errorMessagesContainsAPN = true;
break;
}
}
expect(errorMessagesContainsAPN).to.be.true;
expect(infoMessages).to.not.be.empty;
let infoMessagesContainsStatus = false;
// Search for message, in older node, may be in random order.
for (const message of infoMessages) {
if (message.includes('status 403')) {
infoMessagesContainsStatus = true;
break;
}
}
expect(infoMessagesContainsStatus).to.be.true;
});
// node-apn started closing connections in response to a bug report where HTTP 500 responses
// persisted until a new connection was reopened
it('Closes connections when HTTP 500 responses are received', async () => {
let establishedConnections = 0;
let responseDelay = 50;
server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
// Wait 50ms before sending the responses in parallel
setTimeout(() => {
expect(requestBody).to.equal(MOCK_BODY);
res.writeHead(500);
res.end('{"reason": "InternalServerError"}');
}, responseDelay);
});
server.on('connection', () => (establishedConnections += 1));
await new Promise(resolve => server.on('listening', resolve));
client = createClient(CLIENT_TEST_PORT);
const runRequestWithInternalServerError = async () => {
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const device = MOCK_DEVICE_TOKEN;
let receivedError;
try {
await client.write(mockNotification, device, 'device', 'post');
} catch (e) {
receivedError = e;
}
expect(receivedError).to.exist;
expect(receivedError.device).to.equal(device);
expect(receivedError.error).to.be.an.instanceof(VError);
expect(receivedError.error.message).to.have.string('stream ended unexpectedly');
};
await runRequestWithInternalServerError();
await runRequestWithInternalServerError();
await runRequestWithInternalServerError();
expect(establishedConnections).to.equal(3); // should close and establish new connections on http 500
// Validate that nothing wrong happens when multiple HTTP 500s are received simultaneously.
// (no segfaults, all promises get resolved, etc.)
responseDelay = 50;
await Promise.allSettled([
runRequestWithInternalServerError(),
runRequestWithInternalServerError(),
runRequestWithInternalServerError(),
runRequestWithInternalServerError(),
]);
expect(establishedConnections).to.equal(4); // should close and establish new connections on http 500
});
it('Handles unexpected invalid JSON responses', async () => {
let establishedConnections = 0;
const responseDelay = 0;
server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
// Wait 50ms before sending the responses in parallel
setTimeout(() => {
expect(requestBody).to.equal(MOCK_BODY);
res.writeHead(500);
res.end('PC LOAD LETTER');
}, responseDelay);
});
server.on('connection', () => (establishedConnections += 1));
await new Promise(resolve => server.on('listening', resolve));
client = createClient(CLIENT_TEST_PORT);
const runRequestWithInternalServerError = async () => {
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const device = MOCK_DEVICE_TOKEN;
let receivedError;
try {
await client.write(mockNotification, device, 'device', 'post');
} catch (e) {
receivedError = e;
}
// Should not happen, but if it does, the promise should resolve with an error
expect(receivedError).to.exist;
expect(receivedError.device).to.equal(device);
expect(
receivedError.error.message.startsWith(
'Unexpected error processing APNs response: Unexpected token'
)
).to.equal(true);
};
await runRequestWithInternalServerError();
await runRequestWithInternalServerError();
expect(establishedConnections).to.equal(1); // Currently reuses the connection.
});
it('Handles APNs timeouts', async () => {
let didGetRequest = false;
let didGetResponse = false;
server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
didGetRequest = true;
setTimeout(() => {
res.writeHead(200);
res.end('');
didGetResponse = true;
}, 1900);
});
client = createClient(CLIENT_TEST_PORT);
const onListeningPromise = new Promise(resolve => server.on('listening', resolve));
await onListeningPromise;
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const performRequestExpectingTimeout = async () => {
const device = MOCK_DEVICE_TOKEN;
let receivedError;
try {
await client.write(mockNotification, device, 'device', 'post');
} catch (e) {
receivedError = e;
}
expect(receivedError).to.exist;
expect(receivedError).to.deep.equal({
device,
error: new VError('apn write timeout'),
});
expect(didGetRequest).to.be.true;
expect(didGetResponse).to.be.false;
};
await performRequestExpectingTimeout();
didGetResponse = false;
didGetRequest = false;
// Should be able to have multiple in flight requests all get notified that the server is shutting down
await Promise.all([
performRequestExpectingTimeout(),
performRequestExpectingTimeout(),
performRequestExpectingTimeout(),
performRequestExpectingTimeout(),
]);
});
it('Handles goaway frames and retries the request on a new connection', async () => {
let didGetRequest = false;
let establishedConnections = 0;
server = createAndStartMockLowLevelServer(TEST_PORT, stream => {
const { session } = stream;
const errorCode = 1;
didGetRequest = true;
session.goaway(errorCode);
});
server.on('connection', () => (establishedConnections += 1));
client = createClient(CLIENT_TEST_PORT);
// Setup logger.
const infoMessages = [];
const errorMessages = [];
const mockInfoLogger = message => {
infoMessages.push(message);
};
const mockErrorLogger = message => {
errorMessages.push(message);
};
mockInfoLogger.enabled = true;
mockErrorLogger.enabled = true;
client.setLogger(mockInfoLogger, mockErrorLogger);
const onListeningPromise = new Promise(resolve => server.on('listening', resolve));
await onListeningPromise;
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const performRequestExpectingGoAway = async () => {
const device = MOCK_DEVICE_TOKEN;
let receivedError;
try {
await client.write(mockNotification, device, 'device', 'post');
} catch (e) {
receivedError = e;
}
expect(receivedError).to.exist;
expect(receivedError.device).to.equal(device);
expect(receivedError.error).to.be.an.instanceof(VError);
expect(didGetRequest).to.be.true;
didGetRequest = false;
};
await performRequestExpectingGoAway();
await performRequestExpectingGoAway();
expect(establishedConnections).to.equal(8);
expect(errorMessages).to.not.be.empty;
let errorMessagesContainsGoAway = false;
// Search for message, in older node, may be in random order.
for (const message of errorMessages) {
if (message.includes('GOAWAY')) {
errorMessagesContainsGoAway = true;
break;
}
}
expect(errorMessagesContainsGoAway).to.be.true;
expect(infoMessages).to.not.be.empty;
});
it('Handles unexpected protocol errors (no response sent)', async () => {
let didGetRequest = false;
let establishedConnections = 0;
let responseTimeout = 0;
server = createAndStartMockLowLevelServer(TEST_PORT, stream => {
setTimeout(() => {
const { session } = stream;
didGetRequest = true;
if (session) {
session.destroy();
}
}, responseTimeout);
});
server.on('connection', () => (establishedConnections += 1));
client = createClient(CLIENT_TEST_PORT);
// Setup logger.
const infoMessages = [];
const errorMessages = [];
const mockInfoLogger = message => {
infoMessages.push(message);
};
const mockErrorLogger = message => {
errorMessages.push(message);
};
mockInfoLogger.enabled = true;
mockErrorLogger.enabled = true;
client.setLogger(mockInfoLogger, mockErrorLogger);
const onListeningPromise = new Promise(resolve => server.on('listening', resolve));
await onListeningPromise;
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const performRequestExpectingDisconnect = async () => {
const device = MOCK_DEVICE_TOKEN;
let receivedError;
try {
await client.write(mockNotification, device, 'device', 'post');
} catch (e) {
receivedError = e;
}
expect(receivedError).to.exist;
expect(receivedError).to.deep.equal({
device,
error: new VError('stream ended unexpectedly with status null and empty body'),
});
expect(didGetRequest).to.be.true;
};
await performRequestExpectingDisconnect();
didGetRequest = false;
await performRequestExpectingDisconnect();
didGetRequest = false;
expect(establishedConnections).to.equal(2);
responseTimeout = 10;
await Promise.all([
performRequestExpectingDisconnect(),
performRequestExpectingDisconnect(),
performRequestExpectingDisconnect(),
performRequestExpectingDisconnect(),
]);
expect(establishedConnections).to.equal(3);
expect(errorMessages).to.not.be.empty;
let errorMessagesContainsGoAway = false;
// Search for message, in older node, may be in random order.
for (const message of errorMessages) {
if (message.includes('GOAWAY')) {
errorMessagesContainsGoAway = true;
break;
}
}
expect(errorMessagesContainsGoAway).to.be.true;
expect(infoMessages).to.not.be.empty;
let infoMessagesContainsStatus = false;
// Search for message, in older node, may be in random order.
for (const message of infoMessages) {
if (message.includes('status null')) {
infoMessagesContainsStatus = true;
break;
}
}
expect(infoMessagesContainsStatus).to.be.true;
});
it('Establishes a connection through a proxy server', async () => {
let didRequest = false;
let establishedConnections = 0;
let requestsServed = 0;
const method = HTTP2_METHOD_POST;
const path = PATH_DEVICE;
const proxyPort = TEST_PORT - 1;
server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
expect(req.headers).to.deep.equal({
':authority': '127.0.0.1',
':method': method,
':path': path,
':scheme': 'https',
'apns-someheader': 'somevalue',
});
expect(requestBody).to.equal(MOCK_BODY);
// res.setHeader('X-Foo', 'bar');
// res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.writeHead(200);
res.end('');
requestsServed += 1;
didRequest = true;
});
server.on('connection', () => (establishedConnections += 1));
await new Promise(resolve => server.once('listening', resolve));
// Proxy forwards all connections to TEST_PORT.
const sockets = [];
let proxy = net.createServer(clientSocket => {
clientSocket.once('data', () => {
const serverSocket = net.createConnection(TEST_PORT, () => {
clientSocket.write('HTTP/1.1 200 OK\r\n\r\n');
clientSocket.pipe(serverSocket);
setTimeout(() => {
serverSocket.pipe(clientSocket);
}, 1);
});
sockets.push(clientSocket, serverSocket);
});
clientSocket.on('error', () => {});
});
await new Promise(resolve => proxy.listen(proxyPort, resolve));
// Don't block the tests if this server doesn't shut down properly.
proxy.unref();
// Client configured with a port that the server is not listening on.
client = createClient(CLIENT_TEST_PORT);
// Not adding a proxy config will cause a failure with a network error.
client.config.proxy = { host: '127.0.0.1', port: proxyPort };
const runSuccessfulRequest = async () => {
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const device = MOCK_DEVICE_TOKEN;
const result = await client.write(mockNotification, device, 'device', 'post');
expect(result).to.deep.equal({ device });
expect(didRequest).to.be.true;
};
expect(establishedConnections).to.equal(0); // should not establish a connection until it's needed
// Validate that when multiple valid requests arrive concurrently,
// only one HTTP/2 connection gets established.
await Promise.all([
runSuccessfulRequest(),
runSuccessfulRequest(),
runSuccessfulRequest(),
runSuccessfulRequest(),
runSuccessfulRequest(),
]);
didRequest = false;
await runSuccessfulRequest();
expect(establishedConnections).to.equal(1); // should establish a connection to the server and reuse it
expect(requestsServed).to.equal(6);
// Shut down proxy server properly.
await new Promise(resolve => {
sockets.forEach(socket => socket.end(''));
proxy.close(() => {
resolve();
});
});
proxy = null;
});
it('Throws an error when there is a bad proxy server', async () => {
// Client configured with a port that the server is not listening on.
client = createClient(CLIENT_TEST_PORT);
// Not adding a proxy config will cause a failure with a network error.
client.config.proxy = { host: '127.0.0.1', port: 'NOT_A_PORT' };
// Setup logger.
const infoMessages = [];
const errorMessages = [];
const mockInfoLogger = message => {
infoMessages.push(message);
};
const mockErrorLogger = message => {
errorMessages.push(message);
};
mockInfoLogger.enabled = true;
mockErrorLogger.enabled = true;
client.setLogger(mockInfoLogger, mockErrorLogger);
const runUnsuccessfulRequest = async () => {
const mockHeaders = { 'apns-someheader': 'somevalue' };
const mockNotification = {
headers: mockHeaders,
body: MOCK_BODY,
};
const device = MOCK_DEVICE_TOKEN;
let receivedError;
try {
await client.write(mockNotification, device, 'device', 'post');
} catch (e) {
receivedError = e;
}
expect(receivedError).to.exist;
expect(receivedError.device).to.equal(device);
expect(receivedError.error.code).to.equal('ERR_SOCKET_BAD_PORT');
};
await runUnsuccessfulRequest();
expect(errorMessages).to.not.be.empty;
let errorMessagesContainsStatus = false;
// Search for message, in older node, may be in random order.
for (const message of errorMessages) {
if (message.includes('NOT_A_PORT')) {
errorMessagesContainsStatus = true;
break;
}
}
expect(errorMessagesContainsStatus).to.be.true;
expect(infoMessages).to.be.empty;
});
// let fakes, Client;
// beforeEach(() => {
// fakes = {
// config: sinon.stub(),
// EndpointManager: sinon.stub(),
// endpointManager: new EventEmitter(),
// };
// fakes.EndpointManager.returns(fakes.endpointManager);
// fakes.endpointManager.shutdown = sinon.stub();
// Client = require("../lib/client")(fakes);
// });
// describe("constructor", () => {
// it("prepares the configuration with passed options", () => {
// let options = { production: true };
// let client = new Client(options);
// expect(fakes.config).to.be.calledWith(options);
// });
// describe("EndpointManager instance", function() {
// it("is created", () => {
// let client = new Client();
// expect(fakes.EndpointManager).to.be.calledOnce;
// expect(fakes.EndpointManager).to.be.calledWithNew;
// });
// it("is passed the prepared configuration", () => {
// const returnSentinel = { "configKey": "configValue"};
// fakes.config.returns(returnSentinel);
// let client = new Client({});
// expect(fakes.EndpointManager).to.be.calledWith(returnSentinel);
// });
// });
// });
describe('write', () => {
// beforeEach(() => {
// fakes.config.returnsArg(0);
// fakes.endpointManager.getStream = sinon.stub();
// fakes.EndpointManager.returns(fakes.endpointManager);