Files
back_end_oudelaa/test/async-video.e2e-spec.ts

170 lines
9.3 KiB
TypeScript

import { INestApplication, ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Test } from '@nestjs/testing';
import { getModelToken } from '@nestjs/mongoose';
import { JwtService } from '@nestjs/jwt';
import { Model } from 'mongoose';
import * as request from 'supertest';
import { spawn, ChildProcess } from 'child_process';
import { mkdtemp, readFile, unlink, rmdir } from 'fs/promises';
import { join, resolve } from 'path';
import { tmpdir } from 'os';
import { AppModule } from '../src/app.module';
import { User, UserDocument } from '../src/modules/users/schemas/user.schema';
import { Post, PostDocument } from '../src/modules/posts/schemas/post.schema';
import { VideoJobsService } from '../src/modules/posts/video-jobs.service';
import { VideoProcessingService } from '../src/infrastructure/storage/video-processing.service';
import { MediaProcessService } from '../src/infrastructure/storage/media-process.service';
import { MusicRole } from '../src/common/enums/music-role.enum';
const isolated = process.env.E2E_MONGODB_URI ? describe : describe.skip;
isolated('async video and musical discovery on private MongoDB', () => {
let app: INestApplication;
let users: Model<UserDocument>;
let posts: Model<PostDocument>;
let owner: UserDocument;
let token: string;
let stranger: string;
let clip: Buffer;
let directory: string;
const children: ChildProcess[] = [];
const stamp = Date.now();
beforeAll(async () => {
const module = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = module.createNestApplication();
const config = app.get(ConfigService);
config.set('videoJobs.enabled', true);
config.set('videoProcessing.enabled', true);
config.set('imageProcessing.enabled', false);
app.setGlobalPrefix('api/v1');
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
await app.listen(0, '127.0.0.1');
users = app.get(getModelToken(User.name));
posts = app.get(getModelToken(Post.name));
owner = await users.create({ name: 'Video owner', username: `video_owner_${stamp}`, email: `video${stamp}@example.com`, password: 'unused-test-password' });
const other = await users.create({ name: 'Video stranger', username: `video_other_${stamp}`, email: `video_other${stamp}@example.com`, password: 'unused-test-password' });
const jwt = new JwtService();
token = jwt.sign({ sub: owner.id, role: 'user', tokenType: 'access' }, { secret: 'test-access-secret-123456' });
stranger = jwt.sign({ sub: other.id, role: 'user', tokenType: 'access' }, { secret: 'test-access-secret-123456' });
directory = await mkdtemp(join(tmpdir(), 'oudelaa-async-clip-'));
const file = join(directory, 'clip.mp4');
await app.get(MediaProcessService).run('ffmpeg', ['-y', '-hide_banner', '-loglevel', 'error',
'-f', 'lavfi', '-i', 'color=c=black:s=160x90:r=5:d=2', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', file], 15000);
clip = await readFile(file);
}, 90000);
afterAll(async () => {
for (const child of children) {
if (child.pid && child.exitCode === null && child.signalCode === null) {
const ended = new Promise((done) => child.once('exit', done));
child.kill();
await ended;
}
}
if (app) await app.close();
if (directory) {
await unlink(join(directory, 'clip.mp4')).catch(() => undefined);
await rmdir(directory).catch(() => undefined);
}
});
const create = async () => {
const response = await request(app.getHttpServer()).post('/api/v1/posts')
.set('Authorization', `Bearer ${token}`).field('content', 'Queued music performance')
.attach('videoFile', clip, { filename: 'clip.mp4', contentType: 'video/mp4' }).expect(201);
expect(response.body.processingStatus).toBe('pending');
expect(response.body.videoJob).toBeUndefined();
return String(response.body._id || response.body.id);
};
it('stages the HTTP upload, hides pending content, and atomically admits one worker', async () => {
const spy = jest.spyOn(app.get(VideoProcessingService), 'optimizeForPlayback');
const id = await create();
expect(spy).not.toHaveBeenCalled();
await request(app.getHttpServer()).get(`/api/v1/posts/${id}`).set('Authorization', `Bearer ${stranger}`).expect(404);
const jobs = app.get(VideoJobsService);
const results = await Promise.all([jobs.processOne(), jobs.processOne()]);
expect(results.sort()).toEqual([false, true]);
const finished = await posts.findById(id).select('+videoJob').lean();
expect(finished?.processingStatus).toBe('ready');
expect(finished?.videoJob).toBeUndefined();
expect(finished?.videoUrl).toContain('/processed/');
expect(finished?.hlsUrl).toContain('.m3u8');
expect(finished?.durationSeconds).toBe(2);
await request(app.getHttpServer()).get(`/api/v1/posts/${id}`).set('Authorization', `Bearer ${stranger}`).expect(200);
spy.mockRestore();
}, 60000);
it('processes a durable pending post in an independent Node worker process', async () => {
const id = await create();
let logs = '';
const child = spawn(process.execPath, [resolve('dist/legacy/src/video-worker.js')], {
cwd: process.cwd(), windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, MONGODB_URI: process.env.E2E_MONGODB_URI,
VIDEO_JOBS_ENABLED: 'true', VIDEO_PROCESSING_ENABLED: 'true', IMAGE_PROCESSING_ENABLED: 'false',
VIDEO_PROCESSING_GENERATE_HLS: 'true', REDIS_ENABLED: 'false', QUEUE_ENABLED: 'false' },
});
children.push(child);
child.stdout?.on('data', (chunk) => { logs = (logs + chunk.toString()).slice(-1500); });
child.stderr?.on('data', (chunk) => { logs = (logs + chunk.toString()).slice(-1500); });
const deadline = Date.now() + 45000;
let state = '';
while (Date.now() < deadline && child.exitCode === null && child.signalCode === null) {
state = (await posts.findById(id).lean())?.processingStatus ?? '';
if (state === 'ready' || state === 'failed') break;
await new Promise((done) => setTimeout(done, 150));
}
if (state !== 'ready') throw new Error(`Independent worker ended in ${state}: ${logs}`);
expect(state).toBe('ready');
const ended = new Promise((done) => child.once('exit', done));
child.kill();
await ended;
}, 60000);
it('recovers an abandoned final attempt and restricts manual retry to its owner', async () => {
const id = await create();
await posts.updateOne({ _id: id }, { $set: { processingStatus: 'processing',
'videoJob.attempts': 3, 'videoJob.leaseUntil': new Date(0) } });
await app.get(VideoJobsService).processOne();
expect((await posts.findById(id).lean())?.processingStatus).toBe('failed');
await request(app.getHttpServer()).post(`/api/v1/posts/${id}/video/retry`).set('Authorization', `Bearer ${stranger}`).expect(404);
await request(app.getHttpServer()).post(`/api/v1/posts/${id}/video/retry`).set('Authorization', `Bearer ${token}`).expect(201);
expect((await posts.findById(id).lean())?.processingStatus).toBe('pending');
await posts.updateOne({ _id: id }, { $set: { isDeleted: true } });
expect(await app.get(VideoJobsService).processOne()).toBe(false);
});
it('reclaims an ordinary expired lease and successfully publishes its retry', async () => {
const id = await create();
await posts.updateOne({ _id: id }, { $set: { processingStatus: 'processing',
'videoJob.attempts': 1, 'videoJob.leaseUntil': new Date(0), 'videoJob.leaseToken': 'old-worker' } });
expect(await app.get(VideoJobsService).processOne()).toBe(true);
const finished = await posts.findById(id).select('+videoJob').lean();
expect(finished?.processingStatus).toBe('ready');
expect(finished?.videoJob).toBeUndefined();
}, 60000);
it('finds public musicians across the dateline with exact radius and musical filters', async () => {
const instrument = `oud-${stamp}`;
const artists = await users.insertMany([
{ longitude: -179.9, isPrivate: false }, { longitude: 0, isPrivate: false }, { longitude: -179.9, isPrivate: true },
].map((position, index) => ({ ...position, latitude: 0, name: 'Nearby artist',
username: `geo_${stamp}_${index}`, email: `geo${stamp}_${index}@example.com`, password: 'unused-test-password',
musicRoles: [MusicRole.COMPOSER], favoriteInstruments: [instrument], favoriteMaqamat: ['راست'] })));
const response = await request(app.getHttpServer()).get('/api/v1/users/discover')
.set('Authorization', `Bearer ${token}`).query({ instrument, maqam: 'راست', latitude: 0,
longitude: 179.9, radiusKm: 30, hasAvatarOnly: false, includeRoleBuckets: false }).expect(200);
expect(response.body.items.map((artist: any) => String(artist._id))).toEqual([artists[0].id]);
});
it('matches Arabic musical search with alef variants and vowel marks on real documents', async () => {
const created = await request(app.getHttpServer()).post('/api/v1/posts')
.set('Authorization', `Bearer ${token}`).field('content', `أُغنية عُود ${stamp}`).expect(201);
const response = await request(app.getHttpServer()).get('/api/v1/search/posts')
.set('Authorization', `Bearer ${token}`).query({ q: `اغنية عود ${stamp}` }).expect(200);
expect(response.body.items.map((post: any) => String(post._id))).toContain(String(created.body._id));
});
});