File size: 6,203 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/**

 * Credential Health Cache

 *

 * In-memory cache for provider credential health status.

 * Follows the same pattern as localHealthCheck.ts β€” globalThis singleton

 * survives HMR re-evaluation.

 *

 * Tracks testStatus, lastError, lastTested per connectionId with

 * configurable TTL. Auto-expiry on read for stale entries.

 */

export interface CredentialHealthStatus {
  connectionId: string;
  provider: string;
  /** "active" | "error" | "unknown" β€” mirrors testStatus from provider_connections */
  status: "active" | "error" | "unknown";
  lastTested: Date;
  lastError?: string;
  lastErrorType?: string;
  lastErrorSource?: string;
  /** Consecutive failures since last success */
  consecutiveFailures: number;
  /** Response time of the last test in ms */
  responseTimeMs?: number;
}

export interface CredentialCacheEntry {
  status: CredentialHealthStatus;
  /** Expiry timestamp (epoch ms) */
  expiresAt: number;
}

// ── Config ────────────────────────────────────────────────────────────────

const DEFAULT_TTL_MS = 5 * 60 * 1000; // 5 minutes
const STALE_THRESHOLD_MS = 10 * 60 * 1000; // 10 minutes β€” considered stale
const MAX_ENTRIES = 500;

// ── State (globalThis singleton) ──────────────────────────────────────────

declare global {
  var __omnirouteCredentialCache:
    | {
        initialized: boolean;
        cache: Map<string, CredentialCacheEntry>;
      }
    | undefined;
}

function getCacheState() {
  if (!globalThis.__omnirouteCredentialCache) {
    globalThis.__omnirouteCredentialCache = {
      initialized: false,
      cache: new Map(),
    };
  }
  return globalThis.__omnirouteCredentialCache;
}

// ── Public API ────────────────────────────────────────────────────────────

/**

 * Get cached credential health for a connection.

 * Returns undefined if not cached or expired.

 */
export function getCredentialHealth(connectionId: string): CredentialHealthStatus | undefined {
  const state = getCacheState();
  const entry = state.cache.get(connectionId);

  if (!entry) return undefined;
  if (Date.now() > entry.expiresAt) {
    // Expired β€” remove and return undefined
    state.cache.delete(connectionId);
    return undefined;
  }

  return entry.status;
}

/**

 * Check if a connection's credential health is "active" (recently tested and passing).

 * Returns:

 *   - true  β†’ healthy, proceed

 *   - false β†’ known-bad, skip

 *   - undefined β†’ unknown / not cached (proceed but mark as unchecked)

 */
export function isCredentialHealthy(connectionId: string): boolean | undefined {
  const status = getCredentialHealth(connectionId);
  if (!status) return undefined;

  if (status.status === "active") return true;
  if (status.status === "error") return false;

  return undefined;
}

/**

 * Check if a connection's credential status is stale (not tested recently).

 */
export function isCredentialStale(connectionId: string): boolean {
  const status = getCredentialHealth(connectionId);
  if (!status) return true; // Not cached = stale

  const age = Date.now() - status.lastTested.getTime();
  return age > STALE_THRESHOLD_MS;
}

/**

 * Update the cached health status for a connection.

 */
export function setCredentialHealth(

  connectionId: string,

  provider: string,

  status: "active" | "error" | "unknown",

  lastError?: string,

  lastErrorType?: string,

  lastErrorSource?: string,

  responseTimeMs?: number

): void {
  const state = getCacheState();

  // Enforce max entries (evict oldest if full)
  if (state.cache.size >= MAX_ENTRIES) {
    const oldest = state.cache.entries().next().value;
    if (oldest) state.cache.delete(oldest[0]);
  }

  const prev = state.cache.get(connectionId);
  const consecutiveFailures =
    status === "error"
      ? (prev?.status.consecutiveFailures ?? 0) + 1
      : status === "active"
        ? 0
        : (prev?.status.consecutiveFailures ?? 0);

  state.cache.set(connectionId, {
    status: {
      connectionId,
      provider,
      status,
      lastTested: new Date(),
      lastError,
      lastErrorType,
      lastErrorSource,
      consecutiveFailures,
      responseTimeMs,
    },
    expiresAt: Date.now() + DEFAULT_TTL_MS,
  });
}

/**

 * Remove a connection from the cache (e.g., connection deleted).

 */
export function removeCredentialHealth(connectionId: string): void {
  const state = getCacheState();
  state.cache.delete(connectionId);
}

/**

 * Get all cached credential health statuses (for monitoring API).

 */
export function getAllCredentialHealth(): Record<string, CredentialHealthStatus> {
  const state = getCacheState();
  const result: Record<string, CredentialHealthStatus> = {};

  for (const [id, entry] of state.cache.entries()) {
    if (Date.now() <= entry.expiresAt) {
      result[id] = entry.status;
    } else {
      state.cache.delete(id); // Clean expired on read
    }
  }

  return result;
}

/**

 * Get cache summary stats for health API.

 */
export function getCredentialHealthSummary(): {
  total: number;
  healthy: number;
  failed: number;
  unknown: number;
  stale: number;
} {
  const all = getAllCredentialHealth();
  const entries = Object.values(all);
  const now = Date.now();

  return {
    total: entries.length,
    healthy: entries.filter((e) => e.status === "active").length,
    failed: entries.filter((e) => e.status === "error").length,
    unknown: entries.filter((e) => e.status === "unknown").length,
    stale: entries.filter((e) => now - e.lastTested.getTime() > STALE_THRESHOLD_MS).length,
  };
}

/**

 * Mark cache as initialized (called by scheduler on startup).

 */
export function initCredentialCache(): void {
  getCacheState().initialized = true;
}