@geastack/host 0.1.17 → 0.1.19

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 CHANGED
@@ -11,9 +11,11 @@
11
11
  #include <cstdint>
12
12
  #include <cstdio>
13
13
  #include <cstring>
14
+ #include <mutex>
14
15
  #include <string>
15
16
  #include <vector>
16
17
 
18
+ #include "esp_heap_caps.h"
17
19
  #include "esp_log.h"
18
20
  #include "esp_timer.h"
19
21
  #include "freertos/FreeRTOS.h"
@@ -189,8 +191,7 @@ public:
189
191
  #if GEA_EMBEDDED_AUDIO_DISABLED
190
192
  return 0;
191
193
  #else
192
- ensureTask();
193
- if (!audioTask_ || !toneQueue_) return 0;
194
+ if (!ensureTask()) return 0;
194
195
  // Half-duplex capture can close the speaker between replies. Revalidate
195
196
  // its hardware state when the first playback source attaches again.
196
197
  if (!streams_.active()) driverOpen_.store(false, std::memory_order_release);
@@ -522,7 +523,12 @@ private:
522
523
  }
523
524
  }
524
525
 
525
- void ensureTask() {
526
+ bool ensureTask() {
527
+ // Volume and exclusive-playback controls also use this engine, but do not
528
+ // need its tone/stream worker. Claim that worker's stack only on first use.
529
+ // Serialize callers so a failed start can retry without leaking a stack or
530
+ // starting two tasks against the same static TCB.
531
+ std::lock_guard<std::mutex> lock(taskStartMutex_);
526
532
  #if GEA_AUDIO_DEBUG_TIMING
527
533
  const int64_t totalStartUs = esp_timer_get_time();
528
534
  int64_t queueUs = 0;
@@ -543,7 +549,7 @@ private:
543
549
  #endif
544
550
  if (!toneQueue_) {
545
551
  ESP_LOGE(kTag, "Tone queue creation failed");
546
- return;
552
+ return false;
547
553
  }
548
554
  }
549
555
 
@@ -552,6 +558,17 @@ private:
552
558
  const int64_t taskStartUs = esp_timer_get_time();
553
559
  attemptedTask = true;
554
560
  #endif
561
+ // OutputDriver::open may access flash/NVS, so this stack must remain
562
+ // internal even when the application places its UI stacks in PSRAM.
563
+ audioTaskStack_ = static_cast<StackType_t *>(
564
+ heap_caps_malloc(kTaskStackBytes, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
565
+ if (!audioTaskStack_) {
566
+ if (!audioTaskFailureLogged_) {
567
+ audioTaskFailureLogged_ = true;
568
+ ESP_LOGE(kTag, "Audio task stack allocation failed");
569
+ }
570
+ return false;
571
+ }
555
572
  audioTask_ = xTaskCreateStatic(
556
573
  &AudioEngine::audioTaskEntry,
557
574
  "gea_audio",
@@ -565,6 +582,8 @@ private:
565
582
  startedTask = audioTask_ != nullptr;
566
583
  #endif
567
584
  if (!audioTask_) {
585
+ heap_caps_free(audioTaskStack_);
586
+ audioTaskStack_ = nullptr;
568
587
  if (!audioTaskFailureLogged_) {
569
588
  audioTaskFailureLogged_ = true;
570
589
  ESP_LOGE(kTag, "Audio task creation failed");
@@ -588,6 +607,7 @@ private:
588
607
  startedTask ? 1 : 0);
589
608
  }
590
609
  #endif
610
+ return audioTask_ != nullptr;
591
611
  }
592
612
 
593
613
  void submitTone(const Tone &tone) {
@@ -596,8 +616,7 @@ private:
596
616
  return;
597
617
  #else
598
618
  if (exclusivePlayback_.load(std::memory_order_acquire)) return;
599
- ensureTask();
600
- if (!toneQueue_) return;
619
+ if (!ensureTask()) return;
601
620
 
602
621
  if (xQueueSend(toneQueue_, &tone, 0) != pdPASS) {
603
622
  const int64_t nowUs = esp_timer_get_time();
@@ -617,6 +636,7 @@ private:
617
636
 
618
637
  QueueHandle_t toneQueue_ = nullptr;
619
638
  audio::PcmStreamMixer streams_;
639
+ std::mutex taskStartMutex_;
620
640
  TaskHandle_t audioTask_ = nullptr;
621
641
  OscillatorState oscillators_[kMaxOscillators]{};
622
642
  ActiveTone activeTones_[kMaxActiveTones]{};
@@ -625,7 +645,7 @@ private:
625
645
  StaticQueue_t toneQueueStorage_{};
626
646
  std::uint8_t toneQueueBuffer_[kQueueDepth * sizeof(Tone)]{};
627
647
  StaticTask_t audioTaskStorage_{};
628
- StackType_t audioTaskStack_[kTaskStackBytes]{};
648
+ StackType_t *audioTaskStack_ = nullptr;
629
649
  std::atomic<bool> exclusivePlayback_{false};
630
650
  std::atomic<bool> flushPending_{false};
631
651
  std::atomic<bool> driverOpen_{false};
package/host/image.cpp CHANGED
@@ -26,6 +26,9 @@
26
26
  #include <cstdio>
27
27
  #include <cstring>
28
28
  #include <sys/stat.h>
29
+ #if defined(_WIN32)
30
+ #include <direct.h> // _mkdir: the Windows CRT has no POSIX mkdir(path, mode)
31
+ #endif
29
32
  #include <unordered_map>
30
33
  #include <vector>
31
34
 
@@ -64,12 +67,22 @@ bool ensureMounted() {
64
67
  }
65
68
  } // namespace gea::platform::storage
66
69
 
70
+ // Optional hooks a generated program defines weakly. A COFF linker cannot pair
71
+ // a weak reference with a weak definition (each names its own default), so a
72
+ // target that links a default for every such hook (lld-link /alternatename)
73
+ // sets GEA_LINKED_HOOK_DEFAULTS and the references become ordinary ones.
74
+ #if defined(GEA_LINKED_HOOK_DEFAULTS) && GEA_LINKED_HOOK_DEFAULTS
75
+ #define GEA_PROGRAM_HOOK
76
+ #else
77
+ #define GEA_PROGRAM_HOOK __attribute__((weak))
78
+ #endif
79
+
67
80
  namespace gea::host {
68
81
 
69
82
  extern "C" bool gea_embedded_asset_lookup(const char *path,
70
83
  const unsigned char **data,
71
84
  unsigned long *length)
72
- __attribute__((weak));
85
+ GEA_PROGRAM_HOOK;
73
86
 
74
87
  namespace {
75
88
 
@@ -79,6 +92,22 @@ gea::framework::graphics::ImageStore &store() {
79
92
 
80
93
  int integer(double value) { return static_cast<int>(value); }
81
94
 
95
+ // An absolute filesystem path: `/...`, and on Windows also a drive path
96
+ // (`C:/...`, `C:\...`) or a UNC path (`\\server\...`), which is how an
97
+ // absolute path is spelled there.
98
+ bool isAbsoluteFilePath(const char *path) {
99
+ if (path[0] == '/')
100
+ return true;
101
+ #if defined(_WIN32)
102
+ if (path[0] == '\\' && path[1] == '\\')
103
+ return true;
104
+ const bool drive = (path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z');
105
+ return drive && path[1] == ':' && (path[2] == '/' || path[2] == '\\');
106
+ #else
107
+ return false;
108
+ #endif
109
+ }
110
+
82
111
  // mkdir -p of the parent directories in `path` (FAT/VFS); existing dirs are
83
112
  // fine.
84
113
  void makeParentDirs(const std::string &path) {
@@ -86,8 +115,13 @@ void makeParentDirs(const std::string &path) {
86
115
  if (path[i] != '/')
87
116
  continue;
88
117
  const std::string dir = path.substr(0, i);
89
- if (!dir.empty())
118
+ if (!dir.empty()) {
119
+ #if defined(_WIN32)
120
+ ::_mkdir(dir.c_str());
121
+ #else
90
122
  ::mkdir(dir.c_str(), 0777);
123
+ #endif
124
+ }
91
125
  }
92
126
  }
93
127
 
@@ -190,7 +224,7 @@ double ImageService::loadAssetPath(const char *path) const {
190
224
  // Fallback: an absolute filesystem path (e.g. an EPUB cover extracted to the
191
225
  // SD card). Lets `<img src="/sdcard/...">` show runtime images through the
192
226
  // framework's own decode/render path instead of only bundled assets.
193
- if (path[0] == '/')
227
+ if (isAbsoluteFilePath(path))
194
228
  return loadFile(std::string(path));
195
229
  return -1.0;
196
230
  }
@@ -416,7 +450,7 @@ extern "C" double gea_host_image_acquire_asset_path(const char *path, bool *owne
416
450
  if (gea::host::gea_embedded_asset_lookup(path, &data, &length))
417
451
  return gea::host::image.loadBytesPtr(data, length);
418
452
  }
419
- if (path[0] != '/') return -1.0;
453
+ if (!gea::host::isAbsoluteFilePath(path)) return -1.0;
420
454
  const int id = static_cast<int>(gea::host::image.loadFile(path));
421
455
  auto &images = gea::framework::graphics::ImageStore::instance();
422
456
  if (id >= 0 && images.retain(id)) {
package/host/rtc_esp.cpp CHANGED
@@ -852,7 +852,12 @@ EspPeerState *ensurePeer(EspPeerState* state, bool answer = false) {
852
852
  // audio on CPU1: moving both overloaded CPU0 and delayed microphone encoding.
853
853
  // On CPU0 transport must stay below capture/send (24/5), above UI (3).
854
854
  // Other peers retain their established scheduling.
855
+ #if GEA_RTC_HAS_VIDEO
855
856
  const bool separateVideoTransport = state->vp8_video && state->packet_wake;
857
+ #else
858
+ // A build without video has no VP8 transport to separate.
859
+ const bool separateVideoTransport = false;
860
+ #endif
856
861
  if (xTaskCreatePinnedToCoreWithCaps(main_loop_trampoline, "gea_rtc_loop", kPeerStackBytes, state,
857
862
  separateVideoTransport ? 4 : 7, &state->main_loop_task,
858
863
  separateVideoTransport ? 0 : 1,
package/host/timers.cpp CHANGED
@@ -24,6 +24,20 @@
24
24
  namespace gea::host {
25
25
 
26
26
  namespace {
27
+ // Reset releases arbitrary native captures. Those destructors must run without
28
+ // a scheduler lock and cannot repopulate either queue being retired.
29
+ std::atomic<bool> scheduledCallbacksRetired{false};
30
+ thread_local unsigned callbackResetDepth = 0;
31
+ struct CallbackResetScope {
32
+ CallbackResetScope() { ++callbackResetDepth; }
33
+ ~CallbackResetScope() { --callbackResetDepth; }
34
+ CallbackResetScope(const CallbackResetScope &) = delete;
35
+ CallbackResetScope &operator=(const CallbackResetScope &) = delete;
36
+ };
37
+ bool callbacksRejected()
38
+ {
39
+ return callbackResetDepth != 0 || scheduledCallbacksRetired.load(std::memory_order_acquire);
40
+ }
27
41
 
28
42
  std::atomic<const char *> callbackStage{"idle"};
29
43
 
@@ -82,7 +96,7 @@ public:
82
96
 
83
97
  double schedule(TimerCallback callback, double delayMs, bool interval)
84
98
  {
85
- if (!callback) return 0;
99
+ if (!callback || callbacksRejected()) return 0;
86
100
  auto timer = std::make_shared<ScheduledTimer>();
87
101
  timer->id = nextTimerId();
88
102
  timer->callback = std::move(callback);
@@ -91,6 +105,7 @@ public:
91
105
  timer->interval = interval;
92
106
  if (timer->interval && timer->delayMs <= 0) timer->delayMs = 1;
93
107
  std::lock_guard<std::mutex> lock(mutex_);
108
+ if (callbacksRejected()) return 0;
94
109
  timers_.push_back(timer);
95
110
  return timer->id;
96
111
  }
@@ -124,6 +139,7 @@ public:
124
139
  }
125
140
 
126
141
  for (auto &timer : due) {
142
+ if (scheduledCallbacksRetired.load(std::memory_order_acquire)) break;
127
143
  if (timer->active && timer->callback) timer->callback();
128
144
 
129
145
  std::lock_guard<std::mutex> lock(mutex_);
@@ -141,11 +157,14 @@ public:
141
157
 
142
158
  void reset()
143
159
  {
144
- std::lock_guard<std::mutex> lock(mutex_);
145
- for (auto &timer : timers_) {
146
- if (timer) timer->active = false;
160
+ std::vector<std::shared_ptr<ScheduledTimer>> retired;
161
+ {
162
+ std::lock_guard<std::mutex> lock(mutex_);
163
+ for (auto &timer : timers_) {
164
+ if (timer) timer->active = false;
165
+ }
166
+ retired.swap(timers_);
147
167
  }
148
- timers_.clear();
149
168
  }
150
169
 
151
170
  private:
@@ -157,10 +176,16 @@ private:
157
176
 
158
177
  void compactInactiveTimers()
159
178
  {
160
- std::lock_guard<std::mutex> lock(mutex_);
161
- timers_.erase(
162
- std::remove_if(timers_.begin(), timers_.end(), [](const auto &timer) { return !timer || (!timer->active && !timer->running); }),
163
- timers_.end());
179
+ std::vector<std::shared_ptr<ScheduledTimer>> retired;
180
+ {
181
+ std::lock_guard<std::mutex> lock(mutex_);
182
+ for (const auto &timer : timers_) {
183
+ if (timer && !timer->active && !timer->running) retired.push_back(timer);
184
+ }
185
+ timers_.erase(
186
+ std::remove_if(timers_.begin(), timers_.end(), [](const auto &timer) { return !timer || (!timer->active && !timer->running); }),
187
+ timers_.end());
188
+ }
164
189
  }
165
190
 
166
191
  std::mutex mutex_;
@@ -181,7 +206,7 @@ public:
181
206
  #if GEA_EMBEDDED_RAF_PERF
182
207
  perfStats_.requestCount++;
183
208
  #endif
184
- if (!callback) {
209
+ if (!callback || callbacksRejected()) {
185
210
  #if GEA_EMBEDDED_RAF_PERF
186
211
  perfStats_.droppedCount++;
187
212
  #endif
@@ -212,6 +237,7 @@ public:
212
237
  #endif
213
238
 
214
239
  for (int i = 0; i < count; i++) {
240
+ if (scheduledCallbacksRetired.load(std::memory_order_acquire)) break;
215
241
  if (active[i]) {
216
242
  [[maybe_unused]] const std::int64_t callbackStartUs = rafPerfNowUs();
217
243
  active[i](timestampMs);
@@ -232,7 +258,8 @@ public:
232
258
 
233
259
  void reset()
234
260
  {
235
- pending_.clear();
261
+ std::vector<AnimationFrameCallback> retired;
262
+ retired.swap(pending_);
236
263
  }
237
264
 
238
265
  void resetPerfStats()
@@ -279,12 +306,14 @@ private:
279
306
 
280
307
  double setTimeout(TimerCallback callback, double delayMs)
281
308
  {
309
+ if (callbacksRejected()) return 0;
282
310
  if (workers::Context::isWorkerCurrent()) return workers::Context::current()->schedule(std::move(callback), delayMs, false);
283
311
  return TimerScheduler::instance().schedule(std::move(callback), delayMs, false);
284
312
  }
285
313
 
286
314
  double setInterval(TimerCallback callback, double delayMs)
287
315
  {
316
+ if (callbacksRejected()) return 0;
288
317
  if (workers::Context::isWorkerCurrent()) return workers::Context::current()->schedule(std::move(callback), delayMs, true);
289
318
  return TimerScheduler::instance().schedule(std::move(callback), delayMs, true);
290
319
  }
@@ -303,6 +332,7 @@ void clearInterval(double id)
303
332
 
304
333
  void resetScheduledTimers()
305
334
  {
335
+ CallbackResetScope retirement;
306
336
  TimerScheduler::instance().reset();
307
337
  }
308
338
 
@@ -313,10 +343,13 @@ double requestAnimationFrame(AnimationFrameCallback callback)
313
343
 
314
344
  void runAnimationFrameCallbacks(AnimationFrameTimestamp timestampMs)
315
345
  {
346
+ if (callbacksRejected()) return;
316
347
  callbackStage.store("worker_callbacks", std::memory_order_relaxed);
317
348
  workers::Context::runMainPending();
349
+ if (scheduledCallbacksRetired.load(std::memory_order_acquire)) { callbackStage.store("idle", std::memory_order_relaxed); return; }
318
350
  callbackStage.store("timer_callbacks", std::memory_order_relaxed);
319
351
  TimerScheduler::instance().run(static_cast<double>(timestampMs));
352
+ if (scheduledCallbacksRetired.load(std::memory_order_acquire)) { callbackStage.store("idle", std::memory_order_relaxed); return; }
320
353
  callbackStage.store("animation_callbacks", std::memory_order_relaxed);
321
354
  AnimationFrameQueue::instance().run(timestampMs);
322
355
  callbackStage.store("idle", std::memory_order_relaxed);
@@ -329,9 +362,17 @@ const char *animationFrameCallbackStage()
329
362
 
330
363
  void resetAnimationFrameCallbacks()
331
364
  {
365
+ CallbackResetScope retirement;
332
366
  AnimationFrameQueue::instance().reset();
333
367
  }
334
368
 
369
+ void retireScheduledCallbacks()
370
+ {
371
+ scheduledCallbacksRetired.store(true, std::memory_order_release);
372
+ resetScheduledTimers();
373
+ resetAnimationFrameCallbacks();
374
+ }
375
+
335
376
  void animationFramePerfStatsReset()
336
377
  {
337
378
  AnimationFrameQueue::instance().resetPerfStats();
@@ -2,10 +2,12 @@
2
2
  #include "host/websocket.h"
3
3
  #include "host/worker.h"
4
4
  #include "host/websocket_message.h"
5
+ #include "host/websocket_platform.h"
5
6
 
6
7
  #include <algorithm>
7
8
  #include <atomic>
8
9
  #include <chrono>
10
+ #include <cstdio>
9
11
  #include <stdexcept>
10
12
  #include <functional>
11
13
  #include <deque>
@@ -81,7 +83,33 @@ std::unordered_map<NativeWebSocketHandle, CallbackTable> &callbackTable() {
81
83
  static Table mainTable;
82
84
  static std::unordered_map<workers::Context *, std::weak_ptr<Table>> tables;
83
85
  const auto context = workers::Context::current();
84
- if (context->isMain()) return mainTable;
86
+ if (context->isMain()) {
87
+ // One process cleanup per main owner, rather than one accumulating entry
88
+ // per reconnect. Admission is closed before Context invokes this cleanup.
89
+ static bool cleanupInstalled = false;
90
+ if (!cleanupInstalled) {
91
+ context->addCleanup([key = context.get()] {
92
+ for (;;) {
93
+ NativeWebSocketHandle handle = 0;
94
+ {
95
+ std::lock_guard lock(ownerMutex);
96
+ for (const auto &entry : owners) {
97
+ auto owner = entry.second.lock();
98
+ if (owner && owner.get() == key) { handle = entry.first; break; }
99
+ }
100
+ if (handle) owners.erase(handle);
101
+ }
102
+ if (!handle) break;
103
+ try { destroy_handle(handle); }
104
+ catch (...) { std::fputs("WebSocket main cleanup failed; continuing retirement\n", stderr); }
105
+ }
106
+ Table retiredCallbacks;
107
+ retiredCallbacks.swap(mainTable);
108
+ });
109
+ cleanupInstalled = true;
110
+ }
111
+ return mainTable;
112
+ }
85
113
  std::lock_guard lock(mutex);
86
114
  auto table = tables[context.get()].lock();
87
115
  if (!table) {
@@ -96,6 +124,28 @@ std::unordered_map<NativeWebSocketHandle, CallbackTable> &callbackTable() {
96
124
  return *table;
97
125
  }
98
126
 
127
+ bool callbackAdmissionOpen(NativeWebSocketHandle handle) {
128
+ std::shared_ptr<workers::Context> owner;
129
+ { std::lock_guard lock(ownerMutex); auto entry = owners.find(handle); if (entry != owners.end()) owner = entry->second.lock(); }
130
+ if (!owner || owner->stopped()) return false;
131
+ std::lock_guard lock(instancesMutex());
132
+ return instances().find(handle) != instances().end();
133
+ }
134
+
135
+ static CallbackTable detachCallbacks(NativeWebSocketHandle handle) {
136
+ CallbackTable callbacks;
137
+ auto &table = callbackTable();
138
+ auto entry = table.find(handle);
139
+ if (entry != table.end()) {
140
+ callbacks.on_open.swap(entry->second.on_open);
141
+ callbacks.on_message.swap(entry->second.on_message);
142
+ callbacks.on_close.swap(entry->second.on_close);
143
+ callbacks.on_error.swap(entry->second.on_error);
144
+ table.erase(entry);
145
+ }
146
+ return callbacks;
147
+ }
148
+
99
149
  #if defined(ESP_PLATFORM) && !defined(GEA_EMBEDDED_WIFI_DISABLED)
100
150
  void platform_open(NativeWebSocketHandle, const std::string &, const std::string &, const std::string &);
101
151
  std::size_t platform_buffered(NativeWebSocketHandle);
@@ -114,6 +164,66 @@ __attribute__((weak)) void platform_reap() {}
114
164
  __attribute__((weak)) void platform_set_producer(NativeWebSocketHandle, TextProducer) {}
115
165
  #endif
116
166
 
167
+ bool transport_open(NativeWebSocketHandle handle) {
168
+ {
169
+ std::lock_guard lock(instancesMutex());
170
+ auto it = instances().find(handle);
171
+ if (it == instances().end() || it->second.readyState != WebSocket::CONNECTING) return false;
172
+ it->second.readyState = WebSocket::OPEN;
173
+ }
174
+ enqueue(PendingEvent{handle, EventKind::Open, {}, 0});
175
+ return true;
176
+ }
177
+
178
+ void transport_message(NativeWebSocketHandle handle, std::string text) {
179
+ TextConsumer consumer;
180
+ {
181
+ std::lock_guard lock(instancesMutex());
182
+ auto it = instances().find(handle);
183
+ if (it == instances().end() || it->second.readyState != WebSocket::OPEN) return;
184
+ consumer = it->second.consumer;
185
+ }
186
+ if (text.size() > 1024 * 1024) {
187
+ transport_error(handle, "WebSocket message exceeds 1 MiB");
188
+ platform_close(handle);
189
+ return;
190
+ }
191
+ try {
192
+ if (!consumer || !consumer(text))
193
+ enqueue(PendingEvent{handle, EventKind::Message, std::move(text), 0});
194
+ } catch (const std::exception &error) {
195
+ transport_error(handle, error.what());
196
+ } catch (...) {
197
+ transport_error(handle, "WebSocket native consumer failed");
198
+ }
199
+ }
200
+
201
+ void transport_closing(NativeWebSocketHandle handle) {
202
+ std::lock_guard lock(instancesMutex());
203
+ auto it = instances().find(handle);
204
+ if (it != instances().end() && it->second.readyState != WebSocket::CLOSED)
205
+ it->second.readyState = WebSocket::CLOSING;
206
+ }
207
+
208
+ void transport_close(NativeWebSocketHandle handle, int code, const std::string &reason) {
209
+ TextConsumer retiredConsumer;
210
+ {
211
+ std::lock_guard lock(instancesMutex());
212
+ auto it = instances().find(handle);
213
+ if (it == instances().end() || it->second.readyState == WebSocket::CLOSED) return;
214
+ it->second.readyState = WebSocket::CLOSED;
215
+ retiredConsumer = std::move(it->second.consumer);
216
+ it->second.messages = TextMessageAssembler{};
217
+ }
218
+ // Release native captures outside the instance lock, before the close callback.
219
+ retiredConsumer = {};
220
+ enqueue(PendingEvent{handle, EventKind::Close, reason, code});
221
+ }
222
+
223
+ void transport_error(NativeWebSocketHandle handle, const std::string &reason) {
224
+ enqueue(PendingEvent{handle, EventKind::Error, reason, 0});
225
+ }
226
+
117
227
  void setTextProducer(NativeWebSocketHandle handle, TextProducer producer) {
118
228
  // The producer runs exclusively on the native socket sender, whose priority
119
229
  // platform_set_producer raises for audio. Promoting the caller's realm here
@@ -122,32 +232,50 @@ void setTextProducer(NativeWebSocketHandle handle, TextProducer producer) {
122
232
  }
123
233
 
124
234
  void setTextConsumer(NativeWebSocketHandle handle, TextConsumer consumer) {
125
- std::lock_guard lock(instancesMutex());
126
- auto it = instances().find(handle);
127
- if (it == instances().end()) throw std::invalid_argument("Closed WebSocket native sink");
128
- it->second.consumer = std::move(consumer);
235
+ TextConsumer retired;
236
+ {
237
+ std::lock_guard lock(instancesMutex());
238
+ auto it = instances().find(handle);
239
+ if (it == instances().end() || it->second.readyState == WebSocket::CLOSED)
240
+ throw std::invalid_argument("Closed WebSocket native sink");
241
+ retired = std::move(it->second.consumer);
242
+ it->second.consumer = std::move(consumer);
243
+ }
244
+ // Native captured-object destruction may call back into the facade.
129
245
  }
130
246
 
131
247
  NativeWebSocketHandle create_handle(const std::string &url, const std::string &protocols, const std::string &headers) {
248
+ auto owner = workers::Context::current();
249
+ if (owner->stopped()) throw std::runtime_error("WebSocket owner context is closed");
250
+ (void)callbackTable(); // Admit owner cleanup before allocating facade state.
132
251
  auto handle = nextHandle()++;
133
252
  {
134
253
  std::lock_guard<std::mutex> lock(instancesMutex());
135
254
  instances()[handle] = WebSocketInstance{url, WebSocket::CONNECTING, {}};
136
255
  }
137
- auto owner = workers::Context::current();
138
- (void)callbackTable();
139
256
  { std::lock_guard lock(ownerMutex); owners[handle] = owner; }
140
- if (!owner->isMain()) owner->addCleanup([handle] { destroy_handle(handle); });
141
- platform_open(handle, url, protocols, headers);
257
+ try {
258
+ if (!owner->isMain()) owner->addCleanup([handle] { destroy_handle(handle); });
259
+ platform_open(handle, url, protocols, headers);
260
+ } catch (...) { destroy_handle(handle); throw; }
142
261
  return handle;
143
262
  }
144
263
 
145
264
  void destroy_handle(NativeWebSocketHandle handle) {
146
- platform_destroy(handle);
265
+ WebSocketInstance retired;
266
+ CallbackTable callbacks;
267
+ {
268
+ std::lock_guard<std::mutex> lock(instancesMutex());
269
+ auto it = instances().find(handle);
270
+ if (it == instances().end()) return;
271
+ retired = std::move(it->second);
272
+ instances().erase(it);
273
+ }
147
274
  { std::lock_guard lock(ownerMutex); owners.erase(handle); }
148
- std::lock_guard<std::mutex> lock(instancesMutex());
149
- instances().erase(handle);
150
- callbackTable().erase(handle);
275
+ callbacks = detachCallbacks(handle);
276
+ // Ownership is absent before transport/captured-owner teardown can reenter.
277
+ // All callbacks are released outside table erasure and instance/owner locks.
278
+ platform_destroy(handle);
151
279
  }
152
280
 
153
281
  void runCallbacks() {
@@ -165,17 +293,52 @@ void test_inject_close(NativeWebSocketHandle handle, int code, const std::string
165
293
  enqueue(PendingEvent{handle, EventKind::Close, reason, code});
166
294
  }
167
295
 
296
+ void set_open_callback(NativeWebSocketHandle handle, std::function<void()> cb) {
297
+ if (!callbackAdmissionOpen(handle)) return;
298
+ std::function<void()> retired;
299
+ auto &slot = callbackTable()[handle].on_open;
300
+ retired.swap(slot);
301
+ slot.swap(cb);
302
+ // No table references may be used after captured-owner destruction reenters.
303
+ }
168
304
  void test_set_open_callback(NativeWebSocketHandle handle, std::function<void()> cb) {
169
- callbackTable()[handle].on_open = std::move(cb);
305
+ set_open_callback(handle, std::move(cb));
306
+ }
307
+
308
+ void set_message_callback(NativeWebSocketHandle handle, std::function<void(const std::string &)> cb) {
309
+ if (!callbackAdmissionOpen(handle)) return;
310
+ std::function<void(const std::string &)> retired;
311
+ auto &slot = callbackTable()[handle].on_message;
312
+ retired.swap(slot);
313
+ slot.swap(cb);
314
+ // No table references may be used after captured-owner destruction reenters.
170
315
  }
171
316
  void test_set_message_callback(NativeWebSocketHandle handle, std::function<void(const std::string &)> cb) {
172
- callbackTable()[handle].on_message = std::move(cb);
317
+ set_message_callback(handle, std::move(cb));
318
+ }
319
+
320
+ void set_close_callback(NativeWebSocketHandle handle, std::function<void(int, const std::string &)> cb) {
321
+ if (!callbackAdmissionOpen(handle)) return;
322
+ std::function<void(int, const std::string &)> retired;
323
+ auto &slot = callbackTable()[handle].on_close;
324
+ retired.swap(slot);
325
+ slot.swap(cb);
326
+ // No table references may be used after captured-owner destruction reenters.
173
327
  }
174
328
  void test_set_close_callback(NativeWebSocketHandle handle, std::function<void(int, const std::string &)> cb) {
175
- callbackTable()[handle].on_close = std::move(cb);
329
+ set_close_callback(handle, std::move(cb));
330
+ }
331
+
332
+ void set_error_callback(NativeWebSocketHandle handle, std::function<void(const std::string &)> cb) {
333
+ if (!callbackAdmissionOpen(handle)) return;
334
+ std::function<void(const std::string &)> retired;
335
+ auto &slot = callbackTable()[handle].on_error;
336
+ retired.swap(slot);
337
+ slot.swap(cb);
338
+ // No table references may be used after captured-owner destruction reenters.
176
339
  }
177
340
  void test_set_error_callback(NativeWebSocketHandle handle, std::function<void(const std::string &)> cb) {
178
- callbackTable()[handle].on_error = std::move(cb);
341
+ set_error_callback(handle, std::move(cb));
179
342
  }
180
343
 
181
344
  } // namespace websocket
@@ -197,10 +360,12 @@ void dispatch(PendingEvent ev) {
197
360
  break;
198
361
  }
199
362
  case EventKind::Close: {
363
+ // Detach every script capture before transport teardown can reenter or
364
+ // erase this entry. No map iterator survives an external call.
365
+ auto callbacks = websocket::detachCallbacks(ev.handle);
200
366
  websocket::platform_close(ev.handle);
201
- const auto callback = std::move(it->second.on_close);
202
- table.erase(it);
203
- if (callback) callback(ev.code, ev.text);
367
+ if (!workers::Context::current()->stopped() && callbacks.on_close)
368
+ callbacks.on_close(ev.code, ev.text);
204
369
  break;
205
370
  }
206
371
  case EventKind::Error: {