@webrtc-node/webrtc 0.2.2 → 0.2.3

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.
@@ -2,6 +2,8 @@
2
2
  #include <rtc/rtc.hpp>
3
3
 
4
4
  #include "certificate.hpp"
5
+ #include "send_queue.hpp"
6
+ #include "teardown_tasks.hpp"
5
7
 
6
8
  #include <algorithm>
7
9
  #include <atomic>
@@ -31,6 +33,71 @@ struct ChannelBinding;
31
33
  struct EventDispatcher;
32
34
  struct IceUdpMuxBinding;
33
35
  struct PeerBinding;
36
+ struct EnvironmentState;
37
+ void CleanupEnvironment(EnvironmentState *state);
38
+
39
+ using webrtc_node::SendQueue;
40
+ using webrtc_node::TeardownTasks;
41
+
42
+ struct EnvironmentState {
43
+ Napi::FunctionReference dataChannelConstructor;
44
+ std::vector<std::weak_ptr<PeerBinding>> peers;
45
+ std::vector<std::weak_ptr<IceUdpMuxBinding>> listeners;
46
+ std::shared_ptr<SendQueue> sendQueue = std::make_shared<SendQueue>();
47
+ std::shared_ptr<TeardownTasks> teardownTasks = std::make_shared<TeardownTasks>();
48
+ Napi::Env::CleanupHook<decltype(&CleanupEnvironment), EnvironmentState> cleanupHook;
49
+ };
50
+
51
+ std::mutex environmentMutex;
52
+ size_t environmentCount = 0;
53
+
54
+ // Unlike the untyped wrapper, dispatch also runs with a null environment so
55
+ // queued native payloads are reclaimed when Node discards callbacks at exit.
56
+ class NativeDispatcher {
57
+ using Job = std::function<void(Napi::Env, Napi::Function)>;
58
+ static void Dispatch(Napi::Env env, Napi::Function callback, void *, Job *job) {
59
+ std::unique_ptr<Job> owned(job);
60
+ (*owned)(env, callback);
61
+ }
62
+ using Function = Napi::TypedThreadSafeFunction<void, Job, Dispatch>;
63
+ Function function;
64
+ bool released = false;
65
+
66
+ public:
67
+ static NativeDispatcher New(Napi::Env env, Napi::Function callback, const char *name) {
68
+ NativeDispatcher dispatcher;
69
+ dispatcher.function = Function::New(env, callback, name, 0, 1);
70
+ // Cleanup hooks run in reverse registration order. Stop our producers before
71
+ // Node closes any of the thread-safe function handles they can still call.
72
+ auto *state = env.GetInstanceData<EnvironmentState>();
73
+ state->cleanupHook.Remove(env);
74
+ state->cleanupHook = env.AddCleanupHook(CleanupEnvironment, state);
75
+ return dispatcher;
76
+ }
77
+ template <typename Data, typename Callback>
78
+ napi_status NonBlockingCall(Data *data, Callback callback) {
79
+ if (released)
80
+ return napi_closing;
81
+ auto job = std::make_unique<Job>([data, callback](Napi::Env env, Napi::Function fn) {
82
+ callback(env, fn, data);
83
+ });
84
+ auto status = function.NonBlockingCall(job.get());
85
+ if (status == napi_ok)
86
+ job.release();
87
+ // Node consumes our acquisition when environment shutdown returns napi_closing.
88
+ // The handle must never be used again, including by Release().
89
+ else if (status == napi_closing)
90
+ released = true;
91
+ return status;
92
+ }
93
+ void Unref(Napi::Env env) { function.Unref(env); }
94
+ void Release() {
95
+ if (!released) {
96
+ released = true;
97
+ function.Release();
98
+ }
99
+ }
100
+ };
34
101
 
35
102
  std::atomic<uint32_t> nextChannelId{1};
36
103
  constexpr auto PEER_CLOSE_TIMEOUT = std::chrono::seconds(5);
@@ -201,6 +268,7 @@ struct ChannelOptions {
201
268
  };
202
269
 
