]>
Commit | Line | Data |
---|---|---|
bfe2ef6b | 1 | import { createWriteStream, remove } from 'fs-extra' |
3455c265 | 2 | import got, { CancelableRequest, NormalizedOptions, Options as GotOptions, RequestError, Response } from 'got' |
8729a870 | 3 | import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent' |
4c99953a | 4 | import { ACTIVITY_PUB, BINARY_CONTENT_TYPES, PEERTUBE_VERSION, REQUEST_TIMEOUTS, WEBSERVER } from '../initializers/constants' |
db4b15f2 | 5 | import { pipelinePromise } from './core-utils' |
ac036180 | 6 | import { logger, loggerTagsFactory } from './logger' |
8729a870 | 7 | import { getProxy, isProxyEnabled } from './proxy' |
8 | ||
ac036180 C |
9 | const lTags = loggerTagsFactory('request') |
10 | ||
5842a854 | 11 | const httpSignature = require('@peertube/http-signature') |
da854ddd | 12 | |
b5c36108 C |
13 | export interface PeerTubeRequestError extends Error { |
14 | statusCode?: number | |
15 | responseBody?: any | |
3455c265 | 16 | responseHeaders?: any |
b5c36108 C |
17 | } |
18 | ||
db4b15f2 | 19 | type PeerTubeRequestOptions = { |
4c99953a | 20 | timeout?: number |
db4b15f2 C |
21 | activityPub?: boolean |
22 | bodyKBLimit?: number // 1MB | |
23 | httpSignature?: { | |
24 | algorithm: string | |
25 | authorizationHeaderName: string | |
26 | keyId: string | |
27 | key: string | |
28 | headers: string[] | |
29 | } | |
30 | jsonResponse?: boolean | |
31 | } & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'> | |
32 | ||
33 | const peertubeGot = got.extend({ | |
8729a870 | 34 | ...getAgent(), |
35 | ||
db4b15f2 C |
36 | headers: { |
37 | 'user-agent': getUserAgent() | |
38 | }, | |
39 | ||
40 | handlers: [ | |
41 | (options, next) => { | |
42 | const promiseOrStream = next(options) as CancelableRequest<any> | |
b329abc2 | 43 | const bodyKBLimit = options.context?.bodyKBLimit as number |
db4b15f2 C |
44 | if (!bodyKBLimit) throw new Error('No KB limit for this request') |
45 | ||
b329abc2 C |
46 | const bodyLimit = bodyKBLimit * 1000 |
47 | ||
db4b15f2 C |
48 | /* eslint-disable @typescript-eslint/no-floating-promises */ |
49 | promiseOrStream.on('downloadProgress', progress => { | |
b329abc2 C |
50 | if (progress.transferred > bodyLimit && progress.percent !== 1) { |
51 | const message = `Exceeded the download limit of ${bodyLimit} B` | |
ac036180 | 52 | logger.warn(message, lTags()) |
b329abc2 C |
53 | |
54 | // CancelableRequest | |
55 | if (promiseOrStream.cancel) { | |
56 | promiseOrStream.cancel() | |
57 | return | |
58 | } | |
59 | ||
60 | // Stream | |
61 | (promiseOrStream as any).destroy() | |
db4b15f2 C |
62 | } |
63 | }) | |
e0ce715a | 64 | |
db4b15f2 C |
65 | return promiseOrStream |
66 | } | |
67 | ], | |
68 | ||
69 | hooks: { | |
70 | beforeRequest: [ | |
71 | options => { | |
72 | const headers = options.headers || {} | |
73 | headers['host'] = options.url.host | |
74 | }, | |
75 | ||
76 | options => { | |
77 | const httpSignatureOptions = options.context?.httpSignature | |
78 | ||
79 | if (httpSignatureOptions) { | |
80 | const method = options.method ?? 'GET' | |
81 | const path = options.path ?? options.url.pathname | |
82 | ||
83 | if (!method || !path) { | |
84 | throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`) | |
85 | } | |
86 | ||
87 | httpSignature.signRequest({ | |
88 | getHeader: function (header) { | |
89 | return options.headers[header] | |
90 | }, | |
91 | ||
92 | setHeader: function (header, value) { | |
93 | options.headers[header] = value | |
94 | }, | |
95 | ||
96 | method, | |
97 | path | |
98 | }, httpSignatureOptions) | |
99 | } | |
100 | } | |
3455c265 C |
101 | ], |
102 | ||
103 | beforeRetry: [ | |
104 | (_options: NormalizedOptions, error: RequestError, retryCount: number) => { | |
105 | logger.debug('Retrying request to %s.', error.request.requestUrl, { retryCount, error: buildRequestError(error), ...lTags() }) | |
106 | } | |
db4b15f2 | 107 | ] |
da854ddd | 108 | } |
db4b15f2 | 109 | }) |
e4f97bab | 110 | |
db4b15f2 C |
111 | function doRequest (url: string, options: PeerTubeRequestOptions = {}) { |
112 | const gotOptions = buildGotOptions(options) | |
113 | ||
114 | return peertubeGot(url, gotOptions) | |
115 | .catch(err => { throw buildRequestError(err) }) | |
116 | } | |
117 | ||
118 | function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) { | |
119 | const gotOptions = buildGotOptions(options) | |
120 | ||
121 | return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' }) | |
122 | .catch(err => { throw buildRequestError(err) }) | |
e4f97bab | 123 | } |
dac0a531 | 124 | |
db4b15f2 C |
125 | async function doRequestAndSaveToFile ( |
126 | url: string, | |
bfe2ef6b | 127 | destPath: string, |
db4b15f2 | 128 | options: PeerTubeRequestOptions = {} |
bfe2ef6b | 129 | ) { |
4c99953a | 130 | const gotOptions = buildGotOptions({ ...options, timeout: options.timeout ?? REQUEST_TIMEOUTS.FILE }) |
02988fdc | 131 | |
db4b15f2 | 132 | const outFile = createWriteStream(destPath) |
bfe2ef6b | 133 | |
db4b15f2 C |
134 | try { |
135 | await pipelinePromise( | |
136 | peertubeGot.stream(url, gotOptions), | |
137 | outFile | |
138 | ) | |
139 | } catch (err) { | |
140 | remove(destPath) | |
ac036180 | 141 | .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err, ...lTags() })) |
bfe2ef6b | 142 | |
db4b15f2 C |
143 | throw buildRequestError(err) |
144 | } | |
0d0e8dd0 C |
145 | } |
146 | ||
8729a870 | 147 | function getAgent () { |
148 | if (!isProxyEnabled()) return {} | |
149 | ||
150 | const proxy = getProxy() | |
151 | ||
ac036180 | 152 | logger.info('Using proxy %s.', proxy, lTags()) |
8729a870 | 153 | |
154 | const proxyAgentOptions = { | |
155 | keepAlive: true, | |
156 | keepAliveMsecs: 1000, | |
157 | maxSockets: 256, | |
158 | maxFreeSockets: 256, | |
159 | scheduling: 'lifo' as 'lifo', | |
160 | proxy | |
161 | } | |
162 | ||
163 | return { | |
164 | agent: { | |
165 | http: new HttpProxyAgent(proxyAgentOptions), | |
166 | https: new HttpsProxyAgent(proxyAgentOptions) | |
167 | } | |
168 | } | |
169 | } | |
170 | ||
e0ce715a | 171 | function getUserAgent () { |
66170ca8 | 172 | return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})` |
e0ce715a C |
173 | } |
174 | ||
62549e6c C |
175 | function isBinaryResponse (result: Response<any>) { |
176 | return BINARY_CONTENT_TYPES.has(result.headers['content-type']) | |
177 | } | |
178 | ||
dedcd583 C |
179 | async function findLatestRedirection (url: string, options: PeerTubeRequestOptions, iteration = 1) { |
180 | if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url) | |
181 | ||
182 | const { headers } = await peertubeGot(url, { followRedirect: false, ...buildGotOptions(options) }) | |
183 | ||
184 | if (headers.location) return findLatestRedirection(headers.location, options, iteration + 1) | |
185 | ||
186 | return url | |
187 | } | |
188 | ||
9f10b292 | 189 | // --------------------------------------------------------------------------- |
dac0a531 | 190 | |
65fcc311 | 191 | export { |
e4f97bab | 192 | doRequest, |
db4b15f2 | 193 | doJSONRequest, |
58d515e3 | 194 | doRequestAndSaveToFile, |
62549e6c | 195 | isBinaryResponse, |
ca3d5912 | 196 | getAgent, |
dedcd583 | 197 | findLatestRedirection, |
b3fc41a1 | 198 | peertubeGot |
65fcc311 | 199 | } |
bfe2ef6b C |
200 | |
201 | // --------------------------------------------------------------------------- | |
202 | ||
db4b15f2 C |
203 | function buildGotOptions (options: PeerTubeRequestOptions) { |
204 | const { activityPub, bodyKBLimit = 1000 } = options | |
bfe2ef6b | 205 | |
db4b15f2 | 206 | const context = { bodyKBLimit, httpSignature: options.httpSignature } |
bfe2ef6b | 207 | |
db4b15f2 C |
208 | let headers = options.headers || {} |
209 | ||
e7053b1d C |
210 | if (!headers.date) { |
211 | headers = { ...headers, date: new Date().toUTCString() } | |
212 | } | |
db4b15f2 | 213 | |
e7053b1d | 214 | if (activityPub && !headers.accept) { |
db4b15f2 | 215 | headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER } |
bfe2ef6b | 216 | } |
db4b15f2 C |
217 | |
218 | return { | |
219 | method: options.method, | |
bbb3be68 | 220 | dnsCache: true, |
4c99953a | 221 | timeout: options.timeout ?? REQUEST_TIMEOUTS.DEFAULT, |
db4b15f2 C |
222 | json: options.json, |
223 | searchParams: options.searchParams, | |
ac036180 | 224 | retry: 2, |
db4b15f2 C |
225 | headers, |
226 | context | |
227 | } | |
228 | } | |
229 | ||
b5c36108 C |
230 | function buildRequestError (error: RequestError) { |
231 | const newError: PeerTubeRequestError = new Error(error.message) | |
db4b15f2 C |
232 | newError.name = error.name |
233 | newError.stack = error.stack | |
234 | ||
b5c36108 C |
235 | if (error.response) { |
236 | newError.responseBody = error.response.body | |
3455c265 | 237 | newError.responseHeaders = error.response.headers |
b5c36108 | 238 | newError.statusCode = error.response.statusCode |
db4b15f2 C |
239 | } |
240 | ||
b5c36108 | 241 | return newError |
bfe2ef6b | 242 | } |