uWebSockets C++ error on send(): cork buffer must not be acquired without checking cancork

I’m developing a websoscket server for an embedded system. The requirements are very simple: send updates to a list of signals ids the webapp subscribes to. Everything works fine until the crash happens.
The problem seems to be part of the corking mechanism and I’ve tried to reproduce it under different conditions but the problem still occurs.
In my implementation I have a custom pub/sub because I want to deliver more signal updates at once in one message: this is realized in a separate thread that sends asynchronous messages to the connected clients with a frequency of 10 times per second (with the available updates).
The problem seems to happen when there is a collision with the send and message callback.

This is my app setup, very similar to default:

    auto app
        = uWS::App()
              .ws<ClientData>(
                  "/*", { /* Settings */
                          .compression      = uWS::CompressOptions(uWS::DEDICATED_COMPRESSOR_4KB | uWS::DEDICATED_DECOMPRESSOR),
                          .maxPayloadLength = 100 * 1024 * 1024,
                          .idleTimeout      = 16,
                          .maxBackpressure  = 100 * 1024 * 1024,
                          .closeOnBackpressureLimit = false,
                          .resetIdleTimeoutOnSend   = false,
                          .sendPingsAutomatically   = true,
                          /* Handlers */
                          // handshaking callback
                          .upgrade =
                              [this](auto *res, auto *req, auto *context)
                          {
                              auto subprotocols = String(req->getHeader("sec-websocket-protocol"));
                              auto jwt          = this->GetJwtFromSubprotocols(subprotocols);

                              if(!this->ValidateJwt(jwt))
                              {
                                  res->writeStatus("401");
                                  res->end("Invalid jwt");
                                  return;
                              }

                              if(this->IsMaximumCapacityReached())
                              {
                                  res->writeStatus("503");
                                  res->end("Maximum number of clients reached");
                                  return;
                              }

                              res->upgrade(ClientData{}, req->getHeader("sec-websocket-key"),
                                           req->getHeader("sec-websocket-protocol"), req->getHeader("sec-websocket-extensions"),
                                           context);
                          },
                          .open    = [this](auto *ws) { this->OnOpen(ws); },
                          .message = [this](auto *ws, std::string_view message, uWS::OpCode) { this->OnMessage(ws, message); },
                          .dropped =
                              [](auto * /*ws*/, std::string_view /*message*/, uWS::OpCode /*opCode*/)
                          {
                              /* A message was dropped due to set maxBackpressure and closeOnBackpressureLimit limit */
                          },
                          .drain =
                              [](auto * /*ws*/)
                          {
                              /* Check ws->getBufferedAmount() here */
                          },
                          .ping =
                              [](auto * /*ws*/, std::string_view)
                          {
                              /* Not implemented yet */
                          },
                          .pong =
                              [](auto * /*ws*/, std::string_view)
                          {
                              /* Not implemented yet */
                          },
                          .close = [this](auto *ws, int /*code*/, std::string_view /*message*/) { this->OnClose(ws); } })
              .listen("127.0.0.1", 50000,
                      [](auto *listen_socket)
                      {
                          if(listen_socket)
                          {
                              LogDebug("Ready on port 50000");
                          }
                      });

The Sender thread cyclically executes this code protected by mutex:

Sync lock(*_clientsMutex);
for(auto client : *_clients)
{
    SendRealtimeUpdate(client);
}

the SendRealtimeUpdate method after some elaboration provides a msg as std::string and sends it client->send(msg, uWS::OpCode::TEXT);

I think I’m missing something maybe there is a proper sync to implement between the message callback and the send of my thread that can happen in any moment.

I tried to use the uWebSockets pub/sub internal mechanism using the signal id as topic and it automatically manages the send when it is ready and this works. However this is inefficient because I want to send in a message multiple signals update and not one.

2

Swift – Friday Pie’s comment is correct. uWebSockets is not thread-safe except for very few functions such as timers and “defer”.

Your comment asked:

need to send a message every 1second to all connected clients

Below is a thread-safe way to use a timer to send a message.

#include "App.h"
   
using namespace std;

struct PerSocketData {};

uWS::WebSocket<false, true, PerSocketData> *gws=nullptr;
    
int main() {
   auto loop = uWS::Loop::get();

   struct us_timer_t *delayTimer = us_create_timer((struct us_loop_t *) loop, 0, 0);

   us_timer_set(delayTimer, [](struct us_timer_t *) {
                               if (gws) {
                                  cout << "calling send" << endl;
                                  gws->send("from server", uWS::OpCode::TEXT);
                               }
                            }, 1000, 1000);
   
   uWS::App app;

   app.ws<PerSocketData>("/*", {
         .idleTimeout = 0,
         .sendPingsAutomatically = false,
         .open = [](auto *ws) {
                    gws = ws;
                 },
         .close = [](auto */*ws*/, int /*code*/, std::string_view /*message*/) {
                     gws = nullptr;
                  }
      }).listen(9001, [](auto *) {
                      });

   app.run();
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật