Commit 9040b08

Browse files
mcollinaaduh95
authored andcommitted
net: support TCP handle transfer on Windows
Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #64460Fixes: #64456 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Stefan Stojanovic <stefan.stojanovic@janeasystems.com> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
1 parent 1216481 commit 9040b08

11 files changed

Lines changed: 50 additions & 77 deletions

‎doc/api/errors.md‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3512,14 +3512,6 @@ An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
35123512
via a `worker_threads``postMessage()` call while it was not in a transferable
35133513
state, for example because it had already started reading or had buffered data.
35143514

3515-
<aid="ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED"></a>
3516-
3517-
### `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`
3518-
3519-
An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
3520-
on a platform where moving the underlying handle between event loops is not
3521-
supported (currently Windows).
3522-
35233515
<aid="ERR_WORKER_INIT_FAILED"></a>
35243516

35253517
### `ERR_WORKER_INIT_FAILED`

‎doc/api/net.md‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -766,9 +766,7 @@ threads.
766766
The socket must be a freshly accepted or created TCP connection: it must still
767767
be attached to a live handle, must not be connecting or destroyed, and must not
768768
have started reading or have buffered data. Otherwise `postMessage()` throws
769-
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported, and only
770-
on Unix-like platforms; on Windows `postMessage()` throws
771-
`ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
769+
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported.
772770

773771
```cjs
774772
constnet=require('node:net');

‎doc/api/worker_threads.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1247,8 +1247,7 @@ freshly accepted or created TCP connection that has not yet started reading and
12471247
has no buffered data, otherwise `postMessage()` throws
12481248
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. This makes it possible to accept
12491249
connections on one thread and distribute them across a pool of worker threads.
1250-
Only TCP handles are supported, and only on Unix-like platforms; on Windows
1251-
`postMessage()` throws `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
1250+
Only TCP handles are supported.
12521251
12531252
If `value` contains {SharedArrayBuffer} instances, those are accessible
12541253
from either thread. They cannot be listed in `transferList`.

‎lib/internal/errors.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,8 +1932,6 @@ E('ERR_WORKER_HANDLE_NOT_TRANSFERABLE',
19321932
'%s cannot be transferred in its current state; it must be a freshly '+
19331933
'created or accepted handle that has not started reading and has no '+
19341934
'pending writes',Error);
1935-
E('ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED',
1936-
'Transferring a %s to another thread is not supported on this platform',Error);
19371935
E('ERR_WORKER_INIT_FAILED','Worker initialization failure: %s',Error);
19381936
E('ERR_WORKER_INVALID_EXEC_ARGV',(errors,msg='invalid execArgv flags')=>
19391937
`Initiated Worker with ${msg}: ${ArrayPrototypeJoin(errors,', ')}`,

‎lib/net.js‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,6 @@ const {
120120
ERR_SOCKET_CONNECTION_TIMEOUT,
121121
ERR_SOCKET_HANDLE_ADOPTED,
122122
ERR_WORKER_HANDLE_NOT_TRANSFERABLE,
123-
ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED,
124123
},
125124
genericNodeError,
126125
}=require('internal/errors');
@@ -1600,9 +1599,6 @@ Socket.prototype[kReinitializeHandle] = function reinitializeHandle(handle) {
16001599
// connecting or destroyed, and with no data already buffered in either
16011600
// direction (which would otherwise be lost on the sending side).
16021601
functionassertTransferableSocket(socket){
1603-
if(isWindows){
1604-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Socket');
1605-
}
16061602
consthandle=socket._handle;
16071603
if(handle==null||!(handleinstanceofTCP)||
16081604
socket.destroyed||socket.connecting||
@@ -2364,9 +2360,6 @@ Server.prototype._listen2 = setupListenHandle; // legacy alias
23642360
// underlying listening socket (and its pending accept queue) to that thread's
23652361
// event loop. Only a server bound to a live TCP handle can be transferred.
23662362
functionassertTransferableServer(server){
2367-
if(isWindows){
2368-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Server');
2369-
}
23702363
if(server._handle==null||!(server._handleinstanceofTCP)){
23712364
thrownewERR_WORKER_HANDLE_NOT_TRANSFERABLE('net.Server');
23722365
}

‎src/tcp_wrap.cc‎

Lines changed: 41 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -380,57 +380,66 @@ void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
380380
}
381381

382382
BaseObject::TransferMode TCPWrap::GetTransferMode() const {
383-
#ifdef _WIN32
384-
// Re-adopting a socket into another thread's event loop requires
385-
// re-associating it with that loop's IOCP, which needs same-process
386-
// WSADuplicateSocket support that is not wired up yet. The JS net layer
387-
// throws a clearer error before reaching here; this is the backstop for the
388-
// low-level `socket._handle` transfer path.
389-
return TransferMode::kDisallowCloneAndTransfer;
390-
#else
391383
// Only a live handle that is not already being torn down can be transferred.
392384
// Higher-level guards (no buffered reads, no pending writes) are enforced by
393385
// the JS net.Socket/net.Server layer before a handle reaches here.
394386
if (!HandleWrap::IsAlive(this) || IsHandleClosing())
395387
return TransferMode::kDisallowCloneAndTransfer;
396388
return TransferMode::kTransferable;
397-
#endif
398389
}
399390

400391
std::unique_ptr<worker::TransferData> TCPWrap::TransferForMessaging() {
401-
#ifdef _WIN32
402-
return {};
403-
#else
404392
CHECK_NE(GetTransferMode(), TransferMode::kDisallowCloneAndTransfer);
405393

406394
uv_os_fd_t fd;
407395
if (uv_fileno(reinterpret_cast<uv_handle_t*>(&handle_), &fd) != 0) return {};
408396

409-
// dup() the descriptor so the receiving event loop owns an independent
410-
// reference to the same socket. We then close the source handle, which
411-
// renders it unusable on this side (true transfer semantics) while the dup
412-
// keeps the underlying socket alive for the destination thread.
413-
int dup_fd = dup(fd);
414-
if (dup_fd < 0) return {};
397+
#ifdef _WIN32
398+
// A socket that is already associated with an IOCP cannot be associated with
399+
// another one. Create a same-process duplicate that is not associated with
400+
// any IOCP yet; uv_tcp_open() will associate it with the receiving loop.
401+
WSAPROTOCOL_INFOW protocol_info;
402+
uv_os_sock_t source_socket = reinterpret_cast<uv_os_sock_t>(fd);
403+
if (WSADuplicateSocketW(
404+
source_socket, GetCurrentProcessId(), &protocol_info) != 0) {
405+
return {};
406+
}
407+
uv_os_sock_t duplicate = WSASocketW(FROM_PROTOCOL_INFO,
408+
FROM_PROTOCOL_INFO,
409+
FROM_PROTOCOL_INFO,
410+
&protocol_info,
411+
0,
412+
WSA_FLAG_OVERLAPPED);
413+
if (duplicate == static_cast<uv_os_sock_t>(-1)) return {};
414+
#else
415+
// Unix threads share the descriptor table, so dup() creates an independent
416+
// reference to the same socket for the receiving event loop.
417+
uv_os_sock_t duplicate = dup(fd);
418+
if (duplicate < 0) return {};
419+
#endif
415420

416421
SocketType type =
417422
provider_type() == ProviderType::PROVIDER_TCPSERVERWRAP ? SERVER : SOCKET;
418423

419-
// Stop watching the fd and tear down the source handle.
424+
// Stop watching the original socket and tear down the source handle. The
425+
// duplicate keeps the underlying socket alive until the destination adopts
426+
// it, or until TransferData is destroyed if the message is not delivered.
420427
Close();
421428

422-
return std::make_unique<TransferData>(dup_fd, type);
423-
#endif
429+
return std::make_unique<TransferData>(duplicate, type);
424430
}
425431

426432
TCPWrap::TransferData::~TransferData() {
427-
// Only reached if the message was never delivered (e.g. the destination port
428-
// closed in flight); close the dup'd fd so it is not leaked.
429-
if (fd_ >= 0) {
433+
#ifdef _WIN32
434+
if (socket_ != static_cast<uv_os_sock_t>(-1))
435+
CHECK_EQ(0, closesocket(socket_));
436+
#else
437+
if (socket_ >= 0) {
430438
uv_fs_t req;
431-
CHECK_EQ(0, uv_fs_close(nullptr, &req, fd_, nullptr));
439+
CHECK_EQ(0, uv_fs_close(nullptr, &req, socket_, nullptr));
432440
uv_fs_req_cleanup(&req);
433441
}
442+
#endif
434443
}
435444

436445
BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
@@ -453,10 +462,14 @@ BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
453462
TCPWrap* wrap = BaseObject::Unwrap<TCPWrap>(obj);
454463
if (wrap == nullptr) return {};
455464

456-
if (uv_tcp_open(&wrap->handle_, fd_) != 0) return {};
465+
if (uv_tcp_open(&wrap->handle_, socket_) != 0) return {};
457466

458-
wrap->set_fd(fd_);
459-
fd_ = -1; // Ownership has been handed to the new handle.
467+
#ifdef _WIN32
468+
socket_ = static_cast<uv_os_sock_t>(-1);
469+
#else
470+
wrap->set_fd(socket_);
471+
socket_ = -1;
472+
#endif
460473
return BaseObjectPtr<BaseObject>(wrap);
461474
}
462475

‎src/tcp_wrap.h‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,10 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
6262
}
6363
}
6464

65-
// Transfer the underlying socket to another thread via .postMessage(). Within
66-
// a single process all threads share the same file descriptor table, so the
67-
// transfer dup()s the fd and re-adopts it (uv_tcp_open) in the receiving
68-
// event loop. This is the building block for distributing listening sockets
69-
// and accepted connections across worker_threads.
65+
// Transfer the underlying socket to another thread via .postMessage(). The
66+
// transfer duplicates the socket and re-adopts it (uv_tcp_open) in the
67+
// receiving event loop. This is the building block for distributing
68+
// listening sockets and accepted connections across worker_threads.
7069
BaseObject::TransferMode GetTransferMode() constoverride;
7170
std::unique_ptr<worker::TransferData> TransferForMessaging() override;
7271

@@ -75,7 +74,8 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
7574

7675
classTransferData : publicworker::TransferData {
7776
public:
78-
explicitTransferData(int fd, SocketType type) : fd_(fd), type_(type) {}
77+
explicitTransferData(uv_os_sock_t socket, SocketType type)
78+
: socket_(socket), type_(type) {}
7979
~TransferData() override;
8080

8181
BaseObjectPtr<BaseObject> Deserialize(
@@ -88,7 +88,7 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
8888
SET_SELF_SIZE(TransferData)
8989

9090
private:
91-
int fd_;
91+
uv_os_sock_t socket_;
9292
SocketType type_;
9393
};
9494

‎test/parallel/test-net-server-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

‎test/parallel/test-net-socket-transfer-worker-http.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
consthttp=require('http');

‎test/parallel/test-net-socket-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 9040b08

Browse files
mcollinaaduh95
authored andcommitted
net: support TCP handle transfer on Windows
Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #64460Fixes: #64456 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Stefan Stojanovic <stefan.stojanovic@janeasystems.com> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
1 parent 1216481 commit 9040b08

11 files changed

Lines changed: 50 additions & 77 deletions

‎doc/api/errors.md‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3512,14 +3512,6 @@ An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
35123512
via a `worker_threads``postMessage()` call while it was not in a transferable
35133513
state, for example because it had already started reading or had buffered data.
35143514

3515-
<aid="ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED"></a>
3516-
3517-
### `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`
3518-
3519-
An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
3520-
on a platform where moving the underlying handle between event loops is not
3521-
supported (currently Windows).
3522-
35233515
<aid="ERR_WORKER_INIT_FAILED"></a>
35243516

35253517
### `ERR_WORKER_INIT_FAILED`

‎doc/api/net.md‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -766,9 +766,7 @@ threads.
766766
The socket must be a freshly accepted or created TCP connection: it must still
767767
be attached to a live handle, must not be connecting or destroyed, and must not
768768
have started reading or have buffered data. Otherwise `postMessage()` throws
769-
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported, and only
770-
on Unix-like platforms; on Windows `postMessage()` throws
771-
`ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
769+
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported.
772770

