1676 Commits
Author SHA1 Message Date
George Barnett e208367c8e Allow UDP GRO tests to fail in some circumstances (#2387)
Motivation:

The recently added UDP GRO tests fail on some older Linux Kernel
versions. We believe that UDP GRO support on loopback was limited in
early versions so we should tolerate those failures.

However, we've verified that on 5.15 and newer that GRO is supported so
we should not tolerate failure in those cases.

Modifications:

- Add shims to CNIOLinux to get system info via uname
- Verify GRO works before running GRO tests and if it doesn't then
  validate the kernel version isn't greater than 5.15.

Results:

Less flaky tests.
2023-03-13 11:12:06 +00:00
serandCory Benfield 8193940b9a Buffer pool for message headers and addresses. (#2378)
* Pool buffers for messages and addresses.

* Revert changes related to controlMessageStorage

* Cosmetic fix.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-03-10 16:06:02 +00:00
George Barnett d1fa3e29bf Add support for UDP_GRO (#2385)
Motivation:

Support was added for UDP_SEGMENT in #2372 which allows for large UDP
datagrams to be written to a socket by letting the kernel or NIC segment
the data across multiple datagrams. This reduces traversals across the
network stack which can lead to performance improvements. UDP_GRO is the
receive-side counterpart allowing the kernel/NIC to aggregate datagrams
and reduce network stack traversals.

Modifications:

- Add a function in CNIOLinux to check whether UDP_GRO is supported
- Add the relevant socket and channel options
- Add tests

Result:

- UDP_GRO can be enabled where supported and applications may receive
  large buffers.
2023-03-06 07:12:09 -08:00
Rick Newton-Rogers 5f5fa9a2b2 mark syncShutdownGracefully noasync (#2381)
mark syncShutdownGracefully noasync

Motivation:

The code as-is blocks the calling thread.

Modifications:

* mark `EventLoopGroup.syncShutdownGracefully()` and `NIOThreadPool.syncShutdownGracefully()` noasync on Swift > 5.7
* offer NIOThreadPool.shutdownGracefully()
* add renamed to syncShutdownGracefully()
2023-03-02 06:20:23 -08:00
ser 652e01c003 Fix memory binding. (#2376)
* Fix memory binding.

* Cosmetic fix.
2023-03-01 03:54:42 -08:00
Andrew TrickandCory Benfield e63326aa50 Fix an upcoming compiler warning on implicit raw pointer casts. (#2377)
setOption forms a raw pointer to a generic argument. The compiler will
warn on this as of:

[proposal] Constrain implicit raw pointer conversion... #1963
https://github.com/apple/swift-evolution/pull/1963

/Sources/NIOPosix/BaseSocket.swift:286:31: warning: forming
'UnsafeRawPointer' to a variable of type 'T'; this is likely incorrect
because 'T' may contain an object reference.

                option_value: &val,
                              ^

Ideally, this would be fixed by adding a BitwiseCopyable constraint to
the 'value' parameter of 'BaseSocker.setOption'. That would not only
eliminate the warning, but would make the API safer. But
BitwiseCopyable isn't quite ready for public use. In the meantime,
this is a reasonable workaround.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-02-28 00:23:36 -08:00
Johannes WeissandCory Benfield a296f30e45 OnLoopSendable: Sendable containers if on EventLoop (#2370)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-02-27 07:11:37 -08:00
George BarnettandCory Benfield 19b878f461 Add support for UDP_SEGMENT (#2372)
Motivation:

On Linux, the UDP_SEGMENT socket option allows for large buffers to be
written to the kernel and segmented by the kernel (or in some cases the
NIC) into smaller datagrams. This can substantially decrease the number
of syscalls.

This can be set on a per message basis on a per socket basis. This
change adds per socket configuration.

Modifications:

- Add a CNIOLinux function to check whether UDP_SEGMENT is supported on
  that particular Linux.
- Add a helper to `System` to check whether UDP_SEGMENT is supported on
  the current platform.
- On Linux only:
  - add the udp socket option level
  - add the udp_segment socket option
- Add the `DatagramSegmentSize` channel option.
- Get/Set the option in `DatagramChannel`

Results:

UDP GSO is supported on Linux.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-02-27 13:18:58 +00:00
Cory Benfield 108d4646a9 Make our time types transparent (#2374)
Motivation:

Our time types are trivial, and they should be fully transparent. This
produces minor performance improvements in code handling time types, but
is mostly useful in terms of allowing the compiler to observe that these
functions have no side effects, thereby eliding some ARC traffic.

Modifications:

Make our time types inlinable.

Result:

Better performance.
2023-02-21 13:06:06 +00:00
George Barnett 4dfae01cc6 Add a pooled recv buffer allocator (#2362)
Motivation:

Channels can read `ChannelOptions.maxMessagesPerRead` times from a
socket in each read cycle. They typically re-use the same buffer for
each read and rely on it CoWing if necessary. If we read more than once
in a cycle then we may CoW the buffer. Instead of reusing one buffer we
can reuse a pool of buffers limited by `maxMessagesPerRead` and cycle
through each, reducing the chance of CoWing the buffers.

Modifications:

- Extend `RecvByteBufferAllocator` to provide the size of the next
  buffer with a default implementation returning `nil`.
- Add an recv buffer pool which lazily grows up to a fixed size and
  attempts to reuse buffers where possible if doing so avoids CoWing.

Results:

Fewer allocations
2023-02-20 17:00:19 +00:00
Cory Benfield 9afaf801e5 Don't retain a task when all we want is a time (#2373)
Motivation:

To know when we next need to wake up, we keep track of what the next
deadline will be. This works great, but in order to keep track of this
UInt64 we save off an entire ScheduledTask. This object is quite wide (6
pointers wide), and two of those pointers require ARC traffic, so doing
this saving produces unnecessary overhead.

Worse, saving this task plays poorly with task cancellation. If the
saved task is cancelled, this has the effect of "retaining" that task
until the next event loop tick. This is unlikely to produce catastrophic
bugs in real programs, where the loop does tick, but it violates our
tests which rigorously assume that we will always drop a task when it is
cancelled. In specific manufactured cases it's possible to produce leaks
of non-trivial duration.

Modifications:

- Wrote a weirdly complex test.
- Moved the implementation of Task.readyIn to a method on NIODeadline
- Saved a NIODeadline instead of a ScheduledTask

Result:

Minor performance improvement in the core event loop processing, minor
correctness improvement.
2023-02-20 07:27:58 -08:00
carolinacass 5db1dfabb0 Building swift-nio with Swift 5.7 for iOS using Xcode 14.0 at 2.48.0. (#2369)
Motivation:
swift- nio was failing builds that should pass

Modifications:
Adding available to the necessary sections
2023-02-17 10:05:43 -08:00
George Barnett 734a0ba103 Add availability requirements to TCPThroughputBenchmark (#2368)
Motivation:

- Uses Concurrency but missing availability requirements; does not build
  on macOS.

Modifications:

- Add availability requirements/guards

Result:

Compiles on macOS
2023-02-16 11:55:14 +00:00
ser ab43dc6949 TCP channel throughput benchmark. (#2367)
* TCP channel throughput benchmark.

* Cosmetic fixes.

* Add license to the source code.
2023-02-15 16:00:10 +00:00
Cory Benfield 8ccf253641 Clarify on EL semantics (#2366) 2023-02-13 10:10:31 +00:00
Franz Busch b6b62665e9 NIOAsyncWriter: Provide a fast path for single element writes (#2365)
# Motivation
We are currently always allocating a new `Deque` when we get a single element write in the `NIOAsyncWriter`

# Modification
Provide a fast path method on the `NIOAsyncWriterSinkDelegate` protocol which will be called when we receive a single element write and are currently writable.

# Result
Performance win for the single write cases.
2023-02-10 15:16:41 +00:00
Cory Benfield 39047aec7c Make PooledBuffer safer. (#2363)
Motivation:

PooledBuffer is an inherently unsafe type, but its original incarnation
was less safe than it needed to be. In particular, we can rewrite it to
ensure that it is compatible with automatic reference counting.

Modifications:

- Rewrite PooledBuffer to use ManagedBuffer
- Clean up alignment math
- Use scoped accessors
- Add hooks for future non-scoped access

Result:

Safer, clearer code
2023-02-08 07:59:17 +00:00
ser 1e7ad9a0db Pool buffers for ivecs and storage refs in the event loop. (#2358)
* Pool buffers for ivecs and storage refs in the event loop.

* Introduce PoolElement for poolable objects and add some bounds checks for the pooled buffers.

* Some polishes.

* Fix build failure with Swift 5.5/5.6

* User raw pointers instead of typed.
2023-02-07 13:48:26 +00:00
George Barnett dfd4bdad89 Add UDP performance tests (#2360)
Motivation:

We don't have any UDP performance tests.

Modifications:

- Add UDP perf tests

Result:

We can measure perf improvements for UDP.
2023-02-06 15:50:47 +00:00
George Barnett 0d6137f250 Remove unused array (#2361)
Motivation:

The `PendingDatagramWritesManager` unconditionally creates an array and
reserves capacity... only to never use it.

Modifications:

Remove the unsued code.

Result:

Fewer allocations.
2023-02-03 09:25:14 +00:00
Oleksandr ZhurbaandOleksandrZhurba 555f1db039 Special case EventLoopPromise.succeed() when Value is Void (#2311)
Co-authored-by: OleksandrZhurba <56148913+OleksandrZhurba@users.noreply.github.com>
2023-01-19 09:06:07 -08:00
Philip Brown 59e1f6f375 Tail allocate mutex and a generic value using ManagedBuffer (#2349)
Motivation:

Currently, NIOLock and NIOLockedValueBox incur unnecessary allocation and indirection costs.

Modifications:

Create namespace LockOperations for organization
Create LockStorage<Value>, a subclass of ManagedBuffer<LockPrimitive, Value>
Store the mutex as the header and the generic value as the first and only element
Update NIOLock and NIOLockedValueBox to use LockStorage

Result:

Optimal lock and value memory layout
Fewer allocations and less indirection
Code generation is excellent
2023-01-17 16:11:10 +00:00
serandCory Benfield c8ec84ef3b Prepare mmsghdr structure properly. (#2346)
Motivation:

According to the Linux man page the msg_len field supposed to be used to return a number of bytes sent for the particular message.
It does not make a sense to initialize it with a size of the message.

Modifications:

Change msg_leg field initialization, use 0 instead of message size.

Result:

Use sendmmsg() call properly.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-01-12 11:22:56 +00:00
Franz Busch 602989b003 Implement remoteAddress0 and localAddress0 on EmbeddedChannel (#2345)
# Motivation
`EmbeddedChannel` is often used in testing and currently any code under testing that uses `context.localAddress` cannot be mocked, since `EmbeddedChannelCore` is always throwing.

# Modification
Use the same values for `localAddress` in `localAddress0()`. Same for `remoteAddress`

# Result
We can now properly test code that needs local/remote addresses with `EmbeddedChannel`
2023-01-12 02:55:18 -08:00
David Nadoba 1ce136b4c3 Fix main nightly CI (#2337)
* Fix nightly CI

* conditionalization of signal for architecture
2023-01-09 18:34:48 +00:00
Ahmad Alhashemi 91e5b3b609 Allow writing and reading empty datagrams (#2341)
Motivation:

Empty UDP datagrams could be used to have a meaning.
Empty datagrams were being silently dropped on write.
Receiving an empty diagram causes an assertion failure (possible DDoS).

Modifications:

Remove early exit when writing empty datagrams and non-empty assertion when reading them.

Result:

We can now write and read empty datagrams.
2023-01-09 02:45:15 -08:00
Saleem Abdulrasool cd0aa5907b NIOCore: repair the Windows build of NIOCore (#2339)
The addition of the new IP constant resulted in a build failure on
Windows.  Add the import for the equivalent constant to repair the
build.
2022-12-22 16:37:54 -05:00
thomas-gill-0xff b201ff561d Remove useless instance variables in the SelectableEventLoop (#2338)
Motivation:

Less code we have - less bugs we have.
The fix remove few lines of code keeping the same functionality.

Modifications:

Just remove some useless instance variables.

Result:

Less code.
2022-12-21 03:41:44 -08:00
Johannes Weiss 86e8b5f5b5 add easier async to future conversion (#2334) 2022-12-19 11:05:47 +00:00
Cory Benfield a58500af68 Make EventLoopFuture.wait() unavailable from async (#2331)
Motivation:

ELF.wait() waits for a condition variable to become true, which can
frequently lead to extremely long waits. This is a bad thing to call on
a Swift Concurrency thread, especially as we have ELF.get() which is
preferable.

Modifications:

Make ELF.wait() unavailable from async.

Result:

Users are encouraged to use the correct primitive.
2022-12-12 06:13:24 -08:00
Cory Benfield abf2b35e6d Remove implicit ByteBuffer copy in copyMemory (#2330)
Motivation:

withVeryUnsafeBytes has a reference to `self` that it is using. This
necessarily triggers a copy when we subsequently use `self` inside the
block. The effect of that copy is an extra retain/release pair, and a
call to beginAccess, that we simply don't need.

Modifications:

Replace the call to `_setBytesAssumingUniqueBufferAccess` with a
manually inlined equivalent.

Result:

Avoids the extra copy of `self`, removes a retain/release and a
beginAccess.
2022-12-12 11:58:23 +00:00
David Nadoba 810544ec41 Add RawSocketBootstrap (#2320) 2022-12-01 15:35:04 +01:00
Rick Newton-Rogers 00341c9277 cap read+pread POSIX read sizes at Int32.max (#2323)
Cap NonBlockingFileIO reads at Int32.max

Motivation:

We wish to avoid overly large reads resulting in EINVAL signals being
triggered resulting in errors. We workaround the issiue in the
NonBlockingFileIO level to keep the lower levels as simple as possible.

Modifications:

`NonBlockingFileIO` `read0` amends read `byteCount`s to be `Int32.max` if they are larger than that value.

Result:

Large `NonBlockingFileIO` reads no longer result in precondition
failures.
2022-11-28 13:19:12 +00:00
David Nadoba 0b4edd8329 Add NIOBSDSocket.ProtocolSubtype (#2317)
* RawSocket prototype

* Conform `ProtocolSubtype` to `Hashable`

* Add public `NIOIPProtocol` type

Make `ProtocolSubtype` internal

* Subset of IANA protocols with an RFC

* Add `CustomStringConvertible` to `NIOIPProtocol`

* Add `init(_ rawValue: Int)`

* Rename `NIOBSDSocket.ProtocolSubtype.ip` to `.default`

* Add `NIOBSDSocket.ProtocolSubtype.mptcp`

and remove `NIOBSDSocket.mptcpProtocolSubtype`
2022-11-22 06:01:52 -08:00
Cory Benfield dd074002a5 Remove _NIOBeta (#2319)
Motivation:

Having deprecated the NIOBeta entrypoints in #2300, we can now safely
remove it.

Modifications:

Remove all source files in _NIOBeta
Remove the _NIOBeta product and target

Result:

We're ready for 5.8 work!
2022-11-21 14:56:23 +00:00
David Nadoba e855380cb5 Make NIOHTTP1TestServer Sendable (#2318)
`NIOHTTP1TestServer` is actually `Sendable` through an `EventLoop` which is also used as an `EventLoopGroup`.
2022-11-17 17:40:15 +00:00
Cory Benfield 72b8e3f52c Correctly include netinet/in.h (#2315)
Motivation:

IPV6_RECVPKTINFO and IPV6_PKTINFO are not currently directly included.
On Apple platforms, these are found by including netinet/in.h, so we
should include that header directly.

Modifications:

- Add the correct include to shims.c

Result:

Better macOS builds
2022-11-15 01:58:25 -08:00
taylorswiftandCory Benfield 75970eb980 add witnesses for ByteBufferView.reserveCapacity(_:), append(_:), and append(contentsOf:) (#2309)
* add witnesses for ByteBufferView.reserveCapacity(_:), append(_:), and append(contentsOf:)

* align with project style

* fix incorrect ByteBufferView implementations, add unit tests

* use withUnsafeBytes(of:) instead of CollectionOfOne in ByteBufferView.append(_:)

* address review comments

* Add missing Linux tests

Co-authored-by: Cory Benfield <lukasa@apple.com>
2022-11-14 10:01:25 +00:00
Cory Benfield 558e4f2fb8 MPTCP support on Linux (#2308)
Motivation

MPTCP provides multipath capability for TCP connections. This
allows TCP connections to consume multiple independent network
paths, providing devices with a number of capabilities to
improve throughput, latency, or reliability.

MPTCP is not totally transparent, and requires servers to support
the functionality as well as clients. To that end, we should expose
some MPTCP capability.

Importantly, MPTCP uses a number of new socket flags and options.
To enable us to support this when it is available but gracefully fail
when it is not, we've hardcoded a number of Linux kernel constants
instead of relying on libc to expose them. This is safe to do on Linux
because its syscall layer is ABI stable.

Modifications

- Add ClientBootstrap and ServerBootstrap flags for MPTCP
- Plumb MPTCP through the stack
- Add new socket options for MPTCP

Result

MPTCP is supported on Linux
2022-11-09 11:02:45 +00:00
David Nadoba 6e404d1614 Add NIOAsyncTestingChannel.waitForOut/InboundWrite() (#2307) 2022-11-08 11:45:24 +00:00
carolinacass af41276062 Use #fileID/#filePath instead of #file (#2306)
Motivation:

#fileID introduced in Swift 5.3, so no longer need to use #file anywhere

Modifications:

Changed #file to #filePath or #fileID depending on the situation
2022-11-03 16:43:13 +00:00
David Nadoba 06d4028cde Add missing Sendable requirements (#2305) 2022-11-03 14:41:42 +01:00
George BarnettandCory Benfield edfceecba1 Add utilties for reading and writing UUIDs (#2045)
Motivation:

UUIDs are often sent over the wire but writing and reading their bytes
to/from a buffer is a bit of a pain.

Modifications:

- Add utilties to 'NIOFoundationCompat' for reading/writing and
  getting/setting a UUID on a `ByteBuffer`.

Result:

Easier to write/read UUIDs to/from a buffer.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2022-10-31 06:25:28 -07:00
George Barnett d086bab75a Make NIOWebSocketServerUpgrader Sendable (#2304)
Motivation:

The `NIOWebSocketServerUpgrader` is marked as not being `Sendable`, but
it has no mutable state and makes no assumptions about the event loop it
is invoked on, so it should be `Sendable`. The two user-provided
callbacks which are injected in `init` are marked as being `Sendable`
but require Swift 5.7 to express this safely.

Modifications:

- Add `@unchecked Sendable` conformance to `NIOWebSocketServerUpgrader`

Result:

- `NIOWebSocketServerUpgrader` is Sendable.
2022-10-28 08:46:41 -07:00
George Barnett 73eb597aa3 Don't unconditionally remove the HTTPServerUpgradeHandler (#2303)
Motivation:

The `HTTPServerUpgradeHandler` removes itself from the pipeline after an
upgrade and unbuffers any unconsumed reads. If an upgrade starts but
does not complete successfully then the pipeline may be left in an
unknown state.

If, for example, the failure occurs before the user provided upgrade
handler is run then unbuffered writes may be unwrapped by the wrong
channel handler as the wrong type leading to a crash.

Modifications:

- Only remove the upgrade handler and forward buffered writes if all
  parts of the upgrade complete successfully.
- If part of the upgrade fails then fire an error into the channel
  pipeline without removing the server upgrade handler.
- Remove a few unnecessary `map`s.
- Make `httpEncoder` non-optional since and remove associated dead code
  since it can never be `nil`.

Result:

Upgrade handling is safer.
2022-10-28 07:32:43 -07:00
Franz BuschandCory Benfield 1abe64c5e6 Add benchmarks for NIOAsyncWriter and NIOAsyncSequenceProducer (#2301)
# Motivation
We landed the async bridge types a while back but never added allocation and performance tests. Since we expect these types to be used performance critical paths we really should cover those with tests.

# Modification
Extends the allocation counter scaffolding to support async tests. Furthermore, add allocations tests for both the writer and producer. Lastly, I a also added a performance test for the producer.

# Result
We now have baseline tests for the `NIOAsyncWriter` and `NIOAsyncSequenceProducer`

Co-authored-by: Cory Benfield <lukasa@apple.com>
2022-10-26 03:51:20 -07:00
buttaface 6c31c9a46c Add correct C directory function declarations for Android (#2302)
Motivation

Get the Android build working again

Modifications

- Modify close/open/readdir arguments, as they can be null
- Remove mkpath_np, as it's not there on Android

Result

Android builds again and the same tests pass
2022-10-25 18:12:42 +01:00
Cory Benfield 522f08ca68 Move 5.7 beta APIs to NIOCore (#2300)
Motivation:

As 5.7 has shipped we no longer need to keep these APIs in _NIOBeta.
We're going to do a two-stage removal: first we're going to move the
APIs to NIOCore and keep them in _NIOBeta with deprecations on them. In
a later release, we'll remove the APIs from _NIOBeta entirely.

Modifications:

- Move the TimeAmount + Duration APIs to NIOCore
- Deprecate the APIs in _NIOBeta.

Result:

We're on a path to remove _NIOBeta
2022-10-25 15:38:47 +01:00
Cory Benfield b8d72c770a Add support for removing channel options (#2297)
Motivation

Some bootstraps may require the ability to remove
Channel options from the ChannelOption storage in
cases where setting a higher-level flag makes those
options unusable. This patch adds that functionality.

Modifications

Add ChannelOptions.Storage.remove

Result

Users can remove channel options from storage
2022-10-24 20:25:42 +01:00
Artem Redkin d0ebe8da5d adds create directory method (#2296)
Motivation:
Creating directories is a common task.

Modifications:
 - Adds mkdir syscall
 - Adds create directory implementation
 - Test
2022-10-24 15:02:10 +01:00