Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 | 111x 111x 111x 111x 111x 111x 111x 32x 32x 32x 32x 218x 218x 18x 1x 1x 17x 17x 17x 17x 17x 17x 17x 67x 67x 3x 67x 67x 67x 67x 67x 54x 54x 3x 4x 3x 4x 4x 4x 15x 15x 2x 2x 2x 1x 2x 7x 2x 2x 3x 3x 1x 1x 2x 4x 10x 10x 7x 7x 3x 3x 1x 1x 2x 8x 8x 2x 2x 6x 6x 3x 3x 2x 2x 2x 5x 4x 4x 1x 1x 1x 2x 1x 1x 155x 9x 9x 8x 8x 1x 1x 2x 2x 7x 7x 7x 3x 3x 3x 1x 1x 7x 56x 56x 56x 56x 56x 5x 5x 5x 141x 141x 2x 141x 3x 141x 2x 141x | /**
* Instance Registry Service
*
* Singleton managing multiple GitLab instances with:
* - Per-instance rate limiting
* - Per-instance introspection caching
* - Connection health tracking
* - Instance registration and lookup
*
* This is the central point for multi-instance support, providing
* a unified interface to access GitLab instances regardless of configuration source.
*/
import { logInfo, logWarn, logDebug } from "../logger.js";
import {
InstanceRateLimiter,
RateLimiterConfig,
RateLimitMetrics,
DEFAULT_RATE_LIMIT_CONFIG,
} from "./InstanceRateLimiter.js";
import {
GitLabInstanceConfig,
GitLabInstanceState,
ConnectionStatus,
CachedIntrospection,
} from "../config/instances-schema.js";
import { loadInstancesConfig, LoadedInstancesConfig } from "../config/instances-loader.js";
import { InstanceConnectionPool, PoolStats } from "./InstanceConnectionPool.js";
import { GraphQLClient } from "../graphql/client.js";
/**
* Instance registry entry combining config, state, and rate limiter
*/
interface RegistryEntry {
config: GitLabInstanceConfig;
state: GitLabInstanceState;
rateLimiter: InstanceRateLimiter;
}
/**
* Instance summary for listing
*/
export interface InstanceSummary {
url: string;
label: string | undefined;
connectionStatus: ConnectionStatus;
lastHealthCheck: Date | null;
hasOAuth: boolean;
rateLimit: RateLimitMetrics;
introspection: {
version: string | null;
tier: string | null;
cachedAt: Date | null;
/** Whether the cached introspection data has expired (TTL: 10 min) */
isExpired: boolean;
};
}
/**
* Introspection cache TTL (10 minutes)
*/
const INTROSPECTION_CACHE_TTL_MS = 10 * 60 * 1000;
/**
* Singleton registry managing all GitLab instances
*/
export class InstanceRegistry {
private static instance: InstanceRegistry | null = null;
private instances = new Map<string, RegistryEntry>();
private configSource: LoadedInstancesConfig["source"] = "none";
private configSourceDetails = "";
private initialized = false;
private constructor() {}
/**
* Get singleton instance
*/
public static getInstance(): InstanceRegistry {
InstanceRegistry.instance ??= new InstanceRegistry();
return InstanceRegistry.instance;
}
/**
* Initialize registry from configuration
* Should be called once at startup
*/
public async initialize(): Promise<void> {
if (this.initialized) {
logDebug("InstanceRegistry already initialized, skipping");
return;
}
const config = await loadInstancesConfig();
this.configSource = config.source;
this.configSourceDetails = config.sourceDetails;
for (const instanceConfig of config.instances) {
this.register(instanceConfig);
}
this.initialized = true;
logInfo("InstanceRegistry initialized", {
source: this.configSource,
sourceDetails: this.configSourceDetails,
instanceCount: this.instances.size,
instances: Array.from(this.instances.keys()),
});
}
/**
* Register a GitLab instance
*/
public register(config: GitLabInstanceConfig): void {
const normalizedUrl = this.normalizeUrl(config.url);
if (this.instances.has(normalizedUrl)) {
logWarn("Instance already registered, updating configuration", {
url: normalizedUrl,
});
}
// Create rate limiter with instance-specific config or defaults
const rateLimiterConfig: RateLimiterConfig = config.rateLimit ?? DEFAULT_RATE_LIMIT_CONFIG;
const rateLimiter = new InstanceRateLimiter(rateLimiterConfig);
// Create initial state
const state: GitLabInstanceState = {
...config,
url: normalizedUrl,
connectionStatus: "healthy",
lastHealthCheck: null,
introspectionCache: null,
};
this.instances.set(normalizedUrl, {
config: { ...config, url: normalizedUrl },
state,
rateLimiter,
});
logDebug("Instance registered", {
url: normalizedUrl,
label: config.label,
hasOAuth: !!config.oauth,
rateLimit: rateLimiterConfig,
});
}
/**
* Get instance entry by URL
*/
public get(baseUrl: string): RegistryEntry | undefined {
const normalizedUrl = this.normalizeUrl(baseUrl);
return this.instances.get(normalizedUrl);
}
/**
* Get instance config by URL
*/
public getConfig(baseUrl: string): GitLabInstanceConfig | undefined {
return this.get(baseUrl)?.config;
}
/**
* Get instance state by URL
*/
public getState(baseUrl: string): GitLabInstanceState | undefined {
return this.get(baseUrl)?.state;
}
/**
* List all registered instances
*/
public list(): InstanceSummary[] {
return Array.from(this.instances.values()).map(entry => {
const cache = entry.state.introspectionCache;
const isExpired =
cache !== null && Date.now() - cache.cachedAt.getTime() > INTROSPECTION_CACHE_TTL_MS;
return {
url: entry.config.url,
label: entry.config.label,
connectionStatus: entry.state.connectionStatus,
lastHealthCheck: entry.state.lastHealthCheck,
hasOAuth: !!entry.config.oauth,
rateLimit: entry.rateLimiter.getMetrics(),
introspection: {
version: cache?.version ?? null,
tier: cache?.tier ?? null,
cachedAt: cache?.cachedAt ?? null,
isExpired,
},
};
});
}
/**
* Check if an instance is registered
*/
public has(baseUrl: string): boolean {
const normalizedUrl = this.normalizeUrl(baseUrl);
return this.instances.has(normalizedUrl);
}
/**
* Unregister an instance
*/
public unregister(baseUrl: string): boolean {
const normalizedUrl = this.normalizeUrl(baseUrl);
const existed = this.instances.delete(normalizedUrl);
if (existed) {
logInfo("Instance unregistered", { url: normalizedUrl });
}
return existed;
}
/**
* Get all registered instance URLs
*/
public getUrls(): string[] {
return Array.from(this.instances.keys());
}
/**
* Get the first (or default) instance URL
* Used for backward compatibility when no specific instance is specified
*/
public getDefaultUrl(): string | undefined {
const urls = this.getUrls();
return urls.length > 0 ? urls[0] : undefined;
}
/**
* Acquire a rate limit slot for an instance
* Returns a release function that MUST be called when request completes
*/
public async acquireSlot(baseUrl: string): Promise<() => void> {
const entry = this.get(baseUrl);
if (!entry) {
// If instance not registered, allow request without rate limiting.
// This supports dynamic instances not in config (e.g., non-GitLab URLs via enhancedFetch).
// Use debug level to avoid noisy logs in normal operation.
logDebug("Rate limit slot requested for unregistered instance, allowing", {
url: baseUrl,
});
return () => {};
}
return entry.rateLimiter.acquire();
}
/**
* Get rate limit metrics for an instance
*/
public getRateLimitMetrics(baseUrl: string): RateLimitMetrics | undefined {
return this.get(baseUrl)?.rateLimiter.getMetrics();
}
/**
* Get cached introspection for an instance
*/
public getIntrospection(baseUrl: string): CachedIntrospection | null {
const entry = this.get(baseUrl);
if (!entry) return null;
const cache = entry.state.introspectionCache;
if (!cache) return null;
// Check if cache is still valid
const age = Date.now() - cache.cachedAt.getTime();
if (age > INTROSPECTION_CACHE_TTL_MS) {
logDebug("Introspection cache expired", {
url: baseUrl,
ageMs: age,
ttlMs: INTROSPECTION_CACHE_TTL_MS,
});
return null;
}
return cache;
}
/**
* Set cached introspection for an instance
*/
public setIntrospection(baseUrl: string, introspection: CachedIntrospection): void {
const entry = this.get(baseUrl);
if (!entry) {
logWarn("Cannot cache introspection for unregistered instance", { url: baseUrl });
return;
}
entry.state.introspectionCache = introspection;
logDebug("Introspection cached for instance", {
url: baseUrl,
version: introspection.version,
tier: introspection.tier,
});
}
/**
* Update connection status for an instance
*/
public updateConnectionStatus(baseUrl: string, status: ConnectionStatus): void {
const entry = this.get(baseUrl);
if (!entry) return;
entry.state.connectionStatus = status;
entry.state.lastHealthCheck = new Date();
logDebug("Instance connection status updated", {
url: baseUrl,
status,
});
}
/**
* Clear introspection cache for an instance (or all instances)
*/
public clearIntrospectionCache(baseUrl?: string): void {
if (baseUrl) {
const entry = this.get(baseUrl);
if (entry) {
entry.state.introspectionCache = null;
logDebug("Introspection cache cleared", { url: baseUrl });
}
} else {
for (const entry of this.instances.values()) {
entry.state.introspectionCache = null;
}
logDebug("All introspection caches cleared");
}
}
/**
* Get configuration source info
*/
public getConfigSource(): { source: string; details: string } {
return {
source: this.configSource,
details: this.configSourceDetails,
};
}
/**
* Check if registry has been initialized
*/
public isInitialized(): boolean {
return this.initialized;
}
/**
* Get a thread-safe GraphQL client for an instance
*
* This is the preferred way to get a GraphQL client for multi-instance setups.
* Each instance gets its own client with dedicated connection pool, avoiding
* the singleton endpoint mutation issue.
*
* @param baseUrl - Instance base URL
* @param authHeaders - Optional auth headers (for OAuth per-request tokens)
* @returns GraphQL client or undefined if instance not registered
*/
public getGraphQLClient(
baseUrl: string,
authHeaders?: Record<string, string>
): GraphQLClient | undefined {
const entry = this.get(baseUrl);
if (!entry) return undefined;
const connectionPool = InstanceConnectionPool.getInstance();
return connectionPool.getGraphQLClient(entry.config, authHeaders);
}
/**
* Get connection pool statistics for all instances
*/
public getConnectionPoolStats(): PoolStats[] {
const connectionPool = InstanceConnectionPool.getInstance();
return connectionPool.getStats();
}
/**
* Get connection pool statistics for a specific instance
*/
public getInstancePoolStats(baseUrl: string): PoolStats | undefined {
const connectionPool = InstanceConnectionPool.getInstance();
return connectionPool.getInstanceStats(baseUrl);
}
/**
* Get the Undici dispatcher (HTTP/2 connection pool) for an instance.
* Used by enhancedFetch for per-instance connection pooling.
*
* Lazily creates the connection pool if the instance is registered but
* pool doesn't exist yet (e.g., REST-only calls before any GraphQL calls).
*
* @param baseUrl - GitLab instance base URL
* @returns Undici Pool/Dispatcher or undefined if instance not registered
*/
public getDispatcher(baseUrl: string): unknown {
const connectionPool = InstanceConnectionPool.getInstance();
let dispatcher = connectionPool.getDispatcher(baseUrl);
// Lazily create pool if instance is registered but pool doesn't exist yet
// This ensures per-instance TLS settings are applied for REST calls
if (!dispatcher) {
const normalizedUrl = this.normalizeUrl(baseUrl);
const entry = this.instances.get(normalizedUrl);
if (entry) {
// Creating the GraphQL client also initializes the connection pool
connectionPool.getGraphQLClient(entry.config);
dispatcher = connectionPool.getDispatcher(baseUrl);
}
}
return dispatcher;
}
/**
* Reset registry (for testing)
*/
public reset(): void {
this.instances.clear();
this.configSource = "none";
this.configSourceDetails = "";
this.initialized = false;
logDebug("InstanceRegistry reset");
}
/**
* Reset registry and destroy connection pools (for testing)
*/
public async resetWithPools(): Promise<void> {
this.reset();
await InstanceConnectionPool.resetInstance();
logDebug("InstanceRegistry and connection pools reset");
}
/**
* Normalize URL for consistent lookup
*/
private normalizeUrl(url: string): string {
let normalized = url;
// Remove trailing slash
if (normalized.endsWith("/")) {
normalized = normalized.slice(0, -1);
}
// Remove /api/v4 suffix
if (normalized.endsWith("/api/v4")) {
normalized = normalized.slice(0, -7);
}
// Remove /api/graphql suffix
if (normalized.endsWith("/api/graphql")) {
normalized = normalized.slice(0, -12);
}
return normalized;
}
}
|