paricafe/packages/backend/src/core/HttpRequestService.ts

205 lines
4.9 KiB
TypeScript
Raw Normal View History

/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
2022-09-17 13:27:08 -05:00
import * as http from 'node:http';
import * as https from 'node:https';
2023-07-15 06:07:31 -05:00
import * as net from 'node:net';
2022-09-17 13:27:08 -05:00
import CacheableLookup from 'cacheable-lookup';
import fetch from 'node-fetch';
2022-09-17 13:27:08 -05:00
import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent';
import { Inject, Injectable } from '@nestjs/common';
import { DI } from '@/di-symbols.js';
2022-09-20 15:33:11 -05:00
import type { Config } from '@/config.js';
2022-09-17 13:27:08 -05:00
import { StatusError } from '@/misc/status-error.js';
import { bindThis } from '@/decorators.js';
import { validateContentTypeSetAsActivityPub } from '@/core/activitypub/misc/validator.js';
import type { IObject } from '@/core/activitypub/type.js';
import type { Response } from 'node-fetch';
import type { URL } from 'node:url';
2022-09-17 13:27:08 -05:00
export type HttpRequestSendOptions = {
throwErrorWhenResponseNotOk: boolean;
validators?: ((res: Response) => void)[];
};
@Injectable()
export class HttpRequestService {
2022-09-17 13:27:08 -05:00
/**
* Get http non-proxy agent
2022-09-17 13:27:08 -05:00
*/
private http: http.Agent;
2022-09-17 13:27:08 -05:00
/**
* Get https non-proxy agent
2022-09-17 13:27:08 -05:00
*/
private https: https.Agent;
2022-09-17 13:27:08 -05:00
/**
* Get http proxy or non-proxy agent
2022-09-17 13:27:08 -05:00
*/
public httpAgent: http.Agent;
/**
* Get https proxy or non-proxy agent
*/
2022-09-17 13:27:08 -05:00
public httpsAgent: https.Agent;
constructor(
@Inject(DI.config)
private config: Config,
) {
const cache = new CacheableLookup({
2022-09-17 13:27:08 -05:00
maxTtl: 3600, // 1hours
errorTtl: 30, // 30secs
lookup: false, // nativeのdns.lookupにfallbackしない
});
2022-09-18 13:11:50 -05:00
this.http = new http.Agent({
2022-09-17 13:27:08 -05:00
keepAlive: true,
keepAliveMsecs: 30 * 1000,
2023-07-15 06:07:31 -05:00
lookup: cache.lookup as unknown as net.LookupFunction,
localAddress: config.outgoingAddress,
2023-07-15 06:07:31 -05:00
});
2022-09-18 13:11:50 -05:00
this.https = new https.Agent({
2022-09-17 13:27:08 -05:00
keepAlive: true,
keepAliveMsecs: 30 * 1000,
2023-07-15 06:07:31 -05:00
lookup: cache.lookup as unknown as net.LookupFunction,
localAddress: config.outgoingAddress,
2023-07-15 06:07:31 -05:00
});
perf(federation): Ed25519署名に対応する (#13464) * 1. ed25519キーペアを発行・Personとして公開鍵を送受信 * validate additionalPublicKeys * getAuthUserFromApIdはmainを選ぶ * :v: * fix * signatureAlgorithm * set publicKeyCache lifetime * refresh * httpMessageSignatureAcceptable * ED25519_SIGNED_ALGORITHM * ED25519_PUBLIC_KEY_SIGNATURE_ALGORITHM * remove sign additionalPublicKeys signature requirements * httpMessageSignaturesSupported * httpMessageSignaturesImplementationLevel * httpMessageSignaturesImplementationLevel: '01' * perf(federation): Use hint for getAuthUserFromApId (#13470) * Hint for getAuthUserFromApId * とどのつまりこれでいいのか? * use @misskey-dev/node-http-message-signatures * fix * signedPost, signedGet * ap-request.tsを復活させる * remove digest prerender * fix test? * fix test * add httpMessageSignaturesImplementationLevel to FederationInstance * ManyToOne * fetchPersonWithRenewal * exactKey * :v: * use const * use gen-key-pair fn. from '@misskey-dev/node-http-message-signatures' * update node-http-message-signatures * fix * @misskey-dev/node-http-message-signatures@0.0.0-alpha.11 * getAuthUserFromApIdでupdatePersonの頻度を増やす * cacheRaw.date * use requiredInputs https://github.com/misskey-dev/misskey/pull/13464#discussion_r1509964359 * update @misskey-dev/node-http-message-signatures * clean up * err msg * fix(backend): fetchInstanceMetadataのLockが永遠に解除されない問題を修正 Co-authored-by: まっちゃとーにゅ <17376330+u1-liquid@users.noreply.github.com> * fix httpMessageSignaturesImplementationLevel validation * fix test * fix * comment * comment * improve test * fix * use Promise.all in genRSAAndEd25519KeyPair * refreshAndprepareEd25519KeyPair * refreshAndfindKey * commetn * refactor public keys add * digestプリレンダを復活させる RFC実装時にどうするか考える * fix, async * fix * !== true * use save * Deliver update person when new key generated (not tested) https://github.com/misskey-dev/misskey/pull/13464#issuecomment-1977049061 * 循環参照で落ちるのを解消? * fix? * Revert "fix?" This reverts commit 0082f6f8e8c5d5febd14933ba9a1ac643f70ca92. * a * logger * log * change logger * 秘密鍵の変更は、フラグではなく鍵を引き回すようにする * addAllKnowingSharedInboxRecipe * nanka meccha kaeta * delivre * キャッシュ有効チェックはロック取得前に行う * @misskey-dev/node-http-message-signatures@0.0.3 * PrivateKeyPem * getLocalUserPrivateKey * fix test * if * fix ap-request * update node-http-message-signatures * fix type error * update package * fix type * update package * retry no key * @misskey-dev/node-http-message-signatures@0.0.8 * fix type error * log keyid * logger * db-resolver * JSON.stringify * HTTP Signatureがなかったり使えなかったりしそうな場合にLD Signatureを活用するように * inbox-delayed use actor if no signature * ユーザーとキーの同一性チェックはhostの一致にする * log signature parse err * save array * とりあえずtryで囲っておく * fetchPersonWithRenewalでエラーが起きたら古いデータを返す * use transactionalEntityManager * fix spdx * @misskey-dev/node-http-message-signatures@0.0.10 * add comment * fix * publicKeyに配列が入ってもいいようにする https://github.com/misskey-dev/misskey/pull/13950 * define additionalPublicKeys * fix * merge fix * refreshAndprepareEd25519KeyPair → refreshAndPrepareEd25519KeyPair * remove gen-key-pair.ts * defaultMaxListeners = 512 * Revert "defaultMaxListeners = 512" This reverts commit f2c412c18057a9300540794ccbe4dfbf6d259ed6. * genRSAAndEd25519KeyPairではキーを直列に生成する? * maxConcurrency: 8 * maxConcurrency: 16 * maxConcurrency: 8 * Revert "genRSAAndEd25519KeyPairではキーを直列に生成する?" This reverts commit d0aada55c1ed5aa98f18731ec82f3ac5eb5a6c16. * maxWorkers: '90%' * Revert "maxWorkers: '90%'" This reverts commit 9e0a93f110456320d6485a871f014f7cdab29b33. * e2e/timelines.tsで個々のテストに対するtimeoutを削除, maxConcurrency: 32 * better error handling of this.userPublickeysRepository.delete * better comment * set result to keypairEntityCache * deliverJobConcurrency: 16, deliverJobPerSec: 1024, inboxJobConcurrency: 4 * inboxJobPerSec: 64 * delete request.headers['host']; * fix * // node-fetch will generate this for us. if we keep 'Host', it won't change with redirects! * move delete host * modify comment * modify comment * fix correct → collect * refreshAndfindKey → refreshAndFindKey * modify comment * modify attachLdSignature * getApId, InboxProcessorService * TODO * [skip ci] add CHANGELOG --------- Co-authored-by: MeiMei <30769358+mei23@users.noreply.github.com> Co-authored-by: まっちゃとーにゅ <17376330+u1-liquid@users.noreply.github.com>
2024-07-17 11:28:17 -05:00
const maxSockets = Math.max(256, config.deliverJobConcurrency ?? 16);
2022-09-17 13:27:08 -05:00
this.httpAgent = config.proxy
? new HttpProxyAgent({
keepAlive: true,
keepAliveMsecs: 30 * 1000,
maxSockets,
2022-09-17 13:27:08 -05:00
maxFreeSockets: 256,
scheduling: 'lifo',
proxy: config.proxy,
localAddress: config.outgoingAddress,
2022-09-17 13:27:08 -05:00
})
2022-09-18 13:11:50 -05:00
: this.http;
2022-09-17 13:27:08 -05:00
this.httpsAgent = config.proxy
? new HttpsProxyAgent({
keepAlive: true,
keepAliveMsecs: 30 * 1000,
maxSockets,
2022-09-17 13:27:08 -05:00
maxFreeSockets: 256,
scheduling: 'lifo',
proxy: config.proxy,
localAddress: config.outgoingAddress,
2022-09-17 13:27:08 -05:00
})
2022-09-18 13:11:50 -05:00
: this.https;
2022-09-17 13:27:08 -05:00
}
/**
* Get agent by URL
2022-09-17 13:27:08 -05:00
* @param url URL
* @param bypassProxy Allways bypass proxy
*/
@bindThis
public getAgentByUrl(url: URL, bypassProxy = false): http.Agent | https.Agent {
if (bypassProxy || (this.config.proxyBypassHosts ?? []).includes(url.hostname)) {
2022-09-18 13:11:50 -05:00
return url.protocol === 'http:' ? this.http : this.https;
2022-09-17 13:27:08 -05:00
} else {
return url.protocol === 'http:' ? this.httpAgent : this.httpsAgent;
}
}
@bindThis
public async getActivityJson(url: string): Promise<IObject> {
const res = await this.send(url, {
method: 'GET',
headers: {
Accept: 'application/activity+json, application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
},
timeout: 5000,
size: 1024 * 256,
}, {
throwErrorWhenResponseNotOk: true,
validators: [validateContentTypeSetAsActivityPub],
});
return await res.json() as IObject;
}
@bindThis
2023-02-01 05:13:22 -06:00
public async getJson<T = unknown>(url: string, accept = 'application/json, */*', headers?: Record<string, string>): Promise<T> {
const res = await this.send(url, {
method: 'GET',
headers: Object.assign({
Accept: accept,
}, headers ?? {}),
timeout: 5000,
size: 1024 * 256,
});
2023-02-01 05:13:22 -06:00
return await res.json() as T;
}
@bindThis
public async getHtml(url: string, accept = 'text/html, */*', headers?: Record<string, string>): Promise<string> {
const res = await this.send(url, {
method: 'GET',
headers: Object.assign({
Accept: accept,
}, headers ?? {}),
timeout: 5000,
});
return await res.text();
}
2022-09-17 13:27:08 -05:00
@bindThis
public async send(
url: string,
args: {
method?: string,
body?: string,
headers?: Record<string, string>,
timeout?: number,
size?: number,
} = {},
extra: HttpRequestSendOptions = {
throwErrorWhenResponseNotOk: true,
validators: [],
},
): Promise<Response> {
const timeout = args.timeout ?? 5000;
const controller = new AbortController();
setTimeout(() => {
controller.abort();
}, timeout);
const res = await fetch(url, {
method: args.method ?? 'GET',
headers: {
'User-Agent': this.config.userAgent,
2023-07-15 06:07:31 -05:00
...(args.headers ?? {}),
},
body: args.body,
size: args.size ?? 10 * 1024 * 1024,
agent: (url) => this.getAgentByUrl(url),
signal: controller.signal,
});
2022-09-17 13:27:08 -05:00
if (!res.ok && extra.throwErrorWhenResponseNotOk) {
throw new StatusError(`${res.status} ${res.statusText}`, res.status, res.statusText);
}
2022-09-17 13:27:08 -05:00
if (res.ok) {
for (const validator of (extra.validators ?? [])) {
validator(res);
}
}
return res;
2022-09-17 13:27:08 -05:00
}
}