diff --git a/app/src/api.js b/app/src/api.js
index 2d57e456..a08959fa 100644
--- a/app/src/api.js
+++ b/app/src/api.js
@@ -236,6 +236,45 @@ export async function getVideo(fileGroupId) {
return [data['file_group'], data['prev'], data['next']];
}
+export async function transcodeVideo(fileGroupId, {video_codec = null, audio_codec = null, container = 'mp4'}) {
+ // Queues a transcode Job; returns the job id. Watch it with `getJob`.
+ const body = {video_codec, audio_codec, container};
+ const response = await apiPost(`${VIDEOS_API}/${fileGroupId}/transcode`, body);
+ if (!response.ok) {
+ const message = await getErrorMessage(response, 'Unable to queue the transcode. See server logs.');
+ toast({type: 'error', title: 'Failed to transcode', description: message, time: 5000});
+ throw new Error(message);
+ }
+ const data = await response.json();
+ return data['job_id'];
+}
+
+export async function getJobs() {
+ const response = await apiGet(`${API_URI}/jobs`);
+ const data = await response.json();
+ return data['jobs'];
+}
+
+export async function getJob(jobId) {
+ const response = await apiGet(`${API_URI}/jobs/${jobId}`);
+ if (!response.ok) {
+ throw new Error(await getErrorMessage(response, 'Unable to get the job'));
+ }
+ const data = await response.json();
+ return data['job'];
+}
+
+export async function cancelJob(jobId) {
+ const response = await apiDelete(`${API_URI}/jobs/${jobId}`);
+ if (!response.ok) {
+ const message = await getErrorMessage(response, 'Unable to cancel the job');
+ toast({type: 'error', title: 'Failed to cancel', description: message, time: 5000});
+ throw new Error(message);
+ }
+ const data = await response.json();
+ return data['job'];
+}
+
export async function getVideoComments(fileGroupId) {
const response = await apiGet(`${VIDEOS_API}/${fileGroupId}/comments`);
let data = await response.json();
diff --git a/app/src/components/ThemeSamplePage.js b/app/src/components/ThemeSamplePage.js
index 7767a317..824f9e7e 100644
--- a/app/src/components/ThemeSamplePage.js
+++ b/app/src/components/ThemeSamplePage.js
@@ -16,6 +16,7 @@ import {
IconStack,
MediaFilterToggle,
MediaGate,
+ Menu,
Message,
MultiSelect,
NumberInput,
@@ -382,6 +383,25 @@ export function ThemeSamplePage() {
)}
+
+ A dropdown of actions
+ {/* The video page's Edit button: one labelled button opens a menu of the
+ rarer actions, so the row stays short. The trailing chevron is what
+ says "menu" rather than "does the thing"; a disabled item stays listed
+ so the user learns it exists. */}
+
+
+
+
A row of actions
{/* `.wrolpi-button-row` is how a page lists the actions on a thing -- the
diff --git a/app/src/components/Vars.js b/app/src/components/Vars.js
index 02d293c3..60cac8b0 100644
--- a/app/src/components/Vars.js
+++ b/app/src/components/Vars.js
@@ -158,6 +158,24 @@ export const downloadAudioCodecOptions = [
{key: 'vorbis', text: 'vorbis', value: 'vorbis'},
];
+// Codecs WROLPi's ffmpeg step can produce. Mirrors TRANSCODE_VIDEO_TARGETS / TRANSCODE_AUDIO_TARGETS /
+// TRANSCODE_CONTAINERS in modules/videos/transcode.py; the API rejects anything else.
+export const TRANSCODE_COPY = 'copy';
+export const transcodeVideoCodecOptions = [
+ {value: TRANSCODE_COPY, label: 'Keep (copy)'},
+ {value: 'h264', label: 'h264 (avc1)'},
+];
+export const transcodeAudioCodecOptions = [
+ {value: TRANSCODE_COPY, label: 'Keep (copy)'},
+ {value: 'aac', label: 'aac'},
+ {value: 'opus', label: 'opus'},
+ {value: 'mp3', label: 'mp3'},
+];
+export const transcodeContainerOptions = [
+ {value: 'mp4', label: 'mp4'},
+ {value: 'mkv', label: 'mkv'},
+];
+
export const Downloaders = {
Archive: 'archive',
File: 'file',
diff --git a/app/src/components/VideoEditMenu.js b/app/src/components/VideoEditMenu.js
new file mode 100644
index 00000000..d84860a7
--- /dev/null
+++ b/app/src/components/VideoEditMenu.js
@@ -0,0 +1,323 @@
+import React, {useEffect, useRef, useState} from 'react';
+import {cancelJob, fetchVideoDownloadDefaults, getJob, transcodeVideo} from '../api';
+import {useWROLMode} from '../hooks/customHooks';
+import {Button, Group, Icon, Menu, Modal, Progress, Select, Stack, Status, Text, toast} from './ui';
+import {
+ TRANSCODE_COPY,
+ transcodeAudioCodecOptions,
+ transcodeContainerOptions,
+ transcodeVideoCodecOptions,
+} from './Vars';
+
+// How often the modal asks the API about the running Job.
+const JOB_POLL_MS = 2000;
+const FINISHED_STATUSES = ['complete', 'failed', 'cancelled'];
+// Embedded thumbnails are "video" streams to ffprobe, but not codecs a user chooses.
+const THUMBNAIL_CODECS = ['mjpeg', 'png', 'bmp', 'gif'];
+
+/** The codec names of a Video's real streams, from the `codec_names`/`codec_types` the API sends. */
+export function currentCodecs(video) {
+ const names = video?.codec_names || [];
+ const types = video?.codec_types || [];
+ const video_ = names.filter((name, i) => types[i] === 'video' && !THUMBNAIL_CODECS.includes(name));
+ const audio = names.filter((name, i) => types[i] === 'audio');
+ return {video: video_, audio};
+}
+
+/**
+ * The transcode target implied by the user's ordered codec preferences: the first preferred codec
+ * that ffmpeg can produce (the same rule the downloader uses). `copy` when none can be.
+ */
+export function preferredTarget(preferences, options) {
+ const producible = options.map(i => i.value).filter(i => i !== TRANSCODE_COPY);
+ for (const codec of preferences || []) {
+ if (producible.includes(codec)) {
+ return codec;
+ }
+ }
+ return TRANSCODE_COPY;
+}
+
+const statusKind = (status) => {
+ if (status === 'complete') return 'complete';
+ if (status === 'running') return 'active';
+ if (status === 'failed' || status === 'cancelled') return 'failed';
+ return 'pending';
+}
+
+/** Progress, status and log tail of one Job, polled until it finishes. */
+export function JobProgress({jobId, onFinished}) {
+ const [job, setJob] = useState(null);
+ const [cancelling, setCancelling] = useState(false);
+ const timer = useRef(null);
+ const finishedRef = useRef(false);
+
+ useEffect(() => {
+ finishedRef.current = false;
+ let cancelled = false;
+
+ const poll = async () => {
+ let latest;
+ try {
+ latest = await getJob(jobId);
+ } catch (e) {
+ console.error(e);
+ return;
+ }
+ if (cancelled) return;
+ setJob(latest);
+ if (FINISHED_STATUSES.includes(latest.status)) {
+ if (!finishedRef.current) {
+ finishedRef.current = true;
+ if (onFinished) onFinished(latest);
+ }
+ return;
+ }
+ timer.current = window.setTimeout(poll, JOB_POLL_MS);
+ };
+
+ poll();
+ return () => {
+ cancelled = true;
+ clearTimeout(timer.current);
+ };
+ // Only a new Job restarts polling; `onFinished` may be a fresh closure on every render.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [jobId]);
+
+ const handleCancel = async () => {
+ setCancelling(true);
+ try {
+ const latest = await cancelJob(jobId);
+ setJob(latest);
+ } catch (e) {
+ console.error(e);
+ } finally {
+ setCancelling(false);
+ }
+ };
+
+ if (!job) {
+ return ;
+ }
+
+ const finished = FINISHED_STATUSES.includes(job.status);
+ const percent = job.progress ?? 0;
+ const logTail = (job.log || []).slice(-8);
+
+ return
+
+ {job.status}
+ {!finished && }
+
+
+ {job.error && {job.error}}
+ {logTail.length > 0 &&
{logTail.join('\n')}
}
+
+}
+
+/**
+ * Choose target codecs for one Video, queue the transcode Job, then watch it.
+ *
+ * The selects start at the user's preferred codecs from the Videos settings (the same preference
+ * lists the downloader honors), so the common case is a glance and a click.
+ */
+export function TranscodeModal({open, onClose, fileGroupId, video, onComplete}) {
+ const wrolModeEnabled = useWROLMode();
+ const [videoCodec, setVideoCodec] = useState(TRANSCODE_COPY);
+ const [audioCodec, setAudioCodec] = useState(TRANSCODE_COPY);
+ const [container, setContainer] = useState('mp4');
+ const [defaultsLoaded, setDefaultsLoaded] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
+ const [jobId, setJobId] = useState(null);
+
+ const current = currentCodecs(video);
+
+ useEffect(() => {
+ if (!open) {
+ return;
+ }
+ // Each opening starts over: a finished Job's progress must not linger on the next open.
+ setJobId(null);
+ setDefaultsLoaded(false);
+ let stale = false;
+ const load = async () => {
+ try {
+ const defaults = await fetchVideoDownloadDefaults();
+ if (stale) return;
+ setVideoCodec(preferredTarget(defaults?.video_codecs, transcodeVideoCodecOptions));
+ setAudioCodec(preferredTarget(defaults?.audio_codecs, transcodeAudioCodecOptions));
+ } catch (e) {
+ console.error(e);
+ } finally {
+ if (!stale) setDefaultsLoaded(true);
+ }
+ };
+ load();
+ return () => {
+ stale = true;
+ };
+ }, [open]);
+
+ const nothingToDo = videoCodec === TRANSCODE_COPY && audioCodec === TRANSCODE_COPY;
+
+ const handleStart = async () => {
+ setSubmitting(true);
+ try {
+ const id = await transcodeVideo(fileGroupId, {
+ video_codec: videoCodec === TRANSCODE_COPY ? null : videoCodec,
+ audio_codec: audioCodec === TRANSCODE_COPY ? null : audioCodec,
+ container,
+ });
+ setJobId(id);
+ } catch (e) {
+ // transcodeVideo already toasted.
+ console.error(e);
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const handleFinished = (job) => {
+ if (job.status === 'complete') {
+ toast({type: 'success', title: 'Transcode complete', description: job.description, time: 5000});
+ if (onComplete) onComplete(job);
+ }
+ };
+
+ const describe = (codecs) => codecs.length ? codecs.join(', ') : 'unknown';
+
+ return
+ Transcode Video
+
+
+
+ Current codecs: video {describe(current.video)}, audio {describe(current.audio)}.
+ Streams set to Keep are copied without re-encoding. Transcoding is slow and slightly
+ reduces quality; the original file is replaced when it finishes.
+
+ {!jobId && <>
+
+
+
+
+ {!jobId && }
+
+
+}
+
+/**
+ * The "Edit" dropdown on the Video page: Refresh (re-download metadata) and Transcode.
+ *
+ * `onRefresh` is awaited; `onTranscodeComplete` is called after the file was replaced so the
+ * page can fetch the Video again (its path and codecs changed).
+ */
+export function VideoEditMenu({videoFile, video, onRefresh, onTranscodeComplete}) {
+ const wrolModeEnabled = useWROLMode();
+ const [transcodeOpen, setTranscodeOpen] = useState(false);
+ const [refreshing, setRefreshing] = useState(false);
+
+ const handleRefresh = async () => {
+ setRefreshing(true);
+ try {
+ await onRefresh();
+ } finally {
+ setRefreshing(false);
+ }
+ };
+
+ const isVideo = !!videoFile?.mimetype?.startsWith('video/');
+
+ return <>
+
+ setTranscodeOpen(false)}
+ fileGroupId={videoFile?.id}
+ video={video}
+ onComplete={onTranscodeComplete}
+ />
+ >
+}
diff --git a/app/src/components/VideoEditMenu.test.js b/app/src/components/VideoEditMenu.test.js
new file mode 100644
index 00000000..6f463b13
--- /dev/null
+++ b/app/src/components/VideoEditMenu.test.js
@@ -0,0 +1,194 @@
+import React from 'react';
+import {act, fireEvent, screen, waitFor} from '@testing-library/react';
+import {renderWithProviders} from '../test-utils';
+import {currentCodecs, JobProgress, preferredTarget, TranscodeModal, VideoEditMenu} from './VideoEditMenu';
+import {TRANSCODE_COPY, transcodeAudioCodecOptions, transcodeVideoCodecOptions} from './Vars';
+
+jest.mock('../api', () => ({
+ cancelJob: jest.fn(),
+ fetchVideoDownloadDefaults: jest.fn(),
+ getJob: jest.fn(),
+ transcodeVideo: jest.fn(),
+}));
+
+import {cancelJob, fetchVideoDownloadDefaults, getJob, transcodeVideo} from '../api';
+
+const video = {
+ codec_names: ['vp9', 'mjpeg', 'opus'],
+ codec_types: ['video', 'video', 'audio'],
+ video_path: 'videos/movie.webm',
+};
+const videoFile = {id: 7, url: 'https://example.com/watch?v=1', mimetype: 'video/webm', video};
+
+// Mantine's Select renders a hidden input next to the visible one, both tied to the label.
+const selectInput = (label) => screen.getAllByLabelText(label).find(i => i.type !== 'hidden');
+
+// `renderWithProviders`' `settings` option replaces the SettingsContext value; the WROL flag lives
+// one level down in its `settings`.
+const wrolMode = {settings: {settings: {wrol_mode: true}}};
+
+const pendingJob = {
+ id: 'transcode_video-abc', status: 'pending', progress: null, log: [], error: null, cancel_requested: false,
+ description: 'Transcode movie.webm',
+};
+
+describe('helpers', () => {
+ test('currentCodecs ignores embedded thumbnail streams', () => {
+ expect(currentCodecs(video)).toEqual({video: ['vp9'], audio: ['opus']});
+ expect(currentCodecs(null)).toEqual({video: [], audio: []});
+ });
+
+ test('preferredTarget picks the first preference ffmpeg can produce', () => {
+ expect(preferredTarget(['vp9', 'h264'], transcodeVideoCodecOptions)).toBe('h264');
+ expect(preferredTarget(['vp9', 'av1'], transcodeVideoCodecOptions)).toBe(TRANSCODE_COPY);
+ expect(preferredTarget(['opus', 'aac'], transcodeAudioCodecOptions)).toBe('opus');
+ expect(preferredTarget([], transcodeAudioCodecOptions)).toBe(TRANSCODE_COPY);
+ expect(preferredTarget(undefined, transcodeAudioCodecOptions)).toBe(TRANSCODE_COPY);
+ });
+});
+
+describe('TranscodeModal', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: ['h264'], audio_codecs: ['vorbis', 'aac']});
+ transcodeVideo.mockResolvedValue('transcode_video-abc');
+ getJob.mockResolvedValue(pendingJob);
+ });
+
+ test('pre-populates from the preferred codecs and queues the Job', async () => {
+ renderWithProviders();
+
+ expect(screen.getByText(/Current codecs: video vp9, audio opus/)).toBeInTheDocument();
+
+ // The defaults arrive: h264 is producible, vorbis is not, so aac is the audio target.
+ await waitFor(() => expect(selectInput('Video codec')).toHaveValue('h264 (avc1)'));
+ expect(selectInput('Audio codec')).toHaveValue('aac');
+ expect(selectInput('Container')).toHaveValue('mp4');
+
+ fireEvent.click(screen.getByRole('button', {name: /Transcode/}));
+
+ await waitFor(() => expect(transcodeVideo).toHaveBeenCalledWith(7, {
+ video_codec: 'h264', audio_codec: 'aac', container: 'mp4',
+ }));
+ // The form is replaced by the Job's progress.
+ await waitFor(() => expect(getJob).toHaveBeenCalledWith('transcode_video-abc'));
+ expect(screen.queryAllByLabelText('Video codec')).toHaveLength(0);
+ expect(await screen.findByText('pending')).toBeInTheDocument();
+ });
+
+ test('refuses to start when every stream is kept', async () => {
+ fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: [], audio_codecs: []});
+ renderWithProviders();
+
+ await waitFor(() => expect(screen.getByText('Choose at least one codec to convert.')).toBeInTheDocument());
+ expect(screen.getByRole('button', {name: /Transcode/})).toBeDisabled();
+ expect(transcodeVideo).not.toHaveBeenCalled();
+ });
+
+ test('WROL Mode disables starting a transcode', async () => {
+ renderWithProviders(
+ ,
+ wrolMode,
+ );
+ await waitFor(() => expect(selectInput('Video codec')).toHaveValue('h264 (avc1)'));
+ expect(screen.getByRole('button', {name: /Transcode/})).toBeDisabled();
+ });
+});
+
+describe('JobProgress', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ test('polls until the Job finishes, then reports once', async () => {
+ const onFinished = jest.fn();
+ getJob
+ .mockResolvedValueOnce({...pendingJob, status: 'running', progress: 40, log: ['out_time_us=1']})
+ .mockResolvedValueOnce({...pendingJob, status: 'complete', progress: 100, log: ['done']});
+
+ renderWithProviders();
+
+ await waitFor(() => expect(screen.getByText('running')).toBeInTheDocument());
+ expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '40');
+ expect(screen.getByTestId('job-log')).toHaveTextContent('out_time_us=1');
+ expect(screen.getByRole('button', {name: 'Cancel'})).toBeInTheDocument();
+
+ await act(async () => {
+ jest.advanceTimersByTime(2000);
+ });
+
+ await waitFor(() => expect(screen.getByText('complete')).toBeInTheDocument());
+ expect(onFinished).toHaveBeenCalledTimes(1);
+ expect(onFinished.mock.calls[0][0].status).toBe('complete');
+ // A finished Job is not polled again, and cannot be cancelled.
+ expect(getJob).toHaveBeenCalledTimes(2);
+ expect(screen.queryByRole('button', {name: 'Cancel'})).not.toBeInTheDocument();
+ });
+
+ test('Cancel asks the API to cancel the Job', async () => {
+ getJob.mockResolvedValue({...pendingJob, status: 'running', progress: 10});
+ cancelJob.mockResolvedValue({...pendingJob, status: 'running', progress: 10, cancel_requested: true});
+
+ renderWithProviders();
+
+ await waitFor(() => expect(screen.getByRole('button', {name: 'Cancel'})).toBeInTheDocument());
+ fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
+
+ await waitFor(() => expect(cancelJob).toHaveBeenCalledWith('transcode_video-abc'));
+ await waitFor(() => expect(screen.getByRole('button', {name: 'Cancelling...'})).toBeDisabled());
+ });
+
+ test('shows the error of a failed Job', async () => {
+ getJob.mockResolvedValue({...pendingJob, status: 'failed', error: 'ffmpeg exited with 1', log: ['boom']});
+
+ renderWithProviders();
+
+ await waitFor(() => expect(screen.getByText('failed')).toBeInTheDocument());
+ expect(screen.getByText('ffmpeg exited with 1')).toBeInTheDocument();
+ });
+});
+
+describe('VideoEditMenu', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: [], audio_codecs: []});
+ });
+
+ test('Refresh calls onRefresh; Transcode opens the modal', async () => {
+ const onRefresh = jest.fn().mockResolvedValue(undefined);
+ renderWithProviders();
+
+ fireEvent.click(screen.getByRole('button', {name: /Edit/}));
+ fireEvent.click(await screen.findByRole('menuitem', {name: /Refresh/}));
+ await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1));
+
+ fireEvent.click(screen.getByRole('button', {name: /Edit/}));
+ fireEvent.click(await screen.findByRole('menuitem', {name: /Transcode/}));
+ await waitFor(() => expect(screen.getByText('Transcode Video')).toBeInTheDocument());
+ });
+
+ test('Refresh is unavailable without a URL, Transcode for non-video files', async () => {
+ const audioFile = {...videoFile, url: null, mimetype: 'audio/mpeg'};
+ renderWithProviders();
+
+ fireEvent.click(screen.getByRole('button', {name: /Edit/}));
+ const refresh = await screen.findByRole('menuitem', {name: /Refresh/});
+ expect(refresh).toBeDisabled();
+ expect(screen.getByRole('menuitem', {name: /Transcode/})).toBeDisabled();
+ });
+
+ test('WROL Mode disables both items', async () => {
+ renderWithProviders(
+ ,
+ wrolMode,
+ );
+ fireEvent.click(screen.getByRole('button', {name: /Edit/}));
+ expect(await screen.findByRole('menuitem', {name: /Refresh/})).toBeDisabled();
+ expect(screen.getByRole('menuitem', {name: /Transcode/})).toBeDisabled();
+ });
+});
diff --git a/app/src/components/VideoPlayer.js b/app/src/components/VideoPlayer.js
index 5b643cb1..14c68f59 100644
--- a/app/src/components/VideoPlayer.js
+++ b/app/src/components/VideoPlayer.js
@@ -24,6 +24,7 @@ import {VideoCard} from "./Videos";
import {TagsSelector} from "../Tags";
import {AddToPlaylistButton} from "./AddToPlaylist";
import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal";
+import {VideoEditMenu} from "./VideoEditMenu";
import {IconPlayerPause, IconPlayerPlay} from "@tabler/icons-react";
const MEDIA_PATH = '/media';
@@ -495,12 +496,12 @@ function VideoPage({videoFile, prevFile, nextFile, fetchVideo, ...props}) {
onClick={async () => await handleDeleteVideo(videoFile.id)}
obeyWROLMode={true}
>Delete
- Refresh
+
diff --git a/modules/videos/schema.py b/modules/videos/schema.py
index 579a6337..0a8423c1 100644
--- a/modules/videos/schema.py
+++ b/modules/videos/schema.py
@@ -186,6 +186,18 @@ class VideoSearchRequest:
deep: bool = False # When True, search all text including captions (d_text)
+@dataclass
+class VideoTranscodeRequest:
+ video_codec: Optional[str] = None # A key of TRANSCODE_VIDEO_TARGETS, or None to copy the stream.
+ audio_codec: Optional[str] = None # A key of TRANSCODE_AUDIO_TARGETS, or None to copy the stream.
+ container: str = 'mp4'
+
+
+@dataclass
+class VideoTranscodeResponse:
+ job_id: str
+
+
@dataclass
class VideoSearchResponse:
videos: List[VideoWithChannel]
diff --git a/modules/videos/test/test_transcode_job.py b/modules/videos/test/test_transcode_job.py
new file mode 100644
index 00000000..8e1326e1
--- /dev/null
+++ b/modules/videos/test/test_transcode_job.py
@@ -0,0 +1,138 @@
+"""Tests for the transcode Job and its API (see `wrolpi.jobs`)."""
+import json
+import shutil
+from unittest import mock
+
+import pytest
+
+from modules.videos.models import Video
+from modules.videos.transcode import make_ffmpeg_progress_parser, transcode_video_job
+from wrolpi import jobs
+from wrolpi.cmd import CommandResult
+from wrolpi.files.models import FileGroup
+from wrolpi.vars import PROJECT_DIR
+
+
+def test_make_ffmpeg_progress_parser():
+ """`-progress pipe:1` lines are converted to whole-percent progress, reported only on change."""
+ reported = []
+ parse = make_ffmpeg_progress_parser(100.0, reported.append)
+ parse('frame=12') # Ignored.
+ parse('out_time_us=25000000')
+ parse('out_time_us=25400000') # Still 25%, not reported again.
+ parse('out_time_ms=50000000') # Older ffmpeg key, also microseconds.
+ parse('out_time_us=garbage')
+ parse('out_time_us=250000000') # Clamped to 100.
+ assert reported == [25, 50, 100]
+
+ # No duration: nothing can be reported.
+ reported.clear()
+ make_ffmpeg_progress_parser(None, reported.append)('out_time_us=25000000')
+ assert reported == []
+
+
+@pytest.mark.asyncio
+async def test_transcode_video_job(test_session, test_directory, async_client, video_factory):
+ """The transcode Job runs ffmpeg inside the Job (log + progress captured) and re-indexes the
+ Video so its FileGroup points at the new file."""
+ video_path = test_directory / 'videos/NO CHANNEL/movie.webm'
+ video_path.parent.mkdir(parents=True, exist_ok=True)
+ video = video_factory(with_video_file=video_path)
+ video.file_group.length = 10
+ test_session.commit()
+ file_group_id = video.file_group_id
+
+ async def fake_run_command(cmd, stdout_callback=None, **kwargs):
+ # ffmpeg reports progress on stdout, then writes the temporary output file. The output
+ # must be a real video: the refresh would otherwise drop the Video model (mimetype changed).
+ stdout_callback('out_time_us=5000000')
+ shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', cmd[-1])
+ return CommandResult(return_code=0, cancelled=False, stdout=b'', stderr=b'ffmpeg version fake', elapsed=1)
+
+ # In tests the file refresh is drained inline by the waiter, inside the Job's task, so its
+ # (many) log lines land in the Job log too and could push the early lines out of the tail.
+ with mock.patch('wrolpi.cmd.run_command', side_effect=fake_run_command), \
+ mock.patch.object(jobs, 'JOB_LOG_LINES', 10_000):
+ job_id = transcode_video_job.enqueue(description='Transcode movie.webm', file_group_id=file_group_id,
+ video_codec='h264', audio_codec='aac', container='mp4')
+ record = await jobs.wait_for_job(job_id)
+
+ assert record['status'] == jobs.COMPLETE, record
+ assert record['result'] == {'path': 'videos/NO CHANNEL/movie.mp4'}
+ assert 'out_time_us=5000000' in record['log'], 'ffmpeg stdout is in the Job log'
+ assert 'ffmpeg version fake' in record['log'], 'ffmpeg stderr is in the Job log'
+ assert any('Transcoding' in i for i in record['log']), 'logger output is in the Job log'
+
+ assert not video_path.exists()
+ assert (test_directory / 'videos/NO CHANNEL/movie.mp4').is_file()
+
+ test_session.expire_all()
+ # The same FileGroup (tags, history) now points at the mp4; no new FileGroup was created.
+ video = Video.find_by_file_group_id(test_session, file_group_id)
+ assert video.video_path == test_directory / 'videos/NO CHANNEL/movie.mp4'
+ assert video.file_group.primary_path == test_directory / 'videos/NO CHANNEL/movie.mp4'
+ assert video.file_group.mimetype == 'video/mp4'
+ # The modeler probed the new file and wrote a fresh sidecar; the webm is gone.
+ assert sorted(i['path'] for i in video.file_group.files) == ['movie.ffprobe.json', 'movie.mp4']
+ assert video.ffprobe_json, 'ffprobe ran again on the new file'
+ assert video.file_group.indexed is True, 'The refresh re-modeled the Video'
+ assert test_session.query(FileGroup).count() == 1
+
+
+@pytest.mark.asyncio
+async def test_transcode_video_job_failure(test_session, test_directory, async_client, video_factory):
+ """A failed ffmpeg fails the Job and leaves the original file in place."""
+ video = video_factory()
+ video_path = video.video_path
+
+ async def fake_run_command(cmd, stdout_callback=None, **kwargs):
+ return CommandResult(return_code=1, cancelled=False, stdout=b'', stderr=b'Conversion failed!', elapsed=1)
+
+ with mock.patch('wrolpi.cmd.run_command', side_effect=fake_run_command):
+ job_id = transcode_video_job.enqueue(file_group_id=video.file_group_id, video_codec='h264')
+ record = await jobs.wait_for_job(job_id)
+
+ assert record['status'] == jobs.FAILED
+ assert 'Conversion failed!' in record['error']
+ assert video_path.is_file()
+
+
+@pytest.mark.asyncio
+async def test_video_transcode_api(async_client, test_session, video_factory, wrol_mode_fixture):
+ """The transcode endpoint validates the request, then queues a Job."""
+ video = video_factory()
+ test_session.commit()
+
+ # Nothing to transcode.
+ request, response = await async_client.post(f'/api/videos/{video.file_group_id}/transcode',
+ content=json.dumps({}))
+ assert response.status == 400, response.json
+ # Unsupported target.
+ request, response = await async_client.post(f'/api/videos/{video.file_group_id}/transcode',
+ content=json.dumps({'video_codec': 'av1'}))
+ assert response.status == 400
+ # Unknown video.
+ request, response = await async_client.post('/api/videos/999999/transcode',
+ content=json.dumps({'video_codec': 'h264'}))
+ assert response.status == 404
+ assert jobs.get_jobs() == [], 'Nothing was queued'
+
+ request, response = await async_client.post(f'/api/videos/{video.file_group_id}/transcode',
+ content=json.dumps({'video_codec': 'h264', 'audio_codec': 'aac'}))
+ assert response.status == 200, response.json
+ job_id = response.json['job_id']
+ record = jobs.get_job(job_id)
+ assert record['status'] == jobs.PENDING
+ assert record['name'] == 'transcode_video'
+ assert record['description'] == f'Transcode {video.video_path.name}'
+ assert record['kwargs'] == {'file_group_id': video.file_group_id, 'video_codec': 'h264',
+ 'audio_codec': 'aac', 'container': 'mp4'}
+ # Do not run it (ffmpeg); cancel instead.
+ jobs.cancel_job(job_id)
+
+ # WROL mode forbids modifying files.
+ await wrol_mode_fixture(True)
+ request, response = await async_client.post(f'/api/videos/{video.file_group_id}/transcode',
+ content=json.dumps({'video_codec': 'h264'}))
+ assert response.status == 403
+ await wrol_mode_fixture(False)
diff --git a/modules/videos/transcode.py b/modules/videos/transcode.py
index 2a97e8e9..45001513 100644
--- a/modules/videos/transcode.py
+++ b/modules/videos/transcode.py
@@ -2,11 +2,13 @@ import asyncio
import os
import pathlib
import shutil
-from typing import List, Optional, Tuple
+from typing import List, Optional, Tuple, Callable
from wrolpi.captions import FFMPEG_BIN
from wrolpi.cmd import run_command
-from wrolpi.common import logger
+from wrolpi.common import logger, get_relative_to_media_directory
+from wrolpi.db import get_db_session
+from wrolpi.jobs import register_job, get_current_job
from wrolpi.vars import DEFAULT_FILE_PERMISSIONS, PYTEST
logger = logger.getChild(__name__)
@@ -114,7 +116,8 @@ async def _acquire_transcode_lock():
async def transcode_video_file(video_path: pathlib.Path,
target_vcodec: Optional[str] = None,
target_acodec: Optional[str] = None,
- container: str = 'mp4') -> pathlib.Path:
+ container: str = 'mp4',
+ duration: Optional[float] = None) -> pathlib.Path:
"""Transcode a video file in place (same stem, possibly a new container extension).
Only one transcode runs at a time machine-wide (across all Sanic workers); this call waits
@@ -123,6 +126,9 @@ async def transcode_video_file(video_path: pathlib.Path,
the final path. The original file is deleted if the extension changed. Returns the final
path.
+ When run inside a Job (see `wrolpi.jobs`), ffmpeg's output is captured into the Job log and, if
+ `duration` (seconds) is known, progress is reported to the Job.
+
@raise RuntimeError: when ffmpeg fails, or there is not enough free disk space.
"""
if not FFMPEG_BIN:
@@ -135,13 +141,39 @@ async def transcode_video_file(video_path: pathlib.Path,
lock = await _acquire_transcode_lock()
try:
- return await _transcode_video_file(video_path, target_vcodec, target_acodec, container)
+ return await _transcode_video_file(video_path, target_vcodec, target_acodec, container, duration)
finally:
lock.release()
+def make_ffmpeg_progress_parser(duration: Optional[float], set_progress: Callable[[float], None]) \
+ -> Callable[[str], None]:
+ """Return a callback for `ffmpeg -progress pipe:1` stdout lines which reports percent complete.
+
+ ffmpeg emits `out_time_us=` (older builds: `out_time_ms`, also microseconds)."""
+ last = [-1]
+
+ def parse(line: str):
+ if not duration or duration <= 0:
+ return
+ key, sep, value = line.partition('=')
+ if not sep or key not in ('out_time_us', 'out_time_ms'):
+ return
+ try:
+ seconds = int(value) / 1_000_000
+ except ValueError:
+ return
+ percent = int(min(100.0, max(0.0, 100.0 * seconds / duration)))
+ if percent != last[0]:
+ last[0] = percent
+ set_progress(percent)
+
+ return parse
+
+
async def _transcode_video_file(video_path: pathlib.Path, target_vcodec: Optional[str],
- target_acodec: Optional[str], container: str) -> pathlib.Path:
+ target_acodec: Optional[str], container: str,
+ duration: Optional[float] = None) -> pathlib.Path:
"""The ffmpeg work of `transcode_video_file`; the caller holds the transcode lock."""
# Notify here, after the lock: the wait for another transcode can last hours, and the user
# should hear "Transcoding" only when this file's work actually begins.
@@ -171,10 +203,18 @@ async def _transcode_video_file(video_path: pathlib.Path, target_vcodec: Optiona
*video_args,
*audio_args,
'-movflags', '+faststart',
+ # Machine-readable progress on stdout (the human progress line is suppressed).
+ '-nostats', '-progress', 'pipe:1',
str(tmp_path))
logger.warning(f'Transcoding {video_path} to {final_path} (video={target_vcodec}, audio={target_acodec})')
try:
- result = await run_command(cmd, cwd=video_path.parent, timeout=TRANSCODE_TIMEOUT)
+ job = get_current_job()
+ if job:
+ # Inside a Job: ffmpeg's output lands in the Job log and progress is reported.
+ result = await job.run_command(cmd, cwd=video_path.parent, timeout=TRANSCODE_TIMEOUT,
+ stdout_callback=make_ffmpeg_progress_parser(duration, job.set_progress))
+ else:
+ result = await run_command(cmd, cwd=video_path.parent, timeout=TRANSCODE_TIMEOUT)
if result.return_code != 0:
raise RuntimeError(
f'ffmpeg exited with {result.return_code} while transcoding {video_path}:'
@@ -207,3 +247,59 @@ async def _transcode_video_file(video_path: pathlib.Path, target_vcodec: Optiona
finally:
os.close(fd)
return final_path
+
+
+def validate_transcode_request(video_codec: Optional[str], audio_codec: Optional[str], container: str):
+ """@raise ValueError: when the request cannot be transcoded."""
+ if not video_codec and not audio_codec:
+ raise ValueError('At least one of video_codec or audio_codec is required')
+ if video_codec and video_codec not in TRANSCODE_VIDEO_TARGETS:
+ raise ValueError(f'Cannot transcode video to {video_codec!r}; supported: {sorted(TRANSCODE_VIDEO_TARGETS)}')
+ if audio_codec and audio_codec not in TRANSCODE_AUDIO_TARGETS:
+ raise ValueError(f'Cannot transcode audio to {audio_codec!r}; supported: {sorted(TRANSCODE_AUDIO_TARGETS)}')
+ if container not in TRANSCODE_CONTAINERS:
+ raise ValueError(f'Unsupported container {container!r}; supported: {TRANSCODE_CONTAINERS}')
+
+
+@register_job('transcode_video')
+async def transcode_video_job(file_group_id: int, video_codec: Optional[str] = None,
+ audio_codec: Optional[str] = None, container: str = 'mp4') -> dict:
+ """Transcode a Video's file, then re-index it so the FileGroup reflects the new file.
+
+ Run as a Job (`transcode_video_job.enqueue(...)`) so the user can watch and cancel it."""
+ from modules.videos.models import Video
+ from wrolpi.files.lib import get_mimetype
+ from wrolpi.files.worker import file_worker
+
+ validate_transcode_request(video_codec, audio_codec, container)
+
+ with get_db_session() as session:
+ video = Video.find_by_file_group_id(session, file_group_id)
+ video_path = video.video_path
+ duration = video.file_group.length
+ if not video_path or not video_path.is_file():
+ raise RuntimeError(f'Video file does not exist: {video_path}')
+
+ final_path = await transcode_video_file(video_path, video_codec, audio_codec, container, duration=duration)
+
+ # Point the existing FileGroup at the new file *before* refreshing. A refresh which finds a
+ # new filename on disk would delete this FileGroup and create another, losing tags and history.
+ with get_db_session(commit=True) as session:
+ video = Video.find_by_file_group_id(session, file_group_id)
+ file_group = video.file_group
+ if final_path != video_path:
+ file_group.files = [
+ {**i, 'path': final_path.name, 'mimetype': get_mimetype(final_path)}
+ if i['path'] == video_path.name else i
+ for i in file_group.files
+ ]
+ file_group.primary_path = final_path
+ file_group.mimetype = get_mimetype(final_path)
+ # The streams changed: the modeler must ffprobe the file again.
+ video.ffprobe_json = None
+ file_group.indexed = False
+
+ job_id = file_worker.queue_refresh([final_path], send_events=False)
+ await file_worker.wait_for_job(job_id)
+
+ return {'path': str(get_relative_to_media_directory(final_path))}
diff --git a/modules/videos/video/api.py b/modules/videos/video/api.py
index ac1bc60f..03c0a5ed 100644
--- a/modules/videos/video/api.py
+++ b/modules/videos/video/api.py
@@ -7,11 +7,12 @@ from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from wrolpi.api_utils import json_response
-from wrolpi.common import logger
-from wrolpi.errors import InvalidOrderBy
+from wrolpi.common import logger, wrol_mode_check
+from wrolpi.errors import InvalidOrderBy, InvalidJob
from wrolpi.schema import JSONErrorResponse
from . import lib
from .. import schema
+from ..transcode import transcode_video_job, validate_transcode_request
video_bp = Blueprint('Video', '/api/videos')
@@ -55,6 +56,31 @@ def video_get_captions(_: Request, file_group_id: int):
return json_response({'captions': video.get_caption_chunks()})
+@video_bp.post('//transcode')
+@openapi.description('Queue a Job which transcodes the Video to the requested codecs/container.')
+@openapi.body({'application/json': schema.VideoTranscodeRequest})
+@openapi.response(HTTPStatus.OK, schema.VideoTranscodeResponse)
+@openapi.response(HTTPStatus.BAD_REQUEST, JSONErrorResponse)
+@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
+@validate(schema.VideoTranscodeRequest)
+@wrol_mode_check
+async def video_transcode(_: Request, file_group_id: int, body: schema.VideoTranscodeRequest):
+ try:
+ validate_transcode_request(body.video_codec, body.audio_codec, body.container)
+ except ValueError as e:
+ raise InvalidJob(str(e))
+ # Raises UnknownVideo (404) before anything is queued.
+ video = lib.get_video(file_group_id)
+ job_id = transcode_video_job.enqueue(
+ description=f'Transcode {video.video_path.name}',
+ file_group_id=file_group_id,
+ video_codec=body.video_codec,
+ audio_codec=body.audio_codec,
+ container=body.container,
+ )
+ return json_response({'job_id': job_id})
+
+
@video_bp.post('/search')
@openapi.definition(
summary='Search Video titles and captions',
diff --git a/wrolpi/contexts.py b/wrolpi/contexts.py
index e1c0b73b..9e94a7af 100644
--- a/wrolpi/contexts.py
+++ b/wrolpi/contexts.py
@@ -106,6 +106,12 @@ def attach_shared_contexts(app: Sanic):
app.shared_ctx.file_worker_status = manager.dict()
app.shared_ctx.file_worker_jobs = manager.dict()
+ # Jobs (wrolpi/jobs.py): FIFO queue of registered functions run one at a time by the
+ # perpetual-tasks owner. Never persisted; an API restart loses them.
+ app.shared_ctx.jobs = manager.dict()
+ app.shared_ctx.jobs_queue = manager.Queue()
+ app.shared_ctx.jobs_lock = multiprocessing.Lock()
+
reset_shared_contexts(app)
@@ -205,6 +211,14 @@ def reset_shared_contexts(app: Sanic):
break
app.shared_ctx.file_worker_status.clear()
app.shared_ctx.file_worker_jobs.clear()
+
+ # Jobs
+ while True:
+ try:
+ app.shared_ctx.jobs_queue.get_nowait()
+ except queue.Empty:
+ break
+ app.shared_ctx.jobs.clear()
app.shared_ctx.file_worker_status.update(dict(
status='idle',
task_type=None,
diff --git a/wrolpi/errors.py b/wrolpi/errors.py
index 76a822bf..da7a6939 100644
--- a/wrolpi/errors.py
+++ b/wrolpi/errors.py
@@ -211,3 +211,15 @@ class InvalidArchiveMember(APIError):
code = 'INVALID_ARCHIVE_MEMBER'
summary = 'The requested member does not exist in the archive.'
status_code = HTTPStatus.BAD_REQUEST
+
+
+class UnknownJob(APIError):
+ code = 'UNKNOWN_JOB'
+ summary = 'The Job cannot be found.'
+ status_code = HTTPStatus.NOT_FOUND
+
+
+class InvalidJob(APIError):
+ code = 'INVALID_JOB'
+ summary = 'The Job request is invalid.'
+ status_code = HTTPStatus.BAD_REQUEST
diff --git a/wrolpi/jobs.py b/wrolpi/jobs.py
new file mode 100644
index 00000000..04cf2d9a
--- /dev/null
+++ b/wrolpi/jobs.py
@@ -0,0 +1,414 @@
+"""In-memory FIFO queue of background Jobs.
+
+A Job is a call of a *registered* function with JSON-able kwargs. Any Sanic worker may enqueue a
+Job; the perpetual-tasks owner process runs them one at a time, in order. Python logging emitted
+while a Job runs, and the output of subprocesses started through `JobContext.run_command`, are
+captured into the Job's log. A caller may wait for a Job, poll it, or cancel it.
+
+Jobs are never written to disk: when the API restarts they are lost.
+
+>>> @register_job('example')
+>>> async def example(path: str):
+>>> job = get_current_job()
+>>> job.set_progress(50)
+>>> await job.run_command(('ls', path))
+
+>>> job_id = enqueue_job('example', description='List a directory', path='/tmp')
+>>> await wait_for_job(job_id)
+
+Functions are registered by name (rather than enqueued as objects) because kwargs and the call
+must cross the process boundary between Sanic workers; a name and JSON kwargs always can.
+"""
+import asyncio
+import contextvars
+import inspect
+import json
+import logging
+import multiprocessing
+import os
+import pathlib
+import queue
+import time
+import uuid
+from collections import deque
+from functools import partial
+from http import HTTPStatus
+from typing import Callable, Dict, List, Optional
+
+from sanic import Blueprint
+from sanic.request import Request
+from sanic_ext.extensions.openapi import openapi
+
+from wrolpi.api_utils import api_app, json_response, perpetual_signal
+from wrolpi.common import logger
+from wrolpi.dates import now
+from wrolpi.errors import UnknownJob, InvalidJob
+from wrolpi.events import Events
+from wrolpi.schema import JSONErrorResponse
+from wrolpi.vars import PYTEST
+
+logger = logger.getChild(__name__)
+
+JOB_HANDLERS: Dict[str, Callable] = dict()
+
+PENDING = 'pending'
+RUNNING = 'running'
+COMPLETE = 'complete'
+FAILED = 'failed'
+CANCELLED = 'cancelled'
+FINISHED_STATUSES = (COMPLETE, FAILED, CANCELLED)
+
+# Only the tail of a Job's log is kept; ffmpeg alone can emit thousands of lines.
+JOB_LOG_LINES = 200
+# Finished Jobs kept for the UI/API before the oldest are forgotten.
+JOB_HISTORY_LIMIT = 100
+# How often the running Job checks whether it has been cancelled from another process.
+JOB_CANCEL_POLL_SECONDS = 0.05 if PYTEST else 1
+# The Job log lives in this process; it is copied to the shared dict at most this often.
+JOB_LOG_FLUSH_SECONDS = 0 if PYTEST else 0.5
+
+
+def _jobs() -> dict:
+ try:
+ return api_app.shared_ctx.jobs
+ except AttributeError:
+ raise RuntimeError('Sanic shared_ctx has not been initialized. If testing, use `async_client` fixture.')
+
+
+def _queue():
+ return api_app.shared_ctx.jobs_queue
+
+
+def _lock() -> multiprocessing.Lock:
+ return api_app.shared_ctx.jobs_lock
+
+
+def register_job(name: str):
+ """Register a function that can be run as a Job by `name`.
+
+ The function may be sync or async, and is called with the kwargs given to `enqueue_job`. Use
+ `get_current_job()` inside the function for logging, progress, subprocesses, and cancellation.
+ The wrapped function gains an `enqueue(description=None, **kwargs)` method.
+ """
+
+ def wrapper(func: Callable):
+ if name in JOB_HANDLERS and not PYTEST:
+ raise RuntimeError(f'register_job: job name already taken {name}')
+ JOB_HANDLERS[name] = func
+ setattr(func, 'enqueue', partial(enqueue_job, name))
+ return func
+
+ return wrapper
+
+
+def enqueue_job(name: str, description: str = None, **kwargs) -> str:
+ """Add a Job to the end of the queue. Returns its id.
+
+ @raise InvalidJob: when `name` is not registered, or kwargs are not JSON serializable.
+ """
+ if name not in JOB_HANDLERS:
+ raise InvalidJob(f'No job is registered with the name {name!r}')
+ try:
+ json.dumps(kwargs)
+ except (TypeError, ValueError) as e:
+ raise InvalidJob(f'Job kwargs must be JSON serializable: {e}')
+
+ job_id = f'{name}-{uuid.uuid4().hex[:8]}'
+ record = dict(
+ id=job_id,
+ name=name,
+ description=description or name,
+ kwargs=kwargs,
+ status=PENDING,
+ created_at=now().isoformat(),
+ started_at=None,
+ finished_at=None,
+ error=None,
+ progress=None,
+ result=None,
+ log=[],
+ pid=None,
+ cancel_requested=False,
+ )
+ with _lock():
+ _jobs()[job_id] = record
+ _prune_finished_jobs()
+ _queue().put_nowait(job_id)
+ logger.info(f'enqueue_job: {job_id} ({description or name})')
+ return job_id
+
+
+def get_job(job_id: str) -> dict:
+ """@raise UnknownJob: when no Job has this id."""
+ record = _jobs().get(job_id)
+ if not record:
+ raise UnknownJob(f'Job {job_id} does not exist')
+ return dict(record)
+
+
+def get_jobs() -> List[dict]:
+ """All Jobs, oldest first."""
+ return sorted((dict(i) for i in _jobs().values()), key=lambda i: i['created_at'])
+
+
+def _update_job(job_id: str, **changes):
+ """Manager dict values are copies; a change must be written back as a whole record."""
+ with _lock():
+ record = _jobs().get(job_id)
+ if record is None:
+ return
+ record = dict(record)
+ record.update(changes)
+ _jobs()[job_id] = record
+
+
+def _prune_finished_jobs():
+ """Forget the oldest finished Jobs beyond `JOB_HISTORY_LIMIT`. The caller holds the lock."""
+ jobs = _jobs()
+ finished = sorted((i for i in jobs.values() if i['status'] in FINISHED_STATUSES),
+ key=lambda i: i['finished_at'] or '')
+ for record in finished[:max(0, len(finished) - JOB_HISTORY_LIMIT)]:
+ del jobs[record['id']]
+
+
+def cancel_job(job_id: str) -> dict:
+ """Cancel a pending Job immediately, or ask the running Job to stop.
+
+ A running Job's handler is cancelled (its `run_command` subprocess is killed) the next time the
+ worker polls. Finished Jobs are unchanged.
+ """
+ with _lock():
+ record = _jobs().get(job_id)
+ if not record:
+ raise UnknownJob(f'Job {job_id} does not exist')
+ record = dict(record)
+ if record['status'] == PENDING:
+ record.update(status=CANCELLED, finished_at=now().isoformat())
+ logger.info(f'cancel_job: cancelled pending {job_id}')
+ elif record['status'] == RUNNING:
+ record['cancel_requested'] = True
+ logger.info(f'cancel_job: requested cancel of running {job_id}')
+ _jobs()[job_id] = record
+ return record
+
+
+def _cancel_requested(job_id: str) -> bool:
+ record = _jobs().get(job_id)
+ return bool(record and record.get('cancel_requested'))
+
+
+class JobContext:
+ """The running Job, available to its handler via `get_current_job()`."""
+
+ def __init__(self, job_id: str, name: str):
+ self.id = job_id
+ self.name = name
+ self._log: deque = deque(maxlen=JOB_LOG_LINES)
+ self._last_flush = 0.0
+ self._dirty = False
+
+ def log(self, line: str):
+ """Append a line to the Job's log. Must never call `logger` (the log handler would recurse)."""
+ self._log.append(str(line).rstrip())
+ self._dirty = True
+ if time.monotonic() - self._last_flush >= JOB_LOG_FLUSH_SECONDS:
+ self.flush()
+
+ def flush(self):
+ if not self._dirty:
+ return
+ self._last_flush = time.monotonic()
+ self._dirty = False
+ _update_job(self.id, log=list(self._log))
+
+ def set_progress(self, percent: Optional[float]):
+ """Report progress 0-100 to the UI."""
+ if percent is not None:
+ percent = max(0.0, min(100.0, float(percent)))
+ _update_job(self.id, progress=percent)
+
+ def cancel_requested(self) -> bool:
+ return _cancel_requested(self.id)
+
+ async def run_command(self, cmd: tuple[str | pathlib.Path, ...], stdout_callback: Callable = None, **kwargs):
+ """`wrolpi.cmd.run_command` whose stdout lines (live) and stderr tail (on exit) are
+ captured into this Job's log. `stdout_callback` still receives each stdout line."""
+ from wrolpi.cmd import run_command
+
+ def _callback(line: str):
+ self.log(line)
+ if stdout_callback:
+ stdout_callback(line)
+
+ result = await run_command(cmd, stdout_callback=_callback, **kwargs)
+ if result.stderr:
+ for line in result.stderr.decode(errors='replace').splitlines()[-JOB_LOG_LINES:]:
+ if line.strip():
+ self.log(line)
+ self.flush()
+ return result
+
+
+_current_job: contextvars.ContextVar[Optional[JobContext]] = contextvars.ContextVar('current_job', default=None)
+
+
+def get_current_job() -> Optional[JobContext]:
+ """The Job whose handler is running in this task, or None outside of a Job."""
+ return _current_job.get()
+
+
+class JobLogHandler(logging.Handler):
+ """Copies log records emitted inside a running Job into that Job's log.
+
+ The context variable is set on the task that runs the handler, so only records from the Job
+ (and tasks it spawns) are captured, not those of the other coroutines in this process."""
+
+ def emit(self, record: logging.LogRecord):
+ job = _current_job.get()
+ if job is None:
+ return
+ try:
+ job.log(self.format(record))
+ except Exception:
+ self.handleError(record)
+
+
+_log_handler = JobLogHandler()
+_log_handler.setFormatter(logging.Formatter('%(levelname)s:%(name)s:%(message)s'))
+if not any(isinstance(i, JobLogHandler) for i in logging.getLogger().handlers):
+ logging.getLogger().addHandler(_log_handler)
+
+
+def _json_safe(value):
+ try:
+ json.dumps(value)
+ return value
+ except (TypeError, ValueError):
+ return str(value)
+
+
+async def _run_job(job_id: str):
+ """Run one Job to completion (or failure/cancellation) in this process."""
+ record = _jobs().get(job_id)
+ if not record or record['status'] != PENDING:
+ # Cancelled while it was waiting in the queue.
+ return
+
+ name = record['name']
+ context = JobContext(job_id, name)
+ handler = JOB_HANDLERS.get(name)
+ if handler is None:
+ _update_job(job_id, status=FAILED, error=f'No handler is registered for {name!r}',
+ finished_at=now().isoformat())
+ return
+
+ _update_job(job_id, status=RUNNING, started_at=now().isoformat(), pid=os.getpid())
+ token = _current_job.set(context)
+ try:
+ async def call():
+ result = handler(**record['kwargs'])
+ if inspect.isawaitable(result):
+ result = await result
+ return result
+
+ # The task copies the current context, so the handler (and any tasks it creates) see this Job.
+ task = asyncio.create_task(call())
+ while not task.done():
+ await asyncio.wait({task}, timeout=JOB_CANCEL_POLL_SECONDS)
+ if not task.done() and _cancel_requested(job_id):
+ task.cancel()
+ try:
+ await task
+ except BaseException: # noqa Includes CancelledError; the Job is what was cancelled.
+ pass
+ context.log('Cancelled')
+ context.flush()
+ _update_job(job_id, status=CANCELLED, finished_at=now().isoformat())
+ logger.warning(f'Job {job_id} was cancelled')
+ Events.send_user_notify(f'Cancelled: {record["description"]}')
+ return
+
+ try:
+ result = task.result()
+ except asyncio.CancelledError:
+ # The worker itself is shutting down; leave the record honest.
+ _update_job(job_id, status=CANCELLED, finished_at=now().isoformat())
+ raise
+ except Exception as e:
+ logger.error(f'Job {job_id} failed', exc_info=e)
+ context.flush()
+ _update_job(job_id, status=FAILED, error=str(e) or repr(e), finished_at=now().isoformat())
+ Events.send_user_notify(f'Failed: {record["description"]}')
+ return
+
+ context.flush()
+ _update_job(job_id, status=COMPLETE, result=_json_safe(result), progress=100.0,
+ finished_at=now().isoformat())
+ logger.info(f'Job {job_id} completed')
+ Events.send_user_notify(f'Completed: {record["description"]}')
+ finally:
+ context.flush()
+ _current_job.reset(token)
+
+
+async def process_job_queue() -> int:
+ """Run every queued Job, in order. Returns how many were run."""
+ count = 0
+ while True:
+ try:
+ job_id = _queue().get_nowait()
+ except queue.Empty:
+ return count
+ count += 1
+ await _run_job(job_id)
+
+
+@perpetual_signal(sleep=0.5)
+async def job_worker():
+ """The single consumer of the Job queue; runs in the perpetual-tasks owner process only."""
+ try:
+ job_id = _queue().get_nowait()
+ except queue.Empty:
+ return
+ await _run_job(job_id)
+
+
+async def wait_for_job(job_id: str, timeout: float = 300) -> dict:
+ """Wait for a Job to finish; returns its record.
+
+ In tests (no perpetual loop) the queue is drained by this waiter so the Job actually runs.
+
+ @raise TimeoutError: when the Job has not finished in time.
+ """
+ start = time.time()
+ while time.time() - start < timeout:
+ record = get_job(job_id)
+ if record['status'] in FINISHED_STATUSES:
+ return record
+ if PYTEST:
+ await process_job_queue()
+ await asyncio.sleep(0.01 if PYTEST else 0.5)
+ raise TimeoutError(f'Job {job_id} did not finish in time')
+
+
+jobs_bp = Blueprint('Jobs', url_prefix='/api/jobs')
+
+
+@jobs_bp.get('/')
+@openapi.description('List all Jobs, oldest first. Jobs are not saved; an API restart forgets them.')
+async def get_jobs_request(_: Request):
+ return json_response({'jobs': get_jobs()})
+
+
+@jobs_bp.get('/')
+@openapi.description('Get one Job, including its log tail.')
+@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
+async def get_job_request(_: Request, job_id: str):
+ return json_response({'job': get_job(job_id)})
+
+
+@jobs_bp.delete('/')
+@openapi.description('Cancel a pending or running Job. Allowed in WROL Mode: it only stops work.')
+@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
+async def cancel_job_request(_: Request, job_id: str):
+ return json_response({'job': cancel_job(job_id)})
diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py
index 95d36512..5bcab2b9 100644
--- a/wrolpi/root_api.py
+++ b/wrolpi/root_api.py
@@ -35,6 +35,7 @@ from wrolpi.errors import WROLModeEnabled, InvalidConfig, ValidationError
from wrolpi.events import get_events, Events
from wrolpi.files import files_bp
from wrolpi.files.lib import get_file_statistics, search_file_suggestion_count
+from wrolpi.jobs import jobs_bp
from wrolpi.log_levels import int_to_name
from wrolpi.speedtest import speedtest_bp
from wrolpi.tags import Tag
@@ -60,6 +61,7 @@ api_app.blueprint(docs_bp)
api_app.blueprint(files_bp)
api_app.blueprint(flasher_bp)
api_app.blueprint(inventory_bp)
+api_app.blueprint(jobs_bp)
api_app.blueprint(map_bp)
api_app.blueprint(speedtest_bp)
api_app.blueprint(videos_bp)
diff --git a/wrolpi/test/test_jobs.py b/wrolpi/test/test_jobs.py
new file mode 100644
index 00000000..c9f7b026
--- /dev/null
+++ b/wrolpi/test/test_jobs.py
@@ -0,0 +1,212 @@
+import asyncio
+import logging
+from http import HTTPStatus
+
+import pytest
+
+from wrolpi import jobs
+from wrolpi.errors import InvalidJob, UnknownJob
+from wrolpi.jobs import register_job, enqueue_job, wait_for_job, get_job, get_current_job, cancel_job, \
+ process_job_queue, get_jobs
+
+test_logger = logging.getLogger('wrolpi.test.jobs')
+
+order = []
+
+
+@register_job('test_add')
+async def job_add(a: int, b: int):
+ order.append(('add', a, b))
+ test_logger.warning(f'adding {a} and {b}')
+ return a + b
+
+
+@register_job('test_sync')
+def job_sync(value: str):
+ return value.upper()
+
+
+@register_job('test_fail')
+async def job_fail(message: str):
+ raise RuntimeError(message)
+
+
+@register_job('test_progress')
+async def job_progress():
+ job = get_current_job()
+ job.log('first line')
+ job.set_progress(42)
+ return {'job_id': job.id}
+
+
+@register_job('test_slow')
+async def job_slow(seconds: float):
+ await asyncio.sleep(seconds)
+ return 'done'
+
+
+@register_job('test_command')
+async def job_command():
+ job = get_current_job()
+ result = await job.run_command(('sh', '-c', 'echo out1; echo out2; echo err1 >&2'))
+ return result.return_code
+
+
+@register_job('test_slow_command')
+async def job_slow_command():
+ job = get_current_job()
+ result = await job.run_command(('sleep', '30'))
+ return result.cancelled
+
+
+@pytest.mark.asyncio
+async def test_jobs_fifo(async_client):
+ """Jobs run in the order they were queued; sync and async handlers both work; results are stored."""
+ order.clear()
+ first = enqueue_job('test_add', a=1, b=2)
+ second = enqueue_job('test_add', a=3, b=4)
+ third = enqueue_job('test_sync', value='abc')
+
+ for job_id in (first, second, third):
+ assert get_job(job_id)['status'] == jobs.PENDING
+
+ assert (await wait_for_job(third))['status'] == jobs.COMPLETE
+ assert order == [('add', 1, 2), ('add', 3, 4)]
+ assert get_job(first)['result'] == 3
+ assert get_job(second)['result'] == 7
+ assert get_job(third)['result'] == 'ABC'
+ assert get_job(first)['progress'] == 100
+ assert get_job(first)['started_at'] and get_job(first)['finished_at']
+ assert [i['id'] for i in get_jobs()] == [first, second, third]
+
+
+@pytest.mark.asyncio
+async def test_jobs_capture_logging(async_client):
+ """`logging` emitted while a Job runs is captured into that Job's log, and only that Job's."""
+ a = enqueue_job('test_add', a=5, b=6)
+ b = enqueue_job('test_add', a=7, b=8)
+ await wait_for_job(b)
+ a_log = get_job(a)['log']
+ assert any('adding 5 and 6' in i for i in a_log), a_log
+ assert not any('adding 7 and 8' in i for i in a_log), a_log
+ assert any('adding 7 and 8' in i for i in get_job(b)['log'])
+
+
+@pytest.mark.asyncio
+async def test_jobs_failure(async_client):
+ """A handler exception fails the Job and records the error; the queue keeps going."""
+ failed = enqueue_job('test_fail', message='boom')
+ after = enqueue_job('test_sync', value='after')
+ record = await wait_for_job(after)
+ assert record['status'] == jobs.COMPLETE
+ failed = get_job(failed)
+ assert failed['status'] == jobs.FAILED
+ assert failed['error'] == 'boom'
+ assert any('boom' in i for i in failed['log'])
+
+
+@pytest.mark.asyncio
+async def test_jobs_context(async_client):
+ """The handler can log, report progress, and learn its own id through `get_current_job`."""
+ job_id = enqueue_job('test_progress', description='Progress test')
+ record = await wait_for_job(job_id)
+ assert record['result'] == {'job_id': job_id}
+ assert record['description'] == 'Progress test'
+ assert 'first line' in record['log']
+ assert record['progress'] == 100 # Completion sets 100.
+ assert get_current_job() is None, 'No Job is running outside of the worker'
+
+
+@pytest.mark.asyncio
+async def test_jobs_run_command_captured(async_client):
+ """stdout and stderr of a Job subprocess land in the Job log."""
+ job_id = enqueue_job('test_command')
+ record = await wait_for_job(job_id)
+ assert record['status'] == jobs.COMPLETE, record
+ assert record['result'] == 0
+ assert 'out1' in record['log'] and 'out2' in record['log'] and 'err1' in record['log']
+
+
+@pytest.mark.asyncio
+async def test_jobs_cancel_pending(async_client):
+ """A pending Job is cancelled immediately and never runs."""
+ order.clear()
+ job_id = enqueue_job('test_add', a=1, b=1)
+ record = cancel_job(job_id)
+ assert record['status'] == jobs.CANCELLED
+ assert record['finished_at']
+ assert await process_job_queue() == 1, 'The queued id is consumed'
+ assert order == [], 'The cancelled Job did not run'
+ assert get_job(job_id)['status'] == jobs.CANCELLED
+
+
+@pytest.mark.asyncio
+async def test_jobs_cancel_running(async_client):
+ """A running Job is cancelled the next time the worker polls; its subprocess is killed."""
+ job_id = enqueue_job('test_slow_command')
+ task = asyncio.create_task(process_job_queue())
+ # Wait for the Job to actually be running.
+ for _ in range(200):
+ if get_job(job_id)['status'] == jobs.RUNNING:
+ break
+ await asyncio.sleep(0.01)
+ else:
+ raise AssertionError('Job never started')
+
+ record = cancel_job(job_id)
+ assert record['cancel_requested'] is True
+ await asyncio.wait_for(task, timeout=5)
+ record = get_job(job_id)
+ assert record['status'] == jobs.CANCELLED
+ assert 'Cancelled' in record['log']
+
+
+@pytest.mark.asyncio
+async def test_jobs_validation(async_client):
+ with pytest.raises(InvalidJob):
+ enqueue_job('does_not_exist')
+ with pytest.raises(InvalidJob):
+ enqueue_job('test_add', a=object(), b=1)
+ with pytest.raises(UnknownJob):
+ get_job('nope')
+ with pytest.raises(UnknownJob):
+ cancel_job('nope')
+
+
+@pytest.mark.asyncio
+async def test_jobs_prune(async_client):
+ """Only the newest finished Jobs are kept."""
+ old_limit = jobs.JOB_HISTORY_LIMIT
+ jobs.JOB_HISTORY_LIMIT = 2
+ try:
+ ids = [enqueue_job('test_sync', value=str(i)) for i in range(3)]
+ await wait_for_job(ids[-1])
+ # A new enqueue triggers the prune.
+ newest = enqueue_job('test_sync', value='x')
+ remaining = {i['id'] for i in get_jobs()}
+ assert ids[0] not in remaining
+ assert ids[1] in remaining and ids[2] in remaining and newest in remaining
+ finally:
+ jobs.JOB_HISTORY_LIMIT = old_limit
+
+
+@pytest.mark.asyncio
+async def test_jobs_api(async_client):
+ """Jobs can be listed, fetched, and cancelled over the API."""
+ job_id = enqueue_job('test_slow', description='Sleepy', seconds=30)
+
+ request, response = await async_client.get('/api/jobs')
+ assert response.status == HTTPStatus.OK
+ assert [i['id'] for i in response.json['jobs']] == [job_id]
+
+ request, response = await async_client.get(f'/api/jobs/{job_id}')
+ assert response.status == HTTPStatus.OK
+ assert response.json['job']['description'] == 'Sleepy'
+ assert response.json['job']['status'] == jobs.PENDING
+
+ request, response = await async_client.delete(f'/api/jobs/{job_id}')
+ assert response.status == HTTPStatus.OK
+ assert response.json['job']['status'] == jobs.CANCELLED
+
+ request, response = await async_client.get('/api/jobs/nope')
+ assert response.status == HTTPStatus.NOT_FOUND