This commit is contained in:
ditiqi 2025-03-02 16:45:36 +08:00
parent 8c0a478ae0
commit d0a5571b50
1 changed files with 456 additions and 389 deletions

View File

@ -1,452 +1,519 @@
import http from 'node:http'
import { EventEmitter } from 'node:events'
import debug from 'debug'
import { GetHandler } from './handlers/GetHandler'
import { HeadHandler } from './handlers/HeadHandler'
import { OptionsHandler } from './handlers/OptionsHandler'
import { PatchHandler } from './handlers/PatchHandler'
import { PostHandler } from './handlers/PostHandler'
import { DeleteHandler } from './handlers/DeleteHandler'
import { validateHeader } from './validators/HeaderValidator'
import type stream from 'node:stream'
import type { ServerOptions, RouteHandler, WithOptional } from './types'
import { MemoryLocker } from './lockers'
import { EVENTS, Upload, DataStore, REQUEST_METHODS, ERRORS, TUS_RESUMABLE, EXPOSED_HEADERS, CancellationContext } from './utils'
import { message } from 'antd';
import http from "node:http";
import { EventEmitter } from "node:events";
import debug from "debug";
import { GetHandler } from "./handlers/GetHandler";
import { HeadHandler } from "./handlers/HeadHandler";
import { OptionsHandler } from "./handlers/OptionsHandler";
import { PatchHandler } from "./handlers/PatchHandler";
import { PostHandler } from "./handlers/PostHandler";
import { DeleteHandler } from "./handlers/DeleteHandler";
import { validateHeader } from "./validators/HeaderValidator";
import type stream from "node:stream";
import type { ServerOptions, RouteHandler, WithOptional } from "./types";
import { MemoryLocker } from "./lockers";
import {
EVENTS,
Upload,
DataStore,
REQUEST_METHODS,
ERRORS,
TUS_RESUMABLE,
EXPOSED_HEADERS,
CancellationContext,
} from "./utils";
/**
*
* TUS服务器支持的各种HTTP方法对应的处理器实例类型
*/
type Handlers = {
GET: InstanceType<typeof GetHandler> // GET请求处理器
HEAD: InstanceType<typeof HeadHandler> // HEAD请求处理器
OPTIONS: InstanceType<typeof OptionsHandler> // OPTIONS请求处理器
PATCH: InstanceType<typeof PatchHandler> // PATCH请求处理器
POST: InstanceType<typeof PostHandler> // POST请求处理器
DELETE: InstanceType<typeof DeleteHandler> // DELETE请求处理器
}
GET: InstanceType<typeof GetHandler>; // GET请求处理器
HEAD: InstanceType<typeof HeadHandler>; // HEAD请求处理器
OPTIONS: InstanceType<typeof OptionsHandler>; // OPTIONS请求处理器
PATCH: InstanceType<typeof PatchHandler>; // PATCH请求处理器
POST: InstanceType<typeof PostHandler>; // POST请求处理器
DELETE: InstanceType<typeof DeleteHandler>; // DELETE请求处理器
};
/**
* TUS服务器事件接口定义
*
*/
interface TusEvents {
/**
*
* @param req HTTP请求对象
* @param res HTTP响应对象
* @param upload
* @param url URL
*/
[EVENTS.POST_CREATE]: (
req: http.IncomingMessage,
res: http.ServerResponse,
upload: Upload,
url: string
) => void
/**
*
* @param req HTTP请求对象
* @param res HTTP响应对象
* @param upload
* @param url URL
*/
[EVENTS.POST_CREATE]: (
req: http.IncomingMessage,
res: http.ServerResponse,
upload: Upload,
url: string
) => void;
/**
* @deprecated ()
* 使 POST_RECEIVE_V2
*/
[EVENTS.POST_RECEIVE]: (
req: http.IncomingMessage,
res: http.ServerResponse,
upload: Upload
) => void
/**
* @deprecated ()
* 使 POST_RECEIVE_V2
*/
[EVENTS.POST_RECEIVE]: (
req: http.IncomingMessage,
res: http.ServerResponse,
upload: Upload
) => void;
/**
* V2版本
* @param req HTTP请求对象
* @param upload
*/
[EVENTS.POST_RECEIVE_V2]: (req: http.IncomingMessage, upload: Upload) => void
/**
* V2版本
* @param req HTTP请求对象
* @param upload
*/
[EVENTS.POST_RECEIVE_V2]: (
req: http.IncomingMessage,
upload: Upload
) => void;
/**
*
* @param req HTTP请求对象
* @param res HTTP响应对象
* @param upload
*/
[EVENTS.POST_FINISH]: (
req: http.IncomingMessage,
res: http.ServerResponse,
upload: Upload
) => void
/**
*
* @param req HTTP请求对象
* @param res HTTP响应对象
* @param upload
*/
[EVENTS.POST_FINISH]: (
req: http.IncomingMessage,
res: http.ServerResponse,
upload: Upload
) => void;
/**
*
* @param req HTTP请求对象
* @param res HTTP响应对象
* @param id
*/
[EVENTS.POST_TERMINATE]: (
req: http.IncomingMessage,
res: http.ServerResponse,
id: string
) => void
/**
*
* @param req HTTP请求对象
* @param res HTTP响应对象
* @param id
*/
[EVENTS.POST_TERMINATE]: (
req: http.IncomingMessage,
res: http.ServerResponse,
id: string
) => void;
}
/**
* EventEmitter事件处理器类型别名
*/
type on = EventEmitter['on']
type emit = EventEmitter['emit']
type on = EventEmitter["on"];
type emit = EventEmitter["emit"];
/**
* TUS服务器接口声明
* EventEmitter,
*/
export declare interface Server {
/**
*
* @param event TusEvents的键之一
* @param listener
* @returns Server实例以支持链式调用
*/
on<Event extends keyof TusEvents>(event: Event, listener: TusEvents[Event]): this
/**
*
* @param eventName
* @param listener
* @returns Server实例以支持链式调用
*/
on(eventName: Parameters<on>[0], listener: Parameters<on>[1]): this
/**
*
* @param event TusEvents的键之一
* @param listener
* @returns emit函数的返回值
*/
emit<Event extends keyof TusEvents>(
event: Event,
listener: TusEvents[Event]
): ReturnType<emit>
/**
*
* @param eventName
* @param listener
* @returns emit函数的返回值
*/
emit(eventName: Parameters<emit>[0], listener: Parameters<emit>[1]): ReturnType<emit>
/**
*
* @param event TusEvents的键之一
* @param listener
* @returns Server实例以支持链式调用
*/
on<Event extends keyof TusEvents>(
event: Event,
listener: TusEvents[Event]
): this;
/**
*
* @param eventName
* @param listener
* @returns Server实例以支持链式调用
*/
on(eventName: Parameters<on>[0], listener: Parameters<on>[1]): this;
/**
*
* @param event TusEvents的键之一
* @param listener
* @returns emit函数的返回值
*/
emit<Event extends keyof TusEvents>(
event: Event,
listener: TusEvents[Event]
): ReturnType<emit>;
/**
*
* @param eventName
* @param listener
* @returns emit函数的返回值
*/
emit(
eventName: Parameters<emit>[0],
listener: Parameters<emit>[1]
): ReturnType<emit>;
}
/**
*
*/
const log = debug('tus-node-server')
const log = debug("tus-node-server");
// biome-ignore lint/suspicious/noUnsafeDeclarationMerging: it's fine
export class Server extends EventEmitter {
datastore: DataStore
handlers: Handlers
options: ServerOptions
datastore: DataStore;
handlers: Handlers;
options: ServerOptions;
/**
* Server
* @param options -
* @throws optionspath datastore
*/
constructor(options: WithOptional<ServerOptions, 'locker'> & { datastore: DataStore }) {
super()
/**
* Server
* @param options -
* @throws optionspath datastore
*/
constructor(
options: WithOptional<ServerOptions, "locker"> & {
datastore: DataStore;
}
) {
super();
if (!options) {
throw new Error("'options' must be defined")
}
if (!options) {
throw new Error("'options' must be defined");
}
if (!options.path) {
throw new Error("'path' is not defined; must have a path")
}
if (!options.path) {
throw new Error("'path' is not defined; must have a path");
}
if (!options.datastore) {
throw new Error("'datastore' is not defined; must have a datastore")
}
if (!options.datastore) {
throw new Error(
"'datastore' is not defined; must have a datastore"
);
}
if (!options.locker) {
options.locker = new MemoryLocker()
}
if (!options.locker) {
options.locker = new MemoryLocker();
}
if (!options.lockDrainTimeout) {
options.lockDrainTimeout = 3000
}
if (!options.lockDrainTimeout) {
options.lockDrainTimeout = 3000;
}
if (!options.postReceiveInterval) {
options.postReceiveInterval = 1000
}
if (!options.postReceiveInterval) {
options.postReceiveInterval = 1000;
}
const { datastore, ...rest } = options
this.options = rest as ServerOptions
this.datastore = datastore
this.handlers = {
// GET 请求处理器应在具体实现中编写
GET: new GetHandler(this.datastore, this.options),
// 这些方法按照 tus 协议处理
HEAD: new HeadHandler(this.datastore, this.options),
OPTIONS: new OptionsHandler(this.datastore, this.options),
PATCH: new PatchHandler(this.datastore, this.options),
POST: new PostHandler(this.datastore, this.options),
DELETE: new DeleteHandler(this.datastore, this.options),
}
// 任何以方法为键分配给此对象的处理器将用于响应这些请求。
// 当数据存储分配给服务器时,它们会被设置/重置。
// 从服务器中移除任何事件监听器时,必须先从每个处理器中移除监听器。
// 这必须在添加 'newListener' 监听器之前完成,以避免为所有请求处理器添加 'removeListener' 事件监听器。
this.on('removeListener', (event: string, listener) => {
this.datastore.removeListener(event, listener)
for (const method of REQUEST_METHODS) {
this.handlers[method].removeListener(event, listener)
}
})
// 当事件监听器被添加到服务器时,确保它们从请求处理器冒泡到服务器级别。
this.on('newListener', (event: string, listener) => {
this.datastore.on(event, listener)
for (const method of REQUEST_METHODS) {
this.handlers[method].on(event, listener)
}
})
}
const { datastore, ...rest } = options;
this.options = rest as ServerOptions;
this.datastore = datastore;
this.handlers = {
// GET 请求处理器应在具体实现中编写
GET: new GetHandler(this.datastore, this.options),
// 这些方法按照 tus 协议处理
HEAD: new HeadHandler(this.datastore, this.options),
OPTIONS: new OptionsHandler(this.datastore, this.options),
PATCH: new PatchHandler(this.datastore, this.options),
POST: new PostHandler(this.datastore, this.options),
DELETE: new DeleteHandler(this.datastore, this.options),
};
// 任何以方法为键分配给此对象的处理器将用于响应这些请求。
// 当数据存储分配给服务器时,它们会被设置/重置。
// 从服务器中移除任何事件监听器时,必须先从每个处理器中移除监听器。
// 这必须在添加 'newListener' 监听器之前完成,以避免为所有请求处理器添加 'removeListener' 事件监听器。
this.on("removeListener", (event: string, listener) => {
this.datastore.removeListener(event, listener);
for (const method of REQUEST_METHODS) {
this.handlers[method].removeListener(event, listener);
}
});
// 当事件监听器被添加到服务器时,确保它们从请求处理器冒泡到服务器级别。
this.on("newListener", (event: string, listener) => {
this.datastore.on(event, listener);
for (const method of REQUEST_METHODS) {
this.handlers[method].on(event, listener);
}
});
}
/**
* GET
* @param path -
* @param handler -
*/
get(path: string, handler: RouteHandler) {
this.handlers.GET.registerPath(path, handler)
}
/**
* GET
* @param path -
* @param handler -
*/
get(path: string, handler: RouteHandler) {
this.handlers.GET.registerPath(path, handler);
}
/**
* 'request'
* @param req - HTTP
* @param res - HTTP
* @returns HTTP
*/
async handle(
req: http.IncomingMessage,
res: http.ServerResponse
// biome-ignore lint/suspicious/noConfusingVoidType: it's fine
): Promise<http.ServerResponse | stream.Writable | void> {
/**
* 'request'
* @param req - HTTP
* @param res - HTTP
* @returns HTTP
*/
async handle(
req: http.IncomingMessage,
res: http.ServerResponse
// biome-ignore lint/suspicious/noConfusingVoidType: it's fine
): Promise<http.ServerResponse | stream.Writable | void> {
const context = this.createContext(req);
log(`[TusServer] handle: ${req.method} ${req.url}`);
// 允许覆盖 HTTP 方法。这样做的原因是某些库/环境不支持 PATCH 和 DELETE 请求,例如浏览器中的 Flash 和 Java 部分环境
if (req.headers["x-http-method-override"]) {
req.method = (
req.headers["x-http-method-override"] as string
).toUpperCase();
}
const onError = async (error: {
status_code?: number;
body?: string;
message: string;
}) => {
let status_code =
error.status_code || ERRORS.UNKNOWN_ERROR.status_code;
let body =
error.body ||
`${ERRORS.UNKNOWN_ERROR.body}${error.message || ""}\n`;
if (this.options.onResponseError) {
const errorMapping = await this.options.onResponseError(
req,
res,
error as Error
);
if (errorMapping) {
status_code = errorMapping.status_code;
body = errorMapping.body;
}
}
return this.write(context, req, res, status_code, body);
};
if (req.method === "GET") {
const handler = this.handlers.GET;
return handler.send(req, res).catch(onError);
}
const context = this.createContext(req)
log(`[TusServer] handle: ${req.method} ${req.url}`)
// 允许覆盖 HTTP 方法。这样做的原因是某些库/环境不支持 PATCH 和 DELETE 请求,例如浏览器中的 Flash 和 Java 部分环境
if (req.headers['x-http-method-override']) {
req.method = (req.headers['x-http-method-override'] as string).toUpperCase()
}
const onError = async (error: {
status_code?: number
body?: string
message: string
}) => {
// Tus-Resumable 头部必须包含在每个请求和响应中,除了 OPTIONS 请求。其值必须是客户端或服务器使用的协议版本。
res.setHeader("Tus-Resumable", TUS_RESUMABLE);
if (
req.method !== "OPTIONS" &&
req.headers["tus-resumable"] === undefined
) {
return this.write(
context,
req,
res,
412,
"Tus-Resumable Required\n"
);
}
// 验证所有必需的头部以符合 tus 协议
const invalid_headers = [];
for (const header_name in req.headers) {
if (req.method === "OPTIONS") {
continue;
}
// 内容类型仅对 PATCH 请求进行检查。对于所有其他请求方法,它将被忽略并视为未设置内容类型,
// 因为某些 HTTP 客户端可能会为此头部强制执行默认值。
// 参见 https://github.com/tus/tus-node-server/pull/116
if (
header_name.toLowerCase() === "content-type" &&
req.method !== "PATCH"
) {
continue;
}
if (
!validateHeader(
header_name,
req.headers[header_name] as string | undefined
)
) {
log(
`Invalid ${header_name} header: ${req.headers[header_name]}`
);
invalid_headers.push(header_name);
}
}
let status_code = error.status_code || ERRORS.UNKNOWN_ERROR.status_code
let body = error.body || `${ERRORS.UNKNOWN_ERROR.body}${error.message || ''}\n`
if (this.options.onResponseError) {
const errorMapping = await this.options.onResponseError(req, res, error as Error)
if (errorMapping) {
status_code = errorMapping.status_code
body = errorMapping.body
}
}
return this.write(context, req, res, status_code, body)
}
if (req.method === 'GET') {
const handler = this.handlers.GET
return handler.send(req, res).catch(onError)
}
if (invalid_headers.length > 0) {
return this.write(
context,
req,
res,
400,
`Invalid ${invalid_headers.join(" ")}\n`
);
}
// 启用 CORS
res.setHeader("Access-Control-Allow-Origin", this.getCorsOrigin(req));
res.setHeader("Access-Control-Expose-Headers", EXPOSED_HEADERS);
if (this.options.allowedCredentials === true) {
res.setHeader("Access-Control-Allow-Credentials", "true");
}
// Tus-Resumable 头部必须包含在每个请求和响应中,除了 OPTIONS 请求。其值必须是客户端或服务器使用的协议版本。
res.setHeader('Tus-Resumable', TUS_RESUMABLE)
if (req.method !== 'OPTIONS' && req.headers['tus-resumable'] === undefined) {
return this.write(context, req, res, 412, 'Tus-Resumable Required\n')
}
// 验证所有必需的头部以符合 tus 协议
const invalid_headers = []
for (const header_name in req.headers) {
if (req.method === 'OPTIONS') {
continue
}
// 内容类型仅对 PATCH 请求进行检查。对于所有其他请求方法,它将被忽略并视为未设置内容类型,
// 因为某些 HTTP 客户端可能会为此头部强制执行默认值。
// 参见 https://github.com/tus/tus-node-server/pull/116
if (header_name.toLowerCase() === 'content-type' && req.method !== 'PATCH') {
continue
}
if (!validateHeader(header_name, req.headers[header_name] as string | undefined)) {
log(`Invalid ${header_name} header: ${req.headers[header_name]}`)
invalid_headers.push(header_name)
}
}
// 调用请求方法的处理器
const handler = this.handlers[req.method as keyof Handlers];
if (handler) {
return handler.send(req, res, context).catch(onError);
}
if (invalid_headers.length > 0) {
return this.write(context, req, res, 400, `Invalid ${invalid_headers.join(' ')}\n`)
}
// 启用 CORS
res.setHeader('Access-Control-Allow-Origin', this.getCorsOrigin(req))
res.setHeader('Access-Control-Expose-Headers', EXPOSED_HEADERS)
if (this.options.allowedCredentials === true) {
res.setHeader('Access-Control-Allow-Credentials', 'true')
}
return this.write(context, req, res, 404, "Not found\n");
}
// 调用请求方法的处理器
const handler = this.handlers[req.method as keyof Handlers]
if (handler) {
/**
* CORS
*
* CORS源地址`origin`
* `origin`
* `*`
*
* @param req HTTP请求对象
* @returns CORS源地址`origin``*`
*
*
* - CORS策略的灵活性
* - `*`CORS配置
*/
private getCorsOrigin(req: http.IncomingMessage): string {
const origin = req.headers.origin;
// 检查请求头中的`origin`是否在允许的源列表中
const isOriginAllowed =
this.options.allowedOrigins?.some(
(allowedOrigin) => allowedOrigin === origin
) ?? true;
// 如果`origin`存在且在允许的源列表中,则返回该`origin`
if (origin && isOriginAllowed) {
return origin;
}
// 如果允许的源列表不为空,则返回列表中的第一个源地址
if (
this.options.allowedOrigins &&
this.options.allowedOrigins.length > 0
) {
return this.options.allowedOrigins[0];
}
return handler.send(req, res, context).catch(onError)
}
// 如果允许的源列表为空,则返回通配符`*`,表示允许所有源地址
return "*";
}
return this.write(context, req, res, 404, 'Not found\n')
}
/**
*
* @param context -
* @param req - HTTP
* @param res - HTTP
* @param status - HTTP
* @param body -
* @param headers -
* @returns HTTP
*/
write(
context: CancellationContext,
req: http.IncomingMessage,
res: http.ServerResponse,
status: number,
body = "",
headers = {}
) {
const isAborted = context.signal.aborted;
/**
* CORS
*
* CORS源地址`origin`
* `origin`
* `*`
*
* @param req HTTP请求对象
* @returns CORS源地址`origin``*`
*
*
* - CORS策略的灵活性
* - `*`CORS配置
*/
private getCorsOrigin(req: http.IncomingMessage): string {
const origin = req.headers.origin
// 检查请求头中的`origin`是否在允许的源列表中
const isOriginAllowed =
this.options.allowedOrigins?.some((allowedOrigin) => allowedOrigin === origin) ??
true
// 如果`origin`存在且在允许的源列表中,则返回该`origin`
if (origin && isOriginAllowed) {
return origin
}
// 如果允许的源列表不为空,则返回列表中的第一个源地址
if (this.options.allowedOrigins && this.options.allowedOrigins.length > 0) {
return this.options.allowedOrigins[0]
}
if (status !== 204) {
// @ts-expect-error not explicitly typed but possible
headers["Content-Length"] = Buffer.byteLength(body, "utf8");
}
// 如果允许的源列表为空,则返回通配符`*`,表示允许所有源地址
return '*'
}
if (isAborted) {
// 此条件处理请求被标记为中止的情况。
// 在这种情况下,服务器通知客户端连接将被关闭。
// 这是通过在响应中设置 'Connection' 头部为 'close' 来传达的。
// 这一步对于防止服务器继续处理不再需要的请求至关重要,从而节省资源。
/**
*
* @param context -
* @param req - HTTP
* @param res - HTTP
* @param status - HTTP
* @param body -
* @param headers -
* @returns HTTP
*/
write(
context: CancellationContext,
req: http.IncomingMessage,
res: http.ServerResponse,
status: number,
body = '',
headers = {}
) {
const isAborted = context.signal.aborted
// @ts-expect-error not explicitly typed but possible
headers.Connection = "close";
if (status !== 204) {
// @ts-expect-error not explicitly typed but possible
headers['Content-Length'] = Buffer.byteLength(body, 'utf8')
}
// 为响应 ('res') 添加 'finish' 事件的事件监听器。
// 'finish' 事件在响应已发送给客户端时触发。
// 一旦响应完成,请求 ('req') 对象将被销毁。
// 销毁请求对象是释放与此请求相关的任何资源的关键步骤,因为它已经被中止。
res.on("finish", () => {
req.destroy();
});
}
if (isAborted) {
// 此条件处理请求被标记为中止的情况。
// 在这种情况下,服务器通知客户端连接将被关闭。
// 这是通过在响应中设置 'Connection' 头部为 'close' 来传达的。
// 这一步对于防止服务器继续处理不再需要的请求至关重要,从而节省资源。
res.writeHead(status, headers);
res.write(body);
return res.end();
}
// @ts-expect-error not explicitly typed but possible
headers.Connection = 'close'
/**
*
* @param args -
* @returns HTTP
*/
// biome-ignore lint/suspicious/noExplicitAny: todo
listen(...args: any[]): http.Server {
return http.createServer(this.handle.bind(this)).listen(...args);
}
// 为响应 ('res') 添加 'finish' 事件的事件监听器。
// 'finish' 事件在响应已发送给客户端时触发。
// 一旦响应完成,请求 ('req') 对象将被销毁。
// 销毁请求对象是释放与此请求相关的任何资源的关键步骤,因为它已经被中止。
res.on('finish', () => {
req.destroy()
})
}
/**
*
* @returns
* @throws
*/
cleanUpExpiredUploads(): Promise<number> {
if (!this.datastore.hasExtension("expiration")) {
throw ERRORS.UNSUPPORTED_EXPIRATION_EXTENSION;
}
res.writeHead(status, headers)
res.write(body)
return res.end()
}
return this.datastore.deleteExpired();
}
/**
*
* @param args -
* @returns HTTP
*/
// biome-ignore lint/suspicious/noExplicitAny: todo
listen(...args: any[]): http.Server {
return http.createServer(this.handle.bind(this)).listen(...args)
}
/**
*
* @param req - HTTP
* @returns
*/
protected createContext(req: http.IncomingMessage) {
// 初始化两个 AbortController
// 1. `requestAbortController` 用于即时请求终止,特别适用于在发生错误时停止客户端上传。
// 2. `abortWithDelayController` 用于在终止前引入延迟,允许服务器有时间完成正在进行的操作。
// 这在未来的请求可能需要获取当前请求持有的锁时特别有用。
const requestAbortController = new AbortController();
const abortWithDelayController = new AbortController();
/**
*
* @returns
* @throws
*/
cleanUpExpiredUploads(): Promise<number> {
if (!this.datastore.hasExtension('expiration')) {
throw ERRORS.UNSUPPORTED_EXPIRATION_EXTENSION
}
// 当 `abortWithDelayController` 被触发时调用此函数,以在指定延迟后中止请求。
const onDelayedAbort = (err: unknown) => {
abortWithDelayController.signal.removeEventListener(
"abort",
onDelayedAbort
);
setTimeout(() => {
requestAbortController.abort(err);
}, this.options.lockDrainTimeout);
};
abortWithDelayController.signal.addEventListener(
"abort",
onDelayedAbort
);
return this.datastore.deleteExpired()
}
// 当请求关闭时,移除监听器以避免内存泄漏。
req.on("close", () => {
abortWithDelayController.signal.removeEventListener(
"abort",
onDelayedAbort
);
});
/**
*
* @param req - HTTP
* @returns
*/
protected createContext(req: http.IncomingMessage) {
// 初始化两个 AbortController
// 1. `requestAbortController` 用于即时请求终止,特别适用于在发生错误时停止客户端上传。
// 2. `abortWithDelayController` 用于在终止前引入延迟,允许服务器有时间完成正在进行的操作。
// 这在未来的请求可能需要获取当前请求持有的锁时特别有用。
const requestAbortController = new AbortController()
const abortWithDelayController = new AbortController()
// 当 `abortWithDelayController` 被触发时调用此函数,以在指定延迟后中止请求。
const onDelayedAbort = (err: unknown) => {
abortWithDelayController.signal.removeEventListener('abort', onDelayedAbort)
setTimeout(() => {
requestAbortController.abort(err)
}, this.options.lockDrainTimeout)
}
abortWithDelayController.signal.addEventListener('abort', onDelayedAbort)
// 当请求关闭时,移除监听器以避免内存泄漏。
req.on('close', () => {
abortWithDelayController.signal.removeEventListener('abort', onDelayedAbort)
})
// 返回一个对象,包含信号和两个中止请求的方法。
// `signal` 用于监听请求中止事件。
// `abort` 方法用于立即中止请求。
// `cancel` 方法用于启动延迟中止序列。
return {
signal: requestAbortController.signal,
abort: () => {
// 立即中止请求
if (!requestAbortController.signal.aborted) {
requestAbortController.abort(ERRORS.ABORTED)
}
},
cancel: () => {
// 启动延迟中止序列,除非它已经在进行中。
if (!abortWithDelayController.signal.aborted) {
abortWithDelayController.abort(ERRORS.ABORTED)
}
},
}
}
// 返回一个对象,包含信号和两个中止请求的方法。
// `signal` 用于监听请求中止事件。
// `abort` 方法用于立即中止请求。
// `cancel` 方法用于启动延迟中止序列。
return {
signal: requestAbortController.signal,
abort: () => {
// 立即中止请求
if (!requestAbortController.signal.aborted) {
requestAbortController.abort(ERRORS.ABORTED);
}
},
cancel: () => {
// 启动延迟中止序列,除非它已经在进行中。
if (!abortWithDelayController.signal.aborted) {
abortWithDelayController.abort(ERRORS.ABORTED);
}
},
};
}
}