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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 32x 32x 32x 32x 32x 32x 1x 1x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 1x 1x 1x 1x 1x 23x 23x 23x 23x 23x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 23x 23x 23x 1x 1x 1x 1x 1x 1x 1x 36x 36x 14x 14x 14x 14x 14x 14x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 36x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 8x 8x 8x 1x 1x 1x 1x 1x 2x 2x 3x 3x 3x 3x 2x 2x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 5x 5x 4x 4x 5x 5x 5x 1x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 1x 1x 1x 1x 1x 2x 4x 4x 4x 4x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 75x 75x 75x 63x 63x 63x 63x 63x 63x 75x 75x 75x 75x 75x 75x 1x 1x 1x 1x 1x 23x 23x 23x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 23x 23x 22x 22x 22x 23x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 22x 22x 23x 23x 22x 22x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 3x 3x 1x 3x 7x 7x 2x 2x 1x 2x 7x 7x 2x 2x 1x 2x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x | /**
* Cache Manager - Build cache volume mount system
*
* Manages persistent build caches across job executions.
* Supports LRU, FIFO, and LFU eviction strategies.
* Generates Docker volume mount arguments for cache directories.
*
* Requirements: Build caching for CI cost reduction
*/
import { promises as fs } from 'fs';
import { join, basename } from 'path';
import { homedir } from 'os';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface CacheEntry {
name: string;
hostPath: string;
sizeBytes: number;
lastUsed: Date;
hitCount: number;
createdAt: Date;
}
export interface CacheStats {
totalEntries: number;
totalSizeBytes: number;
maxSizeBytes: number;
hitRate: number; // 0-1
totalHits: number;
totalMisses: number;
}
export interface CacheVolumeMount {
hostPath: string;
containerPath: string;
readOnly: boolean;
}
// ---------------------------------------------------------------------------
// Serialization helpers (Date round-trip)
// ---------------------------------------------------------------------------
interface SerializedCacheEntry {
name: string;
hostPath: string;
sizeBytes: number;
lastUsed: string;
hitCount: number;
createdAt: string;
}
interface MetadataFile {
entries: SerializedCacheEntry[];
totalHits: number;
totalMisses: number;
}
// ---------------------------------------------------------------------------
// CacheManager
// ---------------------------------------------------------------------------
export class CacheManager {
private cacheDir: string;
private maxSizeBytes: number;
private strategy: 'lru' | 'fifo' | 'lfu';
private entries: Map<string, CacheEntry> = new Map();
private totalHits: number = 0;
private totalMisses: number = 0;
private preConfiguredVolumes: Record<string, string>;
constructor(config: {
directory: string;
maxSizeGB: number;
strategy: 'lru' | 'fifo' | 'lfu';
volumes?: Record<string, string>;
}) {
this.cacheDir = config.directory || join(homedir(), '.buildhive', 'cache');
this.maxSizeBytes = config.maxSizeGB * 1024 * 1024 * 1024;
this.strategy = config.strategy;
this.preConfiguredVolumes = config.volumes ?? {};
}
/**
* Initialize cache directory and load metadata
*/
async initialize(): Promise<void> {
await fs.mkdir(this.cacheDir, { recursive: true });
await this.loadMetadata();
// Register pre-configured volumes as cache entries if not already present
for (const [name, hostPath] of Object.entries(this.preConfiguredVolumes)) {
if (!this.entries.has(name)) {
await fs.mkdir(hostPath, { recursive: true });
this.entries.set(name, {
name,
hostPath,
sizeBytes: 0,
lastUsed: new Date(),
hitCount: 0,
createdAt: new Date(),
});
}
}
await this.saveMetadata();
}
/**
* Get or create a named cache volume. Returns the host path.
* If the cache doesn't exist, creates the directory.
* Records a cache hit or miss.
*/
async getCache(name: string): Promise<string> {
const existing = this.entries.get(name);
if (existing) {
this.totalHits++;
existing.hitCount++;
existing.lastUsed = new Date();
await this.saveMetadata();
return existing.hostPath;
}
// Cache miss
this.totalMisses++;
const hostPath = join(this.cacheDir, name);
await fs.mkdir(hostPath, { recursive: true });
const entry: CacheEntry = {
name,
hostPath,
sizeBytes: 0,
lastUsed: new Date(),
hitCount: 0,
createdAt: new Date(),
};
this.entries.set(name, entry);
await this.saveMetadata();
return hostPath;
}
/**
* Generate Docker volume mount args from recipe cache config.
* Maps recipe cache paths to host cache directories.
*/
generateVolumeMounts(recipeCacheConfig: {
paths: string[];
key?: string;
}): CacheVolumeMount[] {
const mounts: CacheVolumeMount[] = [];
for (const containerPath of recipeCacheConfig.paths) {
// Derive a cache name from the path: e.g. ~/.gradle/caches -> gradle-caches
const cacheName = this.pathToCacheName(containerPath);
const hostPath = join(this.cacheDir, cacheName);
mounts.push({
hostPath,
containerPath,
readOnly: false,
});
}
return mounts;
}
/**
* Convert volume mounts to Docker -v arguments
*/
toDockerArgs(mounts: CacheVolumeMount[]): string[] {
const args: string[] = [];
for (const mount of mounts) {
const mountStr = mount.readOnly
? `${mount.hostPath}:${mount.containerPath}:ro`
: `${mount.hostPath}:${mount.containerPath}`;
args.push('-v', mountStr);
}
return args;
}
/**
* Evict caches based on strategy until under maxSize.
* Returns names of evicted entries.
*/
async evict(): Promise<string[]> {
const evicted: string[] = [];
let totalSize = this.getTotalSize();
while (totalSize > this.maxSizeBytes && this.entries.size > 0) {
const victim = this.selectVictim();
if (!victim) break;
// Remove directory
try {
await fs.rm(victim.hostPath, { recursive: true, force: true });
} catch {
// Directory may already be gone
}
totalSize -= victim.sizeBytes;
this.entries.delete(victim.name);
evicted.push(victim.name);
}
if (evicted.length > 0) {
await this.saveMetadata();
}
return evicted;
}
/**
* Get cache statistics
*/
getStats(): CacheStats {
const totalRequests = this.totalHits + this.totalMisses;
return {
totalEntries: this.entries.size,
totalSizeBytes: this.getTotalSize(),
maxSizeBytes: this.maxSizeBytes,
hitRate: totalRequests > 0 ? this.totalHits / totalRequests : 0,
totalHits: this.totalHits,
totalMisses: this.totalMisses,
};
}
/**
* Clear all caches
*/
async clear(): Promise<void> {
for (const entry of this.entries.values()) {
try {
await fs.rm(entry.hostPath, { recursive: true, force: true });
} catch {
// Ignore cleanup errors
}
}
this.entries.clear();
this.totalHits = 0;
this.totalMisses = 0;
await this.saveMetadata();
}
/**
* Save cache metadata to disk
*/
async saveMetadata(): Promise<void> {
const metadataPath = join(this.cacheDir, '.metadata.json');
const serialized: MetadataFile = {
entries: Array.from(this.entries.values()).map((e) => ({
name: e.name,
hostPath: e.hostPath,
sizeBytes: e.sizeBytes,
lastUsed: e.lastUsed.toISOString(),
hitCount: e.hitCount,
createdAt: e.createdAt.toISOString(),
})),
totalHits: this.totalHits,
totalMisses: this.totalMisses,
};
await fs.writeFile(metadataPath, JSON.stringify(serialized, null, 2), 'utf-8');
}
/**
* Load cache metadata from disk
*/
async loadMetadata(): Promise<void> {
const metadataPath = join(this.cacheDir, '.metadata.json');
try {
const raw = await fs.readFile(metadataPath, 'utf-8');
const data: MetadataFile = JSON.parse(raw);
this.entries.clear();
for (const e of data.entries) {
this.entries.set(e.name, {
name: e.name,
hostPath: e.hostPath,
sizeBytes: e.sizeBytes,
lastUsed: new Date(e.lastUsed),
hitCount: e.hitCount,
createdAt: new Date(e.createdAt),
});
}
this.totalHits = data.totalHits ?? 0;
this.totalMisses = data.totalMisses ?? 0;
} catch {
// No metadata file yet — start fresh
this.entries.clear();
}
}
/**
* Update the recorded size of a cache entry by scanning its directory.
*/
async updateEntrySize(name: string): Promise<void> {
const entry = this.entries.get(name);
if (!entry) return;
entry.sizeBytes = await this.getDirectorySize(entry.hostPath);
await this.saveMetadata();
}
// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------
/**
* Get total size of a directory in bytes
*/
private async getDirectorySize(dirPath: string): Promise<number> {
let total = 0;
try {
const items = await fs.readdir(dirPath, { withFileTypes: true });
for (const item of items) {
const fullPath = join(dirPath, item.name);
if (item.isDirectory()) {
total += await this.getDirectorySize(fullPath);
} else {
const stat = await fs.stat(fullPath);
total += stat.size;
}
}
} catch {
// Directory may not exist or be inaccessible
}
return total;
}
private getTotalSize(): number {
let total = 0;
for (const entry of this.entries.values()) {
total += entry.sizeBytes;
}
return total;
}
/**
* Select the next entry to evict based on the configured strategy.
*/
private selectVictim(): CacheEntry | undefined {
if (this.entries.size === 0) return undefined;
const entries = Array.from(this.entries.values());
switch (this.strategy) {
case 'lru':
// Least recently used — oldest lastUsed
return entries.reduce((oldest, e) =>
e.lastUsed < oldest.lastUsed ? e : oldest
);
case 'fifo':
// First in, first out — oldest createdAt
return entries.reduce((oldest, e) =>
e.createdAt < oldest.createdAt ? e : oldest
);
case 'lfu':
// Least frequently used — lowest hitCount
return entries.reduce((least, e) =>
e.hitCount < least.hitCount ? e : least
);
default:
return entries[0];
}
}
/**
* Convert a filesystem path to a cache name.
* e.g. "~/.gradle/caches" -> "gradle-caches"
* "/root/.gradle/caches" -> "gradle-caches"
*/
private pathToCacheName(fsPath: string): string {
// Expand ~ and remove leading dots/slashes
const normalized = fsPath
.replace(/^~\//, '')
.replace(/^\/+/, '');
// Replace path separators and dots with hyphens, collapse multiple
return normalized
.replace(/[\/\\]+/g, '-')
.replace(/^\.+/, '')
.replace(/\.+/g, '-')
.replace(/-+/g, '-')
.replace(/(^-|-$)/g, '');
}
}
|