Commit Graph
1765 Commits
Author SHA1 Message Date
Cory Benfield 86d05fb79f Mark retroactive conformances appropriately. (#2569)
Motivation:

In nightly Swift, we now need to mark retroactive conformances when
they are intentional. These conformances are safe for us, so we can
safely suppress the warnings.

Modifications:

- Mark NIOFoundationCompat retroactive conformances.

Result:

Nightly builds work again
2023-10-23 19:00:13 +01:00
Si Beaumont f71ae34747 Support disabling body aggregation in NIOHTTP1TestServer (#2563) 2023-10-20 17:53:17 +01:00
Johannes Weiss eb2757d88d NonBlockingFileIO: tolerate chunk handlers from other ELs (#2562) 2023-10-19 12:46:28 -07:00
hamzahrmalikandCory Benfield a41b02c580 Avoid terminating when a precondition is not met in HTTPServerPipelineHandler (#2550)
* Avoid terminating when a precondition is not met in HTTPServerPipelineHandler

* Address review comments

* rename precondition to assertion

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-10-18 06:26:43 -07:00
Rick Newton-Rogers c2da95cca3 Remove continuation resumption inside locks (#2558)
Motivation:

Whilst investigating deadlocking code elsewhere we discovered that
resuming a continuation inside a lock can call deadlocks.

The reason is that
- `withTaskCancellationHandler` takes a sequence's
underlying runtime lock then executes the cancellation handler.
- The task cancellation handler then does work which requires taking the
  NIO-level lock
- If a NIO method on a separate thread then takes the NIO-level lock and
  within it resumes a continuation e.g. in `yield` we will deadlock
because the resumption attempts to obtain the underlying runtime lock.

Modifications:

Do not resume continuations within locks.

Result:

Fewer deadlock opportunities
2023-10-17 16:36:52 +01:00
Franz Busch f38b7fd38a Remove SPI from NIOAsyncChannel, new bootstrap methods, protocol negotiation and HTTP upgrade. (#2548)
# Motivation
Over the past months, we have been working on new async bridges to make using NIO's `Channel` from Swift Concurrency possible. Since this work was far reaching we have opted to land all of it as SPI. Now the time has come and we feel confident enough to make the SPI official API. This comes after testing the new APIs in various scenarios such as HTTP 1&2, HTTP upgrades, protocol negotiation and in benchmarks.

# Modification
This PR removes the SPI from the `NIOAsyncChannel`, the bootstrap methods, protocol negotiation and HTTP upgrade.

# Result
Everyone can use the our new APIs🚀
2023-10-17 14:14:02 +01:00
Franz Busch 0fb8cb7947 Add docs for the async NIO APIs (#2549) 2023-10-16 15:02:43 +01:00
Franz Busch dda031625c Remove NIOProtocolNegotiationResult (#2554)
# Motivation
After playing around more with the new async bootstrap methods, I came to the conclusion that the `NIOProtocolNegotiationResult` isn't carrying its weight. The `NIOProtocolNegotiationResult` is a glorified `EventLoopFuture` with an easy way to recursively resolve nested futures. Furthermore, it forces any nested protocol negotiation to use the same generic type for the end result.

# Modification
This PR removes the `NIOProtocolNegotiationResult` and changes all the tests to be solely based on `EventLoopFuture`s.

# Result
Less code to support the async bootstrap and better composition of nested protocol negotiation handlers.
2023-10-16 13:10:29 +01:00
Franz Busch 17eab37e93 Fix Sendable conformance for Lock (#2556)
# Motivation
The latest nightly toolchains have merged the patch that removes `Sendable` conformance from the various `Unsafe*Pointer` APIs. Our `Lock` type was using such a type internally and had a `Sendable` conformance. This conformance was now failing since the pointer was no longer `Sendable`.

# Modification
This PR changes the `Sendable` conformance of `Lock` to `@unchecked Sendable`.

# Result
No more `Sendable` warnings in non-strict mode on nightly toolchains
2023-10-16 03:48:45 -07:00
Lorenzo Fritzsch 7954dba6de Add jitter support to recurring tasks (#2542)
* Add jitter support

* Add jitter support to all functions managing recurring tasks

* Fix typo

* Fix typos

* PR fixes

* Remove unnecessary `@preconcurrency` annotations.

* Fix tests
2023-10-13 11:13:30 +01:00
Franz Busch 2910d6b203 Call NIOAsyncWriterSinkDelegate outside of the lock (#2547)
* Call `NIOAsyncWriterSinkDelegate` outside of the lock

# Motivation
The current `NIOAsyncWriter` implementation expects that the delegate is called while holding the lock to avoid reentrancy issues. However, this prevents us from executing the delegate calls directly on the `EventLoop` if we are on it already.

# Modification
This moves all of the delegate calls outside of the locks and adds protection against reentrancy into the state machine.

# Result
Less allocations.

Clarify the reentrancy problems in docs and protect against them in the writer

* Code review
2023-10-12 08:33:51 -07:00
Lorenzo FritzschandGeorge Barnett 421fcec525 Fix overflow (#2543)
* Fix overflow

* Replace unchecked operation `&*` with `multipliedReportingOverflow` method and add unit tests for underflow/overflow cases

* PR fixes

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2023-10-12 07:07:52 -07:00
Johannes Weiss 8c3cac7774 perf tests: reset BB indices after every iteration (#2544) 2023-10-10 16:15:11 +01:00
Franz Busch 94cc73dfbb Improve performance of NIOAsyncChannel (#2539)
* Implement fast paths for `AsyncChannelInboundStreamChannelHandler`

* Add `_TinyArray` from `swift-certificates`

* Implement single element customization point in `NIOAsyncChannelOutboundWriterHandler`

* Call the single element optimization more often and store suspended producers in `_TinyArray`.

* Update thresholds

* Fix compiler warning
2023-10-09 07:39:25 -07:00
Franz Busch c2d8eed7e6 Add customization point for scheduling ExecutorJobs on EventLoops (#2538)
# Motivation
Currently, the NIO's EventLoop conformance to the `SerialExecutor` protocol always uses `execute` to schedule the actual job. However, the closure for `execute` has to close over the job and the `EventLoop` itself; hence, it always allocates. Since jobs are a very fine grained object in Concurrency that are created a lot this lead to millions of allocations in even small benchmarks.

# Modification
This PR provides a customization point for `EventLoop`s to execute `ExecutorJob`s directly. For `SelectableEventLoop` we store a type erased `UnownedJob` in our `ScheduledTask` and just run it right away.

# Result
No more allocations when NIO's EL is used as a `SerialExecutor`.
2023-10-09 06:00:57 -07:00
Franz Busch 4ab8b98f9d Introduce new typed HTTPClientUpgrader and WebSocketClientUpgrader (#2526)
* Introduce new typed `HTTPClientUpgrader` and `WebSocketClientUpgrader`

# Motivation
In my previous PR https://github.com/apple/swift-nio/pull/2517, I added a new typed `HTTPServerUpgrader` and corresponding implementation for the `WebSocketServerUpgrader`. The goal of those is to carry type information across HTTP upgrades which allows us to build fully typed pipelines.

# Modification
This PR adds a few things:
1. A new `NIOTypedHttpClientUpgradeHandler` + `NIOTypedHttpClientProtocolUpgrader`. I also moved the state handling to a separate state machine. Similar to the server PR I did not unify the state machine between the newly typed and untyped upgrade handlers since they differ in logic.
2. A new `NIOTypedWebSocketClientUpgrader`
3. An overhauled WebSocket client example.

# Result
This is the last missing piece of dynamic pipeline changing where we did not carry around the type information. After this PR lands, we can finalize the `AsyncChannel` and async typed NIO pieces.

* Remove availability on the protocols
2023-10-06 16:33:25 +01:00
Franz Busch 6dd3e08b8e SPI(AsyncChannel): Update the concurrency documentation (#2529)
# Motivation
We have done quite some changes on the new async interfaces and our documentation needs some updating.

# Modification
This PR updates the concurrency interop documentation to reflect the latest APIs.
2023-10-04 07:50:40 -07:00
David Nadoba d367dc0a87 Tolerate empty HTTP response body parts (#2531)
* Tolerate empty HTTP response body parts

### Motivation

Empty HTTP response body parts currently eagerly end a response. This is unexpected and against NIOs documented behaviour.

### Modification

- add test which send an empty response body part and would previously fail
- skip empty response body parts

### Result

Users can send empty body parts without ending the response.

* add comment explaining why we do it here instead of fixing it at the source

* move empty body part logic to `writeChunk`
2023-10-04 06:42:26 -07:00
Franz Busch f114f99f20 SPI(AsyncChannel): Make NIOAsyncChannel a struct (#2528)
# Motivation
To reduce allocations when wrapping a channel into a `NIOAsyncChannel` we should make the `NIOAsyncChannel` a struct instead of a class.

# Modification
This PR changes the `NIOAsyncChannel` to a struct.
2023-10-04 10:34:11 +01:00
Franz Busch 44a7487246 Breaking SPI(AsyncChannel): Align back pressure naming (#2527)
# Motivation
We spelled back pressure a few different ways throughout our async interfaces.

# Modification
This PR aligns to `backPressure` everywhere and uses `back pressure` in comments.
2023-10-03 15:41:50 +01:00
Franz Busch 388b85a2e6 Fix Sendable warning in NIOPipeBoostrap (#2530)
# Motivation
We were accessing `self` in a `@Sendable` function in the `NIOPipeBoostrap`. The 5.10 compiler correctly diagnoses this as a Sendable violation since the bootstrap is in-fact not Sendable.

# Modification
Store the `channelOptions` in a local variable outside of the `@Sendable` function.

# Result
No more Sendable warnings on 5.10
2023-10-03 14:21:59 +01:00
Franz Busch de07e573d6 Introduce new typed HTTPServerUpgrader and WebSocketServerUpgrader (#2517)
* Introduce new typed `HTTPServerUpgrader` and `WebSocketServerUpgrader`

# Motivation
With our new `NIOAsyncChannel` and typed bootstrap APIs we want to be able to let users spell out their pipeline in a typed way. Pipelines can contain handlers that have to make a forking decision such as HTTP upgrading. Our current `HTTPServerUpgradeHandler` is one of those handlers but it lacks strict typing. To interact nicely with our new typed APIs we need to have a new variant of the `HTTPServerUpgradeHandler` that can carry type information.

# Modification
This PR adds a few things:
1. A new `NIOTypedHTTPServerUpgradeHandler` + `NIOTypedHTTPServeProtocolUpgrader`. I also moved the state handling logic to a separate state machine. I thought about unifying the state machines of the _old_ handler and the new one but they differ in behaviour which makes the state machine more complicated.
2. A new `NIOTypedWebSocketServerUpgrader` that conforms to `NIOTypedHTTPServerProtocolUpgrader`
3. An overhauled WebSocket server example that fully uses Concurrency.

# Result
We now have a way to fully type the server side of HTTP protocol upgrading.

Code review

Update parameter names for new API and fix example

* Introduce new configuration struct and rename to `UpgradablePipeline`

* Review comments
2023-10-02 07:26:16 -07:00
Rick Newton-Rogers 67553a7d6d Bump minimum Swift version to 5.7 (#2524)
* Bump minimum Swift version to 5.7

Motivation:

Now that Swift 5.9 is GM we should update the supported versions and
remove 5.6

Modifications:

* Update `Package.swift`
* Remove `#if swift(>=5.7)` guards
* Delete the 5.6 docker compose file and make a 5.10 one
* Update integration test script
* Update docs

Result:

Remove support for Swift 5.6, add 5.10

* fix indentation issues

* 5.9 docker image use release image
2023-10-02 11:38:07 +01:00
Stanislav Yaglo e4aaf2ca35 Update CNIOSHA1.h to support C++ mode (#2523) 2023-09-27 10:46:26 +01:00
Michael StackandCory Benfield ebb271a6a9 Fix failed c++ compile of CNIOAtomics.h (#2518)
Motivation:

    On c++ compile, we get 'error: unknown type name '_Bool' DECLARE_ATOMIC_OPERATIONS(_Bool, _Bool)'

    The c++ compile is happening when SwiftPM builds a module
    with swiftSettings: [.interoperabilityMode(.Cxx)] set and
    where nio is a dependency.

Modifications:

* Sources/CNIOAtomics/include/CNIOAtomics.h

 Conditionally, if __cplusplus, use bool type instead of
 _Bool (a c-type only) for booleans.

Result:

 Compiles where previous it error'd.

After your change, what will change.

 No change other than now it compiles under c++.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-09-20 23:40:54 -07:00
Franz Busch 37c1a793a4 Remove ProtocolNegotiationHandler protocol (#2519)
# Motivation
When we created the first round of new async bootstrap APIs we added a `ProtocolNegotiationHandler` protocol to identify handlers that are doing protocol negotiation. Since then, we have changed the way how the async bootstraps work and we no longer need this protocol.

# Modification
Remove the `ProtocolNegotiationHandler` protocol
2023-09-20 18:05:50 +01:00
Cory Benfield 3db5c4aeee Support for custom protocols in DatagramBootstrap (#2516)
Motivation

This patch adds support for custom protocol families to
DatagramBootstrap. In most cases this isn't useful, and will fail, but
in many OSes it's a recognised system for non-root processes to get a
way to send ICMP echo requests. This is worth supporting.

Modifications

- Expose the `ProtocolSubtype` type publicly.
- Add a `protocolSubtype` setter on `DatagramBootstrap`
- Write a test that actually does ICMP as non-root

Results

Users can send ICMP echo requests without root privileges.
2023-09-17 08:03:56 +01:00
Alex Taffe e0d85543d7 Simplify header separator and crlf (#2513)
Everywhere else in the file uses `crlf` and `headerSeperator` when writing those static strings, we shouldn't be using string literals here
2023-09-06 14:52:25 +01:00
Johannes Weiss 4e0248fec4 update CNIOLLHTTP to latest nodejs/llhttp (#2512) 2023-09-04 09:01:59 +01:00
Natik Gadzhi 34a7663c05 Make ByteBuffer Codable (#2509)
This commit adds Codable to ByteBuffer. It encodes in Base64 into a singleValue
container.

- Base64 implementation moved into _NIODataStructures
- Base64 now supports decoding.
2023-08-30 10:32:45 +01:00
Cory Benfield 7d9f892d83 Support users opting-out of us setting framing headers. (#2508)
Motivation:

Right now we always set the framing headers in HTTP requests and
responses that we send. This is a good practice for most users, but
it can cause issues, most notably in responses to CONNECT requests
which requires that we do not set framing headers.

Unfortunately, in NIO's current HTTP/1.1 design it is not possible
for us to suppress these headers. This is because the HTTP encoders
come _earlier_ in the pipeline than the decoders, so the HTTP
encoders do not know structurally what requests they are responding
to.

While we could merge the encoders/decoders, that's a fairly
substantial change. A better short-term change is to offer users
the ability to turn off the NIO header manipulation feature. In
this circumstance, users take on full responsibility for
appropriately framing their HTTP messages.

Modifications

- Add config to HTTPRequestEncoder and HTTPResponseEncoder.
- Plumb this config through.
- Add a bunch of tests.

Result

Users have way more control of HTTP/1.1 messages.
2023-08-22 02:51:05 -07:00
omochimetaru 022999ae6d make public NIOThreadPoolError init (#2503) 2023-08-16 23:59:36 -07:00
495edec1dd Docs: explain the basic safe usage of ByteBuffer (#2499)
* Docs: explain the basic safe usage of ByteBuffer

* Apply suggestions from code review

* Adrress review feedback and clean the note block in inline docc comments

---------

Co-authored-by: Si Beaumont <simonjbeaumont@gmail.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-08-15 13:06:09 +01:00
cdfbb20e92 Adding ByteBuffer.hexDump in xxd and hexdump -C formats (#2475)
* Initial implementation of hexdump for ByteBuffer

* Put that iff back there

* Reword hexDumpShort(): naming, tests, offset and full length support

* Use writerIndex to figure out the convinience end of useful content in the buffer

* hexDumpLong(offset:) — supports offset, and reads full buffer slice, not just readableBytes

* hexDumpLong() extra line failing test

* Using ByteBuffer(string:) instead of the allocator

* Move hexDumps code into ByteBuffer-hexdump.swift

* Optimized String(byte: poadding:)

* Avoid using storage.dumpBytes in hexDumpShort()

* Implemented a cleaner long hexdump

* Implemented the public hexdump API

* Revert ByteBuffer-core.swift to main

* Addressed review feedback!

* hexdump long format with clipped length

* reserve capacity in hexDumpLines

* Addressing review feedback

* String(_ value, radix, padding) and the final test case

* Make the hexDump(format: .detailed) format cleaner

* Spell out if let for Swift 5.8

* Fixed a formatting bug in multiline maxBytes detailed format

* Apply suggestions from code review

Co-authored-by: George Barnett <gbarnett@apple.com>

* Cleaner way to dump a line in .detailed format

* Cleaner generic argument type for String(_, radix:, padding:)

* Revert _storage.dumpBytes test to match previous format

* Simplify printable bytes closure to a single expression so Swift 5.6 is happy

---------

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-08-15 02:39:53 -07:00
taylorswift 8c2654c9c5 match casing of reference links to the casing of the actual referenced declaration/module (#2500) 2023-08-10 00:47:12 -07:00
Johannes WeissandCory Benfield ac695eb00f EventLoopFuture/Promise: only Sendable if Value is Sendable (#2496)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-08-08 03:57:25 -07:00
Franz Busch cf281631ff Avoid using deinit to fulfil the protocol negotiation promise (#2497)
# Motivation

Fixes https://github.com/apple/swift-nio/issues/2494

# Modification
This PR avoids using `deinit` to fulfil the protocol negotiation promise and opts to trap instead when it is being accessed before the handler is added. This allows us to use `handlerAdded` and `handlerRemoved`.

# Result
No more `deinit` usage that can be observed.
2023-08-08 09:17:08 +01:00
Franz Busch 28eb2ac360 AsyncChannel: Provide throwing finish method on test stream (#2493)
# Motivation
We recently provided testing utilities for the `NIOAsyncChannelInboundStream`. On thing that was missing is a way to finish the stream with an error.

# Modification
This PR provides a `finish()` method that takes an error which is thrown from the inbound stream.

# Result
Better way to test code relying on the AsyncChannel work.
2023-08-07 14:21:25 +01:00
finagolfin 1ec71beb8a Get Android building again after #2479 (#2490)
Motivation

NIO wasn't building on Android

Modifications

- Add the right checks for Android

Result

Built and passed all tests on Android AArch64
2023-08-05 07:45:56 +01:00
Si BeaumontandCory Benfield 858cb8927e Add bootstrap APIs for VSOCK sockets (#2479)
* Add bootstrap APIs for vsock sockets

Signed-off-by: Si Beaumont <beaumont@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-08-03 15:03:09 +01:00
Franz Busch 84540145ce Fix leaked promise in NIOTypedApplicationProtocolNegotiationHandler (#2489)
# Motivation
We sometimes leaked a promise in the `NIOTypedApplicationProtocolNegotiationHandler` when the handler was created and immediately deinited.

# Modification
This PR makes sure we always complete the negotiation promise of the handler.

# Result
No more leaked promises.
2023-08-02 11:34:59 +01:00
Cory Benfield 5be5ccb5a7 Initial PoC of Custom Actor Executor support (#2388)
* Support NIO Event Loops as actor executors

Motivation

Swift Concurrency supports having actors opt in to executing
within a "custom executor". This requires being able to be strictly
serial, a constraint that NIO's EventLoops natively meet. It is
useful to have actors be able to express a "tie" to an EventLoop
in order to efficiently access objects that are tied to specific ELs.

Modifications

- Extend EventLoop to expose an executor property
- Provide a simple best-effort default using NIODefaultSerialEventLoopExecutor
- Expose NIOSerialEventLoopExecutor protocol that makes it easy
  for adopters to get a better implementation
- Crash if EmbeddedEventLoop is used
- Add tests

Result

Adopters can use ELs as serial executors

* Prefer #if compiler
2023-07-31 07:19:49 -07:00
e20271f4a3 Make System.coreCount aware of cgroup2 (#2394)
Motivation:

The count already appears to be aware of cgroup1
but doesn't have logic to support cgroup2.

Modifications:

Add logic to parse /sys/fs/cgroup/cpu.max
For details see - https://stackoverflow.com/questions/65551215/get-docker-cpu-memory-limit-inside-container/65554131#65554131

Result:

Core count will adapt if constrained by a cgroup on more modern kernels.

---------

Co-authored-by: Max Desiatov <m_desiatov@apple.com>
Co-authored-by: Gwynne Raskind <gwynne@darkrainfall.org>
2023-07-31 05:50:24 -07:00
Cory BenfieldandFranz Busch 30595ad289 Don't lose or delay writes before channelActive (#2486)
* Don't lose or delay writes before channelActive

Motivation:

In rare circumstances, some users have reported hangs, delays, or
lost writes when writing network proxies. These proxies have
typically been derived from our TLSify example:
https://github.com/apple/swift-nio-examples/tree/main/TLSify

This proxy makes its outbound connections in handlerAdded.
Generally this works without issue, as the connection takes
long enough to set up that channelActive fires before the
outbound connection has been made.

However, in some rare circumstances it is possible to both make an
outbound connection, have it succeed, _and_ read from the network
on that connection before NIO activates the inbound channel. This
would cause users to lose writes.

This violates a cardinal NIO rule: writes should never be lost.
If it is practical for us to delay them and apply them later, we
should. This patch addresses several holes in this area to correctly
handle these outbound writes.

The first hole is that we would fail writes if the Channel wasn't
yet active. This constraint was unnecessary: it was added in a
refactor to use an internal state machine, and while we had a test
that this happened, it didn't protect us from anything. We can
safely buffer a write at this point: and indeed, we _do_ buffer
flushes at this point. So the check was unneeded.

The second hole was that, even if we buffered the writes, we
frequently wouldn't unbuffer them again until a flush happened
after channelActive. This didn't happen on _every_ path: in the
rare case that connect() succeeded immediately, we would flush
the writes. But in all other cases, including listening
connections, we needed _another_ flush to happen to get the
writes out.

This fix patches up both issues and reconciles the flows. Now
we _always_ try to push out flushed writes when we activate the
Channel, just as we always try to read.

Modifications:

- Remove a check that failed writes if we weren't active.
- Remove a test that validated that we did that.
- Attempt to emit flushed writes on channelActive.
- Make sure we mark ourselves writable if we couldn't write
  it all.
- Make `BaseSocket.getOption` non-final so we can hook it
  in the SAL.
- Make `AcceptHandler` non-private so we can use it in tests.
- Extend the SAL to support `getOption`
- Write several SAL tests to ensure we manage our writes.

Result:

No lost writes.

* Code review feedback

---------

Co-authored-by: Franz Busch <f.busch@apple.com>
2023-07-31 04:13:33 -07:00
Franz Busch fd3076131f Add testing interfaces for the stream and writer of the NIOAsyncChannel (#2488)
# Motivation
When using the `NIOAsyncChannel` to build higher level abstractions it is hard to test right now since one cannot drive the `NIOAsyncChannelInputStream` nor the `NIOAsyncChannelOutputWriter`.

# Modification
This PR adds new factory methods to both of those types which allow to either drive the input stream or record the outputs written to the output writer.

# Result
One can now successfully test their code written on top of the input stream and output writer.
2023-07-31 03:29:41 -07:00
Franz Busch df49d6bde4 Rename the waitForFinalResult() methods and provide an ELF convenience (#2483)
# Motivation
The name `waitForFinalResult()` is bad in a couple of ways. First, we normally use `wait` for blocking operations. Secondly, `finalResult` is also just strange because the user only wants to know the _result_ and doesn't even know that there might be intermediates.

# Modification
This PR renames the `waitForFinalResult()` method to be a property on `NIOProtocolNegotiationResult`. Additionally, it provides a conditional extension on `ELF` to avoid a `get()`.

# Result
Better naming for our async interfaces
2023-07-31 02:19:00 -07:00
Franz Busch b25bc5838f Add async TCP echo example (#2463)
* Add async TCP echo example

# Motivation
We introduced new async APIs to our bootstraps that make it easy to use NIO from Swift Concurrency. We should provide examples showing how to use those new APIs. In the future, we want to make those examples the primary ones and remove the non-async based ones.

# Modification
This PR introduces two new targets: `NIOTCPEchoServer` and `NIOTCPEchoClient`. Both targets are executable and provide either the server or client piece of the example.

# Result
New and shiny async example

* Code review

* Adopt NIO singletons

* Review

* George review
2023-07-31 01:53:41 -07:00
taylorswift 22ae903797 correct malformed codelink (#2484) 2023-07-28 02:58:35 -07:00
Johannes Weiss 6c21f51ff5 NIOSingletons: Use NIO in easy mode (#2471)
### Motivation:

SwiftNIO allows and encourages to precisely manage all operating system resources like file descriptors & threads. That is a very important property of the system but in many places -- especially since Swift Concurrency arrived -- many simpler SwiftNIO programs only require a single, globally shared EventLoopGroup. Often even with just one thread.

Long story short: Many, probably most users would happily trade precise control over the threads for not having to pass around `EventLoopGroup`s. Today, many of those users resort to creating (and often leaking) threads because it's simpler. Adding a `.globalSingle` static var which _lazily_ provides singleton `EventLoopGroup`s and `NIOThreadPool`s is IMHO a much better answer.

Finally, this aligns SwiftNIO a little more with Apple's SDKs which have a lot of global singletons that hold onto system resources (`Dispatch`'s thread pool, `URLSession.shared`, ...). At least in `Dispatch`'s case the Apple SDKs actually make it impossible to manage the resources, there can only ever be one global pool of threads. That's fine for app development but wouldn't be good enough for certain server use cases, therefore I propose to add `NIOSingleton`s as an _option_ to the user. Confident programmers (especially in libraries) are still free and encouraged to manage all the resources deterministically and explicitly.

Companion PRs: 
 - https://github.com/apple/swift-nio-transport-services/pull/180
 - https://github.com/swift-server/async-http-client/pull/697

### Modifications:

- Add the `NIOSingletons` type
- Add `MultiThreadedEventLoopGroup.singleton`
- Add `NIOThreadPool.singleton`

### Result:

- Easier use of NIO that requires fewer parameters for users who don't require full control.
- Helps with #2142
- Fixes #2472
- Partially addresses #2473
2023-07-27 00:59:47 -07:00
Iceman b0d43ec5b6 Fix huge compile time of setUUIDBytes (#2482) 2023-07-26 01:17:48 -07:00