118 Commits
Author SHA1 Message Date
George Barnett 1c90641b02 Fix sendability issue in NIOResumableUpload (#299)
Motivation:

The HTTPResumableUpload type is non-sendable and bound to a particular
event loop. It holds a ref to a HTTPResumableUploadHandler which is also
non-sendable and bound to a particular event loop which may be different
to the event loop of the upload. This should not be possible: if the
event loops aren't guaranteed to be the same then the upload can't
possibly hold a handler as it must necessarily cross an isolation
domain.

The sendable view of the uploads are also held in a dictionary protected
by a mutex but also provide access to the loop bound holding the upload.
This makes it a little too easy to accidentally use the loop bound value
from the wrong event loop which will lead to a runtime crash.

Modifications:

- Add a sendable view to the HTTPResumableUploadHandler which dispatches
work to the correct event loop
- Replace occurrences of HTTPResumableUploadHandler with its sendable
view in the HTTPResumableUpload
- Extend the sendable view of HTTPResumableUpload and audit calls using
the loop bound value
- Add a test for multi-thread multi-chunk uploads

Result:

Can do multi-chunk multi-thread uploads without runtime crashes
2025-12-09 09:24:30 +00:00
Cameron Robey 6d2afc1728 Remove non-copyable types to fix crash with exclusivity checking disabled (#300)
Workaround a compiler issue in Swift 6.1 with non-copyable types and
exclusivity checking.

### Motivation:

Code introduced in #298, led to a runtime crash when compiling with
`-Xswiftc -enforce-exclusivity=unchecked`. This fixes the issue by
removing non-copyable types from the implementation, whilst retaining a
fix for copy-on-write behaviour.

### Modifications:

- Change LifecycleStateMachine to not use non-copyable types
- Use a `.modifying` state instead to prevent copy-on-write

### Result:

No runtime crash when compiling with exclusivity checks disabled on
swift 6.1, behaviour otherwise unchanged, apart from possible
performance loss from not using non-copyable types.
2025-12-09 09:07:52 +00:00
Cameron Robey a46134557b Fix copy on write behaviour in QuiescingHelper (#298)
Fix a copy on write issue in QuiescingHelper that led to significant
performance problems when the number of channels became large, or
connection churn.

### Motivation:

When using QuiescingHelper, every channel holds onto a reference to
ChannelCollector, which leads to copy on write behaviour for
`openChannels[]`. This has performance issues when a large number of
channels are open (e.g. 25k channels can be hundreds of KB), and every
time a channel is opened, or closed this is copied. As accepting
channels happens on a single NIO thread, this work is all done on that
thread, and can lead to saturation, and no more channels being accepted.

### Modifications:

Move the state into a non copyable LifecycleStateMachine, to avoid the
copies.

### Result:

Overhead from ChannelCollector disappears (as seen in traces from
http://github.com/apple/swift-profile-recorder).
2025-12-04 11:06:22 +00:00
Cory Benfield 7ee281d816 Make a few cleanups to the dripping download handler (#295)
Motivation

The dripping download handler should aim to be as efficient as possible.

Modifications

Avoid creating a second HTTPFields object when we are sending
content-length in the response.
Avoid an extra flush on the response head.

Results

Better performance behaviour.
2025-11-05 10:14:56 -05:00
Guoye Zhang d5578e7b77 Handle absolute-form requests when converting from/to HTTPTypes (#293)
Handle absolute-form requests when converting from/to HTTPTypes.

### Motivation:

HTTPTypes represent modern HTTP/2 / HTTP/3 semantics which do not
support absolute-form requests.

### Modifications:

When converting an absolute-form request to an HTTPRequest, the request
target is converted to its path. When converting an HTTPRequest back,
the user needs to specify which form to convert to.

### Result:

HTTPRequest no longer contains invalid paths when working with cleartext
HTTP/1 proxies.
2025-11-04 12:31:24 -05:00
hamzahrmalik b87fdbf492 Add makeServerConfigurationWithMTLS (#286)
To mirror https://github.com/apple/swift-nio-ssl/pull/545

This allows users to easily create a tls configuration for servers which
want to do mtls, with reloading
2025-10-23 11:07:45 +01:00
Orhan Yigit YazicilarandCory Benfield 382b5fcd88 Drop Swift 5.10 (#289)
### Motivation:

Swift 5.10 is no longer supported, we should bump the swift-tools
version.

### Modifications:

* Update Swift tools version to 6.0
* Remove unnecessary compiler directives

### Result:

Code reflects our support window.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-10-16 15:29:09 +00:00
hamzahrmalik a55c3dd3a8 Callback for certificate reload failures (#283)
Callback for certificate reload failures

### Motivation:

Users might want to emit a metric or log when rotation fails.

### Modifications:

Add a new callback which is called whenever a reload fails. This
callback is given an instance of CertificateLoadFailure which contains
the error. The CertificateLoadFailure type allows us to evolve this in
future
2025-07-23 15:16:42 +01:00
hamzahrmalik 614cedd4b1 Make a new variant of makeReloaderValidatingSources which takes a Configuration (#282)
In #281 we added a Configuration object. Now it's possible to create a
TimedCertificateReloader with a single configuration parameter. The
makeReloaderValidatingSources function should be updated to also take
this parameter
2025-07-22 17:14:25 +01:00
hamzahrmalik 0abfca1a17 Add callback in TimedCertificateReloader to listen for reloads (#281)
Add callback in TimedCertificateReloader to listen for reloads

### Motivation:

Adopter might want to know when a certificate was reloaded, e.g. to emit
a log or metric

### Modifications:

- Add a new callback in the reloader which is called whenever a reload
happens. The closure is passed a struct which tells us which cert and
key were read, and whether or not theyre 'new'
- Change the initializer to take a config struct to make this more
extensible going forward
2025-07-22 09:57:48 +01:00
Orhan Yigit YazicilarandGeorge Barnett 774c274789 Split RequestResponseHandlers into Sendable and non-Sendable variants (#279)
Motivation:
`RequestResponseHandler` and `RequestResponseWithIDHandler` previously
allowed non-`Sendable` Requests to move across event loops by wrapping
it in `UnsafeTransfer`, which disabled the compiler's sendability
checking. Requiring every Response to be `Sendable` would solve the
safety issue but it limits how the handlers can be used.

Modifications:
* Extracted the common logic of both handlers into a single state
machine.
* Modified the original implementations to have Request conform to
`Sendable`
* Introduced two new variants that don't care if the Request is
`Sendable` as promises moving to different event loops would be failed
with an error.
* Removed the UnsafeTransfer type as it is not used anymore.
* Added unit tests to confirm that the Sendable variants allow for
promises for different event loops and non-Sendable variants fail the
promises with an Error.

Result:
* Compiler's sendability checks are restored for the handlers.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-07-03 13:00:21 +01:00
Raphael c6714eeaa4 Responsiveness fallback handler (#278)
### Motivation:

The SimpleResponsivenessRequestMux knows how to handle a few different
requests. For those it doesn’t know how to handle, it responds with a
404.

It would be helpful if the handler had a mode where it optionally
forwards requests it doesn’t know how to handle to a fallback channel
handler so that users can respond to these requests.

### Modifications:

The mux has a new initializer that can configure it to accept unexpected
requests, i.e., those not defined by itself. In this case it will
forward requests down the pipeline. However, its default behavior
remains the same: respond with a 404.

### Result:

When setting up the mux, users can add additional handler to the
pipeline and configure the mux to forward its requests.
2025-06-19 10:35:30 +01:00
Franz Busch 145db1962f TimedCertificateReloader prevents non-self-signed certificates from b… (#274)
…eing loaded

Fix certificate check and make sure all code paths throw an error.

### Motivation:

TimedCertificateReloader currently has an invalid check that
accidecanlly enforces self-signed certificates. Additionally some code
paths of `reload()` did not throw an error which made it hard for the
call site to judge if the reloader was initialized successfully or not.
Further, the missing errors also meant that the `run()` method would
never be able to log these.

### Modifications:

* Updated the certificate check to validate the the public key of the
private key matches the cert's public key (instead of checking the
signature).
* Added three new error cases.

### Result:

* A caller can now be sure that their certificate and private key pair
are valid after calling `reload()` the first time.
* Errors in future reloads will be surfaced using the provided logger
and do not go unnoticed.
* You can actually use the reloader with normal certificates.
2025-05-30 12:31:14 +00:00
Franz Busch 24cb15c9bc Support certificate chains from single PEM in TimedCertificateReloader (#273)
## Motivation

The new `TimedCertificateReloader` currently only supports loading PEM
files with a single cert. It is often the case that a single PEM file
contains an entire certificate chain.

## Modification

Modifies the code to support loading an entire certificate chain from a
single PEM file.

## Result

PEM based certificate chain support in our new
`TimedCertificateReloader`
2025-05-20 14:25:46 +00:00
Gus Cairo 949cf2d3c8 Add a TimedCertificateReloader (#269)
This PR adds a `CertificateReloader` protocol and a
`TimedCertificateReloader` implementation.

A `CertificateReloader` allows for certificate-key pairs to be observed
and updated. A `TimedCertificateReloader` does this every set interval
of time.

This PR also provides an extension on `TLSConfiguration` to enable this
reloading ability in NIO applications, so that updated certificates and
keys can be used during SSL handshakes; as well as conformance of the
`TimedCertificateReloader` to `swift-service-lifecycle`'s `Service`
protocol, for easy composition.
2025-05-14 13:37:05 +01:00
Marc Prud'hommeaux 8526b90bc4 Ignore return value of signal() on Android (#266)
See https://github.com/apple/swift-nio/pull/3181 and
https://github.com/apple/swift-nio/issues/3180
2025-04-09 13:16:39 +00:00
George Barnett a0189d045c Strict concurrency for NIOResumableUpload (#265)
HTTPResumableUpload contains the core logic. It uses an event loop to
synchronize its state internally. Some methods are safe to call from off
of that event loop and have been moved to a new sendable view. The
HTTPResumableUpload type is marked as explicitly not sendable.

As such, most other types now hold on to the sendable view and use that
as the interface to HTTPResumableUpload.

HTTPResumableUploadChannel must be sendable (it's a Channel) and now
uses safe abstractions (where possible).
2025-04-08 09:21:01 +01:00
George Barnett b6b5e1133f Strict concurrency for NIONFS3 and NIONFS3Tests (#264) 2025-04-07 15:09:17 +01:00
George Barnett cf3de22478 Strict concurrency for NIOExtrasPerformanceTester (#263) 2025-04-02 12:26:48 +00:00
George Barnett 1a16877a1b Strict concurrency for HTTPServerWithQuiescingDemo (#262) 2025-04-02 13:20:46 +01:00
George Barnett c92af9d4ef Strict concurrency for HTTPTypes and friends (#259) 2025-04-01 15:44:08 +00:00
George Barnett 7241067079 Strict concurrency for NIOHTTPResponsiveness and NIOHTTPResponsivenessTests (#261) 2025-04-01 15:32:33 +00:00
George Barnett dc6987e77e Strict concurrency for NIOSOCKS (#256) 2025-04-01 14:33:46 +00:00
George Barnett 0447b0359e Strict concurrency for NIOHTTPCompression (#257) 2025-04-01 15:29:54 +01:00
George Barnett 20c59b2d64 Strict concurrency for NIOExtras and NIOExtrasTests (#254) 2025-03-31 11:53:06 +01:00
Guoye Zhang 00f3f72d2f Eliminate hasPrefix usage for pseudo HTTP header names (#248)
UTF8 view is faster than hasPrefix

rdar://144395951
2025-02-15 18:14:17 -08:00
Rick Newton-Rogers 926c3e19e7 Avoid integer overrun in NIOHTTPResponsiveness (#247)
We use 8*10^9 in `NIOHTTPResponsiveness` however this number will
overrun the integer size on platforms with 32-bit pointer-width such as
watchOS.

This change drops down to use 1*10^9 on such platforms.
2025-01-31 16:00:41 +00:00
Eric RosenbergandGeorge Barnett 4804de1953 Responsiveness under Working Conditions (#242)
Implementation of
https://datatracker.ietf.org/doc/draft-ietf-ippm-responsiveness/ (draft
5) with flexible download and upload handlers to suit other use cases as
well.

### Motivation:

The provided handlers are useful for measuring responsiveness and
testing things like performance of proxies

### Modifications:

Add `NIOHTTPResponsiveness` and `NIOHTTPResponsivenessServer`

### Result:

We'll now have an implementation of the Responsiveness under Working
Conditions draft

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-01-21 17:14:26 +00:00
Marc Prud'hommeauxandGeorge Barnett aa0d902637 Android support (#244)
Add Android support

### Motivation:

Support the Android platform.

### Modifications:

Add Android imports and fix the default temporary directory to be
correct for the OS.

### Result:

The package will build and test on Android.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-01-14 16:48:42 +00:00
George Barnett 74a143a79f Fix warnings (#245)
Motivation:

The latest NIO release deprecated a number of APIs and added more
Sendable contraints.

Modifications:

- Use sync APIs where possible
- Use `_deprecated` but not `@deprecated` NIOFileHandle API
- Stop using NIOAny

Result:

No warnings
2025-01-14 11:24:08 +00:00
Eric Rosenberg 066c8e4ccd support h2 stream resets through user events (#241)
Allow applications to trigger HTTP/2 stream resets while using
NIOHTTPTypesHTTP2's codecs

### Motivation:

Resetting streams with specific error codes is required by some
applications such as those implementing the CONNECT method
(see https://datatracker.ietf.org/doc/html/rfc9113#section-8.5-8).
Unfortunately, the HTTP2ToHTTP codecs don't expose this capability to
applications.

### Modifications:

Introduce an outbound user event applications can trigger when needing
to reset an HTTP/2 stream.

### Result:

Now applications can trigger HTTP/2 stream resets while using the codecs
provided by NIOHTTPTypesHTTP2
2025-01-07 08:05:05 +00:00
Rick Newton-Rogers 5c7978016e Enable MemberImportVisibility check on all targets (#240)
Enable MemberImportVisibility check on all targets. Use a standard
string header and footer to bracket the new block for ease of updating
in the future with scripts.
2024-12-13 15:07:05 +01:00
fde9d65d2e Import HTTP resumable upload sample code (#203)
Support HTTP resumable upload.

### Motivation:

Supporting HTTP resumable upload protocol defined in
https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-resumable-upload-05

* Interop version 3: iOS 17.0, macOS 14.0
* Interop version 5: iOS 18.0, macOS 15.0
* Interop version 6: iOS 18.1, macOS 15.1

### Modifications:

2 new public classes, `HTTPResumableUploadHandler` and
`HTTPResumableUploadContext`, and a few other supporting objects to
manage resumable uploads and translate them into regular uploads.

---------

Co-authored-by: Jonathan Flat <jflat@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-12-11 07:39:13 +00:00
Rick Newton-Rogers 3f776e9aaf Migrate CI to use GitHub Actions. (#234)
### Motivation:

To migrate to GitHub actions and centralised infrastructure.

### Modifications:

Changes of note:
* Adopt swift-format using rules from SwiftNIO
* Remove scripts and docker files which are no longer needed

### Result:

Feature parity with old CI.
2024-10-28 14:00:57 +00:00
Rick Newton-RogersandRick Newton-Rogers 4f888611eb LineBasedFrameDecoder.decodeLast handle more frames (#229)
### Motivation:

`LineBasedFrameDecoder.decodeLast` throws an error if there is more than
one frame’s worth of bytes remaining in the buffer.

This is in violation of the `NIOSingleStepByteToMessageDecoder`protocol
requirement that this method be called in a loop until all bytes are
decoded.

### Modifications:

* The method now only throws if the decode operation could not return a
frame and there are bytes left in the buffer (previously only the latter
criterion applied).
* Method documentation is updated.
* Test added.

### Result:

`LineBasedFrameDecoder.decodeLast` can cope with more edge cases.

Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
2024-09-11 16:44:42 +01:00
Dimitri Bouniol d1ead62745 Conditional Response Compression (#225)
* Added support for conditional response compression

* Updated expectations to be fulfilled via a defer

* Updated compression response predicate to return an intent enum rather than a boolean
2024-07-18 16:19:20 +01:00
Joannis Orlandos ef36e67dbb Use oldHeaders.count when reserving capacity in HTTPFields (#223) 2024-05-20 05:05:55 -07:00
David NadobaandCory Benfield 8b9030df7c Enable automatic compression format detection (#208)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-03-26 02:57:29 -07:00
Iceman 3bbec9883a Fix NIOHTTPDecompression bug for multi-request channels (#221)
Motivation:

`NIOHTTPDecompression` erroneously accumulates decompressed data sizes across multiple requests in a single channel, leading to unwarranted `DecompressionError.limit` errors. This affects applications using persistent connections, as the decompression limits are improperly enforced. This change aims to address and rectify this issue.

Modifications:

- Add initialization of `inflated` within `Decompressor.initializeDecoder`.
- Introduced new tests to validate decompression functionality across multiple requests on the same channel

Result:

This fix ensures each request's decompression size is independently considered, eliminating incorrect limit errors, and enhancing reliability for applications using HTTP compression with persistent connections.
2024-03-20 01:58:49 -07:00
Hovik Melikyan c992030a2d Fixed the shutdown order for quiescing demo (#220) 2024-03-18 01:11:05 -07:00
Adam FowlerandFranz Busch a3b640d7dc Make HTTP type conversion code public (#216)
* Make HTTP1 type conversion code public

* Convert HTTP1TypeConversionError to struct

---------

Co-authored-by: Franz Busch <f.busch@apple.com>
2024-02-12 02:25:12 -08:00
Johannes WeissandJohannes Weiss cdd1580a03 LineBasedFrameDecoder: can be a NIOSingleStepByteToMessageDecoder (#217)
Co-authored-by: Johannes Weiss <johannes@jweiss.io>
2024-02-06 16:31:09 +00:00
Adam Fowler 6717fd068f Add RemovableChannelHandler comformance to HTTPType channel handlers (#213) 2023-12-06 10:00:50 +00:00
Alastair Houghton 373b8bba29 Changes for Musl support. (#211)
Make sure we import `Musl` rather than `Glibc`.
2023-11-28 08:38:46 -08:00
George Barnett df34965cd7 Don't reserve capacity for NIOPCAPRingBuffer (#209)
Motivation:

The NIOPCAPRingBuffer can limit the number of fragment or the total
number of bytes in its buffer or both. When configuring the buffer to
limit only the maximum number of bytes it sets the maximum number of
fragments allowed to `.max`. On `init` the buffer has enough capacity
reserved to store tha maximum number of fragments.

This would be a large and potentially totally unnecessary allocation.
That is, if it didn't crash at runtime. It crashes at runtime as
`CircularBuffer` converts the requested capacity to a `UInt32` which
traps if you pass it an `Int.max`.

Modifications:

- Don't reserve capacity on init
- Adjust the test which tests the byte limit to not set a capacity as
  well

Result:

- `NIOPCAPRingBuffer(maximumBytes:)` doesn't crash
2023-11-03 10:04:31 +00:00
Guoye Zhang 798c962495 Add HTTP types adapter for SwiftNIO (#202)
* Add HTTP types adapter for SwiftNIO

* swiftformat

* Guard on Swift 5.8

* Review comments

* Update swift-http-types to 0.1.1

* Update swift-http-types to 1.0.0

* Review feedback

* Review feedback

* Bump minimum Swift version to 5.7.1

* Allow Host in any order
2023-10-20 17:55:23 +01:00
Rick Newton-Rogers 6c3819cf2a Bump minimum Swift version to 5.7 (#207)
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 docs

Result:

Remove support for Swift 5.6, add 5.10
2023-10-04 10:17:34 +01:00
Franz Busch fb70a0f5e9 Use #if canImport(Darwin) where possible (#201) 2023-06-21 14:12:47 +01:00
Cory Benfield 9cdb93e321 Drop Swift 5.5 (#197)
Motivation

Per SwiftNIO's formal version policy, we are ready to drop support for
Swift 5.5.

Modifications

This patch removes the support for 5.5 and all supporting
infrastructure. This includes the test generation functionality, which
is no longer required, as well as the files generated by that
functionality. It updates the dockerfile for 5.8, and it removes all
conditional compilation checks that are now definitionally true.

Result

A nice, clean, 5.6+ codebase
2023-04-13 16:47:28 +01:00
Cory Benfield 0e0d0aab66 Fix documentation and add support for CI-ing it (#196)
* Fix documentation and add support for CI-ing it

* Soundness cleanup
2023-04-11 11:25:17 +01:00