All files / src/services ConnectionManager.ts

72.8% Statements 83/114
55.55% Branches 35/63
88.23% Functions 15/17
72.8% Lines 83/114

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 32510x 10x 10x 10x 10x 10x               10x 10x 45x 45x 45x 45x 45x 45x 10x 10x         55x 55x       36x 2x     34x 34x       34x 1x     33x 1x       32x       32x       32x   31x 31x       31x                                                                                       31x 31x   31x 2x 2x 2x   29x     29x         26x 26x     26x           26x     28x   28x           135x 108x               6x 6x                                                                                                                       5x 3x   2x       4x 3x   1x       4x 3x   1x       5x 3x   2x       4x 3x   1x       7x 1x   6x       2x 1x   1x       2x 1x   1x       2x 1x   1x                                                                                 44x 44x 44x 44x 44x 44x      
import { GraphQLClient } from "../graphql/client";
import { GitLabVersionDetector, GitLabInstanceInfo } from "./GitLabVersionDetector";
import { SchemaIntrospector, SchemaInfo } from "./SchemaIntrospector";
import { GITLAB_BASE_URL, GITLAB_TOKEN } from "../config";
import { isOAuthEnabled } from "../oauth/index";
import { logger } from "../logger";
 
interface CacheEntry {
  schemaInfo: SchemaInfo;
  instanceInfo: GitLabInstanceInfo;
  timestamp: number;
}
 
export class ConnectionManager {
  private static instance: ConnectionManager | null = null;
  private client: GraphQLClient | null = null;
  private versionDetector: GitLabVersionDetector | null = null;
  private schemaIntrospector: SchemaIntrospector | null = null;
  private instanceInfo: GitLabInstanceInfo | null = null;
  private schemaInfo: SchemaInfo | null = null;
  private isInitialized: boolean = false;
  private static introspectionCache = new Map<string, CacheEntry>();
  private static readonly CACHE_TTL = 10 * 60 * 1000; // 10 minutes in milliseconds
 
  private constructor() {}
 
  public static getInstance(): ConnectionManager {
    ConnectionManager.instance ??= new ConnectionManager();
    return ConnectionManager.instance;
  }
 
