Skip to content

支持服务优雅关闭,避免重启回复中断和面板缓存数据丢失 - #4258

Merged
Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
feitianbubu:pr/8486b0d77893aecd72790f949022eff581262042
Jul 2, 2026
Merged

Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
feitianbubu:pr/8486b0d77893aecd72790f949022eff581262042

Conversation

@feitianbubu

@feitianbubu feitianbubu commented Apr 15, 2026 •

Copy link
Copy Markdown
Member

⚠️ 提交说明 / PR Notice

支持服务优雅关闭,避免重启时流式回复被打断;并在关闭时落库数据看板缓存,避免重启丢失未导出的看板数据。

🔗 关联 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

  1. docker compose启动
  2. 执行一个较长的流式回复
  3. docker compose up -d
  4. 系统会等待流式回复结束再重启, 最长等待120s(可配置)
image image

Summary by CodeRabbit

  • Refactor
    • Enhanced HTTP server startup to run non-blocking and handle startup errors more safely.
    • Added graceful shutdown on termination signals (SIGINT/SIGTERM), using a configurable default 120-second timeout.
    • Ensures shutdown is followed by optional persistence of in-memory quota/board data when data export is enabled.

@coderabbitai

coderabbitai Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Replaced the blocking server start with an explicit http.Server running in a goroutine, and added signal-driven graceful shutdown with a configurable timeout plus optional quota cache persistence before exit.

Changes

Server Lifecycle Shutdown

Layer / File(s) Summary
Startup and shutdown flow
main.go
main.go adds shutdown support imports, starts the HTTP server asynchronously, waits for SIGINT/SIGTERM, shuts down with a timeout, and saves cached quota data when export is enabled.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped through the shutdown gate,
With signals soft and timing great.
The server bows, then fades from view,
And cached-up crumbs are saved anew.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed The PR flushes in-memory quota data on shutdown, which addresses the reported dashboard data loss after gateway restarts.
Out of Scope Changes check ✅ Passed The changes stay focused on graceful shutdown and quota cache persistence, with no clear unrelated code changes.
Title check ✅ Passed 标题准确概括了本次变更:支持优雅关闭,并避免重启时流式回复中断和面板缓存数据丢失。
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7e26b240-b77a-4b94-a32c-1f08b5e4c444

📥 Commits

Reviewing files that changed from the base of the PR and between 8c8661d and f053843.

📒 Files selected for processing (1)
  • main.go

Comment thread main.go
Comment on lines 196 to +207
// 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())
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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 -->

Comment thread main.go
Comment on lines +215 to +222
// 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")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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).
@feitianbubu feitianbubu changed the title 支持New优雅关闭,避免重启时流式回复被打断 支持New优雅关闭,避免服务重启回复中断和面板缓存数据丢失 Jun 26, 2026
@feitianbubu feitianbubu changed the title 支持New优雅关闭,避免服务重启回复中断和面板缓存数据丢失 支持服务优雅关闭,避免重启回复中断和面板缓存数据丢失 Jun 26, 2026
@Calcium-Ion
Calcium-Ion merged commit 986d90a into QuantumNous:main Jul 2, 2026
henrydontbbai added a commit to henrydontbbai/henry-newapi that referenced this pull request Jul 2, 2026
* 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]>
liulixin-lex pushed a commit to liulixin-lex/xy-api that referenced this pull request Jul 7, 2026
* 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).
quqi1599 pushed a commit to rebecca554owen/new-api that referenced this pull request Jul 7, 2026
* 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).
xiaomingchen pushed a commit to xiaomingchen/new-api that referenced this pull request Jul 10, 2026
* 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).
Jacobinwwey pushed a commit to Jacobinwwey/new-api that referenced this pull request Jul 11, 2026
* 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).
ruanhangjian pushed a commit to ruanhangjian/new-api that referenced this pull request Jul 11, 2026
* 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).
noah-wung pushed a commit to noah-wung/new-api that referenced this pull request Jul 17, 2026
* 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).
zhaodechao2008 pushed a commit to zhaodechao2008/new-api that referenced this pull request Jul 27, 2026
* 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).
330079598 pushed a commit to 330079598/new-api that referenced this pull request Aug 19, 2026
* 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).
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
* 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).
XuYang8026 pushed a commit to heiying0917/new-api that referenced this pull request Sep 17, 2026
* 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)
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
* 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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

重启网关后导致数据看板部分数据丢失

2 participants