Skip to content

Feat/optimize logging - #1691

Closed
whatattitude wants to merge 233 commits into
QuantumNous:mainfrom
Furion-cn:feat/optimize-logging
Closed

Feat/optimize logging#1691
whatattitude wants to merge 233 commits into
QuantumNous:mainfrom
Furion-cn:feat/optimize-logging

Conversation

@whatattitude

@whatattitude whatattitude commented Aug 29, 2025

Copy link
Copy Markdown

Summary by CodeRabbit

  • New Features

    • Batch jobs: presign, register, start endpoints.
    • Added XAI channel; expanded Gemini media/thinking support.
    • New proxy routes: /v1/messages, /v1/responses.
    • Toggle request-body logging; pprof status/enable/disable APIs.
    • Prometheus metrics endpoint; traffic stats endpoint.
    • Billing export to Excel; token-based quota reports.
    • Per-user channel/token visibility; user rate-limit query.
    • Ping/health checks; mock responses via X-Test-Traffic.
  • Improvements

    • Container log rotation/cleanup; daily log sharding.
    • Clearer errors, stronger streaming handling.
  • Documentation

    • Added usage guide; removed outdated channel settings doc.
  • Chores

    • CI pushes to Tencent Cloud Registry; revamped Docker image/entrypoint.

@coderabbitai

coderabbitai Bot commented Aug 29, 2025

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

Switches CI to build/push a NewAPI Docker image to Tencent Cloud. Overhauls Dockerfile/runtime (private bases, log rotation, entrypoint). Adds logging, metrics, pprof toggle, traffic monitoring, request persistence, and extensive relay refactors (info/execute split, proxy mode, new XAI channel, Volcengine batch). Expands models/migrations, controllers, middleware, DTOs, and routes.

Changes

