Repository navigation
支持服务优雅关闭,避免重启回复中断和面板缓存数据丢失 - #4258
Calcium-Ion merged 2 commits into
Conversation
WalkthroughReplaced the blocking server start with an explicit ChangesServer Lifecycle Shutdown
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@main.go`:
- Around line 215-222: The HTTP server shutdown only stops srv; you must also
wait for the relay/background goroutine pool (common.relayGoPool from
common/gopool.go) to drain before exiting main. After calling srv.Shutdown(ctx)
and before returning, call the relay pool's shutdown/wait method (e.g.,
common.relayGoPool.Shutdown(ctx) or common.relayGoPool.Wait()) or implement a
drain loop that checks relayGoPool.ActiveWorkers()/len(relayGoPool.workers) and
blocks until zero (respecting the same ctx timeout) so long-lived relay tasks
complete gracefully.
- Around line 196-207: Move the LogStartupSuccess call to after you successfully
bind the socket: perform a net.Listen("tcp", ":"+port) first (add the net
import), if listen returns without error then call
common.LogStartupSuccess(startTime, port), then start the server with
srv.Serve(listener) in the goroutine (or wrap listener in the existing srv).
Update the goroutine to use srv.Serve(listener) and still treat
http.ErrServerClosed as non-fatal; ensure the listener is closed on shutdown so
resources are cleaned up.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
| // Log startup success message | ||
| common.LogStartupSuccess(startTime, port) | ||
|
|
||
| err = server.Run(":" + port) | ||
| if err != nil { | ||
| common.FatalLog("failed to start HTTP server: " + err.Error()) | ||
| srv := &http.Server{ | ||
| Addr: ":" + port, | ||
| Handler: server, | ||
| } | ||
|
|
||
| go func() { | ||
| if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { | ||
| common.FatalLog("failed to start HTTP server: " + err.Error()) | ||
| } |
There was a problem hiding this comment.
Bind the listener before logging startup success.
Line 197 logs a successful startup before Line 205 has actually bound the port. If the bind fails, operators still get a false-positive “started” log and the real failure only appears from a background goroutine.
Suggested shape
- common.LogStartupSuccess(startTime, port)
-
- srv := &http.Server{
- Addr: ":" + port,
- Handler: server,
- }
-
- go func() {
- if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
- common.FatalLog("failed to start HTTP server: " + err.Error())
- }
- }()
+ ln, err := net.Listen("tcp", ":"+port)
+ if err != nil {
+ common.FatalLog("failed to start HTTP server: " + err.Error())
+ }
+ common.LogStartupSuccess(startTime, port)
+
+ srv := &http.Server{
+ Handler: server,
+ }
+
+ go func() {
+ if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ common.FatalLog("failed to start HTTP server: " + err.Error())
+ }
+ }()Also add the net import.
</details>
<details>
<summary>🤖 Prompt for AI Agents</summary>
Verify each finding against the current code and only fix it if needed.
In @main.go around lines 196 - 207, Move the LogStartupSuccess call to after you
successfully bind the socket: perform a net.Listen("tcp", ":"+port) first (add
the net import), if listen returns without error then call
common.LogStartupSuccess(startTime, port), then start the server with
srv.Serve(listener) in the goroutine (or wrap listener in the existing srv).
Update the goroutine to use srv.Serve(listener) and still treat
http.ErrServerClosed as non-fatal; ensure the listener is closed on shutdown so
resources are cleaned up.
</details>
<!-- fingerprinting:phantom:medusa:grasshopper:322129d1-9e03-4e22-80a1-b6f30e657d48 -->
<!-- This is an auto-generated comment by CodeRabbit -->
| // SSE streams may run for minutes; give them time to finish before forced exit | ||
| shutdownTimeout := time.Duration(common.GetEnvOrDefault("SHUTDOWN_TIMEOUT_SECONDS", 120)) * time.Second | ||
| ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) | ||
| defer cancel() | ||
| if err := srv.Shutdown(ctx); err != nil { | ||
| common.SysError(fmt.Sprintf("server forced to shutdown: %v", err)) | ||
| } | ||
| common.SysLog("server exited") |
There was a problem hiding this comment.
Wait for relay/background workers before returning from main.
srv.Shutdown(ctx) only waits for the http.Server. The relay path also uses common.relayGoPool (common/gopool.go:1-23), and this file starts several long-lived goroutines above. Line 222 returns from main immediately afterward, so anything still running outside the HTTP server is still terminated abruptly on process exit. That leaves a gap in the graceful-shutdown guarantee for streams offloaded to those workers.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@main.go` around lines 215 - 222, The HTTP server shutdown only stops srv; you
must also wait for the relay/background goroutine pool (common.relayGoPool from
common/gopool.go) to drain before exiting main. After calling srv.Shutdown(ctx)
and before returning, call the relay pool's shutdown/wait method (e.g.,
common.relayGoPool.Shutdown(ctx) or common.relayGoPool.Wait()) or implement a
drain loop that checks relayGoPool.ActiveWorkers()/len(relayGoPool.workers) and
blocks until zero (respecting the same ctx timeout) so long-lived relay tasks
complete gracefully.
Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679).
* feat: improve advanced custom route editor * Bump Electron lockfile dependencies * feat: bill doubao seedance-2.0 by output resolution and video input (QuantumNous#5300) * feat: support doubao seedance 2.0 safety_identifier/priority and 4k billing (QuantumNous#5824) * feat: support safety_identifier and priority for doubao video * feat: add 4k resolution billing tier for doubao video * chore: run `bun format` to automatically format the frontend code * fix(web): 修复自定义 HTML 样式被过滤及排版间距异常的问题 (QuantumNous#5795) * fix(web): 修复自定义 HTML 样式被过滤及排版间距异常的问题 * fix(web): isolate custom HTML rendering --------- Co-authored-by: CaIon <[email protected]> * feat: support Wan2.7 i2v media mapping (QuantumNous#4984) * feat: support Wan2.7 i2v media mapping * fix: normalize wan2.7 i2v image inputs * perf(web): optimize web Rsbuild and Tailwind build pipeline (QuantumNous#5786) * fix(dev): run only default frontend in dev-web - simplify make dev-web to install default dependencies and start web/default only. - keep dev-web-classic as the standalone classic entry and scope its install to classic. * chore(build): align make targets with web naming - rename frontend make targets and variables to use the web terminology consistently. - keep default and classic dev port overrides available under the updated names. * fix(web): inject app styles into isolated HTML (QuantumNous#5860) - clone loaded application style nodes into the Shadow DOM for custom HTML rendering. - keep HTML rendering isolated while restoring layout and typography that depend on app CSS. * fix: keep page state when switching tabs within the same route (QuantumNous#5796) AnimatedOutlet keyed its motion container by the full pathname, so navigating between params of the same route (e.g. the dashboard tabs under /dashboard/$section) changed the key and remounted the route component, discarding its in-memory state. The most visible symptom: the dashboard time range resets to the default every time you switch sub-tabs (Model Analytics / Flow / User Analytics). Key the transition by the matched route id instead, so param-only navigation re-renders in place while real page-to-page navigation still plays the enter animation. This also preserves state across the other $section tab pages (usage logs, models, system settings). * 支持服务优雅关闭,避免重启回复中断和面板缓存数据丢失 (QuantumNous#4258) * feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679). * docs: update AGENTS.md * Make quota logging synchronous and delay startup log --------- Co-authored-by: CaIon <[email protected]> Co-authored-by: feitianbubu <[email protected]> Co-authored-by: t0ng7u <[email protected]> Co-authored-by: olwater <[email protected]> Co-authored-by: Scott <[email protected]> Co-authored-by: QuentinHsu <[email protected]> Co-authored-by: henrydontbbai <[email protected]>
* feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679).
* feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679).
* feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679).
* feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679).
* feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679).
* feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679).
* feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679).
* feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679).
* feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679).
* feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679). (cherry picked from commit 986d90a)
* feat: add graceful shutdown with configurable timeout * fix: flush quota dashboard cache on graceful shutdown Persist the in-memory CacheQuotaData aggregation to the quota_data table before process exit, so a restart no longer drops up to one DataExportInterval window of dashboard data (issue QuantumNous#5679).
🔗 关联 Issue / Related Issue
Fixes #5679
📝 变更描述 / Description
将 main.go 中原来的 server.Run() 阻塞启动方式改为 http.Server + goroutine 启动,监听 SIGINT/SIGTERM 信号后调用 srv.Shutdown() 实现优雅关闭。
这样在部署重启或容器停止时,已有的请求(特别是 SSE 长连接)能在超时时间内正常完成,而不是被直接杀掉。超时时间通过环境变量
SHUTDOWN_TIMEOUT_SECONDS控制,默认 120 秒。在此基础上,关闭流程末尾(
srv.Shutdown()之后、进程退出前)新增对数据看板缓存的强制落库:当DataExportEnabled开启时调用model.SaveQuotaDataCache(),把内存中尚未到达DataExportInterval导出周期的聚合数据写入quota_data表。解决 #5679 —— 此前每次重启最多会丢失一个导出周期(默认 5 分钟)的看板数据。该 flush 依赖优雅关闭提供的退出时机,故与本 PR 一并提交。📸 运行证明 / Proof of Work
Summary by CodeRabbit