-
Notifications
You must be signed in to change notification settings - Fork 10.2k
/
Copy pathHttpConnection.test.ts
1619 lines (1400 loc) · 69.3 KB
/
HttpConnection.test.ts
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
import { HttpResponse } from "../src/HttpClient";
import { HttpConnection, INegotiateResponse, TransportSendQueue } from "../src/HttpConnection";
import { IHttpConnectionOptions } from "../src/IHttpConnectionOptions";
import { HttpTransportType, ITransport, TransferFormat } from "../src/ITransport";
import { getUserAgentHeader } from "../src/Utils";
import { HttpError } from "../src/Errors";
import { ILogger, LogLevel } from "../src/ILogger";
import { NullLogger } from "../src/Loggers";
import { EventSourceConstructor, WebSocketConstructor } from "../src/Polyfills";
import { eachEndpointUrl, eachTransport, VerifyLogger } from "./Common";
import { TestHttpClient } from "./TestHttpClient";
import { TestTransport } from "./TestTransport";
import { TestEvent, TestWebSocket } from "./TestWebSocket";
import { PromiseSource, registerUnhandledRejectionHandler, SyncPoint } from "./Utils";
import { HeaderNames } from "../src/HeaderNames";
const commonOptions: IHttpConnectionOptions = {
logger: NullLogger.instance,
};
const defaultConnectionId = "abc123";
const defaultConnectionToken = "123abc";
const defaultNegotiateResponse: INegotiateResponse = {
availableTransports: [
{ transport: "WebSockets", transferFormats: ["Text", "Binary"] },
{ transport: "ServerSentEvents", transferFormats: ["Text"] },
{ transport: "LongPolling", transferFormats: ["Text", "Binary"] },
],
connectionId: defaultConnectionId,
connectionToken: defaultConnectionToken,
negotiateVersion: 1,
};
function ServerSentEventsNotAllowed() { throw new Error("Don't allow ServerSentEvents."); }
function WebSocketNotAllowed() { throw new Error("Don't allow Websockets."); }
registerUnhandledRejectionHandler();
describe("HttpConnection", () => {
it("cannot be created with relative url if document object is not present", () => {
expect(() => new HttpConnection("/test", commonOptions))
.toThrow("Cannot resolve '/test'.");
});
it("cannot be created with relative url if window object is not present", () => {
(global as any).window = {};
expect(() => new HttpConnection("/test", commonOptions))
.toThrow("Cannot resolve '/test'.");
delete (global as any).window;
});
it("starting connection fails if getting id fails", async () => {
await VerifyLogger.run(async (logger) => {
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => Promise.reject("error"))
.on("GET", () => ""),
logger,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow(new Error("Failed to complete negotiation with the server: error"));
},
"Failed to start the connection: Error: Failed to complete negotiation with the server: error",
"Failed to complete negotiation with the server: error");
});
it("cannot start a running connection", async () => {
await VerifyLogger.run(async (logger) => {
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => defaultNegotiateResponse),
logger,
transport: {
connect() {
return Promise.resolve();
},
send() {
return Promise.resolve();
},
stop() {
return Promise.resolve();
},
onclose: null,
onreceive: null,
},
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
try {
await connection.start(TransferFormat.Text);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("Cannot start an HttpConnection that is not in the 'Disconnected' state.");
} finally {
(options.transport as ITransport).onclose!();
await connection.stop();
}
});
});
it("can start a stopped connection", async () => {
await VerifyLogger.run(async (logger) => {
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => {
return Promise.reject("reached negotiate.");
})
.on("GET", () => ""),
logger,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow(new Error("Failed to complete negotiation with the server: reached negotiate."));
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow(new Error("Failed to complete negotiation with the server: reached negotiate."));
},
"Failed to complete negotiation with the server: reached negotiate.",
"Failed to start the connection: Error: Failed to complete negotiation with the server: reached negotiate.");
});
it("can stop a starting connection", async () => {
await VerifyLogger.run(async (logger) => {
const stoppingPromise = new PromiseSource();
const startingPromise = new PromiseSource();
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", async () => {
startingPromise.resolve();
await stoppingPromise;
return "{}";
}),
logger,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
const startPromise = connection.start(TransferFormat.Text);
await startingPromise;
const stopPromise = connection.stop();
stoppingPromise.resolve();
await stopPromise;
await expect(startPromise)
.rejects
.toThrow("The connection was stopped during negotiation.");
},
"Failed to start the connection: Error: The connection was stopped during negotiation.");
});
it("cannot send with an un-started connection", async () => {
await VerifyLogger.run(async (logger) => {
const connection = new HttpConnection("http://tempuri.org");
await expect(connection.send("LeBron James"))
.rejects
.toThrow("Cannot send data if the connection is not in the 'Connected' State.");
});
});
it("sending before start doesn't throw synchronously", async () => {
await VerifyLogger.run(async (logger) => {
const connection = new HttpConnection("http://tempuri.org");
try {
connection.send("test").catch((e) => {});
} catch (e) {
expect(false).toBe(true);
}
});
});
it("cannot be started if negotiate returns non 200 response", async () => {
await VerifyLogger.run(async (logger) => {
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => new HttpResponse(999))
.on("GET", () => ""),
logger,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("Unexpected status code returned from negotiate '999'");
},
"Failed to start the connection: Error: Unexpected status code returned from negotiate '999'");
});
it("all transport failure errors get aggregated", async () => {
await VerifyLogger.run(async (loggerImpl) => {
let negotiateCount: number = 0;
const options: IHttpConnectionOptions = {
WebSocket: false,
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => {
negotiateCount++;
return defaultNegotiateResponse;
})
.on("GET", () => new HttpResponse(200))
.on("DELETE", () => new HttpResponse(202)),
logger: loggerImpl,
transport: HttpTransportType.WebSockets,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("Unable to connect to the server with any of the available transports. WebSockets failed: Error: WebSocket failed to connect. " +
"The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, " +
"or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled. ServerSentEvents failed: Error: 'ServerSentEvents' is disabled by the client. LongPolling failed: Error: 'LongPolling' is disabled by the client.");
expect(negotiateCount).toEqual(1);
},
/* eslint-disable max-len */
"Failed to start the transport 'WebSockets': Error: WebSocket failed to connect. The connection could not be found on the server, " +
"either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",
"Failed to start the connection: Error: Unable to connect to the server with any of the available transports. WebSockets failed: " +
"Error: WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled. ServerSentEvents failed: Error: 'ServerSentEvents' is disabled by the client. LongPolling failed: Error: 'LongPolling' is disabled by the client.");
/* eslint-enable max-len */
});
it("negotiate called again when transport fails to start and falls back", async () => {
await VerifyLogger.run(async (loggerImpl) => {
let negotiateCount: number = 0;
const options: IHttpConnectionOptions = {
EventSource: ServerSentEventsNotAllowed,
WebSocket: WebSocketNotAllowed,
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => {
negotiateCount++;
return defaultNegotiateResponse;
})
.on("GET", () => new HttpResponse(200))
.on("DELETE", () => new HttpResponse(202)),
logger: loggerImpl,
transport: HttpTransportType.WebSockets | HttpTransportType.ServerSentEvents,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("Unable to connect to the server with any of the available transports. WebSockets failed: Error: Don't allow Websockets. ServerSentEvents failed: Error: Don't allow ServerSentEvents. LongPolling failed: Error: 'LongPolling' is disabled by the client.");
expect(negotiateCount).toEqual(2);
},
"Failed to start the transport 'WebSockets': Error: Don't allow Websockets.",
"Failed to start the transport 'ServerSentEvents': Error: Don't allow ServerSentEvents.",
"Failed to start the connection: Error: Unable to connect to the server with any of the available transports. WebSockets failed: Error: Don't allow Websockets. ServerSentEvents failed: Error: Don't allow ServerSentEvents. LongPolling failed: Error: 'LongPolling' is disabled by the client.");
});
it("failed re-negotiate fails start", async () => {
await VerifyLogger.run(async (loggerImpl) => {
let negotiateCount: number = 0;
const options: IHttpConnectionOptions = {
EventSource: ServerSentEventsNotAllowed,
WebSocket: WebSocketNotAllowed,
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => {
negotiateCount++;
if (negotiateCount === 2) {
throw new Error("negotiate failed");
}
return defaultNegotiateResponse;
})
.on("GET", () => new HttpResponse(200))
.on("DELETE", () => new HttpResponse(202)),
logger: loggerImpl,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("negotiate failed");
expect(negotiateCount).toEqual(2);
},
"Failed to start the transport 'WebSockets': Error: Don't allow Websockets.",
"Failed to complete negotiation with the server: Error: negotiate failed",
"Failed to start the connection: Error: Failed to complete negotiation with the server: Error: negotiate failed");
});
it("can stop a non-started connection", async () => {
await VerifyLogger.run(async (logger) => {
const connection = new HttpConnection("http://tempuri.org", { ...commonOptions, logger });
await connection.stop();
});
});
it("start throws after all transports fail", async () => {
await VerifyLogger.run(async (logger) => {
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => ({ connectionId: "42", availableTransports: [] }))
.on("GET", () => { throw new Error("fail"); }),
logger,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org?q=myData", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("None of the transports supported by the client are supported by the server.");
},
"Failed to start the connection: Error: None of the transports supported by the client are supported by the server.");
});
it("preserves user's query string", async () => {
await VerifyLogger.run(async (logger) => {
const connectUrl = new PromiseSource<string>();
const fakeTransport: ITransport = {
connect(url: string): Promise<void> {
connectUrl.resolve(url);
return Promise.resolve();
},
send(): Promise<void> {
return Promise.resolve();
},
stop(): Promise<void> {
return Promise.resolve();
},
onclose: null,
onreceive: null,
};
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => "{ \"connectionId\": \"42\" }")
.on("GET", () => ""),
logger,
transport: fakeTransport,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org?q=myData", options);
try {
const startPromise = connection.start(TransferFormat.Text);
expect(await connectUrl).toBe("http://tempuri.org?q=myData&id=42");
await startPromise;
} finally {
(options.transport as ITransport).onclose!();
await connection.stop();
}
});
});
eachEndpointUrl((givenUrl: string, expectedUrl: string) => {
it(`negotiate request for '${givenUrl}' puts 'negotiate' at the end of the path`, async () => {
await VerifyLogger.run(async (logger) => {
const negotiateUrl = new PromiseSource<string>();
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", (r) => {
negotiateUrl.resolve(r.url || "");
throw new HttpError("We don't care how this turns out", 500);
})
.on("GET", () => {
return new HttpResponse(204);
})
.on("DELETE", () => new HttpResponse(202)),
logger,
} as IHttpConnectionOptions;
const connection = new HttpConnection(givenUrl, options);
try {
const startPromise = connection.start(TransferFormat.Text);
expect(await negotiateUrl).toBe(expectedUrl);
await expect(startPromise).rejects.toThrow("We don't care how this turns out");
} finally {
await connection.stop();
}
},
"Failed to complete negotiation with the server: Error: We don't care how this turns out: Status code '500'",
"Failed to start the connection: Error: Failed to complete negotiation with the server: Error: We don't care how this turns out: Status code '500'");
});
});
eachTransport((requestedTransport: HttpTransportType) => {
it(`cannot be started if requested ${HttpTransportType[requestedTransport]} transport not available on server`, async () => {
await VerifyLogger.run(async (logger) => {
// Clone the default response
const negotiateResponse = { ...defaultNegotiateResponse };
// Remove the requested transport from the response
negotiateResponse.availableTransports = negotiateResponse.availableTransports!
.filter((f) => f.transport !== HttpTransportType[requestedTransport]);
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => negotiateResponse)
.on("GET", () => new HttpResponse(204)),
logger,
transport: requestedTransport,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow(`Unable to connect to the server with any of the available transports. ${negotiateResponse.availableTransports[0].transport} failed: Error: '${negotiateResponse.availableTransports[0].transport}' is disabled by the client.` +
` ${negotiateResponse.availableTransports[1].transport} failed: Error: '${negotiateResponse.availableTransports[1].transport}' is disabled by the client.`);
},
/Failed to start the connection: Error: Unable to connect to the server with any of the available transports. [a-zA-Z]+\b failed: Error: '[a-zA-Z]+\b' is disabled by the client. [a-zA-Z]+\b failed: Error: '[a-zA-Z]+\b' is disabled by the client./);
});
it(`cannot be started if server's only transport (${HttpTransportType[requestedTransport]}) is masked out by the transport option`, async () => {
await VerifyLogger.run(async (logger) => {
const negotiateResponse = {
availableTransports: [
{ transport: "WebSockets", transferFormats: ["Text", "Binary"] },
{ transport: "ServerSentEvents", transferFormats: ["Text"] },
{ transport: "LongPolling", transferFormats: ["Text", "Binary"] },
],
connectionId: "abc123",
};
// Build the mask by inverting the requested transport
const transportMask = ~requestedTransport;
// Remove all transports other than the requested one
negotiateResponse.availableTransports = negotiateResponse.availableTransports
.filter((r) => r.transport === HttpTransportType[requestedTransport]);
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => negotiateResponse)
.on("GET", () => new HttpResponse(204)),
logger,
transport: transportMask,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
try {
await connection.start(TransferFormat.Text);
fail("Expected connection.start to throw!");
} catch (e) {
expect(e.message).toBe(`Unable to connect to the server with any of the available transports. ${HttpTransportType[requestedTransport]} failed: Error: '${HttpTransportType[requestedTransport]}' is disabled by the client.`);
}
},
`Failed to start the connection: Error: Unable to connect to the server with any of the available transports. ${HttpTransportType[requestedTransport]} failed: Error: '${HttpTransportType[requestedTransport]}' is disabled by the client.`);
});
});
for (const [val, name] of [[null, "null"], [undefined, "undefined"], [0, "0"]]) {
it(`can be started when transport mask is ${name}`, async () => {
let websocketOpen: (() => any) | null = null;
const sync: SyncPoint = new SyncPoint();
const websocket = class WebSocket {
constructor() {
this._onopen = null;
}
private _onopen: ((this: WebSocket, ev: Event) => any) | null;
public get onopen(): ((this: WebSocket, ev: Event) => any) | null {
return this._onopen;
}
public set onopen(onopen: ((this: WebSocket, ev: Event) => any) | null) {
this._onopen = onopen;
websocketOpen = () => this._onopen!({} as Event);
sync.continue();
}
public close(): void {
}
};
await VerifyLogger.run(async (logger) => {
const options: IHttpConnectionOptions = {
WebSocket: websocket as any,
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => defaultNegotiateResponse)
.on("GET", () => new HttpResponse(200))
.on("DELETE", () => new HttpResponse(202)),
logger,
transport: val,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
const startPromise = connection.start(TransferFormat.Text);
await sync.waitToContinue();
websocketOpen!();
await startPromise;
await connection.stop();
});
});
}
it("cannot be started if no transport available on server and no transport requested", async () => {
await VerifyLogger.run(async (logger) => {
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => ({ connectionId: "42", availableTransports: [] }))
.on("GET", () => ""),
logger,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("None of the transports supported by the client are supported by the server.");
},
"Failed to start the connection: Error: None of the transports supported by the client are supported by the server.");
});
it("does not send negotiate request if WebSockets transport requested explicitly and skipNegotiation is true", async () => {
const websocket = class WebSocket {
constructor() {
throw new Error("WebSocket constructor called.");
}
};
await VerifyLogger.run(async (logger) => {
const options: IHttpConnectionOptions = {
WebSocket: websocket as any,
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => { throw new Error("Should not be called"); })
.on("GET", () => { throw new Error("Should not be called"); }),
logger,
skipNegotiation: true,
transport: HttpTransportType.WebSockets,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("WebSocket constructor called.");
},
"Failed to start the connection: Error: WebSocket constructor called.");
});
it("does not start non WebSockets transport if requested explicitly and skipNegotiation is true", async () => {
await VerifyLogger.run(async (logger) => {
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient(),
logger,
skipNegotiation: true,
transport: HttpTransportType.LongPolling,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("Negotiation can only be skipped when using the WebSocket transport directly.");
},
"Failed to start the connection: Error: Negotiation can only be skipped when using the WebSocket transport directly.");
});
it("redirects to url when negotiate returns it", async () => {
await VerifyLogger.run(async (logger) => {
let firstNegotiate = true;
let firstPoll = true;
const httpClient = new TestHttpClient()
.on("POST", /\/negotiate/, () => {
if (firstNegotiate) {
firstNegotiate = false;
return { url: "https://another.domain.url/chat" };
}
return {
availableTransports: [{ transport: "LongPolling", transferFormats: ["Text"] }],
connectionId: "0rge0d00-0040-0030-0r00-000q00r00e00",
};
})
.on("GET", () => {
if (firstPoll) {
firstPoll = false;
return "";
}
return new HttpResponse(200);
})
.on("DELETE", () => new HttpResponse(202));
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient,
logger,
transport: HttpTransportType.LongPolling,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
try {
await connection.start(TransferFormat.Text);
expect(httpClient.sentRequests.length).toBeGreaterThanOrEqual(4);
expect(httpClient.sentRequests[0].url).toBe("http://tempuri.org/negotiate?negotiateVersion=1");
expect(httpClient.sentRequests[1].url).toBe("https://another.domain.url/chat/negotiate?negotiateVersion=1");
expect(httpClient.sentRequests[2].url).toMatch(/^https:\/\/another\.domain\.url\/chat\?id=0rge0d00-0040-0030-0r00-000q00r00e00/i);
expect(httpClient.sentRequests[3].url).toMatch(/^https:\/\/another\.domain\.url\/chat\?id=0rge0d00-0040-0030-0r00-000q00r00e00/i);
} finally {
await connection.stop();
}
});
});
it("fails to start if negotiate redirects more than 100 times", async () => {
await VerifyLogger.run(async (logger) => {
const httpClient = new TestHttpClient()
.on("POST", /\/negotiate/, () => ({ url: "https://another.domain.url/chat" }));
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient,
logger,
transport: HttpTransportType.LongPolling,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("Negotiate redirection limit exceeded.");
},
"Failed to start the connection: Error: Negotiate redirection limit exceeded.");
});
it("redirects to url when negotiate returns it with access token", async () => {
await VerifyLogger.run(async (logger) => {
let firstNegotiate = true;
let firstPoll = true;
const httpClient = new TestHttpClient()
.on("POST", /\/negotiate/, (r) => {
if (firstNegotiate) {
firstNegotiate = false;
if (r.headers && r.headers.Authorization !== "Bearer firstSecret") {
return new HttpResponse(401, "Unauthorized", "");
}
return { url: "https://another.domain.url/chat", accessToken: "secondSecret" };
}
if (r.headers && r.headers.Authorization !== "Bearer secondSecret") {
return new HttpResponse(401, "Unauthorized", "");
}
return {
availableTransports: [{ transport: "LongPolling", transferFormats: ["Text"] }],
connectionId: "0rge0d00-0040-0030-0r00-000q00r00e00",
};
})
.on("GET", (r) => {
if (r.headers && r.headers.Authorization !== "Bearer secondSecret") {
return new HttpResponse(401, "Unauthorized", "");
}
if (firstPoll) {
firstPoll = false;
return "";
}
return new HttpResponse(204, "No Content", "");
})
.on("DELETE", () => new HttpResponse(202));
const options: IHttpConnectionOptions = {
...commonOptions,
accessTokenFactory: () => "firstSecret",
httpClient,
logger,
transport: HttpTransportType.LongPolling,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
try {
await connection.start(TransferFormat.Text);
expect(httpClient.sentRequests.length).toBe(4);
expect(httpClient.sentRequests[0].url).toBe("http://tempuri.org/negotiate?negotiateVersion=1");
expect(httpClient.sentRequests[1].url).toBe("https://another.domain.url/chat/negotiate?negotiateVersion=1");
expect(httpClient.sentRequests[2].url).toMatch(/^https:\/\/another\.domain\.url\/chat\?id=0rge0d00-0040-0030-0r00-000q00r00e00/i);
expect(httpClient.sentRequests[3].url).toMatch(/^https:\/\/another\.domain\.url\/chat\?id=0rge0d00-0040-0030-0r00-000q00r00e00/i);
} finally {
await connection.stop();
}
});
});
it("throws error if negotiate response has error", async () => {
await VerifyLogger.run(async (logger) => {
const httpClient = new TestHttpClient()
.on("POST", /\/negotiate/, () => ({ error: "Negotiate error." }));
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient,
logger,
transport: HttpTransportType.LongPolling,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("Negotiate error.");
},
"Failed to start the connection: Error: Negotiate error.");
});
it("authorization header removed when token factory returns null and using LongPolling", async () => {
await VerifyLogger.run(async (logger) => {
const availableTransport = { transport: "LongPolling", transferFormats: ["Text"] };
let httpClientGetCount = 0;
let accessTokenFactoryCount = 0;
const options: IHttpConnectionOptions = {
...commonOptions,
accessTokenFactory: () => {
accessTokenFactoryCount++;
if (accessTokenFactoryCount === 1) {
return "A token value";
} else {
// Return a null value after the first call to test the header being removed
return null;
}
},
httpClient: new TestHttpClient()
.on("POST", () => ({ connectionId: "42", availableTransports: [availableTransport] }))
.on("GET", (r) => {
httpClientGetCount++;
const authorizationValue = r.headers![HeaderNames.Authorization];
if (httpClientGetCount === 1) {
if (authorizationValue) {
fail("First long poll request should have a authorization header.");
}
// First long polling request must succeed so start completes
return "";
} else {
// Check second long polling request has its header removed
if (authorizationValue) {
fail("Second long poll request should have no authorization header.");
}
}
})
.on("DELETE", () => new HttpResponse(202)),
logger,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
try {
await connection.start(TransferFormat.Text);
expect(httpClientGetCount).toBeGreaterThanOrEqual(2);
expect(accessTokenFactoryCount).toBeGreaterThanOrEqual(2);
} finally {
await connection.stop();
}
});
});
it("sets inherentKeepAlive feature when using LongPolling", async () => {
await VerifyLogger.run(async (logger) => {
const availableTransport = { transport: "LongPolling", transferFormats: ["Text"] };
let httpClientGetCount = 0;
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => ({ connectionId: "42", availableTransports: [availableTransport] }))
.on("GET", () => {
httpClientGetCount++;
if (httpClientGetCount === 1) {
// First long polling request must succeed so start completes
return "";
}
})
.on("DELETE", () => new HttpResponse(202)),
logger,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
try {
await connection.start(TransferFormat.Text);
expect(connection.features.inherentKeepAlive).toBe(true);
} finally {
await connection.stop();
}
});
});
it("transport handlers set before start", async () => {
await VerifyLogger.run(async (logger) => {
const availableTransport = { transport: "LongPolling", transferFormats: ["Text"] };
let handlersSet = false;
let httpClientGetCount = 0;
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => ({ connectionId: "42", availableTransports: [availableTransport] }))
.on("GET", () => {
httpClientGetCount++;
if (httpClientGetCount === 1) {
if ((connection as any).transport.onreceive && (connection as any).transport.onclose) {
handlersSet = true;
}
// First long polling request must succeed so start completes
return "";
}
})
.on("DELETE", () => new HttpResponse(202)),
logger,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
connection.onreceive = () => null;
try {
await connection.start(TransferFormat.Text);
} finally {
await connection.stop();
}
expect(handlersSet).toBe(true);
});
});
it("transport handlers set before start for custom transports", async () => {
await VerifyLogger.run(async (logger) => {
const availableTransport = { transport: "Custom", transferFormats: ["Text"] };
let handlersSet = false;
const transport: ITransport = {
connect: (url: string, transferFormat: TransferFormat) => {
if (transport.onreceive && transport.onclose) {
handlersSet = true;
}
return Promise.resolve();
},
onclose: null,
onreceive: null,
send: (data: any) => Promise.resolve(),
stop: () => {
if (transport.onclose) {
transport.onclose();
}
return Promise.resolve();
},
};
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => ({ connectionId: "42", availableTransports: [availableTransport] })),
logger,
transport,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
connection.onreceive = () => null;
try {
await connection.start(TransferFormat.Text);
} finally {
await connection.stop();
}
expect(handlersSet).toBe(true);
});
});
it("missing negotiateVersion ignores connectionToken", async () => {
await VerifyLogger.run(async (logger) => {
const availableTransport = { transport: "Custom", transferFormats: ["Text"] };
const transport = {
connect(url: string, transferFormat: TransferFormat) {
return Promise.resolve();
},
send(data: any) {
return Promise.resolve();
},
stop() {
if (transport.onclose) {
transport.onclose();
}
return Promise.resolve();
},
onclose: null,
onreceive: null,
} as ITransport;
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => ({ connectionId: "42", connectionToken: "token", availableTransports: [availableTransport] })),
logger,
transport,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
connection.onreceive = () => null;
try {
await connection.start(TransferFormat.Text);
expect(connection.connectionId).toBe("42");
} finally {
await connection.stop();
}
});
});
it("negotiate version 0 ignores connectionToken", async () => {
await VerifyLogger.run(async (logger) => {
const availableTransport = { transport: "Custom", transferFormats: ["Text"] };
const transport = {
connect(url: string, transferFormat: TransferFormat) {
return Promise.resolve();
},
send(data: any) {
return Promise.resolve();
},
stop() {
if (transport.onclose) {
transport.onclose();
}
return Promise.resolve();
},
onclose: null,
onreceive: null,
} as ITransport;
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => ({ connectionId: "42", connectionToken: "token", negotiateVersion: 0, availableTransports: [availableTransport] })),
logger,
transport,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);
connection.onreceive = () => null;
try {
await connection.start(TransferFormat.Text);
expect(connection.connectionId).toBe("42");
} finally {
await connection.stop();
}
});
});
it("negotiate version 1 uses connectionToken for url and connectionId for property", async () => {
await VerifyLogger.run(async (logger) => {
const availableTransport = { transport: "Custom", transferFormats: ["Text"] };
let connectUrl = "";
const transport = {
connect(url: string, transferFormat: TransferFormat) {
connectUrl = url;
return Promise.resolve();
},
send(data: any) {
return Promise.resolve();
},
stop() {
if (transport.onclose) {
transport.onclose();
}
return Promise.resolve();
},
onclose: null,
onreceive: null,
} as ITransport;
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => ({ connectionId: "42", connectionToken: "token", negotiateVersion: 1, availableTransports: [availableTransport] })),
logger,
transport,
} as IHttpConnectionOptions;
const connection = new HttpConnection("http://tempuri.org", options);