Skip to content
30 changes: 20 additions & 10 deletions lean/components/api/file_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
66 changes: 64 additions & 2 deletions lean/components/cloud/push_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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."""
Expand Down Expand Up @@ -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"]
Expand All @@ -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",
Comment thread
quantconnect-kronos-reviewer[bot] marked this conversation as resolved.
Resolved
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:
Expand Down
68 changes: 67 additions & 1 deletion tests/commands/cloud/test_push.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()

Expand Down
36 changes: 36 additions & 0 deletions tests/components/api/test_file_client.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading