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 | 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 43x 1x 1x 43x 43x 43x 43x 43x 43x 43x 1x 1x 1x 1x 1x 23x 1x 1x 22x 22x 23x 22x 22x 22x 22x 22x 22x 23x 21x 21x 21x 21x 21x 22x 22x 23x 1x 1x 1x 22x 22x 22x 23x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 1x 1x 1x 1x 1x 10x 10x 1x 1x 1x 1x 9x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 17x 16x 16x 16x 16x 17x 14x 17x 2x 2x 12x 12x 12x 12x 12x 12x 12x 17x 1x 1x 12x 12x 12x 20x 8x 8x 8x 8x 8x 8x 8x 20x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 14x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 14x 11x 11x 11x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 11x 11x 11x 11x 9x 14x 3x 3x 3x 3x 10x 10x 10x 10x 10x 10x 10x 10x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 4x 1x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x 1x 1x 5x 1x 1x 4x 5x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 3x 3x 3x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2x 2x 2x 2x 2x 2x 2x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 19x 19x 19x 7x 7x 7x 4x 4x 4x 4x 4x 4x 4x 4x 4x 7x 19x 7x 7x 7x 15x 15x 15x 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 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 4x 4x 1x 5x 5x 1x 1x 1x 1x 1x 5x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 4x 5x 4x 4x 4x 4x 4x 4x 2x 2x 4x 3x 3x 4x 4x 4x 4x 1x 3x 4x 4x 1x 1x 1x 1x 3x 3x 3x 3x 3x 4x 4x 4x 4x 1x | /**
* Artifact Uploader - MVP.4.2.4
*
* Handles artifact upload to storage backends (local or S3).
*
* Features:
* - Local file storage with configurable base path
* - S3 upload with multipart support for large files (>50MB)
* - S3-compatible storage support (MinIO, Cloudflare R2, etc.)
* - Presigned download URL generation
* - Retry logic with exponential backoff
* - Proper error handling and logging
* - Cleanup of temporary files after upload
* - Batch S3 object deletion for retention cleanup
*
* @module storage/artifactUploader
*/
import { promises as fs } from 'fs';
import { createReadStream } from 'fs';
import { join, dirname, basename } from 'path';
import type { StorageConfig, S3Config } from '../config/types.js';
import { createLogger } from '../utils/logger.js';
import {
S3Client,
PutObjectCommand,
GetObjectCommand,
ListObjectsV2Command,
DeleteObjectsCommand,
} from '@aws-sdk/client-s3';
import { Upload } from '@aws-sdk/lib-storage';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
const logger = createLogger('ArtifactUploader');
export interface UploadResult {
url: string;
size: number;
uploadedAt: Date;
}
export interface UploadOptions {
/**
* Maximum number of retry attempts on failure
*/
maxRetries?: number;
/**
* Base delay in milliseconds for exponential backoff
*/
retryDelayMs?: number;
/**
* Whether to delete the source file after successful upload
*/
deleteAfterUpload?: boolean;
}
/** Threshold in bytes above which multipart upload is used (50 MB) */
const MULTIPART_THRESHOLD = 50 * 1024 * 1024;
export class ArtifactUploader {
private config: StorageConfig;
private s3Client: S3Client | null = null;
constructor(config: StorageConfig) {
this.config = config;
logger.info('ArtifactUploader initialized', {
type: config.type,
localPath: config.localPath,
s3Bucket: config.s3?.bucket
});
}
/**
* Lazily create and cache an S3Client instance based on the current config.
*/
private getS3Client(): S3Client {
if (this.s3Client) {
return this.s3Client;
}
const s3Cfg = this.config.s3;
if (!s3Cfg) {
throw new Error('S3 configuration is missing');
}
const clientConfig: Record<string, unknown> = {
region: s3Cfg.region,
};
// Support explicit credentials; omit to use AWS default credential chain
if (s3Cfg.accessKeyId && s3Cfg.secretAccessKey) {
clientConfig.credentials = {
accessKeyId: s3Cfg.accessKeyId,
secretAccessKey: s3Cfg.secretAccessKey,
};
}
// Support S3-compatible endpoints (MinIO, R2, etc.)
if (s3Cfg.endpoint) {
clientConfig.endpoint = s3Cfg.endpoint;
clientConfig.forcePathStyle = true; // Required for most S3-compatible stores
}
this.s3Client = new S3Client(clientConfig as any);
return this.s3Client;
}
/**
* Build the S3 object key from an artifact name, applying the configured path prefix.
*/
private buildS3Key(artifactName: string): string {
const prefix = this.config.s3?.pathPrefix || '';
// Normalise: strip leading slash from artifact name, ensure prefix ends without double slashes
const cleanPrefix = prefix.endsWith('/') ? prefix : prefix ? `${prefix}/` : '';
const cleanName = artifactName.startsWith('/') ? artifactName.slice(1) : artifactName;
return `${cleanPrefix}${cleanName}`;
}
/**
* Build a public-style S3 URL for an object.
*/
private buildS3Url(key: string): string {
const s3Cfg = this.config.s3!;
if (s3Cfg.endpoint) {
// S3-compatible storage - use endpoint-based URL
const base = s3Cfg.endpoint.replace(/\/$/, '');
return `${base}/${s3Cfg.bucket}/${key}`;
}
return `https://${s3Cfg.bucket}.s3.${s3Cfg.region}.amazonaws.com/${key}`;
}
/**
* Upload an artifact to the configured storage backend
*
* @param sourcePath - Absolute path to the artifact file
* @param artifactName - Name/path for the artifact in storage
* @param options - Upload options
* @returns Upload result with URL and metadata
*/
async uploadArtifact(
sourcePath: string,
artifactName: string,
options: UploadOptions = {}
): Promise<UploadResult> {
const {
maxRetries = 3,
retryDelayMs = 1000,
deleteAfterUpload = this.config.cleanupAfterUpload
} = options;
logger.info('Uploading artifact', { sourcePath, artifactName, backend: this.config.type });
try {
// Verify source file exists
const stats = await fs.stat(sourcePath);
if (!stats.isFile()) {
throw new Error(`Source path is not a file: ${sourcePath}`);
}
let result: UploadResult;
// Upload based on storage type
if (this.config.type === 's3') {
result = await this.uploadToS3(sourcePath, artifactName, maxRetries, retryDelayMs);
} else {
result = await this.uploadToLocal(sourcePath, artifactName, maxRetries, retryDelayMs);
}
logger.info('Artifact uploaded successfully', {
url: result.url,
size: result.size
});
// Clean up source file if requested
if (deleteAfterUpload) {
await this.deleteFile(sourcePath);
}
return result;
} catch (error: any) {
logger.error('Failed to upload artifact', {
sourcePath,
artifactName,
error: error.message
});
throw error;
}
}
/**
* Upload artifact to local storage
*
* @param sourcePath - Source file path
* @param artifactName - Target artifact name
* @param maxRetries - Maximum retry attempts
* @param retryDelayMs - Retry delay in milliseconds
* @returns Upload result
*/
private async uploadToLocal(
sourcePath: string,
artifactName: string,
maxRetries: number,
retryDelayMs: number
): Promise<UploadResult> {
const basePath = this.config.localPath || '/tmp/buildhive/artifacts';
const targetPath = join(basePath, artifactName);
logger.debug('Uploading to local storage', { sourcePath, targetPath });
// Ensure target directory exists
await fs.mkdir(dirname(targetPath), { recursive: true });
// Copy file with retry logic
await this.retryOperation(
async () => {
await fs.copyFile(sourcePath, targetPath);
},
maxRetries,
retryDelayMs,
`copy ${sourcePath} to ${targetPath}`
);
// Get file stats
const stats = await fs.stat(targetPath);
return {
url: `file://${targetPath}`,
size: stats.size,
uploadedAt: new Date()
};
}
/**
* Upload artifact to S3
*
* Uses PutObjectCommand for files <= 50 MB and multipart Upload for larger files.
* Supports S3-compatible storage (MinIO, Cloudflare R2) via custom endpoint.
*
* @param sourcePath - Source file path
* @param artifactName - Target artifact name
* @param maxRetries - Maximum retry attempts
* @param retryDelayMs - Retry delay in milliseconds
* @returns Upload result
*/
private async uploadToS3(
sourcePath: string,
artifactName: string,
maxRetries: number,
retryDelayMs: number
): Promise<UploadResult> {
if (!this.config.s3) {
throw new Error('S3 configuration is missing');
}
const client = this.getS3Client();
const key = this.buildS3Key(artifactName);
const stats = await fs.stat(sourcePath);
const fileSize = stats.size;
logger.info('Uploading to S3', {
sourcePath,
bucket: this.config.s3.bucket,
key,
fileSize,
multipart: fileSize > MULTIPART_THRESHOLD
});
try {
if (fileSize > MULTIPART_THRESHOLD) {
// Multipart upload for large files
await this.retryOperation(
async () => {
const upload = new Upload({
client,
params: {
Bucket: this.config.s3!.bucket,
Key: key,
Body: createReadStream(sourcePath),
},
// 10 MB part size, 4 concurrent uploads
partSize: 10 * 1024 * 1024,
queueSize: 4,
});
upload.on('httpUploadProgress', (progress) => {
logger.debug('Multipart upload progress', {
key,
loaded: progress.loaded,
total: progress.total,
});
});
await upload.done();
},
maxRetries,
retryDelayMs,
`multipart upload ${artifactName} to S3`
);
} else {
// Single PutObject for smaller files
await this.retryOperation(
async () => {
const fileStream = createReadStream(sourcePath);
await client.send(
new PutObjectCommand({
Bucket: this.config.s3!.bucket,
Key: key,
Body: fileStream,
ContentLength: fileSize,
})
);
},
maxRetries,
retryDelayMs,
`upload ${artifactName} to S3`
);
}
} catch (error: any) {
throw new Error(
`Failed to upload artifact "${artifactName}" to S3 bucket "${this.config.s3.bucket}": ${error.message}`
);
}
const url = this.buildS3Url(key);
return {
url,
size: fileSize,
uploadedAt: new Date(),
};
}
/**
* Generate a presigned download URL for an artifact in S3.
*
* @param artifactName - The artifact name/path in storage
* @param expiresInSeconds - URL expiration time (default: 3600 = 1 hour)
* @returns Presigned download URL
*/
async getSignedDownloadUrl(
artifactName: string,
expiresInSeconds: number = 3600
): Promise<string> {
if (this.config.type !== 's3' || !this.config.s3) {
throw new Error('Signed URLs are only available with S3 storage');
}
const client = this.getS3Client();
const key = this.buildS3Key(artifactName);
try {
const command = new GetObjectCommand({
Bucket: this.config.s3.bucket,
Key: key,
});
const signedUrl = await getSignedUrl(client, command, {
expiresIn: expiresInSeconds,
});
logger.info('Generated presigned download URL', {
artifactName,
key,
expiresInSeconds,
});
return signedUrl;
} catch (error: any) {
throw new Error(
`Failed to generate presigned URL for "${artifactName}": ${error.message}`
);
}
}
/**
* Delete S3 objects in batch using DeleteObjectsCommand.
*
* @param keys - Array of S3 object keys to delete
* @returns Number of objects successfully deleted
*/
async deleteS3Objects(keys: string[]): Promise<number> {
if (this.config.type !== 's3' || !this.config.s3) {
throw new Error('S3 deletion is only available with S3 storage');
}
if (keys.length === 0) {
return 0;
}
const client = this.getS3Client();
let totalDeleted = 0;
// DeleteObjects supports max 1000 keys per request
const batchSize = 1000;
for (let i = 0; i < keys.length; i += batchSize) {
const batch = keys.slice(i, i + batchSize);
try {
const response = await client.send(
new DeleteObjectsCommand({
Bucket: this.config.s3.bucket,
Delete: {
Objects: batch.map((k) => ({ Key: k })),
Quiet: true,
},
})
);
const errCount = response.Errors?.length || 0;
totalDeleted += batch.length - errCount;
if (errCount > 0) {
logger.warn('Some S3 objects failed to delete', {
errors: response.Errors?.slice(0, 5),
});
}
} catch (error: any) {
logger.error('Batch S3 deletion failed', {
batchStart: i,
batchSize: batch.length,
error: error.message,
});
throw new Error(
`Failed to delete S3 objects (batch starting at ${i}): ${error.message}`
);
}
}
logger.info('S3 batch deletion complete', {
requested: keys.length,
deleted: totalDeleted,
});
return totalDeleted;
}
/**
* Delete a file from the filesystem
*
* @param filePath - Path to the file to delete
*/
private async deleteFile(filePath: string): Promise<void> {
try {
await fs.unlink(filePath);
logger.debug('Deleted file after upload', { filePath });
} catch (error: any) {
logger.warn('Failed to delete file after upload', {
filePath,
error: error.message
});
// Don't throw - deletion failure is not critical
}
}
/**
* Retry an operation with exponential backoff
*
* @param operation - Async operation to retry
* @param maxRetries - Maximum number of retry attempts
* @param baseDelayMs - Base delay for exponential backoff
* @param operationName - Name for logging
*/
private async retryOperation<T>(
operation: () => Promise<T>,
maxRetries: number,
baseDelayMs: number,
operationName: string
): Promise<T> {
let lastError: Error | undefined;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (error: any) {
lastError = error;
if (attempt < maxRetries) {
const delay = baseDelayMs * Math.pow(2, attempt);
logger.warn(`Operation failed, retrying (${attempt + 1}/${maxRetries})`, {
operation: operationName,
error: error.message,
retryDelayMs: delay
});
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
throw new Error(
`Operation failed after ${maxRetries} retries: ${operationName}. ` +
`Last error: ${lastError?.message}`
);
}
/**
* Clean up old artifacts based on retention policy
*
* @param basePath - Base path to scan for old artifacts
* @returns Number of files deleted
*/
async cleanupOldArtifacts(basePath?: string): Promise<number> {
const path = basePath || this.config.localPath || '/tmp/buildhive/artifacts';
const retentionMs = this.config.retentionDays * 24 * 60 * 60 * 1000;
const cutoffTime = Date.now() - retentionMs;
logger.info('Starting artifact cleanup', {
path,
retentionDays: this.config.retentionDays
});
try {
const files = await this.findOldFiles(path, cutoffTime);
let deletedCount = 0;
for (const file of files) {
try {
await fs.unlink(file);
deletedCount++;
logger.debug('Deleted old artifact', { file });
} catch (error: any) {
logger.warn('Failed to delete old artifact', {
file,
error: error.message
});
}
}
logger.info('Artifact cleanup complete', { deletedCount });
return deletedCount;
} catch (error: any) {
logger.error('Artifact cleanup failed', { error: error.message });
return 0;
}
}
/**
* Recursively find files older than the cutoff time
*
* @param dirPath - Directory to scan
* @param cutoffTime - Cutoff timestamp (files older than this will be included)
* @returns Array of file paths
*/
private async findOldFiles(dirPath: string, cutoffTime: number): Promise<string[]> {
const oldFiles: string[] = [];
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(dirPath, entry.name);
if (entry.isDirectory()) {
const subDirFiles = await this.findOldFiles(fullPath, cutoffTime);
oldFiles.push(...subDirFiles);
} else if (entry.isFile()) {
const stats = await fs.stat(fullPath);
if (stats.mtimeMs < cutoffTime) {
oldFiles.push(fullPath);
}
}
}
} catch (error: any) {
if (error.code !== 'ENOENT') {
logger.warn('Error scanning directory for old files', {
dirPath,
error: error.message
});
}
}
return oldFiles;
}
/**
* Get storage statistics
*
* @returns Storage usage statistics
*/
async getStorageStats(): Promise<{
type: 'local' | 's3';
totalFiles: number;
totalSizeBytes: number;
oldestFileDate?: Date;
newestFileDate?: Date;
}> {
if (this.config.type === 's3') {
return this.getS3StorageStats();
}
const basePath = this.config.localPath || '/tmp/buildhive/artifacts';
const files = await this.findAllFiles(basePath);
let totalSize = 0;
let oldestTime: number | undefined;
let newestTime: number | undefined;
for (const file of files) {
const stats = await fs.stat(file);
totalSize += stats.size;
const mtime = stats.mtimeMs;
if (oldestTime === undefined || mtime < oldestTime) {
oldestTime = mtime;
}
if (newestTime === undefined || mtime > newestTime) {
newestTime = mtime;
}
}
return {
type: 'local',
totalFiles: files.length,
totalSizeBytes: totalSize,
oldestFileDate: oldestTime ? new Date(oldestTime) : undefined,
newestFileDate: newestTime ? new Date(newestTime) : undefined
};
}
/**
* Recursively find all files in a directory
*
* @param dirPath - Directory to scan
* @returns Array of file paths
*/
private async findAllFiles(dirPath: string): Promise<string[]> {
const allFiles: string[] = [];
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(dirPath, entry.name);
if (entry.isDirectory()) {
const subDirFiles = await this.findAllFiles(fullPath);
allFiles.push(...subDirFiles);
} else if (entry.isFile()) {
allFiles.push(fullPath);
}
}
} catch (error: any) {
if (error.code !== 'ENOENT') {
logger.warn('Error scanning directory for files', {
dirPath,
error: error.message
});
}
}
return allFiles;
}
/**
* Retrieve storage statistics from S3 using ListObjectsV2 with pagination.
*/
private async getS3StorageStats(): Promise<{
type: 'local' | 's3';
totalFiles: number;
totalSizeBytes: number;
oldestFileDate?: Date;
newestFileDate?: Date;
}> {
if (!this.config.s3) {
throw new Error('S3 configuration is missing');
}
const client = this.getS3Client();
const prefix = this.config.s3.pathPrefix || '';
let totalFiles = 0;
let totalSizeBytes = 0;
let oldestTime: number | undefined;
let newestTime: number | undefined;
let continuationToken: string | undefined;
try {
do {
const response = await client.send(
new ListObjectsV2Command({
Bucket: this.config.s3.bucket,
Prefix: prefix || undefined,
ContinuationToken: continuationToken,
})
);
for (const obj of response.Contents || []) {
totalFiles++;
totalSizeBytes += obj.Size || 0;
if (obj.LastModified) {
const mtime = obj.LastModified.getTime();
if (oldestTime === undefined || mtime < oldestTime) {
oldestTime = mtime;
}
if (newestTime === undefined || mtime > newestTime) {
newestTime = mtime;
}
}
}
continuationToken = response.IsTruncated
? response.NextContinuationToken
: undefined;
} while (continuationToken);
} catch (error: any) {
throw new Error(
`Failed to retrieve S3 storage stats for bucket "${this.config.s3.bucket}": ${error.message}`
);
}
return {
type: 's3',
totalFiles,
totalSizeBytes,
oldestFileDate: oldestTime ? new Date(oldestTime) : undefined,
newestFileDate: newestTime ? new Date(newestTime) : undefined,
};
}
}
|