fix: multi-repo local dev (file:../ deps, package exports, missing deps)
This commit is contained in:
+81
@@ -0,0 +1,81 @@
|
||||
cmake_minimum_required(VERSION 3.25)
|
||||
|
||||
find_package(cmake-bare REQUIRED PATHS node_modules/cmake-bare)
|
||||
find_package(cmake-fetch REQUIRED PATHS node_modules/cmake-fetch)
|
||||
find_package(cmake-napi REQUIRED PATHS node_modules/cmake-napi)
|
||||
find_package(cmake-npm REQUIRED PATHS node_modules/cmake-npm)
|
||||
|
||||
project(udx_native C CXX)
|
||||
|
||||
bare_target(target)
|
||||
|
||||
if(target MATCHES "win32")
|
||||
add_compile_options(/MT$<$<CONFIG:Debug>:d>)
|
||||
endif()
|
||||
|
||||
fetch_package("github:holepunchto/libudx#25b063b")
|
||||
fetch_package("github:holepunchto/libjstl#098664c")
|
||||
|
||||
add_bare_module(udx_native_bare)
|
||||
|
||||
target_sources(
|
||||
${udx_native_bare}
|
||||
PRIVATE
|
||||
binding.cc
|
||||
)
|
||||
|
||||
target_link_libraries(
|
||||
${udx_native_bare}
|
||||
PRIVATE
|
||||
$<TARGET_OBJECTS:udx>
|
||||
jstl
|
||||
PUBLIC
|
||||
udx
|
||||
)
|
||||
|
||||
if(target MATCHES "win32")
|
||||
target_link_libraries(
|
||||
${udx_native_bare}
|
||||
PUBLIC
|
||||
ws2_32
|
||||
)
|
||||
endif()
|
||||
|
||||
add_napi_module(udx_native_napi)
|
||||
|
||||
target_sources(
|
||||
${udx_native_napi}
|
||||
PRIVATE
|
||||
binding.cc
|
||||
)
|
||||
|
||||
target_compile_definitions(
|
||||
${udx_native_napi}
|
||||
PRIVATE
|
||||
NAPI_VERSION=9
|
||||
)
|
||||
|
||||
target_link_libraries(
|
||||
${udx_native_napi}
|
||||
PRIVATE
|
||||
$<TARGET_OBJECTS:udx>
|
||||
jstl
|
||||
PUBLIC
|
||||
udx
|
||||
)
|
||||
|
||||
if(target MATCHES "win32")
|
||||
target_link_libraries(
|
||||
${udx_native_napi}
|
||||
PUBLIC
|
||||
ws2_32
|
||||
)
|
||||
endif()
|
||||
|
||||
resolve_node_module(bare-compat-napi compat)
|
||||
|
||||
target_include_directories(
|
||||
${udx_native_napi}
|
||||
PRIVATE
|
||||
"${compat}/include"
|
||||
)
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+403
@@ -0,0 +1,403 @@
|
||||
# udx-native
|
||||
|
||||
udx is reliable, multiplexed, and congestion-controlled streams over udp.
|
||||
|
||||
```
|
||||
npm i udx-native
|
||||
```
|
||||
|
||||
It's a transport protocol, made only for peer-to-peer networking.
|
||||
|
||||
No handshakes. No encryption. No features. This is good for P2P.\
|
||||
Just fast streams and messages that are composable into powerful things.
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const UDX = require('udx-native')
|
||||
|
||||
const u = new UDX()
|
||||
const a = u.createSocket()
|
||||
const b = u.createSocket()
|
||||
|
||||
b.on('message', function (message) {
|
||||
console.log('received', message.toString())
|
||||
a.close()
|
||||
b.close()
|
||||
})
|
||||
|
||||
b.bind(0)
|
||||
a.send(Buffer.from('hello'), b.address().port)
|
||||
```
|
||||
|
||||
```js
|
||||
const UDX = require('udx-native')
|
||||
|
||||
const u = new UDX()
|
||||
|
||||
const socket1 = u.createSocket()
|
||||
const socket2 = u.createSocket()
|
||||
|
||||
socket1.bind()
|
||||
socket2.bind()
|
||||
|
||||
const stream1 = u.createStream(1)
|
||||
const stream2 = u.createStream(2)
|
||||
|
||||
stream1.connect(socket1, stream2.id, socket2.address().port, '127.0.0.1')
|
||||
stream2.connect(socket2, stream1.id, socket1.address().port, '127.0.0.1')
|
||||
|
||||
stream1.write(Buffer.from('hello'))
|
||||
stream1.end()
|
||||
|
||||
stream2.on('data', function (data) {
|
||||
console.log(data)
|
||||
})
|
||||
|
||||
stream2.on('end', function () {
|
||||
stream2.end()
|
||||
})
|
||||
|
||||
stream1.on('close', function () {
|
||||
console.log('stream1 closed')
|
||||
socket1.close()
|
||||
})
|
||||
|
||||
stream2.on('close', function () {
|
||||
console.log('stream2 closed')
|
||||
socket2.close()
|
||||
})
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
#### `const udx = new UDX()`
|
||||
|
||||
Creates a new UDX instance.
|
||||
|
||||
#### `const bool = UDX.isIPv4(host)`
|
||||
|
||||
Returns `true` if host is an IPv4 address.
|
||||
|
||||
#### `const bool = UDX.isIPv6(host)`
|
||||
|
||||
Returns `true` if host is an IPv6 address.
|
||||
|
||||
#### `const family = UDX.isIP(host)`
|
||||
|
||||
Returns the address family (`4` or `6`). Returns `0` if invalid.
|
||||
|
||||
## Sockets
|
||||
|
||||
#### `const socket = udx.createSocket([options])`
|
||||
|
||||
Creates a new socket instance.
|
||||
|
||||
Available `options`:
|
||||
|
||||
```js
|
||||
{
|
||||
ipv6Only: false,
|
||||
reuseAddress: false
|
||||
}
|
||||
```
|
||||
|
||||
#### `socket.udx`
|
||||
|
||||
It's the UDX instance from where the socket was created.
|
||||
|
||||
#### `socket.streams`
|
||||
|
||||
It's a `Set` that tracks active streams (connected to the socket but not closed).
|
||||
|
||||
#### `socket.userData`
|
||||
|
||||
Optional custom userData. Default is `null`.
|
||||
|
||||
#### `socket.bound`
|
||||
|
||||
Indicates if it's bound to any port. It will be `true` after a successful `bind()`.
|
||||
|
||||
#### `socket.closing`
|
||||
|
||||
It will be `true` after `close()` is called.
|
||||
|
||||
#### `socket.idle`
|
||||
|
||||
Indicates that the socket doesn't have any connected stream.
|
||||
|
||||
#### `socket.busy`
|
||||
|
||||
Indicates that the socket have at least one connected stream.
|
||||
|
||||
#### `socket.address()`
|
||||
|
||||
Returns an object like `{ host, family, port }`. Only available after `bind()`.
|
||||
|
||||
#### `socket.bind([port], [host])`
|
||||
|
||||
The default port is `0`.\
|
||||
If no host specified: it binds to IPv6 `::`. If fails then IPv4 `0.0.0.0`.
|
||||
|
||||
#### `await socket.close()`
|
||||
|
||||
It unbinds the socket so it stops listening for messages.
|
||||
|
||||
#### `socket.setTTL(ttl)`
|
||||
|
||||
Sets the amount of times that a packet is allowed to be forwarded through each router or gateway before being discarded.
|
||||
|
||||
#### `socket.getRecvBufferSize()`
|
||||
|
||||
#### `socket.setRecvBufferSize()`
|
||||
|
||||
#### `socket.getSendBufferSize()`
|
||||
|
||||
#### `socket.setSendBufferSize()`
|
||||
|
||||
#### `await socket.send(buffer, port, [host], [ttl])`
|
||||
|
||||
Sends a message to port and host destination. Default host is `127.0.0.1`.
|
||||
|
||||
#### `socket.trySend(buffer, port, [host], [ttl])`
|
||||
|
||||
Same behaviour as `send()` but no promise.
|
||||
|
||||
#### `socket.on('message', (msg, from) => {})`
|
||||
|
||||
`msg` is a buffer that containts the message.\
|
||||
`from` is an object like `{ host, family, port }`.
|
||||
|
||||
#### `socket.on('close', onclose)`
|
||||
|
||||
Emitted if the socket was ever bound and it got closed.
|
||||
|
||||
#### `socket.on('idle', onidle)`
|
||||
|
||||
Emitted if the socket becomes idle (no active streams).
|
||||
|
||||
#### `socket.on('busy', onbusy)`
|
||||
|
||||
Emitted if the socket becomes busy (at least one active stream).
|
||||
|
||||
#### `socket.on('listening', onlistening)`
|
||||
|
||||
Emitted after a succesfull `bind()` call.
|
||||
|
||||
## Streams
|
||||
|
||||
#### `const stream = udx.createStream(id, [options])`
|
||||
|
||||
Creates a new stream instance that is a Duplex stream.
|
||||
|
||||
Available `options`:
|
||||
|
||||
```js
|
||||
{
|
||||
firewall: (socket, port, host) => true,
|
||||
framed: false,
|
||||
seq: 0
|
||||
}
|
||||
```
|
||||
|
||||
#### `stream.udx`
|
||||
|
||||
It's the UDX instance from where the stream was created.
|
||||
|
||||
#### `stream.socket`
|
||||
|
||||
Refers to the socket that is connected to. Setted when you `connect()` the stream.
|
||||
|
||||
#### `stream.id`
|
||||
|
||||
Custom stream id.
|
||||
|
||||
#### `stream.remoteId`
|
||||
|
||||
Remote stream id. Setted when you `connect()` the stream.
|
||||
|
||||
#### `stream.remoteId`
|
||||
|
||||
Remote stream id. Setted when you `connect()` the stream.
|
||||
|
||||
#### `stream.remoteHost`
|
||||
|
||||
Remote host. Setted when you `connect()` the stream.
|
||||
|
||||
#### `stream.remoteFamily`
|
||||
|
||||
Remote family (`4` or `6`). Setted when you `connect()` the stream.
|
||||
|
||||
#### `stream.remotePort`
|
||||
|
||||
Remote port. Setted when you `connect()` the stream.
|
||||
|
||||
#### `stream.userData`
|
||||
|
||||
Optional custom userData. Default is `null`.
|
||||
|
||||
#### `stream.connected`
|
||||
|
||||
Indicates if the stream is connected to a socket. It becomes `false` if the stream is closed.
|
||||
|
||||
#### `stream.mtu`
|
||||
|
||||
Indicates the maximum size of each packet.
|
||||
|
||||
#### `stream.rtt`
|
||||
|
||||
#### `stream.cwnd`
|
||||
|
||||
#### `stream.inflight`
|
||||
|
||||
#### `stream.localHost`
|
||||
|
||||
Indicates the connected socket host address. By default `null` if not connected.
|
||||
|
||||
#### `stream.localFamily`
|
||||
|
||||
Indicates the connected socket family address (`4` o `6`). By default `0` if not connected.
|
||||
|
||||
#### `stream.localPort`
|
||||
|
||||
Indicates the connected socket port. By default `0` if not connected.
|
||||
|
||||
#### `stream.setInteractive(bool)`
|
||||
|
||||
#### `stream.connect(socket, remoteId, port, [host], [options])`
|
||||
|
||||
Connects the stream using a socket to a: remote stream id, and remote socket port/host.
|
||||
|
||||
If no host specified it uses `127.0.0.1` by default.
|
||||
|
||||
Available `options`:
|
||||
|
||||
```js
|
||||
{
|
||||
ack
|
||||
}
|
||||
```
|
||||
|
||||
#### `await stream.changeRemote(remoteId, port, [host])`
|
||||
|
||||
Change the remote end of the stream.
|
||||
|
||||
If no host specified it uses `127.0.0.1` by default.
|
||||
|
||||
#### `stream.relayTo(destination)`
|
||||
|
||||
Relay stream to another stream.
|
||||
|
||||
#### `await stream.send(buffer)`
|
||||
|
||||
Send a message to another stream. Returns a promise.
|
||||
|
||||
#### `stream.trySend(buffer)`
|
||||
|
||||
Send a message to another stream.
|
||||
|
||||
#### `const drained = await stream.flush()`
|
||||
|
||||
Wait for pending stream writes to have been explicitly acknowledged by the other side of the connection.
|
||||
|
||||
#### `stream.on('connect', onconnect)`
|
||||
|
||||
Emitted after the stream is connected to a socket.
|
||||
|
||||
#### `stream.on('message', onmessage)`
|
||||
|
||||
Emitted if the stream receives a message.
|
||||
|
||||
#### `stream.on('remote-changed', onremotechanged)`
|
||||
|
||||
Emitted when the remote end of the stream changes.
|
||||
|
||||
#### `stream.on('mtu-exceeded', onmtuexceeded)`
|
||||
|
||||
Emitted only once if you write data that exceeds the MTU.
|
||||
|
||||
## Network interfaces
|
||||
|
||||
#### `const interfaces = udx.networkInterfaces()`
|
||||
|
||||
Returns an array of network interfaces, for example:
|
||||
|
||||
```js
|
||||
;[
|
||||
{ name: 'lo', host: '127.0.0.1', family: 4, internal: true },
|
||||
{ name: 'enp4s0', host: '192.168.0.20', family: 4, internal: false },
|
||||
{ name: 'lo', host: '::1', family: 6, internal: true },
|
||||
{
|
||||
name: 'enp4s0',
|
||||
host: 'df08::c8df:bf61:95c1:352b',
|
||||
family: 6,
|
||||
internal: false
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
#### `const watcher = udx.watchNetworkInterfaces([onchange])`
|
||||
|
||||
Listens to changes in the network interfaces. The `watcher` object is iterable.
|
||||
|
||||
#### `watcher.interfaces`
|
||||
|
||||
Array of network interfaces.
|
||||
|
||||
#### `watcher.watch()`
|
||||
|
||||
Starts watching for changes. By default it already does it. This is only useful after you `unwatch()`.
|
||||
|
||||
#### `watcher.unwatch()`
|
||||
|
||||
Stops watching for changes.
|
||||
|
||||
#### `await watcher.destroy()`
|
||||
|
||||
Closes the watcher.
|
||||
|
||||
#### `watcher.on('change', onchange)`
|
||||
|
||||
Emitted after a network interface change.
|
||||
|
||||
#### `watcher.on('close', onclose)`
|
||||
|
||||
Emitted after the watcher is closed.
|
||||
|
||||
## DNS
|
||||
|
||||
#### `const address = await udx.lookup(host, [options])`
|
||||
|
||||
It does a DNS lookup for the IP address. Returns `{ host, family }`.
|
||||
|
||||
Available `options`:
|
||||
|
||||
```js
|
||||
{
|
||||
family: 0 // => 0, 4 or 6
|
||||
}
|
||||
```
|
||||
|
||||
## Dev Setup
|
||||
|
||||
To develop UDX locally, you need to create a libudx prebuild. [bare-make](https://github.com/holepunchto/bare-make) is used for this.
|
||||
|
||||
Requirements: The Clang C-compiler should be installed.
|
||||
|
||||
The other setup steps are:
|
||||
|
||||
- `npm install -g bare-runtime bare-make`
|
||||
- `npm install`
|
||||
- `bare-make generate`
|
||||
- `bare-make build`
|
||||
- `bare-make install`
|
||||
|
||||
When testing changes, rebuild the prebuilds:
|
||||
|
||||
- `bare-make generate`
|
||||
- `bare-make build`
|
||||
- `bare-make install`
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
+1781
File diff suppressed because it is too large
Load Diff
+3
@@ -0,0 +1,3 @@
|
||||
require.addon = require('require-addon')
|
||||
|
||||
module.exports = require.addon('.', __filename)
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the
|
||||
// "Software"), to deal in the Software without restriction, including
|
||||
// without limitation the rights to use, copy, modify, merge, publish,
|
||||
// distribute, sublicense, and/or sell copies of the Software, and to permit
|
||||
// persons to whom the Software is furnished to do so, subject to the
|
||||
// following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included
|
||||
// in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
||||
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
|
||||
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
|
||||
const IPv4Pattern = new RegExp(`^${v4Str}$`)
|
||||
|
||||
const v6Seg = '(?:[0-9a-fA-F]{1,4})'
|
||||
const IPv6Pattern = new RegExp(
|
||||
'^(' +
|
||||
`(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
|
||||
`(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
|
||||
`(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
|
||||
`(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
|
||||
`(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
|
||||
`(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
|
||||
`(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
|
||||
`(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
|
||||
')(%[0-9a-zA-Z-.:]{1,})?$'
|
||||
)
|
||||
|
||||
const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
|
||||
return IPv4Pattern.test(host)
|
||||
})
|
||||
|
||||
const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
|
||||
return IPv6Pattern.test(host)
|
||||
})
|
||||
|
||||
exports.isIP = function isIP(host) {
|
||||
if (isIPv4(host)) return 4
|
||||
if (isIPv6(host)) return 6
|
||||
return 0
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
const events = require('events')
|
||||
const b4a = require('b4a')
|
||||
const binding = require('../binding')
|
||||
|
||||
module.exports = class NetworkInterfaces extends events.EventEmitter {
|
||||
constructor(udx) {
|
||||
super()
|
||||
|
||||
this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t)
|
||||
this._watching = false
|
||||
this._destroying = null
|
||||
|
||||
binding.udx_napi_interface_event_init(
|
||||
udx._handle,
|
||||
this._handle,
|
||||
this,
|
||||
this._onevent,
|
||||
this._onclose
|
||||
)
|
||||
|
||||
this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
|
||||
}
|
||||
|
||||
_onclose() {
|
||||
this.emit('close')
|
||||
}
|
||||
|
||||
_onevent() {
|
||||
this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
|
||||
|
||||
this.emit('change', this.interfaces)
|
||||
}
|
||||
|
||||
watch() {
|
||||
if (this._watching) return this
|
||||
this._watching = true
|
||||
|
||||
binding.udx_napi_interface_event_start(this._handle)
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
unwatch() {
|
||||
if (!this._watching) return this
|
||||
this._watching = false
|
||||
|
||||
binding.udx_napi_interface_event_stop(this._handle)
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
async destroy() {
|
||||
if (this._destroying) return this._destroying
|
||||
this._destroying = events.once(this, 'close')
|
||||
|
||||
binding.udx_napi_interface_event_close(this._handle)
|
||||
|
||||
return this._destroying
|
||||
}
|
||||
|
||||
[Symbol.iterator]() {
|
||||
return this.interfaces[Symbol.iterator]()
|
||||
}
|
||||
}
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
const events = require('events')
|
||||
const b4a = require('b4a')
|
||||
const binding = require('../binding')
|
||||
const ip = require('./ip')
|
||||
|
||||
module.exports = class UDXSocket extends events.EventEmitter {
|
||||
constructor(udx, opts = {}) {
|
||||
super()
|
||||
|
||||
this.udx = udx
|
||||
|
||||
this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t)
|
||||
this._inited = false
|
||||
this._host = null
|
||||
this._family = 0
|
||||
this._ipv6Only = opts.ipv6Only === true
|
||||
this._reuseAddress = opts.reuseAddress === true
|
||||
this._port = 0
|
||||
this._reqs = []
|
||||
this._free = []
|
||||
this._closing = null
|
||||
this._closed = false
|
||||
|
||||
this._view64 = new BigUint64Array(
|
||||
this._handle.buffer,
|
||||
this._handle.byteOffset,
|
||||
this._handle.byteLength >> 3
|
||||
)
|
||||
|
||||
this.streams = new Set()
|
||||
|
||||
this.userData = null
|
||||
}
|
||||
|
||||
get bound() {
|
||||
return this._port !== 0
|
||||
}
|
||||
|
||||
get closing() {
|
||||
return this._closing !== null
|
||||
}
|
||||
|
||||
get idle() {
|
||||
return this.streams.size === 0
|
||||
}
|
||||
|
||||
get busy() {
|
||||
return this.streams.size > 0
|
||||
}
|
||||
|
||||
get bytesTransmitted() {
|
||||
if (this._inited !== true) return 0
|
||||
return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3])
|
||||
}
|
||||
|
||||
get packetsTransmitted() {
|
||||
if (this._inited !== true) return 0
|
||||
return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3])
|
||||
}
|
||||
|
||||
get bytesReceived() {
|
||||
if (this._inited !== true) return 0
|
||||
return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3])
|
||||
}
|
||||
|
||||
get packetsReceived() {
|
||||
if (this._inited !== true) return 0
|
||||
return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3])
|
||||
}
|
||||
|
||||
get packetsDroppedByKernel() {
|
||||
if (this._inited !== true) return 0
|
||||
return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3])
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
bound: this.bound,
|
||||
closing: this.closing,
|
||||
streams: this.streams.size,
|
||||
address: this.address(),
|
||||
ipv6Only: this._ipv6Only,
|
||||
reuseAddress: this._reuseAddress,
|
||||
idle: this.idle,
|
||||
busy: this.busy
|
||||
}
|
||||
}
|
||||
|
||||
_init() {
|
||||
if (this._inited) return
|
||||
|
||||
binding.udx_napi_socket_init(
|
||||
this.udx._handle,
|
||||
this._handle,
|
||||
this,
|
||||
this._onsend,
|
||||
this._onmessage,
|
||||
this._onclose,
|
||||
this._reallocMessage
|
||||
)
|
||||
|
||||
this._inited = true
|
||||
}
|
||||
|
||||
_onsend(id, err) {
|
||||
const req = this._reqs[id]
|
||||
|
||||
const onflush = req.onflush
|
||||
|
||||
req.buffer = null
|
||||
req.onflush = null
|
||||
|
||||
this._free.push(id)
|
||||
|
||||
onflush(err >= 0)
|
||||
|
||||
// gc the free list
|
||||
if (this._free.length >= 16 && this._free.length === this._reqs.length) {
|
||||
this._free = []
|
||||
this._reqs = []
|
||||
}
|
||||
}
|
||||
|
||||
_onmessage(len, port, host, family) {
|
||||
this.emit('message', this.udx._consumeMessage(len), { host, family, port })
|
||||
return this.udx._buffer
|
||||
}
|
||||
|
||||
_onclose() {
|
||||
this.emit('close')
|
||||
}
|
||||
|
||||
_reallocMessage() {
|
||||
return this.udx._reallocMessage()
|
||||
}
|
||||
|
||||
_onidle() {
|
||||
this.emit('idle')
|
||||
}
|
||||
|
||||
_onbusy() {
|
||||
this.emit('busy')
|
||||
}
|
||||
|
||||
_addStream(stream) {
|
||||
if (this.streams.has(stream)) return false
|
||||
this.streams.add(stream)
|
||||
if (this.streams.size === 1) this._onbusy()
|
||||
return true
|
||||
}
|
||||
|
||||
_removeStream(stream) {
|
||||
if (!this.streams.has(stream)) return false
|
||||
this.streams.delete(stream)
|
||||
const closed = this._closeMaybe()
|
||||
if (this.idle && !closed) this._onidle()
|
||||
return true
|
||||
}
|
||||
|
||||
address() {
|
||||
if (!this.bound) return null
|
||||
return { host: this._host, family: this._family, port: this._port }
|
||||
}
|
||||
|
||||
bind(port, host) {
|
||||
if (this.bound) throw new Error('Already bound')
|
||||
if (this.closing) throw new Error('Socket is closed')
|
||||
|
||||
if (!port) port = 0
|
||||
|
||||
let flags = 0
|
||||
if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY
|
||||
if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR
|
||||
|
||||
let family
|
||||
|
||||
if (host) {
|
||||
family = ip.isIP(host)
|
||||
if (!family) throw new Error(`${host} is not a valid IP address`)
|
||||
|
||||
if (!this._inited) this._init()
|
||||
|
||||
this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
|
||||
} else {
|
||||
if (!this._inited) this._init()
|
||||
|
||||
try {
|
||||
host = '::'
|
||||
family = 6
|
||||
this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
|
||||
} catch {
|
||||
host = '0.0.0.0'
|
||||
family = 4
|
||||
this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
|
||||
}
|
||||
}
|
||||
|
||||
this._host = host
|
||||
this._family = family
|
||||
|
||||
this.emit('listening')
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this._closing) return this._closing
|
||||
this._closing = new Promise((resolve) => this.once('close', resolve))
|
||||
this._closeMaybe()
|
||||
return this._closing
|
||||
}
|
||||
|
||||
_closeMaybe() {
|
||||
if (this._closed || this._closing === null) return this._closed
|
||||
|
||||
if (!this._inited) {
|
||||
this._closed = true
|
||||
this.emit('close')
|
||||
return true
|
||||
}
|
||||
|
||||
if (this.idle) {
|
||||
binding.udx_napi_socket_close(this._handle)
|
||||
this._closed = true
|
||||
}
|
||||
|
||||
return this._closed
|
||||
}
|
||||
|
||||
setTTL(ttl) {
|
||||
if (!this._inited) throw new Error('Socket not active')
|
||||
binding.udx_napi_socket_set_ttl(this._handle, ttl)
|
||||
}
|
||||
|
||||
getRecvBufferSize() {
|
||||
if (!this._inited) throw new Error('Socket not active')
|
||||
return binding.udx_napi_socket_get_recv_buffer_size(this._handle)
|
||||
}
|
||||
|
||||
setRecvBufferSize(size) {
|
||||
if (!this._inited) throw new Error('Socket not active')
|
||||
return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size)
|
||||
}
|
||||
|
||||
getSendBufferSize() {
|
||||
if (!this._inited) throw new Error('Socket not active')
|
||||
return binding.udx_napi_socket_get_send_buffer_size(this._handle)
|
||||
}
|
||||
|
||||
setSendBufferSize(size) {
|
||||
if (!this._inited) throw new Error('Socket not active')
|
||||
return binding.udx_napi_socket_set_send_buffer_size(this._handle, size)
|
||||
}
|
||||
|
||||
addMembership(group, ifaceAddress) {
|
||||
if (!this._inited) throw new Error('Socket not active')
|
||||
return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', true)
|
||||
}
|
||||
|
||||
dropMembership(group, ifaceAddress) {
|
||||
if (!this._inited) throw new Error('Socket not active')
|
||||
return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', false)
|
||||
}
|
||||
|
||||
async send(buffer, port, host, ttl) {
|
||||
if (this.closing) return false
|
||||
|
||||
if (!host) host = '127.0.0.1'
|
||||
|
||||
const family = ip.isIP(host)
|
||||
if (!family) throw new Error(`${host} is not a valid IP address`)
|
||||
|
||||
if (!this.bound) this.bind(0)
|
||||
|
||||
const id = this._allocSend()
|
||||
const req = this._reqs[id]
|
||||
|
||||
req.buffer = buffer
|
||||
|
||||
const promise = new Promise((resolve) => {
|
||||
req.onflush = resolve
|
||||
})
|
||||
|
||||
binding.udx_napi_socket_send_ttl(
|
||||
this._handle,
|
||||
req.handle,
|
||||
id,
|
||||
buffer,
|
||||
port,
|
||||
host,
|
||||
family,
|
||||
ttl || 0
|
||||
)
|
||||
|
||||
return promise
|
||||
}
|
||||
|
||||
trySend(buffer, port, host, ttl) {
|
||||
if (this.closing) return
|
||||
|
||||
if (!host) host = '127.0.0.1'
|
||||
|
||||
const family = ip.isIP(host)
|
||||
if (!family) throw new Error(`${host} is not a valid IP address`)
|
||||
|
||||
if (!this.bound) this.bind(0)
|
||||
|
||||
const id = this._allocSend()
|
||||
const req = this._reqs[id]
|
||||
|
||||
req.buffer = buffer
|
||||
req.onflush = noop
|
||||
|
||||
binding.udx_napi_socket_send_ttl(
|
||||
this._handle,
|
||||
req.handle,
|
||||
id,
|
||||
buffer,
|
||||
port,
|
||||
host,
|
||||
family,
|
||||
ttl || 0
|
||||
)
|
||||
}
|
||||
|
||||
_allocSend() {
|
||||
if (this._free.length > 0) return this._free.pop()
|
||||
const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t)
|
||||
return this._reqs.push({ handle, buffer: null, onflush: null }) - 1
|
||||
}
|
||||
}
|
||||
|
||||
function noop() {}
|
||||
+545
@@ -0,0 +1,545 @@
|
||||
const streamx = require('streamx')
|
||||
const b4a = require('b4a')
|
||||
const binding = require('../binding')
|
||||
const ip = require('./ip')
|
||||
|
||||
const MAX_PACKET = 2048
|
||||
const BUFFER_SIZE = 65536 + MAX_PACKET
|
||||
|
||||
module.exports = class UDXStream extends streamx.Duplex {
|
||||
constructor(udx, id, opts = {}) {
|
||||
super({ mapWritable: toBuffer, eagerOpen: true })
|
||||
|
||||
this.udx = udx
|
||||
this.socket = null
|
||||
|
||||
this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t)
|
||||
this._view = new Uint32Array(
|
||||
this._handle.buffer,
|
||||
this._handle.byteOffset,
|
||||
this._handle.byteLength >> 2
|
||||
)
|
||||
this._view16 = new Uint16Array(
|
||||
this._handle.buffer,
|
||||
this._handle.byteOffset,
|
||||
this._handle.byteLength >> 1
|
||||
)
|
||||
this._view64 = new BigUint64Array(
|
||||
this._handle.buffer,
|
||||
this._handle.byteOffset,
|
||||
this._handle.byteLength >> 3
|
||||
)
|
||||
|
||||
this._wreqs = []
|
||||
this._wfree = []
|
||||
|
||||
this._sreqs = []
|
||||
this._sfree = []
|
||||
this._closed = false
|
||||
|
||||
this._flushing = 0
|
||||
this._flushes = []
|
||||
|
||||
this._buffer = null
|
||||
this._reallocData()
|
||||
|
||||
this._onwrite = null
|
||||
this._ondestroy = null
|
||||
this._firewall = opts.firewall || firewallAll
|
||||
|
||||
this._remoteChanging = null
|
||||
this._previousSocket = null
|
||||
|
||||
this.id = id
|
||||
this.remoteId = 0
|
||||
this.remoteHost = null
|
||||
this.remoteFamily = 0
|
||||
this.remotePort = 0
|
||||
|
||||
this.userData = null
|
||||
|
||||
binding.udx_napi_stream_init(
|
||||
this.udx._handle,
|
||||
this._handle,
|
||||
id,
|
||||
opts.framed ? 1 : 0,
|
||||
this,
|
||||
this._ondata,
|
||||
this._onend,
|
||||
this._ondrain,
|
||||
this._onack,
|
||||
this._onsend,
|
||||
this._onmessage,
|
||||
this._onclose,
|
||||
this._onfirewall,
|
||||
this._onremotechanged,
|
||||
this._reallocData,
|
||||
this._reallocMessage
|
||||
)
|
||||
|
||||
if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq)
|
||||
|
||||
binding.udx_napi_stream_recv_start(this._handle, this._buffer)
|
||||
}
|
||||
|
||||
get connected() {
|
||||
return this.socket !== null
|
||||
}
|
||||
|
||||
get mtu() {
|
||||
return this._view16[binding.offsetof_udx_stream_t_mtu >> 1]
|
||||
}
|
||||
|
||||
get rtt() {
|
||||
return this._view[binding.offsetof_udx_stream_t_srtt >> 2]
|
||||
}
|
||||
|
||||
get cwnd() {
|
||||
return this._view[binding.offsetof_udx_stream_t_cwnd >> 2]
|
||||
}
|
||||
|
||||
get rtoCount() {
|
||||
return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1]
|
||||
}
|
||||
|
||||
get retransmits() {
|
||||
return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1]
|
||||
}
|
||||
|
||||
get fastRecoveries() {
|
||||
return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1]
|
||||
}
|
||||
|
||||
get inflight() {
|
||||
return this._view[binding.offsetof_udx_stream_t_inflight >> 2]
|
||||
}
|
||||
|
||||
get bytesTransmitted() {
|
||||
return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3])
|
||||
}
|
||||
|
||||
get packetsTransmitted() {
|
||||
return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3])
|
||||
}
|
||||
|
||||
get bytesReceived() {
|
||||
return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3])
|
||||
}
|
||||
|
||||
get packetsReceived() {
|
||||
return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3])
|
||||
}
|
||||
|
||||
get localHost() {
|
||||
return this.socket ? this.socket.address().host : null
|
||||
}
|
||||
|
||||
get localFamily() {
|
||||
return this.socket ? this.socket.address().family : 0
|
||||
}
|
||||
|
||||
get localPort() {
|
||||
return this.socket ? this.socket.address().port : 0
|
||||
}
|
||||
|
||||
setInteractive(bool) {
|
||||
if (!this._closed) return
|
||||
binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1)
|
||||
}
|
||||
|
||||
connect(socket, remoteId, port, host, opts = {}) {
|
||||
if (this._closed) return
|
||||
|
||||
if (this.connected) throw new Error('Already connected')
|
||||
if (socket.closing) throw new Error('Socket is closed')
|
||||
|
||||
if (typeof host === 'object') {
|
||||
opts = host
|
||||
host = null
|
||||
}
|
||||
|
||||
if (!host) host = '127.0.0.1'
|
||||
|
||||
const family = ip.isIP(host)
|
||||
if (!family) throw new Error(`${host} is not a valid IP address`)
|
||||
if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)
|
||||
|
||||
if (!socket.bound) socket.bind(0)
|
||||
|
||||
this.remoteId = remoteId
|
||||
this.remotePort = port
|
||||
this.remoteHost = host
|
||||
this.remoteFamily = family
|
||||
this.socket = socket
|
||||
|
||||
if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack)
|
||||
|
||||
binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family)
|
||||
|
||||
this.socket._addStream(this)
|
||||
|
||||
this.emit('connect')
|
||||
}
|
||||
|
||||
changeRemote(socket, remoteId, port, host) {
|
||||
if (this._remoteChanging) throw new Error('Remote already changing')
|
||||
|
||||
if (!this.connected) throw new Error('Not yet connected')
|
||||
if (socket.closing) throw new Error('Socket is closed')
|
||||
|
||||
if (this.socket.udx !== socket.udx) {
|
||||
throw new Error('Cannot change to a socket on another UDX instance')
|
||||
}
|
||||
|
||||
if (!host) host = '127.0.0.1'
|
||||
|
||||
const family = ip.isIP(host)
|
||||
if (!family) throw new Error(`${host} is not a valid IP address`)
|
||||
if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)
|
||||
|
||||
if (this.socket !== socket) this._previousSocket = this.socket
|
||||
|
||||
this.remoteId = remoteId
|
||||
this.remotePort = port
|
||||
this.remoteHost = host
|
||||
this.remoteFamily = family
|
||||
this.socket = socket
|
||||
|
||||
this._remoteChanging = new Promise((resolve, reject) => {
|
||||
const onchanged = () => {
|
||||
this.off('close', onclose)
|
||||
resolve()
|
||||
}
|
||||
|
||||
const onclose = () => {
|
||||
this.off('remote-changed', onchanged)
|
||||
reject(new Error('Stream is closed'))
|
||||
}
|
||||
|
||||
this.once('remote-changed', onchanged).once('close', onclose)
|
||||
})
|
||||
|
||||
binding.udx_napi_stream_change_remote(
|
||||
this._handle,
|
||||
socket._handle,
|
||||
remoteId,
|
||||
port,
|
||||
host,
|
||||
family
|
||||
)
|
||||
|
||||
this.socket._addStream(this)
|
||||
|
||||
return this._remoteChanging
|
||||
}
|
||||
|
||||
relayTo(destination) {
|
||||
if (this._closed) return
|
||||
|
||||
binding.udx_napi_stream_relay_to(this._handle, destination._handle)
|
||||
}
|
||||
|
||||
async send(buffer) {
|
||||
if (!this.connected || this._closed) return false
|
||||
|
||||
const id = this._allocSend()
|
||||
const req = this._sreqs[id]
|
||||
|
||||
req.buffer = buffer
|
||||
|
||||
const promise = new Promise((resolve) => {
|
||||
req.onflush = resolve
|
||||
})
|
||||
|
||||
binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
|
||||
|
||||
return promise
|
||||
}
|
||||
|
||||
trySend(buffer) {
|
||||
if (!this.connected || this._closed) return
|
||||
|
||||
const id = this._allocSend()
|
||||
const req = this._sreqs[id]
|
||||
|
||||
req.buffer = buffer
|
||||
req.onflush = noop
|
||||
|
||||
binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
|
||||
}
|
||||
|
||||
async flush() {
|
||||
if ((await streamx.Writable.drained(this)) === false) return false
|
||||
if (this.destroying) return false
|
||||
|
||||
const missing = this._wreqs.length - this._wfree.length
|
||||
if (missing === 0) return true
|
||||
|
||||
return new Promise((resolve) => {
|
||||
this._flushes.push({ flush: this._flushing++, missing, resolve })
|
||||
})
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
id: this.id,
|
||||
connected: this.connected,
|
||||
destroying: this.destroying,
|
||||
destroyed: this.destroyed,
|
||||
remoteId: this.remoteId,
|
||||
remoteHost: this.remoteHost,
|
||||
remoteFamily: this.remoteFamily,
|
||||
remotePort: this.remotePort,
|
||||
mtu: this.mtu,
|
||||
rtt: this.rtt,
|
||||
cwnd: this.cwnd,
|
||||
inflight: this.inflight,
|
||||
socket: this.socket ? this.socket.toJSON() : null
|
||||
}
|
||||
}
|
||||
|
||||
_read(cb) {
|
||||
cb(null)
|
||||
}
|
||||
|
||||
_writeContinue(err) {
|
||||
if (this._onwrite === null) return
|
||||
const cb = this._onwrite
|
||||
this._onwrite = null
|
||||
cb(err)
|
||||
}
|
||||
|
||||
_destroyContinue(err) {
|
||||
if (this._ondestroy === null) return
|
||||
const cb = this._ondestroy
|
||||
this._ondestroy = null
|
||||
cb(err)
|
||||
}
|
||||
|
||||
_writev(buffers, cb) {
|
||||
if (!this.connected)
|
||||
throw customError('Writing while not connected not currently supported', 'ERR_ASSERTION')
|
||||
|
||||
let drained = true
|
||||
|
||||
if (buffers.length === 1) {
|
||||
const id = this._allocWrite(1)
|
||||
const req = this._wreqs[id]
|
||||
|
||||
req.flush = this._flushing
|
||||
req.buffer = buffers[0]
|
||||
|
||||
drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0
|
||||
} else {
|
||||
const id = this._allocWrite(nextBatchSize(buffers.length))
|
||||
const req = this._wreqs[id]
|
||||
|
||||
req.flush = this._flushing
|
||||
req.buffers = buffers
|
||||
|
||||
drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0
|
||||
}
|
||||
|
||||
if (drained) cb(null)
|
||||
else this._onwrite = cb
|
||||
}
|
||||
|
||||
_final(cb) {
|
||||
const id = this._allocWrite(1)
|
||||
const req = this._wreqs[id]
|
||||
|
||||
req.flush = this._flushes
|
||||
req.buffer = b4a.allocUnsafe(0)
|
||||
|
||||
const drained =
|
||||
binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0
|
||||
|
||||
if (drained) cb(null)
|
||||
else this._onwrite = cb
|
||||
}
|
||||
|
||||
_predestroy() {
|
||||
if (!this._closed) binding.udx_napi_stream_destroy(this._handle)
|
||||
this._closed = true
|
||||
this._writeContinue(null)
|
||||
}
|
||||
|
||||
_destroy(cb) {
|
||||
if (this.connected) this._ondestroy = cb
|
||||
else cb(null)
|
||||
}
|
||||
|
||||
_ondata(read) {
|
||||
this.push(this._consumeData(read))
|
||||
return this._buffer
|
||||
}
|
||||
|
||||
_onend(read) {
|
||||
if (read > 0) this.push(this._consumeData(read))
|
||||
this.push(null)
|
||||
}
|
||||
|
||||
_ondrain() {
|
||||
this._writeContinue(null)
|
||||
}
|
||||
|
||||
_flushAck(flush) {
|
||||
for (let i = this._flushes.length - 1; i >= 0; i--) {
|
||||
const f = this._flushes[i]
|
||||
if (f.flush < flush) break
|
||||
f.missing--
|
||||
}
|
||||
|
||||
while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
|
||||
this._flushes.shift().resolve(true)
|
||||
}
|
||||
}
|
||||
|
||||
_onack(id) {
|
||||
const req = this._wreqs[id]
|
||||
|
||||
req.buffers = req.buffer = null
|
||||
this._wfree.push(id)
|
||||
|
||||
if (this._flushes.length > 0) this._flushAck(req.flush)
|
||||
|
||||
// gc the free list
|
||||
if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
|
||||
this._wfree = []
|
||||
this._wreqs = []
|
||||
}
|
||||
}
|
||||
|
||||
_onsend(id, err) {
|
||||
const req = this._sreqs[id]
|
||||
|
||||
const onflush = req.onflush
|
||||
|
||||
req.buffer = null
|
||||
req.onflush = null
|
||||
|
||||
this._sfree.push(id)
|
||||
|
||||
onflush(err >= 0)
|
||||
|
||||
// gc the free list
|
||||
if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
|
||||
this._sfree = []
|
||||
this._sreqs = []
|
||||
}
|
||||
}
|
||||
|
||||
_onmessage(len) {
|
||||
this.emit('message', this.udx._consumeMessage(len))
|
||||
return this.udx._buffer
|
||||
}
|
||||
|
||||
_onclose(err) {
|
||||
this._closed = true
|
||||
|
||||
if (this.socket) {
|
||||
this.socket._removeStream(this)
|
||||
this.socket = null
|
||||
}
|
||||
|
||||
if (this._previousSocket) {
|
||||
this._previousSocket._removeStream(this)
|
||||
this._previousSocket = null
|
||||
}
|
||||
|
||||
// no error, we don't need to do anything
|
||||
if (!err) return this._destroyContinue(null)
|
||||
|
||||
if (this._ondestroy === null) this.destroy(err)
|
||||
else this._destroyContinue(err)
|
||||
}
|
||||
|
||||
_onfirewall(socket, port, host, family) {
|
||||
return this._firewall(socket, port, host, family) ? 1 : 0
|
||||
}
|
||||
|
||||
_onremotechanged() {
|
||||
if (this._previousSocket) {
|
||||
this._previousSocket._removeStream(this)
|
||||
this._previousSocket = null
|
||||
}
|
||||
|
||||
this._remoteChanging = null
|
||||
this.emit('remote-changed')
|
||||
}
|
||||
|
||||
_consumeData(len) {
|
||||
const next = this._buffer.subarray(0, len)
|
||||
this._buffer = this._buffer.subarray(len)
|
||||
if (this._buffer.byteLength < MAX_PACKET) this._reallocData()
|
||||
return next
|
||||
}
|
||||
|
||||
_reallocData() {
|
||||
this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
|
||||
return this._buffer
|
||||
}
|
||||
|
||||
_reallocMessage() {
|
||||
return this.udx._reallocMessage()
|
||||
}
|
||||
|
||||
_allocWrite(size) {
|
||||
if (this._wfree.length === 0) {
|
||||
const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
|
||||
return (
|
||||
this._wreqs.push({
|
||||
handle,
|
||||
size,
|
||||
buffers: null,
|
||||
buffer: null,
|
||||
flush: 0
|
||||
}) - 1
|
||||
)
|
||||
}
|
||||
|
||||
const free = this._wfree.pop()
|
||||
if (size === 1) return free
|
||||
|
||||
const next = this._wreqs[free]
|
||||
if (next.size < size) {
|
||||
next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
|
||||
next.size = size
|
||||
}
|
||||
|
||||
return free
|
||||
}
|
||||
|
||||
_allocSend() {
|
||||
if (this._sfree.length > 0) return this._sfree.pop()
|
||||
const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t)
|
||||
return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1
|
||||
}
|
||||
}
|
||||
|
||||
function noop() {}
|
||||
|
||||
function toBuffer(data) {
|
||||
return typeof data === 'string' ? b4a.from(data) : data
|
||||
}
|
||||
|
||||
function firewallAll(socket, port, host) {
|
||||
return true
|
||||
}
|
||||
|
||||
function customError(message, code) {
|
||||
const error = new Error(message)
|
||||
error.code = code
|
||||
return error
|
||||
}
|
||||
|
||||
function nextBatchSize(n) {
|
||||
// try to coerce the the writevs into sameish size
|
||||
if (n === 1) return 1
|
||||
// group all < 8 to the same size, low mem overhead but save some small allocs
|
||||
if (n < 8) return 8
|
||||
if (n < 16) return 16
|
||||
if (n < 32) return 32
|
||||
if (n < 64) return 64
|
||||
return n
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
const b4a = require('b4a')
|
||||
const binding = require('../binding')
|
||||
const ip = require('./ip')
|
||||
const Socket = require('./socket')
|
||||
const Stream = require('./stream')
|
||||
const NetworkInterfaces = require('./network-interfaces')
|
||||
|
||||
const MAX_MESSAGE = 4096
|
||||
const BUFFER_SIZE = 65536 + MAX_MESSAGE
|
||||
|
||||
module.exports = class UDX {
|
||||
constructor() {
|
||||
this._handle = b4a.alloc(binding.sizeof_udx_napi_t)
|
||||
this._watchers = new Set()
|
||||
this._view64 = new BigUint64Array(
|
||||
this._handle.buffer,
|
||||
this._handle.byteOffset,
|
||||
this._handle.byteLength >> 3
|
||||
)
|
||||
|
||||
this._buffer = null
|
||||
this._reallocMessage()
|
||||
|
||||
binding.udx_napi_init(this._handle, this._buffer)
|
||||
}
|
||||
|
||||
static isIPv4(host) {
|
||||
return ip.isIPv4(host)
|
||||
}
|
||||
|
||||
static isIPv6(host) {
|
||||
return ip.isIPv6(host)
|
||||
}
|
||||
|
||||
static isIP(host) {
|
||||
return ip.isIP(host)
|
||||
}
|
||||
|
||||
get bytesTransmitted() {
|
||||
return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3])
|
||||
}
|
||||
|
||||
get packetsTransmitted() {
|
||||
return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3])
|
||||
}
|
||||
|
||||
get bytesReceived() {
|
||||
return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3])
|
||||
}
|
||||
|
||||
get packetsReceived() {
|
||||
return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3])
|
||||
}
|
||||
|
||||
get packetsDroppedByKernel() {
|
||||
return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3])
|
||||
}
|
||||
|
||||
_consumeMessage(len) {
|
||||
const next = this._buffer.subarray(0, len)
|
||||
this._buffer = this._buffer.subarray(len)
|
||||
if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage()
|
||||
return next
|
||||
}
|
||||
|
||||
_reallocMessage() {
|
||||
// TODO: move reallocation to native
|
||||
this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
|
||||
return this._buffer
|
||||
}
|
||||
|
||||
createSocket(opts) {
|
||||
return new Socket(this, opts)
|
||||
}
|
||||
|
||||
createStream(id, opts) {
|
||||
return new Stream(this, id, opts)
|
||||
}
|
||||
|
||||
networkInterfaces() {
|
||||
let [watcher = null] = this._watchers
|
||||
if (watcher) return watcher.interfaces
|
||||
|
||||
watcher = new NetworkInterfaces(this)
|
||||
watcher.destroy()
|
||||
|
||||
return watcher.interfaces
|
||||
}
|
||||
|
||||
watchNetworkInterfaces(onchange) {
|
||||
const watcher = new NetworkInterfaces(this)
|
||||
|
||||
this._watchers.add(watcher)
|
||||
watcher.on('close', () => {
|
||||
this._watchers.delete(watcher)
|
||||
})
|
||||
|
||||
if (onchange) watcher.on('change', onchange)
|
||||
|
||||
return watcher.watch()
|
||||
}
|
||||
|
||||
async lookup(host, opts = {}) {
|
||||
const { family = 0 } = opts
|
||||
|
||||
const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t)
|
||||
const ctx = {
|
||||
req,
|
||||
resolve: null,
|
||||
reject: null
|
||||
}
|
||||
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
ctx.resolve = resolve
|
||||
ctx.reject = reject
|
||||
})
|
||||
|
||||
binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup)
|
||||
|
||||
return promise
|
||||
}
|
||||
}
|
||||
|
||||
function onlookup(err, host, family) {
|
||||
if (err) this.reject(err)
|
||||
else this.resolve({ host, family })
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"name": "udx-native",
|
||||
"version": "1.19.2",
|
||||
"description": "udx is reliable, multiplexed, and congestion-controlled streams over udp",
|
||||
"main": "lib/udx.js",
|
||||
"files": [
|
||||
"lib",
|
||||
"prebuilds",
|
||||
"binding.cc",
|
||||
"binding.js",
|
||||
"CMakeLists.txt"
|
||||
],
|
||||
"imports": {
|
||||
"events": {
|
||||
"bare": "bare-events",
|
||||
"default": "events"
|
||||
}
|
||||
},
|
||||
"addon": true,
|
||||
"scripts": {
|
||||
"format": "prettier --write .",
|
||||
"lint": "prettier --check .",
|
||||
"test": "npm run lint && npm run test:bare && npm run test:node",
|
||||
"test:node": "node test/all.js",
|
||||
"test:bare": "bare test/all.js",
|
||||
"test:all": "brittle test/*.js test/slow/*.js",
|
||||
"test:generate": "brittle -r test/all.js test/*.js",
|
||||
"bench": "brittle test/bench/*.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/holepunchto/udx-native.git"
|
||||
},
|
||||
"keywords": [
|
||||
"tcp",
|
||||
"udp",
|
||||
"stream",
|
||||
"reliable"
|
||||
],
|
||||
"author": "Holepunch Inc.",
|
||||
"license": "Apache-2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/holepunchto/udx-native/issues"
|
||||
},
|
||||
"homepage": "https://github.com/holepunchto/udx-native#readme",
|
||||
"engines": {
|
||||
"bare": ">=1.17.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"b4a": "^1.5.0",
|
||||
"bare-events": "^2.2.0",
|
||||
"require-addon": "^1.1.0",
|
||||
"streamx": "^2.22.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"bare-compat-napi": "^1.3.0",
|
||||
"brittle": "^3.1.0",
|
||||
"cmake-bare": "^1.1.10",
|
||||
"cmake-fetch": "^1.0.1",
|
||||
"cmake-napi": "^1.0.5",
|
||||
"is-ci": "^3.0.1",
|
||||
"prettier": "^3.6.2",
|
||||
"prettier-config-holepunch": "^2.0.0",
|
||||
"tiny-byte-size": "^1.1.0"
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Reference in New Issue
Block a user