-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.js
111 lines (95 loc) · 2.94 KB
/
http.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
import { once } from "node:events";
import http from "node:http";
import https from "node:https"
import http2 from "node:http2"
import { setTimeout } from 'node:timers/promises'
import fetch from 'node-fetch'
const L1S_HOST = 'l1s.strn.pl'
const httpAgent = new http.Agent()
const httpsAgent = new https.Agent({
servername: L1S_HOST,
})
function acceptHeader (format) {
if (format === 'car') {
return 'application/vnd.ipld.car'
} else if (format === 'raw') {
return 'application/vnd.ipld.raw'
} else {
return null
}
}
export async function sendRequestHttp1 (log) {
const start = Date.now()
let ttfb = null
let cacheHit = false
let requestErr = null
let status = 0
const agent = log.url.protocol === 'https:' ? httpsAgent : httpAgent
const controller = new AbortController();
setTimeout(1000 * 60).then(() => controller.abort())
try {
const res = await fetch(log.url,
{
headers: {
host: L1S_HOST,
accept: acceptHeader(log.format)
},
agent,
signal: controller.signal
},
)
status = res.status
cacheHit = res.headers.get('saturn-cache-status') === 'HIT'
for await (const chunk of res.body) {
if (!ttfb) {
ttfb = Date.now() - start
break
}
}
} catch (err) {
requestErr = err.name + ': ' + err.message
}
return {ttfb, cacheHit, status, format: log.format, requestErr}
}
export async function sendRequestHttp2 (log) {
const start = Date.now()
let ttfb = null
let cacheHit = false
let requestErr = null
let status = 0
const url = new URL(log.url)
const controller = new AbortController();
const timeout = 1000 * 60
setTimeout(timeout).then(() => controller.abort())
const backupTimeout = setTimeout(timeout).then(() => Promise.reject(new Error("Backup timeout")))
const client = http2.connect(url.origin, { servername: L1S_HOST });
const req = client.request(
{
":path": url.pathname + url.search,
accept: acceptHeader(log.format),
host: L1S_HOST,
},
{
endStream: true,
signal: controller.signal,
}
);
const errHandler = async () => {
const [err] = await once(client, "error");
throw err;
};
try {
const [headers] = await Promise.race([once(req, "response"), errHandler(), backupTimeout]);
status = headers[":status"];
cacheHit = headers['saturn-cache-status'] === 'HIT'
for await (const chunk of req) {
if (!ttfb) {
ttfb = Date.now() - start
break
}
}
} catch (err) {
requestErr = err.name + ': ' + err.message
}
return {ttfb, cacheHit, status, format: log.format, requestErr}
}