@geastack/host 0.1.10 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/audio_runtime.cpp +97 -3
- package/host/audio.cpp +395 -10
- package/host/audio_worklet.cpp +611 -0
- package/host/fetch.cpp +17 -0
- package/host/media.cpp +308 -27
- package/host/mjpeg.cpp +205 -0
- package/host/rtc.cpp +458 -48
- package/host/rtc_esp.cpp +897 -75
- package/host/rtc_objects.inc +246 -0
- package/host/timers.cpp +18 -0
- package/host/video.cpp +152 -0
- package/host/websocket.cpp +623 -72
- package/host/worker.cpp +621 -0
- package/include/gea/audio-worklet-runtime.h +165 -0
- package/include/gea/base64-runtime.h +26 -0
- package/include/gea/embedded-host.h +1 -0
- package/include/gea/worker-runtime.h +189 -0
- package/include/host/audio.h +94 -6
- package/include/host/audio_level.h +37 -0
- package/include/host/audio_worklet.h +103 -0
- package/include/host/h264_layout.h +170 -0
- package/include/host/media.h +67 -0
- package/include/host/mjpeg.h +23 -0
- package/include/host/mjpeg_parser.h +126 -0
- package/include/host/pcm_stream.h +122 -0
- package/include/host/rtc.h +38 -20
- package/include/host/rtc_h264.h +76 -0
- package/include/host/rtc_ice_candidate.h +141 -0
- package/include/host/rtc_opus.h +136 -0
- package/include/host/rtc_receive_sdp.h +245 -0
- package/include/host/rtc_rtp.h +170 -0
- package/include/host/rtc_sdp.h +71 -0
- package/include/host/rtc_types.h +166 -0
- package/include/host/rtc_vp8.h +115 -0
- package/include/host/rtc_vp8_capture.h +129 -0
- package/include/host/rtc_vp8_decoder.h +169 -0
- package/include/host/rtc_vp8_receiver.h +55 -0
- package/include/host/timers.h +3 -2
- package/include/host/video.h +39 -0
- package/include/host/video_color.h +90 -0
- package/include/host/video_frame_pool.h +50 -0
- package/include/host/video_pixels.h +178 -0
- package/include/host/websocket.h +20 -1
- package/include/host/websocket_message.h +66 -0
- package/include/host/worker.h +131 -0
- package/package.json +1 -1
- package/services/diagnostics.cpp +120 -19
package/host/worker.cpp
ADDED
|
@@ -0,0 +1,621 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
#include "host/worker.h"
|
|
3
|
+
|
|
4
|
+
#include <algorithm>
|
|
5
|
+
#include <atomic>
|
|
6
|
+
#include <chrono>
|
|
7
|
+
#include <cmath>
|
|
8
|
+
#include <cstdio>
|
|
9
|
+
#include <condition_variable>
|
|
10
|
+
#include <deque>
|
|
11
|
+
#include <mutex>
|
|
12
|
+
#include <stdexcept>
|
|
13
|
+
#include <unordered_map>
|
|
14
|
+
#include <unordered_set>
|
|
15
|
+
#ifdef ESP_PLATFORM
|
|
16
|
+
#include "freertos/FreeRTOS.h"
|
|
17
|
+
#include "freertos/idf_additions.h"
|
|
18
|
+
#include "freertos/task.h"
|
|
19
|
+
#include "esp_heap_caps.h"
|
|
20
|
+
#include "esp_log.h"
|
|
21
|
+
#else
|
|
22
|
+
#include <thread>
|
|
23
|
+
#endif
|
|
24
|
+
|
|
25
|
+
namespace gea::host::workers {
|
|
26
|
+
namespace {
|
|
27
|
+
using Clock = std::chrono::steady_clock;
|
|
28
|
+
constexpr std::size_t maxQueueBytes = 2 * 1024 * 1024;
|
|
29
|
+
constexpr std::size_t maxQueueEntries = 1024;
|
|
30
|
+
thread_local std::shared_ptr<Context> activeContext;
|
|
31
|
+
thread_local MessagePort globalPort;
|
|
32
|
+
std::atomic<std::uint64_t> timerIds{1};
|
|
33
|
+
std::atomic<bool> mainCreated{false};
|
|
34
|
+
std::atomic<const char *> mainStage{"idle"};
|
|
35
|
+
struct Registry {
|
|
36
|
+
std::mutex mutex;
|
|
37
|
+
std::unordered_map<std::string, std::function<void()>> modules;
|
|
38
|
+
std::function<void(std::function<void()>)> realmRunner;
|
|
39
|
+
};
|
|
40
|
+
Registry ®istry() {
|
|
41
|
+
// Generated module registration and adapter installation run from static
|
|
42
|
+
// initializers in other translation units, before their ordering is known.
|
|
43
|
+
static Registry value;
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
struct Context::State {
|
|
49
|
+
struct Task { std::function<void()> callback; std::size_t bytes; };
|
|
50
|
+
struct Timer {
|
|
51
|
+
double id;
|
|
52
|
+
std::function<void()> callback;
|
|
53
|
+
Clock::time_point due;
|
|
54
|
+
std::chrono::milliseconds delay;
|
|
55
|
+
bool repeat;
|
|
56
|
+
};
|
|
57
|
+
bool main;
|
|
58
|
+
int priority;
|
|
59
|
+
int core;
|
|
60
|
+
std::string name;
|
|
61
|
+
std::mutex mutex;
|
|
62
|
+
std::condition_variable wake;
|
|
63
|
+
std::deque<Task> tasks;
|
|
64
|
+
std::vector<Timer> timers;
|
|
65
|
+
std::vector<std::function<void()>> cleanups;
|
|
66
|
+
std::function<void()> pump;
|
|
67
|
+
std::function<void(const std::string &)> error;
|
|
68
|
+
std::size_t bytes = 0;
|
|
69
|
+
bool lastWasTimer = false;
|
|
70
|
+
std::atomic<bool> stopping{false};
|
|
71
|
+
std::atomic<bool> started{false};
|
|
72
|
+
State(bool isMain, std::string label, int priority, int core)
|
|
73
|
+
: main(isMain), priority(priority), core(core), name(std::move(label)) {}
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
Context::Context(bool main, std::string name, int priority, int core)
|
|
77
|
+
: state_(new State(main, std::move(name), priority, core)) {}
|
|
78
|
+
Context::~Context() = default;
|
|
79
|
+
std::shared_ptr<Context> Context::main() {
|
|
80
|
+
static auto context = std::shared_ptr<Context>(new Context(true, "main"));
|
|
81
|
+
mainCreated.store(true, std::memory_order_release);
|
|
82
|
+
return context;
|
|
83
|
+
}
|
|
84
|
+
void Context::runMainPending() {
|
|
85
|
+
if (mainCreated.load(std::memory_order_acquire)) main()->runPending();
|
|
86
|
+
}
|
|
87
|
+
const char *Context::mainPendingStage() { return mainStage.load(std::memory_order_relaxed); }
|
|
88
|
+
bool Context::isWorkerCurrent() { return activeContext && !activeContext->isMain(); }
|
|
89
|
+
std::shared_ptr<Context> Context::current() { return activeContext ? activeContext : main(); }
|
|
90
|
+
std::shared_ptr<Context> Context::create(const std::string &name, int priority, int core) {
|
|
91
|
+
if (core < -1) throw std::invalid_argument("Invalid worker CPU affinity");
|
|
92
|
+
#ifdef ESP_PLATFORM
|
|
93
|
+
if (core >= portNUM_PROCESSORS) throw std::invalid_argument("Worker CPU affinity is unavailable");
|
|
94
|
+
#endif
|
|
95
|
+
return std::shared_ptr<Context>(new Context(false, name, priority, core));
|
|
96
|
+
}
|
|
97
|
+
ContextScope::ContextScope(std::shared_ptr<Context> context) : previous_(std::move(activeContext)) {
|
|
98
|
+
activeContext = std::move(context);
|
|
99
|
+
}
|
|
100
|
+
ContextScope::~ContextScope() { activeContext = std::move(previous_); }
|
|
101
|
+
bool Context::isMain() const { return state_->main; }
|
|
102
|
+
bool Context::stopped() const { return state_->stopping.load(); }
|
|
103
|
+
void Context::prioritizeAudio() {
|
|
104
|
+
if (state_->main || Context::current().get() != this) return;
|
|
105
|
+
#ifdef ESP_PLATFORM
|
|
106
|
+
const auto priority = configMAX_PRIORITIES - 2;
|
|
107
|
+
if (uxTaskPriorityGet(nullptr) < priority) {
|
|
108
|
+
vTaskPrioritySet(nullptr, priority);
|
|
109
|
+
ESP_LOGI("gea_worker", "audio protocol priority=%d", priority);
|
|
110
|
+
}
|
|
111
|
+
#endif
|
|
112
|
+
}
|
|
113
|
+
bool Context::post(std::function<void()> callback, std::size_t bytes) {
|
|
114
|
+
if (!callback) return false;
|
|
115
|
+
std::lock_guard lock(state_->mutex);
|
|
116
|
+
if (state_->stopping || state_->tasks.size() >= maxQueueEntries || bytes > maxQueueBytes - state_->bytes)
|
|
117
|
+
return false;
|
|
118
|
+
state_->tasks.push_back({std::move(callback), bytes});
|
|
119
|
+
state_->bytes += bytes;
|
|
120
|
+
state_->wake.notify_one();
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
void Context::setPump(std::function<void()> pump) { state_->pump = std::move(pump); }
|
|
124
|
+
void Context::setErrorHandler(std::function<void(const std::string &)> handler) {
|
|
125
|
+
std::lock_guard lock(state_->mutex);
|
|
126
|
+
state_->error = std::move(handler);
|
|
127
|
+
}
|
|
128
|
+
void Context::addCleanup(std::function<void()> cleanup) {
|
|
129
|
+
std::lock_guard lock(state_->mutex);
|
|
130
|
+
if (state_->stopping) throw std::runtime_error("Worker context is closed");
|
|
131
|
+
state_->cleanups.push_back(std::move(cleanup));
|
|
132
|
+
}
|
|
133
|
+
void Context::stop() {
|
|
134
|
+
{
|
|
135
|
+
std::lock_guard lock(state_->mutex);
|
|
136
|
+
state_->stopping.store(true);
|
|
137
|
+
}
|
|
138
|
+
state_->wake.notify_all();
|
|
139
|
+
}
|
|
140
|
+
double Context::schedule(std::function<void()> callback, double delayMs, bool repeat) {
|
|
141
|
+
const double normalized = std::isfinite(delayMs) ? std::min(delayMs, 2147483647.0) : 0;
|
|
142
|
+
const auto delay = std::chrono::milliseconds(static_cast<long long>(
|
|
143
|
+
std::max(repeat ? 1.0 : 0.0, normalized)));
|
|
144
|
+
const double id = static_cast<double>(timerIds.fetch_add(1));
|
|
145
|
+
std::lock_guard lock(state_->mutex);
|
|
146
|
+
if (state_->stopping) return 0;
|
|
147
|
+
state_->timers.push_back({id, std::move(callback), Clock::now() + delay, delay, repeat});
|
|
148
|
+
state_->wake.notify_one();
|
|
149
|
+
return id;
|
|
150
|
+
}
|
|
151
|
+
void Context::cancel(double id) {
|
|
152
|
+
std::lock_guard lock(state_->mutex);
|
|
153
|
+
std::erase_if(state_->timers, [id](const auto &timer) { return timer.id == id; });
|
|
154
|
+
}
|
|
155
|
+
void Context::runPending(double budgetMs) {
|
|
156
|
+
struct StageScope {
|
|
157
|
+
bool enabled;
|
|
158
|
+
const char *previous;
|
|
159
|
+
~StageScope() { if (enabled) mainStage.store(previous, std::memory_order_relaxed); }
|
|
160
|
+
} stageScope{state_->main, mainStage.load(std::memory_order_relaxed)};
|
|
161
|
+
const auto stage = [this](const char *name) {
|
|
162
|
+
if (state_->main) mainStage.store(name, std::memory_order_relaxed);
|
|
163
|
+
};
|
|
164
|
+
stage("context_scope");
|
|
165
|
+
ContextScope scope(shared_from_this());
|
|
166
|
+
const auto deadline = Clock::now() + std::chrono::microseconds(static_cast<long long>(budgetMs * 1000));
|
|
167
|
+
do {
|
|
168
|
+
std::function<void()> callback;
|
|
169
|
+
{
|
|
170
|
+
stage("queue_lock");
|
|
171
|
+
std::lock_guard lock(state_->mutex);
|
|
172
|
+
stage("queue_select");
|
|
173
|
+
if (state_->stopping) return;
|
|
174
|
+
// Timers must still advance during a continuous incoming packet stream.
|
|
175
|
+
const auto now = Clock::now();
|
|
176
|
+
auto timer = std::find_if(state_->timers.begin(), state_->timers.end(),
|
|
177
|
+
[now](const auto &candidate) { return candidate.due <= now; });
|
|
178
|
+
if (timer != state_->timers.end() && (state_->tasks.empty() || !state_->lastWasTimer)) {
|
|
179
|
+
state_->lastWasTimer = true;
|
|
180
|
+
callback = timer->callback;
|
|
181
|
+
if (timer->repeat) timer->due = now + timer->delay;
|
|
182
|
+
else state_->timers.erase(timer);
|
|
183
|
+
} else if (!state_->tasks.empty()) {
|
|
184
|
+
state_->lastWasTimer = false;
|
|
185
|
+
auto task = std::move(state_->tasks.front());
|
|
186
|
+
state_->tasks.pop_front();
|
|
187
|
+
state_->bytes -= task.bytes;
|
|
188
|
+
callback = std::move(task.callback);
|
|
189
|
+
} else break;
|
|
190
|
+
}
|
|
191
|
+
try {
|
|
192
|
+
stage("invoke_callback");
|
|
193
|
+
if (callback) callback();
|
|
194
|
+
stage("pump_microtasks");
|
|
195
|
+
if (state_->pump) state_->pump();
|
|
196
|
+
} catch (const std::exception &error) {
|
|
197
|
+
std::function<void(const std::string &)> report;
|
|
198
|
+
{ std::lock_guard lock(state_->mutex); report = state_->error; }
|
|
199
|
+
if (report) report(error.what());
|
|
200
|
+
else std::fprintf(stderr, "[Worker:%s] uncaught callback exception: %s\n", state_->name.c_str(), error.what());
|
|
201
|
+
} catch (...) {
|
|
202
|
+
std::function<void(const std::string &)> report;
|
|
203
|
+
{ std::lock_guard lock(state_->mutex); report = state_->error; }
|
|
204
|
+
if (report) report("Uncaught worker exception");
|
|
205
|
+
else std::fprintf(stderr, "[Worker:%s] uncaught callback exception\n", state_->name.c_str());
|
|
206
|
+
}
|
|
207
|
+
stage("release_callback");
|
|
208
|
+
callback = nullptr;
|
|
209
|
+
stage("check_budget");
|
|
210
|
+
} while (Clock::now() < deadline);
|
|
211
|
+
}
|
|
212
|
+
void Context::loop(std::function<void()> entry) {
|
|
213
|
+
ContextScope scope(shared_from_this());
|
|
214
|
+
std::function<void(std::function<void()>)> runner;
|
|
215
|
+
{ auto &state = registry(); std::lock_guard lock(state.mutex); runner = state.realmRunner; }
|
|
216
|
+
auto body = [this, entry = std::move(entry)]() mutable {
|
|
217
|
+
post(std::move(entry));
|
|
218
|
+
while (!state_->stopping) {
|
|
219
|
+
const auto turnStart = Clock::now();
|
|
220
|
+
constexpr double turnBudgetMs = 4;
|
|
221
|
+
runPending(turnBudgetMs);
|
|
222
|
+
std::unique_lock lock(state_->mutex);
|
|
223
|
+
if (state_->stopping) break;
|
|
224
|
+
const auto now = Clock::now();
|
|
225
|
+
const bool ready = !state_->tasks.empty() ||
|
|
226
|
+
std::any_of(state_->timers.begin(), state_->timers.end(),
|
|
227
|
+
[now](const auto &timer) { return timer.due <= now; });
|
|
228
|
+
if (ready) {
|
|
229
|
+
lock.unlock();
|
|
230
|
+
// A bounded dispatch turn is not a scheduling boundary by itself. A
|
|
231
|
+
// continuously ready worker otherwise immediately starts another turn
|
|
232
|
+
// and excludes lower-priority transport/UI tasks on FreeRTOS.
|
|
233
|
+
if (now - turnStart >= std::chrono::milliseconds(4)) {
|
|
234
|
+
#ifdef ESP_PLATFORM
|
|
235
|
+
vTaskDelay(1);
|
|
236
|
+
#else
|
|
237
|
+
std::this_thread::yield();
|
|
238
|
+
#endif
|
|
239
|
+
}
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
if (state_->timers.empty()) {
|
|
243
|
+
state_->wake.wait(lock, [this] {
|
|
244
|
+
return state_->stopping || !state_->tasks.empty() || !state_->timers.empty();
|
|
245
|
+
});
|
|
246
|
+
} else {
|
|
247
|
+
auto deadline = state_->timers.front().due;
|
|
248
|
+
for (const auto &timer : state_->timers) deadline = std::min(deadline, timer.due);
|
|
249
|
+
state_->wake.wait_until(lock, deadline);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
finish();
|
|
253
|
+
};
|
|
254
|
+
if (runner) runner(std::move(body)); else body();
|
|
255
|
+
}
|
|
256
|
+
void Context::finish() {
|
|
257
|
+
ContextScope scope(shared_from_this());
|
|
258
|
+
stop();
|
|
259
|
+
// Destroy callbacks, native sockets and compiler realm state on their owner.
|
|
260
|
+
std::vector<std::function<void()>> cleanups;
|
|
261
|
+
std::deque<State::Task> abandonedTasks;
|
|
262
|
+
std::vector<State::Timer> abandonedTimers;
|
|
263
|
+
{
|
|
264
|
+
std::lock_guard lock(state_->mutex);
|
|
265
|
+
cleanups.swap(state_->cleanups);
|
|
266
|
+
abandonedTasks.swap(state_->tasks);
|
|
267
|
+
abandonedTimers.swap(state_->timers);
|
|
268
|
+
state_->bytes = 0;
|
|
269
|
+
}
|
|
270
|
+
abandonedTasks.clear();
|
|
271
|
+
abandonedTimers.clear();
|
|
272
|
+
for (auto it = cleanups.rbegin(); it != cleanups.rend(); ++it) (*it)();
|
|
273
|
+
state_->pump = {};
|
|
274
|
+
globalPort.close();
|
|
275
|
+
globalPort = {};
|
|
276
|
+
}
|
|
277
|
+
void Context::start(std::function<void()> entry) {
|
|
278
|
+
if (state_->main || state_->started.exchange(true)) throw std::runtime_error("Worker already started");
|
|
279
|
+
auto context = shared_from_this();
|
|
280
|
+
#ifdef ESP_PLATFORM
|
|
281
|
+
struct Start {
|
|
282
|
+
std::shared_ptr<Context> context;
|
|
283
|
+
std::function<void()> entry;
|
|
284
|
+
bool capsStack = false;
|
|
285
|
+
};
|
|
286
|
+
auto *start = new Start{context, std::move(entry)};
|
|
287
|
+
const auto taskEntry = [](void *argument) {
|
|
288
|
+
bool capsStack;
|
|
289
|
+
{
|
|
290
|
+
std::unique_ptr<Start> start(static_cast<Start *>(argument));
|
|
291
|
+
capsStack = start->capsStack;
|
|
292
|
+
start->context->loop(std::move(start->entry));
|
|
293
|
+
}
|
|
294
|
+
#if CONFIG_FREERTOS_TASK_CREATE_ALLOW_EXT_MEM
|
|
295
|
+
if (capsStack) {
|
|
296
|
+
vTaskDeleteWithCaps(nullptr);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
#else
|
|
300
|
+
(void)capsStack;
|
|
301
|
+
#endif
|
|
302
|
+
vTaskDelete(nullptr);
|
|
303
|
+
};
|
|
304
|
+
const auto core = state_->core < 0 ? tskNO_AFFINITY : state_->core;
|
|
305
|
+
BaseType_t result = pdFAIL;
|
|
306
|
+
bool externalStack = false;
|
|
307
|
+
#if CONFIG_FREERTOS_TASK_CREATE_ALLOW_EXT_MEM
|
|
308
|
+
// Worker code executes with the flash cache enabled. Keep its sizeable
|
|
309
|
+
// stack out of scarce DMA-capable RAM, including on repeated connections.
|
|
310
|
+
// Publish allocation ownership before creation: the task can run immediately.
|
|
311
|
+
start->capsStack = true;
|
|
312
|
+
result = xTaskCreatePinnedToCoreWithCaps(taskEntry, state_->name.c_str(),
|
|
313
|
+
16384, start, state_->priority, nullptr, core, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
|
314
|
+
externalStack = result == pdPASS;
|
|
315
|
+
#endif
|
|
316
|
+
if (result != pdPASS) {
|
|
317
|
+
start->capsStack = false;
|
|
318
|
+
result = xTaskCreatePinnedToCore(taskEntry, state_->name.c_str(),
|
|
319
|
+
16384, start, state_->priority, nullptr, core);
|
|
320
|
+
}
|
|
321
|
+
if (result != pdPASS) {
|
|
322
|
+
ESP_LOGE("gea_worker", "task allocation failed name=%s stack=16384 internal_free=%u internal_largest=%u",
|
|
323
|
+
state_->name.c_str(),
|
|
324
|
+
static_cast<unsigned>(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)),
|
|
325
|
+
static_cast<unsigned>(heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)));
|
|
326
|
+
delete start;
|
|
327
|
+
state_->stopping = true;
|
|
328
|
+
throw std::runtime_error("Cannot create worker task");
|
|
329
|
+
}
|
|
330
|
+
ESP_LOGI("gea_worker", "started name=%s core=%d priority=%d stack=%s", state_->name.c_str(), state_->core, state_->priority,
|
|
331
|
+
externalStack ? "psram" : "internal");
|
|
332
|
+
#else
|
|
333
|
+
std::thread([context, entry = std::move(entry)]() mutable { context->loop(std::move(entry)); }).detach();
|
|
334
|
+
#endif
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
std::size_t MessageData::byteSize() const {
|
|
338
|
+
return std::visit([](const auto &value) { return value.size(); }, value);
|
|
339
|
+
}
|
|
340
|
+
struct MessagePort::Endpoint {
|
|
341
|
+
std::mutex mutex;
|
|
342
|
+
std::weak_ptr<Endpoint> peer;
|
|
343
|
+
std::weak_ptr<Context> owner;
|
|
344
|
+
std::function<void(MessageEvent &)> callback;
|
|
345
|
+
std::deque<MessageEvent> pending;
|
|
346
|
+
std::size_t bytes = 0;
|
|
347
|
+
bool started = false;
|
|
348
|
+
bool closed = false;
|
|
349
|
+
bool scheduled = false;
|
|
350
|
+
std::uint64_t generation = 0;
|
|
351
|
+
};
|
|
352
|
+
struct MessagePort::Ownership {
|
|
353
|
+
std::mutex mutex;
|
|
354
|
+
std::shared_ptr<Endpoint> endpoint;
|
|
355
|
+
};
|
|
356
|
+
namespace {
|
|
357
|
+
void dispatchPort(const std::shared_ptr<MessagePort::Endpoint> &endpoint, std::uint64_t generation);
|
|
358
|
+
void schedulePort(const std::shared_ptr<MessagePort::Endpoint> &endpoint) {
|
|
359
|
+
// Called with endpoint mutex held.
|
|
360
|
+
if (endpoint->closed || endpoint->scheduled || !endpoint->started || !endpoint->callback || endpoint->pending.empty()) return;
|
|
361
|
+
const auto owner = endpoint->owner.lock();
|
|
362
|
+
if (!owner || owner->stopped()) return;
|
|
363
|
+
endpoint->scheduled = true;
|
|
364
|
+
const auto generation = endpoint->generation;
|
|
365
|
+
if (!owner->post([endpoint, generation] { dispatchPort(endpoint, generation); })) {
|
|
366
|
+
endpoint->scheduled = false;
|
|
367
|
+
throw std::runtime_error("MessagePort owner queue is full");
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
void dispatchPort(const std::shared_ptr<MessagePort::Endpoint> &endpoint, std::uint64_t generation) {
|
|
371
|
+
MessageEvent event;
|
|
372
|
+
std::function<void(MessageEvent &)> callback;
|
|
373
|
+
{
|
|
374
|
+
std::lock_guard lock(endpoint->mutex);
|
|
375
|
+
if (generation != endpoint->generation) return;
|
|
376
|
+
endpoint->scheduled = false;
|
|
377
|
+
if (endpoint->closed || !endpoint->started || !endpoint->callback || endpoint->pending.empty()) return;
|
|
378
|
+
// A scheduled task from before a transfer must never deliver in the old realm.
|
|
379
|
+
if (endpoint->owner.lock() != Context::current()) { schedulePort(endpoint); return; }
|
|
380
|
+
event = std::move(endpoint->pending.front());
|
|
381
|
+
endpoint->pending.pop_front();
|
|
382
|
+
endpoint->bytes -= event.data.byteSize();
|
|
383
|
+
callback = endpoint->callback;
|
|
384
|
+
}
|
|
385
|
+
for (auto &port : event.ports) port.adopt(Context::current());
|
|
386
|
+
try { callback(event); } catch (...) {
|
|
387
|
+
std::lock_guard lock(endpoint->mutex);
|
|
388
|
+
schedulePort(endpoint);
|
|
389
|
+
throw;
|
|
390
|
+
}
|
|
391
|
+
std::lock_guard lock(endpoint->mutex);
|
|
392
|
+
schedulePort(endpoint);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
MessagePort::MessagePort(std::shared_ptr<Ownership> ownership) : ownership_(std::move(ownership)) {}
|
|
396
|
+
bool MessagePort::detached() const {
|
|
397
|
+
if (!ownership_) return true;
|
|
398
|
+
std::lock_guard lock(ownership_->mutex);
|
|
399
|
+
return !ownership_->endpoint;
|
|
400
|
+
}
|
|
401
|
+
MessagePort MessagePort::transfer() const {
|
|
402
|
+
std::function<void(MessageEvent &)> retiredHandler;
|
|
403
|
+
return transfer(retiredHandler);
|
|
404
|
+
}
|
|
405
|
+
MessagePort MessagePort::transfer(std::function<void(MessageEvent &)> &retiredHandler) const {
|
|
406
|
+
if (!ownership_) throw std::runtime_error("DataCloneError: detached MessagePort");
|
|
407
|
+
std::lock_guard lock(ownership_->mutex);
|
|
408
|
+
if (!ownership_->endpoint) throw std::runtime_error("DataCloneError: detached MessagePort");
|
|
409
|
+
auto target = std::make_shared<Ownership>();
|
|
410
|
+
target->endpoint = std::move(ownership_->endpoint);
|
|
411
|
+
{
|
|
412
|
+
std::lock_guard endpointLock(target->endpoint->mutex);
|
|
413
|
+
++target->endpoint->generation;
|
|
414
|
+
target->endpoint->scheduled = false;
|
|
415
|
+
retiredHandler.swap(target->endpoint->callback);
|
|
416
|
+
target->endpoint->started = false;
|
|
417
|
+
target->endpoint->owner.reset();
|
|
418
|
+
}
|
|
419
|
+
return MessagePort(std::move(target));
|
|
420
|
+
}
|
|
421
|
+
void MessagePort::adopt(const std::shared_ptr<Context> &owner) const {
|
|
422
|
+
if (!ownership_) return;
|
|
423
|
+
std::shared_ptr<Endpoint> endpoint;
|
|
424
|
+
{ std::lock_guard lock(ownership_->mutex); endpoint = ownership_->endpoint; }
|
|
425
|
+
if (!endpoint) return;
|
|
426
|
+
std::uint64_t generation;
|
|
427
|
+
{
|
|
428
|
+
std::lock_guard lock(endpoint->mutex);
|
|
429
|
+
endpoint->owner = owner;
|
|
430
|
+
generation = endpoint->generation;
|
|
431
|
+
}
|
|
432
|
+
if (!owner->isMain()) {
|
|
433
|
+
std::weak_ptr<Endpoint> weak = endpoint;
|
|
434
|
+
const auto identity = owner.get();
|
|
435
|
+
owner->addCleanup([weak, identity, generation] {
|
|
436
|
+
if (auto endpoint = weak.lock()) {
|
|
437
|
+
std::function<void(MessageEvent &)> callback;
|
|
438
|
+
std::deque<MessageEvent> pending;
|
|
439
|
+
{
|
|
440
|
+
std::lock_guard lock(endpoint->mutex);
|
|
441
|
+
// A port transferred onward belongs to its new realm's teardown.
|
|
442
|
+
if (endpoint->owner.lock().get() != identity || endpoint->generation != generation) return;
|
|
443
|
+
endpoint->closed = true;
|
|
444
|
+
// A moved small std::function may leave its source callable intact.
|
|
445
|
+
// Swap with empty to break native-port/realm-object ownership cycles.
|
|
446
|
+
callback.swap(endpoint->callback);
|
|
447
|
+
pending.swap(endpoint->pending);
|
|
448
|
+
endpoint->bytes = 0;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
void MessagePort::validateTransfers(const std::vector<MessagePort> &ports) const {
|
|
456
|
+
std::shared_ptr<Endpoint> endpoint;
|
|
457
|
+
if (ownership_) { std::lock_guard lock(ownership_->mutex); endpoint = ownership_->endpoint; }
|
|
458
|
+
std::shared_ptr<Endpoint> peer;
|
|
459
|
+
if (endpoint) { std::lock_guard lock(endpoint->mutex); peer = endpoint->peer.lock(); }
|
|
460
|
+
std::unordered_set<const Ownership *> seen;
|
|
461
|
+
for (const auto &port : ports) {
|
|
462
|
+
if (!port.ownership_ || port.ownership_ == ownership_ || !seen.insert(port.ownership_.get()).second)
|
|
463
|
+
throw std::runtime_error("DataCloneError: invalid MessagePort transfer list");
|
|
464
|
+
std::lock_guard lock(port.ownership_->mutex);
|
|
465
|
+
if (!port.ownership_->endpoint || port.ownership_->endpoint == peer)
|
|
466
|
+
throw std::runtime_error("DataCloneError: invalid MessagePort transfer list");
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
void MessagePort::postMessage(MessageData data, const std::vector<MessagePort> &transferPorts) const {
|
|
470
|
+
if (!ownership_) return;
|
|
471
|
+
std::shared_ptr<Endpoint> endpoint;
|
|
472
|
+
{ std::lock_guard lock(ownership_->mutex); endpoint = ownership_->endpoint; }
|
|
473
|
+
if (!endpoint) return;
|
|
474
|
+
std::shared_ptr<Endpoint> peer;
|
|
475
|
+
{ std::lock_guard lock(endpoint->mutex); if (endpoint->closed) return; peer = endpoint->peer.lock(); }
|
|
476
|
+
if (!peer) return;
|
|
477
|
+
std::unordered_set<const Ownership *> seen;
|
|
478
|
+
for (const auto &port : transferPorts) {
|
|
479
|
+
if (port.detached() || port.ownership_ == ownership_ || !seen.insert(port.ownership_.get()).second)
|
|
480
|
+
throw std::runtime_error("DataCloneError: invalid MessagePort transfer list");
|
|
481
|
+
}
|
|
482
|
+
for (const auto &port : transferPorts) {
|
|
483
|
+
std::lock_guard lock(port.ownership_->mutex);
|
|
484
|
+
if (port.ownership_->endpoint == peer)
|
|
485
|
+
throw std::runtime_error("DataCloneError: destination MessagePort cannot transfer itself");
|
|
486
|
+
}
|
|
487
|
+
// Transferring a listening port discards its old handler. Keep those handlers
|
|
488
|
+
// alive until the destination lock is released: destructors may close it.
|
|
489
|
+
std::vector<std::function<void(MessageEvent &)>> retiredHandlers(transferPorts.size());
|
|
490
|
+
{
|
|
491
|
+
std::lock_guard lock(peer->mutex);
|
|
492
|
+
if (peer->closed) return;
|
|
493
|
+
if (peer->pending.size() >= maxQueueEntries || data.byteSize() > maxQueueBytes - peer->bytes)
|
|
494
|
+
throw std::runtime_error("MessagePort queue exceeded its bounded capacity");
|
|
495
|
+
MessageEvent event{std::move(data), {}};
|
|
496
|
+
event.ports.reserve(transferPorts.size());
|
|
497
|
+
for (std::size_t i = 0; i < transferPorts.size(); ++i)
|
|
498
|
+
event.ports.push_back(transferPorts[i].transfer(retiredHandlers[i]));
|
|
499
|
+
peer->bytes += event.data.byteSize();
|
|
500
|
+
peer->pending.push_back(std::move(event));
|
|
501
|
+
schedulePort(peer);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
void MessagePort::setOnMessage(std::function<void(MessageEvent &)> callback) const {
|
|
505
|
+
if (!ownership_) return;
|
|
506
|
+
{
|
|
507
|
+
std::lock_guard lock(ownership_->mutex);
|
|
508
|
+
if (!ownership_->endpoint) return;
|
|
509
|
+
std::lock_guard endpointLock(ownership_->endpoint->mutex);
|
|
510
|
+
callback.swap(ownership_->endpoint->callback);
|
|
511
|
+
ownership_->endpoint->started = true;
|
|
512
|
+
schedulePort(ownership_->endpoint);
|
|
513
|
+
}
|
|
514
|
+
// Callback captures may close this same port when their last reference dies.
|
|
515
|
+
// Release the old handler only after both native locks have been dropped.
|
|
516
|
+
}
|
|
517
|
+
void MessagePort::start() const {
|
|
518
|
+
if (!ownership_) return;
|
|
519
|
+
std::lock_guard lock(ownership_->mutex);
|
|
520
|
+
if (!ownership_->endpoint) return;
|
|
521
|
+
std::lock_guard endpointLock(ownership_->endpoint->mutex);
|
|
522
|
+
ownership_->endpoint->started = true;
|
|
523
|
+
schedulePort(ownership_->endpoint);
|
|
524
|
+
}
|
|
525
|
+
void MessagePort::close() const {
|
|
526
|
+
if (!ownership_) return;
|
|
527
|
+
std::function<void(MessageEvent &)> callback;
|
|
528
|
+
std::deque<MessageEvent> pending;
|
|
529
|
+
{
|
|
530
|
+
std::lock_guard lock(ownership_->mutex);
|
|
531
|
+
if (!ownership_->endpoint) return;
|
|
532
|
+
std::lock_guard endpointLock(ownership_->endpoint->mutex);
|
|
533
|
+
ownership_->endpoint->closed = true;
|
|
534
|
+
callback.swap(ownership_->endpoint->callback);
|
|
535
|
+
pending.swap(ownership_->endpoint->pending);
|
|
536
|
+
ownership_->endpoint->bytes = 0;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
MessageChannel::MessageChannel() {
|
|
540
|
+
auto a = std::make_shared<MessagePort::Endpoint>();
|
|
541
|
+
auto b = std::make_shared<MessagePort::Endpoint>();
|
|
542
|
+
a->peer = b; b->peer = a;
|
|
543
|
+
a->owner = Context::current(); b->owner = Context::current();
|
|
544
|
+
auto first = std::make_shared<MessagePort::Ownership>(); first->endpoint = a;
|
|
545
|
+
auto second = std::make_shared<MessagePort::Ownership>(); second->endpoint = b;
|
|
546
|
+
port1 = MessagePort(first); port2 = MessagePort(second);
|
|
547
|
+
port1.adopt(Context::current());
|
|
548
|
+
port2.adopt(Context::current());
|
|
549
|
+
}
|
|
550
|
+
void setRealmRunner(std::function<void(std::function<void()>)> runner) {
|
|
551
|
+
auto &state = registry();
|
|
552
|
+
std::lock_guard lock(state.mutex);
|
|
553
|
+
state.realmRunner = std::move(runner);
|
|
554
|
+
}
|
|
555
|
+
void registerModule(const std::string &url, std::function<void()> entry) {
|
|
556
|
+
auto &state = registry();
|
|
557
|
+
std::lock_guard lock(state.mutex);
|
|
558
|
+
state.modules[url] = std::move(entry);
|
|
559
|
+
}
|
|
560
|
+
DedicatedWorkerGlobalScope self() { return {}; }
|
|
561
|
+
void DedicatedWorkerGlobalScope::postMessage(MessageData data, const std::vector<MessagePort> &transfer) const {
|
|
562
|
+
globalPort.postMessage(std::move(data), transfer);
|
|
563
|
+
}
|
|
564
|
+
void DedicatedWorkerGlobalScope::validateTransfers(const std::vector<MessagePort> &ports) const { globalPort.validateTransfers(ports); }
|
|
565
|
+
void DedicatedWorkerGlobalScope::setOnMessage(std::function<void(MessageEvent &)> callback) const {
|
|
566
|
+
globalPort.setOnMessage(std::move(callback));
|
|
567
|
+
}
|
|
568
|
+
void DedicatedWorkerGlobalScope::close() const { Context::current()->stop(); }
|
|
569
|
+
struct Worker::State {
|
|
570
|
+
std::shared_ptr<Context> context;
|
|
571
|
+
std::shared_ptr<Context> creator;
|
|
572
|
+
MessagePort port;
|
|
573
|
+
std::function<void(const std::string &)> onError;
|
|
574
|
+
};
|
|
575
|
+
Worker Worker::create(const std::string &url) {
|
|
576
|
+
std::function<void()> entry;
|
|
577
|
+
{ auto &state = registry(); std::lock_guard lock(state.mutex); auto it = state.modules.find(url);
|
|
578
|
+
if (it == state.modules.end()) throw std::runtime_error("Worker module not registered: " + url);
|
|
579
|
+
entry = it->second;
|
|
580
|
+
}
|
|
581
|
+
Worker worker;
|
|
582
|
+
worker.state_ = std::make_shared<State>();
|
|
583
|
+
auto state = worker.state_;
|
|
584
|
+
state->context = Context::create("gea_worker");
|
|
585
|
+
state->creator = Context::current();
|
|
586
|
+
MessageChannel channel;
|
|
587
|
+
state->port = channel.port1;
|
|
588
|
+
auto target = channel.port2.transfer();
|
|
589
|
+
std::weak_ptr<State> weak = state;
|
|
590
|
+
state->context->setErrorHandler([weak, creator = state->creator](const std::string &error) {
|
|
591
|
+
// Only the creator task may acquire a strong State reference: the last
|
|
592
|
+
// reference owns callbacks containing non-atomic, realm-local compiler Refs.
|
|
593
|
+
creator->post([weak, error] {
|
|
594
|
+
if (auto state = weak.lock(); state && state->onError) state->onError(error);
|
|
595
|
+
}, error.size());
|
|
596
|
+
});
|
|
597
|
+
state->context->start([target, entry = std::move(entry)] {
|
|
598
|
+
target.adopt(Context::current());
|
|
599
|
+
globalPort = target;
|
|
600
|
+
entry();
|
|
601
|
+
});
|
|
602
|
+
return worker;
|
|
603
|
+
}
|
|
604
|
+
void Worker::postMessage(MessageData data, const std::vector<MessagePort> &transfer) const {
|
|
605
|
+
if (state_ && !state_->context->stopped()) state_->port.postMessage(std::move(data), transfer);
|
|
606
|
+
}
|
|
607
|
+
void Worker::validateTransfers(const std::vector<MessagePort> &ports) const {
|
|
608
|
+
if (state_) state_->port.validateTransfers(ports);
|
|
609
|
+
}
|
|
610
|
+
void Worker::setOnMessage(std::function<void(MessageEvent &)> callback) const {
|
|
611
|
+
if (state_) state_->port.setOnMessage(std::move(callback));
|
|
612
|
+
}
|
|
613
|
+
void Worker::setOnError(std::function<void(const std::string &)> callback) const {
|
|
614
|
+
if (state_) state_->onError = std::move(callback);
|
|
615
|
+
}
|
|
616
|
+
void Worker::terminate() const {
|
|
617
|
+
if (!state_) return;
|
|
618
|
+
state_->port.close();
|
|
619
|
+
state_->context->stop();
|
|
620
|
+
}
|
|
621
|
+
} // namespace gea::host::workers
|