All files / src/preview manager.ts

99.02% Statements 102/103
97.43% Branches 38/39
73.68% Functions 14/19
100% Lines 96/96

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                                                                            9x     9x                       22x 22x 22x                               7x 1x           6x 6x 1x     5x           5x     5x 5x 5x     5x                 5x           5x     5x 5x   5x 5x 5x   5x     5x             5x 5x   1x   1x                     1x 1x   1x       4x 4x   4x 1x 1x 1x 1x   1x                   1x 1x   1x           3x 3x   3x                       3x   3x                                   6x     6x 6x   6x     5x 5x   5x   5x                     4x 4x   4x 6x 6x   5x 5x   4x     3x 3x     4x             5x 5x   5x 1x     4x 4x   4x     4x 1x 4x 1x 2x 1x   1x     4x             3x 3x   3x   4x 4x 1x                           9x 9x 9x 9x 9x   9x 1x     8x                            
/**
 * Preview Manager
 *
 * Orchestrates preview deployment lifecycle: start, stop, list, status.
 * Uses Docker as the source of truth — no database persistence.
 */
 
import { join } from 'node:path';
import { mkdir, writeFile, rm } from 'node:fs/promises';
import { nanoid } from 'nanoid';
import type { ProjectRepository } from '../db/repositories/project-repository.js';
import type { EventBus } from '../events/types.js';
import type {
  PreviewStatus,
  StartPreviewOptions,
} from './types.js';
import { COMPOSE_PROJECT_PREFIX, PREVIEW_LABELS } from './types.js';
import { discoverConfig } from './config-reader.js';
import { generateComposeFile, generateCaddyfile, generateLabels } from './compose-generator.js';
import {
  isDockerAvailable,
  composeUp,
  composeDown,
  composePs,
  listPreviewProjects,
  getContainerLabels,
} from './docker-client.js';
import { waitForHealthy } from './health-checker.js';
import { allocatePort } from './port-allocator.js';
import { getProjectCloneDir } from '../git/project-clones.js';
import { createModuleLogger } from '../logger/index.js';
import type {
  PreviewBuildingEvent,
  PreviewReadyEvent,
  PreviewStoppedEvent,
  PreviewFailedEvent,
} from '../events/types.js';
 
const log = createModuleLogger('preview');
 
/** Directory for preview deployment artifacts (relative to workspace root) */
const PREVIEWS_DIR = '.cw-previews';
 
export class PreviewManager {
  private readonly projectRepository: ProjectRepository;
  private readonly eventBus: EventBus;
  private readonly workspaceRoot: string;
 
  constructor(
    projectRepository: ProjectRepository,
    eventBus: EventBus,
    workspaceRoot: string,
  ) {
    this.projectRepository = projectRepository;
    this.eventBus = eventBus;
    this.workspaceRoot = workspaceRoot;
  }
 
  /**
   * Start a preview deployment.
   *
   * 1. Check Docker availability
   * 2. Resolve project clone path
   * 3. Discover config from project at target branch
   * 4. Allocate port, generate ID
   * 5. Generate compose + Caddyfile, write to .cw-previews/<id>/
   * 6. Run composeUp, wait for healthy
   * 7. Emit events and return status
   */
  async start(options: StartPreviewOptions): Promise<PreviewStatus> {
    // 1. Check Docker
    if (!(await isDockerAvailable())) {
      throw new Error(
        'Docker is not available. Please ensure Docker is installed and running.',
      );
    }
 
    // 2. Resolve project
    const project = await this.projectRepository.findById(options.projectId);
    if (!project) {
      throw new Error(`Project '${options.projectId}' not found`);
    }
 
    const clonePath = join(
      this.workspaceRoot,
      getProjectCloneDir(project.name, project.id),
    );
 
    // 3. Discover config
    const config = await discoverConfig(clonePath);
 
    // 4. Allocate port and generate ID
    const port = await allocatePort();
    const id = nanoid(10);
    const projectName = `${COMPOSE_PROJECT_PREFIX}${id}`;
 
    // 5. Generate compose artifacts
    const labels = generateLabels({
      initiativeId: options.initiativeId,
      phaseId: options.phaseId,
      projectId: options.projectId,
      branch: options.branch,
      port,
      previewId: id,
    });
 
    const composeYaml = generateComposeFile(config, {
      projectPath: clonePath,
      port,
      deploymentId: id,
      labels,
    });
    const caddyfile = generateCaddyfile(config);
 
    // Write artifacts
    const deployDir = join(this.workspaceRoot, PREVIEWS_DIR, id);
    await mkdir(deployDir, { recursive: true });
 
    const composePath = join(deployDir, 'docker-compose.yml');
    await writeFile(composePath, composeYaml, 'utf-8');
    await writeFile(join(deployDir, 'Caddyfile'), caddyfile, 'utf-8');
 
    log.info({ id, projectName, port, composePath }, 'preview deployment prepared');
 
    // 6. Emit building event
    this.eventBus.emit<PreviewBuildingEvent>({
      type: 'preview:building',
      timestamp: new Date(),
      payload: { previewId: id, initiativeId: options.initiativeId, branch: options.branch, port },
    });
 
    // 7. Build and start
    try {
      await composeUp(composePath, projectName);
    } catch (error) {
      log.error({ id, err: error }, 'compose up failed');
 
      this.eventBus.emit<PreviewFailedEvent>({
        type: 'preview:failed',
        timestamp: new Date(),
        payload: {
          previewId: id,
          initiativeId: options.initiativeId,
          error: (error as Error).message,
        },
      });
 
      // Clean up
      await composeDown(projectName).catch(() => {});
      await rm(deployDir, { recursive: true, force: true }).catch(() => {});
 
      throw new Error(`Preview build failed: ${(error as Error).message}`);
    }
 
    // 8. Health check
    const healthResults = await waitForHealthy(port, config);
    const allHealthy = healthResults.every((r) => r.healthy);
 
    if (!allHealthy && healthResults.length > 0) {
      const failedServices = healthResults
        .filter((r) => !r.healthy)
        .map((r) => r.name);
      log.warn({ id, failedServices }, 'some services failed health checks');
 
      this.eventBus.emit<PreviewFailedEvent>({
        type: 'preview:failed',
        timestamp: new Date(),
        payload: {
          previewId: id,
          initiativeId: options.initiativeId,
          error: `Health checks failed for: ${failedServices.join(', ')}`,
        },
      });
 
      await composeDown(projectName).catch(() => {});
      await rm(deployDir, { recursive: true, force: true }).catch(() => {});
 
      throw new Error(
        `Preview health checks failed for services: ${failedServices.join(', ')}`,
      );
    }
 
    // 9. Success
    const url = `http://localhost:${port}`;
    log.info({ id, url }, 'preview deployment ready');
 
    this.eventBus.emit<PreviewReadyEvent>({
      type: 'preview:ready',
      timestamp: new Date(),
      payload: {
        previewId: id,
        initiativeId: options.initiativeId,
        branch: options.branch,
        port,
        url,
      },
    });
 
    const services = await composePs(projectName);
 
    return {
      id,
      projectName,
      initiativeId: options.initiativeId,
      phaseId: options.phaseId,
      projectId: options.projectId,
      branch: options.branch,
      port,
      status: 'running',
      services,
      composePath,
    };
  }
 
