Skip to content

Commit

Permalink
feat: 整个配置类,不要遍地env了
Browse files Browse the repository at this point in the history
  • Loading branch information
bangbang93 committed Feb 4, 2024
1 parent 44988eb commit 0dc9b60
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 17 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ cd openbmclapi
npm ci
npx tsx src
```
3. 如果你看到了`missing CLUSTER_PORT`的报错,说明一切正常,该设置参数了
3. 如果你看到了`CLUSTER_ID is not set`的报错,说明一切正常,该设置参数了


### 设置参数
Expand Down
14 changes: 6 additions & 8 deletions src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,15 @@ import ms from 'ms'
import {join} from 'path'
import {fileURLToPath} from 'url'
import {Cluster} from './cluster.js'
import {config} from './config.js'

const __dirname = fileURLToPath(new URL('.', import.meta.url))

export async function bootstrap(version: string): Promise<void> {
console.log(colors.green(`booting openbmclapi ${version}`))
if (!process.env.CLUSTER_PORT) {
throw new Error('missing CLUSTER_PORT')
}
const cluster = new Cluster(
process.env.CLUSTER_ID!,
process.env.CLUSTER_SECRET!,
config.clusterId,
config.clusterSecret,
version,
)

Expand All @@ -31,19 +29,19 @@ export async function bootstrap(version: string): Promise<void> {
}

cluster.connect()
const proto = process.env.CLUSTER_BYOC !== 'true' ? 'https' : 'http'
const proto = config.byoc ? 'https' : 'http'
if (proto === 'https') {
console.log('请求证书')
await cluster.requestCert()
}
if (process.env.ENABLE_NGINX) {
if (config.enableNginx) {
if (typeof cluster.port === 'number') {
await cluster.setupNginx(join(__dirname, '..'), cluster.port, proto)
} else {
throw new Error('cluster.port is not a number')
}
}
const server = cluster.setupExpress(proto === 'https' && !process.env.ENABLE_NGINX)
const server = cluster.setupExpress(proto === 'https' && !config.enableNginx)
try {
await cluster.listen()
await cluster.enable()
Expand Down
17 changes: 9 additions & 8 deletions src/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import ProgressBar from 'progress'
import {connect, Socket} from 'socket.io-client'
import {Tail} from 'tail'
import {fileURLToPath} from 'url'
import {config} from './config.js'
import {validateFile} from './file.js'
import MeasureRoute from './measure.route.js'
import {checkSign, hashToFilename} from './util.js'
Expand Down Expand Up @@ -65,9 +66,9 @@ export class Cluster {
private readonly version: string,
) {
if (!clusterId || !clusterSecret) throw new Error('missing config')
this.host = process.env.CLUSTER_IP
this._port = parseInt(process.env.CLUSTER_PORT ?? '4000', 10)
this.publicPort = process.env.CLUSTER_PUBLIC_PORT ? parseInt(process.env.CLUSTER_PUBLIC_PORT, 10) : this._port
this.host = config.clusterIp
this._port = config.port
this.publicPort = config.clusterPublicPort ?? config.port
this.ua = `openbmclapi-cluster/${version}`
this.got = got.extend({
prefixUrl: this.prefixUrl,
Expand Down Expand Up @@ -176,7 +177,7 @@ export class Cluster {
}
})

if (!process.env.DISABLE_ACCESS_LOG) {
if (!config.disableAccessLog) {
app.use(morgan('combined'))
}
app.get('/download/:hash(\\w+)', async (req: Request, res: Response, next: NextFunction) => {
Expand Down Expand Up @@ -262,7 +263,7 @@ export class Cluster {
})

const tail = new Tail(logFile)
if (!process.env.DISABLE_ACCESS_LOG) {
if (!config.disableAccessLog) {
tail.on('line', (line: string) => {
process.stdout.write(line)
process.stdout.write('\n')
Expand Down Expand Up @@ -294,7 +295,7 @@ export class Cluster {
})
}

public async connect(): Promise<void> {
public connect(): void {
if (this.socket) return
this.socket = connect(this.prefixUrl, {
transports: ['websocket'],
Expand Down Expand Up @@ -407,7 +408,7 @@ export class Cluster {
host: this.host,
port: this.publicPort,
version: this.version,
byoc: process.env.CLUSTER_BYOC === 'true',
byoc: config.byoc,
}, ([err, ack]: [unknown, unknown]) => {
if (err) return reject(err)
if (ack !== true) return reject(ack)
Expand Down Expand Up @@ -438,7 +439,7 @@ export class Cluster {
} else {
await Bluebird.try(async () => {
await this.disable()
await this.connect()
this.connect()
await this.enable()
})
.timeout(ms('10m'), 'restart timeout')
Expand Down
50 changes: 50 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import dotenv from 'dotenv'

export class Config {
public static instance: Config

public readonly clusterId: string
public readonly clusterSecret: string
public readonly clusterIp?: string
public readonly port: number = 4000
public readonly clusterPublicPort?: number
public readonly byoc: boolean = false
public readonly disableAccessLog: boolean = false

public readonly enableNginx: boolean = false

private constructor() {
if (!process.env.CLUSTER_ID) {
throw new Error('CLUSTER_ID is not set')
}
this.clusterId = process.env.CLUSTER_ID
if (!process.env.CLUSTER_SECRET) {
throw new Error('CLUSTER_SECRET is not set')
}
this.clusterSecret = process.env.CLUSTER_SECRET
this.clusterIp = process.env.CLUSTER_IP
if (process.env.CLUSTER_PORT) {
this.port = parseInt(process.env.CLUSTER_PORT, 10)
if (isNaN(this.port)) {
throw new Error('CLUSTER_PORT is not a number')
}
}
this.clusterPublicPort = process.env.CLUSTER_PUBLIC_PORT ? parseInt(process.env.CLUSTER_PUBLIC_PORT, 10) : undefined
if (typeof this.clusterPublicPort === 'number' && isNaN(this.clusterPublicPort)) {
throw new Error('CLUSTER_PUBLIC_PORT is not a number')
}
this.byoc = process.env.BYOC === 'true'
this.enableNginx = process.env.ENABLE_NGINX === 'true'
}

public static getInstance(): Config {
if (!Config.instance) {
Config.instance = new Config()
}
return Config.instance
}
}

dotenv.config()

export const config = Config.getInstance()

0 comments on commit 0dc9b60

Please sign in to comment.