|
| 1 | +# Data Model: OAuth Token Refresh Reliability |
| 2 | + |
| 3 | +**Feature**: 023-oauth-state-persistence |
| 4 | +**Date**: 2026-01-12 |
| 5 | + |
| 6 | +## Entity Overview |
| 7 | + |
| 8 | +This feature primarily extends existing entities rather than creating new ones. The key data structures involved are: |
| 9 | + |
| 10 | +1. **OAuthTokenRecord** (existing) - Token persistence |
| 11 | +2. **RefreshSchedule** (existing) - Proactive refresh scheduling |
| 12 | +3. **HealthCalculatorInput** (existing) - Health status calculation |
| 13 | +4. **OAuth Metrics** (new) - Prometheus metrics for observability |
| 14 | + |
| 15 | +## Entity Definitions |
| 16 | + |
| 17 | +### 1. OAuthTokenRecord (Existing - No Changes) |
| 18 | + |
| 19 | +**Location**: `internal/storage/models.go` |
| 20 | + |
| 21 | +```go |
| 22 | +type OAuthTokenRecord struct { |
| 23 | + ServerName string `json:"server_name"` // Storage key (serverName_hash) |
| 24 | + DisplayName string `json:"display_name"` // Actual server name |
| 25 | + AccessToken string `json:"access_token"` |
| 26 | + RefreshToken string `json:"refresh_token"` // Required for proactive refresh |
| 27 | + TokenType string `json:"token_type"` |
| 28 | + ExpiresAt time.Time `json:"expires_at"` |
| 29 | + Scopes []string `json:"scopes"` |
| 30 | + ClientID string `json:"client_id"` // For DCR |
| 31 | + ClientSecret string `json:"client_secret"` // For DCR |
| 32 | + Created time.Time `json:"created"` |
| 33 | + Updated time.Time `json:"updated"` |
| 34 | +} |
| 35 | +``` |
| 36 | + |
| 37 | +**Relationships**: |
| 38 | +- Referenced by: RefreshSchedule (via DisplayName) |
| 39 | +- Stored in: BBolt `oauth_tokens` bucket |
| 40 | + |
| 41 | +**Validation Rules**: |
| 42 | +- `ServerName`: Required, unique per OAuth server |
| 43 | +- `AccessToken`: Required when authenticated |
| 44 | +- `RefreshToken`: Optional, enables proactive refresh |
| 45 | +- `ExpiresAt`: Required for scheduling refresh |
| 46 | + |
| 47 | +### 2. RefreshSchedule (Existing - Extended) |
| 48 | + |
| 49 | +**Location**: `internal/oauth/refresh_manager.go` |
| 50 | + |
| 51 | +```go |
| 52 | +type RefreshSchedule struct { |
| 53 | + ServerName string // Server identifier |
| 54 | + ExpiresAt time.Time // Token expiration time |
| 55 | + ScheduledRefresh time.Time // When refresh will be attempted |
| 56 | + RetryCount int // Number of failed attempts |
| 57 | + LastError error // Most recent failure reason |
| 58 | + Timer *time.Timer // Scheduled timer (internal) |
| 59 | + |
| 60 | + // NEW FIELDS for this feature: |
| 61 | + RetryBackoff time.Duration // Current backoff duration |
| 62 | + MaxBackoff time.Duration // Maximum backoff (5 minutes) |
| 63 | + LastAttempt time.Time // Time of last refresh attempt |
| 64 | + RefreshState RefreshState // Current state for health reporting |
| 65 | +} |
| 66 | + |
| 67 | +// NEW: Refresh state for health status integration |
| 68 | +type RefreshState int |
| 69 | + |
| 70 | +const ( |
| 71 | + RefreshStateIdle RefreshState = iota // No refresh needed |
| 72 | + RefreshStateScheduled // Proactive refresh scheduled |
| 73 | + RefreshStateRetrying // Failed, retrying with backoff |
| 74 | + RefreshStateFailed // Permanently failed (needs re-auth) |
| 75 | +) |
| 76 | +``` |
| 77 | + |
| 78 | +**Lifecycle Invariant**: Schedule exists iff tokens exist for server (created post-auth or when loaded at startup, destroyed when tokens removed). |
| 79 | + |
| 80 | +**State Transitions**: |
| 81 | +``` |
| 82 | +┌─────────────────────────────────────────────────────────────┐ |
| 83 | +│ │ |
| 84 | +│ [Token Saved] ──► Scheduled ──► [80% lifetime] ──► Idle │ |
| 85 | +│ │ │ │ |
| 86 | +│ │ [Refresh Failed] │ │ |
| 87 | +│ ▼ │ │ |
| 88 | +│ Retrying ◄─────────────────────────┘ │ |
| 89 | +│ │ │ |
| 90 | +│ │ [invalid_grant] │ |
| 91 | +│ ▼ │ |
| 92 | +│ Failed ──► [Re-auth] ──► Scheduled │ |
| 93 | +│ │ |
| 94 | +└─────────────────────────────────────────────────────────────┘ |
| 95 | +``` |
| 96 | + |
| 97 | +### 3. HealthCalculatorInput (Existing - Extended) |
| 98 | + |
| 99 | +**Location**: `internal/health/calculator.go` |
| 100 | + |
| 101 | +```go |
| 102 | +type HealthCalculatorInput struct { |
| 103 | + // Existing fields... |
| 104 | + OAuthRequired bool |
| 105 | + OAuthStatus string // "authenticated", "expired", "error", "none" |
| 106 | + TokenExpiresAt *time.Time |
| 107 | + HasRefreshToken bool |
| 108 | + UserLoggedOut bool |
| 109 | + |
| 110 | + // NEW FIELDS for this feature: |
| 111 | + RefreshState RefreshState // From RefreshSchedule |
| 112 | + RefreshRetryCount int // Number of retry attempts |
| 113 | + RefreshLastError string // Human-readable error message |
| 114 | + RefreshNextAttempt *time.Time // When next retry will occur |
| 115 | +} |
| 116 | +``` |
| 117 | + |
| 118 | +**Health Output Mapping**: |
| 119 | + |
| 120 | +| RefreshState | Health Level | Summary | Action | |
| 121 | +|--------------|--------------|---------|--------| |
| 122 | +| Idle | healthy | "Connected" | - | |
| 123 | +| Scheduled | healthy | "Token refresh scheduled" | - | |
| 124 | +| Retrying | degraded | "Token refresh retry pending" | view_logs | |
| 125 | +| Failed | unhealthy | "Refresh token expired" | login | |
| 126 | + |
| 127 | +### 4. OAuth Metrics (New) |
| 128 | + |
| 129 | +**Location**: `internal/observability/metrics.go` |
| 130 | + |
| 131 | +```go |
| 132 | +// Added to MetricsManager struct |
| 133 | +type MetricsManager struct { |
| 134 | + // Existing fields... |
| 135 | + |
| 136 | + // NEW: OAuth refresh metrics |
| 137 | + oauthRefreshTotal *prometheus.CounterVec |
| 138 | + oauthRefreshDuration *prometheus.HistogramVec |
| 139 | +} |
| 140 | +``` |
| 141 | + |
| 142 | +**Metric Definitions**: |
| 143 | + |
| 144 | +```go |
| 145 | +// Counter: Total refresh attempts |
| 146 | +oauthRefreshTotal = prometheus.NewCounterVec( |
| 147 | + prometheus.CounterOpts{ |
| 148 | + Name: "mcpproxy_oauth_refresh_total", |
| 149 | + Help: "Total number of OAuth token refresh attempts", |
| 150 | + }, |
| 151 | + []string{"server", "result"}, |
| 152 | +) |
| 153 | + |
| 154 | +// Histogram: Refresh duration |
| 155 | +oauthRefreshDuration = prometheus.NewHistogramVec( |
| 156 | + prometheus.HistogramOpts{ |
| 157 | + Name: "mcpproxy_oauth_refresh_duration_seconds", |
| 158 | + Help: "OAuth token refresh duration in seconds", |
| 159 | + Buckets: []float64{0.1, 0.5, 1, 2, 5, 10, 30}, |
| 160 | + }, |
| 161 | + []string{"server", "result"}, |
| 162 | +) |
| 163 | +``` |
| 164 | + |
| 165 | +**Labels**: |
| 166 | +- `server`: Server name (e.g., "github-mcp") |
| 167 | +- `result`: One of: |
| 168 | + - `success`: Refresh completed successfully |
| 169 | + - `failed_network`: Network error (retryable) |
| 170 | + - `failed_invalid_grant`: Refresh token expired (permanent) |
| 171 | + - `failed_other`: Other failures |
| 172 | + |
| 173 | +## Configuration Constants |
| 174 | + |
| 175 | +**Location**: `internal/oauth/refresh_manager.go` |
| 176 | + |
| 177 | +```go |
| 178 | +const ( |
| 179 | + // Existing |
| 180 | + DefaultRefreshThreshold = 0.8 // Refresh at 80% of token lifetime |
| 181 | + MinRefreshInterval = 5 * time.Second |
| 182 | + |
| 183 | + // MODIFIED for this feature |
| 184 | + RetryBackoffBase = 10 * time.Second // Was: 2s, Now: 10s (FR-008) |
| 185 | + MaxRetryBackoff = 5 * time.Minute // NEW: Cap at 5 minutes (FR-009) |
| 186 | + MaxRetries = 0 // NEW: Unlimited (until expiration) |
| 187 | +) |
| 188 | +``` |
| 189 | + |
| 190 | +## Data Flow |
| 191 | + |
| 192 | +### Startup Recovery Flow |
| 193 | + |
| 194 | +``` |
| 195 | +1. RefreshManager.Start() |
| 196 | + │ |
| 197 | + ├─► storage.ListOAuthTokens() |
| 198 | + │ |
| 199 | + └─► For each token: |
| 200 | + │ |
| 201 | + ├─► If not expired: |
| 202 | + │ └─► scheduleRefreshLocked(80% lifetime) |
| 203 | + │ |
| 204 | + └─► If access token expired, refresh token exists: |
| 205 | + └─► executeRefresh() immediately |
| 206 | + │ |
| 207 | + ├─► Success: scheduleRefreshLocked(new 80%) |
| 208 | + │ |
| 209 | + └─► Failure: rescheduleWithBackoff() |
| 210 | +``` |
| 211 | + |
| 212 | +### Proactive Refresh Flow |
| 213 | + |
| 214 | +``` |
| 215 | +1. Timer fires at 80% lifetime |
| 216 | + │ |
| 217 | + └─► executeRefresh() |
| 218 | + │ |
| 219 | + ├─► runtime.RefreshOAuthToken(serverName) |
| 220 | + │ │ |
| 221 | + │ └─► mcp-go client.Start() with TokenStore |
| 222 | + │ |
| 223 | + ├─► Success: |
| 224 | + │ ├─► Emit metrics (success) |
| 225 | + │ ├─► Update health status (Idle) |
| 226 | + │ └─► Schedule next refresh |
| 227 | + │ |
| 228 | + └─► Failure: |
| 229 | + ├─► Emit metrics (failed_*) |
| 230 | + ├─► Update health status (Retrying/Failed) |
| 231 | + └─► Reschedule with backoff (if retryable) |
| 232 | +``` |
| 233 | + |
| 234 | +### Health Status Integration Flow |
| 235 | + |
| 236 | +``` |
| 237 | +1. HealthCalculator.Calculate() |
| 238 | + │ |
| 239 | + ├─► Get RefreshSchedule for server |
| 240 | + │ |
| 241 | + └─► Map RefreshState to health: |
| 242 | + │ |
| 243 | + ├─► Retrying: degraded + "Refresh retry pending" |
| 244 | + │ |
| 245 | + ├─► Failed: unhealthy + "Refresh token expired" |
| 246 | + │ |
| 247 | + └─► Other: existing logic |
| 248 | +``` |
| 249 | + |
| 250 | +## Storage Bucket |
| 251 | + |
| 252 | +**Bucket**: `oauth_tokens` (existing) |
| 253 | +**Database**: `~/.mcpproxy/config.db` (BBolt) |
| 254 | + |
| 255 | +No schema changes required. The `OAuthTokenRecord` structure is sufficient for all refresh operations. |
0 commit comments