X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fhelpers%2Frequests.ts;h=6e80995ad3c0061bd851913095e8ec2e5c178162;hb=ac03618098e430acb21c075bdba57ce6d377b12d;hp=2c9da213c112068a666c431ad50d7e586210f5bc;hpb=db4b15f21fbf4e33434e930ffc7fb768cdcf9d42;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/helpers/requests.ts b/server/helpers/requests.ts index 2c9da213c..6e80995ad 100644 --- a/server/helpers/requests.ts +++ b/server/helpers/requests.ts @@ -1,13 +1,22 @@ import { createWriteStream, remove } from 'fs-extra' -import got, { CancelableRequest, Options as GotOptions } from 'got' +import got, { CancelableRequest, Options as GotOptions, RequestError, Response } from 'got' +import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent' import { join } from 'path' import { CONFIG } from '../initializers/config' -import { ACTIVITY_PUB, PEERTUBE_VERSION, WEBSERVER } from '../initializers/constants' +import { ACTIVITY_PUB, BINARY_CONTENT_TYPES, PEERTUBE_VERSION, REQUEST_TIMEOUT, WEBSERVER } from '../initializers/constants' import { pipelinePromise } from './core-utils' import { processImage } from './image-utils' -import { logger } from './logger' +import { logger, loggerTagsFactory } from './logger' +import { getProxy, isProxyEnabled } from './proxy' -const httpSignature = require('http-signature') +const lTags = loggerTagsFactory('request') + +const httpSignature = require('@peertube/http-signature') + +export interface PeerTubeRequestError extends Error { + statusCode?: number + responseBody?: any +} type PeerTubeRequestOptions = { activityPub?: boolean @@ -23,6 +32,8 @@ type PeerTubeRequestOptions = { } & Pick const peertubeGot = got.extend({ + ...getAgent(), + headers: { 'user-agent': getUserAgent() }, @@ -30,13 +41,25 @@ const peertubeGot = got.extend({ handlers: [ (options, next) => { const promiseOrStream = next(options) as CancelableRequest - const bodyKBLimit = options.context?.bodyKBLimit + const bodyKBLimit = options.context?.bodyKBLimit as number if (!bodyKBLimit) throw new Error('No KB limit for this request') + const bodyLimit = bodyKBLimit * 1000 + /* eslint-disable @typescript-eslint/no-floating-promises */ promiseOrStream.on('downloadProgress', progress => { - if (progress.transferred * 1000 > bodyKBLimit && progress.percent !== 1) { - promiseOrStream.cancel(`Exceeded the download limit of ${bodyKBLimit} bytes`) + if (progress.transferred > bodyLimit && progress.percent !== 1) { + const message = `Exceeded the download limit of ${bodyLimit} B` + logger.warn(message, lTags()) + + // CancelableRequest + if (promiseOrStream.cancel) { + promiseOrStream.cancel() + return + } + + // Stream + (promiseOrStream as any).destroy() } }) @@ -84,6 +107,7 @@ function doRequest (url: string, options: PeerTubeRequestOptions = {}) { const gotOptions = buildGotOptions(options) return peertubeGot(url, gotOptions) + .on('retry', logRetryFactory(url)) .catch(err => { throw buildRequestError(err) }) } @@ -91,6 +115,7 @@ function doJSONRequest (url: string, options: PeerTubeRequestOptions = {}) { const gotOptions = buildGotOptions(options) return peertubeGot(url, { ...gotOptions, responseType: 'json' }) + .on('retry', logRetryFactory(url)) .catch(err => { throw buildRequestError(err) }) } @@ -110,7 +135,7 @@ async function doRequestAndSaveToFile ( ) } catch (err) { remove(destPath) - .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err })) + .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err, ...lTags() })) throw buildRequestError(err) } @@ -131,17 +156,58 @@ async function downloadImage (url: string, destDir: string, destName: string, si } } +function getAgent () { + if (!isProxyEnabled()) return {} + + const proxy = getProxy() + + logger.info('Using proxy %s.', proxy, lTags()) + + const proxyAgentOptions = { + keepAlive: true, + keepAliveMsecs: 1000, + maxSockets: 256, + maxFreeSockets: 256, + scheduling: 'lifo' as 'lifo', + proxy + } + + return { + agent: { + http: new HttpProxyAgent(proxyAgentOptions), + https: new HttpsProxyAgent(proxyAgentOptions) + } + } +} + function getUserAgent () { return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})` } +function isBinaryResponse (result: Response) { + return BINARY_CONTENT_TYPES.has(result.headers['content-type']) +} + +async function findLatestRedirection (url: string, options: PeerTubeRequestOptions, iteration = 1) { + if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url) + + const { headers } = await peertubeGot(url, { followRedirect: false, ...buildGotOptions(options) }) + + if (headers.location) return findLatestRedirection(headers.location, options, iteration + 1) + + return url +} + // --------------------------------------------------------------------------- export { doRequest, doJSONRequest, doRequestAndSaveToFile, - downloadImage + isBinaryResponse, + downloadImage, + findLatestRedirection, + peertubeGot } // --------------------------------------------------------------------------- @@ -153,29 +219,41 @@ function buildGotOptions (options: PeerTubeRequestOptions) { let headers = options.headers || {} - headers = { ...headers, date: new Date().toUTCString() } + if (!headers.date) { + headers = { ...headers, date: new Date().toUTCString() } + } - if (activityPub) { + if (activityPub && !headers.accept) { headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER } } return { method: options.method, + dnsCache: true, + timeout: REQUEST_TIMEOUT, json: options.json, searchParams: options.searchParams, + retry: 2, headers, context } } -function buildRequestError (error: any) { - const newError = new Error(error.message) +function buildRequestError (error: RequestError) { + const newError: PeerTubeRequestError = new Error(error.message) newError.name = error.name newError.stack = error.stack - if (error.response?.body) { - error.responseBody = error.response.body + if (error.response) { + newError.responseBody = error.response.body + newError.statusCode = error.response.statusCode } return newError } + +function logRetryFactory (url: string) { + return (retryCount: number, error: RequestError) => { + logger.debug('Retrying request to %s.', url, { retryCount, error, ...lTags() }) + } +}