From a0450953d56009251c72ed8a05d8690def117a20 Mon Sep 17 00:00:00 2001 From: "marcel.kocisek" Date: Thu, 11 Sep 2025 18:06:27 +0200 Subject: [PATCH 1/8] add max of 100 files max 10GB of non versioned files max 5GB of versioned files --- mergin/client_push.py | 45 +++++++++++++++-------- mergin/common.py | 10 +++++- mergin/editor.py | 2 +- mergin/local_changes.py | 39 +++++++++++++++++++- mergin/merginproject.py | 14 ++++---- mergin/test/test_local_changes.py | 59 +++++++++++++++++++++++++++++++ 6 files changed, 145 insertions(+), 24 deletions(-) diff --git a/mergin/client_push.py b/mergin/client_push.py index 2400c959..188167db 100644 --- a/mergin/client_push.py +++ b/mergin/client_push.py @@ -24,7 +24,14 @@ from .local_changes import LocalChange, LocalChanges -from .common import UPLOAD_CHUNK_ATTEMPT_WAIT, UPLOAD_CHUNK_ATTEMPTS, UPLOAD_CHUNK_SIZE, ClientError, ErrorCode +from .common import ( + MAX_UPLOAD_VERSIONED_SIZE, + UPLOAD_CHUNK_ATTEMPT_WAIT, + UPLOAD_CHUNK_ATTEMPTS, + UPLOAD_CHUNK_SIZE, + MAX_UPLOAD_MEDIA_SIZE, + ClientError, +) from .merginproject import MerginProject from .editor import filter_changes from .utils import get_data_checksum @@ -296,7 +303,7 @@ def push_project_async(mc, directory) -> Optional[UploadJob]: mp.log.info(f"--- push {project_path} - nothing to do") return - mp.log.debug("push changes:\n" + pprint.pformat(changes)) + mp.log.debug("push changes:\n" + pprint.pformat(asdict(changes))) tmp_dir = tempfile.TemporaryDirectory(prefix="python-api-client-") # If there are any versioned files (aka .gpkg) that are not updated through a diff, @@ -304,20 +311,15 @@ def push_project_async(mc, directory) -> Optional[UploadJob]: # That's because if there are pending transactions, checkpointing or switching from WAL mode # won't work, and we would end up with some changes left in -wal file which do not get # uploaded. The temporary copy using geodiff uses sqlite backup API and should copy everything. - for f in changes["updated"]: - if mp.is_versioned_file(f["path"]) and "diff" not in f: + for f in changes.updated: + if mp.is_versioned_file(f.path) and not f.diff: mp.copy_versioned_file_for_upload(f, tmp_dir.name) - for f in changes["added"]: - if mp.is_versioned_file(f["path"]): + for f in changes.added: + if mp.is_versioned_file(f.path): mp.copy_versioned_file_for_upload(f, tmp_dir.name) - local_changes = LocalChanges( - added=[LocalChange(**change) for change in changes["added"]], - updated=[LocalChange(**change) for change in changes["updated"]], - removed=[LocalChange(**change) for change in changes["removed"]], - ) - job = create_upload_job(mc, mp, local_changes, tmp_dir) + job = create_upload_job(mc, mp, changes, tmp_dir) return job @@ -471,7 +473,7 @@ def remove_diff_files(job: UploadJob) -> None: os.remove(diff_file) -def get_push_changes_batch(mc, mp: MerginProject) -> Tuple[dict, int]: +def get_push_changes_batch(mc, mp: MerginProject) -> Tuple[LocalChanges, int]: """ Get changes that need to be pushed to the server. """ @@ -479,4 +481,19 @@ def get_push_changes_batch(mc, mp: MerginProject) -> Tuple[dict, int]: project_role = mp.project_role() changes = filter_changes(mc, project_role, changes) - return changes, sum(len(v) for v in changes.values()) + local_changes = LocalChanges( + added=[LocalChange(**change) for change in changes["added"]], + updated=[LocalChange(**change) for change in changes["updated"]], + removed=[LocalChange(**change) for change in changes["removed"]], + ) + if local_changes.get_media_upload_size() > MAX_UPLOAD_MEDIA_SIZE: + raise ClientError( + f"Total size of media files to upload exceeds the maximum allowed size of {MAX_UPLOAD_MEDIA_SIZE / (1024**3)} GiB." + ) + + if local_changes.get_gpgk_upload_size() > MAX_UPLOAD_VERSIONED_SIZE: + raise ClientError( + f"Total size of GPKG files to upload exceeds the maximum allowed size of {MAX_UPLOAD_VERSIONED_SIZE / (1024**3)} GiB." + ) + + return local_changes, sum(len(v) for v in changes.values()) diff --git a/mergin/common.py b/mergin/common.py index 25b58c48..bc4c60ce 100644 --- a/mergin/common.py +++ b/mergin/common.py @@ -24,6 +24,12 @@ # seconds to wait between sync callback calls SYNC_CALLBACK_WAIT = 0.01 +# maximum size of media files able to upload in one push (in bytes) +MAX_UPLOAD_MEDIA_SIZE = 10 * (1024**3) + +# maximum size of GPKG files able to upload in one push (in bytes) +MAX_UPLOAD_VERSIONED_SIZE = 5 * (1024**3) + # default URL for submitting logs MERGIN_DEFAULT_LOGS_URL = "https://g4pfq226j0.execute-api.eu-west-1.amazonaws.com/mergin_client_log_submit" @@ -39,7 +45,9 @@ class ErrorCode(Enum): class ClientError(Exception): - def __init__(self, detail: str, url=None, server_code=None, server_response=None, http_error=None, http_method=None): + def __init__( + self, detail: str, url=None, server_code=None, server_response=None, http_error=None, http_method=None + ): self.detail = detail self.url = url self.http_error = http_error diff --git a/mergin/editor.py b/mergin/editor.py index b1dac863..bb8f1d18 100644 --- a/mergin/editor.py +++ b/mergin/editor.py @@ -1,7 +1,7 @@ from itertools import filterfalse from typing import Callable, Dict, List -from .utils import is_mergin_config, is_qgis_file, is_versioned_file +from .utils import is_qgis_file EDITOR_ROLE_NAME = "editor" diff --git a/mergin/local_changes.py b/mergin/local_changes.py index 511960cd..a73be299 100644 --- a/mergin/local_changes.py +++ b/mergin/local_changes.py @@ -1,6 +1,10 @@ from dataclasses import dataclass, field from datetime import datetime -from typing import Dict, Optional, List, Tuple +from typing import Optional, List, Tuple + +from .utils import is_versioned_file + +MAX_UPLOAD_CHANGES = 100 @dataclass @@ -55,6 +59,18 @@ class LocalChanges: updated: List[LocalChange] = field(default_factory=list) removed: List[LocalChange] = field(default_factory=list) + def __post_init__(self): + """ + Enforce a limit of changes combined from `added` and `updated`. + """ + total_changes = len(self.get_upload_changes()) + if total_changes > MAX_UPLOAD_CHANGES: + # Calculate how many changes to keep from `added` and `updated` + added_limit = min(len(self.added), MAX_UPLOAD_CHANGES) + updated_limit = MAX_UPLOAD_CHANGES - added_limit + self.added = self.added[:added_limit] + self.updated = self.updated[:updated_limit] + def to_server_payload(self) -> dict: return { "added": [change.to_server_data() for change in self.added], @@ -96,3 +112,24 @@ def update_chunks(self, server_chunks: List[Tuple[str, str]]) -> None: for change in self.updated: change.chunks = self._map_unique_chunks(change.chunks, server_chunks) + + def get_media_upload_size(self) -> int: + """ + Calculate the total size of media files in added and updated changes. + """ + total_size = 0 + for change in self.get_upload_changes(): + if not is_versioned_file(change.path): + total_size += change.size + return total_size + + def get_gpgk_upload_size(self) -> int: + """ + Calculate the total size of gpgk files in added and updated changes. + Do not calculate diffs (only new or overwriten files). + """ + total_size = 0 + for change in self.get_upload_changes(): + if is_versioned_file(change.path) and not change.diff: + total_size += change.size + return total_size diff --git a/mergin/merginproject.py b/mergin/merginproject.py index 72b1449c..61b417e5 100644 --- a/mergin/merginproject.py +++ b/mergin/merginproject.py @@ -21,7 +21,7 @@ conflicted_copy_file_name, edit_conflict_file_name, ) - +from .local_changes import LocalChange this_dir = os.path.dirname(os.path.realpath(__file__)) @@ -470,20 +470,20 @@ def get_push_changes(self): changes["updated"] = [f for f in changes["updated"] if f not in not_updated] return changes - def copy_versioned_file_for_upload(self, f, tmp_dir): + def copy_versioned_file_for_upload(self, f: LocalChange, tmp_dir: str) -> str: """ Make a temporary copy of the versioned file using geodiff, to make sure that we have full content in a single file (nothing left in WAL journal) """ - path = f["path"] + path = f.path self.log.info("Making a temporary copy (full upload): " + path) tmp_file = os.path.join(tmp_dir, path) os.makedirs(os.path.dirname(tmp_file), exist_ok=True) self.geodiff.make_copy_sqlite(self.fpath(path), tmp_file) - f["size"] = os.path.getsize(tmp_file) - f["checksum"] = generate_checksum(tmp_file) - f["chunks"] = [str(uuid.uuid4()) for i in range(math.ceil(f["size"] / UPLOAD_CHUNK_SIZE))] - f["upload_file"] = tmp_file + f.size = os.path.getsize(tmp_file) + f.checksum = generate_checksum(tmp_file) + f.chunks = [str(uuid.uuid4()) for i in range(math.ceil(f.size / UPLOAD_CHUNK_SIZE))] + f.upload_file = tmp_file return tmp_file def get_list_of_push_changes(self, push_changes): diff --git a/mergin/test/test_local_changes.py b/mergin/test/test_local_changes.py index 6fe18388..8c263c7d 100644 --- a/mergin/test/test_local_changes.py +++ b/mergin/test/test_local_changes.py @@ -118,3 +118,62 @@ def test_local_changes_get_upload_changes(): assert len(upload_changes) == 2 # Only added and updated should be included assert upload_changes[0].path == "file1.txt" # First change is from added assert upload_changes[1].path == "file2.txt" # Second change is from updated + + +def test_local_changes_get_media_upload_size(): + """Test the get_media_upload_size method of LocalChanges.""" + # Create sample LocalChange instances + added = [ + LocalChange(path="file1.txt", checksum="abc123", size=1024, mtime=datetime.now()), + LocalChange(path="file2.jpg", checksum="xyz789", size=2048, mtime=datetime.now()), + ] + updated = [ + LocalChange(path="file3.mp4", checksum="lmn456", size=5120, mtime=datetime.now()), + LocalChange(path="file4.gpkg", checksum="opq123", size=1024, mtime=datetime.now()), + ] + + # Initialize LocalChanges + local_changes = LocalChanges(added=added, updated=updated) + + # Call get_media_upload_size + media_size = local_changes.get_media_upload_size() + + # Assertions + assert media_size == 8192 # Only non-versioned files (txt, jpg, mp4) are included + + +def test_local_changes_get_gpgk_upload_size(): + """Test the get_gpgk_upload_size method of LocalChanges.""" + # Create sample LocalChange instances + added = [ + LocalChange(path="file1.gpkg", checksum="abc123", size=1024, mtime=datetime.now()), + LocalChange(path="file2.gpkg", checksum="xyz789", size=2048, mtime=datetime.now(), diff={"path": "diff1"}), + ] + updated = [ + LocalChange(path="file3.gpkg", checksum="lmn456", size=5120, mtime=datetime.now()), + LocalChange(path="file4.txt", checksum="opq123", size=1024, mtime=datetime.now()), + ] + + # Initialize LocalChanges + local_changes = LocalChanges(added=added, updated=updated) + + # Call get_gpgk_upload_size + gpkg_size = local_changes.get_gpgk_upload_size() + + # Assertions + assert gpkg_size == 6144 # Only GPKG files without diffs are included + + +def test_local_changes_post_init(): + """Test the __post_init__ method of LocalChanges.""" + # Create more than MAX_UPLOAD_CHANGES changes + added = [LocalChange(path=f"file{i}.txt", checksum="abc123", size=1024, mtime=datetime.now()) for i in range(80)] + updated = [LocalChange(path=f"file{i}.txt", checksum="xyz789", size=2048, mtime=datetime.now()) for i in range(21)] + + # Initialize LocalChanges + local_changes = LocalChanges(added=added, updated=updated) + + # Assertions + assert len(local_changes.added) == 80 # All 80 added changes are included + assert len(local_changes.updated) == 20 # Only 20 updated changes are included to respect the limit + assert len(local_changes.added) + len(local_changes.updated) == 100 # Total is limited to MAX_UPLOAD_CHANGES From 50b62244b53c33e4fdc221f452c7e80069c5ffcd Mon Sep 17 00:00:00 2001 From: "marcel.kocisek" Date: Thu, 11 Sep 2025 18:09:05 +0200 Subject: [PATCH 2/8] black --- mergin/test/test_common.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/mergin/test/test_common.py b/mergin/test/test_common.py index d86229e1..7a1dbbdf 100644 --- a/mergin/test/test_common.py +++ b/mergin/test/test_common.py @@ -1,5 +1,6 @@ from ..common import ClientError, ErrorCode + def test_client_error_is_blocked_sync(): """Test the is_blocked_sync method of ClientError.""" error = ClientError(detail="", server_code=None) @@ -12,6 +13,7 @@ def test_client_error_is_blocked_sync(): error.server_code = ErrorCode.ProjectVersionExists.value assert error.is_blocking_sync() is True + def test_client_error_is_rate_limit(): """Test the is_rate_limit method of ClientError.""" error = ClientError(detail="", http_error=None) @@ -21,6 +23,7 @@ def test_client_error_is_rate_limit(): error.http_error = 429 assert error.is_rate_limit() is True + def test_client_error_is_retryable_sync(): """Test the is_retryable_sync method of ClientError.""" error = ClientError(detail="", server_code=None, http_error=None) @@ -43,4 +46,4 @@ def test_client_error_is_retryable_sync(): error.http_error = 500 assert error.is_retryable_sync() is False error.http_error = 429 - assert error.is_retryable_sync() is True \ No newline at end of file + assert error.is_retryable_sync() is True From 0fc2a9eff0cf1781aa4fdbd5ef5255e36306e0c1 Mon Sep 17 00:00:00 2001 From: "marcel.kocisek" Date: Fri, 12 Sep 2025 10:02:30 +0200 Subject: [PATCH 3/8] Find just one file over limit in transaction --- mergin/client_push.py | 11 +++-- mergin/common.py | 4 +- mergin/local_changes.py | 25 +++++----- mergin/test/test_client.py | 18 +++++++ mergin/test/test_local_changes.py | 79 +++++++++++++++++++++---------- 5 files changed, 94 insertions(+), 43 deletions(-) diff --git a/mergin/client_push.py b/mergin/client_push.py index 188167db..bfe8132b 100644 --- a/mergin/client_push.py +++ b/mergin/client_push.py @@ -486,14 +486,17 @@ def get_push_changes_batch(mc, mp: MerginProject) -> Tuple[LocalChanges, int]: updated=[LocalChange(**change) for change in changes["updated"]], removed=[LocalChange(**change) for change in changes["removed"]], ) - if local_changes.get_media_upload_size() > MAX_UPLOAD_MEDIA_SIZE: + + over_limit_media = local_changes.get_media_upload_over_size(MAX_UPLOAD_MEDIA_SIZE) + if over_limit_media: raise ClientError( - f"Total size of media files to upload exceeds the maximum allowed size of {MAX_UPLOAD_MEDIA_SIZE / (1024**3)} GiB." + f"File {over_limit_media.path} to upload exceeds the maximum allowed size of {MAX_UPLOAD_MEDIA_SIZE / (1024**3)} GB." ) - if local_changes.get_gpgk_upload_size() > MAX_UPLOAD_VERSIONED_SIZE: + over_limit_gpkg = local_changes.get_gpgk_upload_over_size(MAX_UPLOAD_VERSIONED_SIZE) + if over_limit_gpkg: raise ClientError( - f"Total size of GPKG files to upload exceeds the maximum allowed size of {MAX_UPLOAD_VERSIONED_SIZE / (1024**3)} GiB." + f"Geopackage {over_limit_gpkg.path} to upload exceeds the maximum allowed size of {MAX_UPLOAD_VERSIONED_SIZE / (1024**3)} GB." ) return local_changes, sum(len(v) for v in changes.values()) diff --git a/mergin/common.py b/mergin/common.py index bc4c60ce..25df4f4d 100644 --- a/mergin/common.py +++ b/mergin/common.py @@ -24,10 +24,10 @@ # seconds to wait between sync callback calls SYNC_CALLBACK_WAIT = 0.01 -# maximum size of media files able to upload in one push (in bytes) +# maximum size of media file able to upload in one push (in bytes) MAX_UPLOAD_MEDIA_SIZE = 10 * (1024**3) -# maximum size of GPKG files able to upload in one push (in bytes) +# maximum size of GPKG file able to upload in one push (in bytes) MAX_UPLOAD_VERSIONED_SIZE = 5 * (1024**3) # default URL for submitting logs diff --git a/mergin/local_changes.py b/mergin/local_changes.py index a73be299..06c5872d 100644 --- a/mergin/local_changes.py +++ b/mergin/local_changes.py @@ -113,23 +113,22 @@ def update_chunks(self, server_chunks: List[Tuple[str, str]]) -> None: for change in self.updated: change.chunks = self._map_unique_chunks(change.chunks, server_chunks) - def get_media_upload_size(self) -> int: + def get_media_upload_over_size(self, size_limit: int) -> Optional[LocalChange]: """ - Calculate the total size of media files in added and updated changes. + Find the first media file in added and updated changes that exceeds the size limit. + :return: The first LocalChange that exceeds the size limit, or None if no such file exists. """ - total_size = 0 for change in self.get_upload_changes(): - if not is_versioned_file(change.path): - total_size += change.size - return total_size + if not is_versioned_file(change.path) and change.size > size_limit: + return change - def get_gpgk_upload_size(self) -> int: + def get_gpgk_upload_over_size(self, size_limit: int) -> Optional[LocalChange]: """ - Calculate the total size of gpgk files in added and updated changes. - Do not calculate diffs (only new or overwriten files). + Find the first GPKG file in added and updated changes that exceeds the size limit. + Do not include diffs (only new or overwritten files). + :param size_limit: The size limit in bytes. + :return: The first LocalChange that exceeds the size limit, or None if no such file exists. """ - total_size = 0 for change in self.get_upload_changes(): - if is_versioned_file(change.path) and not change.diff: - total_size += change.size - return total_size + if is_versioned_file(change.path) and not change.diff and change.size > size_limit: + return change diff --git a/mergin/test/test_client.py b/mergin/test/test_client.py index fdd988a3..a529d027 100644 --- a/mergin/test/test_client.py +++ b/mergin/test/test_client.py @@ -3211,3 +3211,21 @@ def test_client_project_sync_retry(mc): with pytest.raises(ClientError): mc.sync_project(project_dir) assert mock_push_project_async.call_count == 2 + +def test_push_file_limits(mc): + test_project = "test_push_file_limits" + project = API_USER + "/" + test_project + project_dir = os.path.join(TMP_DIR, test_project) + cleanup(mc, project, [project_dir]) + mc.create_project(test_project) + mc.download_project(project, project_dir) + shutil.copy(os.path.join(TEST_DATA_DIR, "base.gpkg"), project_dir) + # setting to some minimal value to mock limit hit + with patch("mergin.client_push.MAX_UPLOAD_VERSIONED_SIZE", 1): + with pytest.raises(ClientError, match=f"base.gpkg to upload exceeds the maximum allowed size of {1/1024**3}"): + mc.push_project(project_dir) + + shutil.copy(os.path.join(TEST_DATA_DIR, "test.txt"), project_dir) + with patch("mergin.client_push.MAX_UPLOAD_MEDIA_SIZE", 1): + with pytest.raises(ClientError, match=f"test.txt to upload exceeds the maximum allowed size of {1/1024**3}"): + mc.push_project(project_dir) diff --git a/mergin/test/test_local_changes.py b/mergin/test/test_local_changes.py index 8c263c7d..dceab27a 100644 --- a/mergin/test/test_local_changes.py +++ b/mergin/test/test_local_changes.py @@ -1,6 +1,6 @@ from datetime import datetime -from ..local_changes import LocalChange, LocalChanges +from ..local_changes import LocalChange, LocalChanges, MAX_UPLOAD_CHANGES def test_local_changes_from_dict(): @@ -120,60 +120,91 @@ def test_local_changes_get_upload_changes(): assert upload_changes[1].path == "file2.txt" # Second change is from updated -def test_local_changes_get_media_upload_size(): - """Test the get_media_upload_size method of LocalChanges.""" +def test_local_changes_get_media_upload_over_size(): + """Test the get_media_upload_file method of LocalChanges.""" + # Define constants + SIZE_LIMIT_MB = 10 + SIZE_LIMIT_BYTES = SIZE_LIMIT_MB * 1024 * 1024 + SMALL_FILE_SIZE = 1024 + LARGE_FILE_SIZE = 15 * 1024 * 1024 + # Create sample LocalChange instances added = [ - LocalChange(path="file1.txt", checksum="abc123", size=1024, mtime=datetime.now()), - LocalChange(path="file2.jpg", checksum="xyz789", size=2048, mtime=datetime.now()), + LocalChange(path="file1.txt", checksum="abc123", size=SMALL_FILE_SIZE, mtime=datetime.now()), + LocalChange(path="file2.jpg", checksum="xyz789", size=LARGE_FILE_SIZE, mtime=datetime.now()), # Over limit ] updated = [ - LocalChange(path="file3.mp4", checksum="lmn456", size=5120, mtime=datetime.now()), - LocalChange(path="file4.gpkg", checksum="opq123", size=1024, mtime=datetime.now()), + LocalChange(path="file3.mp4", checksum="lmn456", size=5 * 1024 * 1024, mtime=datetime.now()), + LocalChange(path="file4.gpkg", checksum="opq123", size=SMALL_FILE_SIZE, mtime=datetime.now()), ] # Initialize LocalChanges local_changes = LocalChanges(added=added, updated=updated) - # Call get_media_upload_size - media_size = local_changes.get_media_upload_size() + # Call get_media_upload_file with a size limit + media_file = local_changes.get_media_upload_over_size(SIZE_LIMIT_BYTES) # Assertions - assert media_size == 8192 # Only non-versioned files (txt, jpg, mp4) are included + assert media_file is not None + assert media_file.path == "file2.jpg" # The first file over the limit + assert media_file.size == LARGE_FILE_SIZE + +def test_local_changes_get_gpgk_upload_over_size(): + """Test the get_gpgk_upload_file method of LocalChanges.""" + # Define constants + SIZE_LIMIT_MB = 10 + SIZE_LIMIT_BYTES = SIZE_LIMIT_MB * 1024 * 1024 + SMALL_FILE_SIZE = 1024 + LARGE_FILE_SIZE = 15 * 1024 * 1024 -def test_local_changes_get_gpgk_upload_size(): - """Test the get_gpgk_upload_size method of LocalChanges.""" # Create sample LocalChange instances added = [ - LocalChange(path="file1.gpkg", checksum="abc123", size=1024, mtime=datetime.now()), - LocalChange(path="file2.gpkg", checksum="xyz789", size=2048, mtime=datetime.now(), diff={"path": "diff1"}), + LocalChange(path="file1.gpkg", checksum="abc123", size=SMALL_FILE_SIZE, mtime=datetime.now()), + LocalChange( + path="file2.gpkg", checksum="xyz789", size=LARGE_FILE_SIZE, mtime=datetime.now(), diff=None + ), # Over limit ] updated = [ - LocalChange(path="file3.gpkg", checksum="lmn456", size=5120, mtime=datetime.now()), - LocalChange(path="file4.txt", checksum="opq123", size=1024, mtime=datetime.now()), + LocalChange(path="file3.gpkg", checksum="lmn456", size=5 * 1024 * 1024, mtime=datetime.now()), + LocalChange(path="file4.txt", checksum="opq123", size=SMALL_FILE_SIZE, mtime=datetime.now()), ] # Initialize LocalChanges local_changes = LocalChanges(added=added, updated=updated) - # Call get_gpgk_upload_size - gpkg_size = local_changes.get_gpgk_upload_size() + # Call get_gpgk_upload_file with a size limit + gpkg_file = local_changes.get_gpgk_upload_over_size(SIZE_LIMIT_BYTES) # Assertions - assert gpkg_size == 6144 # Only GPKG files without diffs are included + assert gpkg_file is not None + assert gpkg_file.path == "file2.gpkg" # The first GPKG file over the limit + assert gpkg_file.size == LARGE_FILE_SIZE + assert gpkg_file.diff is None # Ensure it doesn't include diffs def test_local_changes_post_init(): """Test the __post_init__ method of LocalChanges.""" + # Define constants + ADDED_COUNT = 80 + UPDATED_COUNT = 21 + SMALL_FILE_SIZE = 1024 + LARGE_FILE_SIZE = 2048 + # Create more than MAX_UPLOAD_CHANGES changes - added = [LocalChange(path=f"file{i}.txt", checksum="abc123", size=1024, mtime=datetime.now()) for i in range(80)] - updated = [LocalChange(path=f"file{i}.txt", checksum="xyz789", size=2048, mtime=datetime.now()) for i in range(21)] + added = [ + LocalChange(path=f"file{i}.txt", checksum="abc123", size=SMALL_FILE_SIZE, mtime=datetime.now()) + for i in range(ADDED_COUNT) + ] + updated = [ + LocalChange(path=f"file{i}.txt", checksum="xyz789", size=LARGE_FILE_SIZE, mtime=datetime.now()) + for i in range(UPDATED_COUNT) + ] # Initialize LocalChanges local_changes = LocalChanges(added=added, updated=updated) # Assertions - assert len(local_changes.added) == 80 # All 80 added changes are included - assert len(local_changes.updated) == 20 # Only 20 updated changes are included to respect the limit - assert len(local_changes.added) + len(local_changes.updated) == 100 # Total is limited to MAX_UPLOAD_CHANGES + assert len(local_changes.added) == ADDED_COUNT # All added changes are included + assert len(local_changes.updated) == MAX_UPLOAD_CHANGES - ADDED_COUNT # Only enough updated changes are included + assert len(local_changes.added) + len(local_changes.updated) == MAX_UPLOAD_CHANGES # Total is limited From 607e148e997b4fefef7460c62453b9b7a1caa8cd Mon Sep 17 00:00:00 2001 From: "marcel.kocisek" Date: Fri, 12 Sep 2025 10:05:54 +0200 Subject: [PATCH 4/8] black swan --- mergin/test/test_client.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mergin/test/test_client.py b/mergin/test/test_client.py index a529d027..4f49d090 100644 --- a/mergin/test/test_client.py +++ b/mergin/test/test_client.py @@ -3212,6 +3212,7 @@ def test_client_project_sync_retry(mc): mc.sync_project(project_dir) assert mock_push_project_async.call_count == 2 + def test_push_file_limits(mc): test_project = "test_push_file_limits" project = API_USER + "/" + test_project @@ -3224,7 +3225,7 @@ def test_push_file_limits(mc): with patch("mergin.client_push.MAX_UPLOAD_VERSIONED_SIZE", 1): with pytest.raises(ClientError, match=f"base.gpkg to upload exceeds the maximum allowed size of {1/1024**3}"): mc.push_project(project_dir) - + shutil.copy(os.path.join(TEST_DATA_DIR, "test.txt"), project_dir) with patch("mergin.client_push.MAX_UPLOAD_MEDIA_SIZE", 1): with pytest.raises(ClientError, match=f"test.txt to upload exceeds the maximum allowed size of {1/1024**3}"): From 3041e750fb3dc218f9c39c7dc0ea7bc31a4b40da Mon Sep 17 00:00:00 2001 From: "marcel.kocisek" Date: Tue, 16 Sep 2025 14:26:45 +0200 Subject: [PATCH 5/8] Move validation to post_init - change version of python in tests --- .github/workflows/autotests.yml | 2 +- mergin/client_push.py | 24 +++++---------- mergin/local_changes.py | 45 +++++++++++++++------------- mergin/test/test_client.py | 8 ++--- mergin/test/test_local_changes.py | 50 ++++++++++++++++--------------- 5 files changed, 63 insertions(+), 66 deletions(-) diff --git a/.github/workflows/autotests.yml b/.github/workflows/autotests.yml index fc658a58..8848e103 100644 --- a/.github/workflows/autotests.yml +++ b/.github/workflows/autotests.yml @@ -19,7 +19,7 @@ jobs: - uses: actions/setup-python@v2 with: - python-version: '3.x' + python-version: '3.8' - name: Install python package dependencies run: | diff --git a/mergin/client_push.py b/mergin/client_push.py index bfe8132b..75ab0659 100644 --- a/mergin/client_push.py +++ b/mergin/client_push.py @@ -22,7 +22,7 @@ import time from typing import List, Tuple, Optional, ByteString -from .local_changes import LocalChange, LocalChanges +from .local_changes import ChangesValidationError, LocalChange, LocalChanges from .common import ( MAX_UPLOAD_VERSIONED_SIZE, @@ -481,22 +481,14 @@ def get_push_changes_batch(mc, mp: MerginProject) -> Tuple[LocalChanges, int]: project_role = mp.project_role() changes = filter_changes(mc, project_role, changes) - local_changes = LocalChanges( - added=[LocalChange(**change) for change in changes["added"]], - updated=[LocalChange(**change) for change in changes["updated"]], - removed=[LocalChange(**change) for change in changes["removed"]], - ) - - over_limit_media = local_changes.get_media_upload_over_size(MAX_UPLOAD_MEDIA_SIZE) - if over_limit_media: - raise ClientError( - f"File {over_limit_media.path} to upload exceeds the maximum allowed size of {MAX_UPLOAD_MEDIA_SIZE / (1024**3)} GB." + try: + local_changes = LocalChanges( + added=[LocalChange(**change) for change in changes["added"]], + updated=[LocalChange(**change) for change in changes["updated"]], + removed=[LocalChange(**change) for change in changes["removed"]], ) - - over_limit_gpkg = local_changes.get_gpgk_upload_over_size(MAX_UPLOAD_VERSIONED_SIZE) - if over_limit_gpkg: + except ChangesValidationError as e: raise ClientError( - f"Geopackage {over_limit_gpkg.path} to upload exceeds the maximum allowed size of {MAX_UPLOAD_VERSIONED_SIZE / (1024**3)} GB." + f"Some files exceeded maximum upload size. Files: {', '.join([c.path for c in e.invalid_changes])}. Maximum size for media files is {e.max_media_upload_size / (1024**3)} GB and for geopackage files {e.max_versioned_upload_size / (1024**3)} GB." ) - return local_changes, sum(len(v) for v in changes.values()) diff --git a/mergin/local_changes.py b/mergin/local_changes.py index 06c5872d..6a7e8ac4 100644 --- a/mergin/local_changes.py +++ b/mergin/local_changes.py @@ -3,10 +3,20 @@ from typing import Optional, List, Tuple from .utils import is_versioned_file +from .common import MAX_UPLOAD_MEDIA_SIZE, MAX_UPLOAD_VERSIONED_SIZE MAX_UPLOAD_CHANGES = 100 +# The custom exception +class ChangesValidationError(Exception): + def __init__(self, message, invalid_changes=[], max_media_upload_size=None, max_versioned_upload_size=None): + super().__init__(message) + self.invalid_changes = invalid_changes if invalid_changes is not None else [] + self.max_media_upload_size = max_media_upload_size + self.max_versioned_upload_size = max_versioned_upload_size + + @dataclass class BaseLocalChange: path: str @@ -63,7 +73,20 @@ def __post_init__(self): """ Enforce a limit of changes combined from `added` and `updated`. """ - total_changes = len(self.get_upload_changes()) + upload_changes = self.get_upload_changes() + total_changes = len(upload_changes) + oversize_changes = [] + for change in upload_changes: + if not is_versioned_file(change.path) and change.size > MAX_UPLOAD_MEDIA_SIZE: + oversize_changes.append(change) + elif not change.diff and change.size > MAX_UPLOAD_VERSIONED_SIZE: + oversize_changes.append(change) + if oversize_changes: + error = ChangesValidationError("Some files exceed the maximum upload size", oversize_changes) + error.max_media_upload_size = MAX_UPLOAD_MEDIA_SIZE + error.max_versioned_upload_size = MAX_UPLOAD_VERSIONED_SIZE + raise error + if total_changes > MAX_UPLOAD_CHANGES: # Calculate how many changes to keep from `added` and `updated` added_limit = min(len(self.added), MAX_UPLOAD_CHANGES) @@ -112,23 +135,3 @@ def update_chunks(self, server_chunks: List[Tuple[str, str]]) -> None: for change in self.updated: change.chunks = self._map_unique_chunks(change.chunks, server_chunks) - - def get_media_upload_over_size(self, size_limit: int) -> Optional[LocalChange]: - """ - Find the first media file in added and updated changes that exceeds the size limit. - :return: The first LocalChange that exceeds the size limit, or None if no such file exists. - """ - for change in self.get_upload_changes(): - if not is_versioned_file(change.path) and change.size > size_limit: - return change - - def get_gpgk_upload_over_size(self, size_limit: int) -> Optional[LocalChange]: - """ - Find the first GPKG file in added and updated changes that exceeds the size limit. - Do not include diffs (only new or overwritten files). - :param size_limit: The size limit in bytes. - :return: The first LocalChange that exceeds the size limit, or None if no such file exists. - """ - for change in self.get_upload_changes(): - if is_versioned_file(change.path) and not change.diff and change.size > size_limit: - return change diff --git a/mergin/test/test_client.py b/mergin/test/test_client.py index 2216ae1f..eac871be 100644 --- a/mergin/test/test_client.py +++ b/mergin/test/test_client.py @@ -3225,11 +3225,11 @@ def test_push_file_limits(mc): mc.download_project(project, project_dir) shutil.copy(os.path.join(TEST_DATA_DIR, "base.gpkg"), project_dir) # setting to some minimal value to mock limit hit - with patch("mergin.client_push.MAX_UPLOAD_VERSIONED_SIZE", 1): - with pytest.raises(ClientError, match=f"base.gpkg to upload exceeds the maximum allowed size of {1/1024**3}"): + with patch("mergin.local_changes.MAX_UPLOAD_VERSIONED_SIZE", 1): + with pytest.raises(ClientError, match=f"Some files exceeded maximum upload size. Files: base.gpkg."): mc.push_project(project_dir) shutil.copy(os.path.join(TEST_DATA_DIR, "test.txt"), project_dir) - with patch("mergin.client_push.MAX_UPLOAD_MEDIA_SIZE", 1): - with pytest.raises(ClientError, match=f"test.txt to upload exceeds the maximum allowed size of {1/1024**3}"): + with patch("mergin.local_changes.MAX_UPLOAD_MEDIA_SIZE", 1): + with pytest.raises(ClientError, match=f"Some files exceeded maximum upload size. Files: test.txt."): mc.push_project(project_dir) diff --git a/mergin/test/test_local_changes.py b/mergin/test/test_local_changes.py index dceab27a..57365761 100644 --- a/mergin/test/test_local_changes.py +++ b/mergin/test/test_local_changes.py @@ -1,6 +1,8 @@ from datetime import datetime +import pytest +from unittest.mock import patch -from ..local_changes import LocalChange, LocalChanges, MAX_UPLOAD_CHANGES +from ..local_changes import ChangesValidationError, LocalChange, LocalChanges, MAX_UPLOAD_CHANGES def test_local_changes_from_dict(): @@ -120,10 +122,10 @@ def test_local_changes_get_upload_changes(): assert upload_changes[1].path == "file2.txt" # Second change is from updated -def test_local_changes_get_media_upload_over_size(): +def test_local_changes_post_init_validation_media(): """Test the get_media_upload_file method of LocalChanges.""" # Define constants - SIZE_LIMIT_MB = 10 + SIZE_LIMIT_MB = 5 SIZE_LIMIT_BYTES = SIZE_LIMIT_MB * 1024 * 1024 SMALL_FILE_SIZE = 1024 LARGE_FILE_SIZE = 15 * 1024 * 1024 @@ -139,18 +141,16 @@ def test_local_changes_get_media_upload_over_size(): ] # Initialize LocalChanges - local_changes = LocalChanges(added=added, updated=updated) - - # Call get_media_upload_file with a size limit - media_file = local_changes.get_media_upload_over_size(SIZE_LIMIT_BYTES) - - # Assertions - assert media_file is not None - assert media_file.path == "file2.jpg" # The first file over the limit - assert media_file.size == LARGE_FILE_SIZE + with patch("mergin.local_changes.MAX_UPLOAD_MEDIA_SIZE", SIZE_LIMIT_BYTES): + with pytest.raises(ChangesValidationError, match="Some files exceed") as err: + LocalChanges(added=added, updated=updated) + print(err.value.invalid_changes) + assert len(err.value.invalid_changes) == 1 + assert "file2.jpg" == err.value.invalid_changes[0].path + assert err.value.invalid_changes[0].size == LARGE_FILE_SIZE -def test_local_changes_get_gpgk_upload_over_size(): +def test_local_changes_post_init_validation_media(): """Test the get_gpgk_upload_file method of LocalChanges.""" # Define constants SIZE_LIMIT_MB = 10 @@ -166,21 +166,23 @@ def test_local_changes_get_gpgk_upload_over_size(): ), # Over limit ] updated = [ - LocalChange(path="file3.gpkg", checksum="lmn456", size=5 * 1024 * 1024, mtime=datetime.now()), + LocalChange( + path="file3.gpkg", + checksum="lmn456", + size=SIZE_LIMIT_BYTES + 1, + mtime=datetime.now(), + diff={"path": "file3-diff.gpkg", "checksum": "diff123", "size": 1024, "mtime": datetime.now()}, + ), LocalChange(path="file4.txt", checksum="opq123", size=SMALL_FILE_SIZE, mtime=datetime.now()), ] # Initialize LocalChanges - local_changes = LocalChanges(added=added, updated=updated) - - # Call get_gpgk_upload_file with a size limit - gpkg_file = local_changes.get_gpgk_upload_over_size(SIZE_LIMIT_BYTES) - - # Assertions - assert gpkg_file is not None - assert gpkg_file.path == "file2.gpkg" # The first GPKG file over the limit - assert gpkg_file.size == LARGE_FILE_SIZE - assert gpkg_file.diff is None # Ensure it doesn't include diffs + with patch("mergin.local_changes.MAX_UPLOAD_VERSIONED_SIZE", SIZE_LIMIT_BYTES): + with pytest.raises(ChangesValidationError) as err: + LocalChanges(added=added, updated=updated) + assert len(err.value.invalid_changes) == 1 + assert "file2.gpkg" == err.value.invalid_changes[0].path + assert err.value.invalid_changes[0].size == LARGE_FILE_SIZE def test_local_changes_post_init(): From 350aedc336a363bad2ffe7114e4b35de22d26564 Mon Sep 17 00:00:00 2001 From: "marcel.kocisek" Date: Tue, 16 Sep 2025 15:17:02 +0200 Subject: [PATCH 6/8] get rid of glob.glob --- mergin/test/test_client.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mergin/test/test_client.py b/mergin/test/test_client.py index eac871be..1c55933e 100644 --- a/mergin/test/test_client.py +++ b/mergin/test/test_client.py @@ -2328,8 +2328,10 @@ def test_clean_diff_files(mc): shutil.copy(mp.fpath("inserted_1_A.gpkg"), mp.fpath(f_updated)) mc.push_project(project_dir) - diff_files = glob.glob("*-diff-*", root_dir=os.path.split(mp.fpath_meta("inserted_1_A.gpkg"))[0]) + directory = os.path.split(mp.fpath_meta("inserted_1_A.gpkg"))[0] + diff_files = [f for f in os.listdir(directory) if "-diff-" in f] + # Assert that no matching files are found assert diff_files == [] From 0b585ee3b2996cced0cd730ca6d9d3293efec178 Mon Sep 17 00:00:00 2001 From: "marcel.kocisek" Date: Thu, 18 Sep 2025 12:51:48 +0200 Subject: [PATCH 7/8] move file size to consts --- mergin/client_push.py | 2 +- mergin/local_changes.py | 6 +----- mergin/merginproject.py | 4 ++-- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/mergin/client_push.py b/mergin/client_push.py index 79c66a42..814b5ec0 100644 --- a/mergin/client_push.py +++ b/mergin/client_push.py @@ -495,6 +495,6 @@ def get_push_changes_batch(mc, mp: MerginProject) -> Tuple[LocalProjectChanges, ) except ChangesValidationError as e: raise ClientError( - f"Some files exceeded maximum upload size. Files: {', '.join([c.path for c in e.invalid_changes])}. Maximum size for media files is {e.max_media_upload_size / (1024**3)} GB and for geopackage files {e.max_versioned_upload_size / (1024**3)} GB." + f"Some files exceeded maximum upload size. Files: {', '.join([c.path for c in e.invalid_changes])}. Maximum size for media files is {MAX_UPLOAD_MEDIA_SIZE / (1024**3)} GB and for geopackage files {MAX_UPLOAD_VERSIONED_SIZE / (1024**3)} GB." ) return local_changes, sum(len(v) for v in changes.values()) diff --git a/mergin/local_changes.py b/mergin/local_changes.py index 3045ccb4..d67e91f5 100644 --- a/mergin/local_changes.py +++ b/mergin/local_changes.py @@ -10,11 +10,9 @@ # The custom exception class ChangesValidationError(Exception): - def __init__(self, message, invalid_changes=[], max_media_upload_size=None, max_versioned_upload_size=None): + def __init__(self, message, invalid_changes=[]): super().__init__(message) self.invalid_changes = invalid_changes if invalid_changes is not None else [] - self.max_media_upload_size = max_media_upload_size - self.max_versioned_upload_size = max_versioned_upload_size @dataclass @@ -96,8 +94,6 @@ def __post_init__(self): oversize_changes.append(change) if oversize_changes: error = ChangesValidationError("Some files exceed the maximum upload size", oversize_changes) - error.max_media_upload_size = MAX_UPLOAD_MEDIA_SIZE - error.max_versioned_upload_size = MAX_UPLOAD_VERSIONED_SIZE raise error if total_changes > MAX_UPLOAD_CHANGES: diff --git a/mergin/merginproject.py b/mergin/merginproject.py index 61b417e5..cd519131 100644 --- a/mergin/merginproject.py +++ b/mergin/merginproject.py @@ -21,7 +21,7 @@ conflicted_copy_file_name, edit_conflict_file_name, ) -from .local_changes import LocalChange +from .local_changes import FileChange this_dir = os.path.dirname(os.path.realpath(__file__)) @@ -470,7 +470,7 @@ def get_push_changes(self): changes["updated"] = [f for f in changes["updated"] if f not in not_updated] return changes - def copy_versioned_file_for_upload(self, f: LocalChange, tmp_dir: str) -> str: + def copy_versioned_file_for_upload(self, f: FileChange, tmp_dir: str) -> str: """ Make a temporary copy of the versioned file using geodiff, to make sure that we have full content in a single file (nothing left in WAL journal) From 7440f3fbfeae03fc2cca8105f454f69d44147426 Mon Sep 17 00:00:00 2001 From: "marcel.kocisek" Date: Thu, 18 Sep 2025 15:05:41 +0200 Subject: [PATCH 8/8] Update docstring for sync method --- mergin/client.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mergin/client.py b/mergin/client.py index 72edf8ba..14606c6b 100644 --- a/mergin/client.py +++ b/mergin/client.py @@ -1554,6 +1554,8 @@ def sync_project_generator(self, project_directory): def sync_project(self, project_directory): """ + Syncs project by pulling server changes and pushing local changes. There is intorduced retry mechanism + for handling server conflicts (when server has changes that we do not have yet or somebody else is syncing). See description of _sync_project_generator(). :param project_directory: Project's directory