FileWorker: Async queue-based file synchronization system

Introduces FileWorker for background file operations with dual-queue
architecture (public/private). Handles refresh, move, and rename tasks
with progress tracking, job completion monitoring, and batch processing.
Compares DB FileGroups to filesystem state using FileGroupDiff to detect
new/modified/deleted files. Designed for memory efficiency on Raspberry Pi.
This commit is contained in:
Roland 2026-01-09 14:01:25 -07:00
parent 1d9b794fca
commit 173284699d
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
49 changed files with 4256 additions and 861 deletions

View file

@ -185,7 +185,7 @@ async def test_archives_search_no_query(test_session, archive_factory, async_cli
@skip_circleci
@pytest.mark.asyncio
async def test_archive_upload(test_session, async_client, singlefile_contents_factory, make_multipart_form,
await_switches, events_history):
await_switches, events_fixture):
"""Test converting a SingleFile from the SingleFile browser extension to an Archive."""
singlefile_contents = singlefile_contents_factory(title='upload title', url='https://example.com/single-file-url')
forms = [
@ -204,8 +204,7 @@ async def test_archive_upload(test_session, async_client, singlefile_contents_fa
assert archive.screenshot_path.is_file(), 'Screenshot should have been created'
assert archive.file_group.title == 'upload title', 'Title was not correct'
assert archive.file_group.url == 'https://example.com/single-file-url', 'SingleFile URL should be trusted'
events = list(events_history)
assert events and events[0]['event'] == 'upload_archive', 'Event should have been sent.'
events_fixture.assert_has_event('upload_archive')
@pytest.mark.asyncio

View file

@ -20,7 +20,6 @@ from wrolpi.api_utils import CustomJSONEncoder
from wrolpi.collections import Collection
from wrolpi.common import get_wrolpi_config
from wrolpi.db import get_db_session
from wrolpi.files import lib as files_lib
from wrolpi.files.models import FileGroup
from wrolpi.test.common import skip_circleci
@ -85,7 +84,7 @@ async def test_relationships(async_client, test_session, example_singlefile):
@pytest.mark.asyncio
async def test_archive_title(async_client, test_session, archive_factory, singlefile_contents_factory):
async def test_archive_title(async_client, test_session, archive_factory, singlefile_contents_factory, refresh_files):
"""An Archive's title can be fetched in multiple ways. This tests from most to least reliable."""
# Create some test files, delete all records for a fresh refresh.
archive_factory(
@ -98,7 +97,7 @@ async def test_archive_title(async_client, test_session, archive_factory, single
async def reset_and_get_archive():
test_session.query(FileGroup).delete()
test_session.commit()
await files_lib.refresh_files()
await refresh_files()
return test_session.query(Archive).one()
archive1: Archive = await reset_and_get_archive()
@ -175,7 +174,8 @@ async def test_archive_refresh_deleted_archive(async_client, test_session, archi
@pytest.mark.asyncio
async def test_fills_contents_with_refresh(async_client, test_session, archive_factory, singlefile_contents_factory):
async def test_fills_contents_with_refresh(async_client, test_session, archive_factory, singlefile_contents_factory,
refresh_files):
"""Refreshing archives fills in any missing contents."""
archive1 = archive_factory('example.com', 'https://example.com/one')
archive2 = archive_factory('example.com', 'https://example.com/one')
@ -208,7 +208,7 @@ async def test_fills_contents_with_refresh(async_client, test_session, archive_f
assert not archive4.file_group.d_text
# Fill the contents.
await files_lib.refresh_files()
await refresh_files()
# The archives will be renamed with their title.
archive1, archive2, archive3, archive4 = test_session.query(Archive).order_by(Archive.id)
assert not archive4.file_group.d_text
@ -291,7 +291,7 @@ def test_get_domains(test_session, archive_factory):
@skip_circleci
@pytest.mark.asyncio
async def test_new_archive(test_session, test_directory, fake_now):
async def test_new_archive(test_session, test_directory, fake_now, async_client):
singlefile, readability, screenshot = make_fake_archive_result()
fake_now(datetime(2000, 1, 1))
archive1 = await model_archive_result('https://example.com', singlefile, readability, screenshot)
@ -334,7 +334,7 @@ async def test_new_archive(test_session, test_directory, fake_now):
@pytest.mark.asyncio
async def test_get_title_from_html(test_directory, test_session, fake_now):
async def test_get_title_from_html(test_directory, test_session, fake_now, async_client):
fake_now(datetime(2000, 1, 1))
singlefile, readability, screenshot = make_fake_archive_result()
archive = await model_archive_result('https://example.com', singlefile, readability, screenshot)
@ -584,11 +584,11 @@ async def test_refresh_archives(test_session, test_directory, async_client, make
@pytest.mark.asyncio
async def test_refresh_archives_index(test_session, make_files_structure):
async def test_refresh_archives_index(test_session, make_files_structure, refresh_files):
"""Archives are indexed using ArchiveIndexer and archive_modeler."""
# The start of a typical singlefile html file.
singlefile_contents = '''<!DOCTYPE html> <html lang="en"><!--
Page saved with SingleFile
Page saved with SingleFile
url: https://example.com
saved date: Mon May 16 2022 23:51:35 GMT+0000 (Coordinated Universal Time)
--><head><meta charset="utf-8">
@ -609,7 +609,7 @@ async def test_refresh_archives_index(test_session, make_files_structure):
'archive/example.com/2021-10-05-16-20-10_NA.readability.html': '<html></html>',
})
await files_lib.refresh_files()
await refresh_files()
archive: Archive = test_session.query(Archive).one()
assert archive.singlefile_path == singlefile
@ -625,7 +625,7 @@ async def test_refresh_archives_index(test_session, make_files_structure):
@pytest.mark.asyncio
async def test_archive_meta(async_client, test_session, make_files_structure):
async def test_archive_meta(async_client, test_session, make_files_structure, refresh_files):
# The start of a typical singlefile html file.
singlefile_contents = '''<!DOCTYPE html> <html lang="en">
<script data-vue-meta="ssr" type="application/ld+json">
@ -640,7 +640,7 @@ async def test_archive_meta(async_client, test_session, make_files_structure):
'archive/example.com/2021-10-05-16-20-10_NA.readability.html': '<html></html>',
})
await files_lib.refresh_files()
await refresh_files()
archive: Archive = test_session.query(Archive).one()
assert archive.singlefile_path == singlefile
@ -655,19 +655,19 @@ async def test_archive_meta(async_client, test_session, make_files_structure):
@pytest.mark.asyncio
async def test_refresh_archives_deleted_singlefile(async_client, test_session, make_files_structure,
singlefile_contents_factory):
singlefile_contents_factory, refresh_files):
"""Removing a Singlefile file from a FileGroup makes that group no longer an Archive."""
singlefile, readability = make_files_structure({
'2022-09-04-16-20-11_The Title.html': singlefile_contents_factory(),
'2022-09-04-16-20-11_The Title.readability.json': '{"url": "https://example.com"}',
})
await files_lib.refresh_files()
await refresh_files()
assert test_session.query(FileGroup).one().model == 'archive'
assert test_session.query(Archive).count() == 1
# Remove singlefile, FileGroup is no longer an Archive.
singlefile.unlink()
await files_lib.refresh_files()
await refresh_files()
assert test_session.query(FileGroup).one().model is None
assert test_session.query(Archive).count() == 0
@ -709,7 +709,7 @@ def test_archive_order(test_session, test_directory, archive_factory):
@pytest.mark.asyncio
async def test_archive_download_index(test_session, test_directory, image_bytes_factory):
async def test_archive_download_index(test_session, test_directory, image_bytes_factory, async_client):
"""An Archive is indexed when it is downloaded."""
singlefile = '<html><title>the singlefile</title></html>'
readability = dict(
@ -732,7 +732,7 @@ async def test_archive_download_index(test_session, test_directory, image_bytes_
'Did not store the screenshot'
def test_archive_history(test_session, archive_factory):
def test_archive_history(test_session, archive_factory, async_client):
"""Archive's can have a history of other archives.
Archive's with an empty URL are not associated."""

View file

@ -94,6 +94,7 @@ def video_cleanup():
''')
def claim_videos_for_channels(channel_ids: List[int]):
"""
Assign Videos to specific Channels based on directory paths.

View file

@ -11,7 +11,7 @@ from wrolpi.common import logger, \
get_media_directory, wrol_mode_check, background_task
from wrolpi.db import get_db_curs, get_db_session
from wrolpi.downloader import save_downloads_config, download_manager, Download
from wrolpi.errors import APIError, ValidationError, RefreshConflict
from wrolpi.errors import APIError, ValidationError, FileWorkerConflict
from wrolpi.events import Events
from wrolpi.tags import Tag
from .. import schema
@ -269,8 +269,8 @@ async def tag_channel(session: Session, tag_name: str | None, directory: pathlib
Move the Channel to the new directory, if provided."""
if directory and flags.refreshing.is_set():
raise RefreshConflict('Refusing to move channel while file refresh is in progress')
if directory and flags.file_worker_busy.is_set():
raise FileWorkerConflict('Refusing to move channel while FileWorker is busy')
channel = Channel.find_by_id(session, channel_id)

View file

@ -190,7 +190,7 @@ async def test_channel_empty_url_doesnt_conflict(async_client, test_session, tes
@pytest.mark.asyncio
async def test_channel_download_requires_refresh(
async_client, test_session, mock_video_extract_info, download_channel, video_download_manager,
video_factory, events_history, await_switches):
video_factory, events_fixture, await_switches, await_background_tasks):
"""A Channel cannot be downloaded until it has been refreshed.
Videos already downloaded are not downloaded again."""
@ -228,6 +228,8 @@ async def test_channel_download_requires_refresh(
await video_download_manager.do_downloads()
await video_download_manager.wait_for_all_downloads()
await await_switches()
# Wait for background tasks including channel refresh which processes the file worker queue
await await_background_tasks()
# Channel was refreshed before downloading videos.
assert_refreshed(True)
@ -235,8 +237,10 @@ async def test_channel_download_requires_refresh(
# Only the missing video was downloaded.
assert downloaded_urls == ['https://example.com/2']
# Should not send refresh events because downloads are automated.
assert list(events_history) == []
# Should not send user-facing events - only internal FileWorker events are allowed.
user_facing_events = ['user_notify_message', 'directory_refresh', 'files_refreshed']
for event_name in user_facing_events:
events_fixture.assert_no_event(event_name)
@pytest.mark.asyncio

View file

@ -13,7 +13,8 @@ from wrolpi.common import Base, ModelHelper, logger, get_media_directory, get_re
background_task, replace_file
from wrolpi.db import get_db_curs, get_db_session
from wrolpi.downloader import Download
from wrolpi.files.lib import refresh_files, split_path_stem_and_suffix
from wrolpi.files.lib import split_path_stem_and_suffix
from wrolpi.files.worker import file_worker
from wrolpi.files.models import FileGroup
from wrolpi.tags import Tag, TagFile
from wrolpi.vars import PYTEST, VIDEO_INFO_JSON_KEYS_TO_CLEAN
@ -900,9 +901,10 @@ class Channel(ModelHelper, Base):
# Perform info_json in background task. Channel will be marked as refreshed after this completes.
async def _():
# Refresh all files within this channel's directory first.
from modules.videos.common import update_view_counts_and_censored
await refresh_files([directory], send_events=send_events)
job_id = file_worker.queue_refresh([directory])
await file_worker.wait_for_job(job_id)
# Update view count second.
from modules.videos.common import update_view_counts_and_censored
await update_view_counts_and_censored(id_)
with get_db_session(commit=True) as session_:
channel_ = cls.find_by_id(session_, id_)

View file

@ -9,12 +9,11 @@ from modules.videos.video import lib as video_lib
from wrolpi.common import get_wrolpi_config
from wrolpi.db import get_db_curs
from wrolpi.downloader import Download
from wrolpi.files.lib import refresh_files
from wrolpi.files.models import FileGroup
@pytest.mark.asyncio
async def test_refresh_videos_index(async_client, test_session, test_directory, video_factory):
async def test_refresh_videos_index(async_client, test_session, test_directory, video_factory, refresh_files):
"""The video modeler indexes video data into the Video's FileGroup."""
video_factory(with_video_file=True, with_caption_file=True, with_poster_ext='jpg', with_info_json=True)
test_session.commit()
@ -54,12 +53,12 @@ async def test_refresh_videos(async_client, test_session, test_directory, simple
with_info_json=True, with_poster_ext='jpg')
test_session.commit()
video1.file_group.size = video1.file_group.data = None
video1.file_group.paths = list()
video1.file_group.files = []
# video2 is in the test directory.
video2 = video_factory(channel_id=simple_channel.id, with_video_file=True, with_info_json=True,
with_poster_ext='jpg')
video2.file_group.data = None
video2.file_group.paths = []
video2.file_group.files = []
test_session.commit()
assert not video1.file_group.size, 'video1 should not have size during creation'
@ -76,7 +75,7 @@ async def test_refresh_videos(async_client, test_session, test_directory, simple
with get_db_curs(commit=True) as curs:
stmt = "INSERT INTO file_group (mimetype, directory, primary_path, indexed, files, model)" \
" values ('video/mp4', %(directory)s, %(primary_path)s, true, %(files)s, 'video') RETURNING id"
params = {'directory': str(test_directory), 'primary_path': str(video_file), 'files': list()}
params = {'directory': str(test_directory), 'primary_path': str(video_file), 'files': '[]'}
curs.execute(stmt, params)
video4_id = curs.fetchall()[0][0]
stmt = "INSERT INTO video (file_group_id) values (%(video_id)s)"

View file

@ -11,7 +11,6 @@ from modules.videos.models import Channel, Video
from wrolpi.collections import Collection
from wrolpi.common import get_absolute_media_path, get_wrolpi_config
from wrolpi.downloader import Download, DownloadFrequency
from wrolpi.files import lib as files_lib
from wrolpi.vars import PROJECT_DIR
from .. import common
from ..common import convert_image, update_view_counts_and_censored, extract_video_duration, generate_video_poster, \
@ -411,11 +410,11 @@ async def test_ffprobe_json(async_client, video_file, corrupted_video_file):
@pytest.mark.asyncio
async def test_video_ffprobe_json(async_client, test_session, video_file):
async def test_video_ffprobe_json(async_client, test_session, video_file, refresh_files):
"""ffprobe data is extracted when a video is modeled."""
with mock.patch('modules.videos.lib.extract_video_duration') as mock_extract_video_duration:
mock_extract_video_duration.side_effect = Exception('duration should be from ffprobe json')
await files_lib.refresh_files()
await refresh_files()
video = test_session.query(Video).one()
assert video.ffprobe_json

View file

@ -10,7 +10,6 @@ from modules.videos.lib import parse_video_file_name, validate_video, get_statis
from modules.videos.models import Video, Channel
from wrolpi.common import get_wrolpi_config
from wrolpi.downloader import Download, RSSDownloader
from wrolpi.files import lib as files_lib
from wrolpi.files.models import FileGroup
from wrolpi.vars import PROJECT_DIR
@ -142,7 +141,8 @@ async def test_get_statistics(test_session, video_factory, channel_factory):
@pytest.mark.asyncio
async def test_orphaned_files(async_client, test_session, make_files_structure, test_directory, video_factory):
async def test_orphaned_files(async_client, test_session, make_files_structure, test_directory, video_factory,
refresh_files):
# A Video without associated files is not orphaned.
vid1 = video_factory(title='vid1', with_video_file=True)
# The video files will be removed...
@ -159,7 +159,7 @@ async def test_orphaned_files(async_client, test_session, make_files_structure,
# Remove vid3 video. Poster is now orphaned.
vid3.video_path.unlink()
vid3_poster_path = vid3.poster_path
await files_lib.refresh_files()
await refresh_files()
test_session.commit()
# 6 files when two video files are deleted.

View file

@ -4,7 +4,6 @@ import pytest
from modules.videos.models import Video
from wrolpi.errors import FileGroupIsTagged
from wrolpi.files import lib as files_lib
from wrolpi.files.models import FileGroup
@ -47,7 +46,8 @@ async def test_delete_video_with_tag(async_client, test_session, video_factory,
@pytest.mark.asyncio
async def test_video_channel_refresh(async_client, test_session, test_directory, channel_factory, video_factory):
async def test_video_channel_refresh(async_client, test_session, test_directory, channel_factory, video_factory,
refresh_files):
"""A Video will be associated with a Channel when it's files are in that Channel's directory."""
# Create a video file in this channel's directory.
channel = channel_factory()
@ -60,7 +60,7 @@ async def test_video_channel_refresh(async_client, test_session, test_directory,
test_session.query(FileGroup).delete()
test_session.commit()
await files_lib.refresh_files()
await refresh_files()
assert test_session.query(FileGroup).count() == 2
assert test_session.query(Video).count() == 2

View file

@ -22,7 +22,8 @@ from wrolpi.dates import Seconds
from wrolpi.events import Events
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.downloader import DownloadFrequency
from wrolpi.files.lib import refresh_files, split_file_name_words
from wrolpi.files.lib import split_file_name_words
from wrolpi.files.worker import file_worker
from wrolpi.files.models import FileGroup
from wrolpi.vars import PYTEST, DOCKERIZED
@ -550,8 +551,8 @@ async def remove_outdated_zim_files(path: pathlib.Path = None) -> int:
file.unlink()
deleted_count += 1
# Must refresh synchronously to clean up DB before returning.
await refresh_files(outdated)
# Refresh synchronously to clean up DB before returning.
await file_worker.refresh_sync(list(outdated))
await restart_kiwix()

View file

@ -10,15 +10,14 @@ from modules.zim.models import TagZimEntry, ZimSubscription
from wrolpi import tags, flags
from wrolpi.common import DownloadFileInfo, get_wrolpi_config
from wrolpi.downloader import Download, import_downloads_config, get_download_manager_config
from wrolpi.files import lib as files_lib
from wrolpi.files.models import FileGroup
from wrolpi.test.common import skip_circleci
@pytest.mark.asyncio
async def test_get_zim(async_client, test_session, zim_path_factory):
async def test_get_zim(async_client, test_session, zim_path_factory, refresh_files):
zim_path_factory()
await files_lib.refresh_files()
await refresh_files()
assert lib.get_zim(test_session, 1)
@ -27,9 +26,9 @@ async def test_get_zim(async_client, test_session, zim_path_factory):
@pytest.mark.asyncio
async def test_zim_get_entry(async_client, test_session, zim_path_factory):
async def test_zim_get_entry(async_client, test_session, zim_path_factory, refresh_files):
zim_path_factory()
await files_lib.refresh_files()
await refresh_files()
entry: Entry = lib.get_entry('one', 1)
assert entry.path == 'one'
@ -389,13 +388,13 @@ async def test_zim_subscription_download_import(async_client, test_session):
@pytest.mark.asyncio
async def test_zim_modeler(async_client, test_session, zim_factory):
async def test_zim_modeler(async_client, test_session, zim_factory, refresh_files):
"""Zim modeler sets FileGroup title and a_text."""
zim = zim_factory('the_zim_title.zim')
assert zim.file_group.indexed is False
test_session.commit()
await files_lib.refresh_files()
await refresh_files()
fg: FileGroup = test_session.query(FileGroup).one()
assert fg.indexed is True