File size: 1,957 Bytes
94e1b2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
 * Express Application Entry Point
 * Express 应用主入口
 */

import 'dotenv/config'
import express from 'express'
import type { Server } from 'http'
import { redisClient } from './config/redis'
import { closeQueue } from './config/bull'
import { createLogger } from './utils/logger'
import { startMediaCleanupScheduler } from './services/media-cleanup'
import { appConfig, initializeExpressApp } from './server/bootstrap'
import { setupShutdownHandlers, tryListen } from './server/lifecycle'

// 导入队列处理器以启动 worker
import './queues/processors/video.processor'

const app = express()
const appLogger = createLogger('Server')

let server: Server | null = null
let stopMediaCleanupScheduler: (() => void) | null = null

async function cleanupResources(): Promise<void> {
  try {
    if (stopMediaCleanupScheduler) {
      stopMediaCleanupScheduler()
      stopMediaCleanupScheduler = null
    }

    await closeQueue()
    await redisClient.quit()
    appLogger.info('Graceful shutdown completed')
  } catch (error) {
    appLogger.error('Error during shutdown', { error })
    throw error
  }
}

async function startServer(): Promise<void> {
  try {
    await initializeExpressApp(app, appLogger)

    if (!stopMediaCleanupScheduler) {
      stopMediaCleanupScheduler = startMediaCleanupScheduler()
    }

    server = await tryListen(app, appConfig.port, appConfig.host, appLogger)

    setupShutdownHandlers({
      getServer: () => server,
      onCleanup: cleanupResources,
      logger: appLogger
    })

    appLogger.info('Express application initialized successfully')
  } catch (error) {
    // Keep a raw stderr fallback to avoid silent startup failures
    // when production summary-only logging filters non-summary entries.
    console.error('[StartupFatal]', error)
    appLogger.error('Failed to start server', { error })
    process.exit(1)
  }
}

void startServer()

// 导出 app 用于测试
export default app