38 Commits
Author SHA1 Message Date
Cory Benfield f43b37eb31 Make the FileSystem world strict concurrency clean (#3107)
Motivation:

We have a few other file system modules with a small amount of code, and
a lot of tests. Most of these require no changes for strict concurrency,
so let's tackle them all.

Modifications:

Strict concurrency for filesystem targets enabled. Fixed a few incorrect
test case captures.

Result:

Strict concurrency clean filesystem bits.
2025-02-04 11:01:48 +00:00
1e900b4736 NIOFileSystem: Try ${TMPDIR} first for temporary directory (#3067)
### Motivation:

This PR aligns what temp directory NIOFileSystem will return first:
- First try `${TMPDIR}` as it's an expressed user preference
- On Darwin, try `_CS_DARWIN_USER_TMP_DIR` next. If it's set, return
that.
- Finally, fall back on `/tmp` on Darwin and Linux, and
`/data/local/tmp` on Android.

Closes #2861.

### Modifications:

- Reworks `NIOFileSystem.temporaryDirectory`.

### Result:

- NIOFileSystem will now try `${TMPDIR}` first for the temporary
directory.

### Caveats:

- We might want to align how Swift-NIO and FoundationEssentials resolve
temp directory, and [FoundationEssentials have a different
approach](https://github.com/swiftlang/swift-foundation/blob/9d57f36de757b3d5e3a2f7ffcf27aaec3033509f/Sources/FoundationEssentials/String/String%2BPath.swift#L484-L533).
But, I agree with [this
comment](https://github.com/apple/swift-nio/issues/2861#issuecomment-2327010713),
it feels like TMPDIR is an expected default.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
2025-01-27 08:45:46 +00:00
30e1f2e3f4 feat: Add String(contentsOf: FilePath ...) (#3048)
### Motivation:

Makes it possible to read contents of an NIOFileSystem.FilePath into a
String directly. Closes #3010.

### Modifications:

- Added a new `String+FileSystem.swift` into `NIOFileSystem` target.
- Added basic tests to the existing `ConvenienceTests.swift`.
- Added a test to cover `Array+FileSystem` initializer as well.

### Result:

- String initializer for `FilePath` is now available
- Array initializer for `FilePath` now has a test

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-01-16 12:25:15 +00:00
Michael GechtandGeorge Barnett 29c65edb97 Add parallel removal of items (#3008)
Introduce parallel removal of items, instead of only doing a sequential
removal (and discovery) one-by-one

### Motivation:

#2933 mentioned this function call appears to be slow. If we attempt to
delete a directory with lots of subdirectories, we end up discovering
each subdirectory one by one on a single thread.

### Modifications:

This PR refactors the logic to remove items. Instead of sequentially
discovering and deleting items one by one, we traverse all directories
up to a maximum concurrency, and issue file deletions in parallel within
each directory.

### Result:

The new concurrent implementation was measured to be ~1.4x faster than
`FileManager`, ~1.5x faster than `rm -rf` and ~3x faster than the
current sequential implementation on `main`. This new concurrent
implementation does use the most CPU out of all the other approaches.

Results are broken down into two sections. We delete a copy of the
`swift-nio` repository, where the `.build/` folder has grown to a large
size, providing lots of additional files and subdirectories.

We produce a single CLI using `--configration=release` that can switch
between using the `.sequential` mode (what is currently available on the
`main` branch), `.parallel` (the new concurrent implementation in this
PR) and `filemanager` (uses `Foundation.FileManager` as a comparison).

Resolves https://github.com/apple/swift-nio/issues/2933

#### Normal size

**Description:** The `swift-nio` library as found when building the CLI
used for benchmarking.
**Benchmark run with:** 3579 directories, 11657 files

```
$ hyperfine --runs 10 --warmup 2 --prepare "rm -rf /tmp/swift-nio && cp -r $(pwd) /tmp/swift-nio" ".build/release/NIOTestCLI --sequential /tmp/swift-nio" ".build/release/NIOTestCLI --parallel /tmp/swift-nio" ".build/release/NIOTestCLI --filemanager /tmp/swift-nio" "rm -rf /tmp/swift-nio"
Benchmark 1: .build/release/NIOTestCLI --sequential /tmp/swift-nio
  Time (mean ± σ):      2.712 s ±  0.053 s    [User: 0.526 s, System: 8.632 s]
  Range (min … max):    2.625 s …  2.781 s    10 runs

Benchmark 2: .build/release/NIOTestCLI --parallel /tmp/swift-nio
  Time (mean ± σ):     896.7 ms ±  25.6 ms    [User: 302.9 ms, System: 5313.5 ms]
  Range (min … max):   853.2 ms … 942.1 ms    10 runs

Benchmark 3: .build/release/NIOTestCLI --filemanager /tmp/swift-nio
  Time (mean ± σ):      1.337 s ±  0.076 s    [User: 0.022 s, System: 1.253 s]
  Range (min … max):    1.252 s …  1.508 s    10 runs

Benchmark 4: rm -rf /tmp/swift-nio
  Time (mean ± σ):      1.483 s ±  0.037 s    [User: 0.015 s, System: 1.416 s]
  Range (min … max):    1.413 s …  1.541 s    10 runs

Summary
  .build/release/NIOTestCLI --parallel /tmp/swift-nio ran
    1.49 ± 0.10 times faster than .build/release/NIOTestCLI --filemanager /tmp/swift-nio
    1.65 ± 0.06 times faster than rm -rf /tmp/swift-nio
    3.02 ± 0.10 times faster than .build/release/NIOTestCLI --sequential /tmp/swift-nio
```

#### Large size

**Description:** The `swift-nio` library as found after re-running the
`.github` workflow many times locally. I'm unable to reproduce this
directory size, but have benchmarked against it.
**Benchmark run with:** 15260 directories, 46842 files

```
$ hyperfine --runs 10 --warmup 2 --prepare "rm -rf /tmp/swift-nio && cp -r $(pwd) /tmp/swift-nio" ".build/release/NIOTestCLI --sequential /tmp/swift-nio" ".build/release/NIOTestCLI --parallel /tmp/swift-nio" ".build/release/NIOTestCLI --filemanager /tmp/swift-nio" "rm -rf /tmp/swift-nio"
Benchmark 1: .build/release/NIOTestCLI --sequential /tmp/swift-nio
  Time (mean ± σ):     12.082 s ±  0.354 s    [User: 2.180 s, System: 41.547 s]
  Range (min … max):   11.717 s … 12.923 s    10 runs

Benchmark 2: .build/release/NIOTestCLI --parallel /tmp/swift-nio
  Time (mean ± σ):      4.770 s ±  0.102 s    [User: 1.357 s, System: 25.785 s]
  Range (min … max):    4.570 s …  4.883 s    10 runs

Benchmark 3: .build/release/NIOTestCLI --filemanager /tmp/swift-nio
  Time (mean ± σ):      6.503 s ±  0.115 s    [User: 0.081 s, System: 5.427 s]
  Range (min … max):    6.262 s …  6.687 s    10 runs

Benchmark 4: rm -rf /tmp/swift-nio
  Time (mean ± σ):      7.056 s ±  0.246 s    [User: 0.064 s, System: 6.119 s]
  Range (min … max):    6.435 s …  7.233 s    10 runs

Summary
  .build/release/NIOTestCLI --parallel /tmp/swift-nio ran
    1.36 ± 0.04 times faster than .build/release/NIOTestCLI --filemanager /tmp/swift-nio
    1.48 ± 0.06 times faster than rm -rf /tmp/swift-nio
    2.53 ± 0.09 times faster than .build/release/NIOTestCLI --sequential /tmp/swift-nio
```

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2024-12-10 17:43:29 +00:00
Ali Ali 9140817010 Issue-2900 - Add VisionOS support (#2947)
Add Vision support

### Motivation:
https://github.com/apple/swift-nio/issues/2900 - close this

### Modifications:
- Bump SystemPackage to 1.4.0 and remove @preconcurrency 
- remove `#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) ||
os(Linux) || os(Android)` to allow for visionOS support
- Remove conditional import for swift system

### Result:

Vision OS support
2024-10-24 10:26:32 +00:00
Clinton NkwochaandGeorge Barnett cc1c57c291 Provide APIs to read file into more data types (#2923)
Motivation:

As requested in issues
[#2875](https://github.com/apple/swift-nio/issues/2875) and
[#2876](https://github.com/apple/swift-nio/issues/2876), it would be
convenient to be able to read the contents of a file into more data
types such as `Array`, `ArraySlice` & Foundation's `Data`.

Modifications:

- Extend `Array`, `ArraySlice` & `Data` to be initialisable with the
contents of a file.

Result:

The contents of a file can be read into more data types.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2024-10-21 08:41:10 +00:00
Rick Newton-Rogers fcdb6c3bf3 Adopt NIOThrowingAsyncSequenceProducer 2nd try (#2917)
### Motivation:

Adopt `NIOThrowingAsyncSequenceProducer` in NIOFileSystem to reduce code
duplication.

### Modifications:

Adopt `NIOThrowingAsyncSequenceProducer` in NIOFileSystem
`DirectoryEntryProducer` and `FileChunkProducer`.

This change was previously merged and then backed out due to issues
(#2879). The original change is in the first commit, the second commit
contains additional changes.

In the original adoption of `NIOThrowingAsyncSequenceProducer` the code
did not deal with backpressure being applied very well, in some cases
causes hangs.

A key bug was that it was not protected against re-entrant calls to
`produceMore`. Such calls may happen e.g. when the producer has been
asked to pause producing and then resume again before the initial read
had completed. This resulted in overlapping reads and re-ordered data.

This change introduces a new activity state which is protected by a lock
and keeps track of if we are in the critical section to serialize
access.

`DirectoryEntryProducer` performs most of its logic within a lock and so
doesn't seem to be impacted in the same way.

### Result:

No functional changes. Internal changes reduce code duplication.
2024-10-15 10:14:21 +00:00
Clinton Nkwocha 17ebfcd99d [NIOFileSystem] Provide an API to specify allowing unlimited sized reads (#2914)
Motivation:

As described in issue
[#2877](https://github.com/apple/swift-nio/issues/2877), there is no API
available to specify allowing a read of unlimited size.

Modifications:

- Add a new `public static` property, `unlimited`, to `ByteCount`
representing an unlimited amount of bytes.
- Adapt
`ReadableFileHandleProtocol.readToEnd(fromAbsoluteOffset:maximumSizeAllowed:)`
to work with `maximumSizeAllowed` being `ByteCount.unlimited`.

Result:

An API to specify allowing a read of an unlimited size will be
available.
2024-10-11 09:25:17 +00:00
Clinton Nkwocha 611fa094dc Throw error when the max read amount is greater than ByteBuffer can tolerate (#2911)
Motivation:

As described in issue
[#2878](https://github.com/apple/swift-nio/issues/2878), NIOFileSystem
crashes when reading more than `ByteBuffer` capacity.

Modifications:

- Add a new static property, `byteBufferCapacity`, to `ByteCount`
representing the maximum amount of bytes that can be written to
`ByteBuffer`.
- Throw a `FileSystemError` in
`ReadableFileHandleProtocol.readToEnd(fromAbsoluteOffset:maximumSizeAllowed:)`
when `maximumSizeAllowed` is more than `ByteCount.byteBufferCapacity`.

Result:

NIOFileSystem will `throw` instead of crashing.
2024-10-10 09:32:50 +00:00
Rick Newton-Rogers 0d3043e050 Revert "Adopt NIOThrowingAsyncSequenceProducer (#2879)" (#2892)
This reverts commit 282f5935cf.

### Motivation:

Repeated testing in linux containers has surfaced issues with the
implementation which require some rethinking of the code, let's revert
it for now and fix it up.

### Modifications:

Revert the adoption commit.

### Result:

The change is backed out.
2024-09-20 10:58:47 +00:00
Rick Newton-Rogers 282f5935cf Adopt NIOThrowingAsyncSequenceProducer (#2879)
### Motivation:

Adopt `NIOThrowingAsyncSequenceProducer` in NIOFileSystem to reduce code
duplication.

### Modifications:

Adopt `NIOThrowingAsyncSequenceProducer` in NIOFileSystem
`DirectoryEntryProducer` and `FileChunkProducer`

### Result:

No functional changes. Internal changes reduce code duplication.
2024-09-13 14:21:23 +01:00
Gus Cairo 5d26ac6a04 Include nanoseconds in assertion of timestamp for NIOFileSystem tests (#2869)
Two NIOFileSystem tests are still a bit flaky after (mostly) fixing them
in https://github.com/apple/swift-nio/pull/2842.

```
Test Case 'FileHandleTests.testSetLastAccessAndLastDataModificationTimesToNil' started at 2024-09-06 10:12:54.006
/__w/swift-nio/swift-nio/Tests/NIOFileSystemIntegrationTests/FileHandleTests.swift:1265: error: FileHandleTests.testSetLastAccessAndLastDataModificationTimesToNil : XCTAssertEqual failed: ("1725617573.0") is not equal to ("1725617574.006952") +/- ("1.0") -
Test Case 'FileHandleTests.testSetLastAccessAndLastDataModificationTimesToNil' failed (0.001 seconds)
```

This is because we were dropping the nanoseconds when comparing the
timestamps, which means that sometimes the two timestamps were off by
just over a second. This change includes the nanoseconds to avoid this
problem.
2024-09-06 16:14:43 +00:00
Gustavo Cairo e0deef8db0 Fix NIOFileSystem flaky tests (#2842) 2024-08-13 15:09:40 +01:00
George Barnett ce524be1b9 Fix text availability (#2836)
Motivation:

022ee1328b uses `Task.sleep(for:)` which isn't available in older SDKs.

Modifications:

- Use `Task.sleep(nanoseconds:)`

Result:

Tests compile with older SDKs
2024-08-09 15:53:11 +00:00
Rick Newton-Rogers bd12191411 Clone files on Darwin rather than copying them (#2823)
### Motivation:

Copying regular files on Darwin was taking more time than it needed to
because it was manually opening files and copying over bites rather than
making use of the system's ability to create CoW clones.

### Modifications:

The primary change is to switch `copyItem` to be backed by Darwin's
`copyfile` method rather than `fcopyfile`. `fcopyfile` ignores the flag
we were passing in to indicate that the file should be cloned if
possible, whereas `copyfile` is a higher-level API which takes this into
account.

This change exposes a `copyfile` wrapper method as a new public
function.

This change also adds a workaround to a seeming compiler bug on channel
options blocking building tests on more recent Xcodes.

### Result:

Copying files on Darwin will be faster.
2024-08-05 12:04:52 +01:00
Matt Hope f0451084bb Provide a default CopyStrategy overload for copyItem. (#2818)
FilesystemProtocol/copyItem has an overload providing the default CopyStrategy

Motivation:

Based on user feedback from #2806
This makes it easier to use, especially when copying files such that it is irrelevant.

Modifications:

Add overload providing (at:to:shouldProceedAfterError:shouldCopyItem:) with CopyStrategy.platformDefault
as the strategy.
Fix a cancellation bug which resulted in a test being flaky.
In addition made the test cover that case reliably to prevent it coming back.

Result:

A simpler and more robust to change API will exist for copyItem()
2024-08-01 09:13:47 +00:00
Matt Hope 022ee1328b FileSystem.copyItem can parallelise directory copy (#2806)
Motivation:

Using some limited parallelism can improved the speed of the copy for very limited increase in cpu use.

In circumstances where the source and/or destination are on a high latency device, such as a network file system,
the resulting speed up can be even more significant.
Providing conservative defaults, while allowing users the ability to control it directly if desired, provides for a faster default and access to user targeted gains in performance. 
The use of parallel by default is considered in keeping with the swift-nio model of concurrent capabilities. 

The parallelism used is restricted because the underlying limited resource for this is highly likely to be limited system file descriptors, rather than the limits of the underlying executor itself, especially on embedded devices with significantly more limited concurrent descriptors.

Modifications:

All copyItem overloads except ```copyItem(sourcePath:destinationPath:shouldProceedAfterError:shouldCopyFile)```
can, and likely will, use concurrent copies when copying directories.

A Newly type ```CopyStrategy``` controls the behaviour, allowing:
* ```parallel(maxDescriptors: Int)```
   * Parallel limited to a maximum number of concurrently open file descriptors.
* ```sequential```
   * The previous behaviour, still asynchronous but only one operation at a time
* ```platformDefault``` 
    * Whatever the API determines the default should be from the prior options

The cancellation semantics of copyItem were previously unclear/undocumented. 
These are now stated and cancellation is tested.

There were some aspects of naming/types on this API which were inconsistent/unclear. Those have been altered to aid clarity.
* Less duplication with the protocol docs
* Consistent use of `item` not `file`
* Use DirectoryEntry for the source in both ```shouldXxx``` callbacks

NIOFileSystem package status remains unchanged, it is still _NIOFileSystem with the semantics that entails.

Result:

For any use of the following functions on FileSystemProtocol, when backed by FileSystem:

- ```copyItem(*)```:

The shouldCopyItem check happens before the internal FileSystem "do I know how to copy this sort of FileType" check. This makes the code a little simpler, but the desire is to allow consuming code to filter out anything unexpected if they like without needing to trap errors.

- ```copyItem(sourcePath:destinationPath)```:

Depending on the platform this will become parallel, users on MacOS, Linux and Windows will have up to 4 concurrent file system operations at once.
Empirical testing on a MacBook pro with a significant dense directory hierarchy of 12 GiB had performance improvements of ~50% reduction in elapsed time for CPU usage increases below the noise floor of the testing

- ```copyItem(sourcePath:destinationPath:shouldProceedAfterError:shouldCopyFile)```:
When migrating from this to ```copyItem(sourcePath:destinationPath:copyStrategy:shouldProceedAfterError:shouldCopyItem)```care should be taken to ensure the should callbacks are safe to use in different concurrency domains, or that CopyStrategy.sequential is explicitly stated.
The backward compatibility shim provided does this by default.
2024-07-29 11:14:10 +01:00
finagolfin 4feff3c2f6 Use the new Android overlay and Bionic module from Swift 6 (#2784)
Motivation:

Get this repo building again for Android with the new overlay

Modifications:

- Import the new module or overlay wherever `Glibc` is used
- Keep this repo building with Swift 5 by duplicating some declarations

Result:

All the same tests keep passing on my Android CI, finagolfin/swift-android-sdk#158
2024-07-22 09:58:09 +00:00
Franz Busch c9756e1083 Adopt swift-format (#2794)
* Apply formatting

* Apply no block comments rule

* Apply OmitExplicitReturns

* Apple OnlyOneTrailingClosureArgument

* Apply NoAssignmentInExpressions

* Fix up DontRepeatTypeInStaticProperties lint errors

* Apply `OrderedImports`

* Apply `ReplaceForEachWithForLoop`

* format file

* Enable the formatting pipeline

* Adopt `AmbiguousTrailingClosureOverload`

* Fix license header

* Fix format check

* Fix `EndOfLineComment`

* Fix CI

* Adapt CI script to check if changes when running formatting

* Separate lint and format into to steps

* Fix format

* Adopt `UseEarlyExits`

* Revert "Adopt `UseEarlyExits`"

This reverts commit d1ac5bbe12.
2024-07-19 11:48:17 +02:00
Gustavo Cairo 2b5d277589 Update availability guard (#2739) 2024-06-11 10:55:26 -07:00
Gustavo Cairo bc161803bb Add API for setting last accessed and last modified file times (#2735)
This PR adds API to set a file's last accessed and last modified times, as well as a `touch()` shorthand that updates both to the current time.

Motivation:

Feature request: https://github.com/apple/swift-nio/issues/2712

Modifications:

This PR adds API to set a file's last accessed and last modified times, as well as a `touch()` shorthand that updates both to the current time.

Result:

Files' last accessed and last modified times can be updated.
2024-06-10 16:58:21 +01:00
George Barnett 9428f62793 Add a fallback path if renameat2 fails (#2733)
Motivation:

'renameat2' can fail with EINVAL if the RENAME_NOREPLACE flag isn't
supported. However, not all kernel versions support this flag which can
result in an error when creating a file 'transactionally'.

Using 'renameat2' only happens on Linux as a fallback when O_TMPFILE
isn't available.

Modifications:

- On Linux, fallback to a combination of 'stat' and 'rename' if 'renameat2' fails with EINVAL.
- Add a couple of tests

Result:

Files can still be created exclusively
2024-05-31 09:30:50 +01:00
George Barnett d8bf55d693 Add a version of 'write' for 'ByteBuffer' (#2730)
* Add a version of 'write' for 'ByteBuffer'

Motivation:

At the moment 'WritableFileHandleProtocol' is in terms of
`some Sequence<UInt8>`. To use a `ByteBuffer` users must pass in the
readable view of the buffer, which is inconvenient.

Modifications:

- Add an extension to `WritableFileHandleProtocol` which takes a
  `ByteBuffer`.

Result:

Easier to use API

* fix docs
2024-05-29 14:59:06 +01:00
George Barnett 8c3135b7d4 Add 'withTemporaryDirectory' (#2708)
Motivation:

NIOFileSystem can create the path of a temporary directory but doesn't
offer any API to create and then remove a directory.

Modifications:

- Add `withTemporaryDirectory`

Result:

- Users can get scoped access to a temporary directory which is
  subsequently removed for them
- Resolves #2664
2024-04-26 01:39:06 -07:00
George Barnett f2f4ce8be7 Add ByteBuffer support to BufferedWriter (#2707)
Motivation:

The `BufferedWriter` in `NIOFileSystem` has API in terms
of `some Sequence<UInt8>`, meaning that you need to pass
`byteBuffer.readableBytesView` which is a bit inconvenient.

Modifications:

- Add overloads which allow you to pass `ByteBuffer` directly
- Remove redundant availability guards; they are already applied to the
  type

Result:

- Better API for users
- Resolves #2662
2024-04-26 09:02:57 +01:00
George Barnett 2d840c586f Use NIOThreadPool in NIOFileSystem (#2692)
Motivation:

There are two thread pools: one in NIOFileSystem and one in NIOPosix; we
should avoid the duplication.

Modifications:

- Switch to using NIOThreadPool
- Remove the old thread pool and associated code
- Add an init to FileSystem which takes a thread pool

Result:

Less duplication
2024-03-26 13:15:27 +00:00
George Barnett 10af7c92e7 Remove temp directories after tests (#2690)
Motivation:

A couple of filesystem tests create directories but don't clean up after
themselves.

Modifications:

- Add teardown blocks to remove the temp directories

Result:

No leftover files after running tests
2024-03-25 12:56:08 +00:00
Gustavo Cairo d15793cd20 Change BufferedReader.read(while:) signature (#2688)
Return whether EOF read or predicate doesn't hold anymore in BufferedReader.read(while:)
2024-03-20 04:34:09 -07:00
George Barnett 1e2b3e34af Handle 'atomically' created files more gracefully when detached (#2682)
Motivation:

When a file is created 'atomically' and the descriptor is detached from
its handle then the user is provided with the descriptor for a temporary
file, and the desired file is never created.

Modifications:

Where supported, atomically created files use a temporary unnamed file
which is then linked on close. Elsewhere a temporary named file is
created which is renamed on closed.

Temporary unnamed files are linked in detach but not closed. Temporary
named files are linked to the desired path before being unlinked.

- Break out the logic for materializing a file created using a temporary
  unnamed file
- Add syscalls and error mappings for link(2) and unlink(2)

Result:

Atomically created files behave as expected when detached
2024-03-15 16:45:49 +00:00
George Barnett df5745d6be Underscore the NIOFileSystem module (#2683)
Motivation:

The 'NIOFileSystem' target isn't yet stable API and is made available
via the '_NIOFileSystemModule' product. This doesn't make it obvious
enough that the module isn't yet considered stable.

Modifications:

- Rename 'NIOFileSystem' and 'NIOFileSystemFoundationCompat' such that
  they are prefixed with '_'.

Result:

More obviously not stable API
2024-03-14 08:16:36 -07:00
Stefana-Ioana Dranca a40ad7c034 Prevent BufferedWriter from producing empty files (#2677)
Motivation:

In the current implementation, if the users forget to call 'flush()' on
the writer when creating a new file with 'withFileHandle(forWritingAt:options:execute)' the newly created file is empty.

Modifications:

- Added the 'withBufferedWriter()' method for the 'WritableFileHandleProtocol' and implemented it for
the WriteFileHandle and 'ReadWriteFilehandle'. The method calls flush on the bufferedWriter after
executing the closure that writes the contents to the file as indicated by the user.

Result:

Users can now use the 'withBufferedWriter' method instead of instantiating the bufferedWriter themselves,
reducing the possibility of omitting 'flush()'.
2024-03-12 04:09:24 -07:00
finagolfin 53be20532e Build the new FileSystem module for Android (#2660)
Motivation:

Get the new module building and tested on my Android CI again

Modifications:

- Add force unwraps where needed
- Update C types and account for nullability annotations in NDK 26
- Use /data/local/tmp for the `temporaryDirectory` and invoke it in the tests, instead of /tmp directly
- Don't copy over extended attributes
- Android doesn't support hard-linking on most partitions, so don't use it for materializing temporary files

Result:

Everything works again on Android
2024-03-05 14:46:54 +00:00
George Barnett cfd51e06f5 Remove large temp file after FS tests (#2658)
* Remove large temp file after FS tests

Motivation:

One of the file system tests copies a large file but didn't clear up
after itself.

Modifications:

- Remove the files after the test

Result:

Less disk space used

* remove tmp
2024-02-19 14:42:55 +00:00
George Barnett 82fd942745 Don't drop bytes from the buffered reader when reading short (#2646)
Motivation:

When the `BufferedReader` reads short when filling its buffer during a
request for some bytes, it may avoid giving the caller all bytes
available. The bytes remain in the buffer and are available on the next
call but this appears to the caller as if the file has been read
completely as the returned bytes are less than those requested.

Modifications:

- Read the expected bytes or whatever is left in the buffer
- Add a test

Result:

Less unexpected behaviour
2024-02-13 09:51:57 +00:00
George Barnett 53965cc348 Only compile FileSystem on some platforms (#2636)
Motivation:

SwiftNIO doesn't compile for visionOS because NIOFileSystem depends on
Swift System which doesn't yet support visionOS.

As NIOFileSystem isn't yet stable API we can define it out on some
platforms.

Modifications:

- Only define NIOFileSystem on macOS, iOS, tvOS, watchOS, Linux and
  Android.
- Only include Swift System on the same platforms

Result:

SwiftNIO compiles on visionOS, albeit without NIOFileSystem.
2024-02-01 13:24:21 +00:00
George Barnett 0e40bcb9ab Avoid overflow in tests where Int is 32-bit (#2626)
Motivation:

A filesystem test uses an `Int` which is too large to store in an `Int`
when `Int` is 32-bits wide. This is a compilation failure.

Modifications:

- Explicitly use `Int64`

Result:

Tests compile when `Int` is only 32-bits
2024-01-17 10:44:24 +00:00
George Barnett 756f25e3c3 Add additional guards in tests for mocking (#2624)
Motivation:

In #2615 some of the syscall tests use a mocking infrastrucutre which is
compiled out in release builds. The tests weren't correctly guarded for
this so fail to build in release mode.

Modifications:

- Add missing guards
- Add missing availability on tests

Result:

Tests compile in release mode
2024-01-16 07:56:08 -08:00
George Barnett f80c69f84b Add NIOFilesystem (#2615)
Motivation:

I/O is typically blocking, but options for interacting with the
filesystem using `async` APIs are limited. This change adds a new module
to NIO, `NIOFileSystem`. At the moment this is exposed as the
`_NIOFileSystem` product while users get a chance to try it out and
provide feedback.

During this time the API of `NIOFileSystem` is subject to change.
Breaking changes will come in _minor_ NIO releases and additive changes
may come in _patch_ releases of NIO.

Modifications:

- Add `NIOFileSystem`, `NIOFileSystemFoundationCompat`,
  `NIOFileSystemTests`, `NIOFileSystemIntegrationTests`, and
  `NIOFileSystemFoundationCompatTests`.
- Update docs
- Update CNIOLinux and CNIODarwin shims

Result:

File system can be accessed via `async` APIs
2024-01-16 03:30:26 -08:00