11 Commits
Author SHA1 Message Date
faumaray e2503244b3 Expose licensing and structured logging configuration
Independent component release / publish (push) Failing after 11s
2026-08-02 01:47:23 +03:00
faumaray 847308c160 Use configured ABI test compilers
Independent component release / publish (push) Failing after 6s
2026-07-30 00:04:29 +03:00
faumaray fccdb2e159 Use shared Gitea artifact registry 2026-07-29 23:43:44 +03:00
faumaray 21e158fae0 Avoid interactive SSH during release checkout 2026-07-29 23:11:54 +03:00
faumaray e4f5d88d14 Add stable C module ABI and component releases 2026-07-29 22:40:35 +03:00
faumaray a1ee8ef10b API: add component update transactions 2026-07-29 00:33:26 +03:00
faumaray 14b6f7a046 API: default independent builds to 2.0.0 2026-07-28 23:18:07 +03:00
faumaray efabac6564 API: make extensions reloadable modules 2026-07-28 22:59:12 +03:00
faumaray 325b1b9ae8 API: centralize plugin URL support 2026-07-28 22:43:26 +03:00
faumaray 257d2a9971 API: expose Void module contract 2026-07-28 22:38:13 +03:00
faumaray 06e06b7622 API: inherit product version and configure logging 2026-07-28 21:05:43 +03:00
16 changed files with 1384 additions and 8 deletions

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
name: Independent component release
on:
push:
tags: [v*]
schedule:
- cron: '17 2 * * *'
workflow_dispatch:
jobs:
publish:
runs-on: echoion-release-serial
steps:
- name: Check out component
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
fetch-depth: 0
persist-credentials: false
- name: Check out pinned public release tools
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
repository: Void/Echoion
ref: ${{ vars.ECHOION_RELEASE_TOOLS_REF }}
path: .echoion-release-tools
fetch-depth: 0
persist-credentials: false
- name: Build, publish, and merge feed transaction
shell: bash
env:
AWS_ACCESS_KEY_ID: ${{ secrets.COMPONENT_OBJECT_STORAGE_ACCESS_KEY }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.COMPONENT_OBJECT_STORAGE_SECRET_KEY }}
AWS_DEFAULT_REGION: ${{ vars.COMPONENT_OBJECT_STORAGE_REGION }}
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
ECHOION_DISTRIBUTION_BACKEND: ${{ vars.ECHOION_DISTRIBUTION_BACKEND }}
ECHOION_DISTRIBUTION_BASE_URL: ${{ vars.ECHOION_DISTRIBUTION_BASE_URL }}
ECHOION_FEED_BASE_URL: ${{ vars.ECHOION_FEED_BASE_URL }}
ECHOION_FEED_COMMIT_SIGNING_KEY: ${{ secrets.RELEASE_FEED_GIT_SIGNING_KEY }}
ECHOION_FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }}
ECHOION_FEED_REPOSITORY: ssh://gitea@git.faumaray.ru/Void/Echoion.git
ECHOION_FEED_SIGNING_KEY_ID: ${{ vars.ECHOION_FEED_SIGNING_KEY_ID }}
ECHOION_OBJECT_STORAGE_BUCKET: ${{ vars.COMPONENT_OBJECT_STORAGE_BUCKET }}
ECHOION_OBJECT_STORAGE_ENDPOINT: ${{ vars.COMPONENT_OBJECT_STORAGE_ENDPOINT }}
ECHOION_OBJECT_STORAGE_PREFIX: ${{ vars.COMPONENT_OBJECT_STORAGE_PREFIX }}
ECHOION_RELEASE_TAG_ALLOWED_SIGNERS: ${{ secrets.RELEASE_TAG_ALLOWED_SIGNERS }}
GITEA_API_URL: ${{ gitea.api_url }}
GITEA_EVENT_NAME: ${{ gitea.event_name }}
GITEA_REF_NAME: ${{ gitea.ref_name }}
GITEA_RUN_NUMBER: ${{ gitea.run_number }}
GITEA_SHA: ${{ gitea.sha }}
GITEA_REPOSITORY: ${{ gitea.repository }}
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
RELEASE_TOOLS_REF: ${{ vars.ECHOION_RELEASE_TOOLS_REF }}
run: |
set -euo pipefail
[[ "$RELEASE_TOOLS_REF" =~ ^[0-9a-f]{40}$ ]]
test "$(git -C .echoion-release-tools rev-parse HEAD)" = "$RELEASE_TOOLS_REF"
.echoion-release-tools/scripts/release-component.sh component.release.json
+2 -1
View File
@@ -1,4 +1,5 @@
*build*
.cache
.idea
AGENTS.md
AGENTS.md
__pycache__/
+84 -1
View File
@@ -1,5 +1,29 @@
cmake_minimum_required(VERSION 4.0.0)
project(EchoionApi VERSION 1.0.0 LANGUAGES CXX)
if(NOT DEFINED ECHOION_PRODUCT_VERSION)
set(ECHOION_PRODUCT_VERSION 0.0.0)
endif()
if(NOT DEFINED ECHOION_COMPONENT_VERSION)
set(ECHOION_COMPONENT_VERSION "${ECHOION_PRODUCT_VERSION}")
endif()
project(EchoionApi VERSION "${ECHOION_COMPONENT_VERSION}" LANGUAGES CXX)
if(PROJECT_IS_TOP_LEVEL)
file(DOWNLOAD
https://github.com/cpm-cmake/CPM.cmake/releases/download/v0.40.8/CPM.cmake
"${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake"
EXPECTED_HASH
SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791)
include("${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake")
CPMAddPackage(
NAME Void
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidlibrary.git
GIT_TAG main
OPTIONS "VOID_ENABLE_TESTING OFF")
option(BUILD_TESTS "Build component tests" ON)
if(BUILD_TESTS)
enable_testing()
endif()
endif()
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -7,6 +31,7 @@ set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
find_package(Threads REQUIRED)
find_package(Boost 1.87 CONFIG REQUIRED)
# ===== Granular API Libraries =====
# Directory structure:
@@ -78,6 +103,44 @@ target_link_libraries(EchoionApiPlugin INTERFACE
Void::Plugin
)
# Shared first-party plugin configuration and URL-host safety helpers. Their
# implementation remains in the SDK so independently built plugins do not
# duplicate or diverge from the same validation rules.
add_library(EchoionApiPluginSdk STATIC
src/ShortUrlSupport.cpp
)
add_library(Echoion::ApiPluginSdk ALIAS EchoionApiPluginSdk)
set_target_properties(EchoionApiPluginSdk PROPERTIES
EXPORT_NAME ApiPluginSdk
POSITION_INDEPENDENT_CODE ON
)
target_compile_features(EchoionApiPluginSdk PUBLIC cxx_std_26)
target_include_directories(EchoionApiPluginSdk PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
target_link_libraries(EchoionApiPluginSdk
PUBLIC
Echoion::ApiPlugin
Void::Data
Void::Net
Void::Text
)
target_include_directories(EchoionApiPluginSdk PRIVATE ${Boost_INCLUDE_DIRS})
# 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)
@@ -224,6 +287,8 @@ target_include_directories(EchoionApi INTERFACE
$<INSTALL_INTERFACE:include/echoion/api>
)
target_link_libraries(EchoionApi INTERFACE
Echoion::ApiModuleAbi
Echoion::ApiPluginSdk
Echoion::ApiBase
Echoion::ApiAudio
Echoion::ApiTrack
@@ -250,6 +315,8 @@ endif()
# Install and export all modules
install(TARGETS
EchoionApiModuleAbi
EchoionApiPluginSdk
EchoionApiBase
EchoionApiAudio
EchoionApiTrack
@@ -271,6 +338,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::
@@ -294,3 +365,15 @@ 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")
add_test(NAME echoion_module_abi_c_header_tests
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/tests/test_module_abi_c.py")
endif()
endif()
+72
View File
@@ -0,0 +1,72 @@
{
"schemaVersion": 1,
"contractId": "echoion.module",
"language": "C",
"header": "echoion/api/module/ModuleAbi.h",
"querySymbol": "echoion_module_abi_query",
"entryPoints": [
{
"name": "echoion_module_abi_query",
"returns": "const echoion_module_descriptor_v1*",
"ownership": "static-borrowed"
}
],
"types": [
{
"name": "echoion_module_descriptor_v1",
"version": 1,
"sizeVersioned": true,
"fields": [
{"name": "struct_size", "type": "size_t"},
{"name": "abi_version", "type": "uint32_t"},
{"name": "component_id", "type": "echoion_string_view_v1"},
{"name": "version_major", "type": "uint32_t"},
{"name": "version_minor", "type": "uint32_t"},
{"name": "version_patch", "type": "uint32_t"},
{"name": "version_prerelease", "type": "echoion_string_view_v1"},
{"name": "abi_hash", "type": "echoion_string_view_v1"},
{"name": "dependencies", "type": "const echoion_module_dependency_v1*"},
{"name": "dependency_count", "type": "size_t"},
{"name": "activation_policy", "type": "echoion_activation_policy_v1"},
{"name": "api", "type": "const echoion_module_api_v1*"},
{"name": "reserved", "type": "const void*[8]"}
]
},
{
"name": "echoion_module_api_v1",
"version": 1,
"sizeVersioned": true,
"fields": [
{"name": "struct_size", "type": "size_t"},
{"name": "abi_version", "type": "uint32_t"},
{"name": "create", "type": "echoion_status_v1 (*)(const echoion_module_host_v1*, echoion_module_instance_v1*)"},
{"name": "destroy", "type": "void (*)(echoion_module_instance_v1)"},
{"name": "activate", "type": "echoion_status_v1 (*)(echoion_module_instance_v1)"},
{"name": "quiesce", "type": "echoion_status_v1 (*)(echoion_module_instance_v1, int64_t)"},
{"name": "checkpoint", "type": "echoion_status_v1 (*)(echoion_module_instance_v1, echoion_write_bytes_fn_v1, void*)"},
{"name": "restore", "type": "echoion_status_v1 (*)(echoion_module_instance_v1, echoion_bytes_view_v1)"},
{"name": "readiness", "type": "echoion_status_v1 (*)(echoion_module_instance_v1, echoion_module_readiness_v1*)"},
{"name": "deactivate", "type": "echoion_status_v1 (*)(echoion_module_instance_v1)"}
]
},
{
"name": "echoion_module_host_v1",
"version": 1,
"sizeVersioned": true,
"fields": [
{"name": "struct_size", "type": "size_t"},
{"name": "abi_version", "type": "uint32_t"},
{"name": "context", "type": "void*"},
{"name": "query_service", "type": "echoion_query_service_fn_v1"},
{"name": "log", "type": "echoion_log_fn_v1"}
]
}
],
"rules": {
"opaqueHandles": true,
"explicitOwnership": true,
"exceptionsCrossBoundary": false,
"cppTypesCrossBoundary": false,
"appendOnlyCompatibility": true
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"schemaVersion": 1,
"componentId": "EchoionApi",
"productCompatibility": ">=2.0.0 <3.0.0",
"publishNightly": true,
"cmakeOptions": {}
}
+59 -2
View File
@@ -197,6 +197,51 @@ namespace Echoion::Api
uint32_t tempCleanupInterval = 3600; // seconds
};
// Process logging. Split mode writes exact-level files (trace.log,
// debug.log, ...) and optionally all.log. Set splitByLevel=false to keep
// the legacy single rotating file.
struct LoggingConfig {
bool console = true;
std::string level = "debug";
bool splitByLevel = true;
bool combined = true;
std::string fileName = "echoion.log";
uint64_t maxFileSizeBytes = 10 * 1024 * 1024;
uint32_t maxFiles = 10;
// "pattern", "json" (JSON Lines), or "logfmt".
std::string format = "pattern";
std::string pattern =
"[{time}] [{level}] [{thread}] {file} - {message}";
// "async", "immediate", or "buffered".
std::string mode = "async";
uint32_t queueCapacity = 2048;
// "block", "drop-newest", or "drop-oldest".
std::string overflowPolicy = "block";
};
// EchoionLicensing issues short-lived signed leases. The activation token
// is read from the named environment variable and is never written to the
// configuration file. Release builds provide the root trust anchor at
// compile time; developmentKeys are accepted only by explicitly opted-in
// development builds.
struct LicensePublicKey {
std::string id;
std::string ed25519;
};
struct LicensingConfig {
bool required = false;
std::string serviceUrl;
std::string productId = "echoion";
std::string activationTokenEnv = "ECHOION_LICENSE_TOKEN";
std::chrono::milliseconds refreshInterval = std::chrono::hours(6);
std::chrono::milliseconds retryInterval = std::chrono::minutes(5);
std::chrono::milliseconds maximumLeaseLifetime =
std::chrono::hours(24);
bool developmentMode = false;
std::vector<LicensePublicKey> developmentKeys;
};
// Component updater. Runtime means the complete relocatable daemon bundle,
// not only the echoiond ELF. Core and managed extension plugins may use
// independent channels, but the updater still enforces the compatibility
@@ -207,6 +252,10 @@ namespace Echoion::Api
};
struct UpdateSourceConfig {
// "direct" addresses one feed document. "component-layout"
// addresses a channel root containing catalog.json and component
// discovery documents.
std::string kind = "direct";
// Empty is only meaningful for the built-in "official" source and
// resolves to the URL injected by the release build.
std::string url;
@@ -255,8 +304,14 @@ namespace Echoion::Api
// Number of previous healthy versions retained in addition to
// active.
uint32_t retainHealthyVersions = 2;
std::map<std::string, UpdateSourceConfig> sources = {
{"official", UpdateSourceConfig{}}};
std::map<std::string, UpdateSourceConfig> sources = {{
"official",
UpdateSourceConfig{.kind = "component-layout",
.url = {},
.publicKeys = {},
.allowUnsigned = false,
.bearerTokenEnv = {}},
}};
UpdateComponentConfig runtime;
UpdateComponentConfig core;
PluginUpdatesConfig plugins;
@@ -294,6 +349,8 @@ namespace Echoion::Api
SecurityConfig security;
FeaturesConfig features;
AdvancedConfig advanced;
LoggingConfig logging;
LicensingConfig licensing;
UpdatesConfig updates;
UrlShorteningConfig urlShortening;
PluginsConfig plugins;
@@ -0,0 +1,207 @@
#pragma once
#include <echoion/api/module/Module.hpp>
#include <echoion/api/module/ModuleAbi.h>
#include <Void/Data/Json.hpp>
#include <chrono>
#include <cstdint>
#include <limits>
#include <memory>
#include <string>
namespace Echoion::Api::Module
{
namespace Detail
{
inline echoion_string_view_v1
stringView(const std::string_view value) noexcept
{
return {.data = value.data(), .size = value.size()};
}
inline echoion_status_v1
status(const Void::Result::Result<void>& result) noexcept
{
return result ? ECHOION_STATUS_OK_V1 : ECHOION_STATUS_INTERNAL_V1;
}
} // namespace Detail
// Transitional adapter for existing C++ lifecycle implementations. The
// exported descriptor and calls are pure C. C++ ownership and exceptions
// remain confined to the module that created the opaque instance.
template <Void::Plugin::module_factory_fn Factory>
struct LegacyModuleAbi final {
struct Instance {
std::unique_ptr<Void::Plugin::IModule> module;
std::string readinessDetail;
};
static echoion_status_v1
create(const echoion_module_host_v1* host,
echoion_module_instance_v1* output) noexcept
{
static_cast<void>(host);
if (output == nullptr) {
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
}
try {
auto module = Factory();
if (!module) {
return ECHOION_STATUS_INTERNAL_V1;
}
auto instance = std::make_unique<Instance>(Instance{
.module = std::move(module), .readinessDetail = {}});
*output = instance.release();
return ECHOION_STATUS_OK_V1;
} catch (...) {
return ECHOION_STATUS_INTERNAL_V1;
}
}
static void destroy(echoion_module_instance_v1 value) noexcept
{
std::unique_ptr<Instance> instance{
static_cast<Instance*>(value)};
}
static echoion_status_v1
activate(echoion_module_instance_v1 value) noexcept
{
Instance* instance = checked(value);
if (instance == nullptr) {
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
}
try {
instance->module->on_load();
return ECHOION_STATUS_OK_V1;
} catch (...) {
return ECHOION_STATUS_INTERNAL_V1;
}
}
static echoion_status_v1
quiesce(echoion_module_instance_v1 value,
const std::int64_t deadlineNanoseconds) noexcept
{
Instance* instance = checked(value);
if (instance == nullptr || deadlineNanoseconds < 0) {
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
}
try {
const auto deadline = std::chrono::steady_clock::time_point{
std::chrono::nanoseconds{deadlineNanoseconds}};
return Detail::status(instance->module->quiesce(deadline));
} catch (...) {
return ECHOION_STATUS_INTERNAL_V1;
}
}
static echoion_status_v1
checkpoint(echoion_module_instance_v1 value,
echoion_write_bytes_fn_v1 writer,
void* writerContext) noexcept
{
Instance* instance = checked(value);
if (instance == nullptr || writer == nullptr) {
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
}
try {
const std::string encoded =
Void::Json::serialize(instance->module->checkpoint());
return writer(
writerContext,
{.data = reinterpret_cast<const std::uint8_t*>(
encoded.data()),
.size = encoded.size()});
} catch (...) {
return ECHOION_STATUS_INTERNAL_V1;
}
}
static echoion_status_v1
restore(echoion_module_instance_v1 value,
const echoion_bytes_view_v1 state) noexcept
{
Instance* instance = checked(value);
if (instance == nullptr ||
(state.data == nullptr && state.size != 0)) {
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
}
try {
const std::string_view encoded =
state.size == 0
? std::string_view{}
: std::string_view{
reinterpret_cast<const char*>(state.data),
state.size};
const auto parsed = Void::Json::parse(encoded);
if (!parsed) {
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
}
return Detail::status(instance->module->restore(*parsed));
} catch (...) {
return ECHOION_STATUS_INTERNAL_V1;
}
}
static echoion_status_v1
readiness(echoion_module_instance_v1 value,
echoion_module_readiness_v1* output) noexcept
{
Instance* instance = checked(value);
if (instance == nullptr || output == nullptr ||
output->struct_size < sizeof(echoion_module_readiness_v1)) {
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
}
try {
const auto result = instance->module->readiness();
instance->readinessDetail = result.detail;
output->ready = result.ready ? 1U : 0U;
output->detail =
Detail::stringView(instance->readinessDetail);
return ECHOION_STATUS_OK_V1;
} catch (...) {
return ECHOION_STATUS_INTERNAL_V1;
}
}
static echoion_status_v1
deactivate(echoion_module_instance_v1 value) noexcept
{
Instance* instance = checked(value);
if (instance == nullptr) {
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
}
try {
return Detail::status(instance->module->deactivate());
} catch (...) {
return ECHOION_STATUS_INTERNAL_V1;
}
}
inline static const echoion_module_api_v1 api{
.struct_size = sizeof(echoion_module_api_v1),
.abi_version = ECHOION_MODULE_ABI_VERSION,
.create = create,
.destroy = destroy,
.activate = activate,
.quiesce = quiesce,
.checkpoint = checkpoint,
.restore = restore,
.readiness = readiness,
.deactivate = deactivate,
.reserved = {},
};
private:
[[nodiscard]] static Instance*
checked(echoion_module_instance_v1 value) noexcept
{
return static_cast<Instance*>(value);
}
};
} // namespace Echoion::Api::Module
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include <echoion/api/module/ModuleAbi.h>
#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";
inline constexpr const char* stableQuerySymbol =
ECHOION_MODULE_ABI_QUERY_SYMBOL;
} // namespace Echoion::Api::Module
extern "C" ECHOION_MODULE_EXPORT const Void::Plugin::ModuleDescriptor*
echoion_module_query();
+131
View File
@@ -0,0 +1,131 @@
#ifndef ECHOION_API_MODULE_MODULE_ABI_H
#define ECHOION_API_MODULE_MODULE_ABI_H
#include <stddef.h>
#include <stdint.h>
#if defined(_WIN32)
#if defined(ECHOION_MODULE_BUILD)
#define ECHOION_MODULE_ABI_EXPORT __declspec(dllexport)
#else
#define ECHOION_MODULE_ABI_EXPORT __declspec(dllimport)
#endif
#else
#define ECHOION_MODULE_ABI_EXPORT __attribute__((visibility("default")))
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define ECHOION_MODULE_ABI_VERSION 1U
#define ECHOION_MODULE_ABI_QUERY_SYMBOL "echoion_module_abi_query"
typedef struct echoion_string_view_v1 {
const char* data;
size_t size;
} echoion_string_view_v1;
typedef struct echoion_bytes_view_v1 {
const uint8_t* data;
size_t size;
} echoion_bytes_view_v1;
typedef enum echoion_status_v1 {
ECHOION_STATUS_OK_V1 = 0,
ECHOION_STATUS_INVALID_ARGUMENT_V1 = 1,
ECHOION_STATUS_INCOMPATIBLE_V1 = 2,
ECHOION_STATUS_UNAVAILABLE_V1 = 3,
ECHOION_STATUS_INTERNAL_V1 = 4
} echoion_status_v1;
typedef enum echoion_activation_policy_v1 {
ECHOION_ACTIVATION_RELOADABLE_V1 = 0,
ECHOION_ACTIVATION_RESTART_REQUIRED_V1 = 1,
ECHOION_ACTIVATION_INSTALLER_REQUIRED_V1 = 2
} echoion_activation_policy_v1;
typedef void* echoion_module_instance_v1;
typedef echoion_status_v1 (*echoion_write_bytes_fn_v1)(
void* context, echoion_bytes_view_v1 value);
typedef echoion_status_v1 (*echoion_query_service_fn_v1)(
void* context, echoion_string_view_v1 service_id, uint32_t minimum_version,
const void** service);
typedef void (*echoion_log_fn_v1)(void* context, uint32_t level,
echoion_string_view_v1 message);
typedef struct echoion_module_host_v1 {
size_t struct_size;
uint32_t abi_version;
void* context;
echoion_query_service_fn_v1 query_service;
echoion_log_fn_v1 log;
const void* reserved[8];
} echoion_module_host_v1;
typedef struct echoion_module_readiness_v1 {
size_t struct_size;
uint8_t ready;
uint8_t reserved_bytes[7];
echoion_string_view_v1 detail;
} echoion_module_readiness_v1;
typedef struct echoion_module_api_v1 {
size_t struct_size;
uint32_t abi_version;
echoion_status_v1 (*create)(const echoion_module_host_v1* host,
echoion_module_instance_v1* instance);
void (*destroy)(echoion_module_instance_v1 instance);
echoion_status_v1 (*activate)(echoion_module_instance_v1 instance);
echoion_status_v1 (*quiesce)(echoion_module_instance_v1 instance,
int64_t steady_clock_deadline_nanoseconds);
echoion_status_v1 (*checkpoint)(echoion_module_instance_v1 instance,
echoion_write_bytes_fn_v1 writer,
void* writer_context);
echoion_status_v1 (*restore)(echoion_module_instance_v1 instance,
echoion_bytes_view_v1 state);
echoion_status_v1 (*readiness)(echoion_module_instance_v1 instance,
echoion_module_readiness_v1* readiness);
echoion_status_v1 (*deactivate)(echoion_module_instance_v1 instance);
const void* reserved[8];
} echoion_module_api_v1;
typedef struct echoion_module_dependency_v1 {
size_t struct_size;
echoion_string_view_v1 component_id;
echoion_string_view_v1 version_range;
echoion_string_view_v1 abi_hash;
uint8_t optional;
uint8_t reserved_bytes[7];
} echoion_module_dependency_v1;
typedef struct echoion_module_descriptor_v1 {
size_t struct_size;
uint32_t abi_version;
echoion_string_view_v1 component_id;
uint32_t version_major;
uint32_t version_minor;
uint32_t version_patch;
echoion_string_view_v1 version_prerelease;
echoion_string_view_v1 abi_hash;
const echoion_module_dependency_v1* dependencies;
size_t dependency_count;
echoion_activation_policy_v1 activation_policy;
const echoion_module_api_v1* api;
const void* reserved[8];
} echoion_module_descriptor_v1;
typedef const echoion_module_descriptor_v1* (*echoion_module_abi_query_fn_v1)(
void);
ECHOION_MODULE_ABI_EXPORT const echoion_module_descriptor_v1*
echoion_module_abi_query(void);
#ifdef __cplusplus
}
#endif
#endif
@@ -3,7 +3,7 @@
#include <PluginTypes.hpp>
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <Void/Plugin/Plugin.hpp>
#include <Void/Plugin/Module.hpp>
#include <cstdint>
#include <string>
@@ -58,7 +58,7 @@ namespace Echoion::Api
// Native, trusted Echoion extension contract. Calls are always made while
// the host holds a Void::Plugin::PluginHandle, so a hot reload cannot
// unmap code that is still executing.
class IExtensionPlugin : public Void::Plugin::IPlugin
class IExtensionPlugin : public Void::Plugin::IModule
{
public:
[[nodiscard]] virtual std::vector<ExtensionCommand> commands() const
@@ -0,0 +1,52 @@
#pragma once
#include <Void/Data/Json.hpp>
#include <cstdint>
#include <expected>
#include <optional>
#include <string>
#include <string_view>
namespace Echoion::Api::Plugin::ShortUrl
{
template <typename T> using Result = std::expected<T, std::string>;
[[nodiscard]] Result<Void::Json::Value>
parseConfigObject(const char* config);
[[nodiscard]] Result<std::string>
requireString(const Void::Json::Value& object, std::string_view key);
[[nodiscard]] Result<std::string>
optionalString(const Void::Json::Value& object, std::string_view key,
std::string_view fallback = {});
[[nodiscard]] Result<bool> optionalBool(const Void::Json::Value& object,
std::string_view key,
bool fallback);
[[nodiscard]] Result<std::int64_t>
optionalInteger(const Void::Json::Value& object, std::string_view key,
std::int64_t fallback, std::int64_t minimum,
std::int64_t maximum);
[[nodiscard]] bool
containsControlCharacters(std::string_view value) noexcept;
[[nodiscard]] std::string trimAscii(std::string_view value);
[[nodiscard]] bool isHeaderName(std::string_view value) noexcept;
[[nodiscard]] bool isBase62(std::string_view value) noexcept;
/// Validate an absolute HTTP(S) URL without making a network request.
[[nodiscard]] Result<void>
validateHttpUrl(std::string_view value, bool requireHttps,
std::size_t maximumLength = 8192);
/// Reject address literals and well-known hostnames that are not publicly
/// routable. DNS-backed validation lives in the external provider because
/// only it opens outbound connections.
[[nodiscard]] bool isObviouslyPrivateHost(std::string_view host) noexcept;
/// Expand ${url} and ${env:NAME}. Environment variables are read without
/// being copied into diagnostics; a missing variable reports only its name.
[[nodiscard]] Result<std::string>
expandTemplate(std::string_view input, std::string_view url,
bool encodeSubstitutions = false);
} // namespace Echoion::Api::Plugin::ShortUrl
+6 -2
View File
@@ -119,14 +119,18 @@ namespace Echoion::Api
SendTeamSpeakChannelMessage,
SendTeamSpeakServerMessage,
// Component updater (append-only; values 89-95).
// Component updater (append-only; values 89-99).
GetUpdateStatus,
GetUpdateConfig,
SetUpdateConfig,
CheckForUpdates,
ApplyUpdate,
RollbackUpdate,
ConfirmUnsignedUpdate
ConfirmUnsignedUpdate,
PreviewUpdateTransaction,
ApplyUpdateTransaction,
RollbackUpdateGeneration,
GetUpdateHistory
};
struct RpcRequest {
+189
View File
@@ -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())
+319
View File
@@ -0,0 +1,319 @@
#include <echoion/api/plugin/ShortUrlSupport.hpp>
#include <Void/Net/Url.hpp>
#include <Void/Text/Url.hpp>
#include <boost/asio/ip/address.hpp>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdlib>
#include <format>
#include <limits>
namespace Echoion::Api::Plugin::ShortUrl
{
namespace
{
[[nodiscard]] bool validEnvironmentName(std::string_view name) noexcept
{
if (name.empty() ||
!(std::isalpha(static_cast<unsigned char>(name.front())) != 0 ||
name.front() == '_')) {
return false;
}
return std::ranges::all_of(
name.substr(1), [](const char character) {
const auto value = static_cast<unsigned char>(character);
return std::isalnum(value) != 0 || character == '_';
});
}
[[nodiscard]] bool
isPrivateV4(const boost::asio::ip::address_v4 address) noexcept
{
const auto value = address.to_uint();
const auto first = static_cast<unsigned>((value >> 24U) & 0xffU);
const auto second = static_cast<unsigned>((value >> 16U) & 0xffU);
const auto third = static_cast<unsigned>((value >> 8U) & 0xffU);
return first == 0U || first == 10U || first == 127U ||
(first == 100U && second >= 64U && second <= 127U) ||
(first == 169U && second == 254U) ||
(first == 172U && second >= 16U && second <= 31U) ||
(first == 192U && second == 168U) ||
(first == 192U && second == 0U && third <= 2U) ||
(first == 198U && (second == 18U || second == 19U)) ||
(first == 198U && second == 51U && third == 100U) ||
(first == 203U && second == 0U && third == 113U) ||
first >= 224U;
}
[[nodiscard]] bool
isPrivateV6(const boost::asio::ip::address_v6 address) noexcept
{
const auto bytes = address.to_bytes();
if (address.is_unspecified() || address.is_loopback() ||
address.is_link_local() || address.is_multicast()) {
return true;
}
if (address.is_v4_mapped()) {
const boost::asio::ip::address_v4::bytes_type mapped{
bytes[12], bytes[13], bytes[14], bytes[15]};
return isPrivateV4(boost::asio::ip::address_v4{mapped});
}
const bool uniqueLocal = (bytes[0] & 0xfeU) == 0xfcU;
const bool documentation = bytes[0] == 0x20U && bytes[1] == 0x01U &&
bytes[2] == 0x0dU && bytes[3] == 0xb8U;
return uniqueLocal || documentation;
}
} // namespace
Result<Void::Json::Value> parseConfigObject(const char* config)
{
if (config == nullptr || *config == '\0') {
return std::unexpected{"plugin configuration is required"};
}
auto parsed = Void::Json::parse(config);
if (!parsed) {
return std::unexpected{
std::format("invalid plugin configuration at {}:{}: {}",
parsed.error().line, parsed.error().col,
parsed.error().message)};
}
if (!parsed->is_object()) {
return std::unexpected{
"plugin configuration must be a JSON object"};
}
return std::move(*parsed);
}
Result<std::string> requireString(const Void::Json::Value& object,
const std::string_view key)
{
const auto* value = object.find(key);
if (value == nullptr || !value->is_string() ||
value->as_string().empty()) {
return std::unexpected{std::format(
"configuration field '{}' must be a non-empty string", key)};
}
return value->as_string();
}
Result<std::string> optionalString(const Void::Json::Value& object,
const std::string_view key,
const std::string_view fallback)
{
const auto* value = object.find(key);
if (value == nullptr) {
return std::string{fallback};
}
if (!value->is_string()) {
return std::unexpected{
std::format("configuration field '{}' must be a string", key)};
}
return value->as_string();
}
Result<bool> optionalBool(const Void::Json::Value& object,
const std::string_view key, const bool fallback)
{
const auto* value = object.find(key);
if (value == nullptr) {
return fallback;
}
if (!value->is_bool()) {
return std::unexpected{
std::format("configuration field '{}' must be a boolean", key)};
}
return value->as_bool();
}
Result<std::int64_t> optionalInteger(const Void::Json::Value& object,
const std::string_view key,
const std::int64_t fallback,
const std::int64_t minimum,
const std::int64_t maximum)
{
const auto* value = object.find(key);
if (value == nullptr) {
return fallback;
}
if (!value->is_number()) {
return std::unexpected{std::format(
"configuration field '{}' must be an integer", key)};
}
const auto number = value->as_number();
if (!std::isfinite(number) || std::floor(number) != number ||
number < static_cast<double>(minimum) ||
number > static_cast<double>(maximum)) {
return std::unexpected{std::format(
"configuration field '{}' must be between {} and {}", key,
minimum, maximum)};
}
return static_cast<std::int64_t>(number);
}
bool containsControlCharacters(const std::string_view value) noexcept
{
return std::ranges::any_of(value, [](const char character) {
const auto byte = static_cast<unsigned char>(character);
return byte < 0x20U || byte == 0x7fU;
});
}
std::string trimAscii(const std::string_view value)
{
const auto isSpace = [](const char character) {
return std::isspace(static_cast<unsigned char>(character)) != 0;
};
const auto first = std::ranges::find_if_not(value, isSpace);
const auto last =
std::find_if_not(value.rbegin(), value.rend(), isSpace).base();
if (first >= last) {
return {};
}
return {first, last};
}
bool isHeaderName(const std::string_view value) noexcept
{
if (value.empty()) {
return false;
}
constexpr std::string_view separators{"()<>@,;:\\\"/[]?={} \t"};
return std::ranges::all_of(value, [separators](const char character) {
const auto byte = static_cast<unsigned char>(character);
return byte > 0x20U && byte < 0x7fU &&
separators.find(character) == std::string_view::npos;
});
}
bool isBase62(const std::string_view value) noexcept
{
return !value.empty() && std::ranges::all_of(value, [](const char c) {
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z');
});
}
Result<void> validateHttpUrl(const std::string_view value,
const bool requireHttps,
const std::size_t maximumLength)
{
if (value.empty() || value.size() > maximumLength ||
containsControlCharacters(value) ||
std::ranges::any_of(value, [](const char c) {
return std::isspace(static_cast<unsigned char>(c)) != 0;
})) {
return std::unexpected{
"URL is empty, too long, or contains whitespace"};
}
const auto parsed = Void::Net::Url::parse(value);
if (!parsed || parsed->host.empty() ||
(parsed->scheme != "http" && parsed->scheme != "https")) {
return std::unexpected{"URL must be an absolute HTTP(S) URL"};
}
if (requireHttps && parsed->scheme != "https") {
return std::unexpected{"URL must use HTTPS"};
}
const auto schemeEnd = value.find("://");
const auto authorityEnd = value.find_first_of("/?#", schemeEnd + 3U);
const auto authority =
value.substr(schemeEnd + 3U, authorityEnd == std::string_view::npos
? std::string_view::npos
: authorityEnd - schemeEnd - 3U);
if (authority.find('@') != std::string_view::npos) {
return std::unexpected{"URL userinfo is not allowed"};
}
return {};
}
bool isObviouslyPrivateHost(const std::string_view host) noexcept
{
std::string lower;
lower.reserve(host.size());
std::ranges::transform(
host, std::back_inserter(lower), [](const char c) {
return static_cast<char>(
std::tolower(static_cast<unsigned char>(c)));
});
while (!lower.empty() && lower.back() == '.') {
lower.pop_back();
}
if (lower == "localhost" || lower.ends_with(".localhost") ||
lower.ends_with(".local") || lower.ends_with(".internal")) {
return true;
}
boost::system::error_code error;
const auto address = boost::asio::ip::make_address(lower, error);
if (error) {
return false;
}
return address.is_v4() ? isPrivateV4(address.to_v4())
: isPrivateV6(address.to_v6());
}
Result<std::string> expandTemplate(const std::string_view input,
const std::string_view url,
const bool encodeSubstitutions)
{
const auto appendReplacement =
[encodeSubstitutions](std::string& destination,
const std::string_view replacement) {
if (encodeSubstitutions) {
destination.append(
Void::Encoding::Url::query_encode(replacement));
} else {
destination.append(replacement);
}
};
std::string output;
output.reserve(input.size() + url.size());
std::size_t position{};
while (position < input.size()) {
const auto marker = input.find("${", position);
if (marker == std::string_view::npos) {
output.append(input.substr(position));
break;
}
output.append(input.substr(position, marker - position));
const auto end = input.find('}', marker + 2U);
if (end == std::string_view::npos) {
return std::unexpected{"unterminated template placeholder"};
}
const auto token = input.substr(marker + 2U, end - marker - 2U);
if (token == "url") {
appendReplacement(output, url);
} else if (token.starts_with("env:")) {
const auto name = token.substr(4U);
if (!validEnvironmentName(name)) {
return std::unexpected{
"invalid environment placeholder name"};
}
const std::string ownedName{name};
const char* value = std::getenv(ownedName.c_str());
if (value == nullptr) {
return std::unexpected{std::format(
"required environment variable '{}' is not set", name)};
}
if (containsControlCharacters(value)) {
return std::unexpected{std::format(
"environment variable '{}' contains control characters",
name)};
}
appendReplacement(output, value);
} else {
return std::unexpected{std::format(
"unsupported template placeholder '${{{}}}'", token)};
}
position = end + 1U;
}
return output;
}
} // namespace Echoion::Api::Plugin::ShortUrl
+95
View File
@@ -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()
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Compile the public module ABI as both C and C++."""
from __future__ import annotations
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
HEADER = ROOT / "include"
class ModuleAbiCTests(unittest.TestCase):
def compile(self, compiler: str, suffix: str, standard: str) -> None:
with tempfile.TemporaryDirectory(
prefix="echoion-module-abi."
) as directory:
source = Path(directory) / f"consumer.{suffix}"
source.write_text(
"""
#include <echoion/api/module/ModuleAbi.h>
int main(void) {
#ifdef __cplusplus
echoion_module_descriptor_v1 descriptor = {};
#else
echoion_module_descriptor_v1 descriptor = {0};
#endif
descriptor.struct_size = sizeof(descriptor);
descriptor.abi_version = ECHOION_MODULE_ABI_VERSION;
return descriptor.api == 0 ? 0 : 1;
}
"""
)
result = subprocess.run(
[
compiler,
standard,
"-Wall",
"-Wextra",
"-Wpedantic",
"-Werror",
"-I",
str(HEADER),
"-fsyntax-only",
str(source),
],
check=False,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
self.assertEqual(result.returncode, 0, result.stderr)
def test_header_is_c11(self) -> None:
self.compile(os.environ.get("CC", "cc"), "c", "-std=c11")
def test_header_is_cpp20(self) -> None:
self.compile(os.environ.get("CXX", "c++"), "cpp", "-std=c++20")
if __name__ == "__main__":
unittest.main()