Files
dstalk/dstalk_core/src/event_bus.hpp
XiuChengWu ba7382db2a feat: add OpenAI-compatible AI provider plugin with SSE streaming support
- Implemented the OpenAI-compatible AI provider plugin, including configuration, chat, and chat_stream functionalities.
- Added support for SSE streaming and tool calls.
- Integrated Boost.JSON for JSON handling.
- Created CMake configuration for the plugin.
- Added error handling and logging throughout the plugin.
2026-05-31 05:37:04 +08:00

51 lines
1.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* @file event_bus.hpp
* @brief Publish-subscribe event bus with shared_mutex for concurrent read access.
* 发布-订阅事件总线,使用 shared_mutex 支持并发读访问。
* Copyright (c) 2026 dstalk contributors. GPLv3.
*/
#pragma once
#include <functional>
#include <mutex>
#include <shared_mutex>
#include <unordered_map>
#include <vector>
namespace dstalk {
using EventHandler = std::function<void(int event_type, const void* data)>;
// 轻量级发布-订阅事件总线 / Lightweight pub-sub event bus.
// 读取者使用 shared_lockemit因此多个处理器可以并发分发
// 写入者使用 unique_locksubscribe / unsubscribe
// Readers use shared_lock (emit) so multiple handlers can be dispatched
// concurrently; writers use unique_lock (subscribe / unsubscribe).
class EventBus {
public:
EventBus() = default;
~EventBus() = default;
// 订阅事件返回订阅ID / Subscribe to an event, returning a subscription id
int subscribe(int event_type, EventHandler handler);
// 取消订阅 / Unsubscribe by subscription id
void unsubscribe(int subscription_id);
// 发布事件 / Emit an event to all matching subscribers
int emit(int event_type, const void* data);
private:
struct Subscription {
int id;
int event_type;
EventHandler handler;
};
mutable std::shared_mutex mutex_; // 读写锁emit 用 sharedsubscribe/unsubscribe 用 unique / RW lock: shared for emit, unique for subscribe/unsubscribe
std::vector<Subscription> subscriptions_; // emit 时线性扫描;对少量订阅者足够 / Linear scan on emit; ok for small subscriber counts
int next_id_ = 1; // 单调递增订阅 ID 计数器 / Monotonic subscription id counter
};
} // namespace dstalk