  /**
   * Stop a preview deployment and clean up artifacts.
   */
  async stop(previewId: string): Promise<void> {
    const projectName = `${COMPOSE_PROJECT_PREFIX}${previewId}`;
 
    // Get labels before stopping to emit event
    const labels = await getContainerLabels(projectName);
    const initiativeId = labels[PREVIEW_LABELS.initiativeId] ?? '';
 
    await composeDown(projectName);
 
    // Clean up deployment directory
    const deployDir = join(this.workspaceRoot, PREVIEWS_DIR, previewId);
    await rm(deployDir, { recursive: true, force: true }).catch(() => {});
 
    log.info({ previewId, projectName }, 'preview stopped');
 
    this.eventBus.emit<PreviewStoppedEvent>({
      type: 'preview:stopped',
      timestamp: new Date(),
      payload: { previewId, initiativeId },
    });
  }
 
  /**
   * List all active preview deployments, optionally filtered by initiative.
   */
  async list(initiativeId?: string): Promise<PreviewStatus[]> {
    const projects = await listPreviewProjects();
    const previews: PreviewStatus[] = [];
 
    for (const project of projects) {
      const labels = await getContainerLabels(project.Name);
      if (!labels[PREVIEW_LABELS.preview]) continue;
 
      const preview = this.labelsToStatus(project.Name, labels, project.ConfigFiles);
      if (!preview) continue;
 
      if (initiativeId && preview.initiativeId !== initiativeId) continue;
 
      // Get service statuses
      preview.services = await composePs(project.Name);
      previews.push(preview);
    }
 
    return previews;
  }
 
  /**
   * Get the status of a specific preview deployment.
   */
  async getStatus(previewId: string): Promise<PreviewStatus | null> {
    const projectName = `${COMPOSE_PROJECT_PREFIX}${previewId}`;
    const labels = await getContainerLabels(projectName);
 
    if (!labels[PREVIEW_LABELS.preview]) {
      return null;
    }
 
    const preview = this.labelsToStatus(projectName, labels, '');
    Iif (!preview) return null;
 
    preview.services = await composePs(projectName);
 
    // Determine status from service states
    if (preview.services.length === 0) {
      preview.status = 'stopped';
    } else if (preview.services.every((s) => s.state === 'running')) {
      preview.status = 'running';
    } else if (preview.services.some((s) => s.state === 'exited' || s.state === 'dead')) {
      preview.status = 'failed';
    } else {
      preview.status = 'building';
    }
 
    return preview;
  }
 
  /**
   * Stop all preview deployments. Called on server shutdown.
   */
  async stopAll(): Promise<void> {
    const projects = await listPreviewProjects();
    log.info({ count: projects.length }, 'stopping all preview deployments');
 
    await Promise.all(
      projects.map(async (project) => {
        const id = project.Name.replace(COMPOSE_PROJECT_PREFIX, '');
        await this.stop(id).catch((err) => {
          log.warn({ projectName: project.Name, err }, 'failed to stop preview');
        });
      }),
    );
  }
 
  /**
   * Reconstruct PreviewStatus from Docker container labels.
   */
  private labelsToStatus(
    projectName: string,
    labels: Record<string, string>,
    composePath: string,
  ): PreviewStatus | null {
    const previewId = labels[PREVIEW_LABELS.previewId] ?? projectName.replace(COMPOSE_PROJECT_PREFIX, '');
    const initiativeId = labels[PREVIEW_LABELS.initiativeId];
    const projectId = labels[PREVIEW_LABELS.projectId];
    const branch = labels[PREVIEW_LABELS.branch];
    const port = parseInt(labels[PREVIEW_LABELS.port] ?? '0', 10);
 
    if (!initiativeId || !projectId || !branch) {
      return null;
    }
 
    return {
      id: previewId,
      projectName,
      initiativeId,
      phaseId: labels[PREVIEW_LABELS.phaseId],
      projectId,
      branch,
      port,
      status: 'running',
      services: [],
      composePath,
    };
  }
}