forked from MercuryWorkshop/epoxy-tls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.js
303 lines (275 loc) · 10.9 KB
/
demo.js
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
import initEpoxy, { EpoxyClient, EpoxyClientOptions, EpoxyHandlers, info as epoxyInfo } from "./pkg/epoxy-bundled.js";
(async () => {
const params = (new URL(location.href)).searchParams;
const should_feature_test = params.has("feature_test");
const should_multiparallel_test = params.has("multi_parallel_test");
const should_parallel_test = params.has("parallel_test");
const should_multiperf_test = params.has("multi_perf_test");
const should_perf_test = params.has("perf_test");
const should_ws_test = params.has("ws_test");
const should_tls_test = params.has("rawtls_test");
const should_udp_test = params.has("udp_test");
const should_reconnect_test = params.has("reconnect_test");
const should_perf2_test = params.has("perf2_test");
const should_wisptransport = params.has("wisptransport");
console.log(
"%cWASM is significantly slower with DevTools open!",
"color:red;font-size:3rem;font-weight:bold"
);
const log = (str) => {
console.log(str);
let el = document.createElement("pre");
el.textContent = str;
document.getElementById("logs").appendChild(el);
window.scrollTo(0, document.body.scrollHeight);
}
await initEpoxy();
let epoxy_client_options = new EpoxyClientOptions();
epoxy_client_options.user_agent = navigator.userAgent;
log("using wisptransport with webrtc backend");
let epoxy_client = new EpoxyClient(async () => {
let peer = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.voip.blackberry.com:3478' }] });
let chan = peer.createDataChannel("wisp");
peer.onnegotiationneeded = e => peer.createOffer().then(d => peer.setLocalDescription(d));
await new Promise(r => {
peer.onicecandidate = event => {
if (event.candidate === null) {
console.log(btoa(JSON.stringify(peer.localDescription)));
let desc = new RTCSessionDescription(JSON.parse(atob(prompt())));
peer.setRemoteDescription(desc);
r()
}
}
});
await new Promise(r => {
chan.onopen = r;
});
let readable = new ReadableStream({
start(controller) {
chan.binaryType = "arraybuffer";
chan.onmessage = ({data}) => controller.enqueue(data);
}
});
let writable = new WritableStream({
write(chunk) {
chan.send(chunk);
}
});
return { read: readable, write: writable };
}, epoxy_client_options);
const tconn0 = performance.now();
await epoxy_client.replace_stream_provider();
const tconn1 = performance.now();
log(`conn establish took ${tconn1 - tconn0} ms or ${(tconn1 - tconn0) / 1000} s`);
// epoxy classes are inspectable
console.log(epoxy_client);
// you can change the user agent and redirect limit in JS
epoxy_client.redirect_limit = 15;
console.log(epoxyInfo);
const test_mux = async (url) => {
const t0 = performance.now();
await epoxy_client.fetch(url);
const t1 = performance.now();
return t1 - t0;
};
const test_native = async (url) => {
const t0 = performance.now();
await fetch(url, { cache: "no-store" });
const t1 = performance.now();
return t1 - t0;
};
const readableStream = (buffer) => {
return new ReadableStream({
start(controller) {
controller.enqueue(buffer);
controller.close();
}
});
};
if (should_feature_test) {
let formdata = new FormData();
formdata.append("a", "b");
for (const url of [
["https://httpbin.org/post", { method: "POST", body: readableStream((new TextEncoder()).encode("abc")) }],
["https://httpbin.org/get", {}],
["https://httpbin.org/gzip", {}],
["https://httpbin.org/brotli", {}],
["https://httpbin.org/redirect/11", {}],
["https://httpbin.org/redirect/1", { redirect: "manual" }],
["https://httpbin.org/post", { method: "POST", body: new URLSearchParams("a=b") }],
["https://httpbin.org/post", { method: "POST", body: formdata }],
["https://httpbin.org/post", { method: "POST", body: "a" }],
["https://httpbin.org/post", { method: "POST", body: (new TextEncoder()).encode("abc") }],
["https://httpbin.org/get", { headers: { "a": "b", "b": "c" } }],
["https://httpbin.org/get", { headers: new Headers({ "a": "b", "b": "c" }) }]
]) {
let resp = await epoxy_client.fetch(url[0], url[1]);
console.warn(url, resp, Object.fromEntries(resp.headers));
log(await resp.text());
}
} else if (should_multiparallel_test) {
const num_tests = 10;
let total_mux_minus_native = 0;
for (const _ of Array(num_tests).keys()) {
let total_mux = 0;
await Promise.all([...Array(num_tests).keys()].map(async i => {
log(`running mux test ${i}`);
return await test_mux("https://httpbin.org/get");
})).then((vals) => { total_mux = vals.reduce((acc, x) => acc + x, 0) });
total_mux = total_mux / num_tests;
let total_native = 0;
await Promise.all([...Array(num_tests).keys()].map(async i => {
log(`running native test ${i}`);
return await test_native("https://httpbin.org/get");
})).then((vals) => { total_native = vals.reduce((acc, x) => acc + x, 0) });
total_native = total_native / num_tests;
log(`avg mux (${num_tests}) took ${total_mux} ms or ${total_mux / 1000} s`);
log(`avg native (${num_tests}) took ${total_native} ms or ${total_native / 1000} s`);
log(`avg mux - avg native (${num_tests}): ${total_mux - total_native} ms or ${(total_mux - total_native) / 1000} s`);
total_mux_minus_native += total_mux - total_native;
}
total_mux_minus_native = total_mux_minus_native / num_tests;
log(`total mux - native (${num_tests} tests of ${num_tests} reqs): ${total_mux_minus_native} ms or ${total_mux_minus_native / 1000} s`);
} else if (should_parallel_test) {
const num_tests = 10;
let total_mux = 0;
await Promise.all([...Array(num_tests).keys()].map(async i => {
log(`running mux test ${i}`);
return await test_mux("https://httpbin.org/get");
})).then((vals) => { total_mux = vals.reduce((acc, x) => acc + x, 0) });
total_mux = total_mux / num_tests;
let total_native = 0;
await Promise.all([...Array(num_tests).keys()].map(async i => {
log(`running native test ${i}`);
return await test_native("https://httpbin.org/get");
})).then((vals) => { total_native = vals.reduce((acc, x) => acc + x, 0) });
total_native = total_native / num_tests;
log(`avg mux (${num_tests}) took ${total_mux} ms or ${total_mux / 1000} s`);
log(`avg native (${num_tests}) took ${total_native} ms or ${total_native / 1000} s`);
log(`avg mux - avg native (${num_tests}): ${total_mux - total_native} ms or ${(total_mux - total_native) / 1000} s`);
} else if (should_multiperf_test) {
const num_tests = 10;
let total_mux_minus_native = 0;
for (const _ of Array(num_tests).keys()) {
let total_mux = 0;
for (const i of Array(num_tests).keys()) {
log(`running mux test ${i}`);
total_mux += await test_mux("https://httpbin.org/get");
}
total_mux = total_mux / num_tests;
let total_native = 0;
for (const i of Array(num_tests).keys()) {
log(`running native test ${i}`);
total_native += await test_native("https://httpbin.org/get");
}
total_native = total_native / num_tests;
log(`avg mux (${num_tests}) took ${total_mux} ms or ${total_mux / 1000} s`);
log(`avg native (${num_tests}) took ${total_native} ms or ${total_native / 1000} s`);
log(`avg mux - avg native (${num_tests}): ${total_mux - total_native} ms or ${(total_mux - total_native) / 1000} s`);
total_mux_minus_native += total_mux - total_native;
}
total_mux_minus_native = total_mux_minus_native / num_tests;
log(`total mux - native (${num_tests} tests of ${num_tests} reqs): ${total_mux_minus_native} ms or ${total_mux_minus_native / 1000} s`);
} else if (should_perf_test) {
const num_tests = 10;
let total_mux = 0;
for (const i of Array(num_tests).keys()) {
log(`running mux test ${i}`);
total_mux += await test_mux("https://httpbin.org/get");
}
total_mux = total_mux / num_tests;
let total_native = 0;
for (const i of Array(num_tests).keys()) {
log(`running native test ${i}`);
total_native += await test_native("https://httpbin.org/get");
}
total_native = total_native / num_tests;
log(`avg mux (${num_tests}) took ${total_mux} ms or ${total_mux / 1000} s`);
log(`avg native (${num_tests}) took ${total_native} ms or ${total_native / 1000} s`);
log(`avg mux - avg native (${num_tests}): ${total_mux - total_native} ms or ${(total_mux - total_native) / 1000} s`);
} else if (should_ws_test) {
let handlers = new EpoxyHandlers(
() => log("opened"),
() => log("closed"),
err => console.error(err),
msg => log(`got "${msg}"`)
);
let ws = await epoxy_client.connect_websocket(
handlers,
"wss://echo.websocket.events",
[],
{ "x-header": "abc" },
);
let i = 0;
while (true) {
log(`sending \`data${i}\``);
await ws.send("data" + i);
i++;
await (new Promise((res, _) => setTimeout(res, 10)));
}
} else if (should_tls_test) {
let decoder = new TextDecoder();
let handlers = new EpoxyHandlers(
() => log("opened"),
() => log("closed"),
err => console.error(err),
msg => { console.log(msg); console.log(decoder.decode(msg).split("\r\n\r\n")[1].length); log(decoder.decode(msg)) },
);
let ws = await epoxy_client.connect_tls(
handlers,
"google.com:443",
);
await ws.send("GET / HTTP 1.1\r\nHost: google.com\r\nConnection: close\r\n\r\n");
await (new Promise((res, _) => setTimeout(res, 500)));
await ws.close();
} else if (should_udp_test) {
let decoder = new TextDecoder();
let handlers = new EpoxyHandlers(
() => log("opened"),
() => log("closed"),
err => console.error(err),
msg => { console.log(msg); log(decoder.decode(msg)) },
);
// tokio example: `cargo r --example echo-udp -- 127.0.0.1:5000`
let ws = await epoxy_client.connect_udp(
handlers,
"127.0.0.1:5000",
);
while (true) {
log("sending `data`");
await ws.send("data");
await (new Promise((res, _) => setTimeout(res, 100)));
}
} else if (should_reconnect_test) {
while (true) {
try {
await epoxy_client.fetch("https://httpbin.org/get");
} catch (e) { console.error(e) }
log("sent req");
await (new Promise((res, _) => setTimeout(res, 500)));
}
} else if (should_perf2_test) {
const num_outer_tests = 10;
const num_inner_tests = 50;
let total_mux_multi = 0;
for (const _ of Array(num_outer_tests).keys()) {
let total_mux = 0;
await Promise.all([...Array(num_inner_tests).keys()].map(async i => {
log(`running mux test ${i}`);
return await test_mux("https://httpbin.org/get");
})).then((vals) => { total_mux = vals.reduce((acc, x) => acc + x, 0) });
total_mux = total_mux / num_inner_tests;
log(`avg mux (${num_inner_tests}) took ${total_mux} ms or ${total_mux / 1000} s`);
total_mux_multi += total_mux;
}
total_mux_multi = total_mux_multi / num_outer_tests;
log(`total avg mux (${num_outer_tests} tests of ${num_inner_tests} reqs): ${total_mux_multi} ms or ${total_mux_multi / 1000} s`);
} else {
console.time();
let resp = await epoxy_client.fetch("https://www.example.com/");
console.timeEnd();
console.log(resp, Object.fromEntries(resp.headers));
log(await resp.text());
}
log("done");
})();