Skip to content

Commit

Permalink
chore: 升级eslint
Browse files Browse the repository at this point in the history
  • Loading branch information
bangbang93 committed Mar 5, 2024
1 parent fe22751 commit a69a2f4
Show file tree
Hide file tree
Showing 8 changed files with 599 additions and 339 deletions.
845 changes: 547 additions & 298 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"zod-validation-error": "^3.0.0"
},
"devDependencies": {
"@bangbang93/eslint-config-recommended": "^0.0.3",
"@bangbang93/eslint-config-recommended": "^1.3.0",
"@tsconfig/node18": "^18.2.2",
"@types/bluebird": "^3.5.27",
"@types/dotenv": "^6.1.1",
Expand All @@ -64,8 +64,8 @@
"@types/progress": "^2.0.5",
"@types/range-parser": "^1.2.7",
"@types/tail": "^2.2.1",
"@typescript-eslint/eslint-plugin": "^5.47.0",
"@typescript-eslint/parser": "^5.47.0",
"@typescript-eslint/eslint-plugin": "^7.1.1",
"@typescript-eslint/parser": "^7.1.1",
"esbuild": "^0.17.18",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
Expand Down
9 changes: 5 additions & 4 deletions src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {config} from './config.js'
import {logger} from './logger.js'
import {TokenManager} from './token.js'

// eslint-disable-next-line @typescript-eslint/naming-convention
const __dirname = fileURLToPath(new URL('.', import.meta.url))

export async function bootstrap(version: string): Promise<void> {
Expand Down Expand Up @@ -55,7 +56,7 @@ export async function bootstrap(version: string): Promise<void> {
process.send('ready')
}

checkFileInterval = setTimeout(checkFile, ms('10m'))
checkFileInterval = setTimeout(() => checkFile, ms('10m'))
} catch (e) {
logger.fatal(e)
if (process.env.NODE_ENV === 'development') {
Expand Down Expand Up @@ -83,7 +84,7 @@ export async function bootstrap(version: string): Promise<void> {
let stopping = false
const onStop = async (signal: NodeJS.Signals): Promise<void> => {
console.log(`got ${signal}, unregistering cluster`)
if (stopping) process.exit(0)
if (stopping) process.kill(process.pid, signal)

stopping = true
clearTimeout(checkFileInterval)
Expand All @@ -97,6 +98,6 @@ export async function bootstrap(version: string): Promise<void> {
server.close()
cluster.nginxProcess?.kill()
}
process.on('SIGTERM', onStop)
process.on('SIGINT', onStop)
process.once('SIGTERM', () => onStop)
process.once('SIGINT', () => onStop)
}
52 changes: 30 additions & 22 deletions src/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import got, {type Got, HTTPError} from 'got'
import {createServer, Server} from 'http'
import {createSecureServer} from 'http2'
import http2Express from 'http2-express-bridge'
import {clone, sum, template} from 'lodash-es'
import {clone, sum, template, toString} from 'lodash-es'
import morgan from 'morgan'
import ms from 'ms'
import {userInfo} from 'node:os'
Expand All @@ -37,6 +37,7 @@ interface ICounters {
bytes: number
}

// eslint-disable-next-line @typescript-eslint/naming-convention
const __dirname = dirname(fileURLToPath(import.meta.url))

export class Cluster {
Expand Down Expand Up @@ -85,12 +86,17 @@ export class Cluster {
const url = options.url
if (!url) return
if (typeof url === 'string') {
if (url.includes('bmclapi.bangbang93.com') || url.includes('bmclapi2.bangbang93.com')) {
if (
url.includes('bmclapi.bangbang93.com') ||
url.includes('bmclapi2.bangbang93.com') ||
url.includes('localhost')
) {
options.headers.authorization = `Bearer ${await this.tokenManager.getToken()}`
}
} else if (
url.hostname.includes('bmclapi.bangbang93.com') ||
url.hostname.includes('bmclapi2.bangbang93.com')
url.hostname.includes('bmclapi2.bangbang93.com') ||
url.hostname.includes('localhost')
) {
options.headers.authorization = `Bearer ${await this.tokenManager.getToken()}`
}
Expand All @@ -110,7 +116,7 @@ export class Cluster {
}

public async getFileList(): Promise<IFileList> {
const FileListSchema = avsc.Type.forSchema({
const fileListSchema = avsc.Type.forSchema({
type: 'array',
items: {
type: 'record',
Expand All @@ -127,7 +133,7 @@ export class Cluster {
})
const decompressed = await decompress(res.body)
return {
files: FileListSchema.fromBuffer(Buffer.from(decompressed)),
files: fileListSchema.fromBuffer(Buffer.from(decompressed)) as IFileList['files'],
}
}

Expand Down Expand Up @@ -194,10 +200,7 @@ export class Cluster {
hasError = true
if (e instanceof HTTPError) {
logger.error({err: e}, `下载文件${file.path}失败: ${e.response.statusCode}, url: ${e.response.url}`)
logger.trace(
{err: e, options: e.options, redirectUrls: e.response.redirectUrls},
e.response.body?.toString(),
)
logger.trace({err: e, options: e.options, redirectUrls: e.response.redirectUrls}, toString(e.response.body))
} else {
logger.error({err: e}, `下载文件${file.path}失败`)
}
Expand All @@ -218,7 +221,7 @@ export class Cluster {
const app = http2Express(express)
app.enable('trust proxy')

app.get('/auth', async (req: Request, res: Response, next: NextFunction) => {
app.get('/auth', (req: Request, res: Response, next: NextFunction) => {
try {
const oldUrl = req.get('x-original-uri')
if (!oldUrl) return res.status(403).send('invalid sign')
Expand All @@ -239,6 +242,7 @@ export class Cluster {
if (!config.disableAccessLog) {
app.use(morgan('combined'))
}
// eslint-disable-next-line @typescript-eslint/no-misused-promises
app.get('/download/:hash(\\w+)', async (req: Request, res: Response, next: NextFunction) => {
try {
const hash = req.params.hash.toLowerCase()
Expand Down Expand Up @@ -333,8 +337,8 @@ export class Cluster {
this.counters.bytes += parseInt(match.groups?.size ?? '0', 10) || 0
})

this.interval = setInterval(async () => {
await fse.ftruncate(logFd.fd)
this.interval = setInterval(() => {
void fse.ftruncate(logFd.fd)
}, ms('60s'))
}

Expand All @@ -359,7 +363,7 @@ export class Cluster {
this.socket.on('message', (msg) => {
logger.info(msg)
})
this.socket.on('connect', async () => {
this.socket.on('connect', () => {
logger.debug('connected')
})
this.socket.on('disconnect', (reason) => {
Expand Down Expand Up @@ -394,7 +398,7 @@ export class Cluster {
public async disable(): Promise<void> {
clearTimeout(this.keepAliveInterval)
this.wantEnable = false
return new Promise((resolve, reject) => {
return await new Promise((resolve, reject) => {
this.socket?.emit('disable', null, ([err, ack]: [unknown, unknown]) => {
this.isEnabled = false
if (err || ack !== true) return reject(err || ack)
Expand All @@ -421,7 +425,7 @@ export class Cluster {
if (!this.isEnabled) {
throw new Error('节点未启用')
}
return new Promise((resolve, reject) => {
return await new Promise((resolve, reject) => {
const counters = clone(this.counters)
this.socket?.emit(
'keep-alive',
Expand Down Expand Up @@ -452,15 +456,15 @@ export class Cluster {
await fse.outputFile(join(this.tmpDir, 'key.pem'), cert.key)
}

public exit(code: number = 0): never {
public exit(code: number = 0): void {
if (this.nginxProcess) {
this.nginxProcess.kill()
}
process.exit(code)
process.kill(process.pid, code)
}

private async _enable(): Promise<void> {
return new Bluebird<void>((resolve, reject) => {
return await new Bluebird<void>((resolve, reject) => {
this.socket?.emit(
'enable',
{
Expand All @@ -475,15 +479,17 @@ export class Cluster {
if (ack !== true) return reject(ack)
resolve()
logger.info(colors.rainbow('start doing my job'))
this.keepAliveInterval = setTimeout(this._keepAlive.bind(this), ms('1m'))
this.keepAliveInterval = setTimeout(() => {
void this._keepAlive()
}, ms('1m'))
},
)
}).timeout(ms('5m'), '节点注册超时')
}

private async _keepAlive(): Promise<void> {
try {
const status = await Bluebird.try(async () => this.keepAlive()).timeout(ms('10s'), 'keep alive timeout')
const status = await Bluebird.try(async () => await this.keepAlive()).timeout(ms('10s'), 'keep alive timeout')
if (!status) {
logger.fatal('kicked by server')
this.exit(1)
Expand All @@ -509,11 +515,13 @@ export class Cluster {
})
}
} finally {
this.keepAliveInterval = setTimeout(this._keepAlive.bind(this), ms('1m'))
this.keepAliveInterval = setTimeout(() => {
void this._keepAlive()
}, ms('1m'))
}
}

private async onConnectionError(event: string, err: Error): Promise<void> {
private onConnectionError(event: string, err: Error): void {
console.error(`${event}: cannot connect to server`, err)
if (this.server) {
this.server.close(() => {
Expand Down
16 changes: 9 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@ import {readFileSync} from 'fs'
import {fileURLToPath} from 'url'
import {bootstrap} from './bootstrap.js'

const packageJson = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'))
const packageJson = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8')) as {
version: string
}

config()
if (process.env.NO_DAEMON || !cluster.isPrimary) {
bootstrap(packageJson.version)
.catch((err) => {
// eslint-disable-next-line no-console
console.error(err)
process.exit(1)
})
bootstrap(packageJson.version).catch((err) => {
// eslint-disable-next-line no-console
console.error(err)
// eslint-disable-next-line n/no-process-exit
process.exit(1)
})
}

if (!process.env.NO_DAEMON && cluster.isPrimary) {
Expand Down
4 changes: 2 additions & 2 deletions src/measure.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {checkSign} from './util.js'
export default function MeasureRouteFactory(config: Config): Router {
const router = express.Router()

const MeasureRoute = router
const measureRoute = router

router.get('/:size(\\d+)', (req, res) => {
const isSignValid = checkSign(req.baseUrl + req.path, config.clusterSecret, req.query as NodeJS.Dict<string>)
Expand All @@ -20,5 +20,5 @@ export default function MeasureRouteFactory(config: Config): Router {
res.end()
})

return MeasureRoute
return measureRoute
}
3 changes: 1 addition & 2 deletions src/storage/base.storage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type {NextFunction, Request, Response} from 'express'
import {join} from 'path'
import {cwd} from 'process'
import type {Config} from '../config.js'
import {logger} from '../logger.js'
import type {IFileInfo} from '../types.js'
Expand All @@ -27,7 +26,7 @@ export function getStorage(config: Config): IStorage {
let storage: IStorage
switch (config.storage) {
case 'file':
storage = new FileStorage(join(cwd(), 'cache'))
storage = new FileStorage(join(process.cwd(), 'cache'))
break
case 'webdav':
storage = new WebdavStorage(config.storageOpts)
Expand Down
3 changes: 2 additions & 1 deletion src/storage/webdav.storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export class WebdavStorage implements IStorage {
}

public async exists(path: string): Promise<boolean> {
return this.client.exists(join(this.basePath, path))
return await this.client.exists(join(this.basePath, path))
}

public getAbsolutePath(path: string): string {
Expand Down Expand Up @@ -120,6 +120,7 @@ export class WebdavStorage implements IStorage {
} while (queue.length !== 0)
}

// eslint-disable-next-line @typescript-eslint/require-await
public async express(hashPath: string, req: Request, res: Response): Promise<{bytes: number; hits: number}> {
const path = join(this.basePath, hashPath)
const file = this.client.getFileDownloadLink(path)
Expand Down

0 comments on commit a69a2f4

Please sign in to comment.