Compare commits
29
Commits
No files matched your search
@@ -1,86 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,437 +0,0 @@
|
||||
# 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 |
|
||||
@@ -1,397 +0,0 @@
|
||||
# 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 |
|
||||
@@ -1,304 +0,0 @@
|
||||
# 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 | - | - | ✓ |
|
||||
@@ -1,357 +0,0 @@
|
||||
# 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 |
|
||||
-272
@@ -1,272 +0,0 @@
|
||||
---
|
||||
BasedOnStyle: LLVM
|
||||
AccessModifierOffset: 0
|
||||
AlignAfterOpenBracket: Align
|
||||
AlignArrayOfStructures: None
|
||||
AlignConsecutiveAssignments:
|
||||
Enabled: false
|
||||
AcrossEmptyLines: false
|
||||
AcrossComments: false
|
||||
AlignCompound: false
|
||||
AlignFunctionPointers: false
|
||||
PadOperators: true
|
||||
AlignConsecutiveBitFields:
|
||||
Enabled: true
|
||||
AcrossEmptyLines: false
|
||||
AcrossComments: false
|
||||
AlignCompound: false
|
||||
AlignFunctionPointers: false
|
||||
PadOperators: false
|
||||
AlignConsecutiveDeclarations:
|
||||
Enabled: false
|
||||
AcrossEmptyLines: false
|
||||
AcrossComments: false
|
||||
AlignCompound: false
|
||||
AlignFunctionPointers: false
|
||||
PadOperators: false
|
||||
AlignConsecutiveMacros:
|
||||
Enabled: false
|
||||
AcrossEmptyLines: false
|
||||
AcrossComments: false
|
||||
AlignCompound: false
|
||||
AlignFunctionPointers: false
|
||||
PadOperators: false
|
||||
AlignConsecutiveShortCaseStatements:
|
||||
Enabled: false
|
||||
AcrossEmptyLines: false
|
||||
AcrossComments: false
|
||||
AlignCaseArrows: false
|
||||
AlignCaseColons: false
|
||||
AlignConsecutiveTableGenBreakingDAGArgColons:
|
||||
Enabled: false
|
||||
AcrossEmptyLines: false
|
||||
AcrossComments: false
|
||||
AlignCompound: false
|
||||
AlignFunctionPointers: false
|
||||
PadOperators: false
|
||||
AlignConsecutiveTableGenCondOperatorColons:
|
||||
Enabled: false
|
||||
AcrossEmptyLines: false
|
||||
AcrossComments: false
|
||||
AlignCompound: false
|
||||
AlignFunctionPointers: false
|
||||
PadOperators: false
|
||||
AlignConsecutiveTableGenDefinitionColons:
|
||||
Enabled: false
|
||||
AcrossEmptyLines: false
|
||||
AcrossComments: false
|
||||
AlignCompound: false
|
||||
AlignFunctionPointers: false
|
||||
PadOperators: false
|
||||
AlignEscapedNewlines: Right
|
||||
AlignOperands: Align
|
||||
AlignTrailingComments:
|
||||
Kind: Always
|
||||
OverEmptyLines: 0
|
||||
AllowAllArgumentsOnNextLine: true
|
||||
AllowAllParametersOfDeclarationOnNextLine: true
|
||||
AllowBreakBeforeNoexceptSpecifier: Never
|
||||
AllowShortBlocksOnASingleLine: Never
|
||||
AllowShortCaseExpressionOnASingleLine: true
|
||||
AllowShortCaseLabelsOnASingleLine: false
|
||||
AllowShortCompoundRequirementOnASingleLine: true
|
||||
AllowShortEnumsOnASingleLine: true
|
||||
AllowShortFunctionsOnASingleLine: All
|
||||
AllowShortIfStatementsOnASingleLine: Never
|
||||
AllowShortLambdasOnASingleLine: All
|
||||
AllowShortLoopsOnASingleLine: false
|
||||
AlwaysBreakAfterDefinitionReturnType: None
|
||||
AlwaysBreakBeforeMultilineStrings: false
|
||||
AttributeMacros:
|
||||
- __capability
|
||||
BinPackArguments: true
|
||||
BinPackParameters: true
|
||||
BitFieldColonSpacing: Both
|
||||
BraceWrapping:
|
||||
AfterCaseLabel: true
|
||||
AfterClass: true
|
||||
AfterControlStatement: Never
|
||||
AfterEnum: false
|
||||
AfterFunction: true
|
||||
AfterNamespace: true
|
||||
AfterObjCDeclaration: false
|
||||
AfterStruct: true
|
||||
AfterUnion: false
|
||||
AfterExternBlock: false
|
||||
BeforeCatch: false
|
||||
BeforeElse: true
|
||||
BeforeLambdaBody: true
|
||||
BeforeWhile: true
|
||||
IndentBraces: true
|
||||
SplitEmptyFunction: true
|
||||
SplitEmptyRecord: true
|
||||
SplitEmptyNamespace: true
|
||||
BreakAdjacentStringLiterals: true
|
||||
BreakAfterAttributes: Leave
|
||||
BreakAfterJavaFieldAnnotations: false
|
||||
BreakAfterReturnType: None
|
||||
BreakArrays: true
|
||||
BreakBeforeBinaryOperators: None
|
||||
BreakBeforeBraces: Linux
|
||||
BreakBeforeConceptDeclarations: Always
|
||||
BreakBeforeInlineASMColon: OnlyMultiline
|
||||
BreakBeforeTernaryOperators: true
|
||||
BreakConstructorInitializers: BeforeColon
|
||||
BreakFunctionDefinitionParameters: false
|
||||
BreakInheritanceList: BeforeColon
|
||||
BreakStringLiterals: true
|
||||
BreakTemplateDeclarations: MultiLine
|
||||
ColumnLimit: 80
|
||||
CommentPragmas: ""
|
||||
CompactNamespaces: false
|
||||
ConstructorInitializerIndentWidth: 4
|
||||
ContinuationIndentWidth: 4
|
||||
Cpp11BracedListStyle: true
|
||||
DerivePointerAlignment: true
|
||||
DisableFormat: false
|
||||
EmptyLineAfterAccessModifier: Always
|
||||
EmptyLineBeforeAccessModifier: LogicalBlock
|
||||
ExperimentalAutoDetectBinPacking: true
|
||||
FixNamespaceComments: true
|
||||
ForEachMacros:
|
||||
- foreach
|
||||
- Q_FOREACH
|
||||
- BOOST_FOREACH
|
||||
IfMacros:
|
||||
- KJ_IF_MAYBE
|
||||
IncludeBlocks: Preserve
|
||||
IncludeCategories:
|
||||
- Regex: ^"(llvm|llvm-c|clang|clang-c)/
|
||||
Priority: 2
|
||||
SortPriority: 0
|
||||
CaseSensitive: true
|
||||
- Regex: ^(<|"(gtest|gmock|isl|json)/)
|
||||
Priority: 3
|
||||
SortPriority: 0
|
||||
CaseSensitive: true
|
||||
- Regex: .*
|
||||
Priority: 1
|
||||
SortPriority: 0
|
||||
CaseSensitive: true
|
||||
IncludeIsMainRegex: (Test)?$
|
||||
IncludeIsMainSourceRegex: ""
|
||||
IndentAccessModifiers: true
|
||||
IndentCaseBlocks: true
|
||||
IndentCaseLabels: true
|
||||
IndentExternBlock: AfterExternBlock
|
||||
IndentGotoLabels: true
|
||||
IndentPPDirectives: None
|
||||
IndentRequiresClause: true
|
||||
IndentWidth: 4
|
||||
IndentWrappedFunctionNames: true
|
||||
InsertBraces: true
|
||||
InsertNewlineAtEOF: true
|
||||
InsertTrailingCommas: None
|
||||
IntegerLiteralSeparator:
|
||||
Binary: 0
|
||||
BinaryMinDigits: 0
|
||||
Decimal: 0
|
||||
DecimalMinDigits: 0
|
||||
Hex: 0
|
||||
HexMinDigits: 0
|
||||
JavaScriptQuotes: Leave
|
||||
JavaScriptWrapImports: true
|
||||
KeepEmptyLines:
|
||||
AtEndOfFile: false
|
||||
AtStartOfBlock: true
|
||||
AtStartOfFile: true
|
||||
LambdaBodyIndentation: Signature
|
||||
LineEnding: DeriveLF
|
||||
MacroBlockBegin: ""
|
||||
MacroBlockEnd: ""
|
||||
MainIncludeChar: AngleBracket
|
||||
MaxEmptyLinesToKeep: 1
|
||||
NamespaceIndentation: All
|
||||
ObjCBinPackProtocolList: Auto
|
||||
ObjCBlockIndentWidth: 2
|
||||
ObjCBreakBeforeNestedBlockParam: true
|
||||
ObjCSpaceAfterProperty: false
|
||||
ObjCSpaceBeforeProtocolList: true
|
||||
PPIndentWidth: -1
|
||||
PackConstructorInitializers: BinPack
|
||||
PenaltyBreakAssignment: 2
|
||||
PenaltyBreakBeforeFirstCallParameter: 19
|
||||
PenaltyBreakComment: 300
|
||||
PenaltyBreakFirstLessLess: 120
|
||||
PenaltyBreakOpenParenthesis: 0
|
||||
PenaltyBreakScopeResolution: 500
|
||||
PenaltyBreakString: 1000
|
||||
PenaltyBreakTemplateDeclaration: 10
|
||||
PenaltyExcessCharacter: 1000000
|
||||
PenaltyIndentedWhitespace: 0
|
||||
PenaltyReturnTypeOnItsOwnLine: 60
|
||||
PointerAlignment: Right
|
||||
QualifierAlignment: Leave
|
||||
ReferenceAlignment: Pointer
|
||||
ReflowComments: true
|
||||
RemoveBracesLLVM: false
|
||||
RemoveParentheses: Leave
|
||||
RemoveSemicolon: false
|
||||
RequiresClausePosition: OwnLine
|
||||
RequiresExpressionIndentation: OuterScope
|
||||
SeparateDefinitionBlocks: Leave
|
||||
ShortNamespaceLines: 1
|
||||
SkipMacroDefinitionBody: false
|
||||
SortIncludes: CaseSensitive
|
||||
SortJavaStaticImport: Before
|
||||
SortUsingDeclarations: LexicographicNumeric
|
||||
SpaceAfterCStyleCast: false
|
||||
SpaceAfterLogicalNot: false
|
||||
SpaceAfterTemplateKeyword: true
|
||||
SpaceAroundPointerQualifiers: Default
|
||||
SpaceBeforeAssignmentOperators: true
|
||||
SpaceBeforeCaseColon: false
|
||||
SpaceBeforeCpp11BracedList: false
|
||||
SpaceBeforeCtorInitializerColon: true
|
||||
SpaceBeforeInheritanceColon: true
|
||||
SpaceBeforeJsonColon: false
|
||||
SpaceBeforeParens: ControlStatements
|
||||
SpaceBeforeParensOptions:
|
||||
AfterControlStatements: true
|
||||
AfterForeachMacros: true
|
||||
AfterFunctionDeclarationName: false
|
||||
AfterFunctionDefinitionName: false
|
||||
AfterIfMacros: true
|
||||
AfterOverloadedOperator: false
|
||||
AfterPlacementOperator: true
|
||||
AfterRequiresInClause: false
|
||||
AfterRequiresInExpression: false
|
||||
BeforeNonEmptyParentheses: false
|
||||
SpaceBeforeRangeBasedForLoopColon: true
|
||||
SpaceBeforeSquareBrackets: false
|
||||
SpaceInEmptyBlock: false
|
||||
SpacesBeforeTrailingComments: 1
|
||||
SpacesInAngles: Never
|
||||
SpacesInContainerLiterals: true
|
||||
SpacesInLineCommentPrefix:
|
||||
Minimum: 1
|
||||
Maximum: -1
|
||||
SpacesInParens: Never
|
||||
SpacesInParensOptions:
|
||||
ExceptDoubleParentheses: false
|
||||
InConditionalStatements: false
|
||||
InCStyleCasts: false
|
||||
InEmptyParentheses: false
|
||||
Other: false
|
||||
SpacesInSquareBrackets: false
|
||||
Standard: Latest
|
||||
StatementAttributeLikeMacros:
|
||||
- Q_EMIT
|
||||
StatementMacros:
|
||||
- Q_UNUSED
|
||||
- QT_REQUIRE_VERSION
|
||||
TabWidth: 4
|
||||
TableGenBreakInsideDAGArg: DontBreak
|
||||
UseTab: Always
|
||||
VerilogBreakBetweenInstancePorts: true
|
||||
WhitespaceSensitiveMacros:
|
||||
- BOOST_PP_STRINGIZE
|
||||
- CF_SWIFT_NAME
|
||||
- NS_SWIFT_NAME
|
||||
- PP_STRINGIZE
|
||||
- STRINGIZE
|
||||
@@ -1,7 +0,0 @@
|
||||
.git
|
||||
build*
|
||||
dist
|
||||
release
|
||||
EchoionWeb/frontend/node_modules
|
||||
EchoionWeb/frontend/web-dist
|
||||
docs
|
||||
@@ -1,193 +0,0 @@
|
||||
# Echoion releases on Gitea
|
||||
|
||||
Echoion release builds run only through `scripts/release.sh`, whose default
|
||||
mode builds, tests, validates, and packages inside
|
||||
`containers/release.Dockerfile`. The runner host only checks out sources and
|
||||
controls Docker; the workflow never starts `echoiond`.
|
||||
|
||||
## One-time Gitea setup
|
||||
|
||||
The workflows target the standard `ubuntu-24.04` label advertised by a default
|
||||
Gitea runner. No custom runner label is required. Use one trusted Linux AMD64
|
||||
runner with capacity set to one so release and feed writes remain serialized
|
||||
on Gitea versions that do not implement workflow `concurrency`. The job image
|
||||
needs Bash, Git with SSH-signature support, OpenSSH client tools, Python 3.10
|
||||
or newer, OpenSSL with Ed25519 support, coreutils, the Docker CLI, and access
|
||||
to a Docker daemon. The release builder itself remains containerized.
|
||||
|
||||
Every workflow starts by running `docker version` and `docker info`. These
|
||||
commands verify both the Docker client in the `ubuntu-24.04` job image and
|
||||
access to the daemon before checkout, secrets, or a long release build are
|
||||
used. A runner installed as a container must have the host socket mounted:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
runner:
|
||||
volumes:
|
||||
- ./data:/data
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
```
|
||||
|
||||
Leave `container.docker_host` at its generated default (`""`) so `act_runner`
|
||||
passes the detected Docker endpoint to job containers. Do not set it to `-`,
|
||||
which explicitly prevents that endpoint from being mounted. Restart the runner
|
||||
after changing its configuration. `scripts/lib/docker-daemon-path.sh` detects
|
||||
when commands run inside the job container and translates checked-out paths
|
||||
through that container's Docker mount table. The release wrapper and
|
||||
control-plane tests both use it because bind mount paths passed to the socket
|
||||
are resolved by the runner host daemon, not inside the Actions job container.
|
||||
|
||||
The SSH checkout steps pin the current `git.faumaray.ru` RSA host key. Its
|
||||
verified fingerprint is
|
||||
`SHA256:fugBYnqAnqmTLsGpafVgQF9gPQzJqps7uHvs48blg2A`. If the Gitea SSH host key
|
||||
is intentionally rotated, verify the new fingerprint through an independent
|
||||
administrator channel and update `ssh-known-hosts` in all three workflows.
|
||||
Never work around a rotation by disabling strict host-key checking.
|
||||
|
||||
The Docker-capable runner executes only protected `main` pushes, manual runs,
|
||||
scheduled nightlies, and signed release tags. The container CI workflow does
|
||||
not run for pull requests because contributor-controlled scripts must not
|
||||
receive a privileged Docker socket or the private-submodule checkout key. If
|
||||
pre-merge CI is required, register a separate ephemeral `echoion-pr` runner
|
||||
without release secrets or host-level Docker access and give it a dedicated
|
||||
workflow. A global runner such as the default installation shown in Gitea must
|
||||
only serve repositories you trust: a workflow with Docker-daemon access can
|
||||
control the runner host.
|
||||
|
||||
Enable Actions and add these repository secrets:
|
||||
|
||||
| Secret | Purpose |
|
||||
| --- | --- |
|
||||
| `RELEASE_CHECKOUT_SSH_KEY` | Read-only deploy key that can clone every private nested repository in `.gitmodules`. |
|
||||
| `RELEASE_BOT_TOKEN` | PAT owned by a dedicated bot, limited to writing releases, tags, and the `release-feed` branch in this repository. |
|
||||
| `RELEASE_TAG_ALLOWED_SIGNERS` | Complete OpenSSH `allowed_signers` lines for maintainers allowed to publish `v*` tags. |
|
||||
| `RELEASE_FEED_ED25519_PRIVATE_KEY` | PEM private key matching `release-keys/echoion-release-2026-07.pub.pem`. Preserve its newlines. |
|
||||
|
||||
The release PAT must not be shared with checkout of nested repositories. The
|
||||
feed signing key must not be stored in Git, runner images, Actions variables,
|
||||
or release assets.
|
||||
|
||||
Create an orphan `release-feed` branch containing a tracked `feeds/`
|
||||
directory, then protect it so only the release bot can push. Protect the `v*`
|
||||
tag pattern so only the release maintainers represented by
|
||||
`RELEASE_TAG_ALLOWED_SIGNERS` can create, update, or delete matching tags. The
|
||||
workflow requires the exact `v*` rule to have an explicit non-empty user or
|
||||
team allowlist. Configure it under repository **Settings → Tags → Protected
|
||||
tags**; a similar pattern such as `v*.*` does not satisfy the release check.
|
||||
Gitea uses the same allowlist for tag creation and later tag changes; when
|
||||
immutable release tags are required, add a server-side pre-receive policy that
|
||||
rejects updates and deletion after creation. Protect `main` in the normal way.
|
||||
|
||||
The updater feed URL is:
|
||||
|
||||
```text
|
||||
https://<gitea>/<owner>/<repo>/raw/branch/release-feed/feeds/echoion-runtime.json
|
||||
```
|
||||
|
||||
The embedded updater trust configuration is represented by
|
||||
`release-keys/official-update-keys.json`. `scripts/release.sh` validates and
|
||||
embeds that JSON automatically. Release workflows also pass the HTTPS
|
||||
`release-feed` branch URL through `--official-update-feed-url`, so a fresh
|
||||
installation has a signed official source without operator-side duplication.
|
||||
|
||||
## Stable and beta releases
|
||||
|
||||
Create an annotated SSH-signed tag. A version without a prerelease suffix goes
|
||||
to `stable`; any strict SemVer prerelease goes to `beta`.
|
||||
|
||||
```bash
|
||||
git config gpg.format ssh
|
||||
git config user.signingkey ~/.ssh/echoion-release-maintainer
|
||||
git tag -s -a v1.2.3 -m 'Echoion 1.2.3'
|
||||
test "$(git cat-file -t refs/tags/v1.2.3)" = tag
|
||||
git push origin v1.2.3
|
||||
```
|
||||
|
||||
The private-key path works without an SSH agent. A `.pub` path may be used
|
||||
instead when its matching private key is already loaded in `ssh-agent`.
|
||||
|
||||
`.gitea/workflows/release.yml` rejects a lightweight tag, a non-SSH
|
||||
signature, an untrusted signer, a repository without the exact `v*` protected
|
||||
tag rule and explicit allowlist, a non-SemVer name, an event object unrelated
|
||||
to the tag, or a checkout whose commit differs from the signed tag target.
|
||||
Release notes contain the signed tag subject and body but not its SSH signature
|
||||
armor.
|
||||
|
||||
The workflow creates or resumes a draft, replaces incomplete draft assets,
|
||||
uploads every file in `dist/`, downloads every asset through Gitea, checks
|
||||
its size and SHA-256, and only then publishes. A rerun against an already
|
||||
published release is read-only and succeeds only when all remote assets still
|
||||
match. The signed aggregate feed is committed after release publication; a
|
||||
feed failure can therefore be retried without replacing a published release.
|
||||
|
||||
## Nightly releases
|
||||
|
||||
`.gitea/workflows/nightly.yml` runs at 02:17 UTC and can also be dispatched
|
||||
manually. The highest published `vMAJOR.MINOR.PATCH` release supplies the next
|
||||
patch as `MAJOR.MINOR.(PATCH+1)-nightly.YYYYMMDD.RUN_NUMBER`. With no published
|
||||
semantic release, nightlies use the root CMake
|
||||
`project(Echoion VERSION x.y.z)` value without incrementing it. Drafts, failed
|
||||
publications, and `nightly-*` releases do not affect the base. Nightlies use the
|
||||
`nightly` channel, publish as prereleases, and keep the newest 14 Gitea
|
||||
releases. The aggregate feed also keeps the newest 14 distinct nightly versions
|
||||
while retaining stable and beta records. Gitea materializes a missing
|
||||
`nightly-*` Git tag only when the download-verified draft is published; the
|
||||
publisher then verifies its commit immediately and never moves an existing tag
|
||||
whose target differs. Stable and beta publishing require their signed tag to
|
||||
exist before creating a draft. If `nightly-*` is protected separately, allow
|
||||
the release bot to create and delete it.
|
||||
|
||||
Every aggregate envelope expires 45 days after generation. Scheduled
|
||||
nightlies normally refresh it daily. Alert when the feed branch has not
|
||||
advanced for more than seven days, and treat 30 days without a successful
|
||||
signing run as urgent.
|
||||
|
||||
## Feed key custody and rotation
|
||||
|
||||
The active public key id is `echoion-release-2026-07`. To rotate, generate the
|
||||
private key on a trusted operator machine:
|
||||
|
||||
```bash
|
||||
umask 077
|
||||
openssl genpkey -algorithm ED25519 -out echoion-release-YYYY-MM.pem
|
||||
openssl pkey -in echoion-release-YYYY-MM.pem -pubout \
|
||||
-out echoion-release-YYYY-MM.pub.pem
|
||||
```
|
||||
|
||||
The PEM public key contains an RFC 8410 SubjectPublicKeyInfo wrapper. The
|
||||
`ed25519` field in `release-keys/official-update-keys.json` must instead contain
|
||||
the standard Base64 encoding of only the raw 32-byte public key. Derive that
|
||||
value with:
|
||||
|
||||
```bash
|
||||
openssl pkey -pubin -in echoion-release-YYYY-MM.pub.pem -outform DER |
|
||||
tail -c 32 |
|
||||
base64 -w0
|
||||
printf '\n'
|
||||
```
|
||||
|
||||
Add the new public key to official builds before signing any feed with it.
|
||||
Keep the old public key embedded for at least one full update lifetime. During
|
||||
the first signing run with the new key, pass each prior envelope key explicitly
|
||||
to `aggregate_update_feed.py` as
|
||||
`--trusted-existing-key OLD_KEY_ID=OLD_PUBLIC_KEY_PATH`; this permits only
|
||||
verification of the old envelope and never selects the old key for signing.
|
||||
Update the signing key id and public-key paths in both release workflows, add
|
||||
the old-key verification argument while an old envelope may exist, and replace
|
||||
the private-key secret. The merger verifies the newly generated signature
|
||||
against the new committed public key before writing either output. Never print
|
||||
the private key or pass it as a command-line argument.
|
||||
|
||||
## Recovery rules
|
||||
|
||||
- A failed build creates no Gitea release.
|
||||
- A failed upload leaves a draft. Rerun the same workflow to replace the
|
||||
partial draft assets.
|
||||
- A failed verification never publishes the draft.
|
||||
- A published release with mismatched assets is immutable; investigate and
|
||||
create a new version instead of replacing it.
|
||||
- A failed feed push leaves the published release available but undiscoverable
|
||||
to auto-update. Rerun the workflow; publication verification is idempotent
|
||||
and the feed step will run again.
|
||||
- Never edit `release-feed` manually. The merger verifies the existing
|
||||
Ed25519 envelope before using any prior entries.
|
||||
@@ -1,3 +0,0 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MCowBQYDK2VwAyEAqD97/GZ6BJaeQpg6shajRcNhwMzvNZ3SvkQtAu6pxEw=
|
||||
-----END PUBLIC KEY-----
|
||||
@@ -1,6 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": "echoion-release-2026-07",
|
||||
"ed25519": "qD97/GZ6BJaeQpg6shajRcNhwMzvNZ3SvkQtAu6pxEw="
|
||||
}
|
||||
]
|
||||
@@ -1,59 +0,0 @@
|
||||
name: Container CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
release-build:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Verify the Docker-capable Gitea runner
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(uname -s)" = Linux
|
||||
command -v docker
|
||||
docker version
|
||||
docker info
|
||||
|
||||
- name: Check out source and nested repositories
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
|
||||
ssh-user: gitea
|
||||
ssh-known-hosts: >-
|
||||
git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
|
||||
persist-credentials: false
|
||||
|
||||
- name: Build, test, and package without starting Echoion
|
||||
env:
|
||||
CI_VERSION: 0.0.0-ci.${{ gitea.run_number }}.${{ gitea.run_attempt }}
|
||||
run: |
|
||||
set -eu
|
||||
scripts/release.sh --version "$CI_VERSION"
|
||||
|
||||
- name: Test release control-plane scripts
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
bash scripts/tests/test-gitea-tag-verification.sh
|
||||
. scripts/lib/docker-daemon-path.sh
|
||||
docker_workspace=$(docker_daemon_path "$PWD")
|
||||
docker run --rm --network none \
|
||||
--volume "$docker_workspace:/workspace:ro" \
|
||||
--workdir /workspace \
|
||||
echoion-release-builder:gcc-16.1.0 \
|
||||
python3 scripts/tests/test_aggregate_update_feed.py
|
||||
docker run --rm --network none \
|
||||
--volume "$docker_workspace:/workspace:ro" \
|
||||
--workdir /workspace \
|
||||
echoion-release-builder:gcc-16.1.0 \
|
||||
python3 scripts/tests/test_gitea_release.py
|
||||
@@ -1,184 +0,0 @@
|
||||
name: Nightly release
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '17 2 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish-nightly:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Verify the Docker-capable Gitea runner
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(uname -s)" = Linux
|
||||
command -v docker
|
||||
docker version
|
||||
docker info
|
||||
|
||||
- name: Check out main and nested repositories
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
|
||||
ssh-user: gitea
|
||||
ssh-known-hosts: >-
|
||||
git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
|
||||
persist-credentials: false
|
||||
|
||||
- name: Derive the nightly identity
|
||||
shell: bash
|
||||
env:
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
API_URL: ${{ gitea.api_url }}
|
||||
SERVER_URL: ${{ gitea.server_url }}
|
||||
REPOSITORY: ${{ gitea.repository }}
|
||||
RUN_NUMBER: ${{ gitea.run_number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
date_id=$(date -u +%Y%m%d)
|
||||
owner=${REPOSITORY%%/*}
|
||||
repo=${REPOSITORY#*/}
|
||||
version=$(
|
||||
python3 scripts/gitea_release.py \
|
||||
--api-url "$API_URL" \
|
||||
derive-nightly-version \
|
||||
--owner "$owner" \
|
||||
--repo "$repo" \
|
||||
--cmake-file CMakeLists.txt \
|
||||
--date-id "$date_id" \
|
||||
--run-number "$RUN_NUMBER"
|
||||
)
|
||||
tag="nightly-${date_id}-${RUN_NUMBER}"
|
||||
artifact="echoion-${version}-linux-x86_64.tar.zst"
|
||||
url="${SERVER_URL}/${REPOSITORY}/releases/download/${tag}/${artifact}"
|
||||
feed_url="${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/echoion-runtime.json"
|
||||
python3 scripts/validate-semver.py "$version"
|
||||
{
|
||||
printf 'RELEASE_TAG=%s\n' "$tag"
|
||||
printf 'RELEASE_VERSION=%s\n' "$version"
|
||||
printf 'RELEASE_CHANNEL=nightly\n'
|
||||
printf 'RELEASE_PRERELEASE=true\n'
|
||||
printf 'RELEASE_ARTIFACT_URL=%s\n' "$url"
|
||||
printf 'RELEASE_FEED_URL=%s\n' "$feed_url"
|
||||
printf 'RELEASE_TARGET=%s\n' "$(git rev-parse HEAD)"
|
||||
} >>"$GITHUB_ENV"
|
||||
|
||||
- name: Build and test the dynamic nightly in Docker
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
scripts/release.sh \
|
||||
--version "$RELEASE_VERSION" \
|
||||
--update-url "$RELEASE_ARTIFACT_URL" \
|
||||
--official-update-feed-url "$RELEASE_FEED_URL" \
|
||||
--update-channel nightly \
|
||||
--update-valid-days 45
|
||||
{
|
||||
printf 'Automated nightly from %s.\n\n' "$RELEASE_TARGET"
|
||||
printf 'This prerelease is retained for fourteen nightly runs.\n'
|
||||
} >"$RUNNER_TEMP/release-notes.md"
|
||||
|
||||
- name: Create draft, upload, download-verify, and publish
|
||||
shell: bash
|
||||
env:
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
API_URL: ${{ gitea.api_url }}
|
||||
REPOSITORY: ${{ gitea.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
owner=${REPOSITORY%%/*}
|
||||
repo=${REPOSITORY#*/}
|
||||
python3 scripts/gitea_release.py \
|
||||
--api-url "$API_URL" \
|
||||
publish \
|
||||
--owner "$owner" \
|
||||
--repo "$repo" \
|
||||
--tag "$RELEASE_TAG" \
|
||||
--target "$RELEASE_TARGET" \
|
||||
--name "Echoion nightly $RELEASE_VERSION" \
|
||||
--body-file "$RUNNER_TEMP/release-notes.md" \
|
||||
--artifacts dist \
|
||||
--allow-missing-draft-tag \
|
||||
--prerelease
|
||||
|
||||
- name: Retain fourteen Gitea nightly releases
|
||||
shell: bash
|
||||
env:
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
API_URL: ${{ gitea.api_url }}
|
||||
REPOSITORY: ${{ gitea.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
owner=${REPOSITORY%%/*}
|
||||
repo=${REPOSITORY#*/}
|
||||
python3 scripts/gitea_release.py \
|
||||
--api-url "$API_URL" \
|
||||
prune-nightlies \
|
||||
--owner "$owner" \
|
||||
--repo "$repo" \
|
||||
--tag-prefix nightly- \
|
||||
--keep 14 \
|
||||
--protect-tag "$RELEASE_TAG"
|
||||
|
||||
- name: Check out the aggregate feed branch
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
ref: release-feed
|
||||
path: feed-state
|
||||
token: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Sign and push the aggregate feed last
|
||||
shell: bash
|
||||
env:
|
||||
FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
key="$RUNNER_TEMP/echoion-release-2026-07.pem"
|
||||
payload="$RUNNER_TEMP/echoion-runtime.payload.json"
|
||||
envelope="$RUNNER_TEMP/echoion-runtime.json"
|
||||
trap 'rm -f -- "$key" "$payload" "$envelope"' EXIT
|
||||
umask 077
|
||||
printf '%s\n' "$FEED_PRIVATE_KEY" >"$key"
|
||||
chmod 0600 "$key"
|
||||
openssl pkey -in "$key" -noout
|
||||
mkdir -p feed-state/feeds
|
||||
existing=()
|
||||
if [[ -s feed-state/feeds/echoion-runtime.json ]]; then
|
||||
existing+=(
|
||||
--existing-envelope feed-state/feeds/echoion-runtime.json
|
||||
)
|
||||
fi
|
||||
python3 scripts/aggregate_update_feed.py \
|
||||
--new-payload \
|
||||
"dist/echoion-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \
|
||||
"${existing[@]}" \
|
||||
--public-key \
|
||||
.gitea/release-keys/echoion-release-2026-07.pub.pem \
|
||||
--private-key "$key" \
|
||||
--key-id echoion-release-2026-07 \
|
||||
--valid-days 45 \
|
||||
--nightly-retention 14 \
|
||||
--output-payload "$payload" \
|
||||
--output-envelope "$envelope"
|
||||
install -m 0644 "$payload" \
|
||||
feed-state/feeds/echoion-runtime.payload.json
|
||||
install -m 0644 "$envelope" feed-state/feeds/echoion-runtime.json
|
||||
git -C feed-state config user.name 'Echoion Release Bot'
|
||||
git -C feed-state config user.email 'release-bot@echoion.invalid'
|
||||
git -C feed-state add \
|
||||
feeds/echoion-runtime.json feeds/echoion-runtime.payload.json
|
||||
if git -C feed-state diff --cached --quiet; then
|
||||
exit 0
|
||||
fi
|
||||
git -C feed-state commit -m \
|
||||
"Feed: nightly ${RELEASE_VERSION}"
|
||||
git -C feed-state push origin HEAD:release-feed
|
||||
@@ -1,192 +0,0 @@
|
||||
name: Signed release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v*
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Verify the Docker-capable Gitea runner
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(uname -s)" = Linux
|
||||
command -v docker
|
||||
docker version
|
||||
docker info
|
||||
|
||||
- name: Check out the signed tag
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
ref: ${{ gitea.ref }}
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
|
||||
ssh-user: gitea
|
||||
ssh-known-hosts: >-
|
||||
git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
|
||||
persist-credentials: false
|
||||
|
||||
- name: Verify protected annotated SSH tag
|
||||
shell: bash
|
||||
env:
|
||||
TAG: ${{ gitea.ref_name }}
|
||||
EXPECTED_EVENT_SHA: ${{ gitea.sha }}
|
||||
EXPECTED_REF: ${{ gitea.ref }}
|
||||
EXPECTED_REF_TYPE: ${{ gitea.ref_type }}
|
||||
TAG_ALLOWED_SIGNERS: ${{ secrets.RELEASE_TAG_ALLOWED_SIGNERS }}
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
API_URL: ${{ gitea.api_url }}
|
||||
REPOSITORY: ${{ gitea.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$EXPECTED_REF_TYPE" = tag
|
||||
test "$EXPECTED_REF" = "refs/tags/$TAG"
|
||||
allowed_signers="$RUNNER_TEMP/echoion-release-allowed-signers"
|
||||
trap 'rm -f -- "$allowed_signers"' EXIT
|
||||
umask 077
|
||||
printf '%s\n' "$TAG_ALLOWED_SIGNERS" >"$allowed_signers"
|
||||
test -s "$allowed_signers"
|
||||
target_commit=$(
|
||||
scripts/verify-gitea-release-tag.sh \
|
||||
--tag "$TAG" \
|
||||
--event-sha "$EXPECTED_EVENT_SHA" \
|
||||
--allowed-signers "$allowed_signers" \
|
||||
--notes-output "$RUNNER_TEMP/release-notes.md"
|
||||
)
|
||||
printf 'RELEASE_TARGET=%s\n' "$target_commit" >>"$GITHUB_ENV"
|
||||
owner=${REPOSITORY%%/*}
|
||||
repo=${REPOSITORY#*/}
|
||||
python3 scripts/gitea_release.py \
|
||||
--api-url "$API_URL" \
|
||||
verify-tag-protection \
|
||||
--owner "$owner" \
|
||||
--repo "$repo" \
|
||||
--required-pattern 'v*'
|
||||
|
||||
- name: Derive the stable or beta release
|
||||
shell: bash
|
||||
env:
|
||||
TAG: ${{ gitea.ref_name }}
|
||||
SERVER_URL: ${{ gitea.server_url }}
|
||||
REPOSITORY: ${{ gitea.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version=${TAG#v}
|
||||
test "$version" != "$TAG"
|
||||
python3 scripts/validate-semver.py "$version"
|
||||
channel=stable
|
||||
prerelease=false
|
||||
if [[ "$version" == *-* ]]; then
|
||||
channel=beta
|
||||
prerelease=true
|
||||
fi
|
||||
artifact="echoion-${version}-linux-x86_64.tar.zst"
|
||||
url="${SERVER_URL}/${REPOSITORY}/releases/download/${TAG}/${artifact}"
|
||||
feed_url="${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/echoion-runtime.json"
|
||||
{
|
||||
printf 'RELEASE_TAG=%s\n' "$TAG"
|
||||
printf 'RELEASE_VERSION=%s\n' "$version"
|
||||
printf 'RELEASE_CHANNEL=%s\n' "$channel"
|
||||
printf 'RELEASE_PRERELEASE=%s\n' "$prerelease"
|
||||
printf 'RELEASE_ARTIFACT_URL=%s\n' "$url"
|
||||
printf 'RELEASE_FEED_URL=%s\n' "$feed_url"
|
||||
} >>"$GITHUB_ENV"
|
||||
|
||||
- name: Build and test the dynamic release in Docker
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
scripts/release.sh \
|
||||
--version "$RELEASE_VERSION" \
|
||||
--update-url "$RELEASE_ARTIFACT_URL" \
|
||||
--official-update-feed-url "$RELEASE_FEED_URL" \
|
||||
--update-channel "$RELEASE_CHANNEL" \
|
||||
--update-valid-days 45
|
||||
|
||||
- name: Create draft, upload, download-verify, and publish
|
||||
shell: bash
|
||||
env:
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
API_URL: ${{ gitea.api_url }}
|
||||
REPOSITORY: ${{ gitea.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
owner=${REPOSITORY%%/*}
|
||||
repo=${REPOSITORY#*/}
|
||||
prerelease=()
|
||||
if [[ "$RELEASE_PRERELEASE" = true ]]; then
|
||||
prerelease+=(--prerelease)
|
||||
fi
|
||||
python3 scripts/gitea_release.py \
|
||||
--api-url "$API_URL" \
|
||||
publish \
|
||||
--owner "$owner" \
|
||||
--repo "$repo" \
|
||||
--tag "$RELEASE_TAG" \
|
||||
--target "$RELEASE_TARGET" \
|
||||
--name "Echoion $RELEASE_VERSION" \
|
||||
--body-file "$RUNNER_TEMP/release-notes.md" \
|
||||
--artifacts dist \
|
||||
"${prerelease[@]}"
|
||||
|
||||
- name: Check out the aggregate feed branch
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
ref: release-feed
|
||||
path: feed-state
|
||||
token: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Sign and push the aggregate feed last
|
||||
shell: bash
|
||||
env:
|
||||
FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
key="$RUNNER_TEMP/echoion-release-2026-07.pem"
|
||||
payload="$RUNNER_TEMP/echoion-runtime.payload.json"
|
||||
envelope="$RUNNER_TEMP/echoion-runtime.json"
|
||||
trap 'rm -f -- "$key" "$payload" "$envelope"' EXIT
|
||||
umask 077
|
||||
printf '%s\n' "$FEED_PRIVATE_KEY" >"$key"
|
||||
chmod 0600 "$key"
|
||||
openssl pkey -in "$key" -noout
|
||||
mkdir -p feed-state/feeds
|
||||
existing=()
|
||||
if [[ -s feed-state/feeds/echoion-runtime.json ]]; then
|
||||
existing+=(
|
||||
--existing-envelope feed-state/feeds/echoion-runtime.json
|
||||
)
|
||||
fi
|
||||
python3 scripts/aggregate_update_feed.py \
|
||||
--new-payload \
|
||||
"dist/echoion-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \
|
||||
"${existing[@]}" \
|
||||
--public-key \
|
||||
.gitea/release-keys/echoion-release-2026-07.pub.pem \
|
||||
--private-key "$key" \
|
||||
--key-id echoion-release-2026-07 \
|
||||
--valid-days 45 \
|
||||
--nightly-retention 14 \
|
||||
--output-payload "$payload" \
|
||||
--output-envelope "$envelope"
|
||||
install -m 0644 "$payload" \
|
||||
feed-state/feeds/echoion-runtime.payload.json
|
||||
install -m 0644 "$envelope" feed-state/feeds/echoion-runtime.json
|
||||
git -C feed-state config user.name 'Echoion Release Bot'
|
||||
git -C feed-state config user.email 'release-bot@echoion.invalid'
|
||||
git -C feed-state add \
|
||||
feeds/echoion-runtime.json feeds/echoion-runtime.payload.json
|
||||
if git -C feed-state diff --cached --quiet; then
|
||||
exit 0
|
||||
fi
|
||||
git -C feed-state commit -m \
|
||||
"Feed: ${RELEASE_CHANNEL} ${RELEASE_VERSION}"
|
||||
git -C feed-state push origin HEAD:release-feed
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
*build*
|
||||
!EchoionStandalone/tests/test_update_build_defaults.cpp
|
||||
release
|
||||
/dist/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.claude
|
||||
.cache
|
||||
.idea
|
||||
AGENTS.md
|
||||
.vscode
|
||||
.opencode/
|
||||
@@ -1,58 +0,0 @@
|
||||
# GitLab CI for Echoion.
|
||||
#
|
||||
# Requires a runner whose image provides the toolchain the project builds
|
||||
# with: GCC 16+ (C++26 with experimental reflection, -freflection), CMake
|
||||
# 4.0+, and the system libraries FFmpeg, SQLite3, OpenSSL, TBB, Qt6 and a
|
||||
# system Boost (>= 1.87) that matches VoidLibrary — a second, vendored Boost
|
||||
# in the same process corrupts URL parsing, so the system copy must be used.
|
||||
# Set the image on the runner or override `image:` below to that container.
|
||||
|
||||
stages:
|
||||
- build
|
||||
- test
|
||||
- package
|
||||
|
||||
variables:
|
||||
GIT_SUBMODULE_STRATEGY: recursive
|
||||
BUILD_DIR: build
|
||||
CMAKE_BUILD_TYPE: RelWithDebInfo
|
||||
|
||||
# Reuse the CMake build tree between jobs on the same ref to skip cold
|
||||
# reconfigure/rebuild.
|
||||
cache:
|
||||
key: "$CI_COMMIT_REF_SLUG"
|
||||
paths:
|
||||
- build/
|
||||
|
||||
build:
|
||||
stage: build
|
||||
script:
|
||||
- cmake -S . -B "$BUILD_DIR" -DCMAKE_BUILD_TYPE="$CMAKE_BUILD_TYPE" -DBUILD_TESTS=ON
|
||||
- cmake --build "$BUILD_DIR" -j "$(nproc)"
|
||||
artifacts:
|
||||
paths:
|
||||
- build/plugins/echoion_plugin.so
|
||||
- build/bin/EchoionDesktop
|
||||
- build/lib/
|
||||
expire_in: 1 week
|
||||
|
||||
test:
|
||||
stage: test
|
||||
needs: ["build"]
|
||||
script:
|
||||
- ctest --test-dir "$BUILD_DIR" --output-on-failure
|
||||
|
||||
# Produce distributable packages only for tagged releases.
|
||||
package:
|
||||
stage: package
|
||||
needs: ["build", "test"]
|
||||
rules:
|
||||
- if: '$CI_COMMIT_TAG'
|
||||
script:
|
||||
- cd "$BUILD_DIR"
|
||||
- cpack -G "TGZ;DEB"
|
||||
artifacts:
|
||||
paths:
|
||||
- build/*.tar.gz
|
||||
- build/*.deb
|
||||
expire_in: 1 month
|
||||
@@ -1,9 +0,0 @@
|
||||
[submodule "EchoionApi"]
|
||||
path = EchoionApi
|
||||
url = ssh://gitea@git.faumaray.ru/void/echoionapi.git
|
||||
[submodule "EchoionCore"]
|
||||
path = EchoionCore
|
||||
url = ssh://gitea@git.faumaray.ru/void/echoioncore.git
|
||||
[submodule "EchoionDesktop"]
|
||||
path = EchoionDesktop
|
||||
url = ssh://gitea@git.faumaray.ru/void/echoiondesktop.git
|
||||
@@ -1,646 +0,0 @@
|
||||
# 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?
|
||||
@@ -1,513 +0,0 @@
|
||||
# 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!
|
||||
@@ -1,76 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to Echoion are documented here. This project adheres to
|
||||
[Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [1.0.0] — 2026-07-04
|
||||
|
||||
The first public release of **Echoion**, a modern, gapless music bot for
|
||||
TeamSpeak. This entry describes the product as shipped, not an incremental
|
||||
diff.
|
||||
|
||||
### Playback
|
||||
|
||||
- **Gapless engine with crossfade.** A dual-decoder pipeline pre-warms the
|
||||
next track while the current one plays, so track boundaries are seamless;
|
||||
an optional crossfade (`bot.crossfade`) blends the transition.
|
||||
- **High-quality audio.** 192 kHz stereo internal pipeline feeding
|
||||
TeamSpeak's native audio system on a steady 20 ms cadence.
|
||||
- **Loudness normalization.** An optional slow AGC evens out quiet and loud
|
||||
tracks (`features.normalizeLoudness`, `features.targetLoudnessDb`).
|
||||
- **Full transport controls.** Play, pause, resume, stop, skip, seek, volume,
|
||||
shuffle and repeat.
|
||||
- **SOCKS5-aware streaming.** Under a SOCKS5 proxy, IP-locked YouTube CDN
|
||||
URLs are transparently downloaded through the proxy (via yt-dlp) and played
|
||||
from a local file, so geo-blocked deployments still get audio.
|
||||
|
||||
### Catalogs & source routing
|
||||
|
||||
- **YouTube** via a native innertube player client (fastest path, one HTTP
|
||||
POST) with yt-dlp as the resolver/fallback and for search.
|
||||
- **Yandex Music** (native, unofficial API) — full tracks with a Plus OAuth
|
||||
token; album, playlist and track URLs, plus in-catalog search.
|
||||
- **Direct audio URLs / radio streams**, plus the wide range of yt-dlp
|
||||
extractors (SoundCloud, Bandcamp, VK, …) for non-YouTube links.
|
||||
- **`SourceRouter`** chains the sources with per-source failure cooldowns,
|
||||
**hedged resolution** (a slow source is raced by the next candidate after
|
||||
300 ms; first success wins), and a stream-URL cache.
|
||||
|
||||
### Commands
|
||||
|
||||
- **Play** — `!play` (searches YouTube + Yandex and lets you `!select`),
|
||||
`!pyt` (YouTube only), `!pya` (Yandex only); a bare URL plays directly.
|
||||
- **Search** — `!search` (both catalogs), `!youtube`/`!yb` (YouTube),
|
||||
`!yandex`/`!ya` (Yandex).
|
||||
- **Radio / autoplay** — `!radio` / `!autoplay [on|off]` keeps the music
|
||||
going with related tracks (YouTube radio mix or Yandex similar tracks) when
|
||||
the queue runs dry; the choice is persisted across restarts.
|
||||
- **Queue & info** — `!queue`, `!np`, `!skip`, `!remove`, `!move`, `!clear`,
|
||||
`!shuffle`, `!repeat`, `!seek`, `!volume`.
|
||||
- **History, favorites, stats** — `!history`, `!fav`, `!stats`, rendered with
|
||||
short links for YouTube tracks.
|
||||
- **Subscriptions** — `!subscribe` / `!unsubscribe` / `!subscribers` for
|
||||
per-user whisper delivery.
|
||||
- **Admin** — `!announce` broadcasts a message to each subscriber exactly
|
||||
once (restart-safe); `!reload` / `!reloadconfig` hot-reload the bot.
|
||||
- **Grouped help** — `!help` renders collapsible sections, with the play and
|
||||
search command families grouped together.
|
||||
|
||||
### Persistence
|
||||
|
||||
- SQLite-backed history, favorites, playlists, subscriptions and a generic
|
||||
key/value store; announcements and the autoplay toggle survive restarts.
|
||||
|
||||
### Platform
|
||||
|
||||
- TeamSpeak 3 / 6 plugin plus a Qt6 desktop client.
|
||||
- **Hot reload** of the core without disconnecting from the server.
|
||||
- HTTP and SOCKS5 proxy support applied across every outbound client.
|
||||
- JSON configuration with hot-reload across the plugin boundary.
|
||||
|
||||
### Build & packaging
|
||||
|
||||
- C++26 (GCC 16+, experimental reflection), CMake 4.0+, CPack packaging
|
||||
(TGZ / DEB / RPM on Linux).
|
||||
|
||||
[1.0.0]: https://git.faumaray.ru/echoion/echoion/-/releases/1.0.0
|
||||
-427
@@ -1,427 +0,0 @@
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(Echoion VERSION 1.0.7 LANGUAGES CXX)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
include(cmake/DependencyLock.cmake)
|
||||
|
||||
# Default to a Release build when the developer/CI did not pick a config.
|
||||
# Without this, single-config generators leave CMAKE_BUILD_TYPE empty and GCC
|
||||
# falls back to -O0, so "production" builds shipped unoptimised. Set this before
|
||||
# any CPMAddPackage() below so fetched dependencies (Void, Boost, quickjs) are
|
||||
# compiled with the same optimisation level as Echoion itself.
|
||||
get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
|
||||
if(NOT _isMultiConfig AND NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
|
||||
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
|
||||
Debug Release RelWithDebInfo MinSizeRel)
|
||||
message(STATUS "No CMAKE_BUILD_TYPE set; defaulting to Release")
|
||||
endif()
|
||||
|
||||
# Use ccache (or sccache) as a compiler launcher when available to speed up
|
||||
# incremental and clean-from-cache rebuilds. Opt-out with -DECHOION_USE_CCACHE=OFF.
|
||||
option(ECHOION_USE_CCACHE "Use ccache/sccache compiler launcher if found" ON)
|
||||
if(ECHOION_USE_CCACHE AND NOT CMAKE_CXX_COMPILER_LAUNCHER)
|
||||
find_program(ECHOION_CCACHE_PROGRAM NAMES ccache sccache)
|
||||
if(ECHOION_CCACHE_PROGRAM)
|
||||
set(CMAKE_C_COMPILER_LAUNCHER "${ECHOION_CCACHE_PROGRAM}")
|
||||
set(CMAKE_CXX_COMPILER_LAUNCHER "${ECHOION_CCACHE_PROGRAM}")
|
||||
message(STATUS "Compiler cache enabled: ${ECHOION_CCACHE_PROGRAM}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Decide linkage before configuring CPM dependencies. Protocol and VoidLibrary
|
||||
# must be part of the validated echoiond artifact in production, otherwise a
|
||||
# release could pair a new daemon with an old/incompatible shared library.
|
||||
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
|
||||
option(ECHOION_STATIC_LINK "Statically link the GCC runtimes" OFF)
|
||||
if(ECHOION_STATIC_LINK)
|
||||
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE)
|
||||
set(BUILD_SHARED_LIBS OFF)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
message(STATUS "Static GCC runtime linking enabled")
|
||||
endif()
|
||||
|
||||
# Release artifacts should not expose checkout, dependency, or build-machine
|
||||
# paths through __FILE__, std::source_location, or optional DWARF data. Keep
|
||||
# developer builds unchanged so local diagnostics can still use absolute paths;
|
||||
# scripts/release.sh enables this option for production builds.
|
||||
option(ECHOION_REPRODUCIBLE_BUILD
|
||||
"Replace local source/build prefixes in compiler-generated paths" OFF)
|
||||
if(ECHOION_REPRODUCIBLE_BUILD)
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
set(_echoionPrefixMaps
|
||||
"${CMAKE_SOURCE_DIR}=Echoion"
|
||||
"${CMAKE_BINARY_DIR}=EchoionBuild")
|
||||
if(DEFINED CPM_Void_SOURCE AND NOT CPM_Void_SOURCE STREQUAL "")
|
||||
list(APPEND _echoionPrefixMaps
|
||||
"${CPM_Void_SOURCE}=VoidLibrary")
|
||||
endif()
|
||||
if(DEFINED CPM_VoidTeamspeak_SOURCE AND
|
||||
NOT CPM_VoidTeamspeak_SOURCE STREQUAL "")
|
||||
list(APPEND _echoionPrefixMaps
|
||||
"${CPM_VoidTeamspeak_SOURCE}=VoidTeamspeak")
|
||||
endif()
|
||||
foreach(_echoionPrefixMap IN LISTS _echoionPrefixMaps)
|
||||
add_compile_options(
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-ffile-prefix-map=${_echoionPrefixMap}>"
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-fmacro-prefix-map=${_echoionPrefixMap}>"
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-fdebug-prefix-map=${_echoionPrefixMap}>")
|
||||
endforeach()
|
||||
message(STATUS "Reproducible compiler path mapping enabled")
|
||||
else()
|
||||
message(WARNING
|
||||
"ECHOION_REPRODUCIBLE_BUILD is not supported by this compiler")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Include CPM
|
||||
file(
|
||||
DOWNLOAD
|
||||
https://github.com/cpm-cmake/CPM.cmake/releases/download/v0.40.8/CPM.cmake
|
||||
${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake
|
||||
EXPECTED_HASH SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791
|
||||
)
|
||||
include(${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake)
|
||||
|
||||
# Include PackageProject.cmake
|
||||
CPMAddPackage(
|
||||
NAME PackageProject.cmake
|
||||
GITHUB_REPOSITORY TheLartians/PackageProject.cmake
|
||||
VERSION 1.11.2
|
||||
)
|
||||
|
||||
# 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 https://git.faumaray.ru/void/voidlibrary.git
|
||||
# Keep clean/container releases reproducible. CPM_Void_SOURCE still
|
||||
# overrides this revision for local dependency development.
|
||||
GIT_TAG ${ECHOION_VOID_REVISION}
|
||||
OPTIONS
|
||||
"VOID_ENABLE_TESTING OFF"
|
||||
)
|
||||
|
||||
# Modern native TeamSpeak client library. Local development can point at the
|
||||
# adjacent history-preserving extraction with:
|
||||
# -DCPM_VoidTeamspeak_SOURCE=$HOME/Project/Personal/VoidTeamspeak
|
||||
CPMAddPackage(
|
||||
NAME VoidTeamspeak
|
||||
GIT_REPOSITORY https://git.faumaray.ru/void/voidteamspeak.git
|
||||
# This revision supplies the typed administration API used by Standalone.
|
||||
GIT_TAG ${ECHOION_VOID_TEAMSPEAK_REVISION}
|
||||
OPTIONS
|
||||
"VOID_TEAMSPEAK_BUILD_TESTS OFF"
|
||||
"VOID_ENABLE_TESTING OFF"
|
||||
)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc")
|
||||
set(CXX_SCAN_FOR_MODULES 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()
|
||||
|
||||
# Link-time optimisation for Release configs only (keeps Debug builds fast).
|
||||
# Experimental C++26 reflection (-freflection) is a front-end feature and is
|
||||
# orthogonal to GCC's LTO, but gate behind an option so it can be disabled if a
|
||||
# given toolchain rejects the combination.
|
||||
option(ECHOION_ENABLE_LTO "Enable interprocedural optimisation for Release builds" ON)
|
||||
if(ECHOION_ENABLE_LTO)
|
||||
include(CheckIPOSupported)
|
||||
check_ipo_supported(RESULT _ipoSupported OUTPUT _ipoError LANGUAGES CXX)
|
||||
if(_ipoSupported)
|
||||
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE ON)
|
||||
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO ON)
|
||||
message(STATUS "Interprocedural optimisation (LTO) enabled for Release")
|
||||
else()
|
||||
message(STATUS "IPO/LTO not supported by toolchain: ${_ipoError}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Unity builds batch translation units to cut compile time. Kept OFF by default
|
||||
# because reflection TUs and Glaze-heavy headers can blow up unity batch memory;
|
||||
# enable per-machine with -DECHOION_UNITY_BUILD=ON.
|
||||
option(ECHOION_UNITY_BUILD "Enable CMake unity (jumbo) builds" OFF)
|
||||
if(ECHOION_UNITY_BUILD)
|
||||
set(CMAKE_UNITY_BUILD ON)
|
||||
set(CMAKE_UNITY_BUILD_BATCH_SIZE 8)
|
||||
message(STATUS "Unity build enabled (batch size 8)")
|
||||
endif()
|
||||
|
||||
# Enable folder organization in IDEs
|
||||
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
|
||||
|
||||
# Options
|
||||
option(BUILD_API "Build EchoionApi" ON)
|
||||
option(BUILD_CORE "Build EchoionCore" ON)
|
||||
option(BUILD_DESKTOP "Build EchoionDesktop" ON)
|
||||
option(BUILD_WEB "Build EchoionWeb browser dashboard" ON)
|
||||
option(BUILD_STANDALONE "Build EchoionStandalone daemon with native TeamSpeak client" ON)
|
||||
option(BUILD_FIRST_PARTY_PLUGINS "Build bundled Echoion extension plugins" ON)
|
||||
option(BUILD_TESTS "Build tests" OFF)
|
||||
|
||||
if(BUILD_TESTS)
|
||||
enable_testing()
|
||||
endif()
|
||||
|
||||
# Find packages
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
# Add subdirectories
|
||||
if(BUILD_API)
|
||||
add_subdirectory(EchoionApi)
|
||||
endif()
|
||||
|
||||
if(BUILD_FIRST_PARTY_PLUGINS)
|
||||
add_subdirectory(plugins)
|
||||
endif()
|
||||
|
||||
if(BUILD_STANDALONE)
|
||||
add_subdirectory(EchoionHost)
|
||||
endif()
|
||||
|
||||
if(BUILD_CORE)
|
||||
add_subdirectory(EchoionCore)
|
||||
endif()
|
||||
|
||||
# EchoionWeb is added after Core so it can reuse the single Boost header
|
||||
# targets Core discovers. Core owns and starts the web server, so link them
|
||||
# here (both targets now exist) and flag Core so the wiring compiles in.
|
||||
if(BUILD_WEB AND BUILD_CORE)
|
||||
add_subdirectory(EchoionWeb)
|
||||
if(TARGET EchoionCore AND TARGET EchoionWeb)
|
||||
target_link_libraries(EchoionCore PRIVATE EchoionWeb)
|
||||
target_compile_definitions(EchoionCore PRIVATE ECHOION_WITH_WEB)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# VoidTeamspeak is resolved above as a regular reusable package. The legacy
|
||||
# TeamSpeak client plugin and in-tree protocol directories are no longer built.
|
||||
|
||||
# The updater is a deliberately small, dynamically linked lifecycle helper.
|
||||
# It validates and journals local operations but leaves network/feed work to
|
||||
# the daemon through typed request files. Define it before Standalone so the
|
||||
# Linux release-staging test can use the real helper binary.
|
||||
if(UNIX AND NOT APPLE)
|
||||
add_subdirectory(packaging/updater)
|
||||
endif()
|
||||
|
||||
# EchoionStandalone links the host-common loader and native protocol client.
|
||||
if(BUILD_STANDALONE)
|
||||
add_subdirectory(EchoionStandalone)
|
||||
endif()
|
||||
|
||||
if(BUILD_DESKTOP)
|
||||
add_subdirectory(EchoionDesktop)
|
||||
endif()
|
||||
|
||||
# The release install component is deliberately runtime-only. Nested projects
|
||||
# keep their normal SDK/development install rules, while scripts/release.sh uses
|
||||
# this component as the single input to dependency collection and packaging.
|
||||
option(ECHOION_INSTALL_RUNTIME_BUNDLE
|
||||
"Provide the relocatable Echoion Runtime install component" ON)
|
||||
if(ECHOION_INSTALL_RUNTIME_BUNDLE)
|
||||
if(TARGET EchoionStandalone)
|
||||
if(UNIX AND NOT APPLE)
|
||||
set_target_properties(EchoionStandalone PROPERTIES
|
||||
INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}"
|
||||
INSTALL_RPATH_USE_LINK_PATH FALSE)
|
||||
endif()
|
||||
install(TARGETS EchoionStandalone
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
COMPONENT Runtime)
|
||||
endif()
|
||||
|
||||
if(TARGET EchoionCore)
|
||||
if(UNIX AND NOT APPLE)
|
||||
set_target_properties(EchoionCore PROPERTIES
|
||||
INSTALL_RPATH "$ORIGIN"
|
||||
INSTALL_RPATH_USE_LINK_PATH FALSE)
|
||||
endif()
|
||||
install(TARGETS EchoionCore
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
COMPONENT Runtime)
|
||||
endif()
|
||||
|
||||
if(TARGET EchoionWeb)
|
||||
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/EchoionWeb/frontend/web-dist/"
|
||||
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/web"
|
||||
COMPONENT Runtime)
|
||||
endif()
|
||||
|
||||
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/config.example.json"
|
||||
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion"
|
||||
COMPONENT Runtime)
|
||||
install(FILES
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion.service.in"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.service.in"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.timer.in"
|
||||
DESTINATION service
|
||||
COMPONENT Runtime)
|
||||
install(PROGRAMS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/validate-release-manifest.py"
|
||||
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/tools"
|
||||
COMPONENT Runtime)
|
||||
|
||||
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
|
||||
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE"
|
||||
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/licenses"
|
||||
RENAME Echoion-LICENSE
|
||||
COMPONENT Runtime)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Bundling and deployment helpers
|
||||
# Function to bundle Qt dependencies
|
||||
function(bundle_qt_dependencies target)
|
||||
if(NOT TARGET ${target})
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
find_program(WINDEPLOYQT windeployqt HINTS ${Qt6Core_DIR}/../../../bin)
|
||||
if(WINDEPLOYQT)
|
||||
add_custom_command(TARGET ${target} POST_BUILD
|
||||
COMMAND ${WINDEPLOYQT}
|
||||
--dir $<TARGET_FILE_DIR:${target}>/qt_libs
|
||||
--release
|
||||
--no-translations
|
||||
--no-compiler-runtime
|
||||
--no-opengl-sw
|
||||
$<TARGET_FILE:${target}>
|
||||
COMMENT "Bundling Qt dependencies for ${target}"
|
||||
)
|
||||
endif()
|
||||
elseif(APPLE)
|
||||
find_program(MACDEPLOYQT macdeployqt HINTS ${Qt6Core_DIR}/../../../bin)
|
||||
if(MACDEPLOYQT)
|
||||
add_custom_command(TARGET ${target} POST_BUILD
|
||||
COMMAND ${MACDEPLOYQT} $<TARGET_FILE:${target}> -always-overwrite
|
||||
COMMENT "Bundling Qt dependencies for ${target}"
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Function to install target with its dependencies
|
||||
function(install_with_dependencies target)
|
||||
if(NOT TARGET ${target})
|
||||
return()
|
||||
endif()
|
||||
|
||||
get_target_property(target_type ${target} TYPE)
|
||||
|
||||
if(target_type STREQUAL "EXECUTABLE")
|
||||
install(TARGETS ${target}
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
BUNDLE DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
)
|
||||
|
||||
# Bundle Qt if needed
|
||||
get_target_property(linked_libs ${target} LINK_LIBRARIES)
|
||||
if(linked_libs)
|
||||
foreach(lib ${linked_libs})
|
||||
if(lib MATCHES "Qt6::")
|
||||
bundle_qt_dependencies(${target})
|
||||
break()
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
elseif(target_type STREQUAL "SHARED_LIBRARY")
|
||||
install(TARGETS ${target}
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Apply bundling to targets after all subdirectories are added
|
||||
if(BUILD_DESKTOP AND TARGET EchoionDesktop)
|
||||
install_with_dependencies(EchoionDesktop)
|
||||
endif()
|
||||
|
||||
if(BUILD_CORE AND TARGET EchoionCore)
|
||||
install_with_dependencies(EchoionCore)
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTS AND UNIX)
|
||||
add_test(NAME echoion_release_manifest_packaging_tests
|
||||
COMMAND bash
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-packaging.sh"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
add_test(NAME echoion_runtime_dependency_packaging_tests
|
||||
COMMAND bash
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-runtime-dependencies.sh"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
add_test(NAME echoion_release_archive_packaging_tests
|
||||
COMMAND bash
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-archive.sh"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
add_test(NAME echoion_frontend_license_packaging_tests
|
||||
COMMAND bash
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-frontend-licenses.sh"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
add_test(NAME echoion_installer_packaging_tests
|
||||
COMMAND bash
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/tests/installer_test.sh")
|
||||
endif()
|
||||
|
||||
# The universal .tar.zst/.run workflow is the supported Linux distribution
|
||||
# format. Keep legacy CPack available for local Windows/macOS experiments,
|
||||
# without publishing inaccurate DEB/RPM host-dependency metadata.
|
||||
option(ECHOION_ENABLE_LEGACY_CPACK "Enable legacy platform packaging" OFF)
|
||||
if(ECHOION_ENABLE_LEGACY_CPACK)
|
||||
set(CPACK_PACKAGE_NAME "Echoion")
|
||||
set(CPACK_PACKAGE_VENDOR "Echoion")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak")
|
||||
set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION})
|
||||
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
|
||||
if(WIN32)
|
||||
set(CPACK_GENERATOR "ZIP;NSIS")
|
||||
set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot")
|
||||
elseif(APPLE)
|
||||
set(CPACK_GENERATOR "DragNDrop")
|
||||
set(CPACK_DMG_VOLUME_NAME "Echoion")
|
||||
else()
|
||||
set(CPACK_GENERATOR "TGZ")
|
||||
endif()
|
||||
include(CPack)
|
||||
endif()
|
||||
|
||||
# Print configuration summary
|
||||
message(STATUS "")
|
||||
message(STATUS "Echoion Configuration:")
|
||||
message(STATUS " Version: ${PROJECT_VERSION}")
|
||||
if(DEFINED ECHOION_RUNTIME_VERSION)
|
||||
message(STATUS " Runtime release version: ${ECHOION_RUNTIME_VERSION}")
|
||||
endif()
|
||||
message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS " Build API: ${BUILD_API}")
|
||||
message(STATUS " Build first-party plugins: ${BUILD_FIRST_PARTY_PLUGINS}")
|
||||
message(STATUS " Build Core: ${BUILD_CORE}")
|
||||
message(STATUS " Build Desktop: ${BUILD_DESKTOP}")
|
||||
message(STATUS " Build Web: ${BUILD_WEB}")
|
||||
message(STATUS " Build Standalone: ${BUILD_STANDALONE}")
|
||||
message(STATUS " Build Tests: ${BUILD_TESTS}")
|
||||
message(STATUS " Static Link: ${ECHOION_STATIC_LINK}")
|
||||
message(STATUS " Runtime install component: ${ECHOION_INSTALL_RUNTIME_BUNDLE}")
|
||||
message(STATUS "")
|
||||
message(STATUS "Install prefix: ${CMAKE_INSTALL_PREFIX}")
|
||||
message(STATUS "To build: cmake --build build")
|
||||
message(STATUS "To install: cmake --install build --prefix <install_dir>")
|
||||
message(STATUS "To release: scripts/release.sh --version <version>")
|
||||
message(STATUS "")
|
||||
@@ -1,54 +0,0 @@
|
||||
{
|
||||
"version": 9,
|
||||
"cmakeMinimumRequired": {
|
||||
"major": 4,
|
||||
"minor": 0,
|
||||
"patch": 0
|
||||
},
|
||||
"configurePresets": [
|
||||
{
|
||||
"name": "linux-release",
|
||||
"displayName": "Linux dynamic runtime release",
|
||||
"description": "Bot, Core, web dashboard, tests, and a runtime-only install component",
|
||||
"generator": "Ninja",
|
||||
"binaryDir": "${sourceDir}/build-release",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"CMAKE_INSTALL_PREFIX": "${sourceDir}/build-release/stage",
|
||||
"BUILD_SHARED_LIBS": "ON",
|
||||
"ECHOION_STATIC_LINK": "OFF",
|
||||
"ECHOION_INSTALL_RUNTIME_BUNDLE": "ON",
|
||||
"ECHOION_ENABLE_LEGACY_CPACK": "OFF",
|
||||
"ECHOION_ENABLE_LTO": "ON",
|
||||
"BUILD_API": "ON",
|
||||
"BUILD_CORE": "ON",
|
||||
"BUILD_WEB": "ON",
|
||||
"ECHOION_BUILD_WEB": "ON",
|
||||
"BUILD_STANDALONE": "ON",
|
||||
"BUILD_FIRST_PARTY_PLUGINS": "ON",
|
||||
"BUILD_DESKTOP": "OFF",
|
||||
"BUILD_TESTS": "ON"
|
||||
}
|
||||
}
|
||||
],
|
||||
"buildPresets": [
|
||||
{
|
||||
"name": "linux-release",
|
||||
"configurePreset": "linux-release",
|
||||
"configuration": "Release"
|
||||
}
|
||||
],
|
||||
"testPresets": [
|
||||
{
|
||||
"name": "linux-release",
|
||||
"configurePreset": "linux-release",
|
||||
"configuration": "Release",
|
||||
"output": {
|
||||
"outputOnFailure": true
|
||||
},
|
||||
"execution": {
|
||||
"noTestsAction": "error"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
-1
Submodule EchoionApi deleted from 3d61e6952f.
-1
Submodule EchoionCore deleted from a277f2102b.
Submodule EchoionDesktop deleted from 2aa44fae9e.
@@ -1,35 +0,0 @@
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(EchoionHost VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
add_library(EchoionHost STATIC
|
||||
src/CoreLoader.cpp
|
||||
)
|
||||
add_library(Echoion::Host ALIAS EchoionHost)
|
||||
|
||||
target_compile_features(EchoionHost PUBLIC cxx_std_26)
|
||||
set_target_properties(EchoionHost PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
target_include_directories(EchoionHost PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
target_link_libraries(EchoionHost
|
||||
PUBLIC
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiConfig
|
||||
Echoion::ApiPlugin
|
||||
Echoion::ApiOpaque
|
||||
Echoion::ApiCoreInterface
|
||||
PRIVATE
|
||||
Echoion::ApiLogger
|
||||
Void::Data
|
||||
Void::Log
|
||||
Void::Plugin
|
||||
Void::System
|
||||
Void::Stacktrace
|
||||
Threads::Threads
|
||||
)
|
||||
|
||||
if(NOT MSVC)
|
||||
target_compile_options(EchoionHost PRIVATE
|
||||
-Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wshadow)
|
||||
endif()
|
||||
@@ -1,100 +0,0 @@
|
||||
#pragma once
|
||||
#include <Void/System/FileWatcher.hpp>
|
||||
#include <Void/Plugin/Manager.hpp>
|
||||
#include <CoreInterface.hpp>
|
||||
#include <PluginTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Host
|
||||
{
|
||||
|
||||
class CoreLoader
|
||||
{
|
||||
public:
|
||||
|
||||
CoreLoader();
|
||||
~CoreLoader();
|
||||
|
||||
Api::Result<void> load(const std::filesystem::path& libraryPath);
|
||||
Api::Result<void> unload();
|
||||
Api::Result<void>
|
||||
hotReload(const std::filesystem::path& newLibraryPath);
|
||||
[[nodiscard]] bool isLoaded() const noexcept;
|
||||
[[nodiscard]] Api::CoreInterfacePtr getCore() const;
|
||||
void setConfigPath(const std::filesystem::path& configPath);
|
||||
[[nodiscard]] std::filesystem::path getConfigPath() const;
|
||||
[[nodiscard]] bool isHotReloading() const noexcept;
|
||||
Api::Result<void>
|
||||
checkpoint(const std::filesystem::path& destination);
|
||||
Api::Result<void>
|
||||
restoreCheckpoint(const std::filesystem::path& source);
|
||||
|
||||
// Automatic hot reload
|
||||
void enableAutoReload();
|
||||
void disableAutoReload();
|
||||
[[nodiscard]] bool isAutoReloadEnabled() const noexcept;
|
||||
|
||||
// Callback for hot reload completion (called after auto-reload
|
||||
// finishes)
|
||||
using HotReloadCallback = std::function<void()>;
|
||||
using HotReloadPrepareCallback = std::function<void()>;
|
||||
void setHotReloadPrepareCallback(HotReloadPrepareCallback callback)
|
||||
{
|
||||
hotReloadPrepareCallback_ = std::move(callback);
|
||||
}
|
||||
void setHotReloadCallback(HotReloadCallback callback)
|
||||
{
|
||||
hotReloadCallback_ = std::move(callback);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Api::Result<void>
|
||||
loadLibraryInternal(const std::filesystem::path& path);
|
||||
Api::Result<void> unloadLibraryInternal();
|
||||
[[nodiscard]] Api::Result<void> refreshCoreHandle();
|
||||
|
||||
Void::Plugin::PluginManager pluginManager_;
|
||||
std::string pluginName_;
|
||||
Api::CoreInterfacePtr core_;
|
||||
std::filesystem::path currentLibraryPath_;
|
||||
std::filesystem::path configPath_;
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<bool> loaded_{false};
|
||||
std::atomic<bool> hotReloading_{false};
|
||||
|
||||
// Auto reload
|
||||
Void::FileSystem::FileWatcher fileWatcher_;
|
||||
std::atomic<bool> autoReloadEnabled_{false};
|
||||
|
||||
// Deferred reload - waits for current track to finish
|
||||
std::thread deferredReloadThread_;
|
||||
std::atomic<bool> hasPendingReload_{false};
|
||||
std::atomic<bool> stopDeferredReload_{false};
|
||||
std::condition_variable deferredReloadCv_;
|
||||
std::filesystem::path pendingReloadPath_;
|
||||
std::string pendingTrackId_; // Track ID that was playing when
|
||||
// reload scheduled
|
||||
mutable std::mutex pendingReloadMutex_;
|
||||
|
||||
// Hot reload completion callback
|
||||
HotReloadPrepareCallback hotReloadPrepareCallback_;
|
||||
HotReloadCallback hotReloadCallback_;
|
||||
|
||||
void onCoreFileChanged();
|
||||
void waitForTrackAndReload(const std::filesystem::path& targetPath,
|
||||
const std::string& trackId);
|
||||
[[nodiscard]] bool isPlaybackActive() const;
|
||||
[[nodiscard]] bool
|
||||
isSameTrackPlaying(const std::string& trackId) const;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Host
|
||||
@@ -1,585 +0,0 @@
|
||||
#include "echoion/host/CoreLoader.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Plugin/Loader.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace Echoion::Host
|
||||
{
|
||||
namespace
|
||||
{
|
||||
bool canCreateHotReloadCopy(const std::filesystem::path& libraryPath)
|
||||
{
|
||||
const auto directory = libraryPath.parent_path();
|
||||
#ifdef _WIN32
|
||||
std::error_code error;
|
||||
const auto status = std::filesystem::status(directory, error);
|
||||
if (error || !std::filesystem::is_directory(status)) {
|
||||
return false;
|
||||
}
|
||||
constexpr auto writable = std::filesystem::perms::owner_write |
|
||||
std::filesystem::perms::group_write |
|
||||
std::filesystem::perms::others_write;
|
||||
return (status.permissions() & writable) !=
|
||||
std::filesystem::perms::none;
|
||||
#else
|
||||
struct stat metadata{};
|
||||
if (::stat(directory.c_str(), &metadata) != 0 ||
|
||||
!S_ISDIR(metadata.st_mode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto effectiveUser = ::geteuid();
|
||||
const auto effectiveGroup = ::getegid();
|
||||
bool usesDirectoryGroup = effectiveGroup == metadata.st_gid;
|
||||
if (!usesDirectoryGroup) {
|
||||
const int count = ::getgroups(0, nullptr);
|
||||
if (count > 0) {
|
||||
std::vector<gid_t> groups(static_cast<std::size_t>(count));
|
||||
if (::getgroups(count, groups.data()) == count) {
|
||||
usesDirectoryGroup =
|
||||
std::ranges::contains(groups, metadata.st_gid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mode_t required{};
|
||||
if (effectiveUser == metadata.st_uid) {
|
||||
required = S_IWUSR | S_IXUSR;
|
||||
} else if (usesDirectoryGroup) {
|
||||
required = S_IWGRP | S_IXGRP;
|
||||
} else {
|
||||
required = S_IWOTH | S_IXOTH;
|
||||
}
|
||||
return (metadata.st_mode & required) == required &&
|
||||
::access(directory.c_str(), W_OK | X_OK) == 0;
|
||||
#endif
|
||||
}
|
||||
} // namespace
|
||||
|
||||
CoreLoader::CoreLoader()
|
||||
: pluginManager_(Void::Plugin::PluginManager::Options{
|
||||
.dlclose_on_swap = false,
|
||||
// Packaged Core libraries live in an immutable, service-readable
|
||||
// directory. Initial load must never create a hotswap sibling
|
||||
// there.
|
||||
.copy_on_load = false,
|
||||
.config_provider =
|
||||
[this](std::string_view) { return configPath_.string(); },
|
||||
.instance_validator =
|
||||
[](Void::Plugin::IPlugin& plugin,
|
||||
const Void::Plugin::PluginInfo&) {
|
||||
return dynamic_cast<Api::ICoreInterface*>(&plugin) !=
|
||||
nullptr;
|
||||
}})
|
||||
{
|
||||
}
|
||||
|
||||
void CoreLoader::enableAutoReload()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (autoReloadEnabled_.load()) {
|
||||
return;
|
||||
}
|
||||
if (!currentLibraryPath_.empty() &&
|
||||
std::filesystem::exists(currentLibraryPath_)) {
|
||||
if (!canCreateHotReloadCopy(currentLibraryPath_)) {
|
||||
Void::Log::info(
|
||||
"CoreLoader", "{}",
|
||||
std::format(
|
||||
"Auto-reload disabled for read-only Core directory: {}",
|
||||
currentLibraryPath_.parent_path().string()));
|
||||
return;
|
||||
}
|
||||
autoReloadEnabled_ = true;
|
||||
Void::Log::info("CoreLoader", "{}",
|
||||
std::format("Enabling auto-reload for: {}",
|
||||
currentLibraryPath_.string()));
|
||||
|
||||
fileWatcher_.watch(
|
||||
currentLibraryPath_,
|
||||
[this](const Void::FileSystem::FileWatcher::Event& event) {
|
||||
if (event.exists) {
|
||||
onCoreFileChanged();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void CoreLoader::disableAutoReload()
|
||||
{
|
||||
autoReloadEnabled_ = false;
|
||||
if (!currentLibraryPath_.empty()) {
|
||||
fileWatcher_.unwatch(currentLibraryPath_);
|
||||
}
|
||||
Void::Log::info("CoreLoader", "{}", "Auto-reload disabled");
|
||||
}
|
||||
|
||||
bool CoreLoader::isAutoReloadEnabled() const noexcept
|
||||
{
|
||||
return autoReloadEnabled_.load();
|
||||
}
|
||||
|
||||
void CoreLoader::onCoreFileChanged()
|
||||
{
|
||||
if (!autoReloadEnabled_.load() || hotReloading_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Void::Log::info(
|
||||
"CoreLoader", "{}",
|
||||
"Core file changed, scheduling hot reload after current track...");
|
||||
|
||||
// Small delay to ensure file write is complete
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
|
||||
// Check if playback is active - if so, defer reload
|
||||
if (isPlaybackActive()) {
|
||||
std::string currentTrackId;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
|
||||
hasPendingReload_ = true;
|
||||
pendingReloadPath_ = currentLibraryPath_;
|
||||
|
||||
// Capture current track ID
|
||||
auto state = core_->getPlaybackSummary();
|
||||
if (state && state->currentTrack.has_value()) {
|
||||
pendingTrackId_ = state->currentTrack->id;
|
||||
currentTrackId = pendingTrackId_;
|
||||
}
|
||||
}
|
||||
|
||||
Void::Log::info(
|
||||
"CoreLoader", "{}",
|
||||
std::format("Playback active (track: {}), deferring reload "
|
||||
"until track finishes",
|
||||
currentTrackId));
|
||||
|
||||
// Start background thread to wait for track end
|
||||
if (deferredReloadThread_.joinable()) {
|
||||
deferredReloadThread_.join();
|
||||
}
|
||||
deferredReloadThread_ = std::thread([this, currentTrackId]() {
|
||||
waitForTrackAndReload(pendingReloadPath_, currentTrackId);
|
||||
});
|
||||
} else {
|
||||
// No playback, reload immediately
|
||||
auto result = hotReload(currentLibraryPath_);
|
||||
if (!result) {
|
||||
Void::Log::error("CoreLoader", "{}",
|
||||
std::format("Auto hot-reload failed: {}",
|
||||
result.error().message));
|
||||
} else {
|
||||
Void::Log::info("CoreLoader", "{}",
|
||||
"Auto hot-reload completed successfully");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool CoreLoader::isPlaybackActive() const
|
||||
{
|
||||
if (!core_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto state = core_->getPlaybackSummary();
|
||||
if (!state) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if currently playing a track
|
||||
return state->isPlaying && state->currentTrack.has_value();
|
||||
}
|
||||
|
||||
bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const
|
||||
{
|
||||
if (!core_ || trackId.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto state = core_->getPlaybackSummary();
|
||||
if (!state || !state->currentTrack.has_value()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return state->currentTrack->id == trackId;
|
||||
}
|
||||
|
||||
void CoreLoader::waitForTrackAndReload(
|
||||
const std::filesystem::path& targetPath, const std::string& trackId)
|
||||
{
|
||||
Void::Log::info(
|
||||
"CoreLoader", "{}",
|
||||
std::format("Waiting for track {} to finish before reload...",
|
||||
trackId));
|
||||
|
||||
// Poll every 500ms to check if the specific track finished
|
||||
// (playback may continue with next track, but we only care about THIS
|
||||
// track). The wait is interruptible so the destructor can join this
|
||||
// thread instead of detaching it (detaching risks use-after-free when
|
||||
// the plugin unloads mid-wait).
|
||||
while (isSameTrackPlaying(trackId)) {
|
||||
std::unique_lock<std::mutex> lock(pendingReloadMutex_);
|
||||
if (deferredReloadCv_.wait_for(
|
||||
lock, std::chrono::milliseconds(500),
|
||||
[this] { return stopDeferredReload_.load(); })) {
|
||||
Void::Log::info(
|
||||
"CoreLoader", "{}",
|
||||
"Deferred hot-reload cancelled (loader shutting down)");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (stopDeferredReload_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Void::Log::info("CoreLoader", "{}",
|
||||
"Track finished, starting hot reload");
|
||||
|
||||
// Clear pending flag
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
|
||||
hasPendingReload_ = false;
|
||||
pendingTrackId_.clear();
|
||||
}
|
||||
|
||||
// Now do the reload
|
||||
auto result = hotReload(targetPath);
|
||||
if (!result) {
|
||||
Void::Log::error("CoreLoader", "{}",
|
||||
std::format("Deferred hot-reload failed: {}",
|
||||
result.error().message));
|
||||
} else {
|
||||
Void::Log::info("CoreLoader", "{}",
|
||||
"Deferred hot-reload completed successfully");
|
||||
}
|
||||
}
|
||||
|
||||
CoreLoader::~CoreLoader()
|
||||
{
|
||||
if (autoReloadEnabled_.load()) {
|
||||
disableAutoReload();
|
||||
}
|
||||
// Signal the deferred reload thread to stop and wait for it. It must
|
||||
// never outlive this object: it dereferences core_ and this.
|
||||
stopDeferredReload_ = true;
|
||||
deferredReloadCv_.notify_all();
|
||||
if (deferredReloadThread_.joinable()) {
|
||||
deferredReloadThread_.join();
|
||||
}
|
||||
if (auto result = unload(); !result) {
|
||||
Void::Log::warn("CoreLoader", "{}",
|
||||
std::format("Unload from destructor failed: {}",
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath)
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
|
||||
if (loaded_) {
|
||||
return Api::fail(Api::ErrorCode::AlreadyExists,
|
||||
"Core already loaded");
|
||||
}
|
||||
|
||||
if (!std::filesystem::exists(libraryPath)) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NotFound,
|
||||
std::format("Library not found: {}", libraryPath.string()));
|
||||
}
|
||||
|
||||
auto result = loadLibraryInternal(libraryPath);
|
||||
if (result) {
|
||||
currentLibraryPath_ = libraryPath;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::unload()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
return unloadLibraryInternal();
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
|
||||
if (!loaded_) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"No core loaded to reload");
|
||||
}
|
||||
|
||||
auto targetPath =
|
||||
newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
|
||||
|
||||
if (!std::filesystem::exists(targetPath)) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NotFound,
|
||||
std::format("New library not found: {}", targetPath.string()));
|
||||
}
|
||||
const bool replacingPath = targetPath != currentLibraryPath_;
|
||||
if (!replacingPath && !canCreateHotReloadCopy(targetPath)) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied,
|
||||
"in-place Core reload requires a writable library directory; "
|
||||
"use "
|
||||
"an immutable versioned path for installed updates");
|
||||
}
|
||||
|
||||
hotReloading_ = true;
|
||||
Void::Log::info("CoreLoader", "{}",
|
||||
"Starting transactional hot reload...");
|
||||
|
||||
// No callback may execute code from the old shared object after this
|
||||
// barrier returns. State capture and dlclose are safe only after event
|
||||
// producers have been drained.
|
||||
if (hotReloadPrepareCallback_) {
|
||||
hotReloadPrepareCallback_();
|
||||
}
|
||||
|
||||
// Core owns exclusive process resources (HTTP/RPC listeners), so its
|
||||
// two generations cannot both be initialized during an RCU swap.
|
||||
// Capture state first, then stop the old services while its plugin
|
||||
// instance remains pinned for rollback.
|
||||
Api::StateBlob state;
|
||||
if (core_) {
|
||||
state = core_->saveState();
|
||||
if (auto stopped = core_->shutdown(); !stopped) {
|
||||
hotReloading_ = false;
|
||||
lock.unlock();
|
||||
if (hotReloadCallback_) {
|
||||
hotReloadCallback_();
|
||||
}
|
||||
return stopped;
|
||||
}
|
||||
}
|
||||
|
||||
const auto reloadResult =
|
||||
replacingPath ? pluginManager_.replace(pluginName_, targetPath)
|
||||
: pluginManager_.reload(pluginName_);
|
||||
if (!reloadResult) {
|
||||
hotReloading_ = false;
|
||||
auto message =
|
||||
std::format("new Core rejected; running Core retained: {}",
|
||||
Void::Plugin::to_string(reloadResult.error()));
|
||||
if (core_) {
|
||||
if (auto initialized = core_->initialize(configPath_);
|
||||
!initialized) {
|
||||
message +=
|
||||
std::format("; retained Core reactivation failed: {}",
|
||||
initialized.error().message);
|
||||
} else if (!state.empty()) {
|
||||
if (auto restored = core_->restoreState(state); !restored) {
|
||||
message += std::format(
|
||||
"; retained Core state restore failed: {}",
|
||||
restored.error().message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Void::Log::warn("CoreLoader", "{}", message);
|
||||
lock.unlock();
|
||||
// The prepare callback removed the event route. Restore it against
|
||||
// the still-current Core even though no swap occurred.
|
||||
if (hotReloadCallback_) {
|
||||
hotReloadCallback_();
|
||||
}
|
||||
return Api::fail(Api::ErrorCode::PluginError, message);
|
||||
}
|
||||
|
||||
if (auto refreshed = refreshCoreHandle(); !refreshed) {
|
||||
hotReloading_ = false;
|
||||
return refreshed;
|
||||
}
|
||||
currentLibraryPath_ = targetPath;
|
||||
if (!state.empty()) {
|
||||
if (auto restored = core_->restoreState(state); !restored) {
|
||||
Void::Log::warn("CoreLoader",
|
||||
"new Core state restore failed: {}",
|
||||
restored.error().message);
|
||||
}
|
||||
}
|
||||
hotReloading_ = false;
|
||||
|
||||
Void::Log::info("CoreLoader", "{}", "Hot reload complete");
|
||||
lock.unlock();
|
||||
if (hotReloadCallback_) {
|
||||
hotReloadCallback_();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
bool CoreLoader::isLoaded() const noexcept { return loaded_.load(); }
|
||||
|
||||
Api::CoreInterfacePtr CoreLoader::getCore() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return core_;
|
||||
}
|
||||
|
||||
void CoreLoader::setConfigPath(const std::filesystem::path& configPath)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
configPath_ = configPath;
|
||||
}
|
||||
|
||||
std::filesystem::path CoreLoader::getConfigPath() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return configPath_;
|
||||
}
|
||||
|
||||
bool CoreLoader::isHotReloading() const noexcept
|
||||
{
|
||||
return hotReloading_.load();
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
CoreLoader::checkpoint(const std::filesystem::path& destination)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!core_) {
|
||||
return Api::fail(Api::ErrorCode::NotInitialized,
|
||||
"cannot checkpoint without a loaded Core");
|
||||
}
|
||||
const auto state = core_->saveState();
|
||||
std::string bytes;
|
||||
bytes.reserve(8 + state.timestamp.size() + state.data.size());
|
||||
auto appendU32 = [&bytes](uint32_t value) {
|
||||
for (int shift : {24, 16, 8, 0}) {
|
||||
bytes.push_back(static_cast<char>((value >> shift) & 0xffU));
|
||||
}
|
||||
};
|
||||
appendU32(state.version);
|
||||
appendU32(static_cast<uint32_t>(state.timestamp.size()));
|
||||
bytes.append(state.timestamp);
|
||||
bytes.append(reinterpret_cast<const char*>(state.data.data()),
|
||||
state.data.size());
|
||||
if (auto result = Void::FileSystem::atomic_write(destination, bytes);
|
||||
!result) {
|
||||
return Api::fail(Api::ErrorCode::PluginError,
|
||||
result.error().message());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
CoreLoader::restoreCheckpoint(const std::filesystem::path& source)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!core_) {
|
||||
return Api::fail(Api::ErrorCode::NotInitialized,
|
||||
"cannot restore without a loaded Core");
|
||||
}
|
||||
auto contents = Void::FileSystem::read_file(source);
|
||||
if (!contents) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
contents.error().message());
|
||||
}
|
||||
if (contents->size() < 8) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"checkpoint header is truncated");
|
||||
}
|
||||
auto readU32 = [&contents](std::size_t offset) {
|
||||
uint32_t value = 0;
|
||||
for (std::size_t index = 0; index < 4; ++index) {
|
||||
value = (value << 8U) |
|
||||
static_cast<unsigned char>((*contents)[offset + index]);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
Api::StateBlob state;
|
||||
state.version = readU32(0);
|
||||
const auto timestampSize = readU32(4);
|
||||
if (timestampSize > contents->size() - 8) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"checkpoint timestamp is truncated");
|
||||
}
|
||||
state.timestamp = contents->substr(8, timestampSize);
|
||||
const auto dataOffset = 8 + timestampSize;
|
||||
state.data.assign(contents->begin() +
|
||||
static_cast<std::ptrdiff_t>(dataOffset),
|
||||
contents->end());
|
||||
return core_->restoreState(state);
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
CoreLoader::loadLibraryInternal(const std::filesystem::path& path)
|
||||
{
|
||||
auto result = pluginManager_.load(path);
|
||||
if (!result) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PluginError,
|
||||
std::format("failed to load Core plugin: {}",
|
||||
Void::Plugin::to_string(result.error())));
|
||||
}
|
||||
pluginName_ = std::move(*result);
|
||||
if (auto refreshed = refreshCoreHandle(); !refreshed) {
|
||||
std::ignore = pluginManager_.unload(pluginName_);
|
||||
pluginName_.clear();
|
||||
return refreshed;
|
||||
}
|
||||
loaded_ = true;
|
||||
Void::Log::info("CoreLoader", "Core plugin '{}' loaded", pluginName_);
|
||||
return {};
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::refreshCoreHandle()
|
||||
{
|
||||
auto pin = std::make_shared<Void::Plugin::PluginHandle>(
|
||||
pluginManager_.acquire(pluginName_));
|
||||
if (!*pin) {
|
||||
return Api::fail(Api::ErrorCode::PluginError,
|
||||
"Core plugin disappeared from the registry");
|
||||
}
|
||||
auto* interface = dynamic_cast<Api::ICoreInterface*>(pin->get());
|
||||
if (interface == nullptr) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::InvalidArgument,
|
||||
"Void plugin does not implement Echoion Core interface");
|
||||
}
|
||||
core_ = Api::CoreInterfacePtr{std::move(pin), interface};
|
||||
return {};
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::unloadLibraryInternal()
|
||||
{
|
||||
if (!loaded_) {
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Log::info("CoreLoader", "{}", "Unloading core library...");
|
||||
|
||||
core_.reset();
|
||||
if (!pluginName_.empty()) {
|
||||
if (auto result = pluginManager_.unload(pluginName_); !result) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PluginError,
|
||||
std::format("failed to unload Core plugin: {}",
|
||||
Void::Plugin::to_string(result.error())));
|
||||
}
|
||||
pluginName_.clear();
|
||||
}
|
||||
|
||||
loaded_ = false;
|
||||
std::cout << "[Echoion] Core library unloaded" << '\n';
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace Echoion::Host
|
||||
@@ -1,202 +0,0 @@
|
||||
# EchoionStandalone — the daemon that runs Core without a TeamSpeak client.
|
||||
#
|
||||
# It uses the host-common CoreLoader/FileWatcher to load and hot-reload Core,
|
||||
# and implements IPluginInterface with the reusable VoidTeamspeak client.
|
||||
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(EchoionStandalone VERSION 1.0.7 LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET
|
||||
libswresample>=4
|
||||
libavutil>=57
|
||||
)
|
||||
pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus)
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
|
||||
set(ECHOION_UPDATE_FEED_URL "" CACHE STRING
|
||||
"Build-time default URL for the official signed update feed")
|
||||
set(ECHOION_UPDATE_PUBLIC_KEYS_JSON "[]" CACHE STRING
|
||||
"Build-time Ed25519 trust anchors as [{\"id\":...,\"ed25519\":...}]")
|
||||
set(ECHOION_RUNTIME_VERSION "${PROJECT_VERSION}" CACHE STRING
|
||||
"Canonical SemVer reported when no installed release manifest is present")
|
||||
string(LENGTH "${ECHOION_RUNTIME_VERSION}" _runtime_version_length)
|
||||
if(_runtime_version_length GREATER 64 OR
|
||||
NOT ECHOION_RUNTIME_VERSION MATCHES
|
||||
"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$")
|
||||
message(FATAL_ERROR
|
||||
"ECHOION_RUNTIME_VERSION must be canonical SemVer without build metadata")
|
||||
endif()
|
||||
if(ECHOION_RUNTIME_VERSION MATCHES "-([^+]+)$")
|
||||
set(_runtime_prerelease "${CMAKE_MATCH_1}")
|
||||
string(REPLACE "." ";" _runtime_prerelease_identifiers
|
||||
"${_runtime_prerelease}")
|
||||
foreach(_identifier IN LISTS _runtime_prerelease_identifiers)
|
||||
if(_identifier MATCHES "^0[0-9]+$")
|
||||
message(FATAL_ERROR
|
||||
"ECHOION_RUNTIME_VERSION has a non-canonical numeric prerelease identifier")
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
foreach(_update_default IN ITEMS
|
||||
ECHOION_UPDATE_FEED_URL ECHOION_UPDATE_PUBLIC_KEYS_JSON
|
||||
ECHOION_RUNTIME_VERSION)
|
||||
if("${${_update_default}}" MATCHES "\\)ECHOION_UPDATE\\\"")
|
||||
message(FATAL_ERROR "${_update_default} contains the generated-header delimiter")
|
||||
endif()
|
||||
endforeach()
|
||||
set(ECHOION_TOOLCHAIN_ABI
|
||||
"${CMAKE_CXX_COMPILER_ID}-${CMAKE_CXX_COMPILER_VERSION}-${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}")
|
||||
configure_file(
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/standalone/UpdateBuildDefaults.hpp.in"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/generated/echoion/standalone/UpdateBuildDefaults.hpp"
|
||||
@ONLY)
|
||||
|
||||
add_executable(EchoionStandalone
|
||||
src/main.cpp
|
||||
src/StandaloneClientInterface.cpp
|
||||
src/AudioEncoder.cpp
|
||||
src/MessageChunker.cpp
|
||||
src/ReleaseManifest.cpp
|
||||
src/RuntimePaths.cpp
|
||||
src/EventCallbackGate.cpp
|
||||
src/UpdateService.cpp
|
||||
)
|
||||
|
||||
target_include_directories(EchoionStandalone PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/generated"
|
||||
)
|
||||
|
||||
target_link_libraries(EchoionStandalone PRIVATE
|
||||
Void::TeamSpeak
|
||||
Echoion::Host
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiPlugin
|
||||
Echoion::ApiOpaque
|
||||
Echoion::ApiPluginInterface
|
||||
Echoion::ApiCoreInterface
|
||||
Echoion::ApiLogger
|
||||
Void::Data
|
||||
Void::Core
|
||||
Void::Log
|
||||
Void::System
|
||||
Void::Stacktrace
|
||||
Void::Archive
|
||||
Void::Crypto
|
||||
Void::Net
|
||||
Void::Plugin
|
||||
Void::Update
|
||||
Threads::Threads
|
||||
PkgConfig::SWRESAMPLE
|
||||
PkgConfig::OPUS
|
||||
OpenSSL::Crypto
|
||||
)
|
||||
|
||||
set_target_properties(EchoionStandalone PROPERTIES
|
||||
OUTPUT_NAME "echoiond"
|
||||
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
|
||||
)
|
||||
|
||||
install(TARGETS EchoionStandalone RUNTIME DESTINATION bin)
|
||||
|
||||
if(BUILD_TESTS)
|
||||
add_executable(echoion_core_loader_reload_tests
|
||||
tests/test_core_loader_reload.cpp)
|
||||
target_link_libraries(echoion_core_loader_reload_tests PRIVATE
|
||||
Echoion::Host Echoion::ApiCoreInterface)
|
||||
target_compile_features(echoion_core_loader_reload_tests PRIVATE cxx_std_26)
|
||||
target_compile_definitions(echoion_core_loader_reload_tests PRIVATE
|
||||
"ECHOION_TEST_CORE_PATH=\"$<TARGET_FILE:EchoionCore>\"")
|
||||
add_dependencies(echoion_core_loader_reload_tests EchoionCore)
|
||||
add_test(NAME echoion_core_loader_reload_tests
|
||||
COMMAND echoion_core_loader_reload_tests)
|
||||
|
||||
add_executable(echoion_standalone_message_tests
|
||||
tests/test_message_chunker.cpp
|
||||
src/MessageChunker.cpp
|
||||
)
|
||||
target_include_directories(echoion_standalone_message_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
)
|
||||
target_compile_features(echoion_standalone_message_tests PRIVATE cxx_std_20)
|
||||
add_test(NAME echoion_standalone_message_tests
|
||||
COMMAND echoion_standalone_message_tests)
|
||||
|
||||
add_executable(echoion_release_manifest_tests
|
||||
tests/test_release_manifest.cpp
|
||||
src/ReleaseManifest.cpp
|
||||
)
|
||||
target_include_directories(echoion_release_manifest_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
)
|
||||
target_compile_features(echoion_release_manifest_tests PRIVATE cxx_std_26)
|
||||
target_link_libraries(echoion_release_manifest_tests PRIVATE
|
||||
Echoion::ApiBase Void::Data Void::System OpenSSL::Crypto)
|
||||
add_test(NAME echoion_release_manifest_tests
|
||||
COMMAND echoion_release_manifest_tests)
|
||||
|
||||
add_executable(echoion_runtime_paths_tests
|
||||
tests/test_runtime_paths.cpp
|
||||
src/RuntimePaths.cpp
|
||||
)
|
||||
target_include_directories(echoion_runtime_paths_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
)
|
||||
target_compile_features(echoion_runtime_paths_tests PRIVATE cxx_std_26)
|
||||
add_test(NAME echoion_runtime_paths_tests
|
||||
COMMAND echoion_runtime_paths_tests)
|
||||
|
||||
add_executable(echoion_event_callback_gate_tests
|
||||
tests/test_event_callback_gate.cpp
|
||||
src/EventCallbackGate.cpp
|
||||
)
|
||||
target_include_directories(echoion_event_callback_gate_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
)
|
||||
target_compile_features(echoion_event_callback_gate_tests PRIVATE cxx_std_26)
|
||||
target_link_libraries(echoion_event_callback_gate_tests PRIVATE
|
||||
Echoion::ApiBase Echoion::ApiConfig Echoion::ApiPlugin
|
||||
Void::Core Threads::Threads)
|
||||
add_test(NAME echoion_event_callback_gate_tests
|
||||
COMMAND echoion_event_callback_gate_tests)
|
||||
|
||||
add_executable(echoion_update_service_tests
|
||||
tests/test_update_service.cpp
|
||||
src/UpdateService.cpp
|
||||
)
|
||||
target_include_directories(echoion_update_service_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
)
|
||||
target_compile_features(echoion_update_service_tests PRIVATE cxx_std_26)
|
||||
target_link_libraries(echoion_update_service_tests PRIVATE
|
||||
Echoion::ApiBase Echoion::ApiConfig
|
||||
Void::Archive Void::Crypto Void::Data Void::Log Void::Net Void::Plugin
|
||||
Void::System Void::Update Threads::Threads)
|
||||
add_test(NAME echoion_update_service_tests
|
||||
COMMAND echoion_update_service_tests)
|
||||
|
||||
add_executable(echoion_update_build_defaults_tests
|
||||
tests/test_update_build_defaults.cpp)
|
||||
target_include_directories(echoion_update_build_defaults_tests PRIVATE
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/generated")
|
||||
target_compile_features(echoion_update_build_defaults_tests PRIVATE
|
||||
cxx_std_20)
|
||||
target_compile_definitions(echoion_update_build_defaults_tests PRIVATE
|
||||
"ECHOION_EXPECTED_RUNTIME_VERSION=\"${ECHOION_RUNTIME_VERSION}\"")
|
||||
add_test(NAME echoion_update_build_defaults_tests
|
||||
COMMAND echoion_update_build_defaults_tests)
|
||||
|
||||
if(TARGET EchoionUpdater)
|
||||
add_test(NAME echoion_stage_release_tests
|
||||
COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_stage_release.sh"
|
||||
"${CMAKE_SOURCE_DIR}/scripts/stage-release.sh"
|
||||
$<TARGET_FILE:EchoionUpdater>
|
||||
"${CMAKE_SOURCE_DIR}/packaging/service")
|
||||
endif()
|
||||
endif()
|
||||
@@ -1,42 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
// Converts Echoion's internal PCM (192 kHz stereo S16, delivered in 20 ms
|
||||
// chunks) into TeamSpeak-ready Opus frames: resample to 48 kHz stereo, then
|
||||
// Opus-encode in exact 20 ms (960 samples/ch) frames. A small PCM ring absorbs
|
||||
// the resampler's priming latency so every emitted frame is exactly 960/ch.
|
||||
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
struct SwrContext;
|
||||
struct OpusEncoder;
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
|
||||
class AudioEncoder
|
||||
{
|
||||
public:
|
||||
|
||||
// inRate defaults to Echoion's 192 kHz internal pipeline.
|
||||
explicit AudioEncoder(int bitrate = 96000, int inRate = 192000);
|
||||
~AudioEncoder();
|
||||
|
||||
AudioEncoder(const AudioEncoder&) = delete;
|
||||
AudioEncoder& operator=(const AudioEncoder&) = delete;
|
||||
|
||||
// Feed one chunk of interleaved stereo S16 at inRate. Returns zero or
|
||||
// more complete Opus frames (each a 20 ms packet).
|
||||
std::vector<std::vector<uint8_t>>
|
||||
encode(std::span<const short> interleaved);
|
||||
|
||||
private:
|
||||
|
||||
SwrContext* swr_ = nullptr;
|
||||
OpusEncoder* enc_ = nullptr;
|
||||
int inRate_ = 192000;
|
||||
std::vector<short> pcm_; // resampled 48 kHz interleaved stereo
|
||||
};
|
||||
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -1,29 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <PluginTypes.hpp>
|
||||
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
// Owns plugin-event callbacks across a dynamically loaded Core boundary.
|
||||
// quiesce() is a lifetime barrier: after it returns no callback object, nor
|
||||
// callback invocation, can still reference code from the old Core image.
|
||||
class EventCallbackGate final
|
||||
{
|
||||
public:
|
||||
void add(Api::EventCallback callback);
|
||||
void quiesce();
|
||||
void dispatch(const Api::PluginEvent& event);
|
||||
|
||||
private:
|
||||
std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
std::vector<Api::EventCallback> callbacks_;
|
||||
std::size_t activeDispatches_{0};
|
||||
bool accepting_{true};
|
||||
};
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
// Split TeamSpeak messages on UTF-8/line boundaries while preserving each
|
||||
// complete markdown-it `:::details ... :::` container in one message.
|
||||
[[nodiscard]] std::vector<std::string>
|
||||
chunkMessage(const std::string& message, std::size_t limit = 900);
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <Types.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
enum class ReleaseFileType : std::uint8_t {
|
||||
Regular,
|
||||
Symlink,
|
||||
};
|
||||
|
||||
struct ReleaseFileEntry {
|
||||
std::filesystem::path path;
|
||||
ReleaseFileType type{ReleaseFileType::Regular};
|
||||
std::uintmax_t size{};
|
||||
std::filesystem::perms mode{std::filesystem::perms::unknown};
|
||||
std::string sha256;
|
||||
std::filesystem::path target;
|
||||
};
|
||||
|
||||
struct ReleaseManifest {
|
||||
std::uint32_t schemaVersion{1};
|
||||
std::string version;
|
||||
std::filesystem::path root;
|
||||
std::filesystem::path executable;
|
||||
std::filesystem::path core;
|
||||
std::string executableSha256;
|
||||
std::string coreSha256;
|
||||
std::vector<ReleaseFileEntry> files;
|
||||
|
||||
[[nodiscard]] static Api::Result<ReleaseManifest>
|
||||
load(const std::filesystem::path& manifestPath);
|
||||
[[nodiscard]] Api::Result<void> validate() const;
|
||||
[[nodiscard]] Api::Result<void> validateInstallLayout() const;
|
||||
};
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -1,42 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <expected>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
[[nodiscard]] std::expected<std::filesystem::path, std::string>
|
||||
runningExecutablePath();
|
||||
|
||||
[[nodiscard]] std::filesystem::path deriveInstallRoot(
|
||||
const std::filesystem::path& executablePath,
|
||||
const std::optional<std::filesystem::path>& homeOverride =
|
||||
std::nullopt);
|
||||
|
||||
[[nodiscard]] std::filesystem::path resolveCorePath(
|
||||
const std::filesystem::path& installRoot,
|
||||
const std::filesystem::path& executableDirectory,
|
||||
const std::optional<std::filesystem::path>& coreOverride =
|
||||
std::nullopt);
|
||||
|
||||
[[nodiscard]] std::filesystem::path resolveStateDirectory(
|
||||
const std::optional<std::filesystem::path>& commandLineOverride,
|
||||
const std::optional<std::filesystem::path>& environmentOverride,
|
||||
const std::optional<std::filesystem::path>& xdgStateHome,
|
||||
const std::optional<std::filesystem::path>& userHome,
|
||||
const std::filesystem::path& fallback);
|
||||
|
||||
[[nodiscard]] std::optional<std::filesystem::path> runtimeWorkingDirectory(
|
||||
const std::filesystem::path& installRoot,
|
||||
const std::filesystem::path& executableDirectory);
|
||||
|
||||
[[nodiscard]] std::optional<std::filesystem::path>
|
||||
bundledCertificateBundle(const std::filesystem::path& installRoot);
|
||||
|
||||
[[nodiscard]] std::expected<std::filesystem::path, std::string>
|
||||
resolveAvatarCacheDirectory(
|
||||
const std::filesystem::path& configuredDirectory,
|
||||
const std::filesystem::path& requestedDirectory = {});
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -1,173 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
// Implements Echoion's host interface by adapting VoidTeamspeak's typed client
|
||||
// operations and events. TeamSpeak protocol details remain inside
|
||||
// VoidTeamspeak; Core only sees the host-neutral Echoion API contract.
|
||||
|
||||
#include <PluginInterface.hpp>
|
||||
|
||||
#include "echoion/standalone/EventCallbackGate.hpp"
|
||||
#include <Void/TeamSpeak/TeamSpeak.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
|
||||
class AudioEncoder;
|
||||
|
||||
// Runtime knobs the protocol client needs that ServerConfig does not carry.
|
||||
// Sourced from environment / defaults by main(), so no Core changes are
|
||||
// required.
|
||||
struct StandaloneSettings {
|
||||
std::string identityPath; // where to load/persist the TS identity
|
||||
std::string avatarCachePath;
|
||||
int securityLevel = 8;
|
||||
int opusBitrate = 96000;
|
||||
};
|
||||
|
||||
class StandaloneClientInterface : public Api::IPluginInterface
|
||||
{
|
||||
public:
|
||||
|
||||
explicit StandaloneClientInterface(StandaloneSettings settings);
|
||||
~StandaloneClientInterface() override;
|
||||
|
||||
// Lifecycle
|
||||
Api::Result<void> initialize() override;
|
||||
Api::Result<void> shutdown() override;
|
||||
|
||||
// Clients
|
||||
[[nodiscard]] Api::Result<std::vector<Api::ClientInfo>>
|
||||
getClients() override;
|
||||
[[nodiscard]] Api::Result<std::optional<Api::ClientInfo>>
|
||||
getClient(uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
getClientIp(uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
getClientAvatarPath(uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
getClientAvatarUrl(uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
requestClientAvatar(uint64_t clientId,
|
||||
const std::string& destDir) override;
|
||||
Api::Result<void> moveClient(uint64_t clientId,
|
||||
uint64_t channelId) override;
|
||||
Api::Result<void> kickClient(uint64_t clientId,
|
||||
const std::string& reason) override;
|
||||
Api::Result<void>
|
||||
kickClientFromChannel(uint64_t clientId,
|
||||
const std::string& reason) override;
|
||||
Api::Result<void> banClient(uint64_t clientId,
|
||||
uint64_t durationSeconds,
|
||||
const std::string& reason) override;
|
||||
[[nodiscard]] Api::Result<std::vector<Api::BanInfo>>
|
||||
getBans() override;
|
||||
Api::Result<void> unban(uint64_t banId) override;
|
||||
|
||||
// Channels
|
||||
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>>
|
||||
getChannels() const override;
|
||||
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>>
|
||||
getChannel(uint64_t channelId) const override;
|
||||
Api::Result<uint64_t> createChannel(
|
||||
const Api::ChannelCreateOptions& options) override;
|
||||
Api::Result<void>
|
||||
editChannel(uint64_t channelId,
|
||||
const Api::ChannelEditOptions& options) override;
|
||||
Api::Result<void> reorderChannel(uint64_t channelId,
|
||||
uint64_t parentId,
|
||||
uint64_t orderAfterId) override;
|
||||
Api::Result<void> deleteChannel(uint64_t channelId,
|
||||
bool force) override;
|
||||
|
||||
[[nodiscard]] Api::Result<std::vector<Api::ServerGroupInfo>>
|
||||
getServerGroups() override;
|
||||
Api::Result<void>
|
||||
addClientToServerGroup(uint64_t groupId,
|
||||
uint64_t clientDatabaseId) override;
|
||||
Api::Result<void>
|
||||
removeClientFromServerGroup(uint64_t groupId,
|
||||
uint64_t clientDatabaseId) override;
|
||||
[[nodiscard]] Api::Result<Api::ServerInfo>
|
||||
getTeamSpeakServerInfo() override;
|
||||
|
||||
// Messaging
|
||||
Api::Result<void>
|
||||
sendTextMessage(uint64_t targetId,
|
||||
const std::string& message) override;
|
||||
Api::Result<void>
|
||||
sendChannelMessage(uint64_t channelId,
|
||||
const std::string& message) override;
|
||||
Api::Result<void>
|
||||
sendServerMessage(const std::string& message) override;
|
||||
|
||||
// Audio
|
||||
Api::Result<void>
|
||||
sendAudioData(const std::span<const short>& data) override;
|
||||
Api::Result<void>
|
||||
setWhisperList(const std::vector<uint64_t>& clientIds) override;
|
||||
|
||||
// Connection
|
||||
Api::Result<void>
|
||||
connectToServer(const Api::ServerConfig& config) override;
|
||||
Api::Result<void> disconnectFromServer() override;
|
||||
[[nodiscard]] bool isConnected() const override;
|
||||
Api::Result<void> reconnect() override;
|
||||
|
||||
// Events
|
||||
void registerEventCallback(const Api::EventCallback& cb) override;
|
||||
void unregisterEventCallback(const Api::EventCallback& cb) override;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
hostControl(const std::string& method,
|
||||
const std::string& requestJson) override;
|
||||
using HostControlHandler = std::function<Api::Result<std::string>(
|
||||
const std::string&, const std::string&)>;
|
||||
void setHostControlHandler(HostControlHandler handler);
|
||||
// Prevent new event dispatches, release registered callbacks and
|
||||
// wait until every callback already in flight has returned. The
|
||||
// host must call this before unloading code that owns an event
|
||||
// callback.
|
||||
void quiesceEventCallbacks();
|
||||
|
||||
private:
|
||||
|
||||
void wireCallbacks();
|
||||
void broadcast(const Api::PluginEvent& event);
|
||||
void loadInitialSnapshot();
|
||||
[[nodiscard]] Api::Result<void> commandResult(
|
||||
const Void::Result::Result<void, Void::TeamSpeak::Error>&
|
||||
result) const;
|
||||
|
||||
StandaloneSettings settings_;
|
||||
std::shared_ptr<Void::TeamSpeak::Identity> identity_;
|
||||
std::unique_ptr<Void::TeamSpeak::Client> client_;
|
||||
std::unique_ptr<AudioEncoder> encoder_;
|
||||
|
||||
Api::ServerConfig currentConfig_{};
|
||||
std::atomic<bool> initialized_{false};
|
||||
|
||||
mutable std::mutex mirrorMutex_;
|
||||
std::map<uint64_t, Void::TeamSpeak::RemoteClient> clients_;
|
||||
std::map<uint64_t, Void::TeamSpeak::Channel> channels_;
|
||||
std::optional<Void::TeamSpeak::ServerInfo> serverInfo_;
|
||||
std::map<uint64_t, std::string> clientIps_;
|
||||
std::map<uint64_t, std::string> avatarHashes_;
|
||||
std::map<uint64_t, std::string> avatarUrls_;
|
||||
std::map<uint64_t, std::string> avatarPaths_;
|
||||
std::vector<uint64_t> whisperList_;
|
||||
std::jthread snapshotThread_;
|
||||
mutable std::mutex hostControlMutex_;
|
||||
HostControlHandler hostControlHandler_;
|
||||
|
||||
EventCallbackGate eventCallbacks_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -1,17 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Standalone::UpdateBuildDefaults
|
||||
{
|
||||
inline constexpr std::string_view FeedUrl =
|
||||
R"ECHOION_UPDATE(@ECHOION_UPDATE_FEED_URL@)ECHOION_UPDATE";
|
||||
inline constexpr std::string_view PublicKeysJson =
|
||||
R"ECHOION_UPDATE(@ECHOION_UPDATE_PUBLIC_KEYS_JSON@)ECHOION_UPDATE";
|
||||
inline constexpr std::string_view RuntimeVersion =
|
||||
R"ECHOION_UPDATE(@ECHOION_RUNTIME_VERSION@)ECHOION_UPDATE";
|
||||
inline constexpr std::string_view ApiVersion =
|
||||
R"ECHOION_UPDATE(@PROJECT_VERSION@)ECHOION_UPDATE";
|
||||
inline constexpr std::string_view ToolchainAbi =
|
||||
R"ECHOION_UPDATE(@ECHOION_TOOLCHAIN_ABI@)ECHOION_UPDATE";
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <Types.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
struct ManagedCoreStartupSelection {
|
||||
std::filesystem::path corePath;
|
||||
std::optional<std::filesystem::path> archivedStore;
|
||||
bool runtimeBaselineChanged = false;
|
||||
};
|
||||
|
||||
// Installed runtime releases own their bundled Core baseline. A runtime
|
||||
// version change archives the previous managed store; Core-only updates
|
||||
// remain active across ordinary restarts of the same runtime.
|
||||
[[nodiscard]] Api::Result<ManagedCoreStartupSelection>
|
||||
selectManagedCoreForStartup(
|
||||
const std::filesystem::path& stateDirectory,
|
||||
const std::filesystem::path& bundledCore,
|
||||
std::optional<std::string_view> installedRuntimeVersion);
|
||||
|
||||
// Roll back any uncommitted managed-plugin activation before Core loads and
|
||||
// discovers plugin `current` links. This must run before PluginHost
|
||||
// startup.
|
||||
[[nodiscard]] Api::Result<void> reconcileManagedPluginUpdates(
|
||||
const std::filesystem::path& stateDirectory);
|
||||
|
||||
// Host-owned update coordinator. Core only forwards authenticated RPC
|
||||
// requests across the append-only host interface; all trust, download,
|
||||
// staging and activation decisions remain in the long-lived daemon.
|
||||
class UpdateService final
|
||||
{
|
||||
public:
|
||||
|
||||
struct Options {
|
||||
std::filesystem::path configPath;
|
||||
std::filesystem::path stateDirectory;
|
||||
std::filesystem::path installRoot;
|
||||
std::filesystem::path runningExecutable;
|
||||
std::filesystem::path currentCore;
|
||||
std::filesystem::path releaseManifestPath;
|
||||
std::string officialFeedUrl;
|
||||
std::string officialPublicKeysJson = "[]";
|
||||
std::string runtimeVersion;
|
||||
std::string apiVersion;
|
||||
std::string toolchainAbi;
|
||||
// Trusted administrator drop directory for file://
|
||||
// feeds/artifacts. Empty selects stateDirectory /
|
||||
// "incoming".
|
||||
std::filesystem::path incomingDirectory;
|
||||
};
|
||||
|
||||
struct Hooks {
|
||||
std::function<Api::Result<void>(
|
||||
const std::filesystem::path&)>
|
||||
replaceCore;
|
||||
std::function<Api::Result<std::string>(const std::string&)>
|
||||
managePlugins;
|
||||
std::function<Api::Result<std::string>(const std::string&)>
|
||||
manageRuntime;
|
||||
std::function<bool()> playbackActive;
|
||||
std::function<std::string()> coreVersion;
|
||||
};
|
||||
|
||||
UpdateService(Options options, Hooks hooks);
|
||||
~UpdateService();
|
||||
|
||||
UpdateService(const UpdateService&) = delete;
|
||||
UpdateService& operator=(const UpdateService&) = delete;
|
||||
UpdateService(UpdateService&&) noexcept;
|
||||
UpdateService& operator=(UpdateService&&) noexcept;
|
||||
|
||||
[[nodiscard]] Api::Result<void> start();
|
||||
void stop() noexcept;
|
||||
|
||||
// Execute host mutations which must not run on the Core RPC stack.
|
||||
// The daemon calls this from its polling loop after an RPC has
|
||||
// returned.
|
||||
void processPendingHostActions();
|
||||
|
||||
// Methods are the internal `updates.*` names forwarded by Core.
|
||||
// Requests and successful responses are JSON documents matching the
|
||||
// web contract.
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
handle(const std::string& method,
|
||||
const std::string& requestJson);
|
||||
|
||||
private:
|
||||
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -1,102 +0,0 @@
|
||||
#include "echoion/standalone/AudioEncoder.hpp"
|
||||
|
||||
extern "C" {
|
||||
#include <libavutil/channel_layout.h>
|
||||
#include <libavutil/opt.h>
|
||||
#include <libavutil/samplefmt.h>
|
||||
#include <libswresample/swresample.h>
|
||||
#include <opus/opus.h>
|
||||
}
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr int OUT_RATE = 48000;
|
||||
constexpr int CHANNELS = 2;
|
||||
constexpr int FRAME_SAMPLES = 960; // 20 ms @ 48 kHz per channel
|
||||
constexpr int FRAME_SHORTS = FRAME_SAMPLES * CHANNELS;
|
||||
constexpr int MAX_OPUS = 4000;
|
||||
} // namespace
|
||||
|
||||
AudioEncoder::AudioEncoder(int bitrate, int inRate) : inRate_(inRate)
|
||||
{
|
||||
AVChannelLayout stereo = AV_CHANNEL_LAYOUT_STEREO;
|
||||
if (swr_alloc_set_opts2(&swr_, &stereo, AV_SAMPLE_FMT_S16, OUT_RATE,
|
||||
&stereo, AV_SAMPLE_FMT_S16, inRate_, 0,
|
||||
nullptr) < 0 ||
|
||||
swr_init(swr_) < 0) {
|
||||
throw std::runtime_error("AudioEncoder: swresample init failed");
|
||||
}
|
||||
|
||||
int err = 0;
|
||||
enc_ = opus_encoder_create(OUT_RATE, CHANNELS, OPUS_APPLICATION_AUDIO,
|
||||
&err);
|
||||
if (err != OPUS_OK || !enc_) {
|
||||
throw std::runtime_error("AudioEncoder: opus encoder init failed");
|
||||
}
|
||||
opus_encoder_ctl(enc_, OPUS_SET_BITRATE(bitrate));
|
||||
opus_encoder_ctl(enc_, OPUS_SET_SIGNAL(OPUS_SIGNAL_MUSIC));
|
||||
}
|
||||
|
||||
AudioEncoder::~AudioEncoder()
|
||||
{
|
||||
if (enc_) {
|
||||
opus_encoder_destroy(enc_);
|
||||
}
|
||||
if (swr_) {
|
||||
swr_free(&swr_);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::vector<uint8_t>>
|
||||
AudioEncoder::encode(std::span<const short> interleaved)
|
||||
{
|
||||
std::vector<std::vector<uint8_t>> out;
|
||||
|
||||
const int inSamplesPerCh =
|
||||
static_cast<int>(interleaved.size() / CHANNELS);
|
||||
if (inSamplesPerCh <= 0) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// Upper bound on resampled samples for this chunk.
|
||||
int maxOut = static_cast<int>(
|
||||
av_rescale_rnd(swr_get_delay(swr_, inRate_) + inSamplesPerCh,
|
||||
OUT_RATE, inRate_, AV_ROUND_UP));
|
||||
std::vector<short> resampled(
|
||||
static_cast<size_t>(maxOut) * CHANNELS, 0);
|
||||
|
||||
const uint8_t* inPtr =
|
||||
reinterpret_cast<const uint8_t*>(interleaved.data());
|
||||
uint8_t* outPtr = reinterpret_cast<uint8_t*>(resampled.data());
|
||||
int gotPerCh = swr_convert(swr_, &outPtr, maxOut, &inPtr,
|
||||
inSamplesPerCh);
|
||||
if (gotPerCh < 0) {
|
||||
return out;
|
||||
}
|
||||
pcm_.insert(pcm_.end(), resampled.begin(),
|
||||
resampled.begin() +
|
||||
static_cast<size_t>(gotPerCh) * CHANNELS);
|
||||
|
||||
// Emit as many full 20 ms frames as we have buffered.
|
||||
size_t consumed = 0;
|
||||
while (pcm_.size() - consumed >= static_cast<size_t>(FRAME_SHORTS)) {
|
||||
uint8_t packet[MAX_OPUS];
|
||||
int n = opus_encode(enc_, pcm_.data() + consumed, FRAME_SAMPLES,
|
||||
packet, MAX_OPUS);
|
||||
if (n > 0) {
|
||||
out.emplace_back(packet, packet + n);
|
||||
}
|
||||
consumed += FRAME_SHORTS;
|
||||
}
|
||||
if (consumed > 0) {
|
||||
pcm_.erase(pcm_.begin(),
|
||||
pcm_.begin() + static_cast<std::ptrdiff_t>(consumed));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -1,42 +0,0 @@
|
||||
#include "echoion/standalone/EventCallbackGate.hpp"
|
||||
|
||||
#include <Void/Core/Scope.hpp>
|
||||
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
void EventCallbackGate::add(Api::EventCallback callback)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
accepting_ = true;
|
||||
callbacks_.push_back(std::move(callback));
|
||||
}
|
||||
|
||||
void EventCallbackGate::quiesce()
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
accepting_ = false;
|
||||
callbacks_.clear();
|
||||
cv_.wait(lock, [this] { return activeDispatches_ == 0; });
|
||||
}
|
||||
|
||||
void EventCallbackGate::dispatch(const Api::PluginEvent& event)
|
||||
{
|
||||
std::vector<Api::EventCallback> callbacks;
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (!accepting_) return;
|
||||
++activeDispatches_;
|
||||
callbacks = callbacks_;
|
||||
}
|
||||
const auto complete = Void::Scope::on_exit([this] {
|
||||
std::lock_guard lock(mutex_);
|
||||
--activeDispatches_;
|
||||
cv_.notify_all();
|
||||
});
|
||||
for (const auto& callback : callbacks) {
|
||||
if (callback) callback(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
#include "echoion/standalone/MessageChunker.hpp"
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
std::vector<std::string> chunkMessage(const std::string& message,
|
||||
std::size_t limit)
|
||||
{
|
||||
if (limit == 0 || message.empty()) {
|
||||
return message.empty() ? std::vector<std::string>{}
|
||||
: std::vector<std::string>{message};
|
||||
}
|
||||
if (message.size() <= limit) {
|
||||
return {message};
|
||||
}
|
||||
|
||||
const auto isBlank = [](const std::string& value) {
|
||||
return value.find_first_not_of(" \t\r\n") == std::string::npos;
|
||||
};
|
||||
std::vector<std::string> chunks;
|
||||
std::string current;
|
||||
int detailsDepth = 0;
|
||||
const auto flush = [&] {
|
||||
if (!current.empty() && !isBlank(current)) {
|
||||
chunks.push_back(current);
|
||||
}
|
||||
current.clear();
|
||||
};
|
||||
|
||||
std::size_t position = 0;
|
||||
while (position < message.size()) {
|
||||
const auto newline = message.find('\n', position);
|
||||
std::string line = newline == std::string::npos
|
||||
? message.substr(position)
|
||||
: message.substr(position, newline - position + 1);
|
||||
position = newline == std::string::npos ? message.size() : newline + 1;
|
||||
|
||||
const bool opens = line.starts_with(":::details");
|
||||
std::string_view trimmed = line;
|
||||
while (!trimmed.empty() &&
|
||||
(trimmed.back() == '\n' || trimmed.back() == '\r' ||
|
||||
trimmed.back() == ' ' || trimmed.back() == '\t')) {
|
||||
trimmed.remove_suffix(1);
|
||||
}
|
||||
const bool closes = trimmed == ":::";
|
||||
|
||||
if (detailsDepth == 0 && !current.empty() &&
|
||||
(opens || current.size() + line.size() > limit)) {
|
||||
flush();
|
||||
}
|
||||
|
||||
// A details block must remain syntactically complete even if it is
|
||||
// longer than the preferred message limit. Normal lines are split at
|
||||
// a UTF-8 code-point boundary.
|
||||
if (detailsDepth == 0 && !opens) {
|
||||
while (line.size() > limit) {
|
||||
std::size_t cut = limit;
|
||||
while (cut > 0 &&
|
||||
(static_cast<unsigned char>(line[cut]) & 0xc0) == 0x80) {
|
||||
--cut;
|
||||
}
|
||||
if (cut == 0) {
|
||||
cut = limit;
|
||||
}
|
||||
flush();
|
||||
auto piece = line.substr(0, cut);
|
||||
if (!isBlank(piece)) {
|
||||
chunks.push_back(std::move(piece));
|
||||
}
|
||||
line.erase(0, cut);
|
||||
}
|
||||
}
|
||||
|
||||
current += line;
|
||||
if (opens) {
|
||||
++detailsDepth;
|
||||
}
|
||||
if (closes && detailsDepth > 0) {
|
||||
--detailsDepth;
|
||||
}
|
||||
}
|
||||
flush();
|
||||
return chunks;
|
||||
}
|
||||
}
|
||||
@@ -1,650 +0,0 @@
|
||||
#include "echoion/standalone/ReleaseManifest.hpp"
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
|
||||
#include <openssl/evp.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <memory>
|
||||
#include <ranges>
|
||||
#include <sstream>
|
||||
#include <tuple>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr auto kExecutablePermissions =
|
||||
std::filesystem::perms::owner_exec |
|
||||
std::filesystem::perms::group_exec |
|
||||
std::filesystem::perms::others_exec;
|
||||
constexpr auto kUnsafeWritablePermissions =
|
||||
std::filesystem::perms::group_write |
|
||||
std::filesystem::perms::others_write;
|
||||
constexpr std::array<std::string_view, 4> kImmutableRoots{
|
||||
"bin", "lib", "service", "share"};
|
||||
constexpr double kMaximumExactJsonInteger = 9'007'199'254'740'991.0;
|
||||
|
||||
Api::Result<std::string> sha256(const std::filesystem::path& path)
|
||||
{
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
if (!input) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"release artifact not found: " +
|
||||
path.string());
|
||||
}
|
||||
using Context =
|
||||
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
|
||||
Context context(EVP_MD_CTX_new(), &EVP_MD_CTX_free);
|
||||
if (!context ||
|
||||
EVP_DigestInit_ex(context.get(), EVP_sha256(), nullptr) != 1) {
|
||||
return Api::fail(Api::ErrorCode::UnknownError,
|
||||
"cannot initialize SHA-256");
|
||||
}
|
||||
std::array<char, 64 * 1024> buffer{};
|
||||
while (input) {
|
||||
input.read(buffer.data(),
|
||||
static_cast<std::streamsize>(buffer.size()));
|
||||
if (const auto count = input.gcount();
|
||||
count > 0 &&
|
||||
EVP_DigestUpdate(context.get(), buffer.data(),
|
||||
static_cast<std::size_t>(count)) != 1) {
|
||||
return Api::fail(Api::ErrorCode::UnknownError,
|
||||
"cannot hash release artifact");
|
||||
}
|
||||
}
|
||||
std::array<unsigned char, EVP_MAX_MD_SIZE> digest{};
|
||||
unsigned int size{};
|
||||
if (EVP_DigestFinal_ex(context.get(), digest.data(), &size) != 1) {
|
||||
return Api::fail(Api::ErrorCode::UnknownError,
|
||||
"cannot finalize release hash");
|
||||
}
|
||||
std::ostringstream output;
|
||||
output << std::hex << std::setfill('0');
|
||||
for (unsigned int index = 0; index < size; ++index) {
|
||||
output << std::setw(2)
|
||||
<< static_cast<unsigned int>(digest[index]);
|
||||
}
|
||||
return output.str();
|
||||
}
|
||||
|
||||
bool isSafeRelativePath(const std::filesystem::path& path)
|
||||
{
|
||||
if (path.empty() || path.is_absolute() || path.has_root_name() ||
|
||||
path.filename().empty() ||
|
||||
std::ranges::contains(path.native(), '\0')) {
|
||||
return false;
|
||||
}
|
||||
if (path.generic_string() !=
|
||||
path.lexically_normal().generic_string()) {
|
||||
return false;
|
||||
}
|
||||
return std::ranges::none_of(path, [](const auto& component) {
|
||||
return component == "." || component == "..";
|
||||
});
|
||||
}
|
||||
|
||||
bool isSha256(std::string_view value)
|
||||
{
|
||||
return value.size() == 64 &&
|
||||
std::ranges::all_of(
|
||||
value, [](const unsigned char character) {
|
||||
return (character >= '0' && character <= '9') ||
|
||||
(character >= 'a' && character <= 'f');
|
||||
});
|
||||
}
|
||||
|
||||
std::optional<std::filesystem::perms> parseMode(std::string_view value)
|
||||
{
|
||||
if (value.size() != 4 || value.front() != '0' ||
|
||||
!std::ranges::all_of(value.substr(1), [](const char character) {
|
||||
return character >= '0' && character <= '7';
|
||||
})) {
|
||||
return std::nullopt;
|
||||
}
|
||||
unsigned int result{};
|
||||
for (const char character : value.substr(1)) {
|
||||
result =
|
||||
result * 8U + static_cast<unsigned int>(character - '0');
|
||||
}
|
||||
return static_cast<std::filesystem::perms>(result);
|
||||
}
|
||||
|
||||
std::optional<std::uintmax_t> parseSize(const Void::Json::Value& entry)
|
||||
{
|
||||
const auto* value = entry.find("size");
|
||||
if (!value || !value->is_number()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const double number = value->as_number();
|
||||
if (!std::isfinite(number) || number < 0.0 ||
|
||||
number > kMaximumExactJsonInteger ||
|
||||
std::trunc(number) != number) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<std::uintmax_t>(number);
|
||||
}
|
||||
|
||||
std::filesystem::path
|
||||
normalizedAbsolute(const std::filesystem::path& path)
|
||||
{
|
||||
std::error_code error;
|
||||
auto absolute = std::filesystem::absolute(path, error);
|
||||
return (error ? path : absolute).lexically_normal();
|
||||
}
|
||||
|
||||
bool isWithin(const std::filesystem::path& root,
|
||||
const std::filesystem::path& candidate)
|
||||
{
|
||||
const auto relative = candidate.lexically_relative(root);
|
||||
return !relative.empty() && !relative.is_absolute() &&
|
||||
std::ranges::none_of(relative, [](const auto& component) {
|
||||
return component == "..";
|
||||
});
|
||||
}
|
||||
|
||||
bool hasUnsafeWritablePermissions(
|
||||
const std::filesystem::file_status& status)
|
||||
{
|
||||
return (status.permissions() & kUnsafeWritablePermissions) !=
|
||||
std::filesystem::perms::none;
|
||||
}
|
||||
|
||||
std::optional<std::filesystem::path>
|
||||
relativeToPayload(const std::filesystem::path& path,
|
||||
const std::filesystem::path& prefix)
|
||||
{
|
||||
if (prefix.empty()) {
|
||||
return path;
|
||||
}
|
||||
const auto relative = path.lexically_relative(prefix);
|
||||
if (!isSafeRelativePath(relative)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return relative;
|
||||
}
|
||||
|
||||
bool isImmutablePayloadPath(const std::filesystem::path& path,
|
||||
const std::filesystem::path& prefix)
|
||||
{
|
||||
const auto relative = relativeToPayload(path, prefix);
|
||||
if (!relative || relative->empty()) {
|
||||
return false;
|
||||
}
|
||||
return std::ranges::contains(kImmutableRoots,
|
||||
relative->begin()->generic_string());
|
||||
}
|
||||
|
||||
Api::Result<std::filesystem::path>
|
||||
payloadPrefix(const ReleaseManifest& manifest)
|
||||
{
|
||||
const auto executable =
|
||||
manifest.executable.lexically_relative(manifest.root);
|
||||
if (!isSafeRelativePath(executable) ||
|
||||
executable.filename() != "echoiond" ||
|
||||
executable.parent_path().filename() != "bin") {
|
||||
return Api::fail(Api::ErrorCode::IncompatibleVersion,
|
||||
"v2 release executable must use the payload "
|
||||
"bin/echoiond layout");
|
||||
}
|
||||
|
||||
const auto prefix = executable.parent_path().parent_path();
|
||||
const auto expectedCore =
|
||||
(manifest.root / prefix / "lib" / "Echoion.ts")
|
||||
.lexically_normal();
|
||||
if (manifest.core.lexically_normal() != expectedCore) {
|
||||
return Api::fail(Api::ErrorCode::IncompatibleVersion,
|
||||
"v2 release Core must use the payload "
|
||||
"lib/Echoion.ts layout");
|
||||
}
|
||||
return prefix;
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
validateImmutableCoverage(const ReleaseManifest& manifest)
|
||||
{
|
||||
auto prefix = payloadPrefix(manifest);
|
||||
if (!prefix) {
|
||||
return std::unexpected(prefix.error());
|
||||
}
|
||||
|
||||
std::unordered_set<std::string> declared;
|
||||
declared.reserve(manifest.files.size());
|
||||
for (const auto& entry : manifest.files) {
|
||||
if (!isImmutablePayloadPath(entry.path, *prefix)) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::InvalidArgument,
|
||||
"release manifest entry is outside the immutable "
|
||||
"payload roots: " +
|
||||
entry.path.string());
|
||||
}
|
||||
declared.insert(entry.path.generic_string());
|
||||
}
|
||||
|
||||
const auto payloadRoot = manifest.root / *prefix;
|
||||
std::error_code payloadError;
|
||||
const auto payloadStatus =
|
||||
std::filesystem::symlink_status(payloadRoot, payloadError);
|
||||
if (payloadError ||
|
||||
payloadStatus.type() != std::filesystem::file_type::directory) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"immutable payload root is missing or has an "
|
||||
"unexpected type: " +
|
||||
payloadRoot.string());
|
||||
}
|
||||
if (hasUnsafeWritablePermissions(payloadStatus)) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"immutable payload directory is group- or "
|
||||
"world-writable: " +
|
||||
payloadRoot.string());
|
||||
}
|
||||
|
||||
for (const auto name : kImmutableRoots) {
|
||||
const auto directory = manifest.root / *prefix / name;
|
||||
std::error_code error;
|
||||
const auto rootStatus =
|
||||
std::filesystem::symlink_status(directory, error);
|
||||
if (error || rootStatus.type() !=
|
||||
std::filesystem::file_type::directory) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NotFound,
|
||||
"immutable payload directory is missing or has an "
|
||||
"unexpected type: " +
|
||||
directory.string());
|
||||
}
|
||||
if (hasUnsafeWritablePermissions(rootStatus)) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"immutable payload directory is group- or "
|
||||
"world-writable: " +
|
||||
directory.string());
|
||||
}
|
||||
|
||||
std::filesystem::recursive_directory_iterator iterator{
|
||||
directory, std::filesystem::directory_options::none, error};
|
||||
const std::filesystem::recursive_directory_iterator end;
|
||||
if (error) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied,
|
||||
"cannot inspect immutable payload directory: " +
|
||||
directory.string());
|
||||
}
|
||||
while (iterator != end) {
|
||||
const auto status = iterator->symlink_status(error);
|
||||
if (error) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied,
|
||||
"cannot inspect immutable payload entry: " +
|
||||
iterator->path().string());
|
||||
}
|
||||
if (status.type() ==
|
||||
std::filesystem::file_type::directory) {
|
||||
if (hasUnsafeWritablePermissions(status)) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied,
|
||||
"immutable payload directory is group- or "
|
||||
"world-writable: " +
|
||||
iterator->path().string());
|
||||
}
|
||||
} else {
|
||||
const auto relative =
|
||||
iterator->path().lexically_relative(manifest.root);
|
||||
if (status.type() !=
|
||||
std::filesystem::file_type::regular &&
|
||||
status.type() !=
|
||||
std::filesystem::file_type::symlink) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"special file is not allowed in "
|
||||
"immutable payload: " +
|
||||
relative.string());
|
||||
}
|
||||
if (!declared.contains(relative.generic_string())) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::InvalidArgument,
|
||||
"undeclared immutable payload entry: " +
|
||||
relative.string());
|
||||
}
|
||||
}
|
||||
|
||||
iterator.increment(error);
|
||||
if (error) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied,
|
||||
"cannot traverse immutable payload directory: " +
|
||||
directory.string());
|
||||
}
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Api::Result<ReleaseManifest>
|
||||
loadVersionOne(const Void::Json::Value& json,
|
||||
const std::filesystem::path& root)
|
||||
{
|
||||
ReleaseManifest manifest;
|
||||
manifest.root = root;
|
||||
manifest.version = json.get_str("version");
|
||||
const auto executableEntry =
|
||||
std::filesystem::path(json.get_str("executable"));
|
||||
const auto coreEntry = std::filesystem::path(json.get_str("core"));
|
||||
if (!isSafeRelativePath(executableEntry) ||
|
||||
!isSafeRelativePath(coreEntry)) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"release artifact paths must stay within the "
|
||||
"manifest directory");
|
||||
}
|
||||
manifest.executable = root / executableEntry;
|
||||
manifest.core = root / coreEntry;
|
||||
if (const auto* hashes = json.find("sha256");
|
||||
hashes && hashes->is_object()) {
|
||||
manifest.executableSha256 = hashes->get_str("executable");
|
||||
manifest.coreSha256 = hashes->get_str("core");
|
||||
}
|
||||
if (manifest.version.empty() ||
|
||||
!isSha256(manifest.executableSha256) ||
|
||||
!isSha256(manifest.coreSha256)) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"release manifest is missing version, "
|
||||
"artifacts, or hashes");
|
||||
}
|
||||
return manifest;
|
||||
}
|
||||
|
||||
Api::Result<ReleaseManifest>
|
||||
loadVersionTwo(const Void::Json::Value& json,
|
||||
const std::filesystem::path& root)
|
||||
{
|
||||
ReleaseManifest manifest;
|
||||
manifest.schemaVersion = 2;
|
||||
manifest.root = root;
|
||||
manifest.version = json.get_str("version");
|
||||
const auto executableEntry =
|
||||
std::filesystem::path(json.get_str("executable"));
|
||||
const auto coreEntry = std::filesystem::path(json.get_str("core"));
|
||||
const auto* files = json.child_array("files");
|
||||
if (manifest.version.empty() ||
|
||||
!isSafeRelativePath(executableEntry) ||
|
||||
!isSafeRelativePath(coreEntry) || !files ||
|
||||
files->as_array().empty()) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"v2 release manifest is missing version, "
|
||||
"artifacts, or files");
|
||||
}
|
||||
|
||||
std::unordered_set<std::string> paths;
|
||||
manifest.files.reserve(files->as_array().size());
|
||||
for (const auto& value : files->as_array()) {
|
||||
if (!value.is_object()) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"release file entries must be objects");
|
||||
}
|
||||
ReleaseFileEntry entry;
|
||||
entry.path = value.get_str("path");
|
||||
if (!isSafeRelativePath(entry.path)) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"release file path is absolute, "
|
||||
"traversing, or not normalized");
|
||||
}
|
||||
if (!paths.insert(entry.path.generic_string()).second) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"duplicate release file path: " +
|
||||
entry.path.string());
|
||||
}
|
||||
|
||||
const auto type = value.get_str("type");
|
||||
if (type == "file") {
|
||||
entry.type = ReleaseFileType::Regular;
|
||||
const auto size = parseSize(value);
|
||||
const auto mode = parseMode(value.get_str("mode"));
|
||||
entry.sha256 = value.get_str("sha256");
|
||||
if (!size || !mode || !isSha256(entry.sha256) ||
|
||||
value.has("target")) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"regular release file entry has "
|
||||
"invalid metadata: " +
|
||||
entry.path.string());
|
||||
}
|
||||
entry.size = *size;
|
||||
entry.mode = *mode;
|
||||
if ((entry.mode & kUnsafeWritablePermissions) !=
|
||||
std::filesystem::perms::none) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"release file is group- or "
|
||||
"world-writable: " +
|
||||
entry.path.string());
|
||||
}
|
||||
} else if (type == "symlink") {
|
||||
entry.type = ReleaseFileType::Symlink;
|
||||
entry.target = value.get_str("target");
|
||||
if (!isSafeRelativePath(entry.target) ||
|
||||
value.has("size") || value.has("sha256") ||
|
||||
value.has("mode")) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::ParseError,
|
||||
"symbolic link entry has invalid metadata: " +
|
||||
entry.path.string());
|
||||
}
|
||||
} else {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"unknown release file type: " + type);
|
||||
}
|
||||
manifest.files.push_back(std::move(entry));
|
||||
}
|
||||
|
||||
const auto executable = std::ranges::find(
|
||||
manifest.files, executableEntry, &ReleaseFileEntry::path);
|
||||
const auto core = std::ranges::find(manifest.files, coreEntry,
|
||||
&ReleaseFileEntry::path);
|
||||
if (executable == manifest.files.end() ||
|
||||
core == manifest.files.end() ||
|
||||
executable->type != ReleaseFileType::Regular ||
|
||||
core->type != ReleaseFileType::Regular) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"release executable and Core must reference "
|
||||
"regular file entries");
|
||||
}
|
||||
if ((executable->mode & kExecutablePermissions) ==
|
||||
std::filesystem::perms::none) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"release executable entry is not executable");
|
||||
}
|
||||
|
||||
manifest.executable = root / executableEntry;
|
||||
manifest.core = root / coreEntry;
|
||||
manifest.executableSha256 = executable->sha256;
|
||||
manifest.coreSha256 = core->sha256;
|
||||
return manifest;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Api::Result<ReleaseManifest>
|
||||
ReleaseManifest::load(const std::filesystem::path& manifestPath)
|
||||
{
|
||||
auto contents = Void::FileSystem::read_file(manifestPath);
|
||||
if (!contents) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
contents.error().message());
|
||||
}
|
||||
auto json = Void::Json::parse(*contents);
|
||||
if (!json || !json->is_object()) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
json ? "release manifest must be an object"
|
||||
: "invalid release manifest: " +
|
||||
json.error().message);
|
||||
}
|
||||
|
||||
std::error_code error;
|
||||
auto root = std::filesystem::weakly_canonical(
|
||||
normalizedAbsolute(manifestPath).parent_path(), error);
|
||||
if (error) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"cannot resolve release root: " + error.message());
|
||||
}
|
||||
|
||||
const auto* schema = json->find("schemaVersion");
|
||||
if (!schema) {
|
||||
return loadVersionOne(*json, root);
|
||||
}
|
||||
if (!schema->is_number() || schema->as_number() != 2.0) {
|
||||
return Api::fail(Api::ErrorCode::IncompatibleVersion,
|
||||
"unsupported release manifest schema version");
|
||||
}
|
||||
return loadVersionTwo(*json, root);
|
||||
}
|
||||
|
||||
Api::Result<void> ReleaseManifest::validate() const
|
||||
{
|
||||
if (schemaVersion == 1) {
|
||||
std::error_code rootError;
|
||||
const auto canonicalRoot =
|
||||
std::filesystem::weakly_canonical(root, rootError);
|
||||
if (rootError) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"cannot resolve release root: " +
|
||||
rootError.message());
|
||||
}
|
||||
for (const auto& [path, expected, executableFile] :
|
||||
{std::tuple{executable, executableSha256, true},
|
||||
std::tuple{core, coreSha256, false}}) {
|
||||
std::error_code error;
|
||||
const auto status =
|
||||
std::filesystem::symlink_status(path, error);
|
||||
if (error ||
|
||||
status.type() != std::filesystem::file_type::regular) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NotFound,
|
||||
"release executable and Core must be regular files");
|
||||
}
|
||||
const auto resolved = std::filesystem::canonical(path, error);
|
||||
if (error || !isWithin(canonicalRoot, resolved)) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::InvalidArgument,
|
||||
"release artifact resolves outside the release root: " +
|
||||
path.string());
|
||||
}
|
||||
if (executableFile &&
|
||||
(status.permissions() & kExecutablePermissions) ==
|
||||
std::filesystem::perms::none) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"release executable is not executable");
|
||||
}
|
||||
auto actual = sha256(path);
|
||||
if (!actual) {
|
||||
return std::unexpected(actual.error());
|
||||
}
|
||||
if (*actual != expected) {
|
||||
return Api::fail(Api::ErrorCode::IncompatibleVersion,
|
||||
"SHA-256 mismatch for " + path.string());
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::error_code rootError;
|
||||
const auto canonicalRoot =
|
||||
std::filesystem::weakly_canonical(root, rootError);
|
||||
if (rootError) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"cannot resolve release root: " +
|
||||
rootError.message());
|
||||
}
|
||||
for (const auto& entry : files) {
|
||||
const auto path = root / entry.path;
|
||||
std::error_code error;
|
||||
const auto status = std::filesystem::symlink_status(path, error);
|
||||
if (error ||
|
||||
status.type() == std::filesystem::file_type::not_found) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"release payload entry is missing: " +
|
||||
entry.path.string());
|
||||
}
|
||||
const auto expectedType = entry.type == ReleaseFileType::Regular
|
||||
? std::filesystem::file_type::regular
|
||||
: std::filesystem::file_type::symlink;
|
||||
if (status.type() != expectedType) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::InvalidArgument,
|
||||
"unexpected file type for release payload entry: " +
|
||||
entry.path.string());
|
||||
}
|
||||
|
||||
const auto resolved = std::filesystem::canonical(path, error);
|
||||
if (error || !isWithin(canonicalRoot, resolved)) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"release payload entry resolves outside the "
|
||||
"release root: " +
|
||||
entry.path.string());
|
||||
}
|
||||
|
||||
if (entry.type == ReleaseFileType::Symlink) {
|
||||
const auto actualTarget =
|
||||
std::filesystem::read_symlink(path, error);
|
||||
if (error || actualTarget.generic_string() !=
|
||||
entry.target.generic_string()) {
|
||||
return Api::fail(Api::ErrorCode::IncompatibleVersion,
|
||||
"symbolic link target mismatch for " +
|
||||
entry.path.string());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto size = std::filesystem::file_size(path, error);
|
||||
if (error || size != entry.size) {
|
||||
return Api::fail(Api::ErrorCode::IncompatibleVersion,
|
||||
"file size mismatch for " +
|
||||
entry.path.string());
|
||||
}
|
||||
if ((status.permissions() & std::filesystem::perms::mask) !=
|
||||
entry.mode) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"file mode mismatch for " +
|
||||
entry.path.string());
|
||||
}
|
||||
auto actual = sha256(path);
|
||||
if (!actual) {
|
||||
return std::unexpected(actual.error());
|
||||
}
|
||||
if (*actual != entry.sha256) {
|
||||
return Api::fail(Api::ErrorCode::IncompatibleVersion,
|
||||
"SHA-256 mismatch for " + entry.path.string());
|
||||
}
|
||||
}
|
||||
return validateImmutableCoverage(*this);
|
||||
}
|
||||
|
||||
Api::Result<void> ReleaseManifest::validateInstallLayout() const
|
||||
{
|
||||
if (schemaVersion != 2) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::IncompatibleVersion,
|
||||
"installation validation requires a v2 release manifest");
|
||||
}
|
||||
if (auto result = validate(); !result) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const std::filesystem::path expectedExecutable{"bin/echoiond"};
|
||||
const std::filesystem::path expectedCore{"lib/Echoion.ts"};
|
||||
const std::filesystem::path expectedWeb{"share/echoion/web/index.html"};
|
||||
if (executable.lexically_normal() != (root / expectedExecutable) ||
|
||||
core.lexically_normal() != (root / expectedCore)) {
|
||||
return Api::fail(Api::ErrorCode::IncompatibleVersion,
|
||||
"installation manifest does not describe the "
|
||||
"canonical runtime layout");
|
||||
}
|
||||
const auto web =
|
||||
std::ranges::find(files, expectedWeb, &ReleaseFileEntry::path);
|
||||
if (web == files.end() || web->type != ReleaseFileType::Regular) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"installation manifest is missing the web "
|
||||
"dashboard entry point");
|
||||
}
|
||||
return {};
|
||||
}
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -1,194 +0,0 @@
|
||||
#include "echoion/standalone/RuntimePaths.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <ranges>
|
||||
#include <system_error>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
namespace
|
||||
{
|
||||
std::filesystem::path absoluteNormalized(std::filesystem::path path)
|
||||
{
|
||||
std::error_code error;
|
||||
auto absolute = std::filesystem::absolute(path, error);
|
||||
if (error) {
|
||||
return path.lexically_normal();
|
||||
}
|
||||
return absolute.lexically_normal();
|
||||
}
|
||||
|
||||
bool isWithinOrEqual(const std::filesystem::path& root,
|
||||
const std::filesystem::path& candidate)
|
||||
{
|
||||
const auto relative = candidate.lexically_relative(root);
|
||||
return !relative.empty() && !relative.is_absolute() &&
|
||||
std::ranges::none_of(relative, [](const auto& component) {
|
||||
return component == "..";
|
||||
});
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::expected<std::filesystem::path, std::string> runningExecutablePath()
|
||||
{
|
||||
std::error_code error;
|
||||
auto executable =
|
||||
std::filesystem::read_symlink("/proc/self/exe", error);
|
||||
if (error || executable.empty()) {
|
||||
return std::unexpected("cannot resolve /proc/self/exe: " +
|
||||
error.message());
|
||||
}
|
||||
auto canonical = std::filesystem::weakly_canonical(executable, error);
|
||||
if (error) {
|
||||
return absoluteNormalized(std::move(executable));
|
||||
}
|
||||
return canonical;
|
||||
}
|
||||
|
||||
std::filesystem::path deriveInstallRoot(
|
||||
const std::filesystem::path& executablePath,
|
||||
const std::optional<std::filesystem::path>& homeOverride)
|
||||
{
|
||||
if (homeOverride && !homeOverride->empty()) {
|
||||
return absoluteNormalized(*homeOverride);
|
||||
}
|
||||
|
||||
const auto executableDirectory =
|
||||
absoluteNormalized(executablePath).parent_path();
|
||||
if (executableDirectory.filename() == "bin") {
|
||||
return executableDirectory.parent_path();
|
||||
}
|
||||
return executableDirectory;
|
||||
}
|
||||
|
||||
std::filesystem::path resolveCorePath(
|
||||
const std::filesystem::path& installRoot,
|
||||
const std::filesystem::path& executableDirectory,
|
||||
const std::optional<std::filesystem::path>& coreOverride)
|
||||
{
|
||||
if (coreOverride && !coreOverride->empty()) {
|
||||
return coreOverride->is_absolute()
|
||||
? coreOverride->lexically_normal()
|
||||
: (installRoot / *coreOverride).lexically_normal();
|
||||
}
|
||||
|
||||
const std::array candidates{
|
||||
installRoot / "lib" / "Echoion.ts",
|
||||
executableDirectory / "Echoion.ts",
|
||||
installRoot / "bin" / "Echoion.ts",
|
||||
installRoot / "plugins" / "Echoion.ts",
|
||||
};
|
||||
for (const auto& candidate : candidates) {
|
||||
std::error_code error;
|
||||
if (std::filesystem::is_regular_file(candidate, error) && !error) {
|
||||
return candidate.lexically_normal();
|
||||
}
|
||||
}
|
||||
return candidates.front().lexically_normal();
|
||||
}
|
||||
|
||||
std::filesystem::path resolveStateDirectory(
|
||||
const std::optional<std::filesystem::path>& commandLineOverride,
|
||||
const std::optional<std::filesystem::path>& environmentOverride,
|
||||
const std::optional<std::filesystem::path>& xdgStateHome,
|
||||
const std::optional<std::filesystem::path>& userHome,
|
||||
const std::filesystem::path& fallback)
|
||||
{
|
||||
if (commandLineOverride && !commandLineOverride->empty()) {
|
||||
return absoluteNormalized(*commandLineOverride);
|
||||
}
|
||||
if (environmentOverride && !environmentOverride->empty()) {
|
||||
return absoluteNormalized(*environmentOverride);
|
||||
}
|
||||
if (xdgStateHome && !xdgStateHome->empty()) {
|
||||
return absoluteNormalized(*xdgStateHome / "echoion");
|
||||
}
|
||||
if (userHome && !userHome->empty()) {
|
||||
return absoluteNormalized(*userHome / ".local" / "state" /
|
||||
"echoion");
|
||||
}
|
||||
return absoluteNormalized(fallback);
|
||||
}
|
||||
|
||||
std::optional<std::filesystem::path> runtimeWorkingDirectory(
|
||||
const std::filesystem::path& installRoot,
|
||||
const std::filesystem::path& executableDirectory)
|
||||
{
|
||||
const auto packagedDirectory = installRoot / "share" / "echoion";
|
||||
std::error_code error;
|
||||
if (std::filesystem::is_regular_file(
|
||||
packagedDirectory / "web" / "index.html", error) &&
|
||||
!error) {
|
||||
// Installed config paths are rooted at the release prefix (for
|
||||
// example ./share/echoion/web), so the working directory must be
|
||||
// the installation root rather than share/echoion itself.
|
||||
return installRoot;
|
||||
}
|
||||
|
||||
error.clear();
|
||||
if (std::filesystem::is_regular_file(
|
||||
executableDirectory / "web" / "index.html", error) &&
|
||||
!error) {
|
||||
return executableDirectory;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<std::filesystem::path>
|
||||
bundledCertificateBundle(const std::filesystem::path& installRoot)
|
||||
{
|
||||
const auto bundle =
|
||||
installRoot / "share" / "echoion" / "certs" / "ca-certificates.crt";
|
||||
std::error_code error;
|
||||
if (!std::filesystem::is_regular_file(bundle, error) || error ||
|
||||
std::filesystem::file_size(bundle, error) == 0 || error) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return bundle.lexically_normal();
|
||||
}
|
||||
|
||||
std::expected<std::filesystem::path, std::string>
|
||||
resolveAvatarCacheDirectory(
|
||||
const std::filesystem::path& configuredDirectory,
|
||||
const std::filesystem::path& requestedDirectory)
|
||||
{
|
||||
if (configuredDirectory.empty()) {
|
||||
return std::unexpected("avatar cache directory is not configured");
|
||||
}
|
||||
|
||||
std::error_code error;
|
||||
const auto configured = std::filesystem::weakly_canonical(
|
||||
absoluteNormalized(configuredDirectory), error);
|
||||
if (error) {
|
||||
return std::unexpected("cannot resolve avatar cache directory: " +
|
||||
error.message());
|
||||
}
|
||||
|
||||
if (!requestedDirectory.empty() && !requestedDirectory.is_absolute() &&
|
||||
(requestedDirectory != requestedDirectory.lexically_normal() ||
|
||||
std::ranges::any_of(requestedDirectory, [](const auto& component) {
|
||||
return component == "." || component == "..";
|
||||
}))) {
|
||||
return std::unexpected("avatar cache subdirectory must be "
|
||||
"normalized and non-traversing");
|
||||
}
|
||||
|
||||
const auto requested = requestedDirectory.empty() ? configured
|
||||
: requestedDirectory.is_absolute()
|
||||
? requestedDirectory
|
||||
: configured / requestedDirectory;
|
||||
const auto resolved = std::filesystem::weakly_canonical(
|
||||
absoluteNormalized(requested), error);
|
||||
if (error) {
|
||||
return std::unexpected(
|
||||
"cannot resolve requested avatar directory: " +
|
||||
error.message());
|
||||
}
|
||||
if (!isWithinOrEqual(configured, resolved)) {
|
||||
return std::unexpected("requested avatar directory is outside the "
|
||||
"configured state cache");
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
} // namespace Echoion::Standalone
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,160 +0,0 @@
|
||||
#include "echoion/host/CoreLoader.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <set>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
int fail(const char* message)
|
||||
{
|
||||
std::cerr << message << '\n';
|
||||
return 1;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
const auto root = std::filesystem::temp_directory_path() /
|
||||
("echoion-core-reload-" + std::to_string(::getpid()));
|
||||
std::filesystem::create_directories(root);
|
||||
const auto cleanup = [&root] {
|
||||
std::error_code ec;
|
||||
std::filesystem::permissions(root / "immutable-lib",
|
||||
std::filesystem::perms::owner_all,
|
||||
std::filesystem::perm_options::add, ec);
|
||||
std::filesystem::remove_all(root, ec);
|
||||
};
|
||||
|
||||
::setenv("XDG_CONFIG_HOME", root.c_str(), 1);
|
||||
::setenv("XDG_CACHE_HOME", root.c_str(), 1);
|
||||
::setenv("HOME", root.c_str(), 1);
|
||||
const auto stateDirectory = root / "runtime-state";
|
||||
::setenv("ECHOION_STATE_DIR", stateDirectory.c_str(), 1);
|
||||
const auto dataDirectory = stateDirectory / "data";
|
||||
::setenv("XDG_DATA_HOME", dataDirectory.c_str(), 1);
|
||||
const auto ytDlp = dataDirectory / "echoion" / "yt-dlp" / "yt-dlp";
|
||||
std::filesystem::create_directories(ytDlp.parent_path());
|
||||
{
|
||||
std::ofstream output{ytDlp};
|
||||
output << "#!/bin/sh\necho 9999.01.01\n";
|
||||
}
|
||||
{
|
||||
std::ofstream output{ytDlp.parent_path() / ".last_update"};
|
||||
output << std::time(nullptr);
|
||||
}
|
||||
std::filesystem::permissions(ytDlp,
|
||||
std::filesystem::perms::owner_read |
|
||||
std::filesystem::perms::owner_write |
|
||||
std::filesystem::perms::owner_exec);
|
||||
const auto config = root / "config.json";
|
||||
{
|
||||
std::ofstream output{config};
|
||||
output << R"({
|
||||
"network": {"rpcEnabled": false},
|
||||
"web": {"enabled": false},
|
||||
"features": {"enableAutoUpdateCheck": false},
|
||||
"advanced": {"cacheEnabled": false}
|
||||
})";
|
||||
}
|
||||
|
||||
const auto coreDirectory = root / "immutable-lib";
|
||||
std::filesystem::create_directories(coreDirectory);
|
||||
const auto corePath = coreDirectory / "Echoion.ts";
|
||||
std::filesystem::copy_file(ECHOION_TEST_CORE_PATH, corePath);
|
||||
const auto directoryEntries = [&coreDirectory] {
|
||||
std::set<std::filesystem::path> entries;
|
||||
for (const auto& entry :
|
||||
std::filesystem::directory_iterator{coreDirectory}) {
|
||||
entries.insert(entry.path().filename());
|
||||
}
|
||||
return entries;
|
||||
};
|
||||
const auto entriesBeforeLoad = directoryEntries();
|
||||
std::filesystem::permissions(coreDirectory,
|
||||
std::filesystem::perms::owner_read |
|
||||
std::filesystem::perms::owner_exec |
|
||||
std::filesystem::perms::group_read |
|
||||
std::filesystem::perms::group_exec |
|
||||
std::filesystem::perms::others_read |
|
||||
std::filesystem::perms::others_exec,
|
||||
std::filesystem::perm_options::replace);
|
||||
|
||||
Echoion::Host::CoreLoader loader;
|
||||
loader.setConfigPath(config);
|
||||
if (auto result = loader.load(corePath); !result) {
|
||||
cleanup();
|
||||
return fail(result.error().message.c_str());
|
||||
}
|
||||
if (directoryEntries() != entriesBeforeLoad) {
|
||||
cleanup();
|
||||
return fail(
|
||||
"initial Core load wrote into the immutable library directory");
|
||||
}
|
||||
loader.enableAutoReload();
|
||||
if (loader.isAutoReloadEnabled()) {
|
||||
cleanup();
|
||||
return fail("auto-reload was enabled for a read-only Core directory");
|
||||
}
|
||||
std::filesystem::permissions(coreDirectory,
|
||||
std::filesystem::perms::owner_all |
|
||||
std::filesystem::perms::group_read |
|
||||
std::filesystem::perms::group_exec |
|
||||
std::filesystem::perms::others_read |
|
||||
std::filesystem::perms::others_exec,
|
||||
std::filesystem::perm_options::replace);
|
||||
loader.enableAutoReload();
|
||||
if (!loader.isAutoReloadEnabled()) {
|
||||
cleanup();
|
||||
return fail(
|
||||
"auto-reload was not enabled for a writable development Core");
|
||||
}
|
||||
loader.disableAutoReload();
|
||||
const auto before = loader.getCore();
|
||||
if (!before) {
|
||||
cleanup();
|
||||
return fail("Core missing after initial load");
|
||||
}
|
||||
if (!std::filesystem::is_regular_file(stateDirectory / "echoion.db") ||
|
||||
std::filesystem::exists(root / "echoion.db") ||
|
||||
!std::filesystem::is_directory(stateDirectory / "logs")) {
|
||||
cleanup();
|
||||
return fail("Core mutable files did not use ECHOION_STATE_DIR");
|
||||
}
|
||||
if (auto result = loader.hotReload(corePath); !result) {
|
||||
cleanup();
|
||||
return fail(result.error().message.c_str());
|
||||
}
|
||||
const auto after = loader.getCore();
|
||||
if (!after || after.get() == before.get()) {
|
||||
cleanup();
|
||||
return fail("Core instance was not transactionally replaced");
|
||||
}
|
||||
|
||||
const auto invalid = root / "Echoion.invalid";
|
||||
{
|
||||
std::ofstream output{invalid, std::ios::binary};
|
||||
output << "not a shared library";
|
||||
}
|
||||
std::filesystem::rename(invalid, corePath);
|
||||
if (auto result = loader.hotReload(corePath); result) {
|
||||
cleanup();
|
||||
return fail("invalid replacement unexpectedly activated");
|
||||
}
|
||||
const auto retained = loader.getCore();
|
||||
if (!retained || retained.get() != after.get() ||
|
||||
!retained->isInitialized()) {
|
||||
cleanup();
|
||||
return fail("running Core was not retained after failed activation");
|
||||
}
|
||||
if (auto result = loader.unload(); !result) {
|
||||
cleanup();
|
||||
return fail(result.error().message.c_str());
|
||||
}
|
||||
cleanup();
|
||||
return 0;
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
#include "echoion/standalone/EventCallbackGate.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
int main()
|
||||
{
|
||||
Echoion::Standalone::EventCallbackGate gate;
|
||||
std::mutex mutex;
|
||||
std::condition_variable enteredCv;
|
||||
std::condition_variable releaseCv;
|
||||
bool entered = false;
|
||||
bool release = false;
|
||||
std::atomic<int> calls{0};
|
||||
auto lifetime = std::make_shared<int>(42);
|
||||
std::weak_ptr<int> observedLifetime = lifetime;
|
||||
|
||||
gate.add([&, lifetime](const Echoion::Api::PluginEvent&) {
|
||||
++calls;
|
||||
std::unique_lock lock(mutex);
|
||||
entered = true;
|
||||
enteredCv.notify_all();
|
||||
releaseCv.wait(lock, [&] { return release; });
|
||||
});
|
||||
lifetime.reset();
|
||||
|
||||
Echoion::Api::PluginEvent event;
|
||||
auto dispatch = std::async(std::launch::async, [&] { gate.dispatch(event); });
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
enteredCv.wait(lock, [&] { return entered; });
|
||||
}
|
||||
|
||||
auto quiesce = std::async(std::launch::async, [&] { gate.quiesce(); });
|
||||
assert(quiesce.wait_for(std::chrono::milliseconds{30}) ==
|
||||
std::future_status::timeout);
|
||||
assert(!observedLifetime.expired());
|
||||
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
release = true;
|
||||
}
|
||||
releaseCv.notify_all();
|
||||
dispatch.get();
|
||||
quiesce.get();
|
||||
assert(observedLifetime.expired());
|
||||
|
||||
gate.dispatch(event);
|
||||
assert(calls == 1);
|
||||
|
||||
gate.add([&](const Echoion::Api::PluginEvent&) { ++calls; });
|
||||
gate.dispatch(event);
|
||||
assert(calls == 2);
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
#include "echoion/standalone/MessageChunker.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
bool check(bool condition, const char* message)
|
||||
{
|
||||
if (!condition) {
|
||||
std::cerr << "FAILED: " << message << '\n';
|
||||
}
|
||||
return condition;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
using Echoion::Standalone::chunkMessage;
|
||||
bool passed = true;
|
||||
|
||||
const std::string header = "# Help\n\n> [!TIP] Prefix is `!`\n\n";
|
||||
const std::string details =
|
||||
":::details ▶ Play — commands\n\n" + std::string(1100, 'x') +
|
||||
"\n\n`!play` query\n> description\n:::\n\n";
|
||||
const auto helpChunks = chunkMessage(header + details, 900);
|
||||
passed &= check(helpChunks.size() == 2,
|
||||
"help header and details block should be separate messages");
|
||||
passed &= check(helpChunks.size() > 1 &&
|
||||
helpChunks[1] == details.substr(0, details.size() - 1),
|
||||
"details container must remain complete even above the limit");
|
||||
|
||||
const std::string utf8Line = std::string(899, 'a') + "я" + "tail";
|
||||
const auto utf8Chunks = chunkMessage(utf8Line, 900);
|
||||
passed &= check(utf8Chunks.size() == 2,
|
||||
"long ordinary line should be split");
|
||||
passed &= check(!utf8Chunks.empty() && utf8Chunks.front().size() == 899,
|
||||
"UTF-8 sequence should not be split in the middle");
|
||||
|
||||
return passed ? 0 : 1;
|
||||
}
|
||||
@@ -1,289 +0,0 @@
|
||||
#include "echoion/standalone/ReleaseManifest.hpp"
|
||||
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <sys/stat.h>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr std::string_view kAbcSha256 =
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
|
||||
|
||||
std::string fileEntry(std::string_view path, std::uintmax_t size,
|
||||
std::string_view mode,
|
||||
std::string_view sha256 = kAbcSha256)
|
||||
{
|
||||
return "{\"path\":\"" + std::string(path) +
|
||||
"\",\"type\":\"file\",\"size\":" + std::to_string(size) +
|
||||
",\"mode\":\"" + std::string(mode) + "\",\"sha256\":\"" +
|
||||
std::string(sha256) + "\"}";
|
||||
}
|
||||
|
||||
std::string symlinkEntry(std::string_view path, std::string_view target)
|
||||
{
|
||||
return "{\"path\":\"" + std::string(path) +
|
||||
"\",\"type\":\"symlink\",\"target\":\"" + std::string(target) +
|
||||
"\"}";
|
||||
}
|
||||
|
||||
std::string manifest(std::vector<std::string> entries,
|
||||
std::string_view executable = "bin/echoiond",
|
||||
std::string_view core = "lib/Echoion.ts")
|
||||
{
|
||||
std::string files;
|
||||
for (const auto& entry : entries) {
|
||||
if (!files.empty()) {
|
||||
files += ',';
|
||||
}
|
||||
files += entry;
|
||||
}
|
||||
return "{\"schemaVersion\":2,\"version\":\"1.2.3\","
|
||||
"\"executable\":\"" +
|
||||
std::string(executable) + "\",\"core\":\"" + std::string(core) +
|
||||
"\",\"files\":[" + files + "]}";
|
||||
}
|
||||
|
||||
bool writeFile(const std::filesystem::path& path, std::string_view contents,
|
||||
std::filesystem::perms permissions)
|
||||
{
|
||||
std::filesystem::create_directories(path.parent_path());
|
||||
if (auto result = Void::FileSystem::atomic_write(path, contents);
|
||||
!result) {
|
||||
std::cerr << result.error().message() << '\n';
|
||||
return false;
|
||||
}
|
||||
std::error_code error;
|
||||
std::filesystem::permissions(
|
||||
path, permissions, std::filesystem::perm_options::replace, error);
|
||||
if (error) {
|
||||
std::cerr << error.message() << '\n';
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
int failures{};
|
||||
const auto check = [&failures](bool condition, std::string_view message) {
|
||||
if (!condition) {
|
||||
std::cerr << message << '\n';
|
||||
++failures;
|
||||
}
|
||||
};
|
||||
|
||||
auto directory = Void::FileSystem::TempDir::open("echoion-manifest-test");
|
||||
if (!directory) {
|
||||
std::cerr << directory.error().message() << '\n';
|
||||
return 1;
|
||||
}
|
||||
const auto root = directory->path();
|
||||
const auto manifestPath = root / "manifest.json";
|
||||
const auto executablePath = root / "bin" / "echoiond";
|
||||
const auto corePath = root / "lib" / "Echoion.ts";
|
||||
const auto webPath = root / "share" / "echoion" / "web" / "index.html";
|
||||
const auto servicePath = root / "service" / "echoion.service.in";
|
||||
const auto aliasPath = root / "lib" / "libEchoionCore.so";
|
||||
const auto otherPath = root / "lib" / "Other.so";
|
||||
const auto executableMode = std::filesystem::perms::owner_read |
|
||||
std::filesystem::perms::owner_write |
|
||||
std::filesystem::perms::owner_exec |
|
||||
std::filesystem::perms::group_read |
|
||||
std::filesystem::perms::group_exec |
|
||||
std::filesystem::perms::others_read |
|
||||
std::filesystem::perms::others_exec;
|
||||
const auto regularMode = std::filesystem::perms::owner_read |
|
||||
std::filesystem::perms::owner_write |
|
||||
std::filesystem::perms::group_read |
|
||||
std::filesystem::perms::others_read;
|
||||
|
||||
if (!writeFile(executablePath, "abc", executableMode) ||
|
||||
!writeFile(corePath, "abc", regularMode) ||
|
||||
!writeFile(webPath, "abc", regularMode) ||
|
||||
!writeFile(servicePath, "abc", regularMode) ||
|
||||
!writeFile(otherPath, "abc", regularMode)) {
|
||||
return 1;
|
||||
}
|
||||
std::error_code error;
|
||||
std::filesystem::create_symlink("Echoion.ts", aliasPath, error);
|
||||
if (error) {
|
||||
std::cerr << error.message() << '\n';
|
||||
return 1;
|
||||
}
|
||||
|
||||
const auto validManifest = manifest({
|
||||
fileEntry("bin/echoiond", 3, "0755"),
|
||||
fileEntry("lib/Echoion.ts", 3, "0644"),
|
||||
fileEntry("lib/Other.so", 3, "0644"),
|
||||
fileEntry("service/echoion.service.in", 3, "0644"),
|
||||
fileEntry("share/echoion/web/index.html", 3, "0644"),
|
||||
symlinkEntry("lib/libEchoionCore.so", "Echoion.ts"),
|
||||
});
|
||||
check(
|
||||
Void::FileSystem::atomic_write(manifestPath, validManifest).has_value(),
|
||||
"failed to write valid manifest");
|
||||
auto loaded = Echoion::Standalone::ReleaseManifest::load(manifestPath);
|
||||
check(loaded.has_value(), "valid v2 manifest was rejected while loading");
|
||||
if (loaded) {
|
||||
check(loaded->validate().has_value(),
|
||||
"valid v2 manifest payload was rejected");
|
||||
check(loaded->validateInstallLayout().has_value(),
|
||||
"valid canonical install layout was rejected");
|
||||
|
||||
const auto undeclaredFile = root / "lib" / "undeclared.so";
|
||||
check(writeFile(undeclaredFile, "abc", regularMode),
|
||||
"failed to create undeclared regular-file fixture");
|
||||
check(!loaded->validate(),
|
||||
"undeclared regular file in immutable payload was accepted");
|
||||
std::filesystem::remove(undeclaredFile, error);
|
||||
|
||||
const auto undeclaredLink = root / "lib" / "undeclared-link.so";
|
||||
std::filesystem::create_symlink("Echoion.ts", undeclaredLink, error);
|
||||
check(!error, "failed to create undeclared symbolic-link fixture");
|
||||
check(!loaded->validate(),
|
||||
"undeclared symbolic link in immutable payload was accepted");
|
||||
std::filesystem::remove(undeclaredLink, error);
|
||||
|
||||
const auto specialFile = root / "lib" / "unexpected.fifo";
|
||||
check(::mkfifo(specialFile.c_str(), 0600) == 0,
|
||||
"failed to create special-file fixture");
|
||||
check(!loaded->validate(),
|
||||
"special file in immutable payload was accepted");
|
||||
std::filesystem::remove(specialFile, error);
|
||||
|
||||
check(writeFile(root / "data" / "mutable-state", "abc", regularMode),
|
||||
"failed to create mutable-root fixture");
|
||||
check(loaded->validate().has_value(),
|
||||
"mutable file outside immutable payload roots was rejected");
|
||||
|
||||
std::filesystem::permissions(root / "lib", std::filesystem::perms::all,
|
||||
std::filesystem::perm_options::replace,
|
||||
error);
|
||||
check(!error, "failed to make immutable directory writable");
|
||||
check(!loaded->validate(),
|
||||
"world-writable immutable directory was accepted");
|
||||
std::filesystem::permissions(root / "lib",
|
||||
std::filesystem::perms::owner_all |
|
||||
std::filesystem::perms::group_read |
|
||||
std::filesystem::perms::group_exec |
|
||||
std::filesystem::perms::others_read |
|
||||
std::filesystem::perms::others_exec,
|
||||
std::filesystem::perm_options::replace,
|
||||
error);
|
||||
check(!error, "failed to restore immutable directory mode");
|
||||
}
|
||||
|
||||
const auto expectLoadFailure = [&](const std::string& contents,
|
||||
std::string_view message) {
|
||||
check(
|
||||
Void::FileSystem::atomic_write(manifestPath, contents).has_value(),
|
||||
"failed to write invalid manifest fixture");
|
||||
check(!Echoion::Standalone::ReleaseManifest::load(manifestPath),
|
||||
message);
|
||||
};
|
||||
expectLoadFailure(manifest({fileEntry("../echoiond", 3, "0755"),
|
||||
fileEntry("lib/Echoion.ts", 3, "0644")},
|
||||
"../echoiond"),
|
||||
"path traversal manifest was accepted");
|
||||
expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0755"),
|
||||
fileEntry("bin/echoiond", 3, "0755"),
|
||||
fileEntry("lib/Echoion.ts", 3, "0644")}),
|
||||
"duplicate payload path was accepted");
|
||||
expectLoadFailure(
|
||||
manifest({fileEntry("bin/echoiond", 3, "0755"),
|
||||
fileEntry("lib/Echoion.ts", 3, "0644"),
|
||||
symlinkEntry("lib/escape.so", "../outside.so")}),
|
||||
"traversing symbolic link target was accepted");
|
||||
expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0777"),
|
||||
fileEntry("lib/Echoion.ts", 3, "0644")}),
|
||||
"world-writable executable metadata was accepted");
|
||||
expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0755"),
|
||||
fileEntry("lib/Echoion.ts", 3, "0666")}),
|
||||
"world-writable non-executable metadata was accepted");
|
||||
check(writeFile(root / "outside.dat", "abc", regularMode),
|
||||
"failed to create outside-root manifest fixture");
|
||||
const auto outsideManifest = manifest({
|
||||
fileEntry("bin/echoiond", 3, "0755"),
|
||||
fileEntry("lib/Echoion.ts", 3, "0644"),
|
||||
fileEntry("lib/Other.so", 3, "0644"),
|
||||
fileEntry("service/echoion.service.in", 3, "0644"),
|
||||
fileEntry("share/echoion/web/index.html", 3, "0644"),
|
||||
symlinkEntry("lib/libEchoionCore.so", "Echoion.ts"),
|
||||
fileEntry("outside.dat", 3, "0644"),
|
||||
});
|
||||
check(Void::FileSystem::atomic_write(manifestPath, outsideManifest)
|
||||
.has_value(),
|
||||
"failed to write outside-root manifest");
|
||||
const auto outside =
|
||||
Echoion::Standalone::ReleaseManifest::load(manifestPath);
|
||||
check(outside.has_value() && !outside->validate(),
|
||||
"manifest entry outside immutable roots was accepted");
|
||||
expectLoadFailure("{\"schemaVersion\":3,\"version\":\"future\"}",
|
||||
"unsupported schema version was accepted");
|
||||
|
||||
check(
|
||||
Void::FileSystem::atomic_write(manifestPath, validManifest).has_value(),
|
||||
"failed to restore valid manifest");
|
||||
loaded = Echoion::Standalone::ReleaseManifest::load(manifestPath);
|
||||
if (!loaded) {
|
||||
std::cerr << "could not reload valid manifest\n";
|
||||
return 1;
|
||||
}
|
||||
{
|
||||
std::ofstream output(corePath, std::ios::trunc);
|
||||
output << "xyz";
|
||||
}
|
||||
check(!loaded->validate(), "tampered payload hash was accepted");
|
||||
check(writeFile(corePath, "abc", regularMode),
|
||||
"failed to restore Core fixture");
|
||||
|
||||
std::filesystem::permissions(corePath, std::filesystem::perms::owner_read,
|
||||
std::filesystem::perm_options::replace, error);
|
||||
check(!error, "failed to modify Core permissions fixture");
|
||||
check(!loaded->validate(), "payload mode mismatch was accepted");
|
||||
std::filesystem::permissions(corePath, regularMode,
|
||||
std::filesystem::perm_options::replace, error);
|
||||
|
||||
std::filesystem::remove(aliasPath, error);
|
||||
std::filesystem::create_symlink("Other.so", aliasPath, error);
|
||||
check(!error, "failed to replace symbolic link fixture");
|
||||
check(!loaded->validate(), "symbolic link target mismatch was accepted");
|
||||
std::filesystem::remove(aliasPath, error);
|
||||
check(writeFile(aliasPath, "abc", regularMode),
|
||||
"failed to create wrong-type fixture");
|
||||
check(!loaded->validate(), "unexpected regular-file type was accepted");
|
||||
std::filesystem::remove(aliasPath, error);
|
||||
std::filesystem::create_symlink("Echoion.ts", aliasPath, error);
|
||||
|
||||
std::filesystem::remove(webPath, error);
|
||||
check(!loaded->validate(), "missing payload entry was accepted");
|
||||
check(writeFile(webPath, "abc", regularMode),
|
||||
"failed to restore web fixture");
|
||||
|
||||
const std::string legacyManifest =
|
||||
"{\"version\":\"legacy\",\"executable\":\"bin/echoiond\","
|
||||
"\"core\":\"lib/Echoion.ts\",\"sha256\":{\"executable\":\"" +
|
||||
std::string(kAbcSha256) + "\",\"core\":\"" + std::string(kAbcSha256) +
|
||||
"\"}}";
|
||||
check(Void::FileSystem::atomic_write(manifestPath, legacyManifest)
|
||||
.has_value(),
|
||||
"failed to write legacy manifest");
|
||||
auto legacy = Echoion::Standalone::ReleaseManifest::load(manifestPath);
|
||||
check(legacy.has_value(), "legacy release manifest was rejected");
|
||||
if (legacy) {
|
||||
check(legacy->validate().has_value(),
|
||||
"legacy release payload was rejected");
|
||||
check(!legacy->validateInstallLayout(),
|
||||
"legacy manifest was accepted for full install validation");
|
||||
}
|
||||
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
#include "echoion/standalone/RuntimePaths.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
class TemporaryTree
|
||||
{
|
||||
public:
|
||||
|
||||
TemporaryTree()
|
||||
{
|
||||
std::random_device random;
|
||||
path_ =
|
||||
std::filesystem::temp_directory_path() /
|
||||
("echoion-runtime-paths-" +
|
||||
std::to_string(static_cast<unsigned long long>(random())));
|
||||
std::filesystem::create_directories(path_);
|
||||
}
|
||||
|
||||
~TemporaryTree()
|
||||
{
|
||||
std::error_code error;
|
||||
std::filesystem::remove_all(path_, error);
|
||||
}
|
||||
|
||||
TemporaryTree(const TemporaryTree&) = delete;
|
||||
TemporaryTree& operator=(const TemporaryTree&) = delete;
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& path() const noexcept
|
||||
{
|
||||
return path_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::filesystem::path path_;
|
||||
};
|
||||
|
||||
bool writeFile(const std::filesystem::path& path)
|
||||
{
|
||||
std::filesystem::create_directories(path.parent_path());
|
||||
std::ofstream output(path);
|
||||
output << "test\n";
|
||||
return output.good();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
int failures{};
|
||||
const auto check = [&failures](bool condition, const std::string& message) {
|
||||
if (!condition) {
|
||||
std::cerr << message << '\n';
|
||||
++failures;
|
||||
}
|
||||
};
|
||||
|
||||
TemporaryTree tree;
|
||||
const auto installRoot = tree.path() / "echoion";
|
||||
const auto executable = installRoot / "bin" / "echoiond";
|
||||
const auto executableDirectory = executable.parent_path();
|
||||
check(Echoion::Standalone::deriveInstallRoot(executable) == installRoot,
|
||||
"bin/echoiond did not resolve to its installation root");
|
||||
check(Echoion::Standalone::deriveInstallRoot(
|
||||
executable, tree.path() / "override") == tree.path() / "override",
|
||||
"ECHOION_HOME-style override was not preferred");
|
||||
|
||||
const auto state = Echoion::Standalone::resolveStateDirectory(
|
||||
tree.path() / "cli-state", tree.path() / "environment-state",
|
||||
tree.path() / "xdg-state", tree.path() / "home",
|
||||
tree.path() / "fallback");
|
||||
check(state == tree.path() / "cli-state",
|
||||
"command-line state directory did not win precedence");
|
||||
check(Echoion::Standalone::resolveStateDirectory(
|
||||
std::nullopt, tree.path() / "environment-state",
|
||||
tree.path() / "xdg-state", tree.path() / "home",
|
||||
tree.path() / "fallback") == tree.path() / "environment-state",
|
||||
"environment state directory did not win precedence");
|
||||
check(Echoion::Standalone::resolveStateDirectory(
|
||||
std::nullopt, std::nullopt, tree.path() / "xdg-state",
|
||||
tree.path() / "home", tree.path() / "fallback") ==
|
||||
tree.path() / "xdg-state" / "echoion",
|
||||
"XDG state directory fallback is incorrect");
|
||||
|
||||
const auto packagedCore = installRoot / "lib" / "Echoion.ts";
|
||||
check(writeFile(packagedCore), "failed to create packaged Core fixture");
|
||||
check(Echoion::Standalone::resolveCorePath(
|
||||
installRoot, executableDirectory) == packagedCore,
|
||||
"packaged Core was not resolved from install-root/lib");
|
||||
check(Echoion::Standalone::resolveCorePath(
|
||||
installRoot, executableDirectory,
|
||||
std::filesystem::path{"custom/Echoion.ts"}) ==
|
||||
installRoot / "custom" / "Echoion.ts",
|
||||
"relative Core override was not anchored at the install root");
|
||||
|
||||
const auto packagedIndex =
|
||||
installRoot / "share" / "echoion" / "web" / "index.html";
|
||||
check(writeFile(packagedIndex), "failed to create packaged web fixture");
|
||||
check(Echoion::Standalone::runtimeWorkingDirectory(
|
||||
installRoot, executableDirectory) == installRoot,
|
||||
"packaged web root did not select the installation root as working "
|
||||
"directory");
|
||||
const auto bundledCertificates =
|
||||
installRoot / "share" / "echoion" / "certs" / "ca-certificates.crt";
|
||||
check(!Echoion::Standalone::bundledCertificateBundle(installRoot),
|
||||
"missing bundled certificate store was accepted");
|
||||
check(writeFile(bundledCertificates),
|
||||
"failed to create bundled certificate store fixture");
|
||||
check(Echoion::Standalone::bundledCertificateBundle(installRoot) ==
|
||||
bundledCertificates,
|
||||
"bundled certificate store was not resolved from the install root");
|
||||
std::filesystem::remove_all(installRoot / "share");
|
||||
const auto developmentIndex = executableDirectory / "web" / "index.html";
|
||||
check(writeFile(developmentIndex),
|
||||
"failed to create development web fixture");
|
||||
check(Echoion::Standalone::runtimeWorkingDirectory(
|
||||
installRoot, executableDirectory) == executableDirectory,
|
||||
"development web root did not select the executable directory");
|
||||
|
||||
const auto avatarCache = tree.path() / "state" / "avatars";
|
||||
std::filesystem::create_directories(avatarCache);
|
||||
check(Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache) ==
|
||||
avatarCache,
|
||||
"empty avatar directory request did not select the state cache");
|
||||
check(Echoion::Standalone::resolveAvatarCacheDirectory(
|
||||
avatarCache, "legacy") == avatarCache / "legacy",
|
||||
"relative avatar directory was not rooted below state");
|
||||
check(!Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache,
|
||||
"../escape"),
|
||||
"traversing avatar directory was accepted");
|
||||
check(!Echoion::Standalone::resolveAvatarCacheDirectory(
|
||||
avatarCache, tree.path() / "outside"),
|
||||
"absolute avatar directory outside state was accepted");
|
||||
const auto avatarEscape = avatarCache / "escape";
|
||||
std::error_code avatarError;
|
||||
std::filesystem::create_symlink(tree.path(), avatarEscape, avatarError);
|
||||
check(!avatarError, "failed to create avatar symlink escape fixture");
|
||||
check(!Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache,
|
||||
"escape/cache"),
|
||||
"avatar directory escaped state through a symbolic link");
|
||||
|
||||
const auto runningExecutable = Echoion::Standalone::runningExecutablePath();
|
||||
check(runningExecutable.has_value() &&
|
||||
std::filesystem::is_regular_file(*runningExecutable),
|
||||
"running executable could not be resolved through /proc/self/exe");
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
stage_script=$1
|
||||
updater=$2
|
||||
service_templates=$3
|
||||
generator=$(dirname -- "$stage_script")/generate-release-manifest.py
|
||||
manifest_validator=$(dirname -- "$stage_script")/validate-release-manifest.py
|
||||
root=$(mktemp -d)
|
||||
trap 'rm -rf -- "$root"' EXIT
|
||||
|
||||
bundle=$root/bundle
|
||||
mkdir -p -- \
|
||||
"$bundle/bin" \
|
||||
"$bundle/lib" \
|
||||
"$bundle/service" \
|
||||
"$bundle/share/echoion/certs" \
|
||||
"$bundle/share/echoion/tools" \
|
||||
"$bundle/share/echoion/web"
|
||||
printf '#!/bin/sh\necho "echoiond must not run during release staging" >&2\nexit 97\n' \
|
||||
> "$bundle/bin/echoiond"
|
||||
chmod 0755 "$bundle/bin/echoiond"
|
||||
install -m 0755 -- "$updater" "$bundle/bin/echoion-updater"
|
||||
printf 'test core\n' > "$bundle/lib/Echoion.ts"
|
||||
install -m 0644 -- \
|
||||
"$service_templates/echoion.service.in" \
|
||||
"$service_templates/echoion-updater.service.in" \
|
||||
"$service_templates/echoion-updater.timer.in" \
|
||||
"$bundle/service/"
|
||||
printf '{"webRoot":"./web"}\n' > "$bundle/share/echoion/config.example.json"
|
||||
printf 'test trust bundle\n' > "$bundle/share/echoion/certs/ca-certificates.crt"
|
||||
install -m 0755 -- "$manifest_validator" \
|
||||
"$bundle/share/echoion/tools/validate-release-manifest.py"
|
||||
printf '<!doctype html>\n' > "$bundle/share/echoion/web/index.html"
|
||||
ln -s -- Echoion.ts "$bundle/lib/libEchoionCore.so"
|
||||
|
||||
python3 "$generator" --root "$bundle" --version 1.2.3
|
||||
python3 "$manifest_validator" --root "$bundle" --version 1.2.3
|
||||
|
||||
bash "$stage_script" "$root/releases" 1.2.3 "$bundle"
|
||||
|
||||
manifest=$root/releases/pending-release.json
|
||||
test -x "$root/releases/1.2.3/bin/echoiond"
|
||||
test -x "$root/releases/1.2.3/bin/echoion-updater"
|
||||
test -f "$root/releases/1.2.3/lib/Echoion.ts"
|
||||
test -L "$root/releases/1.2.3/lib/libEchoionCore.so"
|
||||
grep -q '"version": "1.2.3"' "$manifest"
|
||||
grep -q '"executable": "1.2.3/bin/echoiond"' "$manifest"
|
||||
grep -q '"updater": "1.2.3/bin/echoion-updater"' "$manifest"
|
||||
grep -q '"path": "1.2.3/share/echoion/web/index.html"' "$manifest"
|
||||
python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3
|
||||
|
||||
printf 'tampered\n' >> "$root/releases/1.2.3/lib/Echoion.ts"
|
||||
if python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3 \
|
||||
>/dev/null 2>&1; then
|
||||
echo "tampered Core artifact was accepted" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if bash "$stage_script" "$root/releases" '../unsafe' "$bundle" \
|
||||
>/dev/null 2>&1; then
|
||||
echo "unsafe version was accepted" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,41 +0,0 @@
|
||||
#include "echoion/standalone/UpdateBuildDefaults.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <string_view>
|
||||
|
||||
#ifndef ECHOION_EXPECTED_RUNTIME_VERSION
|
||||
#error "ECHOION_EXPECTED_RUNTIME_VERSION must be defined by CMake"
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
bool check(bool condition, std::string_view message)
|
||||
{
|
||||
if (!condition) {
|
||||
std::cerr << "FAILED: " << message << '\n';
|
||||
}
|
||||
return condition;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
namespace Defaults = Echoion::Standalone::UpdateBuildDefaults;
|
||||
|
||||
bool passed = true;
|
||||
passed &=
|
||||
check(Defaults::RuntimeVersion == ECHOION_EXPECTED_RUNTIME_VERSION,
|
||||
"generated runtime version does not match the configured release "
|
||||
"version");
|
||||
passed &=
|
||||
check(!Defaults::ApiVersion.empty(), "generated API version is empty");
|
||||
passed &= check(!Defaults::ToolchainAbi.empty(),
|
||||
"generated toolchain ABI is empty");
|
||||
passed &=
|
||||
check(Defaults::PublicKeysJson.size() >= 2 &&
|
||||
Defaults::PublicKeysJson.front() == '[' &&
|
||||
Defaults::PublicKeysJson.back() == ']',
|
||||
"generated update public-key configuration is not a JSON array");
|
||||
|
||||
return passed ? 0 : 1;
|
||||
}
|
||||
@@ -1,742 +0,0 @@
|
||||
#include "echoion/standalone/UpdateService.hpp"
|
||||
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Text/Hex.hpp>
|
||||
#include <Void/Update/Update.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
class TemporaryTree
|
||||
{
|
||||
public:
|
||||
|
||||
TemporaryTree()
|
||||
{
|
||||
std::random_device random;
|
||||
path_ =
|
||||
std::filesystem::temp_directory_path() /
|
||||
("echoion-update-service-" +
|
||||
std::to_string(static_cast<unsigned long long>(random())));
|
||||
std::filesystem::create_directories(path_);
|
||||
}
|
||||
|
||||
~TemporaryTree()
|
||||
{
|
||||
std::error_code error;
|
||||
std::filesystem::remove_all(path_, error);
|
||||
}
|
||||
|
||||
TemporaryTree(const TemporaryTree&) = delete;
|
||||
TemporaryTree& operator=(const TemporaryTree&) = delete;
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& path() const noexcept
|
||||
{
|
||||
return path_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::filesystem::path path_;
|
||||
};
|
||||
|
||||
bool writeFile(const std::filesystem::path& path, std::string_view contents)
|
||||
{
|
||||
std::filesystem::create_directories(path.parent_path());
|
||||
std::ofstream output(path, std::ios::binary);
|
||||
output.write(contents.data(),
|
||||
static_cast<std::streamsize>(contents.size()));
|
||||
return output.good();
|
||||
}
|
||||
|
||||
std::string readFile(const std::filesystem::path& path)
|
||||
{
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
return {std::istreambuf_iterator<char>{input},
|
||||
std::istreambuf_iterator<char>{}};
|
||||
}
|
||||
|
||||
bool publishHistoricalVersion(const std::filesystem::path& root,
|
||||
std::string_view versionText,
|
||||
const std::filesystem::path& filename,
|
||||
std::string_view contents)
|
||||
{
|
||||
const auto version = Void::Semver::parse_strict(versionText);
|
||||
if (!version) {
|
||||
return false;
|
||||
}
|
||||
Void::Update::VersionStore store(root);
|
||||
if (auto initialized = store.initialize(); !initialized) {
|
||||
return false;
|
||||
}
|
||||
auto staging = store.prepare(*version);
|
||||
if (!staging || !writeFile(*staging / filename, contents)) {
|
||||
return false;
|
||||
}
|
||||
if (auto published = store.publish(*version, *staging); !published) {
|
||||
return false;
|
||||
}
|
||||
return store.recordHealthy(*version).has_value();
|
||||
}
|
||||
|
||||
bool activatePublishedVersion(const std::filesystem::path& root,
|
||||
std::string_view versionText)
|
||||
{
|
||||
const auto version = Void::Semver::parse_strict(versionText);
|
||||
if (!version) {
|
||||
return false;
|
||||
}
|
||||
Void::Update::VersionStore store(root);
|
||||
if (auto initialized = store.initialize(); !initialized) {
|
||||
return false;
|
||||
}
|
||||
if (auto activated = store.activate(*version); !activated) {
|
||||
return false;
|
||||
}
|
||||
return store.commit().has_value();
|
||||
}
|
||||
|
||||
std::string sha256(std::string_view contents)
|
||||
{
|
||||
auto digest = Void::Crypto::sha256(contents);
|
||||
return digest ? Void::Encoding::Hex::encode(*digest) : std::string{};
|
||||
}
|
||||
|
||||
std::string architecture()
|
||||
{
|
||||
#if defined(__x86_64__) || defined(_M_X64)
|
||||
return "x86_64";
|
||||
#elif defined(__aarch64__) || defined(_M_ARM64)
|
||||
return "aarch64";
|
||||
#elif defined(__i386__) || defined(_M_IX86)
|
||||
return "x86";
|
||||
#else
|
||||
return "unknown";
|
||||
#endif
|
||||
}
|
||||
|
||||
std::string configDocument(const std::filesystem::path& feed)
|
||||
{
|
||||
return R"json({"updates":{"enabled":false,"retainHealthyVersions":1,"sources":{"official":{"url":"file://)json" +
|
||||
feed.string() +
|
||||
R"json(","publicKeys":[],"allowUnsigned":true,"bearerTokenEnv":""}},"runtime":{"enabled":false,"source":"official","channel":"stable","autoApply":false},"core":{"enabled":true,"source":"official","channel":"stable","autoApply":false},"plugins":{"enabled":true,"source":"official","channel":"stable","autoApply":false,"managedOnly":true,"overrides":{}}}})json";
|
||||
}
|
||||
|
||||
std::string release(std::string_view component, std::string_view artifactId,
|
||||
std::string_view version,
|
||||
const std::filesystem::path& artifact,
|
||||
std::string_view contents)
|
||||
{
|
||||
return std::format(
|
||||
R"json({{"component":"{}","artifactId":"{}","channel":"stable","version":"{}","cohort":"test","platform":"linux","arch":"{}","url":"file://{}","size":{},"sha256":"{}","packageType":"file","compatibility":{{"versionContracts":{{}},"exactContracts":{{}}}},"releaseManifestSha256":"0000000000000000000000000000000000000000000000000000000000000000"}})json",
|
||||
component, artifactId, version, architecture(), artifact.string(),
|
||||
contents.size(), sha256(contents));
|
||||
}
|
||||
|
||||
std::string feedDocument(const std::filesystem::path& coreArtifact,
|
||||
std::string_view coreContents,
|
||||
const std::filesystem::path& pluginArtifact,
|
||||
std::string_view pluginContents,
|
||||
std::uint64_t sequence = 1)
|
||||
{
|
||||
return std::format(
|
||||
R"json({{"schemaVersion":1,"feedId":"test","sequence":{},"generatedAt":"2026-01-01T00:00:00Z","expiresAt":"2099-01-01T00:00:00Z","releases":[{},{}]}})json",
|
||||
sequence,
|
||||
release("core", "", "2.0.0", coreArtifact, coreContents),
|
||||
release("plugin", "fixture", "4.0.0", pluginArtifact,
|
||||
pluginContents));
|
||||
}
|
||||
|
||||
const Void::Json::Value*
|
||||
parseResponse(const Echoion::Api::Result<std::string>& response,
|
||||
std::optional<Void::Json::Value>& storage)
|
||||
{
|
||||
if (!response) {
|
||||
return nullptr;
|
||||
}
|
||||
auto parsed = Void::Json::parse(*response);
|
||||
if (!parsed) {
|
||||
return nullptr;
|
||||
}
|
||||
storage = std::move(*parsed);
|
||||
return &*storage;
|
||||
}
|
||||
|
||||
std::string coreCandidateId(const Void::Json::Value& status)
|
||||
{
|
||||
const auto* components = status.find("components");
|
||||
const auto* core = components ? components->find("core") : nullptr;
|
||||
const auto* candidate = core ? core->find("candidate") : nullptr;
|
||||
const auto* id = candidate ? candidate->find("id") : nullptr;
|
||||
return id && id->is_string() ? id->as_string() : std::string{};
|
||||
}
|
||||
|
||||
std::string pluginCandidateId(const Void::Json::Value& status)
|
||||
{
|
||||
const auto* plugins = status.find("plugins");
|
||||
if (!plugins || !plugins->is_array()) {
|
||||
return {};
|
||||
}
|
||||
for (const auto& plugin : plugins->as_array()) {
|
||||
if (plugin.get_str("id") != "fixture") {
|
||||
continue;
|
||||
}
|
||||
const auto* candidate = plugin.find("candidate");
|
||||
const auto* id = candidate ? candidate->find("id") : nullptr;
|
||||
return id && id->is_string() ? id->as_string() : std::string{};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::string componentRollbackVersion(const Void::Json::Value& status,
|
||||
std::string_view componentId)
|
||||
{
|
||||
const auto* components = status.find("components");
|
||||
const auto* component =
|
||||
components ? components->find(componentId) : nullptr;
|
||||
return component ? component->get_str("rollbackVersion")
|
||||
: std::string{};
|
||||
}
|
||||
|
||||
std::string pluginRollbackVersion(const Void::Json::Value& status,
|
||||
std::string_view pluginId)
|
||||
{
|
||||
const auto* plugins = status.find("plugins");
|
||||
if (!plugins || !plugins->is_array()) {
|
||||
return {};
|
||||
}
|
||||
for (const auto& plugin : plugins->as_array()) {
|
||||
if (plugin.get_str("id") == pluginId) {
|
||||
return plugin.get_str("rollbackVersion");
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::string confirmationToken(Echoion::Standalone::UpdateService& service,
|
||||
std::string_view component,
|
||||
std::string_view pluginId,
|
||||
std::string_view candidateId,
|
||||
std::string_view version)
|
||||
{
|
||||
const auto request = std::format(
|
||||
R"json({{"component":"{}","pluginId":"{}","candidateId":"{}","version":"{}","confirmation":"UNSIGNED {}"}})json",
|
||||
component, pluginId, candidateId, version, version);
|
||||
auto response = service.handle("updates.confirmUnsigned", request);
|
||||
if (!response) {
|
||||
return {};
|
||||
}
|
||||
auto parsed = Void::Json::parse(*response);
|
||||
return parsed ? parsed->get_str("confirmationToken") : std::string{};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
int failures{};
|
||||
const auto check = [&failures](bool condition, std::string_view message) {
|
||||
if (!condition) {
|
||||
std::cerr << message << '\n';
|
||||
++failures;
|
||||
}
|
||||
};
|
||||
|
||||
TemporaryTree tree;
|
||||
const auto startupState = tree.path() / "startup-state";
|
||||
const auto bundledStartupCore =
|
||||
tree.path() / "startup-runtime" / "lib" / "Echoion.ts";
|
||||
check(writeFile(bundledStartupCore, "runtime-core"),
|
||||
"failed to write startup Core fixture");
|
||||
const auto startupStore = startupState / "updates" / "components" / "core";
|
||||
check(publishHistoricalVersion(startupStore, "1.1.0", "Echoion.ts",
|
||||
"stale-managed-core"),
|
||||
"failed to publish stale managed Core fixture");
|
||||
check(activatePublishedVersion(startupStore, "1.1.0"),
|
||||
"failed to activate stale managed Core fixture");
|
||||
|
||||
auto firstRuntimeSelection =
|
||||
Echoion::Standalone::selectManagedCoreForStartup(
|
||||
startupState, bundledStartupCore, std::string_view{"2.0.0"});
|
||||
check(firstRuntimeSelection.has_value(),
|
||||
"runtime Core baseline selection failed");
|
||||
if (firstRuntimeSelection) {
|
||||
check(firstRuntimeSelection->corePath == bundledStartupCore,
|
||||
"new runtime did not prefer its bundled Core");
|
||||
check(firstRuntimeSelection->runtimeBaselineChanged,
|
||||
"new runtime did not report a Core baseline change");
|
||||
check(firstRuntimeSelection->archivedStore.has_value() &&
|
||||
std::filesystem::is_regular_file(
|
||||
*firstRuntimeSelection->archivedStore / "versions" /
|
||||
"1.1.0" / "Echoion.ts"),
|
||||
"stale managed Core store was not archived");
|
||||
}
|
||||
|
||||
check(publishHistoricalVersion(startupStore, "1.1.0", "Echoion.ts",
|
||||
"runtime-core"),
|
||||
"failed to seed the new runtime Core store");
|
||||
check(activatePublishedVersion(startupStore, "1.1.0"),
|
||||
"failed to activate the new runtime Core baseline");
|
||||
auto sameRuntimeSelection =
|
||||
Echoion::Standalone::selectManagedCoreForStartup(
|
||||
startupState, bundledStartupCore, std::string_view{"2.0.0"});
|
||||
check(sameRuntimeSelection.has_value() &&
|
||||
sameRuntimeSelection->corePath ==
|
||||
startupStore / "versions" / "1.1.0" / "Echoion.ts" &&
|
||||
!sameRuntimeSelection->runtimeBaselineChanged,
|
||||
"same runtime did not retain its managed Core selection");
|
||||
|
||||
auto nextRuntimeSelection =
|
||||
Echoion::Standalone::selectManagedCoreForStartup(
|
||||
startupState, bundledStartupCore, std::string_view{"2.1.0"});
|
||||
check(nextRuntimeSelection.has_value() &&
|
||||
nextRuntimeSelection->corePath == bundledStartupCore &&
|
||||
nextRuntimeSelection->runtimeBaselineChanged,
|
||||
"next runtime did not invalidate the prior managed Core baseline");
|
||||
|
||||
const auto state = tree.path() / "state";
|
||||
const auto incoming = tree.path() / "incoming";
|
||||
const auto currentCore = tree.path() / "installed" / "Echoion.ts";
|
||||
const auto currentPlugin = tree.path() / "installed" / "fixture.so";
|
||||
const auto installRoot = tree.path() / "runtime";
|
||||
const auto runningExecutable = installRoot / "bin" / "echoiond";
|
||||
const auto coreArtifact = incoming / "Echoion-2.0.0.ts";
|
||||
const auto pluginArtifact = incoming / "fixture-4.0.0.so";
|
||||
const auto feed = incoming / "feed.json";
|
||||
const auto config = tree.path() / "config.json";
|
||||
constexpr std::string_view oldCore = "old-core";
|
||||
constexpr std::string_view newCore = "new-core";
|
||||
constexpr std::string_view oldPlugin = "old-plugin";
|
||||
constexpr std::string_view newPlugin = "new-plugin";
|
||||
check(writeFile(currentCore, oldCore), "failed to write current Core");
|
||||
check(writeFile(currentPlugin, oldPlugin),
|
||||
"failed to write current plugin");
|
||||
check(writeFile(coreArtifact, newCore), "failed to write Core artifact");
|
||||
check(writeFile(pluginArtifact, newPlugin),
|
||||
"failed to write plugin artifact");
|
||||
check(writeFile(feed,
|
||||
feedDocument(coreArtifact, newCore, pluginArtifact,
|
||||
newPlugin, 9)),
|
||||
"failed to write update feed");
|
||||
check(writeFile(config, configDocument(feed)), "failed to write config");
|
||||
check(publishHistoricalVersion(state / "updates" / "components" / "core",
|
||||
"0.9.0", "Echoion.ts", "historical-core"),
|
||||
"failed to seed a historical Core version");
|
||||
check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture",
|
||||
"1.0.0", "fixture.so", "oldest-plugin"),
|
||||
"failed to seed the oldest historical plugin version");
|
||||
check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture",
|
||||
"2.0.0", "fixture.so", "historical-plugin"),
|
||||
"failed to seed a historical plugin version");
|
||||
check(publishHistoricalVersion(installRoot, "0.8.0", "bin/echoiond",
|
||||
"previous-runtime"),
|
||||
"failed to seed a runtime rollback version");
|
||||
check(publishHistoricalVersion(installRoot, "0.9.0", "bin/not-echoiond",
|
||||
"invalid-runtime-rollback"),
|
||||
"failed to seed a runtime rollback decoy");
|
||||
check(publishHistoricalVersion(installRoot, "1.0.0", "bin/echoiond",
|
||||
"current-runtime"),
|
||||
"failed to seed the current runtime version");
|
||||
check(activatePublishedVersion(installRoot, "1.0.0"),
|
||||
"failed to activate the current runtime version");
|
||||
|
||||
std::string coreVersion = "1.0.0";
|
||||
std::string pluginVersion = "3.0.0";
|
||||
std::filesystem::path activatedCore;
|
||||
std::filesystem::path activatedPlugin;
|
||||
int coreReplacements{};
|
||||
int pluginReplacements{};
|
||||
bool rejectCore{};
|
||||
Void::Update::VersionStore pluginStore(state / "plugins" / ".managed" /
|
||||
"fixture");
|
||||
|
||||
const auto makeService = [&] {
|
||||
return Echoion::Standalone::UpdateService(
|
||||
Echoion::Standalone::UpdateService::Options{
|
||||
.configPath = config,
|
||||
.stateDirectory = state,
|
||||
.installRoot = installRoot,
|
||||
.runningExecutable = runningExecutable,
|
||||
.currentCore = currentCore,
|
||||
.releaseManifestPath = {},
|
||||
.officialFeedUrl = {},
|
||||
.officialPublicKeysJson = "[]",
|
||||
.runtimeVersion = "1.0.0",
|
||||
.apiVersion = "1.1.0",
|
||||
.toolchainAbi = "test",
|
||||
.incomingDirectory = incoming},
|
||||
Echoion::Standalone::UpdateService::Hooks{
|
||||
.replaceCore = [&](const std::filesystem::path& path)
|
||||
-> Echoion::Api::Result<void> {
|
||||
++coreReplacements;
|
||||
if (rejectCore) {
|
||||
return Echoion::Api::fail(
|
||||
Echoion::Api::ErrorCode::PluginError,
|
||||
"rejected by test");
|
||||
}
|
||||
activatedCore = path;
|
||||
coreVersion = path.parent_path().filename().string();
|
||||
return {};
|
||||
},
|
||||
.managePlugins = [&](const std::string& request)
|
||||
-> Echoion::Api::Result<std::string> {
|
||||
auto parsed = Void::Json::parse(request);
|
||||
if (!parsed) {
|
||||
return Echoion::Api::fail(
|
||||
Echoion::Api::ErrorCode::ParseError,
|
||||
"invalid test request");
|
||||
}
|
||||
if (parsed->get_str("action") == "status") {
|
||||
return std::format(
|
||||
R"json({{"plugins":[{{"id":"fixture","name":"Fixture","version":"{}","path":"{}","managed":true}}]}})json",
|
||||
pluginVersion, currentPlugin.string());
|
||||
}
|
||||
if (parsed->get_str("action") != "replace") {
|
||||
return Echoion::Api::fail(
|
||||
Echoion::Api::ErrorCode::InvalidArgument,
|
||||
"unexpected test plugin action");
|
||||
}
|
||||
++pluginReplacements;
|
||||
activatedPlugin = parsed->get_str("path");
|
||||
pluginVersion = parsed->get_str("version");
|
||||
return "{}";
|
||||
},
|
||||
.manageRuntime = {},
|
||||
.playbackActive = [] { return false; },
|
||||
.coreVersion = [&] { return coreVersion; }});
|
||||
};
|
||||
auto service = makeService();
|
||||
check(service.start().has_value(), "UpdateService did not start");
|
||||
check(!std::filesystem::exists(
|
||||
pluginStore.versionPath(*Void::Semver::parse("1.0.0"))),
|
||||
"managed plugin startup retention did not prune the oldest version");
|
||||
|
||||
auto checked = service.handle("updates.check", "{}");
|
||||
std::optional<Void::Json::Value> checkedJson;
|
||||
const auto* checkedStatus = parseResponse(checked, checkedJson);
|
||||
check(checkedStatus != nullptr, "manual update check failed");
|
||||
const auto coreId = checkedStatus ? coreCandidateId(*checkedStatus) : "";
|
||||
const auto pluginId =
|
||||
checkedStatus ? pluginCandidateId(*checkedStatus) : "";
|
||||
if ((coreId.empty() || pluginId.empty()) && checked) {
|
||||
std::cerr << "update check response: " << *checked << '\n';
|
||||
}
|
||||
check(!coreId.empty(), "Core candidate was not selected");
|
||||
check(!pluginId.empty(), "plugin candidate was not selected");
|
||||
check(checkedStatus && !checkedStatus->get_bool("checking", true),
|
||||
"completed manual check was returned as still running");
|
||||
auto repeatedCheck = service.handle("updates.check", "{}");
|
||||
std::optional<Void::Json::Value> repeatedJson;
|
||||
const auto* repeatedStatus = parseResponse(repeatedCheck, repeatedJson);
|
||||
check(repeatedStatus && coreCandidateId(*repeatedStatus) == coreId &&
|
||||
pluginCandidateId(*repeatedStatus) == pluginId,
|
||||
"an unchanged feed sequence was incorrectly treated as a replay");
|
||||
const auto replacementFeed = incoming / "replacement-feed.json";
|
||||
check(writeFile(
|
||||
replacementFeed,
|
||||
feedDocument(coreArtifact, newCore, pluginArtifact, newPlugin)),
|
||||
"failed to write replacement update feed");
|
||||
auto replacementConfig = Void::Json::parse(configDocument(replacementFeed));
|
||||
const auto* replacementUpdates =
|
||||
replacementConfig ? replacementConfig->find("updates") : nullptr;
|
||||
check(replacementUpdates != nullptr,
|
||||
"failed to construct replacement updater configuration");
|
||||
bool replacementSaved = false;
|
||||
if (replacementUpdates) {
|
||||
replacementSaved =
|
||||
service
|
||||
.handle("updates.setConfig",
|
||||
std::format(R"({{"config":{}}})",
|
||||
Void::Json::serialize(*replacementUpdates)))
|
||||
.has_value();
|
||||
}
|
||||
check(replacementSaved, "custom source URL could not be saved");
|
||||
auto replacementCheck = service.handle("updates.check", "{}");
|
||||
std::optional<Void::Json::Value> replacementJson;
|
||||
const auto* replacementStatus =
|
||||
parseResponse(replacementCheck, replacementJson);
|
||||
check(replacementStatus && coreCandidateId(*replacementStatus) == coreId &&
|
||||
pluginCandidateId(*replacementStatus) == pluginId,
|
||||
"changing a custom source URL inherited the old feed replay floor");
|
||||
|
||||
const auto rejectedCoreToken =
|
||||
confirmationToken(service, "core", "", coreId, "2.0.0");
|
||||
check(!rejectedCoreToken.empty(), "Core unsigned confirmation failed");
|
||||
rejectCore = true;
|
||||
auto rejectedCoreApply = service.handle(
|
||||
"updates.apply",
|
||||
std::format(
|
||||
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
|
||||
coreId, rejectedCoreToken));
|
||||
check(rejectedCoreApply.has_value(), "failing Core apply did not queue");
|
||||
service.processPendingHostActions();
|
||||
check(coreReplacements == 1,
|
||||
"failing queued Core replacement did not run exactly once");
|
||||
auto replayedCoreApply = service.handle(
|
||||
"updates.apply",
|
||||
std::format(
|
||||
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
|
||||
coreId, rejectedCoreToken));
|
||||
check(!replayedCoreApply.has_value(),
|
||||
"failed unsigned Core apply reused a consumed confirmation token");
|
||||
|
||||
const auto coreToken =
|
||||
confirmationToken(service, "core", "", coreId, "2.0.0");
|
||||
check(!coreToken.empty(), "fresh Core unsigned confirmation failed");
|
||||
rejectCore = false;
|
||||
auto coreApply = service.handle(
|
||||
"updates.apply",
|
||||
std::format(
|
||||
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
|
||||
coreId, coreToken));
|
||||
check(coreApply.has_value(), "Core apply did not queue");
|
||||
check(coreReplacements == 1,
|
||||
"Core was replaced synchronously on the RPC call stack");
|
||||
service.processPendingHostActions();
|
||||
check(coreReplacements == 2, "queued Core replacement did not run");
|
||||
check(readFile(activatedCore) == newCore,
|
||||
"queued Core replacement used the wrong artifact");
|
||||
|
||||
Void::Update::VersionStore coreStore(state / "updates" / "components" /
|
||||
"core");
|
||||
auto activeCoreVersion = coreStore.currentVersion();
|
||||
check(activeCoreVersion && activeCoreVersion->has_value() &&
|
||||
(*activeCoreVersion)->to_string() == "2.0.0",
|
||||
"Core activation was not committed");
|
||||
check(readFile(coreStore.versionPath(*Void::Semver::parse("1.0.0")) /
|
||||
"Echoion.ts") == oldCore,
|
||||
"initial Core was not seeded for rollback");
|
||||
check(!std::filesystem::exists(
|
||||
coreStore.versionPath(*Void::Semver::parse("0.9.0"))),
|
||||
"Core retention did not remove an excess healthy version");
|
||||
|
||||
const auto pluginToken =
|
||||
confirmationToken(service, "plugins", "fixture", pluginId, "4.0.0");
|
||||
check(!pluginToken.empty(), "plugin unsigned confirmation failed");
|
||||
auto pluginApply = service.handle(
|
||||
"updates.apply",
|
||||
std::format(
|
||||
R"json({{"component":"plugins","pluginId":"fixture","candidateId":"{}","version":"4.0.0","confirmationToken":"{}"}})json",
|
||||
pluginId, pluginToken));
|
||||
check(pluginApply.has_value(), "plugin apply failed");
|
||||
check(pluginReplacements == 1 && readFile(activatedPlugin) == newPlugin,
|
||||
"plugin replacement used the wrong artifact");
|
||||
check(readFile(pluginStore.versionPath(*Void::Semver::parse("3.0.0")) /
|
||||
"fixture.so") == oldPlugin,
|
||||
"initial plugin was not seeded for rollback");
|
||||
check(!std::filesystem::exists(
|
||||
pluginStore.versionPath(*Void::Semver::parse("2.0.0"))),
|
||||
"plugin retention did not remove an excess healthy version");
|
||||
auto unsafePluginRollback = service.handle(
|
||||
"updates.rollback",
|
||||
R"({"component":"plugins","pluginId":"../escape","version":"3.0.0"})");
|
||||
check(!unsafePluginRollback.has_value(),
|
||||
"plugin rollback accepted a path-traversal plugin id");
|
||||
auto pluginRollback = service.handle(
|
||||
"updates.rollback",
|
||||
R"({"component":"plugins","pluginId":"fixture","version":"3.0.0"})");
|
||||
check(pluginRollback.has_value() && pluginReplacements == 2 &&
|
||||
readFile(activatedPlugin) == oldPlugin,
|
||||
"plugin rollback did not restore the seeded version");
|
||||
|
||||
auto unadvertisedRollback = service.handle(
|
||||
"updates.rollback", R"({"component":"core","version":"2.0.0"})");
|
||||
check(!unadvertisedRollback.has_value(),
|
||||
"Core rollback accepted a version that was not advertised healthy");
|
||||
auto rollback = service.handle("updates.rollback",
|
||||
R"({"component":"core","version":"1.0.0"})");
|
||||
check(rollback.has_value(), "Core rollback did not queue");
|
||||
check(coreReplacements == 2,
|
||||
"Core rollback ran synchronously on the RPC call stack");
|
||||
service.processPendingHostActions();
|
||||
check(coreReplacements == 3 && readFile(activatedCore) == oldCore,
|
||||
"queued Core rollback did not restore the seed");
|
||||
|
||||
rejectCore = true;
|
||||
auto failedRollback = service.handle(
|
||||
"updates.rollback", R"({"component":"core","version":"2.0.0"})");
|
||||
check(failedRollback.has_value(), "failing Core rollback did not queue");
|
||||
service.processPendingHostActions();
|
||||
activeCoreVersion = coreStore.currentVersion();
|
||||
check(coreReplacements == 4 && activeCoreVersion &&
|
||||
activeCoreVersion->has_value() &&
|
||||
(*activeCoreVersion)->to_string() == "1.0.0",
|
||||
"failed Core replacement did not roll back the VersionStore");
|
||||
auto finalStatus = service.handle("updates.getStatus", "{}");
|
||||
check(finalStatus && finalStatus->contains("rejected by test"),
|
||||
"failed deferred activation was not reported in status/history");
|
||||
const auto plugin4 = *Void::Semver::parse("4.0.0");
|
||||
check(pluginStore.activate(plugin4).has_value(),
|
||||
"could not stage an interrupted plugin activation");
|
||||
check(Echoion::Standalone::reconcileManagedPluginUpdates(state).has_value(),
|
||||
"managed plugin startup reconciliation failed");
|
||||
auto recoveredPluginVersion = pluginStore.currentVersion();
|
||||
check(recoveredPluginVersion && recoveredPluginVersion->has_value() &&
|
||||
(*recoveredPluginVersion)->to_string() == "3.0.0",
|
||||
"startup reconciliation did not roll back the interrupted plugin");
|
||||
const auto sequenceState = state / "updates" / "sequences.json";
|
||||
std::filesystem::remove(sequenceState);
|
||||
std::filesystem::create_directory(sequenceState);
|
||||
check(!service.handle("updates.check", "{}").has_value(),
|
||||
"update check ignored a replay-floor persistence failure");
|
||||
std::filesystem::remove(sequenceState);
|
||||
|
||||
service.stop();
|
||||
auto restarted = makeService();
|
||||
check(restarted.start().has_value(),
|
||||
"restarted UpdateService did not start");
|
||||
auto restartedStatusResponse = restarted.handle("updates.getStatus", "{}");
|
||||
std::optional<Void::Json::Value> restartedStatusJson;
|
||||
const auto* restartedStatus =
|
||||
parseResponse(restartedStatusResponse, restartedStatusJson);
|
||||
check(restartedStatus != nullptr,
|
||||
"restarted UpdateService did not return status");
|
||||
check(restartedStatus &&
|
||||
componentRollbackVersion(*restartedStatus, "runtime") == "0.8.0",
|
||||
"runtime rollback metadata was not reconstructed or accepted an "
|
||||
"invalid payload");
|
||||
check(restartedStatus &&
|
||||
componentRollbackVersion(*restartedStatus, "core") == "2.0.0",
|
||||
"Core rollback metadata was not reconstructed after restart");
|
||||
check(restartedStatus &&
|
||||
pluginRollbackVersion(*restartedStatus, "fixture") == "4.0.0",
|
||||
"plugin rollback metadata was not reconstructed after restart");
|
||||
check(readFile(coreStore.versionPath(*Void::Semver::parse("2.0.0")) /
|
||||
"Echoion.ts") == newCore,
|
||||
"retained Core rollback payload was unavailable after restart");
|
||||
check(readFile(pluginStore.versionPath(*Void::Semver::parse("4.0.0")) /
|
||||
"fixture.so") == newPlugin,
|
||||
"retained plugin rollback payload was unavailable after restart");
|
||||
Void::Update::VersionStore runtimeStore(installRoot);
|
||||
check(readFile(runtimeStore.versionPath(*Void::Semver::parse("0.8.0")) /
|
||||
"bin" / "echoiond") == "previous-runtime",
|
||||
"retained runtime rollback payload was unavailable after restart");
|
||||
restarted.stop();
|
||||
check(writeFile(sequenceState, "{not-json"),
|
||||
"failed to write corrupt replay-floor fixture");
|
||||
auto corruptReplayState = makeService();
|
||||
const auto corruptReplayStart = corruptReplayState.start();
|
||||
check(
|
||||
!corruptReplayStart &&
|
||||
corruptReplayStart.error().message.contains("replay-floor"),
|
||||
"corrupt replay-floor state silently disabled anti-replay persistence");
|
||||
std::filesystem::remove(sequenceState);
|
||||
|
||||
#ifndef _WIN32
|
||||
const auto runtimeLock = installRoot / ".update.lock";
|
||||
const auto runtimeHealth = installRoot / "health.log";
|
||||
std::filesystem::permissions(runtimeLock, std::filesystem::perms::none,
|
||||
std::filesystem::perm_options::replace);
|
||||
std::filesystem::permissions(runtimeHealth, std::filesystem::perms::none,
|
||||
std::filesystem::perm_options::replace);
|
||||
std::ifstream unreadableProbe{runtimeLock, std::ios::binary};
|
||||
if (!unreadableProbe) {
|
||||
auto legacy = makeService();
|
||||
check(legacy.start().has_value(),
|
||||
"unreadable legacy runtime metadata disabled UpdateService");
|
||||
auto legacyStatusResponse = legacy.handle("updates.getStatus", "{}");
|
||||
std::optional<Void::Json::Value> legacyStatusJson;
|
||||
const auto* legacyStatus =
|
||||
parseResponse(legacyStatusResponse, legacyStatusJson);
|
||||
check(legacyStatus &&
|
||||
componentRollbackVersion(*legacyStatus, "runtime").empty(),
|
||||
"unreadable legacy metadata exposed a runtime rollback");
|
||||
legacy.stop();
|
||||
}
|
||||
const auto readableMetadata = std::filesystem::perms::owner_read |
|
||||
std::filesystem::perms::owner_write |
|
||||
std::filesystem::perms::group_read |
|
||||
std::filesystem::perms::others_read;
|
||||
std::filesystem::permissions(runtimeLock, readableMetadata,
|
||||
std::filesystem::perm_options::replace);
|
||||
std::filesystem::permissions(runtimeHealth, readableMetadata,
|
||||
std::filesystem::perm_options::replace);
|
||||
#endif
|
||||
|
||||
TemporaryTree freshTree;
|
||||
const auto freshState = freshTree.path() / "state";
|
||||
const auto freshIncoming = freshTree.path() / "incoming";
|
||||
const auto freshFeed = freshIncoming / "feed.json";
|
||||
const auto freshConfig = freshTree.path() / "config.json";
|
||||
const auto freshCore = freshTree.path() / "installed" / "Echoion.ts";
|
||||
const auto freshInstall = freshTree.path() / "runtime";
|
||||
check(writeFile(freshFeed, "{}"),
|
||||
"failed to write fresh-install feed fixture");
|
||||
check(writeFile(freshConfig, configDocument(freshFeed)),
|
||||
"failed to write fresh-install config fixture");
|
||||
check(writeFile(freshCore, oldCore),
|
||||
"failed to write fresh-install Core fixture");
|
||||
check(writeFile(freshInstall / "versions" / "1.0.0" / "bin" / "echoiond",
|
||||
"fresh-runtime"),
|
||||
"failed to write fresh-install runtime fixture");
|
||||
std::filesystem::create_directory_symlink(
|
||||
std::filesystem::path{"versions"} / "1.0.0", freshInstall / "current");
|
||||
Echoion::Standalone::UpdateService freshService(
|
||||
Echoion::Standalone::UpdateService::Options{
|
||||
.configPath = freshConfig,
|
||||
.stateDirectory = freshState,
|
||||
.installRoot = freshInstall,
|
||||
.runningExecutable = freshInstall / "bin" / "echoiond",
|
||||
.currentCore = freshCore,
|
||||
.releaseManifestPath = {},
|
||||
.officialFeedUrl = {},
|
||||
.officialPublicKeysJson = "[]",
|
||||
.runtimeVersion = "1.0.0",
|
||||
.apiVersion = "1.1.0",
|
||||
.toolchainAbi = "test",
|
||||
.incomingDirectory = freshIncoming},
|
||||
Echoion::Standalone::UpdateService::Hooks{});
|
||||
check(freshService.start().has_value(),
|
||||
"fresh install without VersionStore metadata did not start");
|
||||
auto freshStatusResponse = freshService.handle("updates.getStatus", "{}");
|
||||
std::optional<Void::Json::Value> freshStatusJson;
|
||||
const auto* freshStatus =
|
||||
parseResponse(freshStatusResponse, freshStatusJson);
|
||||
check(freshStatus &&
|
||||
componentRollbackVersion(*freshStatus, "runtime").empty(),
|
||||
"fresh install synthesized runtime rollback metadata");
|
||||
freshService.stop();
|
||||
|
||||
TemporaryTree blockedTree;
|
||||
const auto blockedState = blockedTree.path() / "state";
|
||||
const auto blockedIncoming = blockedTree.path() / "incoming";
|
||||
const auto blockedFeed = blockedIncoming / "feed.json";
|
||||
const auto blockedConfig = blockedTree.path() / "config.json";
|
||||
const auto blockedCore = blockedTree.path() / "installed" / "Echoion.ts";
|
||||
check(writeFile(blockedFeed, "{}"),
|
||||
"failed to write blocked-start feed fixture");
|
||||
check(writeFile(blockedConfig, configDocument(blockedFeed)),
|
||||
"failed to write blocked-start config fixture");
|
||||
check(writeFile(blockedCore, oldCore),
|
||||
"failed to write blocked-start Core fixture");
|
||||
check(writeFile(blockedState / "updates" / "downloads", "not-a-directory"),
|
||||
"failed to create blocked updater directory fixture");
|
||||
Echoion::Standalone::UpdateService blockedService(
|
||||
Echoion::Standalone::UpdateService::Options{
|
||||
.configPath = blockedConfig,
|
||||
.stateDirectory = blockedState,
|
||||
.installRoot = blockedTree.path() / "runtime",
|
||||
.runningExecutable =
|
||||
blockedTree.path() / "runtime" / "bin" / "echoiond",
|
||||
.currentCore = blockedCore,
|
||||
.releaseManifestPath = {},
|
||||
.officialFeedUrl = {},
|
||||
.officialPublicKeysJson = "[]",
|
||||
.runtimeVersion = "1.0.0",
|
||||
.apiVersion = "1.1.0",
|
||||
.toolchainAbi = "test",
|
||||
.incomingDirectory = blockedIncoming},
|
||||
Echoion::Standalone::UpdateService::Hooks{});
|
||||
const auto blockedStart = blockedService.start();
|
||||
check(!blockedStart && blockedStart.error().message.contains("downloads"),
|
||||
"startup masked an earlier updater directory creation failure");
|
||||
blockedService.stop();
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(EchoionWeb VERSION 1.0.0 LANGUAGES CXX)
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
file(GLOB_RECURSE WEB_SOURCES CONFIGURE_DEPENDS "src/**.cpp")
|
||||
add_library(EchoionWeb STATIC ${WEB_SOURCES})
|
||||
add_library(Echoion::Web ALIAS EchoionWeb)
|
||||
|
||||
target_include_directories(EchoionWeb PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
# EchoionCore is configured before this module and creates the header-only
|
||||
# Boost:: targets from the single system Boost. Fall back to discovering them
|
||||
# only if this module is ever built without Core. Check each target because
|
||||
# aliases created by a sibling directory are not necessarily visible here.
|
||||
find_package(Boost 1.87 CONFIG QUIET COMPONENTS system url)
|
||||
foreach(_hdr asio beast system)
|
||||
if(NOT TARGET Boost::${_hdr})
|
||||
add_library(_web_boost_${_hdr}_hdr INTERFACE)
|
||||
add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr)
|
||||
target_include_directories(_web_boost_${_hdr}_hdr INTERFACE
|
||||
"${Boost_INCLUDE_DIRS}")
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
target_link_libraries(EchoionWeb
|
||||
PUBLIC
|
||||
Echoion::ApiConfig
|
||||
Void::Data
|
||||
Void::Log
|
||||
Void::Async
|
||||
PRIVATE
|
||||
Threads::Threads
|
||||
Boost::beast
|
||||
Boost::asio
|
||||
Boost::system
|
||||
Boost::url
|
||||
)
|
||||
|
||||
if(MSVC)
|
||||
target_compile_options(EchoionWeb PRIVATE /W4 /WX-)
|
||||
else()
|
||||
target_compile_options(EchoionWeb PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
|
||||
# ── Browser frontend (Vite + React + TypeScript) ─────────────────────────────
|
||||
# The UI lives in frontend/ and is built with npm/vite into frontend/web-dist.
|
||||
# That build output is what ships next to the runtime binary (default webRoot
|
||||
# "./web", relative to the working directory) and is installed. Opt out with
|
||||
# -DECHOION_BUILD_WEB=OFF to skip the npm build (e.g. for a C++-only CI job).
|
||||
if(BUILD_TESTS)
|
||||
add_executable(echoion_web_security_tests
|
||||
tests/HttpSecurityTests.cpp)
|
||||
target_link_libraries(echoion_web_security_tests PRIVATE
|
||||
EchoionWeb
|
||||
Threads::Threads)
|
||||
add_test(NAME echoion_web_security_tests
|
||||
COMMAND echoion_web_security_tests)
|
||||
endif()
|
||||
|
||||
option(ECHOION_BUILD_WEB "Build the React dashboard frontend with npm/vite" ON)
|
||||
|
||||
set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend")
|
||||
set(_web_dist "${_web_frontend}/web-dist")
|
||||
|
||||
if(ECHOION_BUILD_WEB)
|
||||
find_program(NPM_EXECUTABLE NAMES npm npm.cmd)
|
||||
if(NOT NPM_EXECUTABLE)
|
||||
message(FATAL_ERROR
|
||||
"npm was not found but ECHOION_BUILD_WEB is ON. Install Node.js/npm, "
|
||||
"or configure with -DECHOION_BUILD_WEB=OFF to skip the web frontend.")
|
||||
endif()
|
||||
|
||||
# Rebuild web-dist whenever any source/config under frontend/ (excluding
|
||||
# node_modules and the output dir) changes. CONFIGURE_DEPENDS re-globs at
|
||||
# build time so new files are picked up without re-running CMake.
|
||||
file(GLOB_RECURSE _web_tree_srcs CONFIGURE_DEPENDS
|
||||
LIST_DIRECTORIES FALSE
|
||||
"${_web_frontend}/src/*"
|
||||
"${_web_frontend}/public/*")
|
||||
set(_web_srcs
|
||||
${_web_tree_srcs}
|
||||
"${_web_frontend}/index.html"
|
||||
"${_web_frontend}/package.json"
|
||||
"${_web_frontend}/package-lock.json"
|
||||
"${_web_frontend}/tsconfig.json"
|
||||
"${_web_frontend}/vite.config.ts")
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT "${_web_dist}/index.html"
|
||||
# Release builds run `npm ci` before CMake. This lockfile-aware fallback
|
||||
# keeps direct developer builds convenient without reinstalling on every
|
||||
# incremental build.
|
||||
COMMAND ${NPM_EXECUTABLE} install --prefer-offline --no-audit --no-fund
|
||||
COMMAND ${NPM_EXECUTABLE} run build
|
||||
WORKING_DIRECTORY "${_web_frontend}"
|
||||
DEPENDS ${_web_srcs}
|
||||
COMMENT "Building Echoion web frontend (vite)"
|
||||
VERBATIM)
|
||||
add_custom_target(EchoionWebFrontend ALL
|
||||
DEPENDS "${_web_dist}/index.html")
|
||||
add_dependencies(EchoionWeb EchoionWebFrontend)
|
||||
|
||||
set(_web_assets "${_web_dist}")
|
||||
else()
|
||||
# Frontend build skipped: ship whatever is already in web-dist (a prior
|
||||
# build or a committed snapshot). Falls back to nothing if absent.
|
||||
set(_web_assets "${_web_dist}")
|
||||
endif()
|
||||
|
||||
# Ship the built browser assets next to the runtime binary. Remove the target
|
||||
# first so stale files (e.g. an earlier vanilla-JS build) never linger.
|
||||
add_custom_command(TARGET EchoionWeb POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E rm -rf "${CMAKE_BINARY_DIR}/bin/web"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory
|
||||
"${_web_assets}"
|
||||
"${CMAKE_BINARY_DIR}/bin/web"
|
||||
COMMENT "Copying EchoionWeb static assets to bin/web"
|
||||
)
|
||||
|
||||
install(DIRECTORY "${_web_dist}/" DESTINATION share/echoion/web)
|
||||
@@ -1,3 +0,0 @@
|
||||
node_modules/
|
||||
web-dist/
|
||||
*.tsbuildinfo
|
||||
@@ -1,19 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>Echoion — Music Bot</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
<meta name="theme-color" content="#151522">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-title" content="Echoion">
|
||||
<link rel="apple-touch-icon" href="/icon.svg">
|
||||
<link rel="stylesheet" href="/fonts.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
-2281
File diff suppressed because it is too large.
Load diff
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "echoion-web",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"i18n:check": "node scripts/i18n-check.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.1.0",
|
||||
"@types/react-dom": "^19.1.0",
|
||||
"@types/youtube": "^0.1.2",
|
||||
"@vitejs/plugin-react": "^4.5.0",
|
||||
"typescript": "^5.8.0",
|
||||
"vite": "^6.3.0",
|
||||
"vitest": "^3.1.0"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||
<rect width="24" height="24" rx="5" fill="#151522"/>
|
||||
<rect x="4" y="9" width="3.4" height="10" rx="1.6" fill="#a970ff"/>
|
||||
<rect x="10.3" y="4" width="3.4" height="15" rx="1.6" fill="#ff8080"/>
|
||||
<rect x="16.6" y="12" width="3.4" height="7" rx="1.6" fill="#ffd977"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 335 B |
@@ -1,480 +0,0 @@
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
|
||||
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
|
||||
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
|
||||
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'JetBrains Mono';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-7.woff2") format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-8.woff2") format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-9.woff2") format('woff2');
|
||||
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-10.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-11.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-12.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-7.woff2") format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-8.woff2") format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-9.woff2") format('woff2');
|
||||
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-10.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-11.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-12.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-7.woff2") format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-8.woff2") format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-9.woff2") format('woff2');
|
||||
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-10.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-11.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-12.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-7.woff2") format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-8.woff2") format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-9.woff2") format('woff2');
|
||||
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-10.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-11.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-12.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-7.woff2") format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-8.woff2") format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-9.woff2") format('woff2');
|
||||
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-10.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-11.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Manrope';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url("/fonts/Manrope-12.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,7 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||
<!-- Full-bleed background for the maskable safe area; bars inset ~20%. -->
|
||||
<rect width="512" height="512" fill="#151522"/>
|
||||
<rect x="150" y="232" width="52" height="150" rx="24" fill="#a970ff"/>
|
||||
<rect x="238" y="160" width="52" height="222" rx="24" fill="#ff8080"/>
|
||||
<rect x="326" y="278" width="52" height="104" rx="24" fill="#ffd977"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 412 B |
@@ -1,6 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||
<rect width="512" height="512" rx="112" fill="#151522"/>
|
||||
<rect x="96" y="200" width="72" height="212" rx="34" fill="#a970ff"/>
|
||||
<rect x="220" y="100" width="72" height="312" rx="34" fill="#ff8080"/>
|
||||
<rect x="344" y="264" width="72" height="148" rx="34" fill="#ffd977"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 343 B |
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"name": "Echoion Music Bot",
|
||||
"short_name": "Echoion",
|
||||
"description": "Control the Echoion TeamSpeak music bot and view live server activity.",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"orientation": "any",
|
||||
"background_color": "#0d0d1f",
|
||||
"theme_color": "#151522",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon.svg",
|
||||
"sizes": "any",
|
||||
"type": "image/svg+xml",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/icon-maskable.svg",
|
||||
"sizes": "any",
|
||||
"type": "image/svg+xml",
|
||||
"purpose": "maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
// Minimal, dependency-free service worker: makes the panel installable and
|
||||
// keeps the app shell available offline. It deliberately does NOT touch the
|
||||
// live surfaces — /rpc (WebSockets aren't interceptable anyway),
|
||||
// /config.json, /api/* and /avatar/* all fall through to the network so the
|
||||
// UI never shows stale identity/config.
|
||||
|
||||
// Bump when the player shell changes materially so installed/PWA clients do
|
||||
// not retain an index that references a removed hashed bundle.
|
||||
const CACHE = 'echoion-shell-v4';
|
||||
const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg'];
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(
|
||||
caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting())
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
event.waitUntil(
|
||||
caches
|
||||
.keys()
|
||||
.then((keys) =>
|
||||
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
|
||||
)
|
||||
.then(() => self.clients.claim())
|
||||
);
|
||||
});
|
||||
|
||||
// Only same-origin GETs are cacheable; everything else passes through.
|
||||
function isStaticAsset(url) {
|
||||
return (
|
||||
url.pathname.startsWith('/assets/') ||
|
||||
url.pathname === '/manifest.webmanifest' ||
|
||||
url.pathname.startsWith('/icon') ||
|
||||
url.pathname.startsWith('/fonts') ||
|
||||
url.pathname.endsWith('.css') ||
|
||||
url.pathname.endsWith('.woff2') ||
|
||||
url.pathname.endsWith('.svg')
|
||||
);
|
||||
}
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const req = event.request;
|
||||
if (req.method !== 'GET') return;
|
||||
const url = new URL(req.url);
|
||||
if (url.origin !== self.location.origin) return;
|
||||
|
||||
// Never intercept the live control/config/media surfaces.
|
||||
if (
|
||||
url.pathname === '/config.json' ||
|
||||
url.pathname.startsWith('/api/') ||
|
||||
url.pathname.startsWith('/rpc') ||
|
||||
url.pathname.startsWith('/avatar')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// SPA navigations: network-first, fall back to the cached shell offline.
|
||||
if (req.mode === 'navigate') {
|
||||
event.respondWith(
|
||||
fetch(req).catch(() => caches.match('/').then((r) => r || fetch(req)))
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Hashed static assets: cache-first, populate on first hit.
|
||||
if (isStaticAsset(url)) {
|
||||
event.respondWith(
|
||||
caches.match(req).then(
|
||||
(hit) =>
|
||||
hit ||
|
||||
fetch(req).then((resp) => {
|
||||
if (resp.ok) {
|
||||
const copy = resp.clone();
|
||||
caches.open(CACHE).then((c) => c.put(req, copy));
|
||||
}
|
||||
return resp;
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,103 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
// Diffs the Russian catalog (src/i18n/ru.ts) against every t('…') / tf('…')
|
||||
// literal in src/**/*.ts{,x}, both ways:
|
||||
// - missing: used in code but absent from ru.ts (falls back to English)
|
||||
// - orphaned: present in ru.ts but never used as a literal key
|
||||
//
|
||||
// Dynamic keys can't be found by this scan and must be checked by hand:
|
||||
// - SHORTCUTS labels (lib/shortcuts.ts) rendered via t(sc.label)
|
||||
// - HEADS view titles/subtitles (App.tsx) rendered via t(title)/t(sub)
|
||||
// Orphans reported here may be one of those dynamic keys — the KNOWN_DYNAMIC
|
||||
// list below suppresses the ones we know about.
|
||||
//
|
||||
// Usage: npm run i18n:check (exits 1 when keys are missing)
|
||||
|
||||
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const srcDir = join(root, 'src');
|
||||
const ruFile = join(srcDir, 'i18n', 'ru.ts');
|
||||
|
||||
// Keys reached through variables (see header); keep in sync by hand.
|
||||
const KNOWN_DYNAMIC = new Set([
|
||||
// connection state rendered via t(s.connection) in Sidebar.tsx
|
||||
'connected',
|
||||
'disconnected',
|
||||
'error',
|
||||
// SHORTCUTS labels (lib/shortcuts.ts)
|
||||
'Play / pause',
|
||||
'Seek 5s',
|
||||
'Volume',
|
||||
'Skip / vote skip',
|
||||
'Focus search',
|
||||
'This help',
|
||||
// HEADS view titles/subtitles (App.tsx)
|
||||
'Dashboard',
|
||||
'Live playback and TeamSpeak server activity',
|
||||
'Queue',
|
||||
'Reorder and manage upcoming tracks',
|
||||
'Search',
|
||||
'Find tracks across YouTube and Yandex Music',
|
||||
'Library',
|
||||
'Your favorites and saved playlists',
|
||||
'History & Stats',
|
||||
'Playback history and server insights',
|
||||
'Server & Admin',
|
||||
'Manage subscribers and broadcast',
|
||||
'Updates',
|
||||
'Runtime, Core, and plugin release control',
|
||||
'RPC / API',
|
||||
'Connect to Echoion programmatically',
|
||||
// Sidebar NAV labels rendered via t(item.label) — same strings as HEADS
|
||||
// titles, listed above.
|
||||
]);
|
||||
|
||||
const unescape = (s) => s.replace(/\\(.)/g, '$1');
|
||||
|
||||
function walk(dir, out = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const p = join(dir, name);
|
||||
if (statSync(p).isDirectory()) walk(p, out);
|
||||
else if (/\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name)) {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Catalog keys: top-level `'key': '…'` entries of the ru object literal.
|
||||
const ruKeys = new Set();
|
||||
for (const m of readFileSync(ruFile, 'utf8').matchAll(
|
||||
/^\s*'((?:[^'\\]|\\.)*)':/gm
|
||||
)) {
|
||||
ruKeys.add(unescape(m[1]));
|
||||
}
|
||||
|
||||
// Used keys: every t('…') / tf('…', …) string literal.
|
||||
const used = new Set();
|
||||
for (const file of walk(srcDir)) {
|
||||
if (file === ruFile) continue;
|
||||
const text = readFileSync(file, 'utf8');
|
||||
for (const m of text.matchAll(/\btf?\(\s*'((?:[^'\\]|\\.)*)'/g)) {
|
||||
used.add(unescape(m[1]));
|
||||
}
|
||||
}
|
||||
|
||||
const missing = [...used].filter((k) => !ruKeys.has(k)).sort();
|
||||
const orphaned = [...ruKeys]
|
||||
.filter((k) => !used.has(k) && !KNOWN_DYNAMIC.has(k))
|
||||
.sort();
|
||||
|
||||
if (missing.length) {
|
||||
console.log(`Missing from ru.ts (${missing.length}):`);
|
||||
for (const k of missing) console.log(`\t'${k.replace(/'/g, "\\'")}':`);
|
||||
}
|
||||
if (orphaned.length) {
|
||||
console.log(`\nIn ru.ts but never used as a literal (${orphaned.length}):`);
|
||||
for (const k of orphaned) console.log(`\t'${k.replace(/'/g, "\\'")}'`);
|
||||
console.log('(may be dynamic keys — verify before deleting)');
|
||||
}
|
||||
if (!missing.length && !orphaned.length) console.log('i18n: OK');
|
||||
process.exit(missing.length ? 1 : 0);
|
||||
@@ -1,107 +0,0 @@
|
||||
import { useEffect } from 'react';
|
||||
import { appStore, boot } from './lib/app';
|
||||
import { initRouter } from './lib/router';
|
||||
import { initShortcuts } from './lib/shortcuts';
|
||||
import { initMediaSession } from './lib/mediaSession';
|
||||
import { useStore } from './lib/store';
|
||||
import { useLanguage, t } from './i18n';
|
||||
import { HelpIcon, MenuIcon } from './components/icons';
|
||||
import { Sidebar } from './components/Sidebar';
|
||||
import { MiniPlayer } from './components/MiniPlayer';
|
||||
import { DialogHost } from './components/DialogHost';
|
||||
import { ShortcutsHelp } from './components/ShortcutsHelp';
|
||||
import { DashboardView } from './views/DashboardView';
|
||||
import { QueueView } from './views/QueueView';
|
||||
import { SearchView } from './views/SearchView';
|
||||
import { LibraryView } from './views/LibraryView';
|
||||
import { StatsView } from './views/StatsView';
|
||||
import { ServerView } from './views/ServerView';
|
||||
import { UpdatesView } from './views/UpdatesView';
|
||||
import { RpcView } from './views/RpcView';
|
||||
|
||||
const HEADS: Record<string, [string, string]> = {
|
||||
dashboard: ['Dashboard', 'Live playback and TeamSpeak server activity'],
|
||||
queue: ['Queue', 'Reorder and manage upcoming tracks'],
|
||||
search: ['Search', 'Find tracks across YouTube and Yandex Music'],
|
||||
library: ['Library', 'Your favorites and saved playlists'],
|
||||
stats: ['History & Stats', 'Playback history and server insights'],
|
||||
server: ['Server & Admin', 'Manage subscribers and broadcast'],
|
||||
updates: ['Updates', 'Runtime, Core, and plugin release control'],
|
||||
rpc: ['RPC / API', 'Connect to Echoion programmatically'],
|
||||
};
|
||||
|
||||
export function App() {
|
||||
const s = useStore(appStore);
|
||||
useLanguage(); // re-render everything on language switch
|
||||
|
||||
useEffect(() => {
|
||||
boot();
|
||||
initRouter();
|
||||
initShortcuts();
|
||||
initMediaSession();
|
||||
}, []);
|
||||
|
||||
const [title, sub] = HEADS[s.view] || HEADS.dashboard;
|
||||
|
||||
return (
|
||||
<div id="app">
|
||||
<Sidebar />
|
||||
{s.sidebarOpen && (
|
||||
<div
|
||||
className="drawer-backdrop"
|
||||
onClick={() => appStore.set({ sidebarOpen: false })}
|
||||
/>
|
||||
)}
|
||||
<main className="main">
|
||||
<header className="header">
|
||||
<div className="header-title">
|
||||
<button
|
||||
className="icon-btn hamburger"
|
||||
title={t('Menu')}
|
||||
aria-label={t('Menu')}
|
||||
onClick={() =>
|
||||
appStore.set({ sidebarOpen: !s.sidebarOpen })
|
||||
}
|
||||
>
|
||||
<MenuIcon />
|
||||
</button>
|
||||
<div>
|
||||
<h1>{t(title)}</h1>
|
||||
<div className="header-sub">{t(sub)}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="header-right">
|
||||
<span className="pill">
|
||||
<span className="dot dot-green" />
|
||||
{s.onlineCount} {t('online')}
|
||||
</span>
|
||||
<button
|
||||
className="icon-btn"
|
||||
title={t('Keyboard shortcuts')}
|
||||
aria-label={t('Keyboard shortcuts')}
|
||||
onClick={() =>
|
||||
appStore.set({ shortcutsOpen: true })
|
||||
}
|
||||
>
|
||||
<HelpIcon />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{s.view === 'dashboard' && <DashboardView />}
|
||||
{s.view === 'queue' && <QueueView />}
|
||||
{s.view === 'search' && <SearchView />}
|
||||
{s.view === 'library' && <LibraryView />}
|
||||
{s.view === 'stats' && <StatsView />}
|
||||
{s.view === 'server' && <ServerView />}
|
||||
{s.view === 'updates' && <UpdatesView />}
|
||||
{s.view === 'rpc' && <RpcView />}
|
||||
|
||||
<MiniPlayer />
|
||||
</main>
|
||||
{s.toast && <div className="toast">{s.toast}</div>}
|
||||
<DialogHost />
|
||||
<ShortcutsHelp />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { safeCall, toast } from '../lib/app';
|
||||
import { renderTsMarkup } from '../lib/tsMarkup';
|
||||
import { Modal } from './Modal';
|
||||
import { t } from '../i18n';
|
||||
|
||||
// Announce composer with a live TS6-markdown/BBCode preview (item 14).
|
||||
// Replaces the old prompt(). A small toolbar wraps the selection in common
|
||||
// formatting tags; the preview renders exactly what subscribers will see.
|
||||
const TOOLBAR: Array<{ label: string; before: string; after: string }> = [
|
||||
{ label: 'B', before: '**', after: '**' },
|
||||
{ label: 'I', before: '*', after: '*' },
|
||||
{ label: 'U', before: '[u]', after: '[/u]' },
|
||||
{ label: 'S', before: '~~', after: '~~' },
|
||||
{ label: '</>', before: '`', after: '`' },
|
||||
{ label: '🔗', before: '[', after: '](https://)' },
|
||||
{ label: 'H', before: '# ', after: '' },
|
||||
{ label: '❝', before: '> ', after: '' },
|
||||
];
|
||||
|
||||
export function AnnounceModal({ onClose }: { onClose: () => void }) {
|
||||
const [text, setText] = useState('');
|
||||
const [sending, setSending] = useState(false);
|
||||
let ref: HTMLTextAreaElement | null = null;
|
||||
|
||||
const wrap = (before: string, after: string) => {
|
||||
const el = ref;
|
||||
if (!el) return;
|
||||
const start = el.selectionStart;
|
||||
const end = el.selectionEnd;
|
||||
const selected = text.slice(start, end);
|
||||
const next =
|
||||
text.slice(0, start) + before + selected + after + text.slice(end);
|
||||
setText(next);
|
||||
// Restore focus with the caret after the inserted opening tag.
|
||||
queueMicrotask(() => {
|
||||
el.focus();
|
||||
const pos = start + before.length + selected.length;
|
||||
el.setSelectionRange(pos, pos);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={t('Compose announcement')}
|
||||
onClose={onClose}
|
||||
wide
|
||||
footer={
|
||||
<>
|
||||
<button className="btn btn-ghost" onClick={onClose}>
|
||||
{t('Cancel')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-accent"
|
||||
disabled={!text.trim() || sending}
|
||||
onClick={async () => {
|
||||
setSending(true);
|
||||
const res = await safeCall<{ message?: string }>(
|
||||
'Announce',
|
||||
{ text: text.trim() }
|
||||
);
|
||||
setSending(false);
|
||||
if (res) {
|
||||
toast(res.message || t('Announcement sent'));
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t('Send announcement')}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="announce-toolbar">
|
||||
{TOOLBAR.map((b) => (
|
||||
<button
|
||||
key={b.label}
|
||||
className="btn btn-ghost"
|
||||
type="button"
|
||||
onClick={() => wrap(b.before, b.after)}
|
||||
>
|
||||
{b.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="announce-grid">
|
||||
<textarea
|
||||
ref={(el) => {
|
||||
ref = el;
|
||||
}}
|
||||
className="announce-input"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder={t('Announcement to all subscribers:')}
|
||||
rows={10}
|
||||
/>
|
||||
<div className="announce-preview">
|
||||
<div className="announce-preview-label">
|
||||
{t('Preview')}
|
||||
</div>
|
||||
<div className="ts-markup">
|
||||
{text.trim() ? (
|
||||
renderTsMarkup(text)
|
||||
) : (
|
||||
<span className="muted">
|
||||
{t('Nothing to preview yet')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { avatarColor } from '../lib/format';
|
||||
|
||||
// User avatar: tries the TeamSpeak avatar served at /avatar/<uid>, falling
|
||||
// back to the initial-letter-on-gradient avatar when the image is missing.
|
||||
// `uid` is the stable TeamSpeak unique id.
|
||||
//
|
||||
// The server fetches avatars from TeamSpeak lazily (it must first sync the
|
||||
// client's avatar hash, then download the file), so the first few requests can
|
||||
// 404 while that completes. We retry a handful of times with a growing delay,
|
||||
// bypassing the browser's negative cache with a ?v=N buster, before giving up
|
||||
// and showing initials.
|
||||
const RETRY_DELAYS_MS = [2500, 4000, 6000, 9000];
|
||||
|
||||
export function Avatar(props: {
|
||||
name: string;
|
||||
uid?: string | null;
|
||||
size?: number;
|
||||
className?: string;
|
||||
}) {
|
||||
const { name, uid, size, className } = props;
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
// Reset retry state whenever the target uid changes.
|
||||
useEffect(() => {
|
||||
setAttempt(0);
|
||||
setFailed(false);
|
||||
return () => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
};
|
||||
}, [uid]);
|
||||
|
||||
const style: React.CSSProperties = size
|
||||
? { width: `${size}px`, height: `${size}px` }
|
||||
: {};
|
||||
|
||||
if (uid && !failed) {
|
||||
const src =
|
||||
`/avatar/${encodeURIComponent(uid)}` +
|
||||
(attempt > 0 ? `?v=${attempt}` : '');
|
||||
return (
|
||||
<img
|
||||
className={'avatar avatar-img' + (className ? ` ${className}` : '')}
|
||||
style={style}
|
||||
src={src}
|
||||
alt={name}
|
||||
onError={() => {
|
||||
if (attempt < RETRY_DELAYS_MS.length) {
|
||||
const delay = RETRY_DELAYS_MS[attempt];
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(
|
||||
() => setAttempt((a) => a + 1),
|
||||
delay
|
||||
);
|
||||
} else {
|
||||
setFailed(true);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={'avatar' + (className ? ` ${className}` : '')}
|
||||
style={{ ...style, background: avatarColor(name || '?') }}
|
||||
>
|
||||
{(name || '?').charAt(0).toUpperCase()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
import { useRef, useState } from 'react';
|
||||
|
||||
// Pointer-drag on a bar: the fill tracks the pointer while dragging and
|
||||
// onCommit fires once on release (a plain click is a zero-length drag).
|
||||
// Port of app.js makeDraggableBar.
|
||||
//
|
||||
// When `formatValue` is given, a tooltip bubble follows the pointer on hover
|
||||
// and drag showing the value at that position (item 14) — e.g. a seek time or
|
||||
// a volume percentage.
|
||||
export function Bar(props: {
|
||||
pct: number; // 0..100, authoritative fill when not dragging
|
||||
bufferPct?: number; // 0..100, second fill layer behind the progress
|
||||
slim?: boolean;
|
||||
className?: string;
|
||||
onCommit?: (fraction: number) => void;
|
||||
onDragStart?: () => boolean; // return false to refuse the drag
|
||||
live?: boolean; // live drag feedback: onCommit also fires on move
|
||||
formatValue?: (fraction: number) => string; // tooltip text at a fraction
|
||||
}) {
|
||||
const el = useRef<HTMLDivElement>(null);
|
||||
const [dragPct, setDragPct] = useState<number | null>(null);
|
||||
// Pointer position (0..100) for the tooltip; null when the pointer is away.
|
||||
const [hoverPct, setHoverPct] = useState<number | null>(null);
|
||||
|
||||
const fraction = (e: React.PointerEvent) => {
|
||||
const r = el.current!.getBoundingClientRect();
|
||||
return Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
|
||||
};
|
||||
|
||||
const tipPct = dragPct ?? hoverPct;
|
||||
const showTip = props.formatValue && tipPct != null;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={el}
|
||||
className={
|
||||
'bar' +
|
||||
(props.slim ? ' bar-slim' : '') +
|
||||
(props.className ? ` ${props.className}` : '')
|
||||
}
|
||||
onPointerDown={(e) => {
|
||||
if (props.onDragStart && !props.onDragStart()) return;
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
const f = fraction(e);
|
||||
setDragPct(f * 100);
|
||||
if (props.live) props.onCommit?.(f);
|
||||
}}
|
||||
onPointerMove={(e) => {
|
||||
const f = fraction(e);
|
||||
setHoverPct(f * 100);
|
||||
if (dragPct == null) return;
|
||||
setDragPct(f * 100);
|
||||
if (props.live) props.onCommit?.(f);
|
||||
}}
|
||||
onPointerLeave={() => setHoverPct(null)}
|
||||
onPointerUp={(e) => {
|
||||
if (dragPct == null) return;
|
||||
setDragPct(null);
|
||||
if (!props.live) props.onCommit?.(fraction(e));
|
||||
}}
|
||||
>
|
||||
{props.bufferPct != null && (
|
||||
<div
|
||||
className="bar-buffer"
|
||||
style={{ width: `${Math.min(100, props.bufferPct)}%` }}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
className="bar-fill"
|
||||
style={{ width: `${dragPct ?? props.pct}%` }}
|
||||
/>
|
||||
{showTip && (
|
||||
<div
|
||||
className="bar-tip"
|
||||
style={{ left: `${tipPct}%` }}
|
||||
>
|
||||
{props.formatValue!((tipPct as number) / 100)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Modal } from './Modal';
|
||||
import { useStore } from '../lib/store';
|
||||
import { dialogStore, resolveConfirm, resolvePrompt } from '../lib/dialog';
|
||||
import { t } from '../i18n';
|
||||
|
||||
// Renders the active custom dialog (confirm/prompt). Mounted once at the app
|
||||
// root; see lib/dialog.ts for the confirmDialog/promptDialog helpers.
|
||||
export function DialogHost() {
|
||||
const { current } = useStore(dialogStore);
|
||||
const [text, setText] = useState('');
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Seed the prompt field with its initial value and focus it each time a
|
||||
// new prompt opens.
|
||||
useEffect(() => {
|
||||
if (current && current.kind === 'prompt') {
|
||||
setText(current.initial || '');
|
||||
// Focus after the modal mounts.
|
||||
setTimeout(() => inputRef.current?.focus(), 0);
|
||||
}
|
||||
}, [current]);
|
||||
|
||||
if (!current) return null;
|
||||
|
||||
if (current.kind === 'confirm') {
|
||||
return (
|
||||
<Modal
|
||||
title={current.title}
|
||||
onClose={() => resolveConfirm(false)}
|
||||
footer={
|
||||
<>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={() => resolveConfirm(false)}
|
||||
>
|
||||
{current.cancelLabel || t('Cancel')}
|
||||
</button>
|
||||
<button
|
||||
className={
|
||||
'btn ' +
|
||||
(current.danger ? 'btn-danger' : 'btn-accent')
|
||||
}
|
||||
onClick={() => resolveConfirm(true)}
|
||||
>
|
||||
{current.confirmLabel || t('Confirm')}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p>{current.message}</p>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={current.title}
|
||||
onClose={() => resolvePrompt(null)}
|
||||
footer={
|
||||
<>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={() => resolvePrompt(null)}
|
||||
>
|
||||
{current.cancelLabel || t('Cancel')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-accent"
|
||||
onClick={() => resolvePrompt(text.trim() || null)}
|
||||
>
|
||||
{current.confirmLabel || t('OK')}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
resolvePrompt(text.trim() || null);
|
||||
}}
|
||||
>
|
||||
{current.message && <p>{current.message}</p>}
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder={current.placeholder}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { appStore, safeCall } from '../lib/app';
|
||||
import { useStore } from '../lib/store';
|
||||
import type { LyricsResult } from '../lib/types';
|
||||
import { t } from '../i18n';
|
||||
|
||||
// Lyrics for the current track (via the bot's GetLyrics → lrclib). When the
|
||||
// provider returns time-synced lines we highlight the active one against the
|
||||
// shared playback clock (appStore.positionMs) and keep it scrolled into view;
|
||||
// otherwise we show plain scrollable text. Collapsed by default so we only
|
||||
// fetch when the listener asks for it.
|
||||
export function LyricsPanel() {
|
||||
const s = useStore(appStore);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [lyrics, setLyrics] = useState<LyricsResult | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const activeRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const track = s.current;
|
||||
// Refetch when the track identity changes (url is stable per track).
|
||||
const key = track ? track.url || track.title || '' : '';
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !key) {
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setLyrics(null);
|
||||
safeCall<LyricsResult>('GetLyrics').then((res) => {
|
||||
if (!cancelled) {
|
||||
setLyrics(res);
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [key, open]);
|
||||
|
||||
const synced = lyrics?.synced ?? [];
|
||||
// Index of the last line whose timestamp has passed.
|
||||
const activeIdx = useMemo(() => {
|
||||
if (!synced.length) return -1;
|
||||
let idx = -1;
|
||||
for (let i = 0; i < synced.length; i++) {
|
||||
if (synced[i].ms <= s.positionMs) idx = i;
|
||||
else break;
|
||||
}
|
||||
return idx;
|
||||
}, [synced, s.positionMs]);
|
||||
|
||||
useEffect(() => {
|
||||
activeRef.current?.scrollIntoView({ block: 'nearest' });
|
||||
}, [activeIdx]);
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h3>{t('Lyrics')}</h3>
|
||||
<button
|
||||
className="link"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
disabled={!track}
|
||||
>
|
||||
{open ? t('Hide') : t('Show')}
|
||||
</button>
|
||||
</div>
|
||||
{open && (
|
||||
<div className="lyrics-body">
|
||||
{!track ? (
|
||||
<div className="lyrics-empty">
|
||||
{t('Nothing playing')}
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div className="lyrics-empty">{t('Loading…')}</div>
|
||||
) : !lyrics || !lyrics.found ? (
|
||||
<div className="lyrics-empty">
|
||||
{t('No lyrics found')}
|
||||
</div>
|
||||
) : synced.length ? (
|
||||
<div className="lyrics-synced">
|
||||
{synced.map((line, i) => (
|
||||
<div
|
||||
key={i}
|
||||
ref={i === activeIdx ? activeRef : null}
|
||||
className={
|
||||
'lyrics-line' +
|
||||
(i === activeIdx ? ' active' : '')
|
||||
}
|
||||
>
|
||||
{line.text || '♪'}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<pre className="lyrics-plain">{lyrics.plain}</pre>
|
||||
)}
|
||||
{lyrics && lyrics.found && lyrics.source && (
|
||||
<div className="lyrics-source muted">
|
||||
{t('Lyrics via')} {lyrics.source}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
import { appStore, safeCall } from '../lib/app';
|
||||
import { useStore } from '../lib/store';
|
||||
import { Bar } from './Bar';
|
||||
import { coverStyle, fmtMs } from '../lib/format';
|
||||
import { PauseIcon, PlayIcon, SkipNextIcon } from './icons';
|
||||
import { t } from '../i18n';
|
||||
|
||||
async function togglePlay() {
|
||||
const st = appStore.get().status || {};
|
||||
if (st.isPlaying && !st.isPaused) await safeCall('Pause');
|
||||
else await safeCall('Resume');
|
||||
}
|
||||
|
||||
// Mini player mirrors the current track on views other than Now Playing.
|
||||
export function MiniPlayer() {
|
||||
const s = useStore(appStore);
|
||||
if (s.view === 'dashboard' || !s.current) return null;
|
||||
const playing = !!(s.status && s.status.isPlaying && !s.status.isPaused);
|
||||
const canForceSkip = !!(
|
||||
s.identity &&
|
||||
(s.identity.isAdmin || s.identity.isDj)
|
||||
);
|
||||
const durationMs = s.durationMs || s.current.duration || 0;
|
||||
const pct =
|
||||
durationMs > 0 ? Math.min(100, (s.positionMs / durationMs) * 100) : 0;
|
||||
return (
|
||||
<div className="miniplayer">
|
||||
<div
|
||||
className="mini-cover"
|
||||
style={{ background: coverStyle(s.current) }}
|
||||
/>
|
||||
<div className="mini-info">
|
||||
<div className="mini-title">{s.current.title}</div>
|
||||
<div className="mini-artist">{s.current.artist || ''}</div>
|
||||
</div>
|
||||
<button
|
||||
className="ctrl"
|
||||
title={t('Play/Pause')}
|
||||
onClick={togglePlay}
|
||||
>
|
||||
{playing ? <PauseIcon /> : <PlayIcon />}
|
||||
</button>
|
||||
{canForceSkip && (
|
||||
<button
|
||||
className="ctrl"
|
||||
title={t('Force skip')}
|
||||
onClick={() => safeCall('Skip', { count: 1 })}
|
||||
>
|
||||
<SkipNextIcon />
|
||||
</button>
|
||||
)}
|
||||
<Bar
|
||||
slim
|
||||
className="mini-bar"
|
||||
pct={pct}
|
||||
formatValue={(f) =>
|
||||
durationMs ? fmtMs(Math.round(f * durationMs)) : ''
|
||||
}
|
||||
onDragStart={() => durationMs > 0}
|
||||
onCommit={(f) =>
|
||||
safeCall('Seek', {
|
||||
position: Math.round(f * durationMs),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { Modal } from './Modal';
|
||||
|
||||
describe('Modal accessibility', () => {
|
||||
it('labels the dialog and exposes a named close control', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<Modal title="Confirm update" onClose={() => {}}>
|
||||
<p>Review the candidate.</p>
|
||||
</Modal>
|
||||
);
|
||||
expect(html).toContain('role="dialog"');
|
||||
expect(html).toContain('aria-modal="true"');
|
||||
expect(html).toContain('aria-labelledby=');
|
||||
expect(html).toContain('aria-label="Close"');
|
||||
});
|
||||
});
|
||||
@@ -1,76 +0,0 @@
|
||||
import { useEffect, useId, useRef, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import { CloseIcon } from './icons';
|
||||
import { t } from '../i18n';
|
||||
|
||||
export function Modal(props: {
|
||||
title: string;
|
||||
onClose: () => void;
|
||||
children: ReactNode;
|
||||
footer?: ReactNode;
|
||||
wide?: boolean;
|
||||
}) {
|
||||
const titleId = useId();
|
||||
const modalRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = document.activeElement as HTMLElement | null;
|
||||
const focusable = modalRef.current?.querySelector<HTMLElement>(
|
||||
'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])'
|
||||
);
|
||||
focusable?.focus();
|
||||
return () => previous?.focus();
|
||||
}, []);
|
||||
|
||||
function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
props.onClose();
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Tab' || !modalRef.current) return;
|
||||
const focusable = Array.from(
|
||||
modalRef.current.querySelectorAll<HTMLElement>(
|
||||
'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])'
|
||||
)
|
||||
);
|
||||
if (!focusable.length) return;
|
||||
const first = focusable[0];
|
||||
const last = focusable[focusable.length - 1];
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={props.onClose}>
|
||||
<div
|
||||
ref={modalRef}
|
||||
className={'modal' + (props.wide ? ' modal-wide' : '')}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
onKeyDown={onKeyDown}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="modal-head">
|
||||
<h2 id={titleId}>{props.title}</h2>
|
||||
<button
|
||||
className="icon-btn"
|
||||
aria-label={t('Close')}
|
||||
onClick={props.onClose}
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
<div className="modal-body">{props.children}</div>
|
||||
{props.footer && (
|
||||
<div className="modal-foot">{props.footer}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { shouldCorrectVideoDrift } from '../lib/nowPlayingVideoSync';
|
||||
|
||||
describe('NowPlayingVideo drift correction', () => {
|
||||
it('never seeks while unstarted, cued, or buffering', () => {
|
||||
for (const state of [-1, 3, 5]) {
|
||||
expect(shouldCorrectVideoDrift(state, 0, 30, 10_000)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('waits for cooldown and ignores small playing drift', () => {
|
||||
expect(shouldCorrectVideoDrift(1, 0, 30, 1000)).toBe(false);
|
||||
expect(shouldCorrectVideoDrift(1, 28, 30, 10_000)).toBe(false);
|
||||
expect(shouldCorrectVideoDrift(1, 10, 30, 10_000)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,133 +0,0 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { appStore } from '../lib/app';
|
||||
import {
|
||||
loadYouTubeApi,
|
||||
YOUTUBE_EMBED_HOST,
|
||||
youtubeEmbedVars,
|
||||
} from '../lib/youtube';
|
||||
import { shouldCorrectVideoDrift } from '../lib/nowPlayingVideoSync';
|
||||
|
||||
// The muted YouTube video of the current track, shown in Now Playing when the
|
||||
// user enables it (item 11). The bot's audio is the source of truth, so the
|
||||
// video is always muted and only follows the server position — it resyncs
|
||||
// with a hard seek when it drifts past the threshold, and pauses/plays to
|
||||
// match. Purely a local visual aid; it sends nothing to the server.
|
||||
const SEEK_LEAD_SECONDS = 0.75;
|
||||
|
||||
export function NowPlayingVideo({ videoId }: { videoId: string }) {
|
||||
const mountRef = useRef<HTMLDivElement>(null);
|
||||
const playerRef = useRef<YT.Player | null>(null);
|
||||
const currentVideo = useRef<string>('');
|
||||
const pendingVideo = useRef(videoId);
|
||||
const lastSeekAt = useRef(0);
|
||||
const playIntent = useRef<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
loadYouTubeApi().then(() => {
|
||||
if (cancelled || !mountRef.current) return;
|
||||
const el = document.createElement('div');
|
||||
mountRef.current.appendChild(el);
|
||||
playerRef.current = new YT.Player(el, {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
videoId,
|
||||
host: YOUTUBE_EMBED_HOST,
|
||||
playerVars: youtubeEmbedVars({ mute: 1 }),
|
||||
events: {
|
||||
onReady: () => {
|
||||
const p = playerRef.current;
|
||||
if (!p) return;
|
||||
const requested = pendingVideo.current;
|
||||
const startSeconds = appStore.get().positionMs / 1000;
|
||||
if (requested !== videoId) {
|
||||
p.loadVideoById({ videoId: requested, startSeconds });
|
||||
} else if (startSeconds > 0) {
|
||||
p.seekTo(startSeconds, true);
|
||||
}
|
||||
p.mute();
|
||||
currentVideo.current = requested;
|
||||
lastSeekAt.current = performance.now();
|
||||
playIntent.current = null;
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
playerRef.current?.destroy();
|
||||
playerRef.current = null;
|
||||
if (mountRef.current) mountRef.current.innerHTML = '';
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// Load a new video id in place without recreating the player.
|
||||
useEffect(() => {
|
||||
pendingVideo.current = videoId;
|
||||
const p = playerRef.current;
|
||||
if (!p || !p.loadVideoById || currentVideo.current === videoId) return;
|
||||
p.loadVideoById({
|
||||
videoId,
|
||||
startSeconds: appStore.get().positionMs / 1000,
|
||||
});
|
||||
p.mute();
|
||||
currentVideo.current = videoId;
|
||||
lastSeekAt.current = performance.now();
|
||||
playIntent.current = null;
|
||||
}, [videoId]);
|
||||
|
||||
// Follow the server position: resync on drift, match play/pause state.
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => {
|
||||
const p = playerRef.current;
|
||||
if (!p || !p.getCurrentTime || !p.seekTo) return;
|
||||
const s = appStore.get();
|
||||
const targetSec = s.positionMs / 1000;
|
||||
const playing = !!(
|
||||
s.status &&
|
||||
s.status.isPlaying &&
|
||||
!s.status.isPaused
|
||||
);
|
||||
try {
|
||||
const st = p.getPlayerState();
|
||||
const now = performance.now();
|
||||
// Seeking while CUED/BUFFERING repeatedly restarts YouTube's
|
||||
// buffer. Drift is meaningful only once the playback clock moves.
|
||||
if (shouldCorrectVideoDrift(
|
||||
st,
|
||||
p.getCurrentTime(),
|
||||
targetSec,
|
||||
now - lastSeekAt.current
|
||||
)) {
|
||||
p.seekTo(targetSec + SEEK_LEAD_SECONDS, true);
|
||||
lastSeekAt.current = now;
|
||||
}
|
||||
if (
|
||||
playing &&
|
||||
playIntent.current !== true &&
|
||||
(st === YT.PlayerState.CUED ||
|
||||
st === YT.PlayerState.PAUSED ||
|
||||
st === YT.PlayerState.ENDED)
|
||||
) {
|
||||
p.playVideo();
|
||||
playIntent.current = true;
|
||||
}
|
||||
else if (
|
||||
!playing &&
|
||||
playIntent.current !== false &&
|
||||
(st === YT.PlayerState.PLAYING || st === YT.PlayerState.BUFFERING)
|
||||
) {
|
||||
p.pauseVideo();
|
||||
playIntent.current = false;
|
||||
}
|
||||
p.mute(); // guard against unmute on state changes
|
||||
} catch {
|
||||
/* player not ready yet */
|
||||
}
|
||||
}, 1000);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
|
||||
return <div className="np-video" ref={mountRef} />;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { Avatar } from './Avatar';
|
||||
|
||||
export function PersonRow(props: {
|
||||
name: string;
|
||||
uid?: string | null;
|
||||
sub?: string;
|
||||
status?: string;
|
||||
statusColor?: string;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
const { name, uid, sub, status, statusColor, children } = props;
|
||||
return (
|
||||
<div className="person">
|
||||
<Avatar name={name} uid={uid} />
|
||||
<div className="person-main">
|
||||
<div className="person-name">{name}</div>
|
||||
{sub && <div className="person-sub">{sub}</div>}
|
||||
</div>
|
||||
{status && (
|
||||
<span
|
||||
className="person-status"
|
||||
style={statusColor ? { color: statusColor } : undefined}
|
||||
>
|
||||
{status}
|
||||
</span>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { PlayerControls } from './PlayerControls';
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
function render(over: Partial<Parameters<typeof PlayerControls>[0]> = {}) {
|
||||
return renderToStaticMarkup(
|
||||
<PlayerControls
|
||||
playing={false}
|
||||
positionMs={30_000}
|
||||
durationMs={120_000}
|
||||
canControl
|
||||
volumePct={50}
|
||||
onTogglePlay={noop}
|
||||
onSeekMs={noop}
|
||||
onSeekBy={noop}
|
||||
onVolume={noop}
|
||||
{...over}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe('PlayerControls', () => {
|
||||
it('shows transport, times and volume when controllable', () => {
|
||||
const html = render();
|
||||
expect(html).toContain('0:30');
|
||||
expect(html).toContain('2:00');
|
||||
expect(html).toContain('Back 10 seconds');
|
||||
expect(html).toContain('Forward 10 seconds');
|
||||
expect(html).not.toContain('disabled');
|
||||
});
|
||||
|
||||
it('disables transport when canControl is false', () => {
|
||||
const html = render({ canControl: false });
|
||||
// Play/pause + the two ±10s buttons are disabled…
|
||||
expect(html.match(/disabled/g)?.length).toBe(3);
|
||||
// …but the volume bar (local) is still rendered.
|
||||
expect(html).toContain('50%');
|
||||
});
|
||||
|
||||
it('hides seek buttons and shows LIVE for live sources', () => {
|
||||
const html = render({ live: true });
|
||||
expect(html).not.toContain('Back 10 seconds');
|
||||
expect(html).toContain('LIVE');
|
||||
});
|
||||
|
||||
it('renders skip only when onSkip is given', () => {
|
||||
expect(render()).not.toContain('Play next');
|
||||
expect(render({ onSkip: noop })).toContain('Play next');
|
||||
});
|
||||
|
||||
it('hides the local row when showLocal is false', () => {
|
||||
expect(render({ showLocal: false })).not.toContain('Vol');
|
||||
});
|
||||
|
||||
it('renders the unified settings slot in the local row', () => {
|
||||
expect(render({ settings: <button>Settings gear</button> })).toContain(
|
||||
'Settings gear'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,128 +0,0 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { Bar } from './Bar';
|
||||
import { fmtMs } from '../lib/format';
|
||||
import {
|
||||
ForwardIcon,
|
||||
FullscreenIcon,
|
||||
PauseIcon,
|
||||
PlayIcon,
|
||||
RewindIcon,
|
||||
SkipNextIcon,
|
||||
} from './icons';
|
||||
import { t } from '../i18n';
|
||||
|
||||
// Dashboard playback controls. This component is presentational; authenticated
|
||||
// RPC callbacks are supplied by the dashboard while visitors receive a
|
||||
// disabled, read-only transport surface.
|
||||
export function PlayerControls(props: {
|
||||
playing: boolean;
|
||||
positionMs: number;
|
||||
durationMs: number; // 0 = unknown
|
||||
live?: boolean; // no seekable timeline (Twitch / generic embeds)
|
||||
canControl: boolean; // transport disabled when false; volume stays local
|
||||
bufferedPct?: number; // 0..100 second fill on the seek bar
|
||||
volumePct: number; // 0..100
|
||||
volumeLive?: boolean; // apply volume while dragging (local volume)
|
||||
onTogglePlay: () => void;
|
||||
onSeekMs: (ms: number) => void;
|
||||
onSeekBy?: (deltaSec: number) => void; // renders ±10s when present
|
||||
onVolume: (pct: number) => void;
|
||||
onSkip?: () => void; // renders next-track button when present
|
||||
skipDisabled?: boolean;
|
||||
onFullscreen?: () => void;
|
||||
settings?: ReactNode;
|
||||
showLocal?: boolean; // hide the volume/quality row (default shown)
|
||||
extra?: ReactNode; // view-specific buttons after the seek bar
|
||||
extraLocal?: ReactNode; // view-specific controls in the volume row
|
||||
}) {
|
||||
const { live, durationMs, positionMs, canControl } = props;
|
||||
const progressPct = live
|
||||
? 100
|
||||
: durationMs > 0
|
||||
? Math.min(100, (positionMs / durationMs) * 100)
|
||||
: 0;
|
||||
return (
|
||||
<div className="player-controls">
|
||||
<div className="player-control-row">
|
||||
<button
|
||||
className="ctrl ctrl-main"
|
||||
title={t('Play/Pause')}
|
||||
disabled={!canControl}
|
||||
onClick={props.onTogglePlay}
|
||||
>
|
||||
{props.playing ? <PauseIcon /> : <PlayIcon />}
|
||||
</button>
|
||||
{!live && props.onSeekBy && (
|
||||
<>
|
||||
<button
|
||||
className="ctrl"
|
||||
title={t('Back 10 seconds')}
|
||||
disabled={!canControl}
|
||||
onClick={() => props.onSeekBy!(-10)}
|
||||
>
|
||||
<RewindIcon />
|
||||
</button>
|
||||
<button
|
||||
className="ctrl"
|
||||
title={t('Forward 10 seconds')}
|
||||
disabled={!canControl}
|
||||
onClick={() => props.onSeekBy!(10)}
|
||||
>
|
||||
<ForwardIcon />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{props.onSkip && (
|
||||
<button
|
||||
className="ctrl"
|
||||
title={t('Play next')}
|
||||
disabled={!canControl || props.skipDisabled}
|
||||
onClick={props.onSkip}
|
||||
>
|
||||
<SkipNextIcon />
|
||||
</button>
|
||||
)}
|
||||
<span className="mono">{live ? '—' : fmtMs(positionMs)}</span>
|
||||
<Bar
|
||||
pct={progressPct}
|
||||
bufferPct={live ? undefined : props.bufferedPct}
|
||||
formatValue={(f) =>
|
||||
live || !durationMs
|
||||
? t('LIVE')
|
||||
: fmtMs(Math.round(f * durationMs))
|
||||
}
|
||||
onDragStart={() => !live && durationMs > 0}
|
||||
onCommit={(f) => props.onSeekMs(Math.round(f * durationMs))}
|
||||
/>
|
||||
<span className="mono">
|
||||
{live ? t('LIVE') : fmtMs(durationMs)}
|
||||
</span>
|
||||
{props.extra}
|
||||
</div>
|
||||
{(props.showLocal ?? true) && (
|
||||
<div className="player-control-row player-local-row">
|
||||
<span className="muted">{t('Vol')}</span>
|
||||
<Bar
|
||||
slim
|
||||
live={props.volumeLive}
|
||||
pct={props.volumePct}
|
||||
formatValue={(f) => `${Math.round(f * 100)}%`}
|
||||
onCommit={(f) => props.onVolume(Math.round(f * 100))}
|
||||
/>
|
||||
<span className="mono">{Math.round(props.volumePct)}%</span>
|
||||
{props.settings}
|
||||
{props.onFullscreen && (
|
||||
<button
|
||||
className="ctrl"
|
||||
title={t('Fullscreen')}
|
||||
onClick={props.onFullscreen}
|
||||
>
|
||||
<FullscreenIcon />
|
||||
</button>
|
||||
)}
|
||||
{props.extraLocal}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { appStore } from '../lib/app';
|
||||
import { useStore } from '../lib/store';
|
||||
import { SHORTCUTS } from '../lib/shortcuts';
|
||||
import { t } from '../i18n';
|
||||
|
||||
// Cheat-sheet overlay for keyboard shortcuts, toggled with "?".
|
||||
export function ShortcutsHelp() {
|
||||
const s = useStore(appStore);
|
||||
if (!s.shortcutsOpen) return null;
|
||||
return (
|
||||
<div
|
||||
className="modal-backdrop"
|
||||
onClick={() => appStore.set({ shortcutsOpen: false })}
|
||||
>
|
||||
<div className="modal shortcuts-modal" onClick={(e) => e.stopPropagation()}>
|
||||
<h2>{t('Keyboard shortcuts')}</h2>
|
||||
<div className="shortcuts-list">
|
||||
{SHORTCUTS.map((sc) => (
|
||||
<div key={sc.keys} className="shortcut-row">
|
||||
<kbd>{sc.keys}</kbd>
|
||||
<span>{t(sc.label)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={() => appStore.set({ shortcutsOpen: false })}
|
||||
>
|
||||
{t('Close')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import {
|
||||
appStore,
|
||||
changeLanguage,
|
||||
connectWithToken,
|
||||
getStoredToken,
|
||||
logout,
|
||||
requestToken,
|
||||
showView,
|
||||
type ViewName,
|
||||
} from '../lib/app';
|
||||
import { useStore } from '../lib/store';
|
||||
import { promptDialog } from '../lib/dialog';
|
||||
import { Avatar } from './Avatar';
|
||||
import {
|
||||
CodeIcon,
|
||||
GearIcon,
|
||||
HeartIcon,
|
||||
PlayIcon,
|
||||
QueueIcon,
|
||||
SearchIcon,
|
||||
StatsIcon,
|
||||
UpdateIcon,
|
||||
WatchIcon,
|
||||
} from './icons';
|
||||
import { t, useLanguage } from '../i18n';
|
||||
|
||||
const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [
|
||||
{ view: 'dashboard', icon: <PlayIcon />, label: 'Dashboard' },
|
||||
{ view: 'queue', icon: <QueueIcon />, label: 'Queue' },
|
||||
{ view: 'search', icon: <SearchIcon />, label: 'Search' },
|
||||
{ view: 'library', icon: <HeartIcon />, label: 'Library' },
|
||||
{ view: 'stats', icon: <StatsIcon />, label: 'History & Stats' },
|
||||
{ view: 'server', icon: <GearIcon />, label: 'Server & Admin' },
|
||||
{ view: 'updates', icon: <UpdateIcon />, label: 'Updates' },
|
||||
{ view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' },
|
||||
];
|
||||
|
||||
export function Sidebar() {
|
||||
const s = useStore(appStore);
|
||||
const language = useLanguage();
|
||||
const [token, setToken] = useState(getStoredToken() || '');
|
||||
const isAdmin = !!(s.identity && s.identity.isAdmin);
|
||||
const playing = !!(
|
||||
s.status &&
|
||||
s.status.isPlaying &&
|
||||
!s.status.isPaused
|
||||
);
|
||||
const name = s.identity
|
||||
? s.identity.nickname || s.identity.uid || t('user')
|
||||
: '';
|
||||
|
||||
return (
|
||||
<aside className={'sidebar' + (s.sidebarOpen ? ' open' : '')}>
|
||||
<div className="brand">
|
||||
<div className="brand-icon">
|
||||
<svg viewBox="0 0 24 24" width="22" height="22" fill="#fff">
|
||||
<rect x="4" y="9" width="3.4" height="10" rx="1.6" />
|
||||
<rect x="10.3" y="4" width="3.4" height="15" rx="1.6" />
|
||||
<rect x="16.6" y="12" width="3.4" height="7" rx="1.6" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<div className="brand-name">Echoion</div>
|
||||
<div className="brand-sub">{t('MUSIC BOT · TS3')}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="nav">
|
||||
{NAV.filter(
|
||||
(item) =>
|
||||
(item.view !== 'server' && item.view !== 'updates') ||
|
||||
isAdmin
|
||||
).map((item) => (
|
||||
<button
|
||||
key={item.view}
|
||||
className={
|
||||
'nav-item' +
|
||||
(s.view === item.view ? ' active' : '')
|
||||
}
|
||||
aria-current={s.view === item.view ? 'page' : undefined}
|
||||
onClick={() => showView(item.view)}
|
||||
>
|
||||
<span className="nav-ico">{item.icon}</span>
|
||||
{t(item.label)}
|
||||
{item.view === 'dashboard' && playing && (
|
||||
<span className="live-dot" />
|
||||
)}
|
||||
{item.view === 'queue' && s.queue.length > 0 && (
|
||||
<span className="nav-badge">{s.queue.length}</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
{s.watchUrl && (
|
||||
<a
|
||||
className="nav-item"
|
||||
href={s.watchUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<span className="nav-ico">
|
||||
<WatchIcon />
|
||||
</span>
|
||||
{t('Watch Together')}
|
||||
<span className="nav-external" aria-hidden="true">
|
||||
↗
|
||||
</span>
|
||||
</a>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-foot">
|
||||
<div className="conn-row">
|
||||
<span
|
||||
className={
|
||||
'conn-dot' +
|
||||
(s.connection === 'connected'
|
||||
? ' on'
|
||||
: s.connection === 'error'
|
||||
? ' err'
|
||||
: '')
|
||||
}
|
||||
/>
|
||||
<span>{t(s.connection)}</span>
|
||||
<select
|
||||
className="lang-select"
|
||||
value={language}
|
||||
title={t('Language')}
|
||||
onChange={(e) =>
|
||||
changeLanguage(e.target.value as 'en' | 'ru')
|
||||
}
|
||||
>
|
||||
<option value="en">EN</option>
|
||||
<option value="ru">RU</option>
|
||||
</select>
|
||||
</div>
|
||||
{!s.identity ? (
|
||||
<div>
|
||||
<input
|
||||
type="password"
|
||||
placeholder={t('RPC token')}
|
||||
autoComplete="off"
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
connectWithToken(token);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
className="btn btn-accent"
|
||||
onClick={() => connectWithToken(token)}
|
||||
>
|
||||
{t('Connect')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
title={t('Send my token via TeamSpeak PM')}
|
||||
onClick={async () => {
|
||||
const nickname = await promptDialog({
|
||||
title: t('Get token by nickname'),
|
||||
message: t(
|
||||
'Your TeamSpeak nickname (must be subscribed):'
|
||||
),
|
||||
placeholder: t('Nickname'),
|
||||
confirmLabel: t('Send'),
|
||||
});
|
||||
if (nickname) requestToken(nickname);
|
||||
}}
|
||||
>
|
||||
{t('Get token by nickname…')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="whoami">
|
||||
<Avatar name={name} uid={s.identity.uid} />
|
||||
<span>{name}</span>
|
||||
{isAdmin && (
|
||||
<span className="admin-chip">{t('ADMIN')}</span>
|
||||
)}
|
||||
{!isAdmin && s.identity.isDj && (
|
||||
<span className="admin-chip">{t('DJ')}</span>
|
||||
)}
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={() => {
|
||||
logout();
|
||||
setToken('');
|
||||
}}
|
||||
>
|
||||
{t('Logout')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -1,480 +0,0 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { safeCall, toast } from '../lib/app';
|
||||
import type { RpcMethodName } from '../lib/rpc';
|
||||
import { confirmDialog, promptDialog } from '../lib/dialog';
|
||||
import { EmptyRow } from './TrackRow';
|
||||
import { t, tf } from '../i18n';
|
||||
import { teamSpeakChannelDisplayName } from '../lib/teamspeak';
|
||||
|
||||
interface AdminClient {
|
||||
id: number;
|
||||
databaseId: number | null;
|
||||
uid: string | null;
|
||||
nickname: string;
|
||||
channelId: number;
|
||||
talking: boolean;
|
||||
muted: boolean;
|
||||
deafened: boolean;
|
||||
away: boolean;
|
||||
groups: number[];
|
||||
}
|
||||
|
||||
interface AdminChannel {
|
||||
id: number;
|
||||
name: string;
|
||||
parentId: number | null;
|
||||
default: boolean;
|
||||
password: boolean;
|
||||
maxClients: number;
|
||||
currentClients: number;
|
||||
clients: AdminClient[];
|
||||
channels: AdminChannel[];
|
||||
}
|
||||
|
||||
interface DirectoryResponse {
|
||||
server: {
|
||||
name: string;
|
||||
connected: boolean;
|
||||
clientCount: number;
|
||||
maxClients: number;
|
||||
};
|
||||
channels: AdminChannel[];
|
||||
}
|
||||
|
||||
interface Ban {
|
||||
id: number;
|
||||
uid: string | null;
|
||||
nickname: string | null;
|
||||
reason: string;
|
||||
createdAt: number;
|
||||
durationSeconds: number;
|
||||
}
|
||||
|
||||
interface ServerGroup {
|
||||
id: number;
|
||||
name: string;
|
||||
default: boolean;
|
||||
}
|
||||
|
||||
export function TeamSpeakAdmin() {
|
||||
const [directory, setDirectory] = useState<DirectoryResponse | null>(null);
|
||||
const [bans, setBans] = useState<Ban[]>([]);
|
||||
const [groups, setGroups] = useState<ServerGroup[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const [nextDirectory, nextBans, nextGroups] = await Promise.all([
|
||||
safeCall<DirectoryResponse>('GetTeamSpeakDirectory'),
|
||||
safeCall<{ bans?: Ban[] }>('GetTeamSpeakBans'),
|
||||
safeCall<{ groups?: ServerGroup[] }>('GetTeamSpeakServerGroups'),
|
||||
]);
|
||||
if (nextDirectory) setDirectory(nextDirectory);
|
||||
if (nextBans) setBans(nextBans.bans || []);
|
||||
if (nextGroups) setGroups(nextGroups.groups || []);
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
const mutate = useCallback(
|
||||
async (
|
||||
method: RpcMethodName,
|
||||
params: Record<string, unknown>,
|
||||
message: string
|
||||
) => {
|
||||
const result = await safeCall(method, params);
|
||||
if (!result) return false;
|
||||
toast(message);
|
||||
await refresh();
|
||||
return true;
|
||||
},
|
||||
[refresh]
|
||||
);
|
||||
|
||||
async function sendServerMessage() {
|
||||
const message = await promptDialog({
|
||||
title: t('Server message'),
|
||||
message: t('Message sent to every connected TeamSpeak client:'),
|
||||
confirmLabel: t('Send'),
|
||||
});
|
||||
if (message) {
|
||||
await mutate(
|
||||
'SendTeamSpeakServerMessage',
|
||||
{ message },
|
||||
t('Server message sent')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function createChannel(parentId = 0) {
|
||||
const name = await promptDialog({
|
||||
title: t('Create channel'),
|
||||
message: t('Channel name:'),
|
||||
confirmLabel: t('Create'),
|
||||
});
|
||||
if (name) {
|
||||
await mutate(
|
||||
'CreateTeamSpeakChannel',
|
||||
{ name, parentId, permanent: true },
|
||||
t('Channel created')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function ClientRow({ client }: { client: AdminClient }) {
|
||||
return (
|
||||
<div className="ts-admin-client">
|
||||
<div className="ts-admin-client-main">
|
||||
<span
|
||||
className={'ts-presence' + (client.talking ? ' talking' : '')}
|
||||
/>
|
||||
<strong>{client.nickname}</strong>
|
||||
<span className="muted">#{client.id}</span>
|
||||
{client.away && <span className="ts-tag">{t('away')}</span>}
|
||||
{client.muted && <span className="ts-tag">{t('muted')}</span>}
|
||||
{client.deafened && <span className="ts-tag">{t('deafened')}</span>}
|
||||
</div>
|
||||
<div className="ts-admin-private muted">
|
||||
<span>UID: {client.uid || '—'}</span>
|
||||
<span>DB: {client.databaseId || '—'}</span>
|
||||
<span>{t('Groups')}: {client.groups.join(', ') || '—'}</span>
|
||||
</div>
|
||||
<div className="ts-admin-actions">
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const message = await promptDialog({
|
||||
title: tf('Message {0}', client.nickname),
|
||||
message: t('Private message:'),
|
||||
confirmLabel: t('Send'),
|
||||
});
|
||||
if (message)
|
||||
await mutate(
|
||||
'SendTeamSpeakPrivateMessage',
|
||||
{ clientId: client.id, message },
|
||||
t('Message sent')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Message')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const channelId = await promptDialog({
|
||||
title: tf('Move {0}', client.nickname),
|
||||
message: t('Destination channel ID:'),
|
||||
confirmLabel: t('Move'),
|
||||
});
|
||||
if (channelId && /^\d+$/.test(channelId))
|
||||
await mutate(
|
||||
'MoveTeamSpeakClient',
|
||||
{ clientId: client.id, channelId: Number(channelId) },
|
||||
t('Client moved')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Move')}
|
||||
</button>
|
||||
{client.databaseId && (
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const groupId = await promptDialog({
|
||||
title: t('Add server group'),
|
||||
message: groups.length
|
||||
? groups.map((g) => `${g.id}: ${g.name}`).join('\n')
|
||||
: t('Server group ID:'),
|
||||
confirmLabel: t('Add'),
|
||||
});
|
||||
if (groupId && /^\d+$/.test(groupId))
|
||||
await mutate(
|
||||
'AddTeamSpeakServerGroupMember',
|
||||
{
|
||||
groupId: Number(groupId),
|
||||
clientDatabaseId: client.databaseId,
|
||||
},
|
||||
t('Group added')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Add group')}
|
||||
</button>
|
||||
)}
|
||||
{client.databaseId && client.groups.length > 0 && (
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const groupId = await promptDialog({
|
||||
title: t('Remove server group'),
|
||||
message: `${t('Current groups')}: ${client.groups.join(', ')}`,
|
||||
confirmLabel: t('Remove'),
|
||||
});
|
||||
if (groupId && /^\d+$/.test(groupId))
|
||||
await mutate(
|
||||
'RemoveTeamSpeakServerGroupMember',
|
||||
{
|
||||
groupId: Number(groupId),
|
||||
clientDatabaseId: client.databaseId,
|
||||
},
|
||||
t('Group removed')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Remove group')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="btn btn-danger-ghost"
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirmDialog({
|
||||
title: tf('Kick {0}', client.nickname),
|
||||
message: t('Kick this client from the server?'),
|
||||
confirmLabel: t('Kick'),
|
||||
danger: true,
|
||||
})
|
||||
)
|
||||
await mutate(
|
||||
'KickTeamSpeakClient',
|
||||
{ clientId: client.id, fromServer: true },
|
||||
t('Client kicked')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Kick')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger-ghost"
|
||||
onClick={async () => {
|
||||
const duration = await promptDialog({
|
||||
title: tf('Ban {0}', client.nickname),
|
||||
message: t('Duration in seconds (0 = permanent):'),
|
||||
confirmLabel: t('Continue'),
|
||||
});
|
||||
if (!duration || !/^\d+$/.test(duration)) return;
|
||||
if (
|
||||
await confirmDialog({
|
||||
title: tf('Ban {0}', client.nickname),
|
||||
message: t('Apply this ban now?'),
|
||||
confirmLabel: t('Ban'),
|
||||
danger: true,
|
||||
})
|
||||
)
|
||||
await mutate(
|
||||
'BanTeamSpeakClient',
|
||||
{
|
||||
clientId: client.id,
|
||||
durationSeconds: Number(duration),
|
||||
},
|
||||
t('Client banned')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Ban')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Channel({ channel, depth = 0 }: { channel: AdminChannel; depth?: number }) {
|
||||
const displayName = teamSpeakChannelDisplayName(channel.name);
|
||||
|
||||
return (
|
||||
<div className="ts-admin-channel" style={{ marginLeft: depth * 16 }}>
|
||||
<div className="ts-admin-channel-head">
|
||||
<strong
|
||||
className={displayName.spacer ? 'ts-admin-spacer' : undefined}
|
||||
title={channel.name}
|
||||
>
|
||||
{displayName.label}
|
||||
</strong>
|
||||
<span className="muted">#{channel.id}</span>
|
||||
<span className="ts-capacity">
|
||||
{channel.currentClients}/{channel.maxClients || '∞'}
|
||||
</span>
|
||||
<button className="btn btn-ghost" onClick={() => createChannel(channel.id)}>
|
||||
{t('Add child')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const name = await promptDialog({
|
||||
title: t('Rename channel'),
|
||||
message: channel.name,
|
||||
confirmLabel: t('Save'),
|
||||
});
|
||||
if (name)
|
||||
await mutate(
|
||||
'EditTeamSpeakChannel',
|
||||
{ channelId: channel.id, name },
|
||||
t('Channel updated')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Edit')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const message = await promptDialog({
|
||||
title: tf('Message {0}', channel.name),
|
||||
message: t('Channel message:'),
|
||||
confirmLabel: t('Send'),
|
||||
});
|
||||
if (message)
|
||||
await mutate(
|
||||
'SendTeamSpeakChannelMessage',
|
||||
{ channelId: channel.id, message },
|
||||
t('Message sent')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Message')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const parentId = await promptDialog({
|
||||
title: t('Reorder channel'),
|
||||
message: t('Parent channel ID (0 = root):'),
|
||||
confirmLabel: t('Continue'),
|
||||
});
|
||||
if (parentId === null || !/^\d+$/.test(parentId)) return;
|
||||
const orderAfterId = await promptDialog({
|
||||
title: t('Reorder channel'),
|
||||
message: t('Previous sibling channel ID (0 = first):'),
|
||||
confirmLabel: t('Move'),
|
||||
});
|
||||
if (orderAfterId === null || !/^\d+$/.test(orderAfterId)) return;
|
||||
await mutate(
|
||||
'ReorderTeamSpeakChannel',
|
||||
{
|
||||
channelId: channel.id,
|
||||
parentId: Number(parentId),
|
||||
orderAfterId: Number(orderAfterId),
|
||||
},
|
||||
t('Channel reordered')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Reorder')}
|
||||
</button>
|
||||
{!channel.default && (
|
||||
<button
|
||||
className="btn btn-danger-ghost"
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirmDialog({
|
||||
title: t('Delete channel'),
|
||||
message: tf('Delete {0} and its contents?', channel.name),
|
||||
confirmLabel: t('Delete'),
|
||||
danger: true,
|
||||
})
|
||||
)
|
||||
await mutate(
|
||||
'DeleteTeamSpeakChannel',
|
||||
{ channelId: channel.id, force: true },
|
||||
t('Channel deleted')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Delete')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{channel.clients.map((client) => (
|
||||
<ClientRow key={client.id} client={client} />
|
||||
))}
|
||||
{channel.channels.map((child) => (
|
||||
<Channel key={child.id} channel={child} depth={depth + 1} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="admin-stack">
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<div>
|
||||
<h2>{directory?.server.name || t('TeamSpeak')}</h2>
|
||||
<div className="muted">
|
||||
{directory?.server.connected ? t('Connected') : t('Disconnected')}
|
||||
{' · '}
|
||||
{directory?.server.clientCount || 0}/{directory?.server.maxClients || '∞'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-gap">
|
||||
<button className="btn btn-ghost" onClick={sendServerMessage}>
|
||||
{t('Server message')}
|
||||
</button>
|
||||
<button className="btn btn-ghost" onClick={() => createChannel()}>
|
||||
{t('Create channel')}
|
||||
</button>
|
||||
<button className="btn btn-ghost" disabled={loading} onClick={refresh}>
|
||||
{loading ? t('Loading…') : t('Refresh')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ts-admin-tree">
|
||||
{directory?.channels.length ? (
|
||||
directory.channels.map((channel) => (
|
||||
<Channel key={channel.id} channel={channel} />
|
||||
))
|
||||
) : (
|
||||
<EmptyRow text={t('No TeamSpeak topology available')} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h2>{t('Bans')}</h2>
|
||||
<span className="muted">{bans.length}</span>
|
||||
</div>
|
||||
<div className="tracklist">
|
||||
{bans.length ? (
|
||||
bans.map((ban) => (
|
||||
<div className="ts-ban-row" key={ban.id}>
|
||||
<div>
|
||||
<strong>{ban.nickname || ban.uid || `#${ban.id}`}</strong>
|
||||
<div className="muted">{ban.reason || t('No reason')}</div>
|
||||
</div>
|
||||
<span className="muted">
|
||||
{ban.durationSeconds ? `${ban.durationSeconds}s` : t('Permanent')}
|
||||
</span>
|
||||
<button
|
||||
className="btn btn-danger-ghost"
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirmDialog({
|
||||
title: t('Remove ban'),
|
||||
message: t('Remove this TeamSpeak ban?'),
|
||||
confirmLabel: t('Unban'),
|
||||
danger: true,
|
||||
})
|
||||
)
|
||||
await mutate(
|
||||
'UnbanTeamSpeakClient',
|
||||
{ banId: ban.id },
|
||||
t('Ban removed')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Unban')}
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<EmptyRow text={t('No bans')} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { Track } from '../lib/types';
|
||||
import { coverStyle, fmtMs, sourceInfo } from '../lib/format';
|
||||
import { t } from '../i18n';
|
||||
|
||||
export interface TrackAction {
|
||||
icon: ReactNode;
|
||||
title: string;
|
||||
cls?: string;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
export function TrackRow(props: {
|
||||
track: Track;
|
||||
num?: number;
|
||||
playing?: boolean;
|
||||
sub?: string;
|
||||
actions?: Array<TrackAction | null | false>;
|
||||
rowProps?: React.HTMLAttributes<HTMLDivElement> & { draggable?: boolean };
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
const { track, num, playing, sub, rowProps, children } = props;
|
||||
const actions = (props.actions || []).filter(Boolean) as TrackAction[];
|
||||
const src = sourceInfo(track);
|
||||
return (
|
||||
<div
|
||||
{...rowProps}
|
||||
className={
|
||||
'track-row' +
|
||||
(playing ? ' playing' : '') +
|
||||
(rowProps?.className ? ` ${rowProps.className}` : '')
|
||||
}
|
||||
>
|
||||
{num != null && (
|
||||
<span className="track-num">
|
||||
{String(num).padStart(2, '0')}
|
||||
</span>
|
||||
)}
|
||||
<div
|
||||
className="track-cover"
|
||||
style={{ background: coverStyle(track) }}
|
||||
/>
|
||||
<div className="track-main">
|
||||
<div className="track-title">
|
||||
{track.title || t('(untitled)')}
|
||||
</div>
|
||||
<div className="track-sub">
|
||||
{[track.artist, sub].filter(Boolean).join(' · ')}
|
||||
</div>
|
||||
</div>
|
||||
{src && <span className={src.cls}>{src.label}</span>}
|
||||
{!!track.duration && (
|
||||
<span className="track-dur">{fmtMs(track.duration)}</span>
|
||||
)}
|
||||
{actions.length > 0 && (
|
||||
<div className="track-actions">
|
||||
{actions.map((a, i) => (
|
||||
<button
|
||||
key={i}
|
||||
className={'icon-btn' + (a.cls ? ` ${a.cls}` : '')}
|
||||
title={a.title}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
a.onClick();
|
||||
}}
|
||||
>
|
||||
{a.icon}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyRow({ text }: { text: string }) {
|
||||
return <div className="empty">{text}</div>;
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
import type { SVGProps } from 'react';
|
||||
|
||||
// Inline SVG icon set replacing the raw unicode glyphs (✕ ▶ ⏸ ⚙ …), which
|
||||
// rendered inconsistently across platforms and fonts. Sized in em so icons
|
||||
// scale with the button font-size; color follows currentColor.
|
||||
type IconProps = SVGProps<SVGSVGElement>;
|
||||
|
||||
function makeIcon(d: string) {
|
||||
return function Icon(props: IconProps) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
width="1em"
|
||||
height="1em"
|
||||
fill="currentColor"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
{...props}
|
||||
>
|
||||
<path d={d} />
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
export const PlayIcon = makeIcon('M8 5v14l11-7z');
|
||||
export const PauseIcon = makeIcon('M6 19h4V5H6v14zm8-14v14h4V5h-4z');
|
||||
export const SkipNextIcon = makeIcon('M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z');
|
||||
export const SkipPrevIcon = makeIcon('M6 6h2v12H6zm3.5 6l8.5 6V6l-8.5 6z');
|
||||
export const RewindIcon = makeIcon(
|
||||
'M11 18V6l-8.5 6 8.5 6zm.5-6l8.5 6V6l-8.5 6z'
|
||||
);
|
||||
export const ForwardIcon = makeIcon(
|
||||
'M4 18l8.5-6L4 6v12zm9-12v12l8.5-6L13 6z'
|
||||
);
|
||||
export const ShuffleIcon = makeIcon(
|
||||
'M10.59 9.17L5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41l-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z'
|
||||
);
|
||||
export const RepeatIcon = makeIcon(
|
||||
'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z'
|
||||
);
|
||||
export const HeartIcon = makeIcon(
|
||||
'M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z'
|
||||
);
|
||||
export const CloseIcon = makeIcon(
|
||||
'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'
|
||||
);
|
||||
export const SearchIcon = makeIcon(
|
||||
'M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'
|
||||
);
|
||||
export const QueueIcon = makeIcon(
|
||||
'M15 6H3v2h12V6zm0 4H3v2h12v-2zM3 16h8v-2H3v2zm14-10v8.18c-.31-.11-.65-.18-1-.18-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3V8h3V6h-5z'
|
||||
);
|
||||
export const StatsIcon = makeIcon(
|
||||
'M5 9.2h3V19H5V9.2zM10.6 5h2.8v14h-2.8V5zm5.6 8H19v6h-2.8v-6z'
|
||||
);
|
||||
export const WatchIcon = makeIcon(
|
||||
'M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12zM9.5 8.5l7 3.5-7 3.5v-7z'
|
||||
);
|
||||
export const RoomsIcon = makeIcon(
|
||||
'M4 4h6v6H4V4zm10 0h6v6h-6V4zM4 14h6v6H4v-6zm10 0h6v6h-6v-6z'
|
||||
);
|
||||
export const GearIcon = makeIcon(
|
||||
'M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z'
|
||||
);
|
||||
export const UpdateIcon = makeIcon(
|
||||
'M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.96-.69 2.8l1.46 1.46A7.93 7.93 0 0020 12c0-4.42-3.58-8-8-8zm-5.31 5.2L5.23 7.74A7.93 7.93 0 004 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3c-3.31 0-6-2.69-6-6 0-1.01.25-1.96.69-2.8z'
|
||||
);
|
||||
export const CodeIcon = makeIcon(
|
||||
'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z'
|
||||
);
|
||||
export const FullscreenIcon = makeIcon(
|
||||
'M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z'
|
||||
);
|
||||
export const PowerIcon = makeIcon(
|
||||
'M13 3h-2v10h2V3zm4.83 2.17l-1.42 1.42C17.99 7.86 19 9.81 19 12c0 3.87-3.13 7-7 7s-7-3.13-7-7c0-2.19 1.01-4.14 2.58-5.42L6.17 5.17C4.23 6.82 3 9.26 3 12c0 4.97 4.03 9 9 9s9-4.03 9-9c0-2.74-1.23-5.18-3.17-6.83z'
|
||||
);
|
||||
export const CrownIcon = makeIcon(
|
||||
'M5 16L3 6l5.5 4L12 4l3.5 6L21 6l-2 10H5zm14 3c0 .55-.45 1-1 1H6c-.55 0-1-.45-1-1v-1h14v1z'
|
||||
);
|
||||
export const RefreshIcon = makeIcon(
|
||||
'M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z'
|
||||
);
|
||||
export const PlusIcon = makeIcon('M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z');
|
||||
export const ArrowUpIcon = makeIcon('M4 12l1.41 1.41L11 7.83V20h2V7.83l5.59 5.58L20 12l-8-8-8 8z');
|
||||
export const ArrowDownIcon = makeIcon('M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.59-5.58L4 12l8 8 8-8z');
|
||||
export const VolumeIcon = makeIcon(
|
||||
'M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z'
|
||||
);
|
||||
export const VolumeMuteIcon = makeIcon(
|
||||
'M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z'
|
||||
);
|
||||
export const HelpIcon = makeIcon(
|
||||
'M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z'
|
||||
);
|
||||
export const MenuIcon = makeIcon('M3 6h18v2H3V6zm0 5h18v2H3v-2zm0 5h18v2H3v-2z');
|
||||
export const ExternalLinkIcon = makeIcon(
|
||||
'M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z'
|
||||
);
|
||||
@@ -1,58 +0,0 @@
|
||||
// Web UI localization, mirroring the bot's approach (EchoionCore i18n):
|
||||
// English source strings are the keys; a missing entry falls back to the
|
||||
// English original. Language resolution order matches the bot's
|
||||
// CommandManager::resolveLanguage: the authenticated user's server-side
|
||||
// preference (kv "lang:<uid>", shared with !lang) → local override →
|
||||
// browser language → English.
|
||||
|
||||
import { Store, useStore } from '../lib/store';
|
||||
import { ru } from './ru';
|
||||
|
||||
export type Language = 'en' | 'ru';
|
||||
|
||||
const LS_KEY = 'echoion.lang';
|
||||
|
||||
function initialLanguage(): Language {
|
||||
// Not a browser (node test runner): no stored preference, use English.
|
||||
if (typeof localStorage === 'undefined') return 'en';
|
||||
const stored = localStorage.getItem(LS_KEY);
|
||||
if (stored === 'en' || stored === 'ru') return stored;
|
||||
return (navigator.language || '').toLowerCase().startsWith('ru')
|
||||
? 'ru'
|
||||
: 'en';
|
||||
}
|
||||
|
||||
export const languageStore = new Store<{ language: Language }>({
|
||||
language: initialLanguage(),
|
||||
});
|
||||
|
||||
export function getLanguage(): Language {
|
||||
return languageStore.get().language;
|
||||
}
|
||||
|
||||
// `persist` distinguishes a user choice (saved locally, pushed to the
|
||||
// server by the caller) from applying the server-side preference.
|
||||
export function setLanguage(language: Language, persist = true) {
|
||||
if (persist) localStorage.setItem(LS_KEY, language);
|
||||
languageStore.set({ language });
|
||||
document.documentElement.lang = language;
|
||||
}
|
||||
|
||||
export function t(english: string): string {
|
||||
if (getLanguage() === 'ru') return ru[english] ?? english;
|
||||
return english;
|
||||
}
|
||||
|
||||
// Translate a template, then substitute {0}, {1}, … arguments.
|
||||
export function tf(english: string, ...args: Array<string | number>): string {
|
||||
const template = t(english);
|
||||
return template.replace(/\{(\d+)\}/g, (m, i) => {
|
||||
const v = args[Number(i)];
|
||||
return v === undefined ? m : String(v);
|
||||
});
|
||||
}
|
||||
|
||||
// Components subscribe so a language switch re-renders everything.
|
||||
export function useLanguage(): Language {
|
||||
return useStore(languageStore).language;
|
||||
}
|
||||
@@ -1,455 +0,0 @@
|
||||
// Russian catalog for the web UI. Same philosophy as the bot's compiled-in
|
||||
// RussianCatalog.inc: English source strings are the keys; a missing entry
|
||||
// falls back to English. Placeholders are {0}, {1}, … (see tf()).
|
||||
|
||||
export const ru: Record<string, string> = {
|
||||
// Sidebar / navigation
|
||||
'Dashboard': 'Панель',
|
||||
'Queue': 'Очередь',
|
||||
'Search': 'Поиск',
|
||||
'Library': 'Библиотека',
|
||||
'History & Stats': 'История и статистика',
|
||||
'Watch Together': 'Совместный просмотр',
|
||||
'Server & Admin': 'Сервер и админ',
|
||||
'Updates': 'Обновления',
|
||||
'RPC / API': 'RPC / API',
|
||||
'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3',
|
||||
'Connect': 'Подключиться',
|
||||
'Get token by nickname…': 'Получить токен по нику…',
|
||||
'Send my token via TeamSpeak PM': 'Прислать мой токен личным сообщением в TeamSpeak',
|
||||
'RPC token': 'RPC-токен',
|
||||
'Logout': 'Выйти',
|
||||
'ADMIN': 'АДМИН',
|
||||
'DJ': 'DJ',
|
||||
'connected': 'подключено',
|
||||
'disconnected': 'отключено',
|
||||
'error': 'ошибка',
|
||||
|
||||
// View headers
|
||||
'Live playback and TeamSpeak server activity':
|
||||
'Текущее воспроизведение и активность сервера TeamSpeak',
|
||||
'Reorder and manage upcoming tracks': 'Управляйте порядком предстоящих треков',
|
||||
'Find tracks across YouTube and Yandex Music': 'Ищите треки на YouTube и в Яндекс Музыке',
|
||||
'Your favorites and saved playlists': 'Ваше избранное и сохранённые плейлисты',
|
||||
'Playback history and server insights': 'История воспроизведения и статистика сервера',
|
||||
'Manage subscribers and broadcast': 'Управление подписчиками и объявления',
|
||||
'Runtime, Core, and plugin release control':
|
||||
'Управление выпусками среды, ядра и плагинов',
|
||||
'Connect to Echoion programmatically': 'Подключение к Echoion из кода',
|
||||
|
||||
// Updates
|
||||
'Runtime bundle': 'Среда выполнения',
|
||||
'Core': 'Ядро',
|
||||
'Plugins': 'Плагины',
|
||||
'default source': 'источник по умолчанию',
|
||||
'stable': 'стабильный',
|
||||
'Idle': 'Ожидание',
|
||||
'Installed': 'Установлено',
|
||||
'Available': 'Доступно',
|
||||
'Up to date': 'Актуальная версия',
|
||||
'Candidate attributes': 'Свойства кандидата',
|
||||
'Unsigned': 'Без подписи',
|
||||
'Signed': 'Подписано',
|
||||
'Downgrade': 'Понижение версии',
|
||||
'Incompatible': 'Несовместимо',
|
||||
'Restart required': 'Нужен перезапуск',
|
||||
'Apply {0}': 'Применить {0}',
|
||||
'No update': 'Нет обновления',
|
||||
'Rollback to {0}': 'Откатить до {0}',
|
||||
'No rollback': 'Откат недоступен',
|
||||
'Enabled': 'Включено',
|
||||
'Source': 'Источник',
|
||||
'Channel': 'Канал',
|
||||
'{0} source': 'Источник: {0}',
|
||||
'{0} channel': 'Канал: {0}',
|
||||
'Auto-apply': 'Применять автоматически',
|
||||
'Build default': 'Встроенное значение',
|
||||
'Feed URL': 'URL ленты',
|
||||
'Empty uses the release build default':
|
||||
'Пустое поле использует адрес из сборки выпуска',
|
||||
'Bearer token environment variable': 'Переменная окружения с Bearer-токеном',
|
||||
'Secret is present in the service environment':
|
||||
'Секрет присутствует в окружении службы',
|
||||
'Secret is missing from the service environment':
|
||||
'Секрет отсутствует в окружении службы',
|
||||
'Secret presence was not reported': 'Наличие секрета не сообщено службой',
|
||||
'No bearer token configured': 'Bearer-токен не настроен',
|
||||
'Permit manual unsigned staging':
|
||||
'Разрешить ручную подготовку обновлений без подписи',
|
||||
'Ed25519 trust keys': 'Доверенные ключи Ed25519',
|
||||
'Only public verification keys belong here.':
|
||||
'Здесь должны находиться только открытые ключи проверки.',
|
||||
'Add key': 'Добавить ключ',
|
||||
'Key ID': 'ID ключа',
|
||||
'Public key': 'Открытый ключ',
|
||||
'Remove key {0}': 'Удалить ключ {0}',
|
||||
'No custom keys; the build-injected keyring is used when available.':
|
||||
'Пользовательских ключей нет; используется встроенное в сборку хранилище ключей.',
|
||||
'Remove source': 'Удалить источник',
|
||||
'Managed': 'Управляемый',
|
||||
'Unmanaged': 'Неуправляемый',
|
||||
'Apply': 'Применить',
|
||||
'Rollback': 'Откатить',
|
||||
'Never': 'Никогда',
|
||||
'Automatic updates armed': 'Автоматические обновления активны',
|
||||
'Automatic updates paused': 'Автоматические обновления приостановлены',
|
||||
'Last check: {0}': 'Последняя проверка: {0}',
|
||||
'Next: {0}': 'Следующая: {0}',
|
||||
'Check now': 'Проверить сейчас',
|
||||
'Checking…': 'Проверка…',
|
||||
'Loading update state…': 'Загрузка состояния обновлений…',
|
||||
'Installed plugins': 'Установленные плагины',
|
||||
'Only managed plugins participate in update activation.':
|
||||
'В активации обновлений участвуют только управляемые плагины.',
|
||||
'managed': 'управляемых',
|
||||
'No installed plugins reported': 'Установленные плагины не обнаружены',
|
||||
'Update history': 'История обновлений',
|
||||
'Checks, staging, activation, and rollback outcomes':
|
||||
'Результаты проверок, подготовки, активации и откатов',
|
||||
'When': 'Когда',
|
||||
'Target': 'Цель',
|
||||
'Action': 'Действие',
|
||||
'Result': 'Результат',
|
||||
'Recorded': 'Записано',
|
||||
'No update history yet': 'История обновлений пока пуста',
|
||||
'POLICY DECK': 'ПАНЕЛЬ ПОЛИТИКИ',
|
||||
'Automation and trust': 'Автоматизация и доверие',
|
||||
'Configure timing, independent channels, feeds, and public trust roots.':
|
||||
'Настройте расписание, независимые каналы, ленты и открытые корни доверия.',
|
||||
'Discard changes': 'Отменить изменения',
|
||||
'Save policy': 'Сохранить политику',
|
||||
'Saving…': 'Сохранение…',
|
||||
'Enable the update scheduler': 'Включить планировщик обновлений',
|
||||
'Check interval': 'Интервал проверки',
|
||||
'Schedule jitter': 'Разброс расписания',
|
||||
'Maintenance start (UTC)': 'Начало обслуживания (UTC)',
|
||||
'Maintenance duration': 'Длительность обслуживания',
|
||||
'Maximum runtime deferral': 'Максимальная отсрочка среды',
|
||||
'Previous healthy versions retained': 'Хранимые предыдущие исправные версии',
|
||||
'Component channels': 'Каналы компонентов',
|
||||
'Selections remain independent; incompatible cohorts stay staged.':
|
||||
'Выбор остаётся независимым; несовместимые наборы остаются подготовленными.',
|
||||
'Never modify loose local plugin files':
|
||||
'Никогда не изменять отдельные локальные файлы плагинов',
|
||||
'Plugin channel overrides': 'Переопределения каналов плагинов',
|
||||
'Pin individual managed plugins to another source or channel.':
|
||||
'Назначьте отдельным управляемым плагинам другой источник или канал.',
|
||||
'Add override': 'Добавить переопределение',
|
||||
'No plugin overrides': 'Переопределений плагинов нет',
|
||||
'Sources and trust roots': 'Источники и корни доверия',
|
||||
'Secret values stay in the service environment and are never returned here.':
|
||||
'Значения секретов остаются в окружении службы и никогда не возвращаются сюда.',
|
||||
'Add source': 'Добавить источник',
|
||||
'Confirm unsigned update': 'Подтвердите обновление без подписи',
|
||||
'This artifact has no trusted signature. Type {0} to authorize this exact candidate.':
|
||||
'У этого артефакта нет доверенной подписи. Введите {0}, чтобы разрешить именно этот кандидат.',
|
||||
'Authorize unsigned candidate': 'Разрешить кандидат без подписи',
|
||||
'Confirm downgrade': 'Подтвердите понижение версии',
|
||||
'A downgrade may make saved state incompatible. Type DOWNGRADE to continue.':
|
||||
'Понижение версии может сделать сохранённое состояние несовместимым. Введите DOWNGRADE для продолжения.',
|
||||
'Continue with downgrade': 'Продолжить понижение версии',
|
||||
'Restart Echoion': 'Перезапустить Echoion',
|
||||
'Applying this update restarts Echoion after it becomes idle. Continue?':
|
||||
'После перехода в режим ожидания Echoion будет перезапущен для применения обновления. Продолжить?',
|
||||
'Apply and restart': 'Применить и перезапустить',
|
||||
'{0} update queued': 'Обновление {0} поставлено в очередь',
|
||||
'Confirm rollback': 'Подтвердите откат',
|
||||
'Roll back {0} to {1}?': 'Откатить {0} до {1}?',
|
||||
'Rollback queued': 'Откат поставлен в очередь',
|
||||
'Enable unsigned update policy': 'Разрешить политику обновлений без подписи',
|
||||
'Unsigned staging will be permitted for: {0}. Type ENABLE UNSIGNED to save this policy.':
|
||||
'Подготовка без подписи будет разрешена для: {0}. Введите ENABLE UNSIGNED, чтобы сохранить политику.',
|
||||
'Save unsafe policy': 'Сохранить небезопасную политику',
|
||||
'Update policy saved': 'Политика обновлений сохранена',
|
||||
'Add update source': 'Добавить источник обновлений',
|
||||
'Use a short ID made from letters, numbers, dots, dashes, or underscores.':
|
||||
'Используйте короткий ID из букв, цифр, точек, дефисов или подчёркиваний.',
|
||||
'Invalid source ID': 'Недопустимый ID источника',
|
||||
'That source already exists': 'Такой источник уже существует',
|
||||
'Move every component off this source before removing it':
|
||||
'Перед удалением переведите все компоненты на другой источник',
|
||||
'Remove update source': 'Удалить источник обновлений',
|
||||
'Remove source {0} and its public keys?':
|
||||
'Удалить источник {0} и его открытые ключи?',
|
||||
'Add plugin channel override': 'Добавить переопределение канала плагина',
|
||||
'Enter the exact managed plugin ID.': 'Введите точный ID управляемого плагина.',
|
||||
'That plugin override already exists':
|
||||
'Переопределение для этого плагина уже существует',
|
||||
'Update check completed': 'Проверка обновлений завершена',
|
||||
'Update policy, trust keys, and activation controls are restricted to administrators.':
|
||||
'Политика обновлений, доверенные ключи и активация доступны только администраторам.',
|
||||
|
||||
// Now playing
|
||||
'Nothing playing': 'Ничего не играет',
|
||||
'Up Next': 'Далее',
|
||||
'Open queue →': 'Открыть очередь →',
|
||||
'Listening now': 'Сейчас слушают',
|
||||
'Queue is empty': 'Очередь пуста',
|
||||
'Vol': 'Гром.',
|
||||
'Radio': 'Радио',
|
||||
'Vote skip': 'Голос за пропуск',
|
||||
'Vote skip {0}/{1}': 'Пропуск {0}/{1}',
|
||||
'Shuffle': 'Перемешать',
|
||||
'Restart track': 'Сначала',
|
||||
'Play/Pause': 'Играть/Пауза',
|
||||
'Repeat': 'Повтор',
|
||||
'Favorite': 'В избранное',
|
||||
'Vote to skip': 'Голосовать за пропуск',
|
||||
'Force skip': 'Принудительный пропуск',
|
||||
'Radio mode is admin-only — ask an admin or use !autoplay':
|
||||
'Режим радио доступен только админам — попросите админа или используйте !autoplay',
|
||||
'Radio mode on': 'Режим радио включён',
|
||||
'Radio mode off': 'Режим радио выключен',
|
||||
'Vote passed — track skipped': 'Голосование прошло — трек пропущен',
|
||||
'Added to favorites': 'Добавлено в избранное',
|
||||
'Removed from favorites': 'Удалено из избранного',
|
||||
'Playing now': 'Играет сейчас',
|
||||
'Lyrics': 'Текст песни',
|
||||
'Show': 'Показать',
|
||||
'Hide': 'Скрыть',
|
||||
'Loading…': 'Загрузка…',
|
||||
'No lyrics found': 'Текст не найден',
|
||||
'Lyrics via': 'Текст из',
|
||||
|
||||
// Queue view
|
||||
'Queue is empty — add something from Search': 'Очередь пуста — добавьте что-нибудь из Поиска',
|
||||
'Shuffle queue': 'Перемешать очередь',
|
||||
'Clear': 'Очистить',
|
||||
'Clear the whole queue?': 'Очистить всю очередь?',
|
||||
'Queue cleared': 'Очередь очищена',
|
||||
'Play now': 'Играть сейчас',
|
||||
'Remove': 'Удалить',
|
||||
'{0} tracks': '{0} треков',
|
||||
|
||||
// Search
|
||||
'Search YouTube and Yandex Music… or paste a URL': 'Ищите на YouTube и в Яндекс Музыке… или вставьте ссылку',
|
||||
'All': 'Все',
|
||||
'No results yet — search for something': 'Пока нет результатов — поищите что-нибудь',
|
||||
'Searching “{0}”…': 'Ищем «{0}»…',
|
||||
'Add to queue': 'Добавить в очередь',
|
||||
'Added “{0}” to queue': '«{0}» добавлен в очередь',
|
||||
'Save to favorites': 'Сохранить в избранное',
|
||||
'Saved to favorites': 'Сохранено в избранное',
|
||||
|
||||
// Library
|
||||
'Your favorites': 'Ваше избранное',
|
||||
'Playlists': 'Плейлисты',
|
||||
'Save queue as playlist': 'Сохранить очередь как плейлист',
|
||||
'Authenticate to use favorites': 'Войдите, чтобы пользоваться избранным',
|
||||
'No favorites yet — ♥ a track anywhere': 'Пока нет избранного — нажмите ♥ на любом треке',
|
||||
'No playlists saved yet': 'Плейлистов пока нет',
|
||||
'Playlist name (saves the current queue):': 'Название плейлиста (сохранит текущую очередь):',
|
||||
'Playlist “{0}” saved': 'Плейлист «{0}» сохранён',
|
||||
'Loading playlist “{0}”…': 'Загружаем плейлист «{0}»…',
|
||||
'Saved from web UI': 'Сохранено из веб-интерфейса',
|
||||
'Delete': 'Удалить',
|
||||
'Delete playlist': 'Удалить плейлист',
|
||||
'Delete playlist “{0}”? This cannot be undone.':
|
||||
'Удалить плейлист «{0}»? Это нельзя отменить.',
|
||||
'Playlist “{0}” deleted': 'Плейлист «{0}» удалён',
|
||||
'Close': 'Закрыть',
|
||||
'This playlist is empty': 'Плейлист пуст',
|
||||
|
||||
// Stats
|
||||
'Recently played': 'Недавно игравшие',
|
||||
'Top requesters': 'Топ заказчиков',
|
||||
'Source split': 'Источники',
|
||||
'Nothing played yet': 'Пока ничего не игралось',
|
||||
'No requests logged yet': 'Запросов пока нет',
|
||||
'Queue again': 'Заказать снова',
|
||||
'Tracks played today': 'Треков за сегодня',
|
||||
'Listening hours': 'Часов прослушивания',
|
||||
'Queue additions': 'Добавлений в очередь',
|
||||
'Skips': 'Пропусков',
|
||||
'{0} all-time': '{0} за всё время',
|
||||
'today': 'сегодня',
|
||||
'{0}% skip rate': '{0}% пропусков',
|
||||
'{0} requests': '{0} запросов',
|
||||
|
||||
// Shared playback and action labels
|
||||
'Load': 'Загрузить',
|
||||
'Play next': 'Следующее',
|
||||
'LIVE': 'ЭФИР',
|
||||
'Send': 'Отправить',
|
||||
'Fullscreen': 'Во весь экран',
|
||||
|
||||
// Server & admin
|
||||
'Administration': 'Администрирование',
|
||||
'Administrator authentication required': 'Требуется вход администратора',
|
||||
'Sign in with an account in a configured TeamSpeak admin group.':
|
||||
'Войдите под учётной записью, входящей в настроенную группу администраторов TeamSpeak.',
|
||||
'TeamSpeak': 'TeamSpeak',
|
||||
'Echoion service': 'Служба Echoion',
|
||||
'Bot messaging and runtime operations':
|
||||
'Сообщения бота и управление службой',
|
||||
'Subscribers': 'Подписчики',
|
||||
'Emojis': 'Эмодзи',
|
||||
'Audit history': 'Журнал действий',
|
||||
'Room emojis moved to VoidWatch and are managed from its administration page.':
|
||||
'Эмодзи комнат перенесены в VoidWatch и управляются на его странице администрирования.',
|
||||
'Open VoidWatch admin ↗': 'Открыть панель VoidWatch ↗',
|
||||
'Announce…': 'Объявление…',
|
||||
'Reload config': 'Перезагрузить конфиг',
|
||||
'Restart web UI': 'Перезапустить веб-интерфейс',
|
||||
'Unsub all': 'Отписать всех',
|
||||
'No subscribers': 'Нет подписчиков',
|
||||
'Nobody online right now': 'Сейчас никого нет в сети',
|
||||
'Online': 'В сети',
|
||||
'Offline': 'Не в сети',
|
||||
'Unsub': 'Отписать',
|
||||
'Unsubscribe {0}?': 'Отписать {0}?',
|
||||
'Announcement to all subscribers:': 'Объявление всем подписчикам:',
|
||||
'Announcement sent': 'Объявление отправлено',
|
||||
'Configuration reloaded': 'Конфигурация перезагружена',
|
||||
'Restart the web interface? Everyone disconnects briefly.':
|
||||
'Перезапустить веб-интерфейс? Все ненадолго отключатся.',
|
||||
'Web interface restarting — this page will reconnect':
|
||||
'Веб-интерфейс перезапускается — страница переподключится',
|
||||
'Remove ALL subscriptions? This cannot be undone.':
|
||||
'Удалить ВСЕ подписки? Это нельзя отменить.',
|
||||
'All subscriptions removed': 'Все подписки удалены',
|
||||
'Listening': 'Слушает',
|
||||
'Refresh': 'Обновить',
|
||||
'No audit entries yet': 'Записей аудита пока нет',
|
||||
'client #{0}': 'клиент №{0}',
|
||||
|
||||
// Public TeamSpeak directory
|
||||
'TeamSpeak server': 'Сервер TeamSpeak',
|
||||
'Complete channel directory': 'Полное дерево каналов',
|
||||
'Connected': 'Подключено',
|
||||
'Disconnected': 'Отключено',
|
||||
'No channels available': 'Нет доступных каналов',
|
||||
'Password protected': 'Защищён паролем',
|
||||
'Talking': 'Говорит',
|
||||
'Away': 'Отошёл',
|
||||
'Muted': 'Микрофон выключен',
|
||||
'Deafened': 'Звук выключен',
|
||||
'clients': 'клиентов',
|
||||
'channels': 'каналов',
|
||||
'capacity': 'вместимость',
|
||||
'online': 'в сети',
|
||||
'default': 'по умолчанию',
|
||||
'locked': 'закрыт',
|
||||
'away': 'отошёл',
|
||||
'muted': 'микрофон выкл.',
|
||||
'deafened': 'звук выкл.',
|
||||
|
||||
// TeamSpeak administration
|
||||
'No TeamSpeak topology available': 'Дерево TeamSpeak недоступно',
|
||||
'Message': 'Сообщение',
|
||||
'Message {0}': 'Сообщение для {0}',
|
||||
'Private message:': 'Личное сообщение:',
|
||||
'Channel message:': 'Сообщение в канал:',
|
||||
'Message sent': 'Сообщение отправлено',
|
||||
'Server message': 'Сообщение серверу',
|
||||
'Message sent to every connected TeamSpeak client:':
|
||||
'Сообщение всем подключённым клиентам TeamSpeak:',
|
||||
'Server message sent': 'Сообщение серверу отправлено',
|
||||
'Move': 'Переместить',
|
||||
'Move {0}': 'Переместить {0}',
|
||||
'Destination channel ID:': 'ID целевого канала:',
|
||||
'Client moved': 'Клиент перемещён',
|
||||
'Kick': 'Выгнать',
|
||||
'Kick {0}': 'Выгнать {0}',
|
||||
'Kick this client from the server?': 'Выгнать этого клиента с сервера?',
|
||||
'Client kicked': 'Клиент выгнан',
|
||||
'Ban': 'Заблокировать',
|
||||
'Ban {0}': 'Заблокировать {0}',
|
||||
'Duration in seconds (0 = permanent):':
|
||||
'Срок в секундах (0 = бессрочно):',
|
||||
'Apply this ban now?': 'Заблокировать этого клиента сейчас?',
|
||||
'Client banned': 'Клиент заблокирован',
|
||||
'Bans': 'Блокировки',
|
||||
'No bans': 'Блокировок нет',
|
||||
'No reason': 'Без причины',
|
||||
'Permanent': 'Бессрочно',
|
||||
'Remove ban': 'Снять блокировку',
|
||||
'Remove this TeamSpeak ban?': 'Снять эту блокировку TeamSpeak?',
|
||||
'Unban': 'Разблокировать',
|
||||
'Ban removed': 'Блокировка снята',
|
||||
'Groups': 'Группы',
|
||||
'Current groups': 'Текущие группы',
|
||||
'Server group ID:': 'ID серверной группы:',
|
||||
'Add server group': 'Добавление в серверную группу',
|
||||
'Add group': 'Добавить в группу',
|
||||
'Group added': 'Клиент добавлен в группу',
|
||||
'Remove server group': 'Удаление из серверной группы',
|
||||
'Remove group': 'Удалить из группы',
|
||||
'Group removed': 'Клиент удалён из группы',
|
||||
'Create channel': 'Создать канал',
|
||||
'Channel name:': 'Название канала:',
|
||||
'Create': 'Создать',
|
||||
'Channel created': 'Канал создан',
|
||||
'Add child': 'Добавить подканал',
|
||||
'Rename channel': 'Переименовать канал',
|
||||
'Edit': 'Изменить',
|
||||
'Channel updated': 'Канал обновлён',
|
||||
'Reorder': 'Переместить',
|
||||
'Reorder channel': 'Переместить канал',
|
||||
'Parent channel ID (0 = root):': 'ID родительского канала (0 = корень):',
|
||||
'Previous sibling channel ID (0 = first):':
|
||||
'ID предыдущего канала на этом уровне (0 = первый):',
|
||||
'Channel reordered': 'Канал перемещён',
|
||||
'Delete channel': 'Удалить канал',
|
||||
'Delete {0} and its contents?': 'Удалить {0} вместе с содержимым?',
|
||||
'Channel deleted': 'Канал удалён',
|
||||
'Continue': 'Продолжить',
|
||||
|
||||
// RPC view
|
||||
'Connect programmatically': 'Программное подключение',
|
||||
'Copy snippet': 'Скопировать пример',
|
||||
'Snippet copied': 'Пример скопирован',
|
||||
'Copy': 'Копировать',
|
||||
'{0} copied': '{0} — скопировано',
|
||||
'(authenticate first)': '(сначала войдите)',
|
||||
|
||||
// Auth / connection
|
||||
'Signed in as {0}': 'Вы вошли как {0}',
|
||||
'Welcome, {0}!': 'Добро пожаловать, {0}!',
|
||||
'subscriber': 'подписчик',
|
||||
'friend': 'друг',
|
||||
'user': 'пользователь',
|
||||
'Connection failed': 'Не удалось подключиться',
|
||||
'Reconnected': 'Переподключено',
|
||||
'Logged out': 'Вы вышли',
|
||||
'Your TeamSpeak nickname (must be subscribed):': 'Ваш ник в TeamSpeak (нужна подписка):',
|
||||
'Token sent via TeamSpeak PM': 'Токен отправлен личным сообщением в TeamSpeak',
|
||||
'Request failed': 'Запрос не удался',
|
||||
'Language': 'Язык',
|
||||
'(untitled)': '(без названия)',
|
||||
// Main-UI feature additions (items 9, 11, 14, 15, 18)
|
||||
'Open original link': 'Открыть оригинальную ссылку',
|
||||
'Watch video': 'Смотреть видео',
|
||||
'Hide video': 'Скрыть видео',
|
||||
'Compose announcement': 'Составить объявление',
|
||||
'Send announcement': 'Отправить объявление',
|
||||
'Cancel': 'Отмена',
|
||||
'Preview': 'Предпросмотр',
|
||||
'Nothing to preview yet': 'Пока нечего показать',
|
||||
// Keyboard shortcuts
|
||||
'Keyboard shortcuts': 'Горячие клавиши',
|
||||
'Play / pause': 'Играть / пауза',
|
||||
'Seek 5s': 'Перемотка 5с',
|
||||
'Volume': 'Громкость',
|
||||
'Skip / vote skip': 'Пропустить / голос за пропуск',
|
||||
'Focus search': 'Перейти к поиску',
|
||||
'This help': 'Эта справка',
|
||||
|
||||
// Mobile / unified player / cleanup update
|
||||
'Menu': 'Меню',
|
||||
'Back 10 seconds': 'Назад на 10 секунд',
|
||||
'Forward 10 seconds': 'Вперёд на 10 секунд',
|
||||
'Clear queue': 'Очистить очередь',
|
||||
'Confirm': 'Подтвердить',
|
||||
'OK': 'ОК',
|
||||
'Save': 'Сохранить',
|
||||
'Restart': 'Перезапустить',
|
||||
'Remove all': 'Удалить все',
|
||||
'Unsubscribe': 'Отписаться',
|
||||
'Get token by nickname': 'Получить токен по нику',
|
||||
'Nickname': 'Ник',
|
||||
'Playlist name': 'Название плейлиста',
|
||||
'Save playlist': 'Сохранить плейлист',
|
||||
|
||||
'Add': 'Добавить',
|
||||
};
|
||||
Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user