#include "Stateful.hpp" #include #include #include #include #include // Stateful plugin, schema v2 — same plugin name as v1, so a PluginManager // reload swaps v1 -> v2 in place. State gains a `tag` field; v1 JSON is // migrated by the chain living here (the new build knows the old format). namespace { struct StateV2 { int count = 0; std::string tag = "v2"; // added in v2 }; class PluginV2 final : public VoidTest::IStateful { public: [[nodiscard]] std::string_view name() const noexcept override { return "StatefulPlugin"; } [[nodiscard]] int counter() const override { return m_count.load(std::memory_order_relaxed); } void bump() override { m_count.fetch_add(1, std::memory_order_relaxed); } [[nodiscard]] int schema_version() const override { return 2; } std::atomic m_count{0}; std::string m_tag{"v2"}; }; Void::Json::MigrationChain migrations() { Void::Json::MigrationChain chain; // v1 -> v2: keep count, introduce tag marking the upgrade. chain.add(1, [](Void::Json::Value data) { data.as_object().emplace_back("tag", Void::Json::Value{"migrated"}); return data; }); return chain; } } // namespace template <> struct Void::Json::StateTraits { static constexpr std::uint32_t version = 2; }; extern "C" { void* void_plugin_create() { return new PluginV2; } void void_plugin_destroy(void* p) { delete static_cast(p); } Void::Plugin::PluginInfo void_plugin_info() { return { .abi_version = Void::Plugin::ABI_VERSION, .name = "StatefulPlugin", .plugin_version = "2.0.0", .description = "Stateful test plugin (schema v2)", }; } std::uint32_t void_plugin_state_version() { return 2; } const char* void_plugin_serialize_state(void* instance) { const auto* self = static_cast(instance); const StateV2 state{.count = self->counter(), .tag = self->m_tag}; const auto json = Void::Json::serialize(Void::Json::to_versioned_json(state)); char* out = static_cast(std::malloc(json.size() + 1)); if (out != nullptr) { std::memcpy(out, json.c_str(), json.size() + 1); } return out; } void void_plugin_free_string(const char* s) { std::free(const_cast(s)); // NOLINT } int void_plugin_deserialize_state(void* instance, const char* json, std::uint32_t /*from_version*/) { auto* self = static_cast(instance); const auto parsed = Void::Json::parse(json); if (!parsed.has_value()) { return 1; } // from_versioned_json reads the envelope's own __version and migrates // up to StateV2's version (2) using the chain. const auto state = Void::Json::from_versioned_json(*parsed, migrations()); if (!state.has_value()) { return 2; } self->m_count.store(state->count, std::memory_order_relaxed); self->m_tag = state->tag; return 0; } } // extern "C"