  public async initialize(): Promise<void> {
    if (this.isInitialized) {
      return;
    }
 
    try {
      const oauthMode = isOAuthEnabled();
 
      // In OAuth mode, token comes from request context via enhancedFetch
      // In static mode, require both base URL and token
      if (!GITLAB_BASE_URL) {
        throw new Error("GitLab base URL is required");
      }
 
      if (!oauthMode && !GITLAB_TOKEN) {
        throw new Error("GitLab token is required in static authentication mode");
      }
 
      // Construct GraphQL endpoint from base URL
      const endpoint = `${GITLAB_BASE_URL}/api/graphql`;
 
      // In OAuth mode, don't set static Authorization header
      // enhancedFetch will add the token from request context
      const clientOptions = oauthMode
        ? {}
        : { headers: { Authorization: `Bearer ${GITLAB_TOKEN}` } };
 
      this.client = new GraphQLClient(endpoint, clientOptions);
 
      this.versionDetector = new GitLabVersionDetector(this.client);
      this.schemaIntrospector = new SchemaIntrospector(this.client);
 
      // In OAuth mode, try unauthenticated version detection first
      // Many GitLab instances expose /api/v4/version without auth
      Iif (oauthMode) {
        logger.info("OAuth mode: attempting unauthenticated version detection");
        try {
          const versionResponse = await fetch(`${GITLAB_BASE_URL}/api/v4/version`);
          if (versionResponse.ok) {
            const versionData = (await versionResponse.json()) as {
              version: string;
              enterprise?: boolean;
            };
            logger.info(
              { version: versionData.version },
              "Detected GitLab version without authentication"
            );
 
            // Create basic instance info from unauthenticated response
            // Default to "premium" tier for enterprise instances - will be refined on first authenticated request
            this.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)
            logger.info(
              "OAuth mode: version detected, full introspection deferred until first authenticated request"
            );
          } else {
            logger.info(
              { status: versionResponse.status },
              "OAuth mode: unauthenticated version detection failed, deferring all introspection"
            );
          }
        } catch (error) {
          logger.info(
            { error: error instanceof Error ? error.message : String(error) },
            "OAuth mode: unauthenticated version detection failed, deferring all introspection"
          );
        }
        this.isInitialized = true;
        return;
      }
 
      // Check cache first
      const cached = ConnectionManager.introspectionCache.get(endpoint);
      const now = Date.now();
 
      if (cached && now - cached.timestamp < ConnectionManager.CACHE_TTL) {
        logger.info("Using cached GraphQL introspection data");
        this.instanceInfo = cached.instanceInfo;
        this.schemaInfo = cached.schemaInfo;
      } else {
        logger.debug("Introspecting GitLab GraphQL schema...");
 
        // Detect instance info and introspect schema in parallel
        const [instanceInfo, schemaInfo] = await Promise.all([
          this.versionDetector.detectInstance(),
          this.schemaIntrospector.introspectSchema(),
        ]);
 
        this.instanceInfo = instanceInfo;
        this.schemaInfo = schemaInfo;
 
        // Cache the results
        ConnectionManager.introspectionCache.set(endpoint, {
          instanceInfo,
          schemaInfo,
          timestamp: now,
        });
 
        logger.info("GraphQL schema introspection completed");
      }
 
      this.isInitialized = true;
 
      logger.info(
        {
          version: this.instanceInfo?.version,
          tier: this.instanceInfo?.tier,
          features: this.instanceInfo
            ? Object.entries(this.instanceInfo.features)
                .filter(([, enabled]) => enabled)
                .map(([feature]) => feature)
            : [],
          widgetTypes: this.schemaInfo?.workItemWidgetTypes.length || 0,
          schemaTypes: this.schemaInfo?.typeDefinitions.size || 0,
        },
        "GitLab instance and schema detected"
      );
    } catch (error) {
      logger.error({ err: error as Error }, "Failed to initialize connection");
      throw error;
    }
  }
 
  /**
   * Ensure schema introspection has been performed.
   * In OAuth mode, this should be called within a token context.
   */
  public async ensureIntrospected(): Promise<void> {
    // Already introspected
    if (this.instanceInfo && this.schemaInfo) {
      return;
    }
 
    if (!this.client || !this.versionDetector || !this.schemaIntrospector) {
      throw new Error("Connection not initialized. Call initialize() first.");
    }
 
    const endpoint = this.client.endpoint;
 
    // Check cache first
    const cached = ConnectionManager.introspectionCache.get(endpoint);
    const now = Date.now();
 
    if (cached && now - cached.timestamp < ConnectionManager.CACHE_TTL) {
      logger.info("Using cached GraphQL introspection data");
      this.instanceInfo = cached.instanceInfo;
      this.schemaInfo = cached.schemaInfo;
      return;
    }
 
    logger.debug("Introspecting GitLab GraphQL schema (deferred OAuth mode)...");
 
    // Detect instance info and introspect schema in parallel
    const [instanceInfo, schemaInfo] = await Promise.all([
      this.versionDetector.detectInstance(),
      this.schemaIntrospector.introspectSchema(),
    ]);
 
    this.instanceInfo = instanceInfo;
    this.schemaInfo = schemaInfo;
 
    // Cache the results
    ConnectionManager.introspectionCache.set(endpoint, {
      instanceInfo,
      schemaInfo,
      timestamp: now,
    });
 
    logger.info(
      {
        version: this.instanceInfo?.version,
        tier: this.instanceInfo?.tier,
        widgetTypes: this.schemaInfo?.workItemWidgetTypes.length || 0,
      },
      "GraphQL schema introspection completed (deferred)"
    );
  }
 
  public getClient(): GraphQLClient {
    if (!this.client) {
      throw new Error("Connection not initialized. Call initialize() first.");
    }
    return this.client;
  }
 
  public getVersionDetector(): GitLabVersionDetector {
    if (!this.versionDetector) {
      throw new Error("Connection not initialized. Call initialize() first.");
    }
    return this.versionDetector;
  }
 
  public getSchemaIntrospector(): SchemaIntrospector {
    if (!this.schemaIntrospector) {
      throw new Error("Connection not initialized. Call initialize() first.");
    }
    return this.schemaIntrospector;
  }
 
  public getInstanceInfo(): GitLabInstanceInfo {
    if (!this.instanceInfo) {
      throw new Error("Connection not initialized. Call initialize() first.");
    }
    return this.instanceInfo;
  }
 
  public getSchemaInfo(): SchemaInfo {
    if (!this.schemaInfo) {
      throw new Error("Connection not initialized. Call initialize() first.");
    }
    return this.schemaInfo;
  }
 
  public isFeatureAvailable(feature: keyof GitLabInstanceInfo["features"]): boolean {
    if (!this.instanceInfo) {
      return false;
    }
    return this.instanceInfo.features[feature];
  }
 
  public getTier(): string {
    if (!this.instanceInfo) {
      return "unknown";
    }
    return this.instanceInfo.tier;
  }
 
  public getVersion(): string {
    if (!this.instanceInfo) {
      return "unknown";
    }
    return this.instanceInfo.version;
  }
 
  public isWidgetAvailable(widgetType: string): boolean {
    if (!this.schemaIntrospector) {
      return false;
    }
    return this.schemaIntrospector.isWidgetTypeAvailable(widgetType);
  }
 
  /**
   * 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,
    };
  }
 
  public reset(): void {
    this.client = null;
    this.versionDetector = null;
    this.schemaIntrospector = null;
    this.instanceInfo = null;
    this.schemaInfo = null;
    this.isInitialized = false;
  }
}