API: expose Void module contract
This commit is contained in:
1 parent
06e06b7622
commit
257d2a9971
5 files changed
+429
No files matched your search
@@ -81,6 +81,19 @@ target_link_libraries(EchoionApiPlugin INTERFACE
|
||||
Void::Plugin
|
||||
)
|
||||
|
||||
# Echoion's discovery symbol and SDK aliases for VoidLibrary's reusable C++
|
||||
# module descriptor, lifecycle, SemVer, JSON, Result, and service types.
|
||||
add_library(EchoionApiModuleAbi INTERFACE)
|
||||
add_library(Echoion::ApiModuleAbi ALIAS EchoionApiModuleAbi)
|
||||
set_target_properties(EchoionApiModuleAbi PROPERTIES
|
||||
EXPORT_NAME ApiModuleAbi
|
||||
)
|
||||
target_include_directories(EchoionApiModuleAbi INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
target_link_libraries(EchoionApiModuleAbi INTERFACE Void::Plugin)
|
||||
|
||||
# 6. Config Types (depends on Network, Audio)
|
||||
add_library(EchoionApiConfig INTERFACE)
|
||||
add_library(Echoion::ApiConfig ALIAS EchoionApiConfig)
|
||||
@@ -227,6 +240,7 @@ target_include_directories(EchoionApi INTERFACE
|
||||
$<INSTALL_INTERFACE:include/echoion/api>
|
||||
)
|
||||
target_link_libraries(EchoionApi INTERFACE
|
||||
Echoion::ApiModuleAbi
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiAudio
|
||||
Echoion::ApiTrack
|
||||
@@ -253,6 +267,7 @@ endif()
|
||||
|
||||
# Install and export all modules
|
||||
install(TARGETS
|
||||
EchoionApiModuleAbi
|
||||
EchoionApiBase
|
||||
EchoionApiAudio
|
||||
EchoionApiTrack
|
||||
@@ -274,6 +289,10 @@ install(TARGETS
|
||||
INCLUDES DESTINATION include
|
||||
)
|
||||
|
||||
install(DIRECTORY include/ DESTINATION include)
|
||||
install(FILES abi/echoion-module-v1.json
|
||||
DESTINATION share/echoion/abi)
|
||||
|
||||
install(EXPORT EchoionApiTargets
|
||||
FILE EchoionApiTargets.cmake
|
||||
NAMESPACE Echoion::
|
||||
@@ -297,3 +316,12 @@ install(FILES
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfigVersion.cmake"
|
||||
DESTINATION lib/cmake/EchoionApi
|
||||
)
|
||||
|
||||
if(BUILD_TESTS)
|
||||
find_package(Python3 QUIET COMPONENTS Interpreter)
|
||||
if(Python3_Interpreter_FOUND)
|
||||
add_test(NAME echoion_module_abi_contract_tests
|
||||
COMMAND "${Python3_EXECUTABLE}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/tests/test_abi_contract.py")
|
||||
endif()
|
||||
endif()
|
||||
@@ -0,0 +1,84 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"contractId": "echoion.module",
|
||||
"descriptor": "Void::Plugin::ModuleDescriptor",
|
||||
"querySymbol": "echoion_module_query",
|
||||
"entryPoints": [
|
||||
{
|
||||
"name": "echoion_module_query",
|
||||
"returns": "const Void::Plugin::ModuleDescriptor*"
|
||||
}
|
||||
],
|
||||
"types": [
|
||||
{
|
||||
"name": "Void::Plugin::ModuleDescriptor",
|
||||
"fields": [
|
||||
{
|
||||
"name": "struct_size",
|
||||
"type": "std::size_t"
|
||||
},
|
||||
{
|
||||
"name": "descriptor_version",
|
||||
"type": "std::uint32_t"
|
||||
},
|
||||
{
|
||||
"name": "module_id",
|
||||
"type": "std::string"
|
||||
},
|
||||
{
|
||||
"name": "component_version",
|
||||
"type": "Void::Semver::Version"
|
||||
},
|
||||
{
|
||||
"name": "abi_hash",
|
||||
"type": "std::string"
|
||||
},
|
||||
{
|
||||
"name": "abi_contract",
|
||||
"type": "Void::Json::Value"
|
||||
},
|
||||
{
|
||||
"name": "dependencies",
|
||||
"type": "std::vector<Void::Plugin::ModuleDependency>"
|
||||
},
|
||||
{
|
||||
"name": "activation_policy",
|
||||
"type": "Void::Plugin::ActivationPolicy"
|
||||
},
|
||||
{
|
||||
"name": "create",
|
||||
"type": "Void::Plugin::module_factory_fn"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Void::Plugin::IModule",
|
||||
"methods": [
|
||||
{
|
||||
"name": "activate",
|
||||
"type": "Void::Result::Result<void>(Void::Plugin::ModuleHost&)"
|
||||
},
|
||||
{
|
||||
"name": "quiesce",
|
||||
"type": "Void::Result::Result<void>(std::chrono::steady_clock::time_point)"
|
||||
},
|
||||
{
|
||||
"name": "checkpoint",
|
||||
"type": "Void::Json::Value() const"
|
||||
},
|
||||
{
|
||||
"name": "restore",
|
||||
"type": "Void::Result::Result<void>(const Void::Json::Value&)"
|
||||
},
|
||||
{
|
||||
"name": "readiness",
|
||||
"type": "Void::Plugin::ModuleReadiness() const"
|
||||
},
|
||||
{
|
||||
"name": "deactivate",
|
||||
"type": "Void::Result::Result<void>()"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Plugin/Module.hpp>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#if defined(ECHOION_MODULE_BUILD)
|
||||
#define ECHOION_MODULE_EXPORT __declspec(dllexport)
|
||||
#else
|
||||
#define ECHOION_MODULE_EXPORT __declspec(dllimport)
|
||||
#endif
|
||||
#else
|
||||
#define ECHOION_MODULE_EXPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
namespace Echoion::Api::Module
|
||||
{
|
||||
using Void::Plugin::ActivationPolicy;
|
||||
using Void::Plugin::IModule;
|
||||
using Void::Plugin::module_factory_fn;
|
||||
using Void::Plugin::module_query_fn;
|
||||
using Void::Plugin::ModuleDependency;
|
||||
using Void::Plugin::ModuleDescriptor;
|
||||
using Void::Plugin::ModuleHost;
|
||||
using Void::Plugin::ModuleReadiness;
|
||||
|
||||
inline constexpr auto descriptorVersion =
|
||||
Void::Plugin::MODULE_DESCRIPTOR_VERSION;
|
||||
inline constexpr const char* querySymbol = "echoion_module_query";
|
||||
|
||||
} // namespace Echoion::Api::Module
|
||||
|
||||
extern "C" ECHOION_MODULE_EXPORT const Void::Plugin::ModuleDescriptor*
|
||||
echoion_module_query();
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Canonicalize, hash, classify, and version Echoion module contracts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
SEMVER = re.compile(
|
||||
r"^(?P<major>0|[1-9][0-9]*)\."
|
||||
r"(?P<minor>0|[1-9][0-9]*)\."
|
||||
r"(?P<patch>0|[1-9][0-9]*)$"
|
||||
)
|
||||
|
||||
|
||||
def load_contract(path: Path) -> Any:
|
||||
with path.open(encoding="utf-8") as source:
|
||||
contract = json.load(source)
|
||||
if not isinstance(contract, dict) or contract.get("schemaVersion") != 1:
|
||||
raise ValueError(f"{path}: unsupported ABI contract schema")
|
||||
return contract
|
||||
|
||||
|
||||
def canonical_bytes(contract: Any) -> bytes:
|
||||
return (
|
||||
json.dumps(
|
||||
contract,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
+ "\n"
|
||||
).encode()
|
||||
|
||||
|
||||
def contract_hash(contract: Any) -> str:
|
||||
return "sha256:" + hashlib.sha256(canonical_bytes(contract)).hexdigest()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Compatibility:
|
||||
compatible: bool
|
||||
changed: bool
|
||||
|
||||
|
||||
def compare_contract(old: Any, new: Any) -> Compatibility:
|
||||
"""Return whether new is an append-only superset of old."""
|
||||
if type(old) is not type(new):
|
||||
return Compatibility(False, True)
|
||||
if isinstance(old, dict):
|
||||
changed = len(old) != len(new)
|
||||
for key, old_value in old.items():
|
||||
if key not in new:
|
||||
return Compatibility(False, True)
|
||||
result = compare_contract(old_value, new[key])
|
||||
if not result.compatible:
|
||||
return result
|
||||
changed = changed or result.changed
|
||||
return Compatibility(True, changed)
|
||||
if isinstance(old, list):
|
||||
if len(new) < len(old):
|
||||
return Compatibility(False, True)
|
||||
changed = len(new) != len(old)
|
||||
for index, old_value in enumerate(old):
|
||||
result = compare_contract(old_value, new[index])
|
||||
if not result.compatible:
|
||||
return result
|
||||
changed = changed or result.changed
|
||||
return Compatibility(True, changed)
|
||||
return Compatibility(old == new, old != new)
|
||||
|
||||
|
||||
def classify(
|
||||
old_contract: Any,
|
||||
new_contract: Any,
|
||||
old_source_sha: str,
|
||||
new_source_sha: str,
|
||||
kind: str,
|
||||
) -> str:
|
||||
if old_source_sha == new_source_sha:
|
||||
if canonical_bytes(old_contract) != canonical_bytes(new_contract):
|
||||
raise ValueError("ABI contract changed without a source SHA change")
|
||||
return "unchanged"
|
||||
if kind in {"executable", "assets"}:
|
||||
return "patch"
|
||||
|
||||
comparison = compare_contract(old_contract, new_contract)
|
||||
if not comparison.compatible:
|
||||
return "major"
|
||||
return "minor" if comparison.changed else "patch"
|
||||
|
||||
|
||||
def derive_version(current: str, change: str) -> str:
|
||||
match = SEMVER.fullmatch(current)
|
||||
if match is None:
|
||||
raise ValueError(f"component version is not stable SemVer: {current}")
|
||||
major, minor, patch = (
|
||||
int(match.group("major")),
|
||||
int(match.group("minor")),
|
||||
int(match.group("patch")),
|
||||
)
|
||||
if change == "unchanged":
|
||||
return current
|
||||
if change == "patch":
|
||||
return f"{major}.{minor}.{patch + 1}"
|
||||
if change == "minor":
|
||||
return f"{major}.{minor + 1}.0"
|
||||
if change == "major":
|
||||
return f"{major + 1}.0.0"
|
||||
raise ValueError(f"unsupported change classification: {change}")
|
||||
|
||||
|
||||
def write_or_print(payload: bytes, output: Path | None) -> None:
|
||||
if output is None:
|
||||
sys.stdout.buffer.write(payload)
|
||||
return
|
||||
temporary = output.with_name(output.name + ".tmp")
|
||||
temporary.write_bytes(payload)
|
||||
temporary.replace(output)
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser()
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
canonical = subparsers.add_parser("canonicalize")
|
||||
canonical.add_argument("contract", type=Path)
|
||||
canonical.add_argument("--output", type=Path)
|
||||
|
||||
digest = subparsers.add_parser("hash")
|
||||
digest.add_argument("contract", type=Path)
|
||||
|
||||
classify_parser = subparsers.add_parser("classify")
|
||||
classify_parser.add_argument("old_contract", type=Path)
|
||||
classify_parser.add_argument("new_contract", type=Path)
|
||||
classify_parser.add_argument("--old-source-sha", required=True)
|
||||
classify_parser.add_argument("--new-source-sha", required=True)
|
||||
classify_parser.add_argument(
|
||||
"--kind",
|
||||
choices=("module", "library", "executable", "assets"),
|
||||
default="module",
|
||||
)
|
||||
|
||||
derive = subparsers.add_parser("derive-version")
|
||||
derive.add_argument("current")
|
||||
derive.add_argument(
|
||||
"change", choices=("unchanged", "patch", "minor", "major")
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = build_parser().parse_args()
|
||||
try:
|
||||
if args.command == "canonicalize":
|
||||
write_or_print(
|
||||
canonical_bytes(load_contract(args.contract)), args.output
|
||||
)
|
||||
elif args.command == "hash":
|
||||
print(contract_hash(load_contract(args.contract)))
|
||||
elif args.command == "classify":
|
||||
print(
|
||||
classify(
|
||||
load_contract(args.old_contract),
|
||||
load_contract(args.new_contract),
|
||||
args.old_source_sha,
|
||||
args.new_source_sha,
|
||||
args.kind,
|
||||
)
|
||||
)
|
||||
elif args.command == "derive-version":
|
||||
print(derive_version(args.current, args.change))
|
||||
else:
|
||||
raise AssertionError(args.command)
|
||||
except (OSError, json.JSONDecodeError, ValueError) as error:
|
||||
print(f"abi-contract: {error}", file=sys.stderr)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,95 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
"abi_contract", ROOT / "scripts" / "abi_contract.py"
|
||||
)
|
||||
assert SPEC is not None and SPEC.loader is not None
|
||||
ABI = importlib.util.module_from_spec(SPEC)
|
||||
sys.modules[SPEC.name] = ABI
|
||||
SPEC.loader.exec_module(ABI)
|
||||
|
||||
|
||||
class AbiContractTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.contract = ABI.load_contract(
|
||||
ROOT / "abi" / "echoion-module-v1.json"
|
||||
)
|
||||
|
||||
def classify(self, updated: object, old: str = "a", new: str = "b") -> str:
|
||||
return ABI.classify(self.contract, updated, old, new, "module")
|
||||
|
||||
def test_canonical_hash_is_stable(self) -> None:
|
||||
reordered = {
|
||||
key: self.contract[key] for key in reversed(self.contract.keys())
|
||||
}
|
||||
self.assertEqual(
|
||||
ABI.contract_hash(self.contract), ABI.contract_hash(reordered)
|
||||
)
|
||||
|
||||
def test_unchanged_source_reuses_version_and_artifact(self) -> None:
|
||||
self.assertEqual(
|
||||
ABI.classify(
|
||||
self.contract, copy.deepcopy(self.contract), "same", "same", "module"
|
||||
),
|
||||
"unchanged",
|
||||
)
|
||||
self.assertEqual(ABI.derive_version("2.0.0", "unchanged"), "2.0.0")
|
||||
|
||||
def test_implementation_only_change_increments_patch(self) -> None:
|
||||
self.assertEqual(self.classify(copy.deepcopy(self.contract)), "patch")
|
||||
self.assertEqual(ABI.derive_version("2.0.0", "patch"), "2.0.1")
|
||||
|
||||
def test_append_only_change_increments_minor(self) -> None:
|
||||
updated = copy.deepcopy(self.contract)
|
||||
updated["types"][0]["fields"].append(
|
||||
{
|
||||
"name": "future_field",
|
||||
"type": "uint64_t",
|
||||
"ownership": "value",
|
||||
}
|
||||
)
|
||||
self.assertEqual(self.classify(updated), "minor")
|
||||
self.assertEqual(ABI.derive_version("2.3.9", "minor"), "2.4.0")
|
||||
|
||||
def test_reordered_retyped_and_renamed_fields_are_breaking(self) -> None:
|
||||
for mutate in (
|
||||
lambda fields: fields.reverse(),
|
||||
lambda fields: fields[0].update(type="uint64_t"),
|
||||
lambda fields: fields[0].update(name="renamed"),
|
||||
):
|
||||
with self.subTest(mutate=mutate):
|
||||
updated = copy.deepcopy(self.contract)
|
||||
mutate(updated["types"][0]["fields"])
|
||||
self.assertEqual(self.classify(updated), "major")
|
||||
self.assertEqual(ABI.derive_version("2.3.9", "major"), "3.0.0")
|
||||
|
||||
def test_contract_change_without_source_change_is_rejected(self) -> None:
|
||||
updated = copy.deepcopy(self.contract)
|
||||
updated["types"].append({"name": "future", "fields": []})
|
||||
with self.assertRaisesRegex(
|
||||
ValueError, "without a source SHA change"
|
||||
):
|
||||
self.classify(updated, "same", "same")
|
||||
|
||||
def test_executable_and_assets_changes_increment_patch(self) -> None:
|
||||
incompatible = {"schemaVersion": 1}
|
||||
for kind in ("executable", "assets"):
|
||||
with self.subTest(kind=kind):
|
||||
self.assertEqual(
|
||||
ABI.classify(
|
||||
self.contract, incompatible, "old", "new", kind
|
||||
),
|
||||
"patch",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user