All files / src/services NamespaceTierDetector.ts

97.67% Statements 84/86
91.11% Branches 41/45
100% Functions 11/11
97.61% Lines 82/84

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                          2x   2x 2x 2x         2x           2x         2x                                           2x                                                                                                                   27x   24x   24x 9x   15x 11x   4x 2x     2x           2x 35x             62x             33x 33x   33x     5x 5x 1x 1x         1x     4x                     29x 29x   29x                     2x 29x   1x 1x 3x 2x     1x     28x 28x                       29x   29x 29x                           28x 1x         1x             27x                   27x 1x   1x         27x 27x 27x   27x           1x           1x                             2x 34x   34x 1x 1x             33x 33x   33x                   33x 33x 4x       4x       29x     29x   29x                   2x 5x 5x           2x       7x   7x       12x 12x 12x     7x          
/**
 * Namespace Tier Detector
 *
 * Detects GitLab tier (free/premium/ultimate) per namespace.
 * CRITICAL: Tier is per-NAMESPACE, not per-instance!
 * On gitlab.com, one user can access Free group and Ultimate group simultaneously.
 *
 * Features:
 * - Per-session namespace tier caching (5 min TTL)
 * - GraphQL query for namespace tier detection
 * - Feature availability mapping per tier
 */
 
import { logDebug, logWarn } from "../logger.js";
import { NamespaceTierInfo } from "../oauth/types.js";
import { getTokenContext } from "../oauth/token-context.js";
import { enhancedFetch } from "../utils/fetch.js";
import { GITLAB_BASE_URL } from "../config";
 
/**
 * Cache TTL for namespace tier (5 minutes)
 */
const NAMESPACE_TIER_CACHE_TTL_MS = 5 * 60 * 1000;
 
/**
 * In-memory namespace tier cache
 * Key: `${sessionId}:${namespacePath}`
 */
const namespaceTierCache = new Map<string, NamespaceTierInfo>();
 
/**
 * GraphQL query to get namespace tier
 */
const NAMESPACE_TIER_QUERY = `
  query GetNamespaceTier($fullPath: ID!) {
    namespace(fullPath: $fullPath) {
      id
      fullPath
 
      ... on Group {
        plan
      }
 
      ... on Project {
        group {
          plan
        }
      }
    }
  }
`;
 
/**
 * Feature availability per tier
 */
const TIER_FEATURES: Record<string, Record<string, boolean>> = {
  free: {
    issues: true,
    mergeRequests: true,
    wiki: true,
    snippets: true,
    epics: false,
    iterations: false,
    roadmaps: false,
    okrs: false,
    healthStatus: false,
    weight: false,
    multiLevelEpics: false,
    portfolioManagement: false,
    requirements: false,
    securityDashboard: false,
    complianceFramework: false,
  },
  premium: {
    issues: true,
    mergeRequests: true,
    wiki: true,
    snippets: true,
    epics: true,
    iterations: true,
    roadmaps: true,
    okrs: false,
    healthStatus: true,
    weight: true,
    multiLevelEpics: true,
    portfolioManagement: true,
    requirements: true,
    securityDashboard: false,
    complianceFramework: true,
  },
  ultimate: {
    issues: true,
    mergeRequests: true,
    wiki: true,
    snippets: true,
    epics: true,
    iterations: true,
    roadmaps: true,
    okrs: true,
    healthStatus: true,
    weight: true,
    multiLevelEpics: true,
    portfolioManagement: true,
    requirements: true,
    securityDashboard: true,
    complianceFramework: true,
  },
};
 
/**
 * Normalize plan name to tier
 */
function normalizeTier(plan: string | null | undefined): "free" | "premium" | "ultimate" {
  if (!plan) return "free";
 
  const normalized = plan.toLowerCase();
 
  if (normalized.includes("ultimate") || normalized.includes("gold")) {
    return "ultimate";
  }
  if (normalized.includes("premium") || normalized.includes("silver")) {
    return "premium";
  }
  if (normalized.includes("bronze") || normalized.includes("starter")) {
    return "premium"; // Bronze/Starter maps to Premium tier features
  }
 
  return "free";
}
 
/**
 * Get features for a tier
 */
export function getFeaturesForTier(tier: "free" | "premium" | "ultimate"): Record<string, boolean> {
  return { ...TIER_FEATURES[tier] };
}
 
/**
 * Build cache key from session ID and namespace path
 */
function buildCacheKey(sessionId: string, namespacePath: string): string {
  return `${sessionId}:${namespacePath}`;
}
 
/**
 * Get cached namespace tier info
 */
function getCachedTier(sessionId: string, namespacePath: string): NamespaceTierInfo | null {
  const key = buildCacheKey(sessionId, namespacePath);
  const cached = namespaceTierCache.get(key);
 
  if (!cached) return null;
 
  // Check TTL
  const age = Date.now() - cached.cachedAt.getTime();
  if (age > NAMESPACE_TIER_CACHE_TTL_MS) {
    namespaceTierCache.delete(key);
    logDebug("Namespace tier cache expired", {
      sessionId,
      namespacePath,
      ageMs: age,
    });
    return null;
  }
 
  return cached;
}
 
/**
 * Set cached namespace tier info
 */
