]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/requests.ts
Use worker thread to send HTTP requests
[github/Chocobozzz/PeerTube.git] / server / helpers / requests.ts
CommitLineData
bfe2ef6b 1import { createWriteStream, remove } from 'fs-extra'
3455c265 2import got, { CancelableRequest, NormalizedOptions, Options as GotOptions, RequestError, Response } from 'got'
8729a870 3import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent'
4c99953a 4import { ACTIVITY_PUB, BINARY_CONTENT_TYPES, PEERTUBE_VERSION, REQUEST_TIMEOUTS, WEBSERVER } from '../initializers/constants'
db4b15f2 5import { pipelinePromise } from './core-utils'
ac036180 6import { logger, loggerTagsFactory } from './logger'
8729a870 7import { getProxy, isProxyEnabled } from './proxy'
8
ac036180
C
9const lTags = loggerTagsFactory('request')
10
5842a854 11const httpSignature = require('@peertube/http-signature')
da854ddd 12
b5c36108
C
13export interface PeerTubeRequestError extends Error {
14 statusCode?: number
15 responseBody?: any
3455c265 16 responseHeaders?: any
b5c36108
C
17}
18
db4b15f2 19type 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
33const 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({
319f9670
C
88 getHeader: function (header: string) {
89 const value = options.headers[header.toLowerCase()]
90
91 if (!value) logger.warn('Unknown header requested by http-signature.', { headers: options.headers, header })
92 return value
db4b15f2
C
93 },
94
319f9670 95 setHeader: function (header: string, value: string) {
db4b15f2
C
96 options.headers[header] = value
97 },
98
99 method,
100 path
101 }, httpSignatureOptions)
102 }
103 }
3455c265
C
104 ],
105
106 beforeRetry: [
107 (_options: NormalizedOptions, error: RequestError, retryCount: number) => {
108 logger.debug('Retrying request to %s.', error.request.requestUrl, { retryCount, error: buildRequestError(error), ...lTags() })
109 }
db4b15f2 110 ]
da854ddd 111 }
db4b15f2 112})
e4f97bab 113
db4b15f2
C
114function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
115 const gotOptions = buildGotOptions(options)
116
117 return peertubeGot(url, gotOptions)
118 .catch(err => { throw buildRequestError(err) })
119}
120
121function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
122 const gotOptions = buildGotOptions(options)
123
124 return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
125 .catch(err => { throw buildRequestError(err) })
e4f97bab 126}
dac0a531 127
db4b15f2
C
128async function doRequestAndSaveToFile (
129 url: string,
bfe2ef6b 130 destPath: string,
db4b15f2 131 options: PeerTubeRequestOptions = {}
bfe2ef6b 132) {
4c99953a 133 const gotOptions = buildGotOptions({ ...options, timeout: options.timeout ?? REQUEST_TIMEOUTS.FILE })
02988fdc 134
db4b15f2 135 const outFile = createWriteStream(destPath)
bfe2ef6b 136
db4b15f2
C
137 try {
138 await pipelinePromise(
139 peertubeGot.stream(url, gotOptions),
140 outFile
141 )
142 } catch (err) {
143 remove(destPath)
ac036180 144 .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err, ...lTags() }))
bfe2ef6b 145
db4b15f2
C
146 throw buildRequestError(err)
147 }
0d0e8dd0
C
148}
149
8729a870 150function getAgent () {
151 if (!isProxyEnabled()) return {}
152
153 const proxy = getProxy()
154
ac036180 155 logger.info('Using proxy %s.', proxy, lTags())
8729a870 156
157 const proxyAgentOptions = {
158 keepAlive: true,
159 keepAliveMsecs: 1000,
160 maxSockets: 256,
161 maxFreeSockets: 256,
162 scheduling: 'lifo' as 'lifo',
163 proxy
164 }
165
166 return {
167 agent: {
168 http: new HttpProxyAgent(proxyAgentOptions),
169 https: new HttpsProxyAgent(proxyAgentOptions)
170 }
171 }
172}
173
e0ce715a 174function getUserAgent () {
66170ca8 175 return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
e0ce715a
C
176}
177
62549e6c
C
178function isBinaryResponse (result: Response<any>) {
179 return BINARY_CONTENT_TYPES.has(result.headers['content-type'])
180}
181
dedcd583
C
182async function findLatestRedirection (url: string, options: PeerTubeRequestOptions, iteration = 1) {
183 if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url)
184
185 const { headers } = await peertubeGot(url, { followRedirect: false, ...buildGotOptions(options) })
186
187 if (headers.location) return findLatestRedirection(headers.location, options, iteration + 1)
188
189 return url
190}
191
9f10b292 192// ---------------------------------------------------------------------------
dac0a531 193
65fcc311 194export {
405c83f9
C
195 PeerTubeRequestOptions,
196
e4f97bab 197 doRequest,
db4b15f2 198 doJSONRequest,
58d515e3 199 doRequestAndSaveToFile,
62549e6c 200 isBinaryResponse,
ca3d5912 201 getAgent,
dedcd583 202 findLatestRedirection,
b3fc41a1 203 peertubeGot
65fcc311 204}
bfe2ef6b
C
205
206// ---------------------------------------------------------------------------
207
db4b15f2
C
208function buildGotOptions (options: PeerTubeRequestOptions) {
209 const { activityPub, bodyKBLimit = 1000 } = options
bfe2ef6b 210
db4b15f2 211 const context = { bodyKBLimit, httpSignature: options.httpSignature }
bfe2ef6b 212
db4b15f2
C
213 let headers = options.headers || {}
214
e7053b1d
C
215 if (!headers.date) {
216 headers = { ...headers, date: new Date().toUTCString() }
217 }
db4b15f2 218
e7053b1d 219 if (activityPub && !headers.accept) {
db4b15f2 220 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
bfe2ef6b 221 }
db4b15f2
C
222
223 return {
224 method: options.method,
bbb3be68 225 dnsCache: true,
4c99953a 226 timeout: options.timeout ?? REQUEST_TIMEOUTS.DEFAULT,
db4b15f2
C
227 json: options.json,
228 searchParams: options.searchParams,
ac036180 229 retry: 2,
db4b15f2
C
230 headers,
231 context
232 }
233}
234
b5c36108
C
235function buildRequestError (error: RequestError) {
236 const newError: PeerTubeRequestError = new Error(error.message)
db4b15f2
C
237 newError.name = error.name
238 newError.stack = error.stack
239
b5c36108
C
240 if (error.response) {
241 newError.responseBody = error.response.body
3455c265 242 newError.responseHeaders = error.response.headers
b5c36108 243 newError.statusCode = error.response.statusCode
db4b15f2
C
244 }
245
b5c36108 246 return newError
bfe2ef6b 247}