-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
225 lines (197 loc) · 5.33 KB
/
index.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
import got from "got";
import { Counter, Histogram, Registry } from "prom-client";
import { resolve as resolveUrl } from "url";
import urlTemplate from "url-template";
const requestsCount = new Counter({
name: "http_client_requests_total",
help: "Total number of http client requests",
labelNames: ["base", "method", "path", "code"],
registers: []
});
const requestDuration = new Histogram({
name: "http_client_request_duration_seconds",
help: "Latencies for http client requests",
labelNames: ["base", "method", "path"],
registers: []
});
const requestStageDuration = new Histogram({
name: "http_client_request_stage_duration_seconds",
help: "Latencies for http client requests",
labelNames: ["base", "stage"],
registers: []
});
export function registerMetrics(registry: Registry) {
registry.registerMetric(requestsCount);
registry.registerMetric(requestDuration);
registry.registerMetric(requestStageDuration);
}
function memoize<K, V>(fn: (key: K) => V): (key: K) => V {
const cache = new Map<K, V>();
return (key: K) => {
if (cache.has(key)) {
return cache.get(key) as V;
}
const val = fn(key);
cache.set(key, val);
return val;
};
}
interface Expander {
expand(parameters: any): string;
}
type Parse = (pathTemplate: string) => Expander;
export const parseUrlTemplate: Parse = memoize((pathTemplate: string) =>
urlTemplate.parse(pathTemplate)
);
interface Headers {
[header: string]: number | string | string[] | undefined;
}
interface Options {
baseUrl: string;
headers: Headers;
}
interface Timings {
start?: number;
socket?: number;
lookup?: number;
connect?: number;
upload?: number;
response?: number;
end?: number;
error?: number;
phases: {
wait?: number;
dns?: number;
tcp?: number;
request?: number;
firstByte?: number;
download?: number;
total?: number;
};
}
interface Result {
timings?: Timings;
statusCode?: number;
}
type RequestOptions =
| got.GotJSONOptions
| got.GotFormOptions<string | null>
| got.GotBodyOptions<string | null>;
type Method =
| "GET"
| "PUT"
| "POST"
| "PATCH"
| "DELETE"
| "HEAD"
| "OPTIONS"
| "TRACE"
| "CONNECT";
/**
* Class that can be usefully extended to abstract calls to a http apis.
* @example
* class ExampleCient extends HTTPClient {
* constructor() {
* super({ baseUrl: 'https://example.com/'});
* }
* getThing(id) {
* return this.request('GET', '/thing/{id}', {id});
* }
* }
*/
export class HTTPClient {
baseUrl: string;
headers: Headers;
/**
* Create a HTTPClient
* @param {string} baseUrl base url to use for each request
* @param {Object} headers headers to attach to each request
*/
constructor(opts: Options) {
const { baseUrl, headers } = opts;
this.baseUrl = baseUrl;
this.headers = headers;
// this.agent = agent;
}
/**
* execute request based an path template and params,
* Note that the path is always appended to the baseUrl, a leading /
* does not eliminate the path from the baseUrl.
* @param {string} method http method
* @param {string} pathTemplate RFC 6570 path template string
* @param {Object} [params={}] parameters to be injected into pathTemplate
* @param {Object} [body] body that will be json encoded and sent
* @return {Promise<Result>} result of request, (after passing through handlers)
*/
request(
method: Method,
pathTemplate: string,
params = {},
body?: {},
options?: RequestOptions
) {
const path = parseUrlTemplate(pathTemplate);
const url = resolveUrl(this.baseUrl, path.expand(params));
const stopTimer = requestDuration.startTimer();
const recordDone = (result: Result) => {
stopTimer({ method, path: pathTemplate, base: this.baseUrl });
if (result.timings) {
for (const [stage, value] of Object.entries(result.timings.phases)) {
if (stage === "total") {
continue;
}
if (typeof value !== "number") {
continue;
}
requestStageDuration.observe(
{ stage, base: this.baseUrl },
value / 1000
);
}
}
requestsCount.inc({
method,
path: pathTemplate,
code: result.statusCode || -1,
base: this.baseUrl
});
};
const defaultOptions: got.GotJSONOptions = {
method: method.toUpperCase(),
body,
headers: Object.assign({}, this.headers),
json: true,
retry: 0,
timeout: 60000
// agent: this.agent
};
return got(url, Object.assign(defaultOptions, options)).then(
(res: any) => {
recordDone(res);
return this._handlerResponse(res);
},
(err: got.GotError) => {
recordDone(err.response || err);
return this._handlerError(err);
}
);
}
/**
* map response to result (for overloading)
* @param {Object} res http response
* @return {(Result|Promise<Result>)}
*/
_handlerResponse(res: any) {
return res;
}
/**
* map response error to result (for overloading)
* @param {Object} err error from http response
* @param {Object} err.statusCode http status code
* @param {Object} err.response original http response
* @return {(Result|Promise<Result>)}
*/
_handlerError(err: Error) {
throw err;
}
}