Cohort / File(s) Summary
CI/CD: Tencent Cloud image
.github/workflows/docker-image-amd64.yml
Replaces multi-registry publish with single Tencent Cloud build/push; dispatch inputs added; dynamic tag; checkout v4.
Docker/runtime & logs
Dockerfile, docker-entrypoint.sh, cleanup-logs.sh, logrotate.conf, monitor-logs.sh
Private base images; GOPROXY; cron/logrotate setup; entrypoint wrapper; periodic log cleanup; added tools (curl, logrotate, dcron).
Gitignore & docs
.gitignore, docs/using/using.md, docs/channel/other_setting.md
Ignore new paths/files; add usage guide; remove outdated channel setting doc.
Core config, flags, time, pprof, traffic
common/constants.go, common/init.go, common/logger.go, common/pprof.go, common/time.go, common/traffic_monitor.go, common/format.go, common/gin.go, common/origin.go
Adds flags (mock, logging, sampling), caller info, metrics hooks, pprof server with API toggle, Beijing time helpers, traffic monitor, request-body logging/parsing, origin ID helpers, reusable body reads.
DTO expansions
dto/claude.go, dto/openai_request.go, dto/openai_response.go, dto/realtime.go, dto/error.go
Adds Claude structures/utilities; OpenAI request/media/thinking/config fields; usage tokens fields; reasoning token detail; non-standard status codes.
Metrics
metrics/metrics.go
New Prometheus metrics registry and increment/observe helpers across relay, batch, tokens, errors, logs.
Middleware
middleware/auth.go, middleware/distributor.go, middleware/mock.go, middleware/request-id.go, middleware/request-logger.go, middleware/traffic-monitor.go, middleware/utils.go
Enhanced auth/key sourcing; model extraction incl. multipart; mock-response by header; stronger request-id; request logger with optional body; traffic monitor; unified error response/logging.
Controllers
controller/*.go (batchjob, channel, group, misc, option, pprof, token, usedata, user_rate_limit, task, billing, playground, channel-test)
Adds batch job endpoints; per-user filtering; status/ping; toggle request-log; pprof enable/disable/status; root list tokens; billing/quota export/data endpoints; user rate limit query; logging tweaks.
Models & DB
model/*.go, database/migrations/create_jobs_table.sql, bin/groups.sql, bin/log_requestid.sql
New entities: Job, BatchJob, Group; central DB (CENTRAL_DB) and user rate limit model; sharded logs with RequestID/Usage/ThinkingTokens; request persistence tables; quotas/billing per token; channel Endpoint/fallback; groups initialization/sync; cache fallback-channel retry; migrations and SQL scripts.
Relay core flow
relay/relay-*.go, controller/relay.go, relay/helper/*.go, relay/common/relay_info.go, relay/constant/*
Split info/execute helpers for text/image/audio/embedding/rerank; new proxy relay; enhanced error/retry/mapping; E2E metrics; passthrough-body; RelayInfo enriched (tags, endpoint, headers, direct).
Relay channel adaptors
relay/channel/** (openai, gemini, claude, volcengine, xai, aws, task/suno, adapter/api_request.go, helper.go)
OpenAI: new thinking-disable handling, streaming helpers; Gemini: genai config, media/video/audio, reasoning tokens; Claude: signature change, thinking budget, converters; Volcengine: batch chat with Redis/keepalive; XAI: new channel; header propagation; mock/logging in DoRequest.
Router
router/*.go
New /traffic-stats; batchjob routes; v1 responses/messages; v1beta proxy; admin toggles/endpoints; test ping.
Build & deps
go.mod
Go 1.24 toolchain; upgrades; adds genai, Prometheus, Volcengine SDK, chromedp, Redis helpers, etc.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant Gin as Gin Router
  participant MW as Middleware (Auth/Logger/Traffic)
  participant Relay as Relay (Info/Execute)
  participant Adaptor as Channel Adaptor
  participant Upstream as Upstream API
  participant Metrics as Metrics
  participant Persist as Request Persistence

  Client->>Gin: HTTP request
  Gin->>MW: Auth + RequestID + Logger + Traffic
  MW-->>Gin: Context (user, token, headers)
  Gin->>Relay: TextInfo/ImageInfo/... (parse + validate)
  Relay->>Adaptor: Convert + DoRequest
  Adaptor->>Upstream: HTTP request (propagated headers)
  Upstream-->>Adaptor: HTTP response (stream/non-stream)
  Adaptor-->>Relay: Response + Usage/Status
  Relay->>Metrics: Counters + Duration + Tokens
  alt Persistence enabled and OK
    Relay->>Persist: Save request/response snapshot
  end
  Relay-->>Client: Proxied response
  MW->>MW: RecordRequestEnd()
Loading
sequenceDiagram
  autonumber
  participant Client
  participant Gin
  participant Relay as Relay (Proxy/Batch)
  participant VE as Volcengine Batch
  participant Redis as Redis Cache/Lock
  participant KA as KeepAlive Manager

  Client->>Gin: POST /v1beta/models/* (batch)
  Gin->>Relay: Proxy/Batch handler
  Relay->>Redis: TryAcquireLock(requestID)
  alt Lock exists
    Relay-->>Client: 409 conflict (retry_request_id)
  else Lock acquired
    Relay->>KA: AddBatchResultKey(requestID)
    Relay->>Redis: CreateBatchRequestKey(pending, TTL)
    par Async batch call
      Relay->>VE: CreateBatchChatCompletion(...)
      VE-->>Relay: Result/Error
      Relay->>Redis: SaveBatchResult/SaveBatchError (24h TTL)
    and Wait
      Relay-->>Client: 203 accepted with retry_request_id on timeout
      Note over Relay,Client: On subsequent poll, returns cached result
    end
  end
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~180 minutes

Possibly related PRs

Suggested reviewers

  • creamlike1024
  • xyfacai

Poem

A rabbit taps the Docker drum, tag by tag we hop,
New routes sprout like clover buds, the metrics never stop.
Logs roll, rotate at midnight’s chime,
Batch winds hum through Redis time.
With proxy paws and XAI flair—
We ship, we sip, cool Beijing air. 🐇🚀

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

jiutubaba pushed a commit to jiutubaba/fx-api that referenced this pull request May 17, 2026
…ld dedup

Fixes QuantumNous#1691

- pollOutbox() reused a 10s context for SetOutboxWatermark after event
  processing could take much longer, causing "outbox watermark write
  failed: context deadline exceeded". The watermark never advanced so
  the same 200 events were reprocessed every poll cycle, spiking CPU.
  Now uses an independent 5s context with up to 3 retries (200ms apart).

- When multiple Codex accounts sharing the same 21-22 groups are all
  rate-limited in quick succession, each account_changed event triggered
  redundant bucket rebuild attempts for the same groups. Introduce
  batchSeenKey{groupID, platform} and thread a seen map through the
  handler chain; rebuildBucketsForPlatform skips (group, platform) pairs
  already rebuilt within the same poll batch (~80% fewer rebuild calls in
  the 5-accounts-same-groups scenario).

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
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.

5 participants