203
270
  struct NativeEvent {
271
+ std::shared_ptr<EventDispatcher> dispatcher;
204
272
  std::string target;
205
273
  std::string type;
206
274
  uint32_t channelId = 0;
@@ -247,6 +315,7 @@ struct EventDispatcher : public std::enable_shared_from_this<EventDispatcher> {
247
315
  }
248
316
 
249
317
  void EmitDirect(NativeEvent event) {
318
+ event.dispatcher = shared_from_this();
250
319
  auto *queued = new NativeEvent(std::move(event));
251
320
  std::lock_guard<std::mutex> lock(lifecycleMutex);
252
321
  if (!active) {
@@ -271,7 +340,7 @@ struct EventDispatcher : public std::enable_shared_from_this<EventDispatcher> {
271
340
 
272
341
  private:
273
342
  EventDispatcher(Napi::Env env, Napi::Function callback)
274
- : tsfn(Napi::ThreadSafeFunction::New(env, callback, "webrtc-node events", 0, 1)) {
343
+ : tsfn(NativeDispatcher::New(env, callback, "webrtc-node events")) {
275
344
  tsfn.Unref(env);
276
345
  }
277
346
 
@@ -317,11 +386,20 @@ private:
317
386
  std::shared_ptr<EventDispatcher> *dispatcher) {
318
387
  std::shared_ptr<EventDispatcher> scoped = std::move(*dispatcher);
319
388
  delete dispatcher;
389
+ if (!env || !callback)
390
+ return;
320
391
  scoped->Drain(env, callback);
321
392
  }
322
393
 
323
394
  static void DispatchDirect(Napi::Env env, Napi::Function callback, NativeEvent *event) {
324
395
  std::unique_ptr<NativeEvent> scoped(event);
396
+ if (!env || !callback)
397
+ return;
398
+ {
399
+ std::lock_guard lock(scoped->dispatcher->lifecycleMutex);
400
+ if (!scoped->dispatcher->active)
401
+ return;
402
+ }
325
403
  callback.Call({EventToObject(env, *scoped)});
326
404
  }
327
405
 
@@ -345,7 +423,7 @@ private:
345
423
  std::mutex lifecycleMutex;
346
424
  std::vector<NativeEvent> pendingEvents;
347
425
  bool dispatchScheduled = false;
348
- Napi::ThreadSafeFunction tsfn;
426
+ NativeDispatcher tsfn;
349
427
  };
350
428
 
351
429
  struct IceUdpMuxDispatch {
@@ -421,7 +499,7 @@ private:
421
499
  IceUdpMuxBinding(Napi::Env env, Napi::Function callback, uint16_t port_,
422
500
  std::optional<std::string> address_)
423
501
  : port(port_), address(std::move(address_)),
424
- tsfn(Napi::ThreadSafeFunction::New(env, callback, "webrtc-node ICE UDP mux", 0, 1)) {
502
+ tsfn(NativeDispatcher::New(env, callback, "webrtc-node ICE UDP mux")) {
425
503
  tsfn.Unref(env);
426
504
  }
427
505
 
@@ -435,6 +513,8 @@ private:
435
513
 
436
514
  static void Dispatch(Napi::Env env, Napi::Function callback, IceUdpMuxDispatch *dispatch) {
437
515
  std::unique_ptr<IceUdpMuxDispatch> scoped(dispatch);
516
+ if (!env || !callback)
517
+ return;
438
518
  {
439
519
  std::lock_guard<std::mutex> lock(scoped->binding->lifecycleMutex);
440
520
  if (!scoped->binding->active)
@@ -454,32 +534,20 @@ private:
454
534
  bool active = true;
455
535
  bool tsfnReleased = false;
456
536
  mutable std::mutex lifecycleMutex;
457
- Napi::ThreadSafeFunction tsfn;
537
+ NativeDispatcher tsfn;
458
538
  std::unique_ptr<rtc::IceUdpMuxListener> iceUdpMuxListener;
459
539
  };
460
540
 
461
- std::mutex &IceUdpMuxRegistryMutex() {
462
- static std::mutex mutex;
463
- return mutex;
464
- }
465
-
466
- std::vector<std::weak_ptr<IceUdpMuxBinding>> &IceUdpMuxRegistry() {
467
- static std::vector<std::weak_ptr<IceUdpMuxBinding>> registry;
468
- return registry;
469
- }
470
-
471
- void RegisterIceUdpMuxBinding(const std::shared_ptr<IceUdpMuxBinding> &binding) {
472
- std::lock_guard<std::mutex> lock(IceUdpMuxRegistryMutex());
473
- auto &registry = IceUdpMuxRegistry();
541
+ void RegisterIceUdpMuxBinding(Napi::Env env, const std::shared_ptr<IceUdpMuxBinding> &binding) {
542
+ auto &registry = env.GetInstanceData<EnvironmentState>()->listeners;
474
543
  registry.erase(std::remove_if(registry.begin(), registry.end(),
475
544
  [](const auto &entry) { return entry.expired(); }),
476
545
  registry.end());
477
546
  registry.push_back(binding);
478
547
  }
479
548
 
480
- std::optional<uint16_t> ActiveIceUdpMuxPort() {
481
- std::lock_guard<std::mutex> lock(IceUdpMuxRegistryMutex());
482
- auto &registry = IceUdpMuxRegistry();
549
+ std::optional<uint16_t> ActiveIceUdpMuxPort(Napi::Env env) {
550
+ auto &registry = env.GetInstanceData<EnvironmentState>()->listeners;
483
551
  std::optional<uint16_t> port;
484
552
  registry.erase(std::remove_if(registry.begin(), registry.end(),
485
553
  [&port](const auto &entry) {
@@ -496,18 +564,13 @@ std::optional<uint16_t> ActiveIceUdpMuxPort() {
496
564
  return port;
497
565
  }
498
566
 
499
- void CloseAllIceUdpMuxBindings() {
500
- std::vector<std::shared_ptr<IceUdpMuxBinding>> bindings;
501
- {
502
- std::lock_guard<std::mutex> lock(IceUdpMuxRegistryMutex());
503
- for (auto &entry : IceUdpMuxRegistry()) {
504
- if (auto binding = entry.lock())
505
- bindings.push_back(std::move(binding));
506
- }
507
- IceUdpMuxRegistry().clear();
567
+ void CloseAllIceUdpMuxBindings(EnvironmentState *state) {
568
+ auto entries = std::move(state->listeners);
569
+ state->listeners.clear();
570
+ for (auto &entry : entries) {
571
+ if (auto binding = entry.lock())
572
+ binding->Close();
508
573
  }
509
- for (auto &binding : bindings)
510
- binding->Close();
511
574
  }
512
575
 
513
576
  class NativeIceUdpMuxListener : public Napi::ObjectWrap<NativeIceUdpMuxListener> {
@@ -544,7 +607,7 @@ public:
544
607
  try {
545
608
  binding_ = IceUdpMuxBinding::Create(env, info[1].As<Napi::Function>(),
546
609
  static_cast<uint16_t>(port), std::move(address));
547
- RegisterIceUdpMuxBinding(binding_);
610
+ RegisterIceUdpMuxBinding(env, binding_);
548
611
  } catch (const std::exception &e) {
549
612
  Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
550
613
  }
@@ -580,10 +643,11 @@ struct ChannelBinding : public std::enable_shared_from_this<ChannelBinding> {
580
643
 
581
644
  static std::shared_ptr<ChannelBinding> Create(std::shared_ptr<rtc::DataChannel> dataChannel,
582
645
  std::shared_ptr<EventDispatcher> dispatcher,
646
+ std::shared_ptr<SendQueue> sendQueue,
583
647
  ChannelOptions options,
584
648
  ClosedCallback closedCallback) {
585
649
  auto binding = std::shared_ptr<ChannelBinding>(new ChannelBinding(
586
- std::move(dataChannel), std::move(dispatcher), std::move(options),
650
+ std::move(dataChannel), std::move(dispatcher), std::move(sendQueue), std::move(options),
587
651
  std::move(closedCallback)));
588
652
  binding->AttachCallbacks();
589
653
  return binding;
@@ -603,19 +667,37 @@ struct ChannelBinding : public std::enable_shared_from_this<ChannelBinding> {
603
667
  return options;
604
668
  }
605
669
 
670
+ template <typename Producer> bool Send(size_t size, Producer produce) {
671
+ if (closeRequested.load() || sendsCancelled.load() || !dataChannel->isOpen())
672
+ throw std::runtime_error("DataChannel is not open");
673
+ if (size > dataChannel->maxMessageSize())
674
+ throw std::invalid_argument("Message size exceeds limit");
675
+ sendQueue->EnqueueProduced(size, [&]() {
676
+ auto send = std::make_shared<QueuedSend>(shared_from_this(), produce(), size);
677
+ return [send]() { send->Run(); };
678
+ });
679
+ return true;
680
+ }
681
+
682
+ size_t BufferedAmount() const {
683
+ // Read our backlog first: a handoff to SCTP must never expose a false zero.
684
+ const size_t pending = pendingSendBytes.load();
685
+ return pending + dataChannel->bufferedAmount();
686
+ }
687
+
606
688
  void Close() {
607
- auto dc = dataChannel;
608
- if (!dc)
689
+ if (closeRequested.exchange(true))
609
690
  return;
610
- std::thread([dc = std::move(dc)]() {
691
+ sendQueue->Enqueue([dc = dataChannel]() {
611
692
  try {
612
693
  dc->close();
613
694
  } catch (...) {
614
695
  }
615
- }).detach();
696
+ }, 0, true);
616
697
  }
617
698
 
618
699
  void Destroy() {
700
+ sendsCancelled.store(true);
619
701
  {
620
702
  std::lock_guard<std::mutex> lock(callbacksMutex);
621
703
  if (!callbacksActive)
@@ -633,11 +715,41 @@ struct ChannelBinding : public std::enable_shared_from_this<ChannelBinding> {
633
715
  ChannelOptions options;
634
716
 
635
717
  private:
718
+ struct QueuedSend {
719
+ std::shared_ptr<ChannelBinding> binding;
720
+ rtc::message_variant data;
721
+ size_t size;
722
+
723
+ QueuedSend(std::shared_ptr<ChannelBinding> binding_, rtc::message_variant data_, size_t size_)
724
+ : binding(std::move(binding_)), data(std::move(data_)), size(size_) {
725
+ binding->pendingSendBytes.fetch_add(size);
726
+ }
727
+ ~QueuedSend() { binding->pendingSendBytes.fetch_sub(size); }
728
+
729
+ void Run() {
730
+ if (binding->sendsCancelled.load())
731
+ return;
732
+ try {
733
+ // A false result means SCTP buffered the accepted message; never resend it.
734
+ binding->dataChannel->send(std::move(data));
735
+ } catch (const std::exception &error) {
736
+ NativeEvent event;
737
+ event.target = "datachannel";
738
+ event.type = "error";
739
+ event.channelId = binding->id;
740
+ event.error = error.what();
741
+ binding->Emit(std::move(event));
742
+ }
743
+ }
744
+ };
745
+
636
746
  ChannelBinding(std::shared_ptr<rtc::DataChannel> dataChannel_,
637
- std::shared_ptr<EventDispatcher> dispatcher_, ChannelOptions options_,
747
+ std::shared_ptr<EventDispatcher> dispatcher_, std::shared_ptr<SendQueue> sendQueue_,
748
+ ChannelOptions options_,
638
749
  ClosedCallback closedCallback_)
639
750
  : id(AllocateChannelId()), dataChannel(std::move(dataChannel_)),
640
751
  dispatcher(std::move(dispatcher_)), options(std::move(options_)),
752
+ sendQueue(std::move(sendQueue_)),
641
753
  closedCallback(std::move(closedCallback_)) {}
642
754
 
643
755
  void Emit(NativeEvent event) {
@@ -662,6 +774,7 @@ private:
662
774
 
663
775
  dataChannel->onClosed([weak]() {
664
776
  if (auto self = weak.lock()) {
777
+ self->sendsCancelled.store(true);
665
778
  NativeEvent event;
666
779
  event.target = "datachannel";
667
780
  event.type = "close";
@@ -712,14 +825,16 @@ private:
712
825
  }
713
826
 
714
827
  bool callbacksActive = true;
828
+ std::shared_ptr<SendQueue> sendQueue;
829
+ std::atomic<size_t> pendingSendBytes{0};
830
+ std::atomic<bool> closeRequested{false};
831
+ std::atomic<bool> sendsCancelled{false};
715
832
  std::mutex callbacksMutex;
716
833
  ClosedCallback closedCallback;
717
834
  };
718
835
 
719
836
  class NativeDataChannel : public Napi::ObjectWrap<NativeDataChannel> {
720
837
  public:
721
- static Napi::FunctionReference constructor;
722
-
723
838
  static void Init(Napi::Env env, Napi::Object exports) {
724
839
  Napi::Function func = DefineClass(
725
840
  env, "NativeDataChannel",
@@ -743,8 +858,7 @@ public:
743
858
  InstanceAccessor("isClosed", &NativeDataChannel::GetIsClosed, nullptr),
744
859
  InstanceAccessor("maxMessageSize", &NativeDataChannel::GetMaxMessageSize, nullptr),
745
860
  });
746
- constructor = Napi::Persistent(func);
747
- constructor.SuppressDestruct();
861
+ env.GetInstanceData<EnvironmentState>()->dataChannelConstructor = Napi::Persistent(func);
748
862
  exports.Set("NativeDataChannel", func);
749
863
  }
750
864
 
@@ -752,7 +866,7 @@ public:
752
866
  auto *payload = new std::shared_ptr<ChannelBinding>(std::move(binding));
753
867
  auto external = Napi::External<std::shared_ptr<ChannelBinding>>::New(
754
868
  env, payload, [](Napi::Env, std::shared_ptr<ChannelBinding> *data) { delete data; });
755
- return constructor.New({external});
869
+ return env.GetInstanceData<EnvironmentState>()->dataChannelConstructor.New({external});
756
870
  }
757
871
 
758
872
  NativeDataChannel(const Napi::CallbackInfo &info) : Napi::ObjectWrap<NativeDataChannel>(info) {
@@ -767,8 +881,16 @@ private:
767
881
  Napi::Value SendString(const Napi::CallbackInfo &info) {
768
882
  Napi::Env env = info.Env();
769
883
  try {
770
- std::string value = info[0].ToString().Utf8Value();
771
- bool sent = binding_->dataChannel->send(value);
884
+ Napi::String value = info[0].ToString();
885
+ size_t size;
886
+ if (napi_get_value_string_utf8(env, value, nullptr, 0, &size) != napi_ok)
887
+ throw Napi::Error::New(env);
888
+ bool sent = binding_->Send(size, [&]() {
889
+ std::string data(size, '\0');
890
+ if (napi_get_value_string_utf8(env, value, data.data(), size + 1, nullptr) != napi_ok)
891
+ throw Napi::Error::New(env);
892
+ return rtc::message_variant(std::move(data));
893
+ });
772
894
  return Napi::Boolean::New(env, sent);
773
895
  } catch (const std::exception &e) {
774
896
  Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
@@ -783,7 +905,13 @@ private:
783
905
  throw std::invalid_argument("sendBinary expects a Uint8Array");
784
906
  auto view = info[0].As<Napi::Uint8Array>();
785
907
  const auto *bytes = reinterpret_cast<const rtc::byte *>(view.Data());
786
- bool sent = binding_->dataChannel->send(bytes, view.ByteLength());
908
+ const size_t size = view.ByteLength();
909
+ bool sent = binding_->Send(size, [&]() {
910
+ rtc::binary data(size);
911
+ if (!data.empty())
912
+ std::memcpy(data.data(), bytes, data.size());
913
+ return rtc::message_variant(std::move(data));
914
+ });
787
915
  return Napi::Boolean::New(env, sent);
788
916
  } catch (const std::exception &e) {
789
917
  Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
@@ -851,7 +979,7 @@ private:
851
979
  }
852
980
 
853
981
  Napi::Value GetBufferedAmount(const Napi::CallbackInfo &info) {
854
- return Napi::Number::New(info.Env(), binding_->dataChannel->bufferedAmount());
982
+ return Napi::Number::New(info.Env(), binding_->BufferedAmount());
855
983
  }
856
984
 
857
985
  Napi::Value GetIsOpen(const Napi::CallbackInfo &info) {
@@ -867,8 +995,6 @@ private:
867
995
  }
868
996
  };
869
997
 
870
- Napi::FunctionReference NativeDataChannel::constructor;
871
-
872
998
  Napi::Object EventDispatcher::EventToObject(Napi::Env env, NativeEvent &event) {
873
999
  Napi::Object object = Napi::Object::New(env);
874
1000
  object.Set("target", event.target);
@@ -944,7 +1070,7 @@ rtc::Configuration ParseConfiguration(const Napi::CallbackInfo &info) {
944
1070
  if (input.Has("enableIceUdpMux") && input.Get("enableIceUdpMux").IsBoolean())
945
1071
  config.enableIceUdpMux = input.Get("enableIceUdpMux").ToBoolean().Value();
946
1072
  if (config.enableIceUdpMux) {
947
- if (auto port = ActiveIceUdpMuxPort()) {
1073
+ if (auto port = ActiveIceUdpMuxPort(info.Env())) {
948
1074
  config.portRangeBegin = *port;
949
1075
  config.portRangeEnd = *port;
950
1076
  }
@@ -1043,9 +1169,13 @@ rtc::DataChannelInit ToRtcInit(const ChannelOptions &options) {
1043
1169
 
1044
1170
  struct PeerBinding : public std::enable_shared_from_this<PeerBinding> {
1045
1171
  static std::shared_ptr<PeerBinding> Create(rtc::Configuration config,
1046
- std::shared_ptr<EventDispatcher> dispatcher) {
1172
+ std::shared_ptr<EventDispatcher> dispatcher,
1173
+ std::shared_ptr<SendQueue> sendQueue,
1174
+ std::shared_ptr<TeardownTasks> teardownTasks) {
1047
1175
  auto binding =
1048
- std::shared_ptr<PeerBinding>(new PeerBinding(std::move(config), std::move(dispatcher)));
1176
+ std::shared_ptr<PeerBinding>(new PeerBinding(
1177
+ std::move(config), std::move(dispatcher), std::move(sendQueue),
1178
+ std::move(teardownTasks)));
1049
1179
  binding->AttachCallbacks();
1050
1180
  return binding;
1051
1181
  }
@@ -1058,7 +1188,7 @@ struct PeerBinding : public std::enable_shared_from_this<PeerBinding> {
1058
1188
  }
1059
1189
  std::weak_ptr<PeerBinding> weak = shared_from_this();
1060
1190
  auto channel = ChannelBinding::Create(
1061
- std::move(dataChannel), dispatcher, std::move(options),
1191
+ std::move(dataChannel), dispatcher, sendQueue, std::move(options),
1062
1192
  [weak](uint32_t id, const ChannelBinding *expected) {
1063
1193
  if (auto self = weak.lock())
1064
1194
  self->RemoveChannel(id, expected);
@@ -1095,9 +1225,11 @@ struct PeerBinding : public std::enable_shared_from_this<PeerBinding> {
1095
1225
  std::shared_ptr<EventDispatcher> dispatcher;
1096
1226
 
1097
1227
  private:
1098
- PeerBinding(rtc::Configuration config, std::shared_ptr<EventDispatcher> dispatcher_)
1228
+ PeerBinding(rtc::Configuration config, std::shared_ptr<EventDispatcher> dispatcher_,
1229
+ std::shared_ptr<SendQueue> sendQueue_, std::shared_ptr<TeardownTasks> teardownTasks_)
1099
1230
  : peerConnection(std::make_shared<rtc::PeerConnection>(std::move(config))),
1100
- dispatcher(std::move(dispatcher_)) {}
1231
+ dispatcher(std::move(dispatcher_)), sendQueue(std::move(sendQueue_)),
1232
+ teardownTasks(std::move(teardownTasks_)) {}
1101
1233
 
1102
1234
  void Emit(NativeEvent event) {
1103
1235
  std::lock_guard<std::mutex> lock(callbacksMutex);
@@ -1155,9 +1287,9 @@ private:
1155
1287
  if (!work)
1156
1288
  return;
1157
1289
 
1158
- std::thread([work = std::move(*work)]() mutable {
1290
+ teardownTasks->Start([work = std::move(*work)]() mutable {
1159
1291
  RunPeerTeardown(std::move(work));
1160
- }).detach();
1292
+ });
1161
1293
  }
1162
1294
 
1163
1295
  void AttachCallbacks() {
@@ -1242,49 +1374,33 @@ private:
1242
1374
  }
1243
1375
 
1244
1376
  std::atomic<bool> shutdown{false};
1377
+ std::shared_ptr<SendQueue> sendQueue;
1378
+ std::shared_ptr<TeardownTasks> teardownTasks;
1245
1379
  bool callbacksActive = true;
1246
1380
  std::mutex callbacksMutex;
1247
1381
  std::mutex channelsMutex;
1248
1382
  std::unordered_map<uint32_t, std::shared_ptr<ChannelBinding>> channels;
1249
1383
  };
1250
1384
 
1251
- std::mutex &PeerRegistryMutex() {
1252
- static std::mutex mutex;
1253
- return mutex;
1254
- }
1255
-
1256
- std::vector<std::weak_ptr<PeerBinding>> &PeerRegistry() {
1257
- static std::vector<std::weak_ptr<PeerBinding>> registry;
1258
- return registry;
1259
- }
1260
-
1261
- void RegisterPeerBinding(const std::shared_ptr<PeerBinding> &binding) {
1262
- std::lock_guard<std::mutex> lock(PeerRegistryMutex());
1263
- auto &registry = PeerRegistry();
1385
+ void RegisterPeerBinding(Napi::Env env, const std::shared_ptr<PeerBinding> &binding) {
1386
+ auto &registry = env.GetInstanceData<EnvironmentState>()->peers;
1264
1387
  registry.erase(std::remove_if(registry.begin(), registry.end(),
1265
1388
  [](const auto &entry) { return entry.expired(); }),
1266
1389
  registry.end());
1267
1390
  registry.push_back(binding);
1268
1391
  }
1269
1392
 
1270
- void CloseAllPeerBindings() {
1271
- std::vector<std::shared_ptr<PeerBinding>> bindings;
1272
- {
1273
- std::lock_guard<std::mutex> lock(PeerRegistryMutex());
1274
- for (auto &entry : PeerRegistry()) {
1275
- if (auto binding = entry.lock())
1276
- bindings.push_back(std::move(binding));
1277
- }
1278
- PeerRegistry().clear();
1393
+ void CloseAllPeerBindings(EnvironmentState *state) {
1394
+ auto entries = std::move(state->peers);
1395
+ state->peers.clear();
1396
+ for (auto &entry : entries) {
1397
+ if (auto binding = entry.lock())
1398
+ binding->DestroySync();
1279
1399
  }
1280
- for (auto &binding : bindings)
1281
- binding->DestroySync();
1282
1400
  }
1283
1401
 
1284
1402
  class NativePeerConnection : public Napi::ObjectWrap<NativePeerConnection> {
1285
1403
  public:
1286
- static Napi::FunctionReference constructor;
1287
-
1288
1404
  static void Init(Napi::Env env, Napi::Object exports) {
1289
1405
  Napi::Function func = DefineClass(
1290
1406
  env, "NativePeerConnection",
@@ -1312,8 +1428,6 @@ public:
1312
1428
  InstanceAccessor("maxDataChannelId", &NativePeerConnection::GetMaxDataChannelId,
1313
1429
  nullptr),
1314
1430
  });
1315
- constructor = Napi::Persistent(func);
1316
- constructor.SuppressDestruct();
1317
1431
  exports.Set("NativePeerConnection", func);
1318
1432
  }
1319
1433
 
@@ -1322,9 +1436,17 @@ public:
1322
1436
  Napi::Env env = info.Env();
1323
1437
  if (info.Length() < 2 || !info[1].IsFunction())
1324
1438
  throw Napi::TypeError::New(env, "NativePeerConnection requires an event callback");
1325
- auto dispatcher = EventDispatcher::Create(env, info[1].As<Napi::Function>());
1326
- binding_ = PeerBinding::Create(ParseConfiguration(info), dispatcher);
1327
- RegisterPeerBinding(binding_);
1439
+ try {
1440
+ auto dispatcher = EventDispatcher::Create(env, info[1].As<Napi::Function>());
1441
+ binding_ = PeerBinding::Create(ParseConfiguration(info), dispatcher,
1442
+ env.GetInstanceData<EnvironmentState>()->sendQueue,
1443
+ env.GetInstanceData<EnvironmentState>()->teardownTasks);
1444
+ RegisterPeerBinding(env, binding_);
1445
+ } catch (const Napi::Error &) {
1446
+ throw;
1447
+ } catch (const std::exception &error) {
1448
+ throw Napi::Error::New(env, error.what());
1449
+ }
1328
1450
  }
1329
1451
 
1330
1452
  ~NativePeerConnection() override {
@@ -1335,6 +1457,12 @@ public:
1335
1457
  private:
1336
1458
  std::shared_ptr<PeerBinding> binding_;
1337
1459
 
1460
+ std::shared_ptr<rtc::PeerConnection> RequirePeer(Napi::Env env) const {
1461
+ if (!binding_ || !binding_->peerConnection)
1462
+ throw Napi::Error::New(env, "Native peer connection is closed");
1463
+ return binding_->peerConnection;
1464
+ }
1465
+
1338
1466
  Napi::Value CreateDataChannel(const Napi::CallbackInfo &info) {
1339
1467
  Napi::Env env = info.Env();
1340
1468
  try {
@@ -1342,7 +1470,7 @@ private:
1342
1470
  ChannelOptions options =
1343
1471
  ParseChannelOptions(info.Length() > 1 ? info[1] : env.Undefined());
1344
1472
  auto dataChannel =
1345
- binding_->peerConnection->createDataChannel(label, ToRtcInit(options));
1473
+ RequirePeer(info.Env())->createDataChannel(label, ToRtcInit(options));
1346
1474
  auto channel = binding_->AddChannel(std::move(dataChannel), std::move(options));
1347
1475
  return NativeDataChannel::NewInstance(env, std::move(channel));
1348
1476
  } catch (const std::exception &e) {
@@ -1354,7 +1482,7 @@ private:
1354
1482
  Napi::Value CreateOffer(const Napi::CallbackInfo &info) {
1355
1483
  Napi::Env env = info.Env();
1356
1484
  try {
1357
- return DescriptionToObject(env, binding_->peerConnection->createOffer());
1485
+ return DescriptionToObject(env, RequirePeer(info.Env())->createOffer());
1358
1486
  } catch (const std::exception &e) {
1359
1487
  Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
1360
1488
  return env.Undefined();
@@ -1364,7 +1492,7 @@ private:
1364
1492
  Napi::Value CreateAnswer(const Napi::CallbackInfo &info) {
1365
1493
  Napi::Env env = info.Env();
1366
1494
  try {
1367
- return DescriptionToObject(env, binding_->peerConnection->createAnswer());
1495
+ return DescriptionToObject(env, RequirePeer(info.Env())->createAnswer());
1368
1496
  } catch (const std::exception &e) {
1369
1497
  Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
1370
1498
  return env.Undefined();
@@ -1380,7 +1508,7 @@ private:
1380
1508
  rtc::LocalDescriptionInit init;
1381
1509
  if (info.Length() > 1)
1382
1510
  init = ParseLocalDescriptionInit(info[1]);
1383
- binding_->peerConnection->setLocalDescription(ParseDescriptionType(type), init);
1511
+ RequirePeer(info.Env())->setLocalDescription(ParseDescriptionType(type), init);
1384
1512
  return env.Undefined();
1385
1513
  } catch (const std::exception &e) {
1386
1514
  Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
@@ -1394,7 +1522,7 @@ private:
1394
1522
  Napi::Object object = info[0].As<Napi::Object>();
1395
1523
  std::string type = object.Get("type").ToString().Utf8Value();
1396
1524
  std::string sdp = object.Get("sdp").ToString().Utf8Value();
1397
- binding_->peerConnection->setRemoteDescription(rtc::Description(sdp, type));
1525
+ RequirePeer(info.Env())->setRemoteDescription(rtc::Description(sdp, type));
1398
1526
  return env.Undefined();
1399
1527
  } catch (const std::exception &e) {
1400
1528
  Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
@@ -1411,7 +1539,7 @@ private:
1411
1539
  if (object.Has("sdpMid") && !object.Get("sdpMid").IsNull() &&
1412
1540
  !object.Get("sdpMid").IsUndefined())
1413
1541
  mid = object.Get("sdpMid").ToString().Utf8Value();
1414
- binding_->peerConnection->addRemoteCandidate(rtc::Candidate(candidate, mid));
1542
+ RequirePeer(info.Env())->addRemoteCandidate(rtc::Candidate(candidate, mid));
1415
1543
  return env.Undefined();
1416
1544
  } catch (const std::exception &e) {
1417
1545
  Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
@@ -1422,7 +1550,7 @@ private:
1422
1550
  Napi::Value GatherLocalCandidates(const Napi::CallbackInfo &info) {
1423
1551
  Napi::Env env = info.Env();
1424
1552
  try {
1425
- binding_->peerConnection->gatherLocalCandidates();
1553
+ RequirePeer(info.Env())->gatherLocalCandidates();
1426
1554
  } catch (const std::exception &e) {
1427
1555
  Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
1428
1556
  }
@@ -1432,7 +1560,7 @@ private:
1432
1560
  Napi::Value LocalDescription(const Napi::CallbackInfo &info) {
1433
1561
  Napi::Env env = info.Env();
1434
1562
  try {
1435
- auto description = binding_->peerConnection->localDescription();
1563
+ auto description = RequirePeer(info.Env())->localDescription();
1436
1564
  if (!description)
1437
1565
  return env.Null();
1438
1566
  return DescriptionToObject(env, *description);
@@ -1445,7 +1573,7 @@ private:
1445
1573
  Napi::Value RemoteDescription(const Napi::CallbackInfo &info) {
1446
1574
  Napi::Env env = info.Env();
1447
1575
  try {
1448
- auto description = binding_->peerConnection->remoteDescription();
1576
+ auto description = RequirePeer(info.Env())->remoteDescription();
1449
1577
  if (!description)
1450
1578
  return env.Null();
1451
1579
  return DescriptionToObject(env, *description);
@@ -1458,7 +1586,7 @@ private:
1458
1586
  Napi::Value RemoteFingerprint(const Napi::CallbackInfo &info) {
1459
1587
  Napi::Env env = info.Env();
1460
1588
  try {
1461
- auto fingerprint = binding_->peerConnection->remoteFingerprint();
1589
+ auto fingerprint = RequirePeer(info.Env())->remoteFingerprint();
1462
1590
  if (!fingerprint.isValid())
1463
1591
  return env.Null();
1464
1592
  Napi::Object result = Napi::Object::New(env);
@@ -1477,7 +1605,7 @@ private:
1477
1605
  try {
1478
1606
  rtc::Candidate local;
1479
1607
  rtc::Candidate remote;
1480
- if (!binding_->peerConnection->getSelectedCandidatePair(&local, &remote))
1608
+ if (!RequirePeer(info.Env())->getSelectedCandidatePair(&local, &remote))
1481
1609
  return env.Null();
1482
1610
  Napi::Object pair = Napi::Object::New(env);
1483
1611
  pair.Set("local", CandidateToObject(env, local));
@@ -1499,32 +1627,30 @@ private:
1499
1627
  }
1500
1628
 
1501
1629
  Napi::Value GetConnectionState(const Napi::CallbackInfo &info) {
1502
- return Napi::String::New(info.Env(), ToString(binding_->peerConnection->state()));
1630
+ return Napi::String::New(info.Env(), ToString(RequirePeer(info.Env())->state()));
1503
1631
  }
1504
1632
 
1505
1633
  Napi::Value GetIceConnectionState(const Napi::CallbackInfo &info) {
1506
- return Napi::String::New(info.Env(), ToString(binding_->peerConnection->iceState()));
1634
+ return Napi::String::New(info.Env(), ToString(RequirePeer(info.Env())->iceState()));
1507
1635
  }
1508
1636
 
1509
1637
  Napi::Value GetIceGatheringState(const Napi::CallbackInfo &info) {
1510
- return Napi::String::New(info.Env(), ToString(binding_->peerConnection->gatheringState()));
1638
+ return Napi::String::New(info.Env(), ToString(RequirePeer(info.Env())->gatheringState()));
1511
1639
  }
1512
1640
 
1513
1641
  Napi::Value GetSignalingState(const Napi::CallbackInfo &info) {
1514
- return Napi::String::New(info.Env(), ToString(binding_->peerConnection->signalingState()));
1642
+ return Napi::String::New(info.Env(), ToString(RequirePeer(info.Env())->signalingState()));
1515
1643
  }
1516
1644
 
1517
1645
  Napi::Value GetRemoteMaxMessageSize(const Napi::CallbackInfo &info) {
1518
- return Napi::Number::New(info.Env(), binding_->peerConnection->remoteMaxMessageSize());
1646
+ return Napi::Number::New(info.Env(), RequirePeer(info.Env())->remoteMaxMessageSize());
1519
1647
  }
1520
1648
 
1521
1649
  Napi::Value GetMaxDataChannelId(const Napi::CallbackInfo &info) {
1522
- return Napi::Number::New(info.Env(), binding_->peerConnection->maxDataChannelId());
1650
+ return Napi::Number::New(info.Env(), RequirePeer(info.Env())->maxDataChannelId());
1523
1651
  }
1524
1652
  };
1525
1653
 
1526
- Napi::FunctionReference NativePeerConnection::constructor;
1527
-
1528
1654
  Napi::Value GenerateCertificate(const Napi::CallbackInfo &info) {
1529
1655
  Napi::Env env = info.Env();
1530
1656
  try {
@@ -1606,22 +1732,36 @@ void ConfigureLibDataChannelLogging() {
1606
1732
  rtc::InitLogger(rtc::LogLevel::Error);
1607
1733
  }
1608
1734
 
1609
- void CleanupNative() {
1610
- CloseAllPeerBindings();
1611
- CloseAllIceUdpMuxBindings();
1612
- rtc::Cleanup().wait();
1735
+ void CleanupNative(EnvironmentState *state) {
1736
+ CloseAllPeerBindings(state);
1737
+ CloseAllIceUdpMuxBindings(state);
1738
+ state->teardownTasks->Join();
1739
+ }
1740
+
1741
+ void CleanupEnvironment(EnvironmentState *state) {
1742
+ state->sendQueue->Stop();
1743
+ CleanupNative(state);
1744
+ state->dataChannelConstructor.Reset();
1745
+ std::lock_guard lock(environmentMutex);
1746
+ if (--environmentCount == 0)
1747
+ rtc::Cleanup().wait();
1613
1748
  }
1614
1749
 
1615
1750
  Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
1616
- ConfigureLibDataChannelLogging();
1751
+ std::lock_guard lock(environmentMutex);
1752
+ auto *state = new EnvironmentState();
1753
+ env.SetInstanceData(state);
1754
+ static std::once_flag logging;
1755
+ std::call_once(logging, ConfigureLibDataChannelLogging);
1617
1756
  NativeDataChannel::Init(env, exports);
1618
1757
  NativeIceUdpMuxListener::Init(env, exports);
1619
1758
  NativePeerConnection::Init(env, exports);
1620
1759
  exports.Set("generateCertificate", Napi::Function::New(env, GenerateCertificate));
1621
1760
  exports.Set("importCertificate", Napi::Function::New(env, ImportCertificate));
1622
- env.AddCleanupHook([]() { CleanupNative(); });
1761
+ ++environmentCount;
1762
+ state->cleanupHook = env.AddCleanupHook(CleanupEnvironment, state);
1623
1763
  exports.Set("cleanup", Napi::Function::New(env, [](const Napi::CallbackInfo &info) {
1624
- CleanupNative();
1764
+ CleanupNative(info.Env().GetInstanceData<EnvironmentState>());
1625
1765
  return info.Env().Undefined();
1626
1766
  }));
1627
1767
  return exports;