48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
import { RedisClient } from '../redis/RedisClient'
|
|
import ip from 'internal-ip'
|
|
|
|
const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGUSR2']
|
|
|
|
const NODES_SET = 'poker:infosvr'
|
|
const discovery_channel = 'poker:infosvr:discovery'
|
|
const isProd = process.env.NODE_ENV === 'production'
|
|
|
|
export function registerGracefulShutdown(callback: (err?: Error) => void) {
|
|
/**
|
|
* Gracefully shutdown on uncaught errors
|
|
*/
|
|
process.on('uncaughtException', (err) => {
|
|
console.error(err)
|
|
callback(err)
|
|
})
|
|
|
|
signals.forEach((signal) => {
|
|
process.once(signal, () => callback())
|
|
})
|
|
}
|
|
|
|
async function getNodeAddress(port: number) {
|
|
const host = process.env.SELF_HOSTNAME || await ip.v4()
|
|
return `${ host }:${ port }`
|
|
}
|
|
|
|
export async function registService(port: number) {
|
|
if (!isProd) {
|
|
return
|
|
}
|
|
const address = await getNodeAddress(port)
|
|
const client = new RedisClient()
|
|
await client.sadd(NODES_SET, address)
|
|
await client.publish(discovery_channel, `add,${address}`)
|
|
}
|
|
|
|
export async function unRegistService(port: number) {
|
|
if (!isProd) {
|
|
return
|
|
}
|
|
const address = await getNodeAddress(port)
|
|
const client = new RedisClient()
|
|
await client.srem(NODES_SET, address)
|
|
await client.publish(discovery_channel, `remove,${address}`)
|
|
}
|