-
Notifications
You must be signed in to change notification settings - Fork 415
Feat: workspace file selector, package builder #3207
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
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
e910d93
File selector, package builder
anuunchin 5abcf86
pathspec added, improvements
anuunchin e527326
Test for file selector
anuunchin 40fbd60
Test for package builder
anuunchin 35645f4
digest256_tar_stream util
anuunchin f2c34e7
Unnecessary file selector protocol removed
anuunchin aa7bbd4
Posix path in builder
anuunchin 97e7e85
Relevant notes and dosctring improvements
anuunchin 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
Empty file.
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,46 @@ | ||
| from typing import Iterator, Optional, List | ||
| from pathlib import Path | ||
| from pathspec import PathSpec | ||
| from pathspec.util import iter_tree_files | ||
|
|
||
| from dlt._workspace._workspace_context import WorkspaceRunContext | ||
|
|
||
|
|
||
| class WorkspaceFileSelector: | ||
| """Iterates files in workspace respecting ignore patterns and excluding workspace internals. | ||
|
|
||
| Uses gitignore-style patterns from a configurable ignore file (default .gitignore). Additional | ||
| patterns can be provided as relative paths from workspace root. Settings directory is always excluded. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| context: WorkspaceRunContext, | ||
| additional_excludes: Optional[List[str]] = None, | ||
| ignore_file: str = ".gitignore", | ||
| ) -> None: | ||
| self.root_path: Path = Path(context.run_dir).resolve() | ||
| self.settings_dir: Path = Path(context.settings_dir).resolve() | ||
| self.ignore_file: str = ignore_file | ||
| self.spec: PathSpec = self._build_pathspec(additional_excludes or []) | ||
|
|
||
| def _build_pathspec(self, additional_excludes: List[str]) -> PathSpec: | ||
| """Build PathSpec from ignore file + defaults + additional excludes""" | ||
| patterns: List[str] = [f"{self.settings_dir.relative_to(self.root_path)}/"] | ||
|
|
||
| # Load ignore file if exists | ||
| ignore_path = self.root_path / self.ignore_file | ||
| if ignore_path.exists(): | ||
| with ignore_path.open("r", encoding="utf-8") as f: | ||
| patterns.extend(f.read().splitlines()) | ||
|
|
||
| # Add caller-provided excludes | ||
| patterns.extend(additional_excludes) | ||
|
|
||
| return PathSpec.from_lines("gitwildmatch", patterns) | ||
|
|
||
| def __iter__(self) -> Iterator[Path]: | ||
| """Yield paths of files eligible for deployment""" | ||
| for file_path in iter_tree_files(self.root_path): | ||
| if not self.spec.match_file(file_path): | ||
| yield Path(file_path) | ||
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,19 @@ | ||
| from typing import List | ||
| from dlt.common.typing import TypedDict | ||
|
|
||
| # current version of deployment engine | ||
| DEPLOYMENT_ENGINE_VERSION = 1 | ||
|
|
||
|
|
||
| class TDeploymentFileItem(TypedDict, total=False): | ||
| """TypedDict representing a file in the deployment package""" | ||
|
|
||
| relative_path: str | ||
| size_in_bytes: int | ||
|
|
||
|
|
||
| class TDeploymentManifest(TypedDict, total=False): | ||
| """TypedDict defining the deployment manifest structure""" | ||
|
|
||
| engine_version: int | ||
| files: List[TDeploymentFileItem] |
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,76 @@ | ||
| from io import BytesIO | ||
| from typing import Tuple, BinaryIO, List | ||
| from pathlib import Path | ||
| import tarfile | ||
| import yaml | ||
|
|
||
| from dlt.common.time import precise_time | ||
| from dlt.common.utils import digest256_tar_stream | ||
|
|
||
| from dlt._workspace.deployment.file_selector import WorkspaceFileSelector | ||
| from dlt._workspace.deployment.manifest import ( | ||
| TDeploymentFileItem, | ||
| TDeploymentManifest, | ||
| DEPLOYMENT_ENGINE_VERSION, | ||
| ) | ||
|
|
||
| from dlt._workspace._workspace_context import WorkspaceRunContext | ||
|
|
||
|
|
||
| DEFAULT_DEPLOYMENT_FILES_FOLDER = "files" | ||
| DEFAULT_MANIFEST_FILE_NAME = "manifest.yaml" | ||
| DEFAULT_DEPLOYMENT_PACKAGE_LAYOUT = "deployment-{timestamp}.tar.gz" | ||
|
|
||
|
|
||
| class DeploymentPackageBuilder: | ||
| """Builds gzipped deployment package from file selectors""" | ||
|
|
||
| def __init__(self, context: WorkspaceRunContext): | ||
| self.run_context: WorkspaceRunContext = context | ||
|
|
||
| def write_package_to_stream( | ||
| self, file_selector: WorkspaceFileSelector, output_stream: BinaryIO | ||
| ) -> str: | ||
| """Write deployment package to output stream, return content hash""" | ||
| manifest_files: List[TDeploymentFileItem] = [] | ||
|
|
||
| # Add files to the archive | ||
| with tarfile.open(fileobj=output_stream, mode="w|gz") as tar: | ||
| for file_path in file_selector: | ||
| full_path = self.run_context.run_dir / file_path | ||
| # Use POSIX paths for tar archives (cross-platform compatibility) | ||
| posix_path = file_path.as_posix() | ||
| tar.add( | ||
| full_path, | ||
| arcname=f"{DEFAULT_DEPLOYMENT_FILES_FOLDER}/{posix_path}", | ||
| recursive=False, | ||
| ) | ||
| manifest_files.append( | ||
| { | ||
| "relative_path": posix_path, | ||
| "size_in_bytes": full_path.stat().st_size, | ||
| } | ||
| ) | ||
| # Create and add manifest with file metadata at the end | ||
| manifest: TDeploymentManifest = { | ||
| "engine_version": DEPLOYMENT_ENGINE_VERSION, | ||
| "files": manifest_files, | ||
| } | ||
| manifest_yaml = yaml.dump( | ||
| manifest, allow_unicode=True, default_flow_style=False, sort_keys=False | ||
| ).encode("utf-8") | ||
| manifest_info = tarfile.TarInfo(name=DEFAULT_MANIFEST_FILE_NAME) | ||
| manifest_info.size = len(manifest_yaml) | ||
| tar.addfile(manifest_info, BytesIO(manifest_yaml)) | ||
|
|
||
| return digest256_tar_stream(output_stream) | ||
|
|
||
| def build_package(self, file_selector: WorkspaceFileSelector) -> Tuple[Path, str]: | ||
| """Create deployment package file, return (path, content_hash)""" | ||
| package_name = DEFAULT_DEPLOYMENT_PACKAGE_LAYOUT.format(timestamp=str(precise_time())) | ||
| package_path = Path(self.run_context.get_data_entity(package_name)) | ||
|
|
||
| with open(package_path, "w+b") as f: | ||
| content_hash = self.write_package_to_stream(file_selector, f) | ||
|
|
||
| return package_path, content_hash |
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
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 @@ | ||
| /empty_file.py |
Empty file.
3 changes: 3 additions & 0 deletions
3
tests/workspace/cases/workspaces/default/ducklake_pipeline.py
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,3 @@ | ||
| import dlt | ||
|
|
||
| pipeline = dlt.pipeline(pipeline_name="ducklake_pipeline") |
Empty file.
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,31 @@ | ||
| import os | ||
| import pytest | ||
|
|
||
| from dlt._workspace.deployment.file_selector import WorkspaceFileSelector | ||
|
|
||
| from tests.workspace.utils import isolated_workspace | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "with_additional_exclude", | ||
| [True, False], | ||
| ids=["with_additional_exclude", "without_additional_exclude"], | ||
| ) | ||
| def test_file_selector_respects_gitignore(with_additional_exclude: bool) -> None: | ||
| """Test that .gitignore patterns are respected with and without additional excludes.""" | ||
|
|
||
| additional_excludes = ["additional_exclude/"] if with_additional_exclude else None | ||
| expected_files = { | ||
| "additional_exclude/empty_file.py", | ||
| "ducklake_pipeline.py", | ||
| ".ignorefile", | ||
| } | ||
| if with_additional_exclude: | ||
| expected_files.remove("additional_exclude/empty_file.py") | ||
|
|
||
| with isolated_workspace("default") as ctx: | ||
| selector = WorkspaceFileSelector( | ||
| ctx, additional_excludes=additional_excludes, ignore_file=".ignorefile" | ||
| ) | ||
| files = set([f.as_posix() for f in selector]) | ||
| assert files == expected_files |
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,83 @@ | ||
| import os | ||
| import tarfile | ||
| import yaml | ||
| from io import BytesIO | ||
| from pathlib import Path | ||
| import time | ||
|
|
||
| from dlt._workspace.deployment.package_builder import ( | ||
| DeploymentPackageBuilder, | ||
| DEFAULT_DEPLOYMENT_FILES_FOLDER, | ||
| DEFAULT_MANIFEST_FILE_NAME, | ||
| ) | ||
| from dlt._workspace.deployment.file_selector import WorkspaceFileSelector | ||
| from dlt._workspace.deployment.manifest import DEPLOYMENT_ENGINE_VERSION | ||
|
|
||
| from tests.workspace.utils import isolated_workspace | ||
|
|
||
|
|
||
| def test_write_package_to_stream() -> None: | ||
| """Test building deployment package to a stream and verify structure.""" | ||
|
|
||
| with isolated_workspace("default") as ctx: | ||
| builder = DeploymentPackageBuilder(ctx) | ||
| selector = WorkspaceFileSelector(ctx, ignore_file=".ignorefile") | ||
|
|
||
| stream = BytesIO() | ||
| content_hash = builder.write_package_to_stream(selector, stream) | ||
|
|
||
| assert content_hash | ||
| assert len(content_hash) == 44 # sha3_256 base64 string | ||
|
|
||
| expected_workspace_files = [ | ||
| "additional_exclude/empty_file.py", | ||
| "ducklake_pipeline.py", | ||
| ".ignorefile", | ||
| ] | ||
|
|
||
| # Verify tar.gz structure | ||
| stream.seek(0) | ||
| with tarfile.open(fileobj=stream, mode="r:gz") as tar: | ||
| members = tar.getnames() | ||
|
|
||
| # Tar contains files under "files/" prefix + manifest | ||
| assert DEFAULT_MANIFEST_FILE_NAME in members | ||
| tar_files = [m for m in members if m.startswith(DEFAULT_DEPLOYMENT_FILES_FOLDER)] | ||
| assert set(tar_files) == { | ||
| f"{DEFAULT_DEPLOYMENT_FILES_FOLDER}/{f}" for f in expected_workspace_files | ||
| } | ||
|
|
||
| # Verify manifest structure | ||
| manifest_member = tar.extractfile(DEFAULT_MANIFEST_FILE_NAME) | ||
| manifest = yaml.safe_load(manifest_member) | ||
|
|
||
| assert manifest["engine_version"] == DEPLOYMENT_ENGINE_VERSION | ||
| assert all( | ||
| "relative_path" in file_item and "size_in_bytes" in file_item | ||
| for file_item in manifest["files"] | ||
| ) | ||
|
|
||
| # Manifest has workspace-relative paths (no "files/" prefix) | ||
| manifest_paths = [f["relative_path"] for f in manifest["files"]] | ||
| assert set(manifest_paths) == set(expected_workspace_files) | ||
|
|
||
|
|
||
| def test_build_package() -> None: | ||
| """Test that deployment packages are content-addressable with reproducible hashes.""" | ||
|
|
||
| with isolated_workspace("default") as ctx: | ||
| builder = DeploymentPackageBuilder(ctx) | ||
| selector = WorkspaceFileSelector(ctx) | ||
|
|
||
| package_path, content_hash = builder.build_package(selector) | ||
| assert str(package_path).startswith(f"{ctx.data_dir}{os.sep}deployment-") | ||
| assert len(content_hash) == 44 # sha3_256 base64 string | ||
|
|
||
| # NOTE: Sleep ensures tarballs have different timestamps in their metadata, proving | ||
| # digest256_tar_stream produces identical hashes despite different creation times | ||
| time.sleep(0.2) | ||
anuunchin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| package_path_2, content_hash_2 = builder.build_package(selector) | ||
|
|
||
| assert package_path != package_path_2 | ||
| assert content_hash == content_hash_2 | ||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
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.
Uh oh!
There was an error while loading. Please reload this page.