@geastack/host 0.1.17 → 0.1.18

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.
@@ -0,0 +1,574 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Linux desktop provider: link a WebSocket-enabled libcurl >= 7.86.
3
+ #if defined(__linux__) || defined(GEA_TEST_CURL_WEBSOCKET)
4
+ #include "host/websocket_platform.h"
5
+ #include <atomic>
6
+ #include <chrono>
7
+ #include <cstring>
8
+ #include <curl/curl.h>
9
+ #include <curl/websockets.h>
10
+ #include <deque>
11
+ #include <mutex>
12
+ #include <poll.h>
13
+ #include <thread>
14
+ #include <unordered_map>
15
+ #if defined(GEA_TEST_CURL_PARTIAL_SEND)
16
+ #include <sys/socket.h>
17
+ #endif
18
+ #if LIBCURL_VERSION_NUM < 0x075600
19
+ #error "Desktop WebSocket requires libcurl >= 7.86 with ws/wss enabled"
20
+ #endif
21
+ namespace gea::host::websocket::curl_transport {
22
+ using Clock = std::chrono::steady_clock;
23
+ #if defined(GEA_TEST_CURL_PARTIAL_SEND)
24
+ std::atomic<unsigned> partialSends{0};
25
+ unsigned partial_send_count_for_test() { return partialSends.load(); }
26
+ #endif
27
+ CURLcode initialize() {
28
+ static const auto result = curl_global_init(CURL_GLOBAL_DEFAULT);
29
+ return result;
30
+ }
31
+ constexpr std::size_t maxBytes = 512 * 1024, maxMessages = 1024,
32
+ maxReceive = 1024 * 1024;
33
+ bool utf8(const std::string &text) {
34
+ std::size_t i = 0;
35
+ while (i < text.size()) {
36
+ auto c = static_cast<unsigned char>(text[i++]);
37
+ if (c < 0x80)
38
+ continue;
39
+ unsigned count;
40
+ unsigned scalar;
41
+ if (c >= 0xc2 && c <= 0xdf) {
42
+ count = 1;
43
+ scalar = c & 31;
44
+ } else if (c >= 0xe0 && c <= 0xef) {
45
+ count = 2;
46
+ scalar = c & 15;
47
+ } else if (c >= 0xf0 && c <= 0xf4) {
48
+ count = 3;
49
+ scalar = c & 7;
50
+ } else
51
+ return false;
52
+ const unsigned minimum = count == 1 ? 0x80 : count == 2 ? 0x800 : 0x10000;
53
+ if (text.size() - i < count)
54
+ return false;
55
+ while (count--) {
56
+ auto d = static_cast<unsigned char>(text[i++]);
57
+ if ((d & 0xc0) != 0x80)
58
+ return false;
59
+ scalar = (scalar << 6) | (d & 63);
60
+ }
61
+ if (scalar < minimum || scalar > 0x10ffff ||
62
+ (scalar >= 0xd800 && scalar <= 0xdfff))
63
+ return false;
64
+ }
65
+ return true;
66
+ }
67
+ struct State {
68
+ NativeWebSocketHandle handle;
69
+ std::string url, protocols, headers;
70
+ std::mutex mutex;
71
+ std::deque<std::string> outgoing;
72
+ std::size_t bytes = 0, entries = 0;
73
+ TextProducer producer;
74
+ std::atomic<bool> stop{false}, closing{false}, opened{false}, finished{false};
75
+ std::thread worker;
76
+ explicit State(NativeWebSocketHandle h) : handle(h) {}
77
+ ~State() {
78
+ stop = true;
79
+ if (worker.joinable())
80
+ worker.join();
81
+ }
82
+ void fail(const char *message) {
83
+ opened = false;
84
+ if (!stop.load()) {
85
+ transport_error(handle, message);
86
+ transport_close(handle, 1006, "WebSocket transport failed");
87
+ }
88
+ }
89
+ bool enqueue(std::string text) {
90
+ std::lock_guard lock(mutex);
91
+ if (!opened.load() || closing.load() || stop.load())
92
+ return false;
93
+ if (entries >= maxMessages || text.size() > maxBytes - bytes)
94
+ throw std::length_error("WebSocket send queue exceeds bounded capacity");
95
+ bytes += text.size();
96
+ ++entries;
97
+ outgoing.push_back(std::move(text));
98
+ return true;
99
+ }
100
+ void run();
101
+ };
102
+ struct Registry {
103
+ std::mutex mutex;
104
+ std::unordered_map<NativeWebSocketHandle, std::shared_ptr<State>> live;
105
+ std::vector<std::shared_ptr<State>> retired;
106
+ ~Registry() {
107
+ for (auto &[id, s] : live)
108
+ s->stop = true;
109
+ for (auto &s : retired)
110
+ s->stop = true;
111
+ }
112
+ };
113
+ Registry &registry() {
114
+ static Registry r;
115
+ return r;
116
+ }
117
+ std::shared_ptr<State> find(NativeWebSocketHandle h) {
118
+ auto &r = registry();
119
+ std::lock_guard lock(r.mutex);
120
+ auto i = r.live.find(h);
121
+ return i == r.live.end() ? nullptr : i->second;
122
+ }
123
+ struct Curl {
124
+ CURL *easy = curl_easy_init();
125
+ curl_slist *headers = nullptr;
126
+ ~Curl() {
127
+ if (headers)
128
+ curl_slist_free_all(headers);
129
+ if (easy)
130
+ curl_easy_cleanup(easy);
131
+ }
132
+ };
133
+ void State::run() {
134
+ struct Done {
135
+ State &s;
136
+ ~Done() {
137
+ s.opened = false;
138
+ TextProducer retired;
139
+ {
140
+ std::lock_guard lock(s.mutex);
141
+ s.outgoing.clear();
142
+ retired = std::move(s.producer);
143
+ s.bytes = s.entries = 0;
144
+ }
145
+ retired = {};
146
+ s.finished.store(true, std::memory_order_release);
147
+ }
148
+ } done{*this};
149
+ try {
150
+ if (stop.load())
151
+ return;
152
+ if (closing.load()) {
153
+ transport_close(handle, 1000, "WebSocket closed locally");
154
+ return;
155
+ }
156
+ if (initialize() != CURLE_OK) {
157
+ fail("WebSocket libcurl initialization failed");
158
+ return;
159
+ }
160
+ const auto *version = curl_version_info(CURLVERSION_NOW);
161
+ bool supported = false;
162
+ const bool secure = url.rfind("wss://", 0) == 0;
163
+ for (const char *const *p = version->protocols; p && *p; ++p)
164
+ if (std::strcmp(*p, secure ? "wss" : "ws") == 0)
165
+ supported = true;
166
+ if (!supported) {
167
+ fail("WebSocket protocol not enabled in libcurl");
168
+ return;
169
+ }
170
+ Curl c;
171
+ if (!c.easy) {
172
+ fail("WebSocket allocation failed");
173
+ return;
174
+ }
175
+ curl_easy_setopt(c.easy, CURLOPT_URL, url.c_str());
176
+ curl_easy_setopt(c.easy, CURLOPT_CONNECT_ONLY, 2L);
177
+ curl_easy_setopt(c.easy, CURLOPT_CONNECTTIMEOUT_MS, 10000L);
178
+ curl_easy_setopt(c.easy, CURLOPT_TIMEOUT_MS, 10000L);
179
+ curl_easy_setopt(c.easy, CURLOPT_NOSIGNAL, 1L);
180
+ #if defined(GEA_TEST_CURL_PARTIAL_SEND)
181
+ // Test-only kernel backpressure; the production send algorithm is
182
+ // unchanged.
183
+ curl_easy_setopt(
184
+ c.easy, CURLOPT_SOCKOPTFUNCTION,
185
+ +[](void *, curl_socket_t socket, curlsocktype) -> int {
186
+ const int bytes = 4096;
187
+ return setsockopt(socket, SOL_SOCKET, SO_SNDBUF, &bytes,
188
+ sizeof(bytes)) == 0
189
+ ? CURL_SOCKOPT_OK
190
+ : CURL_SOCKOPT_ERROR;
191
+ });
192
+ #endif
193
+ curl_easy_setopt(c.easy, CURLOPT_NOPROGRESS, 0L);
194
+ curl_easy_setopt(c.easy, CURLOPT_XFERINFODATA, this);
195
+ curl_easy_setopt(
196
+ c.easy, CURLOPT_XFERINFOFUNCTION,
197
+ +[](void *p, curl_off_t, curl_off_t, curl_off_t, curl_off_t) -> int {
198
+ auto *s = static_cast<State *>(p);
199
+ return s->stop.load() || s->closing.load();
200
+ });
201
+ // No redirects, cookies, credentials or TLS-verification overrides.
202
+ if (!protocols.empty()) {
203
+ c.headers = curl_slist_append(
204
+ c.headers, ("Sec-WebSocket-Protocol: " + protocols).c_str());
205
+ if (!c.headers)
206
+ throw std::bad_alloc();
207
+ }
208
+ std::size_t at = 0;
209
+ while (at < headers.size()) {
210
+ auto end = headers.find("\r\n", at);
211
+ auto line = headers.substr(at, end - at);
212
+ auto next = curl_slist_append(c.headers, line.c_str());
213
+ if (!next)
214
+ throw std::bad_alloc();
215
+ c.headers = next;
216
+ at = end + 2;
217
+ }
218
+ if (c.headers)
219
+ curl_easy_setopt(c.easy, CURLOPT_HTTPHEADER, c.headers);
220
+ const auto connected = curl_easy_perform(c.easy);
221
+ if (stop.load())
222
+ return;
223
+ if (closing.load()) {
224
+ transport_close(handle, 1000, "WebSocket closed locally");
225
+ return;
226
+ }
227
+ if (connected != CURLE_OK) {
228
+ fail("WebSocket connection or upgrade failed");
229
+ return;
230
+ }
231
+ opened = true;
232
+ if (!transport_open(handle))
233
+ return;
234
+ curl_socket_t socket = CURL_SOCKET_BAD;
235
+ if (curl_easy_getinfo(c.easy, CURLINFO_ACTIVESOCKET, &socket) != CURLE_OK ||
236
+ socket == CURL_SOCKET_BAD) {
237
+ fail("WebSocket socket unavailable");
238
+ return;
239
+ }
240
+ std::string active, message, control;
241
+ std::size_t sentAt = 0, frameAt = 0;
242
+ bool haveActive = false, messageOpen = false;
243
+ int messageType = 0;
244
+ bool closeSent = false;
245
+ auto sendDeadline = Clock::now(), closeDeadline = Clock::time_point::max();
246
+ auto sendClose = [&](const std::string &payload) {
247
+ std::size_t offset = 0;
248
+ const auto deadline = Clock::now() + std::chrono::seconds(2);
249
+ do {
250
+ std::size_t sent = 0;
251
+ const auto rc =
252
+ curl_ws_send(c.easy, payload.data() + offset,
253
+ payload.size() - offset, &sent, 0, CURLWS_CLOSE);
254
+ if (rc != CURLE_OK && rc != CURLE_AGAIN)
255
+ return false;
256
+ offset += sent;
257
+ if (rc == CURLE_OK && offset == payload.size())
258
+ return true;
259
+ pollfd fd{socket, POLLOUT, 0};
260
+ ::poll(&fd, 1, 10);
261
+ } while (!stop.load() && Clock::now() < deadline);
262
+ return false;
263
+ };
264
+ while (!stop.load()) {
265
+ bool pending;
266
+ {
267
+ std::lock_guard lock(mutex);
268
+ pending = entries != 0;
269
+ }
270
+ if (closing.load() && !closeSent && !pending) {
271
+ if (!sendClose(std::string("\x03\xe8", 2))) {
272
+ transport_close(handle, 1000, "WebSocket closed locally");
273
+ return;
274
+ }
275
+ closeSent = true;
276
+ closeDeadline = Clock::now() + std::chrono::seconds(2);
277
+ }
278
+ if (closeSent && Clock::now() >= closeDeadline) {
279
+ transport_close(handle, 1000, "WebSocket closed locally");
280
+ return;
281
+ }
282
+ if (!closing.load()) {
283
+ TextProducer next;
284
+ {
285
+ std::lock_guard lock(mutex);
286
+ next = producer;
287
+ }
288
+ if (next) {
289
+ auto produced = next();
290
+ if (!produced.empty())
291
+ enqueue(std::move(produced));
292
+ }
293
+ }
294
+ if (!haveActive) {
295
+ std::lock_guard lock(mutex);
296
+ if (!outgoing.empty()) {
297
+ active = std::move(outgoing.front());
298
+ outgoing.pop_front();
299
+ sentAt = 0;
300
+ haveActive = true;
301
+ sendDeadline = Clock::now() + std::chrono::seconds(10);
302
+ }
303
+ }
304
+ if (haveActive) {
305
+ if (!utf8(active)) {
306
+ fail("WebSocket text must be valid UTF-8");
307
+ return;
308
+ }
309
+ std::size_t sent = 0;
310
+ const auto rc =
311
+ curl_ws_send(c.easy, active.data() + sentAt, active.size() - sentAt,
312
+ &sent, 0, CURLWS_TEXT);
313
+ if (rc != CURLE_OK && rc != CURLE_AGAIN) {
314
+ fail("WebSocket send failed");
315
+ return;
316
+ }
317
+ #if defined(GEA_TEST_CURL_PARTIAL_SEND)
318
+ if (rc == CURLE_AGAIN || sent < active.size() - sentAt)
319
+ ++partialSends;
320
+ #endif
321
+ sentAt += sent;
322
+ if (rc == CURLE_OK && sentAt == active.size()) {
323
+ std::lock_guard lock(mutex);
324
+ bytes -= active.size();
325
+ --entries;
326
+ haveActive = false;
327
+ active.clear();
328
+ } else if (Clock::now() >= sendDeadline) {
329
+ fail("WebSocket send timed out");
330
+ return;
331
+ }
332
+ }
333
+ char buffer[16384];
334
+ std::size_t received = 0;
335
+ const curl_ws_frame *meta = nullptr;
336
+ const auto rc =
337
+ curl_ws_recv(c.easy, buffer, sizeof(buffer), &received, &meta);
338
+ if (rc == CURLE_OK && meta) {
339
+ const int flags = meta->flags;
340
+ const auto offset = meta->offset, left = meta->bytesleft;
341
+ if (offset < 0 || left < 0 ||
342
+ static_cast<unsigned long long>(offset) + received +
343
+ static_cast<unsigned long long>(left) >
344
+ maxReceive) {
345
+ fail("WebSocket message exceeds 1 MiB");
346
+ return;
347
+ }
348
+ if (flags & CURLWS_CLOSE) {
349
+ if (offset == 0)
350
+ control.clear();
351
+ if (static_cast<std::size_t>(offset) != control.size() ||
352
+ control.size() + received > 125) {
353
+ fail("Invalid WebSocket close frame");
354
+ return;
355
+ }
356
+ control.append(buffer, received);
357
+ if (left == 0) {
358
+ int code = 1000;
359
+ std::string reason;
360
+ if (control.size() >= 2) {
361
+ code = (static_cast<unsigned char>(control[0]) << 8) |
362
+ static_cast<unsigned char>(control[1]);
363
+ reason = control.substr(2);
364
+ }
365
+ if (!utf8(reason)) {
366
+ fail("Invalid WebSocket close text");
367
+ return;
368
+ }
369
+ if (!closeSent && !haveActive)
370
+ sendClose(control);
371
+ transport_close(handle, code, reason);
372
+ return;
373
+ }
374
+ } else if (flags & (CURLWS_TEXT | CURLWS_BINARY)) {
375
+ const int type = flags & CURLWS_TEXT ? 1 : 2;
376
+ if (offset == 0) {
377
+ frameAt = 0;
378
+ if (!messageOpen) {
379
+ message.clear();
380
+ messageType = type;
381
+ } else if (messageType != type) {
382
+ fail("Invalid WebSocket message type");
383
+ return;
384
+ }
385
+ }
386
+ if (static_cast<std::size_t>(offset) != frameAt ||
387
+ received > maxReceive - message.size()) {
388
+ fail("Invalid or oversized WebSocket frame");
389
+ return;
390
+ }
391
+ frameAt += received;
392
+ message.append(buffer, received);
393
+ if (left == 0) {
394
+ messageOpen = (flags & CURLWS_CONT) != 0;
395
+ if (!messageOpen) {
396
+ if (messageType == 1) {
397
+ if (!utf8(message)) {
398
+ fail("Invalid WebSocket UTF-8 text");
399
+ return;
400
+ }
401
+ transport_message(handle, std::move(message));
402
+ }
403
+ message.clear();
404
+ }
405
+ }
406
+ }
407
+ // libcurl automatically answers pings; controls never alter text
408
+ // assembly.
409
+ } else if (rc != CURLE_AGAIN) {
410
+ if (closing.load())
411
+ transport_close(handle, 1000, "WebSocket closed locally");
412
+ else
413
+ fail("WebSocket receive failed");
414
+ return;
415
+ }
416
+ if (rc == CURLE_AGAIN) {
417
+ pollfd fd{
418
+ socket,
419
+ static_cast<short>(
420
+ POLLIN |
421
+ ((haveActive || (closing.load() && !closeSent)) ? POLLOUT : 0)),
422
+ 0};
423
+ ::poll(&fd, 1, 10);
424
+ }
425
+ }
426
+ } catch (...) {
427
+ fail("WebSocket transport failed");
428
+ }
429
+ }
430
+ } // namespace gea::host::websocket::curl_transport
431
+ namespace gea::host::websocket {
432
+ void platform_open(NativeWebSocketHandle h, const std::string &url,
433
+ const std::string &protocols, const std::string &headers) {
434
+ if (curl_transport::initialize() != CURLE_OK) {
435
+ transport_error(h, "WebSocket libcurl initialization failed");
436
+ transport_close(h, 1006, "WebSocket connection rejected");
437
+ return;
438
+ }
439
+ // URL parser is libcurl's; credentials and fragments are never admitted.
440
+ auto *parsed = curl_url();
441
+ char *scheme = nullptr, *host = nullptr, *part = nullptr;
442
+ bool valid = parsed;
443
+ if (valid)
444
+ valid = curl_url_set(parsed, CURLUPART_URL, url.c_str(),
445
+ CURLU_NON_SUPPORT_SCHEME) == CURLUE_OK;
446
+ if (valid)
447
+ valid = curl_url_get(parsed, CURLUPART_SCHEME, &scheme, 0) == CURLUE_OK &&
448
+ (std::strcmp(scheme, "ws") == 0 || std::strcmp(scheme, "wss") == 0);
449
+ if (valid)
450
+ valid =
451
+ curl_url_get(parsed, CURLUPART_HOST, &host, 0) == CURLUE_OK && *host;
452
+ for (auto field : {CURLUPART_USER, CURLUPART_PASSWORD, CURLUPART_FRAGMENT})
453
+ if (parsed && curl_url_get(parsed, field, &part, 0) == CURLUE_OK) {
454
+ valid = false;
455
+ curl_free(part);
456
+ part = nullptr;
457
+ }
458
+ if (parsed)
459
+ curl_url_cleanup(parsed);
460
+ curl_free(scheme);
461
+ curl_free(host);
462
+ valid = valid && url.find('\0') == std::string::npos &&
463
+ protocols.find_first_of("\r\n") == std::string::npos &&
464
+ protocols.find('\0') == std::string::npos;
465
+ std::size_t at = 0;
466
+ while (valid && at < headers.size()) {
467
+ auto end = headers.find("\r\n", at), colon = headers.find(':', at);
468
+ if (end == std::string::npos || colon == std::string::npos ||
469
+ colon >= end || colon == at) {
470
+ valid = false;
471
+ break;
472
+ }
473
+ const auto name = headers.substr(at, colon - at),
474
+ value = headers.substr(colon + 1, end - colon - 1);
475
+ valid =
476
+ name.find_first_not_of(
477
+ "!#$%&'*+-.^_`|~"
478
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") ==
479
+ std::string::npos &&
480
+ value.find_first_of("\r\n") == std::string::npos &&
481
+ value.find('\0') == std::string::npos;
482
+ at = end + 2;
483
+ }
484
+ if (!valid) {
485
+ transport_error(h, "Invalid WebSocket URL or headers");
486
+ transport_close(h, 1006, "WebSocket connection rejected");
487
+ return;
488
+ }
489
+ auto state = std::make_shared<curl_transport::State>(h);
490
+ state->url = url;
491
+ state->protocols = protocols;
492
+ state->headers = headers;
493
+ auto &r = curl_transport::registry();
494
+ std::lock_guard lock(r.mutex);
495
+ r.live.emplace(h, state);
496
+ try {
497
+ state->worker = std::thread([raw = state.get()] { raw->run(); });
498
+ } catch (...) {
499
+ r.live.erase(h);
500
+ transport_error(h, "WebSocket worker allocation failed");
501
+ transport_close(h, 1006, "WebSocket connection rejected");
502
+ }
503
+ }
504
+ std::size_t platform_buffered(NativeWebSocketHandle h) {
505
+ auto s = curl_transport::find(h);
506
+ if (!s)
507
+ return 0;
508
+ std::lock_guard lock(s->mutex);
509
+ return s->bytes;
510
+ }
511
+ void platform_send(NativeWebSocketHandle h, const std::string &text) {
512
+ auto s = curl_transport::find(h);
513
+ if (!s || !s->enqueue(text))
514
+ throw std::runtime_error("WebSocket is not open");
515
+ }
516
+ void platform_close(NativeWebSocketHandle h) {
517
+ auto s = curl_transport::find(h);
518
+ if (!s)
519
+ return;
520
+ s->closing = true;
521
+ transport_closing(h);
522
+ }
523
+ void platform_destroy(NativeWebSocketHandle h) {
524
+ auto &r = curl_transport::registry();
525
+ std::lock_guard lock(r.mutex);
526
+ auto i = r.live.find(h);
527
+ if (i == r.live.end())
528
+ return;
529
+ i->second->stop = true;
530
+ r.retired.push_back(std::move(i->second));
531
+ r.live.erase(i);
532
+ }
533
+ void platform_reap() {
534
+ std::vector<std::shared_ptr<curl_transport::State>> done;
535
+ auto &r = curl_transport::registry();
536
+ {
537
+ std::lock_guard lock(r.mutex);
538
+ for (auto i = r.live.begin(); i != r.live.end();)
539
+ if (i->second->finished.load(std::memory_order_acquire)) {
540
+ done.push_back(std::move(i->second));
541
+ i = r.live.erase(i);
542
+ } else
543
+ ++i;
544
+ for (auto i = r.retired.begin(); i != r.retired.end();)
545
+ if ((*i)->finished.load(std::memory_order_acquire)) {
546
+ done.push_back(std::move(*i));
547
+ i = r.retired.erase(i);
548
+ } else
549
+ ++i;
550
+ }
551
+ }
552
+ void platform_set_producer(NativeWebSocketHandle h, TextProducer producer) {
553
+ auto s = curl_transport::find(h);
554
+ if (!s)
555
+ throw std::invalid_argument("Closed WebSocket producer");
556
+ TextProducer retired;
557
+ {
558
+ std::lock_guard lock(s->mutex);
559
+ if (s->stop.load() || s->closing.load() || s->finished.load() ||
560
+ WebSocket(h).readyState() >= WebSocket::CLOSING)
561
+ throw std::invalid_argument("Closed WebSocket producer");
562
+ retired = std::move(s->producer);
563
+ s->producer = std::move(producer);
564
+ }
565
+ }
566
+ namespace curl_transport {
567
+ std::size_t transport_count_for_test() {
568
+ auto &r = registry();
569
+ std::lock_guard lock(r.mutex);
570
+ return r.live.size() + r.retired.size();
571
+ }
572
+ } // namespace curl_transport
573
+ } // namespace gea::host::websocket
574
+ #endif
package/host/worker.cpp CHANGED
@@ -31,6 +31,7 @@ thread_local std::shared_ptr<Context> activeContext;
31
31
  thread_local MessagePort globalPort;
32
32
  std::atomic<std::uint64_t> timerIds{1};
33
33
  std::atomic<bool> mainCreated{false};
34
+ std::atomic<bool> mainRetired{false};
34
35
  std::atomic<const char *> mainStage{"idle"};
35
36
  struct Registry {
36
37
  std::mutex mutex;
@@ -79,6 +80,7 @@ Context::~Context() = default;
79
80
  std::shared_ptr<Context> Context::main() {
80
81
  static auto context = std::shared_ptr<Context>(new Context(true, "main"));
81
82
  mainCreated.store(true, std::memory_order_release);
83
+ if (mainRetired.load(std::memory_order_acquire)) context->stop();
82
84
  return context;
83
85
  }
84
86
  void Context::runMainPending() {
@@ -113,21 +115,36 @@ void Context::prioritizeAudio() {
113
115
  bool Context::post(std::function<void()> callback, std::size_t bytes) {
114
116
  if (!callback) return false;
115
117
  std::lock_guard lock(state_->mutex);
116
- if (state_->stopping || state_->tasks.size() >= maxQueueEntries || bytes > maxQueueBytes - state_->bytes)
118
+ if (state_->stopping || (state_->main && mainRetired.load(std::memory_order_acquire)) || state_->tasks.size() >= maxQueueEntries || bytes > maxQueueBytes - state_->bytes)
117
119
  return false;
118
120
  state_->tasks.push_back({std::move(callback), bytes});
119
121
  state_->bytes += bytes;
120
122
  state_->wake.notify_one();
121
123
  return true;
122
124
  }
123
- void Context::setPump(std::function<void()> pump) { state_->pump = std::move(pump); }
125
+ void Context::setPump(std::function<void()> pump) {
126
+ if (!state_->main) { state_->pump = std::move(pump); return; }
127
+ std::function<void()> retired;
128
+ {
129
+ std::lock_guard lock(state_->mutex);
130
+ if (mainRetired.load(std::memory_order_acquire)) return;
131
+ retired.swap(state_->pump);
132
+ state_->pump.swap(pump);
133
+ }
134
+ }
124
135
  void Context::setErrorHandler(std::function<void(const std::string &)> handler) {
125
- std::lock_guard lock(state_->mutex);
126
- state_->error = std::move(handler);
136
+ if (!state_->main) { std::lock_guard lock(state_->mutex); state_->error = std::move(handler); return; }
137
+ std::function<void(const std::string &)> retired;
138
+ {
139
+ std::lock_guard lock(state_->mutex);
140
+ if (mainRetired.load(std::memory_order_acquire)) return;
141
+ retired.swap(state_->error);
142
+ state_->error.swap(handler);
143
+ }
127
144
  }
128
145
  void Context::addCleanup(std::function<void()> cleanup) {
129
146
  std::lock_guard lock(state_->mutex);
130
- if (state_->stopping) throw std::runtime_error("Worker context is closed");
147
+ if (state_->stopping || (state_->main && mainRetired.load(std::memory_order_acquire))) throw std::runtime_error("Worker context is closed");
131
148
  state_->cleanups.push_back(std::move(cleanup));
132
149
  }
133
150
  void Context::stop() {
@@ -143,7 +160,7 @@ double Context::schedule(std::function<void()> callback, double delayMs, bool re
143
160
  std::max(repeat ? 1.0 : 0.0, normalized)));
144
161
  const double id = static_cast<double>(timerIds.fetch_add(1));
145
162
  std::lock_guard lock(state_->mutex);
146
- if (state_->stopping) return 0;
163
+ if (state_->stopping || (state_->main && mainRetired.load(std::memory_order_acquire))) return 0;
147
164
  state_->timers.push_back({id, std::move(callback), Clock::now() + delay, delay, repeat});
148
165
  state_->wake.notify_one();
149
166
  return id;
@@ -192,7 +209,13 @@ void Context::runPending(double budgetMs) {
192
209
  stage("invoke_callback");
193
210
  if (callback) callback();
194
211
  stage("pump_microtasks");
195
- if (state_->pump) state_->pump();
212
+ if (state_->main) {
213
+ // A pump may itself retire the realm: keep its active callable alive
214
+ // locally, and never run it after a task has closed main admission.
215
+ std::function<void()> pump;
216
+ { std::lock_guard lock(state_->mutex); if (!state_->stopping && !mainRetired.load(std::memory_order_acquire)) pump = state_->pump; }
217
+ if (pump) pump();
218
+ } else if (state_->pump) state_->pump();
196
219
  } catch (const std::exception &error) {
197
220
  std::function<void(const std::string &)> report;
198
221
  { std::lock_guard lock(state_->mutex); report = state_->error; }
@@ -274,6 +297,34 @@ void Context::finish() {
274
297
  globalPort.close();
275
298
  globalPort = {};
276
299
  }
300
+ void retireMainContext() {
301
+ if (mainRetired.exchange(true, std::memory_order_acq_rel)) return;
302
+ if (!mainCreated.load(std::memory_order_acquire)) return;
303
+ auto context = Context::main();
304
+ std::deque<Context::State::Task> tasks;
305
+ std::vector<Context::State::Timer> timers;
306
+ std::vector<std::function<void()>> cleanups;
307
+ std::function<void()> pump;
308
+ std::function<void(const std::string &)> error;
309
+ {
310
+ std::lock_guard lock(context->state_->mutex);
311
+ context->state_->stopping.store(true);
312
+ tasks.swap(context->state_->tasks);
313
+ timers.swap(context->state_->timers);
314
+ cleanups.swap(context->state_->cleanups);
315
+ pump.swap(context->state_->pump);
316
+ error.swap(context->state_->error);
317
+ context->state_->bytes = 0;
318
+ }
319
+ // Native captured-owner destructors may reenter any admission API. All are
320
+ // closed before captures are released, with no Context lock held here.
321
+ tasks.clear(); timers.clear(); pump = {}; error = {};
322
+ for (auto it = cleanups.rbegin(); it != cleanups.rend(); ++it) {
323
+ try { if (*it) (*it)(); }
324
+ catch (...) { std::fputs("[Worker:main] process cleanup failed; continuing retirement\n", stderr); }
325
+ }
326
+ }
327
+
277
328
  void Context::start(std::function<void()> entry) {
278
329
  if (state_->main || state_->started.exchange(true)) throw std::runtime_error("Worker already started");
279
330
  auto context = shared_from_this();