function setCachedTier(
  sessionId: string,
  namespacePath: string,
  tierInfo: NamespaceTierInfo
): void {
  const key = buildCacheKey(sessionId, namespacePath);
  namespaceTierCache.set(key, tierInfo);
 
  logDebug("Namespace tier cached", {
    sessionId,
    namespacePath,
    tier: tierInfo.tier,
  });
}
 
/**
 * Clear namespace tier cache for a session
 * Called when user switches instances or session expires
 */
export function clearNamespaceTierCache(sessionId?: string): void {
  if (sessionId) {
    // Clear only for specific session
    const prefix = `${sessionId}:`;
    for (const key of namespaceTierCache.keys()) {
      if (key.startsWith(prefix)) {
        namespaceTierCache.delete(key);
      }
    }
    logDebug("Namespace tier cache cleared for session", { sessionId });
  } else {
    // Clear entire cache
    namespaceTierCache.clear();
    logDebug("All namespace tier caches cleared");
  }
}
 
/**
 * Query GitLab for namespace tier via GraphQL
 */
async function queryNamespaceTier(
  namespacePath: string,
  token: string,
  baseUrl: string
): Promise<NamespaceTierInfo> {
  const graphqlUrl = `${baseUrl}/api/graphql`;
 
  try {
    const response = await enhancedFetch(graphqlUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        query: NAMESPACE_TIER_QUERY,
        variables: { fullPath: namespacePath },
      }),
      // Pass baseUrl for rate limiting to match InstanceRegistry key (supports subpath deployments)
      rateLimitBaseUrl: baseUrl,
    });
 
    if (!response.ok) {
      logWarn("Failed to query namespace tier", {
        namespacePath,
        status: response.status,
      });
      // Return free tier as fallback
      return {
        tier: "free",
        features: getFeaturesForTier("free"),
        cachedAt: new Date(),
      };
    }
 
    const result = (await response.json()) as {
      data?: {
        namespace?: {
          plan?: string;
          group?: { plan?: string };
        };
      };
      errors?: Array<{ message: string }>;
    };
 
    if (result.errors?.length) {
      logWarn("GraphQL errors querying namespace tier", {
        namespacePath,
        errors: result.errors.map(e => e.message),
      });
    }
 
    // Extract plan from response
    const namespace = result.data?.namespace;
    const plan = namespace?.plan ?? namespace?.group?.plan ?? null;
    const tier = normalizeTier(plan);
 
    return {
      tier,
      features: getFeaturesForTier(tier),
      cachedAt: new Date(),
    };
  } catch (error) {
    logWarn("Error querying namespace tier", {
      namespacePath,
      err: error instanceof Error ? error : new Error(String(error)),
    });
 
    // Return free tier as fallback
    return {
      tier: "free",
      features: getFeaturesForTier("free"),
      cachedAt: new Date(),
    };
  }
}
 
/**
 * Get namespace tier with caching
 * Uses current token context for session ID and token
 *
 * @param namespacePath - Full path of the namespace (e.g., "gitlab-org" or "gitlab-org/gitlab")
 * @returns Namespace tier info with features
 */
export async function getNamespaceTier(namespacePath: string): Promise<NamespaceTierInfo> {
  const context = getTokenContext();
 
  if (!context) {
    logWarn("No token context available for namespace tier detection");
    return {
      tier: "free",
      features: getFeaturesForTier("free"),
      cachedAt: new Date(),
    };
  }
 
  const { sessionId, gitlabToken, apiUrl } = context;
  const baseUrl = apiUrl || GITLAB_BASE_URL;
 
  Iif (!baseUrl) {
    logWarn("No base URL available for namespace tier detection");
    return {
      tier: "free",
      features: getFeaturesForTier("free"),
      cachedAt: new Date(),
    };
  }
 
  // Check cache first
  const cached = getCachedTier(sessionId, namespacePath);
  if (cached) {
    logDebug("Namespace tier from cache", {
      namespacePath,
      tier: cached.tier,
    });
    return cached;
  }
 
  // Query GitLab
  const tierInfo = await queryNamespaceTier(namespacePath, gitlabToken, baseUrl);
 
  // Cache result
  setCachedTier(sessionId, namespacePath, tierInfo);
 
  return tierInfo;
}
 
/**
 * Check if a feature is available for a namespace
 *
 * @param namespacePath - Full path of the namespace
 * @param feature - Feature name to check
 * @returns true if feature is available
 */
export async function isFeatureAvailable(namespacePath: string, feature: string): Promise<boolean> {
  const tierInfo = await getNamespaceTier(namespacePath);
  return tierInfo.features[feature] ?? false;
}
 
/**
 * Get namespace tier metrics (for monitoring)
 */
export function getNamespaceTierCacheMetrics(): {
  totalEntries: number;
  entriesBySession: Map<string, number>;
} {
  const entriesBySession = new Map<string, number>();
 
  for (const key of namespaceTierCache.keys()) {
    // Cache key format: ${sessionId}:${namespacePath}
    // sessionId is UUID (no colons), but namespace paths can contain colons.
    // Using lastIndexOf safely handles any future format changes.
    const separatorIndex = key.lastIndexOf(":");
    const sessionId = separatorIndex === -1 ? key : key.slice(0, separatorIndex);
    entriesBySession.set(sessionId, (entriesBySession.get(sessionId) ?? 0) + 1);
  }
 
  return {
    totalEntries: namespaceTierCache.size,
    entriesBySession,
  };
}