Repository navigation
[WIP] Add optional Prometheus metrics endpoint - #3472
CamberLoid wants to merge 35 commits into
Conversation
Signed-off-by: Camber Huang <[email protected]>
Signed-off-by: Camber Huang <[email protected]>
WalkthroughAdds optional Prometheus metrics: a new exported Changes
Sequence DiagramsequenceDiagram
participant Client
participant Gin as "Gin Server"
participant Middleware as "Metrics Middleware"
participant Handler as "App Handler"
participant Prom as "Prometheus Registry"
Client->>Gin: HTTP request
Gin->>Middleware: pass request
Middleware->>Middleware: record start time\nresolve active route_tag
Middleware->>Prom: inc HTTPActiveRequests(route_tag)
Middleware->>Handler: c.Next()
Handler-->>Middleware: response (status)
Middleware->>Middleware: resolve final route & route string
Middleware->>Prom: inc HTTPRequestsTotal(route_tag, method, route, status)
Middleware->>Prom: observe HTTPRequestDuration(route_tag, method, route, seconds)
Middleware->>Prom: dec HTTPActiveRequests(route_tag)
Middleware->>Gin: return response
Gin->>Client: HTTP response
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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
🧹 Nitpick comments (1)
main.go (1)
171-171: Gate metrics middleware behind the feature flag for true opt-in behavior.Line [171] instruments every request even when metrics are disabled. Consider enabling middleware only when
common.MetricsEnabledis true.♻️ Suggested change
- server.Use(metrics.HTTPMiddleware()) + if common.MetricsEnabled { + server.Use(metrics.HTTPMiddleware()) + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@main.go` at line 171, Wrap the metrics middleware registration so it only runs when metrics are enabled: check the feature flag common.MetricsEnabled before calling server.Use(metrics.HTTPMiddleware()). In practice, locate the existing call to server.Use(metrics.HTTPMiddleware()) and guard it with an if common.MetricsEnabled { ... } block (or equivalent) so metrics.HTTPMiddleware() is only mounted when common.MetricsEnabled is true.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@metrics/http.go`:
- Line 18: The metricsRouteTag constant is incorrectly set to "api" which causes
Prometheus/metrics scrapes to be attributed to API SLIs; change the constant
metricsRouteTag to a dedicated value like "metrics" (or "prometheus") and update
all other uses of metricsRouteTag in this file (including the occurrences
referenced around lines 50-52) so the /metrics handler and any route
registration, middleware, or labels use the new tag instead of "api".
In `@router/main.go`:
- Around line 18-20: The /metrics route is being registered on the public router
(router.GET("/metrics", gin.WrapH(promhttp.Handler()))) when
common.MetricsEnabled is true, which exposes operational data; to fix, don't
register it directly on the public router—either move the metrics handler to an
internal/admin router or wrap it with an authentication/allowlist middleware
before registering (e.g., use your existing admin/auth middleware or a
network-restricted router), so replace the direct call to router.GET("/metrics",
gin.WrapH(promhttp.Handler())) with a guarded registration using the chosen
admin/internal router or middleware.
---
Nitpick comments:
In `@main.go`:
- Line 171: Wrap the metrics middleware registration so it only runs when
metrics are enabled: check the feature flag common.MetricsEnabled before calling
server.Use(metrics.HTTPMiddleware()). In practice, locate the existing call to
server.Use(metrics.HTTPMiddleware()) and guard it with an if
common.MetricsEnabled { ... } block (or equivalent) so metrics.HTTPMiddleware()
is only mounted when common.MetricsEnabled is true.
🪄 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: 85baea12-46ae-40a2-9737-17947f5b6e24
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (7)
common/constants.gocommon/init.gogo.modmain.gometrics/http.gometrics/registry.gorouter/main.go
| apiRouteTag = "api" | ||
| relayRouteTag = "relay" | ||
| oldAPIRouteTag = "old_api" | ||
| metricsRouteTag = "api" |
There was a problem hiding this comment.
Use a dedicated route tag for /metrics to avoid contaminating API SLIs.
Line [18] sets metricsRouteTag to "api", so scrape traffic is counted as API traffic. This can skew API request-rate and latency dashboards.
📈 Suggested fix
- metricsRouteTag = "api"
+ metricsRouteTag = "metrics"Also applies to: 50-52
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@metrics/http.go` at line 18, The metricsRouteTag constant is incorrectly set
to "api" which causes Prometheus/metrics scrapes to be attributed to API SLIs;
change the constant metricsRouteTag to a dedicated value like "metrics" (or
"prometheus") and update all other uses of metricsRouteTag in this file
(including the occurrences referenced around lines 50-52) so the /metrics
handler and any route registration, middleware, or labels use the new tag
instead of "api".
| if common.MetricsEnabled { | ||
| router.GET("/metrics", gin.WrapH(promhttp.Handler())) | ||
| } |
There was a problem hiding this comment.
Protect /metrics before exposing it on the public router.
Line [19] registers a scrape endpoint without any auth/network guard. This can leak operational metadata in internet-exposed deployments.
🔐 Suggested hardening
if common.MetricsEnabled {
- router.GET("/metrics", gin.WrapH(promhttp.Handler()))
+ metricsToken := strings.TrimSpace(os.Getenv("METRICS_TOKEN"))
+ metricsHandler := gin.WrapH(promhttp.Handler())
+ router.GET("/metrics", func(c *gin.Context) {
+ if metricsToken == "" || c.GetHeader("Authorization") != "Bearer "+metricsToken {
+ c.AbortWithStatus(http.StatusUnauthorized)
+ return
+ }
+ metricsHandler(c)
+ })
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@router/main.go` around lines 18 - 20, The /metrics route is being registered
on the public router (router.GET("/metrics", gin.WrapH(promhttp.Handler())))
when common.MetricsEnabled is true, which exposes operational data; to fix,
don't register it directly on the public router—either move the metrics handler
to an internal/admin router or wrap it with an authentication/allowlist
middleware before registering (e.g., use your existing admin/auth middleware or
a network-restricted router), so replace the direct call to
router.GET("/metrics", gin.WrapH(promhttp.Handler())) with a guarded
registration using the chosen admin/internal router or middleware.
Signed-off-by: Camber Huang <[email protected]>
Bumps [golang.org/x/image](https://github.com/golang/image) from 0.23.0 to 0.38.0. - [Commits](golang/image@v0.23.0...v0.38.0) --- updated-dependencies: - dependency-name: golang.org/x/image dependency-version: 0.38.0 dependency-type: direct:production ... Signed-off-by: dependabot[bot] <[email protected]>
- Add StreamStatus type (relay/common) to track stream end reason (done/timeout/client_gone/scanner_error/eof/panic/ping_fail) and accumulate soft errors during streaming via sync.Once + sync.Mutex. - Add StreamResult (relay/helper) as the callback interface: adapters call sr.Error() for soft errors, sr.Stop() for fatal, sr.Done() for normal completion. No early-return problem — multiple errors per chunk are naturally supported. - Refactor StreamScannerHandler callback from func(string) bool to func(string, *StreamResult). All 9 channel adapters updated. - Write stream_status into log other JSON field (admin-only) with status ok/error, end_reason, error_count, and error messages. - Frontend: display stream status in log detail expansion for admins.
- Add ValidateURLWithFetchSetting check before fetching MJ image URLs in RelayMidjourneyImage (unauthenticated endpoint) - Add ValidateURLWithFetchSetting check before fetching video URLs in VideoProxy (upstream-controlled URL) - Enable ApplyIPFilterForDomain by default to prevent DNS rebinding bypass of SSRF protection - Elevate FetchModels endpoint from AdminAuth to RootAuth - Update frontend: mark domain IP filtering as recommended, update description and i18n translations (zh-CN/zh-TW/en/fr/ja/ru/vi)
- Refactor Footer component to use a semantic <footer> element for better accessibility. - Update CSS to include a new class for the custom footer, allowing for relative positioning. - Adjust layout to improve responsiveness and visual alignment of footer content.
…responses - Switch /api/oauth/email/bind and /api/oauth/wechat/bind from GET to POST with JSON body for better REST semantics - Normalize password reset endpoint to return consistent responses - Apply url.QueryEscape to WeChat code parameter for robustness
…n copy When copying a token, users can now choose "Copy Connection String" which encodes both the API key and server URL as a JSON clipboard payload (type: newapi_channel_conn). When opening the channel creation form, the clipboard is auto-detected and a banner offers to fill key + base_url, eliminating repeated tab-switching when connecting to another new-api instance.
Added checks to ensure clipboard functionality is available before attempting to read from it. Improved error handling during clipboard read operations to prevent unhandled exceptions.
Bumps [picomatch](https://github.com/micromatch/picomatch) from 4.0.3 to 4.0.4. - [Release notes](https://github.com/micromatch/picomatch/releases) - [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md) - [Commits](micromatch/picomatch@4.0.3...4.0.4) --- updated-dependencies: - dependency-name: picomatch dependency-version: 4.0.4 dependency-type: indirect ... Signed-off-by: dependabot[bot] <[email protected]>
Comment out code that modifies price data based on image count. 测试发现,如果是接入阿里百炼平台的qwen-image-2.0系列模型,这边计费的时候会出现 0.2*n*倍率*n的情况,最前面的0.2*n会直接显示为模型价格。 例如: 日志详情 模型价格 $0.600000,专属倍率 0.3 其他详情 大小 1080*1920, 品质 standard, 生成数量 3, 其他倍率 n: 3.000000 计费过程 模型价格:$0.600000 * 专属倍率:0.3 = $0.180000
The previous commit commented out AddOtherRatio("n") in the Ali
adaptor to fix double-counting but this could cause billing evasion
when n is specified via extra["parameters"] instead of request.N.
Root cause: ImagePriceRatio in GetTokenCountMeta() already included
n, AND channel adaptors added OtherRatio("n"), resulting in n²
billing.
Proper fix:
- Remove n from ImagePriceRatio (keep sizeRatio * qualityRatio only)
- In ImageHelper, add default OtherRatio("n") when adaptor hasn't
set one; set fallback tokens to 1 (base unit)
- Restore Ali adaptor's AddOtherRatio("n") — it uses actual upstream
parameters/response count, preventing billing evasion
Added functionality to save and restore the state of advanced settings in the EditChannelModal using local storage. This enhancement allows users to maintain their preferences when editing channels, improving the overall user experience.
Updated performance checks to provide more detailed error messages, including current usage and thresholds for CPU, memory, and disk. Additionally. Updated localization files to reflect changes in retry options across multiple languages.
Add detection, MIME type mapping, and dimension parsing for HEIC/HEIF images via ISOBMFF ftyp brand inspection and ispe box parsing. Update Gemini relay to accept these formats and refactor getImageConfig to properly retry decoders using buffered data.
parseHEIFDimensions now correctly handles boxSize==1 (64-bit extended size) and boxSize==0 (box-to-EOF), preventing the parser from breaking out of the loop when encountering these valid ISOBMFF box headers before reaching the meta box.
…ns and descriptions Added translations for custom currency display settings across multiple languages, including descriptions for quota display types and exchange rates. This enhances user experience by providing clear information on how quotas are displayed and calculated in different currencies.
There was a problem hiding this comment.
Actionable comments posted: 11
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
web/src/pages/Setting/Operation/SettingsGeneral.jsx (1)
209-217:⚠️ Potential issue | 🟠 MajorMissing default for
quota_display_typecan leave UI in an undefined state.If backend options omit both
general_setting.quota_display_typeand legacyDisplayInCurrencyEnabled, Line 230 sets inputs without a fallback, and subsequent logic treats the type as undefined.💡 Suggested fix
- if ( - currentInputs['general_setting.quota_display_type'] === undefined && - props.options?.DisplayInCurrencyEnabled !== undefined - ) { - currentInputs['general_setting.quota_display_type'] = props.options - .DisplayInCurrencyEnabled - ? 'USD' - : 'TOKENS'; - } + if (currentInputs['general_setting.quota_display_type'] === undefined) { + if (props.options?.DisplayInCurrencyEnabled !== undefined) { + currentInputs['general_setting.quota_display_type'] = props.options + .DisplayInCurrencyEnabled + ? 'USD' + : 'TOKENS'; + } else { + currentInputs['general_setting.quota_display_type'] = 'USD'; + } + }Also applies to: 230-233
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/pages/Setting/Operation/SettingsGeneral.jsx` around lines 209 - 217, The branch that sets currentInputs['general_setting.quota_display_type'] only handles when DisplayInCurrencyEnabled exists and otherwise leaves the value undefined; update the logic in the SettingsGeneral component to provide a safe default when both currentInputs['general_setting.quota_display_type'] and props.options?.DisplayInCurrencyEnabled are undefined (for example set to 'TOKENS' or another app default). Locate the assignment to currentInputs['general_setting.quota_display_type'] and ensure it uses props.options.DisplayInCurrencyEnabled to choose between 'USD' and 'TOKENS', and falls back to the chosen default when neither source is present so downstream logic never sees undefined.relay/channel/claude/relay-claude.go (1)
403-445:⚠️ Potential issue | 🟠 Major
dto.ContentTypeFileis still a no-op here.The new file helpers exist, but this switch still drops every file block because the only integration path is commented out. Requests with PDF/text attachments will still lose those parts, and a file-only message can end up with an empty Claude content list.
🐛 Suggested fix
case dto.ContentTypeImageURL: claudeMediaMessage := dto.ClaudeMediaMessage{ Type: "image", Source: &dto.ClaudeMessageSource{ Type: "base64", }, } imageUrl := mediaMessage.GetImageMedia() if imageUrl == nil { continue } // 使用统一的文件服务获取图片数据 var source *types.FileSource if strings.HasPrefix(imageUrl.Url, "http") { source = types.NewURLFileSource(imageUrl.Url) } else { source = types.NewBase64FileSource(imageUrl.Url, "") } base64Data, mimeType, err := service.GetBase64Data(c, source, "formatting image for Claude") if err != nil { return nil, fmt.Errorf("get file data failed: %s", err.Error()) } claudeMediaMessage.Source.MediaType = mimeType claudeMediaMessage.Source.Data = base64Data claudeMediaMessages = append(claudeMediaMessages, claudeMediaMessage) - // FIXME - //case dto.ContentTypeFile: - // claudeFileMessage, err := buildClaudeFileMessage(c, mediaMessage.GetFile()) - // if err != nil { - // return nil, err - // } - // if claudeFileMessage != nil { - // claudeMediaMessages = append(claudeMediaMessages, *claudeFileMessage) - // } + case dto.ContentTypeFile: + claudeFileMessage, err := buildClaudeFileMessage(c, mediaMessage.GetFile()) + if err != nil { + return nil, err + } + if claudeFileMessage != nil { + claudeMediaMessages = append(claudeMediaMessages, *claudeFileMessage) + } default: continue }If helpful, I can also draft the fail-fast path for unsupported file types so they aren’t silently discarded.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@relay/channel/claude/relay-claude.go` around lines 403 - 445, The switch currently ignores dto.ContentTypeFile causing file attachments to be dropped; restore and implement the file handling branch by adding a case for dto.ContentTypeFile that calls buildClaudeFileMessage(c, mediaMessage.GetFile()), checks the returned error and returns it if present, and appends the non-nil result to claudeMediaMessages (same pattern used for images); also ensure that if buildClaudeFileMessage returns nil (unsupported file type) you either return a clear error or mark the message as unsupported so a file-only message does not produce an empty Claude content list.
🟡 Minor comments (10)
middleware/request-id.go-23-23 (1)
23-23:⚠️ Potential issue | 🟡 MinorAddress inconsistency in request-id generation: middleware vs. relay fallback path.
Line 23 adds
_bp(8 hex chars from build hash) to the request-id, changing format from ~31 chars to ~39 chars. The database field (varchar(64)) accommodates this, and no strict format validators were found in the codebase.However,
relay/common/relay_info.go(lines 443–446) has a fallback that generates request-ids without_bp:reqId = common.GetTimeString() + common.GetRandomString(8). This means inconsistent formats can occur if relay code executes without the middleware setting the context. Ensure this fallback is either removed (since middleware should always run) or updated to match the new format with_bp.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@middleware/request-id.go` at line 23, The request-id format was changed in middleware/request-id.go to include _bp (id := common.GetTimeString() + _bp + common.GetRandomString(8)) but relay/common/relay_info.go still builds fallbacks as reqId = common.GetTimeString() + common.GetRandomString(8); update the relay fallback to match the middleware format by including the same _bp insertion (derive or reuse the same build-prefix logic used by middleware) so the fallback constructs reqId as common.GetTimeString() + _bp + common.GetRandomString(8) (or remove the fallback if you verify middleware always runs).controller/user.go-935-937 (1)
935-937:⚠️ Potential issue | 🟡 MinorUse the standard invalid-params response here.
This is client input validation, not an internal error. Returning
common.ApiError(...)with a hardcoded English string makes this endpoint inconsistent with the rest of the controller and the localized API surface.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@controller/user.go` around lines 935 - 937, The error handling after common.DecodeJson should return the project's standard "invalid-params" response instead of calling common.ApiError with a hardcoded English string; replace the common.ApiError(c, errors.New("invalid request body")) call with the shared invalid-params helper used across controllers (e.g., common.InvalidParams(c) or the equivalent localized helper) so client input validation is consistently reported and localized.web/src/hooks/usage-logs/useUsageLogsData.jsx-608-608 (1)
608-608:⚠️ Potential issue | 🟡 MinorLocalize the fallback end-reason label.
'unknown'bypasses the repo's i18n flow in a user-visible admin string. Please switch it to a translated Chinese source key such ast('未知').✏️ Suggested fix
- let streamValue = statusLabel + ' (' + (ss.end_reason || 'unknown') + ')'; + let streamValue = statusLabel + ' (' + (ss.end_reason || t('未知')) + ')';As per coding guidelines,
web/src/**/*.{ts,tsx,js,jsx}: Frontend i18n: UseuseTranslation()hook and callt('中文key')in components.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/hooks/usage-logs/useUsageLogsData.jsx` at line 608, The fallback literal 'unknown' bypasses i18n; inside the useUsageLogsData hook/component call useTranslation() and replace the inline fallback in the streamValue construction (the variable streamValue that uses ss.end_reason) with a translated key, e.g. t('未知'), so that streamValue becomes statusLabel + ' (' + (ss.end_reason || t('未知')) + ')'; ensure useTranslation is imported from react-i18next and invoked (const { t } = useTranslation()) at the top of the useUsageLogsData scope so t is available where streamValue is formed.web/src/components/table/tokens/TokensColumnDefs.jsx-150-178 (1)
150-178:⚠️ Potential issue | 🟡 MinorDescribe this control as a menu trigger, not an immediate copy action.
Clicking the icon now opens a two-item dropdown, but assistive tech still gets
aria-label='copy token key'. Please rename the label and expose menu semantics (for examplearia-haspopup="menu") so the new behavior is announced correctly.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/components/table/tokens/TokensColumnDefs.jsx` around lines 150 - 178, The Button inside the Dropdown currently uses aria-label='copy token key' which misrepresents the control; update the Button in TokensColumnDefs.jsx (the Dropdown + Button combo) to use a label that indicates it opens a menu (e.g. use t('open token actions menu') instead of 'copy token key'), add aria-haspopup="menu" and expose aria-expanded (bound to the Dropdown open state or a local open boolean) so assistive tech announces menu semantics, and keep stopPropagation; no change to the existing menu items or their onClick handlers (copyTokenKey / copyTokenConnectionString).web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx-144-151 (1)
144-151:⚠️ Potential issue | 🟡 MinorLocalize the new stream-status tooltip end to end.
流状态,异常, and软错误are introduced here, but the locale updates in this PR don’t add those keys, and the'unknown'fallback is hardcoded. Non-Chinese locales will get a mixed-language tooltip.As per coding guidelines,
web/src/**/*.{ts,tsx,js,jsx}: “Frontend i18n: Usei18next… Translation files inweb/src/i18n/locales/{lang}.jsonmust be flat JSON with Chinese source strings as keys.”🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx` around lines 144 - 151, The tooltip uses hardcoded Chinese strings and 'unknown', causing mixed-language output; update buildStreamStatusTooltip to call i18next t(...) for every user-facing token (replace "流状态", "异常", "软错误", and the 'unknown' fallback with t('流状态'), t('异常'), t('软错误'), t('未知') or similar Chinese-source keys) and then add those exact Chinese keys with appropriate translations into every locale JSON under web/src/i18n/locales/*.json (keep files flat JSON with Chinese source strings as keys) so all locales render the tooltip consistently.web/src/pages/Setting/Operation/SettingsGeneral.jsx-164-166 (1)
164-166:⚠️ Potential issue | 🟡 MinorSeveral new user-facing strings bypass i18n translation keys.
New literals like
USD ($),CNY (¥),Tokens,1 USD =, and preview text fragments are hardcoded instead of going throught('中文key'), which will cause partial non-localized UI.As per coding guidelines:
web/src/**/*.{ts,tsx,js,jsx}must use i18next and callt('中文key')in components.Also applies to: 188-193, 285-294, 305-307
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/pages/Setting/Operation/SettingsGeneral.jsx` around lines 164 - 166, The UI strings for quotaDisplayType and preview fragments are hardcoded and must use i18next; update the logic that checks quotaDisplayType (the branches returning 'USD ($)', 'CNY (¥)', 'Tokens', and the '1 USD = ' preview text and other preview fragments around lines noted) to call the translation function t('...') instead of literal strings, ensure the component imports and calls useTranslation() to get t, and replace each literal with an appropriate i18n key (e.g., t('settings.quota.usd'), t('settings.quota.cny'), t('settings.quota.tokens'), t('settings.quota.rate_prefix')) so all user-facing text in the quota display and preview (including the fragments at 188-193, 285-294, 305-307) is localized.web/src/components/table/channels/modals/EditChannelModal.jsx-1314-1321 (1)
1314-1321:⚠️ Potential issue | 🟡 MinorIgnore stale clipboard reads after the modal closes.
A
readText()started on open can resolve afterresetModalState()has already cleared the banner state, which lets an old clipboard result repopulateclipboardConfigfor the next session.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/components/table/channels/modals/EditChannelModal.jsx` around lines 1314 - 1321, A clipboard read started in the modal can finish after resetModalState() clears state and then incorrectly repopulate clipboardConfig; to fix, track the modal's mounted/open state (e.g., an isOpen or isMounted flag or ref set true when modal opens and false in resetModalState/when closing) and, after navigator?.clipboard?.readText().then(...), verify that the modal is still open before calling setClipboardConfig(parsed); ensure the flag is set to false in resetModalState so stale async clipboard results are ignored; reference navigator.clipboard.readText, parseChannelConnectionString, setClipboardConfig, and resetModalState when implementing the guard.web/src/components/table/channels/modals/EditChannelModal.jsx-550-563 (1)
550-563:⚠️ Potential issue | 🟡 MinorClipboard autofill bypasses the normal
base_urlvalidation path.
applyClipboardConfig()writesbase_urldirectly into state/form, so the existing/v1warning and any future field-specific guards inhandleInputChange('base_url', ...)never run for pasted configs.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/components/table/channels/modals/EditChannelModal.jsx` around lines 550 - 563, The clipboard autofill in applyClipboardConfig bypasses base_url validation; update applyClipboardConfig (and/or extract the base_url validation from handleInputChange) so it does not write base_url directly via setInputs or formApiRef.setValue — instead call the existing validation path (e.g., invoke handleInputChange('base_url', config.url) or a shared validateAndSetBaseUrl helper) and then set the key via setInputs/formApiRef; ensure you still clear setClipboardConfig(null) and call showSuccess after the validated value is applied.web/src/components/table/channels/modals/EditChannelModal.jsx-408-410 (1)
408-410:⚠️ Potential issue | 🟡 MinorThe advanced-settings preference can still drift out of sync.
The saved value restored here is still easy to override later:
loadChannel()can reopen the panel based on existing advanced fields, and the desktop close button still bypassestoggleAdvancedSettings(false). A user can explicitly collapse the panel and still see it reopen on the next edit.Also applies to: 1327-1329
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/components/table/channels/modals/EditChannelModal.jsx` around lines 408 - 410, The advanced-settings expanded state can be overridden later; ensure the persisted preference in ADVANCED_SETTINGS_EXPANDED_KEY is authoritative by (1) updating loadChannel to respect and short-circuit any auto-open logic when localStorage has an explicit value (read ADVANCED_SETTINGS_EXPANDED_KEY and skip reopening advanced settings even if channel has advanced fields), and (2) change any desktop close button handler that currently mutates state directly to call toggleAdvancedSettings(false) so it updates both setAdvancedSettingsOpen and localStorage; also mirror this fix where similar logic exists (the other toggle/load usage around the second occurrence) so collapse actions always persist.web/src/components/settings/SystemSetting.jsx-111-111 (1)
111-111:⚠️ Potential issue | 🟡 MinorNew default may not persist when option is missing from backend payload.
fetch_setting.apply_ip_filter_for_domainis initialized totrue, butgetOptions()later overwrites state withnewInputs. If the key is absent (older backend / partial config), the UI can fall back unintentionally.💡 Proposed fix
data.forEach((item) => { switch (item.key) { // ... } newInputs[item.key] = item.value; }); + if (typeof newInputs['fetch_setting.apply_ip_filter_for_domain'] === 'undefined') { + newInputs['fetch_setting.apply_ip_filter_for_domain'] = true; + } setInputs(newInputs); setOriginInputs(newInputs);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/components/settings/SystemSetting.jsx` at line 111, The default for fetch_setting.apply_ip_filter_for_domain is lost when getOptions() overwrites state with newInputs that may be missing that key; update getOptions() (in SystemSetting.jsx) to merge defaults with newInputs (or explicitly set fetch_setting.apply_ip_filter_for_domain = newInputs.fetch_setting?.apply_ip_filter_for_domain ?? inputs.fetch_setting?.apply_ip_filter_for_domain ?? true) so the existing state or the intended true default is preserved when the backend payload omits the key.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@common/gin.go`:
- Around line 231-234: The added TranslateMessage function sets a hardcoded
header "X-Translate-id" with a static SHA-like value which is unrelated to
Prometheus work and provides no per-request tracing; either remove the header
from TranslateMessage or replace it with a dynamic/correlation ID derived from
the request (e.g., from gin.Context.Request or a generated UUID) so each request
gets a unique value, and if this was for temporary debugging revert the change
and handle tracing in a separate PR.
In `@middleware/performance.go`:
- Line 4: The middleware currently returns client-facing errors that include
internal numeric details (host utilization, thresholds) — update the functions
in middleware/performance.go (e.g., PerformanceMiddleware, checkHostUtilization,
respondWithOverloadError or similar helpers referenced around lines 51–67) so
that responses sent to callers contain a generic message like "service
temporarily unavailable due to high load" or "server overloaded", while moving
the precise utilization and threshold values into internal logs/metrics (use
your logger, not the response). Remove or adjust any fmt-based formatting used
solely to construct client-visible messages (and drop the fmt import if no
longer needed). Ensure all occurrences noted (around lines 4, 51–53, 58–60,
65–67) follow this pattern.
In `@model/log.go`:
- Around line 61-62: formatUserLogs is currently not removing the
"reject_reason" key so GetUserLogs may expose admin-only details; update
formatUserLogs to either delete(otherMap, "reject_reason") when formatting
user-visible logs or add an explicit admin flag parameter to
formatUserLogs/GetUserLogs and only include "reject_reason" when that admin flag
is true. Ensure the change references the map being returned (otherMap) and that
callers of GetUserLogs pass the admin flag if you choose the gated approach.
In `@README.zh_TW.md`:
- Around line 73-88: The README change (README.zh_TW.md) adding a partner logo
is unrelated to the PR "[WIP] Add optional Prometheus metrics endpoint"; remove
or revert the logo changes from this branch and either move them into a separate
documentation-only PR or a different branch, and update this PR to only contain
metrics-related changes (ensure files/symbols implementing MetricsEnabled, the
metrics middleware, and the /metrics endpoint are included); alternatively, if
the README change is required for this work, update the PR description to
explain why and list the README modification alongside the MetricsEnabled flag,
metrics middleware, and /metrics endpoint implementations so reviewers can see
the rationale.
In `@relay/channel/task/doubao/adaptor.go`:
- Around line 250-258: The strconv.Atoi call must check and handle its error
instead of discarding it: parse req.Seconds into sec and if strconv.Atoi returns
an error, propagate or return that error (wrap with context) rather than
silently treating duration as zero so r.Duration (and callers) see malformed
input; use the same dto.IntValue/lo.ToPtr logic when no error. Also avoid
unconditionally rewriting text content: only remove existing "text" ContentItem
entries and append a new ContentItem with Type:"text" when req.Prompt is
non-empty (so r.Content and existing text items are preserved when req.Prompt ==
""), referencing the strconv.Atoi(req.Seconds) call, r.Duration, r.Content,
ContentItem, and req.Prompt to locate the changes.
In `@relay/common/stream_status.go`:
- Around line 31-39: Guard all accesses to StreamStatus.EndReason and
StreamStatus.EndError with the existing mutex (mu): modify SetEndReason (and any
helper that sets endOnce) to acquire mu before writing EndReason/EndError (while
still using endOnce to ensure single-set semantics), and update readers
IsNormalEnd, Summary, and any other places that read EndReason/EndError to
acquire mu for the duration of the read so readers see a consistent value;
ensure you hold mu when inspecting these fields and release it immediately
after, keeping endOnce for one-time semantics but using mu for memory ordering
and to prevent data races.
In `@relay/helper/stream_scanner.go`:
- Around line 197-203: The loop must guarantee writeMutex is unlocked even if
dataHandler panics: wrap the protected call in a short anonymous function that
does writeMutex.Lock(); defer writeMutex.Unlock(); then call dataHandler(data,
sr) (you can keep sr.reset() where it is or move it just before the call inside
the closure), so the defer always runs per-iteration; keep the subsequent
sr.IsStopped() check and newStreamResult usage unchanged.
In `@router/api-router.go`:
- Around line 39-42: The bind endpoints mutate the current account and
WeChatBind dereferences session.Get("id").(int) without auth, causing potential
panics; fix by requiring authentication on those routes—apply the UserAuth()
middleware to the POST bind handlers (EmailBind and WeChatBind) so they run
inside the authenticated group (leave WeChatAuth GET public), i.e., add
middleware.UserAuth() to the apiRouter.POST registrations for EmailBind and
WeChatBind to ensure session id exists before dereference.
In `@service/file_service.go`:
- Around line 494-568: The current code scans for the first "ispe" in
parseHEIFDimensions/findISPE which can return a non-primary image's dimensions;
instead, update parseHEIFDimensions to first parse the "meta" box to extract the
primary item id from the "pitm" full-box and then pass that primary item id into
a targeted search; implement helpers (e.g., findPrimaryItemID(metaData []byte)
and findISPEForPrimary(metaData []byte, primaryID int)) and change findISPE
signature to accept primaryID (or add a new findISPEForPrimary) so you resolve
ipma -> ipco mapping for the primary item and only return the ispe whose
property index is referenced by the primary item's property list, rather than
the first ispe encountered; keep function names parseHEIFDimensions and findISPE
(or add findISPEForPrimary/findPrimaryItemID) so the changes are easy to locate.
In `@service/image.go`:
- Around line 162-166: The unbounded io.ReadAll(reader) call can exhaust memory;
change the read to a bounded read using io.LimitReader and a configured max size
(e.g., MaxImageBytes or maxImageSize) so you only read up to the allowed image
size and detect overflow. Replace the io.ReadAll(reader) usage (the data,
readErr := io.ReadAll(reader) block) with a read via
io.ReadAll(io.LimitReader(reader, max+1)) or an equivalent streaming read that
enforces the limit, then return a clear error if the returned data length
exceeds the configured max; add a constant like MaxImageBytes and update the
error message to indicate the payload exceeded the maximum allowed size.
In `@web/src/index.css`:
- Around line 35-38: The global CSS rule setting body { overflow-y: hidden }
disables document scrolling on desktop and breaks pages that rely on document
scroll; instead, scope this overflow change to the VChart container by removing
or reverting the body rule and applying overflow-y: hidden to the VChart
host/container selector (e.g., the element wrapping the chart such as
.vchart-host or the specific chart container ID/class used in your app) so only
the chart's host disables its scrollbar while leaving document scrolling intact.
---
Outside diff comments:
In `@relay/channel/claude/relay-claude.go`:
- Around line 403-445: The switch currently ignores dto.ContentTypeFile causing
file attachments to be dropped; restore and implement the file handling branch
by adding a case for dto.ContentTypeFile that calls buildClaudeFileMessage(c,
mediaMessage.GetFile()), checks the returned error and returns it if present,
and appends the non-nil result to claudeMediaMessages (same pattern used for
images); also ensure that if buildClaudeFileMessage returns nil (unsupported
file type) you either return a clear error or mark the message as unsupported so
a file-only message does not produce an empty Claude content list.
In `@web/src/pages/Setting/Operation/SettingsGeneral.jsx`:
- Around line 209-217: The branch that sets
currentInputs['general_setting.quota_display_type'] only handles when
DisplayInCurrencyEnabled exists and otherwise leaves the value undefined; update
the logic in the SettingsGeneral component to provide a safe default when both
currentInputs['general_setting.quota_display_type'] and
props.options?.DisplayInCurrencyEnabled are undefined (for example set to
'TOKENS' or another app default). Locate the assignment to
currentInputs['general_setting.quota_display_type'] and ensure it uses
props.options.DisplayInCurrencyEnabled to choose between 'USD' and 'TOKENS', and
falls back to the chosen default when neither source is present so downstream
logic never sees undefined.
---
Minor comments:
In `@controller/user.go`:
- Around line 935-937: The error handling after common.DecodeJson should return
the project's standard "invalid-params" response instead of calling
common.ApiError with a hardcoded English string; replace the common.ApiError(c,
errors.New("invalid request body")) call with the shared invalid-params helper
used across controllers (e.g., common.InvalidParams(c) or the equivalent
localized helper) so client input validation is consistently reported and
localized.
In `@middleware/request-id.go`:
- Line 23: The request-id format was changed in middleware/request-id.go to
include _bp (id := common.GetTimeString() + _bp + common.GetRandomString(8)) but
relay/common/relay_info.go still builds fallbacks as reqId =
common.GetTimeString() + common.GetRandomString(8); update the relay fallback to
match the middleware format by including the same _bp insertion (derive or reuse
the same build-prefix logic used by middleware) so the fallback constructs reqId
as common.GetTimeString() + _bp + common.GetRandomString(8) (or remove the
fallback if you verify middleware always runs).
In `@web/src/components/settings/SystemSetting.jsx`:
- Line 111: The default for fetch_setting.apply_ip_filter_for_domain is lost
when getOptions() overwrites state with newInputs that may be missing that key;
update getOptions() (in SystemSetting.jsx) to merge defaults with newInputs (or
explicitly set fetch_setting.apply_ip_filter_for_domain =
newInputs.fetch_setting?.apply_ip_filter_for_domain ??
inputs.fetch_setting?.apply_ip_filter_for_domain ?? true) so the existing state
or the intended true default is preserved when the backend payload omits the
key.
In `@web/src/components/table/channels/modals/EditChannelModal.jsx`:
- Around line 1314-1321: A clipboard read started in the modal can finish after
resetModalState() clears state and then incorrectly repopulate clipboardConfig;
to fix, track the modal's mounted/open state (e.g., an isOpen or isMounted flag
or ref set true when modal opens and false in resetModalState/when closing) and,
after navigator?.clipboard?.readText().then(...), verify that the modal is still
open before calling setClipboardConfig(parsed); ensure the flag is set to false
in resetModalState so stale async clipboard results are ignored; reference
navigator.clipboard.readText, parseChannelConnectionString, setClipboardConfig,
and resetModalState when implementing the guard.
- Around line 550-563: The clipboard autofill in applyClipboardConfig bypasses
base_url validation; update applyClipboardConfig (and/or extract the base_url
validation from handleInputChange) so it does not write base_url directly via
setInputs or formApiRef.setValue — instead call the existing validation path
(e.g., invoke handleInputChange('base_url', config.url) or a shared
validateAndSetBaseUrl helper) and then set the key via setInputs/formApiRef;
ensure you still clear setClipboardConfig(null) and call showSuccess after the
validated value is applied.
- Around line 408-410: The advanced-settings expanded state can be overridden
later; ensure the persisted preference in ADVANCED_SETTINGS_EXPANDED_KEY is
authoritative by (1) updating loadChannel to respect and short-circuit any
auto-open logic when localStorage has an explicit value (read
ADVANCED_SETTINGS_EXPANDED_KEY and skip reopening advanced settings even if
channel has advanced fields), and (2) change any desktop close button handler
that currently mutates state directly to call toggleAdvancedSettings(false) so
it updates both setAdvancedSettingsOpen and localStorage; also mirror this fix
where similar logic exists (the other toggle/load usage around the second
occurrence) so collapse actions always persist.
In `@web/src/components/table/tokens/TokensColumnDefs.jsx`:
- Around line 150-178: The Button inside the Dropdown currently uses
aria-label='copy token key' which misrepresents the control; update the Button
in TokensColumnDefs.jsx (the Dropdown + Button combo) to use a label that
indicates it opens a menu (e.g. use t('open token actions menu') instead of
'copy token key'), add aria-haspopup="menu" and expose aria-expanded (bound to
the Dropdown open state or a local open boolean) so assistive tech announces
menu semantics, and keep stopPropagation; no change to the existing menu items
or their onClick handlers (copyTokenKey / copyTokenConnectionString).
In `@web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx`:
- Around line 144-151: The tooltip uses hardcoded Chinese strings and 'unknown',
causing mixed-language output; update buildStreamStatusTooltip to call i18next
t(...) for every user-facing token (replace "流状态", "异常", "软错误", and the
'unknown' fallback with t('流状态'), t('异常'), t('软错误'), t('未知') or similar
Chinese-source keys) and then add those exact Chinese keys with appropriate
translations into every locale JSON under web/src/i18n/locales/*.json (keep
files flat JSON with Chinese source strings as keys) so all locales render the
tooltip consistently.
In `@web/src/hooks/usage-logs/useUsageLogsData.jsx`:
- Line 608: The fallback literal 'unknown' bypasses i18n; inside the
useUsageLogsData hook/component call useTranslation() and replace the inline
fallback in the streamValue construction (the variable streamValue that uses
ss.end_reason) with a translated key, e.g. t('未知'), so that streamValue becomes
statusLabel + ' (' + (ss.end_reason || t('未知')) + ')'; ensure useTranslation is
imported from react-i18next and invoked (const { t } = useTranslation()) at the
top of the useUsageLogsData scope so t is available where streamValue is formed.
In `@web/src/pages/Setting/Operation/SettingsGeneral.jsx`:
- Around line 164-166: The UI strings for quotaDisplayType and preview fragments
are hardcoded and must use i18next; update the logic that checks
quotaDisplayType (the branches returning 'USD ($)', 'CNY (¥)', 'Tokens', and the
'1 USD = ' preview text and other preview fragments around lines noted) to call
the translation function t('...') instead of literal strings, ensure the
component imports and calls useTranslation() to get t, and replace each literal
with an appropriate i18n key (e.g., t('settings.quota.usd'),
t('settings.quota.cny'), t('settings.quota.tokens'),
t('settings.quota.rate_prefix')) so all user-facing text in the quota display
and preview (including the fragments at 188-193, 285-294, 305-307) is localized.
🪄 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: 8dd66225-df93-4e7a-9231-f01568ea4a07
⛔ Files ignored due to path filters (2)
electron/package-lock.jsonis excluded by!**/package-lock.jsongo.sumis excluded by!**/*.sum
📒 Files selected for processing (66)
README.zh_TW.mdcommon/gin.gocontroller/misc.gocontroller/pricing.gocontroller/user.gocontroller/video_proxy.gocontroller/wechat.godto/openai_image.gogo.modmiddleware/performance.gomiddleware/request-id.gomodel/log.gorelay/channel/ali/dto.gorelay/channel/ali/image.gorelay/channel/ali/image_wan.gorelay/channel/baidu/relay-baidu.gorelay/channel/claude/relay-claude.gorelay/channel/claude/relay_claude_test.gorelay/channel/dify/relay-dify.gorelay/channel/gemini/relay-gemini.gorelay/channel/openai/audio.gorelay/channel/openai/chat_via_responses.gorelay/channel/openai/relay-openai.gorelay/channel/openai/relay_responses.gorelay/channel/task/doubao/adaptor.gorelay/channel/task/doubao/constants.gorelay/channel/task/taskcommon/helpers.gorelay/channel/xai/adaptor.gorelay/channel/xai/text.gorelay/common/relay_info.gorelay/common/stream_status.gorelay/common/stream_status_test.gorelay/helper/stream_result.gorelay/helper/stream_scanner.gorelay/helper/stream_scanner_test.gorelay/image_handler.gorelay/mjproxy_handler.gorouter/api-router.goservice/file_decoder.goservice/file_service.goservice/image.goservice/log_info_generate.gosetting/model_setting/qwen.gosetting/system_setting/fetch_setting.goweb/src/components/layout/Footer.jsxweb/src/components/settings/PersonalSetting.jsxweb/src/components/settings/SystemSetting.jsxweb/src/components/table/channels/modals/EditChannelModal.jsxweb/src/components/table/tokens/TokensColumnDefs.jsxweb/src/components/table/tokens/TokensTable.jsxweb/src/components/table/usage-logs/UsageLogsColumnDefs.jsxweb/src/helpers/token.jsweb/src/hooks/tokens/useTokensData.jsxweb/src/hooks/usage-logs/useUsageLogsData.jsxweb/src/i18n/i18n.jsweb/src/i18n/locales/en.jsonweb/src/i18n/locales/fr.jsonweb/src/i18n/locales/ja.jsonweb/src/i18n/locales/ru.jsonweb/src/i18n/locales/vi.jsonweb/src/i18n/locales/zh-CN.jsonweb/src/i18n/locales/zh-TW.jsonweb/src/index.cssweb/src/pages/Setting/Operation/SettingsChannelAffinity.jsxweb/src/pages/Setting/Operation/SettingsGeneral.jsxweb/src/pages/Setting/Performance/SettingsPerformance.jsx
💤 Files with no reviewable changes (1)
- web/src/pages/Setting/Performance/SettingsPerformance.jsx
✅ Files skipped from review due to trivial changes (5)
- controller/pricing.go
- relay/channel/task/doubao/constants.go
- setting/model_setting/qwen.go
- web/src/helpers/token.js
- setting/system_setting/fetch_setting.go
| TranslateMessage = func(c *gin.Context, key string, args ...map[string]any) string { | ||
| c.Header("X-Translate-id", "d5e7afdfc7f03414b941f9c1e7096be9966510e7") | ||
| return key | ||
| } |
There was a problem hiding this comment.
This change appears unrelated to Prometheus metrics and may be debug code.
The addition of a hardcoded X-Translate-id header with a static SHA-1-like value doesn't align with the PR's stated objective of adding a Prometheus metrics endpoint. A fixed value provides no tracing benefit since it's identical for every request.
If this is intended for debugging or tracing:
- The value should be dynamic (e.g., request-specific ID or correlation ID)
- Consider removing it from this PR and addressing it separately
If this was committed accidentally, please remove it.
,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@common/gin.go` around lines 231 - 234, The added TranslateMessage function
sets a hardcoded header "X-Translate-id" with a static SHA-like value which is
unrelated to Prometheus work and provides no per-request tracing; either remove
the header from TranslateMessage or replace it with a dynamic/correlation ID
derived from the request (e.g., from gin.Context.Request or a generated UUID) so
each request gets a unique value, and if this was for temporary debugging revert
the change and handle tracing in a separate PR.
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" |
There was a problem hiding this comment.
Avoid exposing host utilization and threshold values in client-facing errors.
These messages now disclose internal resource levels and configured limits to callers. Keep external error text generic and move detailed values to internal logs/metrics only.
🔧 Proposed patch (generic client errors)
import (
- "fmt"
+ "errors"
"net/http"
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
)
@@
if config.CPUThreshold > 0 && int(status.CPUUsage) > config.CPUThreshold {
return types.NewErrorWithStatusCode(
- fmt.Errorf("system cpu overloaded (current: %.1f%%, threshold: %d%%)", status.CPUUsage, config.CPUThreshold),
+ errors.New("system cpu overloaded"),
"system_cpu_overloaded", http.StatusServiceUnavailable)
}
@@
if config.MemoryThreshold > 0 && int(status.MemoryUsage) > config.MemoryThreshold {
return types.NewErrorWithStatusCode(
- fmt.Errorf("system memory overloaded (current: %.1f%%, threshold: %d%%)", status.MemoryUsage, config.MemoryThreshold),
+ errors.New("system memory overloaded"),
"system_memory_overloaded", http.StatusServiceUnavailable)
}
@@
if config.DiskThreshold > 0 && int(status.DiskUsage) > config.DiskThreshold {
return types.NewErrorWithStatusCode(
- fmt.Errorf("system disk overloaded (current: %.1f%%, threshold: %d%%)", status.DiskUsage, config.DiskThreshold),
+ errors.New("system disk overloaded"),
"system_disk_overloaded", http.StatusServiceUnavailable)
}Also applies to: 51-53, 58-60, 65-67
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@middleware/performance.go` at line 4, The middleware currently returns
client-facing errors that include internal numeric details (host utilization,
thresholds) — update the functions in middleware/performance.go (e.g.,
PerformanceMiddleware, checkHostUtilization, respondWithOverloadError or similar
helpers referenced around lines 51–67) so that responses sent to callers contain
a generic message like "service temporarily unavailable due to high load" or
"server overloaded", while moving the precise utilization and threshold values
into internal logs/metrics (use your logger, not the response). Remove or adjust
any fmt-based formatting used solely to construct client-visible messages (and
drop the fmt import if no longer needed). Ensure all occurrences noted (around
lines 4, 51–53, 58–60, 65–67) follow this pattern.
| // delete(otherMap, "reject_reason") | ||
| delete(otherMap, "stream_status") |
There was a problem hiding this comment.
Re-hide reject_reason in user log responses.
Line 61 currently stops filtering reject_reason, so GetUserLogs can return admin-only rejection details to regular users via API. Please keep this field removed in formatUserLogs (or gate it with an explicit admin flag).
Suggested fix
- // delete(otherMap, "reject_reason")
+ delete(otherMap, "reject_reason")
delete(otherMap, "stream_status")📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // delete(otherMap, "reject_reason") | |
| delete(otherMap, "stream_status") | |
| delete(otherMap, "reject_reason") | |
| delete(otherMap, "stream_status") |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@model/log.go` around lines 61 - 62, formatUserLogs is currently not removing
the "reject_reason" key so GetUserLogs may expose admin-only details; update
formatUserLogs to either delete(otherMap, "reject_reason") when formatting
user-visible logs or add an explicit admin flag parameter to
formatUserLogs/GetUserLogs and only include "reject_reason" when that admin flag
is true. Ensure the change references the map being returned (otherMap) and that
callers of GetUserLogs pass the admin flag if you choose the gated approach.
| </a><!-- | ||
| --><a href="https://github.com/iOfficeAI/AionUi/" target="_blank"> | ||
| <img src="./docs/images/aionui.png" alt="Aion UI" height="80" /> | ||
| </a><!-- | ||
| --><a href="https://bda.pku.edu.cn/" target="_blank"> | ||
| <img src="./docs/images/pku.png" alt="北京大學" height="80" /> | ||
| </a> | ||
| <a href="https://www.compshare.cn/?ytag=GPU_yy_gh_newapi" target="_blank"> | ||
| </a><!-- | ||
| --><a href="https://www.compshare.cn/?ytag=GPU_yy_gh_newapi" target="_blank"> | ||
| <img src="./docs/images/ucloud.png" alt="UCloud 優刻得" height="80" /> | ||
| </a> | ||
| <a href="https://www.aliyun.com/" target="_blank"> | ||
| </a><!-- | ||
| --><a href="https://www.aliyun.com/" target="_blank"> | ||
| <img src="./docs/images/aliyun.png" alt="阿里雲" height="80" /> | ||
| </a> | ||
| <a href="https://io.net/" target="_blank"> | ||
| </a><!-- | ||
| --><a href="https://io.net/" target="_blank"> | ||
| <img src="./docs/images/io-net.png" alt="IO.NET" height="80" /> | ||
| </a> |
There was a problem hiding this comment.
CRITICAL: File changes are unrelated to PR objectives.
This PR is titled "[WIP] Add optional Prometheus metrics endpoint" and the stated objectives focus entirely on implementing Prometheus metrics collection, Grafana monitoring, and exposing metrics endpoints for operational visibility. However, this file contains only documentation changes to add a partner logo in the README carousel.
The changes in README.zh_TW.md have no connection to:
- Prometheus metrics implementation
MetricsEnabledconfiguration flag- Metrics middleware or
/metricsendpoint - Request/response instrumentation
- Monitoring or observability features
Action required:
- If these README changes are intentional, they should be moved to a separate PR focused on documentation updates
- If the actual metrics implementation code exists, ensure those files are included in this review
- The PR description should clarify why unrelated documentation changes are included
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@README.zh_TW.md` around lines 73 - 88, The README change (README.zh_TW.md)
adding a partner logo is unrelated to the PR "[WIP] Add optional Prometheus
metrics endpoint"; remove or revert the logo changes from this branch and either
move them into a separate documentation-only PR or a different branch, and
update this PR to only contain metrics-related changes (ensure files/symbols
implementing MetricsEnabled, the metrics middleware, and the /metrics endpoint
are included); alternatively, if the README change is required for this work,
update the PR description to explain why and list the README modification
alongside the MetricsEnabled flag, metrics middleware, and /metrics endpoint
implementations so reviewers can see the rationale.
| if sec, _ := strconv.Atoi(req.Seconds); sec > 0 { | ||
| r.Duration = lo.ToPtr(dto.IntValue(sec)) | ||
| } | ||
|
|
||
| r.Content = lo.Reject(r.Content, func(c ContentItem, _ int) bool { return c.Type == "text" }) | ||
| r.Content = append(r.Content, ContentItem{ | ||
| Type: "text", | ||
| Text: req.Prompt, | ||
| }) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo 'TaskSubmitReq definition:'
ast-grep --lang go --pattern $'type TaskSubmitReq struct { $$$ }'
echo
echo 'Validation / usage sites for Prompt and Seconds:'
rg -n -C5 'func\s+ValidateBasicTaskRequest\s*\(|\.Prompt\b|\.Seconds\b' --type=go | sed -n '1,200p'Repository: QuantumNous/new-api
Length of output: 1767
🏁 Script executed:
# Request context from provided code - try alternative approach
# Check if we can find the file through git ls-files
git ls-files '**/adaptor.go' 2>/dev/null | head -20Repository: QuantumNous/new-api
Length of output: 1852
🌐 Web query:
Best practices for error handling with strconv.Atoi in Go - should errors be silently ignored
💡 Result:
No, errors from strconv.Atoi should not be silently ignored. Go's philosophy treats errors as values that must be explicitly handled to ensure robust programs. strconv.Atoi returns (int, error) and can fail with strconv.ErrSyntax for invalid syntax or strconv.ErrRange for out-of-range values. Official Go documentation and best practices emphasize checking errors: - Effective Go: "Occasionally you'll see code that discards the error value in order to ignore the error; this is terrible practice." - Go Blog "Errors are values": Always check errors; program with error values rather than rote if err != nil. - Error handling articles: Explicit checking where errors occur; handle or propagate with context using fmt.Errorf("%w", err). Tools like errcheck and golangci-lint detect unchecked errors, including assignments to _ with strconv.Atoi. Example of proper handling: i, err := strconv.Atoi(s) if err != nil { // Handle: return fmt.Errorf("invalid integer %q: %w", s, err), log, use default, etc. } Silently ignoring (e.g., _, _ := strconv.Atoi(s)) hides bugs like invalid user input, leading to incorrect behavior or panics later.
Citations:
- 1: https://reintech.io/blog/a-guide-to-gos-strconv-package-converting-strings-and-numbers
- 2: https://go.dev/src/strconv/atoi.go?h=Error
- 3: https://pkg.go.dev/strconv
- 4: https://go.dev/doc/articles/error_handling.html
- 5: https://go.dev/doc/effective%5Fgo
- 6: https://go.dev/blog/errors-are-values
- 7: https://go.dev/blog/go1.13-errors
- 8: https://go.dev/blog/error-handling-and-go
- 9: https://golangci.github.io/legacy-v1-doc/usage/linters/
- 10: https://pkg.go.dev/github.com/golangci/errcheck
- 11: https://github.com/kisielk/errcheck
Handle strconv.Atoi error instead of silently ignoring it.
Discarding the error from strconv.Atoi(req.Seconds) violates Go best practices and hides bugs. Malformed req.Seconds values will silently default to 0, dropping the requested duration without feedback. Go's official documentation (Effective Go, Error Handling article) explicitly warns against this pattern. Always check and propagate the error.
Additionally, the code unconditionally rewrites all text content when req.Prompt is provided. If req.Prompt is empty, this removes any existing text items and appends an incomplete {"type":"text"} item (with no Text field due to omitempty), which may not be intentional.
🔧 Suggested fix
- if sec, _ := strconv.Atoi(req.Seconds); sec > 0 {
- r.Duration = lo.ToPtr(dto.IntValue(sec))
- }
-
- r.Content = lo.Reject(r.Content, func(c ContentItem, _ int) bool { return c.Type == "text" })
- r.Content = append(r.Content, ContentItem{
- Type: "text",
- Text: req.Prompt,
- })
+ if req.Seconds != "" {
+ sec, err := strconv.Atoi(req.Seconds)
+ if err != nil {
+ return nil, errors.Wrap(err, "invalid seconds")
+ }
+ if sec > 0 {
+ r.Duration = lo.ToPtr(dto.IntValue(sec))
+ }
+ }
+
+ if req.Prompt != "" {
+ r.Content = lo.Reject(r.Content, func(c ContentItem, _ int) bool { return c.Type == "text" })
+ r.Content = append(r.Content, ContentItem{
+ Type: "text",
+ Text: req.Prompt,
+ })
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if sec, _ := strconv.Atoi(req.Seconds); sec > 0 { | |
| r.Duration = lo.ToPtr(dto.IntValue(sec)) | |
| } | |
| r.Content = lo.Reject(r.Content, func(c ContentItem, _ int) bool { return c.Type == "text" }) | |
| r.Content = append(r.Content, ContentItem{ | |
| Type: "text", | |
| Text: req.Prompt, | |
| }) | |
| if req.Seconds != "" { | |
| sec, err := strconv.Atoi(req.Seconds) | |
| if err != nil { | |
| return nil, errors.Wrap(err, "invalid seconds") | |
| } | |
| if sec > 0 { | |
| r.Duration = lo.ToPtr(dto.IntValue(sec)) | |
| } | |
| } | |
| if req.Prompt != "" { | |
| r.Content = lo.Reject(r.Content, func(c ContentItem, _ int) bool { return c.Type == "text" }) | |
| r.Content = append(r.Content, ContentItem{ | |
| Type: "text", | |
| Text: req.Prompt, | |
| }) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@relay/channel/task/doubao/adaptor.go` around lines 250 - 258, The
strconv.Atoi call must check and handle its error instead of discarding it:
parse req.Seconds into sec and if strconv.Atoi returns an error, propagate or
return that error (wrap with context) rather than silently treating duration as
zero so r.Duration (and callers) see malformed input; use the same
dto.IntValue/lo.ToPtr logic when no error. Also avoid unconditionally rewriting
text content: only remove existing "text" ContentItem entries and append a new
ContentItem with Type:"text" when req.Prompt is non-empty (so r.Content and
existing text items are preserved when req.Prompt == ""), referencing the
strconv.Atoi(req.Seconds) call, r.Duration, r.Content, ContentItem, and
req.Prompt to locate the changes.
| sr := newStreamResult(info.StreamStatus) | ||
| for data := range dataChan { | ||
| sr.reset() | ||
| writeMutex.Lock() | ||
| success := dataHandler(data) | ||
| dataHandler(data, sr) | ||
| writeMutex.Unlock() | ||
| if !success { | ||
| if sr.IsStopped() { |
There was a problem hiding this comment.
Always unlock writeMutex when the handler panics.
If dataHandler panics here, the goroutine-level recover runs before writeMutex.Unlock() and leaves the mutex locked forever. That can leak blocked write work and force the request cleanup path to hit its 5-second timeout.
🐛 Suggested fix
for data := range dataChan {
sr.reset()
- writeMutex.Lock()
- dataHandler(data, sr)
- writeMutex.Unlock()
+ func() {
+ writeMutex.Lock()
+ defer writeMutex.Unlock()
+ dataHandler(data, sr)
+ }()
if sr.IsStopped() {
return
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| sr := newStreamResult(info.StreamStatus) | |
| for data := range dataChan { | |
| sr.reset() | |
| writeMutex.Lock() | |
| success := dataHandler(data) | |
| dataHandler(data, sr) | |
| writeMutex.Unlock() | |
| if !success { | |
| if sr.IsStopped() { | |
| sr := newStreamResult(info.StreamStatus) | |
| for data := range dataChan { | |
| sr.reset() | |
| func() { | |
| writeMutex.Lock() | |
| defer writeMutex.Unlock() | |
| dataHandler(data, sr) | |
| }() | |
| if sr.IsStopped() { |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@relay/helper/stream_scanner.go` around lines 197 - 203, The loop must
guarantee writeMutex is unlocked even if dataHandler panics: wrap the protected
call in a short anonymous function that does writeMutex.Lock(); defer
writeMutex.Unlock(); then call dataHandler(data, sr) (you can keep sr.reset()
where it is or move it just before the call inside the closure), so the defer
always runs per-iteration; keep the subsequent sr.IsStopped() check and
newStreamResult usage unchanged.
| apiRouter.POST("/oauth/email/bind", middleware.CriticalRateLimit(), controller.EmailBind) | ||
| // Non-standard OAuth (WeChat, Telegram) - keep original routes | ||
| apiRouter.GET("/oauth/wechat", middleware.CriticalRateLimit(), controller.WeChatAuth) | ||
| apiRouter.GET("/oauth/wechat/bind", middleware.CriticalRateLimit(), controller.WeChatBind) | ||
| apiRouter.POST("/oauth/wechat/bind", middleware.CriticalRateLimit(), controller.WeChatBind) |
There was a problem hiding this comment.
Require auth on the bind endpoints.
These routes still sit outside UserAuth(), but they mutate the current account. WeChatBind immediately dereferences session.Get("id").(int), so an unauthenticated POST can still hit a panic path instead of being rejected cleanly.
🔐 Minimal fix
- apiRouter.POST("/oauth/email/bind", middleware.CriticalRateLimit(), controller.EmailBind)
+ apiRouter.POST("/oauth/email/bind", middleware.CriticalRateLimit(), middleware.UserAuth(), controller.EmailBind)
...
- apiRouter.POST("/oauth/wechat/bind", middleware.CriticalRateLimit(), controller.WeChatBind)
+ apiRouter.POST("/oauth/wechat/bind", middleware.CriticalRateLimit(), middleware.UserAuth(), controller.WeChatBind)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| apiRouter.POST("/oauth/email/bind", middleware.CriticalRateLimit(), controller.EmailBind) | |
| // Non-standard OAuth (WeChat, Telegram) - keep original routes | |
| apiRouter.GET("/oauth/wechat", middleware.CriticalRateLimit(), controller.WeChatAuth) | |
| apiRouter.GET("/oauth/wechat/bind", middleware.CriticalRateLimit(), controller.WeChatBind) | |
| apiRouter.POST("/oauth/wechat/bind", middleware.CriticalRateLimit(), controller.WeChatBind) | |
| apiRouter.POST("/oauth/email/bind", middleware.CriticalRateLimit(), middleware.UserAuth(), controller.EmailBind) | |
| // Non-standard OAuth (WeChat, Telegram) - keep original routes | |
| apiRouter.GET("/oauth/wechat", middleware.CriticalRateLimit(), controller.WeChatAuth) | |
| apiRouter.POST("/oauth/wechat/bind", middleware.CriticalRateLimit(), middleware.UserAuth(), controller.WeChatBind) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@router/api-router.go` around lines 39 - 42, The bind endpoints mutate the
current account and WeChatBind dereferences session.Get("id").(int) without
auth, causing potential panics; fix by requiring authentication on those
routes—apply the UserAuth() middleware to the POST bind handlers (EmailBind and
WeChatBind) so they run inside the authenticated group (leave WeChatAuth GET
public), i.e., add middleware.UserAuth() to the apiRouter.POST registrations for
EmailBind and WeChatBind to ensure session id exists before dereference.
| // parseHEIFDimensions parses ISOBMFF box tree to find the ispe box | ||
| // and extract image width/height. Returns (width, height, ok). | ||
| func parseHEIFDimensions(data []byte) (int, int, bool) { | ||
| size := len(data) | ||
| if size < 12 { | ||
| return 0, 0, false | ||
| } | ||
|
|
||
| // Walk top-level boxes to find "meta" | ||
| offset := 0 | ||
| for offset+8 <= size { | ||
| boxSize := int(binary.BigEndian.Uint32(data[offset : offset+4])) | ||
| boxType := string(data[offset+4 : offset+8]) | ||
| headerLen := 8 | ||
|
|
||
| if boxSize == 1 { | ||
| // 64-bit extended size | ||
| if offset+16 > size { | ||
| break | ||
| } | ||
| boxSize = int(binary.BigEndian.Uint64(data[offset+8 : offset+16])) | ||
| headerLen = 16 | ||
| } else if boxSize == 0 { | ||
| // box extends to end of data | ||
| boxSize = size - offset | ||
| } | ||
|
|
||
| if boxSize < headerLen || offset+boxSize > size { | ||
| break | ||
| } | ||
|
|
||
| if boxType == "meta" { | ||
| // meta is a full box: 4 bytes version/flags after header | ||
| metaData := data[offset+headerLen : offset+boxSize] | ||
| if len(metaData) < 4 { | ||
| return 0, 0, false | ||
| } | ||
| return findISPE(metaData[4:]) | ||
| } | ||
| offset += boxSize | ||
| } | ||
| return 0, 0, false | ||
| } | ||
|
|
||
| // findISPE recursively searches for the ispe box within container boxes. | ||
| // Path: meta -> iprp -> ipco -> ispe | ||
| func findISPE(data []byte) (int, int, bool) { | ||
| offset := 0 | ||
| size := len(data) | ||
| for offset+8 <= size { | ||
| boxSize := int(binary.BigEndian.Uint32(data[offset : offset+4])) | ||
| boxType := string(data[offset+4 : offset+8]) | ||
| if boxSize < 8 || offset+boxSize > size { | ||
| break | ||
| } | ||
| content := data[offset+8 : offset+boxSize] | ||
| switch boxType { | ||
| case "iprp", "ipco": | ||
| if w, h, ok := findISPE(content); ok { | ||
| return w, h, true | ||
| } | ||
| case "ispe": | ||
| // ispe is a full box: 4 bytes version/flags, then 4 bytes width, 4 bytes height | ||
| if len(content) >= 12 { | ||
| w := int(binary.BigEndian.Uint32(content[4:8])) | ||
| h := int(binary.BigEndian.Uint32(content[8:12])) | ||
| if w > 0 && h > 0 { | ||
| return w, h, true | ||
| } | ||
| } | ||
| } | ||
| offset += boxSize | ||
| } | ||
| return 0, 0, false | ||
| } |
There was a problem hiding this comment.
Resolve HEIF dimensions from the primary item, not the first ispe.
ipco is only a shared property container. Scanning until the first ispe ignores pitm/ipma, so multi-image HEIFs can easily return thumbnail or auxiliary-item dimensions instead of the primary image size. That will leak wrong width/height into downstream validation and any size-based accounting.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@service/file_service.go` around lines 494 - 568, The current code scans for
the first "ispe" in parseHEIFDimensions/findISPE which can return a non-primary
image's dimensions; instead, update parseHEIFDimensions to first parse the
"meta" box to extract the primary item id from the "pitm" full-box and then pass
that primary item id into a targeted search; implement helpers (e.g.,
findPrimaryItemID(metaData []byte) and findISPEForPrimary(metaData []byte,
primaryID int)) and change findISPE signature to accept primaryID (or add a new
findISPEForPrimary) so you resolve ipma -> ipco mapping for the primary item and
only return the ispe whose property index is referenced by the primary item's
property list, rather than the first ispe encountered; keep function names
parseHEIFDimensions and findISPE (or add findISPEForPrimary/findPrimaryItemID)
so the changes are easy to locate.
| // Read all data so we can retry with different decoders | ||
| data, readErr := io.ReadAll(reader) | ||
| if readErr != nil { | ||
| return image.Config{}, "", fmt.Errorf("failed to read image data: %w", readErr) | ||
| } |
There was a problem hiding this comment.
Bound full-stream reads to prevent memory exhaustion.
io.ReadAll(reader) is now unbounded. In URL-based paths this can read arbitrarily large remote payloads into memory and is a DoS risk.
💡 Proposed fix
+const maxImageConfigBytes = int64(constant.MaxFileDownloadMB * 1024 * 1024)
+
func getImageConfig(reader io.Reader) (image.Config, string, error) {
// Read all data so we can retry with different decoders
- data, readErr := io.ReadAll(reader)
+ data, readErr := io.ReadAll(io.LimitReader(reader, maxImageConfigBytes+1))
if readErr != nil {
return image.Config{}, "", fmt.Errorf("failed to read image data: %w", readErr)
}
+ if int64(len(data)) > maxImageConfigBytes {
+ return image.Config{}, "", fmt.Errorf("image size exceeds maximum allowed size of %d bytes", maxImageConfigBytes)
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Read all data so we can retry with different decoders | |
| data, readErr := io.ReadAll(reader) | |
| if readErr != nil { | |
| return image.Config{}, "", fmt.Errorf("failed to read image data: %w", readErr) | |
| } | |
| const maxImageConfigBytes = int64(constant.MaxFileDownloadMB * 1024 * 1024) | |
| func getImageConfig(reader io.Reader) (image.Config, string, error) { | |
| // Read all data so we can retry with different decoders | |
| data, readErr := io.ReadAll(io.LimitReader(reader, maxImageConfigBytes+1)) | |
| if readErr != nil { | |
| return image.Config{}, "", fmt.Errorf("failed to read image data: %w", readErr) | |
| } | |
| if int64(len(data)) > maxImageConfigBytes { | |
| return image.Config{}, "", fmt.Errorf("image size exceeds maximum allowed size of %d bytes", maxImageConfigBytes) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@service/image.go` around lines 162 - 166, The unbounded io.ReadAll(reader)
call can exhaust memory; change the read to a bounded read using io.LimitReader
and a configured max size (e.g., MaxImageBytes or maxImageSize) so you only read
up to the allowed image size and detect overflow. Replace the io.ReadAll(reader)
usage (the data, readErr := io.ReadAll(reader) block) with a read via
io.ReadAll(io.LimitReader(reader, max+1)) or an equivalent streaming read that
enforces the limit, then return a clear error if the returned data length
exceeds the configured max; add a constant like MaxImageBytes and update the
error message to indicate the payload exceeded the maximum allowed size.
| @media (min-width: 768px) { | ||
| body { | ||
| overflow-y: hidden; | ||
| } |
There was a problem hiding this comment.
Don't disable document scrolling globally on desktop.
body { overflow-y: hidden; } removes the fallback scroller for the entire desktop app. Any screen that still relies on document scroll — including the new in-flow footer and pages without their own scroll container — can become unreachable. Please scope this workaround to the VChart host/container instead of body.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@web/src/index.css` around lines 35 - 38, The global CSS rule setting body {
overflow-y: hidden } disables document scrolling on desktop and breaks pages
that rely on document scroll; instead, scope this overflow change to the VChart
container by removing or reverting the body rule and applying overflow-y: hidden
to the VChart host/container selector (e.g., the element wrapping the chart such
as .vchart-host or the specific chart container ID/class used in your app) so
only the chart's host disables its scrollbar while leaving document scrolling
intact.
Signed-off-by: Camber Huang <[email protected]>
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 `@controller/relay.go`:
- Around line 82-97: The deferred metrics block currently records
channel-labeled metrics once at the outer request scope using variables
(relayChannelID, relayStart, newAPIError) that get overwritten across retries;
move per-attempt recording into the retry/attempt scope so each attempt records
its own metrics immediately after the attempt completes: inside the loop where
relayChannelID, attempt start time (relayStart or new local start), and
newAPIError are set, call metrics.RecordRelayRequest(relayModelLabel,
relayChannelID, statusCode) and
metrics.ObserveRelayRequestDuration(relayModelLabel, relayChannelID,
attemptStart) using that attempt's values; keep a separate outer/deferred metric
for end-to-end request only (no channel-specific label) and remove
channel-specific recording from the outer defer to avoid double-counting and
mislabeled durations.
In `@service/text_quota.go`:
- Line 328: recordRelayTokenMetrics is being passed billing-adjusted/estimated
values (summary.PromptTokens and summary.CompletionTokens); instead, when
UsageSource is present use the normalized explicit totals (e.g.,
usage.InputTokens and the corresponding normalized output total) and only fall
back to summary.PromptTokens/summary.CompletionTokens for legacy paths. Update
the call site that invokes recordRelayTokenMetrics to supply explicit usage
totals when available (check UsageSource and use usage.InputTokens for input
tokens and the normalized output token field for completion tokens), otherwise
fallback to the existing summary.*Tokens values.
🪄 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: d0d929b5-970d-46c5-8fa1-11d74ad2490a
📒 Files selected for processing (5)
controller/relay.gometrics/relay.gorelay/common/relay_info.goservice/quota.goservice/text_quota.go
🚧 Files skipped from review as they are similar to previous changes (1)
- relay/common/relay_info.go
| defer func() { | ||
| if !metrics.RelayMetricsEnabled { | ||
| return | ||
| } | ||
|
|
||
| statusCode := c.Writer.Status() | ||
| if newAPIError != nil && newAPIError.StatusCode != 0 { | ||
| statusCode = newAPIError.StatusCode | ||
| } | ||
| if statusCode == 0 { | ||
| statusCode = http.StatusOK | ||
| } | ||
|
|
||
| metrics.RecordRelayRequest(relayModelLabel, relayChannelID, statusCode) | ||
| metrics.ObserveRelayRequestDuration(relayModelLabel, relayChannelID, relayStart) | ||
| }() |
There was a problem hiding this comment.
Channel-labeled metrics are being recorded at the wrong scope.
At Lines 82-97 and Line 220, the deferred recorder runs once for the whole outer request while relayChannelID is overwritten on each retry. A request that fails on channel A and then succeeds on channel B will only emit one sample for B, and its duration includes time spent on A, so channel-level error-rate and latency dashboards will be misleading; please record channel-labeled metrics per attempt and keep any end-to-end metric separate.
Also applies to: 220-220
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@controller/relay.go` around lines 82 - 97, The deferred metrics block
currently records channel-labeled metrics once at the outer request scope using
variables (relayChannelID, relayStart, newAPIError) that get overwritten across
retries; move per-attempt recording into the retry/attempt scope so each attempt
records its own metrics immediately after the attempt completes: inside the loop
where relayChannelID, attempt start time (relayStart or new local start), and
newAPIError are set, call metrics.RecordRelayRequest(relayModelLabel,
relayChannelID, statusCode) and
metrics.ObserveRelayRequestDuration(relayModelLabel, relayChannelID,
attemptStart) using that attempt's values; keep a separate outer/deferred metric
for end-to-end request only (no channel-specific label) and remove
channel-specific recording from the outer defer to avoid double-counting and
mislabeled durations.
| } else { | ||
| model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, summary.Quota) | ||
| model.UpdateChannelUsedQuota(relayInfo.ChannelId, summary.Quota) | ||
| recordRelayTokenMetrics(relayInfo, summary.PromptTokens, summary.CompletionTokens) |
There was a problem hiding this comment.
Don't export billing-adjusted summary.*Tokens as usage totals.
At Line 328, summary.PromptTokens is already mutated for some billing paths (Lines 120-130) and can even fall back to estimated prompt tokens when upstream usage is missing. Since this file later treats usage.InputTokens as the only reliable normalized input total when UsageSource is present (Lines 409-415), the new relay token counters will under-report cached/normalized traffic and may count estimates as real usage unless this uses explicit usage totals with a legacy fallback.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@service/text_quota.go` at line 328, recordRelayTokenMetrics is being passed
billing-adjusted/estimated values (summary.PromptTokens and
summary.CompletionTokens); instead, when UsageSource is present use the
normalized explicit totals (e.g., usage.InputTokens and the corresponding
normalized output total) and only fall back to
summary.PromptTokens/summary.CompletionTokens for legacy paths. Update the call
site that invokes recordRelayTokenMetrics to supply explicit usage totals when
available (check UsageSource and use usage.InputTokens for input tokens and the
normalized output token field for completion tokens), otherwise fallback to the
existing summary.*Tokens values.
51fdfc5 to
2b6f1df
Compare
目前正在试着添加原生的指标endpoint
后续会补上相关设计
close #961
close #2402
[ THIS IS A WIP PR, CODES ARE SUBJECT TO CHANGE ]
Summary by CodeRabbit
New Features
Bug Fixes
Chores