-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin.py
More file actions
198 lines (161 loc) · 6.75 KB
/
Copy pathplugin.py
File metadata and controls
198 lines (161 loc) · 6.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import os
import sys
# Dirty hack to bring our own vendored dependencies without interfering with the host's Python environment
sys.path.insert(
0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "src", "vendor")
)
import json
import yaml
from dacite import Config, from_dict
from typing import Any, Mapping, Protocol, cast
from .src.types.plugins import Plugin as DispatcharrPlugin
from .src.types.plugins import PluginFieldType
from .src.types.config import WaybillConfig
from .src.pipeline import WaybillPipeline
from .src.plan import WaybillPlanFormatter
from .src.apply import WaybillApplier
class WaybillError(Exception):
"""Base class for plugin runtime errors."""
class WaybillConfigurationError(WaybillError):
"""Raised when plugin configuration cannot be parsed or validated."""
class WaybillContextError(WaybillError):
"""Raised when runtime context is missing required contracts."""
class WaybillActionError(WaybillError):
"""Raised when an unsupported action is requested."""
class WaybillValidationError(WaybillError):
"""Raised when one or more fail-action validators are violated."""
class WaybillLogger(Protocol):
def info(self, message: str) -> None: ...
def warning(self, message: str) -> None: ...
def error(self, message: str) -> None: ...
class Plugin(DispatcharrPlugin):
def __init__(self, path: str = "plugin.json") -> None:
# Keep the plugin manifest as source of truth for metadata.
plugin_dir = os.path.dirname(os.path.abspath(__file__))
plugin = self._load_manifest(os.path.join(plugin_dir, path))
super().__init__(
name=plugin.name,
version=plugin.version,
description=plugin.description,
author=plugin.author,
fields=plugin.fields,
actions=plugin.actions,
)
return None
def _load_manifest(self, path: str) -> DispatcharrPlugin:
with open(path, "r", encoding="utf-8") as f:
raw = json.load(f)
return from_dict(
data_class=DispatcharrPlugin,
data=raw,
config=Config(cast=[PluginFieldType]),
)
def _require_logger(self, context: Mapping[str, Any]) -> WaybillLogger:
logger = context.get("logger")
if logger is None:
raise WaybillContextError("Runtime context is missing a logger")
for method in ("info", "warning", "error"):
if not callable(getattr(logger, method, None)):
raise WaybillContextError(
f"Runtime logger is missing required method {method!r}"
)
return cast(WaybillLogger, logger)
def _load_configuration(self, context: Mapping[str, Any]) -> None:
config_data_raw = context.get("settings", {})
if not isinstance(config_data_raw, dict):
raise WaybillConfigurationError("Configuration settings must be a mapping")
config_data = cast(dict[str, Any], config_data_raw)
manifest_value = config_data.get("manifest", "")
if not isinstance(manifest_value, str) or not manifest_value.strip():
raise WaybillConfigurationError(
"Configuration manifest is empty or missing"
)
try:
parsed = yaml.safe_load(manifest_value)
except yaml.YAMLError as e:
raise WaybillConfigurationError(
f"Configuration manifest is not valid YAML: {e}"
) from e
if not isinstance(parsed, dict):
raise WaybillConfigurationError(
"Configuration manifest did not parse to a mapping "
f"(got {type(parsed).__name__})"
)
parsed_dict = cast(dict[Any, Any], parsed)
parsed_mapping: dict[str, Any] = {str(k): v for k, v in parsed_dict.items()}
try:
self.configuration = WaybillConfig(**parsed_mapping)
except TypeError as e:
raise WaybillConfigurationError(
f"Configuration manifest shape is invalid: {e}"
) from e
except ValueError as e:
raise WaybillConfigurationError(
f"Configuration manifest failed invariant checks: {e}"
) from e
return None
def _run_plan(self, logger: WaybillLogger) -> None:
pipeline = WaybillPipeline(self.configuration)
plan = pipeline.compute_plan()
formatter = WaybillPlanFormatter()
for line in formatter.format(plan):
logger.info(line)
if plan.has_failures():
fail_count = sum(
1
for profile in plan.profiles
for group in profile.groups
for member in group.members
for v in member.violations
if v.action == "fail"
)
raise WaybillValidationError(
f"Validation failed: {fail_count} fail violation(s) detected"
)
def _run_apply(
self,
logger: WaybillLogger,
params: Mapping[str, Any],
context: Mapping[str, Any],
) -> None:
settings = context.get("settings", {})
apply_mode: Any = None
if isinstance(settings, dict):
settings_dict = cast(dict[str, Any], settings)
apply_mode = settings_dict.get("apply_mode")
param_mode = params.get("mode")
mode = (
(param_mode if isinstance(param_mode, str) and param_mode else None)
or (apply_mode if isinstance(apply_mode, str) and apply_mode else None)
or "upsert"
)
pipeline = WaybillPipeline(self.configuration)
plan = pipeline.compute_plan()
if plan.has_failures():
fail_count = sum(
1
for profile in plan.profiles
for group in profile.groups
for member in group.members
for v in member.violations
if v.action == "fail"
)
formatter = WaybillPlanFormatter()
for line in formatter.format(plan):
logger.error(line)
raise WaybillValidationError(
f"Validation failed: {fail_count} fail violation(s) detected — database not modified"
)
applier = WaybillApplier(plan, mode, logger)
applier.apply()
def run(self, action: str, params: dict[str, Any], context: dict[str, Any]) -> None:
self._load_configuration(context)
logger = self._require_logger(context)
if action == "plan":
self._run_plan(logger)
return None
if action == "apply":
self._run_apply(logger, params, context)
return None
logger.warning(f"Unknown action: {action!r}")
raise WaybillActionError(f"Unknown action: {action!r}")