led-controller-version-3 3.0.2__py3-none-any.whl
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.
- led_controller_version_3-3.0.2.dist-info/METADATA +172 -0
- led_controller_version_3-3.0.2.dist-info/RECORD +52 -0
- led_controller_version_3-3.0.2.dist-info/WHEEL +4 -0
- led_controller_version_3-3.0.2.dist-info/entry_points.txt +13 -0
- lefx/device/respeaker/__init__.py +35 -0
- lefx/device/respeaker/cli.py +146 -0
- lefx/device/respeaker/contention.py +523 -0
- lefx/device/respeaker/provider.py +158 -0
- lefx/device/respeaker/registration.py +130 -0
- lefx/device/respeaker/sink.py +108 -0
- lefx/device/respeaker/transport.py +344 -0
- lefx/device/respeaker/xvf.py +313 -0
- lefx/engine/__init__.py +110 -0
- lefx/engine/composer.py +203 -0
- lefx/engine/config.py +27 -0
- lefx/engine/errors.py +84 -0
- lefx/engine/inputs.py +196 -0
- lefx/engine/invocation.py +129 -0
- lefx/engine/layers.py +114 -0
- lefx/engine/library.py +181 -0
- lefx/engine/packages/__init__.py +45 -0
- lefx/engine/packages/loader.py +375 -0
- lefx/engine/packages/manifest.py +308 -0
- lefx/engine/registry.py +347 -0
- lefx/engine/renderer.py +63 -0
- lefx/engine/runtime.py +393 -0
- lefx/engine/store.py +125 -0
- lefx/interfaces/__init__.py +40 -0
- lefx/interfaces/api.py +301 -0
- lefx/interfaces/cli.py +380 -0
- lefx/interfaces/client.py +165 -0
- lefx/interfaces/config.py +305 -0
- lefx/interfaces/discovery.py +308 -0
- lefx/interfaces/hosting.py +123 -0
- lefx/interfaces/paths.py +79 -0
- lefx/interfaces/presentation.py +118 -0
- lefx/interfaces/service.py +468 -0
- lefx/sdk/__init__.py +176 -0
- lefx/sdk/calibration.py +202 -0
- lefx/sdk/color.py +108 -0
- lefx/sdk/context.py +72 -0
- lefx/sdk/definitions.py +526 -0
- lefx/sdk/effects.py +63 -0
- lefx/sdk/errors.py +90 -0
- lefx/sdk/parameters.py +469 -0
- lefx/sdk/ports.py +76 -0
- lefx/sdk/validation.py +150 -0
- lefx/sdk/values.py +212 -0
- lefx/sets/core_set/__init__.py +32 -0
- lefx/sets/core_set/core-set.lefxset +0 -0
- lefx/sets/smartspeaker_set/__init__.py +32 -0
- lefx/sets/smartspeaker_set/smartspeaker-set.lefxset +0 -0
lefx/engine/library.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Which package files are loaded, and rebuilding the registry from them.
|
|
2
|
+
|
|
3
|
+
A reload builds a fresh registry and swaps it in only once every source has
|
|
4
|
+
loaded. A source that fails therefore changes nothing at all — there is no
|
|
5
|
+
half-registered state to reason about or clean up.
|
|
6
|
+
|
|
7
|
+
Discovery is explicit: the caller passes the directories to scan. The engine
|
|
8
|
+
reads no environment variables and knows no install layout, because where
|
|
9
|
+
packages live is a deployment question and this is not the deployment layer.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
from dataclasses import dataclass, replace
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Iterable
|
|
18
|
+
|
|
19
|
+
from .errors import PackageError, RegistrationError
|
|
20
|
+
from .packages import LoadedSource, PackageCache, load_source
|
|
21
|
+
from .registry import EffectRegistry
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger("lefx.engine.library")
|
|
24
|
+
|
|
25
|
+
PACKAGE_SUFFIXES = (".lefx", ".lefxset")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(slots=True, frozen=True)
|
|
29
|
+
class SourceEntry:
|
|
30
|
+
"""One package file the library knows about."""
|
|
31
|
+
|
|
32
|
+
path: Path
|
|
33
|
+
enabled: bool = True
|
|
34
|
+
autodiscovered: bool = False
|
|
35
|
+
source_id: str | None = None
|
|
36
|
+
kind: str | None = None
|
|
37
|
+
effect_count: int = 0
|
|
38
|
+
preset_count: int = 0
|
|
39
|
+
error: str | None = None
|
|
40
|
+
|
|
41
|
+
def to_dict(self) -> dict[str, Any]:
|
|
42
|
+
return {
|
|
43
|
+
"path": str(self.path),
|
|
44
|
+
"source_id": self.source_id,
|
|
45
|
+
"kind": self.kind,
|
|
46
|
+
"enabled": self.enabled,
|
|
47
|
+
"autodiscovered": self.autodiscovered,
|
|
48
|
+
"effect_count": self.effect_count,
|
|
49
|
+
"preset_count": self.preset_count,
|
|
50
|
+
"error": self.error,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def discover_packages(directories: Iterable[str | Path]) -> list[Path]:
|
|
55
|
+
"""Every ``.lefx`` and ``.lefxset`` below the given directories, sorted."""
|
|
56
|
+
found: list[Path] = []
|
|
57
|
+
for directory in directories:
|
|
58
|
+
root = Path(directory).expanduser()
|
|
59
|
+
if not root.is_dir():
|
|
60
|
+
continue
|
|
61
|
+
for suffix in PACKAGE_SUFFIXES:
|
|
62
|
+
found.extend(sorted(root.rglob(f"*{suffix}")))
|
|
63
|
+
unique: dict[Path, None] = {}
|
|
64
|
+
for path in found:
|
|
65
|
+
unique.setdefault(path.resolve(), None)
|
|
66
|
+
return list(unique)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class EffectLibrary:
|
|
70
|
+
"""Owns the source list and the registry built from it."""
|
|
71
|
+
|
|
72
|
+
def __init__(self, *, search_paths: Iterable[str | Path] = ()) -> None:
|
|
73
|
+
self._entries: list[SourceEntry] = []
|
|
74
|
+
self._suppressed: set[Path] = set()
|
|
75
|
+
self._cache = PackageCache()
|
|
76
|
+
self._registry = EffectRegistry()
|
|
77
|
+
self._search_paths = [Path(path).expanduser() for path in search_paths]
|
|
78
|
+
self.reload()
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def registry(self) -> EffectRegistry:
|
|
82
|
+
return self._registry
|
|
83
|
+
|
|
84
|
+
def sources(self) -> list[dict[str, Any]]:
|
|
85
|
+
return [entry.to_dict() for entry in self._entries]
|
|
86
|
+
|
|
87
|
+
def add_source(self, path: str | Path, *, enabled: bool = True) -> SourceEntry:
|
|
88
|
+
"""Register a package file and reload. Rejected on the first problem."""
|
|
89
|
+
resolved = Path(path).expanduser().resolve()
|
|
90
|
+
if not resolved.is_file():
|
|
91
|
+
raise PackageError(f"No package file at {resolved}")
|
|
92
|
+
if resolved.suffix not in PACKAGE_SUFFIXES:
|
|
93
|
+
raise PackageError(
|
|
94
|
+
f"{resolved.name} is not a LEFX source; expected one of: "
|
|
95
|
+
f"{', '.join(PACKAGE_SUFFIXES)}"
|
|
96
|
+
)
|
|
97
|
+
self._suppressed.discard(resolved)
|
|
98
|
+
existing = next((item for item in self._entries if item.path == resolved), None)
|
|
99
|
+
if existing is None:
|
|
100
|
+
self._entries.append(SourceEntry(path=resolved, enabled=enabled))
|
|
101
|
+
else:
|
|
102
|
+
self._entries[self._entries.index(existing)] = replace(existing, enabled=enabled)
|
|
103
|
+
self.reload()
|
|
104
|
+
return next(item for item in self._entries if item.path == resolved)
|
|
105
|
+
|
|
106
|
+
def remove_source(self, source_id: str) -> None:
|
|
107
|
+
"""Drop a source and keep it out.
|
|
108
|
+
|
|
109
|
+
Suppression is remembered rather than merely forgotten: a discovered
|
|
110
|
+
file is still sitting in a search path, so without this the next reload
|
|
111
|
+
would quietly bring it back.
|
|
112
|
+
"""
|
|
113
|
+
matching = [item for item in self._entries if item.source_id == source_id]
|
|
114
|
+
if not matching:
|
|
115
|
+
raise PackageError(f"No loaded source with id {source_id!r}")
|
|
116
|
+
self._suppressed.update(item.path for item in matching)
|
|
117
|
+
self._entries = [item for item in self._entries if item.source_id != source_id]
|
|
118
|
+
self.reload()
|
|
119
|
+
|
|
120
|
+
def reload(self) -> None:
|
|
121
|
+
"""Rebuild everything. On failure the previous registry stays in place."""
|
|
122
|
+
self._cache.clear()
|
|
123
|
+
configured = {entry.path for entry in self._entries if not entry.autodiscovered}
|
|
124
|
+
discovered = [
|
|
125
|
+
path
|
|
126
|
+
for path in discover_packages(self._search_paths)
|
|
127
|
+
if path not in configured and path not in self._suppressed
|
|
128
|
+
]
|
|
129
|
+
entries = [entry for entry in self._entries if not entry.autodiscovered]
|
|
130
|
+
entries.extend(SourceEntry(path=path, autodiscovered=True) for path in discovered)
|
|
131
|
+
|
|
132
|
+
registry = EffectRegistry()
|
|
133
|
+
rebuilt: list[SourceEntry] = []
|
|
134
|
+
for entry in entries:
|
|
135
|
+
if not entry.enabled:
|
|
136
|
+
rebuilt.append(replace(entry, effect_count=0, preset_count=0, error=None))
|
|
137
|
+
continue
|
|
138
|
+
try:
|
|
139
|
+
loaded = load_source(entry.path, workdir=self._cache.workdir(entry.path.stem))
|
|
140
|
+
_register(registry, loaded)
|
|
141
|
+
except (PackageError, RegistrationError) as exc:
|
|
142
|
+
# One bad file must not take the rest of the catalogue with it,
|
|
143
|
+
# but it also must not appear half-loaded: its definitions are
|
|
144
|
+
# simply absent and the reason is reported on the entry.
|
|
145
|
+
logger.warning("failed to load effect source %s: %s", entry.path, exc)
|
|
146
|
+
rebuilt.append(replace(entry, error=str(exc), effect_count=0, preset_count=0))
|
|
147
|
+
continue
|
|
148
|
+
rebuilt.append(
|
|
149
|
+
replace(
|
|
150
|
+
entry,
|
|
151
|
+
source_id=loaded.source_id,
|
|
152
|
+
kind=loaded.kind,
|
|
153
|
+
effect_count=len(loaded.packages),
|
|
154
|
+
preset_count=loaded.preset_count,
|
|
155
|
+
error=None,
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
self._entries = rebuilt
|
|
160
|
+
self._registry = registry
|
|
161
|
+
|
|
162
|
+
def close(self) -> None:
|
|
163
|
+
self._cache.clear()
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _register(registry: EffectRegistry, loaded: LoadedSource) -> None:
|
|
167
|
+
for package in loaded.packages:
|
|
168
|
+
registry.register_effect(
|
|
169
|
+
package.effect_class,
|
|
170
|
+
source_id=package.source_id,
|
|
171
|
+
package_id=package.package_id,
|
|
172
|
+
package_version=package.package_version,
|
|
173
|
+
)
|
|
174
|
+
# Presets come second: every one of them references a definition, and
|
|
175
|
+
# validating them needs that definition to be present already.
|
|
176
|
+
for package in loaded.packages:
|
|
177
|
+
for preset in package.presets:
|
|
178
|
+
registry.register_preset(preset)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
__all__ = ["EffectLibrary", "SourceEntry", "discover_packages"]
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""The ``lefx/3`` package format: manifests, verification and loading."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .loader import LoadedPackage, LoadedSource, PackageCache, load_source, sha256_of
|
|
6
|
+
from .manifest import (
|
|
7
|
+
HASHES_NAME,
|
|
8
|
+
MANIFEST_NAME,
|
|
9
|
+
PACKAGE_FORMAT,
|
|
10
|
+
PAYLOAD_DIR,
|
|
11
|
+
PRESETS_NAME,
|
|
12
|
+
SET_FORMAT,
|
|
13
|
+
SET_MANIFEST_NAME,
|
|
14
|
+
build_package_manifest,
|
|
15
|
+
check_manifest_matches_definition,
|
|
16
|
+
param_from_payload,
|
|
17
|
+
parse_package_manifest,
|
|
18
|
+
parse_set_manifest,
|
|
19
|
+
serialize_definition,
|
|
20
|
+
serialize_param,
|
|
21
|
+
serialize_schema,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"HASHES_NAME",
|
|
26
|
+
"MANIFEST_NAME",
|
|
27
|
+
"PACKAGE_FORMAT",
|
|
28
|
+
"PAYLOAD_DIR",
|
|
29
|
+
"PRESETS_NAME",
|
|
30
|
+
"SET_FORMAT",
|
|
31
|
+
"SET_MANIFEST_NAME",
|
|
32
|
+
"LoadedPackage",
|
|
33
|
+
"LoadedSource",
|
|
34
|
+
"PackageCache",
|
|
35
|
+
"build_package_manifest",
|
|
36
|
+
"check_manifest_matches_definition",
|
|
37
|
+
"load_source",
|
|
38
|
+
"param_from_payload",
|
|
39
|
+
"parse_package_manifest",
|
|
40
|
+
"parse_set_manifest",
|
|
41
|
+
"serialize_definition",
|
|
42
|
+
"serialize_param",
|
|
43
|
+
"serialize_schema",
|
|
44
|
+
"sha256_of",
|
|
45
|
+
]
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
"""Reading .lefx and .lefxset archives.
|
|
2
|
+
|
|
3
|
+
Three things are checked before a definition is allowed anywhere near the
|
|
4
|
+
registry: the archive contents still hash to what the build recorded, the
|
|
5
|
+
manifest still describes the class inside, and the class is the one the manifest
|
|
6
|
+
names. Any of them failing rejects the whole source — nothing is registered
|
|
7
|
+
partially.
|
|
8
|
+
|
|
9
|
+
A package carries executable Python. Hashes prove that the bytes were not
|
|
10
|
+
altered after the build; they say nothing about who wrote them. There is no
|
|
11
|
+
sandbox and no signature check, so only load packages you trust.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import importlib.util
|
|
18
|
+
import json
|
|
19
|
+
import shutil
|
|
20
|
+
import sys
|
|
21
|
+
import tempfile
|
|
22
|
+
import threading
|
|
23
|
+
import zipfile
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from io import BytesIO
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from types import ModuleType
|
|
28
|
+
from typing import Any, Iterator, Mapping
|
|
29
|
+
|
|
30
|
+
from lefx.sdk import BaseEffect, DefinitionBase
|
|
31
|
+
|
|
32
|
+
from ..errors import PackageError
|
|
33
|
+
from ..registry import Preset
|
|
34
|
+
from .manifest import (
|
|
35
|
+
HASHES_NAME,
|
|
36
|
+
MANIFEST_NAME,
|
|
37
|
+
PAYLOAD_DIR,
|
|
38
|
+
PRESETS_NAME,
|
|
39
|
+
SET_MANIFEST_NAME,
|
|
40
|
+
check_manifest_matches_definition,
|
|
41
|
+
parse_package_manifest,
|
|
42
|
+
parse_set_manifest,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
_import_lock = threading.Lock()
|
|
46
|
+
_module_counter = 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(slots=True, frozen=True)
|
|
50
|
+
class LoadedPackage:
|
|
51
|
+
"""One verified definition, ready to be registered."""
|
|
52
|
+
|
|
53
|
+
manifest: Mapping[str, Any]
|
|
54
|
+
definition: DefinitionBase
|
|
55
|
+
effect_class: type[BaseEffect]
|
|
56
|
+
presets: tuple[Preset, ...] = ()
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def source_id(self) -> str:
|
|
60
|
+
return self.manifest["source_id"]
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def package_id(self) -> str:
|
|
64
|
+
return self.manifest["package_id"]
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def effect_id(self) -> str:
|
|
68
|
+
return self.manifest["effect_id"]
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def package_version(self) -> int:
|
|
72
|
+
return int(self.manifest["package_version"])
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(slots=True, frozen=True)
|
|
76
|
+
class LoadedSource:
|
|
77
|
+
"""Everything one file contributed — a single package or a whole set."""
|
|
78
|
+
|
|
79
|
+
path: Path
|
|
80
|
+
kind: str
|
|
81
|
+
source_id: str
|
|
82
|
+
packages: tuple[LoadedPackage, ...] = ()
|
|
83
|
+
set_manifest: Mapping[str, Any] | None = None
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def preset_count(self) -> int:
|
|
87
|
+
return sum(len(package.presets) for package in self.packages)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def sha256_of(data: bytes) -> str:
|
|
91
|
+
return hashlib.sha256(data).hexdigest()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _read_json(archive: zipfile.ZipFile, name: str, label: str) -> Any:
|
|
95
|
+
try:
|
|
96
|
+
raw = archive.read(name)
|
|
97
|
+
except KeyError as exc:
|
|
98
|
+
raise PackageError(f"{label} is missing {name}") from exc
|
|
99
|
+
try:
|
|
100
|
+
return json.loads(raw.decode("utf-8"))
|
|
101
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
102
|
+
raise PackageError(f"{label} has malformed {name}: {exc}") from exc
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _verify_hashes(archive: zipfile.ZipFile, label: str) -> None:
|
|
106
|
+
"""Every member the build recorded must still hash to the recorded value."""
|
|
107
|
+
payload = _read_json(archive, HASHES_NAME, label)
|
|
108
|
+
if not isinstance(payload, Mapping) or not isinstance(payload.get("files"), Mapping):
|
|
109
|
+
raise PackageError(f"{label} has a malformed {HASHES_NAME}")
|
|
110
|
+
recorded: Mapping[str, str] = payload["files"]
|
|
111
|
+
if not recorded:
|
|
112
|
+
raise PackageError(f"{label} records no file hashes")
|
|
113
|
+
|
|
114
|
+
present = {name for name in archive.namelist() if not name.endswith("/")}
|
|
115
|
+
for name, expected in recorded.items():
|
|
116
|
+
if name not in present:
|
|
117
|
+
raise PackageError(f"{label} is missing recorded file {name}")
|
|
118
|
+
actual = sha256_of(archive.read(name))
|
|
119
|
+
if actual != expected:
|
|
120
|
+
raise PackageError(
|
|
121
|
+
f"{label} file {name} does not match its recorded hash; "
|
|
122
|
+
"the package was altered after it was built"
|
|
123
|
+
)
|
|
124
|
+
unrecorded = present - set(recorded) - {HASHES_NAME}
|
|
125
|
+
if unrecorded:
|
|
126
|
+
raise PackageError(
|
|
127
|
+
f"{label} contains files that were not part of the build: "
|
|
128
|
+
f"{', '.join(sorted(unrecorded))}"
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _next_module_name(effect_id: str) -> str:
|
|
133
|
+
global _module_counter
|
|
134
|
+
with _import_lock:
|
|
135
|
+
_module_counter += 1
|
|
136
|
+
return f"_lefx_pkg_{effect_id}_{_module_counter}"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _import_entry_module(root: Path, module_name: str, package_alias: str) -> ModuleType:
|
|
140
|
+
"""Import the payload as its own top-level package.
|
|
141
|
+
|
|
142
|
+
The payload directory becomes a package of its own so that relative imports
|
|
143
|
+
inside a source keep working, while nothing about the host application's
|
|
144
|
+
module layout leaks into it.
|
|
145
|
+
"""
|
|
146
|
+
init_path = root / "__init__.py"
|
|
147
|
+
if not init_path.is_file():
|
|
148
|
+
init_path.write_text("", encoding="utf-8")
|
|
149
|
+
|
|
150
|
+
spec = importlib.util.spec_from_file_location(
|
|
151
|
+
package_alias, init_path, submodule_search_locations=[str(root)]
|
|
152
|
+
)
|
|
153
|
+
if spec is None or spec.loader is None:
|
|
154
|
+
raise PackageError(f"Cannot import payload at {root}")
|
|
155
|
+
package = importlib.util.module_from_spec(spec)
|
|
156
|
+
sys.modules[package_alias] = package
|
|
157
|
+
try:
|
|
158
|
+
spec.loader.exec_module(package)
|
|
159
|
+
return importlib.import_module(f"{package_alias}.{module_name}")
|
|
160
|
+
except Exception as exc:
|
|
161
|
+
sys.modules.pop(package_alias, None)
|
|
162
|
+
raise PackageError(f"Failed to import {module_name} from {root}: {exc}") from exc
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _effect_class_from(module: ModuleType, entry_class: str, label: str) -> type[BaseEffect]:
|
|
166
|
+
candidate = getattr(module, entry_class, None)
|
|
167
|
+
if candidate is None:
|
|
168
|
+
raise PackageError(f"{label} declares entry class {entry_class!r}, which is missing")
|
|
169
|
+
if not isinstance(candidate, type) or not issubclass(candidate, BaseEffect):
|
|
170
|
+
raise PackageError(f"{label} entry class {entry_class!r} is not a BaseEffect subclass")
|
|
171
|
+
definition = getattr(candidate, "definition", None)
|
|
172
|
+
if not isinstance(definition, DefinitionBase):
|
|
173
|
+
raise PackageError(f"{label} entry class {entry_class!r} declares no definition")
|
|
174
|
+
return candidate
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _presets_from(payload: Any, manifest: Mapping[str, Any], label: str) -> tuple[Preset, ...]:
|
|
178
|
+
if payload is None:
|
|
179
|
+
return ()
|
|
180
|
+
if not isinstance(payload, Mapping) or not isinstance(payload.get("presets"), Mapping):
|
|
181
|
+
raise PackageError(f"{label} has a malformed {PRESETS_NAME}")
|
|
182
|
+
presets: list[Preset] = []
|
|
183
|
+
for preset_id, entry in payload["presets"].items():
|
|
184
|
+
if not isinstance(entry, Mapping):
|
|
185
|
+
raise PackageError(f"{label} preset {preset_id!r} is not an object")
|
|
186
|
+
unknown = set(entry) - {"title", "description", "tags", "params"}
|
|
187
|
+
if unknown:
|
|
188
|
+
raise PackageError(
|
|
189
|
+
f"{label} preset {preset_id!r} has unknown keys: {', '.join(sorted(unknown))}"
|
|
190
|
+
)
|
|
191
|
+
presets.append(
|
|
192
|
+
Preset(
|
|
193
|
+
preset_id=preset_id,
|
|
194
|
+
source_id=manifest["source_id"],
|
|
195
|
+
effect_id=manifest["effect_id"],
|
|
196
|
+
params=dict(entry.get("params", {})),
|
|
197
|
+
title=entry.get("title", ""),
|
|
198
|
+
description=entry.get("description", ""),
|
|
199
|
+
tags=tuple(entry.get("tags", ())),
|
|
200
|
+
)
|
|
201
|
+
)
|
|
202
|
+
return tuple(presets)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _load_package_archive(
|
|
206
|
+
archive: zipfile.ZipFile, *, label: str, workdir: Path
|
|
207
|
+
) -> LoadedPackage:
|
|
208
|
+
_verify_hashes(archive, label)
|
|
209
|
+
manifest = parse_package_manifest(_read_json(archive, MANIFEST_NAME, label))
|
|
210
|
+
|
|
211
|
+
presets_payload = None
|
|
212
|
+
if PRESETS_NAME in archive.namelist():
|
|
213
|
+
presets_payload = _read_json(archive, PRESETS_NAME, label)
|
|
214
|
+
presets = _presets_from(presets_payload, manifest, label)
|
|
215
|
+
|
|
216
|
+
root = workdir / manifest["effect_id"]
|
|
217
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
218
|
+
for name in archive.namelist():
|
|
219
|
+
if not name.startswith(f"{PAYLOAD_DIR}/") or name.endswith("/"):
|
|
220
|
+
continue
|
|
221
|
+
target = root / Path(name).relative_to(PAYLOAD_DIR)
|
|
222
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
223
|
+
target.write_bytes(archive.read(name))
|
|
224
|
+
|
|
225
|
+
alias = _next_module_name(manifest["effect_id"])
|
|
226
|
+
module = _import_entry_module(root, manifest["entry_module"], alias)
|
|
227
|
+
effect_class = _effect_class_from(module, manifest["entry_class"], label)
|
|
228
|
+
definition = effect_class.get_definition()
|
|
229
|
+
|
|
230
|
+
if definition.id != manifest["effect_id"]:
|
|
231
|
+
raise PackageError(
|
|
232
|
+
f"{label} declares effect_id {manifest['effect_id']!r} but ships "
|
|
233
|
+
f"definition {definition.id!r}"
|
|
234
|
+
)
|
|
235
|
+
check_manifest_matches_definition(manifest, definition)
|
|
236
|
+
|
|
237
|
+
return LoadedPackage(
|
|
238
|
+
manifest=manifest,
|
|
239
|
+
definition=definition,
|
|
240
|
+
effect_class=effect_class,
|
|
241
|
+
presets=presets,
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def load_source(path: str | Path, *, workdir: Path | None = None) -> LoadedSource:
|
|
246
|
+
"""Load a ``.lefx`` or ``.lefxset`` file and verify everything it contains."""
|
|
247
|
+
resolved = Path(path).expanduser().resolve()
|
|
248
|
+
if not resolved.is_file():
|
|
249
|
+
raise PackageError(f"No package file at {resolved}")
|
|
250
|
+
|
|
251
|
+
owns_workdir = workdir is None
|
|
252
|
+
target = Path(workdir) if workdir is not None else Path(
|
|
253
|
+
tempfile.mkdtemp(prefix="lefx-package-")
|
|
254
|
+
)
|
|
255
|
+
try:
|
|
256
|
+
if resolved.suffix == ".lefx":
|
|
257
|
+
with _open_archive(resolved) as archive:
|
|
258
|
+
package = _load_package_archive(
|
|
259
|
+
archive, label=resolved.name, workdir=target
|
|
260
|
+
)
|
|
261
|
+
return LoadedSource(
|
|
262
|
+
path=resolved,
|
|
263
|
+
kind="package",
|
|
264
|
+
source_id=package.source_id,
|
|
265
|
+
packages=(package,),
|
|
266
|
+
)
|
|
267
|
+
if resolved.suffix == ".lefxset":
|
|
268
|
+
return _load_set(resolved, target)
|
|
269
|
+
raise PackageError(
|
|
270
|
+
f"{resolved.name} is not a LEFX source; expected a .lefx or .lefxset file"
|
|
271
|
+
)
|
|
272
|
+
except Exception:
|
|
273
|
+
if owns_workdir:
|
|
274
|
+
shutil.rmtree(target, ignore_errors=True)
|
|
275
|
+
raise
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _open_archive(path: Path) -> zipfile.ZipFile:
|
|
279
|
+
"""Open an archive, reporting a non-archive as a package problem.
|
|
280
|
+
|
|
281
|
+
A file that is not a zip at all is just another malformed package, and the
|
|
282
|
+
library treats every package problem the same way.
|
|
283
|
+
"""
|
|
284
|
+
try:
|
|
285
|
+
return zipfile.ZipFile(path)
|
|
286
|
+
except zipfile.BadZipFile as exc:
|
|
287
|
+
raise PackageError(f"{path.name} is not a readable LEFX archive: {exc}") from exc
|
|
288
|
+
except OSError as exc:
|
|
289
|
+
raise PackageError(f"Cannot read {path}: {exc}") from exc
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _load_set(path: Path, workdir: Path) -> LoadedSource:
|
|
293
|
+
label = path.name
|
|
294
|
+
with _open_archive(path) as archive:
|
|
295
|
+
_verify_hashes(archive, label)
|
|
296
|
+
manifest = parse_set_manifest(_read_json(archive, SET_MANIFEST_NAME, label))
|
|
297
|
+
packages: list[LoadedPackage] = []
|
|
298
|
+
for member in manifest["effects"]:
|
|
299
|
+
name = f"effects/{member}"
|
|
300
|
+
if name not in archive.namelist():
|
|
301
|
+
raise PackageError(f"{label} lists {member!r}, which is not in the archive")
|
|
302
|
+
try:
|
|
303
|
+
inner_archive = zipfile.ZipFile(_member_stream(archive, name))
|
|
304
|
+
except zipfile.BadZipFile as exc:
|
|
305
|
+
raise PackageError(f"{label} member {member!r} is not a readable archive") from exc
|
|
306
|
+
with inner_archive as inner:
|
|
307
|
+
package = _load_package_archive(
|
|
308
|
+
inner, label=f"{label}:{member}", workdir=workdir
|
|
309
|
+
)
|
|
310
|
+
if package.source_id != manifest["source_id"]:
|
|
311
|
+
raise PackageError(
|
|
312
|
+
f"{label} member {member!r} declares source {package.source_id!r} "
|
|
313
|
+
f"but the set is {manifest['source_id']!r}; every member shares "
|
|
314
|
+
"the set's source namespace"
|
|
315
|
+
)
|
|
316
|
+
packages.append(package)
|
|
317
|
+
|
|
318
|
+
_check_unique_ids(packages, label)
|
|
319
|
+
return LoadedSource(
|
|
320
|
+
path=path,
|
|
321
|
+
kind="set",
|
|
322
|
+
source_id=manifest["source_id"],
|
|
323
|
+
packages=tuple(packages),
|
|
324
|
+
set_manifest=manifest,
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _member_stream(archive: zipfile.ZipFile, name: str) -> BytesIO:
|
|
329
|
+
return BytesIO(archive.read(name))
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _check_unique_ids(packages: list[LoadedPackage], label: str) -> None:
|
|
333
|
+
"""Definition and preset ids share one namespace, inside a set as well."""
|
|
334
|
+
seen: dict[str, str] = {}
|
|
335
|
+
for package in packages:
|
|
336
|
+
for identifier, what in _identifiers(package):
|
|
337
|
+
previous = seen.get(identifier)
|
|
338
|
+
if previous is not None:
|
|
339
|
+
raise PackageError(
|
|
340
|
+
f"{label} declares {identifier!r} twice ({previous} and {what})"
|
|
341
|
+
)
|
|
342
|
+
seen[identifier] = what
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _identifiers(package: LoadedPackage) -> Iterator[tuple[str, str]]:
|
|
346
|
+
yield package.effect_id, f"definition in {package.package_id}"
|
|
347
|
+
for preset in package.presets:
|
|
348
|
+
yield preset.preset_id, f"preset in {package.package_id}"
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
@dataclass(slots=True)
|
|
352
|
+
class PackageCache:
|
|
353
|
+
"""Holds the extracted payloads of everything currently loaded."""
|
|
354
|
+
|
|
355
|
+
root: Path = field(
|
|
356
|
+
default_factory=lambda: Path(tempfile.mkdtemp(prefix="lefx-packages-"))
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
def workdir(self, name: str) -> Path:
|
|
360
|
+
target = self.root / name
|
|
361
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
362
|
+
return target
|
|
363
|
+
|
|
364
|
+
def clear(self) -> None:
|
|
365
|
+
shutil.rmtree(self.root, ignore_errors=True)
|
|
366
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
__all__ = [
|
|
370
|
+
"LoadedPackage",
|
|
371
|
+
"LoadedSource",
|
|
372
|
+
"PackageCache",
|
|
373
|
+
"load_source",
|
|
374
|
+
"sha256_of",
|
|
375
|
+
]
|