mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 08:02:14 +00:00
fix: delay auto-clean until next interval after enable
Hot-reload and first enable only reschedule the timer; hard-delete runs on tick only. Align README/i18n, fix settings section indent, ignore local tmp-ui-preview.
This commit is contained in:
1 parent
8f376cf082
commit
2f3f08f5cb
6 files changed
+37
-28
No files matched your search
@@ -44,3 +44,6 @@ Thumbs.db
|
||||
/release/
|
||||
/.tmp/
|
||||
/tmp/
|
||||
|
||||
# Local agent previews
|
||||
/tmp-ui-preview/
|
||||
@@ -55,7 +55,7 @@ Grok2API is a Go-based Grok API gateway with a built-in React admin console. It
|
||||
- **Account relationships**: Web-centered links to Build and Console can share a stable egress identity while runtime state stays independent
|
||||
- **Runtime infrastructure**: SQLite/PostgreSQL, Memory/Redis, and HTTP/SOCKS5/Resin egress
|
||||
- **Admin console**: dashboard, accounts, model routes, client keys, image gallery, video library, request audits, runtime settings, and update checks
|
||||
- **Optional account auto-clean** (off by default): runtime settings can periodically hard-delete accounts already marked `reauthRequired` whose `reauth_marked_at` exceeds the configured minimum age. Cooldown-only and still-active permanent-refresh drain accounts are never selected. Accounts with active video jobs are skipped (not blocking the rest). First scan waits one interval after process start.
|
||||
- **Optional account auto-clean** (off by default): runtime settings can periodically hard-delete accounts already marked `reauthRequired` whose `reauth_marked_at` exceeds the configured minimum age. Cooldown-only and still-active permanent-refresh drain accounts are never selected. Accounts with active video jobs are skipped (not blocking the rest). First scan waits one interval after enable and after process start; config hot-reload only reschedules the next tick (never deletes immediately).
|
||||
|
||||
## Architecture
|
||||
|
||||
|
||||
+1
-1
@@ -56,7 +56,7 @@ Grok2API 是一个以 Go 为核心、内置 React 管理端的 Grok API 网关
|
||||
- **账号关联**:以 Web 为中心展示 Build/Console 弱关联,并可共享稳定出口身份;运行状态仍彼此独立
|
||||
- **运行基础设施**:SQLite/PostgreSQL、Memory/Redis、HTTP/SOCKS5/Resin 出口
|
||||
- **管理后台**:Dashboard、账号、模型、密钥、图库、视频库、请求审计、运行设置和版本检查
|
||||
- **可选账号自动清理**(默认关闭):运行设置可按间隔硬删除已标记 `reauthRequired` 且 `reauth_marked_at` 超过最短保留时长的账号。不会选中纯冷却账号,也不会打断仍可 drain 的永久 refresh 账号;有进行中视频任务的账号会被跳过(不阻塞其余清理)。进程启动后首次扫描等待一个间隔。
|
||||
- **可选账号自动清理**(默认关闭):运行设置可按间隔硬删除已标记 `reauthRequired` 且 `reauth_marked_at` 超过最短保留时长的账号。不会选中纯冷却账号,也不会打断仍可 drain 的永久 refresh 账号;有进行中视频任务的账号会被跳过(不阻塞其余清理)。启用后与进程启动后的首次扫描均等待一个间隔;热更新只重排下一次扫描,不会立即删除。
|
||||
|
||||
## 架构设计
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ type AutoCleanConfig struct {
|
||||
const autoCleanReauthBatchSize = 100
|
||||
|
||||
// UpdateAutoCleanConfig 热更新账号自动清理策略。
|
||||
// 仅唤醒调度器重排 timer;不会在唤醒时立刻硬删(等下一次 interval tick)。
|
||||
func (s *Service) UpdateAutoCleanConfig(value AutoCleanConfig) {
|
||||
s.autoCleanMu.Lock()
|
||||
defer s.autoCleanMu.Unlock()
|
||||
@@ -44,42 +45,46 @@ func (s *Service) autoCleanConfig() AutoCleanConfig {
|
||||
return s.autoClean
|
||||
}
|
||||
|
||||
func autoCleanInterval(cfg AutoCleanConfig) time.Duration {
|
||||
if !cfg.Enabled {
|
||||
return time.Hour
|
||||
}
|
||||
interval := cfg.Interval
|
||||
if interval < time.Minute {
|
||||
return time.Minute
|
||||
}
|
||||
if interval > time.Hour {
|
||||
return time.Hour
|
||||
}
|
||||
return interval
|
||||
}
|
||||
|
||||
// RunAccountAutoClean 在启用时周期性删除过期的 reauthRequired 账号;默认关闭。
|
||||
// 首次执行等待一个 interval,避免进程启动立即清库;启动前写入的 config wake 会被丢弃。
|
||||
// 运行中热更新会通过 wake 立即重扫(仍受 minAge 保护)。
|
||||
// 硬删除只在 timer 到期时执行:启动首轮与热更新(含首次启用)都只排程,不立刻清库。
|
||||
func (s *Service) RunAccountAutoClean(ctx context.Context) {
|
||||
// NewService / 启动接线可能已向 wake 写入;丢弃以免绕过首轮 interval。
|
||||
// NewService / 启动接线可能已向 wake 写入;丢弃以免无意义空转。
|
||||
select {
|
||||
case <-s.autoCleanWake:
|
||||
default:
|
||||
}
|
||||
cfg := s.autoCleanConfig()
|
||||
initial := cfg.Interval
|
||||
if !cfg.Enabled || initial < time.Minute {
|
||||
initial = time.Hour
|
||||
}
|
||||
timer := time.NewTimer(initial)
|
||||
timer := time.NewTimer(autoCleanInterval(s.autoCleanConfig()))
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-s.autoCleanWake:
|
||||
// 配置变更:只重排下一次扫描时间。
|
||||
resetCredentialRefreshTimer(timer, autoCleanInterval(s.autoCleanConfig()))
|
||||
case <-timer.C:
|
||||
cfg := s.autoCleanConfig()
|
||||
if cfg.Enabled {
|
||||
if err := s.runAutoCleanReauth(ctx, cfg); err != nil && ctx.Err() == nil {
|
||||
s.logger.Warn("account_auto_clean_failed", "error", err)
|
||||
}
|
||||
}
|
||||
resetCredentialRefreshTimer(timer, autoCleanInterval(cfg))
|
||||
}
|
||||
cfg = s.autoCleanConfig()
|
||||
if !cfg.Enabled {
|
||||
resetCredentialRefreshTimer(timer, time.Hour)
|
||||
continue
|
||||
}
|
||||
interval := cfg.Interval
|
||||
if interval < time.Minute {
|
||||
interval = time.Minute
|
||||
}
|
||||
if err := s.runAutoCleanReauth(ctx, cfg); err != nil && ctx.Err() == nil {
|
||||
s.logger.Warn("account_auto_clean_failed", "error", err)
|
||||
}
|
||||
resetCredentialRefreshTimer(timer, interval)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,7 +114,8 @@ func (s *Service) runAutoCleanReauth(ctx context.Context, cfg AutoCleanConfig) e
|
||||
}
|
||||
scanned += candidates
|
||||
deleted += len(ids)
|
||||
skipped += candidates - len(ids) // media-blocked + status race; not split for metrics v1
|
||||
// skipped 含 media 跳过与 delete 条件竞态未删;v1 不拆分指标。
|
||||
skipped += candidates - len(ids)
|
||||
for _, id := range ids {
|
||||
if s.sticky != nil {
|
||||
_ = s.sticky.DeleteByAccount(ctx, id)
|
||||
|
||||
@@ -198,7 +198,7 @@ export function SettingsPage() {
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title={t("settings.accounts.title")}>
|
||||
<SettingsSection title={t("settings.accounts.title")}>
|
||||
<div className="space-y-0">
|
||||
<SettingsField controlId="accounts-auto-clean-reauth-enabled" label={t("settings.accounts.autoCleanReauthEnabled")} description={t("settings.accounts.autoCleanReauthEnabledHelp")}>
|
||||
<Controller control={form.control} name="accounts.autoCleanReauthEnabled" render={({ field }) => (
|
||||
|
||||
@@ -760,7 +760,7 @@ const resources = {
|
||||
accounts: {
|
||||
title: "账号维护",
|
||||
autoCleanReauthEnabled: "自动硬删除需重新授权账号",
|
||||
autoCleanReauthEnabledHelp: "默认关闭。启用后按间隔永久删除已标记 reauthRequired 且超过最短保留时长的账号(不可恢复)。不会删除冷却中或仅临时失败的账号;有进行中视频任务的账号会跳过。进程启动后首次扫描等待一个间隔。",
|
||||
autoCleanReauthEnabledHelp: "默认关闭。启用后按间隔永久删除已标记 reauthRequired 且超过最短保留时长的账号(不可恢复)。不会删除冷却中或仅临时失败的账号;有进行中视频任务的账号会跳过。启用后与进程启动后的首次扫描均等待一个间隔。",
|
||||
autoCleanReauthInterval: "自动清理间隔",
|
||||
autoCleanReauthIntervalHelp: "扫描 reauthRequired 账号的时间间隔(1 分钟–1 小时)。",
|
||||
autoCleanReauthMinAge: "标记后最短保留时长",
|
||||
@@ -1250,7 +1250,7 @@ const resources = {
|
||||
errorFrameCount_one: "{{count}} error frame",
|
||||
errorFrameCount_other: "{{count}} error frames",
|
||||
},
|
||||
settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", baseURLHelp: "Primary upstream endpoint used for Grok Build requests.", fallbackBaseURL: "XAI fallback URL", fallbackBaseURLHelp: "Endpoint used when routing to XAI or falling back from Grok Build.", clientVersion: "Client version", clientVersionHelp: "Version sent with Build requests. Use a version that has passed compatibility validation.", clientIdentifier: "Client identifier", clientIdentifierHelp: "Client identity sent with requests; keep it aligned with the upstream protocol.", tokenAuth: "Token auth", tokenAuthHelp: "Authenticates Grok Build upstream requests. Saving an empty value preserves the current secret.", userAgent: "User-Agent", userAgentHelp: "Client User-Agent shared by Grok Build requests and their egress nodes.", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync latest version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill the form with the validated version and User-Agent; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", baseURLHelp: "Base endpoint used for Grok Web API calls and account operations.", statsigMode: "x-statsig source", statsigModeHelp: "Use a fixed value or retrieve request identity dynamically from a signer service.", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigValueHelp: "Fixed x-statsig-id attached to Grok Web requests.", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", statsigSignerURLHelp: "Internal signer endpoint used to retrieve x-statsig-id per request.", quotaTimeout: "Quota timeout", quotaTimeoutHelp: "Maximum time to wait for upstream quota and account-status queries.", chatTimeout: "Chat timeout", chatTimeoutHelp: "Maximum time to wait for a Grok Web chat request to complete.", imageTimeout: "Image timeout", imageTimeoutHelp: "Maximum time to wait for image generation or editing to complete.", videoTimeout: "Video timeout", videoTimeoutHelp: "Maximum time to wait for video generation to complete.", mediaConcurrency: "Media job concurrency", mediaConcurrencyHelp: "Image and video jobs one instance may run concurrently. Changes require a restart.", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffBaseHelp: "Initial retry interval after consecutive quota-recovery check failures.", recoveryBackoffMax: "Maximum recovery backoff", recoveryBackoffMaxHelp: "Maximum interval reached by exponential backoff for quota-recovery checks.", allowNSFW: "Allow NSFW images", allowNSFWHelp: "Allow Grok Web image requests to enable the adult-content preference." }, console: { baseURLHelp: "Base endpoint used for Grok Console requests and account operations.", chatTimeoutHelp: "Maximum time to wait for a Grok Console chat request to complete." }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", importConcurrencyHelp: "Accounts initialized and synchronized concurrently after a batch import.", conversionConcurrency: "Account conversion concurrency", conversionConcurrencyHelp: "Cross-provider account conversions that may run concurrently.", syncConcurrency: "Data sync concurrency", syncConcurrencyHelp: "Quota, status, and capability synchronizations that may run concurrently.", refreshConcurrency: "Credential refresh concurrency", refreshConcurrencyHelp: "Account credential refreshes that may run concurrently.", randomDelay: "Maximum random delay (ms)", randomDelayHelp: "Maximum randomized delay before batch work starts to smooth upstream request bursts." }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxImageSizeHelp: "Largest individual image that may be written to local media storage.", maxTotalSize: "Media storage limit", maxTotalSizeHelp: "Total local storage available to image and video files.", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupThresholdPercentHelp: "Storage utilization that triggers removal of older media files.", cleanupInterval: "Capacity check interval", cleanupIntervalHelp: "Interval between background storage checks and cleanup evaluation.", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs aLine truncated
|
||||
settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", baseURLHelp: "Primary upstream endpoint used for Grok Build requests.", fallbackBaseURL: "XAI fallback URL", fallbackBaseURLHelp: "Endpoint used when routing to XAI or falling back from Grok Build.", clientVersion: "Client version", clientVersionHelp: "Version sent with Build requests. Use a version that has passed compatibility validation.", clientIdentifier: "Client identifier", clientIdentifierHelp: "Client identity sent with requests; keep it aligned with the upstream protocol.", tokenAuth: "Token auth", tokenAuthHelp: "Authenticates Grok Build upstream requests. Saving an empty value preserves the current secret.", userAgent: "User-Agent", userAgentHelp: "Client User-Agent shared by Grok Build requests and their egress nodes.", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync latest version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill the form with the validated version and User-Agent; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", baseURLHelp: "Base endpoint used for Grok Web API calls and account operations.", statsigMode: "x-statsig source", statsigModeHelp: "Use a fixed value or retrieve request identity dynamically from a signer service.", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigValueHelp: "Fixed x-statsig-id attached to Grok Web requests.", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", statsigSignerURLHelp: "Internal signer endpoint used to retrieve x-statsig-id per request.", quotaTimeout: "Quota timeout", quotaTimeoutHelp: "Maximum time to wait for upstream quota and account-status queries.", chatTimeout: "Chat timeout", chatTimeoutHelp: "Maximum time to wait for a Grok Web chat request to complete.", imageTimeout: "Image timeout", imageTimeoutHelp: "Maximum time to wait for image generation or editing to complete.", videoTimeout: "Video timeout", videoTimeoutHelp: "Maximum time to wait for video generation to complete.", mediaConcurrency: "Media job concurrency", mediaConcurrencyHelp: "Image and video jobs one instance may run concurrently. Changes require a restart.", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffBaseHelp: "Initial retry interval after consecutive quota-recovery check failures.", recoveryBackoffMax: "Maximum recovery backoff", recoveryBackoffMaxHelp: "Maximum interval reached by exponential backoff for quota-recovery checks.", allowNSFW: "Allow NSFW images", allowNSFWHelp: "Allow Grok Web image requests to enable the adult-content preference." }, console: { baseURLHelp: "Base endpoint used for Grok Console requests and account operations.", chatTimeoutHelp: "Maximum time to wait for a Grok Console chat request to complete." }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", importConcurrencyHelp: "Accounts initialized and synchronized concurrently after a batch import.", conversionConcurrency: "Account conversion concurrency", conversionConcurrencyHelp: "Cross-provider account conversions that may run concurrently.", syncConcurrency: "Data sync concurrency", syncConcurrencyHelp: "Quota, status, and capability synchronizations that may run concurrently.", refreshConcurrency: "Credential refresh concurrency", refreshConcurrencyHelp: "Account credential refreshes that may run concurrently.", randomDelay: "Maximum random delay (ms)", randomDelayHelp: "Maximum randomized delay before batch work starts to smooth upstream request bursts." }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxImageSizeHelp: "Largest individual image that may be written to local media storage.", maxTotalSize: "Media storage limit", maxTotalSizeHelp: "Total local storage available to image and video files.", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupThresholdPercentHelp: "Storage utilization that triggers removal of older media files.", cleanupInterval: "Capacity check interval", cleanupIntervalHelp: "Interval between background storage checks and cleanup evaluation.", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs aLine truncated
|
||||
|
||||
docs: {
|
||||
title: "API documentation",
|
||||
|
||||
Reference in new issue
Block a user