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 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 | 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 103x 103x 103x 44x 44x 103x 103x 103x 44x 44x 123x 8x 8x 8x 8x 64x 64x 68x 4x 3x 1x 1x 64x 5x 5x 5x 12x 3x 9x 4x 4x 5x 4x 4x 111x 111x 66x 66x 66x 66x 2x 2x 2x 64x 64x 2x 62x 62x 62x 62x 56x 56x 56x 55x 62x 62x 62x 62x 62x 62x 7x 62x 1x 61x 1x 60x 60x 60x 59x 59x 59x 59x 59x 59x 59x 59x 5x 5x 5x 4x 3x 3x 3x 3x 1x 1x 5x 5x 5x 54x 54x 8x 8x 8x 4x 4x 4x 50x 50x 50x 2x 2x 2x 2x 2x 2x 48x 48x 45x 45x 45x 45x 45x 45x 47x 47x 230x 184x 6x 3x 6x 6x 14x 14x 14x 1x 13x 13x 3x 10x 10x 10x 4x 4x 4x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 30x 30x 15x 15x 15x 15x 15x 9x 6x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 5x 2x 5x 2x 6x 3x 3x 5x 2x 2x 11x 1x 1x 7x 7x 6x 6x 6x 6x 8x 8x 7x 7x 7x 7x 12x 12x 11x 11x 11x 11x 6x 6x 5x 5x 5x 4x 4x 3x 3x 3x 7x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 5x 5x 5x 5x 5x 5x 5x 4x 5x 4x 4x 4x 3x 2x 2x 2x 1x 1x 2x 7x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 77x 77x 77x 77x 77x 77x 77x 77x 77x | import { GraphQLClient } from '../graphql/client';
import { GitLabVersionDetector, GitLabInstanceInfo } from './GitLabVersionDetector';
import { SchemaIntrospector, SchemaInfo } from './SchemaIntrospector';
import {
detectTokenScopes,
logTokenScopeInfo,
getToolScopeRequirements,
TokenScopeInfo,
} from './TokenScopeDetector';
import {
GITLAB_BASE_URL,
GITLAB_TOKEN,
GITLAB_INSTANCE_CACHE_MAX,
GITLAB_INSTANCE_TTL_MS,
} from '../config';
import { isOAuthEnabled, getGitLabApiUrlFromContext } from '../oauth/index';
import { enhancedFetch } from '../utils/fetch';
import { logInfo, logDebug, logError } from '../logger';
import { InstanceRegistry } from './InstanceRegistry';
import { CachedIntrospection } from '../config/instances-schema';
import { normalizeInstanceUrl } from '../utils/url';
interface CacheEntry {
schemaInfo: SchemaInfo;
instanceInfo: GitLabInstanceInfo;
timestamp: number;
}
/**
* Per-URL instance state. Each GitLab URL gets isolated client, detectors,
* and introspection data — no shared mutable fields to overwrite.
*/
export interface InstanceState {
client: GraphQLClient;
versionDetector: GitLabVersionDetector;
schemaIntrospector: SchemaIntrospector;
instanceInfo: GitLabInstanceInfo | null;
schemaInfo: SchemaInfo | null;
tokenScopeInfo: TokenScopeInfo | null;
isInitialized: boolean;
/** Tracks which instance URL the cached instanceInfo/schemaInfo belongs to */
introspectedInstanceUrl: string | null;
}
export class ConnectionManager {
private static instance: ConnectionManager | null = null;
/** Per-URL isolated state — each initialize(url) creates its own entry */
private instances = new Map<string, InstanceState>();
/** The "active" instance URL — used as default for no-arg getClient()/getInstanceInfo() */
private currentInstanceUrl: string | null = null;
/** Deduplication map: prevents thundering herd on concurrent ensureIntrospected() calls */
private introspectionPromises = new Map<string, Promise<void>>();
private static introspectionCache = new Map<string, CacheEntry>();
private static readonly CACHE_TTL = 10 * 60 * 1000; // 10 minutes in milliseconds
/** In-flight initialize promises keyed by instance URL — prevents concurrent initialize()
* calls for the same URL from doing duplicate work when HealthMonitor's timeout races. */
private initializePromises = new Map<string, Promise<void>>();
/** Tracks the most recently requested URL so stale inits don't overwrite currentInstanceUrl.
* E.g. init(A) starts, init(B) starts, A finishes last — A must not rebind to itself. */
private latestRequestedUrl: string | null = null;
/**
* Last-access timestamps for per-URL instance entries (epoch ms).
* Used for both TTL expiry and LRU eviction ordering.
*/
private readonly instanceAccessTimes = new Map<string, number>();
/**
* Maximum number of InstanceState entries retained in memory.
* Configurable via GITLAB_INSTANCE_CACHE_MAX; mutable for tests.
* The Number.isFinite guard handles partial test mocks that omit these constants.
*/
private static MAX_INSTANCES: number = Number.isFinite(GITLAB_INSTANCE_CACHE_MAX)
? GITLAB_INSTANCE_CACHE_MAX
: 100;
/**
* Time-to-live for idle InstanceState entries (milliseconds).
* Entries not accessed within this window are evicted on the next insert.
* Configurable via GITLAB_INSTANCE_TTL_MS; mutable for tests.
*/
private static INSTANCE_TTL_MS: number = Number.isFinite(GITLAB_INSTANCE_TTL_MS)
? GITLAB_INSTANCE_TTL_MS
: 60 * 60 * 1000;
/** Update the LRU access timestamp for a cached instance URL. */
private touchInstance(url: string): void {
this.instanceAccessTimes.set(url, Date.now());
}
/**
* Remove an instance entry from all internal tracking maps.
* Does NOT update currentInstanceUrl — callers that evict protected entries
* (evictExpired / evictLRUIfOverCapacity) skip currentInstanceUrl explicitly.
*
* Also clears the corresponding introspectionCache entries so schema payloads
* don't accumulate for evicted URLs (both the bare-URL key and the legacy
* /api/graphql-suffixed key used by older cache writers).
*/
private dropInstance(url: string): void {
this.instances.delete(url);
this.instanceAccessTimes.delete(url);
ConnectionManager.introspectionCache.delete(url);
ConnectionManager.introspectionCache.delete(`${url}/api/graphql`);
}
/**
* Evict all InstanceState entries whose last-access time exceeds INSTANCE_TTL_MS.
* Called on every new insertion to reclaim memory without a background task.
*
* Skipped entries (never evicted here):
* - currentInstanceUrl — keep the active instance alive regardless of age
* - URLs with an in-flight initialize or introspection promise — evicting a partially
* constructed entry would orphan callers awaiting those promises
*/
private evictExpired(): void {
const now = Date.now();
for (const [url, accessedAt] of this.instanceAccessTimes) {
if (now - accessedAt <= ConnectionManager.INSTANCE_TTL_MS) continue;
if (
url === this.currentInstanceUrl ||
this.initializePromises.has(url) ||
this.introspectionPromises.has(url)
)
continue;
this.dropInstance(url);
logDebug('Evicted expired InstanceState', { url, ageMs: now - accessedAt });
}
}
/**
* Evict the least-recently-used InstanceState entries until
* instances.size <= MAX_INSTANCES. Called after every new insertion.
*
* Same skip rules as evictExpired: never evicts currentInstanceUrl or
* entries with in-flight operations. If all remaining entries are
* protected the loop exits early (capacity may temporarily exceed the limit).
*/
private evictLRUIfOverCapacity(): void {
while (this.instances.size > ConnectionManager.MAX_INSTANCES) {
let lruUrl: string | null = null;
let lruTime = Infinity;
for (const [url, accessedAt] of this.instanceAccessTimes) {
if (
url === this.currentInstanceUrl ||
this.initializePromises.has(url) ||
this.introspectionPromises.has(url)
)
continue;
if (accessedAt < lruTime) {
lruTime = accessedAt;
lruUrl = url;
}
}
if (!lruUrl) break; // All remaining entries are protected — cannot evict further
this.dropInstance(lruUrl);
logDebug('Evicted LRU InstanceState', { url: lruUrl });
}
}
private constructor() {}
public static getInstance(): ConnectionManager {
ConnectionManager.instance ??= new ConnectionManager();
return ConnectionManager.instance;
}
public async initialize(instanceUrl?: string): Promise<void> {
const url = normalizeInstanceUrl(instanceUrl ?? GITLAB_BASE_URL);
this.latestRequestedUrl = url;
// Already initialized for this URL — nothing to do
const existing = this.instances.get(url);
if (existing?.isInitialized) {
// Update LRU timestamp: callers that re-request the same URL (e.g. HealthMonitor,
// per-request OAuth bootstrap) must keep the entry alive in the LRU window.
this.touchInstance(url);
// Update currentInstanceUrl to the requested URL
this.currentInstanceUrl = url;
return;
}
// Deduplicate concurrent initialize() calls for the same URL.
// HealthMonitor calls clearInflight(url) after timeout to prevent a hung
// doInitialize() from blocking all future reconnect attempts.
const inflight = this.initializePromises.get(url);
if (inflight) {
return inflight;
}
const promise = this.doInitialize(url);
this.initializePromises.set(url, promise);
try {
await promise;
// Only update currentInstanceUrl if:
// 1. This is still OUR promise AND this is the most recently requested URL
// (prevents stale init A from overwriting after newer init B took over), OR
// 2. No currentInstanceUrl is set AND init succeeded — bootstrap fallback
// so no-arg callers have a URL even if this wasn't the latest request.
const isOurPromise = this.initializePromises.get(url) === promise;
const initSucceeded = this.instances.get(url)?.isInitialized === true;
if (
(isOurPromise && url === this.latestRequestedUrl) ||
(!this.currentInstanceUrl && initSucceeded)
) {
this.currentInstanceUrl = url;
}
} finally {
// Guard: only delete if this is still OUR promise (clearInflight from a
// timed-out attempt A must not wipe retry B's fresh promise).
Eif (this.initializePromises.get(url) === promise) {
this.initializePromises.delete(url);
}
}
}
private async doInitialize(baseUrl: string): Promise<void> {
let state: InstanceState | undefined;
try {
const oauthMode = isOAuthEnabled();
// Initialize InstanceRegistry for multi-instance support
const registry = InstanceRegistry.getInstance();
if (!registry.isInitialized()) {
await registry.initialize();
}
// In OAuth mode, token comes from request context via enhancedFetch
// In static mode, require both base URL and token
if (!baseUrl) {
throw new Error('GitLab base URL is required');
}
if (!oauthMode && !GITLAB_TOKEN) {
throw new Error(
'GITLAB_TOKEN is required in static authentication mode. ' +
'Run `npx @structured-world/gitlab-mcp setup` for interactive configuration, ' +
'or set the environment variable and restart. ' +
'Docs: https://gitlab-mcp.sw.foundation/guide/quick-start',
);
}
// Construct GraphQL endpoint from base URL
const endpoint = `${baseUrl}/api/graphql`;
// In OAuth mode, don't set static auth header
// enhancedFetch will add the token from request context
// GITLAB_TOKEN is guaranteed non-empty here (validated above for non-OAuth mode)
const clientOptions: { headers?: Record<string, string> } = oauthMode
? {}
: { headers: { 'PRIVATE-TOKEN': String(GITLAB_TOKEN) } };
const client = new GraphQLClient(endpoint, clientOptions);
const versionDetector = new GitLabVersionDetector(client);
const schemaIntrospector = new SchemaIntrospector(client);
// Create per-URL state entry (assigned to outer `let state` for catch guard)
state = {
client,
versionDetector,
schemaIntrospector,
instanceInfo: null,
schemaInfo: null,
tokenScopeInfo: null,
isInitialized: false,
introspectedInstanceUrl: null,
};
this.instances.set(baseUrl, state);
// Record access time and reclaim memory from idle/old entries.
// initializePromises.has(baseUrl) is true at this point, so the new
// entry is protected from immediate eviction by the skip rules.
this.touchInstance(baseUrl);
this.evictExpired();
this.evictLRUIfOverCapacity();
// In OAuth mode, try unauthenticated version detection first
// Many GitLab instances expose /api/v4/version without auth
if (oauthMode) {
// This request is intentionally unauthenticated because many GitLab
// instances expose /api/v4/version without authentication.
// skipAuth prevents enhancedFetch from emitting OAuth "no token context"
// warnings for this deliberate version probe.
logInfo('OAuth mode: attempting unauthenticated version detection');
try {
const versionResponse = await enhancedFetch(`${baseUrl}/api/v4/version`, {
retry: false,
skipAuth: true,
});
if (versionResponse.ok) {
const versionData = (await versionResponse.json()) as {
version: string;
enterprise?: boolean;
};
logInfo('Detected GitLab version without authentication', {
version: versionData.version,
});
// Create basic instance info from unauthenticated response
// Default to "premium" tier for enterprise instances - will be refined on first authenticated request
state.instanceInfo = {
version: versionData.version,
tier: versionData.enterprise ? 'premium' : 'free',
features: this.getDefaultFeatures(versionData.enterprise ?? false),
detectedAt: new Date(),
};
// Schema introspection still deferred (requires auth for full introspection)
logInfo(
'OAuth mode: version detected, full introspection deferred until first authenticated request',
);
} else {
logInfo(
'OAuth mode: unauthenticated version detection failed, deferring all introspection',
{
status: versionResponse.status,
},
);
}
} catch (error) {
// Intentionally swallowed: the version probe is a best-effort optimization
// in OAuth mode. Even if GitLab is unreachable here, the OAuth client is
// ready — actual connectivity is verified when the first authenticated
// request arrives. HealthMonitor may also detect unreachability via its
// immediate post-initialization probe and subsequent periodic health checks.
logInfo(
'OAuth mode: unauthenticated version detection failed, deferring all introspection',
{
error: error instanceof Error ? error.message : String(error),
},
);
}
// Verify state is still ours (reinitialize may have replaced it during async work)
Iif (this.instances.get(baseUrl) !== state) return;
state.isInitialized = true;
return;
}
// Step 1: Detect token scopes BEFORE GraphQL introspection
// This prevents ugly 401 stack traces when token lacks api/read_api scope
state.tokenScopeInfo = await detectTokenScopes(baseUrl);
if (state.tokenScopeInfo) {
// Log token scope info — derive total tools dynamically from scope requirements map
const totalTools = Object.keys(getToolScopeRequirements()).length;
logTokenScopeInfo(state.tokenScopeInfo, totalTools, baseUrl);
// If token lacks GraphQL access, skip introspection entirely
if (!state.tokenScopeInfo.hasGraphQLAccess) {
// Detect version via REST (doesn't require api scope for most GitLab versions)
state.instanceInfo = await this.detectVersionViaREST(baseUrl);
state.isInitialized = true;
return;
}
}
// Step 2: Full GraphQL introspection (token has api or read_api scope)
const cached = ConnectionManager.introspectionCache.get(endpoint);
const now = Date.now();
if (cached && now - cached.timestamp < ConnectionManager.CACHE_TTL) {
// Verify state is still ours (reinitialize may have replaced it during prior awaits)
Iif (this.instances.get(baseUrl) !== state) return;
logInfo('Using cached GraphQL introspection data');
state.instanceInfo = cached.instanceInfo;
state.schemaInfo = cached.schemaInfo;
state.schemaIntrospector.rehydrate(cached.schemaInfo);
state.introspectedInstanceUrl = baseUrl;
} else {
logDebug('Introspecting GitLab GraphQL schema...');
// Detect instance info and introspect schema in parallel
const [instanceInfo, schemaInfo] = await Promise.all([
versionDetector.detectInstance(),
schemaIntrospector.introspectSchema(),
]);
// Verify this state entry is still ours (reinitialize may have replaced it)
Iif (this.instances.get(baseUrl) !== state) return;
state.instanceInfo = instanceInfo;
state.schemaInfo = schemaInfo;
state.introspectedInstanceUrl = baseUrl;
// Cache the results
ConnectionManager.introspectionCache.set(endpoint, {
instanceInfo,
schemaInfo,
timestamp: now,
});
logInfo('GraphQL schema introspection completed');
}
state.isInitialized = true;
logInfo('GitLab instance and schema detected', {
version: state.instanceInfo?.version,
tier: state.instanceInfo?.tier,
features: state.instanceInfo
? Object.entries(state.instanceInfo.features)
.filter(([, enabled]) => enabled)
.map(([feature]) => feature)
: [],
widgetTypes: state.schemaInfo?.workItemWidgetTypes.length || 0,
schemaTypes: state.schemaInfo?.typeDefinitions.size || 0,
});
} catch (error) {
// Guard: only delete if this is still OUR state entry — a concurrent retry
// (after clearInflight) may have already replaced it with a fresh one.
if (state && this.instances.get(baseUrl) === state) {
this.dropInstance(baseUrl);
}
logError('Failed to initialize connection', { err: error as Error });
throw error;
}
}
/**
* Ensure schema introspection has been performed.
* In OAuth mode, this should be called within a token context.
* Supports per-instance introspection caching via InstanceRegistry.
*
* Uses Promise-based deduplication to prevent thundering herd when
* multiple concurrent requests trigger introspection simultaneously.
*/
public async ensureIntrospected(explicitUrl?: string): Promise<void> {
// Use explicit URL if provided (handler knows the effective URL),
// otherwise fall back to OAuth context / current instance
const instanceUrl = normalizeInstanceUrl(
explicitUrl ?? getGitLabApiUrlFromContext() ?? this.currentInstanceUrl ?? GITLAB_BASE_URL,
);
const state = this.instances.get(instanceUrl);
if (!state?.client || !state.versionDetector || !state.schemaIntrospector) {
throw new Error('Connection not initialized. Call initialize() first.');
}
// Any ensureIntrospected() call represents active use of the instance —
// touch LRU timestamp on all code paths once state existence is confirmed.
this.touchInstance(instanceUrl);
// Already introspected for THIS instance - reuse cached data
if (state.instanceInfo && state.schemaInfo && state.introspectedInstanceUrl === instanceUrl) {
return;
}
// REST-only mode: token lacks GraphQL access, skip introspection entirely
// (doInitialize set instanceInfo via REST, no point hitting GraphQL)
Iif (state.tokenScopeInfo && !state.tokenScopeInfo.hasGraphQLAccess) {
return;
}
// Deduplication: if another request is already introspecting this instance, await it
const existingPromise = this.introspectionPromises.get(instanceUrl);
if (existingPromise) {
logDebug('Awaiting existing introspection for instance', { url: instanceUrl });
await existingPromise;
return;
}
// Start introspection and register the promise for deduplication
const promise = this.doIntrospection(instanceUrl);
this.introspectionPromises.set(instanceUrl, promise);
try {
await promise;
} finally {
Eif (this.introspectionPromises.get(instanceUrl) === promise) {
this.introspectionPromises.delete(instanceUrl);
}
}
}
/**
* Perform actual introspection logic for an instance.
* Extracted from ensureIntrospected() for deduplication support.
*/
private async doIntrospection(instanceUrl: string): Promise<void> {
const state = this.instances.get(instanceUrl);
Iif (!state?.client || !state.versionDetector || !state.schemaIntrospector) {
throw new Error('Connection not initialized. Call initialize() first.');
}
const { client, versionDetector, schemaIntrospector } = state;
const endpoint = client.endpoint;
const registry = InstanceRegistry.getInstance();
// Check InstanceRegistry cache first (for multi-instance support)
Eif (registry.isInitialized()) {
const cachedIntrospection = registry.getIntrospection(instanceUrl);
if (cachedIntrospection) {
logInfo('Using cached introspection from InstanceRegistry', { url: instanceUrl });
state.instanceInfo = {
version: cachedIntrospection.version,
tier: cachedIntrospection.tier as 'free' | 'premium' | 'ultimate',
features: cachedIntrospection.features as unknown as GitLabInstanceInfo['features'],
detectedAt: cachedIntrospection.cachedAt,
};
const restoredSchema = cachedIntrospection.schemaInfo as SchemaInfo;
state.schemaInfo = restoredSchema;
state.schemaIntrospector.rehydrate(restoredSchema);
state.introspectedInstanceUrl = instanceUrl;
return;
}
}
// Check legacy cache: prefer instanceUrl for multi-instance consistency,
// but fall back to endpoint-keyed entries from older cache format
const primaryCacheKey = instanceUrl;
const legacyCacheKey = endpoint;
let cached = ConnectionManager.introspectionCache.get(primaryCacheKey);
Eif (!cached && primaryCacheKey !== legacyCacheKey) {
cached = ConnectionManager.introspectionCache.get(legacyCacheKey);
}
const now = Date.now();
if (cached && now - cached.timestamp < ConnectionManager.CACHE_TTL) {
logInfo('Using cached GraphQL introspection data');
state.instanceInfo = cached.instanceInfo;
state.schemaInfo = cached.schemaInfo;
state.schemaIntrospector.rehydrate(cached.schemaInfo);
state.introspectedInstanceUrl = instanceUrl;
return;
}
logDebug('Introspecting GitLab GraphQL schema (deferred OAuth mode)...');
// Detect instance info and introspect schema in parallel
// Per-URL state already has the correct client for this instance
const [instanceInfo, schemaInfo] = await Promise.all([
versionDetector.detectInstance(),
schemaIntrospector.introspectSchema(),
]);
// Verify this state entry is still ours (reinitialize may have replaced it)
Iif (this.instances.get(instanceUrl) !== state) return;
state.instanceInfo = instanceInfo;
state.schemaInfo = schemaInfo;
state.introspectedInstanceUrl = instanceUrl;
// Cache the results
ConnectionManager.introspectionCache.set(primaryCacheKey, {
instanceInfo,
schemaInfo,
timestamp: now,
});
// Also cache in InstanceRegistry for multi-instance support
Eif (registry.isInitialized()) {
const cachedIntrospection: CachedIntrospection = {
version: instanceInfo.version,
tier: instanceInfo.tier,
features: instanceInfo.features as unknown as Record<string, boolean>,
schemaInfo,
cachedAt: new Date(),
};
registry.setIntrospection(instanceUrl, cachedIntrospection);
}
logInfo('GraphQL schema introspection completed (deferred)', {
version: state.instanceInfo?.version,
tier: state.instanceInfo?.tier,
widgetTypes: state.schemaInfo?.workItemWidgetTypes.length || 0,
});
}
/**
* Helper to resolve URL and look up per-URL state.
* Returns [state, resolvedUrl] or throws if not initialized.
*/
private resolveState(instanceUrl?: string): [InstanceState, string] {
// Empty string is falsy → falls to currentInstanceUrl (same as undefined/null).
// This is intentional: callers pass either a real URL or nothing.
const url = instanceUrl ? normalizeInstanceUrl(instanceUrl) : this.currentInstanceUrl;
if (!url) {
throw new Error('Connection not initialized. Call initialize() first.');
}
const state = this.instances.get(url);
Iif (!state) {
throw new Error(`Connection not initialized for ${url}. Call initialize() first.`);
}
// Note: state.isInitialized may be false during doInitialize() — the client
// is valid at this point (constructed before map insertion). Failed inits
// delete the entry entirely (see doInitialize catch block), so a present
// entry always has a usable client. Individual getters (getInstanceInfo,
// getSchemaInfo) null-check their respective fields independently.
this.touchInstance(url); // Update LRU access time on every read.
return [state, url];
}
public getClient(instanceUrl?: string): GraphQLClient {
const [state] = this.resolveState(instanceUrl);
return state.client;
}
/**
* Get a thread-safe GraphQL client for the current or specified instance.
*
* In OAuth mode with multi-instance support, this returns a per-instance
* client from the connection pool, avoiding singleton endpoint mutation.
* In static mode, returns the per-URL client from InstanceState.
*
* @param instanceUrl - Optional instance URL (defaults to current context)
* @param authHeaders - Optional auth headers for OAuth per-request tokens
*/
public getInstanceClient(
instanceUrl?: string,
authHeaders?: Record<string, string>,
): GraphQLClient {
const registry = InstanceRegistry.getInstance();
// Determine which instance to use — normalize all sources for consistent Map keys
const rawTargetUrl = instanceUrl ?? getGitLabApiUrlFromContext() ?? this.currentInstanceUrl;
const targetUrl = rawTargetUrl ? normalizeInstanceUrl(rawTargetUrl) : null;
// If registry is initialized and instance is registered, use per-instance client
Iif (targetUrl && registry.isInitialized() && registry.has(targetUrl)) {
const client = registry.getGraphQLClient(targetUrl, authHeaders);
if (client) {
return client;
}
}
// Fallback to per-URL state client
Eif (targetUrl) {
const state = this.instances.get(targetUrl);
if (state) {
this.touchInstance(targetUrl); // Keep entry alive in LRU window.
return state.client;
}
// targetUrl resolved (explicit or from context) but not found anywhere —
// fail fast rather than silently routing to a different instance's client.
throw new Error(`Connection not initialized for ${targetUrl}. Call initialize() first.`);
}
return this.getClient();
}
public getVersionDetector(instanceUrl?: string): GitLabVersionDetector {
const [state] = this.resolveState(instanceUrl);
return state.versionDetector;
}
public getSchemaIntrospector(instanceUrl?: string): SchemaIntrospector {
const [state] = this.resolveState(instanceUrl);
return state.schemaIntrospector;
}
public getInstanceInfo(instanceUrl?: string): GitLabInstanceInfo {
const [state, resolvedUrl] = this.resolveState(instanceUrl);
Iif (!state.instanceInfo) {
throw new Error(
`Instance information is not available for ${resolvedUrl}. Initialization may have completed without version detection (OAuth deferred/REST-only mode).`,
);
}
return state.instanceInfo;
}
public getSchemaInfo(instanceUrl?: string): SchemaInfo {
const [state, resolvedUrl] = this.resolveState(instanceUrl);
Iif (!state.schemaInfo) {
throw new Error(
`Schema information is not available for ${resolvedUrl}. Initialization may have completed without schema introspection.`,
);
}
return state.schemaInfo;
}
/**
* Get the current instance URL (for tracking instance switches)
*/
public getCurrentInstanceUrl(): string | null {
return this.currentInstanceUrl;
}
/**
* Check if initialize() has completed for the given (or current) URL.
* This is an initialization flag, NOT a live connectivity check — use
* HealthMonitor.isInstanceReachable() for runtime reachability.
* True for partial states (OAuth REST-only). HealthMonitor's performConnect
* derives degraded state from getInstanceInfo().version after this check.
*/
public isConnected(instanceUrl?: string): boolean {
const url = instanceUrl ? normalizeInstanceUrl(instanceUrl) : this.currentInstanceUrl;
Eif (!url) return false;
const state = this.instances.get(url);
if (state) this.touchInstance(url); // Keep entry alive in LRU window.
return state?.isInitialized ?? false;
}
public isFeatureAvailable(
feature: keyof GitLabInstanceInfo['features'],
instanceUrl?: string,
): boolean {
const url = instanceUrl ? normalizeInstanceUrl(instanceUrl) : this.currentInstanceUrl;
if (!url) return false;
const state = this.instances.get(url);
Iif (!state?.instanceInfo) return false;
this.touchInstance(url); // Keep entry alive in LRU window.
return state.instanceInfo.features[feature];
}
public getTier(instanceUrl?: string): string {
const url = instanceUrl ? normalizeInstanceUrl(instanceUrl) : this.currentInstanceUrl;
if (!url) return 'unknown';
const state = this.instances.get(url);
Iif (!state?.instanceInfo) return 'unknown';
this.touchInstance(url); // Keep entry alive in LRU window.
return state.instanceInfo.tier;
}
public getVersion(instanceUrl?: string): string {
const url = instanceUrl ? normalizeInstanceUrl(instanceUrl) : this.currentInstanceUrl;
if (!url) return 'unknown';
const state = this.instances.get(url);
Iif (!state?.instanceInfo) return 'unknown';
this.touchInstance(url); // Keep entry alive in LRU window.
return state.instanceInfo.version;
}
public isWidgetAvailable(widgetType: string, instanceUrl?: string): boolean {
const url = instanceUrl ? normalizeInstanceUrl(instanceUrl) : this.currentInstanceUrl;
if (!url) return false;
const state = this.instances.get(url);
Eif (state) this.touchInstance(url); // Keep entry alive in LRU window.
// Read from schemaInfo directly — schemaIntrospector's internal cache may
// not be populated after a cache-hit restore (only schemaInfo is copied).
return state?.schemaInfo?.workItemWidgetTypes.includes(widgetType) ?? false;
}
/**
* Get detected token scope info (null if detection was skipped or failed)
*/
public getTokenScopeInfo(instanceUrl?: string): TokenScopeInfo | null {
const url = instanceUrl ? normalizeInstanceUrl(instanceUrl) : this.currentInstanceUrl;
if (!url) return null;
const state = this.instances.get(url);
Eif (state) this.touchInstance(url); // Keep entry alive in LRU window.
return state?.tokenScopeInfo ?? null;
}
/**
* Re-detect token scopes and update internal state.
* Returns true if scopes changed (requiring tool registry refresh).
*
* Used by whoami action to pick up token permission changes without restart.
*/
public async refreshTokenScopes(): Promise<boolean> {
// Skip in OAuth mode - scopes come from request context, not static token
if (isOAuthEnabled()) {
return false;
}
const url = this.currentInstanceUrl;
Iif (!url) return false;
const state = this.instances.get(url);
Iif (!state) return false;
const previousScopes = state.tokenScopeInfo?.scopes ?? [];
const previousHasGraphQL = state.tokenScopeInfo?.hasGraphQLAccess ?? false;
const previousHasWrite = state.tokenScopeInfo?.hasWriteAccess ?? false;
// Re-detect token scopes against the current instance URL
const newScopeInfo = await detectTokenScopes(url);
if (!newScopeInfo) {
// Detection failed - keep existing state
return false;
}
// Check if scopes changed
const newScopes = newScopeInfo.scopes;
const scopesChanged =
previousScopes.length !== newScopes.length ||
!previousScopes.every((s) => newScopes.includes(s)) ||
previousHasGraphQL !== newScopeInfo.hasGraphQLAccess ||
previousHasWrite !== newScopeInfo.hasWriteAccess;
// Re-check that the state entry is still the live one: a concurrent
// reinitialize() or reset() may have replaced / deleted it while we were
// awaiting detectTokenScopes() above. Writing into a stale object would
// silently lose the refreshed scopes or corrupt a connection that is no
// longer active.
const currentState = this.instances.get(url);
Iif (currentState !== state) {
return false;
}
// Always persist refreshed scope info (even when scopes haven't changed)
// so non-scope metadata in TokenScopeInfo stays fresh
state.tokenScopeInfo = newScopeInfo;
if (scopesChanged) {
logInfo('Token scopes changed - tool registry will be refreshed', {
previousScopes,
newScopes,
hasGraphQLAccess: newScopeInfo.hasGraphQLAccess,
hasWriteAccess: newScopeInfo.hasWriteAccess,
});
}
return scopesChanged;
}
/**
* Detect GitLab version via REST API (fallback when GraphQL is not available).
* Uses GET /api/v4/version; authentication requirements depend on instance
* configuration. This helper always sends the configured token as a fallback.
*/
private async detectVersionViaREST(baseUrl?: string): Promise<GitLabInstanceInfo> {
try {
const url = baseUrl ?? this.currentInstanceUrl ?? GITLAB_BASE_URL;
const response = await enhancedFetch(`${url}/api/v4/version`, {
headers: {
'PRIVATE-TOKEN': GITLAB_TOKEN ?? '',
Accept: 'application/json',
},
retry: false, // Don't retry version detection at startup
});
if (response.ok) {
const data = (await response.json()) as {
version: string;
revision: string;
enterprise?: boolean;
};
logInfo('Detected GitLab version via REST (GraphQL unavailable)', {
version: data.version,
enterprise: data.enterprise,
});
return {
version: data.version,
tier: data.enterprise ? 'premium' : 'free',
features: this.getDefaultFeatures(data.enterprise ?? false),
detectedAt: new Date(),
};
}
// Version endpoint also failed - return minimal info
logInfo('REST version detection failed, using defaults', { status: response.status });
} catch (error) {
logInfo('REST version detection failed, using defaults', {
error: error instanceof Error ? error.message : String(error),
});
}
// Fallback: return unknown version with default features
return {
version: 'unknown',
tier: 'free',
features: this.getDefaultFeatures(false),
detectedAt: new Date(),
};
}
/**
* Get default features based on whether GitLab is enterprise edition.
* In OAuth mode without full introspection, we default to enabling most features
* to allow tools to be available - they will fail gracefully if not actually available.
*/
private getDefaultFeatures(isEnterprise: boolean): GitLabInstanceInfo['features'] {
// Default to enabling most features - better to allow and fail gracefully
// than to block tools that might actually be available
return {
workItems: true,
epics: isEnterprise,
iterations: isEnterprise,
roadmaps: isEnterprise,
portfolioManagement: isEnterprise,
advancedSearch: true,
codeReview: true,
securityDashboard: isEnterprise,
complianceFramework: isEnterprise,
valueStreamAnalytics: isEnterprise,
customFields: isEnterprise,
okrs: isEnterprise,
healthStatus: isEnterprise,
weight: isEnterprise,
multiLevelEpics: isEnterprise,
serviceDesk: true,
requirements: isEnterprise,
qualityManagement: isEnterprise,
timeTracking: true,
crmContacts: true,
vulnerabilities: isEnterprise,
errorTracking: true,
designManagement: true,
linkedResources: true,
emailParticipants: true,
};
}
/**
* Re-initialize connection with a different GitLab instance.
* Used when switching instances in static token mode.
*
* @param newInstanceUrl - The new GitLab instance URL to connect to
*/
public async reinitialize(rawInstanceUrl: string): Promise<void> {
const newInstanceUrl = normalizeInstanceUrl(rawInstanceUrl);
logInfo('Re-initializing ConnectionManager for new instance', {
newInstanceUrl,
});
// Clear state for the NEW URL before re-init. When switching instances,
// keep previous state alive as fallback. When refreshing the same URL,
// save the live state and restore it if re-init fails.
const previousUrl = this.currentInstanceUrl;
const savedState = this.instances.get(newInstanceUrl);
// Only restore states that were successfully initialized; a placeholder
// entry written by doInitialize() before any network step completed is not
// a valid fallback — reinstate it would point currentInstanceUrl at an
// uninitialised connection.
const restorableState = savedState?.isInitialized ? savedState : undefined;
this.initializePromises.delete(newInstanceUrl);
this.introspectionPromises.delete(newInstanceUrl);
this.instances.delete(newInstanceUrl);
this.instanceAccessTimes.delete(newInstanceUrl);
// Clear all caches for the new URL (guard: registry may not be initialized yet)
try {
const registry = InstanceRegistry.getInstance();
registry.clearIntrospectionCache(newInstanceUrl);
} catch {
// InstanceRegistry not initialized — no cache to clear
}
ConnectionManager.introspectionCache.delete(newInstanceUrl);
ConnectionManager.introspectionCache.delete(`${newInstanceUrl}/api/graphql`);
// Re-initialize the connection with the new instance URL
try {
await this.initialize(newInstanceUrl);
} catch (error) {
// On failure: restore the best available state.
// - Same-URL refresh: restore saved state for this URL
// - URL switch: keep previousUrl as the active healthy instance
Eif (restorableState) {
this.instances.set(newInstanceUrl, restorableState);
this.touchInstance(newInstanceUrl); // Restore access timestamp for the revived entry.
}
if (previousUrl && this.instances.has(previousUrl)) {
this.currentInstanceUrl = previousUrl;
} else Eif (restorableState) {
this.currentInstanceUrl = newInstanceUrl;
}
throw error;
}
// Only after successful init: clean up the previous instance state
Eif (previousUrl && previousUrl !== newInstanceUrl) {
this.initializePromises.delete(previousUrl);
this.introspectionPromises.delete(previousUrl);
this.instances.delete(previousUrl);
this.instanceAccessTimes.delete(previousUrl);
}
const state = this.instances.get(newInstanceUrl);
logInfo('ConnectionManager re-initialized', {
version: state?.instanceInfo?.version,
tier: state?.instanceInfo?.tier,
instanceUrl: this.currentInstanceUrl,
});
}
/**
* Clear the inflight initialize promise for a URL.
* Called by HealthMonitor after init timeout — prevents reconnect attempts
* from re-awaiting a hung doInitialize() promise.
*/
public clearInflight(rawUrl: string): void {
const url = normalizeInstanceUrl(rawUrl);
this.initializePromises.delete(url);
this.introspectionPromises.delete(url);
}
public reset(): void {
this.instances.clear();
this.instanceAccessTimes.clear();
this.currentInstanceUrl = null;
this.latestRequestedUrl = null;
this.introspectionPromises.clear();
this.initializePromises.clear();
ConnectionManager.introspectionCache.clear();
// Clear InstanceRegistry introspection cache to prevent doIntrospection()
// from resurrecting stale data after a full reset
try {
InstanceRegistry.getInstance().clearIntrospectionCache();
} catch {
// InstanceRegistry not initialized — nothing to clear
}
}
}
|