Merge branch 'feature/decoupled-state' into 'main'
Migrate Echoion to VoidLibrary: toolchain + core infrastructure See merge request void/echoion!4
This commit is contained in:
commit
1e4a3218b0
23 files changed
+4124
-24
No files matched your search
@@ -0,0 +1,86 @@
|
||||
---
|
||||
name: cpp-pro
|
||||
description: Use when building C++ applications requiring modern C++20/23 features, template metaprogramming, or high-performance systems. Invoke for concepts, ranges, coroutines, SIMD optimization, memory management.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: https://github.com/Jeffallan
|
||||
version: "1.0.0"
|
||||
domain: language
|
||||
triggers: C++, C++20, C++23, modern C++, template metaprogramming, systems programming, performance optimization, SIMD, memory management, CMake
|
||||
role: specialist
|
||||
scope: implementation
|
||||
output-format: code
|
||||
related-skills: rust-engineer, embedded-systems
|
||||
---
|
||||
|
||||
# C++ Pro
|
||||
|
||||
Senior C++ developer with deep expertise in modern C++20/23, systems programming, high-performance computing, and zero-overhead abstractions.
|
||||
|
||||
## Role Definition
|
||||
|
||||
You are a senior C++ engineer with 15+ years of systems programming experience. You specialize in modern C++20/23, template metaprogramming, performance optimization, and building production-grade systems with emphasis on safety, efficiency, and maintainability. You follow C++ Core Guidelines and leverage cutting-edge language features.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Building high-performance C++ applications
|
||||
- Implementing template metaprogramming solutions
|
||||
- Optimizing memory-critical systems
|
||||
- Developing concurrent and parallel algorithms
|
||||
- Creating custom allocators and memory pools
|
||||
- Systems programming and embedded development
|
||||
|
||||
## Core Workflow
|
||||
|
||||
1. **Analyze architecture** - Review build system, compiler flags, performance requirements
|
||||
2. **Design with concepts** - Create type-safe interfaces using C++20 concepts
|
||||
3. **Implement zero-cost** - Apply RAII, constexpr, and zero-overhead abstractions
|
||||
4. **Verify quality** - Run sanitizers, static analysis, and performance benchmarks
|
||||
5. **Optimize** - Profile, measure, and apply targeted optimizations
|
||||
|
||||
## Reference Guide
|
||||
|
||||
Load detailed guidance based on context:
|
||||
|
||||
| Topic | Reference | Load When |
|
||||
|-------|-----------|-----------|
|
||||
| Modern C++ Features | `references/modern-cpp.md` | C++20/23 features, concepts, ranges, coroutines |
|
||||
| Template Metaprogramming | `references/templates.md` | Variadic templates, SFINAE, type traits, CRTP |
|
||||
| Memory & Performance | `references/memory-performance.md` | Allocators, SIMD, cache optimization, move semantics |
|
||||
| Concurrency | `references/concurrency.md` | Atomics, lock-free structures, thread pools, coroutines |
|
||||
| Build & Tooling | `references/build-tooling.md` | CMake, sanitizers, static analysis, testing |
|
||||
|
||||
## Constraints
|
||||
|
||||
### MUST DO
|
||||
- Follow C++ Core Guidelines
|
||||
- Use concepts for template constraints
|
||||
- Apply RAII universally
|
||||
- Use `auto` with type deduction
|
||||
- Prefer `std::unique_ptr` and `std::shared_ptr`
|
||||
- Enable all compiler warnings (-Wall -Wextra -Wpedantic)
|
||||
- Run AddressSanitizer and UndefinedBehaviorSanitizer
|
||||
- Write const-correct code
|
||||
|
||||
### MUST NOT DO
|
||||
- Use raw `new`/`delete` (prefer smart pointers)
|
||||
- Ignore compiler warnings
|
||||
- Use C-style casts (use static_cast, etc.)
|
||||
- Mix exception and error code patterns inconsistently
|
||||
- Write non-const-correct code
|
||||
- Use `using namespace std` in headers
|
||||
- Ignore undefined behavior
|
||||
- Skip move semantics for expensive types
|
||||
|
||||
## Output Templates
|
||||
|
||||
When implementing C++ features, provide:
|
||||
1. Header file with interfaces and templates
|
||||
2. Implementation file (when needed)
|
||||
3. CMakeLists.txt updates (if applicable)
|
||||
4. Test file demonstrating usage
|
||||
5. Brief explanation of design decisions and performance characteristics
|
||||
|
||||
## Knowledge Reference
|
||||
|
||||
C++20/23, concepts, ranges, coroutines, modules, template metaprogramming, SFINAE, type traits, CRTP, smart pointers, custom allocators, move semantics, RAII, SIMD, atomics, lock-free programming, CMake, Conan, sanitizers, clang-tidy, cppcheck, Catch2, GoogleTest
|
||||
@@ -0,0 +1,437 @@
|
||||
# Concurrency and Parallel Programming
|
||||
|
||||
## Atomics and Memory Ordering
|
||||
|
||||
```cpp
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
|
||||
// Basic atomics
|
||||
std::atomic<int> counter{0};
|
||||
std::atomic<bool> flag{false};
|
||||
|
||||
// Memory ordering
|
||||
void producer(std::atomic<int>& data, std::atomic<bool>& ready) {
|
||||
data.store(42, std::memory_order_relaxed);
|
||||
ready.store(true, std::memory_order_release); // Release barrier
|
||||
}
|
||||
|
||||
void consumer(std::atomic<int>& data, std::atomic<bool>& ready) {
|
||||
while (!ready.load(std::memory_order_acquire)) { // Acquire barrier
|
||||
std::this_thread::yield();
|
||||
}
|
||||
int value = data.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// Compare-and-swap
|
||||
bool try_acquire_lock(std::atomic<bool>& lock) {
|
||||
bool expected = false;
|
||||
return lock.compare_exchange_strong(expected, true,
|
||||
std::memory_order_acquire,
|
||||
std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// Fetch-and-add
|
||||
int increment_counter(std::atomic<int>& counter) {
|
||||
return counter.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
```
|
||||
|
||||
## Lock-Free Data Structures
|
||||
|
||||
```cpp
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
|
||||
// Lock-free stack
|
||||
template<typename T>
|
||||
class LockFreeStack {
|
||||
struct Node {
|
||||
T data;
|
||||
Node* next;
|
||||
Node(const T& value) : data(value), next(nullptr) {}
|
||||
};
|
||||
|
||||
std::atomic<Node*> head_{nullptr};
|
||||
|
||||
public:
|
||||
void push(const T& value) {
|
||||
Node* new_node = new Node(value);
|
||||
new_node->next = head_.load(std::memory_order_relaxed);
|
||||
|
||||
while (!head_.compare_exchange_weak(new_node->next, new_node,
|
||||
std::memory_order_release,
|
||||
std::memory_order_relaxed)) {
|
||||
// Retry with updated head
|
||||
}
|
||||
}
|
||||
|
||||
bool pop(T& result) {
|
||||
Node* old_head = head_.load(std::memory_order_relaxed);
|
||||
|
||||
while (old_head &&
|
||||
!head_.compare_exchange_weak(old_head, old_head->next,
|
||||
std::memory_order_acquire,
|
||||
std::memory_order_relaxed)) {
|
||||
// Retry
|
||||
}
|
||||
|
||||
if (old_head) {
|
||||
result = old_head->data;
|
||||
delete old_head; // Note: ABA problem exists
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Lock-free queue (single producer, single consumer)
|
||||
template<typename T, size_t Size>
|
||||
class SPSCQueue {
|
||||
std::array<T, Size> buffer_;
|
||||
alignas(64) std::atomic<size_t> head_{0};
|
||||
alignas(64) std::atomic<size_t> tail_{0};
|
||||
|
||||
public:
|
||||
bool push(const T& item) {
|
||||
size_t head = head_.load(std::memory_order_relaxed);
|
||||
size_t next_head = (head + 1) % Size;
|
||||
|
||||
if (next_head == tail_.load(std::memory_order_acquire)) {
|
||||
return false; // Queue full
|
||||
}
|
||||
|
||||
buffer_[head] = item;
|
||||
head_.store(next_head, std::memory_order_release);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool pop(T& item) {
|
||||
size_t tail = tail_.load(std::memory_order_relaxed);
|
||||
|
||||
if (tail == head_.load(std::memory_order_acquire)) {
|
||||
return false; // Queue empty
|
||||
}
|
||||
|
||||
item = buffer_[tail];
|
||||
tail_.store((tail + 1) % Size, std::memory_order_release);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Thread Pool
|
||||
|
||||
```cpp
|
||||
#include <thread>
|
||||
#include <queue>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
|
||||
class ThreadPool {
|
||||
std::vector<std::thread> workers_;
|
||||
std::queue<std::function<void()>> tasks_;
|
||||
std::mutex queue_mutex_;
|
||||
std::condition_variable condition_;
|
||||
bool stop_ = false;
|
||||
|
||||
public:
|
||||
ThreadPool(size_t num_threads) {
|
||||
for (size_t i = 0; i < num_threads; ++i) {
|
||||
workers_.emplace_back([this] {
|
||||
while (true) {
|
||||
std::function<void()> task;
|
||||
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
condition_.wait(lock, [this] {
|
||||
return stop_ || !tasks_.empty();
|
||||
});
|
||||
|
||||
if (stop_ && tasks_.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
task = std::move(tasks_.front());
|
||||
tasks_.pop();
|
||||
}
|
||||
|
||||
task();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
~ThreadPool() {
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
stop_ = true;
|
||||
}
|
||||
condition_.notify_all();
|
||||
for (auto& worker : workers_) {
|
||||
worker.join();
|
||||
}
|
||||
}
|
||||
|
||||
template<typename F, typename... Args>
|
||||
auto enqueue(F&& f, Args&&... args)
|
||||
-> std::future<typename std::invoke_result_t<F, Args...>> {
|
||||
|
||||
using return_type = typename std::invoke_result_t<F, Args...>;
|
||||
|
||||
auto task = std::make_shared<std::packaged_task<return_type()>>(
|
||||
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
|
||||
);
|
||||
|
||||
std::future<return_type> result = task->get_future();
|
||||
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queue_mutex_);
|
||||
if (stop_) {
|
||||
throw std::runtime_error("enqueue on stopped ThreadPool");
|
||||
}
|
||||
tasks_.emplace([task]() { (*task)(); });
|
||||
}
|
||||
|
||||
condition_.notify_one();
|
||||
return result;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Parallel STL Algorithms
|
||||
|
||||
```cpp
|
||||
#include <algorithm>
|
||||
#include <execution>
|
||||
#include <vector>
|
||||
#include <numeric>
|
||||
|
||||
void parallel_algorithms_demo() {
|
||||
std::vector<int> vec(1'000'000);
|
||||
std::iota(vec.begin(), vec.end(), 0);
|
||||
|
||||
// Parallel sort
|
||||
std::sort(std::execution::par, vec.begin(), vec.end());
|
||||
|
||||
// Parallel for_each
|
||||
std::for_each(std::execution::par_unseq, vec.begin(), vec.end(),
|
||||
[](int& x) { x *= 2; });
|
||||
|
||||
// Parallel transform
|
||||
std::vector<int> result(vec.size());
|
||||
std::transform(std::execution::par, vec.begin(), vec.end(),
|
||||
result.begin(), [](int x) { return x * x; });
|
||||
|
||||
// Parallel reduce
|
||||
int sum = std::reduce(std::execution::par, vec.begin(), vec.end());
|
||||
|
||||
// Parallel transform_reduce (map-reduce)
|
||||
int sum_of_squares = std::transform_reduce(
|
||||
std::execution::par,
|
||||
vec.begin(), vec.end(),
|
||||
0,
|
||||
std::plus<>(),
|
||||
[](int x) { return x * x; }
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Synchronization Primitives
|
||||
|
||||
```cpp
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <condition_variable>
|
||||
|
||||
// Mutex types
|
||||
std::mutex mtx;
|
||||
std::recursive_mutex rec_mtx;
|
||||
std::timed_mutex timed_mtx;
|
||||
std::shared_mutex shared_mtx;
|
||||
|
||||
// RAII locks
|
||||
void exclusive_access() {
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
// Critical section
|
||||
}
|
||||
|
||||
void unique_lock_example() {
|
||||
std::unique_lock<std::mutex> lock(mtx);
|
||||
// Can unlock and relock
|
||||
lock.unlock();
|
||||
// Do some work
|
||||
lock.lock();
|
||||
}
|
||||
|
||||
// Reader-writer lock
|
||||
class SharedData {
|
||||
mutable std::shared_mutex mutex_;
|
||||
std::string data_;
|
||||
|
||||
public:
|
||||
std::string read() const {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
return data_;
|
||||
}
|
||||
|
||||
void write(std::string new_data) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
data_ = std::move(new_data);
|
||||
}
|
||||
};
|
||||
|
||||
// Condition variable
|
||||
class Queue {
|
||||
std::queue<int> queue_;
|
||||
std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
|
||||
public:
|
||||
void push(int value) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
queue_.push(value);
|
||||
}
|
||||
cv_.notify_one();
|
||||
}
|
||||
|
||||
int pop() {
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
cv_.wait(lock, [this] { return !queue_.empty(); });
|
||||
int value = queue_.front();
|
||||
queue_.pop();
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
// std::scoped_lock - multiple mutexes
|
||||
std::mutex mtx1, mtx2;
|
||||
|
||||
void transfer(Account& from, Account& to, int amount) {
|
||||
std::scoped_lock lock(from.mutex, to.mutex); // Deadlock-free
|
||||
from.balance -= amount;
|
||||
to.balance += amount;
|
||||
}
|
||||
```
|
||||
|
||||
## Async and Futures
|
||||
|
||||
```cpp
|
||||
#include <future>
|
||||
|
||||
// std::async
|
||||
auto future = std::async(std::launch::async, []() {
|
||||
return expensive_computation();
|
||||
});
|
||||
|
||||
// Get result (blocks until ready)
|
||||
auto result = future.get();
|
||||
|
||||
// Promise and future
|
||||
void producer(std::promise<int> promise) {
|
||||
int value = compute_value();
|
||||
promise.set_value(value);
|
||||
}
|
||||
|
||||
void consumer(std::future<int> future) {
|
||||
int value = future.get();
|
||||
}
|
||||
|
||||
std::promise<int> promise;
|
||||
std::future<int> future = promise.get_future();
|
||||
|
||||
std::thread producer_thread(producer, std::move(promise));
|
||||
std::thread consumer_thread(consumer, std::move(future));
|
||||
|
||||
// Packaged task
|
||||
std::packaged_task<int(int, int)> task([](int a, int b) {
|
||||
return a + b;
|
||||
});
|
||||
|
||||
std::future<int> task_future = task.get_future();
|
||||
std::thread task_thread(std::move(task), 5, 3);
|
||||
|
||||
int sum = task_future.get(); // 8
|
||||
task_thread.join();
|
||||
```
|
||||
|
||||
## Coroutine-Based Concurrency
|
||||
|
||||
```cpp
|
||||
#include <coroutine>
|
||||
#include <optional>
|
||||
|
||||
// Async task coroutine
|
||||
template<typename T>
|
||||
struct AsyncTask {
|
||||
struct promise_type {
|
||||
std::optional<T> value;
|
||||
std::exception_ptr exception;
|
||||
|
||||
AsyncTask get_return_object() {
|
||||
return AsyncTask{
|
||||
std::coroutine_handle<promise_type>::from_promise(*this)
|
||||
};
|
||||
}
|
||||
|
||||
std::suspend_never initial_suspend() { return {}; }
|
||||
std::suspend_always final_suspend() noexcept { return {}; }
|
||||
|
||||
void return_value(T v) {
|
||||
value = std::move(v);
|
||||
}
|
||||
|
||||
void unhandled_exception() {
|
||||
exception = std::current_exception();
|
||||
}
|
||||
};
|
||||
|
||||
std::coroutine_handle<promise_type> handle;
|
||||
|
||||
AsyncTask(std::coroutine_handle<promise_type> h) : handle(h) {}
|
||||
~AsyncTask() { if (handle) handle.destroy(); }
|
||||
|
||||
T get() {
|
||||
if (!handle.done()) {
|
||||
handle.resume();
|
||||
}
|
||||
|
||||
if (handle.promise().exception) {
|
||||
std::rethrow_exception(handle.promise().exception);
|
||||
}
|
||||
|
||||
return *handle.promise().value;
|
||||
}
|
||||
};
|
||||
|
||||
// Usage
|
||||
AsyncTask<int> async_compute() {
|
||||
co_return 42;
|
||||
}
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Primitive | Use Case | Performance |
|
||||
|-----------|----------|-------------|
|
||||
| std::atomic | Simple shared state | Lock-free |
|
||||
| std::mutex | Exclusive access | Kernel call |
|
||||
| std::shared_mutex | Read-heavy workload | Better than mutex |
|
||||
| Lock-free structures | High contention | Best throughput |
|
||||
| Thread pool | Task parallelism | Avoid thread overhead |
|
||||
| Parallel STL | Data parallelism | Automatic scaling |
|
||||
| std::async | Simple async tasks | Thread pool |
|
||||
| Coroutines | Async I/O | Minimal overhead |
|
||||
|
||||
## Memory Ordering Guide
|
||||
|
||||
| Ordering | Guarantees | Use Case |
|
||||
|----------|-----------|----------|
|
||||
| relaxed | No synchronization | Counters |
|
||||
| acquire | Load barrier | Consumer |
|
||||
| release | Store barrier | Producer |
|
||||
| acq_rel | Both | RMW operations |
|
||||
| seq_cst | Total order | Default |
|
||||
@@ -0,0 +1,397 @@
|
||||
# Memory Management & Performance
|
||||
|
||||
## Smart Pointers
|
||||
|
||||
```cpp
|
||||
#include <memory>
|
||||
|
||||
// unique_ptr - exclusive ownership
|
||||
auto create_resource() {
|
||||
return std::make_unique<Resource>("data");
|
||||
}
|
||||
|
||||
// shared_ptr - reference counting
|
||||
std::shared_ptr<Data> shared = std::make_shared<Data>(42);
|
||||
std::weak_ptr<Data> weak = shared; // Non-owning reference
|
||||
|
||||
// Custom deleters
|
||||
auto file_deleter = [](FILE* fp) { if (fp) fclose(fp); };
|
||||
std::unique_ptr<FILE, decltype(file_deleter)> file(
|
||||
fopen("data.txt", "r"),
|
||||
file_deleter
|
||||
);
|
||||
|
||||
// enable_shared_from_this
|
||||
class Node : public std::enable_shared_from_this<Node> {
|
||||
public:
|
||||
std::shared_ptr<Node> get_shared() {
|
||||
return shared_from_this();
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Custom Allocators
|
||||
|
||||
```cpp
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
// Pool allocator for fixed-size objects
|
||||
template<typename T, size_t PoolSize = 1024>
|
||||
class PoolAllocator {
|
||||
struct Block {
|
||||
alignas(T) std::byte data[sizeof(T)];
|
||||
Block* next;
|
||||
};
|
||||
|
||||
Block pool_[PoolSize];
|
||||
Block* free_list_ = nullptr;
|
||||
|
||||
public:
|
||||
using value_type = T;
|
||||
|
||||
PoolAllocator() {
|
||||
// Initialize free list
|
||||
for (size_t i = 0; i < PoolSize - 1; ++i) {
|
||||
pool_[i].next = &pool_[i + 1];
|
||||
}
|
||||
pool_[PoolSize - 1].next = nullptr;
|
||||
free_list_ = &pool_[0];
|
||||
}
|
||||
|
||||
T* allocate(size_t n) {
|
||||
if (n != 1 || !free_list_) {
|
||||
throw std::bad_alloc();
|
||||
}
|
||||
Block* block = free_list_;
|
||||
free_list_ = free_list_->next;
|
||||
return reinterpret_cast<T*>(block->data);
|
||||
}
|
||||
|
||||
void deallocate(T* p, size_t n) {
|
||||
if (n != 1) return;
|
||||
Block* block = reinterpret_cast<Block*>(p);
|
||||
block->next = free_list_;
|
||||
free_list_ = block;
|
||||
}
|
||||
};
|
||||
|
||||
// Usage
|
||||
std::vector<int, PoolAllocator<int>> vec;
|
||||
|
||||
// Arena allocator - bump allocator
|
||||
class Arena {
|
||||
std::byte* buffer_;
|
||||
size_t size_;
|
||||
size_t offset_ = 0;
|
||||
|
||||
public:
|
||||
Arena(size_t size) : size_(size) {
|
||||
buffer_ = new std::byte[size];
|
||||
}
|
||||
|
||||
~Arena() {
|
||||
delete[] buffer_;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
T* allocate(size_t n = 1) {
|
||||
size_t alignment = alignof(T);
|
||||
size_t space = size_ - offset_;
|
||||
void* ptr = buffer_ + offset_;
|
||||
|
||||
if (std::align(alignment, sizeof(T) * n, ptr, space)) {
|
||||
offset_ = size_ - space + sizeof(T) * n;
|
||||
return static_cast<T*>(ptr);
|
||||
}
|
||||
|
||||
throw std::bad_alloc();
|
||||
}
|
||||
|
||||
void reset() {
|
||||
offset_ = 0;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Move Semantics
|
||||
|
||||
```cpp
|
||||
#include <utility>
|
||||
#include <algorithm>
|
||||
|
||||
class Buffer {
|
||||
size_t size_;
|
||||
char* data_;
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
Buffer(size_t size) : size_(size), data_(new char[size]) {}
|
||||
|
||||
// Destructor
|
||||
~Buffer() { delete[] data_; }
|
||||
|
||||
// Copy constructor
|
||||
Buffer(const Buffer& other) : size_(other.size_), data_(new char[size_]) {
|
||||
std::copy(other.data_, other.data_ + size_, data_);
|
||||
}
|
||||
|
||||
// Copy assignment
|
||||
Buffer& operator=(const Buffer& other) {
|
||||
if (this != &other) {
|
||||
delete[] data_;
|
||||
size_ = other.size_;
|
||||
data_ = new char[size_];
|
||||
std::copy(other.data_, other.data_ + size_, data_);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Move constructor
|
||||
Buffer(Buffer&& other) noexcept
|
||||
: size_(other.size_), data_(other.data_) {
|
||||
other.size_ = 0;
|
||||
other.data_ = nullptr;
|
||||
}
|
||||
|
||||
// Move assignment
|
||||
Buffer& operator=(Buffer&& other) noexcept {
|
||||
if (this != &other) {
|
||||
delete[] data_;
|
||||
size_ = other.size_;
|
||||
data_ = other.data_;
|
||||
other.size_ = 0;
|
||||
other.data_ = nullptr;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
};
|
||||
|
||||
// Perfect forwarding
|
||||
template<typename T>
|
||||
void wrapper(T&& arg) {
|
||||
process(std::forward<T>(arg)); // Preserves lvalue/rvalue
|
||||
}
|
||||
```
|
||||
|
||||
## SIMD Optimization
|
||||
|
||||
```cpp
|
||||
#include <immintrin.h> // AVX/AVX2
|
||||
#include <cstring>
|
||||
|
||||
// Vectorized sum using AVX2
|
||||
float simd_sum(const float* data, size_t size) {
|
||||
__m256 sum_vec = _mm256_setzero_ps();
|
||||
|
||||
size_t i = 0;
|
||||
// Process 8 floats at a time
|
||||
for (; i + 8 <= size; i += 8) {
|
||||
__m256 vec = _mm256_loadu_ps(&data[i]);
|
||||
sum_vec = _mm256_add_ps(sum_vec, vec);
|
||||
}
|
||||
|
||||
// Horizontal sum
|
||||
alignas(32) float temp[8];
|
||||
_mm256_store_ps(temp, sum_vec);
|
||||
float result = 0.0f;
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
result += temp[j];
|
||||
}
|
||||
|
||||
// Handle remaining elements
|
||||
for (; i < size; ++i) {
|
||||
result += data[i];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Vectorized multiply-add
|
||||
void fma_operation(float* result, const float* a, const float* b,
|
||||
const float* c, size_t size) {
|
||||
for (size_t i = 0; i + 8 <= size; i += 8) {
|
||||
__m256 va = _mm256_loadu_ps(&a[i]);
|
||||
__m256 vb = _mm256_loadu_ps(&b[i]);
|
||||
__m256 vc = _mm256_loadu_ps(&c[i]);
|
||||
|
||||
// result[i] = a[i] * b[i] + c[i]
|
||||
__m256 vr = _mm256_fmadd_ps(va, vb, vc);
|
||||
_mm256_storeu_ps(&result[i], vr);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Cache-Friendly Design
|
||||
|
||||
```cpp
|
||||
// Structure of Arrays (SoA) - better cache locality
|
||||
struct ParticlesAoS {
|
||||
struct Particle {
|
||||
float x, y, z;
|
||||
float vx, vy, vz;
|
||||
};
|
||||
std::vector<Particle> particles;
|
||||
};
|
||||
|
||||
struct ParticlesSoA {
|
||||
std::vector<float> x, y, z;
|
||||
std::vector<float> vx, vy, vz;
|
||||
|
||||
void update_positions(float dt) {
|
||||
// All x coordinates are contiguous - better cache usage
|
||||
for (size_t i = 0; i < x.size(); ++i) {
|
||||
x[i] += vx[i] * dt;
|
||||
y[i] += vy[i] * dt;
|
||||
z[i] += vz[i] * dt;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Cache line padding to avoid false sharing
|
||||
struct alignas(64) CacheLinePadded {
|
||||
std::atomic<int> counter;
|
||||
char padding[64 - sizeof(std::atomic<int>)];
|
||||
};
|
||||
|
||||
// Prefetching
|
||||
void process_with_prefetch(const int* data, size_t size) {
|
||||
for (size_t i = 0; i < size; ++i) {
|
||||
// Prefetch data for next iteration
|
||||
if (i + 8 < size) {
|
||||
__builtin_prefetch(&data[i + 8], 0, 1);
|
||||
}
|
||||
// Process current data
|
||||
process(data[i]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Memory Pool
|
||||
|
||||
```cpp
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
template<typename T, size_t ChunkSize = 256>
|
||||
class MemoryPool {
|
||||
struct Chunk {
|
||||
alignas(T) std::byte data[sizeof(T) * ChunkSize];
|
||||
};
|
||||
|
||||
std::vector<std::unique_ptr<Chunk>> chunks_;
|
||||
std::vector<T*> free_list_;
|
||||
size_t current_chunk_offset_ = ChunkSize;
|
||||
|
||||
public:
|
||||
T* allocate() {
|
||||
if (!free_list_.empty()) {
|
||||
T* ptr = free_list_.back();
|
||||
free_list_.pop_back();
|
||||
return ptr;
|
||||
}
|
||||
|
||||
if (current_chunk_offset_ >= ChunkSize) {
|
||||
chunks_.push_back(std::make_unique<Chunk>());
|
||||
current_chunk_offset_ = 0;
|
||||
}
|
||||
|
||||
Chunk* chunk = chunks_.back().get();
|
||||
T* ptr = reinterpret_cast<T*>(
|
||||
&chunk->data[sizeof(T) * current_chunk_offset_++]
|
||||
);
|
||||
return ptr;
|
||||
}
|
||||
|
||||
void deallocate(T* ptr) {
|
||||
free_list_.push_back(ptr);
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
T* construct(Args&&... args) {
|
||||
T* ptr = allocate();
|
||||
new (ptr) T(std::forward<Args>(args)...);
|
||||
return ptr;
|
||||
}
|
||||
|
||||
void destroy(T* ptr) {
|
||||
ptr->~T();
|
||||
deallocate(ptr);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Copy Elision and RVO
|
||||
|
||||
```cpp
|
||||
// Return Value Optimization (RVO)
|
||||
std::vector<int> create_vector() {
|
||||
std::vector<int> vec{1, 2, 3, 4, 5};
|
||||
return vec; // RVO applies, no copy/move
|
||||
}
|
||||
|
||||
// Named Return Value Optimization (NRVO)
|
||||
std::string build_string(bool condition) {
|
||||
std::string result;
|
||||
if (condition) {
|
||||
result = "condition true";
|
||||
} else {
|
||||
result = "condition false";
|
||||
}
|
||||
return result; // NRVO may apply
|
||||
}
|
||||
|
||||
// Guaranteed copy elision (C++17)
|
||||
struct NonMovable {
|
||||
NonMovable() = default;
|
||||
NonMovable(const NonMovable&) = delete;
|
||||
NonMovable(NonMovable&&) = delete;
|
||||
};
|
||||
|
||||
NonMovable create() {
|
||||
return NonMovable{}; // Guaranteed no copy/move in C++17
|
||||
}
|
||||
|
||||
auto obj = create(); // OK in C++17
|
||||
```
|
||||
|
||||
## Alignment and Memory Layout
|
||||
|
||||
```cpp
|
||||
#include <cstddef>
|
||||
|
||||
// Control alignment
|
||||
struct alignas(64) CacheAligned {
|
||||
int data[16];
|
||||
};
|
||||
|
||||
// Check alignment
|
||||
static_assert(alignof(CacheAligned) == 64);
|
||||
|
||||
// Aligned allocation
|
||||
void* aligned_alloc_wrapper(size_t alignment, size_t size) {
|
||||
void* ptr = nullptr;
|
||||
if (posix_memalign(&ptr, alignment, size) != 0) {
|
||||
throw std::bad_alloc();
|
||||
}
|
||||
return ptr;
|
||||
}
|
||||
|
||||
// Placement new with alignment
|
||||
alignas(32) std::byte buffer[sizeof(Data)];
|
||||
Data* obj = new (buffer) Data();
|
||||
obj->~Data(); // Manual destruction needed
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Technique | Use Case | Benefit |
|
||||
|-----------|----------|---------|
|
||||
| Smart Pointers | Ownership management | Memory safety |
|
||||
| Move Semantics | Avoid copies | Performance |
|
||||
| Custom Allocators | Specialized allocation | Speed + control |
|
||||
| SIMD | Parallel computation | 4-8x speedup |
|
||||
| SoA Layout | Sequential access | Cache efficiency |
|
||||
| Memory Pools | Frequent alloc/dealloc | Reduced fragmentation |
|
||||
| Alignment | SIMD/cache optimization | Performance |
|
||||
| RVO/NRVO | Return objects | Zero-copy |
|
||||
@@ -0,0 +1,304 @@
|
||||
# Modern C++20/23 Features
|
||||
|
||||
## Concepts and Constraints
|
||||
|
||||
```cpp
|
||||
#include <concepts>
|
||||
|
||||
// Define custom concepts
|
||||
template<typename T>
|
||||
concept Numeric = std::integral<T> || std::floating_point<T>;
|
||||
|
||||
template<typename T>
|
||||
concept Hashable = requires(T a) {
|
||||
{ std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
concept Container = requires(T c) {
|
||||
typename T::value_type;
|
||||
typename T::iterator;
|
||||
{ c.begin() } -> std::same_as<typename T::iterator>;
|
||||
{ c.end() } -> std::same_as<typename T::iterator>;
|
||||
{ c.size() } -> std::convertible_to<std::size_t>;
|
||||
};
|
||||
|
||||
// Use concepts for function constraints
|
||||
template<Numeric T>
|
||||
T add(T a, T b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Concept-based overloading
|
||||
template<std::integral T>
|
||||
void process(T value) {
|
||||
std::cout << "Processing integer: " << value << '\n';
|
||||
}
|
||||
|
||||
template<std::floating_point T>
|
||||
void process(T value) {
|
||||
std::cout << "Processing float: " << value << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
## Ranges and Views
|
||||
|
||||
```cpp
|
||||
#include <ranges>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
// Ranges-based algorithms
|
||||
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
|
||||
|
||||
// Filter, transform, take - all lazy evaluation
|
||||
auto result = numbers
|
||||
| std::views::filter([](int n) { return n % 2 == 0; })
|
||||
| std::views::transform([](int n) { return n * n; })
|
||||
| std::views::take(3);
|
||||
|
||||
// Copy to vector only when needed
|
||||
std::vector<int> materialized(result.begin(), result.end());
|
||||
|
||||
// Custom range adaptor
|
||||
auto is_even = [](int n) { return n % 2 == 0; };
|
||||
auto square = [](int n) { return n * n; };
|
||||
|
||||
auto pipeline = std::views::filter(is_even)
|
||||
| std::views::transform(square);
|
||||
|
||||
auto processed = numbers | pipeline;
|
||||
```
|
||||
|
||||
## Coroutines
|
||||
|
||||
```cpp
|
||||
#include <coroutine>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
// Generator coroutine
|
||||
template<typename T>
|
||||
struct Generator {
|
||||
struct promise_type {
|
||||
T current_value;
|
||||
|
||||
auto get_return_object() {
|
||||
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
|
||||
}
|
||||
|
||||
std::suspend_always initial_suspend() { return {}; }
|
||||
std::suspend_always final_suspend() noexcept { return {}; }
|
||||
|
||||
std::suspend_always yield_value(T value) {
|
||||
current_value = value;
|
||||
return {};
|
||||
}
|
||||
|
||||
void return_void() {}
|
||||
void unhandled_exception() { std::terminate(); }
|
||||
};
|
||||
|
||||
std::coroutine_handle<promise_type> handle;
|
||||
|
||||
Generator(std::coroutine_handle<promise_type> h) : handle(h) {}
|
||||
~Generator() { if (handle) handle.destroy(); }
|
||||
|
||||
bool move_next() {
|
||||
handle.resume();
|
||||
return !handle.done();
|
||||
}
|
||||
|
||||
T current_value() {
|
||||
return handle.promise().current_value;
|
||||
}
|
||||
};
|
||||
|
||||
// Usage
|
||||
Generator<int> fibonacci() {
|
||||
int a = 0, b = 1;
|
||||
while (true) {
|
||||
co_yield a;
|
||||
auto next = a + b;
|
||||
a = b;
|
||||
b = next;
|
||||
}
|
||||
}
|
||||
|
||||
// Async coroutine
|
||||
#include <future>
|
||||
|
||||
struct Task {
|
||||
struct promise_type {
|
||||
Task get_return_object() {
|
||||
return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
|
||||
}
|
||||
std::suspend_never initial_suspend() { return {}; }
|
||||
std::suspend_never final_suspend() noexcept { return {}; }
|
||||
void return_void() {}
|
||||
void unhandled_exception() {}
|
||||
};
|
||||
|
||||
std::coroutine_handle<promise_type> handle;
|
||||
};
|
||||
|
||||
Task async_operation() {
|
||||
std::cout << "Starting async work\n";
|
||||
co_await std::suspend_always{};
|
||||
std::cout << "Resuming async work\n";
|
||||
}
|
||||
```
|
||||
|
||||
## Three-Way Comparison (Spaceship)
|
||||
|
||||
```cpp
|
||||
#include <compare>
|
||||
|
||||
struct Point {
|
||||
int x, y;
|
||||
|
||||
// Auto-generate all comparison operators
|
||||
auto operator<=>(const Point&) const = default;
|
||||
};
|
||||
|
||||
// Custom spaceship operator
|
||||
struct Version {
|
||||
int major, minor, patch;
|
||||
|
||||
std::strong_ordering operator<=>(const Version& other) const {
|
||||
if (auto cmp = major <=> other.major; cmp != 0) return cmp;
|
||||
if (auto cmp = minor <=> other.minor; cmp != 0) return cmp;
|
||||
return patch <=> other.patch;
|
||||
}
|
||||
|
||||
bool operator==(const Version& other) const = default;
|
||||
};
|
||||
```
|
||||
|
||||
## Designated Initializers
|
||||
|
||||
```cpp
|
||||
struct Config {
|
||||
std::string host = "localhost";
|
||||
int port = 8080;
|
||||
bool ssl_enabled = false;
|
||||
int timeout_ms = 5000;
|
||||
};
|
||||
|
||||
// C++20 designated initializers
|
||||
Config cfg {
|
||||
.host = "example.com",
|
||||
.port = 443,
|
||||
.ssl_enabled = true
|
||||
// timeout_ms uses default
|
||||
};
|
||||
```
|
||||
|
||||
## Modules (C++20)
|
||||
|
||||
```cpp
|
||||
// math.cppm - module interface
|
||||
export module math;
|
||||
|
||||
export namespace math {
|
||||
template<typename T>
|
||||
T add(T a, T b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
class Calculator {
|
||||
public:
|
||||
int multiply(int a, int b);
|
||||
};
|
||||
}
|
||||
|
||||
// Implementation
|
||||
module math;
|
||||
|
||||
int math::Calculator::multiply(int a, int b) {
|
||||
return a * b;
|
||||
}
|
||||
|
||||
// Usage in other files
|
||||
import math;
|
||||
|
||||
int main() {
|
||||
auto result = math::add(5, 3);
|
||||
math::Calculator calc;
|
||||
auto product = calc.multiply(4, 7);
|
||||
}
|
||||
```
|
||||
|
||||
## constexpr Enhancements
|
||||
|
||||
```cpp
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
// C++20: constexpr std::string and std::vector
|
||||
constexpr auto compute_at_compile_time() {
|
||||
std::vector<int> vec{1, 2, 3, 4, 5};
|
||||
std::ranges::reverse(vec);
|
||||
return vec[0]; // Returns 5
|
||||
}
|
||||
|
||||
constexpr int value = compute_at_compile_time();
|
||||
|
||||
// constexpr virtual functions (C++20)
|
||||
struct Base {
|
||||
constexpr virtual int get_value() const { return 42; }
|
||||
constexpr virtual ~Base() = default;
|
||||
};
|
||||
|
||||
struct Derived : Base {
|
||||
constexpr int get_value() const override { return 100; }
|
||||
};
|
||||
```
|
||||
|
||||
## std::format (C++20)
|
||||
|
||||
```cpp
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
|
||||
int main() {
|
||||
std::string msg = std::format("Hello, {}!", "World");
|
||||
|
||||
// Positional arguments
|
||||
auto text = std::format("{1} {0}", "World", "Hello");
|
||||
|
||||
// Formatting options
|
||||
double pi = 3.14159265;
|
||||
auto formatted = std::format("Pi: {:.2f}", pi); // "Pi: 3.14"
|
||||
|
||||
// Custom types
|
||||
struct Point { int x, y; };
|
||||
}
|
||||
|
||||
// Custom formatter
|
||||
template<>
|
||||
struct std::formatter<Point> {
|
||||
constexpr auto parse(format_parse_context& ctx) {
|
||||
return ctx.begin();
|
||||
}
|
||||
|
||||
auto format(const Point& p, format_context& ctx) const {
|
||||
return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Feature | C++17 | C++20 | C++23 |
|
||||
|---------|-------|-------|-------|
|
||||
| Concepts | - | ✓ | ✓ |
|
||||
| Ranges | - | ✓ | ✓ |
|
||||
| Coroutines | - | ✓ | ✓ |
|
||||
| Modules | - | ✓ | ✓ |
|
||||
| Spaceship | - | ✓ | ✓ |
|
||||
| std::format | - | ✓ | ✓ |
|
||||
| std::expected | - | - | ✓ |
|
||||
| std::print | - | - | ✓ |
|
||||
| Deducing this | - | - | ✓ |
|
||||
@@ -0,0 +1,357 @@
|
||||
# Template Metaprogramming
|
||||
|
||||
## Variadic Templates
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <utility>
|
||||
|
||||
// Fold expressions (C++17)
|
||||
template<typename... Args>
|
||||
auto sum(Args... args) {
|
||||
return (args + ...); // Unary right fold
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
void print(Args&&... args) {
|
||||
((std::cout << args << ' '), ...); // Binary left fold
|
||||
std::cout << '\n';
|
||||
}
|
||||
|
||||
// Recursive variadic template
|
||||
template<typename T>
|
||||
void log(T&& value) {
|
||||
std::cout << value << '\n';
|
||||
}
|
||||
|
||||
template<typename T, typename... Args>
|
||||
void log(T&& first, Args&&... rest) {
|
||||
std::cout << first << ", ";
|
||||
log(std::forward<Args>(rest)...);
|
||||
}
|
||||
|
||||
// Parameter pack expansion
|
||||
template<typename... Types>
|
||||
struct TypeList {
|
||||
static constexpr size_t size = sizeof...(Types);
|
||||
};
|
||||
|
||||
template<typename... Args>
|
||||
auto make_tuple_advanced(Args&&... args) {
|
||||
return std::tuple<std::decay_t<Args>...>(std::forward<Args>(args)...);
|
||||
}
|
||||
```
|
||||
|
||||
## SFINAE and if constexpr
|
||||
|
||||
```cpp
|
||||
#include <type_traits>
|
||||
|
||||
// SFINAE with std::enable_if (older style)
|
||||
template<typename T>
|
||||
std::enable_if_t<std::is_integral_v<T>, T>
|
||||
double_value(T value) {
|
||||
return value * 2;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
std::enable_if_t<std::is_floating_point_v<T>, T>
|
||||
double_value(T value) {
|
||||
return value * 2.0;
|
||||
}
|
||||
|
||||
// Modern: if constexpr (C++17)
|
||||
template<typename T>
|
||||
auto process(T value) {
|
||||
if constexpr (std::is_integral_v<T>) {
|
||||
return value * 2;
|
||||
} else if constexpr (std::is_floating_point_v<T>) {
|
||||
return value * 2.0;
|
||||
} else {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
// Detection idiom
|
||||
template<typename T, typename = void>
|
||||
struct has_serialize : std::false_type {};
|
||||
|
||||
template<typename T>
|
||||
struct has_serialize<T, std::void_t<decltype(std::declval<T>().serialize())>>
|
||||
: std::true_type {};
|
||||
|
||||
template<typename T>
|
||||
constexpr bool has_serialize_v = has_serialize<T>::value;
|
||||
|
||||
// Use with if constexpr
|
||||
template<typename T>
|
||||
void save(const T& obj) {
|
||||
if constexpr (has_serialize_v<T>) {
|
||||
obj.serialize();
|
||||
} else {
|
||||
// Default serialization
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Type Traits
|
||||
|
||||
```cpp
|
||||
#include <type_traits>
|
||||
|
||||
// Custom type traits
|
||||
template<typename T>
|
||||
struct remove_all_pointers {
|
||||
using type = T;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct remove_all_pointers<T*> {
|
||||
using type = typename remove_all_pointers<T>::type;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
using remove_all_pointers_t = typename remove_all_pointers<T>::type;
|
||||
|
||||
// Conditional types
|
||||
template<bool Condition, typename T, typename F>
|
||||
struct conditional_type {
|
||||
using type = T;
|
||||
};
|
||||
|
||||
template<typename T, typename F>
|
||||
struct conditional_type<false, T, F> {
|
||||
using type = F;
|
||||
};
|
||||
|
||||
// Compile-time type selection
|
||||
template<size_t N>
|
||||
struct best_integral_type {
|
||||
using type = std::conditional_t<N <= 8, uint8_t,
|
||||
std::conditional_t<N <= 16, uint16_t,
|
||||
std::conditional_t<N <= 32, uint32_t, uint64_t>>>;
|
||||
};
|
||||
|
||||
// Check for member functions
|
||||
template<typename T, typename = void>
|
||||
struct has_reserve : std::false_type {};
|
||||
|
||||
template<typename T>
|
||||
struct has_reserve<T, std::void_t<decltype(std::declval<T>().reserve(size_t{}))>>
|
||||
: std::true_type {};
|
||||
```
|
||||
|
||||
## CRTP (Curiously Recurring Template Pattern)
|
||||
|
||||
```cpp
|
||||
// Static polymorphism with CRTP
|
||||
template<typename Derived>
|
||||
class Shape {
|
||||
public:
|
||||
double area() const {
|
||||
return static_cast<const Derived*>(this)->area_impl();
|
||||
}
|
||||
|
||||
void draw() const {
|
||||
static_cast<const Derived*>(this)->draw_impl();
|
||||
}
|
||||
};
|
||||
|
||||
class Circle : public Shape<Circle> {
|
||||
double radius_;
|
||||
public:
|
||||
Circle(double r) : radius_(r) {}
|
||||
|
||||
double area_impl() const {
|
||||
return 3.14159 * radius_ * radius_;
|
||||
}
|
||||
|
||||
void draw_impl() const {
|
||||
std::cout << "Drawing circle\n";
|
||||
}
|
||||
};
|
||||
|
||||
class Rectangle : public Shape<Rectangle> {
|
||||
double width_, height_;
|
||||
public:
|
||||
Rectangle(double w, double h) : width_(w), height_(h) {}
|
||||
|
||||
double area_impl() const {
|
||||
return width_ * height_;
|
||||
}
|
||||
|
||||
void draw_impl() const {
|
||||
std::cout << "Drawing rectangle\n";
|
||||
}
|
||||
};
|
||||
|
||||
// CRTP for mixin capabilities
|
||||
template<typename Derived>
|
||||
class Printable {
|
||||
public:
|
||||
void print() const {
|
||||
std::cout << static_cast<const Derived*>(this)->to_string() << '\n';
|
||||
}
|
||||
};
|
||||
|
||||
class User : public Printable<User> {
|
||||
std::string name_;
|
||||
public:
|
||||
User(std::string name) : name_(std::move(name)) {}
|
||||
|
||||
std::string to_string() const {
|
||||
return "User: " + name_;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Template Template Parameters
|
||||
|
||||
```cpp
|
||||
#include <vector>
|
||||
#include <list>
|
||||
#include <deque>
|
||||
|
||||
// Template template parameter
|
||||
template<typename T, template<typename, typename> class Container>
|
||||
class Stack {
|
||||
Container<T, std::allocator<T>> data_;
|
||||
|
||||
public:
|
||||
void push(const T& value) {
|
||||
data_.push_back(value);
|
||||
}
|
||||
|
||||
T pop() {
|
||||
T value = data_.back();
|
||||
data_.pop_back();
|
||||
return value;
|
||||
}
|
||||
|
||||
size_t size() const {
|
||||
return data_.size();
|
||||
}
|
||||
};
|
||||
|
||||
// Usage with different containers
|
||||
Stack<int, std::vector> vector_stack;
|
||||
Stack<int, std::deque> deque_stack;
|
||||
Stack<int, std::list> list_stack;
|
||||
```
|
||||
|
||||
## Compile-Time Computation
|
||||
|
||||
```cpp
|
||||
#include <array>
|
||||
|
||||
// Compile-time factorial
|
||||
constexpr int factorial(int n) {
|
||||
return n <= 1 ? 1 : n * factorial(n - 1);
|
||||
}
|
||||
|
||||
constexpr int fact_5 = factorial(5); // Computed at compile time
|
||||
|
||||
// Compile-time prime checking
|
||||
constexpr bool is_prime(int n) {
|
||||
if (n < 2) return false;
|
||||
for (int i = 2; i * i <= n; ++i) {
|
||||
if (n % i == 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Generate compile-time array of primes
|
||||
template<size_t N>
|
||||
constexpr auto generate_primes() {
|
||||
std::array<int, N> primes{};
|
||||
int count = 0;
|
||||
int candidate = 2;
|
||||
|
||||
while (count < N) {
|
||||
if (is_prime(candidate)) {
|
||||
primes[count++] = candidate;
|
||||
}
|
||||
++candidate;
|
||||
}
|
||||
|
||||
return primes;
|
||||
}
|
||||
|
||||
constexpr auto first_10_primes = generate_primes<10>();
|
||||
```
|
||||
|
||||
## Expression Templates
|
||||
|
||||
```cpp
|
||||
// Lazy evaluation with expression templates
|
||||
template<typename E>
|
||||
class VecExpression {
|
||||
public:
|
||||
double operator[](size_t i) const {
|
||||
return static_cast<const E&>(*this)[i];
|
||||
}
|
||||
|
||||
size_t size() const {
|
||||
return static_cast<const E&>(*this).size();
|
||||
}
|
||||
};
|
||||
|
||||
class Vec : public VecExpression<Vec> {
|
||||
std::vector<double> data_;
|
||||
|
||||
public:
|
||||
Vec(size_t n) : data_(n) {}
|
||||
|
||||
double operator[](size_t i) const { return data_[i]; }
|
||||
double& operator[](size_t i) { return data_[i]; }
|
||||
size_t size() const { return data_.size(); }
|
||||
|
||||
// Evaluate expression template
|
||||
template<typename E>
|
||||
Vec& operator=(const VecExpression<E>& expr) {
|
||||
for (size_t i = 0; i < size(); ++i) {
|
||||
data_[i] = expr[i];
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
};
|
||||
|
||||
// Binary operation expression
|
||||
template<typename E1, typename E2>
|
||||
class VecSum : public VecExpression<VecSum<E1, E2>> {
|
||||
const E1& lhs_;
|
||||
const E2& rhs_;
|
||||
|
||||
public:
|
||||
VecSum(const E1& lhs, const E2& rhs) : lhs_(lhs), rhs_(rhs) {}
|
||||
|
||||
double operator[](size_t i) const {
|
||||
return lhs_[i] + rhs_[i];
|
||||
}
|
||||
|
||||
size_t size() const { return lhs_.size(); }
|
||||
};
|
||||
|
||||
// Operator overload
|
||||
template<typename E1, typename E2>
|
||||
VecSum<E1, E2> operator+(const VecExpression<E1>& lhs,
|
||||
const VecExpression<E2>& rhs) {
|
||||
return VecSum<E1, E2>(static_cast<const E1&>(lhs),
|
||||
static_cast<const E2&>(rhs));
|
||||
}
|
||||
|
||||
// Usage: a = b + c + d (no temporaries created!)
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Technique | Use Case | Performance |
|
||||
|-----------|----------|-------------|
|
||||
| Variadic Templates | Variable arguments | Zero overhead |
|
||||
| SFINAE | Conditional compilation | Compile-time |
|
||||
| if constexpr | Type-based branching | Zero overhead |
|
||||
| CRTP | Static polymorphism | No vtable cost |
|
||||
| Expression Templates | Lazy evaluation | Eliminates temps |
|
||||
| Type Traits | Type introspection | Compile-time |
|
||||
| Fold Expressions | Parameter pack ops | Optimal |
|
||||
| Template Specialization | Type-specific impl | Zero overhead |
|
||||
+2
-1
@@ -2,4 +2,5 @@
|
||||
.cache
|
||||
.idea
|
||||
AGENTS.md
|
||||
.vscode
|
||||
.vscode
|
||||
.opencode/
|
||||
@@ -0,0 +1,646 @@
|
||||
# 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<void> 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 <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Opaque state blob - contents are internal to Core
|
||||
struct SerializedState {
|
||||
std::vector<uint8_t> 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 <SerializedState.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
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<StateV1> 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<StateV1> 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 <TrackTypes.hpp>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
// State V0 - Initial version (placeholder for future)
|
||||
struct StateV0 {
|
||||
// Minimal state for testing migration
|
||||
std::vector<std::string> 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<PlaybackState> playback;
|
||||
std::vector<QueueEntryState> queue;
|
||||
std::vector<SessionState> 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<Echoion::Core::StateV1> {
|
||||
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 <Types.hpp>
|
||||
#include <cstdint>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
// Handles migration between state versions
|
||||
class StateMigration {
|
||||
public:
|
||||
// Migrate from any old version to current
|
||||
static Api::Result<StateV1> 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 <format>
|
||||
|
||||
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<uint8_t> data(jsonStr.begin(), jsonStr.end());
|
||||
|
||||
return Api::SerializedState{
|
||||
.data = std::move(data),
|
||||
.version = CURRENT_VERSION,
|
||||
.timestamp = getCurrentTimestampISO8601()
|
||||
};
|
||||
}
|
||||
|
||||
Api::Result<StateV1> 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<uint32_t>(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 <glaze/glaze.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
Api::Result<StateV1> 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<void> 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<void> CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) {
|
||||
std::lock_guard<std::mutex> 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?
|
||||
@@ -0,0 +1,513 @@
|
||||
# Echoion Robustness Improvement Plan
|
||||
|
||||
## Executive Summary
|
||||
|
||||
This plan addresses robustness for 100+ concurrent users on 4core/8GB hardware while maintaining the TeamSpeak plugin architecture with weekly hot-reload capability.
|
||||
|
||||
**Key Architectural Principle**: Plugin and Core are completely decoupled. Core manages its own state serialization/deserialization internally. Plugin only handles opaque state blobs.
|
||||
|
||||
**Dependencies**: Uses only existing dependencies (glaze, Boost, TBB, etc.). No new dependencies required.
|
||||
|
||||
## Current Pain Points
|
||||
|
||||
### 1. Connection Handling (Critical)
|
||||
- **Issue**: Thread-per-client model creates unlimited threads (RpcServer.cpp:167-196)
|
||||
- **Risk**: Resource exhaustion with 100+ users
|
||||
- **Impact**: System instability, crashes
|
||||
|
||||
### 2. No Resource Limits
|
||||
- **Issue**: No memory/CPU limits, unbounded queue growth
|
||||
- **Risk**: OOM kills, audio dropouts
|
||||
- **Impact**: Service degradation for all users
|
||||
|
||||
### 3. Missing Circuit Breakers
|
||||
- **Issue**: yt-dlp failures cascade (no failure isolation)
|
||||
- **Risk**: Repeated failed requests consume resources
|
||||
- **Impact**: Bot becomes unresponsive
|
||||
|
||||
### 4. Race Conditions
|
||||
- **Issue**: Queue modifications lack proper synchronization
|
||||
- **Risk**: Data corruption, crashes
|
||||
- **Impact**: Inconsistent state
|
||||
|
||||
### 5. No Health Monitoring
|
||||
- **Issue**: No self-diagnostics or automatic recovery
|
||||
- **Risk**: Silent failures accumulate
|
||||
- **Impact**: Extended downtime
|
||||
|
||||
## Decoupled State Management Architecture
|
||||
|
||||
The key insight: **Plugin should never know what state Core needs to save**. Core handles all serialization internally using versioned formats.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ TeamSpeak Client │
|
||||
│ ┌───────────────────────────────────────────────────────────────┐ │
|
||||
│ │ EchoionPlugin (.ts plugin) │ │
|
||||
│ │ │ │
|
||||
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │ │
|
||||
│ │ │ Plugin │ │ Health │ │ StateManager │ │ │
|
||||
│ │ │ Interface │ │ Monitor │ │ (Opaque Blob) │ │ │
|
||||
│ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │ │
|
||||
│ │ │ CoreLoader │ │ Connection │ │ Watchdog │ │ │
|
||||
│ │ │ (Hot Reload) │ │ Pool │ │ (Heartbeat) │ │ │
|
||||
│ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ Plugin ONLY knows: │ │
|
||||
│ │ - Core exports: saveState() -> opaque blob │ │
|
||||
│ │ - Core exports: restoreState(blob) -> success/failure │ │
|
||||
│ │ - Plugin stores blob temporarily, passes it back │ │
|
||||
│ │ - Plugin NEVER parses or inspects blob contents │ │
|
||||
│ │ │ │
|
||||
│ └───────────────────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
│ dylib::library (hot reloadable)
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ EchoionCore (.ts library) │
|
||||
│ ┌───────────────────────────────────────────────────────────────┐ │
|
||||
│ │ │ │
|
||||
│ │ Core Internally Manages: │ │
|
||||
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │ │
|
||||
│ │ │ StateVersion │ │ Migration │ │ StateSerializer │ │ │
|
||||
│ │ │ (v1, v2) │ │ Engine │ │ (glaze JSON) │ │ │
|
||||
│ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ State Format can change without Plugin rebuild: │ │
|
||||
│ │ - Old Core saves state v1 │ │
|
||||
│ │ - New Core loads state v1, migrates to v2 internally │ │
|
||||
│ │ - Plugin just passes the blob through │ │
|
||||
│ │ │ │
|
||||
│ └───────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ Core │ │ RPC │ │ Resource │ │
|
||||
│ │ (Main) │◄─┤ Server │ │ Manager │ │
|
||||
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ MusicManager │ │ YtDlpMgr │ │ Session │ │
|
||||
│ │ │ │ (Circuit │ │ Manager │ │
|
||||
│ │ │ │ Breaker) │ │ │ │
|
||||
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Decoupled State Management Design
|
||||
|
||||
### Core Interface (Stable API)
|
||||
|
||||
```cpp
|
||||
// EchoionApi - Stable interface, never changes
|
||||
class ICoreInterface {
|
||||
public:
|
||||
// State management - opaque to Plugin
|
||||
virtual Api::SerializedState saveState() = 0;
|
||||
virtual Api::Result<void> restoreState(const Api::SerializedState& state) = 0;
|
||||
|
||||
// Version info for compatibility
|
||||
virtual uint32_t getStateFormatVersion() = 0;
|
||||
virtual bool canRestoreStateVersion(uint32_t version) = 0;
|
||||
};
|
||||
|
||||
// SerializedState is just an opaque blob
|
||||
namespace Api {
|
||||
struct SerializedState {
|
||||
std::vector<uint8_t> data; // Plugin never inspects this
|
||||
uint32_t version; // Format version for logging only
|
||||
std::string timestamp; // ISO 8601 for debugging
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### Core Internal State Management (Can Change Freely)
|
||||
|
||||
Uses **glaze** (already available) for JSON serialization:
|
||||
|
||||
```cpp
|
||||
// EchoionCore - Internal implementation, can change anytime
|
||||
class Core : public ICoreInterface {
|
||||
private:
|
||||
// Current state format version
|
||||
static constexpr uint32_t CURRENT_STATE_VERSION = 2;
|
||||
|
||||
// Internal state structure - can change without affecting Plugin
|
||||
struct StateV2 {
|
||||
std::vector<QueueEntry> queue;
|
||||
std::optional<PlaybackState> currentTrack;
|
||||
float volume;
|
||||
// ... new fields can be added anytime
|
||||
};
|
||||
|
||||
// Migration support for backward compatibility
|
||||
class StateMigration {
|
||||
public:
|
||||
static StateV2 migrateFromV1(const glz::json_t& v1Data);
|
||||
static StateV2 migrateFromV0(const glz::json_t& v0Data);
|
||||
};
|
||||
|
||||
public:
|
||||
Api::SerializedState saveState() override {
|
||||
StateV2 currentState = captureCurrentState();
|
||||
|
||||
// Serialize to JSON using glaze (already available)
|
||||
std::string jsonState;
|
||||
auto ec = glz::write_json(currentState, jsonState);
|
||||
if (ec) {
|
||||
// Handle error
|
||||
return Api::SerializedState{};
|
||||
}
|
||||
|
||||
// Convert to binary blob
|
||||
std::vector<uint8_t> data(jsonState.begin(), jsonState.end());
|
||||
|
||||
return Api::SerializedState{
|
||||
.data = std::move(data),
|
||||
.version = CURRENT_STATE_VERSION,
|
||||
.timestamp = getCurrentTimestamp()
|
||||
};
|
||||
}
|
||||
|
||||
Api::Result<void> restoreState(const Api::SerializedState& state) override {
|
||||
// Convert blob back to string
|
||||
std::string jsonStr(state.data.begin(), state.data.end());
|
||||
|
||||
// Parse version from JSON using glaze
|
||||
uint32_t dataVersion = extractVersion(jsonStr);
|
||||
|
||||
// Migrate if needed (all handled internally)
|
||||
if (dataVersion == CURRENT_STATE_VERSION) {
|
||||
// Direct parse
|
||||
StateV2 restoredState;
|
||||
auto ec = glz::read_json(restoredState, jsonStr);
|
||||
if (ec) {
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::ParseError,
|
||||
"Failed to parse state"
|
||||
));
|
||||
}
|
||||
applyState(restoredState);
|
||||
} else if (dataVersion == 1) {
|
||||
// Parse as V1, then migrate
|
||||
StateV1 v1State;
|
||||
auto ec = glz::read_json(v1State, jsonStr);
|
||||
if (ec) {
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::ParseError,
|
||||
"Failed to parse V1 state"
|
||||
));
|
||||
}
|
||||
StateV2 migrated = StateMigration::migrateFromV1(v1State);
|
||||
applyState(migrated);
|
||||
} else {
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::IncompatibleVersion,
|
||||
std::format("Cannot restore state version {} (current: {})",
|
||||
dataVersion, CURRENT_STATE_VERSION)
|
||||
));
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Plugin State Management (Simple Pass-Through)
|
||||
|
||||
```cpp
|
||||
// EchoionPlugin - Never touches state internals
|
||||
class CoreLoader {
|
||||
public:
|
||||
Api::Result<void> hotReload(const std::filesystem::path& newLibraryPath) {
|
||||
// 1. Ask Core to save its state (opaque blob)
|
||||
Api::SerializedState state;
|
||||
if (core_) {
|
||||
state = core_->saveState();
|
||||
logInfo(std::format("Saved state: version={}, size={} bytes",
|
||||
state.version, state.data.size()));
|
||||
}
|
||||
|
||||
// 2. Unload old Core
|
||||
auto unloadResult = unloadLibraryInternal();
|
||||
if (!unloadResult) return unloadResult;
|
||||
|
||||
// 3. Load new Core
|
||||
auto loadResult = loadLibraryInternal(newLibraryPath);
|
||||
if (!loadResult) return loadResult;
|
||||
|
||||
// 4. Ask new Core to restore state (it handles migration internally)
|
||||
if (!state.data.empty()) {
|
||||
auto coreVersion = core_->getStateFormatVersion();
|
||||
auto stateVersion = state.version;
|
||||
|
||||
if (core_->canRestoreStateVersion(stateVersion)) {
|
||||
auto restoreResult = core_->restoreState(state);
|
||||
if (!restoreResult) {
|
||||
logError(std::format("Failed to restore state v{} to Core v{}",
|
||||
stateVersion, coreVersion));
|
||||
// Continue with empty state - graceful degradation
|
||||
} else {
|
||||
logInfo("State restored successfully");
|
||||
}
|
||||
} else {
|
||||
logWarning(std::format("Cannot restore state v{} in Core v{}",
|
||||
stateVersion, coreVersion));
|
||||
// Continue with empty state
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### State Format Evolution Example
|
||||
|
||||
```cpp
|
||||
// Week 1: StateV1
|
||||
struct StateV1 {
|
||||
std::vector<QueueEntry> queue;
|
||||
float volume;
|
||||
};
|
||||
|
||||
// Week 2: StateV2 (added new field)
|
||||
struct StateV2 {
|
||||
std::vector<QueueEntry> queue;
|
||||
float volume;
|
||||
bool shuffleMode; // NEW FIELD
|
||||
|
||||
static V2 migrateFromV1(const V1& v1) {
|
||||
return V2{
|
||||
.queue = v1.queue,
|
||||
.volume = v1.volume,
|
||||
.shuffleMode = false // Default for migrated states
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Week 3: StateV3 (changed structure)
|
||||
struct StateV3 {
|
||||
struct Playlist {
|
||||
std::vector<QueueEntry> tracks;
|
||||
uint32_t currentIndex;
|
||||
};
|
||||
|
||||
Playlist playlist; // Changed from flat queue
|
||||
PlaybackSettings settings; // Grouped settings
|
||||
|
||||
static V3 migrateFromV2(const V2& v2) {
|
||||
return V3{
|
||||
.playlist = {.tracks = v2.queue, .currentIndex = 0},
|
||||
.settings = {.volume = v2.volume, .shuffle = v2.shuffleMode}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Plugin never needs to know about these changes!
|
||||
```
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase 0: Decoupled State Management Foundation (Week 0)
|
||||
**Goal**: Establish the decoupled architecture before other improvements
|
||||
|
||||
**New Components**:
|
||||
1. **StateSerializer.hpp/cpp** (Core) - Versioned state serialization using glaze
|
||||
2. **StateMigration.hpp/cpp** (Core) - Migration between versions
|
||||
3. Update **ICoreInterface.hpp** (Api) - Add state management methods
|
||||
4. Refactor **Core.cpp** - Implement internal state management
|
||||
5. Refactor **CoreLoader.cpp** - Use opaque state blobs
|
||||
|
||||
**Key Design Decisions**:
|
||||
- State format uses glaze JSON (already available, high performance)
|
||||
- Version stored in JSON for easy inspection
|
||||
- Migration chain: V0 -> V1 -> V2 -> V3 (each version only knows previous)
|
||||
- Graceful degradation: if migration fails, start fresh (don't crash)
|
||||
|
||||
### Phase 1: Connection Pool & Rate Limiting (Week 1)
|
||||
**Goal**: Handle 100+ concurrent RPC connections safely
|
||||
|
||||
**Components**:
|
||||
1. **ConnectionPool.hpp/cpp** - Fixed-size worker thread pool (16 workers)
|
||||
2. **RateLimiter.hpp/cpp** - Token bucket per client IP (30 req/min, burst 10)
|
||||
3. Update **RpcServer.cpp** - Integrate connection pool
|
||||
|
||||
**Dependencies**: Uses Boost.Asio (already available)
|
||||
|
||||
### Phase 2: Resource Management (Week 1-2)
|
||||
**Goal**: Prevent resource exhaustion on 4core/8GB
|
||||
|
||||
**Components**:
|
||||
1. **ResourceMonitor.hpp/cpp** - Track memory/CPU usage
|
||||
2. Update **MusicManager.cpp** - Queue limits (500 tracks), memory caps
|
||||
3. Update **YtDlpManager.cpp** - Limit concurrent operations (4 max)
|
||||
|
||||
**Dependencies**: Uses standard library + TBB (already available)
|
||||
|
||||
### Phase 3: Circuit Breakers & Fault Isolation (Week 2)
|
||||
**Goal**: Prevent cascading failures
|
||||
|
||||
**Components**:
|
||||
1. **CircuitBreaker.hpp/cpp** - Generic circuit breaker pattern
|
||||
2. Update **YtDlpManager.cpp** - Add circuit breaker (5 failures = 60s cooldown)
|
||||
3. Update **NetworkClient.cpp** - Circuit breaker for HTTP calls
|
||||
|
||||
**Dependencies**: Uses standard library only (chrono, atomic)
|
||||
|
||||
### Phase 4: Session Management (Week 2-3)
|
||||
**Goal**: Support 100+ users with proper session handling
|
||||
|
||||
**Components**:
|
||||
1. **SessionManager.hpp/cpp** - Track authenticated sessions (max 150)
|
||||
2. Update **RpcServer.cpp** - Integrate session management
|
||||
3. Sessions automatically included in Core's state blob (no Plugin changes!)
|
||||
|
||||
**Dependencies**: Uses glaze (already available) + standard library
|
||||
|
||||
### Phase 5: Health Monitoring & Self-Healing (Week 3)
|
||||
**Goal**: Automatic recovery from failures
|
||||
|
||||
**Components**:
|
||||
1. **HealthMonitor.hpp/cpp** - System health checks (every 5s)
|
||||
2. **Watchdog.hpp/cpp** - Detect hangs (15s timeout)
|
||||
3. Update **Plugin.cpp** - Integrate health monitoring
|
||||
|
||||
**Dependencies**: Uses standard library + Boost.Asio (already available)
|
||||
|
||||
### Phase 6: Enhanced yt-dlp Management (Week 3-4)
|
||||
**Goal**: Reliable auto-updates with fallback
|
||||
|
||||
**Components**:
|
||||
1. Update **YtDlpManager.cpp** - Background updates, atomic swap
|
||||
2. **UpdateScheduler.hpp/cpp** - Weekly update scheduling (configurable window)
|
||||
|
||||
**Dependencies**: Uses standard library only
|
||||
|
||||
## Configuration Summary
|
||||
|
||||
```json
|
||||
{
|
||||
"robustness": {
|
||||
"stateManagement": {
|
||||
"format": "glaze_json",
|
||||
"maxStateSizeMB": 10,
|
||||
"migration": {
|
||||
"maxVersionsBackward": 5,
|
||||
"gracefulDegradation": true
|
||||
}
|
||||
},
|
||||
"rpc": {
|
||||
"maxConnections": 150,
|
||||
"workerThreads": 16,
|
||||
"rateLimitRequestsPerMinute": 30,
|
||||
"rateLimitBurst": 10,
|
||||
"connectionTimeoutMs": 30000,
|
||||
"sessionTimeoutMs": 3600000
|
||||
},
|
||||
"resourceLimits": {
|
||||
"maxQueueSize": 500,
|
||||
"maxMemoryMB": 1024,
|
||||
"maxYtDlpConcurrent": 4,
|
||||
"maxAudioBufferMB": 256,
|
||||
"enableMemoryPressureHandling": true,
|
||||
"memoryPressureThresholdMB": 768
|
||||
},
|
||||
"circuitBreaker": {
|
||||
"ytDlpFailureThreshold": 5,
|
||||
"ytDlpResetTimeoutMs": 60000,
|
||||
"networkFailureThreshold": 3,
|
||||
"networkResetTimeoutMs": 30000
|
||||
},
|
||||
"healthMonitor": {
|
||||
"checkIntervalMs": 5000,
|
||||
"unhealthyThresholdMs": 30000,
|
||||
"enableAutoRecovery": true,
|
||||
"maxConsecutiveRecoveries": 3
|
||||
},
|
||||
"watchdog": {
|
||||
"heartbeatIntervalMs": 5000,
|
||||
"timeoutMs": 15000,
|
||||
"enableAutoReload": true
|
||||
},
|
||||
"ytDlp": {
|
||||
"autoUpdate": true,
|
||||
"updateIntervalDays": 7,
|
||||
"updateTimeWindow": "02:00-04:00",
|
||||
"enableFallbackMirrors": true,
|
||||
"requestTimeoutMs": 30000,
|
||||
"enableRequestDeduplication": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Dependencies Used
|
||||
|
||||
All dependencies are already in your project:
|
||||
|
||||
1. **glaze** - JSON serialization for state management
|
||||
2. **Boost.Asio/Beast** - Connection pool, RPC server
|
||||
3. **Boost.UUID** - Session IDs
|
||||
4. **TBB** - Parallel algorithms for resource monitoring
|
||||
5. **standard library** - Circuit breakers, rate limiters, health monitoring
|
||||
|
||||
**No new dependencies required!**
|
||||
|
||||
## Benefits of Decoupled State Management
|
||||
|
||||
1. **Plugin Stability**: Plugin code never changes when Core state format changes
|
||||
2. **Rapid Iteration**: Modify Core state structure without rebuilding Plugin
|
||||
3. **Backward Compatibility**: Old states automatically migrate to new format
|
||||
4. **Forward Compatibility**: Can detect if state is from future version
|
||||
5. **Debugging**: State blobs can be saved to disk and inspected manually (JSON)
|
||||
6. **Testing**: Easy to create test states for specific scenarios
|
||||
7. **Performance**: Uses glaze (high-performance JSON library you already have)
|
||||
|
||||
## Hot-Reload Flow with Decoupled State
|
||||
|
||||
```
|
||||
1. Core V1 running, users connected, music playing
|
||||
│
|
||||
▼
|
||||
2. Developer builds Core V2 (new state format)
|
||||
│
|
||||
▼
|
||||
3. File watcher detects new .ts library
|
||||
│
|
||||
▼
|
||||
4. Plugin asks Core V1: saveState()
|
||||
Core V1 serializes internal state to blob (format V1)
|
||||
│
|
||||
▼
|
||||
5. Plugin unloads Core V1, loads Core V2
|
||||
│
|
||||
▼
|
||||
6. Plugin asks Core V2: restoreState(blob V1)
|
||||
Core V2 internally migrates V1 -> V2
|
||||
Users stay connected, queue preserved
|
||||
│
|
||||
▼
|
||||
7. Core V2 running with migrated state
|
||||
Zero downtime, zero Plugin changes
|
||||
```
|
||||
|
||||
## Success Metrics
|
||||
|
||||
- **Uptime**: >99.9%
|
||||
- **Concurrent Users**: 100+ without degradation
|
||||
- **Memory**: Stable <1GB under load
|
||||
- **Recovery Time**: <5s from failure
|
||||
- **Hot-Reload**: Zero user impact, zero Plugin rebuilds
|
||||
- **State Migration**: 100% success rate for versions within 5 releases
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Review this updated plan** - Does the decoupled state approach meet your needs?
|
||||
2. **State format preferences** - glaze JSON OK, or prefer binary (using std::vector<uint8_t> with custom format)?
|
||||
3. **Migration depth** - Support 5 versions back, or more/less?
|
||||
4. **Start implementation** - Begin with Phase 0 (state management foundation)?
|
||||
|
||||
The decoupled architecture means you can iterate on Core weekly without ever touching Plugin code again, and we're only using dependencies you already have!
|
||||
+25
-2
@@ -1,4 +1,4 @@
|
||||
cmake_minimum_required(VERSION 3.28)
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(Echoion VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
# Include CPM
|
||||
@@ -17,10 +17,33 @@ CPMAddPackage(
|
||||
VERSION 1.11.2
|
||||
)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 23)
|
||||
# VoidLibrary — modular C++26 infrastructure (Json, Logging, Configuration,
|
||||
# Plugin, Service, Async, Functional, System, Fsm, ...). Echoion's in-house
|
||||
# infrastructure is migrated onto these Void:: targets.
|
||||
# For local development against a working copy, configure with
|
||||
# -DCPM_Void_SOURCE=/path/to/VoidLibrary
|
||||
# which CPM honours over the git checkout below.
|
||||
CPMAddPackage(
|
||||
NAME Void
|
||||
GIT_REPOSITORY http://git.faumaray.ru/void/voidlibrary.git
|
||||
GIT_TAG 80293ee56f9f587f27d0c86d25f5cc53548cb6ba
|
||||
OPTIONS
|
||||
"VOID_ENABLE_TESTING OFF"
|
||||
)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# GCC 16+ exposes experimental C++26 reflection (P2996) via -freflection.
|
||||
# Void's header-only INTERFACE modules (Data/Functional/Core) do not propagate
|
||||
# this flag, so apply it tree-wide for every echoion target that may include
|
||||
# <Void/Data/Reflect.hpp>, <Void/Configuration/Bind.hpp>, etc.
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
|
||||
# Guard to C++ only — vendored C dependencies (quickjs) must not see it.
|
||||
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-freflection>)
|
||||
endif()
|
||||
|
||||
# Enable folder organization in IDEs
|
||||
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
|
||||
|
||||
|
||||
+1
-1
Submodule EchoionApi updated: 5e1e3d66c4...0e0f8915e9.
+1
-1
Submodule EchoionCore updated: 53801f2b53...d74a69aa34.
+1
-1
Submodule EchoionDesktop updated: e646080683...bf1cd8e08d.
+1
-1
Submodule EchoionPlugin updated: 0fa9db4691...df1ea8d53f.
@@ -0,0 +1,153 @@
|
||||
# VoidLibrary — work needed to fully migrate Echoion (+ upgrade ideas)
|
||||
|
||||
## STATUS (round 2 complete)
|
||||
|
||||
Almost everything below has now landed. Echoion uses Void for **Json, Logging,
|
||||
Process, Retry, Configuration, EventBus (async), ThreadPool, Cache, Resilience,
|
||||
BufferPool, Result**, and **glaze is fully removed**. The blockers A1–A6 were all
|
||||
implemented in VoidLibrary as universal primitives and consumed by Echoion:
|
||||
|
||||
- **A1 done** — `Void/Data/Reflect.hpp` now reflects `chrono::duration`,
|
||||
**`time_point`**, `variant`, `array`, non-string `map`. TrackInfo/RPC/state
|
||||
serialize via reflection; glaze gone.
|
||||
- **A2 done** — `Void::EventBus` gained `Mode::Async`; Echoion's bus delegates to it.
|
||||
- **A3 done** — `Void::Concurrency::ThreadPool` gained bounded queue + `try_submit`
|
||||
+ rejection stats (Echoion's ConnectionPool deleted).
|
||||
- **A4 done** — `Void::Containers::Cache` (TTL + policy + stats) added; LruCache deleted.
|
||||
- **A5 done** — `Void::Resilience` (TokenBucket, **KeyedRateLimiter<Key>**,
|
||||
CircuitBreaker, ResourceMonitor); Echoion's RateLimiter/CircuitBreaker/
|
||||
ResourceMonitor deleted.
|
||||
- **A6 done** — `Void::BufferPool::BufferPool<T>` added; AudioBufferPool wraps it;
|
||||
bespoke MemoryPool deleted. New `Void::System` metrics (process_memory/cpu) added.
|
||||
|
||||
**Remaining (one item):** the plugin loader is still Echoion's dylib-based
|
||||
`CoreLoader`, not `Void::Plugin`. This is **not** a Void gap — it's an
|
||||
Echoion-side rewrite gated on a live hot-reload test (impedance mismatch: Core
|
||||
implements `ICoreInterface`, `Void::Plugin::Loader` hands back `IPlugin*`). See
|
||||
section B.
|
||||
|
||||
The historical analysis below is retained for reference.
|
||||
|
||||
---
|
||||
|
||||
## A. Blockers — feature parity VoidLibrary must add
|
||||
|
||||
### A1. JSON reflection: native `chrono` / `variant` / `map` / `array` support — HIGHEST IMPACT
|
||||
**Problem.** `Void/Data/Reflect.hpp` only (de)serializes arithmetic, enum, string,
|
||||
`optional`, `vector`, string-keyed map, and aggregates. It cannot handle
|
||||
`std::chrono::duration` / `time_point`, `std::variant`, `std::map` with non-string
|
||||
keys, or `std::array`. A single such member makes a whole struct non-reflectable.
|
||||
|
||||
**Echoion impact.** Forced hand-written `to_json/from_json` for `TrackInfo`, and
|
||||
`*Json` mirror structs for config. It still blocks **`HotReloadState`** (its
|
||||
`BotConfig`/`QueueEntry`/`PlaybackState` carry `chrono`) and **RPC** (`RpcRequest`/
|
||||
`RpcResponse`/`RpcNotification` carry `time_point`).
|
||||
|
||||
**Ask.** Built-in reflection handling for:
|
||||
- `std::chrono::duration<Rep,Period>` → integer count (Meta already exposes
|
||||
`is_duration_v`), and `time_point` → epoch millis — encoding ideally selectable
|
||||
via a field attribute (`[[= Json::ChronoAs{Millis}]]`).
|
||||
- `std::variant` (tagged, or first-that-parses).
|
||||
- `std::map<K,V>` for non-string keys.
|
||||
- `std::array<T,N>`.
|
||||
|
||||
**Payoff.** Removes essentially all remaining manual serializers and directly
|
||||
unblocks the HotReloadState + RPC migrations. **Do this first.**
|
||||
|
||||
### A2. EventBus: async / queued dispatch mode
|
||||
**Problem.** `Void::EventBus::publish()` invokes handlers inline (synchronous).
|
||||
Echoion's bus is async (background thread) because its handlers do **network
|
||||
broadcasts** (`rpcServer_->broadcastEvent`) and **SQLite writes**
|
||||
(`database_->recordPlayback`). Sync dispatch would run that I/O on the publisher's
|
||||
thread (the playback path) → blocking and lock-ordering deadlock risk.
|
||||
|
||||
**Ask.** An async dispatch mode (worker thread or `Void::Concurrency::ThreadPool`
|
||||
backed), e.g. `EventBus(Mode::Async)` with `drain()`/`flush()`, keeping sync as the
|
||||
default. Optional ordered delivery + coalescing.
|
||||
|
||||
**Payoff.** Echoion drops its custom `EventBus` + `GlobalEventBus`.
|
||||
|
||||
### A3. ThreadPool: bounded queue + backpressure / rejection
|
||||
**Problem.** `Void::Concurrency::ThreadPool::submit()` is unbounded. Echoion's
|
||||
`ConnectionPool` exists specifically for admission control: a bounded queue,
|
||||
`try_submit()` returning `false` when full (prevents resource exhaustion under RPC
|
||||
load), plus active / queued / processed / **rejected** stats.
|
||||
|
||||
**Ask.** A bounded-capacity option + `try_submit() -> bool` (or `expected`) + basic
|
||||
counters (pending, active, processed, rejected).
|
||||
|
||||
**Payoff.** Echoion drops `ConnectionPool`.
|
||||
|
||||
### A4. Cache: TTL + eviction policies + stats
|
||||
**Problem.** `Void::Containers::LruCache` is capacity-only. Echoion's `LruCache`
|
||||
has per-entry **TTL** expiry, selectable eviction policy (LRU/LFU/FIFO/TTL), and
|
||||
**stats** (hits/misses/evictions/inserts/hitRate/memoryUsage) — used for audio and
|
||||
metadata caching where TTL matters.
|
||||
|
||||
**Ask.** A richer cache (or options on `LruCache`): per-entry TTL, pluggable
|
||||
eviction policy, hit/miss/eviction counters, optional size/memory accounting.
|
||||
|
||||
**Payoff.** Echoion drops its `Cache`.
|
||||
|
||||
### A5. Resilience primitives — net-new `Void::Resilience` module
|
||||
None of these exist in Void today; all are standard, broadly useful service
|
||||
primitives:
|
||||
- **RateLimiter** — token bucket, per-key, configurable rate + burst, stale-entry
|
||||
cleanup. (echoion `RateLimiter`)
|
||||
- **CircuitBreaker** — CLOSED / OPEN / HALF_OPEN, failure threshold, reset timeout,
|
||||
stats. (echoion `CircuitBreaker`)
|
||||
- **ResourceMonitor** — memory / CPU / queue-depth sampling with threshold +
|
||||
pressure callbacks. (echoion `ResourceMonitor`)
|
||||
|
||||
### A6. MemoryPool: typed audio-buffer / arena pool
|
||||
**Problem.** `Void::Containers::Pool` is a slab **object** pool (`acquire()` →
|
||||
`unique_ptr<T>`). Echoion's `MemoryPool` pools reusable **int16 audio sample
|
||||
buffers** (grow-on-demand, zero-copy views) on the decode→playback hot path.
|
||||
|
||||
**Ask.** A buffer/arena pool variant (pooled contiguous `T` buffers with reuse +
|
||||
high-water stats), or confirm `Pool<std::vector<int16_t>>` is an acceptable fit.
|
||||
|
||||
---
|
||||
|
||||
## B. Already replaceable — no VoidLibrary change needed (Echoion-side work only)
|
||||
|
||||
- **Plugin loader → `Void::Plugin`.** `Loader::reload()` + `Manager` (FileWatcher,
|
||||
RCU-pinned handles so "work never stops for a reload") + the v2
|
||||
`serialize_state`/`deserialize_state` C-ABI protocol already cover — and improve
|
||||
on — Echoion's `CoreLoader`/dylib/`FileWatcher`. The "defer reload until the
|
||||
current track finishes" behaviour is a policy Echoion can layer on `Manager`.
|
||||
- **RPC JSON** and **HotReloadState** are blocked *only* by **A1** (plus the Desktop
|
||||
client moving in lockstep for the RPC wire format).
|
||||
|
||||
---
|
||||
|
||||
## C. Upgrade ideas (general VoidLibrary improvements)
|
||||
|
||||
- **Json:** streaming/SAX parser + incremental serialize for large docs (yt-dlp
|
||||
`-J` playlist output is often MBs); JSON Pointer / path query (`get_as<T>(path)`);
|
||||
parse integers without a `double` round-trip; a `from_json` that collects *all*
|
||||
field errors, not just the first.
|
||||
- **Json reflection:** read-side key aliases, per-field defaults, and the chrono
|
||||
encoding attribute from A1.
|
||||
- **Process:** async/streaming variant (incremental stdout for progress), env-var
|
||||
and working-directory control, and a kill/signal handle for long-running children.
|
||||
- **Retry:** jitter (full / decorrelated) on backoff; an overall deadline / retry
|
||||
budget.
|
||||
- **Logging:** structured (JSON/logfmt) sink; per-module level sourced from
|
||||
`Configuration`; a sampling / rate-limited sink; optional console level-split
|
||||
(info→stdout, error→stderr).
|
||||
- **Configuration:** typed `get_as<T>` with chrono + byte-size units (Echoion config
|
||||
uses `"1GB"`, `"30000ms"`).
|
||||
- **Service:** scoped / child registries; ordered startup with declared dependency
|
||||
edges.
|
||||
|
||||
---
|
||||
|
||||
## Priority (by Echoion unblock value)
|
||||
|
||||
1. **A1** (JSON chrono/variant) — unblocks RPC + HotReloadState and deletes the
|
||||
manual serializers. Biggest single win.
|
||||
2. **A2** (async EventBus) — removes an entire subsystem.
|
||||
3. **A3 / A4** (ThreadPool backpressure, Cache TTL+stats).
|
||||
4. **A5** (resilience module).
|
||||
5. **A6** (audio buffer pool).
|
||||
+91
-17
@@ -1,49 +1,123 @@
|
||||
{
|
||||
"_schema": "Echoion Music Bot Configuration v2.0",
|
||||
"_documentation": "https://github.com/faumaray/echoion/wiki/Configuration",
|
||||
|
||||
"bot": {
|
||||
"_section": "Core Bot Settings",
|
||||
"botName": "Echoion",
|
||||
"commandPrefix": "!",
|
||||
"defaultVolume": 0.5,
|
||||
"maxQueueSize": 100,
|
||||
"trackTimeout": 30000,
|
||||
|
||||
"_reconnection": "Auto-reconnection settings",
|
||||
"autoReconnect": true,
|
||||
"reconnectDelay": 5000,
|
||||
"maxReconnectAttempts": 5,
|
||||
|
||||
"_audio": "Audio quality settings",
|
||||
"preferredQuality": "High",
|
||||
"allowPlaylistImports": true,
|
||||
"maxQueueSize": 100,
|
||||
"trackTimeout": 30000,
|
||||
"allowPlaylistImports": true
|
||||
},
|
||||
|
||||
"youtube": {
|
||||
"_section": "YouTube Integration",
|
||||
"_apiKey": "Optional: YouTube Data API v3 key for faster searches",
|
||||
"youtubeApiKey": null,
|
||||
|
||||
"_cookies": "Fix 'Sign in to confirm' errors using ONE of these methods:",
|
||||
"_cookies_method_1": "Path to cookies.txt file (export from browser extension)",
|
||||
"youtubeCookiesPath": null,
|
||||
"_cookies_method_2": "Use cookies directly from browser: chrome, firefox, safari, edge",
|
||||
"cookiesFromBrowser": null,
|
||||
|
||||
"_performance": "yt-dlp performance tuning",
|
||||
"ytDlpMaxConcurrent": 4,
|
||||
"ytDlpAsyncEnabled": true,
|
||||
|
||||
"_urlShortening": "Shorten YouTube links using faumaray.ru",
|
||||
"enableUrlShortening": true
|
||||
},
|
||||
|
||||
"network": {
|
||||
"_section": "Network & Proxy Settings",
|
||||
"_proxy": "Optional proxy configuration for YouTube access",
|
||||
"proxyType": "HTTP",
|
||||
"proxyHost": null,
|
||||
"proxyPort": null,
|
||||
"proxyUsername": null,
|
||||
"proxyPassword": null,
|
||||
"proxyType": "HTTP",
|
||||
"youtubeApiKey": null,
|
||||
|
||||
"_rpc": "WebSocket RPC server for Desktop/API clients",
|
||||
"rpcEnabled": true,
|
||||
"rpcPort": 8765,
|
||||
"_comment_youtube_cookies": "To fix YouTube 'Sign in to confirm you're not a bot' error, use ONE of these options:",
|
||||
"_comment_option_1": "Option 1: Path to a cookies.txt file exported from your browser",
|
||||
"youtubeCookiesPath": null,
|
||||
"_comment_option_2": "Option 2: Use cookies directly from browser (chrome, firefox, safari, edge)",
|
||||
"cookiesFromBrowser": null,
|
||||
"_comment_yt_dlp": "yt-dlp performance settings:",
|
||||
"ytDlpMaxConcurrent": 4,
|
||||
"ytDlpAsyncEnabled": true,
|
||||
"_comment_url_shortening": "Enable faumaray.ru link shortening for track links in messages",
|
||||
"enableUrlShortening": true
|
||||
"rpcBindAddress": "127.0.0.1"
|
||||
},
|
||||
"server": {
|
||||
|
||||
"teamspeak": {
|
||||
"_section": "TeamSpeak Server Connection",
|
||||
"address": "localhost",
|
||||
"port": 9987,
|
||||
"serverPassword": "",
|
||||
"nickname": "EchoionBot",
|
||||
|
||||
"_channel": "Default channel configuration",
|
||||
"defaultChannelId": null,
|
||||
"channelPassword": null,
|
||||
|
||||
"_permissions": "Server group IDs for access control",
|
||||
"adminGroups": [6, 7],
|
||||
"djGroups": [8],
|
||||
"bannedGroups": []
|
||||
},
|
||||
|
||||
"security": {
|
||||
"_section": "Security & Authentication",
|
||||
"requireAuthForAdmin": true,
|
||||
"maxLoginAttempts": 5,
|
||||
"lockoutDuration": 300000,
|
||||
"sessionTimeout": 3600000,
|
||||
"enableAuditLog": true
|
||||
"enableAuditLog": true,
|
||||
|
||||
"_api": "API authentication for RPC clients",
|
||||
"apiKey": null,
|
||||
"allowCors": false,
|
||||
"corsOrigins": ["http://localhost:3000"]
|
||||
},
|
||||
|
||||
"features": {
|
||||
"_section": "Feature Toggles",
|
||||
"enableHotReload": true,
|
||||
"enableAutoReload": false,
|
||||
"enableAutoUpdateCheck": true,
|
||||
|
||||
"_playback": "Playback behavior settings",
|
||||
"autoStartOnSubscribe": true,
|
||||
"pauseOnEmptySubscribers": true,
|
||||
"resumeOnSubscriberReturn": true,
|
||||
|
||||
"_queue": "Queue management settings",
|
||||
"shuffleMode": "random",
|
||||
"repeatMode": "off",
|
||||
"maxHistorySize": 50
|
||||
},
|
||||
|
||||
"advanced": {
|
||||
"_section": "Advanced Settings (Modify with caution)",
|
||||
"_audio": "Low-level audio configuration",
|
||||
"sampleRate": 192000,
|
||||
"channels": 2,
|
||||
"bufferSize": 7680,
|
||||
|
||||
"_threading": "Thread pool configuration",
|
||||
"commandThreadPoolSize": 4,
|
||||
"networkThreadPoolSize": 4,
|
||||
"decoderThreads": 2,
|
||||
|
||||
"_cache": "Cache and temporary file settings",
|
||||
"cacheEnabled": true,
|
||||
"cacheMaxSize": "1GB",
|
||||
"cacheTTL": 86400,
|
||||
"tempCleanupInterval": 3600
|
||||
}
|
||||
}
|
||||
Executable
+149
@@ -0,0 +1,149 @@
|
||||
#!/bin/bash
|
||||
# Debug script for TeamSpeak Echoion service issues
|
||||
|
||||
set -e
|
||||
|
||||
USER_NAME="${USER_NAME:-bot}"
|
||||
RDP_PORT="${RDP_PORT:-3390}"
|
||||
|
||||
echo "TeamSpeak Echoion - Diagnostic Tool"
|
||||
echo "=================================="
|
||||
echo ""
|
||||
|
||||
# Check user
|
||||
echo "1. Checking user..."
|
||||
echo " Current user: $(whoami)"
|
||||
echo " Target user: $USER_NAME"
|
||||
if [ "$(whoami)" != "$USER_NAME" ]; then
|
||||
echo " ⚠️ Warning: Running as different user"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Check environment
|
||||
echo "2. Checking environment..."
|
||||
echo " XDG_RUNTIME_DIR: ${XDG_RUNTIME_DIR:-not set}"
|
||||
echo " HOME: ${HOME:-not set}"
|
||||
echo " USER: ${USER:-not set}"
|
||||
echo " DBUS_SESSION_BUS_ADDRESS: ${DBUS_SESSION_BUS_ADDRESS:-not set}"
|
||||
echo ""
|
||||
|
||||
# Check directories
|
||||
echo "3. Checking directories..."
|
||||
TS3_DIR="/home/$USER_NAME/TeamSpeak3-Client-linux_amd64"
|
||||
if [ -d "$TS3_DIR" ]; then
|
||||
echo " ✓ TeamSpeak dir: $TS3_DIR"
|
||||
ls -la "$TS3_DIR" | head -5
|
||||
else
|
||||
echo " ✗ TeamSpeak dir not found: $TS3_DIR"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Check certificates
|
||||
echo "4. Checking certificates..."
|
||||
CERT_FILE="/home/$USER_NAME/.config/EchoionTsBot.crt"
|
||||
KEY_FILE="/home/$USER_NAME/.config/EchoionTsBot.key"
|
||||
if [ -f "$CERT_FILE" ]; then
|
||||
echo " ✓ Certificate: $CERT_FILE"
|
||||
ls -la "$CERT_FILE"
|
||||
else
|
||||
echo " ✗ Certificate not found: $CERT_FILE"
|
||||
fi
|
||||
if [ -f "$KEY_FILE" ]; then
|
||||
echo " ✓ Key: $KEY_FILE"
|
||||
ls -la "$KEY_FILE"
|
||||
else
|
||||
echo " ✗ Key not found: $KEY_FILE"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Check port
|
||||
echo "5. Checking port $RDP_PORT..."
|
||||
if ss -tlnp | grep -q ":$RDP_PORT "; then
|
||||
echo " ✗ Port $RDP_PORT is in use:"
|
||||
ss -tlnp | grep ":$RDP_PORT "
|
||||
else
|
||||
echo " ✓ Port $RDP_PORT is available"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Check weston
|
||||
echo "6. Checking weston..."
|
||||
if command -v weston &> /dev/null; then
|
||||
echo " ✓ Weston found: $(which weston)"
|
||||
weston --version 2>/dev/null || echo " Version: unknown"
|
||||
else
|
||||
echo " ✗ Weston not found"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Check dbus
|
||||
echo "7. Checking dbus..."
|
||||
if command -v dbus-run-session &> /dev/null; then
|
||||
echo " ✓ dbus-run-session found: $(which dbus-run-session)"
|
||||
else
|
||||
echo " ✗ dbus-run-session not found"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Check capabilities
|
||||
echo "8. Checking capabilities..."
|
||||
if command -v getcap &> /dev/null; then
|
||||
WESTON_BIN=$(which weston 2>/dev/null || echo "")
|
||||
if [ -n "$WESTON_BIN" ]; then
|
||||
getcap "$WESTON_BIN" 2>/dev/null || echo " No special capabilities"
|
||||
fi
|
||||
else
|
||||
echo " getcap not available"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Check systemd
|
||||
echo "9. Checking systemd..."
|
||||
if systemctl --user is-system-running &>/dev/null; then
|
||||
echo " ✓ Systemd user session is running"
|
||||
else
|
||||
echo " ⚠️ Systemd user session not available (this is OK)"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Check runtime directory
|
||||
echo "10. Checking runtime directory..."
|
||||
RUNTIME_DIR="/tmp/.ts3bot-display-$USER_NAME"
|
||||
if [ -d "$RUNTIME_DIR" ]; then
|
||||
echo " ✓ Runtime dir exists: $RUNTIME_DIR"
|
||||
ls -la "$RUNTIME_DIR"
|
||||
else
|
||||
echo " Runtime dir doesn't exist (will be created): $RUNTIME_DIR"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Test weston directly
|
||||
echo "11. Testing weston startup..."
|
||||
echo " Attempting to start weston for 2 seconds..."
|
||||
TEST_DIR="/tmp/.weston-test-$$"
|
||||
mkdir -p "$TEST_DIR"
|
||||
chmod 700 "$TEST_DIR"
|
||||
|
||||
export XDG_RUNTIME_DIR="$TEST_DIR"
|
||||
timeout 2 dbus-run-session -- weston --backend=rdp --rdp-port=3391 2>&1 | head -20 || true
|
||||
rm -rf "$TEST_DIR"
|
||||
echo ""
|
||||
|
||||
echo "Diagnostic complete!"
|
||||
echo ""
|
||||
echo "Common issues and solutions:"
|
||||
echo ""
|
||||
echo "1. If weston fails to bind to port:"
|
||||
echo " - Try a different port: export RDP_PORT=3391"
|
||||
echo " - Check if another process is using the port"
|
||||
echo ""
|
||||
echo "2. If certificates are not found:"
|
||||
echo " Generate them with:"
|
||||
echo " openssl req -x509 -newkey rsa:4096 -keyout ~/.config/EchoionTsBot.key -out ~/.config/EchoionTsBot.crt -days 365 -nodes"
|
||||
echo ""
|
||||
echo "3. If systemd user session is not available:"
|
||||
echo " - Use system service instead: sudo ~/echoion/scripts/install-service.sh system"
|
||||
echo " - Or start manually: ~/echoion/scripts/run-teamspeak-headless.sh"
|
||||
echo ""
|
||||
echo "4. To test weston directly:"
|
||||
echo " ~/echoion/scripts/run-teamspeak-headless.sh"
|
||||
Executable
+191
@@ -0,0 +1,191 @@
|
||||
#!/bin/bash
|
||||
# Installation script for TeamSpeak Echoion systemd service
|
||||
|
||||
set -e
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
USER_NAME="${USER_NAME:-bot}"
|
||||
INSTALL_TYPE="${1:-user}" # 'user' or 'system'
|
||||
|
||||
echo -e "${GREEN}TeamSpeak Echoion Bot - Service Installer${NC}"
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
|
||||
# Show usage for user without proper session
|
||||
if [ "$INSTALL_TYPE" == "user" ] && [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
|
||||
echo -e "${YELLOW}Note: Running without a full user session${NC}"
|
||||
echo "This is OK - the script will install the service files."
|
||||
echo "You may need to manually reload systemd after installation."
|
||||
echo ""
|
||||
fi
|
||||
|
||||
# Check if running as root for system install
|
||||
if [ "$INSTALL_TYPE" == "system" ] && [ "$EUID" -ne 0 ]; then
|
||||
echo -e "${RED}Error: System installation requires root privileges${NC}"
|
||||
echo "Run: sudo $0 system"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if user is correct
|
||||
if [ "$INSTALL_TYPE" == "user" ] && [ "$(whoami)" != "$USER_NAME" ]; then
|
||||
echo -e "${YELLOW}Warning: You are running as '$(whoami)' but USER_NAME is set to '$USER_NAME'${NC}"
|
||||
echo "This is OK if you're installing for another user."
|
||||
echo "To install for current user, run: USER_NAME=$(whoami) $0"
|
||||
echo ""
|
||||
read -p "Continue anyway? (y/N) " -n 1 -r
|
||||
echo
|
||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Verify bot user exists
|
||||
if ! id "$USER_NAME" &>/dev/null; then
|
||||
echo -e "${RED}Error: User '$USER_NAME' does not exist${NC}"
|
||||
echo "Create the user first: sudo useradd -m -s /bin/bash $USER_NAME"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Installation type: $INSTALL_TYPE"
|
||||
echo "Bot user: $USER_NAME"
|
||||
echo ""
|
||||
|
||||
# Check prerequisites
|
||||
echo -e "${YELLOW}Checking prerequisites...${NC}"
|
||||
|
||||
# Check if weston is installed
|
||||
if ! command -v weston &> /dev/null; then
|
||||
echo -e "${RED}Error: weston is not installed${NC}"
|
||||
echo "Install it with: sudo pacman -S weston"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if dbus-run-session is available
|
||||
if ! command -v dbus-run-session &> /dev/null; then
|
||||
echo -e "${RED}Error: dbus-run-session is not available${NC}"
|
||||
echo "Install it with: sudo pacman -S dbus"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check TeamSpeak directory
|
||||
TS3_DIR="/home/$USER_NAME/TeamSpeak3-Client-linux_amd64"
|
||||
if [ ! -d "$TS3_DIR" ]; then
|
||||
echo -e "${YELLOW}Warning: TeamSpeak directory not found at: $TS3_DIR${NC}"
|
||||
echo "Make sure to install TeamSpeak client there before starting the service"
|
||||
fi
|
||||
|
||||
# Check certificates
|
||||
CERT_FILE="/home/$USER_NAME/.config/EchoionTsBot.crt"
|
||||
KEY_FILE="/home/$USER_NAME/.config/EchoionTsBot.key"
|
||||
if [ ! -f "$CERT_FILE" ] || [ ! -f "$KEY_FILE" ]; then
|
||||
echo -e "${YELLOW}Warning: TLS certificates not found${NC}"
|
||||
echo " Cert: $CERT_FILE"
|
||||
echo " Key: $KEY_FILE"
|
||||
echo "You can generate self-signed certificates with:"
|
||||
echo " openssl req -x509 -newkey rsa:4096 -keyout $KEY_FILE -out $CERT_FILE -days 365 -nodes"
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}Prerequisites check passed!${NC}"
|
||||
echo ""
|
||||
|
||||
# Copy wrapper script
|
||||
echo -e "${YELLOW}Installing wrapper script...${NC}"
|
||||
mkdir -p "/home/$USER_NAME/echoion/scripts"
|
||||
cp "$SCRIPT_DIR/../scripts/run-teamspeak-headless.sh" "/home/$USER_NAME/echoion/scripts/"
|
||||
chown -R "$USER_NAME:$USER_NAME" "/home/$USER_NAME/echoion"
|
||||
chmod +x "/home/$USER_NAME/echoion/scripts/run-teamspeak-headless.sh"
|
||||
echo -e "${GREEN}Wrapper script installed${NC}"
|
||||
echo ""
|
||||
|
||||
# Function to check if we have a working user systemd session
|
||||
has_user_systemd_session() {
|
||||
local user="$1"
|
||||
# Check if we can communicate with the user systemd
|
||||
if sudo -u "$user" systemctl --user --quiet is-system-running 2>/dev/null || \
|
||||
sudo -u "$user" systemctl --user daemon-reload 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
# Install systemd service
|
||||
if [ "$INSTALL_TYPE" == "system" ]; then
|
||||
echo -e "${YELLOW}Installing system service...${NC}"
|
||||
cp "$SCRIPT_DIR/../systemd/teamspeak-echoion.service" /etc/systemd/system/
|
||||
|
||||
# Update user in service file
|
||||
sed -i "s/User=bot/User=$USER_NAME/g" /etc/systemd/system/teamspeak-echoion.service
|
||||
sed -i "s/Group=bot/Group=$USER_NAME/g" /etc/systemd/system/teamspeak-echoion.service
|
||||
sed -i "s|/home/bot|/home/$USER_NAME|g" /etc/systemd/system/teamspeak-echoion.service
|
||||
|
||||
systemctl daemon-reload
|
||||
echo -e "${GREEN}System service installed${NC}"
|
||||
echo ""
|
||||
echo "To start the service:"
|
||||
echo " sudo systemctl start teamspeak-echoion"
|
||||
echo ""
|
||||
echo "To enable on boot:"
|
||||
echo " sudo systemctl enable teamspeak-echoion"
|
||||
echo ""
|
||||
echo "To check status:"
|
||||
echo " sudo systemctl status teamspeak-echoion"
|
||||
else
|
||||
echo -e "${YELLOW}Installing user service...${NC}"
|
||||
|
||||
# Create user systemd directory
|
||||
sudo -u "$USER_NAME" mkdir -p "/home/$USER_NAME/.config/systemd/user"
|
||||
|
||||
# Copy service file
|
||||
cp "$SCRIPT_DIR/../systemd/teamspeak-echoion-user.service" "/home/$USER_NAME/.config/systemd/user/teamspeak-echoion.service"
|
||||
|
||||
# Update paths in service file
|
||||
sed -i "s|/home/bot|/home/$USER_NAME|g" "/home/$USER_NAME/.config/systemd/user/teamspeak-echoion.service"
|
||||
chown "$USER_NAME:$USER_NAME" "/home/$USER_NAME/.config/systemd/user/teamspeak-echoion.service"
|
||||
|
||||
# Try to reload user systemd, but don't fail if not in a session
|
||||
echo -e "${YELLOW}Attempting to reload systemd user daemon...${NC}"
|
||||
if has_user_systemd_session "$USER_NAME"; then
|
||||
echo -e "${GREEN}Systemd user session found, reloading daemon${NC}"
|
||||
sudo -u "$USER_NAME" systemctl --user daemon-reload
|
||||
echo ""
|
||||
echo "To start the service:"
|
||||
echo " systemctl --user start teamspeak-echoion"
|
||||
echo ""
|
||||
echo "To enable on login:"
|
||||
echo " systemctl --user enable teamspeak-echoion"
|
||||
echo ""
|
||||
echo "To check status:"
|
||||
echo " systemctl --user status teamspeak-echoion"
|
||||
else
|
||||
echo -e "${YELLOW}Note: No active systemd user session detected${NC}"
|
||||
echo "This is normal when running via SSH without X11 or from a minimal shell"
|
||||
echo ""
|
||||
echo "The service file has been installed. To complete setup, run these commands"
|
||||
echo "from a proper user session (e.g., after logging in via SSH with a PTY):"
|
||||
echo ""
|
||||
echo " systemctl --user daemon-reload"
|
||||
echo " systemctl --user start teamspeak-echoion"
|
||||
echo " systemctl --user enable teamspeak-echoion"
|
||||
echo ""
|
||||
echo "Or start it manually with:"
|
||||
echo " ~/echoion/scripts/run-teamspeak-headless.sh"
|
||||
fi
|
||||
echo ""
|
||||
echo "To enable lingering (start on boot without login):"
|
||||
echo " sudo loginctl enable-linger $USER_NAME"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo -e "${GREEN}Installation complete!${NC}"
|
||||
echo ""
|
||||
echo "View logs with:"
|
||||
if [ "$INSTALL_TYPE" == "system" ]; then
|
||||
echo " sudo journalctl -u teamspeak-echoion -f"
|
||||
else
|
||||
echo " sudo -u $USER_NAME journalctl --user -u teamspeak-echoion -f"
|
||||
fi
|
||||
Executable
+83
@@ -0,0 +1,83 @@
|
||||
#!/bin/bash
|
||||
# TeamSpeak 3 Headless Runner with Echoion Bot
|
||||
# This script sets up the environment and starts TeamSpeak with Weston compositor
|
||||
|
||||
set -e
|
||||
|
||||
# Configuration
|
||||
USER_NAME="${USER_NAME:-bot}"
|
||||
HOME_DIR="/home/${USER_NAME}"
|
||||
TS3_DIR="${HOME_DIR}/TeamSpeak3-Client-linux_amd64"
|
||||
CONFIG_DIR="${HOME_DIR}/.config"
|
||||
RUNTIME_DIR="/tmp/.ts3bot-display-${USER_NAME}"
|
||||
CERT_FILE="${CONFIG_DIR}/EchoionTsBot.crt"
|
||||
KEY_FILE="${CONFIG_DIR}/EchoionTsBot.key"
|
||||
RDP_PORT="${RDP_PORT:-3390}"
|
||||
|
||||
# Check if running as root
|
||||
if [ "$EUID" -eq 0 ]; then
|
||||
echo "Please do not run this script as root"
|
||||
echo "Run as the bot user: sudo -u ${USER_NAME} $0"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create runtime directory
|
||||
mkdir -p "${RUNTIME_DIR}"
|
||||
chmod 700 "${RUNTIME_DIR}"
|
||||
|
||||
# Export environment variables
|
||||
export XDG_RUNTIME_DIR="${RUNTIME_DIR}"
|
||||
export HOME="${HOME_DIR}"
|
||||
export USER="${USER_NAME}"
|
||||
|
||||
# Check if port is already in use
|
||||
if ss -tlnp | grep -q ":${RDP_PORT} "; then
|
||||
echo "Error: Port ${RDP_PORT} is already in use"
|
||||
echo "Choose a different port by setting RDP_PORT environment variable"
|
||||
echo "Example: RDP_PORT=3391 $0"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if certificates exist and have correct permissions
|
||||
if [ ! -f "${CERT_FILE}" ] || [ ! -f "${KEY_FILE}" ]; then
|
||||
echo "Warning: TLS certificates not found at:"
|
||||
echo " Cert: ${CERT_FILE}"
|
||||
echo " Key: ${KEY_FILE}"
|
||||
echo "RDP connections may not work without certificates"
|
||||
sleep 2
|
||||
else
|
||||
# Check permissions - key should be readable by user
|
||||
if [ ! -r "${KEY_FILE}" ]; then
|
||||
echo "Error: Cannot read key file: ${KEY_FILE}"
|
||||
echo "Fix permissions: chmod 600 ${KEY_FILE}"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check if TeamSpeak directory exists
|
||||
if [ ! -d "${TS3_DIR}" ]; then
|
||||
echo "Error: TeamSpeak directory not found at: ${TS3_DIR}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cd "${TS3_DIR}"
|
||||
|
||||
echo "Starting TeamSpeak 3 with Echoion Bot..."
|
||||
echo " User: ${USER_NAME}"
|
||||
echo " Runtime Dir: ${RUNTIME_DIR}"
|
||||
echo " Weston Backend: RDP"
|
||||
echo " RDP Port: ${RDP_PORT}"
|
||||
echo " TLS Cert: ${CERT_FILE}"
|
||||
echo ""
|
||||
|
||||
# Start dbus-run-session with weston and TeamSpeak
|
||||
# Using explicit IP binding and port
|
||||
exec dbus-run-session -- \
|
||||
weston \
|
||||
--backend=rdp \
|
||||
--xwayland \
|
||||
--rdp-tls-cert="${CERT_FILE}" \
|
||||
--rdp-tls-key="${KEY_FILE}" \
|
||||
--rdp-address=0.0.0.0 \
|
||||
--rdp-port=${RDP_PORT} \
|
||||
-- ./ts3client_runscript.sh "$@"
|
||||
Executable
+85
@@ -0,0 +1,85 @@
|
||||
#!/bin/bash
|
||||
# Quick start script for TeamSpeak Echoion when systemd user session is not available
|
||||
# This script can be used as a fallback when systemctl --user doesn't work
|
||||
|
||||
set -e
|
||||
|
||||
USER_NAME="${USER_NAME:-$(whoami)}"
|
||||
SERVICE_NAME="teamspeak-echoion"
|
||||
|
||||
echo "TeamSpeak Echoion - Quick Start"
|
||||
echo "==============================="
|
||||
echo ""
|
||||
|
||||
# Check if we're in a systemd user session
|
||||
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ] || [ -z "$XDG_RUNTIME_DIR" ]; then
|
||||
echo "No systemd user session detected."
|
||||
echo ""
|
||||
echo "You have three options:"
|
||||
echo ""
|
||||
echo "1. Start via systemd (requires session bus - see below)"
|
||||
echo "2. Start manually with the wrapper script"
|
||||
echo "3. Use a tmux/screen session"
|
||||
echo ""
|
||||
echo -e "\033[1;33mOption 1: Using systemd (recommended for production)\033[0m"
|
||||
echo " First, start a proper user session:"
|
||||
echo " - Log in via SSH with a pseudo-terminal: ssh -t user@host bash"
|
||||
echo " - Or enable lingering and reboot:"
|
||||
echo " sudo loginctl enable-linger $USER_NAME"
|
||||
echo " Then:"
|
||||
echo " systemctl --user daemon-reload"
|
||||
echo " systemctl --user start $SERVICE_NAME"
|
||||
echo ""
|
||||
echo -e "\033[1;33mOption 2: Manual start (for testing)\033[0m"
|
||||
echo " ~/echoion/scripts/run-teamspeak-headless.sh"
|
||||
echo ""
|
||||
echo -e "\033[1;33mOption 3: Using tmux\033[0m"
|
||||
echo " tmux new-session -d -s teamspeak '~/echoion/scripts/run-teamspeak-headless.sh'"
|
||||
echo " tmux attach -t teamspeak"
|
||||
echo ""
|
||||
|
||||
read -p "Would you like to start manually now? (y/N) " -n 1 -r
|
||||
echo
|
||||
if [[ $REPLY =~ ^[Yy]$ ]]; then
|
||||
echo "Starting TeamSpeak..."
|
||||
exec ~/echoion/scripts/run-teamspeak-headless.sh
|
||||
else
|
||||
exit 0
|
||||
fi
|
||||
else
|
||||
# We have a session, try systemd
|
||||
echo "Systemd user session detected!"
|
||||
echo ""
|
||||
|
||||
# Check if service file exists
|
||||
if [ ! -f "$HOME/.config/systemd/user/$SERVICE_NAME.service" ]; then
|
||||
echo "Service file not found. Please run the install script first:"
|
||||
echo " ~/echoion/scripts/install-service.sh user"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if service is running
|
||||
if systemctl --user is-active --quiet $SERVICE_NAME; then
|
||||
echo "Service is already running!"
|
||||
echo "View status: systemctl --user status $SERVICE_NAME"
|
||||
echo "View logs: journalctl --user -u $SERVICE_NAME -f"
|
||||
else
|
||||
echo "Starting service..."
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user start $SERVICE_NAME
|
||||
|
||||
sleep 2
|
||||
|
||||
if systemctl --user is-active --quiet $SERVICE_NAME; then
|
||||
echo -e "\033[0;32mService started successfully!\033[0m"
|
||||
echo ""
|
||||
echo "Status: systemctl --user status $SERVICE_NAME"
|
||||
echo "Logs: journalctl --user -u $SERVICE_NAME -f"
|
||||
echo "Stop: systemctl --user stop $SERVICE_NAME"
|
||||
else
|
||||
echo -e "\033[0;31mService failed to start. Check logs:\033[0m"
|
||||
echo "journalctl --user -u $SERVICE_NAME --no-pager -n 50"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/bin/bash
|
||||
# Alternative start script using tmux for persistence
|
||||
# This is useful when systemd user session is not available
|
||||
|
||||
set -e
|
||||
|
||||
USER_NAME="${USER_NAME:-$(whoami)}"
|
||||
SESSION_NAME="teamspeak-echoion"
|
||||
|
||||
echo "TeamSpeak Echoion - Tmux Session Starter"
|
||||
echo "========================================"
|
||||
echo ""
|
||||
|
||||
# Check if tmux is installed
|
||||
if ! command -v tmux &> /dev/null; then
|
||||
echo "Error: tmux is not installed"
|
||||
echo "Install it with: sudo pacman -S tmux"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if session already exists
|
||||
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
|
||||
echo "Session '$SESSION_NAME' already exists!"
|
||||
echo ""
|
||||
echo "Options:"
|
||||
echo " 1. Attach to existing session: tmux attach -t $SESSION_NAME"
|
||||
echo " 2. Kill existing session: tmux kill-session -t $SESSION_NAME"
|
||||
echo " 3. View logs: tmux capture-pane -t $SESSION_NAME -p | tail -50"
|
||||
echo ""
|
||||
read -p "Kill existing session and start new? (y/N) " -n 1 -r
|
||||
echo
|
||||
if [[ $REPLY =~ ^[Yy]$ ]]; then
|
||||
tmux kill-session -t "$SESSION_NAME"
|
||||
echo "Killed existing session"
|
||||
else
|
||||
echo "Exiting..."
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "Starting new tmux session: $SESSION_NAME"
|
||||
echo ""
|
||||
|
||||
# Create new detached session
|
||||
tmux new-session -d -s "$SESSION_NAME" -n "teamspeak" "bash -c 'cd ~ && echo \"Starting TeamSpeak Echoion...\" && ~/echoion/scripts/run-teamspeak-headless.sh'"
|
||||
|
||||
# Optional: Create additional windows for monitoring
|
||||
tmux new-window -t "$SESSION_NAME" -n "logs" "bash -c 'echo \"Waiting for logs...\" && sleep 5 && journalctl --user -u teamspeak-echoion -f 2>/dev/null || tail -f /tmp/.ts3bot-display-$USER_NAME/*.log 2>/dev/null || echo \"No logs available\"'"
|
||||
|
||||
echo -e "\033[0;32mTmux session started successfully!\033[0m"
|
||||
echo ""
|
||||
echo "To attach to the session:"
|
||||
echo " tmux attach -t $SESSION_NAME"
|
||||
echo ""
|
||||
echo "To view logs without attaching:"
|
||||
echo " tmux capture-pane -t $SESSION_NAME:0 -p"
|
||||
echo ""
|
||||
echo "To detach from session (when attached):"
|
||||
echo " Press Ctrl+B then D"
|
||||
echo ""
|
||||
echo "To kill the session:"
|
||||
echo " tmux kill-session -t $SESSION_NAME"
|
||||
echo ""
|
||||
echo "Switch between windows (when attached):"
|
||||
echo " Ctrl+B then 0 (for TeamSpeak)"
|
||||
echo " Ctrl+B then 1 (for logs)"
|
||||
@@ -0,0 +1,428 @@
|
||||
# TeamSpeak Echoion Bot - Systemd Service
|
||||
|
||||
This directory contains systemd service files and scripts for running TeamSpeak 3 client with Echoion bot in headless mode using Weston Wayland compositor with RDP backend.
|
||||
|
||||
## Files
|
||||
|
||||
- `teamspeak-echoion.service` - System-wide systemd service (runs as root/system)
|
||||
- `teamspeak-echoion-user.service` - User systemd service (runs as user)
|
||||
- `run-teamspeak-headless.sh` - Wrapper script for manual execution
|
||||
- `install-service.sh` - Installation script
|
||||
- `start-echoion.sh` - Quick start helper script (handles DBus session issues)
|
||||
- `diagnose-echoion.sh` - Diagnostic tool for troubleshooting
|
||||
- `start-with-tmux.sh` - Alternative startup using tmux
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. **Weston** - Wayland compositor
|
||||
```bash
|
||||
sudo pacman -S weston
|
||||
```
|
||||
|
||||
2. **DBus** - For session management
|
||||
```bash
|
||||
sudo pacman -S dbus
|
||||
```
|
||||
|
||||
3. **TeamSpeak 3 Client** - Installed in `/home/bot/TeamSpeak3-Client-linux_amd64`
|
||||
|
||||
4. **TLS Certificates** - For RDP connections
|
||||
```bash
|
||||
# Generate self-signed certificates
|
||||
openssl req -x509 -newkey rsa:4096 \
|
||||
-keyout ~/.config/EchoionTsBot.key \
|
||||
-out ~/.config/EchoionTsBot.crt \
|
||||
-days 365 -nodes
|
||||
```
|
||||
|
||||
## Quick Install
|
||||
|
||||
### Option 1: User Service (Recommended)
|
||||
|
||||
Run as your bot user:
|
||||
```bash
|
||||
cd ~/echoion/scripts
|
||||
./install-service.sh user
|
||||
```
|
||||
|
||||
This creates a user service that runs as the bot user.
|
||||
|
||||
**⚠️ Important: DBus Session Error**
|
||||
|
||||
If you get an error like:
|
||||
```
|
||||
Failed to connect to user scope bus via local transport: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined
|
||||
```
|
||||
|
||||
This happens when running from a minimal shell without a full user session. This is **normal** and the service files are still installed correctly. See the [DBus Session section](#dbus-session-setup) below for solutions.
|
||||
|
||||
### Option 2: System Service
|
||||
|
||||
Run as root:
|
||||
```bash
|
||||
cd /path/to/echoion/scripts
|
||||
sudo ./install-service.sh system
|
||||
```
|
||||
|
||||
## Manual Installation
|
||||
|
||||
### User Service
|
||||
|
||||
1. Copy service file:
|
||||
```bash
|
||||
mkdir -p ~/.config/systemd/user
|
||||
cp teamspeak-echoion-user.service ~/.config/systemd/user/teamspeak-echoion.service
|
||||
```
|
||||
|
||||
2. Copy wrapper script:
|
||||
```bash
|
||||
mkdir -p ~/echoion/scripts
|
||||
cp run-teamspeak-headless.sh ~/echoion/scripts/
|
||||
chmod +x ~/echoion/scripts/run-teamspeak-headless.sh
|
||||
```
|
||||
|
||||
3. Reload systemd:
|
||||
```bash
|
||||
systemctl --user daemon-reload
|
||||
```
|
||||
|
||||
4. Start service:
|
||||
```bash
|
||||
systemctl --user start teamspeak-echoion
|
||||
```
|
||||
|
||||
5. Enable on login:
|
||||
```bash
|
||||
systemctl --user enable teamspeak-echoion
|
||||
```
|
||||
|
||||
6. Enable on boot (without login):
|
||||
```bash
|
||||
sudo loginctl enable-linger $(whoami)
|
||||
```
|
||||
|
||||
### System Service
|
||||
|
||||
1. Copy service file:
|
||||
```bash
|
||||
sudo cp teamspeak-echoion.service /etc/systemd/system/
|
||||
```
|
||||
|
||||
2. Edit service file to match your user:
|
||||
```bash
|
||||
sudo systemctl edit --full teamspeak-echoion
|
||||
```
|
||||
|
||||
3. Reload systemd:
|
||||
```bash
|
||||
sudo systemctl daemon-reload
|
||||
```
|
||||
|
||||
4. Start service:
|
||||
```bash
|
||||
sudo systemctl start teamspeak-echoion
|
||||
```
|
||||
|
||||
5. Enable on boot:
|
||||
```bash
|
||||
sudo systemctl enable teamspeak-echoion
|
||||
```
|
||||
|
||||
## DBus Session Setup
|
||||
|
||||
When running the install script or systemd commands via SSH or a minimal shell, you may encounter:
|
||||
```
|
||||
Failed to connect to user scope bus via local transport: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined
|
||||
```
|
||||
|
||||
This is normal and the service files are still installed correctly. Here are the solutions:
|
||||
|
||||
### Solution 1: Use SSH with PTY (Easiest)
|
||||
|
||||
Connect with a pseudo-terminal allocation:
|
||||
```bash
|
||||
ssh -t bot@your-server bash
|
||||
```
|
||||
|
||||
Then run systemd commands normally:
|
||||
```bash
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user start teamspeak-echoion
|
||||
```
|
||||
|
||||
### Solution 2: Enable Lingering and Reboot
|
||||
|
||||
Enable lingering so the user services start on boot without needing a login session:
|
||||
```bash
|
||||
sudo loginctl enable-linger bot
|
||||
```
|
||||
|
||||
Then reboot the server. After reboot, the service will start automatically.
|
||||
|
||||
### Solution 3: Manual Start (No systemd)
|
||||
|
||||
If you just want to test or can't get systemd working:
|
||||
```bash
|
||||
~/echoion/scripts/run-teamspeak-headless.sh
|
||||
```
|
||||
|
||||
Or use the helper script:
|
||||
```bash
|
||||
~/echoion/scripts/start-echoion.sh
|
||||
```
|
||||
|
||||
### Solution 4: Use tmux/screen
|
||||
|
||||
Run in a persistent terminal session:
|
||||
```bash
|
||||
tmux new-session -d -s teamspeak '~/echoion/scripts/run-teamspeak-headless.sh'
|
||||
```
|
||||
|
||||
To view: `tmux attach -t teamspeak`
|
||||
To detach: Press `Ctrl+B` then `D`
|
||||
|
||||
### Solution 5: System Service (No DBus needed)
|
||||
|
||||
Install as a system service instead (requires root):
|
||||
```bash
|
||||
sudo ~/echoion/scripts/install-service.sh system
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Check Service Status
|
||||
|
||||
**User service:**
|
||||
```bash
|
||||
systemctl --user status teamspeak-echoion
|
||||
```
|
||||
|
||||
**System service:**
|
||||
```bash
|
||||
sudo systemctl status teamspeak-echoion
|
||||
```
|
||||
|
||||
### View Logs
|
||||
|
||||
**User service:**
|
||||
```bash
|
||||
journalctl --user -u teamspeak-echoion -f
|
||||
```
|
||||
|
||||
**System service:**
|
||||
```bash
|
||||
sudo journalctl -u teamspeak-echoion -f
|
||||
```
|
||||
|
||||
### Stop Service
|
||||
|
||||
**User service:**
|
||||
```bash
|
||||
systemctl --user stop teamspeak-echoion
|
||||
```
|
||||
|
||||
**System service:**
|
||||
```bash
|
||||
sudo systemctl stop teamspeak-echoion
|
||||
```
|
||||
|
||||
### Restart Service
|
||||
|
||||
**User service:**
|
||||
```bash
|
||||
systemctl --user restart teamspeak-echoion
|
||||
```
|
||||
|
||||
**System service:**
|
||||
```bash
|
||||
sudo systemctl restart teamspeak-echoion
|
||||
```
|
||||
|
||||
## RDP Connection
|
||||
|
||||
Once the service is running, you can connect via RDP to manage TeamSpeak:
|
||||
|
||||
**Default port is now 3390** (changed from 3389 to avoid conflicts):
|
||||
|
||||
```bash
|
||||
xfreerdp3 /v:localhost:3390 /u:bot /p: /cert:ignore
|
||||
```
|
||||
|
||||
Or use any RDP client with:
|
||||
- **Host**: Your server IP or localhost
|
||||
- **Port**: 3390 (default, or change in service file)
|
||||
- **Username**: bot (or your configured user)
|
||||
- **TLS**: Enabled (uses the certificates you provided)
|
||||
|
||||
**To use a different port**, edit the service:
|
||||
```bash
|
||||
systemctl --user edit --full teamspeak-echoion
|
||||
```
|
||||
|
||||
Change `RDP_PORT=3390` to your preferred port.
|
||||
|
||||
## Configuration
|
||||
|
||||
Edit the service file to customize:
|
||||
|
||||
- **User/Group**: Change `bot` to your bot user
|
||||
- **Paths**: Update paths to TeamSpeak, certificates, and scripts
|
||||
- **Environment**: Add or modify environment variables
|
||||
- **Resources**: Adjust `LimitNOFILE` and `LimitNPROC`
|
||||
- **Restart policy**: Change `Restart` and `RestartSec` values
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Service fails to start
|
||||
|
||||
1. Check logs:
|
||||
```bash
|
||||
journalctl -u teamspeak-echoion --no-pager -n 50
|
||||
```
|
||||
|
||||
2. Verify certificates exist:
|
||||
```bash
|
||||
ls -la ~/.config/EchoionTsBot.*
|
||||
```
|
||||
|
||||
3. Test wrapper script manually:
|
||||
```bash
|
||||
~/echoion/scripts/run-teamspeak-headless.sh
|
||||
```
|
||||
|
||||
### Weston/RDP issues
|
||||
|
||||
#### Error: "RDP unable to bind socket"
|
||||
|
||||
This is the most common error. Several things can cause this:
|
||||
|
||||
**1. Port already in use or permission denied**
|
||||
```bash
|
||||
# Check if port is in use
|
||||
sudo ss -tlnp | grep 3389
|
||||
|
||||
# Try a different port (edit service file to use port 3390 or higher)
|
||||
export RDP_PORT=3390
|
||||
~/echoion/scripts/run-teamspeak-headless.sh
|
||||
```
|
||||
|
||||
**2. Certificate issues**
|
||||
```bash
|
||||
# Check certificates exist and are readable
|
||||
ls -la ~/.config/EchoionTsBot.*
|
||||
|
||||
# Generate new certificates if needed
|
||||
openssl req -x509 -newkey rsa:4096 \
|
||||
-keyout ~/.config/EchoionTsBot.key \
|
||||
-out ~/.config/EchoionTsBot.crt \
|
||||
-days 365 -nodes
|
||||
|
||||
# Fix permissions
|
||||
chmod 600 ~/.config/EchoionTsBot.key
|
||||
chmod 644 ~/.config/EchoionTsBot.crt
|
||||
```
|
||||
|
||||
**3. Missing weston RDP backend**
|
||||
```bash
|
||||
# Check if RDP backend is installed
|
||||
ls -la /usr/lib/libweston-*/rdp-backend.so
|
||||
|
||||
# If missing, install weston properly
|
||||
sudo pacman -S weston
|
||||
```
|
||||
|
||||
**4. Test weston without TeamSpeak**
|
||||
```bash
|
||||
# Create test directory
|
||||
mkdir -p /tmp/test-weston
|
||||
export XDG_RUNTIME_DIR=/tmp/test-weston
|
||||
|
||||
# Test weston only
|
||||
dbus-run-session -- weston --backend=rdp --rdp-port=3390
|
||||
|
||||
# If this works, the issue is with the full setup
|
||||
```
|
||||
|
||||
**5. Use alternative port (3390 instead of 3389)**
|
||||
The service now defaults to port 3390 to avoid conflicts. To change the port:
|
||||
|
||||
Edit the service file:
|
||||
```bash
|
||||
systemctl --user edit --full teamspeak-echoion
|
||||
```
|
||||
|
||||
Change:
|
||||
```ini
|
||||
Environment="RDP_PORT=3390"
|
||||
```
|
||||
|
||||
To your preferred port (e.g., 3391, 3392, etc.)
|
||||
|
||||
#### Other RDP issues
|
||||
|
||||
1. Check weston configuration:
|
||||
```bash
|
||||
cat ~/.config/weston.ini
|
||||
```
|
||||
|
||||
2. Run diagnostic script:
|
||||
```bash
|
||||
~/echoion/scripts/diagnose-echoion.sh
|
||||
```
|
||||
|
||||
3. Check weston logs:
|
||||
```bash
|
||||
journalctl --user -u teamspeak-echoion --no-pager -n 100
|
||||
```
|
||||
|
||||
### Permission issues
|
||||
|
||||
1. Check file ownership:
|
||||
```bash
|
||||
ls -la ~/TeamSpeak3-Client-linux_amd64/
|
||||
ls -la ~/.config/EchoionTsBot.*
|
||||
```
|
||||
|
||||
2. Fix permissions:
|
||||
```bash
|
||||
sudo chown -R bot:bot ~/TeamSpeak3-Client-linux_amd64/
|
||||
sudo chown bot:bot ~/.config/EchoionTsBot.*
|
||||
```
|
||||
|
||||
## Security Notes
|
||||
|
||||
1. **Firewall**: Restrict RDP port (3389) access to trusted IPs only
|
||||
```bash
|
||||
sudo ufw allow from 192.168.1.0/24 to any port 3389
|
||||
```
|
||||
|
||||
2. **Certificates**: Use proper TLS certificates in production, not self-signed
|
||||
|
||||
3. **User permissions**: Run as non-root user with minimal privileges
|
||||
|
||||
4. **Network isolation**: Consider running in a container or VM for isolation
|
||||
|
||||
## Uninstallation
|
||||
|
||||
### User Service
|
||||
```bash
|
||||
systemctl --user stop teamspeak-echoion
|
||||
systemctl --user disable teamspeak-echoion
|
||||
rm ~/.config/systemd/user/teamspeak-echoion.service
|
||||
systemctl --user daemon-reload
|
||||
```
|
||||
|
||||
### System Service
|
||||
```bash
|
||||
sudo systemctl stop teamspeak-echoion
|
||||
sudo systemctl disable teamspeak-echoion
|
||||
sudo rm /etc/systemd/system/teamspeak-echoion.service
|
||||
sudo systemctl daemon-reload
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- [Weston Documentation](https://wayland.freedesktop.org/weston.html)
|
||||
- [systemd Documentation](https://www.freedesktop.org/software/systemd/man/)
|
||||
- [TeamSpeak 3 Client](https://www.teamspeak.com/)
|
||||
- [Echoion Bot Documentation](../README.md)
|
||||
@@ -0,0 +1,52 @@
|
||||
[Unit]
|
||||
Description=TeamSpeak 3 Client with Echoion Music Bot
|
||||
After=network.target sound.target
|
||||
Wants=network.target sound.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
|
||||
# Environment setup
|
||||
Environment="XDG_RUNTIME_DIR=/tmp/.ts3bot-display-%u"
|
||||
Environment="HOME=%h"
|
||||
Environment="USER=%u"
|
||||
Environment="RDP_PORT=3390"
|
||||
Environment="WESTON_DEBUG=1"
|
||||
|
||||
# Working directory
|
||||
WorkingDirectory=%h/TeamSpeak3-Client-linux_amd64
|
||||
|
||||
# Create runtime directory
|
||||
ExecStartPre=/bin/mkdir -p /tmp/.ts3bot-display-%u
|
||||
ExecStartPre=/bin/chmod 700 /tmp/.ts3bot-display-%u
|
||||
|
||||
# Check if port is available
|
||||
ExecStartPre=-/bin/sh -c 'ss -tlnp | grep -q ":3390 " && echo "Port 3390 in use, trying alternative" && exit 1 || exit 0'
|
||||
|
||||
# Main command using the wrapper script
|
||||
ExecStart=/home/bot/echoion/scripts/run-teamspeak-headless.sh
|
||||
|
||||
# Restart policy
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
StartLimitInterval=60
|
||||
StartLimitBurst=3
|
||||
|
||||
# Resource limits
|
||||
LimitNOFILE=65536
|
||||
LimitNPROC=4096
|
||||
|
||||
# Security settings - allow binding to ports
|
||||
PrivateNetwork=no
|
||||
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
||||
|
||||
# Ensure we have proper socket permissions
|
||||
UMask=0077
|
||||
|
||||
# Logging
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=teamspeak-echoion
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,55 @@
|
||||
[Unit]
|
||||
Description=TeamSpeak 3 Client with Echoion Music Bot
|
||||
After=network.target sound.target
|
||||
Wants=network.target sound.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=bot
|
||||
Group=bot
|
||||
|
||||
# Working directory where TeamSpeak client is installed
|
||||
WorkingDirectory=/home/bot/TeamSpeak3-Client-linux_amd64
|
||||
|
||||
# Environment setup
|
||||
Environment="XDG_RUNTIME_DIR=/tmp/.ts3bot-display"
|
||||
Environment="HOME=/home/bot"
|
||||
Environment="USER=bot"
|
||||
Environment="DISPLAY=:1"
|
||||
|
||||
# Create runtime directory and start the service
|
||||
ExecStartPre=/bin/mkdir -p /tmp/.ts3bot-display
|
||||
ExecStartPre=/bin/chmod 700 /tmp/.ts3bot-display
|
||||
|
||||
# Main command - runs dbus, weston with RDP backend, and TeamSpeak
|
||||
ExecStart=/bin/bash -c 'cd /home/bot/TeamSpeak3-Client-linux_amd64 && \
|
||||
dbus-run-session -- \
|
||||
weston \
|
||||
--backend=rdp \
|
||||
--xwayland \
|
||||
--rdp-tls-cert=/home/bot/.config/EchoionTsBot.crt \
|
||||
--rdp-tls-key=/home/bot/.config/EchoionTsBot.key \
|
||||
-- ./ts3client_runscript.sh'
|
||||
|
||||
# Restart policy
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
StartLimitInterval=60
|
||||
StartLimitBurst=3
|
||||
|
||||
# Resource limits
|
||||
LimitNOFILE=65536
|
||||
LimitNPROC=4096
|
||||
|
||||
# Security settings
|
||||
NoNewPrivileges=false
|
||||
ProtectSystem=no
|
||||
ProtectHome=no
|
||||
|
||||
# Logging
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=teamspeak-echoion
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Reference in new issue
Block a user