This repository has been archived by the owner on Aug 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
145 lines (128 loc) · 4.06 KB
/
index.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
const { CONSTANTS } = require('./constants');
async function getRequestBody(request) {
if (request.method.match(/GET|HEAD/)) {
return { req: request, body: null };
}
const body = await request.text();
return {
req: new Request(request.url, {
method: request.method,
headers: request.headers,
body,
}),
body,
};
}
async function getResponseBody(response) {
const body = await response.text();
return {
res: new Response(body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
}),
body,
};
}
// These variables are replaced when the worker is
// compiled via webpack using a DefinePlugin
// it has been done this way to reduce the worker bundle
// size and reduce the number of dependencies
//
// The catch blocks will only be triggered from within a node
// environment, which is only during unit testing
let version = 'node';
try {
version = VERSION;
} catch (e) {} // eslint-disable-line no-empty
let host = 'http://localhost';
try {
host = HOST;
} catch (e) {} // eslint-disable-line no-empty
function log(...args) {
if (process.env.NODE_ENV !== 'test') console.log(...args);
}
module.exports.fetchAndCollect = async function fetchAndCollect(request) {
log(`Readme CloudFlare Worker v${version}`, 'https://github.com/readmeio/cloudflare-worker');
const startedDateTime = new Date();
const { req, body: requestBody } = await getRequestBody(request);
const response = await fetch(req);
const requiredHeaders = [CONSTANTS.HEADERS.ID, CONSTANTS.HEADERS.LABEL];
const readmeHeaders = [CONSTANTS.HEADERS.ID, CONSTANTS.HEADERS.LABEL, CONSTANTS.HEADERS.EMAIL];
const missingHeaders = requiredHeaders
.map(header => {
if (!response.headers.has(header)) return header;
return false;
})
.filter(Boolean);
if (missingHeaders.length) {
throw new Error(`Missing headers on the response: ${missingHeaders.join(', ')}`);
}
const { res, body: responseBody } = await getResponseBody(response);
const har = {
log: {
creator: { name: '@readme/cloudflare-worker', version },
entries: [
{
startedDateTime: startedDateTime.toISOString(),
time: new Date().getTime() - startedDateTime.getTime(),
request: {
method: req.method,
url: req.url,
// TODO get http version correctly?
httpVersion: '1.1',
headers: [...req.headers].map(([name, value]) => ({ name, value })),
queryString: [...new URL(req.url).searchParams].map(([name, value]) => ({
name,
value,
})),
postData: {
mimeType: req.headers.get('content-type') || 'application/json',
text: requestBody,
},
},
response: {
status: res.status,
statusText: res.statusText,
headers: [...res.headers]
.map(([name, value]) => ({ name, value }))
// Strip out x-readme-* headers
.filter(header => readmeHeaders.indexOf(header.name) === -1),
content: {
text: responseBody,
size: responseBody.length,
mimeType: res.headers.get('content-type') || 'application/json',
},
},
},
],
},
};
return { har, response: res };
};
module.exports.metrics = function readme(apiKey, group, req, har) {
return fetch(`${host}/v1/request`, {
method: 'POST',
headers: {
authorization: `Basic ${btoa(`${apiKey}:`)}`,
'content-type': 'application/json',
},
body: JSON.stringify([
{
group,
clientIPAddress: req.headers.get('cf-connecting-ip') || '0.0.0.0',
request: har,
},
]),
})
.then(async response => {
log('Response from readme', response);
log(await response.text());
})
.catch(
/* istanbul ignore next */ err => {
if (process.env.NODE_ENV !== 'test') console.error('Error saving log to readme', err);
throw err;
}
);
};