# Phase 0: Decoupled State Management Foundation - Implementation Plan ## Overview Build the foundation for decoupled state management where: - **Plugin** never knows Core's internal state structure - **Core** handles all serialization/deserialization internally - **State format can change** without Plugin rebuilds - **10 versions backward compatibility** with graceful degradation ## Architecture ``` EchoionApi (stable interface) ├── ICoreInterface.hpp - Add state management methods └── SerializedState.hpp - Opaque blob type EchoionCore (internal implementation) ├── StateSerializer.hpp/cpp - Versioned serialization using glaze ├── StateMigration.hpp/cpp - Migration between versions ├── StateV0.hpp, StateV1.hpp, ... - Version-specific state structures └── Core.cpp - Implement state capture/restore EchoionPlugin (unchanged except CoreLoader) └── CoreLoader.cpp - Use opaque blobs, no state parsing ``` ## Files to Create/Modify ### 1. EchoionApi Changes **File**: `EchoionApi/include/echoion/api/interfaces/CoreInterface.hpp` Add to `ICoreInterface`: ```cpp // State management - opaque to caller virtual Api::SerializedState saveState() = 0; virtual Api::Result restoreState(const Api::SerializedState& state) = 0; // Version info virtual uint32_t getStateFormatVersion() const = 0; virtual bool canRestoreStateVersion(uint32_t version) const = 0; ``` **File**: `EchoionApi/include/echoion/api/base/SerializedState.hpp` (NEW) ```cpp #pragma once #include #include #include namespace Echoion::Api { // Opaque state blob - contents are internal to Core struct SerializedState { std::vector data; // Serialized state data (JSON using glaze) uint32_t version = 0; // Format version (for logging/debugging only) std::string timestamp; // ISO 8601 timestamp when saved bool empty() const { return data.empty(); } size_t size() const { return data.size(); } }; // Constants constexpr uint32_t MAX_SUPPORTED_STATE_VERSION_AGE = 10; // Support 10 versions back constexpr uint32_t STATE_VERSION_NONE = 0; } // namespace Echoion::Api ``` ### 2. EchoionCore Changes **File**: `EchoionCore/include/echoion/core/state/StateSerializer.hpp` (NEW) ```cpp #pragma once #include "echoion/core/state/StateVersions.hpp" #include #include #include #include #include namespace Echoion::Core { class StateSerializer { public: // Current version being used static constexpr uint32_t CURRENT_VERSION = 1; // Serialize current state to opaque blob static Api::SerializedState serialize(const StateV1& state); // Deserialize blob to current version (handles migration) static Api::Result deserialize(const Api::SerializedState& blob); // Check if version is supported static bool isVersionSupported(uint32_t version); // Get supported version range static uint32_t getMinimumSupportedVersion(); static uint32_t getCurrentVersion(); private: // Migration functions static Api::Result migrateToV1(const StateV0& old); // Extract version from JSON blob static uint32_t extractVersion(const std::string& jsonStr); }; } // namespace Echoion::Core ``` **File**: `EchoionCore/include/echoion/core/state/StateVersions.hpp` (NEW) ```cpp #pragma once #include #include #include #include #include namespace Echoion::Core { // State V0 - Initial version (placeholder for future) struct StateV0 { // Minimal state for testing migration std::vector trackIds; float volume = 0.5f; }; // State V1 - Current version struct StateV1 { // Playback state struct PlaybackState { Api::TrackInfo currentTrack; std::chrono::milliseconds position{0}; bool isPlaying = false; bool isPaused = false; float volume = 0.5f; bool shuffle = false; bool repeat = false; }; // Queue entry with metadata struct QueueEntryState { Api::TrackInfo track; uint64_t queueId = 0; std::string addedBy; // Nickname or UID std::string addedAt; // ISO 8601 }; // Session state for RPC clients struct SessionState { uint64_t clientId = 0; std::string authToken; std::string lastActivity; // ISO 8601 }; // Main state std::optional playback; std::vector queue; std::vector sessions; // Version info uint32_t version = 1; std::string savedAt; // ISO 8601 }; } // namespace Echoion::Core // Glaze JSON reflection for StateV1 // (Add in StateVersions.cpp or at end of header) template <> struct glz::meta { using T = Echoion::Core::StateV1; static constexpr auto value = object( "playback", &T::playback, "queue", &T::queue, "sessions", &T::sessions, "version", &T::version, "savedAt", &T::savedAt ); }; ``` **File**: `EchoionCore/include/echoion/core/state/StateMigration.hpp` (NEW) ```cpp #pragma once #include "echoion/core/state/StateVersions.hpp" #include #include namespace Echoion::Core { // Handles migration between state versions class StateMigration { public: // Migrate from any old version to current static Api::Result migrate(uint32_t fromVersion, const std::string& jsonData); // Specific migrations static StateV1 fromV0(const StateV0& v0); // Check if migration path exists static bool canMigrate(uint32_t fromVersion); private: // Migration chain: V0 -> V1 -> V2 -> ... // Each version only knows how to migrate from previous }; } // namespace Echoion::Core ``` **File**: `EchoionCore/src/state/StateSerializer.cpp` (NEW) ```cpp #include "echoion/core/state/StateSerializer.hpp" #include "echoion/core/Logger.hpp" #include namespace Echoion::Core { Api::SerializedState StateSerializer::serialize(const StateV1& state) { // Serialize to JSON using glaze std::string jsonStr; auto ec = glz::write_json(state, jsonStr); if (ec) { ECHOION_LOG_ERROR(std::format("Failed to serialize state: {}", glz::format_error(ec, jsonStr))); return Api::SerializedState{}; } // Convert to binary blob std::vector data(jsonStr.begin(), jsonStr.end()); return Api::SerializedState{ .data = std::move(data), .version = CURRENT_VERSION, .timestamp = getCurrentTimestampISO8601() }; } Api::Result StateSerializer::deserialize(const Api::SerializedState& blob) { if (blob.data.empty()) { return std::unexpected(Api::Error( Api::ErrorCode::InvalidArgument, "Empty state blob" )); } // Convert blob to string std::string jsonStr(blob.data.begin(), blob.data.end()); // Extract version uint32_t dataVersion = extractVersion(jsonStr); ECHOION_LOG_INFO(std::format("Deserializing state version {}", dataVersion)); // Check if version is supported if (!isVersionSupported(dataVersion)) { if (dataVersion > CURRENT_VERSION) { return std::unexpected(Api::Error( Api::ErrorCode::IncompatibleVersion, std::format("State version {} is from a newer Core. " "Please update/restart to load this state.", dataVersion) )); } else { return std::unexpected(Api::Error( Api::ErrorCode::IncompatibleVersion, std::format("State version {} is too old. " "Maximum supported age is {} versions.", dataVersion, Api::MAX_SUPPORTED_STATE_VERSION_AGE) )); } } // If current version, parse directly if (dataVersion == CURRENT_VERSION) { StateV1 state; auto ec = glz::read_json(state, jsonStr); if (ec) { return std::unexpected(Api::Error( Api::ErrorCode::ParseError, std::format("Failed to parse state: {}", glz::format_error(ec, jsonStr)) )); } return state; } // Otherwise, migrate return StateMigration::migrate(dataVersion, jsonStr); } bool StateSerializer::isVersionSupported(uint32_t version) { if (version > CURRENT_VERSION) { return false; // Future version } uint32_t minVersion = getMinimumSupportedVersion(); return version >= minVersion && version <= CURRENT_VERSION; } uint32_t StateSerializer::getMinimumSupportedVersion() { // Support 10 versions back, but not below 1 return (CURRENT_VERSION > Api::MAX_SUPPORTED_STATE_VERSION_AGE) ? CURRENT_VERSION - Api::MAX_SUPPORTED_STATE_VERSION_AGE : 1; } uint32_t StateSerializer::getCurrentVersion() { return CURRENT_VERSION; } uint32_t StateSerializer::extractVersion(const std::string& jsonStr) { // Quick extraction without full parse // Look for "version": N pattern size_t pos = jsonStr.find("\"version\""); if (pos != std::string::npos) { pos = jsonStr.find(':', pos); if (pos != std::string::npos) { // Skip whitespace pos++; while (pos < jsonStr.size() && std::isspace(jsonStr[pos])) { pos++; } // Parse number if (pos < jsonStr.size() && std::isdigit(jsonStr[pos])) { return static_cast(std::stoul(jsonStr.substr(pos))); } } } // Default to 0 (unknown/legacy) return 0; } } // namespace Echoion::Core ``` **File**: `EchoionCore/src/state/StateMigration.cpp` (NEW) ```cpp #include "echoion/core/state/StateMigration.hpp" #include "echoion/core/Logger.hpp" #include #include namespace Echoion::Core { Api::Result StateMigration::migrate(uint32_t fromVersion, const std::string& jsonData) { ECHOION_LOG_INFO(std::format("Migrating state from version {} to {}", fromVersion, StateSerializer::CURRENT_VERSION)); // Migration chain: fromVersion -> ... -> CURRENT_VERSION // For now, only V0 -> V1 is implemented // Future: V1 -> V2, V2 -> V3, etc. if (fromVersion == 0) { StateV0 v0; auto ec = glz::read_json(v0, jsonData); if (ec) { return std::unexpected(Api::Error( Api::ErrorCode::ParseError, "Failed to parse V0 state" )); } return fromV0(v0); } // Add more migrations here as versions evolve // if (fromVersion == 1) { return fromV1(...); } return std::unexpected(Api::Error( Api::ErrorCode::IncompatibleVersion, std::format("No migration path from version {}", fromVersion) )); } StateV1 StateMigration::fromV0(const StateV0& v0) { StateV1 v1; // Migrate queue for (const auto& trackId : v0.trackIds) { StateV1::QueueEntryState entry; entry.track.id = trackId; entry.track.title = "Unknown"; entry.track.artist = "Unknown"; v1.queue.push_back(std::move(entry)); } // Migrate playback state if (!v1.queue.empty()) { StateV1::PlaybackState playback; playback.currentTrack = v1.queue[0].track; playback.volume = v0.volume; v1.playback = std::move(playback); } v1.version = 1; v1.savedAt = getCurrentTimestampISO8601(); return v1; } bool StateMigration::canMigrate(uint32_t fromVersion) { return fromVersion >= StateSerializer::getMinimumSupportedVersion() && fromVersion < StateSerializer::CURRENT_VERSION; } } // namespace Echoion::Core ``` ### 3. Core.cpp Modifications **File**: `EchoionCore/src/Core.cpp` Add state management implementation: ```cpp // Add includes #include "echoion/core/state/StateSerializer.hpp" #include "echoion/core/state/StateVersions.hpp" // Add to Core class implementation: Api::SerializedState Core::saveState() { ECHOION_LOG_INFO("Saving Core state..."); StateV1 state; // Capture current playback state if (currentTrack_.has_value()) { StateV1::PlaybackState playback; playback.currentTrack = currentTrack_->track; playback.position = currentTrack_->position; playback.isPlaying = isPlaying_; playback.isPaused = isPaused_; playback.volume = volume_; playback.shuffle = shuffle_; playback.repeat = repeat_; state.playback = std::move(playback); } // Capture queue auto queueResult = musicManager_->getQueue(); if (queueResult) { for (const auto& entry : *queueResult) { StateV1::QueueEntryState entryState; entryState.track = entry.track; entryState.queueId = entry.queueId; entryState.addedBy = entry.addedBy; entryState.addedAt = formatTimestamp(entry.addedAt); state.queue.push_back(std::move(entryState)); } } // Capture sessions (from session manager) // ... session capture code ... // Serialize auto blob = StateSerializer::serialize(state); ECHOION_LOG_INFO(std::format("State saved: version={}, size={} bytes", blob.version, blob.size())); return blob; } Api::Result Core::restoreState(const Api::SerializedState& state) { ECHOION_LOG_INFO(std::format("Restoring Core state: version={}", state.version)); auto result = StateSerializer::deserialize(state); if (!result) { return std::unexpected(result.error()); } const StateV1& stateData = *result; // Restore playback if (stateData.playback.has_value()) { // Restore track, position, volume, etc. // ... restoration code ... } // Restore queue for (const auto& entry : stateData.queue) { // Add to music manager queue // ... queue restoration ... } // Restore sessions // ... session restoration ... ECHOION_LOG_INFO("State restored successfully"); return {}; } uint32_t Core::getStateFormatVersion() const { return StateSerializer::CURRENT_VERSION; } bool Core::canRestoreStateVersion(uint32_t version) const { return StateSerializer::isVersionSupported(version); } ``` ### 4. CoreLoader.cpp Modifications **File**: `EchoionPlugin/src/CoreLoader.cpp` Update hot reload to use opaque blobs: ```cpp Api::Result CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) { std::lock_guard lock(mutex_); if (!loaded_) { return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "No core loaded to reload")); } hotReloading_ = true; ECHOION_LOG_INFO("Starting hot reload with decoupled state..."); // Step 1: Save state as opaque blob (Plugin doesn't know contents) Api::SerializedState stateBlob; if (core_) { stateBlob = core_->saveState(); ECHOION_LOG_INFO(std::format("Saved state: version={}, size={} bytes", stateBlob.version, stateBlob.size())); } // Step 2: Unload old Core auto unloadResult = unloadLibraryInternal(); if (!unloadResult) { hotReloading_ = false; return unloadResult; } // Step 3: Load new Core auto targetPath = newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath; if (!std::filesystem::exists(targetPath)) { hotReloading_ = false; return std::unexpected(Api::Error( Api::ErrorCode::NotFound, std::format("New library not found: {}", targetPath.string()))); } // ... (existing temp file copying code) ... auto loadResult = loadLibraryInternal(tempLibraryPath_); if (!loadResult) { hotReloading_ = false; return loadResult; } // Step 4: Restore state (Core handles migration internally) if (!stateBlob.empty()) { auto coreVersion = core_->getStateFormatVersion(); auto stateVersion = stateBlob.version; ECHOION_LOG_INFO(std::format("Restoring state v{} to Core v{}", stateVersion, coreVersion)); if (core_->canRestoreStateVersion(stateVersion)) { auto restoreResult = core_->restoreState(stateBlob); if (!restoreResult) { ECHOION_LOG_ERROR(std::format("Failed to restore state: {}", restoreResult.error().message)); // Check if it's a version issue if (restoreResult.error().code == Api::ErrorCode::IncompatibleVersion) { // Signal user to update/restart ECHOION_LOG_WARNING("State version incompatible. " "User needs to update/restart."); // Optionally: notify through plugin interface } // Continue with empty state - graceful degradation } else { ECHOION_LOG_INFO("State restored successfully"); } } else { ECHOION_LOG_WARNING(std::format( "Cannot restore state v{} in Core v{}. " "Version age exceeds maximum supported ({} versions).", stateVersion, coreVersion, Api::MAX_SUPPORTED_STATE_VERSION_AGE)); // Continue with empty state } } currentLibraryPath_ = targetPath; hotReloading_ = false; ECHOION_LOG_INFO("Hot reload complete"); return {}; } ``` ## Implementation Order 1. **Create Api types** (SerializedState.hpp) 2. **Update ICoreInterface** (add state methods) 3. **Create StateVersions.hpp** (StateV0, StateV1 structures) 4. **Create StateSerializer** (serialize/deserialize) 5. **Create StateMigration** (V0 -> V1 migration) 6. **Update Core.cpp** (implement saveState/restoreState) 7. **Update CoreLoader.cpp** (use opaque blobs) 8. **Test** (save/restore, migration, version limits) ## Testing Checklist - [ ] Save state creates valid JSON blob - [ ] Restore state works for current version - [ ] Migration V0 -> V1 works correctly - [ ] Version 11 versions old is rejected with clear message - [ ] Version from future signals user to update/restart - [ ] Empty state blob handled gracefully - [ ] Corrupted state handled gracefully (don't crash) - [ ] Hot reload preserves state across Core reload - [ ] State survives 100 hot reloads without corruption ## Success Criteria 1. ✅ Plugin never inspects state blob contents 2. ✅ State format can change without Plugin rebuild 3. ✅ 10 versions backward compatibility 4. ✅ Clear signal to user when version > 10 versions old 5. ✅ Clear signal when state is from future version 6. ✅ Graceful degradation on errors 7. ✅ Uses only glaze (no new dependencies) Ready to start implementation?