operaton-contracts 0.1.0__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.
- OperatonContracts/__init__.py +61 -0
- OperatonContracts/__main__.py +3 -0
- OperatonContracts/checks.py +88 -0
- OperatonContracts/cli.py +124 -0
- OperatonContracts/contracts.py +105 -0
- OperatonContracts/py.typed +0 -0
- OperatonContracts/robotframework.py +212 -0
- OperatonContracts/templates.py +287 -0
- operaton_contracts-0.1.0.dist-info/METADATA +174 -0
- operaton_contracts-0.1.0.dist-info/RECORD +13 -0
- operaton_contracts-0.1.0.dist-info/WHEEL +4 -0
- operaton_contracts-0.1.0.dist-info/entry_points.txt +2 -0
- operaton_contracts-0.1.0.dist-info/licenses/LICENSE +177 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Engine-facing Operaton external task contracts.
|
|
2
|
+
|
|
3
|
+
A worker declares one ``TaskContract`` input and output model per external
|
|
4
|
+
task topic. Element templates are generated from those models (see
|
|
5
|
+
``OperatonContracts.templates`` and the ``operaton-contracts`` command), and
|
|
6
|
+
tasks validate their variables against them at runtime with
|
|
7
|
+
``validate_input`` and ``validate_output``.
|
|
8
|
+
|
|
9
|
+
With the ``robot`` extra, the package is also a Robot Framework library:
|
|
10
|
+
|
|
11
|
+
*** Settings ***
|
|
12
|
+
Library OperatonContracts OperatonTasks
|
|
13
|
+
|
|
14
|
+
*** Tasks ***
|
|
15
|
+
Rescind Study Rights
|
|
16
|
+
${input}= Validate Task Input RescindStudyRightsInput
|
|
17
|
+
|
|
18
|
+
The library class is imported lazily, so ``import OperatonContracts`` never
|
|
19
|
+
loads Robot Framework.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from typing import TYPE_CHECKING
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
from OperatonContracts.contracts import TEMPLATE_KEY
|
|
28
|
+
from OperatonContracts.contracts import TaskContract
|
|
29
|
+
from OperatonContracts.contracts import load_contract
|
|
30
|
+
from OperatonContracts.contracts import template_hints
|
|
31
|
+
from OperatonContracts.contracts import validate_input
|
|
32
|
+
from OperatonContracts.contracts import validate_output
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from OperatonContracts.robotframework import OperatonContracts
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"TEMPLATE_KEY",
|
|
39
|
+
"OperatonContracts",
|
|
40
|
+
"TaskContract",
|
|
41
|
+
"load_contract",
|
|
42
|
+
"template_hints",
|
|
43
|
+
"validate_input",
|
|
44
|
+
"validate_output",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def __getattr__(name: str) -> Any:
|
|
49
|
+
# Robot Framework finds the library class with getattr(module, name).
|
|
50
|
+
if name == "OperatonContracts":
|
|
51
|
+
try:
|
|
52
|
+
from OperatonContracts.robotframework import OperatonContracts
|
|
53
|
+
except ModuleNotFoundError as error:
|
|
54
|
+
if error.name is None or not error.name.startswith("robot"):
|
|
55
|
+
raise
|
|
56
|
+
raise ImportError(
|
|
57
|
+
"The OperatonContracts Robot Framework library needs Robot "
|
|
58
|
+
"Framework: install operaton-contracts[robot]"
|
|
59
|
+
) from error
|
|
60
|
+
return OperatonContracts
|
|
61
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Consistency checks between template specs, purjo topics, and task suites."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import tomllib
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
from typing import Protocol
|
|
11
|
+
|
|
12
|
+
from OperatonContracts.templates import TaskTemplate
|
|
13
|
+
|
|
14
|
+
MISSING_ROBOT = (
|
|
15
|
+
"Robot suite checks need Robot Framework: install operaton-contracts[robot]"
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _TaskSuites(Protocol):
|
|
20
|
+
def check(self, spec: TaskTemplate, task: str) -> list[str]: ...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _robot_suites(root: Path) -> _TaskSuites | None:
|
|
24
|
+
try:
|
|
25
|
+
from OperatonContracts.robotframework import RobotSuites
|
|
26
|
+
except ImportError:
|
|
27
|
+
return None
|
|
28
|
+
return RobotSuites(root)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _duplicates(values: Iterable[str]) -> list[str]:
|
|
32
|
+
seen: set[str] = set()
|
|
33
|
+
duplicates: list[str] = []
|
|
34
|
+
for value in values:
|
|
35
|
+
if value in seen:
|
|
36
|
+
duplicates.append(value)
|
|
37
|
+
seen.add(value)
|
|
38
|
+
return duplicates
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def check_package(
|
|
42
|
+
root: Path,
|
|
43
|
+
specs: Sequence[TaskTemplate],
|
|
44
|
+
*,
|
|
45
|
+
reserved_topics: Iterable[str] = (),
|
|
46
|
+
) -> list[str]:
|
|
47
|
+
"""Return mismatches between specs, external task topics, and task suites.
|
|
48
|
+
|
|
49
|
+
The suite checks need Robot Framework; without it, configured topics are
|
|
50
|
+
reported as unchecked instead of silently passing.
|
|
51
|
+
"""
|
|
52
|
+
errors: list[str] = []
|
|
53
|
+
with (root / "pyproject.toml").open("rb") as stream:
|
|
54
|
+
tool = tomllib.load(stream).get("tool", {}).get("purjo", {})
|
|
55
|
+
topics: dict[str, dict[str, Any]] = tool.get("topics", {})
|
|
56
|
+
|
|
57
|
+
for label, values in (
|
|
58
|
+
("topic", [spec.topic for spec in specs]),
|
|
59
|
+
("template id", [spec.template_id for spec in specs]),
|
|
60
|
+
("filename", [spec.filename for spec in specs]),
|
|
61
|
+
):
|
|
62
|
+
errors.extend(f"Duplicate {label}: {value}" for value in _duplicates(values))
|
|
63
|
+
reserved = set(reserved_topics)
|
|
64
|
+
errors.extend(
|
|
65
|
+
f"Topic is reserved: {spec.topic}" for spec in specs if spec.topic in reserved
|
|
66
|
+
)
|
|
67
|
+
spec_topics = {spec.topic for spec in specs}
|
|
68
|
+
errors.extend(
|
|
69
|
+
f"Topic has no template spec: {topic}"
|
|
70
|
+
for topic in sorted(set(topics) - spec_topics)
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
suites = _robot_suites(root)
|
|
74
|
+
unchecked = False
|
|
75
|
+
for spec in specs:
|
|
76
|
+
config = topics.get(spec.topic)
|
|
77
|
+
if config is None:
|
|
78
|
+
errors.append(f"Topic missing from [tool.purjo.topics]: {spec.topic}")
|
|
79
|
+
continue
|
|
80
|
+
if config.get("process-variables") is not False:
|
|
81
|
+
errors.append(f"{spec.topic}: set process-variables = false")
|
|
82
|
+
if suites is None:
|
|
83
|
+
unchecked = True
|
|
84
|
+
continue
|
|
85
|
+
errors.extend(suites.check(spec, config.get("name", "")))
|
|
86
|
+
if unchecked:
|
|
87
|
+
errors.append(MISSING_ROBOT)
|
|
88
|
+
return errors
|
OperatonContracts/cli.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""``operaton-contracts`` command: generate, check, and validate templates.
|
|
2
|
+
|
|
3
|
+
Configured in the robot package's ``pyproject.toml``::
|
|
4
|
+
|
|
5
|
+
[tool.operaton-contracts]
|
|
6
|
+
specs = "scripts.element_templates:TEMPLATES" # module:attribute
|
|
7
|
+
icon = "scripts/logo.svg" # optional
|
|
8
|
+
schema-url = "https://…?job=release" # optional, pinned default
|
|
9
|
+
reserved-topics = ["legacy.topic"] # optional
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import importlib
|
|
16
|
+
import sys
|
|
17
|
+
import tomllib
|
|
18
|
+
from collections.abc import Sequence
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from OperatonContracts.templates import DEFAULT_SCHEMA_URL
|
|
23
|
+
from OperatonContracts.templates import TEMPLATE_DIR
|
|
24
|
+
from OperatonContracts.templates import TaskTemplate
|
|
25
|
+
from OperatonContracts.checks import check_package
|
|
26
|
+
from OperatonContracts.templates import drift
|
|
27
|
+
from OperatonContracts.templates import render_all
|
|
28
|
+
from OperatonContracts.templates import validate
|
|
29
|
+
from OperatonContracts.templates import write_templates
|
|
30
|
+
|
|
31
|
+
CONFIG_TABLE = "operaton-contracts"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ConfigError(ValueError):
|
|
35
|
+
"""The ``[tool.operaton-contracts]`` configuration is missing or invalid."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class Config:
|
|
40
|
+
root: Path
|
|
41
|
+
specs: tuple[TaskTemplate, ...]
|
|
42
|
+
icon_svg: bytes
|
|
43
|
+
schema_url: str
|
|
44
|
+
reserved_topics: tuple[str, ...]
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def template_dir(self) -> Path:
|
|
48
|
+
return self.root / TEMPLATE_DIR
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def load_config(root: Path) -> Config:
|
|
52
|
+
"""Load the configuration and import the specs relative to ``root``."""
|
|
53
|
+
pyproject = root / "pyproject.toml"
|
|
54
|
+
if not pyproject.exists():
|
|
55
|
+
raise ConfigError(f"{pyproject} not found")
|
|
56
|
+
with pyproject.open("rb") as stream:
|
|
57
|
+
table = tomllib.load(stream).get("tool", {}).get(CONFIG_TABLE)
|
|
58
|
+
if not isinstance(table, dict) or not isinstance(table.get("specs"), str):
|
|
59
|
+
raise ConfigError(
|
|
60
|
+
f'Set [tool.{CONFIG_TABLE}] specs = "module:ATTRIBUTE" in {pyproject}'
|
|
61
|
+
)
|
|
62
|
+
module_name, _, attribute = table["specs"].partition(":")
|
|
63
|
+
if str(root) not in sys.path:
|
|
64
|
+
sys.path.insert(0, str(root))
|
|
65
|
+
specs = getattr(importlib.import_module(module_name), attribute or "TEMPLATES")
|
|
66
|
+
if not all(isinstance(spec, TaskTemplate) for spec in specs):
|
|
67
|
+
raise ConfigError(f"{table['specs']} must be a sequence of TaskTemplate")
|
|
68
|
+
icon = table.get("icon")
|
|
69
|
+
return Config(
|
|
70
|
+
root=root,
|
|
71
|
+
specs=tuple(specs),
|
|
72
|
+
icon_svg=(root / icon).read_bytes() if icon else b"",
|
|
73
|
+
schema_url=str(table.get("schema-url", DEFAULT_SCHEMA_URL)),
|
|
74
|
+
reserved_topics=tuple(table.get("reserved-topics", ())),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
79
|
+
parser = argparse.ArgumentParser(
|
|
80
|
+
prog="operaton-contracts",
|
|
81
|
+
description="Generate, check, and validate Operaton element templates.",
|
|
82
|
+
)
|
|
83
|
+
parser.add_argument(
|
|
84
|
+
"command",
|
|
85
|
+
nargs="?",
|
|
86
|
+
default="check",
|
|
87
|
+
choices=("generate", "check", "validate"),
|
|
88
|
+
help="generate templates, check them offline (default), or validate "
|
|
89
|
+
"them against the pinned upstream schema",
|
|
90
|
+
)
|
|
91
|
+
parser.add_argument(
|
|
92
|
+
"--root",
|
|
93
|
+
type=Path,
|
|
94
|
+
default=Path.cwd(),
|
|
95
|
+
help="robot package directory (default: current directory)",
|
|
96
|
+
)
|
|
97
|
+
arguments = parser.parse_args(argv)
|
|
98
|
+
try:
|
|
99
|
+
config = load_config(arguments.root.resolve())
|
|
100
|
+
except ConfigError as error:
|
|
101
|
+
print(error, file=sys.stderr)
|
|
102
|
+
return 2
|
|
103
|
+
|
|
104
|
+
if arguments.command == "validate":
|
|
105
|
+
validate(sorted(config.template_dir.glob("*.json")), config.schema_url)
|
|
106
|
+
return 0
|
|
107
|
+
rendered = render_all(
|
|
108
|
+
config.specs, icon_svg=config.icon_svg, schema_url=config.schema_url
|
|
109
|
+
)
|
|
110
|
+
if arguments.command == "generate":
|
|
111
|
+
for message in write_templates(config.template_dir, rendered):
|
|
112
|
+
print(message)
|
|
113
|
+
return 0
|
|
114
|
+
|
|
115
|
+
errors = check_package(
|
|
116
|
+
config.root, config.specs, reserved_topics=config.reserved_topics
|
|
117
|
+
)
|
|
118
|
+
errors.extend(drift(config.template_dir, rendered))
|
|
119
|
+
for message in errors:
|
|
120
|
+
print(message, file=sys.stderr)
|
|
121
|
+
if errors:
|
|
122
|
+
return 1
|
|
123
|
+
print("Element templates are up to date")
|
|
124
|
+
return 0
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Task contracts and their runtime validation, independent of any task runner."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from types import ModuleType
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel
|
|
13
|
+
from pydantic import ConfigDict
|
|
14
|
+
from pydantic import JsonValue
|
|
15
|
+
|
|
16
|
+
TEMPLATE_KEY = "x-element-template"
|
|
17
|
+
HINT_KEYS = frozenset({"type", "value"})
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TaskContract(BaseModel):
|
|
21
|
+
"""Base for engine-facing task input and output contracts.
|
|
22
|
+
|
|
23
|
+
Every field needs an ``alias`` (the process variable name) and a
|
|
24
|
+
``title`` (the template label). Field order is template property order.
|
|
25
|
+
Validation is strict: use ``Field(strict=False)`` for values the engine
|
|
26
|
+
sends as text, such as dates.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
model_config = ConfigDict(
|
|
30
|
+
extra="forbid",
|
|
31
|
+
populate_by_name=True,
|
|
32
|
+
strict=True,
|
|
33
|
+
str_strip_whitespace=True,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def template_hints(**hints: JsonValue) -> dict[str, JsonValue]:
|
|
38
|
+
"""Return ``json_schema_extra`` with template-only property hints.
|
|
39
|
+
|
|
40
|
+
``value`` overrides the template default value; ``type`` overrides the
|
|
41
|
+
template property type inferred from the JSON Schema. Required string
|
|
42
|
+
properties and non-empty strings or lists get ``notEmpty``.
|
|
43
|
+
"""
|
|
44
|
+
unknown = sorted(set(hints) - HINT_KEYS)
|
|
45
|
+
if unknown:
|
|
46
|
+
raise ValueError(f"Unknown template hint(s): {', '.join(unknown)}")
|
|
47
|
+
return {TEMPLATE_KEY: hints}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def aliases(contract: type[TaskContract]) -> list[str]:
|
|
51
|
+
"""Return the contract's process variable names in field order."""
|
|
52
|
+
return [info.alias or name for name, info in contract.model_fields.items()]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def validate_input(
|
|
56
|
+
contract: type[TaskContract], variables: Mapping[str, Any]
|
|
57
|
+
) -> dict[str, Any]:
|
|
58
|
+
"""Validate process variables against an input contract.
|
|
59
|
+
|
|
60
|
+
Only the contract's aliases are read from ``variables``, so a task's full
|
|
61
|
+
variable map can be passed; missing ones fall back to contract defaults.
|
|
62
|
+
Returns the values normalized and JSON-compatible (dates become
|
|
63
|
+
``YYYY-MM-DD`` strings), keyed by alias.
|
|
64
|
+
"""
|
|
65
|
+
data = {
|
|
66
|
+
alias: variables[alias] for alias in aliases(contract) if alias in variables
|
|
67
|
+
}
|
|
68
|
+
return contract.model_validate(data).model_dump(mode="json", by_alias=True)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def validate_output(
|
|
72
|
+
contract: type[TaskContract], values: Mapping[str, Any]
|
|
73
|
+
) -> dict[str, Any]:
|
|
74
|
+
"""Validate a task's results against an output contract.
|
|
75
|
+
|
|
76
|
+
Unlike inputs, every value is checked: unknown keys are rejected. Returns
|
|
77
|
+
JSON-compatible values keyed by alias, ready to hand back to the engine.
|
|
78
|
+
"""
|
|
79
|
+
return contract.model_validate(dict(values)).model_dump(mode="json", by_alias=True)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def load_contract(module: ModuleType, name: str) -> type[TaskContract]:
|
|
83
|
+
"""Return the ``TaskContract`` subclass called ``name`` from ``module``."""
|
|
84
|
+
contract = getattr(module, name, None)
|
|
85
|
+
if not (isinstance(contract, type) and issubclass(contract, TaskContract)):
|
|
86
|
+
raise ValueError(f"{name} is not a TaskContract in {module.__name__}")
|
|
87
|
+
return contract
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def import_contracts(name: str, fallback_dirs: Iterable[str] = ()) -> ModuleType:
|
|
91
|
+
"""Import the contracts module, retrying from ``fallback_dirs``.
|
|
92
|
+
|
|
93
|
+
A directory is added to ``sys.path`` only when the module itself (not one
|
|
94
|
+
of its dependencies) is missing and the directory is not there already.
|
|
95
|
+
"""
|
|
96
|
+
try:
|
|
97
|
+
return importlib.import_module(name)
|
|
98
|
+
except ModuleNotFoundError as error:
|
|
99
|
+
if error.name != name:
|
|
100
|
+
raise
|
|
101
|
+
for directory in fallback_dirs:
|
|
102
|
+
if directory not in sys.path:
|
|
103
|
+
sys.path.insert(0, directory)
|
|
104
|
+
return importlib.import_module(name)
|
|
105
|
+
raise
|
|
File without changes
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Robot Framework integration: the ``OperatonContracts`` library and suite checks.
|
|
2
|
+
|
|
3
|
+
Requires the ``robot`` extra (``robotframework``). The rest of the package
|
|
4
|
+
works without it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from dataclasses import field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from robot.api import get_model
|
|
15
|
+
from robot.api.deco import keyword
|
|
16
|
+
from robot.api.deco import library
|
|
17
|
+
from robot.api.parsing import ModelVisitor
|
|
18
|
+
from robot.libraries.BuiltIn import BuiltIn
|
|
19
|
+
from robot.libraries.BuiltIn import RobotNotRunningError
|
|
20
|
+
|
|
21
|
+
from OperatonContracts.contracts import aliases
|
|
22
|
+
from OperatonContracts.contracts import import_contracts
|
|
23
|
+
from OperatonContracts.contracts import load_contract
|
|
24
|
+
from OperatonContracts.contracts import validate_input
|
|
25
|
+
from OperatonContracts.templates import TaskTemplate
|
|
26
|
+
from OperatonContracts.templates import contract_properties
|
|
27
|
+
|
|
28
|
+
TASK_SCOPE = "${BPMN:TASK}"
|
|
29
|
+
VALIDATE_KEYWORD = "Validate Task Input"
|
|
30
|
+
# Directories never collected as task suites (purjo collects suites
|
|
31
|
+
# recursively; tests and tooling are excluded from robot.zip by .wrapignore).
|
|
32
|
+
SKIPPED_DIRS = frozenset({"tests", "lib", "examples", "node_modules", "__pycache__"})
|
|
33
|
+
_MISSING = object()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _suite_directory() -> str | None:
|
|
37
|
+
"""Return the directory of the running suite, if Robot is running."""
|
|
38
|
+
try:
|
|
39
|
+
source = BuiltIn().get_variable_value("${SUITE SOURCE}")
|
|
40
|
+
except RobotNotRunningError:
|
|
41
|
+
return None
|
|
42
|
+
if not source:
|
|
43
|
+
return None
|
|
44
|
+
path = Path(source)
|
|
45
|
+
return str(path if path.is_dir() else path.parent)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@library(scope="GLOBAL", auto_keywords=False)
|
|
49
|
+
class OperatonContracts:
|
|
50
|
+
"""Validates Robot task variables against ``TaskContract`` models.
|
|
51
|
+
|
|
52
|
+
Import it with the name of the module that holds the contracts:
|
|
53
|
+
``Library OperatonContracts OperatonTasks``. purjo and
|
|
54
|
+
``python -m robot`` run with the robot package on ``sys.path``; otherwise
|
|
55
|
+
the module is imported from the running suite's directory.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(self, contracts: str = "OperatonTasks") -> None:
|
|
59
|
+
directory = _suite_directory()
|
|
60
|
+
self._module = import_contracts(contracts, [directory] if directory else [])
|
|
61
|
+
|
|
62
|
+
@keyword("Validate Task Input")
|
|
63
|
+
def validate_task_input(self, contract: str) -> dict[str, Any]:
|
|
64
|
+
"""Validate the task's input variables against ``contract``.
|
|
65
|
+
|
|
66
|
+
Reads ``${alias}`` for every contract field, validates the values,
|
|
67
|
+
and returns them normalized and JSON-compatible (dates become
|
|
68
|
+
``YYYY-MM-DD`` strings), keyed by alias. Unset variables are left out
|
|
69
|
+
so contract defaults apply; suites normally declare typed defaults
|
|
70
|
+
(``${False}``, ``${0}``, ``@{EMPTY}``) that match the contract's.
|
|
71
|
+
"""
|
|
72
|
+
model = load_contract(self._module, contract)
|
|
73
|
+
builtin = BuiltIn()
|
|
74
|
+
variables: dict[str, Any] = {}
|
|
75
|
+
for alias in aliases(model):
|
|
76
|
+
value = builtin.get_variable_value(f"${{{alias}}}", _MISSING)
|
|
77
|
+
if value is not _MISSING:
|
|
78
|
+
variables[alias] = value
|
|
79
|
+
return validate_input(model, variables)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def normalize(name: str) -> str:
|
|
83
|
+
"""Normalize a name the way Robot Framework matches keywords, tasks, and
|
|
84
|
+
variables: ignoring case, spaces, and underscores."""
|
|
85
|
+
return "".join(name.split()).replace("_", "").casefold()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _unwrap(token: str) -> str:
|
|
89
|
+
"""Return ``name`` from ``${name}``, ``@{name}``, ``&{name}``, or ``name``."""
|
|
90
|
+
if len(token) > 3 and token[1] == "{" and token.endswith("}"):
|
|
91
|
+
return token[2:-1]
|
|
92
|
+
return token
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _variable_name(token: str) -> str:
|
|
96
|
+
"""Return the bare name of ``${name}``, ``@{name: type}``, or ``name``."""
|
|
97
|
+
return _unwrap(token).split(":", 1)[0].strip()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _is_typed(declared: str, values: tuple[str, ...]) -> bool:
|
|
101
|
+
"""Whether a suite default yields a non-string value at runtime."""
|
|
102
|
+
if declared[0] in "@&" or ":" in declared[2:-1]:
|
|
103
|
+
return True
|
|
104
|
+
return len(values) == 1 and values[0].startswith(("${", "@{", "&{"))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass
|
|
108
|
+
class _Suite:
|
|
109
|
+
path: Path
|
|
110
|
+
# normalized name -> (declared name, values)
|
|
111
|
+
variables: dict[str, tuple[str, tuple[str, ...]]] = field(default_factory=dict)
|
|
112
|
+
# normalized task name -> normalized output names / contract names
|
|
113
|
+
task_outputs: dict[str, set[str]] = field(default_factory=dict)
|
|
114
|
+
task_contracts: dict[str, set[str]] = field(default_factory=dict)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class _SuiteVisitor(ModelVisitor): # type: ignore[misc]
|
|
118
|
+
def __init__(self, suite: _Suite) -> None:
|
|
119
|
+
self.suite = suite
|
|
120
|
+
self.task: str | None = None
|
|
121
|
+
|
|
122
|
+
def visit_Variable(self, node: Any) -> None:
|
|
123
|
+
name = normalize(_variable_name(node.name))
|
|
124
|
+
self.suite.variables[name] = (node.name, tuple(node.value))
|
|
125
|
+
|
|
126
|
+
def visit_TestCase(self, node: Any) -> None:
|
|
127
|
+
self.task = normalize(node.name)
|
|
128
|
+
self.suite.task_outputs[self.task] = set()
|
|
129
|
+
self.suite.task_contracts[self.task] = set()
|
|
130
|
+
self.generic_visit(node)
|
|
131
|
+
self.task = None
|
|
132
|
+
|
|
133
|
+
def visit_Var(self, node: Any) -> None:
|
|
134
|
+
scope = normalize(_unwrap(node.scope or ""))
|
|
135
|
+
if self.task is not None and scope == normalize("BPMN:TASK"):
|
|
136
|
+
name = normalize(_variable_name(node.name))
|
|
137
|
+
self.suite.task_outputs[self.task].add(name)
|
|
138
|
+
|
|
139
|
+
def visit_KeywordCall(self, node: Any) -> None:
|
|
140
|
+
keyword_name = (node.keyword or "").rsplit(".", 1)[-1]
|
|
141
|
+
if (
|
|
142
|
+
self.task is not None
|
|
143
|
+
and normalize(keyword_name) == normalize(VALIDATE_KEYWORD)
|
|
144
|
+
and node.args
|
|
145
|
+
):
|
|
146
|
+
self.suite.task_contracts[self.task].add(node.args[0])
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _suite_paths(root: Path) -> list[Path]:
|
|
150
|
+
return [
|
|
151
|
+
path
|
|
152
|
+
for path in sorted(root.rglob("*.robot"))
|
|
153
|
+
if not path.name.startswith("test_")
|
|
154
|
+
and not any(
|
|
155
|
+
part.startswith(".") or part in SKIPPED_DIRS
|
|
156
|
+
for part in path.relative_to(root).parts[:-1]
|
|
157
|
+
)
|
|
158
|
+
]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class RobotSuites:
|
|
162
|
+
"""The robot package's task suites, for checking them against contracts."""
|
|
163
|
+
|
|
164
|
+
def __init__(self, root: Path) -> None:
|
|
165
|
+
self.root = root
|
|
166
|
+
# normalized task name -> every suite defining it
|
|
167
|
+
self.tasks: dict[str, list[_Suite]] = {}
|
|
168
|
+
for path in _suite_paths(root):
|
|
169
|
+
suite = _Suite(path)
|
|
170
|
+
_SuiteVisitor(suite).visit(get_model(path))
|
|
171
|
+
for task in suite.task_outputs:
|
|
172
|
+
self.tasks.setdefault(task, []).append(suite)
|
|
173
|
+
|
|
174
|
+
def check(self, spec: TaskTemplate, task: str) -> list[str]:
|
|
175
|
+
"""Return mismatches between the suite defining ``task`` and ``spec``."""
|
|
176
|
+
matches = self.tasks.get(normalize(task), [])
|
|
177
|
+
if not matches:
|
|
178
|
+
return [f"{spec.topic}: no Robot suite defines task {task!r}"]
|
|
179
|
+
if len(matches) > 1:
|
|
180
|
+
names = ", ".join(str(m.path.relative_to(self.root)) for m in matches)
|
|
181
|
+
return [
|
|
182
|
+
f"{spec.topic}: task {task!r} is defined in several suites "
|
|
183
|
+
f"({names}); purjo would run all of them"
|
|
184
|
+
]
|
|
185
|
+
suite = matches[0]
|
|
186
|
+
key = normalize(task)
|
|
187
|
+
errors: list[str] = []
|
|
188
|
+
for alias, schema, _required in contract_properties(spec.inputs):
|
|
189
|
+
declared = suite.variables.get(normalize(alias))
|
|
190
|
+
if declared is None:
|
|
191
|
+
errors.append(
|
|
192
|
+
f"{suite.path.name}: input {alias!r} needs a default "
|
|
193
|
+
"in *** Variables ***"
|
|
194
|
+
)
|
|
195
|
+
elif schema.get("type", "string") != "string" and not _is_typed(*declared):
|
|
196
|
+
errors.append(
|
|
197
|
+
f"{suite.path.name}: default of {declared[0]} is a string; "
|
|
198
|
+
f"use a typed default such as ${{False}}, ${{0}}, or @{{EMPTY}}"
|
|
199
|
+
)
|
|
200
|
+
for alias, _schema, _required in contract_properties(spec.outputs):
|
|
201
|
+
if normalize(alias) not in suite.task_outputs[key]:
|
|
202
|
+
errors.append(
|
|
203
|
+
f"{suite.path.name}: task {task!r} must set output "
|
|
204
|
+
f"{alias!r} with VAR ... scope={TASK_SCOPE}"
|
|
205
|
+
)
|
|
206
|
+
contract = spec.inputs.__name__
|
|
207
|
+
if contract not in suite.task_contracts[key]:
|
|
208
|
+
errors.append(
|
|
209
|
+
f"{suite.path.name}: task {task!r} must call "
|
|
210
|
+
f"{VALIDATE_KEYWORD} {contract}"
|
|
211
|
+
)
|
|
212
|
+
return errors
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Render and validate Operaton element templates from task contracts.
|
|
2
|
+
|
|
3
|
+
Element templates are rendered from ``TaskTemplate`` specs and the
|
|
4
|
+
``TaskContract`` models they reference. Schema validation needs the
|
|
5
|
+
``templates`` extra (``jsonschema``).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Iterable
|
|
14
|
+
from collections.abc import Sequence
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
from urllib.request import urlopen
|
|
19
|
+
|
|
20
|
+
from OperatonContracts.contracts import TEMPLATE_KEY
|
|
21
|
+
from OperatonContracts.contracts import TaskContract
|
|
22
|
+
|
|
23
|
+
TEMPLATE_DIR = Path(".operaton") / "element-templates"
|
|
24
|
+
DEFAULT_SCHEMA_URL = (
|
|
25
|
+
"https://gitlab.com/vasara-bpm/vscode-operaton-bpmn-js-modeler/"
|
|
26
|
+
"-/jobs/artifacts/v0.8.3/raw/"
|
|
27
|
+
"operaton-element-templates-schema-v0.8.3.json?job=release"
|
|
28
|
+
)
|
|
29
|
+
ALIAS_PATTERN = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
30
|
+
# Input property types the Camunda 7 element-template schema allows, and the
|
|
31
|
+
# JSON type each one's ``value`` must have.
|
|
32
|
+
VALUE_TYPES: dict[str, type] = {
|
|
33
|
+
"String": str,
|
|
34
|
+
"Text": str,
|
|
35
|
+
"Hidden": str,
|
|
36
|
+
"Dropdown": str,
|
|
37
|
+
"Boolean": bool,
|
|
38
|
+
"List": list,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class TemplateError(ValueError):
|
|
43
|
+
"""A contract model cannot be rendered as an element template."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class TemplateGroup:
|
|
48
|
+
"""One property group in the modeler's properties panel."""
|
|
49
|
+
|
|
50
|
+
id: str
|
|
51
|
+
label: str
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
DEFAULT_GROUPS = (
|
|
55
|
+
TemplateGroup("inputs", "Inputs"),
|
|
56
|
+
TemplateGroup("outputs", "Results"),
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class TaskTemplate:
|
|
62
|
+
"""Template-level metadata for one external task topic.
|
|
63
|
+
|
|
64
|
+
``input_group`` and ``output_group`` are group ids from ``groups``; use
|
|
65
|
+
the same id for both to show every property in one group.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
topic: str
|
|
69
|
+
template_id: str
|
|
70
|
+
name: str
|
|
71
|
+
description: str
|
|
72
|
+
filename: str
|
|
73
|
+
inputs: type[TaskContract]
|
|
74
|
+
outputs: type[TaskContract]
|
|
75
|
+
groups: tuple[TemplateGroup, ...] = DEFAULT_GROUPS
|
|
76
|
+
input_group: str = "inputs"
|
|
77
|
+
output_group: str = "outputs"
|
|
78
|
+
version: int = 1
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def contract_properties(
|
|
82
|
+
model: type[TaskContract],
|
|
83
|
+
) -> list[tuple[str, dict[str, Any], bool]]:
|
|
84
|
+
for name, info in model.model_fields.items():
|
|
85
|
+
if info.alias is None:
|
|
86
|
+
raise TemplateError(f"{model.__name__}.{name} needs an alias")
|
|
87
|
+
if not ALIAS_PATTERN.fullmatch(info.alias):
|
|
88
|
+
raise TemplateError(
|
|
89
|
+
f"{model.__name__}.{name}: alias {info.alias!r} must be a plain "
|
|
90
|
+
"identifier usable as a Robot variable name"
|
|
91
|
+
)
|
|
92
|
+
if info.title is None:
|
|
93
|
+
raise TemplateError(f"{model.__name__}.{name} needs a title")
|
|
94
|
+
schema = model.model_json_schema(by_alias=True)
|
|
95
|
+
required = set(schema.get("required", ()))
|
|
96
|
+
return [
|
|
97
|
+
(alias, prop, alias in required)
|
|
98
|
+
for alias, prop in schema.get("properties", {}).items()
|
|
99
|
+
]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _choices(values: Iterable[Any]) -> list[dict[str, Any]]:
|
|
103
|
+
return [{"name": str(value), "value": value} for value in values]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _input_property(
|
|
107
|
+
alias: str, schema: dict[str, Any], required: bool, group: str
|
|
108
|
+
) -> dict[str, Any]:
|
|
109
|
+
hints: dict[str, Any] = schema.get(TEMPLATE_KEY, {})
|
|
110
|
+
prop: dict[str, Any] = {"label": schema["title"]}
|
|
111
|
+
if "description" in schema:
|
|
112
|
+
prop["description"] = schema["description"]
|
|
113
|
+
|
|
114
|
+
json_type = schema.get("type")
|
|
115
|
+
items: dict[str, Any] = schema.get("items", {})
|
|
116
|
+
if json_type == "boolean":
|
|
117
|
+
prop["type"] = "Boolean"
|
|
118
|
+
elif json_type == "string" and "enum" in schema:
|
|
119
|
+
prop["type"] = "Dropdown"
|
|
120
|
+
prop["choices"] = _choices(schema["enum"])
|
|
121
|
+
elif json_type == "string":
|
|
122
|
+
prop["type"] = "String"
|
|
123
|
+
elif json_type == "array" and items.get("type") == "string":
|
|
124
|
+
prop["type"] = "List"
|
|
125
|
+
if "enum" in items:
|
|
126
|
+
prop["display"] = "taglist"
|
|
127
|
+
prop["choices"] = _choices(items["enum"])
|
|
128
|
+
else:
|
|
129
|
+
prop["itemType"] = "String"
|
|
130
|
+
elif "type" not in hints:
|
|
131
|
+
raise TemplateError(
|
|
132
|
+
f"{alias}: unsupported JSON Schema {_describe(schema)}; Enum, "
|
|
133
|
+
"Optional, and nested models produce $ref/anyOf schemas. Use "
|
|
134
|
+
"Literal, a plain type, or add a type hint"
|
|
135
|
+
)
|
|
136
|
+
if "type" in hints:
|
|
137
|
+
prop["type"] = hints["type"]
|
|
138
|
+
if prop["type"] not in VALUE_TYPES:
|
|
139
|
+
raise TemplateError(
|
|
140
|
+
f"{alias}: template type {prop['type']!r} is not one of "
|
|
141
|
+
f"{', '.join(VALUE_TYPES)}"
|
|
142
|
+
)
|
|
143
|
+
if prop["type"] == "Dropdown" and "choices" not in prop:
|
|
144
|
+
raise TemplateError(f"{alias}: a Dropdown needs Literal choices")
|
|
145
|
+
|
|
146
|
+
if "value" in hints:
|
|
147
|
+
prop["value"] = hints["value"]
|
|
148
|
+
elif "default" in schema:
|
|
149
|
+
prop["value"] = schema["default"]
|
|
150
|
+
elif prop["type"] == "List":
|
|
151
|
+
prop["value"] = []
|
|
152
|
+
else:
|
|
153
|
+
prop["value"] = f"${{{alias}}}"
|
|
154
|
+
if not isinstance(prop["value"], VALUE_TYPES[prop["type"]]):
|
|
155
|
+
raise TemplateError(
|
|
156
|
+
f"{alias}: value {prop['value']!r} does not fit template type "
|
|
157
|
+
f"{prop['type']}; add a value hint"
|
|
158
|
+
)
|
|
159
|
+
if (
|
|
160
|
+
schema.get("minLength", 0) >= 1
|
|
161
|
+
or schema.get("minItems", 0) >= 1
|
|
162
|
+
or (required and prop["type"] == "String")
|
|
163
|
+
):
|
|
164
|
+
prop["constraints"] = {"notEmpty": True}
|
|
165
|
+
prop["group"] = group
|
|
166
|
+
prop["binding"] = {"type": "camunda:inputParameter", "name": alias}
|
|
167
|
+
return prop
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _describe(schema: dict[str, Any]) -> str:
|
|
171
|
+
keys = [key for key in ("type", "$ref", "anyOf", "allOf") if key in schema]
|
|
172
|
+
return ", ".join(f"{key}={schema[key]!r}" for key in keys) or "without a type"
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _output_property(alias: str, schema: dict[str, Any], group: str) -> dict[str, Any]:
|
|
176
|
+
prop: dict[str, Any] = {"label": schema["title"]}
|
|
177
|
+
if "description" in schema:
|
|
178
|
+
prop["description"] = schema["description"]
|
|
179
|
+
prop.update(
|
|
180
|
+
{
|
|
181
|
+
"type": "String",
|
|
182
|
+
"value": alias,
|
|
183
|
+
"group": group,
|
|
184
|
+
"binding": {"type": "camunda:outputParameter", "source": f"${{{alias}}}"},
|
|
185
|
+
}
|
|
186
|
+
)
|
|
187
|
+
return prop
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def render(spec: TaskTemplate, *, icon_svg: bytes, schema_url: str) -> dict[str, Any]:
|
|
191
|
+
"""Render one element template from its spec and contract models."""
|
|
192
|
+
group_ids = [group.id for group in spec.groups]
|
|
193
|
+
for group_id in (spec.input_group, spec.output_group):
|
|
194
|
+
if group_id not in group_ids:
|
|
195
|
+
raise TemplateError(f"{spec.topic}: unknown group id {group_id!r}")
|
|
196
|
+
properties: list[dict[str, Any]] = [
|
|
197
|
+
{
|
|
198
|
+
"label": "Implementation",
|
|
199
|
+
"type": "Hidden",
|
|
200
|
+
"value": "external",
|
|
201
|
+
"binding": {"type": "property", "name": "camunda:type"},
|
|
202
|
+
},
|
|
203
|
+
{
|
|
204
|
+
"label": "External Task Topic",
|
|
205
|
+
"type": "Hidden",
|
|
206
|
+
"value": spec.topic,
|
|
207
|
+
"binding": {"type": "property", "name": "camunda:topic"},
|
|
208
|
+
},
|
|
209
|
+
]
|
|
210
|
+
properties.extend(
|
|
211
|
+
_input_property(alias, schema, required, spec.input_group)
|
|
212
|
+
for alias, schema, required in contract_properties(spec.inputs)
|
|
213
|
+
)
|
|
214
|
+
properties.extend(
|
|
215
|
+
_output_property(alias, schema, spec.output_group)
|
|
216
|
+
for alias, schema, _required in contract_properties(spec.outputs)
|
|
217
|
+
)
|
|
218
|
+
icon = base64.b64encode(icon_svg).decode("ascii")
|
|
219
|
+
return {
|
|
220
|
+
"$schema": schema_url,
|
|
221
|
+
"name": spec.name,
|
|
222
|
+
"id": spec.template_id,
|
|
223
|
+
"description": spec.description,
|
|
224
|
+
"version": spec.version,
|
|
225
|
+
"appliesTo": ["bpmn:ServiceTask"],
|
|
226
|
+
"groups": [{"id": group.id, "label": group.label} for group in spec.groups],
|
|
227
|
+
"properties": properties,
|
|
228
|
+
"icon": {"contents": f"data:image/svg+xml;base64,{icon}"},
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def dumps(template: dict[str, Any]) -> str:
|
|
233
|
+
"""Serialize a template in the committed file format."""
|
|
234
|
+
return json.dumps(template, indent=2, ensure_ascii=False) + "\n"
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def validate(paths: Sequence[Path], schema_url: str) -> None:
|
|
238
|
+
"""Validate template files against the pinned upstream schema."""
|
|
239
|
+
if not paths:
|
|
240
|
+
raise TemplateError("No element templates were found")
|
|
241
|
+
from jsonschema import Draft7Validator # the "templates" extra
|
|
242
|
+
|
|
243
|
+
with urlopen(schema_url, timeout=30) as response:
|
|
244
|
+
schema = json.load(response)
|
|
245
|
+
Draft7Validator.check_schema(schema)
|
|
246
|
+
validator = Draft7Validator(schema)
|
|
247
|
+
for path in paths:
|
|
248
|
+
validator.validate(json.loads(path.read_text(encoding="utf-8")))
|
|
249
|
+
print(f"Validated {path.name}")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def render_all(
|
|
253
|
+
specs: Sequence[TaskTemplate], *, icon_svg: bytes, schema_url: str
|
|
254
|
+
) -> dict[str, str]:
|
|
255
|
+
"""Render every spec, keyed by template filename."""
|
|
256
|
+
return {
|
|
257
|
+
spec.filename: dumps(render(spec, icon_svg=icon_svg, schema_url=schema_url))
|
|
258
|
+
for spec in specs
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def write_templates(template_dir: Path, rendered: dict[str, str]) -> list[str]:
|
|
263
|
+
"""Write rendered templates, remove stale ones, and describe the changes."""
|
|
264
|
+
template_dir.mkdir(parents=True, exist_ok=True)
|
|
265
|
+
messages: list[str] = []
|
|
266
|
+
for path in sorted(template_dir.glob("*.json")):
|
|
267
|
+
if path.name not in rendered:
|
|
268
|
+
path.unlink()
|
|
269
|
+
messages.append(f"Removed stale {path.name}")
|
|
270
|
+
for filename, text in rendered.items():
|
|
271
|
+
(template_dir / filename).write_text(text, encoding="utf-8")
|
|
272
|
+
messages.append(f"Wrote {filename}")
|
|
273
|
+
return messages
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def drift(template_dir: Path, rendered: dict[str, str]) -> list[str]:
|
|
277
|
+
"""Return differences between committed and rendered templates."""
|
|
278
|
+
errors = [
|
|
279
|
+
f"Stray element template: {path.name}"
|
|
280
|
+
for path in sorted(template_dir.glob("*.json"))
|
|
281
|
+
if path.name not in rendered
|
|
282
|
+
]
|
|
283
|
+
for filename, text in rendered.items():
|
|
284
|
+
path = template_dir / filename
|
|
285
|
+
if not path.exists() or path.read_text(encoding="utf-8") != text:
|
|
286
|
+
errors.append(f"Out of date: {filename}; run generate")
|
|
287
|
+
return errors
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: operaton-contracts
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Pydantic task contracts, runtime validation, and generated element templates for Operaton external tasks, with optional Robot Framework support
|
|
5
|
+
Project-URL: Homepage, https://datakurre.github.io/operaton-contracts/
|
|
6
|
+
Project-URL: Documentation, https://datakurre.github.io/operaton-contracts/
|
|
7
|
+
Project-URL: Repository, https://github.com/datakurre/operaton-contracts
|
|
8
|
+
Project-URL: Issues, https://github.com/datakurre/operaton-contracts/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/datakurre/operaton-contracts/blob/main/CHANGELOG.md
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: bpmn,camunda,element-templates,operaton,purjo,robotframework
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Framework :: Pydantic :: 2
|
|
15
|
+
Classifier: Framework :: Robot Framework
|
|
16
|
+
Classifier: Framework :: Robot Framework :: Library
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.12
|
|
22
|
+
Requires-Dist: pydantic>=2.7
|
|
23
|
+
Provides-Extra: robot
|
|
24
|
+
Requires-Dist: robotframework>=7.3; extra == 'robot'
|
|
25
|
+
Provides-Extra: templates
|
|
26
|
+
Requires-Dist: jsonschema>=4; extra == 'templates'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# operaton-contracts
|
|
30
|
+
|
|
31
|
+
Pydantic task contracts for Robot Framework packages served as
|
|
32
|
+
[Operaton](https://operaton.org/) (Camunda 7) external tasks, for example by
|
|
33
|
+
[purjo](https://github.com/datakurre/purjo).
|
|
34
|
+
|
|
35
|
+
Documentation: <https://datakurre.github.io/operaton-contracts/>
|
|
36
|
+
|
|
37
|
+
One model per external task topic is the source of truth for what the task
|
|
38
|
+
accepts and returns:
|
|
39
|
+
|
|
40
|
+
- **At runtime** each Robot task validates and normalizes its process
|
|
41
|
+
variables with `Validate Task Input`.
|
|
42
|
+
- **At build time** `operaton-contracts generate` renders one bpmn.io element
|
|
43
|
+
template per topic from the same models, and `operaton-contracts check`
|
|
44
|
+
verifies that the templates, `[tool.purjo.topics]`, and the Robot suites
|
|
45
|
+
agree.
|
|
46
|
+
|
|
47
|
+
```console
|
|
48
|
+
uv add operaton-contracts # runtime: pydantic + robotframework
|
|
49
|
+
uv add --group dev "operaton-contracts[templates]" # adds jsonschema for validate
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Contracts
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
# OperatonTasks.py
|
|
56
|
+
from datetime import date
|
|
57
|
+
from typing import Any, Literal
|
|
58
|
+
|
|
59
|
+
from pydantic import Field
|
|
60
|
+
from OperatonContracts import TaskContract, template_hints
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class RescindStudyRightsInput(TaskContract):
|
|
64
|
+
study_right_ids: list[str] = Field(
|
|
65
|
+
alias="studyRightIds",
|
|
66
|
+
title="Study right IDs",
|
|
67
|
+
min_length=1,
|
|
68
|
+
json_schema_extra=template_hints(value=["${studyRightId}"]),
|
|
69
|
+
)
|
|
70
|
+
cancellation_date: date = Field(
|
|
71
|
+
alias="cancellationDate", title="Cancellation date", strict=False
|
|
72
|
+
)
|
|
73
|
+
dry_run: bool = Field(alias="dryRun", title="Dry run", default=False)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class RescindStudyRightsOutput(TaskContract):
|
|
77
|
+
result: dict[str, Any] = Field(alias="result", title="Result variable")
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`TaskContract` is strict, forbids extra fields, and strips strings. Every
|
|
81
|
+
field needs an `alias` (the process variable name) and a `title` (the
|
|
82
|
+
template label). Use `Literal[...]` for choices; `Enum`, `Optional`, and nested
|
|
83
|
+
models are not supported in template inputs. `template_hints(value=...,
|
|
84
|
+
type=...)` sets template-only defaults and property types.
|
|
85
|
+
|
|
86
|
+
## Robot tasks
|
|
87
|
+
|
|
88
|
+
```robotframework
|
|
89
|
+
*** Settings ***
|
|
90
|
+
Library OperatonContracts OperatonTasks
|
|
91
|
+
|
|
92
|
+
*** Variables ***
|
|
93
|
+
${BPMN:TASK} local
|
|
94
|
+
@{studyRightIds} @{EMPTY}
|
|
95
|
+
${cancellationDate} ${EMPTY}
|
|
96
|
+
${dryRun} ${False}
|
|
97
|
+
|
|
98
|
+
*** Tasks ***
|
|
99
|
+
Rescind Study Rights
|
|
100
|
+
${input}= Validate Task Input RescindStudyRightsInput
|
|
101
|
+
Log ${input}[studyRightIds]
|
|
102
|
+
VAR ${result}= ${{{}}} scope=${BPMN:TASK}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`Validate Task Input` reads `${alias}` for every field, validates, and returns
|
|
106
|
+
the values JSON-compatible (dates as `YYYY-MM-DD`), keyed by alias. Declare
|
|
107
|
+
typed suite defaults (`${False}`, `${0}`, `@{EMPTY}`): strict contracts reject
|
|
108
|
+
the string `"0"` or `"false"`. The library imports the contracts module from
|
|
109
|
+
`sys.path`, falling back to the running suite's directory.
|
|
110
|
+
|
|
111
|
+
## Element templates
|
|
112
|
+
|
|
113
|
+
```toml
|
|
114
|
+
# pyproject.toml of the robot package
|
|
115
|
+
[tool.operaton-contracts]
|
|
116
|
+
specs = "scripts.element_templates:TEMPLATES" # module:attribute
|
|
117
|
+
icon = "scripts/logo.svg" # optional SVG icon
|
|
118
|
+
reserved-topics = ["legacy.topic"] # optional
|
|
119
|
+
# schema-url = "…" # optional; pinned default
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
# scripts/element_templates.py
|
|
124
|
+
from OperatonContracts.templates import TaskTemplate, TemplateGroup
|
|
125
|
+
from OperatonTasks import RescindStudyRightsInput, RescindStudyRightsOutput
|
|
126
|
+
|
|
127
|
+
TEMPLATES = (
|
|
128
|
+
TaskTemplate(
|
|
129
|
+
topic="study_rights.rescind",
|
|
130
|
+
template_id="org.example.study-rights-rescind",
|
|
131
|
+
name="Rescind Study Rights",
|
|
132
|
+
description="Rescind active study rights.",
|
|
133
|
+
filename="study-rights-rescind.json",
|
|
134
|
+
inputs=RescindStudyRightsInput,
|
|
135
|
+
outputs=RescindStudyRightsOutput,
|
|
136
|
+
groups=(TemplateGroup("main", "Rescission"),),
|
|
137
|
+
input_group="main",
|
|
138
|
+
output_group="main",
|
|
139
|
+
),
|
|
140
|
+
)
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
```console
|
|
144
|
+
operaton-contracts generate # write .operaton/element-templates/*.json
|
|
145
|
+
operaton-contracts check # offline: drift and package consistency
|
|
146
|
+
operaton-contracts validate # against the pinned upstream schema (network)
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`check` fails when committed templates differ from the generated ones, when
|
|
150
|
+
specs and `[tool.purjo.topics]` differ, when a topic is reserved or lacks
|
|
151
|
+
`process-variables = false`, or when the suite defining a topic's task lacks a
|
|
152
|
+
typed default for an input, the `Validate Task Input` call, or a
|
|
153
|
+
`VAR … scope=${BPMN:TASK}` for an output. Names are matched the way Robot
|
|
154
|
+
matches them, suites are collected recursively (skipping hidden directories,
|
|
155
|
+
`tests/`, `lib/`, `examples/`, and `test_*.robot`), and a task name defined in
|
|
156
|
+
more than one suite is an error.
|
|
157
|
+
|
|
158
|
+
## Development
|
|
159
|
+
|
|
160
|
+
```console
|
|
161
|
+
uv run --group dev --group docs make test check docs # with uv
|
|
162
|
+
devenv shell -- make test check docs # or with devenv
|
|
163
|
+
make build
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
`make docs-serve` previews the documentation site, which is published to
|
|
167
|
+
GitHub Pages from `main` by `.github/workflows/docs.yml`.
|
|
168
|
+
|
|
169
|
+
## License
|
|
170
|
+
|
|
171
|
+
Apache License 2.0; see [LICENSE](LICENSE).
|
|
172
|
+
|
|
173
|
+
Releases are published to PyPI by `.github/workflows/release.yml` with
|
|
174
|
+
trusted publishing when a `v*` tag matching the project version is pushed.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
OperatonContracts/__init__.py,sha256=2QDHQcgLds4cpD8zs6DtWDSWzbhv5uCw8ZGSBpmURxk,2091
|
|
2
|
+
OperatonContracts/__main__.py,sha256=bB5XAld6e58Eup_58nRxD31pUXbJNqIMSbdxgyJXkyU,65
|
|
3
|
+
OperatonContracts/checks.py,sha256=uSNkvMHepfaH8Vts0uEMVvdMJwxoFnV9ZN7sTPJvqBg,2772
|
|
4
|
+
OperatonContracts/cli.py,sha256=c9dcJQcKPLtgYWcQ1ysEEOnqRXCAOowKs7jv-TPtRy8,4251
|
|
5
|
+
OperatonContracts/contracts.py,sha256=b9Sw0ZTya9kR1F24q42arxAj8OU6ZdanDly-EUw9XJI,3769
|
|
6
|
+
OperatonContracts/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
OperatonContracts/robotframework.py,sha256=9EvLmmljpTN7pCB1Bkfxc7_g6K_sZ4UbjcpsKD2Ou3Q,8372
|
|
8
|
+
OperatonContracts/templates.py,sha256=UAeyNA-x5mlfHU8X4IqfpSB1tYIceKz9-S5j2dV6uGA,9934
|
|
9
|
+
operaton_contracts-0.1.0.dist-info/METADATA,sha256=PYqBWjCvWU1npzPwea0_77i78jW6f1dcEEiXi91V51E,6466
|
|
10
|
+
operaton_contracts-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
11
|
+
operaton_contracts-0.1.0.dist-info/entry_points.txt,sha256=cE_CUoKPQVwUjVO35fdt-Ra8qoiDQEh1kvHCsWGF-d8,66
|
|
12
|
+
operaton_contracts-0.1.0.dist-info/licenses/LICENSE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
|
|
13
|
+
operaton_contracts-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|