pinta-lib 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.3
2
+ Name: pinta-lib
3
+ Version: 0.1.0
4
+ Summary: Common library for the elevation production system
5
+ Requires-Python: >=3.12, <3.14
6
+ Project-URL: Homepage, https://github.com/nlsfi/pinta
7
+ Project-URL: Repository, https://github.com/nlsfi/pinta
8
+ Description-Content-Type: text/markdown
9
+
10
+ # Common utils
11
+
12
+ This component contains common utils between components.
@@ -0,0 +1,3 @@
1
+ # Common utils
2
+
3
+ This component contains common utils between components.
@@ -0,0 +1,78 @@
1
+ [project]
2
+ name = "pinta-lib"
3
+ version = "0.1.0"
4
+ description = "Common library for the elevation production system"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12,<3.14"
7
+ dependencies = []
8
+
9
+ [project.urls]
10
+ Homepage = "https://github.com/nlsfi/pinta"
11
+ Repository = "https://github.com/nlsfi/pinta"
12
+
13
+ [tool.uv]
14
+ default-groups = [
15
+ "dev",
16
+ "lint",
17
+ ]
18
+
19
+ [tool.uv.build-backend]
20
+ module-name = [
21
+ "pinta_test_utils",
22
+ "pinta_common",
23
+ ]
24
+ include = [
25
+ "py.typed",
26
+ "constraints.txt",
27
+ ]
28
+
29
+ [tool.semantic_release]
30
+ commit_parser = "conventional-monorepo"
31
+ major_on_zero = false
32
+ allow_zero_version = true
33
+ commit_message = """
34
+ chore(release): pinta-lib@{version}
35
+
36
+ Automatically generated by python-semantic-release
37
+ """
38
+ tag_format = "pinta-lib-v{version}"
39
+ version_toml = ["pyproject.toml:project.version"]
40
+ build_command = """
41
+ set -euo pipefail
42
+ python -m pip install uv packaging
43
+ rm -rf dist
44
+ uv lock --upgrade-package "$PACKAGE_NAME"
45
+ git add ../../uv.lock
46
+ python ../../scripts/build_constraints.py --module pinta_common
47
+ uv build --out-dir dist
48
+ python ../../scripts/check_wheel_constraints.py --module pinta_common
49
+ """
50
+
51
+ [tool.semantic_release.commit_parser_options]
52
+ path_filters = ["."]
53
+ scope_prefix = "lib"
54
+ minor_tags = ["feat"]
55
+ patch_tags = [
56
+ "fix",
57
+ "build",
58
+ ]
59
+
60
+ [tool.semantic_release.changelog]
61
+ mode = "init"
62
+ exclude_commit_patterns = ['(?!(?:feat|fix)(?:\([^)]*?\))?!?: ).*']
63
+
64
+ [tool.semantic_release.branches.main]
65
+ match = "(main|master)"
66
+ prerelease_token = "dev"
67
+
68
+ [dependency-groups]
69
+ dev = ["pytest>=9.0.2"]
70
+ lint = [
71
+ "prek",
72
+ "mypy",
73
+ "ruff",
74
+ ]
75
+
76
+ [build-system]
77
+ requires = ["uv_build>=0.13.7,<0.14.0"]
78
+ build-backend = "uv_build"
@@ -0,0 +1,75 @@
1
+ [project]
2
+ name = "pinta-lib"
3
+ version = "0.1.0"
4
+ description = "Common library for the elevation production system"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12,<3.14"
7
+
8
+ dependencies = [
9
+ ]
10
+
11
+ [project.urls]
12
+ Homepage = "https://github.com/nlsfi/pinta"
13
+ Repository = "https://github.com/nlsfi/pinta"
14
+
15
+ [tool.uv]
16
+ default-groups = ["dev", "lint"]
17
+
18
+ [dependency-groups]
19
+ dev = [
20
+ "pytest>=9.0.2",
21
+ ]
22
+ lint = [
23
+ "prek",
24
+ "mypy",
25
+ "ruff",
26
+ ]
27
+
28
+ [build-system]
29
+ requires = ["uv_build>=0.13.7,<0.14.0"]
30
+ build-backend = "uv_build"
31
+
32
+ [tool.uv.build-backend]
33
+ module-name = ["pinta_test_utils", "pinta_common"]
34
+ include = ["py.typed", "constraints.txt"]
35
+
36
+ [tool.semantic_release]
37
+ commit_parser = "conventional-monorepo"
38
+ major_on_zero = false
39
+ allow_zero_version = true
40
+ commit_message = """\
41
+ chore(release): pinta-lib@{version}
42
+
43
+ Automatically generated by python-semantic-release
44
+ """
45
+ tag_format = "pinta-lib-v{version}"
46
+ version_toml = ["pyproject.toml:project.version"]
47
+ build_command = """
48
+ set -euo pipefail
49
+ python -m pip install uv packaging
50
+ rm -rf dist
51
+ uv lock --upgrade-package "$PACKAGE_NAME"
52
+ git add ../../uv.lock
53
+ python ../../scripts/build_constraints.py --module pinta_common
54
+ uv build --out-dir dist
55
+ python ../../scripts/check_wheel_constraints.py --module pinta_common
56
+ """
57
+
58
+ [tool.semantic_release.commit_parser_options]
59
+ path_filters = ["."]
60
+ scope_prefix = "lib"
61
+ # Only feat, fix and build (dependency bumps) commits are releasable
62
+ minor_tags = ["feat"]
63
+ patch_tags = ["fix", "build"]
64
+
65
+ [tool.semantic_release.changelog]
66
+ # Re-create the changelog from the full history on every release
67
+ mode = "init"
68
+ # Keep only feat and fix commits in the changelog
69
+ exclude_commit_patterns = [
70
+ '''(?!(?:feat|fix)(?:\([^)]*?\))?!?: ).*''',
71
+ ]
72
+
73
+ [tool.semantic_release.branches.main]
74
+ match = "(main|master)"
75
+ prerelease_token = "dev"
@@ -0,0 +1,8 @@
1
+ # Copyright (c) 2026 National Land Survey of Finland
2
+ # (https://www.maanmittauslaitos.fi/en).
3
+ # This file is part of the Pinta.
4
+ # Licensed under the MIT License; see the repository LICENSE file.
5
+
6
+ from pinta_common.settings import MASK_OGR_ENV_PREFIX, Settings
7
+
8
+ __all__ = ["MASK_OGR_ENV_PREFIX", "Settings"]
@@ -0,0 +1,16 @@
1
+ # Copyright (c) 2026 National Land Survey of Finland
2
+ # (https://www.maanmittauslaitos.fi/en).
3
+ # This file is part of the Pinta.
4
+ # Licensed under the MIT License; see the repository LICENSE file.
5
+
6
+ # DAG ids
7
+ DAG_ID_HELLO_WORLD = "print_hello_world"
8
+ DAG_ID_LOAD_DEM = "load_dem_from_files"
9
+ DAG_ID_PROCESS_PRODUCTION_AREAS = "process_production_areas"
10
+ DAG_ID_CALCULATE_REFERENCE_DEM = "calculate_reference_dem"
11
+ DAG_ID_CALCULATE_DEM_DIFF = "calculate_dem_diff"
12
+ DAG_ID_INITIALIZE_DEM_PREVIEW = "initialize_dem_preview"
13
+ DAG_ID_DISSOLVE_UPDATE_AREAS = "dissolve_update_areas"
14
+ DAG_ID_REGISTER_UPDATE_AREAS = "register_update_areas"
15
+ DAG_ID_SUGGEST_MASKED_UPDATE_AREAS = "suggest_masked_update_areas"
16
+ DAG_ID_CALCULATE_RASTERS_FOR_PRODUCTION_AREA = "calculate_rasters_for_production_area"
@@ -0,0 +1,36 @@
1
+ # Copyright (c) 2026 National Land Survey of Finland
2
+ # (https://www.maanmittauslaitos.fi/en).
3
+ # This file is part of the Pinta.
4
+ # Licensed under the MIT License; see the repository LICENSE file.
5
+
6
+ from collections.abc import Iterable
7
+ from pathlib import Path
8
+
9
+
10
+ class MissingEnvironmentError(RuntimeError):
11
+ def __init__(self, env_variable_name: str) -> None:
12
+ super().__init__(
13
+ f"Environment configuration error: {env_variable_name}",
14
+ )
15
+
16
+
17
+ class FeatureFlagError(Exception):
18
+ pass
19
+
20
+
21
+ class FeatureFlagConfigError(FeatureFlagError):
22
+ def __init__(self, config_file: Path, reason: str) -> None:
23
+ super().__init__(f"Invalid feature flag config {config_file}: {reason}")
24
+
25
+
26
+ class FeatureFlagDefinitionError(FeatureFlagError):
27
+ def __init__(self, name: str, reason: str) -> None:
28
+ super().__init__(f'Invalid feature flag "{name}": {reason}')
29
+
30
+
31
+ class MissingFeatureFlagError(FeatureFlagError):
32
+ def __init__(self, config_file: Path, names: Iterable[str]) -> None:
33
+ self.names = sorted(names)
34
+ super().__init__(
35
+ f"Feature flags missing from {config_file}: {', '.join(self.names)}"
36
+ )
@@ -0,0 +1,127 @@
1
+ # Copyright (c) 2026 National Land Survey of Finland
2
+ # (https://www.maanmittauslaitos.fi/en).
3
+ # This file is part of the Pinta.
4
+ # Licensed under the MIT License; see the repository LICENSE file.
5
+
6
+ import json
7
+ import logging
8
+ import time
9
+ from dataclasses import dataclass
10
+ from functools import lru_cache
11
+ from pathlib import Path
12
+
13
+ from pinta_common import exceptions, settings
14
+
15
+ LOGGER = logging.getLogger(__name__)
16
+
17
+ DEFAULT_TTL_SECONDS = 5.0
18
+
19
+
20
+ class FeatureFlagRegistry:
21
+ """Declared flags and their states, re-read from the config file every ttl."""
22
+
23
+ def __init__(self, config_file: Path, ttl: float = DEFAULT_TTL_SECONDS) -> None:
24
+ if not config_file.exists():
25
+ raise exceptions.FeatureFlagConfigError(config_file, "file not found")
26
+ self._config_file = config_file
27
+ self._ttl = ttl
28
+ self._flags: dict[str, FeatureFlag] = {}
29
+
30
+ def flag(self, name: str) -> "FeatureFlag | None":
31
+ """Return the declared flag with the given name."""
32
+ return self._flags.get(name)
33
+
34
+ def add(self, feature_flag: "FeatureFlag") -> None:
35
+ """Declare a flag, raising if the config file does not contain it."""
36
+ self._state(feature_flag.name)
37
+ self._flags[feature_flag.name] = feature_flag
38
+
39
+ def flag_state(self, name: str) -> bool:
40
+ """Return the current state of the flag from the config file."""
41
+ return self._state(name)[name]
42
+
43
+ def _state(self, *extra_names: str) -> dict[str, bool]:
44
+ bucket = (
45
+ int(time.monotonic() // self._ttl) if self._ttl > 0 else time.monotonic_ns()
46
+ )
47
+ names = tuple(sorted((*self._flags, *extra_names)))
48
+ return _load_state(self._config_file, bucket, names)
49
+
50
+
51
+ def clear_cache() -> None:
52
+ """Force a re-read of the config file on the next state lookup."""
53
+ _load_state.cache_clear()
54
+
55
+
56
+ @lru_cache(maxsize=1)
57
+ def _load_state(
58
+ config_file: Path, _bucket: int, names: tuple[str, ...]
59
+ ) -> dict[str, bool]:
60
+ """Read the config file and check that it contains every name."""
61
+ LOGGER.debug("Reading feature flags from %s", config_file)
62
+ try:
63
+ content = json.loads(config_file.read_text(encoding="utf-8"))
64
+ except json.JSONDecodeError as e:
65
+ raise exceptions.FeatureFlagConfigError(config_file, str(e)) from e
66
+
67
+ state: dict[str, bool] = {}
68
+ for name, entry in content.items():
69
+ enabled = entry.get("enabled") if isinstance(entry, dict) else None
70
+ if not isinstance(enabled, bool):
71
+ raise exceptions.FeatureFlagConfigError(
72
+ config_file, f'"{name}" must have a boolean "enabled" value'
73
+ )
74
+ state[name] = enabled
75
+
76
+ missing = set(names) - state.keys()
77
+ if missing:
78
+ raise exceptions.MissingFeatureFlagError(config_file, missing)
79
+ return state
80
+
81
+
82
+ def _create_registry() -> FeatureFlagRegistry | None:
83
+ # No config file is needed in development mode, every flag is enabled
84
+ if settings.Settings.DEVELOPMENT_MODE:
85
+ return None
86
+ return FeatureFlagRegistry(Path(settings.Settings.FEATURE_FLAG_CONFIG))
87
+
88
+
89
+ _registry = _create_registry()
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class FeatureFlag:
94
+ """A flag that exists in this project. Declaring one registers it."""
95
+
96
+ name: str
97
+ description: str
98
+
99
+ def __post_init__(self) -> None:
100
+ if not self.name.strip():
101
+ raise exceptions.FeatureFlagDefinitionError(self.name, "name is empty")
102
+ if not self.description.strip():
103
+ raise exceptions.FeatureFlagDefinitionError(
104
+ self.name, "description is empty"
105
+ )
106
+ if _registry is None:
107
+ LOGGER.warning("No feature flag registry, development mode is active.")
108
+ return
109
+ existing = _registry.flag(self.name)
110
+ if existing is None:
111
+ _registry.add(self)
112
+ elif existing != self:
113
+ raise exceptions.FeatureFlagDefinitionError(self.name, "declared twice")
114
+
115
+ @property
116
+ def enabled(self) -> bool:
117
+ """Current state, from the config file."""
118
+ if _registry is None:
119
+ return True
120
+ return _registry.flag_state(self.name)
121
+
122
+ def __bool__(self) -> bool:
123
+ # Lets you write `if FLAG_SOMETHING:`
124
+ return self.enabled
125
+
126
+ def __str__(self) -> str:
127
+ return f"{self.name} - enabled: {self.enabled}"
@@ -0,0 +1,12 @@
1
+ # Copyright (c) 2026 National Land Survey of Finland
2
+ # (https://www.maanmittauslaitos.fi/en).
3
+ # This file is part of the Pinta.
4
+ # Licensed under the MIT License; see the repository LICENSE file.
5
+
6
+ from pinta_common import constants
7
+ from pinta_common.feature_flag_registry import FeatureFlag
8
+
9
+ FLAG_TEST_DAG_PRINT_CURRENT_TIME = FeatureFlag(
10
+ name="FLAG_TEST_DAG_PRINT_CURRENT_TIME",
11
+ description=f"Prints the current time in the {constants.DAG_ID_HELLO_WORLD} DAG",
12
+ )
File without changes
@@ -0,0 +1,77 @@
1
+ # Copyright (c) 2026 National Land Survey of Finland
2
+ # (https://www.maanmittauslaitos.fi/en).
3
+ # This file is part of the Pinta.
4
+ # Licensed under the MIT License; see the repository LICENSE file.
5
+
6
+ import os
7
+
8
+ from pinta_common import exceptions
9
+
10
+ TRUTHY_STRINGS = ("1", "true", "yes", "t")
11
+
12
+ # Every environment variable with this prefix holds one vector mask source,
13
+ # read by the processing component.
14
+ MASK_OGR_ENV_PREFIX = "PINTA_PROCESSING_MASK_OGR_"
15
+
16
+
17
+ def _require(name: str) -> str:
18
+ """Return the environment variable `name` or raise if it is unset."""
19
+ try:
20
+ return os.environ[name]
21
+ except KeyError:
22
+ raise exceptions.MissingEnvironmentError(name) from None
23
+
24
+
25
+ def _is_truthy(value: str) -> bool:
26
+ """Check if the env variable represents a truthy value."""
27
+ return value.lower() in TRUTHY_STRINGS
28
+
29
+
30
+ class _Settings:
31
+ """Pinta shared runtime configuration read from the environment.
32
+
33
+ Each value is read from the environment on access rather than at import
34
+ time.
35
+ """
36
+
37
+ @property
38
+ def DB_SRID(self) -> str: # noqa: N802
39
+ return _require("DB_SRID")
40
+
41
+ @property
42
+ def DB_DEM_PIXEL_SIZE(self) -> int: # noqa: N802
43
+ return int(_require("DB_DEM_PIXEL_SIZE"))
44
+
45
+ @property
46
+ def DB_DEM_NODATA(self) -> float: # noqa: N802
47
+ return float(_require("DB_DEM_NODATA"))
48
+
49
+ @property
50
+ def DB_DEFAULT_TILE_SIZE(self) -> int: # noqa: N802
51
+ return int(os.environ.get("DB_DEFAULT_TILE_SIZE", "256"))
52
+
53
+ @property
54
+ def DB_JOB_TEMPLATE_NAME(self) -> str: # noqa: N802
55
+ return os.environ.get("DB_JOB_TEMPLATE_NAME", "job_template")
56
+
57
+ @property
58
+ def DB_JOB_WRITER_ROLE(self) -> str: # noqa: N802
59
+ # Group role QGIS editors write through. Same variable the job database
60
+ # migrations create the role from.
61
+ return os.environ.get("DB_JOB_WRITER_ROLE", "pinta_writer")
62
+
63
+ @property
64
+ def LASTOOLS_DEMO_MODE(self) -> bool: # noqa: N802
65
+ # When set to a truthy value, LASTools commands are invoked with `-demo`.
66
+ return _is_truthy(os.environ.get("LASTOOLS_DEMO_MODE", ""))
67
+
68
+ @property
69
+ def DEVELOPMENT_MODE(self) -> bool: # noqa: N802
70
+ return _is_truthy(os.environ.get("PINTA_DEVELOPMENT_MODE", ""))
71
+
72
+ @property
73
+ def FEATURE_FLAG_CONFIG(self) -> str: # noqa: N802
74
+ return _require("PINTA_FEATURE_FLAG_CONFIG")
75
+
76
+
77
+ Settings = _Settings()
@@ -0,0 +1,4 @@
1
+ # Copyright (c) 2026 National Land Survey of Finland
2
+ # (https://www.maanmittauslaitos.fi/en).
3
+ # This file is part of the Pinta.
4
+ # Licensed under the MIT License; see the repository LICENSE file.
@@ -0,0 +1,4 @@
1
+ # Copyright (c) 2026 National Land Survey of Finland
2
+ # (https://www.maanmittauslaitos.fi/en).
3
+ # This file is part of the Pinta.
4
+ # Licensed under the MIT License; see the repository LICENSE file.
@@ -0,0 +1,39 @@
1
+ # Copyright (c) 2026 National Land Survey of Finland
2
+ # (https://www.maanmittauslaitos.fi/en).
3
+ # This file is part of the Pinta.
4
+ # Licensed under the MIT License; see the repository LICENSE file.
5
+
6
+ import json
7
+ import pathlib
8
+ from collections.abc import Callable, Iterator
9
+
10
+ import pytest
11
+ from pinta_common import feature_flag_registry
12
+
13
+
14
+ @pytest.fixture(autouse=True)
15
+ def _isolate_feature_flag_registry() -> Iterator[None]:
16
+ """Fail the test if it leaves a registry behind for the next one."""
17
+ registry_before = feature_flag_registry._registry
18
+ yield
19
+ feature_flag_registry.clear_cache()
20
+ assert feature_flag_registry._registry is registry_before, (
21
+ "feature flag registry leaked from the test"
22
+ )
23
+
24
+
25
+ @pytest.fixture
26
+ def set_feature_flags(
27
+ monkeypatch: "pytest.MonkeyPatch", tmp_path: pathlib.Path
28
+ ) -> Callable[[dict[str, bool]], pathlib.Path]:
29
+ """Write a flag config file and point the registry at it for this test."""
30
+
31
+ def _set_feature_flags(flag_values: dict[str, bool]) -> pathlib.Path:
32
+ config_file = tmp_path / "feature_flags.json"
33
+ content = {name: {"enabled": enabled} for name, enabled in flag_values.items()}
34
+ config_file.write_text(json.dumps(content), encoding="utf-8")
35
+ registry = feature_flag_registry.FeatureFlagRegistry(config_file, ttl=0)
36
+ monkeypatch.setattr(feature_flag_registry, "_registry", registry)
37
+ return config_file
38
+
39
+ return _set_feature_flags
@@ -0,0 +1,27 @@
1
+ # Copyright (c) 2026 National Land Survey of Finland
2
+ # (https://www.maanmittauslaitos.fi/en).
3
+ # This file is part of the Pinta.
4
+ # Licensed under the MIT License; see the repository LICENSE file.
5
+
6
+ from pathlib import Path
7
+
8
+
9
+ def get_test_data_path(relative_path: str | Path, check_if_exists: bool = True) -> Path:
10
+ """
11
+ Return the absolute path to a file or folder inside test_data, relative to the project root.
12
+ """
13
+ project_root = get_project_root()
14
+ test_data_dir = project_root / "test_data"
15
+ if check_if_exists:
16
+ assert test_data_dir.exists(), (
17
+ f"test_data directory not found at {test_data_dir}"
18
+ )
19
+ resource = test_data_dir / Path(relative_path)
20
+ if check_if_exists:
21
+ assert resource.exists(), f"Resource not found at {resource}"
22
+ return resource
23
+
24
+
25
+ def get_project_root() -> Path:
26
+ """Return the absolute path to the project root."""
27
+ return Path(__file__).parent.parent.parent.parent.parent
File without changes
@@ -0,0 +1,77 @@
1
+ # Copyright (c) 2026 National Land Survey of Finland
2
+ # (https://www.maanmittauslaitos.fi/en).
3
+ # This file is part of the Pinta.
4
+ # Licensed under the MIT License; see the repository LICENSE file.
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+
9
+
10
+ def _get_optimal_worker_number_for_pytest_xdist(config: pytest.Config) -> int:
11
+ cpu_count = _get_available_cpu_count(config)
12
+ if config.option.maxprocesses:
13
+ cpu_count = min(cpu_count, config.option.maxprocesses)
14
+ return cpu_count
15
+
16
+
17
+ def _get_available_cpu_count(config: pytest.Config) -> int:
18
+ try:
19
+ import psutil # noqa: PLC0415
20
+ except ImportError:
21
+ pass
22
+ else:
23
+ use_logical = config.option.numprocesses == "logical"
24
+ count = psutil.cpu_count(logical=use_logical) or psutil.cpu_count()
25
+ if count:
26
+ return count
27
+ try:
28
+ from os import sched_getaffinity # noqa: PLC0415
29
+
30
+ def cpu_count() -> int:
31
+ return len(sched_getaffinity(0))
32
+
33
+ except ImportError:
34
+ try:
35
+ from os import cpu_count # type: ignore[assignment] # noqa: PLC0415
36
+ except ImportError:
37
+ from multiprocessing import cpu_count # noqa: PLC0415
38
+ try:
39
+ n = cpu_count()
40
+ except NotImplementedError:
41
+ return 1
42
+ return n or 1
43
+
44
+
45
+ def get_number_of_workers(
46
+ config: "pytest.Config",
47
+ run_package_tests_with_one_worker: bool = False,
48
+ ) -> int:
49
+ """Determine how many workers to use when running tests.
50
+
51
+ This hook is called only if using -n auto.
52
+
53
+ If number of workers is zero, debugging works.
54
+ To enable debugging when running multiple tests,
55
+ comment out line "addopts = ..." in pytest.ini.
56
+ """
57
+ if not config.invocation_params.args:
58
+ return 0
59
+
60
+ invocation_string = config.invocation_params.args[0]
61
+ # Running a single test
62
+ if "::" in invocation_string:
63
+ return 0
64
+
65
+ optimal_count = _get_optimal_worker_number_for_pytest_xdist(config)
66
+ if not run_package_tests_with_one_worker:
67
+ return optimal_count
68
+
69
+ path = Path(invocation_string)
70
+ if path.is_dir():
71
+ for child in path.iterdir():
72
+ if child.is_dir() and child.name != "__pycache__":
73
+ # Running package which contains directories
74
+ return optimal_count
75
+
76
+ # Running a single package, probably 0 workers will do just fine
77
+ return 0