From 9447849d77d2e46eceaea05820f4b8485f9eb664 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 8 Nov 2026 20:12:49 +0800 Subject: [PATCH 1/5] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=87=AD=E8=AF=81?= =?UTF-8?q?=E8=BF=90=E8=90=A5=E5=B7=A1=E6=A3=80=E7=A7=AF=E5=8E=8B=E4=B8=8E?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E5=90=8E=E7=8A=B6=E6=80=81=E5=88=B7=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../workflows/token-guard-v2-scheduler.yml | 47 ++ .../repository/account_token_guard_v2.go | 17 +- ...account_token_guard_v2_integration_test.go | 8 +- ...ken_guard_v2_scheduler_integration_test.go | 195 +++++++ .../service/account_token_guard_v2.go | 130 ++++- .../account_token_guard_v2_budget_test.go | 14 +- .../account_token_guard_v2_scheduler_test.go | 509 ++++++++++++++++++ .../service/account_token_guard_v2_test.go | 59 +- docs/account-token-guard-v2.md | 6 +- frontend/src/i18n/locales/en/tokenGuardV2.ts | 16 + frontend/src/i18n/locales/zh/tokenGuardV2.ts | 16 + .../src/views/admin/ops/TokenGuardV2View.vue | 80 ++- .../ops/__tests__/TokenGuardV2View.spec.ts | 132 +++++ 13 files changed, 1161 insertions(+), 68 deletions(-) create mode 100644 .github/workflows/token-guard-v2-scheduler.yml create mode 100644 backend/internal/repository/account_token_guard_v2_scheduler_integration_test.go create mode 100644 backend/internal/service/account_token_guard_v2_scheduler_test.go diff --git a/.github/workflows/token-guard-v2-scheduler.yml b/.github/workflows/token-guard-v2-scheduler.yml new file mode 100644 index 000000000000..2527131b171d --- /dev/null +++ b/.github/workflows/token-guard-v2-scheduler.yml @@ -0,0 +1,47 @@ +name: Credential patrol scheduling + +on: + pull_request: + paths: + - 'backend/internal/service/account_token_guard_v2*.go' + - 'backend/internal/repository/account_token_guard_v2*.go' + - 'frontend/src/views/admin/ops/TokenGuardV2View.vue' + - 'frontend/src/views/admin/ops/__tests__/TokenGuardV2View.spec.ts' + - '.github/workflows/token-guard-v2-scheduler.yml' + +permissions: + contents: read + +jobs: + scheduler: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Scheduling, cancellation and retained re-login budget under race detector + shell: bash + run: | + set -euo pipefail + mkdir -p test-evidence + git rev-parse HEAD > test-evidence/head.txt + (cd backend && go test -race -tags=unit ./internal/service -run '^Test(AccountTokenGuardV2|ReloginBudget|ExhaustedRelogin|RestoredBudget)' -count=1 -v -timeout=10m) 2>&1 | tee test-evidence/scheduler.log + - name: PostgreSQL cutoff, lease fencing and budget persistence + shell: bash + env: + CI: 'true' + run: | + set -euo pipefail + (cd backend && go test -tags=integration ./internal/repository -run '^Test(AccountTokenGuardV2|ReloginBudget)' -count=1 -v -timeout=15m) 2>&1 | tee test-evidence/storage.log + if grep -Eq -- '--- SKIP:|no tests to run' test-evidence/storage.log; then exit 1; fi + - uses: actions/upload-artifact@v7 + if: always() + with: + name: credential-patrol-${{ github.event.pull_request.head.sha }} + path: test-evidence/ + if-no-files-found: error diff --git a/backend/internal/repository/account_token_guard_v2.go b/backend/internal/repository/account_token_guard_v2.go index 2375b69268bf..44b91c4623c8 100644 --- a/backend/internal/repository/account_token_guard_v2.go +++ b/backend/internal/repository/account_token_guard_v2.go @@ -95,7 +95,7 @@ func (r *accountTokenGuardV2Repository) ListAccounts(ctx context.Context) ([]ser return result, rows.Err() } -func (r *accountTokenGuardV2Repository) ClaimDue(ctx context.Context, owner string, leaseDuration time.Duration, limit int) ([]service.AccountTokenGuardV2Record, error) { +func (r *accountTokenGuardV2Repository) ClaimDue(ctx context.Context, owner string, leaseDuration time.Duration, limit int, dueBefore time.Time) ([]service.AccountTokenGuardV2Record, error) { if limit <= 0 { limit = 10 } @@ -105,6 +105,7 @@ func (r *accountTokenGuardV2Repository) ClaimDue(ctx context.Context, owner stri FROM account_token_guard_v2_accounts WHERE enabled = TRUE AND next_probe_at <= NOW() + AND next_probe_at <= $4 AND (lease_until IS NULL OR lease_until < NOW()) ORDER BY next_probe_at ASC, account_id ASC LIMIT $1 @@ -122,7 +123,7 @@ func (r *accountTokenGuardV2Repository) ClaimDue(ctx context.Context, owner stri guard.cooldown_until, guard.blocked_reason, COALESCE(guard.lease_owner, ''), guard.lease_until, guard.created_at, guard.updated_at, guard.refresh_failure_code, guard.last_refresh_failure_at - `, limit, owner, int64(leaseDuration.Seconds())) + `, limit, owner, int64(leaseDuration.Seconds()), dueBefore) if err != nil { return nil, err } @@ -171,7 +172,7 @@ func (r *accountTokenGuardV2Repository) CompleteProbe(ctx context.Context, accou lease_owner = NULL, lease_until = NULL, updated_at = NOW() - WHERE account_id = $1 AND lease_owner = $2 + WHERE account_id = $1 AND lease_owner = $2 AND lease_until > NOW() `, accountID, owner, result.ProbeState, result.ProbeDetail, result.FailStreak, result.LastProbeAt, result.LastReauthAt, result.NextProbeAt, result.CooldownUntil, result.BlockedReason) @@ -188,6 +189,16 @@ func (r *accountTokenGuardV2Repository) CompleteProbe(ctx context.Context, accou return nil } +// ReleaseProbe abandons a claim without advancing its schedule or inspection +// history. Each claim has its own owner token, so a late release cannot clear a +// replacement claim after this lease expires. +func (r *accountTokenGuardV2Repository) ReleaseProbe(ctx context.Context, accountID int64, owner string) error { + _, err := r.db.ExecContext(ctx, `UPDATE account_token_guard_v2_accounts + SET lease_owner = NULL, lease_until = NULL, updated_at = NOW() + WHERE account_id = $1 AND lease_owner = $2`, accountID, owner) + return err +} + func (r *accountTokenGuardV2Repository) MarkReauthRequested(ctx context.Context, accountID int64, requestedAt, cooldownUntil time.Time) error { _, err := r.db.ExecContext(ctx, ` UPDATE account_token_guard_v2_accounts diff --git a/backend/internal/repository/account_token_guard_v2_integration_test.go b/backend/internal/repository/account_token_guard_v2_integration_test.go index adbaa2d8fafd..3bc65c76790b 100644 --- a/backend/internal/repository/account_token_guard_v2_integration_test.go +++ b/backend/internal/repository/account_token_guard_v2_integration_test.go @@ -26,11 +26,11 @@ func TestAccountTokenGuardV2RepositoryLeasesAndReauth(t *testing.T) { }) guard := NewAccountTokenGuardV2Repository(integrationDB) require.NoError(t, guard.UpsertAccount(ctx, account.ID, false, false)) - claimed, err := guard.ClaimDue(ctx, "instance-a", time.Minute, 10) + claimed, err := guard.ClaimDue(ctx, "instance-a", time.Minute, 10, time.Now()) require.NoError(t, err) require.Empty(t, claimed, "paused accounts must not be scheduled") require.NoError(t, guard.UpsertAccount(ctx, account.ID, true, true)) - claimed, err = guard.ClaimDue(ctx, "instance-a", time.Minute, 10) + claimed, err = guard.ClaimDue(ctx, "instance-a", time.Minute, 10, time.Now()) require.NoError(t, err) require.Len(t, claimed, 1) other, err := guard.ClaimAccount(ctx, account.ID, "instance-b", time.Minute) @@ -47,11 +47,11 @@ func TestAccountTokenGuardV2RepositoryLeasesAndReauth(t *testing.T) { require.Empty(t, stored.LeaseOwner) require.Nil(t, stored.LeaseUntil) require.Equal(t, service.AccountTokenGuardV2ProbeOK, stored.ProbeState) - claimed, err = guard.ClaimDue(ctx, "instance-b", time.Minute, 10) + claimed, err = guard.ClaimDue(ctx, "instance-b", time.Minute, 10, time.Now()) require.NoError(t, err) require.Empty(t, claimed) require.NoError(t, guard.RescheduleEnabled(ctx)) - claimed, err = guard.ClaimDue(ctx, "instance-b", time.Minute, 10) + claimed, err = guard.ClaimDue(ctx, "instance-b", time.Minute, 10, time.Now()) require.NoError(t, err) require.Len(t, claimed, 1) _, err = integrationDB.ExecContext(ctx, `UPDATE account_token_guard_v2_accounts SET lease_until = NOW() - INTERVAL '1 second' WHERE account_id = $1`, account.ID) diff --git a/backend/internal/repository/account_token_guard_v2_scheduler_integration_test.go b/backend/internal/repository/account_token_guard_v2_scheduler_integration_test.go new file mode 100644 index 000000000000..45a272789c15 --- /dev/null +++ b/backend/internal/repository/account_token_guard_v2_scheduler_integration_test.go @@ -0,0 +1,195 @@ +//go:build integration + +package repository + +import ( + "context" + "database/sql" + "fmt" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func newGuardSchedulerAccount(t *testing.T, nextProbe time.Time, enabled bool) int64 { + t.Helper() + account := mustCreateAccount(t, testEntClient(t), &service.Account{ + Name: "credential-guard-scheduler", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, + Credentials: map[string]any{"access_token": "synthetic"}, + }) + t.Cleanup(func() { + _, err := integrationDB.ExecContext(context.Background(), `DELETE FROM accounts WHERE id=$1`, account.ID) + require.NoError(t, err) + }) + guard := NewAccountTokenGuardV2Repository(integrationDB) + require.NoError(t, guard.UpsertAccount(context.Background(), account.ID, enabled, true)) + _, err := integrationDB.ExecContext(context.Background(), `UPDATE account_token_guard_v2_accounts SET next_probe_at=$2 WHERE account_id=$1`, account.ID, nextProbe) + require.NoError(t, err) + return account.ID +} + +func guardSchedulerDatabaseNow(t *testing.T) time.Time { + t.Helper() + var now time.Time + require.NoError(t, integrationDB.QueryRow(`SELECT clock_timestamp()`).Scan(&now)) + return now +} + +func TestAccountTokenGuardV2ClaimDueHonorsCycleCutoffAndDatabaseTime(t *testing.T) { + ctx := context.Background() + now := guardSchedulerDatabaseNow(t) + cutoff := now.Add(-time.Minute) + oldID := newGuardSchedulerAccount(t, cutoff.Add(-time.Second), true) + newID := newGuardSchedulerAccount(t, cutoff.Add(30*time.Second), true) + futureID := newGuardSchedulerAccount(t, now.Add(2*time.Hour), true) + newGuardSchedulerAccount(t, cutoff.Add(-time.Second), false) + guard := NewAccountTokenGuardV2Repository(integrationDB) + + claimed, err := guard.ClaimDue(ctx, "cutoff-old", time.Minute, 10, cutoff) + require.NoError(t, err) + require.Len(t, claimed, 1, "accounts becoming due after this cycle started wait for the next cycle") + require.Equal(t, oldID, claimed[0].AccountID) + require.NoError(t, guard.ReleaseProbe(ctx, oldID, "cutoff-old")) + + // Even a future caller cutoff cannot turn the repository into a claimant + // for accounts that have not reached their actual scheduled time. + claimed, err = guard.ClaimDue(ctx, "cutoff-future", time.Minute, 10, now.Add(3*time.Hour)) + require.NoError(t, err) + var ids []int64 + for _, record := range claimed { + ids = append(ids, record.AccountID) + } + require.ElementsMatch(t, []int64{oldID, newID}, ids) + record, err := guard.GetAccount(ctx, futureID) + require.NoError(t, err) + require.Empty(t, record.LeaseOwner) +} + +func TestAccountTokenGuardV2ExpiredClaimCannotCompleteOrReleaseReplacement(t *testing.T) { + ctx := context.Background() + now := guardSchedulerDatabaseNow(t) + id := newGuardSchedulerAccount(t, now.Add(-time.Minute), true) + guard := NewAccountTokenGuardV2Repository(integrationDB) + _, err := integrationDB.ExecContext(ctx, `UPDATE account_token_guard_v2_accounts + SET probe_state='auth', probe_detail='credential was rejected', fail_streak=7, + last_probe_at=$2, blocked_reason='automatic re-login cooling down' + WHERE account_id=$1`, id, now.Add(-2*time.Minute)) + require.NoError(t, err) + before, err := guard.GetAccount(ctx, id) + require.NoError(t, err) + oldClaim, err := guard.ClaimAccount(ctx, id, "claim-old", time.Minute) + require.NoError(t, err) + require.NotNil(t, oldClaim) + _, err = integrationDB.ExecContext(ctx, `UPDATE account_token_guard_v2_accounts + SET lease_until=NOW()-INTERVAL '1 second' WHERE account_id=$1`, id) + require.NoError(t, err) + completion := service.AccountTokenGuardV2ProbeCompletion{ + ProbeState: service.AccountTokenGuardV2ProbeOK, LastProbeAt: now, NextProbeAt: now.Add(time.Hour), + } + require.ErrorIs(t, guard.CompleteProbe(ctx, id, "claim-old", completion), sql.ErrNoRows, + "a stale result must be rejected even before a replacement is claimed") + + newClaim, err := guard.ClaimAccount(ctx, id, "claim-new", time.Minute) + require.NoError(t, err) + require.NotNil(t, newClaim) + require.ErrorIs(t, guard.CompleteProbe(ctx, id, "claim-old", completion), sql.ErrNoRows) + require.NoError(t, guard.ReleaseProbe(ctx, id, "claim-old"), "a late release is harmless and idempotent") + stored, err := guard.GetAccount(ctx, id) + require.NoError(t, err) + require.Equal(t, "claim-new", stored.LeaseOwner) + require.Equal(t, newClaim.LeaseUntil, stored.LeaseUntil) + + canceled, cancel := context.WithCancel(ctx) + cancel() + require.ErrorIs(t, guard.ReleaseProbe(canceled, id, "claim-new"), context.Canceled) + require.NoError(t, guard.ReleaseProbe(context.WithoutCancel(canceled), id, "claim-new"), + "cleanup must remain possible after the cycle is canceled") + require.NoError(t, guard.ReleaseProbe(ctx, id, "claim-new"), "repeated cleanup is harmless") + stored, err = guard.GetAccount(ctx, id) + require.NoError(t, err) + require.Empty(t, stored.LeaseOwner) + require.Nil(t, stored.LeaseUntil) + require.Equal(t, before.ProbeState, stored.ProbeState) + require.Equal(t, before.ProbeDetail, stored.ProbeDetail) + require.Equal(t, before.FailStreak, stored.FailStreak) + require.Equal(t, before.LastProbeAt, stored.LastProbeAt) + require.Equal(t, before.NextProbeAt, stored.NextProbeAt) + require.Equal(t, before.BlockedReason, stored.BlockedReason) + claimed, err := guard.ClaimDue(ctx, "claim-retry", time.Minute, 1, now) + require.NoError(t, err) + require.Len(t, claimed, 1, "release does not postpone the unfinished inspection") + require.Equal(t, id, claimed[0].AccountID) +} + +func TestAccountTokenGuardV2ConcurrentClaimsInspectAccountOnce(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cutoff := guardSchedulerDatabaseNow(t).Add(-time.Hour) + id := newGuardSchedulerAccount(t, cutoff.Add(-time.Second), true) + guard := NewAccountTokenGuardV2Repository(integrationDB) + type claimResult struct { + owner string + records []service.AccountTokenGuardV2Record + err error + } + results := make(chan claimResult, 8) + start := make(chan struct{}) + var workers sync.WaitGroup + for i := range 8 { + workers.Add(1) + go func() { + defer workers.Done() + <-start + owner := fmt.Sprintf("claim-racer-%d", i) + records, err := guard.ClaimDue(ctx, owner, time.Minute, 1, cutoff) + results <- claimResult{owner: owner, records: records, err: err} + }() + } + close(start) + workers.Wait() + close(results) + count := 0 + for result := range results { + require.NoError(t, result.err) + for _, record := range result.records { + count++ + require.Equal(t, id, record.AccountID) + require.Equal(t, result.owner, record.LeaseOwner) + } + } + require.Equal(t, 1, count, "concurrent workers must never inspect the same live lease") +} + +func TestAccountTokenGuardV2ClaimDueCanDrainThirtyAccounts(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cutoff := guardSchedulerDatabaseNow(t).Add(-time.Hour) + want := make(map[int64]bool) + for range 30 { + want[newGuardSchedulerAccount(t, cutoff.Add(-time.Second), true)] = true + } + guard := NewAccountTokenGuardV2Repository(integrationDB) + seen := make(map[int64]bool) + for i := 0; i < 31; i++ { + owner := fmt.Sprintf("claim-drain-%d", i) + claimed, err := guard.ClaimDue(ctx, owner, time.Minute, 1, cutoff) + require.NoError(t, err) + if len(claimed) == 0 { + break + } + require.Len(t, claimed, 1) + record := claimed[0] + require.True(t, want[record.AccountID]) + require.False(t, seen[record.AccountID], "one cycle must not reclaim an account it completed") + require.Equal(t, owner, record.LeaseOwner) + seen[record.AccountID] = true + now := time.Now() + require.NoError(t, guard.CompleteProbe(ctx, record.AccountID, owner, service.AccountTokenGuardV2ProbeCompletion{ + ProbeState: service.AccountTokenGuardV2ProbeOK, LastProbeAt: now, NextProbeAt: now.Add(time.Minute), + })) + } + require.Len(t, seen, 30, "a cycle can continue beyond the old ten-account batch") +} diff --git a/backend/internal/service/account_token_guard_v2.go b/backend/internal/service/account_token_guard_v2.go index 57e2a8f09b6a..6a8fb94525cb 100644 --- a/backend/internal/service/account_token_guard_v2.go +++ b/backend/internal/service/account_token_guard_v2.go @@ -11,10 +11,12 @@ import ( "os" "strings" "sync" + "sync/atomic" "time" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" "github.com/google/uuid" + "golang.org/x/sync/errgroup" ) const ( @@ -27,6 +29,8 @@ const ( AccountTokenGuardV2ProbeInterval = 30 * time.Minute AccountTokenGuardV2RetryInterval = 5 * time.Minute accountTokenGuardV2LeaseDuration = 2 * time.Minute + accountTokenGuardV2CycleDuration = 90 * time.Second + accountTokenGuardV2ProbeWorkers = 3 AccountTokenGuardV2ReloginCooldown = 30 * time.Minute AccountTokenGuardV2FailThreshold = 2 @@ -116,8 +120,9 @@ type AccountTokenGuardV2Repository interface { PruneDeletedAccounts(ctx context.Context) (int64, error) GetAccount(ctx context.Context, accountID int64) (*AccountTokenGuardV2Record, error) ListAccounts(ctx context.Context) ([]AccountTokenGuardV2Record, error) - ClaimDue(ctx context.Context, owner string, leaseDuration time.Duration, limit int) ([]AccountTokenGuardV2Record, error) + ClaimDue(ctx context.Context, owner string, leaseDuration time.Duration, limit int, dueBefore time.Time) ([]AccountTokenGuardV2Record, error) ClaimAccount(ctx context.Context, accountID int64, owner string, leaseDuration time.Duration) (*AccountTokenGuardV2Record, error) + ReleaseProbe(ctx context.Context, accountID int64, owner string) error CompleteProbe(ctx context.Context, accountID int64, owner string, result AccountTokenGuardV2ProbeCompletion) error MarkReauthRequested(ctx context.Context, accountID int64, requestedAt, cooldownUntil time.Time) error RescheduleEnabled(ctx context.Context) error @@ -187,6 +192,7 @@ type AccountTokenGuardV2Service struct { reauth *OpenAIOAuthReauthService leaseOwner string + runMu sync.Mutex startOnce sync.Once rootCtx context.Context cancel context.CancelFunc @@ -258,7 +264,7 @@ func (s *AccountTokenGuardV2Service) Start() { ticker := time.NewTicker(time.Minute) defer ticker.Stop() runCycle := func() { - ctx, cancel := context.WithTimeout(s.rootCtx, 90*time.Second) + ctx, cancel := context.WithTimeout(s.rootCtx, accountTokenGuardV2CycleDuration) defer cancel() if rows, err := s.repo.ListAccounts(ctx); err == nil && len(rows) > 0 { s.reauth.EnsureWorker() @@ -402,6 +408,18 @@ func (s *AccountTokenGuardV2Service) recordView(ctx context.Context, record Acco } func (s *AccountTokenGuardV2Service) RunDue(ctx context.Context) (int, error) { + // A cycle waits for its probes and final lease writes before releasing this + // lock. Overlapping callers must not multiply the bounded worker pool. + if !s.runMu.TryLock() { + return 0, nil + } + defer s.runMu.Unlock() + startedAt := time.Now() + ctx, cancel := context.WithTimeout(ctx, accountTokenGuardV2CycleDuration) + defer cancel() + // Freeze eligibility at cycle start. A long cycle must not repeatedly probe + // accounts whose retry interval elapses while other accounts are running. + dueBefore := s.clockNow() // Clean all orphaned records, including paused accounts and future probes. // Only the database's account deletion state is authoritative, not read errors. removed, err := s.repo.PruneDeletedAccounts(ctx) @@ -411,17 +429,38 @@ func (s *AccountTokenGuardV2Service) RunDue(ctx context.Context) (int, error) { if removed > 0 { slog.Info("account_token_guard_v2_deleted_accounts_pruned", "count", removed) } - records, err := s.repo.ClaimDue(ctx, s.leaseOwner, accountTokenGuardV2LeaseDuration, 10) - if err != nil { - return 0, err - } - for i := range records { - if err := ctx.Err(); err != nil { - return i, err - } - s.runProbe(ctx, records[i]) + group, workCtx := errgroup.WithContext(ctx) + var completed atomic.Int64 + for range accountTokenGuardV2ProbeWorkers { + group.Go(func() error { + for { + if err := workCtx.Err(); err != nil { + return err + } + // Claim only when this slot is free: no leased account waits + // behind a slow probe, and every claim has its own fencing token. + owner := s.newProbeOwner() + records, err := s.repo.ClaimDue(workCtx, owner, accountTokenGuardV2LeaseDuration, 1, dueBefore) + if err != nil { + return err + } + if len(records) == 0 { + return nil + } + if err := s.runProbe(workCtx, records[0]); err != nil { + return err + } + completed.Add(1) + } + }) } - return len(records), nil + err = group.Wait() + slog.Info("account_token_guard_v2_cycle_completed", "processed", completed.Load(), "duration_ms", time.Since(startedAt).Milliseconds(), "cancelled", ctx.Err() != nil) + return int(completed.Load()), err +} + +func (s *AccountTokenGuardV2Service) newProbeOwner() string { + return s.leaseOwner + "/" + uuid.NewString() } func (s *AccountTokenGuardV2Service) ProbeNow(ctx context.Context, accountID int64) (*AccountTokenGuardV2Account, error) { @@ -432,14 +471,16 @@ func (s *AccountTokenGuardV2Service) ProbeNow(ctx context.Context, accountID int if existing == nil { return nil, infraerrors.New(http.StatusNotFound, "TOKEN_GUARD_V2_NOT_FOUND", "monitored account not found") } - record, err := s.repo.ClaimAccount(ctx, accountID, s.leaseOwner, accountTokenGuardV2LeaseDuration) + record, err := s.repo.ClaimAccount(ctx, accountID, s.newProbeOwner(), accountTokenGuardV2LeaseDuration) if err != nil { return nil, infraerrors.New(http.StatusInternalServerError, "TOKEN_GUARD_V2_CLAIM_FAILED", "failed to start account inspection") } if record == nil { return nil, infraerrors.Conflict("TOKEN_GUARD_V2_PROBE_BUSY", "account inspection is already running") } - s.runProbe(ctx, *record) + if err := s.runProbe(ctx, *record); err != nil { + return nil, err + } return s.accountView(ctx, accountID) } @@ -460,11 +501,24 @@ func (s *AccountTokenGuardV2Service) ReloginNow(ctx context.Context, accountID i return task, nil } -func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record AccountTokenGuardV2Record) { +func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record AccountTokenGuardV2Record) error { + owner := record.LeaseOwner + // CompleteProbe normally clears the lease. Early failures and cancellation + // still release this claim without changing the probe history or due time. + defer func() { + releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + if err := s.repo.ReleaseProbe(releaseCtx, record.AccountID, owner); err != nil { + slog.Warn("account_token_guard_v2_lease_release_failed", "account_id", record.AccountID) + } + }() + if err := ctx.Err(); err != nil { + return err + } rules, err := s.GetRules(ctx) if err != nil { slog.Warn("account_token_guard_v2_rules_read_failed", "error", err) - return + return err } now := s.clockNow() completion := AccountTokenGuardV2ProbeCompletion{ @@ -473,15 +527,21 @@ func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record Accoun CooldownUntil: record.CooldownUntil, } account, err := s.accounts.GetAccount(ctx, record.AccountID) + if ctx.Err() != nil { + return ctx.Err() + } if err != nil || account == nil || account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || account.IsCredentialShadow() || account.IsOpenAIPersonalAccessToken() || account.IsOpenAIAgentIdentity() { completion.ProbeDetail = "account is no longer an eligible OpenAI OAuth parent account" completion.BlockedReason = completion.ProbeDetail - s.completeProbe(ctx, record.AccountID, completion) - return + return s.completeProbe(ctx, record.AccountID, owner, completion) } probeCtx, cancel := context.WithTimeout(ctx, 30*time.Second) state, detail := s.probeAccount(probeCtx, account) cancel() + if err := ctx.Err(); err != nil { + // Stopping the scheduler is not an account authentication failure. + return err + } completion.ProbeState = state completion.ProbeDetail = detail completion.BlockedReason = "" @@ -489,11 +549,13 @@ func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record Accoun pending := false if hasBudget { var updated *AccountTokenGuardV2Record - updated, pending, err = budgetRepo.ReconcileReloginBudget(ctx, record.AccountID, s.leaseOwner, rules, now, state) + updated, pending, err = budgetRepo.ReconcileReloginBudget(ctx, record.AccountID, owner, rules, now, state) + if ctx.Err() != nil { + return ctx.Err() + } if err != nil || updated == nil { completion.BlockedReason = "re-login budget could not be reconciled" - s.completeProbe(ctx, record.AccountID, completion) - return + return s.completeProbe(ctx, record.AccountID, owner, completion) } record = *updated completion.CooldownUntil = record.CooldownUntil @@ -522,8 +584,11 @@ func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record Accoun } if hasBudget && record.Enabled && record.AutoReloginEnabled && !record.AutoReloginExhausted && !pending && completion.FailStreak >= rules.FailStreakThreshold && !cooldownActive { task, taskErr := s.reauth.createTaskForProfile(ctx, record.AccountID, "codex", func(createCtx context.Context, id int64, hash string) (*OpenAIOAuthReauthTaskRecord, error) { - return budgetRepo.CreateAutomaticRelogin(createCtx, id, hash, s.leaseOwner, rules, s.clockNow()) + return budgetRepo.CreateAutomaticRelogin(createCtx, id, hash, owner, rules, s.clockNow()) }) + if ctx.Err() != nil { + return ctx.Err() + } if taskErr == nil && task != nil { completion.LastReauthAt = &now cooldown := now.Add(time.Duration(rules.ReloginCooldownSeconds) * time.Second) @@ -534,18 +599,33 @@ func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record Accoun } else if taskErr != nil { completion.BlockedReason = "automatic re-login could not be queued" completion.ProbeDetail = detail + "; " + completion.BlockedReason + slog.Warn("account_token_guard_v2_relogin_queue_failed", "account_id", record.AccountID, "reason", safeTokenGuardReloginReason(taskErr)) } } } - s.completeProbe(ctx, record.AccountID, completion) + if ctx.Err() != nil { + return ctx.Err() + } + return s.completeProbe(ctx, record.AccountID, owner, completion) +} + +func safeTokenGuardReloginReason(err error) string { + switch reason := infraerrors.Reason(err); reason { + case "OPENAI_REAUTH_UNAVAILABLE", "OPENAI_REAUTH_WORKER_UNAVAILABLE", "OPENAI_REAUTH_CONFIG_REQUIRED", "OPENAI_REAUTH_CONFIG_READ_FAILED", "OPENAI_REAUTH_CONFIG_DECRYPT_FAILED", "OPENAI_REAUTH_ENCRYPTION_KEY_REQUIRED", "OPENAI_REAUTH_CREDENTIAL_SNAPSHOT_FAILED", "OPENAI_REAUTH_ACCOUNT_NOT_FOUND", "OPENAI_REAUTH_ACCOUNT_INVALID", "OPENAI_REAUTH_TASK_CREATE_FAILED": + return reason + default: + return "unknown" + } } -func (s *AccountTokenGuardV2Service) completeProbe(ctx context.Context, accountID int64, completion AccountTokenGuardV2ProbeCompletion) { +func (s *AccountTokenGuardV2Service) completeProbe(ctx context.Context, accountID int64, owner string, completion AccountTokenGuardV2ProbeCompletion) error { persistCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer cancel() - if err := s.repo.CompleteProbe(persistCtx, accountID, s.leaseOwner, completion); err != nil { + if err := s.repo.CompleteProbe(persistCtx, accountID, owner, completion); err != nil { slog.Warn("account_token_guard_v2_probe_save_failed", "account_id", accountID, "error", err) + return err } + return nil } func (s *AccountTokenGuardV2Service) probeAccount(ctx context.Context, account *Account) (string, string) { diff --git a/backend/internal/service/account_token_guard_v2_budget_test.go b/backend/internal/service/account_token_guard_v2_budget_test.go index 122625f9f545..836b05d69f49 100644 --- a/backend/internal/service/account_token_guard_v2_budget_test.go +++ b/backend/internal/service/account_token_guard_v2_budget_test.go @@ -12,6 +12,8 @@ import ( ) func (r *accountTokenGuardV2TestRepo) ReconcileReloginBudget(_ context.Context, _ int64, _ string, rules AccountTokenGuardV2Rules, at time.Time, state string) (*AccountTokenGuardV2Record, bool, error) { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil { return nil, false, errors.New("missing record") } @@ -32,6 +34,8 @@ func (r *accountTokenGuardV2TestRepo) CreateAutomaticRelogin(ctx context.Context } func (r *accountTokenGuardV2TestRepo) ResumeReloginBudget(_ context.Context, _ int64, rules AccountTokenGuardV2Rules, now time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil { return errors.New("missing record") } @@ -126,7 +130,7 @@ func TestExhaustedReloginStillProbesAndManualFailureDoesNotRestartAutomation(t * AccountID: 42, Enabled: true, AutoReloginEnabled: true, ReloginFailStreak: 3, AutoReloginExhausted: true, }} svc := NewAccountTokenGuardV2Service(repo, nil, reader, accountTokenGuardV2TestProber{err: errors.New("invalid token")}, reauth) - svc.runProbe(context.Background(), *repo.record) + require.NoError(t, svc.runProbe(context.Background(), *repo.record)) require.NotNil(t, repo.completion) require.Equal(t, AccountTokenGuardV2ProbeAuth, repo.completion.ProbeState) require.Contains(t, repo.completion.BlockedReason, "exhausted") @@ -135,7 +139,7 @@ func TestExhaustedReloginStillProbesAndManualFailureDoesNotRestartAutomation(t * // A manually initiated failure is accounted too; observing it cannot resume. now := time.Now() repo.outcomes = []AccountReloginOutcome{{ID: 9, Status: OpenAIOAuthReauthStatusFailed, FinishedAt: &now}} - svc.runProbe(context.Background(), *repo.record) + require.NoError(t, svc.runProbe(context.Background(), *repo.record)) require.True(t, repo.record.AutoReloginExhausted) require.Zero(t, tasks.createCalls) } @@ -182,16 +186,16 @@ func TestRestoredBudgetPlainOKKeepsCooldownBeforeAnotherAuthProbe(t *testing.T) require.NoError(t, err) until := now.Add(time.Minute) now = now.Add(time.Second) - svc.runProbe(ctx, *repo.record) + require.NoError(t, svc.runProbe(ctx, *repo.record)) require.Equal(t, AccountTokenGuardV2ProbeOK, repo.completion.ProbeState) require.Equal(t, &until, repo.completion.CooldownUntil) prober.err = errors.New("invalid token") now = until.Add(-time.Nanosecond) - svc.runProbe(ctx, *repo.record) + require.NoError(t, svc.runProbe(ctx, *repo.record)) require.Zero(t, tasks.createCalls) require.Equal(t, &until, repo.completion.CooldownUntil) now = until - svc.runProbe(ctx, *repo.record) + require.NoError(t, svc.runProbe(ctx, *repo.record)) require.Equal(t, 1, tasks.createCalls, "the explicit recovery cooldown opens only at its boundary") } diff --git a/backend/internal/service/account_token_guard_v2_scheduler_test.go b/backend/internal/service/account_token_guard_v2_scheduler_test.go new file mode 100644 index 000000000000..68e39a832805 --- /dev/null +++ b/backend/internal/service/account_token_guard_v2_scheduler_test.go @@ -0,0 +1,509 @@ +package service + +import ( + "context" + "errors" + "sort" + "sync" + "sync/atomic" + "testing" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +type schedulerProbeClaim struct { + id int64 + owner string +} + +// This queue models exclusive claims and rescheduling, including across workers. +// It deliberately has no budget interface: scheduler tests never create logins. +type schedulerProbeQueue struct { + mu sync.Mutex + records map[int64]AccountTokenGuardV2Record + claims []schedulerProbeClaim + completed []schedulerProbeClaim + released []schedulerProbeClaim + cutoffs []time.Time + releaseErrs []error +} + +func newSchedulerProbeQueue(count int, at time.Time) *schedulerProbeQueue { + r := &schedulerProbeQueue{records: make(map[int64]AccountTokenGuardV2Record)} + for id := 1; id <= count; id++ { + r.records[int64(id)] = AccountTokenGuardV2Record{ + AccountID: int64(id), Enabled: true, AutoReloginEnabled: true, + ProbeState: AccountTokenGuardV2ProbePending, NextProbeAt: at.Add(-time.Minute), + } + } + return r +} + +func (r *schedulerProbeQueue) UpsertAccount(context.Context, int64, bool, bool) error { + return errors.New("unexpected scheduler test upsert") +} +func (r *schedulerProbeQueue) DeleteAccount(context.Context, int64) error { + return errors.New("unexpected scheduler test delete") +} +func (r *schedulerProbeQueue) PruneDeletedAccounts(context.Context) (int64, error) { + return 0, nil +} +func (r *schedulerProbeQueue) GetAccount(_ context.Context, id int64) (*AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() + record, ok := r.records[id] + if !ok { + return nil, nil + } + return &record, nil +} +func (r *schedulerProbeQueue) ListAccounts(context.Context) ([]AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() + records := make([]AccountTokenGuardV2Record, 0, len(r.records)) + for _, record := range r.records { + records = append(records, record) + } + return records, nil +} +func (r *schedulerProbeQueue) ClaimDue(ctx context.Context, owner string, duration time.Duration, limit int, dueBefore time.Time) ([]AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() + if err := ctx.Err(); err != nil { + return nil, err + } + r.cutoffs = append(r.cutoffs, dueBefore) + var due []AccountTokenGuardV2Record + for _, record := range r.records { + if record.Enabled && record.LeaseOwner == "" && !record.NextProbeAt.After(dueBefore) { + due = append(due, record) + } + } + sort.Slice(due, func(i, j int) bool { + if due[i].NextProbeAt.Equal(due[j].NextProbeAt) { + return due[i].AccountID < due[j].AccountID + } + return due[i].NextProbeAt.Before(due[j].NextProbeAt) + }) + if len(due) > limit { + due = due[:limit] + } + for i := range due { + due[i] = r.claimLocked(due[i], owner, duration) + } + return due, nil +} +func (r *schedulerProbeQueue) claimLocked(record AccountTokenGuardV2Record, owner string, duration time.Duration) AccountTokenGuardV2Record { + until := time.Now().Add(duration) + record.LeaseOwner, record.LeaseUntil = owner, &until + r.records[record.AccountID] = record + r.claims = append(r.claims, schedulerProbeClaim{record.AccountID, owner}) + return record +} +func (r *schedulerProbeQueue) ClaimAccount(ctx context.Context, id int64, owner string, duration time.Duration) (*AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() + if err := ctx.Err(); err != nil { + return nil, err + } + record, ok := r.records[id] + if !ok || record.LeaseOwner != "" { + return nil, nil + } + record = r.claimLocked(record, owner, duration) + return &record, nil +} +func (r *schedulerProbeQueue) CompleteProbe(_ context.Context, id int64, owner string, result AccountTokenGuardV2ProbeCompletion) error { + r.mu.Lock() + defer r.mu.Unlock() + record := r.records[id] + if owner == "" || record.LeaseOwner != owner { + return errors.New("scheduler test completion lost its claim") + } + r.completed = append(r.completed, schedulerProbeClaim{id, owner}) + record.ProbeState, record.ProbeDetail = result.ProbeState, result.ProbeDetail + record.FailStreak, record.LastProbeAt = result.FailStreak, &result.LastProbeAt + record.NextProbeAt = result.NextProbeAt + record.LeaseOwner, record.LeaseUntil = "", nil + r.records[id] = record + return nil +} +func (r *schedulerProbeQueue) ReleaseProbe(ctx context.Context, id int64, owner string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.released = append(r.released, schedulerProbeClaim{id, owner}) + r.releaseErrs = append(r.releaseErrs, ctx.Err()) + if err := ctx.Err(); err != nil { + return err + } + record := r.records[id] + if record.LeaseOwner == owner { + record.LeaseOwner, record.LeaseUntil = "", nil + r.records[id] = record + } + return nil +} +func (r *schedulerProbeQueue) MarkReauthRequested(context.Context, int64, time.Time, time.Time) error { + return errors.New("unexpected scheduler test re-login") +} +func (r *schedulerProbeQueue) RescheduleEnabled(context.Context) error { return nil } + +type schedulerProbeReader struct{} + +func (schedulerProbeReader) GetAccount(_ context.Context, id int64) (*Account, error) { + return &Account{ID: id, Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Credentials: map[string]any{"access_token": "synthetic-scheduler-token"}}, nil +} +func (schedulerProbeReader) GetProxy(context.Context, int64) (*Proxy, error) { return nil, nil } + +type schedulerProbeFunc func(context.Context, *Account) (*OpenAIModelsResponse, error) + +func (f schedulerProbeFunc) FetchOpenAIModelsList(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) { + return f(ctx, account) +} + +type schedulerCycleResult struct { + count int + err error +} + +func schedulerStartCycle(svc *AccountTokenGuardV2Service, ctx context.Context) <-chan schedulerCycleResult { + done := make(chan schedulerCycleResult, 1) + go func() { + count, err := svc.RunDue(ctx) + done <- schedulerCycleResult{count, err} + }() + return done +} + +func schedulerAwaitCycle(t *testing.T, done <-chan schedulerCycleResult) schedulerCycleResult { + t.Helper() + select { + case result := <-done: + return result + case <-time.After(3 * time.Second): + t.Fatal("scheduler did not finish its bounded work") + return schedulerCycleResult{} + } +} + +func schedulerAwaitStarted(t *testing.T, started <-chan int64, count int) { + t.Helper() + for i := 0; i < count; i++ { + select { + case <-started: + case <-time.After(3 * time.Second): + t.Fatal("scheduler did not fill its available probe slots") + } + } +} + +func TestAccountTokenGuardV2SchedulerDrainsThirtyDueAccounts(t *testing.T) { + at := time.Now() + repo := newSchedulerProbeQueue(30, at) + svc := NewAccountTokenGuardV2Service(repo, nil, schedulerProbeReader{}, accountTokenGuardV2TestProber{}, nil) + t.Cleanup(svc.cancel) + svc.now = func() time.Time { return at } + result := schedulerAwaitCycle(t, schedulerStartCycle(svc, context.Background())) + require.NoError(t, result.err) + require.Equal(t, 30, result.count) + repo.mu.Lock() + defer repo.mu.Unlock() + require.Len(t, repo.completed, 30, "one cycle must drain beyond the old batch of ten") + owners := make(map[string]bool) + for _, claim := range repo.claims { + require.NotEmpty(t, claim.owner) + require.False(t, owners[claim.owner], "each acquisition needs a fresh lease token") + owners[claim.owner] = true + } + for _, completion := range repo.completed { + require.True(t, owners[completion.owner], "completion must use the acquired token") + } + for _, record := range repo.records { + require.Equal(t, AccountTokenGuardV2ProbeOK, record.ProbeState) + require.Empty(t, record.LeaseOwner) + } +} + +func TestAccountTokenGuardV2SchedulerKeepsCycleCutoffWhenClockAdvances(t *testing.T) { + at := time.Now() + repo := newSchedulerProbeQueue(4, at) + future := repo.records[4] + future.NextProbeAt = at.Add(30 * time.Second) + repo.records[4] = future + var clock atomic.Int64 + clock.Store(at.UnixNano()) + prober := schedulerProbeFunc(func(context.Context, *Account) (*OpenAIModelsResponse, error) { + clock.Store(at.Add(2 * time.Minute).UnixNano()) + return nil, nil + }) + svc := NewAccountTokenGuardV2Service(repo, nil, schedulerProbeReader{}, prober, nil) + t.Cleanup(svc.cancel) + svc.now = func() time.Time { return time.Unix(0, clock.Load()) } + result := schedulerAwaitCycle(t, schedulerStartCycle(svc, context.Background())) + require.NoError(t, result.err) + require.Equal(t, 3, result.count) + repo.mu.Lock() + defer repo.mu.Unlock() + require.Nil(t, repo.records[4].LastProbeAt, "future work belongs to the next cycle") + for _, cutoff := range repo.cutoffs { + require.True(t, cutoff.Equal(at), "all claims in a cycle share its starting cutoff") + } +} + +func TestAccountTokenGuardV2SchedulerRefillsSlotsWhileOneProbeIsSlow(t *testing.T) { + const total = 20 + repo := newSchedulerProbeQueue(total, time.Now()) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + started := make(chan int64, total) + fastCompleted := make(chan struct{}, total) + slowGate, firstWaveGate := make(chan struct{}), make(chan struct{}) + var active, peak atomic.Int32 + prober := schedulerProbeFunc(func(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) { + current := active.Add(1) + defer active.Add(-1) + for previous := peak.Load(); current > previous; previous = peak.Load() { + if peak.CompareAndSwap(previous, current) { + break + } + } + started <- account.ID + gate := firstWaveGate + if account.ID == 1 { + gate = slowGate + } + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-gate: + } + if account.ID != 1 { + fastCompleted <- struct{}{} + } + return nil, nil + }) + svc := NewAccountTokenGuardV2Service(repo, nil, schedulerProbeReader{}, prober, nil) + t.Cleanup(svc.cancel) + done := schedulerStartCycle(svc, ctx) + schedulerAwaitStarted(t, started, 3) + close(firstWaveGate) + for i := 0; i < total-1; i++ { + select { + case <-fastCompleted: + case <-time.After(3 * time.Second): + t.Fatal("a slow probe prevented available slots from draining later accounts") + } + } + require.EqualValues(t, 3, peak.Load(), "probe concurrency must stay bounded at three") + close(slowGate) + result := schedulerAwaitCycle(t, done) + require.NoError(t, result.err) + require.Equal(t, total, result.count) +} + +func TestAccountTokenGuardV2SchedulerCancellationReleasesOnlyRunningClaims(t *testing.T) { + repo := newSchedulerProbeQueue(30, time.Now()) + for id, record := range repo.records { + record.FailStreak = 2 + repo.records[id] = record + } + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + started := make(chan int64, 30) + prober := schedulerProbeFunc(func(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) { + started <- account.ID + <-ctx.Done() + // Cancellation must win even when a transport reports an auth-shaped error. + return nil, errors.New("invalid token") + }) + svc := NewAccountTokenGuardV2Service(repo, nil, schedulerProbeReader{}, prober, nil) + t.Cleanup(svc.cancel) + done := schedulerStartCycle(svc, ctx) + schedulerAwaitStarted(t, started, 3) + repo.mu.Lock() + claimed := len(repo.claims) + repo.mu.Unlock() + require.Equal(t, 3, claimed, "queued accounts must not be leased before a slot is free") + cancel() + result := schedulerAwaitCycle(t, done) + require.ErrorIs(t, result.err, context.Canceled) + repo.mu.Lock() + defer repo.mu.Unlock() + require.Len(t, repo.claims, 3) + require.Len(t, repo.released, 3) + for _, err := range repo.releaseErrs { + require.NoError(t, err, "lease cleanup must survive caller cancellation") + } + for _, record := range repo.records { + require.Empty(t, record.LeaseOwner) + require.Equal(t, 2, record.FailStreak, "a cancelled request is not another auth failure") + require.NotEqual(t, AccountTokenGuardV2ProbeAuth, record.ProbeState) + } +} + +func TestAccountTokenGuardV2SchedulerOverlappingCyclesDoNotMultiplyConcurrency(t *testing.T) { + repo := newSchedulerProbeQueue(12, time.Now()) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + started := make(chan int64, 12) + gate := make(chan struct{}) + prober := schedulerProbeFunc(func(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) { + started <- account.ID + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-gate: + return nil, nil + } + }) + svc := NewAccountTokenGuardV2Service(repo, nil, schedulerProbeReader{}, prober, nil) + t.Cleanup(svc.cancel) + first := schedulerStartCycle(svc, ctx) + schedulerAwaitStarted(t, started, 3) + second := schedulerAwaitCycle(t, schedulerStartCycle(svc, ctx)) + require.Zero(t, second.count, "an overlapping cycle must not start another worker pool") + repo.mu.Lock() + claimed := len(repo.claims) + repo.mu.Unlock() + require.Equal(t, 3, claimed) + close(gate) + result := schedulerAwaitCycle(t, first) + require.NoError(t, result.err) + require.Equal(t, 12, result.count) +} + +func TestAccountTokenGuardV2ManualProbeUsesFreshClaimToken(t *testing.T) { + reauth, reader, _, _, _, _ := newReauthTestService("acct-1") + repo := newSchedulerProbeQueue(0, time.Now()) + repo.records[42] = AccountTokenGuardV2Record{AccountID: 42, Enabled: true} + svc := NewAccountTokenGuardV2Service(repo, nil, reader, accountTokenGuardV2TestProber{}, reauth) + t.Cleanup(svc.cancel) + for attempt := 0; attempt < 2; attempt++ { + view, err := svc.ProbeNow(context.Background(), 42) + require.NoError(t, err) + require.Equal(t, AccountTokenGuardV2ProbeOK, view.ProbeState) + } + repo.mu.Lock() + defer repo.mu.Unlock() + require.Len(t, repo.claims, 2) + require.Len(t, repo.completed, 2) + require.NotEqual(t, repo.claims[0].owner, repo.claims[1].owner) + require.Equal(t, repo.claims, repo.completed, "manual completions must retain their claim token") +} + +type schedulerBudgetQueue struct { + *schedulerProbeQueue + budgetOwners []string + createOwners []string + cancelAtReconcile context.CancelFunc + cancelAtCreate context.CancelFunc +} + +func (r *schedulerBudgetQueue) ReconcileReloginBudget(_ context.Context, id int64, owner string, _ AccountTokenGuardV2Rules, _ time.Time, _ string) (*AccountTokenGuardV2Record, bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + record := r.records[id] + if owner == "" || owner != record.LeaseOwner { + return nil, false, errors.New("budget reconciliation used a stale lease token") + } + r.budgetOwners = append(r.budgetOwners, owner) + if r.cancelAtReconcile != nil { + r.cancelAtReconcile() + } + return &record, false, nil +} +func (r *schedulerBudgetQueue) CreateAutomaticRelogin(_ context.Context, id int64, _ string, owner string, _ AccountTokenGuardV2Rules, _ time.Time) (*OpenAIOAuthReauthTaskRecord, error) { + r.mu.Lock() + defer r.mu.Unlock() + if owner == "" || owner != r.records[id].LeaseOwner { + return nil, errors.New("automatic re-login used a stale lease token") + } + r.createOwners = append(r.createOwners, owner) + if r.cancelAtCreate != nil { + r.cancelAtCreate() + } + return &OpenAIOAuthReauthTaskRecord{ID: 1, AccountID: id, Status: OpenAIOAuthReauthStatusQueued}, nil +} +func (*schedulerBudgetQueue) ResumeReloginBudget(context.Context, int64, AccountTokenGuardV2Rules, time.Time) error { + return errors.New("unexpected scheduler test budget recovery") +} + +func TestAccountTokenGuardV2AutomaticReloginPreservesProbeClaimToken(t *testing.T) { + reauth, reader, reauthRepo, _, _, _ := newReauthTestService("acct-1") + require.NoError(t, reauthRepo.UpsertConfig(context.Background(), reauthEmailConfig(42, "user@example.test", "encrypted:https://mail.example.test/code"))) + repo := &schedulerBudgetQueue{schedulerProbeQueue: newSchedulerProbeQueue(0, time.Now())} + repo.records[42] = AccountTokenGuardV2Record{AccountID: 42, Enabled: true, AutoReloginEnabled: true, FailStreak: 1} + svc := NewAccountTokenGuardV2Service(repo, nil, reader, accountTokenGuardV2TestProber{err: errors.New("invalid token")}, reauth) + t.Cleanup(svc.cancel) + _, err := svc.ProbeNow(context.Background(), 42) + require.NoError(t, err) + repo.mu.Lock() + defer repo.mu.Unlock() + require.Len(t, repo.claims, 1) + owner := repo.claims[0].owner + require.Equal(t, []string{owner}, repo.budgetOwners) + require.Equal(t, []string{owner}, repo.createOwners) + require.Equal(t, []schedulerProbeClaim{{42, owner}}, repo.completed) +} + +func TestAccountTokenGuardV2CancellationAfterProbePreservesInspectionHistory(t *testing.T) { + for _, stage := range []string{"budget reconciliation", "task creation"} { + t.Run(stage, func(t *testing.T) { + reauth, reader, reauthRepo, _, _, _ := newReauthTestService("acct-1") + require.NoError(t, reauthRepo.UpsertConfig(context.Background(), reauthEmailConfig(42, "user@example.test", "encrypted:https://mail.example.test/code"))) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + repo := &schedulerBudgetQueue{schedulerProbeQueue: newSchedulerProbeQueue(0, time.Now())} + original := AccountTokenGuardV2Record{ + AccountID: 42, Enabled: true, AutoReloginEnabled: true, FailStreak: 1, + ProbeState: AccountTokenGuardV2ProbePending, ProbeDetail: "previous inspection", + BlockedReason: "previous automation state", NextProbeAt: time.Now().Add(-time.Minute), + } + repo.records[42] = original + if stage == "budget reconciliation" { + repo.cancelAtReconcile = cancel + } else { + repo.cancelAtCreate = cancel + } + svc := NewAccountTokenGuardV2Service(repo, nil, reader, accountTokenGuardV2TestProber{err: errors.New("invalid token")}, reauth) + t.Cleanup(svc.cancel) + view, err := svc.ProbeNow(ctx, 42) + require.ErrorIs(t, err, context.Canceled) + require.Nil(t, view) + repo.mu.Lock() + defer repo.mu.Unlock() + require.Empty(t, repo.completed, "cancellation must not publish another inspection outcome") + require.Len(t, repo.released, 1) + require.NoError(t, repo.releaseErrs[0], "cleanup must use a context independent of the cancelled operation") + require.Equal(t, original, repo.records[42], "leave the prior failure count, due time and diagnostics unchanged") + require.Len(t, repo.budgetOwners, 1) + if stage == "budget reconciliation" { + require.Empty(t, repo.createOwners, "a cancelled reconciliation must not start a login") + } else { + require.Len(t, repo.createOwners, 1, "an already-created task keeps its own durable lifecycle") + } + }) + } +} + +func TestSafeTokenGuardReloginReasonDoesNotExposeProviderDetails(t *testing.T) { + for _, test := range []struct { + name string + err error + want string + }{ + {"allowlisted reason", infraerrors.ServiceUnavailable("OPENAI_REAUTH_WORKER_UNAVAILABLE", "synthetic-private-provider-response"), "OPENAI_REAUTH_WORKER_UNAVAILABLE"}, + {"unlisted application reason", infraerrors.ServiceUnavailable("OPENAI_REAUTH_MODE_UNAVAILABLE", "synthetic-private-provider-response"), "unknown"}, + {"arbitrary reason", infraerrors.ServiceUnavailable("synthetic-private-reason", "synthetic-private-provider-response"), "unknown"}, + {"plain provider error", errors.New("synthetic-private-provider-response"), "unknown"}, + } { + t.Run(test.name, func(t *testing.T) { + reason := safeTokenGuardReloginReason(test.err) + require.Equal(t, test.want, reason) + require.NotContains(t, reason, "synthetic-private") + }) + } +} diff --git a/backend/internal/service/account_token_guard_v2_test.go b/backend/internal/service/account_token_guard_v2_test.go index d02bf929bd8f..b5a019f600f5 100644 --- a/backend/internal/service/account_token_guard_v2_test.go +++ b/backend/internal/service/account_token_guard_v2_test.go @@ -15,6 +15,7 @@ import ( ) type accountTokenGuardV2TestRepo struct { + mu sync.Mutex createTask func(context.Context, int64, string) (*OpenAIOAuthReauthTaskRecord, error) outcomes []AccountReloginOutcome record *AccountTokenGuardV2Record @@ -27,6 +28,8 @@ type accountTokenGuardV2TestRepo struct { } func (r *accountTokenGuardV2TestRepo) PruneDeletedAccounts(context.Context) (int64, error) { + r.mu.Lock() + defer r.mu.Unlock() if r.pruneErr != nil { return 0, r.pruneErr } @@ -38,6 +41,8 @@ func (r *accountTokenGuardV2TestRepo) PruneDeletedAccounts(context.Context) (int } func (r *accountTokenGuardV2TestRepo) UpsertAccount(_ context.Context, accountID int64, enabled, autoRelogin bool) error { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil { r.record = &AccountTokenGuardV2Record{AccountID: accountID, NextProbeAt: time.Now()} } @@ -46,10 +51,14 @@ func (r *accountTokenGuardV2TestRepo) UpsertAccount(_ context.Context, accountID return nil } func (r *accountTokenGuardV2TestRepo) DeleteAccount(context.Context, int64) error { + r.mu.Lock() + defer r.mu.Unlock() r.record = nil return nil } func (r *accountTokenGuardV2TestRepo) GetAccount(context.Context, int64) (*AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil { return nil, nil } @@ -57,26 +66,46 @@ func (r *accountTokenGuardV2TestRepo) GetAccount(context.Context, int64) (*Accou return ©, nil } func (r *accountTokenGuardV2TestRepo) ListAccounts(context.Context) ([]AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil { return nil, nil } return []AccountTokenGuardV2Record{*r.record}, nil } -func (r *accountTokenGuardV2TestRepo) ClaimDue(context.Context, string, time.Duration, int) ([]AccountTokenGuardV2Record, error) { +func (r *accountTokenGuardV2TestRepo) ClaimDue(_ context.Context, owner string, duration time.Duration, _ int, dueBefore time.Time) ([]AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() r.claimed = true - if r.record == nil || r.claimBusy { + if r.record == nil || r.claimBusy || !r.record.Enabled || r.record.NextProbeAt.After(dueBefore) || (r.record.LeaseUntil != nil && r.record.LeaseUntil.After(time.Now())) { return nil, nil } + until := time.Now().Add(duration) + r.record.LeaseOwner, r.record.LeaseUntil = owner, &until return []AccountTokenGuardV2Record{*r.record}, nil } -func (r *accountTokenGuardV2TestRepo) ClaimAccount(context.Context, int64, string, time.Duration) (*AccountTokenGuardV2Record, error) { +func (r *accountTokenGuardV2TestRepo) ClaimAccount(_ context.Context, _ int64, owner string, duration time.Duration) (*AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil || r.claimBusy { return nil, nil } + until := time.Now().Add(duration) + r.record.LeaseOwner, r.record.LeaseUntil = owner, &until copy := *r.record return ©, nil } +func (r *accountTokenGuardV2TestRepo) ReleaseProbe(_ context.Context, _ int64, owner string) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.record != nil && r.record.LeaseOwner == owner { + r.record.LeaseOwner, r.record.LeaseUntil = "", nil + } + return nil +} func (r *accountTokenGuardV2TestRepo) CompleteProbe(_ context.Context, _ int64, _ string, result AccountTokenGuardV2ProbeCompletion) error { + r.mu.Lock() + defer r.mu.Unlock() r.completion = &result if r.record != nil { r.record.ProbeState = result.ProbeState @@ -87,6 +116,7 @@ func (r *accountTokenGuardV2TestRepo) CompleteProbe(_ context.Context, _ int64, r.record.NextProbeAt = result.NextProbeAt r.record.CooldownUntil = result.CooldownUntil r.record.BlockedReason = result.BlockedReason + r.record.LeaseOwner, r.record.LeaseUntil = "", nil } return nil } @@ -94,6 +124,8 @@ func (r *accountTokenGuardV2TestRepo) MarkReauthRequested(context.Context, int64 return nil } func (r *accountTokenGuardV2TestRepo) RescheduleEnabled(context.Context) error { + r.mu.Lock() + defer r.mu.Unlock() r.rescheduled = true return nil } @@ -115,15 +147,16 @@ type accountTokenGuardV2TestProber struct{ err error } type accountTokenGuardV2BlockingRepo struct { accountTokenGuardV2TestRepo - started chan struct{} - finished chan struct{} - once sync.Once + started chan struct{} + finished chan struct{} + once sync.Once + finishedOnce sync.Once } -func (r *accountTokenGuardV2BlockingRepo) ClaimDue(ctx context.Context, _ string, _ time.Duration, _ int) ([]AccountTokenGuardV2Record, error) { +func (r *accountTokenGuardV2BlockingRepo) ClaimDue(ctx context.Context, _ string, _ time.Duration, _ int, _ time.Time) ([]AccountTokenGuardV2Record, error) { r.once.Do(func() { close(r.started) }) <-ctx.Done() - close(r.finished) + r.finishedOnce.Do(func() { close(r.finished) }) return nil, ctx.Err() } @@ -175,7 +208,7 @@ func TestAccountTokenGuardV2Explicit403PolicyDoesNotQueueRelogin(t *testing.T) { svc := NewAccountTokenGuardV2Service(guardRepo, nil, reader, accountTokenGuardV2TestProber{err: fmt.Errorf("wrapped: %w", &codexModelsManifestUpstreamError{ err: errors.New("unauthorized synthetic-private"), statusCode: http.StatusForbidden, body: []byte(body), })}, reauth) - svc.runProbe(context.Background(), *guardRepo.record) + require.NoError(t, svc.runProbe(context.Background(), *guardRepo.record)) require.NotNil(t, guardRepo.completion) require.Equal(t, AccountTokenGuardV2ProbeTransient, guardRepo.completion.ProbeState) require.Equal(t, accountTokenGuardV2PolicyBlocked, guardRepo.completion.BlockedReason) @@ -220,7 +253,7 @@ func TestAccountTokenGuardV2SecondAuthFailureQueuesRelogin(t *testing.T) { record, err := guardRepo.GetAccount(context.Background(), 42) require.NoError(t, err) - svc.runProbe(context.Background(), *record) + require.NoError(t, svc.runProbe(context.Background(), *record)) require.NotNil(t, guardRepo.completion) require.Equal(t, AccountTokenGuardV2ProbeAuth, guardRepo.completion.ProbeState) @@ -246,7 +279,7 @@ func TestAccountTokenGuardV2ActiveReloginTaskIsNotDuplicated(t *testing.T) { record, err := guardRepo.GetAccount(context.Background(), 42) require.NoError(t, err) - svc.runProbe(context.Background(), *record) + require.NoError(t, svc.runProbe(context.Background(), *record)) require.Same(t, existing, reauthRepo.task) require.Equal(t, 1, reauthRepo.createCalls) @@ -318,7 +351,7 @@ func TestAccountTokenGuardV2InvalidSavedRulesDoNotQueueRelogin(t *testing.T) { repo := &accountTokenGuardV2TestRepo{record: &record} settings := &accountTokenGuardV2TestSettings{raw: "invalid-json"} svc := NewAccountTokenGuardV2Service(repo, settings, reader, accountTokenGuardV2TestProber{err: errors.New("invalid token")}, reauth) - svc.runProbe(context.Background(), record) + require.NoError(t, svc.runProbe(context.Background(), record)) require.Zero(t, reauthRepo.createCalls) require.Nil(t, repo.completion) } @@ -340,7 +373,7 @@ func TestAccountTokenGuardV2CustomRulesDriveProbe(t *testing.T) { record, err := guardRepo.GetAccount(context.Background(), 42) require.NoError(t, err) - svc.runProbe(context.Background(), *record) + require.NoError(t, svc.runProbe(context.Background(), *record)) require.Equal(t, 1, reauthRepo.createCalls) require.WithinDuration(t, guardRepo.completion.LastProbeAt.Add(45*time.Second), guardRepo.completion.NextProbeAt, time.Second) diff --git a/docs/account-token-guard-v2.md b/docs/account-token-guard-v2.md index 77a38760b646..002144d4d987 100644 --- a/docs/account-token-guard-v2.md +++ b/docs/account-token-guard-v2.md @@ -18,10 +18,14 @@ 3. 在账号列表的“运行开关”列即时切换“自动巡检”和“自动重登”,修改即保存;账号编辑弹窗仅保存登录凭据,保留已有开关。自动巡检开关控制后续自动巡检;手动巡检、手动重登仍可使用。暂停或移除巡检账号不会取消已经进入重登队列的任务。 4. 在“巡检规则”页配置间隔、阈值和冷却。默认正常巡检 30 分钟、鉴权失败复检 5 分钟、失败阈值 2 次、重登冷却 30 分钟。保存规则后已启用账号立即重新排期;后台每分钟领取一次到期账号,实际时间有调度误差。 -巡检读取现有 access token,通过现有 OpenAI 模型列表请求判断凭据状态,不发送付费生成请求。401 或明确的令牌拒绝归为鉴权失败;一般 403 归授权拒绝,手机号/安全验证与账号退役不触发自动重登。其余异常归为临时失败。模型列表可访问并不能证明所有生成模型、额度或权限可用。每轮最多领取 10 个账号,轮次预算 90 秒,单次探测预算 30 秒。数据库租约防止多个实例同时巡检同一账号。 +巡检读取现有 access token,通过现有 OpenAI 模型列表请求判断凭据状态,不发送付费生成请求。401 或明确的令牌拒绝归为鉴权失败;一般 403 归授权拒绝,手机号/安全验证与账号退役不触发自动重登。其余异常归为临时失败。模型列表可访问并不能证明所有生成模型、额度或权限可用。后台每分钟开始一轮,使用 3 个独立巡检位,在 90 秒轮次预算内持续处理本轮开始时已到期的账号;每个空闲位只领取 1 个,单次探测预算 30 秒。巡检并发与重登 Worker 并发独立。慢请求仍可能造成积压,页面的“下次巡检”是最早可执行时间,不承诺该时刻完成或所有账号都在一分钟内扫完。 + +每次领取使用独立租约标识,预算核算、自动重登入队及巡检回写均核对本次租约;旧巡检无法覆盖重新领取后的状态。服务取消或读取失败时,以独立短超时归还未完成租约,不改变历史巡检结果、失败计数和下次计划;本轮等待清理结束后才退出。停止服务本身不计为账号鉴权失败。正常探测超时仍按原有临时失败处理。 鉴权失败达到阈值且开启自动重登时,创建持久化任务,由独立 Worker 执行。活跃任务的唯一索引防止重复排队。重登成功前校验账号身份及原凭据快照;原子写回新凭据、完成任务、恢复账号调度并写入调度通知。并发手动编辑或令牌刷新后,旧任务不能覆盖新凭据。 +“巡检失败次数”与“重登失败预算”分别计数。页面根据开关、登录资料、活跃任务、失败预算、冷却和鉴权失败阈值显示当前自动恢复阶段;历史巡检异常保留在详情。点击立即巡检或立即重登后立即重新读取状态,不必等待下一次 30 秒页面轮询。重登任务显示成功后,仍需后续新鲜巡检通过才能证明凭据已恢复。自动重登入队失败的服务日志只记录账号内部编号与固定错误码,不记录上游原文或秘密。 + 通过 2FA 自动登记时使用 password_totp 和账号代理,加密保存密码与 TOTP。首次登录仍复用外部登录服务,之后的自动重登由程序管理的本地 Worker 处理。导入成功但登记失败时,当前弹窗保留登录结果和输入,重试无需再次登录。 账号只要登记在凭证运营中,旧凭证守护就跳过其自动巡检和重登,并拒绝旧页面的手动重登,包括在凭证运营中暂停的账号。删除凭证运营登记后,账号才可能再次进入旧守护所配置的范围,旧守护仍需自己的登录资料。 diff --git a/frontend/src/i18n/locales/en/tokenGuardV2.ts b/frontend/src/i18n/locales/en/tokenGuardV2.ts index 1a1c769c41fb..30c8bd11de73 100644 --- a/frontend/src/i18n/locales/en/tokenGuardV2.ts +++ b/frontend/src/i18n/locales/en/tokenGuardV2.ts @@ -36,6 +36,22 @@ export default { } }, reloginBudgetCount: 'Re-login failure budget: {count}/{limit}', + lastInspectionFailure: 'Last inspection failure (history)', + automationStates: { + paused: 'Automatic inspections paused', + disabled: 'Automatic re-login disabled; inspections continue', + configuration: 'Login configuration is incomplete; automatic re-login unavailable', + queued: 'Re-login task queued', + running: 'Re-login in progress; waiting for the task to finish', + verifying: 'New credentials saved; waiting for a later inspection to verify them', + cooldown: 'Automatic re-login cooling down until {until}', + blocked: 'Automatic recovery is unavailable; review the service status and failure details', + waiting: 'Authentication failure confirmation: {count}/{limit}; waiting for the next inspection', + scheduled: 'Re-login threshold reached; waiting for automatic processing', + healthy: 'Latest inspection accepted the credentials', + retryInspection: 'Waiting for the next inspection retry', + inspectionPending: 'Waiting for the first inspection' + }, reloginBudgetExhausted: 'Automatic re-login exhausted; inspections continue', reloginBackoffUntil: 'Re-login cooldown until', resumeReloginBudget: 'Restore budget (no immediate login)', diff --git a/frontend/src/i18n/locales/zh/tokenGuardV2.ts b/frontend/src/i18n/locales/zh/tokenGuardV2.ts index 170a152438e0..de08f367d581 100644 --- a/frontend/src/i18n/locales/zh/tokenGuardV2.ts +++ b/frontend/src/i18n/locales/zh/tokenGuardV2.ts @@ -36,6 +36,22 @@ export default { } }, reloginBudgetCount: '重登失败预算:{count}/{limit}', + lastInspectionFailure: '上次巡检异常(历史记录)', + automationStates: { + paused: '自动巡检已暂停', + disabled: '自动重登已关闭,巡检继续', + configuration: '登录配置不完整,无法自动重登', + queued: '重登任务已排队', + running: '正在重登,等待任务完成', + verifying: '新凭据已保存,等待后续巡检验证', + cooldown: '自动重登冷却至 {until}', + blocked: '自动恢复暂不可用,请查看服务状态与异常详情', + waiting: '鉴权失败确认:{count}/{limit},等待下一次巡检', + scheduled: '已达到重登阈值,等待自动处理', + healthy: '最近巡检鉴权通过', + retryInspection: '等待下一次巡检重试', + inspectionPending: '等待首次巡检' + }, reloginBudgetExhausted: '自动重登预算已耗尽,巡检继续', reloginBackoffUntil: '重登冷却至', resumeReloginBudget: '恢复预算(不立即重登)', diff --git a/frontend/src/views/admin/ops/TokenGuardV2View.vue b/frontend/src/views/admin/ops/TokenGuardV2View.vue index f4771c010891..4e601394e9bd 100644 --- a/frontend/src/views/admin/ops/TokenGuardV2View.vue +++ b/frontend/src/views/admin/ops/TokenGuardV2View.vue @@ -23,14 +23,14 @@
@@ -97,13 +97,12 @@ {{ t('tokenGuardV2.reloginBudgetCount', { count: item.relogin_fail_streak || 0, limit: status.relogin_max_failures || 3 }) }} - {{ t('tokenGuardV2.reloginBudgetExhausted') }} - {{ t('tokenGuardV2.reloginBackoffUntil') }} {{ date(item.cooldown_until) }} + {{ automationLabel(item) }}
- {{ t(`tokenGuardV2.probeStates.${item.probe_state || 'pending'}`) }}{{ t('tokenGuardV2.operationFailure.automationBlocked') }}
{{ t('tokenGuardV2.operationFailure.refreshAttempt') }}
+ {{ t(`tokenGuardV2.probeStates.${item.probe_state || 'pending'}`) }}
{{ t('tokenGuardV2.operationFailure.refreshAttempt') }}
{{ item.fail_streak }} - {{ date(item.last_probe_at) }}{{ t('tokenGuardV2.next') }} {{ date(item.next_probe_at) }}{{ t('tokenGuardV2.paused') }} + {{ date(item.last_probe_at) }}
{{ t('tokenGuardV2.lastInspectionFailure') }}
{{ t('tokenGuardV2.next') }} {{ date(item.next_probe_at) }}{{ t('tokenGuardV2.paused') }} {{ date(item.latest_task?.finished_at || item.latest_task?.created_at || item.last_reauth_at) }}{{ taskLabel(item.latest_task) }}
@@ -282,6 +281,8 @@ const rulesSaving = ref(false) const rulesDirty = ref(false) const error = ref(''), notice = ref('') let timer: ReturnType | undefined +let loadGeneration = 0 +const currentTime = ref(Date.now()) const blankDraft = (): SaveTokenGuardV2Account => ({ account_id: 0, @@ -414,6 +415,37 @@ const proxyLabel = (source: TokenGuardV2ProxySource = 'account', proxyId?: numbe return proxy ? proxyOptionLabel(proxy) : `#${proxyId}` } const probeClass = (state: string) => state === 'ok' ? 'ok' : state === 'auth' ? 'danger' : '' +const activeTaskStates = ['queued', 'running', 'callback_processing'] +function automationState(item: TokenGuardV2Account) { + const task = item.latest_task + if (task?.status === 'queued') return 'queued' + if (task && activeTaskStates.includes(task.status)) return 'running' + if (!item.enabled) return 'paused' + const finishedAt = Date.parse(task?.finished_at || '') + const probeAt = Date.parse(item.last_probe_at || '') + if (task?.status === 'succeeded' && Number.isFinite(finishedAt) && (!Number.isFinite(probeAt) || probeAt < finishedAt)) return 'verifying' + if (!item.auto_relogin_enabled) return 'disabled' + if (item.auto_relogin_exhausted) return 'exhausted' + if (!item.login_config?.configured) return 'configuration' + if (Date.parse(item.cooldown_until || '') > currentTime.value) return 'cooldown' + if (item.blocked_reason) return 'blocked' + if (item.probe_state === 'auth') return item.fail_streak < status.fail_streak_threshold ? 'waiting' : 'scheduled' + if (item.probe_state === 'ok') return 'healthy' + if (item.probe_state === 'transient') return 'retryInspection' + return 'inspectionPending' +} +function automationLabel(item: TokenGuardV2Account) { + const state = automationState(item) + if (state === 'exhausted') return t('tokenGuardV2.reloginBudgetExhausted') + if (state === 'waiting') return t('tokenGuardV2.automationStates.waiting', { count: item.fail_streak, limit: status.fail_streak_threshold }) + if (state === 'cooldown') return t('tokenGuardV2.automationStates.cooldown', { until: date(item.cooldown_until) }) + return t(`tokenGuardV2.automationStates.${state}`) +} +function invalidateLoad() { + // A response fetched before a mutation must never replace its newer result. + loadGeneration++ + loading.value = false +} const safeTaskToken = (value: string) => ['queued', 'running', 'callback_processing', 'failed', 'succeeded', 'starting', 'protocol_connecting', 'email_submitted', 'waiting_otp', 'otp_submitted', 'password_submitted', 'mfa_submitted', 'waiting_callback', 'exchanging_token', 'applying_credentials'].includes(value) ? value : 'unknown' const taskLabel = (task: TokenGuardV2Task) => task.diagnostic ? `${safeTaskToken(task.status)}: ${safeDiagnosticToken(task.diagnostic.stage)} · ${safeDiagnosticToken(task.diagnostic.reason)} · ${Number.isFinite(task.diagnostic.elapsed_ms) ? task.diagnostic.elapsed_ms : 0} ms${task.diagnostic.http_status && task.diagnostic.http_status >= 100 && task.diagnostic.http_status <= 599 ? ` · HTTP ${task.diagnostic.http_status}` : ''}` @@ -456,8 +488,9 @@ function openEdit(item: TokenGuardV2Account) { } function closeEditor() { if (!saving.value) editorOpen.value = false } -async function load(silent = false) { - if (loading.value || runtimeSaving.value || busyId.value) return +async function load(silent = false, afterAction = false) { + if ((!afterAction && (loading.value || busyId.value || saving.value || rulesSaving.value)) || runtimeSaving.value) return + const generation = ++loadGeneration loading.value = true if (!silent) error.value = '' try { @@ -467,6 +500,8 @@ async function load(silent = false) { listProxies(), listGroups('openai') ]) + if (generation !== loadGeneration) return + currentTime.value = Date.now() Object.assign(status, guard) if (guard.runtime_settings && !runtimeSaving.value) { Object.assign(runtimeDraft, guard.runtime_settings) @@ -477,14 +512,15 @@ async function load(silent = false) { proxies.value = managedProxies groups.value = openAIGroups } catch (value) { - if (!silent) error.value = message(value) + if (generation === loadGeneration && !silent) error.value = message(value) } finally { - loading.value = false + if (generation === loadGeneration) loading.value = false } } async function saveRulesConfig() { if (rulesSaving.value || !rulesDirty.value) return + invalidateLoad() rulesSaving.value = true; error.value = ''; notice.value = '' try { const saved = await saveTokenGuardV2Rules({ @@ -508,6 +544,7 @@ async function saveRulesConfig() { async function save() { if (saving.value || !draft.account_id || !encryptionReady.value) return + invalidateLoad() saving.value = true; error.value = ''; notice.value = '' try { const payload = { ...draft } @@ -515,7 +552,7 @@ async function save() { else await createTokenGuardV2Account(payload) notice.value = t('tokenGuardV2.saved') editorOpen.value = false - await load(true) + await load(true, true) } catch (value) { error.value = message(value) } finally { @@ -524,19 +561,23 @@ async function save() { } async function act(item: TokenGuardV2Account, action: () => Promise, successKey: string) { - if (busyId.value) return + if (busyId.value || runtimeSaving.value) return + invalidateLoad() busyId.value = item.account_id; error.value = ''; notice.value = '' try { const result = await action() const failure = successKey === 'tokenGuardV2.inspectionQueued' ? probeOperationFailure(result as TokenGuardV2Account) : successKey === 'tokenGuardV2.reloginQueued' ? taskOperationFailure(result as TokenGuardV2Task) : undefined - if (failure) error.value = `${t(`tokenGuardV2.operationFailure.reasons.${failure.category}`)} ${t(`tokenGuardV2.operationFailure.actions.${failure.action}`)}` + const recoveryInProgress = successKey === 'tokenGuardV2.inspectionQueued' && failure?.category === 'requires_relogin' + && ['waiting', 'scheduled', 'queued', 'running', 'cooldown', 'verifying'].includes(automationState(result as TokenGuardV2Account)) + if (failure && !recoveryInProgress) error.value = `${t(`tokenGuardV2.operationFailure.reasons.${failure.category}`)} ${t(`tokenGuardV2.operationFailure.actions.${failure.action}`)}` else notice.value = t(successKey, { account: item.account_name }) - await load(true) } catch (value) { error.value = message(value) } finally { + // Keep duplicate actions blocked until the post-action read is applied. + await load(true, true) busyId.value = 0 } } @@ -550,6 +591,7 @@ async function resumeBudget(item: TokenGuardV2Account) { async function toggleSwitch(item: TokenGuardV2Account, field: 'enabled' | 'auto_relogin_enabled', event: Event) { const input = event.target as HTMLInputElement if (busyId.value) { input.checked = item[field]; return } + invalidateLoad() busyId.value = item.account_id; error.value = ''; notice.value = '' try { const saved = await updateTokenGuardV2Switches(item.account_id, { [field]: !item[field] }) @@ -565,7 +607,8 @@ async function toggleSwitch(item: TokenGuardV2Account, field: 'enabled' | 'auto_ async function changeRuntime(field: keyof TokenGuardV2RuntimeSettings, event: Event) { const select = event.target as HTMLSelectElement - if (runtimeSaving.value || !runtimeLoaded.value) return + if (runtimeSaving.value || busyId.value || !runtimeLoaded.value) return + invalidateLoad() const input = { ...runtimeDraft, [field]: field === 'worker_concurrency' ? Number(select.value) : select.value } runtimeSaving.value = true; error.value = ''; notice.value = '' try { @@ -592,9 +635,12 @@ watch(() => filteredAccounts.value.length, (total) => { onMounted(() => { void load() - timer = setInterval(() => { if (document.visibilityState === 'visible' && !editorOpen.value) void load(true) }, 30_000) + timer = setInterval(() => { + currentTime.value = Date.now() + if (document.visibilityState === 'visible' && !editorOpen.value) void load(true) + }, 30_000) }) -onBeforeUnmount(() => { if (timer) clearInterval(timer) }) +onBeforeUnmount(() => { loadGeneration++; if (timer) clearInterval(timer) })