773771
```cjs
774772
constnet=require('node:net');

‎doc/api/worker_threads.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1247,8 +1247,7 @@ freshly accepted or created TCP connection that has not yet started reading and
12471247
has no buffered data, otherwise `postMessage()` throws
12481248
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. This makes it possible to accept
12491249
connections on one thread and distribute them across a pool of worker threads.
1250-
Only TCP handles are supported, and only on Unix-like platforms; on Windows
1251-
`postMessage()` throws `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
1250+
Only TCP handles are supported.
12521251
12531252
If `value` contains {SharedArrayBuffer} instances, those are accessible
12541253
from either thread. They cannot be listed in `transferList`.

‎lib/internal/errors.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,8 +1932,6 @@ E('ERR_WORKER_HANDLE_NOT_TRANSFERABLE',
19321932
'%s cannot be transferred in its current state; it must be a freshly '+
19331933
'created or accepted handle that has not started reading and has no '+
19341934
'pending writes',Error);
1935-
E('ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED',
1936-
'Transferring a %s to another thread is not supported on this platform',Error);
19371935
E('ERR_WORKER_INIT_FAILED','Worker initialization failure: %s',Error);
19381936
E('ERR_WORKER_INVALID_EXEC_ARGV',(errors,msg='invalid execArgv flags')=>
19391937
`Initiated Worker with ${msg}: ${ArrayPrototypeJoin(errors,', ')}`,

‎lib/net.js‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,6 @@ const {
120120
ERR_SOCKET_CONNECTION_TIMEOUT,
121121
ERR_SOCKET_HANDLE_ADOPTED,
122122
ERR_WORKER_HANDLE_NOT_TRANSFERABLE,
123-
ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED,
124123
},
125124
genericNodeError,
126125
}=require('internal/errors');
@@ -1600,9 +1599,6 @@ Socket.prototype[kReinitializeHandle] = function reinitializeHandle(handle) {
16001599
// connecting or destroyed, and with no data already buffered in either
16011600
// direction (which would otherwise be lost on the sending side).
16021601
functionassertTransferableSocket(socket){
1603-
if(isWindows){
1604-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Socket');
1605-
}
16061602
consthandle=socket._handle;
16071603
if(handle==null||!(handleinstanceofTCP)||
16081604
socket.destroyed||socket.connecting||
@@ -2364,9 +2360,6 @@ Server.prototype._listen2 = setupListenHandle; // legacy alias
23642360
// underlying listening socket (and its pending accept queue) to that thread's
23652361
// event loop. Only a server bound to a live TCP handle can be transferred.
23662362
functionassertTransferableServer(server){
2367-
if(isWindows){
2368-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Server');
2369-
}
23702363
if(server._handle==null||!(server._handleinstanceofTCP)){
23712364
thrownewERR_WORKER_HANDLE_NOT_TRANSFERABLE('net.Server');
23722365
}

‎src/tcp_wrap.cc‎

Lines changed: 41 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -380,57 +380,66 @@ void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
380380
}
381381

382382
BaseObject::TransferMode TCPWrap::GetTransferMode() const {
383-
#ifdef _WIN32
384-
// Re-adopting a socket into another thread's event loop requires
385-
// re-associating it with that loop's IOCP, which needs same-process
386-
// WSADuplicateSocket support that is not wired up yet. The JS net layer
387-
// throws a clearer error before reaching here; this is the backstop for the
388-
// low-level `socket._handle` transfer path.
389-
return TransferMode::kDisallowCloneAndTransfer;
390-
#else
391383
// Only a live handle that is not already being torn down can be transferred.
392384
// Higher-level guards (no buffered reads, no pending writes) are enforced by
393385
// the JS net.Socket/net.Server layer before a handle reaches here.
394386
if (!HandleWrap::IsAlive(this) || IsHandleClosing())
395387
return TransferMode::kDisallowCloneAndTransfer;
396388
return TransferMode::kTransferable;
397-
#endif
398389
}
399390

400391
std::unique_ptr<worker::TransferData> TCPWrap::TransferForMessaging() {
401-
#ifdef _WIN32
402-
return {};
403-
#else
404392
CHECK_NE(GetTransferMode(), TransferMode::kDisallowCloneAndTransfer);
405393

406394
uv_os_fd_t fd;
407395
if (uv_fileno(reinterpret_cast<uv_handle_t*>(&handle_), &fd) != 0) return {};
408396

409-
// dup() the descriptor so the receiving event loop owns an independent
410-
// reference to the same socket. We then close the source handle, which
411-
// renders it unusable on this side (true transfer semantics) while the dup
412-
// keeps the underlying socket alive for the destination thread.
413-
int dup_fd = dup(fd);
414-
if (dup_fd < 0) return {};
397+
#ifdef _WIN32
398+
// A socket that is already associated with an IOCP cannot be associated with
399+
// another one. Create a same-process duplicate that is not associated with
400+
// any IOCP yet; uv_tcp_open() will associate it with the receiving loop.
401+
WSAPROTOCOL_INFOW protocol_info;
402+
uv_os_sock_t source_socket = reinterpret_cast<uv_os_sock_t>(fd);
403+
if (WSADuplicateSocketW(
404+
source_socket, GetCurrentProcessId(), &protocol_info) != 0) {
405+
return {};
406+
}
407+
uv_os_sock_t duplicate = WSASocketW(FROM_PROTOCOL_INFO,
408+
FROM_PROTOCOL_INFO,
409+
FROM_PROTOCOL_INFO,
410+
&protocol_info,
411+
0,
412+
WSA_FLAG_OVERLAPPED);
413+
if (duplicate == static_cast<uv_os_sock_t>(-1)) return {};
414+
#else
415+
// Unix threads share the descriptor table, so dup() creates an independent
416+
// reference to the same socket for the receiving event loop.
417+
uv_os_sock_t duplicate = dup(fd);
418+
if (duplicate < 0) return {};
419+
#endif
415420

416421
SocketType type =
417422
provider_type() == ProviderType::PROVIDER_TCPSERVERWRAP ? SERVER : SOCKET;
418423

419-
// Stop watching the fd and tear down the source handle.
424+
// Stop watching the original socket and tear down the source handle. The
425+
// duplicate keeps the underlying socket alive until the destination adopts
426+
// it, or until TransferData is destroyed if the message is not delivered.
420427
Close();
421428

422-
return std::make_unique<TransferData>(dup_fd, type);
423-
#endif
429+
return std::make_unique<TransferData>(duplicate, type);
424430
}
425431

426432
TCPWrap::TransferData::~TransferData() {
427-
// Only reached if the message was never delivered (e.g. the destination port
428-
// closed in flight); close the dup'd fd so it is not leaked.
429-
if (fd_ >= 0) {
433+
#ifdef _WIN32
434+
if (socket_ != static_cast<uv_os_sock_t>(-1))
435+
CHECK_EQ(0, closesocket(socket_));
436+
#else
437+
if (socket_ >= 0) {
430438
uv_fs_t req;
431-
CHECK_EQ(0, uv_fs_close(nullptr, &req, fd_, nullptr));
439+
CHECK_EQ(0, uv_fs_close(nullptr, &req, socket_, nullptr));
432440
uv_fs_req_cleanup(&req);
433441
}
442+
#endif
434443
}
435444

436445
BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
@@ -453,10 +462,14 @@ BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
453462
TCPWrap* wrap = BaseObject::Unwrap<TCPWrap>(obj);
454463
if (wrap == nullptr) return {};
455464

456-
if (uv_tcp_open(&wrap->handle_, fd_) != 0) return {};
465+
if (uv_tcp_open(&wrap->handle_, socket_) != 0) return {};
457466

458-
wrap->set_fd(fd_);
459-
fd_ = -1; // Ownership has been handed to the new handle.
467+
#ifdef _WIN32
468+
socket_ = static_cast<uv_os_sock_t>(-1);
469+
#else
470+
wrap->set_fd(socket_);
471+
socket_ = -1;
472+
#endif
460473
return BaseObjectPtr<BaseObject>(wrap);
461474
}
462475

‎src/tcp_wrap.h‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,10 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
6262
}
6363
}
6464

65-
// Transfer the underlying socket to another thread via .postMessage(). Within
66-
// a single process all threads share the same file descriptor table, so the
67-
// transfer dup()s the fd and re-adopts it (uv_tcp_open) in the receiving
68-
// event loop. This is the building block for distributing listening sockets
69-
// and accepted connections across worker_threads.
65+
// Transfer the underlying socket to another thread via .postMessage(). The
66+
// transfer duplicates the socket and re-adopts it (uv_tcp_open) in the
67+
// receiving event loop. This is the building block for distributing
68+
// listening sockets and accepted connections across worker_threads.
7069
BaseObject::TransferMode GetTransferMode() constoverride;
7170
std::unique_ptr<worker::TransferData> TransferForMessaging() override;
7271

@@ -75,7 +74,8 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
7574

7675
classTransferData : publicworker::TransferData {
7776
public:
78-
explicitTransferData(int fd, SocketType type) : fd_(fd), type_(type) {}
77+
explicitTransferData(uv_os_sock_t socket, SocketType type)
78+
: socket_(socket), type_(type) {}
7979
~TransferData() override;
8080

8181
BaseObjectPtr<BaseObject> Deserialize(
@@ -88,7 +88,7 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
8888
SET_SELF_SIZE(TransferData)
8989

9090
private:
91-
int fd_;
91+
uv_os_sock_t socket_;
9292
SocketType type_;
9393
};
9494

‎test/parallel/test-net-server-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

‎test/parallel/test-net-socket-transfer-worker-http.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
consthttp=require('http');

‎test/parallel/test-net-socket-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 9040b08

Browse files
mcollinaaduh95
authored andcommitted
net: support TCP handle transfer on Windows
Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #64460Fixes: #64456 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Stefan Stojanovic <stefan.stojanovic@janeasystems.com> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
1 parent 1216481 commit 9040b08

11 files changed

Lines changed: 50 additions & 77 deletions

‎doc/api/errors.md‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3512,14 +3512,6 @@ An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
35123512
via a `worker_threads``postMessage()` call while it was not in a transferable
35133513
state, for example because it had already started reading or had buffered data.
35143514

3515-
<aid="ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED"></a>
3516-
3517-
### `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`
3518-
3519-
An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
3520-
on a platform where moving the underlying handle between event loops is not
3521-
supported (currently Windows).
3522-
35233515
<aid="ERR_WORKER_INIT_FAILED"></a>
35243516

35253517
### `ERR_WORKER_INIT_FAILED`

‎doc/api/net.md‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -766,9 +766,7 @@ threads.
766766
The socket must be a freshly accepted or created TCP connection: it must still
767767
be attached to a live handle, must not be connecting or destroyed, and must not
768768
have started reading or have buffered data. Otherwise `postMessage()` throws
769-
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported, and only
770-
on Unix-like platforms; on Windows `postMessage()` throws
771-
`ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
769+
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported.
772770

773771
```cjs
774772
constnet=require('node:net');

‎doc/api/worker_threads.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1247,8 +1247,7 @@ freshly accepted or created TCP connection that has not yet started reading and
12471247
has no buffered data, otherwise `postMessage()` throws
12481248
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. This makes it possible to accept
12491249
connections on one thread and distribute them across a pool of worker threads.
1250-
Only TCP handles are supported, and only on Unix-like platforms; on Windows
1251-
`postMessage()` throws `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
1250+
Only TCP handles are supported.
12521251
12531252
If `value` contains {SharedArrayBuffer} instances, those are accessible
12541253
from either thread. They cannot be listed in `transferList`.

‎lib/internal/errors.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,8 +1932,6 @@ E('ERR_WORKER_HANDLE_NOT_TRANSFERABLE',
19321932
'%s cannot be transferred in its current state; it must be a freshly '+
19331933
'created or accepted handle that has not started reading and has no '+
19341934
'pending writes',Error);
1935-
E('ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED',
1936-
'Transferring a %s to another thread is not supported on this platform',Error);
19371935
E('ERR_WORKER_INIT_FAILED','Worker initialization failure: %s',Error);
19381936
E('ERR_WORKER_INVALID_EXEC_ARGV',(errors,msg='invalid execArgv flags')=>
19391937
`Initiated Worker with ${msg}: ${ArrayPrototypeJoin(errors,', ')}`,

‎lib/net.js‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,6 @@ const {
120120
ERR_SOCKET_CONNECTION_TIMEOUT,
121121
ERR_SOCKET_HANDLE_ADOPTED,
122122
ERR_WORKER_HANDLE_NOT_TRANSFERABLE,
123-
ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED,
124123
},
125124
genericNodeError,
126125
}=require('internal/errors');
@@ -1600,9 +1599,6 @@ Socket.prototype[kReinitializeHandle] = function reinitializeHandle(handle) {
16001599
// connecting or destroyed, and with no data already buffered in either
16011600
// direction (which would otherwise be lost on the sending side).
16021601
functionassertTransferableSocket(socket){
1603-
if(isWindows){
1604-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Socket');
1605-
}
16061602
consthandle=socket._handle;
16071603
if(handle==null||!(handleinstanceofTCP)||
16081604
socket.destroyed||socket.connecting||
@@ -2364,9 +2360,6 @@ Server.prototype._listen2 = setupListenHandle; // legacy alias
23642360
// underlying listening socket (and its pending accept queue) to that thread's
23652361
// event loop. Only a server bound to a live TCP handle can be transferred.
23662362
functionassertTransferableServer(server){
2367-
if(isWindows){
2368-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Server');
2369-
}
23702363
if(server._handle==null||!(server._handleinstanceofTCP)){
23712364
thrownewERR_WORKER_HANDLE_NOT_TRANSFERABLE('net.Server');
23722365
}

‎src/tcp_wrap.cc‎

Lines changed: 41 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -380,57 +380,66 @@ void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
380380
}
381381

382382
BaseObject::TransferMode TCPWrap::GetTransferMode() const {
383-
#ifdef _WIN32
384-
// Re-adopting a socket into another thread's event loop requires
385-
// re-associating it with that loop's IOCP, which needs same-process
386-
// WSADuplicateSocket support that is not wired up yet. The JS net layer
387-
// throws a clearer error before reaching here; this is the backstop for the
388-
// low-level `socket._handle` transfer path.
389-
return TransferMode::kDisallowCloneAndTransfer;
390-
#else
391383
// Only a live handle that is not already being torn down can be transferred.
392384
// Higher-level guards (no buffered reads, no pending writes) are enforced by
393385
// the JS net.Socket/net.Server layer before a handle reaches here.
394386
if (!HandleWrap::IsAlive(this) || IsHandleClosing())
395387
return TransferMode::kDisallowCloneAndTransfer;
396388
return TransferMode::kTransferable;
397-
#endif
398389
}
399390

400391
std::unique_ptr<worker::TransferData> TCPWrap::TransferForMessaging() {
401-
#ifdef _WIN32
402-
return {};
403-
#else
404392
CHECK_NE(GetTransferMode(), TransferMode::kDisallowCloneAndTransfer);
405393

406394
uv_os_fd_t fd;
407395
if (uv_fileno(reinterpret_cast<uv_handle_t*>(&handle_), &fd) != 0) return {};
408396

409-
// dup() the descriptor so the receiving event loop owns an independent
410-
// reference to the same socket. We then close the source handle, which
411-
// renders it unusable on this side (true transfer semantics) while the dup
412-
// keeps the underlying socket alive for the destination thread.
413-
int dup_fd = dup(fd);
414-
if (dup_fd < 0) return {};
397+
#ifdef _WIN32
398+
// A socket that is already associated with an IOCP cannot be associated with
399+
// another one. Create a same-process duplicate that is not associated with
400+
// any IOCP yet; uv_tcp_open() will associate it with the receiving loop.
401+
WSAPROTOCOL_INFOW protocol_info;
402+
uv_os_sock_t source_socket = reinterpret_cast<uv_os_sock_t>(fd);
403+
if (WSADuplicateSocketW(
404+
source_socket, GetCurrentProcessId(), &protocol_info) != 0) {
405+
return {};
406+
}
407+
uv_os_sock_t duplicate = WSASocketW(FROM_PROTOCOL_INFO,
408+
FROM_PROTOCOL_INFO,
409+
FROM_PROTOCOL_INFO,
410+
&protocol_info,
411+
0,
412+
WSA_FLAG_OVERLAPPED);
413+
if (duplicate == static_cast<uv_os_sock_t>(-1)) return {};
414+
#else
415+
// Unix threads share the descriptor table, so dup() creates an independent
416+
// reference to the same socket for the receiving event loop.
417+
uv_os_sock_t duplicate = dup(fd);
418+
if (duplicate < 0) return {};
419+
#endif
415420

416421
SocketType type =
417422
provider_type() == ProviderType::PROVIDER_TCPSERVERWRAP ? SERVER : SOCKET;
418423

419-
// Stop watching the fd and tear down the source handle.
424+
// Stop watching the original socket and tear down the source handle. The
425+
// duplicate keeps the underlying socket alive until the destination adopts
426+
// it, or until TransferData is destroyed if the message is not delivered.
420427
Close();
421428

422-
return std::make_unique<TransferData>(dup_fd, type);
423-
#endif
429+
return std::make_unique<TransferData>(duplicate, type);
424430
}
425431

426432
TCPWrap::TransferData::~TransferData() {
427-
// Only reached if the message was never delivered (e.g. the destination port
428-
// closed in flight); close the dup'd fd so it is not leaked.
429-
if (fd_ >= 0) {
433+
#ifdef _WIN32
434+
if (socket_ != static_cast<uv_os_sock_t>(-1))
435+
CHECK_EQ(0, closesocket(socket_));
436+
#else
437+
if (socket_ >= 0) {
430438
uv_fs_t req;
431-
CHECK_EQ(0, uv_fs_close(nullptr, &req, fd_, nullptr));
439+
CHECK_EQ(0, uv_fs_close(nullptr, &req, socket_, nullptr));
432440
uv_fs_req_cleanup(&req);
433441
}
442+
#endif
434443
}
435444

436445
BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
@@ -453,10 +462,14 @@ BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
453462
TCPWrap* wrap = BaseObject::Unwrap<TCPWrap>(obj);
454463
if (wrap == nullptr) return {};
455464

456-
if (uv_tcp_open(&wrap->handle_, fd_) != 0) return {};
465+
if (uv_tcp_open(&wrap->handle_, socket_) != 0) return {};
457466

458-
wrap->set_fd(fd_);
459-
fd_ = -1; // Ownership has been handed to the new handle.
467+
#ifdef _WIN32
468+
socket_ = static_cast<uv_os_sock_t>(-1);
469+
#else
470+
wrap->set_fd(socket_);
471+
socket_ = -1;
472+
#endif
460473
return BaseObjectPtr<BaseObject>(wrap);
461474
}
462475

‎src/tcp_wrap.h‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,10 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
6262
}
6363
}
6464

65-
// Transfer the underlying socket to another thread via .postMessage(). Within
66-
// a single process all threads share the same file descriptor table, so the
67-
// transfer dup()s the fd and re-adopts it (uv_tcp_open) in the receiving
68-
// event loop. This is the building block for distributing listening sockets
69-
// and accepted connections across worker_threads.
65+
// Transfer the underlying socket to another thread via .postMessage(). The
66+
// transfer duplicates the socket and re-adopts it (uv_tcp_open) in the
67+
// receiving event loop. This is the building block for distributing
68+
// listening sockets and accepted connections across worker_threads.
7069
BaseObject::TransferMode GetTransferMode() constoverride;
7170
std::unique_ptr<worker::TransferData> TransferForMessaging() override;
7271

@@ -75,7 +74,8 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
7574

7675
classTransferData : publicworker::TransferData {
7776
public:
78-
explicitTransferData(int fd, SocketType type) : fd_(fd), type_(type) {}
77+
explicitTransferData(uv_os_sock_t socket, SocketType type)
78+
: socket_(socket), type_(type) {}
7979
~TransferData() override;
8080

8181
BaseObjectPtr<BaseObject> Deserialize(
@@ -88,7 +88,7 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
8888
SET_SELF_SIZE(TransferData)
8989

9090
private:
91-
int fd_;
91+
uv_os_sock_t socket_;
9292
SocketType type_;
9393
};
9494

‎test/parallel/test-net-server-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

‎test/parallel/test-net-socket-transfer-worker-http.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
consthttp=require('http');

‎test/parallel/test-net-socket-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 9040b08

Browse files
mcollinaaduh95
authored andcommitted
net: support TCP handle transfer on Windows
Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #64460Fixes: #64456 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Stefan Stojanovic <stefan.stojanovic@janeasystems.com> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
1 parent 1216481 commit 9040b08

11 files changed

Lines changed: 50 additions & 77 deletions

‎doc/api/errors.md‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3512,14 +3512,6 @@ An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
35123512
via a `worker_threads``postMessage()` call while it was not in a transferable
35133513
state, for example because it had already started reading or had buffered data.
35143514

3515-
<aid="ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED"></a>
3516-
3517-
### `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`
3518-
3519-
An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
3520-
on a platform where moving the underlying handle between event loops is not
3521-
supported (currently Windows).
3522-
35233515
<aid="ERR_WORKER_INIT_FAILED"></a>
35243516

35253517
### `ERR_WORKER_INIT_FAILED`

‎doc/api/net.md‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -766,9 +766,7 @@ threads.
766766
The socket must be a freshly accepted or created TCP connection: it must still
767767
be attached to a live handle, must not be connecting or destroyed, and must not
768768
have started reading or have buffered data. Otherwise `postMessage()` throws
769-
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported, and only
770-
on Unix-like platforms; on Windows `postMessage()` throws
771-
`ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
769+
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported.
772770

773771
```cjs
774772
constnet=require('node:net');

‎doc/api/worker_threads.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1247,8 +1247,7 @@ freshly accepted or created TCP connection that has not yet started reading and
12471247
has no buffered data, otherwise `postMessage()` throws
12481248
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. This makes it possible to accept
12491249
connections on one thread and distribute them across a pool of worker threads.
1250-
Only TCP handles are supported, and only on Unix-like platforms; on Windows
1251-
`postMessage()` throws `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
1250+
Only TCP handles are supported.
12521251
12531252
If `value` contains {SharedArrayBuffer} instances, those are accessible
12541253
from either thread. They cannot be listed in `transferList`.

‎lib/internal/errors.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,8 +1932,6 @@ E('ERR_WORKER_HANDLE_NOT_TRANSFERABLE',
19321932
'%s cannot be transferred in its current state; it must be a freshly '+
19331933
'created or accepted handle that has not started reading and has no '+
19341934
'pending writes',Error);
1935-
E('ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED',
1936-
'Transferring a %s to another thread is not supported on this platform',Error);
19371935
E('ERR_WORKER_INIT_FAILED','Worker initialization failure: %s',Error);
19381936
E('ERR_WORKER_INVALID_EXEC_ARGV',(errors,msg='invalid execArgv flags')=>
19391937
`Initiated Worker with ${msg}: ${ArrayPrototypeJoin(errors,', ')}`,

‎lib/net.js‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,6 @@ const {
120120
ERR_SOCKET_CONNECTION_TIMEOUT,
121121
ERR_SOCKET_HANDLE_ADOPTED,
122122
ERR_WORKER_HANDLE_NOT_TRANSFERABLE,
123-
ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED,
124123
},
125124
genericNodeError,
126125
}=require('internal/errors');
@@ -1600,9 +1599,6 @@ Socket.prototype[kReinitializeHandle] = function reinitializeHandle(handle) {
16001599
// connecting or destroyed, and with no data already buffered in either
16011600
// direction (which would otherwise be lost on the sending side).
16021601
functionassertTransferableSocket(socket){
1603-
if(isWindows){
1604-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Socket');
1605-
}
16061602
consthandle=socket._handle;
16071603
if(handle==null||!(handleinstanceofTCP)||
16081604
socket.destroyed||socket.connecting||
@@ -2364,9 +2360,6 @@ Server.prototype._listen2 = setupListenHandle; // legacy alias
23642360
// underlying listening socket (and its pending accept queue) to that thread's
23652361
// event loop. Only a server bound to a live TCP handle can be transferred.
23662362
functionassertTransferableServer(server){
2367-
if(isWindows){
2368-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Server');
2369-
}
23702363
if(server._handle==null||!(server._handleinstanceofTCP)){
23712364
thrownewERR_WORKER_HANDLE_NOT_TRANSFERABLE('net.Server');
23722365
}

‎src/tcp_wrap.cc‎

Lines changed: 41 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -380,57 +380,66 @@ void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
380380
}
381381

382382
BaseObject::TransferMode TCPWrap::GetTransferMode() const {
383-
#ifdef _WIN32
384-
// Re-adopting a socket into another thread's event loop requires
385-
// re-associating it with that loop's IOCP, which needs same-process
386-
// WSADuplicateSocket support that is not wired up yet. The JS net layer
387-
// throws a clearer error before reaching here; this is the backstop for the
388-
// low-level `socket._handle` transfer path.
389-
return TransferMode::kDisallowCloneAndTransfer;
390-
#else
391383
// Only a live handle that is not already being torn down can be transferred.
392384
// Higher-level guards (no buffered reads, no pending writes) are enforced by
393385
// the JS net.Socket/net.Server layer before a handle reaches here.
394386
if (!HandleWrap::IsAlive(this) || IsHandleClosing())
395387
return TransferMode::kDisallowCloneAndTransfer;
396388
return TransferMode::kTransferable;
397-
#endif
398389
}
399390

400391
std::unique_ptr<worker::TransferData> TCPWrap::TransferForMessaging() {
401-
#ifdef _WIN32
402-
return {};
403-
#else
404392
CHECK_NE(GetTransferMode(), TransferMode::kDisallowCloneAndTransfer);
405393

406394
uv_os_fd_t fd;
407395
if (uv_fileno(reinterpret_cast<uv_handle_t*>(&handle_), &fd) != 0) return {};
408396

409-
// dup() the descriptor so the receiving event loop owns an independent
410-
// reference to the same socket. We then close the source handle, which
411-
// renders it unusable on this side (true transfer semantics) while the dup
412-
// keeps the underlying socket alive for the destination thread.
413-
int dup_fd = dup(fd);
414-
if (dup_fd < 0) return {};
397+
#ifdef _WIN32
398+
// A socket that is already associated with an IOCP cannot be associated with
399+
// another one. Create a same-process duplicate that is not associated with
400+
// any IOCP yet; uv_tcp_open() will associate it with the receiving loop.
401+
WSAPROTOCOL_INFOW protocol_info;
402+
uv_os_sock_t source_socket = reinterpret_cast<uv_os_sock_t>(fd);
403+
if (WSADuplicateSocketW(
404+
source_socket, GetCurrentProcessId(), &protocol_info) != 0) {
405+
return {};
406+
}
407+
uv_os_sock_t duplicate = WSASocketW(FROM_PROTOCOL_INFO,
408+
FROM_PROTOCOL_INFO,
409+
FROM_PROTOCOL_INFO,
410+
&protocol_info,
411+
0,
412+
WSA_FLAG_OVERLAPPED);
413+
if (duplicate == static_cast<uv_os_sock_t>(-1)) return {};
414+
#else
415+
// Unix threads share the descriptor table, so dup() creates an independent
416+
// reference to the same socket for the receiving event loop.
417+
uv_os_sock_t duplicate = dup(fd);
418+
if (duplicate < 0) return {};
419+
#endif
415420

416421
SocketType type =
417422
provider_type() == ProviderType::PROVIDER_TCPSERVERWRAP ? SERVER : SOCKET;
418423

419-
// Stop watching the fd and tear down the source handle.
424+
// Stop watching the original socket and tear down the source handle. The
425+
// duplicate keeps the underlying socket alive until the destination adopts
426+
// it, or until TransferData is destroyed if the message is not delivered.
420427
Close();
421428

422-
return std::make_unique<TransferData>(dup_fd, type);
423-
#endif
429+
return std::make_unique<TransferData>(duplicate, type);
424430
}
425431

426432
TCPWrap::TransferData::~TransferData() {
427-
// Only reached if the message was never delivered (e.g. the destination port
428-
// closed in flight); close the dup'd fd so it is not leaked.
429-
if (fd_ >= 0) {
433+
#ifdef _WIN32
434+
if (socket_ != static_cast<uv_os_sock_t>(-1))
435+
CHECK_EQ(0, closesocket(socket_));
436+
#else
437+
if (socket_ >= 0) {
430438
uv_fs_t req;
431-
CHECK_EQ(0, uv_fs_close(nullptr, &req, fd_, nullptr));
439+
CHECK_EQ(0, uv_fs_close(nullptr, &req, socket_, nullptr));
432440
uv_fs_req_cleanup(&req);
433441
}
442+
#endif
434443
}
435444

436445
BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
@@ -453,10 +462,14 @@ BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
453462
TCPWrap* wrap = BaseObject::Unwrap<TCPWrap>(obj);
454463
if (wrap == nullptr) return {};
455464

456-
if (uv_tcp_open(&wrap->handle_, fd_) != 0) return {};
465+
if (uv_tcp_open(&wrap->handle_, socket_) != 0) return {};
457466

458-
wrap->set_fd(fd_);
459-
fd_ = -1; // Ownership has been handed to the new handle.
467+
#ifdef _WIN32
468+
socket_ = static_cast<uv_os_sock_t>(-1);
469+
#else
470+
wrap->set_fd(socket_);
471+
socket_ = -1;
472+
#endif
460473
return BaseObjectPtr<BaseObject>(wrap);
461474
}
462475

‎src/tcp_wrap.h‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,10 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
6262
}
6363
}
6464

65-
// Transfer the underlying socket to another thread via .postMessage(). Within
66-
// a single process all threads share the same file descriptor table, so the
67-
// transfer dup()s the fd and re-adopts it (uv_tcp_open) in the receiving
68-
// event loop. This is the building block for distributing listening sockets
69-
// and accepted connections across worker_threads.
65+
// Transfer the underlying socket to another thread via .postMessage(). The
66+
// transfer duplicates the socket and re-adopts it (uv_tcp_open) in the
67+
// receiving event loop. This is the building block for distributing
68+
// listening sockets and accepted connections across worker_threads.
7069
BaseObject::TransferMode GetTransferMode() constoverride;
7170
std::unique_ptr<worker::TransferData> TransferForMessaging() override;
7271

@@ -75,7 +74,8 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
7574

7675
classTransferData : publicworker::TransferData {
7776
public:
78-
explicitTransferData(int fd, SocketType type) : fd_(fd), type_(type) {}
77+
explicitTransferData(uv_os_sock_t socket, SocketType type)
78+
: socket_(socket), type_(type) {}
7979
~TransferData() override;
8080

8181
BaseObjectPtr<BaseObject> Deserialize(
@@ -88,7 +88,7 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
8888
SET_SELF_SIZE(TransferData)
8989

9090
private:
91-
int fd_;
91+
uv_os_sock_t socket_;
9292
SocketType type_;
9393
};
9494

‎test/parallel/test-net-server-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

‎test/parallel/test-net-socket-transfer-worker-http.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
consthttp=require('http');

‎test/parallel/test-net-socket-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 9040b08

Browse files
mcollinaaduh95
authored andcommitted
net: support TCP handle transfer on Windows
Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #64460Fixes: #64456 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Stefan Stojanovic <stefan.stojanovic@janeasystems.com> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
1 parent 1216481 commit 9040b08

11 files changed

Lines changed: 50 additions & 77 deletions

‎doc/api/errors.md‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3512,14 +3512,6 @@ An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
35123512
via a `worker_threads``postMessage()` call while it was not in a transferable
35133513
state, for example because it had already started reading or had buffered data.
35143514

3515-
<aid="ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED"></a>
3516-
3517-
### `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`
3518-
3519-
An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
3520-
on a platform where moving the underlying handle between event loops is not
3521-
supported (currently Windows).
3522-
35233515
<aid="ERR_WORKER_INIT_FAILED"></a>
35243516

35253517
### `ERR_WORKER_INIT_FAILED`

‎doc/api/net.md‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -766,9 +766,7 @@ threads.
766766
The socket must be a freshly accepted or created TCP connection: it must still
767767
be attached to a live handle, must not be connecting or destroyed, and must not
768768
have started reading or have buffered data. Otherwise `postMessage()` throws
769-
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported, and only
770-
on Unix-like platforms; on Windows `postMessage()` throws
771-
`ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
769+
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported.
772770

773771
```cjs
774772
constnet=require('node:net');

‎doc/api/worker_threads.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1247,8 +1247,7 @@ freshly accepted or created TCP connection that has not yet started reading and
12471247
has no buffered data, otherwise `postMessage()` throws
12481248
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. This makes it possible to accept
12491249
connections on one thread and distribute them across a pool of worker threads.
1250-
Only TCP handles are supported, and only on Unix-like platforms; on Windows
1251-
`postMessage()` throws `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
1250+
Only TCP handles are supported.
12521251
12531252
If `value` contains {SharedArrayBuffer} instances, those are accessible
12541253
from either thread. They cannot be listed in `transferList`.

‎lib/internal/errors.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,8 +1932,6 @@ E('ERR_WORKER_HANDLE_NOT_TRANSFERABLE',
19321932
'%s cannot be transferred in its current state; it must be a freshly '+
19331933
'created or accepted handle that has not started reading and has no '+
19341934
'pending writes',Error);
1935-
E('ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED',
1936-
'Transferring a %s to another thread is not supported on this platform',Error);
19371935
E('ERR_WORKER_INIT_FAILED','Worker initialization failure: %s',Error);
19381936
E('ERR_WORKER_INVALID_EXEC_ARGV',(errors,msg='invalid execArgv flags')=>
19391937
`Initiated Worker with ${msg}: ${ArrayPrototypeJoin(errors,', ')}`,

‎lib/net.js‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,6 @@ const {
120120
ERR_SOCKET_CONNECTION_TIMEOUT,
121121
ERR_SOCKET_HANDLE_ADOPTED,
122122
ERR_WORKER_HANDLE_NOT_TRANSFERABLE,
123-
ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED,
124123
},
125124
genericNodeError,
126125
}=require('internal/errors');
@@ -1600,9 +1599,6 @@ Socket.prototype[kReinitializeHandle] = function reinitializeHandle(handle) {
16001599
// connecting or destroyed, and with no data already buffered in either
16011600
// direction (which would otherwise be lost on the sending side).
16021601
functionassertTransferableSocket(socket){
1603-
if(isWindows){
1604-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Socket');
1605-
}
16061602
consthandle=socket._handle;
16071603
if(handle==null||!(handleinstanceofTCP)||
16081604
socket.destroyed||socket.connecting||
@@ -2364,9 +2360,6 @@ Server.prototype._listen2 = setupListenHandle; // legacy alias
23642360
// underlying listening socket (and its pending accept queue) to that thread's
23652361
// event loop. Only a server bound to a live TCP handle can be transferred.
23662362
functionassertTransferableServer(server){
2367-
if(isWindows){
2368-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Server');
2369-
}
23702363
if(server._handle==null||!(server._handleinstanceofTCP)){
23712364
thrownewERR_WORKER_HANDLE_NOT_TRANSFERABLE('net.Server');
23722365
}

‎src/tcp_wrap.cc‎

Lines changed: 41 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -380,57 +380,66 @@ void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
380380
}
381381

382382
BaseObject::TransferMode TCPWrap::GetTransferMode() const {
383-
#ifdef _WIN32
384-
// Re-adopting a socket into another thread's event loop requires
385-
// re-associating it with that loop's IOCP, which needs same-process
386-
// WSADuplicateSocket support that is not wired up yet. The JS net layer
387-
// throws a clearer error before reaching here; this is the backstop for the
388-
// low-level `socket._handle` transfer path.
389-
return TransferMode::kDisallowCloneAndTransfer;
390-
#else
391383
// Only a live handle that is not already being torn down can be transferred.
392384
// Higher-level guards (no buffered reads, no pending writes) are enforced by
393385
// the JS net.Socket/net.Server layer before a handle reaches here.
394386
if (!HandleWrap::IsAlive(this) || IsHandleClosing())
395387
return TransferMode::kDisallowCloneAndTransfer;
396388
return TransferMode::kTransferable;
397-
#endif
398389
}
399390

400391
std::unique_ptr<worker::TransferData> TCPWrap::TransferForMessaging() {
401-
#ifdef _WIN32
402-
return {};
403-
#else
404392
CHECK_NE(GetTransferMode(), TransferMode::kDisallowCloneAndTransfer);
405393

406394
uv_os_fd_t fd;
407395
if (uv_fileno(reinterpret_cast<uv_handle_t*>(&handle_), &fd) != 0) return {};
408396

409-
// dup() the descriptor so the receiving event loop owns an independent
410-
// reference to the same socket. We then close the source handle, which
411-
// renders it unusable on this side (true transfer semantics) while the dup
412-
// keeps the underlying socket alive for the destination thread.
413-
int dup_fd = dup(fd);
414-
if (dup_fd < 0) return {};
397+
#ifdef _WIN32
398+
// A socket that is already associated with an IOCP cannot be associated with
399+
// another one. Create a same-process duplicate that is not associated with
400+
// any IOCP yet; uv_tcp_open() will associate it with the receiving loop.
401+
WSAPROTOCOL_INFOW protocol_info;
402+
uv_os_sock_t source_socket = reinterpret_cast<uv_os_sock_t>(fd);
403+
if (WSADuplicateSocketW(
404+
source_socket, GetCurrentProcessId(), &protocol_info) != 0) {
405+
return {};
406+
}
407+
uv_os_sock_t duplicate = WSASocketW(FROM_PROTOCOL_INFO,
408+
FROM_PROTOCOL_INFO,
409+
FROM_PROTOCOL_INFO,
410+
&protocol_info,
411+
0,
412+
WSA_FLAG_OVERLAPPED);
413+
if (duplicate == static_cast<uv_os_sock_t>(-1)) return {};
414+
#else
415+
// Unix threads share the descriptor table, so dup() creates an independent
416+
// reference to the same socket for the receiving event loop.
417+
uv_os_sock_t duplicate = dup(fd);
418+
if (duplicate < 0) return {};
419+
#endif
415420

416421
SocketType type =
417422
provider_type() == ProviderType::PROVIDER_TCPSERVERWRAP ? SERVER : SOCKET;
418423

419-
// Stop watching the fd and tear down the source handle.
424+
// Stop watching the original socket and tear down the source handle. The
425+
// duplicate keeps the underlying socket alive until the destination adopts
426+
// it, or until TransferData is destroyed if the message is not delivered.
420427
Close();
421428

422-
return std::make_unique<TransferData>(dup_fd, type);
423-
#endif
429+
return std::make_unique<TransferData>(duplicate, type);
424430
}
425431

426432
TCPWrap::TransferData::~TransferData() {
427-
// Only reached if the message was never delivered (e.g. the destination port
428-
// closed in flight); close the dup'd fd so it is not leaked.
429-
if (fd_ >= 0) {
433+
#ifdef _WIN32
434+
if (socket_ != static_cast<uv_os_sock_t>(-1))
435+
CHECK_EQ(0, closesocket(socket_));
436+
#else
437+
if (socket_ >= 0) {
430438
uv_fs_t req;
431-
CHECK_EQ(0, uv_fs_close(nullptr, &req, fd_, nullptr));
439+
CHECK_EQ(0, uv_fs_close(nullptr, &req, socket_, nullptr));
432440
uv_fs_req_cleanup(&req);
433441
}
442+
#endif
434443
}
435444

436445
BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
@@ -453,10 +462,14 @@ BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
453462
TCPWrap* wrap = BaseObject::Unwrap<TCPWrap>(obj);
454463
if (wrap == nullptr) return {};
455464

456-
if (uv_tcp_open(&wrap->handle_, fd_) != 0) return {};
465+
if (uv_tcp_open(&wrap->handle_, socket_) != 0) return {};
457466

458-
wrap->set_fd(fd_);
459-
fd_ = -1; // Ownership has been handed to the new handle.
467+
#ifdef _WIN32
468+
socket_ = static_cast<uv_os_sock_t>(-1);
469+
#else
470+
wrap->set_fd(socket_);
471+
socket_ = -1;
472+
#endif
460473
return BaseObjectPtr<BaseObject>(wrap);
461474
}
462475

‎src/tcp_wrap.h‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,10 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
6262
}
6363
}
6464

65-
// Transfer the underlying socket to another thread via .postMessage(). Within
66-
// a single process all threads share the same file descriptor table, so the
67-
// transfer dup()s the fd and re-adopts it (uv_tcp_open) in the receiving
68-
// event loop. This is the building block for distributing listening sockets
69-
// and accepted connections across worker_threads.
65+
// Transfer the underlying socket to another thread via .postMessage(). The
66+
// transfer duplicates the socket and re-adopts it (uv_tcp_open) in the
67+
// receiving event loop. This is the building block for distributing
68+
// listening sockets and accepted connections across worker_threads.
7069
BaseObject::TransferMode GetTransferMode() constoverride;
7170
std::unique_ptr<worker::TransferData> TransferForMessaging() override;
7271

@@ -75,7 +74,8 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
7574

7675
classTransferData : publicworker::TransferData {
7776
public:
78-
explicitTransferData(int fd, SocketType type) : fd_(fd), type_(type) {}
77+
explicitTransferData(uv_os_sock_t socket, SocketType type)
78+
: socket_(socket), type_(type) {}
7979
~TransferData() override;
8080

8181
BaseObjectPtr<BaseObject> Deserialize(
@@ -88,7 +88,7 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
8888
SET_SELF_SIZE(TransferData)
8989

9090
private:
91-
int fd_;
91+
uv_os_sock_t socket_;
9292
SocketType type_;
9393
};
9494

‎test/parallel/test-net-server-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

‎test/parallel/test-net-socket-transfer-worker-http.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
consthttp=require('http');

‎test/parallel/test-net-socket-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 9040b08

Browse files
mcollinaaduh95
authored andcommitted
net: support TCP handle transfer on Windows
Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #64460Fixes: #64456 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Stefan Stojanovic <stefan.stojanovic@janeasystems.com> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
1 parent 1216481 commit 9040b08

11 files changed

Lines changed: 50 additions & 77 deletions

‎doc/api/errors.md‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3512,14 +3512,6 @@ An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
35123512
via a `worker_threads``postMessage()` call while it was not in a transferable
35133513
state, for example because it had already started reading or had buffered data.
35143514

3515-
<aid="ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED"></a>
3516-
3517-
### `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`
3518-
3519-
An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
3520-
on a platform where moving the underlying handle between event loops is not
3521-
supported (currently Windows).
3522-
35233515
<aid="ERR_WORKER_INIT_FAILED"></a>
35243516

35253517
### `ERR_WORKER_INIT_FAILED`

‎doc/api/net.md‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -766,9 +766,7 @@ threads.
766766
The socket must be a freshly accepted or created TCP connection: it must still
767767
be attached to a live handle, must not be connecting or destroyed, and must not
768768
have started reading or have buffered data. Otherwise `postMessage()` throws
769-
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported, and only
770-
on Unix-like platforms; on Windows `postMessage()` throws
771-
`ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
769+
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported.
772770

773771
```cjs
774772
constnet=require('node:net');

‎doc/api/worker_threads.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1247,8 +1247,7 @@ freshly accepted or created TCP connection that has not yet started reading and
12471247
has no buffered data, otherwise `postMessage()` throws
12481248
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. This makes it possible to accept
12491249
connections on one thread and distribute them across a pool of worker threads.
1250-
Only TCP handles are supported, and only on Unix-like platforms; on Windows
1251-
`postMessage()` throws `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
1250+
Only TCP handles are supported.
12521251
12531252
If `value` contains {SharedArrayBuffer} instances, those are accessible
12541253
from either thread. They cannot be listed in `transferList`.

‎lib/internal/errors.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,8 +1932,6 @@ E('ERR_WORKER_HANDLE_NOT_TRANSFERABLE',
19321932
'%s cannot be transferred in its current state; it must be a freshly '+
19331933
'created or accepted handle that has not started reading and has no '+
19341934
'pending writes',Error);
1935-
E('ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED',
1936-
'Transferring a %s to another thread is not supported on this platform',Error);
19371935
E('ERR_WORKER_INIT_FAILED','Worker initialization failure: %s',Error);
19381936
E('ERR_WORKER_INVALID_EXEC_ARGV',(errors,msg='invalid execArgv flags')=>
19391937
`Initiated Worker with ${msg}: ${ArrayPrototypeJoin(errors,', ')}`,

‎lib/net.js‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,6 @@ const {
120120
ERR_SOCKET_CONNECTION_TIMEOUT,
121121
ERR_SOCKET_HANDLE_ADOPTED,
122122
ERR_WORKER_HANDLE_NOT_TRANSFERABLE,
123-
ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED,
124123
},
125124
genericNodeError,
126125
}=require('internal/errors');
@@ -1600,9 +1599,6 @@ Socket.prototype[kReinitializeHandle] = function reinitializeHandle(handle) {
16001599
// connecting or destroyed, and with no data already buffered in either
16011600
// direction (which would otherwise be lost on the sending side).
16021601
functionassertTransferableSocket(socket){
1603-
if(isWindows){
1604-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Socket');
1605-
}
16061602
consthandle=socket._handle;
16071603
if(handle==null||!(handleinstanceofTCP)||
16081604
socket.destroyed||socket.connecting||
@@ -2364,9 +2360,6 @@ Server.prototype._listen2 = setupListenHandle; // legacy alias
23642360
// underlying listening socket (and its pending accept queue) to that thread's
23652361
// event loop. Only a server bound to a live TCP handle can be transferred.
23662362
functionassertTransferableServer(server){
2367-
if(isWindows){
2368-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Server');
2369-
}
23702363
if(server._handle==null||!(server._handleinstanceofTCP)){
23712364
thrownewERR_WORKER_HANDLE_NOT_TRANSFERABLE('net.Server');
23722365
}

‎src/tcp_wrap.cc‎

Lines changed: 41 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -380,57 +380,66 @@ void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
380380
}
381381

382382
BaseObject::TransferMode TCPWrap::GetTransferMode() const {
383-
#ifdef _WIN32
384-
// Re-adopting a socket into another thread's event loop requires
385-
// re-associating it with that loop's IOCP, which needs same-process
386-
// WSADuplicateSocket support that is not wired up yet. The JS net layer
387-
// throws a clearer error before reaching here; this is the backstop for the
388-
// low-level `socket._handle` transfer path.
389-
return TransferMode::kDisallowCloneAndTransfer;
390-
#else
391383
// Only a live handle that is not already being torn down can be transferred.
392384
// Higher-level guards (no buffered reads, no pending writes) are enforced by
393385
// the JS net.Socket/net.Server layer before a handle reaches here.
394386
if (!HandleWrap::IsAlive(this) || IsHandleClosing())
395387
return TransferMode::kDisallowCloneAndTransfer;
396388
return TransferMode::kTransferable;
397-
#endif
398389
}
399390

400391
std::unique_ptr<worker::TransferData> TCPWrap::TransferForMessaging() {
401-
#ifdef _WIN32
402-
return {};
403-
#else
404392
CHECK_NE(GetTransferMode(), TransferMode::kDisallowCloneAndTransfer);
405393

406394
uv_os_fd_t fd;
407395
if (uv_fileno(reinterpret_cast<uv_handle_t*>(&handle_), &fd) != 0) return {};
408396

409-
// dup() the descriptor so the receiving event loop owns an independent
410-
// reference to the same socket. We then close the source handle, which
411-
// renders it unusable on this side (true transfer semantics) while the dup
412-
// keeps the underlying socket alive for the destination thread.
413-
int dup_fd = dup(fd);
414-
if (dup_fd < 0) return {};
397+
#ifdef _WIN32
398+
// A socket that is already associated with an IOCP cannot be associated with
399+
// another one. Create a same-process duplicate that is not associated with
400+
// any IOCP yet; uv_tcp_open() will associate it with the receiving loop.
401+
WSAPROTOCOL_INFOW protocol_info;
402+
uv_os_sock_t source_socket = reinterpret_cast<uv_os_sock_t>(fd);
403+
if (WSADuplicateSocketW(
404+
source_socket, GetCurrentProcessId(), &protocol_info) != 0) {
405+
return {};
406+
}
407+
uv_os_sock_t duplicate = WSASocketW(FROM_PROTOCOL_INFO,
408+
FROM_PROTOCOL_INFO,
409+
FROM_PROTOCOL_INFO,
410+
&protocol_info,
411+
0,
412+
WSA_FLAG_OVERLAPPED);
413+
if (duplicate == static_cast<uv_os_sock_t>(-1)) return {};
414+
#else
415+
// Unix threads share the descriptor table, so dup() creates an independent
416+
// reference to the same socket for the receiving event loop.
417+
uv_os_sock_t duplicate = dup(fd);
418+
if (duplicate < 0) return {};
419+
#endif
415420

416421
SocketType type =
417422
provider_type() == ProviderType::PROVIDER_TCPSERVERWRAP ? SERVER : SOCKET;
418423

419-
// Stop watching the fd and tear down the source handle.
424+
// Stop watching the original socket and tear down the source handle. The
425+
// duplicate keeps the underlying socket alive until the destination adopts
426+
// it, or until TransferData is destroyed if the message is not delivered.
420427
Close();
421428

422-
return std::make_unique<TransferData>(dup_fd, type);
423-
#endif
429+
return std::make_unique<TransferData>(duplicate, type);
424430
}
425431

426432
TCPWrap::TransferData::~TransferData() {
427-
// Only reached if the message was never delivered (e.g. the destination port
428-
// closed in flight); close the dup'd fd so it is not leaked.
429-
if (fd_ >= 0) {
433+
#ifdef _WIN32
434+
if (socket_ != static_cast<uv_os_sock_t>(-1))
435+
CHECK_EQ(0, closesocket(socket_));
436+
#else
437+
if (socket_ >= 0) {
430438
uv_fs_t req;
431-
CHECK_EQ(0, uv_fs_close(nullptr, &req, fd_, nullptr));
439+
CHECK_EQ(0, uv_fs_close(nullptr, &req, socket_, nullptr));
432440
uv_fs_req_cleanup(&req);
433441
}
442+
#endif
434443
}
435444

436445
BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
@@ -453,10 +462,14 @@ BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
453462
TCPWrap* wrap = BaseObject::Unwrap<TCPWrap>(obj);
454463
if (wrap == nullptr) return {};
455464

456-
if (uv_tcp_open(&wrap->handle_, fd_) != 0) return {};
465+
if (uv_tcp_open(&wrap->handle_, socket_) != 0) return {};
457466

458-
wrap->set_fd(fd_);
459-
fd_ = -1; // Ownership has been handed to the new handle.
467+
#ifdef _WIN32
468+
socket_ = static_cast<uv_os_sock_t>(-1);
469+
#else
470+
wrap->set_fd(socket_);
471+
socket_ = -1;
472+
#endif
460473
return BaseObjectPtr<BaseObject>(wrap);
461474
}
462475

‎src/tcp_wrap.h‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,10 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
6262
}
6363
}
6464

65-
// Transfer the underlying socket to another thread via .postMessage(). Within
66-
// a single process all threads share the same file descriptor table, so the
67-
// transfer dup()s the fd and re-adopts it (uv_tcp_open) in the receiving
68-
// event loop. This is the building block for distributing listening sockets
69-
// and accepted connections across worker_threads.
65+
// Transfer the underlying socket to another thread via .postMessage(). The
66+
// transfer duplicates the socket and re-adopts it (uv_tcp_open) in the
67+
// receiving event loop. This is the building block for distributing
68+
// listening sockets and accepted connections across worker_threads.
7069
BaseObject::TransferMode GetTransferMode() constoverride;
7170
std::unique_ptr<worker::TransferData> TransferForMessaging() override;
7271

@@ -75,7 +74,8 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
7574

7675
classTransferData : publicworker::TransferData {
7776
public:
78-
explicitTransferData(int fd, SocketType type) : fd_(fd), type_(type) {}
77+
explicitTransferData(uv_os_sock_t socket, SocketType type)
78+
: socket_(socket), type_(type) {}
7979
~TransferData() override;
8080

8181
BaseObjectPtr<BaseObject> Deserialize(
@@ -88,7 +88,7 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
8888
SET_SELF_SIZE(TransferData)
8989

9090
private:
91-
int fd_;
91+
uv_os_sock_t socket_;
9292
SocketType type_;
9393
};
9494

‎test/parallel/test-net-server-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

‎test/parallel/test-net-socket-transfer-worker-http.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
consthttp=require('http');

‎test/parallel/test-net-socket-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 9040b08

Browse files
mcollinaaduh95
authored andcommitted
net: support TCP handle transfer on Windows
Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #64460Fixes: #64456 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Stefan Stojanovic <stefan.stojanovic@janeasystems.com> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
1 parent 1216481 commit 9040b08

11 files changed

Lines changed: 50 additions & 77 deletions

‎doc/api/errors.md‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3512,14 +3512,6 @@ An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
35123512
via a `worker_threads``postMessage()` call while it was not in a transferable
35133513
state, for example because it had already started reading or had buffered data.
35143514

3515-
<aid="ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED"></a>
3516-
3517-
### `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`
3518-
3519-
An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
3520-
on a platform where moving the underlying handle between event loops is not
3521-
supported (currently Windows).
3522-
35233515
<aid="ERR_WORKER_INIT_FAILED"></a>
35243516

35253517
### `ERR_WORKER_INIT_FAILED`

‎doc/api/net.md‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -766,9 +766,7 @@ threads.
766766
The socket must be a freshly accepted or created TCP connection: it must still
767767
be attached to a live handle, must not be connecting or destroyed, and must not
768768
have started reading or have buffered data. Otherwise `postMessage()` throws
769-
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported, and only
770-
on Unix-like platforms; on Windows `postMessage()` throws
771-
`ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
769+
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported.
772770

773771
```cjs
774772
constnet=require('node:net');

‎doc/api/worker_threads.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1247,8 +1247,7 @@ freshly accepted or created TCP connection that has not yet started reading and
12471247
has no buffered data, otherwise `postMessage()` throws
12481248
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. This makes it possible to accept
12491249
connections on one thread and distribute them across a pool of worker threads.
1250-
Only TCP handles are supported, and only on Unix-like platforms; on Windows
1251-
`postMessage()` throws `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
1250+
Only TCP handles are supported.
12521251
12531252
If `value` contains {SharedArrayBuffer} instances, those are accessible
12541253
from either thread. They cannot be listed in `transferList`.

‎lib/internal/errors.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,8 +1932,6 @@ E('ERR_WORKER_HANDLE_NOT_TRANSFERABLE',
19321932
'%s cannot be transferred in its current state; it must be a freshly '+
19331933
'created or accepted handle that has not started reading and has no '+
19341934
'pending writes',Error);
1935-
E('ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED',
1936-
'Transferring a %s to another thread is not supported on this platform',Error);
19371935
E('ERR_WORKER_INIT_FAILED','Worker initialization failure: %s',Error);
19381936
E('ERR_WORKER_INVALID_EXEC_ARGV',(errors,msg='invalid execArgv flags')=>
19391937
`Initiated Worker with ${msg}: ${ArrayPrototypeJoin(errors,', ')}`,

‎lib/net.js‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,6 @@ const {
120120
ERR_SOCKET_CONNECTION_TIMEOUT,
121121
ERR_SOCKET_HANDLE_ADOPTED,
122122
ERR_WORKER_HANDLE_NOT_TRANSFERABLE,
123-
ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED,
124123
},
125124
genericNodeError,
126125
}=require('internal/errors');
@@ -1600,9 +1599,6 @@ Socket.prototype[kReinitializeHandle] = function reinitializeHandle(handle) {
16001599
// connecting or destroyed, and with no data already buffered in either
16011600
// direction (which would otherwise be lost on the sending side).
16021601
functionassertTransferableSocket(socket){
1603-
if(isWindows){
1604-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Socket');
1605-
}
16061602
consthandle=socket._handle;
16071603
if(handle==null||!(handleinstanceofTCP)||
16081604
socket.destroyed||socket.connecting||
@@ -2364,9 +2360,6 @@ Server.prototype._listen2 = setupListenHandle; // legacy alias
23642360
// underlying listening socket (and its pending accept queue) to that thread's
23652361
// event loop. Only a server bound to a live TCP handle can be transferred.
23662362
functionassertTransferableServer(server){
2367-
if(isWindows){
2368-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Server');
2369-
}
23702363
if(server._handle==null||!(server._handleinstanceofTCP)){
23712364
thrownewERR_WORKER_HANDLE_NOT_TRANSFERABLE('net.Server');
23722365
}

‎src/tcp_wrap.cc‎

Lines changed: 41 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -380,57 +380,66 @@ void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
380380
}
381381

382382
BaseObject::TransferMode TCPWrap::GetTransferMode() const {
383-
#ifdef _WIN32
384-
// Re-adopting a socket into another thread's event loop requires
385-
// re-associating it with that loop's IOCP, which needs same-process
386-
// WSADuplicateSocket support that is not wired up yet. The JS net layer
387-
// throws a clearer error before reaching here; this is the backstop for the
388-
// low-level `socket._handle` transfer path.
389-
return TransferMode::kDisallowCloneAndTransfer;
390-
#else
391383
// Only a live handle that is not already being torn down can be transferred.
392384
// Higher-level guards (no buffered reads, no pending writes) are enforced by
393385
// the JS net.Socket/net.Server layer before a handle reaches here.
394386
if (!HandleWrap::IsAlive(this) || IsHandleClosing())
395387
return TransferMode::kDisallowCloneAndTransfer;
396388
return TransferMode::kTransferable;
397-
#endif
398389
}
399390

400391
std::unique_ptr<worker::TransferData> TCPWrap::TransferForMessaging() {
401-
#ifdef _WIN32
402-
return {};
403-
#else
404392
CHECK_NE(GetTransferMode(), TransferMode::kDisallowCloneAndTransfer);
405393

406394
uv_os_fd_t fd;
407395
if (uv_fileno(reinterpret_cast<uv_handle_t*>(&handle_), &fd) != 0) return {};
408396

409-
// dup() the descriptor so the receiving event loop owns an independent
410-
// reference to the same socket. We then close the source handle, which
411-
// renders it unusable on this side (true transfer semantics) while the dup
412-
// keeps the underlying socket alive for the destination thread.
413-
int dup_fd = dup(fd);
414-
if (dup_fd < 0) return {};
397+
#ifdef _WIN32
398+
// A socket that is already associated with an IOCP cannot be associated with
399+
// another one. Create a same-process duplicate that is not associated with
400+
// any IOCP yet; uv_tcp_open() will associate it with the receiving loop.
401+
WSAPROTOCOL_INFOW protocol_info;
402+
uv_os_sock_t source_socket = reinterpret_cast<uv_os_sock_t>(fd);
403+
if (WSADuplicateSocketW(
404+
source_socket, GetCurrentProcessId(), &protocol_info) != 0) {
405+
return {};
406+
}
407+
uv_os_sock_t duplicate = WSASocketW(FROM_PROTOCOL_INFO,
408+
FROM_PROTOCOL_INFO,
409+
FROM_PROTOCOL_INFO,
410+
&protocol_info,
411+
0,
412+
WSA_FLAG_OVERLAPPED);
413+
if (duplicate == static_cast<uv_os_sock_t>(-1)) return {};
414+
#else
415+
// Unix threads share the descriptor table, so dup() creates an independent
416+
// reference to the same socket for the receiving event loop.
417+
uv_os_sock_t duplicate = dup(fd);
418+
if (duplicate < 0) return {};
419+
#endif
415420

416421
SocketType type =
417422
provider_type() == ProviderType::PROVIDER_TCPSERVERWRAP ? SERVER : SOCKET;
418423

419-
// Stop watching the fd and tear down the source handle.
424+
// Stop watching the original socket and tear down the source handle. The
425+
// duplicate keeps the underlying socket alive until the destination adopts
426+
// it, or until TransferData is destroyed if the message is not delivered.
420427
Close();
421428

422-
return std::make_unique<TransferData>(dup_fd, type);
423-
#endif
429+
return std::make_unique<TransferData>(duplicate, type);
424430
}
425431

426432
TCPWrap::TransferData::~TransferData() {
427-
// Only reached if the message was never delivered (e.g. the destination port
428-
// closed in flight); close the dup'd fd so it is not leaked.
429-
if (fd_ >= 0) {
433+
#ifdef _WIN32
434+
if (socket_ != static_cast<uv_os_sock_t>(-1))
435+
CHECK_EQ(0, closesocket(socket_));
436+
#else
437+
if (socket_ >= 0) {
430438
uv_fs_t req;
431-
CHECK_EQ(0, uv_fs_close(nullptr, &req, fd_, nullptr));
439+
CHECK_EQ(0, uv_fs_close(nullptr, &req, socket_, nullptr));
432440
uv_fs_req_cleanup(&req);
433441
}
442+
#endif
434443
}
435444

436445
BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
@@ -453,10 +462,14 @@ BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
453462
TCPWrap* wrap = BaseObject::Unwrap<TCPWrap>(obj);
454463
if (wrap == nullptr) return {};
455464

456-
if (uv_tcp_open(&wrap->handle_, fd_) != 0) return {};
465+
if (uv_tcp_open(&wrap->handle_, socket_) != 0) return {};
457466

458-
wrap->set_fd(fd_);
459-
fd_ = -1; // Ownership has been handed to the new handle.
467+
#ifdef _WIN32
468+
socket_ = static_cast<uv_os_sock_t>(-1);
469+
#else
470+
wrap->set_fd(socket_);
471+
socket_ = -1;
472+
#endif
460473
return BaseObjectPtr<BaseObject>(wrap);
461474
}
462475

‎src/tcp_wrap.h‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,10 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
6262
}
6363
}
6464

65-
// Transfer the underlying socket to another thread via .postMessage(). Within
66-
// a single process all threads share the same file descriptor table, so the
67-
// transfer dup()s the fd and re-adopts it (uv_tcp_open) in the receiving
68-
// event loop. This is the building block for distributing listening sockets
69-
// and accepted connections across worker_threads.
65+
// Transfer the underlying socket to another thread via .postMessage(). The
66+
// transfer duplicates the socket and re-adopts it (uv_tcp_open) in the
67+
// receiving event loop. This is the building block for distributing
68+
// listening sockets and accepted connections across worker_threads.
7069
BaseObject::TransferMode GetTransferMode() constoverride;
7170
std::unique_ptr<worker::TransferData> TransferForMessaging() override;
7271

@@ -75,7 +74,8 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
7574

7675
classTransferData : publicworker::TransferData {
7776
public:
78-
explicitTransferData(int fd, SocketType type) : fd_(fd), type_(type) {}
77+
explicitTransferData(uv_os_sock_t socket, SocketType type)
78+
: socket_(socket), type_(type) {}
7979
~TransferData() override;
8080

8181
BaseObjectPtr<BaseObject> Deserialize(
@@ -88,7 +88,7 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
8888
SET_SELF_SIZE(TransferData)
8989

9090
private:
91-
int fd_;
91+
uv_os_sock_t socket_;
9292
SocketType type_;
9393
};
9494

‎test/parallel/test-net-server-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

‎test/parallel/test-net-socket-transfer-worker-http.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
consthttp=require('http');

‎test/parallel/test-net-socket-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 9040b08

Browse files
mcollinaaduh95
authored andcommitted
net: support TCP handle transfer on Windows
Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #64460Fixes: #64456 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Stefan Stojanovic <stefan.stojanovic@janeasystems.com> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
1 parent 1216481 commit 9040b08

11 files changed

Lines changed: 50 additions & 77 deletions

‎doc/api/errors.md‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3512,14 +3512,6 @@ An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
35123512
via a `worker_threads``postMessage()` call while it was not in a transferable
35133513
state, for example because it had already started reading or had buffered data.
35143514

3515-
<aid="ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED"></a>
3516-
3517-
### `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`
3518-
3519-
An attempt was made to transfer a `net.Socket` or `net.Server` to another thread
3520-
on a platform where moving the underlying handle between event loops is not
3521-
supported (currently Windows).
3522-
35233515
<aid="ERR_WORKER_INIT_FAILED"></a>
35243516

35253517
### `ERR_WORKER_INIT_FAILED`

‎doc/api/net.md‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -766,9 +766,7 @@ threads.
766766
The socket must be a freshly accepted or created TCP connection: it must still
767767
be attached to a live handle, must not be connecting or destroyed, and must not
768768
have started reading or have buffered data. Otherwise `postMessage()` throws
769-
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported, and only
770-
on Unix-like platforms; on Windows `postMessage()` throws
771-
`ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
769+
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. Only TCP sockets are supported.
772770

773771
```cjs
774772
constnet=require('node:net');

‎doc/api/worker_threads.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1247,8 +1247,7 @@ freshly accepted or created TCP connection that has not yet started reading and
12471247
has no buffered data, otherwise `postMessage()` throws
12481248
`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. This makes it possible to accept
12491249
connections on one thread and distribute them across a pool of worker threads.
1250-
Only TCP handles are supported, and only on Unix-like platforms; on Windows
1251-
`postMessage()` throws `ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED`.
1250+
Only TCP handles are supported.
12521251
12531252
If `value` contains {SharedArrayBuffer} instances, those are accessible
12541253
from either thread. They cannot be listed in `transferList`.

‎lib/internal/errors.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,8 +1932,6 @@ E('ERR_WORKER_HANDLE_NOT_TRANSFERABLE',
19321932
'%s cannot be transferred in its current state; it must be a freshly '+
19331933
'created or accepted handle that has not started reading and has no '+
19341934
'pending writes',Error);
1935-
E('ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED',
1936-
'Transferring a %s to another thread is not supported on this platform',Error);
19371935
E('ERR_WORKER_INIT_FAILED','Worker initialization failure: %s',Error);
19381936
E('ERR_WORKER_INVALID_EXEC_ARGV',(errors,msg='invalid execArgv flags')=>
19391937
`Initiated Worker with ${msg}: ${ArrayPrototypeJoin(errors,', ')}`,

‎lib/net.js‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,6 @@ const {
120120
ERR_SOCKET_CONNECTION_TIMEOUT,
121121
ERR_SOCKET_HANDLE_ADOPTED,
122122
ERR_WORKER_HANDLE_NOT_TRANSFERABLE,
123-
ERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED,
124123
},
125124
genericNodeError,
126125
}=require('internal/errors');
@@ -1600,9 +1599,6 @@ Socket.prototype[kReinitializeHandle] = function reinitializeHandle(handle) {
16001599
// connecting or destroyed, and with no data already buffered in either
16011600
// direction (which would otherwise be lost on the sending side).
16021601
functionassertTransferableSocket(socket){
1603-
if(isWindows){
1604-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Socket');
1605-
}
16061602
consthandle=socket._handle;
16071603
if(handle==null||!(handleinstanceofTCP)||
16081604
socket.destroyed||socket.connecting||
@@ -2364,9 +2360,6 @@ Server.prototype._listen2 = setupListenHandle; // legacy alias
23642360
// underlying listening socket (and its pending accept queue) to that thread's
23652361
// event loop. Only a server bound to a live TCP handle can be transferred.
23662362
functionassertTransferableServer(server){
2367-
if(isWindows){
2368-
thrownewERR_WORKER_HANDLE_TRANSFER_UNSUPPORTED('net.Server');
2369-
}
23702363
if(server._handle==null||!(server._handleinstanceofTCP)){
23712364
thrownewERR_WORKER_HANDLE_NOT_TRANSFERABLE('net.Server');
23722365
}

‎src/tcp_wrap.cc‎

Lines changed: 41 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -380,57 +380,66 @@ void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
380380
}
381381

382382
BaseObject::TransferMode TCPWrap::GetTransferMode() const {
383-
#ifdef _WIN32
384-
// Re-adopting a socket into another thread's event loop requires
385-
// re-associating it with that loop's IOCP, which needs same-process
386-
// WSADuplicateSocket support that is not wired up yet. The JS net layer
387-
// throws a clearer error before reaching here; this is the backstop for the
388-
// low-level `socket._handle` transfer path.
389-
return TransferMode::kDisallowCloneAndTransfer;
390-
#else
391383
// Only a live handle that is not already being torn down can be transferred.
392384
// Higher-level guards (no buffered reads, no pending writes) are enforced by
393385
// the JS net.Socket/net.Server layer before a handle reaches here.
394386
if (!HandleWrap::IsAlive(this) || IsHandleClosing())
395387
return TransferMode::kDisallowCloneAndTransfer;
396388
return TransferMode::kTransferable;
397-
#endif
398389
}
399390

400391
std::unique_ptr<worker::TransferData> TCPWrap::TransferForMessaging() {
401-
#ifdef _WIN32
402-
return {};
403-
#else
404392
CHECK_NE(GetTransferMode(), TransferMode::kDisallowCloneAndTransfer);
405393

406394
uv_os_fd_t fd;
407395
if (uv_fileno(reinterpret_cast<uv_handle_t*>(&handle_), &fd) != 0) return {};
408396

409-
// dup() the descriptor so the receiving event loop owns an independent
410-
// reference to the same socket. We then close the source handle, which
411-
// renders it unusable on this side (true transfer semantics) while the dup
412-
// keeps the underlying socket alive for the destination thread.
413-
int dup_fd = dup(fd);
414-
if (dup_fd < 0) return {};
397+
#ifdef _WIN32
398+
// A socket that is already associated with an IOCP cannot be associated with
399+
// another one. Create a same-process duplicate that is not associated with
400+
// any IOCP yet; uv_tcp_open() will associate it with the receiving loop.
401+
WSAPROTOCOL_INFOW protocol_info;
402+
uv_os_sock_t source_socket = reinterpret_cast<uv_os_sock_t>(fd);
403+
if (WSADuplicateSocketW(
404+
source_socket, GetCurrentProcessId(), &protocol_info) != 0) {
405+
return {};
406+
}
407+
uv_os_sock_t duplicate = WSASocketW(FROM_PROTOCOL_INFO,
408+
FROM_PROTOCOL_INFO,
409+
FROM_PROTOCOL_INFO,
410+
&protocol_info,
411+
0,
412+
WSA_FLAG_OVERLAPPED);
413+
if (duplicate == static_cast<uv_os_sock_t>(-1)) return {};
414+
#else
415+
// Unix threads share the descriptor table, so dup() creates an independent
416+
// reference to the same socket for the receiving event loop.
417+
uv_os_sock_t duplicate = dup(fd);
418+
if (duplicate < 0) return {};
419+
#endif
415420

416421
SocketType type =
417422
provider_type() == ProviderType::PROVIDER_TCPSERVERWRAP ? SERVER : SOCKET;
418423

419-
// Stop watching the fd and tear down the source handle.
424+
// Stop watching the original socket and tear down the source handle. The
425+
// duplicate keeps the underlying socket alive until the destination adopts
426+
// it, or until TransferData is destroyed if the message is not delivered.
420427
Close();
421428

422-
return std::make_unique<TransferData>(dup_fd, type);
423-
#endif
429+
return std::make_unique<TransferData>(duplicate, type);
424430
}
425431

426432
TCPWrap::TransferData::~TransferData() {
427-
// Only reached if the message was never delivered (e.g. the destination port
428-
// closed in flight); close the dup'd fd so it is not leaked.
429-
if (fd_ >= 0) {
433+
#ifdef _WIN32
434+
if (socket_ != static_cast<uv_os_sock_t>(-1))
435+
CHECK_EQ(0, closesocket(socket_));
436+
#else
437+
if (socket_ >= 0) {
430438
uv_fs_t req;
431-
CHECK_EQ(0, uv_fs_close(nullptr, &req, fd_, nullptr));
439+
CHECK_EQ(0, uv_fs_close(nullptr, &req, socket_, nullptr));
432440
uv_fs_req_cleanup(&req);
433441
}
442+
#endif
434443
}
435444

436445
BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
@@ -453,10 +462,14 @@ BaseObjectPtr<BaseObject> TCPWrap::TransferData::Deserialize(
453462
TCPWrap* wrap = BaseObject::Unwrap<TCPWrap>(obj);
454463
if (wrap == nullptr) return {};
455464

456-
if (uv_tcp_open(&wrap->handle_, fd_) != 0) return {};
465+
if (uv_tcp_open(&wrap->handle_, socket_) != 0) return {};
457466

458-
wrap->set_fd(fd_);
459-
fd_ = -1; // Ownership has been handed to the new handle.
467+
#ifdef _WIN32
468+
socket_ = static_cast<uv_os_sock_t>(-1);
469+
#else
470+
wrap->set_fd(socket_);
471+
socket_ = -1;
472+
#endif
460473
return BaseObjectPtr<BaseObject>(wrap);
461474
}
462475

‎src/tcp_wrap.h‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,10 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
6262
}
6363
}
6464

65-
// Transfer the underlying socket to another thread via .postMessage(). Within
66-
// a single process all threads share the same file descriptor table, so the
67-
// transfer dup()s the fd and re-adopts it (uv_tcp_open) in the receiving
68-
// event loop. This is the building block for distributing listening sockets
69-
// and accepted connections across worker_threads.
65+
// Transfer the underlying socket to another thread via .postMessage(). The
66+
// transfer duplicates the socket and re-adopts it (uv_tcp_open) in the
67+
// receiving event loop. This is the building block for distributing
68+
// listening sockets and accepted connections across worker_threads.
7069
BaseObject::TransferMode GetTransferMode() constoverride;
7170
std::unique_ptr<worker::TransferData> TransferForMessaging() override;
7271

@@ -75,7 +74,8 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
7574

7675
classTransferData : publicworker::TransferData {
7776
public:
78-
explicitTransferData(int fd, SocketType type) : fd_(fd), type_(type) {}
77+
explicitTransferData(uv_os_sock_t socket, SocketType type)
78+
: socket_(socket), type_(type) {}
7979
~TransferData() override;
8080

8181
BaseObjectPtr<BaseObject> Deserialize(
@@ -88,7 +88,7 @@ class TCPWrap : public ConnectionWrap<TCPWrap, uv_tcp_t> {
8888
SET_SELF_SIZE(TransferData)
8989

9090
private:
91-
int fd_;
91+
uv_os_sock_t socket_;
9292
SocketType type_;
9393
};
9494

‎test/parallel/test-net-server-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

‎test/parallel/test-net-socket-transfer-worker-http.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
consthttp=require('http');

‎test/parallel/test-net-socket-transfer-worker.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@
77

88
constcommon=require('../common');
99

10-
if(common.isWindows){
11-
common.skip('transferring TCP handles between threads is not supported on '+
12-
'Windows yet');
13-
}
14-
1510
constassert=require('assert');
1611
constnet=require('net');
1712
const{

0 commit comments

Comments
 (0)