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>
Motivation:
The performance of firstIndex and lastIndex is
dramatically improved by addding custom
indexing methods as detailed in issue 1385.
Modifications:
Added methods to ByteBufferView:
_customIndexOfEquatableElement
for firstIndex
_customLastIndexOfEquatableElement
for lastIndex
Added a unit test for firstIndex and lastIndex
to ensure functional behaviour is unchanged.
Result:
firstIndex and lastIndex behave as before.
Performance is improved by approximately 20% for
the shortest searches.
When tested searching over 1024 byte buffer
with either no match or a match at the end
I observed approximately 15 times performance
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Use a macro to define the interface for the typed atomics. This reduces
the boiler plate that is expanded by hand. More importantly, it makes
it easier to add new types in the future.
Co-authored-by: Cory Benfield <lukasa@apple.com>
This removes support for Unix Domain Sockets from NIO on Windows.
Although Windows 10.17063 introduced basic support for UDS, the support
is incomplete and has differences from the tradtional UDS sockets in
terms of behaviour. Excise the support initially to get NIO to build on
Windows.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
For compatibility with 2.13.1 and earlier, we're adding the
AcceptHandler after the serverChannelInitializer runs. If that's the
best solution is discussed in #1392.
Modifications:
- add AcceptHandler after the serverChannelInitializer
- give the AcceptHandler the name AcceptHandler
Result:
- better compatibility
Motivation:
http-parser shipped a patche for node.js CVE-2019-15605, which allowed
HTTP request smuggling. This affected SwiftNIO as well, and so we need
to immediately ship an update to help protect affected users.
A CVE for SwiftNIO will follow, but as this patch is in the wild and
SwiftNIO is known to be affected we should not delay shipping this fix.
Modifications:
- Update http-parser.
- Add regression tests to validate this behaviour.
Result:
Close request smugging vector.
Motivation:
getInteger used the normal, generic implementation for UInt8s, however
they can be made considerably faster by using a specialised method.
ByteBufferIterator was also affected by this.
Modifications:
Use a specialised version for UInt8s for getInteger.
Result:
- ByteBufferView can be iterated about 20% faster.
Motivation:
This updates all vendored code and also lets github know what's vendored
code through `.gitattributes`.
Modifications:
- http_parser update
- attribution
Result:
- better github stats
- up to date software
Motivation:
EventLoopError does not conform to CustomStringConvertible. When these
errors appear in programs depending on NIO the source of the error is
non-obvious to the user.
EventLoopError.shutdown, for example, would appear in logs as
"shutdown" with no indication that it was the event loop being referred
to.
Modifications:
- Conform EventLoopError to CustomStringConvertible
Result:
- More helpful error descriptions for EventLoopError
Motivation:
Often we know ahead of time that we will need to write a certain number
of bytes into a buffer. It is useful to ensure the buffer has enough
capacity to store these bytes without causing unnecessary allocations.
However, `reserveCapacity()` is defined in terms of the capacity of the
buffer and it's can be easy to forget that this does not take into
account the writer index.
Modifications:
- Add a method which reserves enough capacity to write at least the
specified number of bytes.
- Update `writeWithUnsafeMutableBytes(minimumWritableBytes:body:)` to use the
new method.
Result:
It's easier for users to reserve enough writable capacity ahead of time.
resolves#1355 shaving off some bytes from IOError struct
Motivation:
It's important for frequently used errors to fit in existential containers because otherwise throwing them leads to allocations.
Modifications:
- Don't store `StaticString`s anymore which are 2 words + 1 bytes wide
Result:
Fewer allocations when IOErrors are thrown.
Motivation:
The channel initializers should see the the Channel after the options
have been applied so they can potentially override the options.
Modifications:
Set the options before the channel initialiser rather than after.
Result:
- More sense, more compatibility with Netty
- fixes#1114
Co-authored-by: George Barnett <gbrntt@gmail.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Calling `function(otherFunction)` allocates, but
`function({ otherFunction($0) }` does not.
See: SR-12115 and SR-12116.
Modifications:
Avoid passing functions directly; pass them in new closures instead.
Result:
Fewer allocations.
## Motivation:
In SwiftNIO's codebase, most things were always testable just as well as user code is. With one big missing piece: We could never make the `Selector` do arbitrary things to the `Channel` implementations which lead to super expensive to (create, read, understand) integration tests like [`testWriteAndFlushFromReentrantFlushNowTriggeredOutOfWritabilityWhereOuterSaysAllWrittenAndInnerDoesNot `](https://github.com/apple/swift-nio/blob/5dc9083c6a78b10432b4b55b95704e61ca08f09d/Tests/NIOTests/StreamChannelsTest.swift#L468-L760).
## Modification
Add SAL, a 'syscall abstraction layer' which makes it possible to assert all syscalls that come through a `Socket` or the `Selector` by mocking them. It lets the NIO programmer play the kernel in these "SAL tests" which makes it possible to assert the exact syscalls (with their parameters) and decide the syscalls' returns.
## Result
Finally, we're able to write proper unit tests for scenarios where the `Channel` drove the `Selector` incorrectly.
* Recursive file reading not building up EventLoopFuture chain
# Motivation:
After a long discussion with @adam-fowler today in aws-sdk-swift about how to recursively build a streaming interface (see https://github.com/swift-aws/aws-sdk-swift-core/pull/181), we came to the conclusion that it’s probably for the best not to build up an EventLoopFuture chain, since all EventLoopFutures are kept in memory while iterating. It would be better to create a promise that is captured by the recursive function, because in this case the internal EventLoopFutures can be released.
The memory footprint should be O(1) instead O(n) with a EventLoopFuture chain.
Later today, @adam-fowler made me aware of this code in NIO and that it uses a chain.
# Modifications:
```swift
_read(remainingReads: Int, bytesReadSoFar: Int64)
```
The internal read function no longer returns an EventLoopFuture. All Futures end with an `whenSuccess` or `whenFailure` case.
# Result:
From my understanding the memory footprint should be reduced when reading large files. The interface stays completely the same.
Motivation:
Non-functional change: `bind0(_ makeSocketAddress: () throws -> SocketAddress)
-> EventLoopFuture<Channel>` calls `bind0` with a `register` closure that is
passed an event loop as first argument. However, the name of the first parameter
of the closure declaration is named "eventGroup" which is confusing. It should
therefore be renamed to "eventLoop" which is consistent with other closures
passed as `register` arguments at other callsites.
Modifications:
Rename (unused) closure parameter "eventGroup" to "eventLoop".
Result:
Improved code readability.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Motivation:
The `ByteBuffer` API currently has `setString`/`writeString` support for the `String`
type but no support for the `Substring` type (see #1332).
Modifications:
Add `setSubstring`/`writeSubstring` functions to `ByteBuffer`. We do not change
the exisiting set-/writeString API to take a generic `StringProtocol` argument
as it would change the ABI and adds performance overhead. We also do not let
`setString` call into `setSubstring` for now, as Substring currently (as of
Swift 5.1.3) has no fast access to the backing storage and this therefore would
introduce a performance regression.
Result:
ByteBuffer API for writing Substrings.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
improve flushNow re-entrancy protection
Motivation:
The fix in #1344 wasn't complete, there is another, quite complicated scenario where we would still forget to send flushed bytes until we see another `flush` call. The scenario is
1: writable()
2: --> flushNow (result: .writtenCompletely)
3: --> writabilityChanged callout
4: --> flushNow because user calls writeAndFlush (result: .couldNotWriteEverything)
5: --> registerForWritable (because line 4 could not write everything and flushNow returned .register)
6: --> unregisterForWritable (because line 2 wrote everything and flushNow returned .unregister)
Line 6 undoes the registeration in line 5.
Modification:
This fix makes sure that flushNow never re-enters and therefore the problem described above cannot happen anymore.
Result:
Hopefully actually fixes rdar://58571521
Motivation:
We add an empty `bindTimeout` function to `ServerBootstrap`. While
ServerBootstrap itself is based on a blocking socket bind operation, this
enables the possibility of having bind be asynchronous in other use cases and
it unifies the API with other Bootstrap classes, e.g. `NIOTSListenerBootstrap`.
See also #1135.
Modifications:
Add `bindTimeout` function to `ServerBootstrap`.
Add `Bootstrap.testServerBootstrapBindTimeout` test.
Result:
`ServerBootstrap` has a `bindTimeout` function/API compatibility with other
Bootstrap classes.
There is no `ChannelPipeline.addHTTPServerHandlers` but there is `ChannelPipeline.configureHTTPServerPipeline`.
Comment for `HTTPResponseDecoder` mentioning `ChannelPipeline.addHTTPClientHandlers` is correct.
On 32-bit systems we would try to read 4 byte, which is incorrect. From `man timerfd_read`:
> (...) then the buffer given to read(2) returns an unsigned 8-byte integer (uint64_t) containing the number of expirations that have occurred (...)
> A read(2) will fail with the error EINVAL if the size of the supplied buffer is less than 8 bytes.
Motivation:
The class name was a typo.
It is a client upgrader that upgrades WebSocket connections, so the updated name suits better.
Modifications:
Change class name of ‘NIOHTTPWebClientSocketUpgrader’ to ‘NIOHTTPWebSocketClientUpgrader’.
Update the WebSocket client example that uses this class.
Add a typealias to allow the old class name to be used.
Result:
Improved naming.
Motivation:
The byte to message decoder example on the ‘verifyDecoder’ method was not compiling.
Modifications:
Added the example output objects to an array so that they match the method signature.
Result:
The example is now compiling and can serve as the basis for creating an implementation from the example.
Motivation:
`subscript(name:)` and `first(name:)` incorrectly referred users to
`getCanonicalForm` for a maximally decomposed list of header fields.
This no longer exists.
Modifications:
Point users to `subscript(canonicalForm:)`.
Result:
More accurate documenation.
Motivation:
When initializing an `HTTPMethod` with a `String` we currently switch over all expected values to pick an explicit value, only to overwrite our found explicit value with a catchall `RAW(value: String)`. This doesn’t make a ton of sense. This went unnoticed because we use the conditional conformance on `RawRepresentable` to be `Equatable`. But `switch`es don’t use the `Equatable` protocol to match enums. The issue is visible there.
Modifications:
Added a testcase with a switch that fails, if the `.RAW(value: String)` value is used for `”GET”`. Removed the final overwrite in HTTPMethod(rawValue: String). Therefore the test passes.
Result:
We can initialize the HTTPMethod with a String and get an explicit value.
Motivation:
In performance tests was shown that the current base 64 encoding function doesn’t perform very well.
https://github.com/apple/swift-nio/issues/1322
Modifications:
This commit replaces the current Base64 implementation with a more performant one (by using UInt8 bytes instead of Unicode.Scalars).
Result:
The API will stay the same. Base64 encoding is just faster.
Motivation:
`ByteBuffer` should implement the `Hashable` protocol as stated by: https://github.com/apple/swift-nio/issues/1320
Modifications:
Implemented the `Hashable` protocol for `ByteBuffer` and added a test `testHasherUsesReadBuffersOnly`.
Result:
`ByteBuffer` implements the `Hashable` protocol. The test `testHasherUsesReadBuffersOnly` is failing for the moment though.
Motivation:
EmbeddedChannel advanced time to the distant future so that all
scheduled tasks would be run. However, if tasks were recursively
scheduled by executing the already scheduled tasks then the channel
would never finish.
Modifications:
When calling finish() on EmbeddedChannel, only run the tasks which have
been scheduled at that point in time.
Result:
Recursively scheduled tasks terminate when finish-ing the
EmbeddedChannel.
Motivation:
SelectableEventLoop's description was taking a lock and would also lock
every single scheduled task. That's overkill.
Modifications:
Make it only log the thread and selector (which don't require locks).
Result:
better description
Motivation:
Certain issues are easier debugged if we can print the thread names.
Modifications:
- add the thread name to SelectableEventLoop's description
- make EventLoop and NIOThread CustomStringConvertible
Result:
easier debugging.
Motivation:
We incorrectly asserted that HEAD and DELETE may not have request
bodies, but they can, it's just unlikely.
Modifications:
Change the categorisation of HEAD and DELETE.
Result:
Better behaviour in unusual cases.