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 | 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 18x 15x 18x 18x 18x 18x 18x 18x 8x 8x 8x 5x 3x 2x 1x 1x 7x 6x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 4x 4x 2x 4x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 5x 8x 5x 4x 4x 4x 4x 4x 9x 9x | import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { MediaService } from '@app/modules/media/media.service';
import sharp from 'sharp';
import { Readable } from 'stream';
import {
S3Client,
PutObjectCommand,
GetObjectCommand,
GetObjectCommandOutput,
} from '@aws-sdk/client-s3';
import { ConfigService } from '@nestjs/config';
import { v4 as uuid } from 'uuid';
import { Histogram, register } from 'prom-client';
import { Logger } from '@nestjs/common';
import { withRetry } from '@app/common/utils/retry';
interface MediaProcessPayload {
id: number;
type: 'IMAGE' | 'VIDEO' | 'FLOORPLAN';
storageKey: string;
mimeType: string;
}
@Processor('media')
export class MediaProcessor extends WorkerHost {
private readonly r2: S3Client;
private readonly bucket: string;
private readonly logger = new Logger(MediaProcessor.name);
private static readonly processingHistogram: Histogram<string> = (register.getSingleMetric('media_processing_duration_seconds') as Histogram<string>) ?? new Histogram({
name: 'media_processing_duration_seconds',
help: 'Time taken to process media jobs',
buckets: [0.5, 1, 2, 5, 10, 30, 60],
labelNames: ['type'] as const,
registers: [register],
});
constructor(private readonly mediaService: MediaService, private readonly config: ConfigService) {
super();
this.bucket = this.config.get<string>('R2_BUCKET') || 'media-bucket';
const endpoint = this.config.get<string>('R2_ENDPOINT');
const region = this.config.get<string>('R2_REGION', 'us-east-1');
this.r2 = new S3Client({
region,
credentials: {
accessKeyId: this.config.get<string>('R2_ACCESS_KEY_ID') || '',
secretAccessKey: this.config.get<string>('R2_SECRET_ACCESS_KEY') || '',
} as any,
endpoint: endpoint || undefined,
forcePathStyle: !!endpoint,
});
}
async process(job: Job<MediaProcessPayload>): Promise<void> {
const { id, type, storageKey, mimeType } = job.data;
const endTimer = MediaProcessor.processingHistogram.startTimer({ type });
if (type === 'IMAGE') {
await this.processImage(id, storageKey, mimeType);
} else if (type === 'FLOORPLAN') {
await this.processFloorPlan(id, storageKey, mimeType);
} else if (type === 'VIDEO') {
await this.processVideo(id, storageKey);
}
endTimer();
}
private async processImage(id: number, storageKey: string, _mimeType: string): Promise<void> {
const buffer = await this.downloadToBuffer(storageKey);
// Generate variants
const variants: Record<string, string> = {};
const fullKey = `media/variants/${id}/${uuid()}-1024.jpg`;
const thumbKey = `media/variants/${id}/${uuid()}-256.jpg`;
// 1024px
const fullBuf = await sharp(buffer).resize(1024).jpeg({ quality: 80 }).toBuffer();
await this.uploadBuffer(fullKey, fullBuf, 'image/jpeg');
variants.preview1024 = fullKey;
// 256px thumbnail
const thumbBuf = await sharp(buffer).resize(256).jpeg({ quality: 70 }).toBuffer();
await this.uploadBuffer(thumbKey, thumbBuf, 'image/jpeg');
variants.thumbnail256 = thumbKey;
// Update DB
await this.mediaService.updateVariants(id, variants);
}
private async processFloorPlan(id: number, storageKey: string, _mimeType: string): Promise<void> {
// Download first page only using sharp(page:0)
const buffer = await this.downloadToBuffer(storageKey);
const variants: Record<string, string> = {};
const previewKey = `media/variants/${id}/${uuid()}-floorplan-1024.png`;
const thumbKey = `media/variants/${id}/${uuid()}-floorplan-256.png`;
const previewBuf = await sharp(buffer, { page: 0 }).resize(1024).png().toBuffer();
await this.uploadBuffer(previewKey, previewBuf, 'image/png');
variants.preview1024 = previewKey;
const thumbBuf = await sharp(buffer, { page: 0 }).resize(256).png().toBuffer();
await this.uploadBuffer(thumbKey, thumbBuf, 'image/png');
variants.thumbnail256 = thumbKey;
await this.mediaService.updateVariants(id, variants);
}
private async processVideo(id: number, storageKey: string): Promise<void> {
const tmpDir = `/tmp/${id}-${Date.now()}`;
const inputPath = `${tmpDir}/input.mp4`;
const hlsDir = `${tmpDir}/hls`;
const thumbnailPath = `${tmpDir}/thumb.jpg`;
const fs = await import('node:fs/promises');
const path = await import('node:path');
// @ts-ignore – runtime import, types may be missing
const ffmpeg = (await import('fluent-ffmpeg')).default;
// @ts-ignore – runtime import, types may be missing
const ffmpegStatic = await import('ffmpeg-static');
ffmpeg.setFfmpegPath(ffmpegStatic as any);
await fs.mkdir(hlsDir, { recursive: true });
// Download original
const buffer = await this.downloadToBuffer(storageKey);
await fs.writeFile(inputPath, buffer);
// 1) Transcode to 720p HLS
await new Promise<void>((resolve, reject) => {
ffmpeg(inputPath)
.addOption('-preset', 'veryfast')
.videoCodec('libx264')
.size('?x720')
.outputOptions([
'-hls_time 4',
'-hls_playlist_type vod',
'-hls_segment_filename', path.join(hlsDir, 'seg_%03d.ts'),
])
.output(path.join(hlsDir, 'index.m3u8'))
.on('end', () => resolve())
.on('error', (err: any) => reject(err))
.run();
});
// 2) Extract thumbnail at 1s
await new Promise<void>((resolve, reject) => {
ffmpeg(inputPath)
.screenshots({ timestamps: ['1'], filename: 'thumb.jpg', folder: tmpDir, size: '320x?' })
.on('error', (err: any) => reject(err))
.on('end', () => resolve());
});
// Upload artifacts
const uuid = (await import('uuid')).v4;
const hlsBaseKey = `media/variants/${id}/${uuid()}`;
const hlsIndexKey = `${hlsBaseKey}/index.m3u8`;
// Upload HLS files
const hlsFiles = await fs.readdir(hlsDir);
for (const file of hlsFiles) {
const key = `${hlsBaseKey}/${file}`;
const body = await fs.readFile(path.join(hlsDir, file));
await this.uploadBuffer(key, body, file.endsWith('.ts') ? 'video/MP2T' : 'application/vnd.apple.mpegurl');
}
// Upload thumbnail
const thumbBuf = await fs.readFile(thumbnailPath);
const thumbKey = `media/variants/${id}/${uuid()}-thumb.jpg`;
await this.uploadBuffer(thumbKey, thumbBuf, 'image/jpeg');
// Update DB variants
await this.mediaService.updateVariants(id, { hlsUrl: hlsIndexKey, thumbnail: thumbKey });
// Cleanup tmp files
await fs.rm(tmpDir, { recursive: true, force: true });
}
private async downloadToBuffer(key: string): Promise<Buffer> {
return withRetry(
async () => {
const { Body } = (await this.r2.send(
new GetObjectCommand({ Bucket: this.bucket, Key: key }),
)) as GetObjectCommandOutput;
if (!Body) throw new Error('Empty body');
const stream = Body as Readable;
const chunks: Buffer[] = [];
for await (const chunk of stream) {
chunks.push(chunk as Buffer);
}
return Buffer.concat(chunks);
},
{
tries: 3,
baseDelayMs: 1000,
maxDelayMs: 5000,
onAttempt: (attempt, err) => {
this.logger.warn(`S3 download retry attempt ${attempt} for key ${key}`, { error: err instanceof Error ? err.message : String(err) });
},
}
);
}
private async uploadBuffer(key: string, buf: Buffer, contentType: string) {
return withRetry(
async () => {
await this.r2.send(
new PutObjectCommand({
Bucket: this.bucket,
Key: key,
Body: buf,
ContentType: contentType,
ACL: 'private', // Enforce private ACL for security
}),
);
},
{
tries: 3,
baseDelayMs: 1000,
maxDelayMs: 5000,
onAttempt: (attempt, err) => {
this.logger.warn(`S3 upload retry attempt ${attempt} for key ${key}`, { error: err instanceof Error ? err.message : String(err) });
},
}
);
}
} |