Motivation:
Usually, you spawn a new MultiThreadedEventLoopGroup to run NIO
programs. But if you're a very simple command line utility, that may not
be necessary, so why not just re-use the main thread?
Modifications:
Allow taking over threads and making them EventLoops.
Result:
Fewer threads if you want.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
The names of most of the BSD socket option values were brought over into
their NIO helper properties, with their namespace removed. This vastly
increases the risk of collision, particularly for things like TCP_INFO,
which just became .info.
Modifications:
- Added the prefixes back, e.g. `.info` is now `.tcp_info`.
- Renamed socket type `.dgram` to `.datagram`, as this is the nice clean
API and we should use nice clean names.
Result:
Better APIs
Motivation:
It is valuable to be able to provide additional context for any kind of assertion failure, such as obvious points of API misuse or when the purpose of the assertion itself is unclear.
Modifications:
Added an overload of preconditionInEventLoop() that accepts a message autoclosure parameter in the same fashion as `Swift.precondition(_:file:line:)`. Default the implementation of the original version to calling the new one with an empty message. Add defaulted implementation of the new version which forwards the message closure to precondition(). Add the new message parameter directly to assertInEventLoop() without a forwarder since it is not a customization point.
Result:
It is now possible to optionally provide explanatory messages to be included when the "in event loop" precondition fails, as with any other precondition.
Add Optional ECN MetaData to Addressed Envelope
Motivation:
This is a very small step along the path to #1472
Modifications:
Add an optional metadata field to addressed envelope. Currently the only possible data is ECN information. This is not currently populated anywhere.
Result:
Metadata in place for future work.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Newer Swift 5.3 snapshots have spotted more vars that could be lets.
Modifications:
Made two vars lets.
Result:
The word `let` appears more frequently; the word `var`, less so.
This finishes up the encapsulation that is required to ensure that we
are not leaking libc interfaces to clients but instead vend an
enumeration that they can use. The enumeration is open so although we
may not have the full interface enumerated, users will not be prevented
from using alternate values.
Motivation:
In one of the previous patches, we accidentally merged the deprecation
of `ChannelOptions.Types.SocketOption.init` which will break a lot of
NIO programs.
Modifications:
Undo the deprecation.
Result:
NIOTS builds without warnings.
This adds a new enumeration which encapsulates the socket type values.
This enables ports to provide the same surface with a different name as
necessary.
* NIO: Add new `BSDSocket` namespace
This starts the split of the POSIX/Linux/Darwin/BSD interfaces and the
BSD Socket interfaces in order to support Windows. The constants on
Windows are not part of the C standard library and need to be explicitly
prefixed. Use the import by name to avoid the `#if` conditions on the
wrapped versions. This will allow us to cleanly cleave the dependency
on the underlying C library.
This change adds a `BSDSocket.OptionLevel` and `BSDSocket.Option` types
which allow us to get proper enumerations for these values and pipe them
throughout the NIO codebase.
* Apply suggestions from code review
Co-Authored-By: Cory Benfield <lukasa@apple.com>
Motivation:
Today, we just expect the ELGs passed to the bootstraps to be the
correct ones, if not, we crash.
Modifications:
Offer an alternative `validatingGroup:` `init` that just returns `nil`
if the ELGs are of the wrong types.
Result:
Easier to work with multi-stack systems for example when the user might
pass an ELG for either NIO on Sockets or NIO on Network.framework.
Motivation:
Previously, NIOThreadPool would use super long thread names. Linux
doesn't allow more than 15 bytes (+ \0 char) so in the end they would
never get set at all.
Modifications:
- Shorten NIOThreadPool's thread names
- Only take the first 15 characters of thread names in general on Linux
Result:
We don't lose thread names on Linux.
This furthers the behaviour uniformity of special casing behaviour for
other platforms (e.g. Darwin, Windows) and defaulting to the Linux
behaviour as the rest of the code base assumes that the Linux behaviour
is a reasonable fallback. Ensuring that the paths taken are always
uniformly taken helps identify the changes necessary for a port and make
it easier to reason about the changes.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
There are three different error domains that we deal with in NIO, which
need to be differentiated. Store the error with the domain to ensure
that we can identify the error domain.
This adds the necessary code to add a module constructor for NIO. On
Windows, the socketing subsystem (WinSock) must be explicitly
initialized unlike Unices. Add a module constructor that will be
handled by the C runtime to initialize the subsystem before the module
code is executed so that the user does not need to worry about this.
Since there is no way to inject this in Swift, write a tiny helper in C
and link that into the final NIO binary.
Since swift-package-manager does not support mixed-language directories,
add this to `CNIOWindows` which will need to be statically linked and
must always be imported as `@_implementationOnly` as this cannot be
linked into any user libraries.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
testSafeToExecuteTrue/False accessed an internal property of the event
loop without synchronisation.
Modifications:
Fix the threading issue.
Result:
Tests with TSan happy.
Motivation:
Since #1395, we crash when something is scheduled to an already shutdown
EventLoop. That's a good intent (#1383) but we feel it's a little too
risky right now.
Modifications:
Print an ERROR instead of just crashing.
Result:
Fewer crashes.
A `FileDescriptor` is not necessarily selectable (e.g. Windows), and a
selectable is not necessarily a `FileDescriptor` (e.g. Windows).
This will allow a basic `Selector` on Windows which will use `WSASelect`
to select on sockets for some basic functionality even though
IOCompletionPorts are preferred.
* NIO: implement core counting on Windows
Implement the core counting logic for Windows, which does not support
`sysconf`. It uses the Windows SDK to get the processor topology and
computes the core count from the topology.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Motivation:
It's not always possible to initialize `HTTPHeaders` with all the headers one needs to set. In such case, the underlying array will be expanded as and when needed upon headers being appended. `Array` provides the means to reserve capacity to optimize such use case. This PR exposes this functionality in `HTTPHeaders`.
Modifications:
Expose method `reserveCapacity(_ minimumCapacity: Int)` and computed variable `capacity: Int` in `HTTPHeaders` and added some tests.
Result:
Developers will be able to control the capacity of the underlying headers array as such:
```
var headers = HTTPHeaders()
headers.reserveCapacity(5)
```
Co-authored-by: Ludovic Dewailly <ldewailly@apple.com>
Treat the `autoreleasepool` case for Darwin as the special case rather
than Linux as the special case. This is following the case throughout
the rest of the code base. This is also needed for the Windows port.
The path was duplicated because the compiler was not previously able to
optimize with the constant value and would generate poor code. This has
now been addressed, so unify the blocking and non-blocking paths.
Co-authored-by: Cory Benfield <lukasa@apple.com>
In most of the code, Linux is treated as the fallback case. This
adjusts the selector implementation to follow the same pattern, checking
if on Darwin and using kqueue (which would also be available on F/BSD)
and otherwise falling back to `epoll` (assuming Linux). This
homogeneous behaviour makes it easier to reason about when trying to add
support for additional platforms.
Replace the non-portable `u_*_t` types with the C standard `u*_t` types
instead. Remove the Unix headers as the only headers really needed are
the C standard headers. Provide shims for deprecated `strings.h`
functions in terms of "modern" (C89+) functions from `string.h`. Move
an android only include into the implementation from the interface.
This enables building this library on Windows.
Co-Authored-By: George Barnett <gbrntt@gmail.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
* prevent execution of tasks on an already shutdown EL
* fixup! prevent execution of tasks on an already shutdown EL
* fixup! prevent execution of tasks on an already shutdown EL
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Motivation:
To read the bytes from timerfd, we use Glibc.read directly but we should use try! Posix.read
Modifications:
Using Posix instead of Glibc for read operation with try! to check for any error.
Result:
Fixes#1341
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
* removed decodeLast function from NIOChatServer
* updated decodeLast function from WebSocketFrameDecoder
* default implementation of decodeLast function
* removed implementation of decodeLast in WebSocketFrameDecoder
Motivation:
The macOS build was broken by #1424, also the Thread.swift file became
a bit of a mess with `#if os(...)/#else` everywhere.
Modifications:
- fix macOS build
- cleanup Thread by splitting it into ThreadPosix & ThreadWindows
Result:
- build working again
- cleaner code
This restructures `Thread` to have a more generic representation of a
thread handle. Using that it is possible to have an implementation of
the threading APIs for Windows.
Similarly, introduce an abstraction over the Thread Specific Key. This
allows us to abstract away the key type and the usage.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Add support for Windows to the `NIOConcurrencyHelpers`, replacing the
`pthreads` usage for Windows threading primitives.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
* Add offset writes and file size support to NonBlockingFileIO
Motivation:
NonBlockingFileIO currently only supports writes from 0 or appending,
if opened with O_APPEND. To facilitate random read/write file access
the API needs to evolve.
Modifications:
- Add toOffset function parameter to write for offset file write access
- Add changeFileSize function for growing or shrinking the file
- Add readFileSize function for asynchronously reading the file size
Result:
- Improve API for random access scenarios
- Provide method for reading and writing file size
* Conform to code review
* Formatting
* Update Sources/NIO/NonBlockingFileIO.swift
Co-Authored-By: Johannes Weiss <johannesweiss@apple.com>
* Update Sources/NIO/NonBlockingFileIO.swift
Co-Authored-By: Johannes Weiss <johannesweiss@apple.com>
* Modify offset handling to support partial writes.
Clean up stray comment.
* Fix precondition check within offset pwrite handling
* Improve guard for readability
* White space cleanup
* Single spacing issue
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
On LLP64 hosts, `Int` is mapped to `intptr_t` and `UInt` to `uintptr_t`.
As a result, we need to ensure that we map the atomic extensions to
those types for type conversions.
Add the types for `uintptr_t` and `intptr_t` so that they can be used to
implement `CNIOConcurrencyHelpers` on Windows.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Motivation:
Resolve#1409
Modifications:
Using withContiguousStorageIfAvailable if string.utf8 supports an internal representation in a form. Otherwise, fall back to use withUnsafeBufferPointer.
Result:
Save an allocation for each hash function update
On LLP64 platforms, `Int` is mapped to `intptr_t` and `UInt` is mapped
to `uintptr_t`. Use the newly minted `CNIOAtomics` operations to
support these semantics.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>