This commit is contained in:
Meghdad committed 2026-07-14 12:51:36 +03:30
commit f035fcef4f
134 files changed
+18678

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
{
"name": "@easy-stream/worker",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p ../../packages/contracts/tsconfig.json && tsc -p ../../packages/media/tsconfig.json && tsc -p ../../packages/database/tsconfig.json && tsc -p tsconfig.json --noEmit",
"test": "tsc -p ../../packages/contracts/tsconfig.json && tsc -p ../../packages/media/tsconfig.json && tsc -p ../../packages/database/tsconfig.json && vitest run",
"dev": "tsx watch src/cli.ts work",
"scan": "tsx src/cli.ts scan",
"package": "tsx src/cli.ts package",
"prepare:media": "tsx src/cli.ts prepare",
"work": "tsx src/cli.ts work",
"clean": "rm -rf dist"
},
"dependencies": {
"@easy-stream/contracts": "workspace:*",
"@easy-stream/database": "workspace:*",
"@easy-stream/media": "workspace:*",
"@sinclair/typebox": "^0.34.41",
"bullmq": "^5.61.2",
"ioredis": "^5.10.1"
},
"devDependencies": {
"@types/node": "^24.10.0",
"tsx": "^4.20.6",
"typescript": "^5.9.3",
"vitest": "^3.2.4"
}
}
+52
View File
@@ -0,0 +1,52 @@
import path from 'node:path';
import { evictCache, pruneOrphanedFonts, type EvictionResult } from '@easy-stream/media';
import { removeGenerationsFromRegistry } from './registry.js';
export interface CacheSweepOptions {
cacheRoot: string;
registryPath: string;
capacityBytes: number;
highWatermark: number;
lowWatermark: number;
playbackTtlMs: number;
protectedKeys?: ReadonlySet<string>;
fontOrphanMinimumAgeMs?: number;
now?: Date;
}
export interface CacheSweepResult extends EvictionResult {
registryEntriesRemoved: string[];
orphanFontsRemoved: string[];
}
/** Sweeps only disposable cache generations. Durable derived media is deliberately out of scope. */
export async function sweepCache(options: CacheSweepOptions): Promise<CacheSweepResult> {
const now = options.now ?? new Date();
const fontOptions = {
minimumAgeMs: options.fontOrphanMinimumAgeMs ?? 60 * 60 * 1000,
now,
};
const beforeFonts = await pruneOrphanedFonts(options.cacheRoot, fontOptions);
const eviction = await evictCache(path.join(options.cacheRoot, 'generations'), {
capacityBytes: options.capacityBytes,
highWatermark: options.highWatermark,
lowWatermark: options.lowWatermark,
...(options.protectedKeys === undefined ? {} : { protectedKeys: options.protectedKeys }),
overheadBytes: beforeFonts.retainedBytes,
minimumRetentionMs: options.playbackTtlMs,
now,
});
const registryEntriesRemoved = await removeGenerationsFromRegistry(
options.registryPath,
new Set(eviction.evicted),
);
const afterFonts = eviction.evicted.length === 0
? { removed: [] as string[], retainedBytes: beforeFonts.retainedBytes }
: await pruneOrphanedFonts(options.cacheRoot, fontOptions);
return {
...eviction,
afterBytes: Math.max(0, eviction.afterBytes - beforeFonts.retainedBytes + afterFonts.retainedBytes),
registryEntriesRemoved,
orphanFontsRemoved: [...beforeFonts.removed, ...afterFonts.removed],
};
}
+339
View File
@@ -0,0 +1,339 @@
import { createHash } from 'node:crypto';
import path from 'node:path';
import {
assDialogueText,
classifyMedia,
fingerprintSource,
normalizeStreamLanguage,
normalizeTracks,
probeMedia,
readSubtitleAsAss,
walkArchive,
type Classification,
type NormalizedTrack,
type ProbeStream,
type SourceFingerprint,
} from '@easy-stream/media';
export type CatalogKind = 'MOVIE' | 'SERIES';
export interface ParsedMediaIdentity {
kind: CatalogKind;
title: string;
seasonNumber?: number;
episodeNumber?: number;
episodeTitle?: string;
}
export interface SnapshotSubtitle {
id: string;
streamIndex: number;
codec: string;
sourceLanguage: string;
language: string;
label: string;
sourceDefault: boolean;
sourceForced: boolean;
default: boolean;
forced: false;
}
export interface SnapshotMediaItem {
id: string;
titleId: string;
kind: 'MOVIE' | 'EPISODE';
sourcePath: string;
durationSeconds: number;
seasonNumber?: number;
episodeNumber?: number;
title: { en: string; fa?: string };
published: boolean;
compatibility: Classification['class'];
compatibilityReasons: string[];
fingerprint: SourceFingerprint;
streams: NormalizedTrack[];
subtitles: SnapshotSubtitle[];
}
export interface SnapshotSeason {
number: number;
title: { en: string };
episodes: SnapshotMediaItem[];
}
export interface SnapshotTitle {
id: string;
slug: string;
kind: CatalogKind;
title: { en: string; fa?: string };
published: boolean;
playable: boolean;
mediaItemId: string;
resumeMediaItemId: string;
runtimeSeconds?: number;
seasonCount?: number;
episodeCount?: number;
seasons: SnapshotSeason[];
mediaItems: SnapshotMediaItem[];
}
export interface InventorySnapshot {
version: 1;
generatedAt: string;
archiveRoot: string;
items: SnapshotTitle[];
}
export interface PublicMediaItem {
id: string;
kind: 'MOVIE' | 'EPISODE';
seasonNumber?: number;
episodeNumber?: number;
name?: { fa?: string; en?: string };
durationSeconds: number;
compatibility: Classification['class'];
published: boolean;
}
export interface PublicTitleDetail {
id: string;
slug: string;
kind: CatalogKind;
name: { fa: string; en?: string };
playable: boolean;
resumeMediaItemId?: string;
synopsis: { fa?: string; en?: string };
seasons?: Array<{ number: number; episodeCount: number }>;
mediaItems: PublicMediaItem[];
updatedAt: string;
}
export interface CatalogSnapshot {
version: 1;
generatedAt: string;
titles: PublicTitleDetail[];
}
export interface ScanArchiveResult {
catalog: CatalogSnapshot;
inventory: InventorySnapshot;
}
export function deterministicUuid(value: string): string {
const bytes = createHash('sha256').update(value).digest().subarray(0, 16);
bytes[6] = (bytes[6] ?? 0) & 0x0f | 0x50;
bytes[8] = (bytes[8] ?? 0) & 0x3f | 0x80;
const hex = bytes.toString('hex');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
function cleanName(value: string): string {
return value
.replace(/\[[^\]]*\]/gu, ' ')
.replace(/[._]+/gu, ' ')
.replace(/\s+/gu, ' ')
.trim();
}
export function slugify(value: string): string {
return value.normalize('NFKD').toLocaleLowerCase('en-US')
.replace(/\p{Mark}+/gu, '')
.replace(/[^\p{Letter}\p{Number}]+/gu, '-')
.replace(/^-+|-+$/gu, '')
.slice(0, 180) || deterministicUuid(value);
}
export function parseMediaIdentity(relativePath: string): ParsedMediaIdentity {
const extension = path.extname(relativePath);
const filename = path.basename(relativePath, extension);
const parent = path.basename(path.dirname(relativePath));
const combined = filename.match(/\bS(?:eason)?\s*(\d{1,3})\s*E(?:p(?:isode)?)?\s*(\d{1,4})\b/iu);
const parentSeason = parent.match(/^(.*?)(?:[\s._-]+S(?:eason)?\s*(\d{1,3}))$/iu);
const episode = combined?.[2]
?? filename.match(/(?:-|–)\s*(\d{1,4})(?=(?:[.\s_\[]|$))/u)?.[1]
?? filename.match(/\bE(?:p(?:isode)?)?\s*(\d{1,4})\b/iu)?.[1];
if (episode !== undefined) {
const season = Number(combined?.[1] ?? parentSeason?.[2] ?? 1);
const title = cleanName(parentSeason?.[1] ?? parent);
return {
kind: 'SERIES',
title: title || cleanName(filename),
seasonNumber: season,
episodeNumber: Number(episode),
episodeTitle: `Episode ${Number(episode)}`,
};
}
return { kind: 'MOVIE', title: cleanName(filename) };
}
export interface ScanArchiveOptions {
archiveRoot: string;
ffmpegPath?: string;
ffprobePath?: string;
onFile?: (relativePath: string, current: number) => void;
}
const TEXT_SUBTITLE_CODECS = new Set(['ass', 'ssa', 'subrip', 'srt', 'webvtt', 'mov_text']);
export function shouldInspectSubtitleContent(stream: ProbeStream): boolean {
return stream.codec_type === 'subtitle'
&& TEXT_SUBTITLE_CODECS.has(stream.codec_name ?? '')
&& normalizeStreamLanguage(stream) === 'und';
}
async function inspectFile(
sourcePath: string,
archiveRoot: string,
options: ScanArchiveOptions,
): Promise<{ identity: ParsedMediaIdentity; media: SnapshotMediaItem }> {
const relativePath = path.relative(archiveRoot, sourcePath).split(path.sep).join('/');
const identity = parseMediaIdentity(relativePath);
const [probe, fingerprint] = await Promise.all([
probeMedia(sourcePath, options.ffprobePath === undefined ? {} : { ffprobePath: options.ffprobePath }),
fingerprintSource(archiveRoot, sourcePath),
]);
const compatibility = classifyMedia(probe);
const titleId = deterministicUuid(`title:${identity.kind}:${identity.title.toLocaleLowerCase('en-US')}`);
const mediaId = deterministicUuid(`media:${relativePath}`);
const tracks = normalizeTracks(probe);
const subtitles: SnapshotSubtitle[] = [];
for (const stream of probe.streams.filter((candidate) => candidate.codec_type === 'subtitle')) {
let content: string | undefined;
const declaredLanguage = normalizeStreamLanguage(stream);
if (shouldInspectSubtitleContent(stream)) {
try {
content = await readSubtitleAsAss(sourcePath, stream.index, {
archiveRoot,
maxDurationSeconds: 10 * 60,
...(options.ffmpegPath === undefined ? {} : { ffmpegPath: options.ffmpegPath }),
});
} catch {
// Preserve the track as undetermined; packaging will report extraction failures.
}
}
const language = content === undefined
? declaredLanguage
: normalizeStreamLanguage(stream, assDialogueText(content));
const track = tracks.find((candidate) => candidate.index === stream.index);
if (track !== undefined) {
track.language = language;
track.default = language === 'fa';
track.forced = false;
}
subtitles.push({
id: deterministicUuid(`subtitle:${relativePath}:${stream.index}`),
streamIndex: stream.index,
codec: stream.codec_name ?? 'unknown',
sourceLanguage: stream.tags?.language ?? 'und',
language,
label: stream.tags?.title ?? language,
sourceDefault: stream.disposition?.default === 1,
sourceForced: stream.disposition?.forced === 1,
default: language === 'fa',
forced: false,
});
}
const duration = Number(probe.format.duration);
const published = ['COPY', 'AUDIO_TRANSCODE'].includes(compatibility.class);
return {
identity,
media: {
id: mediaId,
titleId,
kind: identity.kind === 'SERIES' ? 'EPISODE' : 'MOVIE',
sourcePath: relativePath,
durationSeconds: Number.isFinite(duration) ? duration : 0,
...(identity.seasonNumber === undefined ? {} : { seasonNumber: identity.seasonNumber }),
...(identity.episodeNumber === undefined ? {} : { episodeNumber: identity.episodeNumber }),
title: { en: identity.episodeTitle ?? identity.title },
published,
compatibility: compatibility.class,
compatibilityReasons: compatibility.reasons,
fingerprint,
streams: tracks,
subtitles,
},
};
}
export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArchiveResult> {
const root = path.resolve(options.archiveRoot);
const grouped = new Map<string, { identity: ParsedMediaIdentity; media: SnapshotMediaItem[] }>();
let current = 0;
for await (const sourcePath of walkArchive(root)) {
current += 1;
const relative = path.relative(root, sourcePath).split(path.sep).join('/');
options.onFile?.(relative, current);
const inspected = await inspectFile(sourcePath, root, options);
const key = `${inspected.identity.kind}:${inspected.identity.title.toLocaleLowerCase('en-US')}`;
const group = grouped.get(key) ?? { identity: inspected.identity, media: [] };
group.media.push(inspected.media);
grouped.set(key, group);
}
const items: SnapshotTitle[] = [...grouped.values()].map(({ identity, media }) => {
media.sort((left, right) => (left.seasonNumber ?? 0) - (right.seasonNumber ?? 0)
|| (left.episodeNumber ?? 0) - (right.episodeNumber ?? 0));
const first = media[0];
if (first === undefined) throw new Error('Internal catalog group is empty');
const seasonsByNumber = new Map<number, SnapshotMediaItem[]>();
for (const item of media) {
if (item.kind !== 'EPISODE') continue;
const season = item.seasonNumber ?? 1;
const episodes = seasonsByNumber.get(season) ?? [];
episodes.push(item);
seasonsByNumber.set(season, episodes);
}
const seasons = [...seasonsByNumber.entries()].sort(([left], [right]) => left - right)
.map(([number, episodes]) => ({ number, title: { en: `Season ${number}` }, episodes }));
const published = media.some((item) => item.published);
return {
id: first.titleId,
slug: slugify(identity.title),
kind: identity.kind,
title: { en: identity.title },
published,
playable: published,
mediaItemId: first.id,
resumeMediaItemId: first.id,
...(identity.kind === 'MOVIE' ? { runtimeSeconds: first.durationSeconds } : {}),
...(identity.kind === 'SERIES' ? { seasonCount: seasons.length, episodeCount: media.length } : {}),
seasons,
mediaItems: media,
};
});
items.sort((left, right) => left.title.en.localeCompare(right.title.en));
const generatedAt = new Date().toISOString();
const titles: PublicTitleDetail[] = items.map((item) => ({
id: item.id,
slug: item.slug,
kind: item.kind,
// Filename-derived text is a safe temporary fallback until metadata matching supplies Persian.
name: { fa: item.title.fa ?? item.title.en, en: item.title.en },
playable: item.playable,
...(item.playable ? { resumeMediaItemId: item.resumeMediaItemId } : {}),
synopsis: {},
...(item.kind === 'SERIES'
? { seasons: item.seasons.map((season) => ({ number: season.number, episodeCount: season.episodes.length })) }
: {}),
mediaItems: item.mediaItems.map((media): PublicMediaItem => ({
id: media.id,
kind: media.kind,
...(media.seasonNumber === undefined ? {} : { seasonNumber: media.seasonNumber }),
...(media.episodeNumber === undefined ? {} : { episodeNumber: media.episodeNumber }),
name: { fa: media.title.fa ?? media.title.en, en: media.title.en },
durationSeconds: media.durationSeconds,
compatibility: media.compatibility,
published: media.published,
})),
updatedAt: generatedAt,
}));
return {
catalog: { version: 1, generatedAt, titles },
inventory: { version: 1, generatedAt, archiveRoot: root, items },
};
}
export function findMediaItem(snapshot: InventorySnapshot, idOrPath: string): SnapshotMediaItem | undefined {
return snapshot.items.flatMap((item) => item.mediaItems)
.find((media) => media.id === idOrPath || media.sourcePath === idOrPath);
}
+567
View File
@@ -0,0 +1,567 @@
#!/usr/bin/env node
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import path from 'node:path';
import {
createDatabase,
markArchiveScanFailed,
markArchiveScanRunning,
markArchiveScanSucceeded,
syncCatalogSnapshot,
type Database,
} from '@easy-stream/database';
import {
classifyMedia,
extractAndStoreFonts,
extractSubtitleVariants,
evictCacheGeneration,
fingerprintSource,
isPathInside,
normalizeStreamLanguage,
packageProgressiveHls,
prepareCompatibilityHls,
probeMedia,
publishGenerationFonts,
pruneOrphanedFonts,
resolveInside,
touchCacheGeneration,
writeCacheMetadata,
} from '@easy-stream/media';
import {
deterministicUuid,
findMediaItem,
scanArchive,
type InventorySnapshot,
type SnapshotMediaItem,
} from './catalog.js';
import { sweepCache } from './cache-lifecycle.js';
import {
normalizeTrackLabel,
removeGenerationFromRegistry,
updateRegistry,
} from './registry.js';
for (const candidate of [process.env.ENV_FILE, '.env', '../../.env']) {
if (!candidate) continue;
try {
process.loadEnvFile?.(candidate);
break;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
}
interface Arguments {
command?: string;
flags: Map<string, string | true>;
}
interface CommandRuntime {
protectedCacheKeys?: () => Promise<ReadonlySet<string>>;
}
function parseArguments(argv: readonly string[]): Arguments {
const flags = new Map<string, string | true>();
let command: string | undefined;
for (let index = 0; index < argv.length; index += 1) {
const value = argv[index];
if (value === undefined || value === '--') continue;
if (!value.startsWith('--') && command === undefined) {
command = value;
continue;
}
if (!value.startsWith('--')) throw new Error(`Unexpected positional argument: ${value}`);
const equals = value.indexOf('=');
if (equals >= 0) {
flags.set(value.slice(2, equals), value.slice(equals + 1));
continue;
}
const next = argv[index + 1];
if (next !== undefined && !next.startsWith('--')) {
flags.set(value.slice(2), next);
index += 1;
} else {
flags.set(value.slice(2), true);
}
}
return { ...(command === undefined ? {} : { command }), flags };
}
function flag(arguments_: Arguments, name: string, fallback?: string): string | undefined {
const value = arguments_.flags.get(name);
if (value === true) throw new Error(`--${name} requires a value`);
return value ?? fallback;
}
async function writeJsonAtomic(destinationPath: string, value: unknown): Promise<void> {
const destination = path.resolve(destinationPath);
await mkdir(path.dirname(destination), { recursive: true, mode: 0o750 });
const temporary = `${destination}.${process.pid}.tmp`;
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o640 });
await rename(temporary, destination);
}
async function scanCommand(arguments_: Arguments): Promise<void> {
const archiveRoot = path.resolve(flag(arguments_, 'root', './movies') ?? './movies');
const output = flag(arguments_, 'output');
const inventoryOutput = flag(arguments_, 'inventory-output')
?? (output === undefined ? undefined : path.join(path.dirname(output), 'inventory.json'));
if ((output !== undefined && isPathInside(archiveRoot, path.resolve(output)))
|| (inventoryOutput !== undefined && isPathInside(archiveRoot, path.resolve(inventoryOutput)))) {
throw new Error('Catalog output must not be written into the read-only archive');
}
const result = await scanArchive({
archiveRoot,
...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }),
...(flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }),
onFile(relativePath, current) {
process.stderr.write(`[scan ${current}] ${relativePath}\n`);
},
});
if (output !== undefined) {
await Promise.all([
writeJsonAtomic(output, result.catalog),
...(inventoryOutput === undefined ? [] : [writeJsonAtomic(inventoryOutput, result.inventory)]),
]);
}
// Direct scans stay portable; the long-running worker passes DATABASE_URL explicitly.
const databaseUrl = flag(arguments_, 'database');
const databaseSync = databaseUrl === undefined
? undefined
: await withDatabase(databaseUrl, (database) => syncCatalogSnapshot(database, result.catalog));
if (output === undefined) process.stdout.write(`${JSON.stringify(result.catalog, null, 2)}\n`);
else {
process.stdout.write(`${JSON.stringify({
output: path.resolve(output),
...(inventoryOutput === undefined ? {} : { inventoryOutput: path.resolve(inventoryOutput) }),
titles: result.catalog.titles.length,
mediaItems: result.catalog.titles.reduce((sum, item) => sum + item.mediaItems.length, 0),
...(databaseSync === undefined ? {} : { databaseSync }),
})}\n`);
}
}
async function withDatabase<T>(
connectionString: string,
action: (database: Database) => Promise<T>,
): Promise<T> {
const connection = createDatabase(connectionString, { max: 2 });
try {
return await action(connection.db);
} finally {
await connection.close();
}
}
async function loadInventory(snapshotPath: string): Promise<InventorySnapshot> {
const value = JSON.parse(await readFile(snapshotPath, 'utf8')) as InventorySnapshot;
if (value.version !== 1 || !Array.isArray(value.items)) throw new Error('Unsupported catalog snapshot');
return value;
}
async function sourceSelection(
arguments_: Arguments,
archiveRoot: string,
): Promise<{ media: SnapshotMediaItem; sourcePath: string }> {
const mediaItem = flag(arguments_, 'media-item');
const requestedSource = flag(arguments_, 'source');
const inventoryPath = flag(arguments_, 'inventory', './data/inventory.json') ?? './data/inventory.json';
let inventory: InventorySnapshot | undefined;
try {
inventory = await loadInventory(inventoryPath);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || mediaItem !== undefined) throw error;
}
const selected = mediaItem === undefined
? (requestedSource === undefined ? undefined : inventory === undefined ? undefined : findMediaItem(inventory, requestedSource))
: inventory === undefined ? undefined : findMediaItem(inventory, mediaItem);
if (selected !== undefined) {
return { media: selected, sourcePath: await resolveInside(archiveRoot, path.join(archiveRoot, selected.sourcePath)) };
}
if (mediaItem !== undefined) throw new Error(`Media item was not found in ${inventoryPath}: ${mediaItem}`);
if (requestedSource === undefined) throw new Error('package requires --media-item ID or --source PATH');
const sourcePath = await resolveInside(
archiveRoot,
path.isAbsolute(requestedSource) ? requestedSource : path.join(archiveRoot, requestedSource),
);
const relative = path.relative(archiveRoot, sourcePath).split(path.sep).join('/');
const ffprobePath = flag(arguments_, 'ffprobe');
const probe = await probeMedia(sourcePath, ffprobePath === undefined ? {} : { ffprobePath });
const fingerprint = await fingerprintSource(archiveRoot, sourcePath);
const classification = classifyMedia(probe);
return {
sourcePath,
media: {
id: deterministicUuid(`media:${relative}`),
titleId: deterministicUuid(`title:${relative}`),
kind: 'MOVIE',
sourcePath: relative,
durationSeconds: Number(probe.format.duration) || 0,
title: { en: path.basename(relative, path.extname(relative)) },
published: ['COPY', 'AUDIO_TRANSCODE'].includes(classification.class),
compatibility: classification.class,
compatibilityReasons: classification.reasons,
fingerprint,
streams: [],
subtitles: [],
},
};
}
async function packageCommand(arguments_: Arguments, runtime: CommandRuntime): Promise<void> {
const archiveRoot = path.resolve(flag(arguments_, 'root', './movies') ?? './movies');
const cacheRoot = path.resolve(flag(arguments_, 'cache', './data/media-cache') ?? './data/media-cache');
const registryPath = path.resolve(flag(arguments_, 'registry', './data/package-registry.json') ?? './data/package-registry.json');
if (isPathInside(archiveRoot, cacheRoot) || isPathInside(archiveRoot, registryPath)) {
throw new Error('Cache and registry must be outside the read-only archive');
}
const selected = await sourceSelection(arguments_, archiveRoot);
const [probe, fingerprint] = await Promise.all([
probeMedia(selected.sourcePath, flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }),
fingerprintSource(archiveRoot, selected.sourcePath),
]);
const classification = classifyMedia(probe);
if (!['COPY', 'AUDIO_TRANSCODE'].includes(classification.class)) {
throw new Error(`Media requires offline preparation (${classification.class}): ${classification.reasons.join(', ')}`);
}
const generationId = deterministicUuid(`generation:cmaf-v1:${fingerprint.digest}`);
const generationPath = `generations/${generationId}`;
const ffmpegPath = flag(arguments_, 'ffmpeg');
const ffprobePath = flag(arguments_, 'ffprobe');
const preparing = async (error?: string): Promise<void> => {
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
generationId,
state: error === undefined ? 'PREPARING' : 'FAILED',
playable: false,
...(error === undefined ? { pollAfterMs: 1000 } : { reasonCode: 'PACKAGE_FAILED' }),
durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds,
});
};
type Assets = {
subtitles: Awaited<ReturnType<typeof extractSubtitleVariants>>;
fonts: Awaited<ReturnType<typeof extractAndStoreFonts>>;
};
let assetError: unknown;
let assetsPromise: Promise<Assets | undefined> | undefined;
const startAssets = (): void => {
if (assetsPromise !== undefined) return;
assetsPromise = Promise.all([
extractSubtitleVariants(selected.sourcePath, probe, {
archiveRoot,
outputRoot: cacheRoot,
generation: generationPath,
...(ffmpegPath === undefined ? {} : { ffmpegPath }),
}),
extractAndStoreFonts(selected.sourcePath, probe, {
archiveRoot,
fontRoot: path.join(cacheRoot, 'assets', 'fonts'),
...(ffmpegPath === undefined ? {} : { ffmpegPath }),
...(flag(arguments_, 'font-sanitizer') === undefined ? {} : { sanitizerPath: flag(arguments_, 'font-sanitizer') as string }),
}),
]).then(async ([subtitles, storedFonts]) => ({
subtitles,
fonts: await publishGenerationFonts(storedFonts, cacheRoot, path.join(cacheRoot, generationPath)),
})).catch((error: unknown) => {
assetError = error;
return undefined;
});
};
let result: Awaited<ReturnType<typeof packageProgressiveHls>>;
try {
result = await packageProgressiveHls({
archiveRoot,
cacheRoot,
sourcePath: selected.sourcePath,
fingerprint,
probe,
classification,
generation: generationId,
...(ffmpegPath === undefined ? {} : { ffmpegPath }),
...(ffprobePath === undefined ? {} : { ffprobePath }),
async onProgress(progress) {
startAssets();
await preparing(progress.state === 'FAILED'
? progress.error ?? 'Unknown packaging error'
: undefined);
},
});
} catch (error) {
await assetsPromise;
await preparing(error instanceof Error ? error.message : String(error));
throw error;
}
startAssets();
const assets = await assetsPromise;
if (assetError !== undefined || assets === undefined) {
const error = assetError instanceof Error ? assetError : new Error(String(assetError ?? 'Asset preparation failed'));
await preparing(error.message);
throw error;
}
const { subtitles, fonts } = assets;
const audioStreams = probe.streams.filter((stream) => stream.codec_type === 'audio');
const fontUrls = fonts.map((font) => `/media/${generationPath}/fonts/${font.sha256}.${font.format}`);
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
generationId,
state: 'READY',
playable: true,
manifestPath: `/media/${generationPath}/master.m3u8`,
durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds,
audioTracks: audioStreams.map((stream, index) => ({
id: deterministicUuid(`audio:${selected.media.id}:${stream.index}`),
language: normalizeStreamLanguage(stream),
label: normalizeTrackLabel(stream.tags?.title, normalizeStreamLanguage(stream)),
default: index === 0,
})),
subtitleTracks: subtitles.map((subtitle) => ({
id: deterministicUuid(`subtitle:${selected.media.id}:${subtitle.streamIndex}`),
language: subtitle.language,
label: subtitle.language,
default: subtitle.default,
forced: subtitle.forced,
assUrl: `/media/${path.relative(cacheRoot, subtitle.assPath).split(path.sep).join('/')}`,
vttUrl: `/media/${path.relative(cacheRoot, subtitle.vttPath).split(path.sep).join('/')}`,
fontUrls,
})),
});
await writeCacheMetadata(path.join(cacheRoot, 'generations'), path.join(cacheRoot, generationPath), {
key: generationId,
lastAccessedAt: new Date().toISOString(),
active: false,
building: false,
pinned: false,
});
const protectedKeys = await runtime.protectedCacheKeys?.();
const cacheSweep = await sweepCache({
cacheRoot,
registryPath,
capacityBytes: numericFlag(arguments_, 'cache-max-bytes', process.env.CACHE_MAX_BYTES, 2_147_483_648_000),
highWatermark: numericFlag(arguments_, 'cache-high-watermark', process.env.CACHE_HIGH_WATERMARK, 0.85),
lowWatermark: numericFlag(arguments_, 'cache-low-watermark', process.env.CACHE_LOW_WATERMARK, 0.75),
playbackTtlMs: numericFlag(arguments_, 'playback-ttl-seconds', process.env.PLAYBACK_TTL_SECONDS, 4 * 60 * 60) * 1000,
...(protectedKeys === undefined ? {} : { protectedKeys }),
});
process.stdout.write(`${JSON.stringify({ mediaItemId: selected.media.id, generationId, manifestPath: `/media/${generationPath}/master.m3u8`, knownAacRepairs: result.knownAacRepairs, subtitles: subtitles.length, fonts: fonts.length, cacheSweep })}\n`);
}
function numericFlag(
arguments_: Arguments,
name: string,
environmentValue: string | undefined,
fallback: number,
): number {
const value = flag(arguments_, name, environmentValue);
const number = value === undefined ? fallback : Number(value);
if (!Number.isFinite(number)) throw new Error(`--${name} must be a finite number`);
return number;
}
async function prepareCommand(arguments_: Arguments): Promise<void> {
const archiveRoot = path.resolve(flag(arguments_, 'root', './movies') ?? './movies');
const derivedRoot = path.resolve(flag(arguments_, 'derived', process.env.DERIVED_ROOT ?? './data/media-derived') ?? './data/media-derived');
const registryPath = path.resolve(flag(arguments_, 'registry', './data/package-registry.json') ?? './data/package-registry.json');
if (isPathInside(archiveRoot, derivedRoot) || isPathInside(archiveRoot, registryPath)) {
throw new Error('Derived output and registry must be outside the read-only archive');
}
const selected = await sourceSelection(arguments_, archiveRoot);
const [probe, fingerprint] = await Promise.all([
probeMedia(selected.sourcePath, flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }),
fingerprintSource(archiveRoot, selected.sourcePath),
]);
const classification = classifyMedia(probe);
if (classification.class === 'HOLD_HDR') throw new Error('HDR_UNSUPPORTED_V1');
if (classification.class !== 'VIDEO_TRANSCODE') {
throw new Error(`Offline video compatibility encoding is not applicable to ${classification.class}`);
}
const generationId = deterministicUuid(`generation:compat-h264-v1:${fingerprint.digest}`);
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
generationId,
state: 'PREPARING',
playable: false,
pollAfterMs: 5000,
durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds,
});
try {
const result = await prepareCompatibilityHls({
archiveRoot,
derivedRoot,
sourcePath: selected.sourcePath,
fingerprint,
probe,
classification,
generation: generationId,
...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }),
...(flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }),
});
const generationPath = `generations/${generationId}`;
const [subtitles, storedFonts] = await Promise.all([
extractSubtitleVariants(selected.sourcePath, probe, {
archiveRoot,
outputRoot: derivedRoot,
generation: generationPath,
...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }),
}),
extractAndStoreFonts(selected.sourcePath, probe, {
archiveRoot,
fontRoot: path.join(derivedRoot, 'assets', 'fonts'),
...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }),
...(flag(arguments_, 'font-sanitizer') === undefined ? {} : { sanitizerPath: flag(arguments_, 'font-sanitizer') as string }),
}),
]);
const fonts = await publishGenerationFonts(storedFonts, derivedRoot, path.join(derivedRoot, generationPath));
const fontUrls = fonts.map((font) => `/media/derived/${generationPath}/fonts/${font.sha256}.${font.format}`);
const audioStreams = probe.streams.filter((stream) => stream.codec_type === 'audio');
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
generationId,
state: 'READY',
playable: true,
manifestPath: `/media/derived/${generationPath}/master.m3u8`,
durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds,
audioTracks: audioStreams.map((stream, index) => ({
id: deterministicUuid(`audio:${selected.media.id}:${stream.index}`),
language: normalizeStreamLanguage(stream),
label: normalizeTrackLabel(stream.tags?.title, normalizeStreamLanguage(stream)),
default: index === 0,
})),
subtitleTracks: subtitles.map((subtitle) => ({
id: deterministicUuid(`subtitle:${selected.media.id}:${subtitle.streamIndex}`),
language: subtitle.language,
label: subtitle.language,
default: subtitle.default,
forced: subtitle.forced,
assUrl: `/media/derived/${path.relative(derivedRoot, subtitle.assPath).split(path.sep).join('/')}`,
vttUrl: `/media/derived/${path.relative(derivedRoot, subtitle.vttPath).split(path.sep).join('/')}`,
fontUrls,
})),
});
process.stdout.write(`${JSON.stringify({ mediaItemId: selected.media.id, generationId, manifestPath: `/media/derived/${generationPath}/master.m3u8`, knownAacRepairs: result.knownAacRepairs })}\n`);
} catch (error) {
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
generationId,
state: 'FAILED',
playable: false,
reasonCode: 'COMPATIBILITY_ENCODE_FAILED',
durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds,
});
throw error;
}
}
async function workCommand(arguments_: Arguments): Promise<void> {
const redisUrl = flag(arguments_, 'redis', process.env.REDIS_URL);
if (redisUrl === undefined) throw new Error('REDIS_URL or --redis is required');
const archiveRoot = flag(arguments_, 'root', process.env.ARCHIVE_ROOT ?? './movies') ?? './movies';
const cacheRoot = flag(arguments_, 'cache', process.env.MEDIA_CACHE_ROOT ?? process.env.CACHE_ROOT ?? './data/media-cache') ?? './data/media-cache';
const catalog = flag(arguments_, 'catalog', process.env.CATALOG_SNAPSHOT_PATH ?? './data/catalog.json') ?? './data/catalog.json';
const inventory = flag(arguments_, 'inventory', process.env.MEDIA_INVENTORY_PATH ?? process.env.INVENTORY_SNAPSHOT_PATH ?? './data/inventory.json') ?? './data/inventory.json';
const registry = flag(arguments_, 'registry', process.env.PACKAGE_REGISTRY_PATH ?? './data/package-registry.json') ?? './data/package-registry.json';
const configuredDatabaseUrl = flag(arguments_, 'database', process.env.DATABASE_URL);
const databaseUrl = configuredDatabaseUrl?.trim() ? configuredDatabaseUrl : undefined;
const concurrency = Number(flag(
arguments_,
'concurrency',
process.env.MEDIA_WORKER_CONCURRENCY ?? process.env.JIT_REMUX_CONCURRENCY ?? '2',
));
const ffmpegPath = flag(arguments_, 'ffmpeg', process.env.FFMPEG_PATH);
const ffprobePath = flag(arguments_, 'ffprobe', process.env.FFPROBE_PATH);
const mediaTools = [
...(ffmpegPath === undefined ? [] : ['--ffmpeg', ffmpegPath]),
...(ffprobePath === undefined ? [] : ['--ffprobe', ffprobePath]),
];
const { startMediaQueueWorker } = await import('./work.js');
let running: ReturnType<typeof startMediaQueueWorker>;
running = startMediaQueueWorker({
redisUrl,
concurrency,
async dispatch(command) {
if (command.type === 'media.playback.requested') {
await main([
'package', '--root', archiveRoot, '--cache', cacheRoot, '--inventory', inventory,
'--registry', registry, '--media-item', command.mediaItemId, ...mediaTools,
], { protectedCacheKeys: () => running.protectedCacheGenerations() });
} else if (command.type === 'archive.scan.requested') {
if (databaseUrl !== undefined) {
const updated = await withDatabase(databaseUrl, (database) => markArchiveScanRunning(database, command.jobId));
if (!updated) throw new Error(`Archive scan job is missing or not runnable: ${command.jobId}`);
}
await main([
'scan', '--root', archiveRoot, '--output', catalog, '--inventory-output', inventory,
...(databaseUrl === undefined ? [] : ['--database', databaseUrl]),
...mediaTools,
]);
} else if (command.type === 'package.eviction.requested') {
if ((await running.protectedCacheGenerations()).has(command.generationId)) {
throw new Error(`Cache generation has an active playback lease: ${command.generationId}`);
}
const evicted = await evictCacheGeneration(cacheRoot, command.generationId);
if (evicted) {
await removeGenerationFromRegistry(registry, command.generationId);
await pruneOrphanedFonts(cacheRoot);
}
} else if (command.type === 'cache.generation.accessed') {
await running.recordCacheLease(command.generationId, command.protectedUntil);
await touchCacheGeneration(cacheRoot, command.generationId, {
accessedAt: command.accessedAt,
protectedUntil: command.protectedUntil,
});
} else if (command.type === 'media.publication.changed') {
// Publication state is owned by the API/database; no media mutation is necessary.
} else {
const exhaustive: never = command;
throw new Error(`Unsupported media command: ${String(exhaustive)}`);
}
},
async onCompleted(command) {
if (command.type !== 'archive.scan.requested' || databaseUrl === undefined) return;
const updated = await withDatabase(databaseUrl, (database) => markArchiveScanSucceeded(
database,
command.jobId,
{ catalogPath: path.resolve(catalog), inventoryPath: path.resolve(inventory) },
));
if (!updated) throw new Error(`Archive scan job did not remain RUNNING: ${command.jobId}`);
},
async onFailed(command, error, job) {
if (command?.type === 'archive.scan.requested' && databaseUrl !== undefined) {
try {
await withDatabase(databaseUrl, (database) => markArchiveScanFailed(database, command.jobId, error.message));
} catch (statusError) {
process.stderr.write(`${JSON.stringify({ level: 'error', queue: 'easy-stream-media', jobId: job?.id, command: command.type, error: 'Unable to persist failed job status', detail: statusError instanceof Error ? statusError.message : String(statusError) })}\n`);
}
}
process.stderr.write(`${JSON.stringify({ level: 'error', queue: 'easy-stream-media', jobId: job?.id, command: command?.type, error: error.message })}\n`);
},
});
process.stdout.write(`${JSON.stringify({ state: 'WORKING', queue: 'easy-stream-media', concurrency })}\n`);
await new Promise<void>((resolve) => {
process.once('SIGINT', resolve);
process.once('SIGTERM', resolve);
});
await running.close();
}
export async function main(
argv = process.argv.slice(2),
runtime: CommandRuntime = {},
): Promise<void> {
const arguments_ = parseArguments(argv);
if (arguments_.command === 'scan') await scanCommand(arguments_);
else if (arguments_.command === 'package') await packageCommand(arguments_, runtime);
else if (arguments_.command === 'prepare') await prepareCommand(arguments_);
else if (arguments_.command === 'work') await workCommand(arguments_);
else {
process.stderr.write('Usage:\n worker scan --root DIR [--output FILE] [--inventory-output FILE] [--database URL]\n worker package --root DIR --cache DIR (--media-item ID | --source FILE) [--inventory FILE] [--registry FILE]\n worker prepare --root DIR --derived DIR (--media-item ID | --source FILE) [--inventory FILE]\n worker work --redis URL [--database URL] [--concurrency N]\n');
process.exitCode = arguments_.command === undefined ? 0 : 2;
}
}
if (import.meta.url === new URL(process.argv[1] ?? '', 'file:').href) {
main().catch((error: unknown) => {
process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
process.exitCode = 1;
});
}
+16
View File
@@ -0,0 +1,16 @@
import { pathToFileURL } from 'node:url';
import { main } from './cli.js';
export * from './catalog.js';
export * from './registry.js';
export * from './cache-lifecycle.js';
export * from './work.js';
export { main } from './cli.js';
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
main().catch((error: unknown) => {
process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
process.exitCode = 1;
});
}
+155
View File
@@ -0,0 +1,155 @@
import { randomUUID } from 'node:crypto';
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { PackageRegistrySchema } from '@easy-stream/contracts';
import { Value } from '@sinclair/typebox/value';
const MAX_TRACK_LABEL_LENGTH = 100;
const UNSAFE_LABEL_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu;
/** Converts untrusted container metadata into a bounded, single-line UI label. */
export function normalizeTrackLabel(value: string | undefined, fallback: string): string {
const clean = (candidate: string | undefined): string => (candidate ?? '')
.normalize('NFKC')
.replace(UNSAFE_LABEL_CHARACTERS, ' ')
.replace(/\s+/gu, ' ')
.trim();
const label = clean(value) || clean(fallback) || 'und';
if (label.length <= MAX_TRACK_LABEL_LENGTH) return label;
// JSON Schema maxLength is enforced at this boundary. Avoid leaving a lone
// high surrogate when the UTF-16 limit cuts through an astral character.
let end = MAX_TRACK_LABEL_LENGTH;
const finalCodeUnit = label.charCodeAt(end - 1);
if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) end -= 1;
return label.slice(0, end).trimEnd();
}
export interface RegistryAudioTrack {
id: string;
language: string;
label: string;
default: boolean;
}
export interface RegistrySubtitleTrack {
id: string;
language: string;
label: string;
default: boolean;
forced: boolean;
assUrl?: string;
vttUrl?: string;
fontUrls: string[];
}
export interface RegistryGeneration {
mediaItemId: string;
state: 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED';
generationId?: string;
manifestPath?: string;
/** True once a progressive EVENT manifest has enough validated media. */
playable: boolean;
reasonCode?: string;
pollAfterMs?: number;
durationSeconds?: number;
audioTracks?: RegistryAudioTrack[];
subtitleTracks?: RegistrySubtitleTrack[];
}
export interface PackageRegistry {
version: 1;
updatedAt: string;
packages: RegistryGeneration[];
}
const writes = new Map<string, Promise<void>>();
export async function readRegistry(registryPath: string): Promise<PackageRegistry> {
try {
const value: unknown = JSON.parse(await readFile(registryPath, 'utf8'));
assertValidRegistry(value, `Invalid package registry at ${registryPath}`);
return value;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
return { version: 1, updatedAt: new Date(0).toISOString(), packages: [] };
}
}
export async function writeRegistry(registryPath: string, registry: PackageRegistry): Promise<void> {
assertValidRegistry(registry, `Refusing to publish invalid package registry at ${registryPath}`);
const destination = path.resolve(registryPath);
await mkdir(path.dirname(destination), { recursive: true, mode: 0o750 });
const temporary = `${destination}.${process.pid}.${randomUUID()}.tmp`;
await writeFile(temporary, `${JSON.stringify(registry, null, 2)}\n`, { mode: 0o640 });
await rename(temporary, destination);
}
function assertValidRegistry(value: unknown, message: string): asserts value is PackageRegistry {
if (Value.Check(PackageRegistrySchema, value)) return;
const detail = [...Value.Errors(PackageRegistrySchema, value)]
.slice(0, 8)
.map((error) => `${error.path || '/'} ${error.message}`)
.join('; ');
throw new Error(`${message}: ${detail}`);
}
export async function updateRegistry(
registryPath: string,
mediaItemId: string,
generation: RegistryGeneration,
): Promise<void> {
const key = path.resolve(registryPath);
const previous = writes.get(key) ?? Promise.resolve();
const current = previous.catch(() => undefined).then(async () => {
const registry = await readRegistry(key);
registry.updatedAt = new Date().toISOString();
const index = registry.packages.findIndex((entry) => entry.mediaItemId === mediaItemId);
if (index < 0) registry.packages.push(generation);
else {
const current = registry.packages[index];
// An idempotent package verification must never make an already served generation
// disappear or regress to PREPARING/FAILED.
if (current !== undefined && current.generationId === generation.generationId
&& current.state === 'READY' && generation.state !== 'READY') return;
registry.packages[index] = generation;
}
await writeRegistry(key, registry);
});
writes.set(key, current);
try {
await current;
} finally {
if (writes.get(key) === current) writes.delete(key);
}
}
export async function removeGenerationFromRegistry(registryPath: string, generationId: string): Promise<boolean> {
return (await removeGenerationsFromRegistry(registryPath, new Set([generationId]))).length > 0;
}
export async function removeGenerationsFromRegistry(
registryPath: string,
generationIds: ReadonlySet<string>,
): Promise<string[]> {
const key = path.resolve(registryPath);
const previous = writes.get(key) ?? Promise.resolve();
let removed: string[] = [];
const current = previous.catch(() => undefined).then(async () => {
const registry = await readRegistry(key);
removed = registry.packages
.flatMap((entry) => entry.generationId && generationIds.has(entry.generationId) ? [entry.generationId] : []);
if (removed.length === 0) return;
const packages = registry.packages.filter((entry) => entry.generationId === undefined || !generationIds.has(entry.generationId));
registry.packages = packages;
registry.updatedAt = new Date().toISOString();
await writeRegistry(key, registry);
});
writes.set(key, current);
try {
await current;
return removed;
} finally {
if (writes.get(key) === current) writes.delete(key);
}
}
+70
View File
@@ -0,0 +1,70 @@
import {
CACHE_GENERATION_LEASES_KEY,
MediaCommandSchema,
type MediaCommand,
} from '@easy-stream/contracts';
import { Value } from '@sinclair/typebox/value';
import { Worker, type Job } from 'bullmq';
import { Redis } from 'ioredis';
export const MEDIA_QUEUE_NAME = 'easy-stream-media';
export interface MediaQueueWorkerOptions {
redisUrl: string;
concurrency?: number;
dispatch: (command: MediaCommand, job: Job<MediaCommand>) => Promise<void>;
onCompleted?: (command: MediaCommand, job: Job<MediaCommand>) => Promise<void>;
onFailed?: (command: MediaCommand | undefined, error: Error, job: Job<MediaCommand> | undefined) => Promise<void>;
}
export interface RunningMediaWorker {
worker: Worker<MediaCommand>;
recordCacheLease(generationId: string, protectedUntil: string): Promise<void>;
protectedCacheGenerations(now?: Date): Promise<ReadonlySet<string>>;
close(): Promise<void>;
}
export function startMediaQueueWorker(options: MediaQueueWorkerOptions): RunningMediaWorker {
const concurrency = options.concurrency ?? 2;
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 32) {
throw new RangeError('Worker concurrency must be between 1 and 32');
}
const redisOptions = {
maxRetriesPerRequest: null,
enableReadyCheck: true,
} as const;
const connection = new Redis(options.redisUrl, redisOptions);
const leases = new Redis(options.redisUrl, redisOptions);
const worker = new Worker<MediaCommand>(
MEDIA_QUEUE_NAME,
async (job) => {
if (!Value.Check(MediaCommandSchema, job.data)) throw new Error(`Invalid media command in job ${job.id ?? 'unknown'}`);
await options.dispatch(job.data, job);
await options.onCompleted?.(job.data, job);
},
{ connection, concurrency },
);
worker.on('failed', (job, error) => {
void options.onFailed?.(job?.data, error, job);
});
worker.on('error', (error) => {
void options.onFailed?.(undefined, error, undefined);
});
return {
worker,
async recordCacheLease(generationId, protectedUntil) {
const expiration = Date.parse(protectedUntil);
if (!Number.isFinite(expiration)) throw new Error('Invalid cache lease expiration');
await leases.zadd(CACHE_GENERATION_LEASES_KEY, 'GT', expiration, generationId);
},
async protectedCacheGenerations(now = new Date()) {
const timestamp = now.getTime();
await leases.zremrangebyscore(CACHE_GENERATION_LEASES_KEY, '-inf', timestamp);
return new Set(await leases.zrangebyscore(CACHE_GENERATION_LEASES_KEY, timestamp + 1, '+inf'));
},
async close() {
await worker.close();
await Promise.all([connection.quit(), leases.quit()]);
},
};
}
+63
View File
@@ -0,0 +1,63 @@
import { mkdtemp, mkdir, stat, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { writeCacheMetadata } from '@easy-stream/media';
import { describe, expect, it } from 'vitest';
import { sweepCache } from '../src/cache-lifecycle.js';
import { readRegistry, updateRegistry } from '../src/registry.js';
describe('worker cache lifecycle', () => {
it('evicts to the low watermark, removes registry rows, and prunes font orphans', async () => {
const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-sweep-'));
const cacheRoot = path.join(base, 'cache');
const generations = path.join(cacheRoot, 'generations');
const registryPath = path.join(base, 'registry.json');
const oldGeneration = '11111111-1111-4111-8111-111111111111';
const protectedGeneration = '22222222-2222-4222-8222-222222222222';
for (const generation of [oldGeneration, protectedGeneration]) {
const directory = path.join(generations, generation);
await mkdir(directory, { recursive: true });
await writeFile(path.join(directory, 'segment.m4s'), Buffer.alloc(60));
await writeCacheMetadata(generations, directory, {
key: generation,
bytes: 60,
lastAccessedAt: '2020-01-01T00:00:00.000Z',
active: false,
building: false,
pinned: false,
});
await updateRegistry(registryPath, generation, {
mediaItemId: generation,
generationId: generation,
state: 'READY',
playable: true,
manifestPath: `/media/generations/${generation}/master.m3u8`,
});
}
const fontStore = path.join(cacheRoot, 'assets', 'fonts', 'sha256');
const orphanFont = path.join(fontStore, `${'a'.repeat(64)}.ttf`);
await mkdir(fontStore, { recursive: true });
await writeFile(orphanFont, Buffer.alloc(10));
const result = await sweepCache({
cacheRoot,
registryPath,
capacityBytes: 100,
highWatermark: 0.85,
lowWatermark: 0.75,
playbackTtlMs: 0,
protectedKeys: new Set([protectedGeneration]),
fontOrphanMinimumAgeMs: 0,
now: new Date('2999-01-01T00:00:00.000Z'),
});
expect(result.evicted).toEqual([oldGeneration]);
expect(result.registryEntriesRemoved).toEqual([oldGeneration]);
expect(result.orphanFontsRemoved).toEqual([path.basename(orphanFont)]);
expect((await readRegistry(registryPath)).packages).toEqual([
expect.objectContaining({ generationId: protectedGeneration }),
]);
await expect(stat(path.join(generations, oldGeneration))).rejects.toMatchObject({ code: 'ENOENT' });
await expect(stat(path.join(generations, protectedGeneration))).resolves.toBeDefined();
});
});
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest';
import { deterministicUuid, parseMediaIdentity, shouldInspectSubtitleContent, slugify } from '../src/catalog.js';
describe('catalog filename parsing', () => {
it('groups the supplied season folder and episode filename', () => {
expect(parseMediaIdentity('Mushoku Tensei S3/Mushoku Tensei S3 - 01.[SS][720p][MixFlixTop].mkv'))
.toEqual({ kind: 'SERIES', title: 'Mushoku Tensei', seasonNumber: 3, episodeNumber: 1, episodeTitle: 'Episode 1' });
});
it('creates stable UUIDs and Unicode-safe slugs', () => {
expect(deterministicUuid('same')).toBe(deterministicUuid('same'));
expect(deterministicUuid('same')).toMatch(/^[0-9a-f-]{36}$/u);
expect(slugify('فیلم نمونه')).toBe('فیلم-نمونه');
});
it('samples only unknown textual subtitle languages during archive scans', () => {
expect(shouldInspectSubtitleContent({ index: 2, codec_type: 'subtitle', codec_name: 'ass', tags: { language: 'qad' } })).toBe(true);
expect(shouldInspectSubtitleContent({ index: 3, codec_type: 'subtitle', codec_name: 'ass', tags: { language: 'und' } })).toBe(true);
expect(shouldInspectSubtitleContent({ index: 4, codec_type: 'subtitle', codec_name: 'ass', tags: { language: 'per' } })).toBe(false);
expect(shouldInspectSubtitleContent({ index: 5, codec_type: 'subtitle', codec_name: 'subrip', tags: { language: 'eng' } })).toBe(false);
expect(shouldInspectSubtitleContent({ index: 6, codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle' })).toBe(false);
});
});
+100
View File
@@ -0,0 +1,100 @@
import { mkdtemp, readFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { PackageRegistrySchema } from '@easy-stream/contracts';
import { Value } from '@sinclair/typebox/value';
import {
normalizeTrackLabel,
readRegistry,
removeGenerationFromRegistry,
updateRegistry,
} from '../src/registry.js';
describe('local generation registry', () => {
it('atomically records API-loadable per-media status', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-'));
const registryPath = path.join(directory, 'package-registry.json');
const mediaItemId = '11111111-1111-4111-8111-111111111111';
const generationId = '22222222-2222-4222-8222-222222222222';
await updateRegistry(registryPath, mediaItemId, {
mediaItemId, generationId, state: 'READY', playable: true,
manifestPath: `/media/generations/${generationId}/master.m3u8`,
});
const registry = await readRegistry(registryPath);
expect(registry.packages[0]).toMatchObject({ state: 'READY', playable: true });
expect(Value.Check(PackageRegistrySchema, registry)).toBe(true);
expect(JSON.parse(await readFile(registryPath, 'utf8'))).toMatchObject({ version: 1 });
await updateRegistry(registryPath, mediaItemId, {
mediaItemId, generationId, state: 'PREPARING', playable: false,
});
expect((await readRegistry(registryPath)).packages[0]).toMatchObject({
state: 'READY', playable: true, manifestPath: `/media/generations/${generationId}/master.m3u8`,
});
expect(await removeGenerationFromRegistry(registryPath, generationId)).toBe(true);
expect((await readRegistry(registryPath)).packages).toEqual([]);
});
it('normalizes oversized and control-character container labels for the API contract', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-label-'));
const registryPath = path.join(directory, 'package-registry.json');
const mediaItemId = '11111111-1111-4111-8111-111111111111';
const generationId = '22222222-2222-4222-8222-222222222222';
const rawMkvTitle = ` Persian\u0000\n\tAudio\u202e ${'x'.repeat(180)} `;
const label = normalizeTrackLabel(rawMkvTitle, 'fa');
expect(label.length).toBeLessThanOrEqual(100);
expect(label).toBe(`Persian Audio ${'x'.repeat(86)}`);
expect(label).not.toMatch(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u);
await updateRegistry(registryPath, mediaItemId, {
mediaItemId,
generationId,
state: 'READY',
playable: true,
manifestPath: `/media/generations/${generationId}/master.m3u8`,
audioTracks: [{
id: '33333333-3333-4333-8333-333333333333',
language: 'fa',
label,
default: true,
}],
});
const registry = await readRegistry(registryPath);
expect(Value.Check(PackageRegistrySchema, registry)).toBe(true);
expect(registry.packages[0]?.audioTracks?.[0]?.label).toBe(label);
});
it('rejects an invalid update before replacing a valid registry file', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-invalid-'));
const registryPath = path.join(directory, 'package-registry.json');
const mediaItemId = '11111111-1111-4111-8111-111111111111';
const generationId = '22222222-2222-4222-8222-222222222222';
await updateRegistry(registryPath, mediaItemId, {
mediaItemId,
generationId,
state: 'READY',
playable: true,
manifestPath: `/media/generations/${generationId}/master.m3u8`,
});
const before = await readFile(registryPath, 'utf8');
await expect(updateRegistry(registryPath, mediaItemId, {
mediaItemId,
generationId,
state: 'READY',
playable: true,
manifestPath: `/media/generations/${generationId}/master.m3u8`,
audioTracks: [{
id: '33333333-3333-4333-8333-333333333333',
language: 'en',
label: 'x'.repeat(101),
default: true,
}],
})).rejects.toThrow(/Refusing to publish invalid package registry/u);
expect(await readFile(registryPath, 'utf8')).toBe(before);
expect(Value.Check(PackageRegistrySchema, await readRegistry(registryPath))).toBe(true);
});
});
+13
View File
@@ -0,0 +1,13 @@
import { describe, expect, it } from 'vitest';
import { MEDIA_QUEUE_NAME, startMediaQueueWorker } from '../src/work.js';
describe('BullMQ media worker', () => {
it('uses the API queue name and rejects unsafe concurrency before connecting', () => {
expect(MEDIA_QUEUE_NAME).toBe('easy-stream-media');
expect(() => startMediaQueueWorker({
redisUrl: 'redis://127.0.0.1:1',
concurrency: 0,
async dispatch() {},
})).toThrow('concurrency');
});
});
+15
View File
@@ -0,0 +1,15 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"types": ["node"],
"paths": {
"@easy-stream/contracts": ["packages/contracts/dist/index.d.ts"],
"@easy-stream/database": ["packages/database/dist/index.d.ts"],
"@easy-stream/media": ["packages/media/dist/index.d.ts"]
}
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.test.ts"]
}