diff --git a/lean/components/api/file_client.py b/lean/components/api/file_client.py index cb22194a..65b0ae7b 100644 --- a/lean/components/api/file_client.py +++ b/lean/components/api/file_client.py @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import List +from typing import List, Optional from lean.components.api.api_client import * from lean.models.api import QCFullFile, QCMinimalFile @@ -53,39 +53,49 @@ def get_all(self, project_id: int) -> List[QCFullFile]: return [QCFullFile(**file) for file in data["files"]] - def create(self, project_id: int, file_name: str, content: str) -> None: + def create(self, project_id: int, file_name: str, content: str, code_source_id: Optional[str] = None) -> None: """Creates a new file. :param project_id: the id of the project to create a file for :param file_name: the name of the file to create :param content: the content of the file to create + :param code_source_id: the source of the code changes (e.g., "cli") """ - data = self._api.post("files/create", { + self._api.post("files/create", self._with_code_source_id({ "projectId": project_id, "name": file_name, "content": content - }) + }, code_source_id)) - def update(self, project_id: int, file_name: str, content: str) -> None: + def update(self, project_id: int, file_name: str, content: str, code_source_id: Optional[str] = None) -> None: """Updates an existing file. :param project_id: the id of the project to update a file in :param file_name: the name of the file to update :param content: the new content of the file + :param code_source_id: the source of the code changes (e.g., "cli") """ - data = self._api.post("files/update", { + self._api.post("files/update", self._with_code_source_id({ "projectId": project_id, "name": file_name, "content": content - }) + }, code_source_id)) - def delete(self, project_id: int, file_name: str) -> None: + def delete(self, project_id: int, file_name: str, code_source_id: Optional[str] = None) -> None: """Deletes an existing file. :param project_id: the id of the project the file belongs to :param file_name: the name of the file to delete + :param code_source_id: the source of the code changes (e.g., "cli") """ - self._api.post("files/delete", { + self._api.post("files/delete", self._with_code_source_id({ "projectId": project_id, "name": file_name - }) + }, code_source_id)) + + @staticmethod + def _with_code_source_id(request_parameters: dict, code_source_id: Optional[str]) -> dict: + # The API only checks the project's collaboration lock when codeSourceId is sent + if code_source_id is not None: + request_parameters["codeSourceId"] = code_source_id + return request_parameters diff --git a/lean/components/cloud/push_manager.py b/lean/components/cloud/push_manager.py index 21b9bd72..5c47c7d1 100644 --- a/lean/components/cloud/push_manager.py +++ b/lean/components/cloud/push_manager.py @@ -12,7 +12,8 @@ # limitations under the License. from pathlib import Path -from typing import List, Dict, Optional +from functools import partial +from typing import Any, List, Dict, Optional from lean.components.api.api_client import APIClient from lean.components.config.project_config_manager import ProjectConfigManager @@ -23,6 +24,7 @@ from lean.models.api import QCLanguage, QCProject from lean.models.utils import LeanLibraryReference from lean.models.encryption import ActionType +from lean.models.errors import RequestFailedError class PushManager: """The PushManager class is responsible for synchronizing local projects to the cloud.""" @@ -305,7 +307,17 @@ def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_act if not force: update_args["code_source_id"] = "cli" if update_args != {}: - self._api_client.projects.update(cloud_project.projectId, **update_args) + try: + self._api_client.projects.update(cloud_project.projectId, **update_args) + except RequestFailedError as error: + if error.response.status_code != 413: + raise + # projects/update checks a new encryption key before it writes any file, but the per-file path + # sends the key last, so a refused key would leave the cloud files encrypted or decrypted anyway + cloud_encryption_key = cloud_project.encryptionKey.id if cloud_project.encryptionKey else '' + if update_args["encryption_key"] != cloud_encryption_key: + raise + self._push_one_by_one(cloud_project, update_args) if "encryption_key" in update_args: del update_args["encryption_key"] @@ -320,6 +332,56 @@ def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_act self._logger.info(f"Successfully updated {updated_keys_str} for '{cloud_project.name}'") + def _push_one_by_one(self, cloud_project: QCProject, update_args: Dict[str, Any]) -> None: + """Pushes a project that is too large for a single projects/update request, with one request per change. + + The files go first and the other metadata last. The API checks the collaboration lock on files/* requests + that carry codeSourceId, but not on a projects/update without files, so a lock held by someone else stops + the push before any file is written. + + :param cloud_project: the cloud project to push to + :param update_args: the arguments of the projects/update request that was too large + """ + project_id = cloud_project.projectId + code_source_id = update_args.get("code_source_id") + local_files = update_args["files"] + local_file_names = {file["name"] for file in local_files} + self._logger.info(f"'{cloud_project.name}' is too large to push in one request, pushing its changed files one by one") + # Library files come with their own names, which may be the same as the project's files + cloud_files = {file.name: file for file in self._api_client.files.get_all(project_id) if not file.isLibrary} + + # Deletes go first, so a rename in a project at its file quota doesn't go over the quota + requests = [(f"deleting '{cloud_file.name}'", + partial(self._api_client.files.delete, project_id, cloud_file.name, code_source_id=code_source_id)) + for cloud_file in cloud_files.values() + if cloud_file.name not in local_file_names] + for file in local_files: + cloud_file = cloud_files.get(file["name"]) + if cloud_file is None: + requests.append((f"creating '{file['name']}'", + partial(self._api_client.files.create, project_id, file["name"], file["content"], + code_source_id=code_source_id))) + elif cloud_file.content != file["content"]: + requests.append((f"updating '{file['name']}'", + partial(self._api_client.files.update, project_id, file["name"], file["content"], + code_source_id=code_source_id))) + requests.append(("updating the project details", + partial(self._api_client.projects.update, project_id, + **{key: value for key, value in update_args.items() if key != "files"}))) + + for index, (description, request) in enumerate(requests): + try: + request() + except Exception as error: + if index == 0: + raise RuntimeError(f"{description} failed, nothing was pushed: {error}") from error + if index == len(requests) - 1: + raise RuntimeError(f"All files of '{cloud_project.name}' were pushed, but updating the project " + f"details failed. Fix the problem and push again. Error: {error}") from error + raise RuntimeError(f"Only part of '{cloud_project.name}' was pushed: {description} failed, so the " + f"cloud project now mixes old and new code. Fix the problem and push again. " + f"Error: {error}") from error + def _get_cloud_project(self, project_id: int, organization_id: str) -> QCProject: project = next(iter(p for p in self._cloud_projects if p.projectId == project_id), None) if project is None: diff --git a/tests/commands/cloud/test_push.py b/tests/commands/cloud/test_push.py index bfb70c91..c77927a0 100644 --- a/tests/commands/cloud/test_push.py +++ b/tests/commands/cloud/test_push.py @@ -20,7 +20,8 @@ from lean.commands import lean from lean.components.cloud.push_manager import PushManager -from lean.models.api import QCFullFile +from lean.models.api import ProjectEncryptionKey, QCFullFile +from lean.models.errors import RequestFailedError from tests.test_helpers import create_fake_lean_cli_directory, create_api_project from tests.conftest import initialize_container from lean.container import container @@ -315,6 +316,71 @@ def test_cloud_push_keeps_encryption_key_path_outside_project_when_push_renames_ assert new_config.get("encryption-key-path") == str(encryption_file_path) +def test_cloud_push_writes_no_files_when_a_too_large_push_turns_on_encryption() -> None: + create_fake_lean_cli_directory() + + project_path = Path.cwd() / "Python Project" + + encryption_file_path = project_path / "encryption.txt" + encryption_file_path.write_text("KtSwJtq5a4uuQmxbPqcCP3d8yMRz5TZxDBAKy7kGwPcvcvsNBdCprGYwSBN8ntJa5JNNYHTB2GrBpAbkA38kCdnceegffZH7") + keys_api_data = {'keys': [{'name': 'test', 'hash': get_project_key_hash(encryption_file_path)}]} + + api_client = mock.Mock() + api_client.encryption_keys.list = mock.MagicMock(return_value=keys_api_data) + api_client.projects.create = mock.MagicMock(return_value=create_api_project(1, "Python Project")) + api_client.projects.update = mock.MagicMock(side_effect=[RequestFailedError(mock.Mock(status_code=413)), None]) + api_client.files.get_all = mock.MagicMock(return_value=[]) + + init_container(api_client_to_use=api_client) + + project_config = container.project_config_manager.get_project_config(project_path) + project_config.set("encrypted", False) + + result = CliRunner().invoke(lean, ["cloud", "push", "--project", project_path, "--encrypt", "--key", encryption_file_path]) + + assert result.exit_code == 0 + # The cloud may still refuse the key, so the files must not be pushed one by one before it is accepted + api_client.projects.update.assert_called_once() + api_client.files.create.assert_not_called() + api_client.files.update.assert_not_called() + api_client.files.delete.assert_not_called() + +def test_cloud_push_pushes_files_one_by_one_when_a_too_large_project_keeps_its_encryption_key() -> None: + create_fake_lean_cli_directory() + + project_path = Path.cwd() / "Python Project" + + encryption_file_path = project_path / "encryption.txt" + encryption_file_path.write_text("KtSwJtq5a4uuQmxbPqcCP3d8yMRz5TZxDBAKy7kGwPcvcvsNBdCprGYwSBN8ntJa5JNNYHTB2GrBpAbkA38kCdnceegffZH7") + key_hash = get_project_key_hash(encryption_file_path) + keys_api_data = {'keys': [{'name': 'test', 'hash': key_hash}]} + + cloud_project = create_api_project(1, "Python Project") + cloud_project.encrypted = True + cloud_project.encryptionKey = ProjectEncryptionKey(id=key_hash, name="test") + + api_client = mock.Mock() + api_client.encryption_keys.list = mock.MagicMock(return_value=keys_api_data) + api_client.projects.create = mock.MagicMock(return_value=cloud_project) + api_client.projects.update = mock.MagicMock(side_effect=[RequestFailedError(mock.Mock(status_code=413)), None]) + api_client.files.get_all = mock.MagicMock(return_value=[]) + + init_container(api_client_to_use=api_client) + + project_config = container.project_config_manager.get_project_config(project_path) + project_config.set("encrypted", False) + + result = CliRunner().invoke(lean, ["cloud", "push", "--project", project_path, "--encrypt", "--key", encryption_file_path]) + + assert result.exit_code == 0 + expected_encrypted_files = _get_expected_encrypted_files_content() + api_client.files.create.assert_has_calls([mock.call(1, name, content, code_source_id="cli") + for name, content in expected_encrypted_files.items()]) + assert api_client.files.create.call_count == len(expected_encrypted_files) + assert api_client.projects.update.call_count == 2 + assert api_client.projects.update.call_args.kwargs["encryption_key"] == key_hash + assert "files" not in api_client.projects.update.call_args.kwargs + def test_cloud_push_aborts_sending_encrypted_files_when_local_file_encrypted_with_key_x_and_given_key_y() -> None: create_fake_lean_cli_directory() diff --git a/tests/components/api/test_file_client.py b/tests/components/api/test_file_client.py new file mode 100644 index 00000000..f780d15d --- /dev/null +++ b/tests/components/api/test_file_client.py @@ -0,0 +1,36 @@ +# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. +# Lean CLI v1.0. Copyright 2021 QuantConnect Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Optional +from unittest import mock + +import pytest + +from lean.components.api.file_client import FileClient + + +@pytest.mark.parametrize("method, args, endpoint, expected_parameters", [ + ("create", (1, "main.py", "content"), "files/create", {"projectId": 1, "name": "main.py", "content": "content"}), + ("update", (1, "main.py", "content"), "files/update", {"projectId": 1, "name": "main.py", "content": "content"}), + ("delete", (1, "main.py"), "files/delete", {"projectId": 1, "name": "main.py"}) +]) +@pytest.mark.parametrize("code_source_id", [None, "cli"]) +def test_file_client_sends_code_source_id_only_when_given(method: str, args: tuple, endpoint: str, + expected_parameters: dict, code_source_id: Optional[str]) -> None: + api_client = mock.Mock() + + getattr(FileClient(api_client), method)(*args, code_source_id=code_source_id) + + if code_source_id is not None: + expected_parameters = {**expected_parameters, "codeSourceId": code_source_id} + api_client.post.assert_called_once_with(endpoint, expected_parameters) diff --git a/tests/components/util/test_push_manager.py b/tests/components/util/test_push_manager.py index aa0dc7dd..bdb5923c 100644 --- a/tests/components/util/test_push_manager.py +++ b/tests/components/util/test_push_manager.py @@ -11,14 +11,16 @@ # See the License for the specific language governing permissions and # limitations under the License. +from datetime import datetime from pathlib import Path -from typing import List +from typing import List, Optional from unittest import mock import pytest import platform from lean.components.cloud.push_manager import PushManager from lean.container import container -from lean.models.api import QCLanguage, QCProject +from lean.models.api import QCFullFile, QCLanguage, QCProject +from lean.models.errors import RequestFailedError from tests.test_helpers import create_fake_lean_cli_directory, create_api_project, create_lean_environments from tests.test_helpers import create_fake_lean_cli_project from lean.components import forbidden_characters @@ -508,6 +510,155 @@ def test_push_projects_updates_name_in_cloud_if_required(test_platform: str, uns args, kwargs = api_client.projects.update.call_args assert kwargs['name'] == expected_correct_project_name +def _create_too_large_project_push_manager(api_client: mock.Mock) -> PushManager: + create_fake_lean_cli_directory() + + project_path = Path.cwd() / "Python Project" + (project_path / "new_file.py").write_text("# new file", encoding="utf-8") + container.project_config_manager.get_project_config(project_path).set("cloud-id", 1000) + + def get_local_project_path(project_name, *args, **kwargs): + return Path.cwd() / project_name + + project_manager = mock.Mock() + project_manager.get_project_libraries = mock.MagicMock(return_value=[]) + project_manager.get_source_files = mock.MagicMock(return_value=[project_path / "main.py", + project_path / "research.ipynb", + project_path / "new_file.py"]) + project_manager.get_local_project_path = mock.MagicMock(side_effect=get_local_project_path) + + api_client.projects.get = mock.MagicMock(return_value=create_api_project(1000, project_path.name)) + return _create_push_manager(api_client, project_manager) + + +def _create_cloud_file(name: str, content: str, is_library: bool = False) -> QCFullFile: + return QCFullFile(name=name, content=content, modified=datetime.now(), isLibrary=is_library) + + +@pytest.mark.parametrize("force, expected_code_source_id", [(False, "cli"), (True, None)]) +def test_push_projects_pushes_files_one_by_one_when_the_project_is_too_large(force: bool, + expected_code_source_id: Optional[str]) -> None: + api_client = mock.Mock() + api_client.projects.update = mock.MagicMock(side_effect=[RequestFailedError(mock.Mock(status_code=413)), None]) + push_manager = _create_too_large_project_push_manager(api_client) + + project_path = Path.cwd() / "Python Project" + main_content = (project_path / "main.py").read_text(encoding="utf-8") + research_content = (project_path / "research.ipynb").read_text(encoding="utf-8") + api_client.files.get_all = mock.MagicMock(return_value=[ + _create_cloud_file("main.py", main_content), + # A trailing character can matter too, a non-breaking space is a syntax error in Python + _create_cloud_file("research.ipynb", research_content + "\u00a0"), + _create_cloud_file("removed.py", "# removed locally"), + _create_cloud_file("Library/library.py", "# library file", is_library=True) + ]) + + push_manager.push_projects([project_path], force=force) + + assert api_client.projects.update.call_count == 2 + first_call_kwargs = api_client.projects.update.call_args_list[0].kwargs + second_call_args, second_call_kwargs = api_client.projects.update.call_args_list[1] + assert "files" in first_call_kwargs + assert first_call_kwargs.get("code_source_id") == expected_code_source_id + assert second_call_args[0] == 1000 + assert second_call_kwargs == {key: value for key, value in first_call_kwargs.items() if key != "files"} + + api_client.files.create.assert_called_once_with(1000, "new_file.py", "# new file", + code_source_id=expected_code_source_id) + api_client.files.update.assert_called_once_with(1000, "research.ipynb", research_content, + code_source_id=expected_code_source_id) + api_client.files.delete.assert_called_once_with(1000, "removed.py", code_source_id=expected_code_source_id) + + # Deletes go first and the metadata last, so a collaboration lock stops the push before anything is written + write_calls = [name for name, _, _ in api_client.mock_calls + if name in ["projects.update", "files.delete", "files.create", "files.update"]] + assert write_calls == ["projects.update", "files.delete", "files.update", "files.create", "projects.update"] + + +def test_push_projects_one_by_one_ignores_library_files_named_like_project_files() -> None: + api_client = mock.Mock() + api_client.projects.update = mock.MagicMock(side_effect=[RequestFailedError(mock.Mock(status_code=413)), None]) + push_manager = _create_too_large_project_push_manager(api_client) + + project_path = Path.cwd() / "Python Project" + main_content = (project_path / "main.py").read_text(encoding="utf-8") + research_content = (project_path / "research.ipynb").read_text(encoding="utf-8") + # The API lists the files of the project's libraries after its own, under their own names + api_client.files.get_all = mock.MagicMock(return_value=[ + _create_cloud_file("main.py", "# old main"), + _create_cloud_file("research.ipynb", research_content), + _create_cloud_file("new_file.py", "# new file"), + _create_cloud_file("renamed.py", "# renamed locally"), + _create_cloud_file("main.py", main_content, is_library=True), + _create_cloud_file("renamed.py", "# library file", is_library=True) + ]) + + assert push_manager.push_projects([project_path]) + + api_client.files.update.assert_called_once_with(1000, "main.py", main_content, code_source_id="cli") + api_client.files.delete.assert_called_once_with(1000, "renamed.py", code_source_id="cli") + api_client.files.create.assert_not_called() + + +def test_push_projects_leaves_the_project_unchanged_when_the_first_file_push_fails() -> None: + api_client = mock.Mock() + api_client.projects.update = mock.MagicMock(side_effect=[RequestFailedError(mock.Mock(status_code=413)), None]) + api_client.files.get_all = mock.MagicMock(return_value=[]) + api_client.files.create = mock.MagicMock(side_effect=RequestFailedError(mock.Mock(), "You do not have write permission")) + push_manager = _create_too_large_project_push_manager(api_client) + + push_manager.push_projects([Path.cwd() / "Python Project"]) + + api_client.files.create.assert_called_once() + api_client.projects.update.assert_called_once() + push_manager._logger.warn.assert_called_once_with("Cannot push 'Python Project': creating 'main.py' failed, " + "nothing was pushed: You do not have write permission") + push_manager._logger.info.assert_any_call("Please pull any required changes and push with --force") + + +def test_push_projects_returns_false_when_a_file_push_fails_after_other_files_were_pushed() -> None: + api_client = mock.Mock() + api_client.projects.update = mock.MagicMock(side_effect=[RequestFailedError(mock.Mock(status_code=413)), None]) + api_client.files.get_all = mock.MagicMock(return_value=[]) + api_client.files.create = mock.MagicMock(side_effect=[None, RequestFailedError(mock.Mock(), "Internal error")]) + push_manager = _create_too_large_project_push_manager(api_client) + + assert not push_manager.push_projects([Path.cwd() / "Python Project"]) + + assert api_client.files.create.call_count == 2 + api_client.projects.update.assert_called_once() + warning = push_manager._logger.warn.call_args.args[0] + assert "Only part of 'Python Project' was pushed: creating 'research.ipynb' failed" in warning + assert "Internal error" in warning + + +def test_push_projects_returns_false_when_only_the_project_details_fail_after_the_files_were_pushed() -> None: + api_client = mock.Mock() + api_client.projects.update = mock.MagicMock(side_effect=[RequestFailedError(mock.Mock(status_code=413)), + RequestFailedError(mock.Mock(), "Name already taken")]) + api_client.files.get_all = mock.MagicMock(return_value=[]) + push_manager = _create_too_large_project_push_manager(api_client) + + assert not push_manager.push_projects([Path.cwd() / "Python Project"]) + + assert api_client.files.create.call_count == 3 + warning = push_manager._logger.warn.call_args.args[0] + assert "All files of 'Python Project' were pushed, but updating the project details failed" in warning + assert "Name already taken" in warning + + +def test_push_projects_does_not_push_files_one_by_one_on_other_errors() -> None: + api_client = mock.Mock() + api_client.projects.update = mock.MagicMock(side_effect=RequestFailedError(mock.Mock(status_code=400))) + push_manager = _create_too_large_project_push_manager(api_client) + + push_manager.push_projects([Path.cwd() / "Python Project"]) + + api_client.projects.update.assert_called_once() + api_client.files.get_all.assert_not_called() + api_client.files.create.assert_not_called() + + def test_push_projects_updates_name_locally_if_updated_by_cloud() -> None: project_name = "Python Project"