server.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. import fs from 'node:fs/promises';
  2. import { URL } from 'node:url';
  3. import { Transform } from 'node:stream';
  4. import { Readable } from 'node:stream';
  5. import { pipeline } from 'node:stream/promises';
  6. import { Hono } from 'hono';
  7. import { logger } from 'hono/logger';
  8. import { createServer as createNodeServer } from 'node:http';
  9. import process from 'node:process';
  10. import { createAdaptorServer } from '@hono/node-server'
  11. // 新增:导入 Socket.IO
  12. import { Server } from 'socket.io';
  13. // 创建 Hono 应用
  14. const app = new Hono();// API路由
  15. // 全局使用 Hono 日志中间件(记录所有请求)
  16. app.use('*', logger());
  17. // 常量定义
  18. const isProduction = process.env.NODE_ENV === 'production';
  19. const port = process.env.PORT || 8080;
  20. const base = process.env.BASE || '/';
  21. const ABORT_DELAY = 10000;
  22. console.log('========================================');
  23. console.log('开始初始化服务器...');
  24. console.log(`环境: ${isProduction ? '生产环境' : '开发环境'}`);
  25. console.log(`端口: ${port}`);
  26. console.log(`基础路径: ${base}`);
  27. console.log('========================================');
  28. // 解析基础路径为 URL 对象,方便后续处理
  29. const baseUrl = new URL(base, `http://localhost:${port}`);
  30. console.log(`基础URL解析完成: ${baseUrl.href}`);
  31. // 先创建服务器实例
  32. console.log('正在创建服务器实例...');
  33. const parentServer = createAdaptorServer({
  34. fetch: app.fetch,
  35. createServer: createNodeServer,
  36. port: port,
  37. })
  38. console.log('服务器实例创建成功');
  39. // 新增:初始化 Socket.IO 服务器
  40. console.log('正在初始化 Socket.IO 服务器...');
  41. const io = new Server(parentServer, {
  42. // // 配置 CORS,根据实际需求调整
  43. // cors: {
  44. // origin: isProduction ? process.env.FRONTEND_URL || false : "http://localhost:8080",
  45. // methods: ["GET", "POST"],
  46. // credentials: true
  47. // },
  48. // // 路径配置,避免与其他路由冲突
  49. // path: `${base}socket.io`
  50. });
  51. console.log('Socket.IO 服务器初始化完成');
  52. // 生产环境中间件
  53. let compressionMiddleware;
  54. let sirvMiddleware;
  55. if (isProduction) {
  56. console.log('生产环境: 加载压缩和静态文件中间件...');
  57. compressionMiddleware = (await import('compression')).default();
  58. sirvMiddleware = (await import('sirv')).default('./dist/client', {
  59. extensions: [],
  60. baseUrl: base
  61. });
  62. console.log('生产环境中间件加载完成');
  63. }
  64. // Vite 开发服务器
  65. /** @type {import('vite').ViteDevServer | undefined} */
  66. let vite;
  67. if (!isProduction) {
  68. console.log('开发环境: 初始化 Vite 开发服务器...');
  69. const { createServer } = await import('vite');
  70. vite = await createServer({
  71. server: { middlewareMode: {
  72. server: parentServer
  73. },
  74. hmr: {
  75. port: 8081,
  76. clientPort: 443,
  77. path: 'vite-hmr'
  78. },
  79. proxy: {
  80. '/vite-hmr': {
  81. target: 'ws://localhost:8081',
  82. ws: true,
  83. },
  84. },
  85. },
  86. appType: 'custom',
  87. base,
  88. });
  89. console.log('Vite 开发服务器初始化完成');
  90. }
  91. // 加载 API 路由
  92. if (!isProduction) {
  93. console.log('开发环境: 从 Vite 加载 API 路由...');
  94. const apiModule = await vite.ssrLoadModule('./src/server/api.ts');
  95. app.route('/', apiModule.default);
  96. console.log('API 路由加载完成');
  97. }else{
  98. console.log('生产环境: 加载编译后的 API 路由...');
  99. const api = (await import('./dist/api/api.js')).default
  100. app.route('/', api);
  101. console.log('API 路由加载完成');
  102. }
  103. // 新增:加载 Socket.IO 中间件和路由
  104. if (!isProduction) {
  105. console.log('开发环境: 从 Vite 加载 Socket.IO 路由和中间件...');
  106. const socketModule = await vite.ssrLoadModule('./src/server/socket.ts');
  107. // 应用认证中间件
  108. if (socketModule.authMiddleware) {
  109. console.log('应用 Socket.IO 认证中间件');
  110. io.use(socketModule.authMiddleware);
  111. }
  112. // 应用路由
  113. if (socketModule.default) {
  114. console.log('注册 Socket.IO 路由处理');
  115. socketModule.default(io);
  116. }
  117. console.log('Socket.IO 路由和中间件加载完成');
  118. } else {
  119. console.log('生产环境: 加载编译后的 Socket.IO 路由和中间件...');
  120. try {
  121. const socket = (await import('./dist/socket/socket.js')).default;
  122. // 应用认证中间件
  123. if (socket.authMiddleware) {
  124. console.log('应用 Socket.IO 认证中间件');
  125. io.use(socket.authMiddleware);
  126. }
  127. // 应用路由
  128. if (socket.default) {
  129. console.log('注册 Socket.IO 路由处理');
  130. socket.default(io);
  131. }
  132. console.log('Socket.IO 路由和中间件加载完成');
  133. } catch (err) {
  134. console.error('加载 Socket.IO 模块失败:', err);
  135. }
  136. }
  137. // 请求处理中间件 - 通用逻辑
  138. app.use(async (c, next) => {
  139. try {
  140. // 使用 c.env 获取原生请求响应对象
  141. const req = c.env.incoming;
  142. const res = c.env.outgoing;
  143. const url = new URL(req.url, `http://${req.headers.host}`);
  144. const path = url.pathname;
  145. // 检查是否匹配基础路径
  146. if (!path.startsWith(baseUrl.pathname)) {
  147. return c.text('未找到', 404);
  148. }
  149. // 开发环境:使用 Vite 中间件
  150. if (!isProduction && vite) {
  151. // 使用 Vite 中间件处理请求
  152. const handled = await new Promise((resolve) => {
  153. vite.middlewares(req, res, () => resolve(false));
  154. });
  155. // 如果 Vite 中间件已经处理了请求,直接返回
  156. if (handled) {
  157. return c.body;
  158. }
  159. }
  160. // 生产环境:使用 compression 和 sirv 中间件
  161. else if (isProduction) {
  162. // 先尝试 compression 中间件
  163. const compressed = await new Promise((resolve) => {
  164. compressionMiddleware(req, res, () => resolve(false));
  165. });
  166. if (compressed) {
  167. return c.body;
  168. }
  169. // 再尝试 sirv 中间件处理静态文件
  170. const served = await new Promise((resolve) => {
  171. sirvMiddleware(req, res, () => resolve(false));
  172. });
  173. if (served) {
  174. return c.body;
  175. }
  176. }
  177. await next()
  178. } catch (e) {
  179. if (!isProduction && vite) {
  180. vite.ssrFixStacktrace(e);
  181. }
  182. console.error('请求处理中间件错误:', e.stack);
  183. return c.text('服务器内部错误', 500);
  184. }
  185. });
  186. // 请求处理中间件 - SSR 渲染逻辑
  187. app.use(async (c) => {
  188. try {
  189. // 使用 c.env 获取原生请求响应对象
  190. const req = c.env.incoming;
  191. const res = c.env.outgoing;
  192. const url = new URL(req.url, `http://${req.headers.host}`);
  193. const path = url.pathname;
  194. // 检查是否匹配基础路径
  195. if (!path.startsWith(baseUrl.pathname)) {
  196. return c.text('未找到', 404);
  197. }
  198. // 处理基础路径
  199. const normalizedUrl = path.replace(baseUrl.pathname, '/') || '/';
  200. console.log(`处理请求: ${normalizedUrl}`);
  201. // 处理所有其他请求的 SSR 逻辑
  202. /** @type {string} */
  203. let template;
  204. /** @type {import('./src/server/index.tsx').render} */
  205. let render;
  206. if (!isProduction && vite) {
  207. console.log('开发环境: 加载模板和渲染函数...');
  208. // 开发环境:读取最新模板并转换
  209. const module = (await vite.ssrLoadModule('/src/server/index.tsx'));
  210. template = module.template;
  211. template = await vite.transformIndexHtml(normalizedUrl, template);
  212. render = module.render;
  213. console.log('开发环境模板处理完成');
  214. } else {
  215. // 生产环境:使用缓存的模板
  216. console.log('生产环境: 加载编译后的模板和渲染函数...');
  217. const module = await import('./dist/server/index.js');
  218. // 读取 manifest.json 并处理模板
  219. try {
  220. // 读取 manifest
  221. const manifestPath = new URL('./dist/client/.vite/manifest.json', import.meta.url);
  222. const manifestContent = await fs.readFile(manifestPath, 'utf-8');
  223. const manifest = JSON.parse(manifestContent);
  224. console.log('生产环境: 成功读取 manifest.json');
  225. // 获取 index.html 对应的资源信息
  226. const indexManifest = manifest['index.html'];
  227. if (!indexManifest) {
  228. throw new Error('manifest 中未找到 index.html 入口配置');
  229. }
  230. template = module.template;
  231. // 替换 CSS 链接
  232. const cssLinks = indexManifest.css?.map(cssFile => {
  233. // 结合基础路径生成完整 URL(处理 base 前缀)
  234. const cssUrl = new URL(cssFile, baseUrl).pathname;
  235. return `<link href="${cssUrl}" rel="stylesheet" />`;
  236. }).join('\n') || ''; // 无 CSS 则清空
  237. // 替换入口脚本
  238. const jsEntryPath = new URL(indexManifest.file, baseUrl).pathname;
  239. const entryScript = `<script type="module" src="${jsEntryPath}"></script>`;
  240. // 执行替换
  241. template = template
  242. .replace(/<link href="\/src\/style.css" rel="stylesheet"\/>/, cssLinks)
  243. .replace(/<script type="module" src="\/src\/client\/index.tsx"><\/script>/, entryScript);
  244. console.log('生产环境模板处理完成');
  245. } catch (err) {
  246. console.error('生产环境模板处理失败:', err);
  247. throw err; // 终止启动,避免使用错误模板
  248. }
  249. render = module.render;
  250. }
  251. let didError = false;
  252. let abortController;
  253. // 创建一个可读流用于 SSR 渲染内容
  254. const [htmlStart, htmlEnd] = template.split(`<!--app-html-->`);
  255. const ssrStream = new Readable({ read: () => {} });
  256. // 写入 HTML 头部
  257. ssrStream.push(htmlStart);
  258. // 设置响应头和状态码
  259. c.header('Content-Type', 'text/html');
  260. // 处理渲染
  261. const { pipe, abort } = render(normalizedUrl, {
  262. onShellError() {
  263. didError = true;
  264. c.status(500);
  265. ssrStream.push('<h1>服务器渲染出错</h1>');
  266. ssrStream.push(null); // 结束流
  267. },
  268. onShellReady() {
  269. console.log(`开始渲染页面: ${normalizedUrl}`);
  270. // 将渲染结果通过管道传入 ssrStream
  271. const transformStream = new Transform({
  272. transform(chunk, encoding, callback) {
  273. ssrStream.push(chunk, encoding);
  274. callback();
  275. }
  276. });
  277. pipe(transformStream);
  278. // 当 transformStream 完成时,添加 HTML 尾部
  279. transformStream.on('finish', () => {
  280. ssrStream.push(htmlEnd);
  281. ssrStream.push(null); // 结束流
  282. console.log(`页面渲染完成: ${normalizedUrl}`);
  283. });
  284. },
  285. onError(error) {
  286. didError = true;
  287. console.error('渲染过程出错:', error);
  288. },
  289. });
  290. // 设置超时中止
  291. abortController = new AbortController();
  292. const abortTimeout = setTimeout(() => {
  293. console.log(`渲染超时,终止请求: ${normalizedUrl}`);
  294. abort();
  295. abortController.abort();
  296. }, ABORT_DELAY);
  297. // 将流通过 Hono 响应返回
  298. return c.body(ssrStream, {
  299. onEnd: () => {
  300. clearTimeout(abortTimeout);
  301. }
  302. });
  303. } catch (e) {
  304. if (!isProduction && vite) {
  305. vite.ssrFixStacktrace(e);
  306. }
  307. console.error('SSR 处理错误:', e.stack);
  308. return c.text('服务器内部错误', 500);
  309. }
  310. });
  311. // 启动服务器
  312. console.log('准备启动服务器...');
  313. parentServer.listen(port, () => {
  314. console.log('========================================');
  315. console.log(`服务器已成功启动!`);
  316. console.log(`访问地址: http://localhost:${port}`);
  317. console.log(`Socket.IO 路径: ${base}socket.io`);
  318. console.log(`环境: ${isProduction ? '生产环境' : '开发环境'}`);
  319. console.log('========================================');
  320. })
  321. // 统一的服务器关闭处理函数
  322. const shutdownServer = async () => {
  323. console.log('正在关闭服务器...');
  324. // 新增:关闭 Socket.IO 服务器
  325. console.log('正在关闭 Socket.IO 服务器...');
  326. await io.close();
  327. console.log('Socket.IO 服务器已关闭');
  328. // 关闭 Vite 开发服务器(包括 HMR 服务)
  329. if (!isProduction && vite) {
  330. console.log('正在关闭 Vite 开发服务器(包括 HMR 服务)...');
  331. try {
  332. await vite.close();
  333. console.log('Vite 开发服务器已关闭');
  334. } catch (err) {
  335. console.error('关闭 Vite 服务器时出错:', err);
  336. }
  337. }
  338. // 关闭主服务器
  339. parentServer.close((err) => {
  340. if (err) {
  341. console.error('关闭主服务器时出错:', err);
  342. process.exit(1);
  343. }
  344. console.log('主服务器已关闭');
  345. process.exit(0);
  346. });
  347. };
  348. // 处理进程终止信号(包括 Ctrl+C)
  349. process.on('SIGINT', shutdownServer); // 处理 Ctrl+C
  350. process.on('SIGTERM', shutdownServer); // 处理 kill 命令