1781 Commits
Author SHA1 Message Date
Franz Busch 702cd7c56d Fix the typed HTTP upgrade compiler guards (#2594)
The compiler guards were unnecessarily complex and I also didn't cover 3 methods where we used the types.
2023-11-16 03:30:21 -08:00
Franz Busch c46199386c Revert "Back out new typed HTTP protocol upgrader (#2579)" (#2593)
* Revert "Back out new typed HTTP protocol upgrader (#2579)"

# Motivation
We have reverted the typed HTTP protocol upgrader pieces since adopters were running into a compiler bug (https://github.com/apple/swift/pull/69459) that caused the compiler to emit strong references to `swift_getExtendedExistentialTypeMetadata`. The problem is that `swift_getExtendedExistentialTypeMetadata` is not available on older runtimes before constrained existentials have been introduced. This caused adopters to run into runtime crashes when loading any library compiled with this NIO code.

# Modifications
This PR reverts the revert and guard all new code in a compiler guard that checks that we are either on non-Darwin platforms or on a new enough Swift compiler that contains the fix.

# Result
We can offer the typed HTTP upgrade code to our adopters again.

* Add compiler guards
2023-11-15 18:58:27 +00:00
Franz Busch 1040927f12 Add closeOnDeinit to the NIOAsyncChannel init (#2592)
* Add `closeOnDeinit` to the `NIOAsyncChannel` init

# Motivation
In my previous PR, I already did the work to add `finishOnDeinit` configuration to the `NIOAsyncWriter` and `NIOAsyncSequenceProducer`. This PR also automatically migrated the `NIOAsyncChanell` to set the `finishOnDeinit = false`. This was intentional since we really want users to not use the deinit based cleanup; however, it also broke all current adopters of this API semantically and they might now run into the preconditions.

# Modification
This PR reverts the change in `NIOAsyncChannel` and does the usual deprecate + new init dance to provide users to configure this behaviour while still nudging them to check that this is really what they want.

# Result
Easier migration without semantically breaking current adopters of `NIOAsyncChannel`.

* Rename to `wrappingChannelSynchronously`
2023-11-15 05:42:53 -08:00
Franz Busch 118de503e2 Add withInboundOutboud to NIOAsyncChannel and deprecate deinit ba… (#2589)
* Add `withInboundOutboud` to `NIOAsyncChannel` and deprecate deinit based cleanup

# Motivation
We just released our new async NIO APIs and have already gotten quite a bunch of feedback from adopters. One of the feedback was that the deinit based closing that we have added to the `NIOAsyncChannel` has caused problems since it leads to unexpected closure of their `Channel`. Furthermore, it makes it impossible to determine how many open sockets a program has at any given time since deinit based clean up relies on the optimizer and can happen at random times.

# Modifications
This PR adds new inits to `NIOAsyncSequenceProducer` and `NIOAsyncWriter` which disable the `deinit` based clean up and instead replace them with an assertion. This allows developers to still catch these issues at debug time. Furthermore, I added a new `withInboundOutbound` scoped access to `NIOAsyncChannel` which will close the channel at the end of the scope. This still gives users a nice API while not having to care much about closing themselves.

# Result
We are no longer using deinit based clean up and bring back one of the core principles of NIO which is deterministic resource usage.

* Review comments

* Internal labels for closure arguments

* Rename to `executeThenCloseChannel`

* Actually call `sinkDeinitialized`

* Change preconditions

* Move logic to deinits

* Rename to `executeThenClose` and review nits
2023-11-13 03:37:54 -08:00
John HarrisonandCory Benfield fa977dc16b Fixing an issue with CNIOSHA1 missing an #include for the BYTE_ORDER define. (#2584)
When building swift-nio with a system with explicit modules (bazel build rules) I was getting incorrect sha1 results. It turns out the root cause is the `BYTE_ORDER` macro was not defined in my build context.

Using `-Wundef` in clang I was seeing:

```
Sources/CNIOSHA1/c_nio_sha1.c:56:7: error: '__linux__' is not defined, evaluates to 0 [-Werror,-Wundef]
      ^
Sources/CNIOSHA1/c_nio_sha1.c:63:5: error: 'BYTE_ORDER' is not defined, evaluates to 0 [-Werror,-Wundef]
    ^
Sources/CNIOSHA1/c_nio_sha1.c:63:19: error: 'BIG_ENDIAN' is not defined, evaluates to 0 [-Werror,-Wundef]
                  ^
Sources/CNIOSHA1/c_nio_sha1.c:113:5: error: 'BYTE_ORDER' is not defined, evaluates to 0 [-Werror,-Wundef]
    ^
Sources/CNIOSHA1/c_nio_sha1.c:113:19: error: 'LITTLE_ENDIAN' is not defined, evaluates to 0 [-Werror,-Wundef]
                  ^
Sources/CNIOSHA1/c_nio_sha1.c:222:5: error: 'BYTE_ORDER' is not defined, evaluates to 0 [-Werror,-Wundef]
    ^
Sources/CNIOSHA1/c_nio_sha1.c:222:19: error: 'BIG_ENDIAN' is not defined, evaluates to 0 [-Werror,-Wundef]
                  ^
Sources/CNIOSHA1/c_nio_sha1.c:267:5: error: 'BYTE_ORDER' is not defined, evaluates to 0 [-Werror,-Wundef]
    ^
Sources/CNIOSHA1/c_nio_sha1.c:267:19: error: 'BIG_ENDIAN' is not defined, evaluates to 0 [-Werror,-Wundef]
```

The soundness check was not actually signaling an error because it was implicitly comparing 0 to 0.

This change includes an update to the `#include`'s to ensure `BIG_ENDIAN` is defined on macOS and updates the soundness check to have an explicit error if `BYTE_ORDER` is not defined.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-11-09 10:40:55 -08:00
Franz Busch 035141dddb Fix reordering/reentrancy bug in NIOAsyncWriter + NIOAsyncChannel (#2587)
* Fix reordering/reentrancy bug in `NIOAsyncWriter` + `NIOAsyncChannel`

# Motivation
While testing the latest async interfaces we found a potential reordering/reentrancy bug in the `NIOAsyncWriter`. This was caused due to our latest performance changes where we fast-pathed calls in `didYield` to not hop. The problem was in the following flow:

1. Task 1: Calls `outbound.write()` -> which led an `EventLoop` enqueue with `didYield`
2. Task 1: Calls `outbound.write()` -> which led an `EventLoop` enqueue with `didYield`
3. EventLoop: While processing the write from 1. the channel became **not** writable
4. Task 1: Calls `outbound.write()` -> which lead to buffering the write in the writer's state machine since we are **not** writable
5. EventLoop: While still processing the write from 1. the channel became writable again -> We informed the `NIOAsyncWriter` about this which unbuffered the write in 4. that was stored in the state machine and call `didYield`. Since, we are on the EventLoop already we processed the write right away

The above flow show-cases a flow where we reordered the write in 2. and 4.

# Modification
This PR fixes the above issue while upholding a few constraints:

1. Produce as few context switches as possible
2. Minimize allocations

I tried different approaches but in the end decided to do the following:
1. Make sure to never call `didYield/didTerminate` from calls on the `NIOAsyncWriter.Sink`
2. Don't coalesce the elements of different writes in the `NIOAsyncWriter` but rather use the suspended tasks to retry a write after they were suspended. I choose to do this since I wanted to avoid any allocation (remember writers are `some Sequence`) and because we assume that continuous contention in a multi producer pattern is low.
3. Make sure that `Sink.finish()` is terminal and does not lead to a `didTerminate` event. This is in line with 1.

One important thing to call out, our `writer.finish()` method is not `async` we have to buffer the finish event and deliver it with the yield that got buffered before we transitioned to `writerFinished`.

# Result
No more reordering/reentrancy problems in `NIOAsyncWriter` or `NIOAsyncChannel`.

* Code review
2023-11-08 10:38:49 +00:00
George Barnett 23977a932f Fix spelling of retroactive guard (#2586)
Motivation:

`hasFeature(RetroactiveAttribute)` doesn't work as expected, but
`$RetroactiveAttribute` does.

Modifications:

Switch from `hasFeature` to `$RetroactiveAttribute`.

Result:

- `@retroactive` is applied appropriately
2023-11-06 12:38:18 +00:00
Rick Newton-Rogers 853522d908 use feature-specific guard for @retroactive (#2581)
Motivation:

We should use the more granular guard for uses of @retroactive rather
than coarse swift versions to guard against corner-cases

Modifications:

Switch `#if compiler(>=5.11)` for `#if hasFeature(RetroactiveAttribute)`

Result:

No change in most cases, more protected against corner-cases.
2023-11-01 03:34:16 -07:00
Franz Busch 9497e44248 Fix exclusive access violation in NIOAsyncChannelOutboundWriterHandler (#2580)
# Motivation
We were setting `self.sink = nil` in the `NIOAsyncChannelOutboundWriterHandler` twice in the same call stack which is an exclusivity violation. This happens because the first `self.sink = nil` triggers the `didTerminate` delegate call which again triggered `self.sink = nil`.

# Modification
This PR changes the code to only call `self.sink?.finish()` and only sets the `sink` to `nil` in the `didTerminate` implementation. This follows what we do for the inbound handler implementation. I also added a test that triggers this exclusivity violation.

# Result
No more exclusivity violations in our code.
2023-10-27 17:52:46 +01:00
Franz Busch 8c238f2cc1 Back out new typed HTTP protocol upgrader (#2579)
# Motivation
We got reports in https://github.com/apple/swift-nio/issues/2574 that our new typed HTTP upgrader are hitting a Swift compiler bug which manifests in a runtime crash on older iOS/macOS/etc.

# Modification
This PR backs out the new typed HTTP protocol upgrader APIs so that we can unblock our users until the Swift compiler bug is fixed.

# Result
No more crashes for our users.
2023-10-27 15:48:23 +01:00
Franz Busch 740fc734f3 Fix concurrency doc APIs (#2575)
Our Concurrency doc article got a bit outdated when we renamed `inboundStream` and `outboundWriter` to `inbound` and `outbound`
2023-10-26 08:03:51 +01:00
Adam FowlerandCory Benfield 95a4eaa0bc Add async version of NIOThreadPool.runIfActive (#2566)
* Add async version of NIOThreadPool.runIfActive

* Changes from comments in PR

Remove no longer supported code
Add tests for errors being thrown, and the thread pool not being active

* Collapse async runIfActive into one function

* remove whitespace

* Make T Sendable

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-10-25 08:56:00 -07:00
Cory Benfield 54c85cb263 Fix thread-safety issues in TCPThroughputBenchmark (#2537)
Motivation:

Several thread-safety issues were missed in code review. This patch fixes them.

Modifications:

- Removed the use of an unstructured Task, replaced with eventLoop.execute to
  ServerHandler's EventLoop.
- Stopped ClientHandler reaching into the benchmark object without any
  synchronization, used promises and event loop hops instead.

Result:

Thread safety is back
2023-10-25 02:20:49 -07:00
Franz Busch 935dbdf114 Add support for unidirectional NIOPipeBootstrap (#2560)
* Add support for unidirectional `NIOPipeBootstrap`

# Motivation
In some scenarios, it is useful to only have either an input or output side for a `PipeChannel`. This fixes https://github.com/apple/swift-nio/issues/2444.

# Modification
This PR adds new methods to `NIOPipeBootstrap` that make either the input or the output optional. Furthermore, I am intentionally breaking the API for the new async methods since those haven't shipped yet to reflect the same API there.

# Result
It is now possible to bootstrap a `PipeChannel` with either the input or output side closed.

* Docs and naming
2023-10-24 10:18:22 -07:00
Franz Busch 26838898af Add support for async VSock bootstrap methods (#2561)
* Add support for async VSock bootstrap methods

# Motivation
We are about to release our new async bootstrap methods that retain the type information of the various initializers. While developing those we also added support for VSock in NIO; however, we missed adding support for the async bootstrap methods.

# Modification
This PR adds new async bootstrap methods that take a `VSockAddress` and a test for it.

# Result
Support for async VSock bootstrap.

* Update docs
2023-10-24 09:15:05 -07:00
Max Desiatov 39d1be7fc9 Mention file length in bytes in readFileSize explicitly (#2572)
The rest of the functions on `NonBlockingFileIO` are explicit in the fact that they count buffer length in bytes. `readFileSize` should be explicit in its documentation too.
2023-10-24 05:41:04 -07:00
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