Files
EchoionApi/include/echoion/api/EventBus.hpp
T
2026-02-01 23:05:41 +03:00

270 lines
6.2 KiB
C++

#pragma once
#include "Types.hpp"
#include "echoion/api/ConfigTypes.hpp"
#include "echoion/api/PluginTypes.hpp"
#include "echoion/api/TrackTypes.hpp"
#include <functional>
#include <typeindex>
#include <unordered_map>
#include <vector>
#include <mutex>
#include <shared_mutex>
#include <queue>
#include <thread>
#include <condition_variable>
#include <atomic>
namespace Echoion::Api {
// Base event interface
struct IEvent {
virtual ~IEvent() = default;
virtual std::type_index getType() const = 0;
std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now();
};
// Typed event wrapper
template<typename T>
struct Event : IEvent {
T data;
explicit Event(T d) : data(std::move(d)) {}
std::type_index getType() const override {
return std::type_index(typeid(T));
}
};
// Event handler type
template<typename T>
using EventHandler = std::function<void(const T&)>;
// Subscription token for unsubscribing
class SubscriptionToken {
public:
using Id = uint64_t;
SubscriptionToken() = default;
explicit SubscriptionToken(Id id, std::type_index type,
std::weak_ptr<std::function<void(const std::shared_ptr<IEvent>&)>> handler)
: id_(id), type_(type), handler_(std::move(handler)) {}
[[nodiscard]] bool isValid() const { return id_ != 0; }
[[nodiscard]] Id getId() const { return id_; }
[[nodiscard]] std::type_index getType() const { return type_; }
private:
Id id_ = 0;
std::type_index type_ = std::type_index(typeid(void));
std::weak_ptr<std::function<void(const std::shared_ptr<IEvent>&)>> handler_;
friend class EventBus;
};
// Event bus for decoupled communication
class EventBus {
public:
EventBus();
~EventBus();
// Delete copy/move
EventBus(const EventBus&) = delete;
EventBus& operator=(const EventBus&) = delete;
EventBus(EventBus&&) = delete;
EventBus& operator=(EventBus&&) = delete;
// Start processing events
void start();
void stop();
// Publish an event (thread-safe)
template<typename T>
void publish(T event) {
auto evt = std::make_shared<Event<T>>(std::move(event));
{
std::lock_guard<std::mutex> lock(queueMutex_);
eventQueue_.push(evt);
}
queueCv_.notify_one();
}
// Subscribe to events (thread-safe)
template<typename T>
[[nodiscard]] SubscriptionToken subscribe(EventHandler<T> handler) {
auto wrappedHandler = std::make_shared<std::function<void(const std::shared_ptr<IEvent>&)>>(
[h = std::move(handler)](const std::shared_ptr<IEvent>& evt) {
if (auto typedEvt = std::dynamic_pointer_cast<Event<T>>(evt)) {
h(typedEvt->data);
}
}
);
std::type_index type(typeid(T));
auto id = nextId_++;
{
std::unique_lock<std::shared_mutex> lock(handlersMutex_);
handlers_[type][id] = wrappedHandler;
}
return SubscriptionToken(id, type, wrappedHandler);
}
// Unsubscribe from events
void unsubscribe(const SubscriptionToken& token);
// Process a single event immediately (for synchronous processing)
void processOne();
// Wait for and process one event (blocking)
bool waitAndProcessOne(std::chrono::milliseconds timeout);
// Clear all pending events
void clearQueue();
// Get number of pending events
[[nodiscard]] size_t getPendingEventCount() const;
private:
void processEvents();
mutable std::shared_mutex handlersMutex_;
std::unordered_map<std::type_index, std::unordered_map<SubscriptionToken::Id,
std::shared_ptr<std::function<void(const std::shared_ptr<IEvent>&)>>>> handlers_;
mutable std::mutex queueMutex_;
std::queue<std::shared_ptr<IEvent>> eventQueue_;
std::condition_variable queueCv_;
std::atomic<bool> running_{false};
std::atomic<bool> stopRequested_{false};
std::jthread eventThread_;
std::atomic<SubscriptionToken::Id> nextId_{1};
};
// Global event bus singleton
class GlobalEventBus {
public:
[[nodiscard]] static EventBus& instance();
private:
GlobalEventBus() = default;
};
// Common event types for Echoion
namespace Events {
// Playback events
struct PlaybackStarted {
TrackInfo track;
uint64_t clientId;
};
struct PlaybackPaused {
std::chrono::milliseconds position;
};
struct PlaybackResumed {
std::chrono::milliseconds position;
};
struct PlaybackStopped {};
struct TrackFinished {
TrackInfo track;
bool autoSkipped;
};
struct VolumeChanged {
float oldVolume;
float newVolume;
uint64_t changedByClientId;
};
// Queue events
struct TrackQueued {
TrackInfo track;
uint64_t queueId;
uint64_t addedByClientId;
uint32_t position;
};
struct TrackRemoved {
uint64_t queueId;
uint64_t removedByClientId;
};
struct QueueCleared {
uint64_t clearedByClientId;
};
struct QueueShuffled {
uint64_t triggeredByClientId;
};
// Connection events
struct ClientConnected {
ClientInfo client;
};
struct ClientDisconnected {
uint64_t clientId;
std::string reason;
};
struct ChannelChanged {
uint64_t clientId;
uint64_t oldChannelId;
uint64_t newChannelId;
};
// Error events
struct PlaybackError {
ErrorCode code;
std::string message;
std::optional<TrackInfo> track;
};
struct NetworkError {
std::string url;
ErrorCode code;
std::string message;
};
// Configuration events
struct ConfigReloaded {
BotConfig newConfig;
};
struct ConfigChanged {
std::string key;
std::string oldValue;
std::string newValue;
};
// Cache events
struct CacheHit {
std::string key;
std::string type;
};
struct CacheMiss {
std::string key;
std::string type;
};
struct CacheEvicted {
std::string key;
std::string reason;
};
} // namespace Events
// Helper macros for event publishing/subscribing
#define ECHOION_PUBLISH(event) Echoion::Api::GlobalEventBus::instance().publish(event)
#define ECHOION_SUBSCRIBE(type, handler) Echoion::Api::GlobalEventBus::instance().subscribe<type>(handler)
} // namespace Echoion::Api