-
Notifications
You must be signed in to change notification settings - Fork 6
[CDF-27549] Dune App resource (Files API + zip, alpha flag) #2777
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
ronpal
wants to merge
3
commits into
main
Choose a base branch
from
cdf-27549-dune-apps
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import shutil | ||
| from collections.abc import Callable, Iterable, Sequence | ||
| from pathlib import Path | ||
|
|
||
| from pydantic import ValidationError | ||
|
|
||
| from cognite_toolkit._cdf_tk.builders._base import Builder | ||
| from cognite_toolkit._cdf_tk.cruds import AppCRUD | ||
| from cognite_toolkit._cdf_tk.data_classes import ( | ||
| BuildDestinationFile, | ||
| BuildSourceFile, | ||
| BuiltResourceList, | ||
| ModuleLocation, | ||
| ) | ||
| from cognite_toolkit._cdf_tk.exceptions import ToolkitFileExistsError, ToolkitNotADirectoryError, ToolkitValueError | ||
| from cognite_toolkit._cdf_tk.tk_warnings import ( | ||
| FileReadWarning, | ||
| HighSeverityWarning, | ||
| LowSeverityWarning, | ||
| ToolkitWarning, | ||
| WarningList, | ||
| ) | ||
| from cognite_toolkit._cdf_tk.yaml_classes import AppsYAML | ||
|
|
||
|
|
||
| class AppBuilder(Builder): | ||
| _resource_folder = AppCRUD.folder_name | ||
|
|
||
| def __init__(self, build_dir: Path, warn: Callable[[ToolkitWarning], None]) -> None: | ||
| super().__init__(build_dir, warn=warn) | ||
|
|
||
| def build( | ||
| self, | ||
| source_files: list[BuildSourceFile], | ||
| module: ModuleLocation, | ||
| console: Callable[[str], None] | None = None, | ||
| ) -> Iterable[BuildDestinationFile | Sequence[ToolkitWarning]]: | ||
| for source_file in source_files: | ||
| if source_file.loaded is None: | ||
| continue | ||
| if source_file.source.path.parent.parent != module.dir: | ||
| continue | ||
|
|
||
| loader, warning = self._get_loader(source_file.source.path) | ||
| if loader is None: | ||
| if warning is not None: | ||
| yield [warning] | ||
| continue | ||
|
|
||
| warnings = WarningList[FileReadWarning]() | ||
| if loader is AppCRUD: | ||
| warnings = self.copy_app_directory_to_build(source_file) | ||
|
|
||
| destination_path = self._create_destination_path(source_file.source.path, loader.kind) | ||
|
|
||
| yield BuildDestinationFile( | ||
| path=destination_path, | ||
| loaded=source_file.loaded, | ||
| loader=loader, | ||
| source=source_file.source, | ||
| extra_sources=None, | ||
| warnings=warnings, | ||
| ) | ||
|
|
||
| def validate_directory( | ||
| self, | ||
| built_resources: BuiltResourceList, | ||
| module: ModuleLocation, | ||
| ) -> WarningList[ToolkitWarning]: | ||
| warnings = WarningList[ToolkitWarning]() | ||
| has_config_files = any(resource.kind == AppCRUD.kind for resource in built_resources) | ||
| if has_config_files: | ||
| return warnings | ||
| config_files_misplaced = [ | ||
| file | ||
| for file in module.source_paths_by_resource_folder[AppCRUD.folder_name] | ||
| if AppCRUD.is_supported_file(file) | ||
| ] | ||
| if config_files_misplaced: | ||
| for yaml_source_path in config_files_misplaced: | ||
| required_location = module.dir / AppCRUD.folder_name / yaml_source_path.name | ||
| warning = LowSeverityWarning( | ||
| f"The required App resource configuration file " | ||
| f"was not found in {required_location.as_posix()!r}. " | ||
| f"The file {yaml_source_path.as_posix()!r} is currently " | ||
| f"considered part of the App's artifacts and " | ||
| f"will not be processed by the Toolkit.", | ||
| ) | ||
| warnings.append(warning) | ||
| return warnings | ||
|
|
||
| def copy_app_directory_to_build(self, source_file: BuildSourceFile) -> WarningList[FileReadWarning]: | ||
| raw_content = source_file.loaded | ||
| if raw_content is None: | ||
| raise ToolkitValueError("App source file should be a YAML file.") | ||
| raw_apps = raw_content if isinstance(raw_content, list) else [raw_content] | ||
| warnings = WarningList[FileReadWarning]() | ||
| for raw_app in raw_apps: | ||
| try: | ||
| app_config = AppsYAML.model_validate(raw_app) | ||
| except ValidationError as e: | ||
| warnings.append( | ||
| HighSeverityWarning( | ||
| f"App in {source_file.source.path.as_posix()!r} has invalid configuration: {e}", | ||
| ), | ||
| ) | ||
| continue | ||
|
|
||
| app_directory = source_file.source.path.with_name(app_config.app_external_id) | ||
|
|
||
| if not app_directory.is_dir(): | ||
| raise ToolkitNotADirectoryError( | ||
| f"App directory not found for appExternalId {app_config.app_external_id} defined in {source_file.source.path.as_posix()!r}.", | ||
| ) | ||
|
|
||
| destination = self.build_dir / self.resource_folder / app_config.app_external_id | ||
| if destination.exists(): | ||
| raise ToolkitFileExistsError( | ||
| f"App {app_config.app_external_id!r} is duplicated. If this is unexpected, ensure you have a clean build directory.", | ||
| ) | ||
| shutil.copytree(app_directory, destination, ignore=shutil.ignore_patterns("__pycache__")) | ||
|
|
||
| return warnings | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| """Apps API: Dune apps as classic files under /dune-apps/ (same pattern as Streamlit + /files).""" | ||
|
|
||
| from collections.abc import Iterable, Sequence | ||
| from typing import Literal | ||
|
|
||
| from cognite_toolkit._cdf_tk.client.cdf_client import CDFResourceAPI, PagedResponse, ResponseItems | ||
| from cognite_toolkit._cdf_tk.client.cdf_client.api import Endpoint | ||
| from cognite_toolkit._cdf_tk.client.http_client import ( | ||
| HTTPClient, | ||
| ItemsSuccessResponse, | ||
| RequestMessage, | ||
| SuccessResponse, | ||
| ) | ||
| from cognite_toolkit._cdf_tk.client.identifiers import ExternalId | ||
| from cognite_toolkit._cdf_tk.client.request_classes.filters import DuneAppFilter | ||
| from cognite_toolkit._cdf_tk.client.resource_classes.app import AppRequest, AppResponse | ||
|
|
||
|
|
||
| class AppsAPI(CDFResourceAPI[AppResponse]): | ||
| """Dune apps are file metadata objects under ``/dune-apps/`` with a zip uploaded to ``uploadUrl``.""" | ||
|
|
||
| def __init__(self, http_client: HTTPClient) -> None: | ||
| super().__init__( | ||
| http_client=http_client, | ||
| method_endpoint_map={ | ||
| "create": Endpoint(method="POST", path="/files", item_limit=1, concurrency_max_workers=1), | ||
| "retrieve": Endpoint(method="POST", path="/files/byids", item_limit=1000, concurrency_max_workers=1), | ||
| "update": Endpoint(method="POST", path="/files/update", item_limit=1000, concurrency_max_workers=1), | ||
| "delete": Endpoint(method="POST", path="/files/delete", item_limit=1000, concurrency_max_workers=1), | ||
| "list": Endpoint(method="POST", path="/files/list", item_limit=1000), | ||
| }, | ||
| ) | ||
|
|
||
| def _validate_page_response(self, response: SuccessResponse | ItemsSuccessResponse) -> PagedResponse[AppResponse]: | ||
| return PagedResponse[AppResponse].model_validate_json(response.body) | ||
|
|
||
| def _reference_response(self, response: SuccessResponse) -> ResponseItems[ExternalId]: | ||
| return ResponseItems[ExternalId].model_validate_json(response.body) | ||
|
|
||
| def create(self, items: Sequence[AppRequest], overwrite: bool = False) -> list[AppResponse]: | ||
| endpoint = self._method_endpoint_map["create"] | ||
| results: list[AppResponse] = [] | ||
| for item in items: | ||
| request = RequestMessage( | ||
| endpoint_url=self._make_url(endpoint.path), | ||
| method=endpoint.method, | ||
| body_content=item.dump(), | ||
| parameters={"overwrite": overwrite}, | ||
| ) | ||
| response = self._http_client.request_single_retries(request) | ||
| result = response.get_success_or_raise(request) | ||
| results.append(AppResponse.model_validate_json(result.body)) | ||
| return results | ||
|
|
||
| def retrieve(self, items: Sequence[ExternalId], ignore_unknown_ids: bool = False) -> list[AppResponse]: | ||
| return self._request_item_response( | ||
| items, method="retrieve", extra_body={"ignoreUnknownIds": ignore_unknown_ids} | ||
| ) | ||
|
|
||
| def update(self, items: Sequence[AppRequest], mode: Literal["patch", "replace"] = "replace") -> list[AppResponse]: | ||
| return self._update(items, mode=mode) | ||
|
|
||
| def delete(self, items: Sequence[ExternalId], ignore_unknown_ids: bool = False) -> None: | ||
| self._request_no_response(items, "delete", extra_body={"ignoreUnknownIds": ignore_unknown_ids}) | ||
|
|
||
| def paginate( | ||
| self, | ||
| filter: DuneAppFilter | None = None, | ||
| limit: int = 100, | ||
| cursor: str | None = None, | ||
| ) -> PagedResponse[AppResponse]: | ||
| return self._paginate( | ||
| cursor=cursor, | ||
| limit=limit, | ||
| body={"filter": (filter or DuneAppFilter()).dump()}, | ||
| ) | ||
|
|
||
| def iterate( | ||
| self, | ||
| filter: DuneAppFilter | None = None, | ||
| limit: int | None = 100, | ||
| ) -> Iterable[list[AppResponse]]: | ||
| return self._iterate( | ||
| limit=limit, | ||
| body={"filter": (filter or DuneAppFilter()).dump()}, | ||
| ) | ||
|
|
||
| def list( | ||
| self, | ||
| filter: DuneAppFilter | None = None, | ||
| limit: int | None = 100, | ||
| ) -> list[AppResponse]: | ||
| return self._list( | ||
| limit=limit, | ||
| body={"filter": (filter or DuneAppFilter()).dump()}, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current implementation uses
dict.get()on raw dictionaries, which goes against the repository's style guide that promotes using typed data structures for safety and clarity (lines 6-7, 41). Refactoring to use theAppsYAMLPydantic model for validation will make the code more robust and align with best practices.This also fixes a potential bug where the build process would continue even if a
versionis missing, only to fail later during deployment. With this change, the validation happens earlier.You'll need to add the following imports:
References