diff --git a/wrolpi/collections/api.py b/wrolpi/collections/api.py index ed9d7073..8e497bf7 100644 --- a/wrolpi/collections/api.py +++ b/wrolpi/collections/api.py @@ -10,6 +10,7 @@ from sanic_ext.extensions.openapi import openapi from wrolpi.api_utils import json_response from wrolpi.common import wrol_mode_check +from wrolpi.db import get_db_session from wrolpi.errors import ValidationError from wrolpi.schema import JSONErrorResponse from . import lib, schema @@ -89,21 +90,21 @@ async def create_collection_endpoint(request: Request, body: schema.CollectionCr @wrol_mode_check async def add_collection_item_endpoint(request: Request, collection_id: int, body: schema.AddItemRequest): """Append (or insert at ``position``) a file/zim/url item into the collection.""" - session = request.ctx.session try: - item, created = lib.add_collection_item( - session, collection_id, item_kind=body.item_kind, - file_group_id=body.file_group_id, zim_id=body.zim_id, zim_entry=body.zim_entry, - url=body.url, title=body.title, position=body.position) + # Read-then-write, so the session must begin as a writer (see `get_db_session`). + with get_db_session(commit=True) as session: + item, created = lib.add_collection_item( + session, collection_id, item_kind=body.item_kind, + file_group_id=body.file_group_id, zim_id=body.zim_id, zim_entry=body.zim_entry, + url=body.url, title=body.title, position=body.position) + # 201 when a new item was created; 200 when the item already existed (idempotent add). + status = HTTPStatus.CREATED if created else HTTPStatus.OK + return json_response({'item': item.dict()}, status=status) except UnknownCollection as e: return json_response({'error': str(e)}, status=HTTPStatus.NOT_FOUND) except ValidationError as e: return json_response({'error': str(e)}, status=HTTPStatus.BAD_REQUEST) - # 201 when a new item was created; 200 when the item already existed (idempotent add). - status = HTTPStatus.CREATED if created else HTTPStatus.OK - return json_response({'item': item.dict()}, status=status) - @collection_bp.delete('//items/') @openapi.summary('Remove an item from a collection') @@ -112,9 +113,9 @@ async def add_collection_item_endpoint(request: Request, collection_id: int, bod @wrol_mode_check async def remove_collection_item_endpoint(request: Request, collection_id: int, item_id: int): """Remove a single item by its id and close the ordering gap.""" - session = request.ctx.session try: - removed = lib.remove_collection_item(session, collection_id, item_id) + with get_db_session(commit=True) as session: + removed = lib.remove_collection_item(session, collection_id, item_id) except UnknownCollection as e: return json_response({'error': str(e)}, status=HTTPStatus.NOT_FOUND) @@ -137,15 +138,14 @@ async def remove_collection_item_endpoint(request: Request, collection_id: int, async def reorder_collection_items_endpoint(request: Request, collection_id: int, body: schema.ReorderItemsRequest): """Set the item order from a full list of item ids (used by drag-and-drop).""" - session = request.ctx.session try: - lib.reorder_collection_items(session, collection_id, body.item_ids) + with get_db_session(commit=True) as session: + lib.reorder_collection_items(session, collection_id, body.item_ids) + data = lib.get_collection_with_stats(session, collection_id) except UnknownCollection as e: return json_response({'error': str(e)}, status=HTTPStatus.NOT_FOUND) except ValueError as e: return json_response({'error': str(e)}, status=HTTPStatus.BAD_REQUEST) - - data = lib.get_collection_with_stats(session, collection_id) return json_response({'collection': data}) diff --git a/wrolpi/collections/test/test_playlist_items.py b/wrolpi/collections/test/test_playlist_items.py index 8a1bf0b7..b25f417f 100644 --- a/wrolpi/collections/test/test_playlist_items.py +++ b/wrolpi/collections/test/test_playlist_items.py @@ -156,6 +156,41 @@ async def test_add_file_item(async_client, test_session, test_directory): assert items[0]['file_group']['id'] == fg.id +@pytest.mark.asyncio +async def test_item_write_endpoints_use_write_intent_sessions(async_client, test_session): + """The item write endpoints (add/remove/reorder) each open their session with + `get_db_session(commit=True)` — the deferred `request.ctx.session` reads before its first + write, which SQLite fails instantly on concurrent writes (see `get_db_session`).""" + from unittest import mock + from wrolpi.collections import api as collections_api + from wrolpi.db import get_db_session + + _, response = await async_client.post('/api/collections', json={'name': 'Locks'}) + cid = response.json['collection']['id'] + + commit_kwargs = list() + + def recording_get_db_session(*args, **kwargs): + commit_kwargs.append(kwargs.get('commit', args[0] if args else False)) + return get_db_session(*args, **kwargs) + + with mock.patch.object(collections_api, 'get_db_session', recording_get_db_session): + _, response = await async_client.post(f'/api/collections/{cid}/items', + json={'item_kind': 'url', 'url': '/u/a', 'title': 'a'}) + assert response.status_code == HTTPStatus.CREATED, response.json + item_id = response.json['item']['id'] + + _, response = await async_client.put(f'/api/collections/{cid}/items/order', + json={'item_ids': [item_id]}) + assert response.status_code == HTTPStatus.OK, response.json + + _, response = await async_client.delete(f'/api/collections/{cid}/items/{item_id}') + assert response.status_code == HTTPStatus.NO_CONTENT + + assert len(commit_kwargs) == 3, 'Each item write endpoint must open its own session' + assert all(commit is True for commit in commit_kwargs) + + @pytest.mark.asyncio async def test_reorder_and_remove_items(async_client, test_session): """Items can be reordered by id and removed, with positions kept contiguous.""" diff --git a/wrolpi/common.py b/wrolpi/common.py index c74e7cbb..377afa11 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -639,11 +639,6 @@ class ConfigFile: f' during import: {rel_path}' Events.send_config_save_failed(message) raise RuntimeError(message) - version = self.read_config_file(file).get('version') - if version and version > self.version: - message = f'Refusing to overwrite newer config ({rel_path}): {version} > {self.version}' - Events.send_config_save_failed(message) - raise RuntimeError(message) # Don't overwrite a real config while testing. if PYTEST and not is_tempfile(file): @@ -653,6 +648,13 @@ class ConfigFile: # Only one process can write to a config. with api_app.shared_ctx.config_save_lock: + # The version check reads the file, so it must hold the lock. + if file.exists() and overwrite is False: + version = self.read_config_file(file).get('version') + if version and version > self.version: + message = f'Refusing to overwrite newer config ({rel_path}): {version} > {self.version}' + Events.send_config_save_failed(message) + raise RuntimeError(message) try: # Config directory may not exist (parents=True for nested file_names like inventory/catalog.yaml). if not file.parent.is_dir(): @@ -788,7 +790,8 @@ class ConfigFile: def write_config_data(config: dict, config_file: pathlib.Path, width: int = 90): - """Write a config dict to a YAML file. Decimals are converted to str; all other Python objects are rejected. + """Write a config dict to a YAML file atomically (readers never see a truncated config). + Decimals are converted to str; all other Python objects are rejected. Shared by `ConfigFile` and `MultiFileConfig` so both serialize configs identically (Decimal-safe, fsync'd).""" @@ -798,14 +801,26 @@ def write_config_data(config: dict, config_file: pathlib.Path, width: int = 90): _ConfigDumper.add_representer(Decimal, lambda dumper, data: dumper.represent_str(str(data))) - with config_file.open('wt') as fh: - try: - yaml.dump(config, fh, Dumper=_ConfigDumper, width=width, sort_keys=True) - except yaml.representer.RepresenterError as e: - raise ValueError(f'Config contains a Python object that cannot be serialized: {e}') from e - # Wait for data to be written before releasing lock. - fh.flush() - os.fsync(fh.fileno()) + # Same directory as the config so the rename is atomic. + fd, temporary_path = tempfile.mkstemp(dir=config_file.parent, prefix=f'{config_file.name}.', suffix='.tmp') + try: + # The rename keeps the temporary file's 0600, so give it the config's mode. + mode = config_file.stat().st_mode & 0o777 if config_file.exists() else 0o644 + os.chmod(temporary_path, mode) + with os.fdopen(fd, 'wt') as fh: + fd = None # The file object owns the descriptor now. + try: + yaml.dump(config, fh, Dumper=_ConfigDumper, width=width, sort_keys=True) + except yaml.representer.RepresenterError as e: + raise ValueError(f'Config contains a Python object that cannot be serialized: {e}') from e + fh.flush() + os.fsync(fh.fileno()) + os.replace(temporary_path, config_file) + except BaseException: + if fd is not None: + os.close(fd) + pathlib.Path(temporary_path).unlink(missing_ok=True) + raise def read_config_data(file: pathlib.Path) -> dict: diff --git a/wrolpi/test/test_common.py b/wrolpi/test/test_common.py index a6839af6..23f75197 100644 --- a/wrolpi/test/test_common.py +++ b/wrolpi/test/test_common.py @@ -1076,6 +1076,69 @@ async def test_config_valid(async_client, test_wrolpi_config): assert config.is_valid() is True +@pytest.mark.asyncio +async def test_write_config_data_failure_preserves_existing_file(async_client, test_wrolpi_config): + """A failed config write must leave the existing config file untouched, and no write may leave + a temporary file behind.""" + + def temporary_leftovers() -> list: + return [i for i in test_wrolpi_config.parent.iterdir() + if i.name.startswith(test_wrolpi_config.name) and i.name != test_wrolpi_config.name] + + test_wrolpi_config.write_text('version: 5\nwrol_mode: true\n') + + # `object()` cannot be serialized; the key sorts last so YAML would emit partial output first. + with pytest.raises(ValueError): + common.write_config_data({'version': 6, 'zzz': object()}, test_wrolpi_config) + + # The original file survives the failed write, and no temporary file is left behind. + assert common.read_config_data(test_wrolpi_config) == {'version': 5, 'wrol_mode': True} + assert not temporary_leftovers() + + # A successful write replaces the contents and leaves no temporary file behind. + common.write_config_data({'version': 6}, test_wrolpi_config) + assert common.read_config_data(test_wrolpi_config) == {'version': 6} + assert not temporary_leftovers() + + +@pytest.mark.asyncio +async def test_save_version_check_runs_under_config_save_lock(async_client, test_wrolpi_config): + """`ConfigFile.save` must read the config file for its version check only while holding + `config_save_lock`, otherwise it can read a config another process is writing.""" + from wrolpi.api_utils import api_app + + config = get_wrolpi_config() + config.dump_config() + + class RecordingLock: + def __init__(self, lock): + self.lock = lock + self.held = False + + def __enter__(self): + self.lock.__enter__() + self.held = True + + def __exit__(self, *args): + self.held = False + return self.lock.__exit__(*args) + + recording_lock = RecordingLock(api_app.shared_ctx.config_save_lock) + lock_held_during_read = list() + real_read_config_file = config.read_config_file + + def recording_read_config_file(*args, **kwargs): + lock_held_during_read.append(recording_lock.held) + return real_read_config_file(*args, **kwargs) + + with mock.patch.object(api_app.shared_ctx, 'config_save_lock', recording_lock), \ + mock.patch.object(config, 'read_config_file', recording_read_config_file): + config.dump_config() + + assert lock_held_during_read, 'The version check never read the config file' + assert all(lock_held_during_read), 'The config file was read without holding config_save_lock' + + @pytest.mark.parametrize('name,expected_name', [ ('foo', 'foo'), (pathlib.Path('foo'), pathlib.Path('foo')),