@hangox/mg-cli 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,211 @@
1
+ /**
2
+ * 连接管理器
3
+ * 管理 Provider 和 Consumer 的 WebSocket 连接
4
+ */
5
+
6
+ import type { WebSocket } from 'ws'
7
+ import { ConnectionType, HEARTBEAT_TIMEOUT } from '../shared/constants.js'
8
+ import type { ConnectionInfo } from '../shared/types.js'
9
+ import { generateId } from '../shared/utils.js'
10
+ import { Logger } from './logger.js'
11
+
12
+ /** 带连接信息的 WebSocket */
13
+ export interface ManagedWebSocket extends WebSocket {
14
+ /** 连接 ID */
15
+ connectionId: string
16
+ /** 连接信息 */
17
+ connectionInfo: ConnectionInfo
18
+ /** 是否存活 */
19
+ isAlive: boolean
20
+ }
21
+
22
+ /**
23
+ * 连接管理器
24
+ */
25
+ export class ConnectionManager {
26
+ private logger: Logger
27
+
28
+ /** Provider 连接(按页面 URL 索引) */
29
+ private providers = new Map<string, ManagedWebSocket>()
30
+
31
+ /** Consumer 连接 */
32
+ private consumers = new Map<string, ManagedWebSocket>()
33
+
34
+ /** 所有连接(按 ID 索引) */
35
+ private allConnections = new Map<string, ManagedWebSocket>()
36
+
37
+ /** 心跳检查定时器 */
38
+ private heartbeatTimer: NodeJS.Timeout | null = null
39
+
40
+ constructor(logger: Logger) {
41
+ this.logger = logger
42
+ }
43
+
44
+ /**
45
+ * 启动心跳检查
46
+ */
47
+ startHeartbeatCheck(interval: number = 30000): void {
48
+ if (this.heartbeatTimer) {
49
+ clearInterval(this.heartbeatTimer)
50
+ }
51
+
52
+ this.heartbeatTimer = setInterval(() => {
53
+ this.checkHeartbeats()
54
+ }, interval)
55
+ }
56
+
57
+ /**
58
+ * 停止心跳检查
59
+ */
60
+ stopHeartbeatCheck(): void {
61
+ if (this.heartbeatTimer) {
62
+ clearInterval(this.heartbeatTimer)
63
+ this.heartbeatTimer = null
64
+ }
65
+ }
66
+
67
+ /**
68
+ * 检查所有连接的心跳
69
+ */
70
+ private checkHeartbeats(): void {
71
+ const now = Date.now()
72
+
73
+ for (const [id, ws] of this.allConnections) {
74
+ const lastActive = ws.connectionInfo.lastActiveAt.getTime()
75
+ const elapsed = now - lastActive
76
+
77
+ if (elapsed > HEARTBEAT_TIMEOUT) {
78
+ this.logger.warn(`连接 ${id} 心跳超时,关闭连接`)
79
+ this.removeConnection(ws)
80
+ ws.terminate()
81
+ }
82
+ }
83
+ }
84
+
85
+ /**
86
+ * 添加连接
87
+ */
88
+ addConnection(
89
+ ws: WebSocket,
90
+ type: ConnectionType,
91
+ pageUrl?: string,
92
+ pageId?: string
93
+ ): ManagedWebSocket {
94
+ const connectionId = generateId()
95
+ const now = new Date()
96
+
97
+ const connectionInfo: ConnectionInfo = {
98
+ id: connectionId,
99
+ type,
100
+ pageUrl,
101
+ pageId,
102
+ connectedAt: now,
103
+ lastActiveAt: now,
104
+ }
105
+
106
+ const managedWs = ws as ManagedWebSocket
107
+ managedWs.connectionId = connectionId
108
+ managedWs.connectionInfo = connectionInfo
109
+ managedWs.isAlive = true
110
+
111
+ this.allConnections.set(connectionId, managedWs)
112
+
113
+ if (type === ConnectionType.PROVIDER && pageUrl) {
114
+ // 如果已有同页面的连接,先移除旧的
115
+ const existing = this.providers.get(pageUrl)
116
+ if (existing) {
117
+ this.logger.info(`页面 ${pageUrl} 已有连接,替换为新连接`)
118
+ this.removeConnection(existing)
119
+ existing.close()
120
+ }
121
+ this.providers.set(pageUrl, managedWs)
122
+ this.logger.info(`Provider 连接: ${pageUrl}`)
123
+ } else if (type === ConnectionType.CONSUMER) {
124
+ this.consumers.set(connectionId, managedWs)
125
+ this.logger.info(`Consumer 连接: ${connectionId}`)
126
+ }
127
+
128
+ return managedWs
129
+ }
130
+
131
+ /**
132
+ * 移除连接
133
+ */
134
+ removeConnection(ws: ManagedWebSocket): void {
135
+ const { connectionId, connectionInfo } = ws
136
+
137
+ this.allConnections.delete(connectionId)
138
+
139
+ if (connectionInfo.type === ConnectionType.PROVIDER && connectionInfo.pageUrl) {
140
+ this.providers.delete(connectionInfo.pageUrl)
141
+ this.logger.info(`Provider 断开: ${connectionInfo.pageUrl}`)
142
+ } else if (connectionInfo.type === ConnectionType.CONSUMER) {
143
+ this.consumers.delete(connectionId)
144
+ this.logger.info(`Consumer 断开: ${connectionId}`)
145
+ }
146
+ }
147
+
148
+ /**
149
+ * 更新连接活跃时间
150
+ */
151
+ updateLastActive(ws: ManagedWebSocket): void {
152
+ ws.connectionInfo.lastActiveAt = new Date()
153
+ ws.isAlive = true
154
+ }
155
+
156
+ /**
157
+ * 根据页面 URL 查找 Provider
158
+ */
159
+ findProviderByPageUrl(pageUrl: string): ManagedWebSocket | undefined {
160
+ return this.providers.get(pageUrl)
161
+ }
162
+
163
+ /**
164
+ * 获取第一个可用的 Provider
165
+ */
166
+ getFirstProvider(): ManagedWebSocket | undefined {
167
+ const iterator = this.providers.values()
168
+ const first = iterator.next()
169
+ return first.value
170
+ }
171
+
172
+ /**
173
+ * 获取所有 Provider 信息
174
+ */
175
+ getAllProviders(): ConnectionInfo[] {
176
+ return Array.from(this.providers.values()).map((ws) => ws.connectionInfo)
177
+ }
178
+
179
+ /**
180
+ * 获取连接统计
181
+ */
182
+ getStats(): { providers: number; consumers: number; total: number } {
183
+ return {
184
+ providers: this.providers.size,
185
+ consumers: this.consumers.size,
186
+ total: this.allConnections.size,
187
+ }
188
+ }
189
+
190
+ /**
191
+ * 获取所有已连接的页面 URL
192
+ */
193
+ getConnectedPageUrls(): string[] {
194
+ return Array.from(this.providers.keys())
195
+ }
196
+
197
+ /**
198
+ * 关闭所有连接
199
+ */
200
+ closeAll(): void {
201
+ this.stopHeartbeatCheck()
202
+
203
+ for (const ws of this.allConnections.values()) {
204
+ ws.close()
205
+ }
206
+
207
+ this.providers.clear()
208
+ this.consumers.clear()
209
+ this.allConnections.clear()
210
+ }
211
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 守护进程启动脚本
3
+ * 这个脚本被 daemon.ts 作为子进程启动
4
+ */
5
+
6
+ import { startServerForeground } from './daemon.js'
7
+
8
+ // 解析命令行参数
9
+ const args = process.argv.slice(2)
10
+ let port: number | undefined
11
+
12
+ for (let i = 0; i < args.length; i++) {
13
+ if (args[i] === '--port' && args[i + 1]) {
14
+ port = parseInt(args[i + 1], 10)
15
+ }
16
+ }
17
+
18
+ // 启动 Server
19
+ startServerForeground(port).catch((error) => {
20
+ console.error('守护进程启动失败:', error)
21
+ process.exit(1)
22
+ })
@@ -0,0 +1,211 @@
1
+ /**
2
+ * 守护进程管理
3
+ */
4
+
5
+ import { spawn, ChildProcess } from 'node:child_process'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { dirname, join } from 'node:path'
8
+ import {
9
+ readServerInfo,
10
+ writeServerInfo,
11
+ deleteServerInfo,
12
+ isProcessRunning,
13
+ killProcess,
14
+ ensureConfigDir,
15
+ getCurrentISOTime,
16
+ formatDuration,
17
+ } from '../shared/utils.js'
18
+ import { SERVER_START_TIMEOUT, DEFAULT_PORT } from '../shared/constants.js'
19
+ import { ErrorCode, MGError } from '../shared/errors.js'
20
+ import type { ServerInfo } from '../shared/types.js'
21
+ import { createServer } from './websocket-server.js'
22
+ import { createLogger, LogLevel } from './logger.js'
23
+
24
+ /**
25
+ * 检查 Server 是否在运行
26
+ */
27
+ export function isServerRunning(): { running: boolean; info: ServerInfo | null } {
28
+ const info = readServerInfo()
29
+
30
+ if (!info) {
31
+ return { running: false, info: null }
32
+ }
33
+
34
+ // 检查进程是否存在
35
+ if (!isProcessRunning(info.pid)) {
36
+ // 进程不存在,清理旧文件
37
+ deleteServerInfo()
38
+ return { running: false, info: null }
39
+ }
40
+
41
+ return { running: true, info }
42
+ }
43
+
44
+ /**
45
+ * 启动 Server(前台模式)
46
+ */
47
+ export async function startServerForeground(port?: number): Promise<void> {
48
+ const { running, info } = isServerRunning()
49
+
50
+ if (running && info) {
51
+ throw new MGError(
52
+ ErrorCode.SERVER_ALREADY_RUNNING,
53
+ `Server 已在运行中 (PID: ${info.pid}, 端口: ${info.port})`
54
+ )
55
+ }
56
+
57
+ ensureConfigDir()
58
+
59
+ const logger = createLogger({
60
+ console: true,
61
+ file: true,
62
+ minLevel: LogLevel.INFO,
63
+ })
64
+
65
+ const server = createServer({
66
+ port: port || DEFAULT_PORT,
67
+ logger,
68
+ })
69
+
70
+ // 注册信号处理
71
+ const cleanup = async () => {
72
+ console.log('\n正在停止 Server...')
73
+ await server.stop()
74
+ deleteServerInfo()
75
+ process.exit(0)
76
+ }
77
+
78
+ process.on('SIGINT', cleanup)
79
+ process.on('SIGTERM', cleanup)
80
+
81
+ try {
82
+ const actualPort = await server.start()
83
+
84
+ // 写入 Server 信息
85
+ writeServerInfo({
86
+ port: actualPort,
87
+ pid: process.pid,
88
+ startedAt: getCurrentISOTime(),
89
+ })
90
+
91
+ console.log(`\nMG Server 启动成功`)
92
+ console.log(`监听端口: ${actualPort}`)
93
+ console.log(`进程 PID: ${process.pid}`)
94
+ console.log(`运行模式: 前台`)
95
+ console.log(`\n按 Ctrl+C 停止...`)
96
+ } catch (error) {
97
+ logger.error('Server 启动失败:', error)
98
+ throw error
99
+ }
100
+ }
101
+
102
+ /**
103
+ * 启动 Server(守护进程模式)
104
+ */
105
+ export async function startServerDaemon(port?: number): Promise<ServerInfo> {
106
+ const { running, info } = isServerRunning()
107
+
108
+ if (running && info) {
109
+ throw new MGError(
110
+ ErrorCode.SERVER_ALREADY_RUNNING,
111
+ `Server 已在运行中 (PID: ${info.pid}, 端口: ${info.port})`
112
+ )
113
+ }
114
+
115
+ ensureConfigDir()
116
+
117
+ // 获取当前模块的路径
118
+ const currentFile = fileURLToPath(import.meta.url)
119
+ const currentDir = dirname(currentFile)
120
+ const serverScript = join(currentDir, 'daemon-runner.js')
121
+
122
+ // 启动子进程
123
+ const args = ['--foreground']
124
+ if (port) {
125
+ args.push('--port', String(port))
126
+ }
127
+
128
+ const child: ChildProcess = spawn(process.execPath, [serverScript, ...args], {
129
+ detached: true,
130
+ stdio: 'ignore',
131
+ env: {
132
+ ...process.env,
133
+ MG_DAEMON: '1',
134
+ },
135
+ })
136
+
137
+ child.unref()
138
+
139
+ // 等待 Server 启动
140
+ const startTime = Date.now()
141
+ while (Date.now() - startTime < SERVER_START_TIMEOUT) {
142
+ await new Promise((resolve) => setTimeout(resolve, 200))
143
+
144
+ const { running, info } = isServerRunning()
145
+ if (running && info) {
146
+ return info
147
+ }
148
+ }
149
+
150
+ throw new MGError(ErrorCode.SERVER_START_FAILED, 'Server 启动超时')
151
+ }
152
+
153
+ /**
154
+ * 停止 Server
155
+ */
156
+ export function stopServer(): { stopped: boolean; info: ServerInfo | null } {
157
+ const { running, info } = isServerRunning()
158
+
159
+ if (!running || !info) {
160
+ return { stopped: false, info: null }
161
+ }
162
+
163
+ // 终止进程
164
+ const killed = killProcess(info.pid)
165
+
166
+ if (killed) {
167
+ deleteServerInfo()
168
+ }
169
+
170
+ return { stopped: killed, info }
171
+ }
172
+
173
+ /**
174
+ * 重启 Server
175
+ */
176
+ export async function restartServer(port?: number): Promise<ServerInfo> {
177
+ const { info: oldInfo } = stopServer()
178
+
179
+ // 等待旧进程完全停止
180
+ await new Promise((resolve) => setTimeout(resolve, 500))
181
+
182
+ // 启动新 Server
183
+ return startServerDaemon(port || oldInfo?.port)
184
+ }
185
+
186
+ /**
187
+ * 获取 Server 状态
188
+ */
189
+ export function getServerStatus(): {
190
+ running: boolean
191
+ port?: number
192
+ pid?: number
193
+ startedAt?: string
194
+ uptime?: string
195
+ } {
196
+ const { running, info } = isServerRunning()
197
+
198
+ if (!running || !info) {
199
+ return { running: false }
200
+ }
201
+
202
+ const uptimeMs = Date.now() - new Date(info.startedAt).getTime()
203
+
204
+ return {
205
+ running: true,
206
+ port: info.port,
207
+ pid: info.pid,
208
+ startedAt: info.startedAt,
209
+ uptime: formatDuration(uptimeMs),
210
+ }
211
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Server 模块导出
3
+ */
4
+
5
+ export { MGServer, createServer, type ServerOptions } from './websocket-server.js'
6
+ export { ConnectionManager, type ManagedWebSocket } from './connection-manager.js'
7
+ export { RequestHandler } from './request-handler.js'
8
+ export { Logger, createLogger, LogLevel, type LoggerOptions } from './logger.js'
@@ -0,0 +1,117 @@
1
+ /**
2
+ * 日志模块
3
+ */
4
+
5
+ import { appendFileSync, existsSync, mkdirSync } from 'node:fs'
6
+ import { dirname } from 'node:path'
7
+ import { SERVER_LOG_FILE } from '../shared/constants.js'
8
+ import { formatLogTime } from '../shared/utils.js'
9
+
10
+ export enum LogLevel {
11
+ DEBUG = 'DEBUG',
12
+ INFO = 'INFO',
13
+ WARN = 'WARN',
14
+ ERROR = 'ERROR',
15
+ }
16
+
17
+ export interface LoggerOptions {
18
+ /** 是否输出到控制台 */
19
+ console?: boolean
20
+ /** 是否输出到文件 */
21
+ file?: boolean
22
+ /** 日志文件路径 */
23
+ filePath?: string
24
+ /** 最小日志级别 */
25
+ minLevel?: LogLevel
26
+ }
27
+
28
+ const levelPriority: Record<LogLevel, number> = {
29
+ [LogLevel.DEBUG]: 0,
30
+ [LogLevel.INFO]: 1,
31
+ [LogLevel.WARN]: 2,
32
+ [LogLevel.ERROR]: 3,
33
+ }
34
+
35
+ /**
36
+ * 日志记录器
37
+ */
38
+ export class Logger {
39
+ private options: Required<LoggerOptions>
40
+
41
+ constructor(options: LoggerOptions = {}) {
42
+ this.options = {
43
+ console: options.console ?? true,
44
+ file: options.file ?? false,
45
+ filePath: options.filePath ?? SERVER_LOG_FILE,
46
+ minLevel: options.minLevel ?? LogLevel.INFO,
47
+ }
48
+
49
+ // 确保日志目录存在
50
+ if (this.options.file) {
51
+ const dir = dirname(this.options.filePath)
52
+ if (!existsSync(dir)) {
53
+ mkdirSync(dir, { recursive: true })
54
+ }
55
+ }
56
+ }
57
+
58
+ /**
59
+ * 记录日志
60
+ */
61
+ private log(level: LogLevel, message: string, ...args: unknown[]): void {
62
+ // 检查日志级别
63
+ if (levelPriority[level] < levelPriority[this.options.minLevel]) {
64
+ return
65
+ }
66
+
67
+ const timestamp = formatLogTime()
68
+ const formattedMessage = `[${timestamp}] [${level}] ${message}`
69
+
70
+ // 输出到控制台
71
+ if (this.options.console) {
72
+ const consoleMethod = level === LogLevel.ERROR ? console.error : console.log
73
+ if (args.length > 0) {
74
+ consoleMethod(formattedMessage, ...args)
75
+ } else {
76
+ consoleMethod(formattedMessage)
77
+ }
78
+ }
79
+
80
+ // 输出到文件
81
+ if (this.options.file) {
82
+ try {
83
+ const fileMessage =
84
+ args.length > 0
85
+ ? `${formattedMessage} ${JSON.stringify(args)}\n`
86
+ : `${formattedMessage}\n`
87
+ appendFileSync(this.options.filePath, fileMessage)
88
+ } catch (error) {
89
+ // 文件写入失败时静默处理
90
+ if (this.options.console) {
91
+ console.error('日志文件写入失败:', error)
92
+ }
93
+ }
94
+ }
95
+ }
96
+
97
+ debug(message: string, ...args: unknown[]): void {
98
+ this.log(LogLevel.DEBUG, message, ...args)
99
+ }
100
+
101
+ info(message: string, ...args: unknown[]): void {
102
+ this.log(LogLevel.INFO, message, ...args)
103
+ }
104
+
105
+ warn(message: string, ...args: unknown[]): void {
106
+ this.log(LogLevel.WARN, message, ...args)
107
+ }
108
+
109
+ error(message: string, ...args: unknown[]): void {
110
+ this.log(LogLevel.ERROR, message, ...args)
111
+ }
112
+ }
113
+
114
+ /** 创建默认日志记录器 */
115
+ export function createLogger(options?: LoggerOptions): Logger {
116
+ return new Logger(options)
117
+ }