Merge branch 'main' into jw-clientboot-docs

This commit is contained in:
Johannes Weiss authored and GitHub committed 2025-02-13 22:43:43 +00:00
commit adde82b2d5
179 files changed
+6031 -1736

No files matched your search

@@ -18,4 +18,4 @@ runs:
GH_TOKEN: ${{ inputs.token }}
run: |
gh pr view ${{ github.event.number }} --repo ${{ github.repository }} --json labels \
| jq -e '[.labels[].name] | any(. == "⚠️ semver/major" or . == "semver/minor" or . == "semver/patch" or . == "semver/none")'
| jq -e '[.labels[].name] | any(. == "⚠️ semver/major" or . == "🆕 semver/minor" or . == "🔨 semver/patch" or . == "semver/none")'
+2 -2
View File
@@ -5,10 +5,10 @@ changelog:
- ⚠️ semver/major
- title: SemVer Minor
labels:
- semver/minor
- 🆕 semver/minor
- title: SemVer Patch
labels:
- semver/patch
- 🔨 semver/patch
- title: Other Changes
labels:
- semver/none
+32 -14
View File
@@ -24,7 +24,11 @@ on:
default: true
linux_nightly_6_0_enabled:
type: boolean
description: "Boolean to enable the Linux nightly 6.0 Swift version matrix job. Defaults to true."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly."
default: false
linux_nightly_6_1_enabled:
type: boolean
description: "Boolean to enable the Linux nightly 6.1 Swift version matrix job. Defaults to true."
default: true
linux_nightly_main_enabled:
type: boolean
@@ -33,30 +37,44 @@ on:
windows_6_0_enabled:
type: boolean
description: "Boolean to enable the Windows 6.0 Swift version matrix job. Defaults to true."
description: "Boolean to enable the Windows 6.0 Swift version matrix job. Currently has no effect!" # TODO: implement Windows benchmarking
default: false
windows_nightly_6_0_enabled:
type: boolean
description: "Boolean to enable the Windows nightly 6.0 Swift version matrix job. Defaults to true."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly." # TODO: implement Windows benchmarking
default: false
windows_nightly_main_enabled:
type: boolean
description: "Boolean to enable the Windows nightly main Swift version matrix job. Defaults to true."
description: "Boolean to enable the Windows nightly main Swift version matrix job. Currently has no effect!" # TODO: implement Windows benchmarking
default: false
jobs:
construct-matrix:
name: Construct Benchmarks matrix
runs-on: ubuntu-latest
outputs:
benchmarks-matrix: '${{ steps.generate-matrix.outputs.benchmarks-matrix }}'
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false
- id: generate-matrix
run: echo "benchmarks-matrix=$(curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/generate_matrix.sh | bash)" >> "$GITHUB_OUTPUT"
env:
MATRIX_LINUX_COMMAND: "swift package --package-path ${{ inputs.benchmark_package_path }} ${{ inputs.swift_package_arguments }} benchmark baseline check --check-absolute-path ${{ inputs.benchmark_package_path }}/Thresholds/${SWIFT_VERSION}/"
MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q libjemalloc-dev"
MATRIX_LINUX_5_9_ENABLED: ${{ inputs.linux_5_9_enabled }}
MATRIX_LINUX_5_10_ENABLED: ${{ inputs.linux_5_10_enabled }}
MATRIX_LINUX_6_0_ENABLED: ${{ inputs.linux_6_0_enabled }}
MATRIX_LINUX_NIGHTLY_6_1_ENABLED: ${{ inputs.linux_nightly_6_1_enabled }}
MATRIX_LINUX_NIGHTLY_MAIN_ENABLED: ${{ inputs.linux_nightly_main_enabled }}
benchmarks:
name: Benchmarks
needs: construct-matrix
# Workaround https://github.com/nektos/act/issues/1875
uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main
with:
name: "Benchmarks"
matrix_linux_command: "apt-get update -y -q && apt-get install -y -q libjemalloc-dev && swift package --package-path ${{ inputs.benchmark_package_path }} ${{ inputs.swift_package_arguments }} benchmark baseline check --check-absolute-path ${{ inputs.benchmark_package_path }}/Thresholds/${SWIFT_VERSION}/"
matrix_linux_5_9_enabled: ${{ inputs.linux_5_9_enabled }}
matrix_linux_5_10_enabled: ${{ inputs.linux_5_10_enabled }}
matrix_linux_6_0_enabled: ${{ inputs.linux_6_0_enabled }}
matrix_linux_nightly_6_0_enabled: ${{ inputs.linux_nightly_6_0_enabled }}
matrix_linux_nightly_main_enabled: ${{ inputs.linux_nightly_main_enabled }}
matrix_windows_6_0_enabled: ${{ inputs.windows_6_0_enabled }}
matrix_windows_nightly_6_0_enabled: ${{ inputs.windows_nightly_6_0_enabled }}
matrix_windows_nightly_main_enabled: ${{ inputs.windows_nightly_main_enabled }}
matrix_string: '${{ needs.construct-matrix.outputs.benchmarks-matrix }}'
+31 -13
View File
@@ -16,6 +16,10 @@ on:
description: "Boolean to enable the Linux 6.0 Swift version matrix job. Defaults to true."
default: true
linux_nightly_6_0_enabled:
type: boolean
description: "⚠️ Deprecated, we no longer run against 6.0 nightly."
default: false
linux_nightly_6_1_enabled:
type: boolean
description: "Boolean to enable the Linux nightly 6.0 Swift version matrix job. Defaults to true."
default: true
@@ -26,30 +30,44 @@ on:
windows_6_0_enabled:
type: boolean
description: "Boolean to enable the Windows 6.0 Swift version matrix job. Defaults to true."
description: "Boolean to enable the Windows 6.0 Swift version matrix job. Defaults to false. Currently has no effect!" # TODO: implement Windows Cxx compat checking
default: false
windows_nightly_6_0_enabled:
type: boolean
description: "Boolean to enable the Windows nightly 6.0 Swift version matrix job. Defaults to true."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly." # TODO: implement Windows Cxx compat checking
default: false
windows_nightly_main_enabled:
type: boolean
description: "Boolean to enable the Windows nightly main Swift version matrix job. Defaults to true."
description: "Boolean to enable the Windows nightly main Swift version matrix job. Defaults to false. Currently has no effect!" # TODO: implement Windows Cxx compat checking
default: false
jobs:
construct-matrix:
name: Construct Cxx interop matrix
runs-on: ubuntu-latest
outputs:
cxx-interop-matrix: '${{ steps.generate-matrix.outputs.cxx-interop-matrix }}'
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false
- id: generate-matrix
run: echo "cxx-interop-matrix=$(curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/generate_matrix.sh | bash)" >> "$GITHUB_OUTPUT"
env:
MATRIX_LINUX_COMMAND: "curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/check-cxx-interop-compatibility.sh | bash"
MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q curl jq"
MATRIX_LINUX_5_9_ENABLED: ${{ inputs.linux_5_9_enabled }}
MATRIX_LINUX_5_10_ENABLED: ${{ inputs.linux_5_10_enabled }}
MATRIX_LINUX_6_0_ENABLED: ${{ inputs.linux_6_0_enabled }}
MATRIX_LINUX_NIGHTLY_6_1_ENABLED: ${{ inputs.linux_nightly_6_1_enabled }}
MATRIX_LINUX_NIGHTLY_MAIN_ENABLED: ${{ inputs.linux_nightly_main_enabled }}
cxx-interop:
name: Cxx interop
needs: construct-matrix
# Workaround https://github.com/nektos/act/issues/1875
uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main
with:
name: "Cxx interop"
matrix_linux_command: "apt-get update -y -q && apt-get install -y -q jq && curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/check-cxx-interop-compatibility.sh | bash"
matrix_linux_5_9_enabled: ${{ inputs.linux_5_9_enabled }}
matrix_linux_5_10_enabled: ${{ inputs.linux_5_10_enabled }}
matrix_linux_6_0_enabled: ${{ inputs.linux_6_0_enabled }}
matrix_linux_nightly_6_0_enabled: ${{ inputs.linux_nightly_6_0_enabled }}
matrix_linux_nightly_main_enabled: ${{ inputs.linux_nightly_main_enabled }}
matrix_windows_6_0_enabled: ${{ inputs.windows_6_0_enabled }}
matrix_windows_nightly_6_0_enabled: ${{ inputs.windows_nightly_6_0_enabled }}
matrix_windows_nightly_main_enabled: ${{ inputs.windows_nightly_main_enabled }}
matrix_string: '${{ needs.construct-matrix.outputs.cxx-interop-matrix }}'
+22 -5
View File
@@ -14,8 +14,8 @@ jobs:
with:
linux_5_9_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
linux_5_10_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
linux_nightly_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
cxx-interop:
@@ -30,10 +30,27 @@ jobs:
with:
benchmark_package_path: "Benchmarks"
construct-integration-test-matrix:
name: Construct integration test matrix
runs-on: ubuntu-latest
outputs:
integration-test-matrix: '${{ steps.generate-matrix.outputs.integration-test-matrix }}'
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false
- id: generate-matrix
run: echo "integration-test-matrix=$(curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/generate_matrix.sh | bash)" >> "$GITHUB_OUTPUT"
env:
MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q lsof dnsutils netcat-openbsd net-tools curl jq"
MATRIX_LINUX_COMMAND: "./scripts/integration_tests.sh"
integration-tests:
name: Integration Tests
name: Integration tests
needs: construct-integration-test-matrix
# Workaround https://github.com/nektos/act/issues/1875
uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main
with:
name: "Integration tests"
matrix_linux_command: "apt-get update -y -q && apt-get install -y -q lsof dnsutils netcat-openbsd net-tools curl jq && ./scripts/integration_tests.sh"
matrix_string: '${{ needs.construct-integration-test-matrix.outputs.integration-test-matrix }}'
+22 -5
View File
@@ -18,8 +18,8 @@ jobs:
with:
linux_5_9_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
linux_5_10_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
linux_nightly_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
benchmarks:
@@ -34,13 +34,30 @@ jobs:
# Workaround https://github.com/nektos/act/issues/1875
uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
construct-integration-test-matrix:
name: Construct integration test matrix
runs-on: ubuntu-latest
outputs:
integration-test-matrix: '${{ steps.generate-matrix.outputs.integration-test-matrix }}'
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false
- id: generate-matrix
run: echo "integration-test-matrix=$(curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/generate_matrix.sh | bash)" >> "$GITHUB_OUTPUT"
env:
MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q lsof dnsutils netcat-openbsd net-tools curl jq"
MATRIX_LINUX_COMMAND: "./scripts/integration_tests.sh"
integration-tests:
name: Integration Tests
name: Integration tests
needs: construct-integration-test-matrix
# Workaround https://github.com/nektos/act/issues/1875
uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main
with:
name: "Integration tests"
matrix_linux_command: "apt-get update -y -q && apt-get install -y -q lsof dnsutils netcat-openbsd net-tools curl jq && ./scripts/integration_tests.sh"
matrix_string: '${{ needs.construct-integration-test-matrix.outputs.integration-test-matrix }}'
vsock-tests:
name: Vsock tests
+1 -1
View File
@@ -6,7 +6,7 @@ on:
jobs:
semver-label-check:
name: Semantic Version label check
name: Semantic version label check
runs-on: ubuntu-latest
timeout-minutes: 1
steps:
@@ -0,0 +1,40 @@
name: Matrix Load
on:
workflow_call:
inputs:
name:
type: string
description: "The name of the workflow used for the concurrency group."
required: true
matrix_path:
type: string
description: "The path of the test matrix definition."
default: ""
jobs:
load-matrix:
name: Prepare matrices
runs-on: ubuntu-latest
outputs:
swift-matrix: ${{ steps.load-matrix.outputs.swift-matrix }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false
- name: Mark the workspace as safe
# https://github.com/actions/checkout/issues/766
run: git config --global --add safe.directory ${GITHUB_WORKSPACE}
- id: load-matrix
run: |
printf "swift-matrix=%s" "$(jq -c '.' ${{ inputs.matrix_path }})" >> "$GITHUB_OUTPUT"
execute-matrix:
name: Execute matrix
needs: load-matrix
# Workaround https://github.com/nektos/act/issues/1875
uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main
with:
name: ${{ inputs.name }}
matrix_string: '${{ needs.load-matrix.outputs.swift-matrix }}'
+31 -13
View File
@@ -46,15 +46,26 @@ on:
description: "The command of the 6.0 Swift version linux matrix job to execute."
matrix_linux_nightly_6_0_enabled:
type: boolean
description: "Boolean to enable the nightly 6.0 Swift version matrix job. Defaults to true."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly."
default: true
matrix_linux_nightly_6_0_container_image:
type: string
description: "Container image for the nightly 6.0 Swift version matrix job. Defaults to matching Swift Ubuntu image."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly."
default: "swiftlang/swift:nightly-6.0-jammy"
matrix_linux_nightly_6_0_command_override:
type: string
description: "The command of the nightly 6.0 Swift version linux matrix job to execute."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly."
matrix_linux_nightly_6_1_enabled:
type: boolean
description: "Boolean to enable the nightly 6.1 Swift version matrix job. Defaults to true."
default: true
matrix_linux_nightly_6_1_container_image:
type: string
description: "Container image for the nightly 6.1 Swift version matrix job. Defaults to matching Swift Ubuntu image."
default: "swiftlang/swift:nightly-6.1-jammy"
matrix_linux_nightly_6_1_command_override:
type: string
description: "The command of the nightly 6.1 Swift version linux matrix job to execute."
matrix_linux_nightly_main_enabled:
type: boolean
description: "Boolean to enable the nightly main Swift version matrix job. Defaults to true."
@@ -80,11 +91,18 @@ on:
description: "The command of the 6.0 Swift version windows matrix job to execute."
matrix_windows_nightly_6_0_enabled:
type: boolean
description: "Boolean to enable the nightly 6.0 Swift version matrix job. Defaults to true."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly."
default: false
matrix_windows_nightly_6_0_command_override:
type: string
description: "The command of the nightly 6.0 Swift version windows matrix job to execute."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly."
matrix_windows_nightly_6_1_enabled:
type: boolean
description: "Boolean to enable the nightly 6.1 Swift version matrix job. Defaults to true."
default: false
matrix_windows_nightly_6_1_command_override:
type: string
description: "The command of the nightly 6.1 Swift version windows matrix job to execute."
matrix_windows_nightly_main_enabled:
type: boolean
description: "Boolean to enable the nightly main Swift version matrix job. Defaults to true."
@@ -116,9 +134,9 @@ jobs:
- image: ${{ inputs.matrix_linux_6_0_container_image }}
swift_version: "6.0"
enabled: ${{ inputs.matrix_linux_6_0_enabled }}
- image: ${{ inputs.matrix_linux_nightly_6_0_container_image }}
swift_version: "nightly-6.0"
enabled: ${{ inputs.matrix_linux_nightly_6_0_enabled }}
- image: ${{ inputs.matrix_linux_nightly_6_1_container_image }}
swift_version: "nightly-6.1"
enabled: ${{ inputs.matrix_linux_nightly_6_1_enabled }}
- image: ${{ inputs.matrix_linux_nightly_main_container_image }}
swift_version: "nightly-main"
enabled: ${{ inputs.matrix_linux_nightly_main_enabled }}
@@ -143,7 +161,7 @@ jobs:
COMMAND_OVERRIDE_5_9: ${{ inputs.matrix_linux_5_9_command_override }}
COMMAND_OVERRIDE_5_10: ${{ inputs.matrix_linux_5_10_command_override }}
COMMAND_OVERRIDE_6_0: ${{ inputs.matrix_linux_6_0_command_override }}
COMMAND_OVERRIDE_NIGHTLY_6_0: ${{ inputs.matrix_linux_nightly_6_0_command_override }}
COMMAND_OVERRIDE_NIGHTLY_6_1: ${{ inputs.matrix_linux_nightly_6_1_command_override }}
COMMAND_OVERRIDE_NIGHTLY_MAIN: ${{ inputs.matrix_linux_nightly_main_command_override }}
run: |
apt-get -qq update && apt-get -qq -y install curl
@@ -185,9 +203,9 @@ jobs:
matrix:
# We are specifying only the major and minor of the docker images to automatically pick up the latest patch release
swift:
- image: swiftlang/swift:nightly-6.0-windowsservercore-1809
swift_version: "nightly-6.0"
enabled: ${{ inputs.matrix_windows_nightly_6_0_enabled }}
- image: swiftlang/swift:nightly-6.1-windowsservercore-1809
swift_version: "nightly-6.1"
enabled: ${{ inputs.matrix_windows_nightly_6_1_enabled }}
- image: swiftlang/swift:nightly-main-windowsservercore-1809
swift_version: "nightly-main"
enabled: ${{ inputs.matrix_windows_nightly_main_enabled }}
@@ -207,4 +225,4 @@ jobs:
- name: Run matrix job
if: ${{ matrix.swift.enabled }}
run: |
docker run --env SWIFT_VERSION="${{ matrix.swift.swift_version }}" --env COMMAND="${{ inputs.matrix_windows_command }}" --env COMMAND_OVERRIDE_NIGHTLY_6_0="${{ inputs.matrix_windows_nightly_6_0_command_override }}" --env COMMAND_OVERRIDE_NIGHTLY_MAIN="${{ inputs.matrix_windows_nightly_main_command_override }}" -v ${{ github.workspace }}:C:\source ${{ matrix.swift.image }} cmd /s /c "swift --version & cd C:\source\ & powershell -File __check-matrix-job.ps1"
docker run --env SWIFT_VERSION="${{ matrix.swift.swift_version }}" --env COMMAND="${{ inputs.matrix_windows_command }}" --env COMMAND_OVERRIDE_NIGHTLY_6_1="${{ inputs.matrix_windows_nightly_6_1_command_override }}" --env COMMAND_OVERRIDE_NIGHTLY_MAIN="${{ inputs.matrix_windows_nightly_main_command_override }}" -v ${{ github.workspace }}:C:\source ${{ matrix.swift.image }} cmd /s /c "swift --version & cd C:\source\ & powershell -File __check-matrix-job.ps1"
+67
View File
@@ -0,0 +1,67 @@
name: Matrix
on:
workflow_call:
inputs:
name:
type: string
description: "The name of the workflow used for the concurrency group."
required: true
matrix_string:
type: string
description: "The test matrix definition."
required: true
# We will cancel previously triggered workflow runs
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ inputs.name }}
cancel-in-progress: true
jobs:
execute-matrix:
name: ${{ matrix.config.platform }} (${{ matrix.config.name }})
runs-on: ${{ matrix.config.runner }}
strategy:
fail-fast: false
matrix: ${{ fromJson(inputs.matrix_string) }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false
submodules: true
- name: Pull Docker image
run: docker pull ${{ matrix.config.image }}
- name: Run matrix job
if: ${{ matrix.config.platform != 'Windows' }}
run: |
if [[ -n "${{ matrix.config.setup_command }}" ]]; then
setup_command_expression="${{ matrix.config.setup_command }} &&"
else
setup_command_expression=""
fi
workspace="/$(basename ${{ github.workspace }})"
docker run -v ${{ github.workspace }}:"$workspace" \
-w "$workspace" \
-e SWIFT_VERSION="${{ matrix.config.swift_version }}" \
-e setup_command_expression="$setup_command_expression" \
-e workspace="$workspace" \
${{ matrix.config.image }} \
bash -c "swift --version && git config --global --add safe.directory \"$workspace\" && $setup_command_expression ${{ matrix.config.command }} ${{ matrix.config.command_arguments }}"
- name: Run matrix job (Windows)
if: ${{ matrix.config.platform == 'Windows' }}
run: |
if (-not [string]::IsNullOrEmpty("${{ matrix.config.setup_command }}")) {
$setup_command_expression = "${{ matrix.config.setup_command }} &"
} else {
$setup_command_expression = ""
}
$workspace = "C:\" + (Split-Path ${{ github.workspace }} -Leaf)
docker run -v ${{ github.workspace }}:$($workspace) `
-w $($workspace) `
-e SWIFT_VERSION="${{ matrix.config.swift_version }}" `
-e setup_command_expression=%setup_command_expression% `
${{ matrix.config.image }} `
cmd /s /c "swift --version & powershell Invoke-Expression ""$($setup_command_expression) ${{ matrix.config.command }} ${{ matrix.config.command_arguments }}"""
env:
SWIFT_VERSION: ${{ matrix.config.swift_version }}
+57 -25
View File
@@ -29,11 +29,19 @@ on:
default: ""
linux_nightly_6_0_enabled:
type: boolean
description: "Boolean to enable the Linux nightly 6.0 Swift version matrix job. Defaults to true."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly."
default: true
linux_nightly_6_0_arguments_override:
type: string
description: "The arguments passed to swift test in the Linux nightly 6.0 Swift version matrix job."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly."
default: ""
linux_nightly_6_1_enabled:
type: boolean
description: "Boolean to enable the Linux nightly 6.1 Swift version matrix job. Defaults to true."
default: true
linux_nightly_6_1_arguments_override:
type: string
description: "The arguments passed to swift test in the Linux nightly 6.1 Swift version matrix job."
default: ""
linux_nightly_main_enabled:
type: boolean
@@ -46,7 +54,7 @@ on:
windows_6_0_enabled:
type: boolean
description: "Boolean to enable the Windows 6.0 Swift version matrix job. Defaults to true."
description: "Boolean to enable the Windows 6.0 Swift version matrix job. Defaults to false."
default: false
windows_6_0_arguments_override:
type: string
@@ -54,15 +62,23 @@ on:
default: ""
windows_nightly_6_0_enabled:
type: boolean
description: "Boolean to enable the Windows nightly 6.0 Swift version matrix job. Defaults to true."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly."
default: false
windows_nightly_6_0_arguments_override:
type: string
description: "The arguments passed to swift test in the Windows nightly 6.0 Swift version matrix job."
description: "⚠️ Deprecated, we no longer run against 6.0 nightly."
default: ""
windows_nightly_6_1_enabled:
type: boolean
description: "Boolean to enable the Windows nightly 6.1 Swift version matrix job. Defaults to false."
default: false
windows_nightly_6_1_arguments_override:
type: string
description: "The arguments passed to swift test in the Windows nightly 6.1 Swift version matrix job."
default: ""
windows_nightly_main_enabled:
type: boolean
description: "Boolean to enable the Windows nightly main Swift version matrix job. Defaults to true."
description: "Boolean to enable the Windows nightly main Swift version matrix job. Defaults to false."
default: false
windows_nightly_main_arguments_override:
type: string
@@ -70,27 +86,43 @@ on:
default: ""
jobs:
construct-matrix:
name: Construct unit test matrix
runs-on: ubuntu-latest
outputs:
unit-test-matrix: '${{ steps.generate-matrix.outputs.unit-test-matrix }}'
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false
- id: generate-matrix
run: echo "unit-test-matrix=$(curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/generate_matrix.sh | bash)" >> "$GITHUB_OUTPUT"
env:
MATRIX_LINUX_COMMAND: "swift test"
MATRIX_LINUX_5_9_ENABLED: ${{ inputs.linux_5_9_enabled }}
MATRIX_LINUX_5_9_COMMAND_ARGUMENTS: ${{ inputs.linux_5_9_arguments_override }}
MATRIX_LINUX_5_10_ENABLED: ${{ inputs.linux_5_10_enabled }}
MATRIX_LINUX_5_10_COMMAND_ARGUMENTS: ${{ inputs.linux_5_10_arguments_override }}
MATRIX_LINUX_6_0_ENABLED: ${{ inputs.linux_6_0_enabled }}
MATRIX_LINUX_6_0_COMMAND_ARGUMENTS: ${{ inputs.linux_6_0_arguments_override }}
MATRIX_LINUX_NIGHTLY_6_1_ENABLED: ${{ inputs.linux_nightly_6_1_enabled }}
MATRIX_LINUX_NIGHTLY_6_1_COMMAND_ARGUMENTS: ${{ inputs.linux_nightly_6_1_arguments_override }}
MATRIX_LINUX_NIGHTLY_MAIN_ENABLED: ${{ inputs.linux_nightly_main_enabled }}
MATRIX_LINUX_NIGHTLY_MAIN_COMMAND_ARGUMENTS: ${{ inputs.linux_nightly_main_arguments_override }}
MATRIX_WINDOWS_COMMAND: "swift test"
MATRIX_WINDOWS_6_0_ENABLED: ${{ inputs.windows_6_0_enabled }}
MATRIX_WINDOWS_6_0_COMMAND_ARGUMENTS: ${{ inputs.windows_6_0_arguments_override }}
MATRIX_WINDOWS_NIGHTLY_6_1_ENABLED: ${{ inputs.windows_nightly_6_1_enabled }}
MATRIX_WINDOWS_NIGHTLY_6_1_COMMAND_ARGUMENTS: ${{ inputs.windows_nightly_6_1_arguments_override }}
MATRIX_WINDOWS_NIGHTLY_MAIN_ENABLED: ${{ inputs.windows_nightly_main_enabled }}
MATRIX_WINDOWS_NIGHTLY_MAIN_COMMAND_ARGUMENTS: ${{ inputs.windows_nightly_main_arguments_override }}
unit-tests:
name: Unit tests
needs: construct-matrix
# Workaround https://github.com/nektos/act/issues/1875
uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main
with:
name: "Unit tests"
matrix_linux_command: "swift test"
matrix_linux_5_9_enabled: ${{ inputs.linux_5_9_enabled }}
matrix_linux_5_9_command_override: "swift test ${{ inputs.linux_5_9_arguments_override }}"
matrix_linux_5_10_enabled: ${{ inputs.linux_5_10_enabled }}
matrix_linux_5_10_command_override: "swift test ${{ inputs.linux_5_10_arguments_override }}"
matrix_linux_6_0_enabled: ${{ inputs.linux_6_0_enabled }}
matrix_linux_6_0_command_override: "swift test ${{ inputs.linux_6_0_arguments_override }}"
matrix_linux_nightly_6_0_enabled: ${{ inputs.linux_nightly_6_0_enabled }}
matrix_linux_nightly_6_0_command_override: "swift test ${{ inputs.linux_nightly_6_0_arguments_override }}"
matrix_linux_nightly_main_enabled: ${{ inputs.linux_nightly_main_enabled }}
matrix_linux_nightly_main_command_override: "swift test ${{ inputs.linux_nightly_main_arguments_override }}"
matrix_windows_command: "swift test"
matrix_windows_6_0_enabled: ${{ inputs.windows_6_0_enabled }}
matrix_windows_6_0_command_override: "swift test ${{ inputs.windows_6_0_arguments_override }}"
matrix_windows_nightly_6_0_enabled: ${{ inputs.windows_nightly_6_0_enabled }}
matrix_windows_nightly_6_0_command_override: "swift test ${{ inputs.windows_nightly_6_0_arguments_override }}"
matrix_windows_nightly_main_enabled: ${{ inputs.windows_nightly_main_enabled }}
matrix_windows_nightly_main_command_override: "swift test ${{ inputs.windows_nightly_main_arguments_override }}"
matrix_string: '${{ needs.construct-matrix.outputs.unit-test-matrix }}'
+1 -1
View File
@@ -1,5 +1,5 @@
.DS_Store
/.build
.build
/.index-build
/Packages
/*.xcodeproj
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 555
"mallocCountTotal" : 108
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 556
"mallocCountTotal" : 110
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 548
"mallocCountTotal" : 108
}
@@ -1,3 +0,0 @@
{
"mallocCountTotal" : 548
}
@@ -0,0 +1,3 @@
{
"mallocCountTotal" : 108
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 548
"mallocCountTotal" : 108
}
+2 -5
View File
@@ -5,7 +5,6 @@ your contribution to Apple and the community, and agree by submitting the patch
that your contributions are licensed under the Apache 2.0 license (see
`LICENSE.txt`).
## How to submit a bug report
Please ensure to specify the following:
@@ -20,7 +19,6 @@ Please ensure to specify the following:
* OS version and the output of `uname -a`
* Network configuration
### Example
```
@@ -89,7 +87,7 @@ SwiftNIO has been created to be high performance. The integration tests cover s
### Formatting
Try to keep your lines less than 120 characters long so github can correctly display your changes.
Try to keep your lines less than 120 characters long so GitHub can correctly display your changes.
SwiftNIO uses the [swift-format](https://github.com/swiftlang/swift-format) tool to bring consistency to code formatting. There is a specific [.swift-format](./.swift-format) configuration file. This will be checked and enforced on PRs. Note that the check will run on the current most recent stable version target which may not match that in your own local development environment.
@@ -106,7 +104,6 @@ act --container-architecture linux/amd64 --action-offline-mode --bind workflow_c
This will run the format checks, binding to your local checkout so the edits made are to your own source.
### Extensibility
Try to make sure your code is robust to future extensions. The public interface is very hard to change after release - please refer to the [API guidelines](./docs/public-api.md)
@@ -115,4 +112,4 @@ Try to make sure your code is robust to future extensions. The public interface
Please open a pull request at https://github.com/apple/swift-nio. Make sure the CI passes, and then wait for code review.
After review you may be asked to make changes. When you are ready, use the request re-review feature of github or mention the reviewers by name in a comment.
After review you may be asked to make changes. When you are ready, use the request re-review feature of GitHub or mention the reviewers by name in a comment.
@@ -19,8 +19,8 @@ source defines.sh
token=$(create_token)
start_server "$token"
do_curl "$token" -H "foo: bar" --http1.0 \
"http://foobar.com/dynamic/info" > "${tmp:?"tmp variable not set"}/out"
if ! grep -q '("foo", "bar")' "$tmp/out"; then
"http://foobar.com/dynamic/info" >"${tmp:?"tmp variable not set"}/out"
if ! grep -q 'foo: bar' "$tmp/out"; then
fail "couldn't find header in response"
fi
stop_server "$token"
@@ -1,50 +1,59 @@
{
"10000000_asyncsequenceproducer": 19,
"1000000_asyncwriter": 1000013,
"1000_addHandlers": 44000,
"1000_addHandlers_sync": 36000,
"1000_addRemoveHandlers_handlercontext": 8032,
"1000_addRemoveHandlers_handlername": 8032,
"1000_addRemoveHandlers_handlertype": 8032,
"1000_autoReadGetAndSet": 18000,
"1000000_asyncwriter": 1000050,
"1000_addHandlers": 44050,
"1000_addHandlers_sync": 37050,
"1000_addRemoveHandlers_handlercontext": 8050,
"1000_addRemoveHandlers_handlername": 8050,
"1000_addRemoveHandlers_handlertype": 8050,
"1000_autoReadGetAndSet": 18050,
"1000_autoReadGetAndSet_sync": 0,
"1000_copying_bytebufferview_to_array": 1000,
"1000_copying_circularbuffer_to_array": 1000,
"1000_getHandlers": 8034,
"1000_getHandlers_sync": 34,
"1000_reqs_1_conn": 26363,
"1000_rst_connections": 145004,
"1000_tcpbootstraps": 3001,
"1000_tcpconnections": 152002,
"1000_udp_reqs": 6014,
"1000_udpbootstraps": 2000,
"1000_udpconnections": 75008,
"1_reqs_1000_conn": 389000,
"bytebuffer_lots_of_rw": 2005,
"1000_copying_bytebufferview_to_array": 1050,
"1000_copying_circularbuffer_to_array": 1050,
"1000_getHandlers": 8050,
"1000_getHandlers_sync": 35,
"1000_reqs_1_conn": 26400,
"1000_rst_connections": 145050,
"1000_tcpbootstraps": 3050,
"1000_tcpconnections": 152050,
"1000_udp_reqs": 6050,
"1000_udpbootstraps": 2050,
"1000_udpconnections": 75050,
"1_reqs_1000_conn": 384050,
"assume_isolated_scheduling_10000_executions": 89,
"bytebuffer_lots_of_rw": 2050,
"creating_10000_headers": 0,
"decode_1000_ws_frames": 2000,
"decode_1000_ws_frames": 2050,
"encode_1000_ws_frames_holding_buffer": 3,
"encode_1000_ws_frames_holding_buffer_with_mask": 2003,
"encode_1000_ws_frames_holding_buffer_with_mask": 2050,
"encode_1000_ws_frames_holding_buffer_with_space": 3,
"encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2003,
"encode_1000_ws_frames_new_buffer": 3000,
"encode_1000_ws_frames_new_buffer_with_mask": 5000,
"encode_1000_ws_frames_new_buffer_with_space": 3000,
"encode_1000_ws_frames_new_buffer_with_space_with_mask": 5000,
"encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050,
"encode_1000_ws_frames_new_buffer": 3050,
"encode_1000_ws_frames_new_buffer_with_mask": 5050,
"encode_1000_ws_frames_new_buffer_with_space": 3050,
"encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050,
"execute_hop_10000_tasks": 0,
"future_erase_result": 4001,
"future_lots_of_callbacks": 53001,
"get_100000_headers_canonical_form": 700000,
"get_100000_headers_canonical_form_trimming_whitespace": 700000,
"get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700000,
"get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700000,
"flat_schedule_10000_tasks": 100100,
"flat_schedule_assume_isolated_10000_tasks": 90100,
"future_assume_isolated_lots_of_callbacks": 74050,
"future_erase_result": 4050,
"future_lots_of_callbacks": 74050,
"get_100000_headers_canonical_form": 700050,
"get_100000_headers_canonical_form_trimming_whitespace": 700050,
"get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050,
"get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050,
"modifying_1000_circular_buffer_elements": 0,
"modifying_byte_buffer_view": 6000,
"ping_pong_1000_reqs_1_conn": 319,
"read_10000_chunks_from_file": 110009,
"schedule_10000_tasks": 40084,
"schedule_and_run_10000_tasks": 50010,
"modifying_byte_buffer_view": 6050,
"ping_pong_1000_reqs_1_conn": 314,
"read_10000_chunks_from_file": 110050,
"schedule_10000_tasks": 40100,
"schedule_and_run_10000_tasks": 50050,
"schedule_assume_isolated_10000_tasks": 40100,
"schedule_with_deadline_10000_tasks": 40100,
"schedule_with_deadline_assume_isolated_10000_tasks": 40100,
"scheduling_10000_executions": 89,
"udp_1000_reqs_1_conn": 6156,
"udp_1_reqs_1000_conn": 162000
"submit_10000_tasks": 20100,
"submit_assume_isolated_10000_tasks": 20100,
"udp_1000_reqs_1_conn": 6200,
"udp_1_reqs_1000_conn": 162050
}
@@ -1,50 +1,59 @@
{
"10000000_asyncsequenceproducer": 19,
"1000000_asyncwriter": 1000013,
"1000_addHandlers": 44000,
"1000_addHandlers_sync": 36000,
"1000_addRemoveHandlers_handlercontext": 8032,
"1000_addRemoveHandlers_handlername": 8032,
"1000_addRemoveHandlers_handlertype": 8032,
"1000_autoReadGetAndSet": 18000,
"1000000_asyncwriter": 1000050,
"1000_addHandlers": 44050,
"1000_addHandlers_sync": 37050,
"1000_addRemoveHandlers_handlercontext": 8050,
"1000_addRemoveHandlers_handlername": 8050,
"1000_addRemoveHandlers_handlertype": 8050,
"1000_autoReadGetAndSet": 18050,
"1000_autoReadGetAndSet_sync": 0,
"1000_copying_bytebufferview_to_array": 1000,
"1000_copying_circularbuffer_to_array": 1000,
"1000_getHandlers": 8034,
"1000_getHandlers_sync": 34,
"1000_reqs_1_conn": 26372,
"1000_rst_connections": 147004,
"1000_tcpbootstraps": 4001,
"1000_tcpconnections": 154002,
"1000_udp_reqs": 6014,
"1000_udpbootstraps": 2000,
"1000_udpconnections": 75008,
"1_reqs_1000_conn": 398000,
"bytebuffer_lots_of_rw": 2005,
"1000_copying_bytebufferview_to_array": 1050,
"1000_copying_circularbuffer_to_array": 1050,
"1000_getHandlers": 8050,
"1000_getHandlers_sync": 35,
"1000_reqs_1_conn": 26400,
"1000_rst_connections": 147050,
"1000_tcpbootstraps": 4050,
"1000_tcpconnections": 154050,
"1000_udp_reqs": 6050,
"1000_udpbootstraps": 2050,
"1000_udpconnections": 75050,
"1_reqs_1000_conn": 393050,
"assume_isolated_scheduling_10000_executions": 89,
"bytebuffer_lots_of_rw": 2050,
"creating_10000_headers": 0,
"decode_1000_ws_frames": 2000,
"decode_1000_ws_frames": 2050,
"encode_1000_ws_frames_holding_buffer": 3,
"encode_1000_ws_frames_holding_buffer_with_mask": 2003,
"encode_1000_ws_frames_holding_buffer_with_mask": 2050,
"encode_1000_ws_frames_holding_buffer_with_space": 3,
"encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2003,
"encode_1000_ws_frames_new_buffer": 3000,
"encode_1000_ws_frames_new_buffer_with_mask": 5000,
"encode_1000_ws_frames_new_buffer_with_space": 3000,
"encode_1000_ws_frames_new_buffer_with_space_with_mask": 5000,
"encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050,
"encode_1000_ws_frames_new_buffer": 3050,
"encode_1000_ws_frames_new_buffer_with_mask": 5050,
"encode_1000_ws_frames_new_buffer_with_space": 3050,
"encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050,
"execute_hop_10000_tasks": 0,
"future_erase_result": 4001,
"future_lots_of_callbacks": 53001,
"get_100000_headers_canonical_form": 700000,
"get_100000_headers_canonical_form_trimming_whitespace": 700000,
"get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700000,
"get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700000,
"flat_schedule_10000_tasks": 100100,
"flat_schedule_assume_isolated_10000_tasks": 90100,
"future_assume_isolated_lots_of_callbacks": 74050,
"future_erase_result": 4050,
"future_lots_of_callbacks": 74050,
"get_100000_headers_canonical_form": 700050,
"get_100000_headers_canonical_form_trimming_whitespace": 700050,
"get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050,
"get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050,
"modifying_1000_circular_buffer_elements": 0,
"modifying_byte_buffer_view": 6000,
"ping_pong_1000_reqs_1_conn": 334,
"read_10000_chunks_from_file": 110009,
"schedule_10000_tasks": 40084,
"schedule_and_run_10000_tasks": 50010,
"modifying_byte_buffer_view": 6050,
"ping_pong_1000_reqs_1_conn": 329,
"read_10000_chunks_from_file": 110050,
"schedule_10000_tasks": 40100,
"schedule_and_run_10000_tasks": 50050,
"schedule_assume_isolated_10000_tasks": 40100,
"schedule_with_deadline_10000_tasks": 40100,
"schedule_with_deadline_assume_isolated_10000_tasks": 40100,
"scheduling_10000_executions": 89,
"udp_1000_reqs_1_conn": 6156,
"udp_1_reqs_1000_conn": 162000
"submit_10000_tasks": 20100,
"submit_assume_isolated_10000_tasks": 20100,
"udp_1000_reqs_1_conn": 6200,
"udp_1_reqs_1000_conn": 162050
}
@@ -1,50 +1,59 @@
{
"10000000_asyncsequenceproducer": 19,
"1000000_asyncwriter": 1000013,
"1000_addHandlers": 44000,
"1000_addHandlers_sync": 36000,
"1000_addRemoveHandlers_handlercontext": 8032,
"1000_addRemoveHandlers_handlername": 8032,
"1000_addRemoveHandlers_handlertype": 8032,
"1000_autoReadGetAndSet": 18000,
"1000000_asyncwriter": 1000050,
"1000_addHandlers": 44050,
"1000_addHandlers_sync": 37050,
"1000_addRemoveHandlers_handlercontext": 8050,
"1000_addRemoveHandlers_handlername": 8050,
"1000_addRemoveHandlers_handlertype": 8050,
"1000_autoReadGetAndSet": 18050,
"1000_autoReadGetAndSet_sync": 0,
"1000_copying_bytebufferview_to_array": 1000,
"1000_copying_circularbuffer_to_array": 1000,
"1000_getHandlers": 8034,
"1000_getHandlers_sync": 34,
"1000_reqs_1_conn": 26363,
"1000_rst_connections": 145004,
"1000_tcpbootstraps": 3001,
"1000_tcpconnections": 152002,
"1000_udp_reqs": 6014,
"1000_udpbootstraps": 2000,
"1000_udpconnections": 75008,
"1_reqs_1000_conn": 389000,
"bytebuffer_lots_of_rw": 2005,
"1000_copying_bytebufferview_to_array": 1050,
"1000_copying_circularbuffer_to_array": 1050,
"1000_getHandlers": 8050,
"1000_getHandlers_sync": 35,
"1000_reqs_1_conn": 26400,
"1000_rst_connections": 145050,
"1000_tcpbootstraps": 3050,
"1000_tcpconnections": 152050,
"1000_udp_reqs": 6050,
"1000_udpbootstraps": 2050,
"1000_udpconnections": 75050,
"1_reqs_1000_conn": 384000,
"assume_isolated_scheduling_10000_executions": 89,
"bytebuffer_lots_of_rw": 2050,
"creating_10000_headers": 0,
"decode_1000_ws_frames": 2000,
"decode_1000_ws_frames": 2050,
"encode_1000_ws_frames_holding_buffer": 3,
"encode_1000_ws_frames_holding_buffer_with_mask": 2003,
"encode_1000_ws_frames_holding_buffer_with_mask": 2050,
"encode_1000_ws_frames_holding_buffer_with_space": 3,
"encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2003,
"encode_1000_ws_frames_new_buffer": 3000,
"encode_1000_ws_frames_new_buffer_with_mask": 5000,
"encode_1000_ws_frames_new_buffer_with_space": 3000,
"encode_1000_ws_frames_new_buffer_with_space_with_mask": 5000,
"encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050,
"encode_1000_ws_frames_new_buffer": 3050,
"encode_1000_ws_frames_new_buffer_with_mask": 5050,
"encode_1000_ws_frames_new_buffer_with_space": 3050,
"encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050,
"execute_hop_10000_tasks": 0,
"future_erase_result": 4001,
"future_lots_of_callbacks": 53001,
"get_100000_headers_canonical_form": 700000,
"get_100000_headers_canonical_form_trimming_whitespace": 700000,
"get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700000,
"get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700000,
"flat_schedule_10000_tasks": 100100,
"flat_schedule_assume_isolated_10000_tasks": 90100,
"future_assume_isolated_lots_of_callbacks": 74050,
"future_erase_result": 4050,
"future_lots_of_callbacks": 74050,
"get_100000_headers_canonical_form": 700050,
"get_100000_headers_canonical_form_trimming_whitespace": 700050,
"get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050,
"get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050,
"modifying_1000_circular_buffer_elements": 0,
"modifying_byte_buffer_view": 6000,
"ping_pong_1000_reqs_1_conn": 319,
"read_10000_chunks_from_file": 110009,
"schedule_10000_tasks": 40084,
"schedule_and_run_10000_tasks": 50010,
"modifying_byte_buffer_view": 6050,
"ping_pong_1000_reqs_1_conn": 314,
"read_10000_chunks_from_file": 110050,
"schedule_10000_tasks": 40100,
"schedule_and_run_10000_tasks": 50050,
"schedule_assume_isolated_10000_tasks": 40100,
"schedule_with_deadline_10000_tasks": 40100,
"schedule_with_deadline_assume_isolated_10000_tasks": 40100,
"scheduling_10000_executions": 89,
"udp_1000_reqs_1_conn": 6156,
"udp_1_reqs_1000_conn": 162000
"submit_10000_tasks": 20100,
"submit_assume_isolated_10000_tasks": 20100,
"udp_1000_reqs_1_conn": 6200,
"udp_1_reqs_1000_conn": 162050
}
@@ -1,50 +0,0 @@
{
"10000000_asyncsequenceproducer": 19,
"1000000_asyncwriter": 1000013,
"1000_addHandlers": 44000,
"1000_addHandlers_sync": 36000,
"1000_addRemoveHandlers_handlercontext": 8032,
"1000_addRemoveHandlers_handlername": 8032,
"1000_addRemoveHandlers_handlertype": 8032,
"1000_autoReadGetAndSet": 18000,
"1000_autoReadGetAndSet_sync": 0,
"1000_copying_bytebufferview_to_array": 1000,
"1000_copying_circularbuffer_to_array": 1000,
"1000_getHandlers": 8034,
"1000_getHandlers_sync": 34,
"1000_reqs_1_conn": 26363,
"1000_rst_connections": 145004,
"1000_tcpbootstraps": 3001,
"1000_tcpconnections": 152002,
"1000_udp_reqs": 6014,
"1000_udpbootstraps": 2000,
"1000_udpconnections": 75008,
"1_reqs_1000_conn": 389000,
"bytebuffer_lots_of_rw": 2005,
"creating_10000_headers": 0,
"decode_1000_ws_frames": 2000,
"encode_1000_ws_frames_holding_buffer": 3,
"encode_1000_ws_frames_holding_buffer_with_mask": 2003,
"encode_1000_ws_frames_holding_buffer_with_space": 3,
"encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2003,
"encode_1000_ws_frames_new_buffer": 3000,
"encode_1000_ws_frames_new_buffer_with_mask": 5000,
"encode_1000_ws_frames_new_buffer_with_space": 3000,
"encode_1000_ws_frames_new_buffer_with_space_with_mask": 5000,
"execute_hop_10000_tasks": 0,
"future_erase_result": 4001,
"future_lots_of_callbacks": 53001,
"get_100000_headers_canonical_form": 700000,
"get_100000_headers_canonical_form_trimming_whitespace": 700000,
"get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700000,
"get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700000,
"modifying_1000_circular_buffer_elements": 0,
"modifying_byte_buffer_view": 6000,
"ping_pong_1000_reqs_1_conn": 319,
"read_10000_chunks_from_file": 110009,
"schedule_10000_tasks": 40084,
"schedule_and_run_10000_tasks": 50010,
"scheduling_10000_executions": 89,
"udp_1000_reqs_1_conn": 6156,
"udp_1_reqs_1000_conn": 162000
}
@@ -0,0 +1,59 @@
{
"10000000_asyncsequenceproducer": 19,
"1000000_asyncwriter": 1000050,
"1000_addHandlers": 44050,
"1000_addHandlers_sync": 37050,
"1000_addRemoveHandlers_handlercontext": 8050,
"1000_addRemoveHandlers_handlername": 8050,
"1000_addRemoveHandlers_handlertype": 8050,
"1000_autoReadGetAndSet": 18050,
"1000_autoReadGetAndSet_sync": 0,
"1000_copying_bytebufferview_to_array": 1050,
"1000_copying_circularbuffer_to_array": 1050,
"1000_getHandlers": 8050,
"1000_getHandlers_sync": 35,
"1000_reqs_1_conn": 26400,
"1000_rst_connections": 145050,
"1000_tcpbootstraps": 3050,
"1000_tcpconnections": 152050,
"1000_udp_reqs": 6050,
"1000_udpbootstraps": 2050,
"1000_udpconnections": 75050,
"1_reqs_1000_conn": 384050,
"assume_isolated_scheduling_10000_executions": 89,
"bytebuffer_lots_of_rw": 2050,
"creating_10000_headers": 0,
"decode_1000_ws_frames": 2050,
"encode_1000_ws_frames_holding_buffer": 3,
"encode_1000_ws_frames_holding_buffer_with_mask": 2050,
"encode_1000_ws_frames_holding_buffer_with_space": 3,
"encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050,
"encode_1000_ws_frames_new_buffer": 3050,
"encode_1000_ws_frames_new_buffer_with_mask": 5050,
"encode_1000_ws_frames_new_buffer_with_space": 3050,
"encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050,
"execute_hop_10000_tasks": 0,
"flat_schedule_10000_tasks": 100100,
"flat_schedule_assume_isolated_10000_tasks": 90100,
"future_assume_isolated_lots_of_callbacks": 74050,
"future_erase_result": 4050,
"future_lots_of_callbacks": 74050,
"get_100000_headers_canonical_form": 700050,
"get_100000_headers_canonical_form_trimming_whitespace": 700050,
"get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050,
"get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050,
"modifying_1000_circular_buffer_elements": 0,
"modifying_byte_buffer_view": 6050,
"ping_pong_1000_reqs_1_conn": 314,
"read_10000_chunks_from_file": 110050,
"schedule_10000_tasks": 40100,
"schedule_and_run_10000_tasks": 50050,
"schedule_assume_isolated_10000_tasks": 40100,
"schedule_with_deadline_10000_tasks": 40100,
"schedule_with_deadline_assume_isolated_10000_tasks": 40100,
"scheduling_10000_executions": 89,
"submit_10000_tasks": 20100,
"submit_assume_isolated_10000_tasks": 20100,
"udp_1000_reqs_1_conn": 6200,
"udp_1_reqs_1000_conn": 162050
}
@@ -1,50 +1,59 @@
{
"10000000_asyncsequenceproducer": 19,
"1000000_asyncwriter": 1000013,
"1000_addHandlers": 44000,
"1000_addHandlers_sync": 36000,
"1000_addRemoveHandlers_handlercontext": 8032,
"1000_addRemoveHandlers_handlername": 8032,
"1000_addRemoveHandlers_handlertype": 8032,
"1000_autoReadGetAndSet": 18000,
"1000000_asyncwriter": 1000050,
"1000_addHandlers": 44050,
"1000_addHandlers_sync": 37050,
"1000_addRemoveHandlers_handlercontext": 8050,
"1000_addRemoveHandlers_handlername": 8050,
"1000_addRemoveHandlers_handlertype": 8050,
"1000_autoReadGetAndSet": 18050,
"1000_autoReadGetAndSet_sync": 0,
"1000_copying_bytebufferview_to_array": 1000,
"1000_copying_circularbuffer_to_array": 1000,
"1000_getHandlers": 8034,
"1000_getHandlers_sync": 34,
"1000_reqs_1_conn": 26363,
"1000_rst_connections": 145004,
"1000_tcpbootstraps": 3001,
"1000_tcpconnections": 152002,
"1000_udp_reqs": 6014,
"1000_udpbootstraps": 2000,
"1000_udpconnections": 75008,
"1_reqs_1000_conn": 389000,
"bytebuffer_lots_of_rw": 2005,
"1000_copying_bytebufferview_to_array": 1050,
"1000_copying_circularbuffer_to_array": 1050,
"1000_getHandlers": 8050,
"1000_getHandlers_sync": 35,
"1000_reqs_1_conn": 26400,
"1000_rst_connections": 145050,
"1000_tcpbootstraps": 3050,
"1000_tcpconnections": 152050,
"1000_udp_reqs": 6050,
"1000_udpbootstraps": 2050,
"1000_udpconnections": 75050,
"1_reqs_1000_conn": 384050,
"assume_isolated_scheduling_10000_executions": 89,
"bytebuffer_lots_of_rw": 2050,
"creating_10000_headers": 0,
"decode_1000_ws_frames": 2000,
"decode_1000_ws_frames": 2050,
"encode_1000_ws_frames_holding_buffer": 3,
"encode_1000_ws_frames_holding_buffer_with_mask": 2003,
"encode_1000_ws_frames_holding_buffer_with_mask": 2050,
"encode_1000_ws_frames_holding_buffer_with_space": 3,
"encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2003,
"encode_1000_ws_frames_new_buffer": 3000,
"encode_1000_ws_frames_new_buffer_with_mask": 5000,
"encode_1000_ws_frames_new_buffer_with_space": 3000,
"encode_1000_ws_frames_new_buffer_with_space_with_mask": 5000,
"encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050,
"encode_1000_ws_frames_new_buffer": 3050,
"encode_1000_ws_frames_new_buffer_with_mask": 5050,
"encode_1000_ws_frames_new_buffer_with_space": 3050,
"encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050,
"execute_hop_10000_tasks": 0,
"future_erase_result": 4001,
"future_lots_of_callbacks": 53001,
"get_100000_headers_canonical_form": 700000,
"get_100000_headers_canonical_form_trimming_whitespace": 700000,
"get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700000,
"get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700000,
"flat_schedule_10000_tasks": 100100,
"flat_schedule_assume_isolated_10000_tasks": 80100,
"future_assume_isolated_lots_of_callbacks": 74050,
"future_erase_result": 4050,
"future_lots_of_callbacks": 74050,
"get_100000_headers_canonical_form": 500050,
"get_100000_headers_canonical_form_trimming_whitespace": 500050,
"get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 500050,
"get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 500050,
"modifying_1000_circular_buffer_elements": 0,
"modifying_byte_buffer_view": 6000,
"ping_pong_1000_reqs_1_conn": 319,
"read_10000_chunks_from_file": 110009,
"schedule_10000_tasks": 40084,
"schedule_and_run_10000_tasks": 50010,
"modifying_byte_buffer_view": 6050,
"ping_pong_1000_reqs_1_conn": 314,
"read_10000_chunks_from_file": 110050,
"schedule_10000_tasks": 40100,
"schedule_and_run_10000_tasks": 50050,
"schedule_assume_isolated_10000_tasks": 40100,
"schedule_with_deadline_10000_tasks": 40100,
"schedule_with_deadline_assume_isolated_10000_tasks": 40100,
"scheduling_10000_executions": 89,
"udp_1000_reqs_1_conn": 6156,
"udp_1_reqs_1000_conn": 162000
"submit_10000_tasks": 20100,
"submit_assume_isolated_10000_tasks": 20100,
"udp_1000_reqs_1_conn": 6200,
"udp_1_reqs_1000_conn": 162050
}
@@ -0,0 +1,34 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import NIOPosix
func run(identifier: String) {
measure(identifier: identifier) {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next()
let dg = DispatchGroup()
try! loop.submit {
for _ in 0..<10_000 {
dg.enter()
loop.assumeIsolated().execute { dg.leave() }
}
}.wait()
dg.wait()
try! group.syncShutdownGracefully()
return 10_000
}
}
@@ -0,0 +1,41 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import NIOCore
import NIOPosix
func run(identifier: String) {
measure(identifier: identifier) {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next()
let counter = try! loop.submit { () -> Int in
var counter: Int = 0
let deadline = NIODeadline.now() + .hours(1)
for _ in 0..<10000 {
loop.flatScheduleTask(deadline: deadline) {
counter &+= 1
return loop.makeSucceededFuture(counter)
}
}
return counter
}.wait()
try! group.syncShutdownGracefully()
return counter
}
}
@@ -0,0 +1,41 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import NIOCore
import NIOPosix
func run(identifier: String) {
measure(identifier: identifier) {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next()
let counter = try! loop.submit { () -> Int in
var counter: Int = 0
let deadline = NIODeadline.now() + .hours(1)
for _ in 0..<10000 {
loop.assumeIsolated().flatScheduleTask(deadline: deadline) {
counter &+= 1
return loop.makeSucceededFuture(counter)
}
}
return counter
}.wait()
try! group.syncShutdownGracefully()
return counter
}
}
@@ -0,0 +1,122 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOEmbedded
// This test is an equivalent of test_future_lots_of_callbacks.swift. It should
// have the same allocations as that test, and any difference is a bug.
func run(identifier: String) {
measure(identifier: identifier) {
struct MyError: Error {}
@inline(never)
func doThenAndFriends(loop: EventLoop) {
let p = loop.makePromise(of: Int.self)
let f = p.futureResult.assumeIsolated().flatMap { (r: Int) -> EventLoopFuture<Int> in
// This call allocates a new Future, and
// so does flatMap(), so this is two Futures.
loop.makeSucceededFuture(r + 1)
}.flatMapThrowing { (r: Int) -> Int in
// flatMapThrowing allocates a new Future, and calls `flatMap`
// which also allocates, so this is two.
r + 2
}.map { (r: Int) -> Int in
// map allocates a new future, and calls `flatMap` which
// also allocates, so this is two.
r + 2
}.flatMapThrowing { (r: Int) -> Int in
// flatMapThrowing allocates a future on the error path and
// calls `flatMap`, which also allocates, so this is two.
throw MyError()
}.flatMapError { (err: Error) -> EventLoopFuture<Int?> in
// This call allocates a new Future, and so does flatMapError,
// so this is two Futures.
loop.makeFailedFuture(err)
}.flatMapErrorThrowing { (err: Error) -> Int? in
// flatMapError allocates a new Future, and calls flatMapError,
// so this is two Futures
throw err
}.recover { (err: Error) -> Int? in
// recover allocates a future, and calls flatMapError, so
// this is two Futures.
nil
}.unwrap { () -> Int in
// unwrap calls map, with an extra closure, so this is three.
1
}.always { (Int) -> Void in
// This is a do-nothing call, but it can't be optimised out.
// always calls whenComplete but adds a new closure, so it allocates
// two times.
_ = 1 + 1
}.flatMapResult { (Int) -> Result<Int?, Error> in
// flatMapResult allocates a new future and creates a _whenComplete closure,
// so this is two.
.success(5)
}
.unwrap(orReplace: 5) // Same as unwrap above, this is three.
// Add some when*.
f.whenSuccess {
// whenSuccess should be just one.
_ = $0 + 1
}
f.whenFailure { _ in
// whenFailure should also be just one.
fatalError()
}
f.whenComplete {
// whenComplete should also be just one.
switch $0 {
case .success:
()
case .failure:
fatalError()
}
}
p.assumeIsolated().succeed(0)
// Wait also allocates a lock.
_ = try! f.nonisolated().wait()
}
@inline(never)
func doAnd(loop: EventLoop) {
// This isn't relevant to this test, but we keep it here to keep the numbers lining up.
let p1 = loop.makePromise(of: Int.self)
let p2 = loop.makePromise(of: Int.self)
let p3 = loop.makePromise(of: Int.self)
// Each call to and() allocates a Future. The calls to
// and(result:) allocate two.
let f = p1.futureResult
.and(p2.futureResult)
.and(p3.futureResult)
.and(value: 1)
.and(value: 1)
p1.succeed(1)
p2.succeed(1)
p3.succeed(1)
_ = try! f.wait()
}
let el = EmbeddedEventLoop()
for _ in 0..<1000 {
doThenAndFriends(loop: el)
doAnd(loop: el)
}
return 1000
}
}
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2017-2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -37,19 +37,52 @@ func run(identifier: String) {
// flatMapThrowing allocates a future on the error path and
// calls `flatMap`, which also allocates, so this is two.
throw MyError()
}.flatMapError { (err: Error) -> EventLoopFuture<Int> in
}.flatMapError { (err: Error) -> EventLoopFuture<Int?> in
// This call allocates a new Future, and so does flatMapError,
// so this is two Futures.
loop.makeFailedFuture(err)
}.flatMapErrorThrowing { (err: Error) -> Int in
}.flatMapErrorThrowing { (err: Error) -> Int? in
// flatMapError allocates a new Future, and calls flatMapError,
// so this is two Futures
throw err
}.recover { (err: Error) -> Int in
}.recover { (err: Error) -> Int? in
// recover allocates a future, and calls flatMapError, so
// this is two Futures.
nil
}.unwrap { () -> Int in
// unwrap calls map, with an extra closure, so this is three.
1
}.always { (Int) -> Void in
// This is a do-nothing call, but it can't be optimised out.
// always calls whenComplete but adds a new closure, so it allocates
// two times.
_ = 1 + 1
}.flatMapResult { (Int) -> Result<Int?, Error> in
// flatMapResult allocates a new future and creates a _whenComplete closure,
// so this is two.
.success(5)
}
.unwrap(orReplace: 5) // Same as unwrap above, this is three.
// Add some when*.
f.whenSuccess {
// whenSuccess should be just one.
_ = $0 + 1
}
f.whenFailure { _ in
// whenFailure should also be just one.
fatalError()
}
f.whenComplete {
// whenComplete should also be just one.
switch $0 {
case .success:
()
case .failure:
fatalError()
}
}
p.succeed(0)
// Wait also allocates a lock.
@@ -0,0 +1,37 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import NIOPosix
func run(identifier: String) {
measure(identifier: identifier) {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next()
let counter = try! loop.submit { () -> Int in
var counter: Int = 0
for _ in 0..<10000 {
loop.assumeIsolated().scheduleTask(in: .hours(1)) {
counter &+= 1
}
}
return counter
}.wait()
try! group.syncShutdownGracefully()
return counter
}
}
@@ -0,0 +1,40 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import NIOCore
import NIOPosix
func run(identifier: String) {
measure(identifier: identifier) {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next()
let counter = try! loop.submit { () -> Int in
var counter: Int = 0
let deadline = NIODeadline.now() + .hours(1)
for _ in 0..<10000 {
loop.scheduleTask(deadline: deadline) {
counter &+= 1
}
}
return counter
}.wait()
try! group.syncShutdownGracefully()
return counter
}
}
@@ -0,0 +1,41 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import NIOCore
import NIOPosix
func run(identifier: String) {
measure(identifier: identifier) {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next()
let counter = try! loop.submit { () -> Int in
var counter: Int = 0
let deadline = NIODeadline.now() + .hours(1)
for _ in 0..<10000 {
loop.assumeIsolated().scheduleTask(deadline: deadline) {
counter &+= 1
return counter
}
}
return counter
}.wait()
try! group.syncShutdownGracefully()
return counter
}
}
@@ -0,0 +1,38 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import NIOPosix
func run(identifier: String) {
measure(identifier: identifier) {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next()
let counter = try! loop.submit { () -> Int in
var counter: Int = 0
for _ in 0..<10000 {
_ = loop.submit {
counter &+= 1
return counter
}
}
return counter
}.wait()
try! group.syncShutdownGracefully()
return counter
}
}
@@ -0,0 +1,38 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import NIOPosix
func run(identifier: String) {
measure(identifier: identifier) {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next()
let counter = try! loop.submit { () -> Int in
var counter: Int = 0
for _ in 0..<10000 {
_ = loop.assumeIsolated().submit {
counter &+= 1
return counter
}
}
return counter
}.wait()
try! group.syncShutdownGracefully()
return counter
}
}
+9
View File
@@ -95,3 +95,12 @@ This product contains a derivation of the mocking infrastructure from Swift Syst
* https://www.apache.org/licenses/LICENSE-2.0
* HOMEPAGE:
* https://github.com/apple/swift-system
---
This product contains a derivation of "TokenBucket.swift" from Swift Package Manager.
* LICENSE (Apache License 2.0):
* https://www.apache.org/licenses/LICENSE-2.0
* HOMEPAGE:
* https://github.com/swiftlang/swift-package-manager
+62 -27
View File
@@ -23,7 +23,7 @@ let swiftAtomics: PackageDescription.Target.Dependency = .product(name: "Atomics
let swiftCollections: PackageDescription.Target.Dependency = .product(name: "DequeModule", package: "swift-collections")
let swiftSystem: PackageDescription.Target.Dependency = .product(name: "SystemPackage", package: "swift-system")
// These platforms require a depdency on `NIOPosix` from `NIOHTTP1` to maintain backward
// These platforms require a dependency on `NIOPosix` from `NIOHTTP1` to maintain backward
// compatibility with previous NIO versions.
let historicalNIOPosixDependencyRequired: [Platform] = [.macOS, .iOS, .tvOS, .watchOS, .linux, .android]
@@ -105,7 +105,8 @@ let package = Package(
"_NIODataStructures",
swiftAtomics,
swiftCollections,
]
],
swiftSettings: strictConcurrencySettings
),
.target(
name: "NIOPosix",
@@ -119,7 +120,8 @@ let package = Package(
swiftAtomics,
],
exclude: includePrivacyManifest ? [] : ["PrivacyInfo.xcprivacy"],
resources: includePrivacyManifest ? [.copy("PrivacyInfo.xcprivacy")] : []
resources: includePrivacyManifest ? [.copy("PrivacyInfo.xcprivacy")] : [],
swiftSettings: strictConcurrencySettings
),
.target(
name: "NIO",
@@ -127,21 +129,24 @@ let package = Package(
"NIOCore",
"NIOEmbedded",
"NIOPosix",
]
],
swiftSettings: strictConcurrencySettings
),
.target(
name: "_NIOConcurrency",
dependencies: [
.target(name: "NIO", condition: .when(platforms: historicalNIOPosixDependencyRequired)),
"NIOCore",
]
],
swiftSettings: strictConcurrencySettings
),
.target(
name: "NIOFoundationCompat",
dependencies: [
.target(name: "NIO", condition: .when(platforms: historicalNIOPosixDependencyRequired)),
"NIOCore",
]
],
swiftSettings: strictConcurrencySettings
),
.target(
name: "CNIOAtomics",
@@ -216,7 +221,8 @@ let package = Package(
.target(name: "NIO", condition: .when(platforms: historicalNIOPosixDependencyRequired)),
"NIOCore",
swiftCollections,
]
],
swiftSettings: strictConcurrencySettings
),
.target(
name: "NIOTestUtils",
@@ -242,7 +248,7 @@ let package = Package(
path: "Sources/NIOFileSystem",
exclude: includePrivacyManifest ? [] : ["PrivacyInfo.xcprivacy"],
resources: includePrivacyManifest ? [.copy("PrivacyInfo.xcprivacy")] : [],
swiftSettings: [
swiftSettings: strictConcurrencySettings + [
.define("ENABLE_MOCKING", .when(configuration: .debug))
]
),
@@ -251,7 +257,8 @@ let package = Package(
dependencies: [
"_NIOFileSystem"
],
path: "Sources/_NIOFileSystemExported"
path: "Sources/_NIOFileSystemExported",
swiftSettings: strictConcurrencySettings
),
.target(
name: "_NIOFileSystemFoundationCompat",
@@ -259,7 +266,8 @@ let package = Package(
"_NIOFileSystem",
"NIOFoundationCompat",
],
path: "Sources/NIOFileSystemFoundationCompat"
path: "Sources/NIOFileSystemFoundationCompat",
swiftSettings: strictConcurrencySettings
),
// MARK: - Examples
@@ -270,7 +278,8 @@ let package = Package(
"NIOPosix",
"NIOCore",
],
exclude: ["README.md"]
exclude: ["README.md"],
swiftSettings: strictConcurrencySettings
),
.executableTarget(
name: "NIOTCPEchoClient",
@@ -278,7 +287,8 @@ let package = Package(
"NIOPosix",
"NIOCore",
],
exclude: ["README.md"]
exclude: ["README.md"],
swiftSettings: strictConcurrencySettings
),
.executableTarget(
name: "NIOEchoServer",
@@ -287,7 +297,8 @@ let package = Package(
"NIOCore",
"NIOConcurrencyHelpers",
],
exclude: ["README.md"]
exclude: ["README.md"],
swiftSettings: strictConcurrencySettings
),
.executableTarget(
name: "NIOEchoClient",
@@ -296,7 +307,8 @@ let package = Package(
"NIOCore",
"NIOConcurrencyHelpers",
],
exclude: ["README.md"]
exclude: ["README.md"],
swiftSettings: strictConcurrencySettings
),
.executableTarget(
name: "NIOHTTP1Server",
@@ -325,7 +337,8 @@ let package = Package(
"NIOCore",
"NIOConcurrencyHelpers",
],
exclude: ["README.md"]
exclude: ["README.md"],
swiftSettings: strictConcurrencySettings
),
.executableTarget(
name: "NIOChatClient",
@@ -334,7 +347,8 @@ let package = Package(
"NIOCore",
"NIOConcurrencyHelpers",
],
exclude: ["README.md"]
exclude: ["README.md"],
swiftSettings: strictConcurrencySettings
),
.executableTarget(
name: "NIOWebSocketServer",
@@ -361,7 +375,8 @@ let package = Package(
dependencies: [
"NIOPosix",
"NIOCore",
]
],
swiftSettings: strictConcurrencySettings
),
.executableTarget(
name: "NIOUDPEchoServer",
@@ -369,7 +384,8 @@ let package = Package(
"NIOPosix",
"NIOCore",
],
exclude: ["README.md"]
exclude: ["README.md"],
swiftSettings: strictConcurrencySettings
),
.executableTarget(
name: "NIOUDPEchoClient",
@@ -377,7 +393,8 @@ let package = Package(
"NIOPosix",
"NIOCore",
],
exclude: ["README.md"]
exclude: ["README.md"],
swiftSettings: strictConcurrencySettings
),
.executableTarget(
name: "NIOAsyncAwaitDemo",
@@ -429,7 +446,8 @@ let package = Package(
"NIOConcurrencyHelpers",
"NIOCore",
"NIOEmbedded",
]
],
swiftSettings: strictConcurrencySettings
),
.testTarget(
name: "NIOPosixTests",
@@ -441,6 +459,7 @@ let package = Package(
"NIOConcurrencyHelpers",
"NIOEmbedded",
"CNIOLinux",
"CNIODarwin",
"NIOTLS",
]
),
@@ -505,15 +524,18 @@ let package = Package(
dependencies: [
"NIOCore",
"NIOFoundationCompat",
]
],
swiftSettings: strictConcurrencySettings
),
.testTarget(
name: "NIOTests",
dependencies: ["NIO"]
dependencies: ["NIO"],
swiftSettings: strictConcurrencySettings
),
.testTarget(
name: "NIOSingletonsTests",
dependencies: ["NIOCore", "NIOPosix"]
dependencies: ["NIOCore", "NIOPosix"],
swiftSettings: strictConcurrencySettings
),
.testTarget(
name: "NIOFileSystemTests",
@@ -524,7 +546,7 @@ let package = Package(
swiftCollections,
swiftSystem,
],
swiftSettings: [
swiftSettings: strictConcurrencySettings + [
.define("ENABLE_MOCKING", .when(configuration: .debug))
]
),
@@ -541,14 +563,16 @@ let package = Package(
// for the integration tests. Exclude the whole tree from
// the build.
"Test Data"
]
],
swiftSettings: strictConcurrencySettings
),
.testTarget(
name: "NIOFileSystemFoundationCompatTests",
dependencies: [
"_NIOFileSystem",
"_NIOFileSystemFoundationCompat",
]
],
swiftSettings: strictConcurrencySettings
),
]
)
@@ -556,7 +580,7 @@ let package = Package(
if Context.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil {
package.dependencies += [
.package(url: "https://github.com/apple/swift-atomics.git", from: "1.1.0"),
.package(url: "https://github.com/apple/swift-collections.git", from: "1.0.2"),
.package(url: "https://github.com/apple/swift-collections.git", from: "1.1.0"),
.package(url: "https://github.com/apple/swift-system.git", from: "1.4.0"),
]
} else {
@@ -566,3 +590,14 @@ if Context.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil {
.package(path: "../swift-system"),
]
}
// --- STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
for target in package.targets {
if target.type != .plugin {
var settings = target.swiftSettings ?? []
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
settings.append(.enableUpcomingFeature("MemberImportVisibility"))
target.swiftSettings = settings
}
}
// --- END: STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
+3 -3
View File
@@ -86,7 +86,7 @@ SwiftNIO | Minimum Swift Version
`2.43.0 ..< 2.51.0` | 5.5.2
`2.51.0 ..< 2.60.0` | 5.6
`2.60.0 ..< 2.65.0` | 5.7
`2.65.0 ..< 2.76.0 | 5.8
`2.65.0 ..< 2.76.0` | 5.8
`2.76.0 ...` | 5.9
### SwiftNIO 1
@@ -116,7 +116,7 @@ SemVer and SwiftNIO's Public API guarantees should result in a working program w
SwiftNIO is fundamentally a low-level tool for building high-performance networking applications in Swift. It particularly targets those use-cases where using a "thread-per-connection" model of concurrency is inefficient or untenable. This is a common limitation when building servers that use a large number of relatively low-utilization connections, such as HTTP servers.
To achieve its goals SwiftNIO extensively uses "non-blocking I/O": hence the name! Non-blocking I/O differs from the more common blocking I/O model because the application does not wait for data to be sent to or received from the network: instead, SwiftNIO asks for the kernel to notify it when I/O operations can be performed without waiting.
To achieve its goals, SwiftNIO extensively uses "non-blocking I/O": hence the name! Non-blocking I/O differs from the more common blocking I/O model because the application does not wait for data to be sent to or received from the network: instead, SwiftNIO asks for the kernel to notify it when I/O operations can be performed without waiting.
SwiftNIO does not aim to provide high-level solutions like, for example, web frameworks do. Instead, SwiftNIO is focused on providing the low-level building blocks for these higher-level applications. When it comes to building a web application, most users will not want to use SwiftNIO directly: instead, they'll want to use one of the many great web frameworks available in the Swift ecosystem. Those web frameworks, however, may choose to use SwiftNIO under the covers to provide their networking support.
@@ -139,7 +139,7 @@ All SwiftNIO applications are ultimately constructed of these various components
#### EventLoops and EventLoopGroups
The basic I/O primitive of SwiftNIO is the event loop. The event loop is an object that waits for events (usually I/O related events, such as "data received") to happen and then fires some kind of callback when they do. In almost all SwiftNIO applications there will be relatively few event loops: usually only one or two per CPU core the application wants to use. Generally speaking event loops run for the entire lifetime of your application, spinning in an endless loop dispatching events.
The basic I/O primitive of SwiftNIO is the event loop. The event loop is an object that waits for events (usually I/O related events, such as "data received") to happen and then fires some kind of callback when they do. In almost all SwiftNIO applications there will be relatively few event loops: usually only one or two per CPU core the application wants to use. Generally speaking, event loops run for the entire lifetime of your application, spinning in an endless loop dispatching events.
Event loops are gathered together into event loop *groups*. These groups provide a mechanism to distribute work around the event loops. For example, when listening for inbound connections the listening socket will be registered on one event loop. However, we don't want all connections that are accepted on that listening socket to be registered with the same event loop, as that would potentially overload one event loop while leaving the others empty. For that reason, the event loop group provides the ability to spread load across multiple event loops.
@@ -24,8 +24,11 @@ struct AsyncChannelIO<Request, Response> {
}
func start() async throws -> AsyncChannelIO<Request, Response> {
try await channel.pipeline.addHandler(RequestResponseHandler<HTTPRequestHead, NIOHTTPClientResponseFull>())
.get()
try await channel.eventLoop.submit {
try channel.pipeline.syncOperations.addHandler(
RequestResponseHandler<HTTPRequestHead, NIOHTTPClientResponseFull>()
)
}.get()
return self
}
+5 -13
View File
@@ -18,19 +18,9 @@ private final class ChatHandler: ChannelInboundHandler {
public typealias InboundIn = ByteBuffer
public typealias OutboundOut = ByteBuffer
private func printByte(_ byte: UInt8) {
#if os(Android)
print(Character(UnicodeScalar(byte)), terminator: "")
#else
fputc(Int32(byte), stdout)
#endif
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
var buffer = Self.unwrapInboundIn(data)
while let byte: UInt8 = buffer.readInteger() {
printByte(byte)
}
let buffer = Self.unwrapInboundIn(data)
print(String(buffer: buffer))
}
public func errorCaught(context: ChannelHandlerContext, error: Error) {
@@ -47,7 +37,9 @@ let bootstrap = ClientBootstrap(group: group)
// Enable SO_REUSEADDR.
.channelOption(.socketOption(.so_reuseaddr), value: 1)
.channelInitializer { channel in
channel.pipeline.addHandler(ChatHandler())
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(ChatHandler())
}
}
defer {
try! group.syncShutdownGracefully()
+35
View File
@@ -15,6 +15,8 @@
extension EventLoopFuture {
/// Get the value/error from an `EventLoopFuture` in an `async` context.
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
/// This function can be used to bridge an `EventLoopFuture` into the `async` world. Ie. if you're in an `async`
/// function and want to get the result of this future.
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@@ -37,6 +39,9 @@ extension EventLoopFuture {
#if canImport(Dispatch)
extension EventLoopGroup {
/// Shuts down the event loop gracefully.
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@inlinable
public func shutdownGracefully() async throws {
@@ -82,6 +87,8 @@ extension EventLoopPromise {
extension Channel {
/// Shortcut for calling `write` and `flush`.
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
/// - Parameters:
/// - data: the data to write
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@@ -113,6 +120,9 @@ extension Channel {
extension ChannelOutboundInvoker {
/// Register on an `EventLoop` and so have all its IO handled.
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
/// - Parameters:
/// - file: The file this function was called in, for debugging purposes.
/// - line: The line this function was called on, for debugging purposes.
@@ -122,6 +132,9 @@ extension ChannelOutboundInvoker {
}
/// Bind to a `SocketAddress`.
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
/// - Parameters:
/// - address: the `SocketAddress` to which we should bind the `Channel`.
/// - file: The file this function was called in, for debugging purposes.
@@ -132,6 +145,9 @@ extension ChannelOutboundInvoker {
}
/// Connect to a `SocketAddress`.
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
/// - Parameters:
/// - address: the `SocketAddress` to which we should connect the `Channel`.
/// - file: The file this function was called in, for debugging purposes.
@@ -143,6 +159,8 @@ extension ChannelOutboundInvoker {
/// Shortcut for calling `write` and `flush`.
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
/// - Parameters:
/// - data: the data to write
/// - file: The file this function was called in, for debugging purposes.
@@ -159,6 +177,8 @@ extension ChannelOutboundInvoker {
/// Close the `Channel` and so the connection if one exists.
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
/// - Parameters:
/// - mode: the `CloseMode` that is used
/// - file: The file this function was called in, for debugging purposes.
@@ -170,6 +190,8 @@ extension ChannelOutboundInvoker {
/// Trigger a custom user outbound event which will flow through the `ChannelPipeline`.
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
/// - Parameters:
/// - event: the event itself.
/// - file: The file this function was called in, for debugging purposes.
@@ -196,17 +218,26 @@ extension ChannelPipeline {
try await self.addHandler(handler, name: name, position: position).get()
}
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@preconcurrency
public func removeHandler(_ handler: RemovableChannelHandler & Sendable) async throws {
try await self.removeHandler(handler).get()
}
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func removeHandler(name: String) async throws {
try await self.removeHandler(name: name).get()
}
///
/// - warning: This method currently violates Structured Concurrency because cancellation isn't respected.
///
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@available(
*,
@@ -224,6 +255,7 @@ extension ChannelPipeline {
message:
"ChannelHandlerContext is not Sendable and it is therefore not safe to be used outside of its EventLoop"
)
@preconcurrency
public func context(handler: ChannelHandler & Sendable) async throws -> ChannelHandlerContext {
try await self.context(handler: handler).map { UnsafeTransfer($0) }.get().wrappedValue
@@ -423,6 +455,9 @@ struct AsyncSequenceFromIterator<AsyncIterator: AsyncIteratorProtocol>: AsyncSeq
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension AsyncSequenceFromIterator: Sendable where AsyncIterator: Sendable {}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension EventLoop {
@preconcurrency
@@ -301,15 +301,25 @@ public struct NIOAsyncChannel<Inbound: Sendable, Outbound: Sendable>: Sendable {
}
}
self._outbound.finish()
// We ignore errors from close, since all we care about is that the channel has been closed
// at this point.
self.channel.close(promise: nil)
// `closeFuture` should never be failed, so we could ignore the error. However, do an
// assertionFailure to guide bad Channel implementations that are incorrectly failing this
// future to stop failing it.
do {
self._outbound.finish()
try await self.channel.close().get()
try await self.channel.closeFuture.get()
} catch {
if let error = error as? ChannelError, error == .alreadyClosed {
return result
}
throw error
assertionFailure(
"""
The channel's closeFuture should never be failed, but it was failed with error: \(error).
This is an error in the channel's implementation.
Refer to `Channel/closeFuture`'s documentation for more information.
"""
)
}
return result
}
}
@@ -188,7 +188,7 @@ extension NIOAsyncChannelHandler: ChannelInboundHandler {
// We are making sure to be on our event loop so we can safely use self in whenComplete
channelReadTransformation(unwrapped)
.hop(to: context.eventLoop)
.assumeIsolated()
.assumeIsolatedUnsafeUnchecked()
.whenComplete { result in
switch result {
case .success:
@@ -105,7 +105,7 @@ public struct NIOAsyncSequenceProducer<
/// to yield new elements to the sequence.
/// 2. The ``sequence`` which is the actual `AsyncSequence` and
/// should be passed to the consumer.
public struct NewSequence {
public struct NewSequence: Sendable {
/// The source of the ``NIOAsyncSequenceProducer`` used to yield and finish.
public let source: Source
/// The actual sequence which should be passed to the consumer.
@@ -268,7 +268,7 @@ extension NIOAsyncSequenceProducer {
}
/// The result of a call to ``NIOAsyncSequenceProducer/Source/yield(_:)``.
public enum YieldResult: Hashable {
public enum YieldResult: Hashable, Sendable {
/// Indicates that the caller should produce more elements for now. The delegate's ``NIOAsyncSequenceProducerDelegate/produceMore()``
/// will **NOT** get called, since the demand was already signalled through this ``NIOAsyncSequenceProducer/Source/YieldResult``.
case produceMore
@@ -1173,7 +1173,38 @@ extension NIOAsyncWriter {
delegate: delegate
)
case .initial, .finished, .writerFinished:
case .writerFinished(
let isWritable,
let inDelegateOutcall,
var suspendedYields,
let cancelledYields,
let bufferedYieldIDs,
let delegate,
let error
):
// We have a suspended yield at this point that hasn't been cancelled yet.
// It was buffered before we became finished, so we still have to deliver it.
// We need to store the yield now.
self._state = .modifying
let suspendedYield = SuspendedYield(
yieldID: yieldID,
continuation: continuation
)
suspendedYields.append(suspendedYield)
self._state = .writerFinished(
isWritable: isWritable,
inDelegateOutcall: inDelegateOutcall,
suspendedYields: suspendedYields,
cancelledYields: cancelledYields,
bufferedYieldIDs: bufferedYieldIDs,
delegate: delegate,
error: error
)
case .initial, .finished:
preconditionFailure("This should have already been handled by `yield()`")
case .modifying:
@@ -1501,7 +1532,7 @@ extension NIOAsyncWriter {
self._state = .writerFinished(
isWritable: isWritable,
inDelegateOutcall: inDelegateOutcall,
inDelegateOutcall: false,
suspendedYields: .init(),
cancelledYields: cancelledYields,
bufferedYieldIDs: bufferedYieldIDs,
+10 -7
View File
@@ -39,7 +39,7 @@ extension ByteBuffer {
// this is not technically correct because we shouldn't just bind
// the memory to `UInt8` but it's not a real issue either and we
// need to work around https://bugs.swift.org/browse/SR-9604
[UInt8](UnsafeRawBufferPointer(fastRebase: ptr[range]).bindMemory(to: UInt8.self))
[UInt8](UnsafeRawBufferPointer(rebasing: ptr[range]).bindMemory(to: UInt8.self))
}
}
@@ -205,7 +205,10 @@ extension ByteBuffer {
}
return self.withUnsafeReadableBytes { pointer in
assert(range.lowerBound >= 0 && (range.upperBound - range.lowerBound) <= pointer.count)
return String(decoding: UnsafeRawBufferPointer(fastRebase: pointer[range]), as: Unicode.UTF8.self)
return String(
decoding: UnsafeRawBufferPointer(rebasing: pointer[range]),
as: Unicode.UTF8.self
)
}
}
@@ -329,7 +332,7 @@ extension ByteBuffer {
self.withVeryUnsafeMutableBytes { destCompleteStorage in
assert(destCompleteStorage.count >= index + allBytesCount)
let dest = destCompleteStorage[index..<index + allBytesCount]
dispatchData.copyBytes(to: .init(fastRebase: dest), count: dest.count)
dispatchData.copyBytes(to: .init(rebasing: dest), count: dest.count)
}
return allBytesCount
}
@@ -348,7 +351,7 @@ extension ByteBuffer {
return nil
}
return self.withUnsafeReadableBytes { pointer in
DispatchData(bytes: UnsafeRawBufferPointer(fastRebase: pointer[range]))
DispatchData(bytes: UnsafeRawBufferPointer(rebasing: pointer[range]))
}
}
@@ -497,7 +500,7 @@ extension ByteBuffer {
precondition(count >= 0, "Can't write fewer than 0 bytes")
self.reserveCapacity(index + count)
self.withVeryUnsafeMutableBytes { pointer in
let dest = UnsafeMutableRawBufferPointer(fastRebase: pointer[index..<index + count])
let dest = UnsafeMutableRawBufferPointer(rebasing: pointer[index..<index + count])
_ = dest.initializeMemory(as: UInt8.self, repeating: byte)
}
return count
@@ -730,13 +733,13 @@ extension ByteBuffer: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let base64String = try container.decode(String.self)
self = try ByteBuffer(bytes: base64String.base64Decoded())
self = try ByteBuffer(bytes: base64String._base64Decoded())
}
/// Encodes this buffer as a base64 string in a single value container.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
let base64String = String(base64Encoding: self.readableBytesView)
let base64String = String(_base64Encoding: self.readableBytesView)
try container.encode(base64String)
}
}
+13 -12
View File
@@ -31,11 +31,10 @@ import WASILibc
@usableFromInline let sysMalloc: @convention(c) (size_t) -> UnsafeMutableRawPointer? = malloc
@usableFromInline let sysRealloc: @convention(c) (UnsafeMutableRawPointer?, size_t) -> UnsafeMutableRawPointer? =
realloc
/// Xcode 13 GM shipped with a bug in the SDK that caused `free`'s first argument to be annotated as
/// non-nullable. To that end, we define a thunk through to `free` that matches that constraint, as we
/// never pass a `nil` pointer to it.
@usableFromInline let sysFree: @convention(c) (UnsafeMutableRawPointer) -> Void = { free($0) }
@inlinable
func sysFree(_ ptr: UnsafeMutableRawPointer) {
free(ptr)
}
extension _ByteBufferSlice: Equatable {}
@@ -503,7 +502,9 @@ public struct ByteBuffer {
@inlinable
mutating func _setBytesAssumingUniqueBufferAccess(_ bytes: UnsafeRawBufferPointer, at index: _Index) {
let targetPtr = UnsafeMutableRawBufferPointer(fastRebase: self._slicedStorageBuffer.dropFirst(Int(index)))
let targetPtr = UnsafeMutableRawBufferPointer(
rebasing: self._slicedStorageBuffer.dropFirst(Int(index))
)
targetPtr.copyMemory(from: bytes)
}
@@ -515,7 +516,7 @@ public struct ByteBuffer {
func ensureCapacityAndReturnStorageBase(capacity: Int) -> UnsafeMutablePointer<UInt8> {
self._ensureAvailableCapacity(_Capacity(capacity), at: index)
let newBytesPtr = UnsafeMutableRawBufferPointer(
fastRebase: self._slicedStorageBuffer[Int(index)..<Int(index) + Int(capacity)]
rebasing: self._slicedStorageBuffer[Int(index)..<Int(index) + Int(capacity)]
)
return newBytesPtr.bindMemory(to: UInt8.self).baseAddress!
}
@@ -659,7 +660,7 @@ public struct ByteBuffer {
self._copyStorageAndRebaseIfNeeded()
// this is safe because we always know that readerIndex >= writerIndex
let range = Range<Int>(uncheckedBounds: (lower: self.readerIndex, upper: self.writerIndex))
return try body(.init(fastRebase: self._slicedStorageBuffer[range]))
return try body(.init(rebasing: self._slicedStorageBuffer[range]))
}
/// Yields the bytes currently writable (`bytesWritable` = `capacity` - `writerIndex`). Before reading those bytes you must first
@@ -677,7 +678,7 @@ public struct ByteBuffer {
_ body: (UnsafeMutableRawBufferPointer) throws -> T
) rethrows -> T {
self._copyStorageAndRebaseIfNeeded()
return try body(.init(fastRebase: self._slicedStorageBuffer.dropFirst(self.writerIndex)))
return try body(.init(rebasing: self._slicedStorageBuffer.dropFirst(self.writerIndex)))
}
/// This vends a pointer of the `ByteBuffer` at the `writerIndex` after ensuring that the buffer has at least `minimumWritableBytes` of writable bytes available.
@@ -748,7 +749,7 @@ public struct ByteBuffer {
public func withUnsafeReadableBytes<T>(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T {
// This is safe, writerIndex >= readerIndex
let range = Range<Int>(uncheckedBounds: (lower: self.readerIndex, upper: self.writerIndex))
return try body(.init(fastRebase: self._slicedStorageBuffer[range]))
return try body(.init(rebasing: self._slicedStorageBuffer[range]))
}
/// Yields a buffer pointer containing this `ByteBuffer`'s readable bytes. You may hold a pointer to those bytes
@@ -769,7 +770,7 @@ public struct ByteBuffer {
let storageReference: Unmanaged<AnyObject> = Unmanaged.passUnretained(self._storage)
// This is safe, writerIndex >= readerIndex
let range = Range<Int>(uncheckedBounds: (lower: self.readerIndex, upper: self.writerIndex))
return try body(.init(fastRebase: self._slicedStorageBuffer[range]), storageReference)
return try body(.init(rebasing: self._slicedStorageBuffer[range]), storageReference)
}
/// See `withUnsafeReadableBytesWithStorageManagement` and `withVeryUnsafeBytes`.
@@ -1120,7 +1121,7 @@ extension ByteBuffer {
self._ensureAvailableCapacity(_Capacity(length), at: _toIndex(toIndex))
self.withVeryUnsafeMutableBytes { ptr in
let srcPtr = UnsafeRawBufferPointer(start: ptr.baseAddress!.advanced(by: fromIndex), count: length)
let targetPtr = UnsafeMutableRawBufferPointer(fastRebase: ptr.dropFirst(toIndex))
let targetPtr = UnsafeMutableRawBufferPointer(rebasing: ptr.dropFirst(toIndex))
targetPtr.copyMemory(from: srcPtr)
}
+17 -1
View File
@@ -67,7 +67,7 @@ extension ByteBuffer {
return self.withUnsafeReadableBytes { ptr in
var value: T = 0
withUnsafeMutableBytes(of: &value) { valuePtr in
valuePtr.copyMemory(from: UnsafeRawBufferPointer(fastRebase: ptr[range]))
valuePtr.copyMemory(from: UnsafeRawBufferPointer(rebasing: ptr[range]))
}
return _toEndianness(value: value, endianness: endianness)
}
@@ -116,6 +116,7 @@ extension ByteBuffer {
}
extension FixedWidthInteger {
/// Returns the next power of two.
@inlinable
func nextPowerOf2() -> Self {
@@ -134,6 +135,21 @@ extension FixedWidthInteger {
return 1 << ((Self.bitWidth - 1) - self.leadingZeroBitCount)
}
/// Initialize an integer from a byte buffer of exactly the right size.
/// The bytes will be read using the host system's endianness.
///
/// - Parameters:
/// - buffer: The ByteBuffer to read from
/// - endianness: The endianness to use when reading the integer, defaults to the host system's endianness.
@inlinable
public init?(buffer: ByteBuffer, endianness: Endianness = .host) {
var buffer = buffer
guard let value = buffer.readInteger(endianness: endianness, as: Self.self), buffer.readableBytes == 0 else {
return nil
}
self = value
}
}
extension UInt32 {
+6
View File
@@ -107,6 +107,12 @@ public protocol Channel: AnyObject, ChannelOutboundInvoker, _NIOPreconcurrencySe
var allocator: ByteBufferAllocator { get }
/// The `closeFuture` will fire when the `Channel` has been closed.
///
/// - Important: This future should never be failed: it signals when the channel has been closed, and this action should not fail,
/// regardless of whether the close happenned cleanly or not.
/// If you are interested in any errors thrown during `close` to diagnose any unclean channel closures, you
/// should instead use the future returned from ``ChannelOutboundInvoker/close(mode:file:line:)-7hlgf``
/// or pass a promise via ``ChannelOutboundInvoker/close(mode:promise:)``.
var closeFuture: EventLoopFuture<Void> { get }
/// The `ChannelPipeline` which handles all I/O events and requests associated with this `Channel`.
+13 -11
View File
@@ -114,7 +114,7 @@ public final class AcceptBackoffHandler: ChannelDuplexHandler, RemovableChannelH
}
private func scheduleRead(at: NIODeadline, context: ChannelHandlerContext) {
self.scheduledRead = context.eventLoop.assumeIsolated().scheduleTask(deadline: at) {
self.scheduledRead = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(deadline: at) {
self.doRead(context)
}
}
@@ -252,7 +252,9 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl
}
let writePromise = promise ?? context.eventLoop.makePromise()
writePromise.futureResult.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
writePromise.futureResult.hop(
to: context.eventLoop
).assumeIsolatedUnsafeUnchecked().whenComplete { (_: Result<Void, Error>) in
self.lastWriteCompleteTime = .now()
}
context.write(data, promise: writePromise)
@@ -272,7 +274,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl
}
if self.reading {
self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask(
self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(
in: timeout,
self.makeReadTimeoutTask(context, timeout)
)
@@ -282,7 +284,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl
let diff = .now() - self.lastReadTime
if diff >= timeout {
// Reader is idle - set a new timeout and trigger an event through the pipeline
self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask(
self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(
in: timeout,
self.makeReadTimeoutTask(context, timeout)
)
@@ -290,7 +292,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl
context.fireUserInboundEventTriggered(IdleStateEvent.read)
} else {
// Read occurred before the timeout - set a new timeout with shorter delay.
self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask(
self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(
deadline: self.lastReadTime + timeout,
self.makeReadTimeoutTask(context, timeout)
)
@@ -309,7 +311,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl
if diff >= timeout {
// Writer is idle - set a new timeout and notify the callback.
self.scheduledWriterTask = context.eventLoop.assumeIsolated().scheduleTask(
self.scheduledWriterTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(
in: timeout,
self.makeWriteTimeoutTask(context, timeout)
)
@@ -317,7 +319,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl
context.fireUserInboundEventTriggered(IdleStateEvent.write)
} else {
// Write occurred before the timeout - set a new timeout with shorter delay.
self.scheduledWriterTask = context.eventLoop.assumeIsolated().scheduleTask(
self.scheduledWriterTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(
deadline: self.lastWriteCompleteTime + timeout,
self.makeWriteTimeoutTask(context, timeout)
)
@@ -332,7 +334,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl
}
if self.reading {
self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask(
self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(
in: timeout,
self.makeAllTimeoutTask(context, timeout)
)
@@ -345,7 +347,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl
let diff = .now() - latestLast
if diff >= timeout {
// Reader is idle - set a new timeout and trigger an event through the pipeline
self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask(
self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(
in: timeout,
self.makeAllTimeoutTask(context, timeout)
)
@@ -353,7 +355,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl
context.fireUserInboundEventTriggered(IdleStateEvent.all)
} else {
// Read occurred before the timeout - set a new timeout with shorter delay.
self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask(
self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(
deadline: latestLast + timeout,
self.makeAllTimeoutTask(context, timeout)
)
@@ -367,7 +369,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl
_ body: @escaping (ChannelHandlerContext, TimeAmount) -> (() -> Void)
) -> Scheduled<Void>? {
if let timeout = amount {
return context.eventLoop.assumeIsolated().scheduleTask(in: timeout, body(context, timeout))
return context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(in: timeout, body(context, timeout))
}
return nil
}
+1 -1
View File
@@ -64,7 +64,7 @@ public typealias ConnectTimeoutOption = ChannelOptions.Types.ConnectTimeoutOptio
public typealias AllowRemoteHalfClosureOption = ChannelOptions.Types.AllowRemoteHalfClosureOption
extension ChannelOptions {
public enum Types {
public enum Types: Sendable {
/// `SocketOption` allows users to specify configuration settings that are directly applied to the underlying socket file descriptor.
///
+158 -16
View File
@@ -176,10 +176,14 @@ public final class ChannelPipeline: ChannelInvoker {
let future: EventLoopFuture<Void>
if self.eventLoop.inEventLoop {
future = self.eventLoop.makeCompletedFuture(self.addHandlerSync(handler, name: name, position: position))
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
future = self.eventLoop.makeCompletedFuture(
self.addHandlerSync(handler, name: name, position: syncPosition)
)
} else {
future = self.eventLoop.submit {
try self.addHandlerSync(handler, name: name, position: position).get()
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self.addHandlerSync(handler, name: name, position: syncPosition).get()
}
}
@@ -198,7 +202,7 @@ public final class ChannelPipeline: ChannelInvoker {
fileprivate func addHandlerSync(
_ handler: ChannelHandler,
name: String? = nil,
position: ChannelPipeline.Position = .last
position: ChannelPipeline.SynchronousOperations.Position = .last
) -> Result<Void, Error> {
self.eventLoop.assertInEventLoop()
@@ -472,10 +476,10 @@ public final class ChannelPipeline: ChannelInvoker {
let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self)
if self.eventLoop.inEventLoop {
promise.assumeIsolated().completeWith(self.contextSync(handler: handler))
promise.assumeIsolatedUnsafeUnchecked().completeWith(self.contextSync(handler: handler))
} else {
self.eventLoop.execute {
promise.assumeIsolated().completeWith(self.contextSync(handler: handler))
promise.assumeIsolatedUnsafeUnchecked().completeWith(self.contextSync(handler: handler))
}
}
@@ -501,10 +505,10 @@ public final class ChannelPipeline: ChannelInvoker {
let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self)
if self.eventLoop.inEventLoop {
promise.assumeIsolated().completeWith(self.contextSync(name: name))
promise.assumeIsolatedUnsafeUnchecked().completeWith(self.contextSync(name: name))
} else {
self.eventLoop.execute {
promise.assumeIsolated().completeWith(self.contextSync(name: name))
promise.assumeIsolatedUnsafeUnchecked().completeWith(self.contextSync(name: name))
}
}
@@ -534,10 +538,10 @@ public final class ChannelPipeline: ChannelInvoker {
let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self)
if self.eventLoop.inEventLoop {
promise.assumeIsolated().completeWith(self._contextSync(handlerType: handlerType))
promise.assumeIsolatedUnsafeUnchecked().completeWith(self._contextSync(handlerType: handlerType))
} else {
self.eventLoop.execute {
promise.assumeIsolated().completeWith(self._contextSync(handlerType: handlerType))
promise.assumeIsolatedUnsafeUnchecked().completeWith(self._contextSync(handlerType: handlerType))
}
}
@@ -1119,14 +1123,38 @@ extension ChannelPipeline {
/// - position: The position in the `ChannelPipeline` to add the handlers.
/// - Returns: A result representing whether the handlers were added or not.
fileprivate func addHandlersSync(
_ handlers: [ChannelHandler],
_ handlers: [ChannelHandler & Sendable],
position: ChannelPipeline.Position
) -> Result<Void, Error> {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
switch syncPosition {
case .first, .after:
return self._addHandlersSync(handlers.reversed(), position: syncPosition)
case .last, .before:
return self._addHandlersSync(handlers, position: syncPosition)
}
}
/// Synchronously adds the provided `ChannelHandler`s to the pipeline in the order given, taking
/// account of the behaviour of `ChannelHandler.add(first:)`.
///
/// This duplicate of the above method exists to avoid needing to rebox the array of existentials
/// from any (ChannelHandler & Sendable) to any ChannelHandler.
///
/// - Important: Must be called on the `EventLoop`.
/// - Parameters:
/// - handlers: The array of `ChannelHandler`s to add.
/// - position: The position in the `ChannelPipeline` to add the handlers.
/// - Returns: A result representing whether the handlers were added or not.
fileprivate func addHandlersSyncNotSendable(
_ handlers: [ChannelHandler],
position: ChannelPipeline.SynchronousOperations.Position
) -> Result<Void, Error> {
switch position {
case .first, .after:
return self._addHandlersSync(handlers.reversed(), position: position)
return self._addHandlersSyncNotSendable(handlers.reversed(), position: position)
case .last, .before:
return self._addHandlersSync(handlers, position: position)
return self._addHandlersSyncNotSendable(handlers, position: position)
}
}
@@ -1139,7 +1167,36 @@ extension ChannelPipeline {
/// - Returns: A result representing whether the handlers were added or not.
private func _addHandlersSync<Handlers: Sequence>(
_ handlers: Handlers,
position: ChannelPipeline.Position
position: ChannelPipeline.SynchronousOperations.Position
) -> Result<Void, Error> where Handlers.Element == ChannelHandler & Sendable {
self.eventLoop.assertInEventLoop()
for handler in handlers {
let result = self.addHandlerSync(handler, position: position)
switch result {
case .success:
()
case .failure:
return result
}
}
return .success(())
}
/// Synchronously adds a sequence of `ChannelHandlers` to the pipeline at the given position.
///
/// This duplicate of the above method exists to avoid needing to rebox the array of existentials
/// from any (ChannelHandler & Sendable) to any ChannelHandler.
///
/// - Important: Must be called on the `EventLoop`.
/// - Parameters:
/// - handlers: A sequence of handlers to add.
/// - position: The position in the `ChannelPipeline` to add the handlers.
/// - Returns: A result representing whether the handlers were added or not.
private func _addHandlersSyncNotSendable<Handlers: Sequence>(
_ handlers: Handlers,
position: ChannelPipeline.SynchronousOperations.Position
) -> Result<Void, Error> where Handlers.Element == ChannelHandler {
self.eventLoop.assertInEventLoop()
@@ -1186,22 +1243,56 @@ extension ChannelPipeline {
public func addHandler(
_ handler: ChannelHandler,
name: String? = nil,
position: ChannelPipeline.Position = .last
position: ChannelPipeline.SynchronousOperations.Position = .last
) throws {
try self._pipeline.addHandlerSync(handler, name: name, position: position).get()
}
/// Add a handler to the pipeline.
///
/// - Important: This *must* be called on the event loop.
/// - Parameters:
/// - handler: The handler to add.
/// - name: The name to use for the `ChannelHandler` when it's added. If no name is specified the one will be generated.
/// - position: The position in the `ChannelPipeline` to add `handler`. Defaults to `.last`.
@available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead")
@_disfavoredOverload
public func addHandler(
_ handler: ChannelHandler,
name: String? = nil,
position: ChannelPipeline.Position = .last
) throws {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self._pipeline.addHandlerSync(handler, name: name, position: syncPosition).get()
}
/// Add an array of handlers to the pipeline.
///
/// - Important: This *must* be called on the event loop.
/// - Parameters:
/// - handlers: The handlers to add.
/// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`.
public func addHandlers(
_ handlers: [ChannelHandler],
position: ChannelPipeline.SynchronousOperations.Position = .last
) throws {
try self._pipeline.addHandlersSyncNotSendable(handlers, position: position).get()
}
/// Add an array of handlers to the pipeline.
///
/// - Important: This *must* be called on the event loop.
/// - Parameters:
/// - handlers: The handlers to add.
/// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`.
@available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead")
@_disfavoredOverload
public func addHandlers(
_ handlers: [ChannelHandler],
position: ChannelPipeline.Position = .last
) throws {
try self._pipeline.addHandlersSync(handlers, position: position).get()
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self._pipeline.addHandlersSyncNotSendable(handlers, position: syncPosition).get()
}
/// Add one or more handlers to the pipeline.
@@ -1210,11 +1301,27 @@ extension ChannelPipeline {
/// - Parameters:
/// - handlers: The handlers to add.
/// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`.
public func addHandlers(
_ handlers: ChannelHandler...,
position: ChannelPipeline.SynchronousOperations.Position = .last
) throws {
try self._pipeline.addHandlersSyncNotSendable(handlers, position: position).get()
}
/// Add one or more handlers to the pipeline.
///
/// - Important: This *must* be called on the event loop.
/// - Parameters:
/// - handlers: The handlers to add.
/// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`.
@available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead")
@_disfavoredOverload
public func addHandlers(
_ handlers: ChannelHandler...,
position: ChannelPipeline.Position = .last
) throws {
try self._pipeline.addHandlersSync(handlers, position: position).get()
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self._pipeline.addHandlersSyncNotSendable(handlers, position: syncPosition).get()
}
/// Remove a `ChannelHandler` from the `ChannelPipeline`.
@@ -1522,6 +1629,41 @@ extension ChannelPipeline {
}
}
extension ChannelPipeline.SynchronousOperations {
/// A `Position` within the `ChannelPipeline`'s `SynchronousOperations` used to insert non-sendable handlers
/// into the `ChannelPipeline` at a certain position.
public enum Position {
/// The first `ChannelHandler` -- the front of the `ChannelPipeline`.
case first
/// The last `ChannelHandler` -- the back of the `ChannelPipeline`.
case last
/// Before the given `ChannelHandler`.
case before(ChannelHandler)
/// After the given `ChannelHandler`.
case after(ChannelHandler)
public init(_ position: ChannelPipeline.Position) {
switch position {
case .first:
self = .first
case .last:
self = .last
case .before(let handler):
self = .before(handler)
case .after(let handler):
self = .after(handler)
}
}
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@available(*, unavailable)
extension ChannelPipeline.SynchronousOperations.Position: Sendable {}
/// Special `ChannelHandler` that forwards all events to the `Channel.Unsafe` implementation.
final class HeadChannelHandler: _ChannelOutboundHandler, Sendable {
+1 -1
View File
@@ -749,7 +749,7 @@ extension ByteToMessageHandler: RemovableChannelHandler {
public func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) {
precondition(self.removalState == .notBeingRemoved)
self.removalState = .removalStarted
context.eventLoop.assumeIsolated().execute {
context.eventLoop.assumeIsolatedUnsafeUnchecked().execute {
self.processLeftovers(context: context)
assert(!self.state.isLeftoversNeedProcessing, "illegal state: \(self.state)")
switch self.removalState {
-1
View File
@@ -21,7 +21,6 @@ More specialized modules provide concrete implementations of many of the abstrac
- ``EventLoopGroup``
- ``EventLoop``
- ``NIOEventLoopGroupProvider``
- ``EventLoopIterator``
- ``Scheduled``
- ``RepeatedTask``
@@ -138,10 +138,11 @@ guaranteed to fire on the same isolation domain as the ``ChannelHandlerContext``
of data race is present. However, Swift Concurrency cannot guarantee this at compile time,
as the specific isolation domain is determined only at runtime.
In these contexts, today users can make their callbacks safe using ``NIOLoopBound`` and
``NIOLoopBoundBox``. These values can only be constructed on the event loop, and only allow
access to their values on the same event loop. These constraints are enforced at runtime,
so at compile time these are unconditionally `Sendable`.
In these contexts, users that cannot require NIO 2.77.0 can make their callbacks
safe using ``NIOLoopBound`` and ``NIOLoopBoundBox``. These values can only be
constructed on the event loop, and only allow access to their values on the same
event loop. These constraints are enforced at runtime, so at compile time these are
unconditionally `Sendable`.
> Warning: ``NIOLoopBound`` and ``NIOLoopBoundBox`` replace compile-time isolation checks
with runtime ones. This makes it possible to introduce crashes in your code. Please
@@ -150,18 +151,43 @@ so at compile time these are unconditionally `Sendable`.
``EventLoop``, use ``EventLoopFuture/hop(to:)`` to move it to your isolation domain
before using these types.
> Note: In a future NIO release we intend to improve the ergonomics of this common problem
by offering a related type that can only be created from an ``EventLoopFuture`` on a
given ``EventLoop``. This minimises the number of runtime checks, and will make it
easier and more pleasant to write this kind of code.
From NIO 2.77.0, new types were introduced to make this common problem easier. These types are
``EventLoopFuture/Isolated`` and ``EventLoopPromise/Isolated``. These isolated view types
can only be constructed from an existing Future or Promise, and they can only be constructed
on the ``EventLoop`` to which those futures or promises are bound. Because they are not
`Sendable`, we can be confident that these values never escape the isolation domain in which
they are created, which must be the same isolation domain where the callbacks execute.
As a result, these types can drop the `@Sendable` requirements on all the future closures, and
many of the `Sendable` requirements on the return types from future closures. They can also
drop the `Sendable` requirements from the promise completion functions.
These isolated views can be obtained by calling ``EventLoopFuture/assumeIsolated()`` or
``EventLoopPromise/assumeIsolated()``.
> Warning: ``EventLoopFuture/assumeIsolated()`` and ``EventLoopPromise/assumeIsolated()``
supplement compile-time isolation checks with runtime ones. This makes it possible
to introduce crashes in your code. Please ensure that you are 100% confident that the
isolation domains align. If you are not sure that the ``EventLoopFuture`` or
``EventLoopPromise`` you wish to attach a callback to is bound to your
``EventLoop``, use ``EventLoopFuture/hop(to:)`` to move it to your isolation domain
before using these types.
> Warning: ``EventLoopFuture/assumeIsolated()`` and ``EventLoopPromise/assumeIsolated()``
**must not** be called from a Swift concurrency context, either an async method or
from within an actor. This is because it uses runtime checking of the event loop
to confirm that the value is not being sent to a different concurrency domain.
When using an ``EventLoop`` as a custom actor executor, this API can be used to retrieve
a value that region based isolation will then allow to be sent to another domain.
## Interacting with Event Loops on the Event Loop
As with Futures, there are occasionally times where it is necessary to schedule
``EventLoop`` operations on the ``EventLoop`` where your code is currently executing.
Much like with ``EventLoopFuture``, you can use ``NIOLoopBound`` and ``NIOLoopBoundBox``
to make these callbacks safe.
Much like with ``EventLoopFuture``, if you need to support NIO versions before 2.77.0
you can use ``NIOLoopBound`` and ``NIOLoopBoundBox`` to make these callbacks safe.
> Warning: ``NIOLoopBound`` and ``NIOLoopBoundBox`` replace compile-time isolation checks
with runtime ones. This makes it possible to introduce crashes in your code. Please
@@ -170,7 +196,27 @@ to make these callbacks safe.
``EventLoop``, use ``EventLoopFuture/hop(to:)`` to move it to your isolation domain
before using these types.
> Note: In a future NIO release we intend to improve the ergonomics of this common problem
by offering a related type that can only be created from an ``EventLoopFuture`` on a
given ``EventLoop``. This minimises the number of runtime checks, and will make it
easier and more pleasant to write this kind of code.
From NIO 2.77.0, a new type was introduced to make this common problem easier. This type is
``NIOIsolatedEventLoop``. This isolated view type can only be constructed from an existing
``EventLoop``, and it can only be constructed on the ``EventLoop`` that is being wrapped.
Because this type is not `Sendable`, we can be confident that this value never escapes the
isolation domain in which it was created, which must be the same isolation domain where the
callbacks execute.
As a result, this type can drop the `@Sendable` requirements on all the operation closures, and
many of the `Sendable` requirements on the return types from these closures.
This isolated view can be obtained by calling ``EventLoop/assumeIsolated()``.
> Warning: ``EventLoop/assumeIsolated()`` supplements compile-time isolation checks with
runtime ones. This makes it possible to introduce crashes in your code. Please ensure
that you are 100% confident that the isolation domains align. If you are not sure that
the your code is running on the relevant ``EventLoop``, prefer the non-isolated type.
> Warning: ``EventLoop/assumeIsolated()`` **must not** be called from a Swift concurrency
context, either an async method or from within an actor. This is because it uses runtime
checking of the event loop to confirm that the value is not being sent to a different
concurrency domain.
When using an ``EventLoop`` as a custom actor executor, this API can be used to retrieve
a value that region based isolation will then allow to be sent to another domain.
+241 -6
View File
@@ -269,6 +269,9 @@ public protocol EventLoop: EventLoopGroup {
@preconcurrency
func submit<T>(_ task: @escaping @Sendable () throws -> T) -> EventLoopFuture<T>
/// The current time of the event loop.
var now: NIODeadline { get }
/// Schedule a `task` that is executed by this `EventLoop` at the given time.
///
/// - Parameters:
@@ -392,6 +395,74 @@ public protocol EventLoop: EventLoopGroup {
///
/// - NOTE: Event loops only need to implemented this if they provide a custom scheduled callback implementation.
func cancelScheduledCallback(_ scheduledCallback: NIOScheduledCallback)
/// Submit a given task to be executed by the ``EventLoop``, from a context where the caller
/// statically knows that the context is isolated.
///
/// This is an optional performance hook. ``EventLoop`` implementers are not required to implement
/// this witness, but may choose to do so to enable better performance of the isolated EL views. If
/// they do so, ``EventLoop/Isolated/execute`` will perform better.
func _executeIsolatedUnsafeUnchecked(_ task: @escaping () -> Void)
/// Submit a given task to be executed by the ``EventLoop```, from a context where the caller
/// statically knows that the context is isolated.
///
/// Once the execution is complete the returned ``EventLoopFuture`` is notified.
///
/// This is an optional performance hook. ``EventLoop`` implementers are not required to implement
/// this witness, but may choose to do so to enable better performance of the isolated EL views. If
/// they do so, ``EventLoop/Isolated/submit`` will perform better.
///
/// - Parameters:
/// - task: The closure that will be submitted to the ``EventLoop`` for execution.
/// - Returns: ``EventLoopFuture`` that is notified once the task was executed.
func _submitIsolatedUnsafeUnchecked<T>(_ task: @escaping () throws -> T) -> EventLoopFuture<T>
/// Schedule a `task` that is executed by this ``EventLoop`` at the given time, from a context where the caller
/// statically knows that the context is isolated.
///
/// This is an optional performance hook. ``EventLoop`` implementers are not required to implement
/// this witness, but may choose to do so to enable better performance of the isolated EL views. If
/// they do so, ``EventLoop/Isolated/scheduleTask(deadline:_:)`` will perform better.
///
/// - Parameters:
/// - deadline: The instant in time before which the task will not execute.
/// - task: The synchronous task to run. As with everything that runs on the ``EventLoop```, it must not block.
/// - Returns: A ``Scheduled``` object which may be used to cancel the task if it has not yet run, or to wait
/// on the completion of the task.
///
/// - Note: You can only cancel a task before it has started executing.
@discardableResult
func _scheduleTaskIsolatedUnsafeUnchecked<T>(
deadline: NIODeadline,
_ task: @escaping () throws -> T
) -> Scheduled<T>
/// Schedule a `task` that is executed by this ``EventLoop`` after the given amount of time, from a context where the caller
/// statically knows that the context is isolated.
///
/// This is an optional performance hook. ``EventLoop`` implementers are not required to implement
/// this witness, but may choose to do so to enable better performance of the isolated EL views. If
/// they do so, ``EventLoop/Isolated/scheduleTask(in:_:)`` will perform better.
///
/// - Parameters:
/// - in: The amount of time before which the task will not execute.
/// - task: The synchronous task to run. As with everything that runs on the ``EventLoop``, it must not block.
/// - Returns: A ``Scheduled`` object which may be used to cancel the task if it has not yet run, or to wait
/// on the completion of the task.
///
/// - Note: You can only cancel a task before it has started executing.
/// - Note: The `in` value is clamped to a maximum when running on a Darwin-kernel.
@discardableResult
func _scheduleTaskIsolatedUnsafeUnchecked<T>(
in: TimeAmount,
_ task: @escaping () throws -> T
) -> Scheduled<T>
}
extension EventLoop {
/// Default implementation of `now`: Returns `NIODeadline.now()`.
public var now: NIODeadline { .now() }
}
extension EventLoop {
@@ -414,6 +485,54 @@ extension EventLoop {
{
nil
}
/// Default implementation: wraps the task in an UnsafeTransfer.
@inlinable
public func _executeIsolatedUnsafeUnchecked(_ task: @escaping () -> Void) {
self.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(task)
self.execute {
unsafeTransfer.wrappedValue()
}
}
/// Default implementation: wraps the task in an UnsafeTransfer.
@inlinable
public func _submitIsolatedUnsafeUnchecked<T>(_ task: @escaping () throws -> T) -> EventLoopFuture<T> {
self.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(task)
return self.submit {
try unsafeTransfer.wrappedValue()
}
}
/// Default implementation: wraps the task in an UnsafeTransfer.
@inlinable
@discardableResult
public func _scheduleTaskIsolatedUnsafeUnchecked<T>(
deadline: NIODeadline,
_ task: @escaping () throws -> T
) -> Scheduled<T> {
self.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(task)
return self.scheduleTask(deadline: deadline) {
try unsafeTransfer.wrappedValue()
}
}
/// Default implementation: wraps the task in an UnsafeTransfer.
@inlinable
@discardableResult
public func _scheduleTaskIsolatedUnsafeUnchecked<T>(
in delay: TimeAmount,
_ task: @escaping () throws -> T
) -> Scheduled<T> {
self.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(task)
return self.scheduleTask(in: delay) {
try unsafeTransfer.wrappedValue()
}
}
}
extension EventLoop {
@@ -543,6 +662,88 @@ public struct TimeAmount: Hashable, Sendable {
}
}
/// Contains the logic for parsing time amounts from strings,
/// and printing pretty strings to represent time amounts.
extension TimeAmount: CustomStringConvertible {
/// Errors thrown when parsint a TimeAmount from a string
internal enum ValidationError: Error, Equatable {
/// Can't parse the provided unit
case unsupportedUnit(String)
/// Can't parse the number into a Double
case invalidNumber(String)
}
/// Creates a TimeAmount from a string representation with an optional default unit.
///
/// Supports formats like:
/// - "5s" (5 seconds)
/// - "100ms" (100 milliseconds)
/// - "42" (42 of default unit)
/// - "1 hr" (1 hour)
///
/// This function only supports one pair of the number and units, i.e. "5s" or "100ms" but not "5s 100ms".
///
/// Supported units:
/// - h, hr, hrs (hours)
/// - m, min (minutes)
/// - s, sec, secs (seconds)
/// - ms, millis (milliseconds)
/// - us, µs, micros (microseconds)
/// - ns, nanos (nanoseconds)
///
/// - Parameters:
/// - userProvidedString: The string to parse
///
/// - Throws: ValidationError if the string cannot be parsed
public init(_ userProvidedString: String) throws {
let lowercased = String(userProvidedString.filter { !$0.isWhitespace }).lowercased()
let parsedNumbers = lowercased.prefix(while: { $0.isWholeNumber || $0 == "," || $0 == "." })
let parsedUnit = String(lowercased.dropFirst(parsedNumbers.count))
guard let numbers = Int64(parsedNumbers) else {
throw ValidationError.invalidNumber("'\(userProvidedString)' cannot be parsed as number and unit")
}
switch parsedUnit {
case "h", "hr", "hrs":
self = .hours(numbers)
case "m", "min":
self = .minutes(numbers)
case "s", "sec", "secs":
self = .seconds(numbers)
case "ms", "millis":
self = .milliseconds(numbers)
case "us", "µs", "micros":
self = .microseconds(numbers)
case "ns", "nanos":
self = .nanoseconds(numbers)
default:
throw ValidationError.unsupportedUnit("Unknown unit '\(parsedUnit)' in '\(userProvidedString)'")
}
}
/// Returns a human-readable string representation of the time amount
/// using the most appropriate unit
public var description: String {
let fullNS = self.nanoseconds
let (fullUS, remUS) = fullNS.quotientAndRemainder(dividingBy: 1_000)
let (fullMS, remMS) = fullNS.quotientAndRemainder(dividingBy: 1_000_000)
let (fullS, remS) = fullNS.quotientAndRemainder(dividingBy: 1_000_000_000)
if remS == 0 {
return "\(fullS) s"
} else if remMS == 0 {
return "\(fullMS) ms"
} else if remUS == 0 {
return "\(fullUS) us"
} else {
return "\(fullNS) ns"
}
}
}
extension TimeAmount: Comparable {
@inlinable
public static func < (lhs: TimeAmount, rhs: TimeAmount) -> Bool {
@@ -753,12 +954,13 @@ extension EventLoop {
/// - Returns: An `EventLoopFuture` containing the result of `task`'s execution.
@inlinable
@preconcurrency
public func submit<T: Sendable>(_ task: @escaping @Sendable () throws -> T) -> EventLoopFuture<T> {
public func submit<T>(_ task: @escaping @Sendable () throws -> T) -> EventLoopFuture<T> {
let promise: EventLoopPromise<T> = makePromise(file: #fileID, line: #line)
self.execute {
do {
promise.succeed(try task())
// UnsafeUnchecked is allowed here because we know we are on the EL.
promise.assumeIsolatedUnsafeUnchecked().succeed(try task())
} catch let err {
promise.fail(err)
}
@@ -807,7 +1009,15 @@ extension EventLoop {
let promise: EventLoopPromise<T> = self.makePromise(file: file, line: line)
let scheduled = self.scheduleTask(deadline: deadline, task)
scheduled.futureResult.flatMap { $0 }.cascade(to: promise)
scheduled.futureResult.whenComplete { result in
switch result {
case .success(let futureResult):
promise.completeWith(futureResult)
case .failure(let error):
promise.fail(error)
}
}
return .init(promise: promise, cancellationTask: { scheduled.cancel() })
}
@@ -849,7 +1059,15 @@ extension EventLoop {
let promise: EventLoopPromise<T> = self.makePromise(file: file, line: line)
let scheduled = self.scheduleTask(in: delay, task)
scheduled.futureResult.flatMap { $0 }.cascade(to: promise)
scheduled.futureResult.whenComplete { result in
switch result {
case .success(let futureResult):
promise.completeWith(futureResult)
case .failure(let error):
promise.fail(error)
}
}
return .init(promise: promise, cancellationTask: { scheduled.cancel() })
}
@@ -1246,16 +1464,33 @@ extension EventLoopGroup {
}
#endif
/// This type is intended to be used by libraries which use NIO, and offer their users either the option
/// Deprecated.
///
/// This type was intended to be used by libraries which use NIO, and offer their users either the option
/// to `.share` an existing event loop group or create (and manage) a new one (`.createNew`) and let it be
/// managed by given library and its lifecycle.
///
/// Please use a `group: any EventLoopGroup` parameter instead. If you want to default to a global
/// singleton group instead, consider group: any EventLoopGroup = MultiThreadedEventLoopGroup.singleton` or
/// similar.
///
/// - See also: https://github.com/apple/swift-nio/issues/2142
public enum NIOEventLoopGroupProvider {
/// Use an `EventLoopGroup` provided by the user.
/// The owner of this group is responsible for its lifecycle.
case shared(EventLoopGroup)
/// Create a new `EventLoopGroup` when necessary.
/// Deprecated. Create a new `EventLoopGroup` when necessary.
/// The library which accepts this provider takes ownership of the created event loop group,
/// and must ensure its proper shutdown when the library is being shut down.
@available(
*,
deprecated,
message: """
Please use `.shared(existingGroup)` or use the singleton via \
`.shared(MultiThreadedEventLoopGroup.singleton)` or similar
"""
)
case createNew
}
@@ -14,8 +14,14 @@
/// A struct wrapping an ``EventLoop`` that ensures all calls to any method on this struct
/// are coming from the event loop.
@usableFromInline
struct IsolatedEventLoop {
///
/// This type is explicitly not `Sendable`. It may only be constructed on an event loop,
/// using ``EventLoop/assumeIsolated()``, and may not subsequently be passed to other isolation
/// domains.
///
/// Using this type relaxes the need to have the closures for ``EventLoop/execute(_:)``,
/// ``EventLoop/submit(_:)``, and ``EventLoop/scheduleTask(in:_:)`` to be `@Sendable`.
public struct NIOIsolatedEventLoop {
@usableFromInline
let _wrapped: EventLoop
@@ -25,13 +31,10 @@ struct IsolatedEventLoop {
}
/// Submit a given task to be executed by the `EventLoop`
@available(*, noasync)
@inlinable
func execute(_ task: @escaping () -> Void) {
self._wrapped.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(task)
self._wrapped.execute {
unsafeTransfer.wrappedValue()
}
public func execute(_ task: @escaping () -> Void) {
self._wrapped._executeIsolatedUnsafeUnchecked(task)
}
/// Submit a given task to be executed by the `EventLoop`. Once the execution is complete the returned `EventLoopFuture` is notified.
@@ -39,39 +42,35 @@ struct IsolatedEventLoop {
/// - Parameters:
/// - task: The closure that will be submitted to the `EventLoop` for execution.
/// - Returns: `EventLoopFuture` that is notified once the task was executed.
@available(*, noasync)
@inlinable
func submit<T>(_ task: @escaping () throws -> T) -> EventLoopFuture<T> {
self._wrapped.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(task)
return self._wrapped.submit {
try unsafeTransfer.wrappedValue()
}
public func submit<T>(_ task: @escaping () throws -> T) -> EventLoopFuture<T> {
self._wrapped._submitIsolatedUnsafeUnchecked(task)
}
/// Schedule a `task` that is executed by this `EventLoop` at the given time.
///
/// - Parameters:
/// - deadline: The time at which the task should run.
/// - task: The synchronous task to run. As with everything that runs on the `EventLoop`, it must not block.
/// - Returns: A `Scheduled` object which may be used to cancel the task if it has not yet run, or to wait
/// on the completion of the task.
///
/// - Note: You can only cancel a task before it has started executing.
@discardableResult
@available(*, noasync)
@inlinable
func scheduleTask<T>(
public func scheduleTask<T>(
deadline: NIODeadline,
_ task: @escaping () throws -> T
) -> Scheduled<T> {
self._wrapped.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(task)
return self._wrapped.scheduleTask(deadline: deadline) {
try unsafeTransfer.wrappedValue()
}
self._wrapped._scheduleTaskIsolatedUnsafeUnchecked(deadline: deadline, task)
}
/// Schedule a `task` that is executed by this `EventLoop` after the given amount of time.
///
/// - Parameters:
/// - delay: The time to wait before running the task.
/// - task: The synchronous task to run. As with everything that runs on the `EventLoop`, it must not block.
/// - Returns: A `Scheduled` object which may be used to cancel the task if it has not yet run, or to wait
/// on the completion of the task.
@@ -79,16 +78,13 @@ struct IsolatedEventLoop {
/// - Note: You can only cancel a task before it has started executing.
/// - Note: The `in` value is clamped to a maximum when running on a Darwin-kernel.
@discardableResult
@available(*, noasync)
@inlinable
func scheduleTask<T>(
public func scheduleTask<T>(
in delay: TimeAmount,
_ task: @escaping () throws -> T
) -> Scheduled<T> {
self._wrapped.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(task)
return self._wrapped.scheduleTask(in: delay) {
try unsafeTransfer.wrappedValue()
}
self._wrapped._scheduleTaskIsolatedUnsafeUnchecked(in: delay, task)
}
/// Schedule a `task` that is executed by this `EventLoop` at the given time.
@@ -97,48 +93,88 @@ struct IsolatedEventLoop {
/// this event loop might differ.
///
/// - Parameters:
/// - deadline: The time at which we should run the asynchronous task.
/// - file: The file in which the task is scheduled.
/// - line: The line of the `file` in which the task is scheduled.
/// - task: The asynchronous task to run. As with everything that runs on the `EventLoop`, it must not block.
/// - Returns: A `Scheduled` object which may be used to cancel the task if it has not yet run, or to wait
/// on the full execution of the task, including its returned `EventLoopFuture`.
///
/// - Note: You can only cancel a task before it has started executing.
@discardableResult
@available(*, noasync)
@inlinable
func flatScheduleTask<T: Sendable>(
public func flatScheduleTask<T: Sendable>(
deadline: NIODeadline,
file: StaticString = #file,
line: UInt = #line,
_ task: @escaping () throws -> EventLoopFuture<T>
) -> Scheduled<T> {
self._wrapped.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(task)
return self._wrapped.flatScheduleTask(deadline: deadline, file: file, line: line) {
try unsafeTransfer.wrappedValue()
let promise: EventLoopPromise<T> = self._wrapped.makePromise(file: file, line: line)
let scheduled = self.scheduleTask(deadline: deadline, task)
scheduled.futureResult.whenComplete { result in
switch result {
case .success(let futureResult):
promise.completeWith(futureResult)
case .failure(let error):
promise.fail(error)
}
}
return .init(promise: promise, cancellationTask: { scheduled.cancel() })
}
/// Returns the wrapped event loop.
@inlinable
func nonisolated() -> any EventLoop {
public func nonisolated() -> any EventLoop {
self._wrapped
}
}
extension EventLoop {
/// Assumes the calling context is isolated to the event loop.
@usableFromInline
func assumeIsolated() -> IsolatedEventLoop {
IsolatedEventLoop(self)
@inlinable
@available(*, noasync)
public func assumeIsolated() -> NIOIsolatedEventLoop {
self.preconditionInEventLoop()
return NIOIsolatedEventLoop(self)
}
/// Assumes the calling context is isolated to the event loop.
///
/// This version of ``EventLoop/assumeIsolated()`` omits the runtime
/// isolation check in release builds and doesn't prevent you using it
/// from using it in async contexts.
@inlinable
public func assumeIsolatedUnsafeUnchecked() -> NIOIsolatedEventLoop {
self.assertInEventLoop()
return NIOIsolatedEventLoop(self)
}
}
@available(*, unavailable)
extension NIOIsolatedEventLoop: Sendable {}
extension EventLoopFuture {
/// A struct wrapping an ``EventLoopFuture`` that ensures all calls to any method on this struct
/// are coming from the event loop of the future.
@usableFromInline
struct Isolated {
///
/// This type is explicitly not `Sendable`. It may only be constructed on an event loop,
/// using ``EventLoopFuture/assumeIsolated()``, and may not subsequently be passed to other isolation
/// domains.
///
/// Using this type relaxes the need to have the closures for the various ``EventLoopFuture``
/// callback-attaching functions be `Sendable`.
public struct Isolated {
@usableFromInline
let _wrapped: EventLoopFuture<Value>
@inlinable
init(_wrapped: EventLoopFuture<Value>) {
self._wrapped = _wrapped
}
/// When the current `EventLoopFuture<Value>` is fulfilled, run the provided callback,
/// which will provide a new `EventLoopFuture`.
///
@@ -160,6 +196,9 @@ extension EventLoopFuture {
/// }
/// ```
///
/// Note that the returned ``EventLoopFuture`` still needs a `Sendable` wrapped value,
/// as it may have been created on a different event loop.
///
/// Note: In a sense, the `EventLoopFuture<NewValue>` is returned before it's created.
///
/// - Parameters:
@@ -167,14 +206,29 @@ extension EventLoopFuture {
/// a new `EventLoopFuture`.
/// - Returns: A future that will receive the eventual value.
@inlinable
func flatMap<NewValue: Sendable>(
@available(*, noasync)
public func flatMap<NewValue: Sendable>(
_ callback: @escaping (Value) -> EventLoopFuture<NewValue>
) -> EventLoopFuture<NewValue>.Isolated {
self._wrapped.eventLoop.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(callback)
return self._wrapped.flatMap {
unsafeTransfer.wrappedValue($0)
}.assumeIsolated()
let next = EventLoopPromise<NewValue>.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop)
let base = self._wrapped
base._whenCompleteIsolated {
switch base._value! {
case .success(let t):
let futureU = callback(t)
if futureU.eventLoop.inEventLoop {
return futureU._addCallback {
next._setValue(value: futureU._value!)
}
} else {
futureU.cascade(to: next)
return CallbackList()
}
case .failure(let error):
return next._setValue(value: .failure(error))
}
}
return next.futureResult.assumeIsolatedUnsafeUnchecked()
}
/// When the current `EventLoopFuture<Value>` is fulfilled, run the provided callback, which
@@ -192,14 +246,26 @@ extension EventLoopFuture {
/// a new value lifted into a new `EventLoopFuture`.
/// - Returns: A future that will receive the eventual value.
@inlinable
func flatMapThrowing<NewValue>(
@available(*, noasync)
public func flatMapThrowing<NewValue>(
_ callback: @escaping (Value) throws -> NewValue
) -> EventLoopFuture<NewValue>.Isolated {
self._wrapped.eventLoop.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(callback)
return self._wrapped.flatMapThrowing {
try unsafeTransfer.wrappedValue($0)
}.assumeIsolated()
let next = EventLoopPromise<NewValue>.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop)
let base = self._wrapped
base._whenCompleteIsolated {
switch base._value! {
case .success(let t):
do {
let r = try callback(t)
return next._setValue(value: .success(r))
} catch {
return next._setValue(value: .failure(error))
}
case .failure(let e):
return next._setValue(value: .failure(e))
}
}
return next.futureResult.assumeIsolatedUnsafeUnchecked()
}
/// When the current `EventLoopFuture<Value>` is in an error state, run the provided callback, which
@@ -217,14 +283,26 @@ extension EventLoopFuture {
/// a new value lifted into a new `EventLoopFuture`.
/// - Returns: A future that will receive the eventual value or a rethrown error.
@inlinable
func flatMapErrorThrowing(
@available(*, noasync)
public func flatMapErrorThrowing(
_ callback: @escaping (Error) throws -> Value
) -> EventLoopFuture<Value>.Isolated {
self._wrapped.eventLoop.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(callback)
return self._wrapped.flatMapErrorThrowing {
try unsafeTransfer.wrappedValue($0)
}.assumeIsolated()
let next = EventLoopPromise<Value>.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop)
let base = self._wrapped
base._whenCompleteIsolated {
switch base._value! {
case .success(let t):
return next._setValue(value: .success(t))
case .failure(let e):
do {
let r = try callback(e)
return next._setValue(value: .success(r))
} catch {
return next._setValue(value: .failure(error))
}
}
}
return next.futureResult.assumeIsolatedUnsafeUnchecked()
}
/// When the current `EventLoopFuture<Value>` is fulfilled, run the provided callback, which
@@ -254,14 +332,21 @@ extension EventLoopFuture {
/// a new value lifted into a new `EventLoopFuture`.
/// - Returns: A future that will receive the eventual value.
@inlinable
func map<NewValue>(
@available(*, noasync)
public func map<NewValue>(
_ callback: @escaping (Value) -> (NewValue)
) -> EventLoopFuture<NewValue>.Isolated {
self._wrapped.eventLoop.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(callback)
return self._wrapped.map {
unsafeTransfer.wrappedValue($0)
}.assumeIsolated()
if NewValue.self == Value.self && NewValue.self == Void.self {
self.whenSuccess(callback as! (Value) -> Void)
return self as! EventLoopFuture<NewValue>.Isolated
} else {
let next = EventLoopPromise<NewValue>.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop)
let base = self._wrapped
base._whenCompleteIsolated {
next._setValue(value: base._value!.map(callback))
}
return next.futureResult.assumeIsolatedUnsafeUnchecked()
}
}
/// When the current `EventLoopFuture<Value>` is in an error state, run the provided callback, which
@@ -279,14 +364,29 @@ extension EventLoopFuture {
/// a new value lifted into a new `EventLoopFuture`.
/// - Returns: A future that will receive the recovered value.
@inlinable
func flatMapError(
@available(*, noasync)
public func flatMapError(
_ callback: @escaping (Error) -> EventLoopFuture<Value>
) -> EventLoopFuture<Value>.Isolated where Value: Sendable {
self._wrapped.eventLoop.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(callback)
return self._wrapped.flatMapError {
unsafeTransfer.wrappedValue($0)
}.assumeIsolated()
let next = EventLoopPromise<Value>.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop)
let base = self._wrapped
base._whenCompleteIsolated {
switch base._value! {
case .success(let t):
return next._setValue(value: .success(t))
case .failure(let e):
let t = callback(e)
if t.eventLoop.inEventLoop {
return t._addCallback {
next._setValue(value: t._value!)
}
} else {
t.cascade(to: next)
return CallbackList()
}
}
}
return next.futureResult.assumeIsolatedUnsafeUnchecked()
}
/// When the current `EventLoopFuture<Value>` is fulfilled, run the provided callback, which
@@ -303,14 +403,26 @@ extension EventLoopFuture {
/// a new value or error lifted into a new `EventLoopFuture`.
/// - Returns: A future that will receive the eventual value.
@inlinable
func flatMapResult<NewValue, SomeError: Error>(
@available(*, noasync)
public func flatMapResult<NewValue, SomeError: Error>(
_ body: @escaping (Value) -> Result<NewValue, SomeError>
) -> EventLoopFuture<NewValue>.Isolated {
self._wrapped.eventLoop.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(body)
return self._wrapped.flatMapResult {
unsafeTransfer.wrappedValue($0)
}.assumeIsolated()
let next = EventLoopPromise<NewValue>.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop)
let base = self._wrapped
base._whenCompleteIsolated {
switch base._value! {
case .success(let value):
switch body(value) {
case .success(let newValue):
return next._setValue(value: .success(newValue))
case .failure(let error):
return next._setValue(value: .failure(error))
}
case .failure(let e):
return next._setValue(value: .failure(e))
}
}
return next.futureResult.assumeIsolatedUnsafeUnchecked()
}
/// When the current `EventLoopFuture<Value>` is in an error state, run the provided callback, which
@@ -326,14 +438,21 @@ extension EventLoopFuture {
/// a new value lifted into a new `EventLoopFuture`.
/// - Returns: A future that will receive the recovered value.
@inlinable
func recover(
@available(*, noasync)
public func recover(
_ callback: @escaping (Error) -> Value
) -> EventLoopFuture<Value>.Isolated {
self._wrapped.eventLoop.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(callback)
return self._wrapped.recover {
unsafeTransfer.wrappedValue($0)
}.assumeIsolated()
let next = EventLoopPromise<Value>.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop)
let base = self._wrapped
base._whenCompleteIsolated {
switch base._value! {
case .success(let t):
return next._setValue(value: .success(t))
case .failure(let e):
return next._setValue(value: .success(callback(e)))
}
}
return next.futureResult.assumeIsolatedUnsafeUnchecked()
}
/// Adds an observer callback to this `EventLoopFuture` that is called when the
@@ -347,11 +466,14 @@ extension EventLoopFuture {
/// - Parameters:
/// - callback: The callback that is called with the successful result of the `EventLoopFuture`.
@inlinable
func whenSuccess(_ callback: @escaping (Value) -> Void) {
self._wrapped.eventLoop.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(callback)
return self._wrapped.whenSuccess {
unsafeTransfer.wrappedValue($0)
@available(*, noasync)
public func whenSuccess(_ callback: @escaping (Value) -> Void) {
let base = self._wrapped
base._whenCompleteIsolated {
if case .success(let t) = base._value! {
callback(t)
}
return CallbackList()
}
}
@@ -366,11 +488,14 @@ extension EventLoopFuture {
/// - Parameters:
/// - callback: The callback that is called with the failed result of the `EventLoopFuture`.
@inlinable
func whenFailure(_ callback: @escaping (Error) -> Void) {
self._wrapped.eventLoop.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(callback)
return self._wrapped.whenFailure {
unsafeTransfer.wrappedValue($0)
@available(*, noasync)
public func whenFailure(_ callback: @escaping (Error) -> Void) {
let base = self._wrapped
base._whenCompleteIsolated {
if case .failure(let e) = base._value! {
callback(e)
}
return CallbackList()
}
}
@@ -380,13 +505,14 @@ extension EventLoopFuture {
/// - Parameters:
/// - callback: The callback that is called when the `EventLoopFuture` is fulfilled.
@inlinable
func whenComplete(
@available(*, noasync)
public func whenComplete(
_ callback: @escaping (Result<Value, Error>) -> Void
) {
self._wrapped.eventLoop.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(callback)
return self._wrapped.whenComplete {
unsafeTransfer.wrappedValue($0)
let base = self._wrapped
base._whenCompleteIsolated {
callback(base._value!)
return CallbackList()
}
}
@@ -397,14 +523,12 @@ extension EventLoopFuture {
/// - callback: the callback that is called when the `EventLoopFuture` is fulfilled.
/// - Returns: the current `EventLoopFuture`
@inlinable
func always(
@available(*, noasync)
public func always(
_ callback: @escaping (Result<Value, Error>) -> Void
) -> EventLoopFuture<Value> {
self._wrapped.eventLoop.assertInEventLoop()
let unsafeTransfer = UnsafeTransfer(callback)
return self._wrapped.always {
unsafeTransfer.wrappedValue($0)
}
) -> EventLoopFuture<Value>.Isolated {
self.whenComplete { result in callback(result) }
return self
}
/// Unwrap an `EventLoopFuture` where its type parameter is an `Optional`.
@@ -416,10 +540,11 @@ extension EventLoopFuture {
/// ```
///
/// - Parameters:
/// - orReplace: the value of the returned `EventLoopFuture` when then resolved future's value is `Optional.some()`.
/// - replacement: the value of the returned `EventLoopFuture` when then resolved future's value is `Optional.some()`.
/// - Returns: an new `EventLoopFuture` with new type parameter `NewValue` and the value passed in the `orReplace` parameter.
@inlinable
func unwrap<NewValue>(
@available(*, noasync)
public func unwrap<NewValue>(
orReplace replacement: NewValue
) -> EventLoopFuture<NewValue>.Isolated where Value == NewValue? {
self.map { (value) -> NewValue in
@@ -440,12 +565,13 @@ extension EventLoopFuture {
/// ```
///
/// - Parameters:
/// - orElse: a closure that returns the value of the returned `EventLoopFuture` when then resolved future's value
/// - callback: a closure that returns the value of the returned `EventLoopFuture` when then resolved future's value
/// is `Optional.some()`.
/// - Returns: an new `EventLoopFuture` with new type parameter `NewValue` and with the value returned by the closure
/// passed in the `orElse` parameter.
@inlinable
func unwrap<NewValue>(
@available(*, noasync)
public func unwrap<NewValue>(
orElse callback: @escaping () -> NewValue
) -> EventLoopFuture<NewValue>.Isolated where Value == NewValue? {
self.map { (value) -> NewValue in
@@ -458,34 +584,72 @@ extension EventLoopFuture {
/// Returns the wrapped event loop future.
@inlinable
func nonisolated() -> EventLoopFuture<Value> {
public func nonisolated() -> EventLoopFuture<Value> {
self._wrapped
}
}
/// Assumes the calling context is isolated to the future's event loop.
@usableFromInline
func assumeIsolated() -> Isolated {
/// Returns a variant of this ``EventLoopFuture`` with less strict
/// `Sendable` requirements. Can only be called from on the
/// ``EventLoop`` to which this ``EventLoopFuture`` is bound, will crash
/// if that invariant fails to be met.
@inlinable
@available(*, noasync)
public func assumeIsolated() -> Isolated {
self.eventLoop.preconditionInEventLoop()
return Isolated(_wrapped: self)
}
/// Returns a variant of this ``EventLoopFuture`` with less strict
/// `Sendable` requirements. Can only be called from on the
/// ``EventLoop`` to which this ``EventLoopFuture`` is bound, will crash
/// if that invariant fails to be met in debug builds.
///
/// This is an unsafe version of ``EventLoopFuture/assumeIsolated()`` which
/// omits the runtime check in release builds.
@inlinable
@available(*, noasync)
public func assumeIsolatedUnsafeUnchecked() -> Isolated {
self.eventLoop.assertInEventLoop()
return Isolated(_wrapped: self)
}
}
@available(*, unavailable)
extension EventLoopFuture.Isolated: Sendable {}
extension EventLoopPromise {
/// A struct wrapping an ``EventLoopPromise`` that ensures all calls to any method on this struct
/// are coming from the event loop of the promise.
@usableFromInline
struct Isolated {
///
/// This type is explicitly not `Sendable`. It may only be constructed on an event loop,
/// using ``EventLoopPromise/assumeIsolated()``, and may not subsequently be passed to other isolation
/// domains.
///
/// Using this type relaxes the need to have the promise completion functions accept `Sendable`
/// values, as this type can only be handled on the ``EventLoop``.
///
/// This type does not offer the full suite of completion functions that ``EventLoopPromise``
/// does, as many of those functions do not require `Sendable` values already. It only offers
/// versions for the functions that do require `Sendable` types. If you have an
/// ``EventLoopPromise/Isolated`` but need a regular ``EventLoopPromise``, use
/// ``EventLoopPromise/Isolated/nonisolated()`` to unwrap the value.
public struct Isolated {
@usableFromInline
let _wrapped: EventLoopPromise<Value>
@inlinable
init(_wrapped: EventLoopPromise<Value>) {
self._wrapped = _wrapped
}
/// Deliver a successful result to the associated `EventLoopFuture<Value>` object.
///
/// - Parameters:
/// - value: The successful result of the operation.
@inlinable
func succeed(_ value: Value) {
self._wrapped.futureResult.eventLoop.assertInEventLoop()
@available(*, noasync)
public func succeed(_ value: Value) {
self._wrapped._setValue(value: .success(value))._run()
}
@@ -504,22 +668,43 @@ extension EventLoopPromise {
/// - Parameters:
/// - result: The result which will be used to succeed or fail this promise.
@inlinable
func completeWith(_ result: Result<Value, Error>) {
self._wrapped.futureResult.eventLoop.assertInEventLoop()
@available(*, noasync)
public func completeWith(_ result: Result<Value, Error>) {
self._wrapped._setValue(value: result)._run()
}
/// Returns the wrapped event loop promise.
@inlinable
func nonisolated() -> EventLoopPromise<Value> {
public func nonisolated() -> EventLoopPromise<Value> {
self._wrapped
}
}
/// Assumes the calling context is isolated to the promise's event loop.
@usableFromInline
func assumeIsolated() -> Isolated {
/// Returns a variant of this ``EventLoopPromise`` with less strict
/// `Sendable` requirements. Can only be called from on the
/// ``EventLoop`` to which this ``EventLoopPromise`` is bound, will crash
/// if that invariant fails to be met.
@inlinable
@available(*, noasync)
public func assumeIsolated() -> Isolated {
self.futureResult.eventLoop.preconditionInEventLoop()
return Isolated(_wrapped: self)
}
/// Returns a variant of this ``EventLoopPromise`` with less strict
/// `Sendable` requirements. Can only be called from on the
/// ``EventLoop`` to which this ``EventLoopPromise`` is bound, will crash
/// if that invariant fails to be met.
///
/// This is an unsafe version of ``EventLoopPromise/assumeIsolated()`` which
/// omits the runtime check in release builds and doesn't prevent you using it
/// from using it in async contexts.
@inlinable
public func assumeIsolatedUnsafeUnchecked() -> Isolated {
self.futureResult.eventLoop.assertInEventLoop()
return Isolated(_wrapped: self)
}
}
@available(*, unavailable)
extension EventLoopPromise.Isolated: Sendable {}
+21 -6
View File
@@ -26,9 +26,9 @@ import Dispatch
/// In particular, note that _run() here continues to obtain and execute lists of callbacks until it completes.
/// This eliminates recursion when processing `flatMap()` chains.
@usableFromInline
internal struct CallbackList: Sendable {
internal struct CallbackList {
@usableFromInline
internal typealias Element = @Sendable () -> CallbackList
internal typealias Element = () -> CallbackList
@usableFromInline
internal var firstCallback: Optional<Element>
@usableFromInline
@@ -115,6 +115,9 @@ internal struct CallbackList: Sendable {
}
}
@available(*, unavailable)
extension CallbackList: Sendable {}
/// Internal error for operations that return results that were not replaced
@usableFromInline
internal struct OperationPlaceholderError: Error {
@@ -163,7 +166,12 @@ public struct EventLoopPromise<Value> {
internal static func makeUnleakablePromise(eventLoop: EventLoop, line: UInt = #line) -> EventLoopPromise<Value> {
EventLoopPromise<Value>(
eventLoop: eventLoop,
file: "BUG in SwiftNIO (please report), unleakable promise leaked.",
file: """
EventLoopGroup shut down with unfulfilled promises remaining. \
This suggests that the EventLoopGroup was shut down with unfinished work outstanding which is \
illegal. Either switch to using the singleton EventLoopGroups or fix the issue by only shutting down \
the EventLoopGroups when all the work associated with them has finished.
""",
line: line
)
}
@@ -774,7 +782,7 @@ extension EventLoopFuture {
/// Add a callback. If there's already a value, invoke it and return the resulting list of new callback functions.
@inlinable
internal func _addCallback(_ callback: @escaping @Sendable () -> CallbackList) -> CallbackList {
internal func _addCallback(_ callback: @escaping () -> CallbackList) -> CallbackList {
self.eventLoop.assertInEventLoop()
if self._value == nil {
self._callbacks.append(callback)
@@ -795,14 +803,21 @@ extension EventLoopFuture {
@inlinable
internal func _internalWhenComplete(_ callback: @escaping @Sendable () -> CallbackList) {
if self.eventLoop.inEventLoop {
self._addCallback(callback)._run()
self._whenCompleteIsolated(callback)
} else {
self.eventLoop.execute {
self._addCallback(callback)._run()
self._whenCompleteIsolated(callback)
}
}
}
/// Add a callback. If there's already a value, run as much of the chain as we can.
@inlinable
internal func _whenCompleteIsolated(_ callback: @escaping () -> CallbackList) {
self.eventLoop.assertInEventLoop()
self._addCallback(callback)._run()
}
/// Adds an observer callback to this `EventLoopFuture` that is called when the
/// `EventLoopFuture` has a success result.
///
-2
View File
@@ -373,7 +373,6 @@ extension NIOFileHandle {
use NIOFileSystem as a replacement API.
"""
)
@available(*, noasync, message: "This method may block the calling thread")
public convenience init(
path: String,
mode: Mode = .read,
@@ -415,7 +414,6 @@ extension NIOFileHandle {
use NIOFileSystem as a replacement API.
"""
)
@available(*, noasync, message: "This method may block the calling thread")
public convenience init(path: String) throws {
try self.init(_deprecatedPath: path)
}
-3
View File
@@ -93,9 +93,6 @@ public struct FileRegion: Sendable {
}
}
@available(*, unavailable)
extension FileRegion: Sendable {}
extension FileRegion {
/// Create a new `FileRegion` forming a complete file.
///
-43
View File
@@ -1,43 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// MARK: Rebasing shims
// FIXME: Duplicated in NIO.
// These methods are shimmed in to NIO until https://github.com/apple/swift/pull/34879 is resolved.
// They address the fact that the current rebasing initializers are surprisingly expensive and do excessive
// checked arithmetic. This expense forces them to often be outlined, reducing the ability to optimise out
// further preconditions and branches.
extension UnsafeRawBufferPointer {
@inlinable
init(fastRebase slice: Slice<UnsafeRawBufferPointer>) {
let base = slice.base.baseAddress?.advanced(by: slice.startIndex)
self.init(start: base, count: slice.endIndex &- slice.startIndex)
}
@inlinable
init(fastRebase slice: Slice<UnsafeMutableRawBufferPointer>) {
let base = slice.base.baseAddress?.advanced(by: slice.startIndex)
self.init(start: base, count: slice.endIndex &- slice.startIndex)
}
}
extension UnsafeMutableRawBufferPointer {
@inlinable
init(fastRebase slice: Slice<UnsafeMutableRawBufferPointer>) {
let base = slice.base.baseAddress?.advanced(by: slice.startIndex)
self.init(start: base, count: slice.endIndex &- slice.startIndex)
}
}
+205 -22
View File
@@ -75,7 +75,8 @@ public protocol SocketOptionProvider: _NIOPreconcurrencySendable {
/// - value: The value to set the socket option to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
func unsafeSetSocketOption<Value>(
@preconcurrency
func unsafeSetSocketOption<Value: Sendable>(
level: SocketOptionLevel,
name: SocketOptionName,
value: Value
@@ -95,7 +96,8 @@ public protocol SocketOptionProvider: _NIOPreconcurrencySendable {
/// - value: The value to set the socket option to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
func unsafeSetSocketOption<Value>(
@preconcurrency
func unsafeSetSocketOption<Value: Sendable>(
level: NIOBSDSocket.OptionLevel,
name: NIOBSDSocket.Option,
value: Value
@@ -114,7 +116,11 @@ public protocol SocketOptionProvider: _NIOPreconcurrencySendable {
/// - name: The name of the socket option, e.g. `SO_REUSEADDR`.
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
func unsafeGetSocketOption<Value>(level: SocketOptionLevel, name: SocketOptionName) -> EventLoopFuture<Value>
@preconcurrency
func unsafeGetSocketOption<Value: Sendable>(
level: SocketOptionLevel,
name: SocketOptionName
) -> EventLoopFuture<Value>
#endif
/// Obtain the value of the socket option for the given level and name.
@@ -129,7 +135,8 @@ public protocol SocketOptionProvider: _NIOPreconcurrencySendable {
/// - name: The name of the socket option, e.g. `SO_REUSEADDR`.
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
func unsafeGetSocketOption<Value>(
@preconcurrency
func unsafeGetSocketOption<Value: Sendable>(
level: NIOBSDSocket.OptionLevel,
name: NIOBSDSocket.Option
) -> EventLoopFuture<Value>
@@ -137,7 +144,7 @@ public protocol SocketOptionProvider: _NIOPreconcurrencySendable {
#if !os(Windows)
extension SocketOptionProvider {
func unsafeSetSocketOption<Value>(
func unsafeSetSocketOption<Value: Sendable>(
level: NIOBSDSocket.OptionLevel,
name: NIOBSDSocket.Option,
value: Value
@@ -149,7 +156,7 @@ extension SocketOptionProvider {
)
}
func unsafeGetSocketOption<Value>(
func unsafeGetSocketOption<Value: Sendable>(
level: NIOBSDSocket.OptionLevel,
name: NIOBSDSocket.Option
) -> EventLoopFuture<Value> {
@@ -175,6 +182,12 @@ public typealias NIOLinger = linger
// around. As a result, if you change one, you should probably change them all.
//
// You are welcome to add more helper methods here, but each helper method you add must be tested.
//
// Please note that to work around a Swift compiler issue regarding lookup of the Sendability of
// libc types across modules, the actual calls to `unsafeSetSocketOption` and `unsafeGetSocketOption`
// _must_ be made inside non-`public` non-`@inlinable` methods. Otherwise we'll produce crashes
// in release mode. NIO's integration tests are a good canary for this: if you call your method
// from an alloc counter test in the integration tests, it'll crash if you messed it up.
extension SocketOptionProvider {
/// Sets the socket option SO_LINGER to `value`.
///
@@ -183,6 +196,176 @@ extension SocketOptionProvider {
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setSoLinger(_ value: linger) -> EventLoopFuture<Void> {
self._setSoLinger(value)
}
/// Gets the value of the socket option SO_LINGER.
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getSoLinger() -> EventLoopFuture<NIOLinger> {
self._getSoLinger()
}
/// Sets the socket option IP_MULTICAST_IF to `value`.
///
/// - Parameters:
/// - value: The value to set IP_MULTICAST_IF to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPMulticastIF(_ value: in_addr) -> EventLoopFuture<Void> {
self._setIPMulticastIF(value)
}
/// Gets the value of the socket option IP_MULTICAST_IF.
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPMulticastIF() -> EventLoopFuture<in_addr> {
self._getIPMulticastIF()
}
/// Sets the socket option IP_MULTICAST_TTL to `value`.
///
/// - Parameters:
/// - value: The value to set IP_MULTICAST_TTL to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPMulticastTTL(_ value: CUnsignedChar) -> EventLoopFuture<Void> {
self._setIPMulticastTTL(value)
}
/// Gets the value of the socket option IP_MULTICAST_TTL.
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPMulticastTTL() -> EventLoopFuture<CUnsignedChar> {
self._getIPMulticastTTL()
}
/// Sets the socket option IP_MULTICAST_LOOP to `value`.
///
/// - Parameters:
/// - value: The value to set IP_MULTICAST_LOOP to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPMulticastLoop(_ value: CUnsignedChar) -> EventLoopFuture<Void> {
self._setIPMulticastLoop(value)
}
/// Gets the value of the socket option IP_MULTICAST_LOOP.
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPMulticastLoop() -> EventLoopFuture<CUnsignedChar> {
self._getIPMulticastLoop()
}
/// Sets the socket option IPV6_MULTICAST_IF to `value`.
///
/// - Parameters:
/// - value: The value to set IPV6_MULTICAST_IF to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPv6MulticastIF(_ value: CUnsignedInt) -> EventLoopFuture<Void> {
self._setIPv6MulticastIF(value)
}
/// Gets the value of the socket option IPV6_MULTICAST_IF.
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPv6MulticastIF() -> EventLoopFuture<CUnsignedInt> {
self._getIPv6MulticastIF()
}
/// Sets the socket option IPV6_MULTICAST_HOPS to `value`.
///
/// - Parameters:
/// - value: The value to set IPV6_MULTICAST_HOPS to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPv6MulticastHops(_ value: CInt) -> EventLoopFuture<Void> {
self._setIPv6MulticastHops(value)
}
/// Gets the value of the socket option IPV6_MULTICAST_HOPS.
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPv6MulticastHops() -> EventLoopFuture<CInt> {
self._getIPv6MulticastHops()
}
/// Sets the socket option IPV6_MULTICAST_LOOP to `value`.
///
/// - Parameters:
/// - value: The value to set IPV6_MULTICAST_LOOP to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPv6MulticastLoop(_ value: CUnsignedInt) -> EventLoopFuture<Void> {
self._setIPv6MulticastLoop(value)
}
/// Gets the value of the socket option IPV6_MULTICAST_LOOP.
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPv6MulticastLoop() -> EventLoopFuture<CUnsignedInt> {
self._getIPv6MulticastLoop()
}
#if os(Linux) || os(FreeBSD) || os(Android)
/// Gets the value of the socket option TCP_INFO.
///
/// This socket option cannot be set.
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getTCPInfo() -> EventLoopFuture<tcp_info> {
self._getTCPInfo()
}
#endif
#if canImport(Darwin)
/// Gets the value of the socket option TCP_CONNECTION_INFO.
///
/// This socket option cannot be set.
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getTCPConnectionInfo() -> EventLoopFuture<tcp_connection_info> {
self._getTCPConnectionInfo()
}
#endif
#if os(Linux)
/// Gets the value of the socket option MPTCP_INFO.
///
/// This socket option cannot be set.
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getMPTCPInfo() -> EventLoopFuture<mptcp_info> {
self._getMPTCPInfo()
}
#endif
// MARK: Non-public non-inlinable actual implementations for the above.
//
// As discussed above, these are needed to work around a compiler issue
// that was present at least up to the 6.0 compiler series. This prevents
// the specialization being emitted in the caller code, which is unfortunate,
// but it also ensures that we avoid the crash. We should remove these when
// they're no longer needed.
/// Sets the socket option SO_LINGER to `value`.
///
/// - Parameters:
/// - value: The value to set SO_LINGER to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
private func _setSoLinger(_ value: linger) -> EventLoopFuture<Void> {
#if os(WASI)
self.eventLoop.makeFailedFuture(SocketOptionProviderError.unsupported)
#else
@@ -194,7 +377,7 @@ extension SocketOptionProvider {
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getSoLinger() -> EventLoopFuture<NIOLinger> {
private func _getSoLinger() -> EventLoopFuture<NIOLinger> {
#if os(WASI)
self.eventLoop.makeFailedFuture(SocketOptionProviderError.unsupported)
#else
@@ -208,7 +391,7 @@ extension SocketOptionProvider {
/// - value: The value to set IP_MULTICAST_IF to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPMulticastIF(_ value: in_addr) -> EventLoopFuture<Void> {
private func _setIPMulticastIF(_ value: in_addr) -> EventLoopFuture<Void> {
self.unsafeSetSocketOption(level: .ip, name: .ip_multicast_if, value: value)
}
@@ -216,7 +399,7 @@ extension SocketOptionProvider {
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPMulticastIF() -> EventLoopFuture<in_addr> {
private func _getIPMulticastIF() -> EventLoopFuture<in_addr> {
self.unsafeGetSocketOption(level: .ip, name: .ip_multicast_if)
}
@@ -226,7 +409,7 @@ extension SocketOptionProvider {
/// - value: The value to set IP_MULTICAST_TTL to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPMulticastTTL(_ value: CUnsignedChar) -> EventLoopFuture<Void> {
private func _setIPMulticastTTL(_ value: CUnsignedChar) -> EventLoopFuture<Void> {
self.unsafeSetSocketOption(level: .ip, name: .ip_multicast_ttl, value: value)
}
@@ -234,7 +417,7 @@ extension SocketOptionProvider {
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPMulticastTTL() -> EventLoopFuture<CUnsignedChar> {
private func _getIPMulticastTTL() -> EventLoopFuture<CUnsignedChar> {
self.unsafeGetSocketOption(level: .ip, name: .ip_multicast_ttl)
}
@@ -244,7 +427,7 @@ extension SocketOptionProvider {
/// - value: The value to set IP_MULTICAST_LOOP to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPMulticastLoop(_ value: CUnsignedChar) -> EventLoopFuture<Void> {
private func _setIPMulticastLoop(_ value: CUnsignedChar) -> EventLoopFuture<Void> {
self.unsafeSetSocketOption(level: .ip, name: .ip_multicast_loop, value: value)
}
@@ -252,7 +435,7 @@ extension SocketOptionProvider {
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPMulticastLoop() -> EventLoopFuture<CUnsignedChar> {
private func _getIPMulticastLoop() -> EventLoopFuture<CUnsignedChar> {
self.unsafeGetSocketOption(level: .ip, name: .ip_multicast_loop)
}
@@ -262,7 +445,7 @@ extension SocketOptionProvider {
/// - value: The value to set IPV6_MULTICAST_IF to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPv6MulticastIF(_ value: CUnsignedInt) -> EventLoopFuture<Void> {
private func _setIPv6MulticastIF(_ value: CUnsignedInt) -> EventLoopFuture<Void> {
self.unsafeSetSocketOption(level: .ipv6, name: .ipv6_multicast_if, value: value)
}
@@ -270,7 +453,7 @@ extension SocketOptionProvider {
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPv6MulticastIF() -> EventLoopFuture<CUnsignedInt> {
private func _getIPv6MulticastIF() -> EventLoopFuture<CUnsignedInt> {
self.unsafeGetSocketOption(level: .ipv6, name: .ipv6_multicast_if)
}
@@ -280,7 +463,7 @@ extension SocketOptionProvider {
/// - value: The value to set IPV6_MULTICAST_HOPS to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPv6MulticastHops(_ value: CInt) -> EventLoopFuture<Void> {
private func _setIPv6MulticastHops(_ value: CInt) -> EventLoopFuture<Void> {
self.unsafeSetSocketOption(level: .ipv6, name: .ipv6_multicast_hops, value: value)
}
@@ -288,7 +471,7 @@ extension SocketOptionProvider {
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPv6MulticastHops() -> EventLoopFuture<CInt> {
private func _getIPv6MulticastHops() -> EventLoopFuture<CInt> {
self.unsafeGetSocketOption(level: .ipv6, name: .ipv6_multicast_hops)
}
@@ -298,7 +481,7 @@ extension SocketOptionProvider {
/// - value: The value to set IPV6_MULTICAST_LOOP to.
/// - Returns: An `EventLoopFuture` that fires when the option has been set,
/// or if an error has occurred.
public func setIPv6MulticastLoop(_ value: CUnsignedInt) -> EventLoopFuture<Void> {
private func _setIPv6MulticastLoop(_ value: CUnsignedInt) -> EventLoopFuture<Void> {
self.unsafeSetSocketOption(level: .ipv6, name: .ipv6_multicast_loop, value: value)
}
@@ -306,7 +489,7 @@ extension SocketOptionProvider {
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getIPv6MulticastLoop() -> EventLoopFuture<CUnsignedInt> {
private func _getIPv6MulticastLoop() -> EventLoopFuture<CUnsignedInt> {
self.unsafeGetSocketOption(level: .ipv6, name: .ipv6_multicast_loop)
}
@@ -317,7 +500,7 @@ extension SocketOptionProvider {
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getTCPInfo() -> EventLoopFuture<tcp_info> {
private func _getTCPInfo() -> EventLoopFuture<tcp_info> {
self.unsafeGetSocketOption(level: .tcp, name: .tcp_info)
}
#endif
@@ -329,7 +512,7 @@ extension SocketOptionProvider {
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getTCPConnectionInfo() -> EventLoopFuture<tcp_connection_info> {
private func _getTCPConnectionInfo() -> EventLoopFuture<tcp_connection_info> {
self.unsafeGetSocketOption(level: .tcp, name: .tcp_connection_info)
}
#endif
@@ -341,7 +524,7 @@ extension SocketOptionProvider {
///
/// - Returns: An `EventLoopFuture` containing the value of the socket option, or
/// any error that occurred while retrieving the socket option.
public func getMPTCPInfo() -> EventLoopFuture<mptcp_info> {
private func _getMPTCPInfo() -> EventLoopFuture<mptcp_info> {
self.unsafeGetSocketOption(level: .mptcp, name: .mptcp_info)
}
#endif
@@ -13,6 +13,7 @@
//===----------------------------------------------------------------------===//
#if !canImport(Darwin) || os(macOS)
import NIOCore
import NIOPosix
struct StrictCrashTests {
@@ -13,6 +13,7 @@
//===----------------------------------------------------------------------===//
#if !canImport(Darwin) || os(macOS)
import NIOCore
import NIOPosix
import Foundation
+3 -1
View File
@@ -58,7 +58,9 @@ let bootstrap = ClientBootstrap(group: group)
// Enable SO_REUSEADDR.
.channelOption(.socketOption(.so_reuseaddr), value: 1)
.channelInitializer { channel in
channel.pipeline.addHandler(EchoHandler())
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(EchoHandler())
}
}
defer {
try! group.syncShutdownGracefully()
+57 -30
View File
@@ -199,24 +199,28 @@ public final class NIOAsyncTestingChannel: Channel {
/// `nil` because ``NIOAsyncTestingChannel``s don't have parents.
public let parent: Channel? = nil
// This is only written once, from a single thread, and never written again, so it's _technically_ thread-safe. Most methods cannot safely
// These two variables are only written once, from a single thread, and never written again, so they're _technically_ thread-safe. Most methods cannot safely
// be used from multiple threads, but `isActive`, `isOpen`, `eventLoop`, and `closeFuture` can all safely be used from any thread. Just.
#if compiler(>=5.10)
@usableFromInline
nonisolated(unsafe) var channelcore: EmbeddedChannelCore!
nonisolated(unsafe) private var _pipeline: ChannelPipeline!
#else
@usableFromInline
var channelcore: EmbeddedChannelCore!
private var _pipeline: ChannelPipeline!
#endif
private struct State {
var isWritable: Bool
var localAddress: SocketAddress?
var remoteAddress: SocketAddress?
}
/// Guards any of the getters/setters that can be accessed from any thread.
private let stateLock: NIOLock = NIOLock()
// Guarded by `stateLock`
private var _isWritable: Bool = true
// Guarded by `stateLock`
private var _localAddress: SocketAddress? = nil
// Guarded by `stateLock`
private var _remoteAddress: SocketAddress? = nil
private var _pipeline: ChannelPipeline!
private let stateLock = NIOLockedValueBox(
State(isWritable: true, localAddress: nil, remoteAddress: nil)
)
/// - see: `Channel._channelCore`
public var _channelCore: ChannelCore {
@@ -231,11 +235,11 @@ public final class NIOAsyncTestingChannel: Channel {
/// - see: `Channel.isWritable`
public var isWritable: Bool {
get {
self.stateLock.withLock { self._isWritable }
self.stateLock.withLockedValue { $0.isWritable }
}
set {
self.stateLock.withLock { () -> Void in
self._isWritable = newValue
self.stateLock.withLockedValue {
$0.isWritable = newValue
}
}
}
@@ -243,11 +247,11 @@ public final class NIOAsyncTestingChannel: Channel {
/// - see: `Channel.localAddress`
public var localAddress: SocketAddress? {
get {
self.stateLock.withLock { self._localAddress }
self.stateLock.withLockedValue { $0.localAddress }
}
set {
self.stateLock.withLock { () -> Void in
self._localAddress = newValue
self.stateLock.withLockedValue {
$0.localAddress = newValue
}
}
}
@@ -255,11 +259,11 @@ public final class NIOAsyncTestingChannel: Channel {
/// - see: `Channel.remoteAddress`
public var remoteAddress: SocketAddress? {
get {
self.stateLock.withLock { self._remoteAddress }
self.stateLock.withLockedValue { $0.remoteAddress }
}
set {
self.stateLock.withLock { () -> Void in
self._remoteAddress = newValue
self.stateLock.withLockedValue {
$0.remoteAddress = newValue
}
}
}
@@ -283,8 +287,11 @@ public final class NIOAsyncTestingChannel: Channel {
/// - Parameters:
/// - handler: The `ChannelHandler` to add to the `ChannelPipeline` before register.
/// - loop: The ``NIOAsyncTestingEventLoop`` to use.
public convenience init(handler: ChannelHandler, loop: NIOAsyncTestingEventLoop = NIOAsyncTestingEventLoop()) async
{
@preconcurrency
public convenience init(
handler: ChannelHandler & Sendable,
loop: NIOAsyncTestingEventLoop = NIOAsyncTestingEventLoop()
) async {
await self.init(handlers: [handler], loop: loop)
}
@@ -295,16 +302,32 @@ public final class NIOAsyncTestingChannel: Channel {
/// - Parameters:
/// - handlers: The `ChannelHandler`s to add to the `ChannelPipeline` before register.
/// - loop: The ``NIOAsyncTestingEventLoop`` to use.
@preconcurrency
public convenience init(
handlers: [ChannelHandler],
handlers: [ChannelHandler & Sendable],
loop: NIOAsyncTestingEventLoop = NIOAsyncTestingEventLoop()
) async {
try! await self.init(loop: loop) { channel in
try channel.pipeline.syncOperations.addHandlers(handlers)
}
}
/// Create a new instance.
///
/// During creation it will automatically also register itself on the ``NIOAsyncTestingEventLoop``.
///
/// - Parameters:
/// - loop: The ``NIOAsyncTestingEventLoop`` to use.
/// - channelInitializer: The initialization closure which will be run on the `EventLoop` before registration. This could be used to add handlers using `syncOperations`.
public convenience init(
loop: NIOAsyncTestingEventLoop = NIOAsyncTestingEventLoop(),
channelInitializer: @escaping @Sendable (NIOAsyncTestingChannel) throws -> Void
) async throws {
self.init(loop: loop)
try! await self._pipeline.addHandlers(handlers)
// This will never throw...
try! await self.register()
try await loop.submit {
try channelInitializer(self)
}.get()
try await self.register()
}
/// Asynchronously closes the ``NIOAsyncTestingChannel``.
@@ -671,3 +694,7 @@ extension NIOAsyncTestingChannel.LeftOverState: @unchecked Sendable {}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension NIOAsyncTestingChannel.BufferState: @unchecked Sendable {}
#endif
// Synchronous options are never Sendable.
@available(*, unavailable)
extension NIOAsyncTestingChannel.SynchronousOptions: Sendable {}
+133 -36
View File
@@ -14,7 +14,13 @@
#if canImport(Dispatch)
import Atomics
#if canImport(Darwin)
import Dispatch
#else
@preconcurrency import Dispatch
#endif
import NIOConcurrencyHelpers
import NIOCore
import _NIODataStructures
@@ -63,7 +69,9 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable {
/// The current "time" for this event loop. This is an amount in nanoseconds.
/// As we need to access this from any thread, we store this as an atomic.
private let _now = ManagedAtomic<UInt64>(0)
internal var now: NIODeadline {
/// The current "time" for this event loop. This is an amount in nanoseconds.
public var now: NIODeadline {
NIODeadline.uptimeNanoseconds(self._now.load(ordering: .relaxed))
}
@@ -126,7 +134,7 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable {
private func insertTask<ReturnType>(
taskID: UInt64,
deadline: NIODeadline,
promise: EventLoopPromise<ReturnType>,
promise: EventLoopPromise<ReturnType>?,
task: @escaping () throws -> ReturnType
) {
dispatchPrecondition(condition: .onQueue(self.queue))
@@ -137,12 +145,13 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable {
insertOrder: self.nextTaskNumber(),
task: {
do {
promise.succeed(try task())
// UnsafeUnchecked is acceptable because we know we're in the loop here.
promise?.assumeIsolatedUnsafeUnchecked().succeed(try task())
} catch let err {
promise.fail(err)
promise?.fail(err)
}
},
promise.fail
{ promise?.fail($0) }
)
self.scheduledTasks.push(task)
@@ -150,45 +159,36 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable {
/// - see: `EventLoop.scheduleTask(deadline:_:)`
@discardableResult
public func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T> {
let promise: EventLoopPromise<T> = self.makePromise()
let taskID = self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed)
@preconcurrency
public func scheduleTask<T>(
deadline: NIODeadline,
_ task: @escaping @Sendable () throws -> T
) -> Scheduled<T> {
let scheduled: Scheduled<T>
switch self._prepareToSchedule(returnType: T.self) {
case .doSchedule(let taskID, let promise, let returned):
scheduled = returned
switch self.state.load(ordering: .acquiring) {
case .open:
break
case .closing, .closed:
// If the event loop is shut down, or shutting down, immediately cancel the task.
promise.fail(EventLoopError.cancelled)
return Scheduled(promise: promise, cancellationTask: {})
}
let scheduled = Scheduled(
promise: promise,
cancellationTask: {
if self.inEventLoop {
self.removeTask(taskID: taskID)
} else {
self.queue.async {
self.removeTask(taskID: taskID)
}
// Ok, actually do it.
if self.inEventLoop {
self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task)
} else {
self.queue.async {
self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task)
}
}
)
if self.inEventLoop {
self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task)
} else {
self.queue.async {
self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task)
}
case .returnImmediately(let returned):
scheduled = returned
}
return scheduled
}
/// - see: `EventLoop.scheduleTask(in:_:)`
@discardableResult
public func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T> {
@preconcurrency
public func scheduleTask<T>(in: TimeAmount, _ task: @escaping @Sendable () throws -> T) -> Scheduled<T> {
self.scheduleTask(deadline: self.now + `in`, task)
}
@@ -228,7 +228,8 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable {
/// On an `NIOAsyncTestingEventLoop`, `execute` will simply use `scheduleTask` with a deadline of _now_. Unlike with the other operations, this will
/// immediately execute, to eliminate a common class of bugs.
public func execute(_ task: @escaping () -> Void) {
@preconcurrency
public func execute(_ task: @escaping @Sendable () -> Void) {
if self.inEventLoop {
self.scheduleTask(deadline: self.now, task)
} else {
@@ -357,7 +358,8 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable {
}
/// - see: `EventLoop.shutdownGracefully`
public func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) {
@preconcurrency
public func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping @Sendable (Error?) -> Void) {
self.queue.async {
self._shutdownGracefully()
queue.async {
@@ -395,6 +397,62 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable {
dispatchPrecondition(condition: .notOnQueue(self.queue))
}
public func _executeIsolatedUnsafeUnchecked(_ task: @escaping () -> Void) {
// Call directly to insertTask. That function has a thread-safety check, and
// the rest of this method is using thread-safe operations so we don't
// need any extra debug-mode checking here.
let taskID = self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed)
self.insertTask(
taskID: taskID,
deadline: self.now,
promise: nil,
task: task
)
}
public func _submitIsolatedUnsafeUnchecked<T>(_ task: @escaping () throws -> T) -> EventLoopFuture<T> {
// Call directly to insertTask. That function has a thread-safety check, and
// the rest of this method is using thread-safe operations so we don't
// need any extra debug-mode checking here.
let promise = self.makePromise(of: T.self)
let taskID = self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed)
self.insertTask(
taskID: taskID,
deadline: self.now,
promise: promise,
task: task
)
return promise.futureResult
}
@discardableResult
public func _scheduleTaskIsolatedUnsafeUnchecked<T>(
deadline: NIODeadline,
_ task: @escaping () throws -> T
) -> Scheduled<T> {
// Call directly to insertTask. That function has a thread-safety check, and
// the rest of this method is using thread-safe operations so we don't
// need any extra debug-mode checking here.
let scheduled: Scheduled<T>
switch self._prepareToSchedule(returnType: T.self) {
case .doSchedule(let taskID, let promise, let returned):
scheduled = returned
self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task)
case .returnImmediately(let returned):
scheduled = returned
}
return scheduled
}
@discardableResult
public func _scheduleTaskIsolatedUnsafeUnchecked<T>(
in delay: TimeAmount,
_ task: @escaping () throws -> T
) -> Scheduled<T> {
self._scheduleTaskIsolatedUnsafeUnchecked(deadline: self.now + delay, task)
}
public func preconditionInEventLoop(file: StaticString, line: UInt) {
dispatchPrecondition(condition: .onQueue(self.queue))
}
@@ -403,6 +461,45 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable {
dispatchPrecondition(condition: .notOnQueue(self.queue))
}
enum ScheduleCreationResult<TaskReturnType> {
case doSchedule(taskID: UInt64, promise: EventLoopPromise<TaskReturnType>, scheduled: Scheduled<TaskReturnType>)
case returnImmediately(Scheduled<TaskReturnType>)
}
private func _prepareToSchedule<ReturnType>(
returnType: ReturnType.Type = ReturnType.self
) -> ScheduleCreationResult<ReturnType> {
let promise = self.makePromise(of: ReturnType.self)
switch self.state.load(ordering: .acquiring) {
case .open:
break
case .closing, .closed:
// If the event loop is shut down, or shutting down, immediately cancel the task.
promise.fail(EventLoopError.cancelled)
return .returnImmediately(Scheduled(promise: promise, cancellationTask: {}))
}
let taskID = self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed)
let scheduled = Scheduled(
promise: promise,
cancellationTask: {
if self.inEventLoop {
self.removeTask(taskID: taskID)
} else {
self.queue.async {
self.removeTask(taskID: taskID)
}
}
}
)
return .doSchedule(
taskID: taskID,
promise: promise,
scheduled: scheduled
)
}
deinit {
precondition(scheduledTasks.isEmpty, "NIOAsyncTestingEventLoop freed with unexecuted scheduled tasks!")
}
+89 -10
View File
@@ -28,14 +28,30 @@ import Darwin
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Bionic)
import Bionic
#elseif canImport(Android)
import Android
#elseif canImport(WASILibc)
import WASILibc
#else
#error("Unknown C library.")
#endif
private func printError(_ string: StaticString) {
string.withUTF8Buffer { buf in
var buf = buf
while buf.count > 0 {
// 2 is stderr
let rc = write(2, buf.baseAddress, buf.count)
if rc < 0 {
let err = errno
if err == EINTR { continue }
fatalError("Unexpected error writing: \(err)")
}
buf = .init(rebasing: buf.dropFirst(Int(rc)))
}
}
}
internal struct EmbeddedScheduledTask {
let id: UInt64
let task: () -> Void
@@ -94,8 +110,9 @@ extension EmbeddedScheduledTask: Comparable {
/// responsible for ensuring they never call into the `EmbeddedEventLoop` in an
/// unsynchronized fashion.
public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible {
private var _now: NIODeadline = .uptimeNanoseconds(0)
/// The current "time" for this event loop. This is an amount in nanoseconds.
internal var _now: NIODeadline = .uptimeNanoseconds(0)
public var now: NIODeadline { _now }
private enum State { case open, closing, closed }
private var state: State = .open
@@ -113,7 +130,7 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible {
public let description = "EmbeddedEventLoop"
#if canImport(Darwin) || canImport(Glibc) || canImport(Musl) || canImport(Bionic)
#if canImport(Darwin) || canImport(Glibc) || canImport(Musl) || canImport(Android)
private let myThread: pthread_t = pthread_self()
func isCorrectThread() -> Bool {
@@ -145,14 +162,13 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible {
"EmbeddedEventLoop is not thread-safe. You can only use it from the thread you created it on."
)
} else {
fputs(
printError(
"""
ERROR: NIO API misuse: EmbeddedEventLoop is not thread-safe. \
You can only use it from the thread you created it on. This problem will be upgraded to a forced \
crash in future versions of SwiftNIO.
""",
stderr
"""
)
}
return
@@ -184,7 +200,7 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible {
insertOrder: self.nextTaskNumber(),
task: {
do {
promise.succeed(try task())
promise.assumeIsolated().succeed(try task())
} catch let err {
promise.fail(err)
}
@@ -303,6 +319,16 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible {
}
#endif
public func preconditionInEventLoop(file: StaticString, line: UInt) {
self.checkCorrectThread()
// Currently, inEventLoop is always true so this always passes.
}
public func preconditionNotInEventLoop(file: StaticString, line: UInt) {
// As inEventLoop always returns true, this must always preconditon.
preconditionFailure("Always in EmbeddedEventLoop", file: file, line: line)
}
public func _preconditionSafeToWait(file: StaticString, line: UInt) {
self.checkCorrectThread()
// EmbeddedEventLoop always allows a wait, as waiting will essentially always block
@@ -329,6 +355,36 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible {
return
}
public func _executeIsolatedUnsafeUnchecked(_ task: @escaping () -> Void) {
// Because of the way EmbeddedEL works, we can just delegate this directly
// to execute.
self.execute(task)
}
public func _submitIsolatedUnsafeUnchecked<T>(_ task: @escaping () throws -> T) -> EventLoopFuture<T> {
// Because of the way EmbeddedEL works, we can delegate this directly to schedule. Note that I didn't
// say submit: we don't have an override of submit here.
self.scheduleTask(deadline: self._now, task).futureResult
}
@discardableResult
public func _scheduleTaskIsolatedUnsafeUnchecked<T>(
deadline: NIODeadline,
_ task: @escaping () throws -> T
) -> Scheduled<T> {
// Because of the way EmbeddedEL works, we can delegate this directly to schedule.
self.scheduleTask(deadline: deadline, task)
}
@discardableResult
public func _scheduleTaskIsolatedUnsafeUnchecked<T>(
in delay: TimeAmount,
_ task: @escaping () throws -> T
) -> Scheduled<T> {
// Because of the way EmbeddedEL works, we can delegate this directly to schedule.
self.scheduleTask(in: delay, task)
}
deinit {
self.checkCorrectThread()
precondition(scheduledTasks.isEmpty, "Embedded event loop freed with unexecuted scheduled tasks!")
@@ -354,6 +410,11 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible {
}()
}
// EmbeddedEventLoop is extremely _not_ Sendable. However, the EventLoop protocol
// requires it to be. We are doing some runtime enforcement of correct use, but
// ultimately we can't have the compiler validating this usage.
extension EmbeddedEventLoop: @unchecked Sendable {}
@usableFromInline
class EmbeddedChannelCore: ChannelCore {
var isOpen: Bool {
@@ -473,8 +534,11 @@ class EmbeddedChannelCore: ChannelCore {
self.pipeline.syncOperations.fireChannelInactive()
self.pipeline.syncOperations.fireChannelUnregistered()
let loopBoundSelf = NIOLoopBound(self, eventLoop: self.eventLoop)
eventLoop.execute {
// ensure this is executed in a delayed fashion as the users code may still traverse the pipeline
let `self` = loopBoundSelf.value
self.removeHandlers(pipeline: self.pipeline)
self.closePromise.succeed(())
}
@@ -572,6 +636,10 @@ class EmbeddedChannelCore: ChannelCore {
}
}
// ChannelCores are basically never Sendable.
@available(*, unavailable)
extension EmbeddedChannelCore: Sendable {}
/// `EmbeddedChannel` is a `Channel` implementation that does neither any
/// actual IO nor has a proper eventing mechanism. The prime use-case for
/// `EmbeddedChannel` is in unit tests when you want to feed the inbound events
@@ -856,8 +924,8 @@ public final class EmbeddedChannel: Channel {
@inlinable
@discardableResult public func writeInbound<T>(_ data: T) throws -> BufferState {
self.embeddedEventLoop.checkCorrectThread()
self.pipeline.fireChannelRead(data)
self.pipeline.fireChannelReadComplete()
self.pipeline.syncOperations.fireChannelRead(NIOAny(data))
self.pipeline.syncOperations.fireChannelReadComplete()
try self.throwIfErrorCaught()
return self.channelcore.inboundBuffer.isEmpty ? .empty : .full(Array(self.channelcore.inboundBuffer))
}
@@ -1075,5 +1143,16 @@ extension EmbeddedChannel {
}
}
// EmbeddedChannel is extremely _not_ Sendable. However, the Channel protocol
// requires it to be. We are doing some runtime enforcement of correct use, but
// ultimately we can't have the compiler validating this usage.
extension EmbeddedChannel: @unchecked Sendable {}
@available(*, unavailable)
extension EmbeddedChannel.LeftOverState: @unchecked Sendable {}
@available(*, unavailable)
extension EmbeddedChannel.BufferState: @unchecked Sendable {}
@available(*, unavailable)
extension EmbeddedChannel.SynchronousOptions: Sendable {}
-120
View File
@@ -1,120 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2024 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// How to perform copies. Currently only relevant to directory level copies when using
/// ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)``
/// or other overloads that use the default behaviour
public struct CopyStrategy: Hashable, Sendable {
// Avoid exposing to prevent alterations being breaking changes
internal enum Wrapped: Hashable, Sendable {
// platformDefault is reified into one of the concrete options below:
case sequential
// Constraints on this value are enforced only on making `CopyStrategy`,
// the early error check there is desirable over validating on downstream use.
case parallel(_ maxDescriptors: Int)
}
internal let wrapped: Wrapped
private init(_ wrapped: Wrapped) {
self.wrapped = wrapped
}
// These selections are relatively arbitrary but the rationale is as follows:
//
// - Never exceed the default OS limits even if 4 such operations
// were happening at once
// - Sufficient to enable significant speed up from parallelism
// - Not wasting effort by pushing contention to the underlying storage device
// Further we assume an SSD or similar underlying storage tech.
// Users on spinning rust need to account for that themselves anyway
//
// That said, empirical testing for this has not been performed, suggestions welcome
//
// Note: for now we model the directory scan as needing two handles because, during the creation
// of the destination directory we hold the handle for a while copying attributes
// a much more complex internal state machine could allow doing two of these if desired
// This may not result in a faster copy though so things are left simple
internal static func determinePlatformDefault() -> Wrapped {
#if os(macOS) || os(Linux) || os(Windows)
// 4 concurrent file copies/directory scans.
// Avoiding storage system contention is the dominant aspect here.
// Empirical testing on an SSD copying to the same volume with a dense directory of small
// files and sub directories of similar shape totalling 12GB showed improvements in elapsed
// time for (expected) increases in CPU time up to parallel(8), beyond this the increases
// in CPU came with only moderate gains.
// Anyone tuning this is encouraged to cover worst case scenarios.
return .parallel(8)
#elseif os(iOS) || os(tvOS) || os(watchOS) || os(Android)
// Reduced maximum descriptors in embedded world
// This is chosen based on biasing to safety, not empirical testing.
return .parallel(4)
#else
// Safety first, if we have no view on it keep it simple.
return .sequential
#endif
}
}
extension CopyStrategy {
// A copy fundamentally can't work without two descriptors unless you copy
// everything into memory which is infeasible/inefficeint for large copies.
private static let minDescriptorsAllowed = 2
/// Operate in whatever manner is deemed a reasonable default for the platform.
/// This will limit the maximum file descriptors usage based on 'reasonable' defaults.
///
/// Current assumptions (which are subject to change):
/// - Only one copy operation would be performed at once
/// - The copy operation is not intended to be the primary activity on the device
public static let platformDefault: Self = Self(Self.determinePlatformDefault())
/// The copy is done asynchronously, but only one operation will occur at a time.
/// This is the only way to guarantee only one callback to the `shouldCopyItem` will happen at a time
public static let sequential: Self = Self(.sequential)
/// Allow multiple IO operations to run concurrently, including file copies/directory creation and scanning
///
/// - Parameter maxDescriptors: a conservative limit on the number of concurrently open
/// file descriptors involved in the copy. This number must be >= 2 though, if you are using a value that low
/// you should use ``sequential``
///
/// - Throws: ``FileSystemError/Code-swift.struct/invalidArgument`` if `maxDescriptors`
/// is less than 2.
///
public static func parallel(maxDescriptors: Int) throws -> Self {
guard maxDescriptors >= Self.minDescriptorsAllowed else {
// 2 is not quite the same as sequential, you could have two concurrent directory listings for example
// less than 2 and you can't actually do a _copy_ though so it's non-sensical.
throw FileSystemError(
code: .invalidArgument,
message: "Can't do a copy operation without at least 2 file descriptors '\(maxDescriptors)' is illegal",
cause: nil,
location: .here()
)
}
return .init(.parallel(maxDescriptors))
}
}
extension CopyStrategy: CustomStringConvertible {
public var description: String {
switch self.wrapped {
case .sequential:
return "sequential"
case let .parallel(maxDescriptors):
return "parallel with max \(maxDescriptors) descriptors"
}
}
}
+6 -4
View File
@@ -21,7 +21,7 @@ import SystemPackage
/// An `AsyncSequence` of entries in a directory.
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public struct DirectoryEntries: AsyncSequence {
public struct DirectoryEntries: AsyncSequence, Sendable {
public typealias AsyncIterator = DirectoryIterator
public typealias Element = DirectoryEntry
@@ -35,7 +35,8 @@ public struct DirectoryEntries: AsyncSequence {
/// Creates a ``DirectoryEntries`` sequence by wrapping an `AsyncSequence` of _batches_ of
/// directory entries.
public init<S: AsyncSequence>(wrapping sequence: S) where S.Element == Batched.Element {
@preconcurrency
public init<S: AsyncSequence & Sendable>(wrapping sequence: S) where S.Element == Batched.Element {
self.batchedSequence = Batched(wrapping: sequence)
}
@@ -85,7 +86,7 @@ extension DirectoryEntries {
/// The ``Batched`` sequence uses `Array<DirectoryEntry>` as its element type rather
/// than `DirectoryEntry`. This can enable better performance by reducing the number of
/// executor hops at the cost of ease-of-use.
public struct Batched: AsyncSequence {
public struct Batched: AsyncSequence, Sendable {
public typealias AsyncIterator = BatchedIterator
public typealias Element = [DirectoryEntry]
@@ -93,7 +94,8 @@ extension DirectoryEntries {
/// Creates a ``DirectoryEntries/Batched`` sequence by wrapping an `AsyncSequence`
/// of directory entry batches.
public init<S: AsyncSequence>(wrapping sequence: S) where S.Element == Element {
@preconcurrency
public init<S: AsyncSequence & Sendable>(wrapping sequence: S) where S.Element == Element {
self.stream = BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>(wrapping: sequence)
}
+159 -131
View File
@@ -32,12 +32,11 @@ import Bionic
///
/// ### Creating a `FileSystem`
///
/// You should prefer using the `shared` instance of the file system. The
/// `shared` instance uses two threads unless the `SWIFT_FILE_SYSTEM_THREAD_COUNT`
/// environment variable is set.
/// You should prefer using the `shared` instance of the file system. The `shared` instance uses two
/// threads unless the `SWIFT_FILE_SYSTEM_THREAD_COUNT` environment variable is set.
///
/// If you require more granular control you can create a ``FileSystem`` with the required number
/// of threads by calling ``withFileSystem(numberOfThreads:_:)`` or by using ``init(threadPool:)``.
/// If you require more granular control you can create a ``FileSystem`` with the required number of
/// threads by calling ``withFileSystem(numberOfThreads:_:)`` or by using ``init(threadPool:)``.
///
/// ### Errors
///
@@ -54,8 +53,8 @@ public struct FileSystem: Sendable, FileSystemProtocol {
/// Returns a shared global instance of the ``FileSystem``.
///
/// The file system executes blocking work in a thread pool which defaults to having two
/// threads. This can be modified by `blockingPoolThreadCountSuggestion` or by
/// setting the `NIO_SINGLETON_BLOCKING_POOL_THREAD_COUNT` environment variable.
/// threads. This can be modified by `blockingPoolThreadCountSuggestion` or by setting the
/// `NIO_SINGLETON_BLOCKING_POOL_THREAD_COUNT` environment variable.
public static var shared: FileSystem { globalFileSystem }
private let threadPool: NIOThreadPool
@@ -70,8 +69,8 @@ public struct FileSystem: Sendable, FileSystemProtocol {
/// Creates a new ``FileSystem`` using the provided thread pool.
///
/// - Parameter threadPool: A started thread pool to execute blocking system calls on. The
/// ``FileSystem`` doesn't take ownership of the thread pool and you remain responsible
/// for shutting it down when necessary.
/// ``FileSystem`` doesn't take ownership of the thread pool and you remain responsible for
/// shutting it down when necessary.
public init(threadPool: NIOThreadPool) {
self.init(threadPool: threadPool, ownsThreadPool: false)
}
@@ -217,8 +216,8 @@ public struct FileSystem: Sendable, FileSystemProtocol {
/// Error codes thrown include:
/// - ``FileSystemError/Code-swift.struct/fileAlreadyExists`` if a file or directory already
/// exists .
/// - ``FileSystemError/Code-swift.struct/invalidArgument`` if a component in the `path`
/// prefix does not exist and `createIntermediateDirectories` is `false`.
/// - ``FileSystemError/Code-swift.struct/invalidArgument`` if a component in the `path` prefix
/// does not exist and `createIntermediateDirectories` is `false`.
///
/// #### Implementation details
///
@@ -248,10 +247,10 @@ public struct FileSystem: Sendable, FileSystemProtocol {
/// #### Errors
///
/// Error codes thrown include:
/// - ``FileSystemError/Code-swift.struct/invalidArgument`` if the template doesn't end
/// in at least 3 'X's.
/// - ``FileSystemError/Code-swift.struct/permissionDenied`` if the user doesn't have
/// permission to create a directory at the path specified in the template.
/// - ``FileSystemError/Code-swift.struct/invalidArgument`` if the template doesn't end in at
/// least 3 'X's.
/// - ``FileSystemError/Code-swift.struct/permissionDenied`` if the user doesn't have permission
/// to create a directory at the path specified in the template.
///
/// #### Implementation details
///
@@ -277,9 +276,9 @@ public struct FileSystem: Sendable, FileSystemProtocol {
///
/// - Parameters:
/// - path: The path of the file.
/// - infoAboutSymbolicLink: If the file is a symbolic link and this parameter is `true` then information
/// about the link will be returned, otherwise information about the destination of the
/// symbolic link is returned.
/// - infoAboutSymbolicLink: If the file is a symbolic link and this parameter is `true`,
/// then information about the link will be returned. Otherwise, information about the
/// destination of the symbolic link is returned.
/// - Returns: Information about the file at the given path or `nil` if no file exists.
public func info(
forFileAt path: FilePath,
@@ -299,18 +298,18 @@ public struct FileSystem: Sendable, FileSystemProtocol {
/// - symbolic link, or
/// - directory.
///
/// But `shouldCopyItem` can be used to ignore things outside this supported set.
/// `shouldCopyItem` can be used to ignore objects not part of this set.
///
/// #### Errors
///
/// In addition to the already documented errors these may be thrown
/// - ``FileSystemError/Code-swift.struct/unsupported`` if an item to be copied is not a
/// regular file, symbolic link or directory.
/// - ``FileSystemError/Code-swift.struct/unsupported`` if an item to be copied is not a regular
/// file, symbolic link or directory.
///
/// #### Implementation details
///
/// This function is platform dependent. On Darwin the `copyfile(2)` system call is
/// used and items are cloned where possible. On Linux the `sendfile(2)` system call is used.
/// This function is platform dependent. On Darwin the `copyfile(2)` system call is used and
/// items are cloned where possible. On Linux the `sendfile(2)` system call is used.
public func copyItem(
at sourcePath: FilePath,
to destinationPath: FilePath,
@@ -334,8 +333,8 @@ public struct FileSystem: Sendable, FileSystemProtocol {
)
}
// By doing this before looking at the type we allow callers to decide whether
// unanticipated kinds of entries can be safely ignored without needing changes upstream
// By doing this before looking at the type, we allow callers to decide whether
// unanticipated kinds of entries can be safely ignored without needing changes upstream.
if await shouldCopyItem(.init(path: sourcePath, type: info.type)!, destinationPath) {
switch info.type {
case .regular:
@@ -367,6 +366,8 @@ public struct FileSystem: Sendable, FileSystemProtocol {
}
}
/// See ``FileSystemProtocol/removeItem(at:strategy:recursively:)``
///
/// Deletes the file or directory (and its contents) at `path`.
///
/// Only regular files, symbolic links and directories may be removed. If the file at `path` is
@@ -388,11 +389,14 @@ public struct FileSystem: Sendable, FileSystemProtocol {
///
/// - Parameters:
/// - path: The path to delete.
/// - removalStrategy: Whether to delete files sequentially (one-by-one), or perform a
/// concurrent scan of the tree at `path` and delete files when they are found.
/// - removeItemRecursively: Whether or not to remove items recursively.
/// - Returns: The number of deleted items which may be zero if `path` did not exist.
@discardableResult
public func removeItem(
at path: FilePath,
strategy removalStrategy: RemovalStrategy,
recursively removeItemRecursively: Bool
) async throws -> Int {
// Try to remove the item: we might just get lucky.
@@ -400,7 +404,7 @@ public struct FileSystem: Sendable, FileSystemProtocol {
switch result {
case .success:
// Great; we removed 1 whole item.
// Great; we removed an entire item.
return 1
case .failure(.noSuchFileOrDirectory):
@@ -413,8 +417,8 @@ public struct FileSystem: Sendable, FileSystemProtocol {
code: .notEmpty,
message: """
Can't remove directory at path '\(path)', it isn't empty and \
'removeItemRecursively' is false. Remove items from the directory first \
or set 'removeItemRecursively' to true when calling \
'removeItemRecursively' is false. Remove items from the directory first or \
set 'removeItemRecursively' to true when calling \
'removeItem(at:recursively:)'.
""",
cause: nil,
@@ -422,41 +426,62 @@ public struct FileSystem: Sendable, FileSystemProtocol {
)
}
var (subdirectories, filesRemoved) = try await self.withDirectoryHandle(
atPath: path
) { directory in
var subdirectories = [FilePath]()
var filesRemoved = 0
for try await batch in directory.listContents().batched() {
for entry in batch {
switch entry.type {
case .directory:
subdirectories.append(entry.path)
default:
filesRemoved += try await self.removeOneItem(at: entry.path)
}
}
}
return (subdirectories, filesRemoved)
switch removalStrategy.wrapped {
case .sequential:
return try await self.removeItemSequentially(at: path)
case let .parallel(maxDescriptors):
return try await self.removeConcurrently(at: path, maxDescriptors)
}
for subdirectory in subdirectories {
filesRemoved += try await self.removeItem(at: subdirectory)
}
// The directory should be empty now. Remove ourself.
filesRemoved += try await self.removeOneItem(at: path)
return filesRemoved
case let .failure(errno):
throw FileSystemError.remove(errno: errno, path: path, location: .here())
}
}
@discardableResult
private func removeItemSequentially(
at path: FilePath
) async throws -> Int {
var (subdirectories, filesRemoved) = try await self.withDirectoryHandle(
atPath: path
) { directory in
var subdirectories = [FilePath]()
var filesRemoved = 0
for try await batch in directory.listContents().batched() {
for entry in batch {
switch entry.type {
case .directory:
subdirectories.append(entry.path)
default:
filesRemoved += try await self.removeOneItem(at: entry.path)
}
}
}
return (subdirectories, filesRemoved)
}
for subdirectory in subdirectories {
filesRemoved += try await self.removeItemSequentially(at: subdirectory)
}
// The directory should be empty now. Remove ourself.
filesRemoved += try await self.removeOneItem(at: path)
return filesRemoved
}
private func removeConcurrently(
at path: FilePath,
_ maxDescriptors: Int
) async throws -> Int {
let bucket: TokenBucket = .init(tokens: maxDescriptors)
return try await self.discoverAndRemoveItemsInTree(at: path, bucket)
}
/// Moves the named file or directory to a new location.
///
/// Only regular files, symbolic links and directories may be moved. If the item to be is a
@@ -491,7 +516,7 @@ public struct FileSystem: Sendable, FileSystemProtocol {
case .differentLogicalDevices:
// Fall back to copy and remove.
try await self.copyItem(at: sourcePath, to: destinationPath)
try await self.removeItem(at: sourcePath)
try await self.removeItem(at: sourcePath, strategy: .platformDefault)
}
}
@@ -519,9 +544,9 @@ public struct FileSystem: Sendable, FileSystemProtocol {
withItemAt existingPath: FilePath
) async throws {
do {
try await self.removeItem(at: destinationPath)
try await self.removeItem(at: destinationPath, strategy: .platformDefault)
try await self.moveItem(at: existingPath, to: destinationPath)
try await self.removeItem(at: existingPath)
try await self.removeItem(at: existingPath, strategy: .platformDefault)
} catch let error as FileSystemError {
throw FileSystemError(
message: "Can't replace '\(destinationPath)' with '\(existingPath)'.",
@@ -611,31 +636,35 @@ public struct FileSystem: Sendable, FileSystemProtocol {
///
/// #### Implementation details
///
/// On Darwin this function uses `confstr(3)` and gets the value of `_CS_DARWIN_USER_TEMP_DIR`;
/// the users temporary directory. Typically items are removed after three days if they are not
/// accessed.
///
/// On Linux this returns "/tmp".
/// On all platforms, this function first attempts to read the `TMPDIR` environment variable and returns that path, omitting trailing slashes.
/// If that fails:
/// - On Darwin this function uses `confstr(3)` and gets the value of `_CS_DARWIN_USER_TEMP_DIR`;
/// the users temporary directory. Typically items are removed after three days if they are not
/// accessed.
/// - On Android this returns "/data/local/tmp".
/// - On other platforms this returns "/tmp".
///
/// - Returns: The path to a temporary directory.
public var temporaryDirectory: FilePath {
get async throws {
if let tmpdir = getenv("TMPDIR") {
return FilePath(String(cString: tmpdir))
}
#if canImport(Darwin)
return try await self.threadPool.runIfActive {
try Libc.constr(_CS_DARWIN_USER_TEMP_DIR).map { path in
FilePath(path)
}.mapError { errno in
FileSystemError.confstr(
name: "_CS_DARWIN_USER_TEMP_DIR",
errno: errno,
location: .here()
)
}.get()
let result = Libc.constr(_CS_DARWIN_USER_TEMP_DIR)
switch result {
case .success(let path):
return FilePath(path)
case .failure(_):
return FilePath("/tmp")
}
}
#elseif os(Android)
return "/data/local/tmp"
return FilePath("/data/local/tmp")
#else
return "/tmp"
return FilePath("/tmp")
#endif
}
}
@@ -674,8 +703,8 @@ private let globalFileSystem: FileSystem = {
extension NIOSingletons {
/// Returns a shared global instance of the ``FileSystem``.
///
/// The file system executes blocking work in a thread pool see `blockingPoolThreadCountSuggestion`
/// for the default behaviour and ways to control it.
/// The file system executes blocking work in a thread pool. See
/// `blockingPoolThreadCountSuggestion` for the default behaviour and ways to control it.
public static var fileSystem: FileSystem { globalFileSystem }
}
@@ -737,7 +766,8 @@ extension FileSystem {
}
}
/// Opens `path` for reading and writing and returns ``ReadWriteFileHandle`` or ``FileSystemError``.
/// Opens `path` for reading and writing and returns ``ReadWriteFileHandle`` or
/// ``FileSystemError``.
private func _openFile(
forReadingAndWritingAt path: FilePath,
options: OpenOptions.Write
@@ -777,15 +807,16 @@ extension FileSystem {
withIntermediateDirectories createIntermediateDirectories: Bool,
permissions: FilePermissions
) -> Result<Void, FileSystemError> {
// Logic, assuming we are creating intermediate directories: try creating the directory,
// if it fails with ENOENT (no such file or directory) then drop the last component and
// append it to a buffer. Repeat until the path is empty meaning we cannot create the
// directory, or we succeed in which case we can append build up our original path
// creating directories one at a time.
// We assume that we will be creating intermediate directories:
// - Try creating the directory. If it fails with ENOENT (no such file or directory), then
// drop the last component and append it to a buffer.
// - Repeat until the path is empty. This means we cannot create the directory or we
// succeed, in which case we can build up our original path and create directories one at
// a time.
var droppedComponents: [FilePath.Component] = []
var path = fullPath
// Normalize the path to remove any '..' which may not be necessary.
// Normalize the path to remove any superflous '..'.
path.lexicallyNormalize()
if path.isEmpty {
@@ -857,28 +888,24 @@ extension FileSystem {
}
}
/// Represents an item in a directory that needs copying, or
/// an explicit indication of the end of items.
/// The provision of the ``endOfDir`` case significantly simplifies the parallel code
/// Represents an item in a directory that needs copying, or an explicit indication of the end
/// of items. The provision of the ``endOfDir`` case significantly simplifies the parallel code
enum DirCopyItem: Hashable, Sendable {
case endOfDir
case toCopy(from: DirectoryEntry, to: FilePath)
}
/// Creates the directory ``destinationPath`` based on the directory at ``sourcePath``
/// including any permissions/attributes.
/// It does not copy the contents but does indicate the items directly within ``sourcePath`` which
/// should be copied
/// Creates the directory ``destinationPath`` based on the directory at ``sourcePath`` including
/// any permissions/attributes. It does not copy the contents but indicates the items within
/// ``sourcePath`` which should be copied.
///
/// This is a little cumbersome because it is used by ``copyDirectorySequential`` and
/// ``copyDirectoryParallel``.
/// It is desirable to use the file descriptor for the directory itself for as little time as possible
/// (certainly not across async invocations).
/// The down stream paths in the parallel and sequential paths are very different
/// - Returns:
/// An array of `DirCopyItem` which have passed the ``shouldCopyItem```filter
/// The target file paths will all be in ``destinationPath``
/// The array will always finish with an ``DirCopyItem.endOfDir``
/// This is a little cumbersome, because it is used by ``copyDirectorySequential`` and
/// ``copyDirectoryParallel``. It is desirable to use the directories' file descriptor for as
/// little time as possible, and certainly not across asynchronous invocations. The downstream
/// paths in the parallel and sequential paths are very different
/// - Returns: An array of `DirCopyItem` which have passed the ``shouldCopyItem``` filter. The
/// target file paths will all be in ``destinationPath``. The array will always finish with
/// an ``DirCopyItem.endOfDir``.
private func prepareDirectoryForRecusiveCopy(
from sourcePath: FilePath,
to destinationPath: FilePath,
@@ -917,26 +944,24 @@ extension FileSystem {
}
}
} catch let error as FileSystemError where error.code == .unsupported {
// Not all file systems support extended attributes. Swallow errors which indicate
// that is the case.
// Not all file systems support extended attributes. Swallow errors indicating this.
()
}
#endif
// Build a list of items the caller needs to deal with,
// they then do any further work after closing the current directory
// Build a list of items the caller needs to deal with, then do any further work after
// closing the current directory.
var contentsToCopy = [DirCopyItem]()
for try await batch in dir.listContents().batched() {
for entry in batch {
// Any further work is pointless, we are under no obligation to cleanup
// so exit as fast and cleanly as possible.
// Any further work is pointless. We are under no obligation to cleanup. Exit as
// fast and cleanly as possible.
try Task.checkCancellation()
let entryDestination = destinationPath.appending(entry.name)
if await shouldCopyItem(entry, entryDestination) {
// Assume there's a good chance of everything in the batch
// being included in the common case.
// Let geometric growth go from this point though.
// Assume there's a good chance of everything in the batch being included in
// the common case. Let geometric growth go from this point though.
if contentsToCopy.isEmpty {
// Reserve space for the endOfDir entry too.
contentsToCopy.reserveCapacity(batch.count + 1)
@@ -967,8 +992,8 @@ extension FileSystem {
}
}
/// This could be achieved through quite complicated special casing of the parallel copy.
/// The resulting code is far harder to read and debug though so this is kept as a special case
/// This could be achieved through quite complicated special casing of the parallel copy. The
/// resulting code is far harder to read and debug, so this is kept as a special case.
private func copyDirectorySequential(
from sourcePath: FilePath,
to destinationPath: FilePath,
@@ -981,9 +1006,9 @@ extension FileSystem {
_ destination: FilePath
) async -> Bool
) async throws {
// Strategy: find all needed items to copy/recurse into while the directory is open;
// defer actual copying and recursion until after the source directory has been closed
// to avoid consuming too many file descriptors.
// Strategy: find all needed items to copy/recurse into while the directory is open; defer
// actual copying and recursion until after the source directory has been closed to avoid
// consuming too many file descriptors.
let toCopy = try await self.prepareDirectoryForRecusiveCopy(
from: sourcePath,
to: destinationPath,
@@ -997,9 +1022,9 @@ extension FileSystem {
// Sequential cases doesn't need to worry about this, it uses simple recursion.
continue
case let .toCopy(source, destination):
// Note: The entry type could have changed between finding it and acting on it.
// This is inherent in file systems, just more likely in an async environment
// we just accept those coming through as regular errors.
// Note: The entry type could have changed between finding it and acting on it. This
// is inherent in file systems, just more likely in an asynchronous environment. We
// just accept those coming through as regular errors.
switch source.type {
case .regular:
do {
@@ -1069,12 +1094,14 @@ extension FileSystem {
shouldCopyItem: shouldCopyItem
)
case let .parallel(maxDescriptors):
// Note that maxDescriptors was validated on construction of CopyStrategy.
// See notes on CopyStrategy about assumptions on descriptor use.
// For now we take the worst case peak for every operation, which is 2 descriptors,
// this keeps the downstream limiting code simple
// We do not preclude the use of more granular limiting in future (e.g. a directory
// scan only requires 1), for now we just drop any excess remainder entirely.
// Note that maxDescriptors was validated on construction of CopyStrategy. See notes on
// CopyStrategy about assumptions on descriptor use. For now, we take the worst case
// peak for every operation, which is two file descriptors. This keeps the downstream
// limiting code simple.
//
// We do not preclude the use of more granular limiting in the future (e.g. a directory
// scan requires only a single file descriptor). For now we just drop any excess
// remainder entirely.
let limitValue = maxDescriptors / 2
return try await self.copyDirectoryParallel(
from: sourcePath,
@@ -1086,9 +1113,9 @@ extension FileSystem {
}
}
/// Building block of the parallel directory copy implementation
/// Each invovation of this is allowed to consume two file descriptors,
/// any further work (if any) should be sent to `yield` for future processing
/// Building block of the parallel directory copy implementation. Each invocation of this is
/// allowed to consume two file descriptors. Any further work (if any) should be sent to `yield`
/// for future processing.
func copySelfAndEnqueueChildren(
from: DirectoryEntry,
to: FilePath,
@@ -1344,7 +1371,7 @@ extension FileSystem {
// Check that the destination doesn't exist. 'rename' will remove it otherwise!
switch self._info(forFileAt: destinationPath, infoAboutSymbolicLink: true) {
case .success(.none):
// Doens't exist: continue
// Doesn't exist: continue
()
case .success(.some):
@@ -1375,8 +1402,7 @@ extension FileSystem {
return .success(.moved)
case .failure(.improperLink):
// The two paths are on different logical devices; copy and then remove the
// original.
// The two paths are on different logical devices; copy and then remove the original.
return .success(.differentLogicalDevices)
case let .failure(errno):
@@ -1410,7 +1436,8 @@ extension FileSystem {
let lastComponent = lastComponentPath.string
// Finding the index of the last non-'X' character in `lastComponent.string` and advancing it by one.
// Finding the index of the last non-'X' character in `lastComponent.string` and advancing
// it by one.
let prefix: String
var index = lastComponent.lastIndex(where: { $0 != "X" })
if index != nil {
@@ -1484,7 +1511,8 @@ extension FileSystem {
case let .failure(error):
if let systemCallError = error.cause as? FileSystemError.SystemCallError {
switch systemCallError.errno {
// If the file at the generated path already exists, we generate a new file path.
// If the file at the generated path already exists, we generate a new file
// path.
case .fileExists, .isDirectory:
break
default:
+66 -10
View File
@@ -249,19 +249,23 @@ public protocol FileSystemProtocol: Sendable {
/// at the given path then this function returns zero.
///
/// If the item at the `path` is a directory and `removeItemRecursively` is `true` then the
/// contents of all of its subdirectories will be removed recursively before the directory
/// at `path`. Symbolic links are removed (but their targets are not deleted).
/// contents of all of its subdirectories will be removed recursively before the directory at
/// `path`. Symbolic links are removed (but their targets are not deleted).
///
/// - Parameters:
/// - path: The path to delete.
/// - removeItemRecursively: If the item being removed is a directory, remove it by
/// recursively removing its children. Setting this to `true` is synonymous with
/// calling `rm -r`, setting this false is synonymous to calling `rmdir`. Ignored if
/// - removalStrategy: Whether to delete files sequentially (one-by-one), or perform a
/// concurrent scan of the tree at `path` and delete files when they are found. Ignored if
/// the item being removed isn't a directory.
/// - removeItemRecursively: If the item being removed is a directory, remove it by
/// recursively removing its children. Setting this to `true` is synonymous with calling
/// `rm -r`, setting this false is synonymous to calling `rmdir`. Ignored if the item
/// being removed isn't a directory.
/// - Returns: The number of deleted items which may be zero if `path` did not exist.
@discardableResult
func removeItem(
at path: FilePath,
strategy removalStrategy: RemovalStrategy,
recursively removeItemRecursively: Bool
) async throws -> Int
@@ -588,9 +592,12 @@ extension FileSystemProtocol {
/// The item to be removed must be a regular file, symbolic link or directory. If no file exists
/// at the given path then this function returns zero.
///
/// If the item at the `path` is a directory then the contents of all of its subdirectories
/// will be removed recursively before the directory at `path`. Symbolic links are removed (but
/// their targets are not deleted).
/// If the item at the `path` is a directory then the contents of all of its subdirectories will
/// be removed recursively before the directory at `path`. Symbolic links are removed (but their
/// targets are not deleted).
///
/// The strategy for deletion will be determined automatically depending on the discovered
/// platform.
///
/// - Parameters:
/// - path: The path to delete.
@@ -599,7 +606,56 @@ extension FileSystemProtocol {
public func removeItem(
at path: FilePath
) async throws -> Int {
try await self.removeItem(at: path, recursively: true)
try await self.removeItem(at: path, strategy: .platformDefault, recursively: true)
}
/// Deletes the file or directory (and its contents) at `path`.
///
/// The item to be removed must be a regular file, symbolic link or directory. If no file exists
/// at the given path then this function returns zero.
///
/// If the item at the `path` is a directory then the contents of all of its subdirectories will
/// be removed recursively before the directory at `path`. Symbolic links are removed (but their
/// targets are not deleted).
///
/// The strategy for deletion will be determined automatically depending on the discovered
/// platform.
///
/// - Parameters:
/// - path: The path to delete.
/// - removeItemRecursively: If the item being removed is a directory, remove it by
/// recursively removing its children. Setting this to `true` is synonymous with calling
/// `rm -r`, setting this false is synonymous to calling `rmdir`. Ignored if the item
/// being removed isn't a directory.
/// - Returns: The number of deleted items which may be zero if `path` did not exist.
@discardableResult
public func removeItem(
at path: FilePath,
recursively removeItemRecursively: Bool
) async throws -> Int {
try await self.removeItem(at: path, strategy: .platformDefault, recursively: removeItemRecursively)
}
/// Deletes the file or directory (and its contents) at `path`.
///
/// The item to be removed must be a regular file, symbolic link or directory. If no file exists
/// at the given path then this function returns zero.
///
/// If the item at the `path` is a directory then the contents of all of its subdirectories will
/// be removed recursively before the directory at `path`. Symbolic links are removed (but their
/// targets are not deleted).
///
/// - Parameters:
/// - path: The path to delete.
/// - removalStrategy: Whether to delete files sequentially (one-by-one), or perform a
/// concurrent scan of the tree at `path` and delete files when they are found.
/// - Returns: The number of deleted items which may be zero if `path` did not exist.
@discardableResult
public func removeItem(
at path: FilePath,
strategy removalStrategy: RemovalStrategy
) async throws -> Int {
try await self.removeItem(at: path, strategy: removalStrategy, recursively: true)
}
/// Create a directory at the given path.
@@ -659,7 +715,7 @@ extension FileSystemProtocol {
try await execute(handle, directory)
}
} tearDown: { _ in
try await self.removeItem(at: directory, recursively: true)
try await self.removeItem(at: directory, strategy: .platformDefault, recursively: true)
}
}
}
+184
View File
@@ -0,0 +1,184 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2024 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// How many file descriptors to open when performing I/O operations.
enum IOStrategy: Hashable, Sendable {
// platformDefault is reified into one of the concrete options below:
case sequential
case parallel(_ maxDescriptors: Int)
// These selections are relatively arbitrary but the rationale is as follows:
//
// - Never exceed the default OS limits even if 4 such operations were happening at once.
// - Sufficient to enable significant speed up from parallelism
// - Not wasting effort by pushing contention to the underlying storage device. Further we
// assume an SSD or similar underlying storage tech. Users on spinning rust need to account
// for that themselves anyway.
//
// That said, empirical testing for this has not been performed, suggestions welcome.
//
// Note: The directory scan is modelled after a copy strategy needing two handles: during the
// creation of the destination directory we hold the handle while copying attributes. A much
// more complex internal state machine could allow doing two of these if desired. This may not
// result in a faster copy though so things are left simple.
internal static func determinePlatformDefault() -> Self {
#if os(macOS) || os(Linux) || os(Windows)
// Eight file descriptors allow for four concurrent file copies/directory scans. Avoiding
// storage system contention is of utmost importance.
//
// Testing was performed on an SSD, while copying objects (a dense directory of small files
// and subdirectories of similar shape) to the same volume, totalling 12GB. Results showed
// improvements in elapsed time for (expected) increases in CPU time up to parallel(8).
// Beyond this, the increases in CPU led to only moderate gains.
//
// Anyone tuning this is encouraged to cover worst case scenarios.
return .parallel(8)
#elseif os(iOS) || os(tvOS) || os(watchOS) || os(Android)
// Reduced maximum descriptors in embedded world. This is chosen based on biasing towards
// safety, not empirical testing.
return .parallel(4)
#else
// Safety first. If we do not know what system we run on, we keep it simple.
return .sequential
#endif
}
}
/// How to perform copies. Currently only relevant to directory level copies when using
/// ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` or other
/// overloads that use the default behaviour.
public struct CopyStrategy: Hashable, Sendable {
internal let wrapped: IOStrategy
private init(_ strategy: IOStrategy) {
switch strategy {
case .sequential:
self.wrapped = .sequential
case let .parallel(maxDescriptors):
self.wrapped = .parallel(maxDescriptors)
}
}
// A copy fundamentally can't work without two descriptors unless you copy everything into
// memory which is infeasible/inefficient for large copies.
private static let minDescriptorsAllowed = 2
/// Operate in whatever manner is deemed a reasonable default for the platform. This will limit
/// the maximum file descriptors usage based on reasonable defaults.
///
/// Current assumptions (which are subject to change):
/// - Only one copy operation would be performed at once
/// - The copy operation is not intended to be the primary activity on the device
public static let platformDefault: Self = Self(IOStrategy.determinePlatformDefault())
/// The copy is done asynchronously, but only one operation will occur at a time. This is the
/// only way to guarantee only one callback to the `shouldCopyItem` will happen at a time.
public static let sequential: Self = Self(.sequential)
/// Allow multiple I/O operations to run concurrently, including file copies/directory creation
/// and scanning.
///
/// - Parameter maxDescriptors: a conservative limit on the number of concurrently open file
/// descriptors involved in the copy. This number must be >= 2 though, if you are using a
/// value that low you should use ``sequential``
///
/// - Throws: ``FileSystemError/Code-swift.struct/invalidArgument`` if `maxDescriptors` is less
/// than 2.
///
public static func parallel(maxDescriptors: Int) throws -> Self {
guard maxDescriptors >= Self.minDescriptorsAllowed else {
// 2 is not quite the same as sequential, you could have two concurrent directory
// listings for example less than 2 and you can't actually do a _copy_ though so it's
// non-sensical.
throw FileSystemError(
code: .invalidArgument,
message: "Can't do a copy operation without at least 2 file descriptors '\(maxDescriptors)' is illegal",
cause: nil,
location: .here()
)
}
return .init(.parallel(maxDescriptors))
}
}
extension CopyStrategy: CustomStringConvertible {
public var description: String {
switch self.wrapped {
case .sequential:
return "sequential"
case let .parallel(maxDescriptors):
return "parallel with max \(maxDescriptors) descriptors"
}
}
}
/// How to perform file deletions. Currently only relevant to directory level deletions when using
/// ``FileSystemProtocol/removeItem(at:strategy:recursively:)`` or other overloads that use the
/// default behaviour.
public struct RemovalStrategy: Hashable, Sendable {
internal let wrapped: IOStrategy
private init(_ strategy: IOStrategy) {
switch strategy {
case .sequential:
self.wrapped = .sequential
case let .parallel(maxDescriptors):
self.wrapped = .parallel(maxDescriptors)
}
}
// A deletion requires no file descriptors. We only consume a file descriptor while scanning the
// contents of a directory, so the minimum is 1.
private static let minRequiredDescriptors = 1
/// Operate in whatever manner is deemed a reasonable default for the platform. This will limit
/// the maximum file descriptors usage based on reasonable defaults.
///
/// Current assumptions (which are subject to change):
/// - Only one delete operation would be performed at once
/// - The delete operation is not intended to be the primary activity on the device
public static let platformDefault: Self = Self(IOStrategy.determinePlatformDefault())
/// Traversal of directories and removal of files will be done sequentially without any
/// parallelization.
public static let sequential: Self = Self(.sequential)
/// Allow for one or more directory scans to run at the same time. Removal of files will happen
/// on asynchronous tasks in parallel.
///
/// Setting `maxDescriptors` to 1, will limit the speed of directory discovery. Deletion of
/// files within that directory will run in parallel, but discovery of subdirectories will be
/// limited to one at a time.
public static func parallel(maxDescriptors: Int) throws -> Self {
guard maxDescriptors >= Self.minRequiredDescriptors else {
throw FileSystemError(
code: .invalidArgument,
message:
"Can't do a remove operation without at least one file descriptor '\(maxDescriptors)' is illegal",
cause: nil,
location: .here()
)
}
return .init(.parallel(maxDescriptors))
}
}
extension RemovalStrategy: CustomStringConvertible {
public var description: String {
switch self.wrapped {
case .sequential:
return "sequential"
case let .parallel(maxDescriptors):
return "parallel with max \(maxDescriptors) descriptors"
}
}
}
@@ -16,7 +16,7 @@ import NIOCore
/// Wraps a ``NIOThrowingAsyncSequenceProducer<Element>`` or ``AnyAsyncSequence<Element>``.
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal enum BufferedOrAnyStream<Element, Delegate: NIOAsyncSequenceProducerDelegate> {
internal enum BufferedOrAnyStream<Element: Sendable, Delegate: NIOAsyncSequenceProducerDelegate>: Sendable {
typealias AsyncSequenceProducer = NIOThrowingAsyncSequenceProducer<
Element, Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, Delegate
>
@@ -28,7 +28,7 @@ internal enum BufferedOrAnyStream<Element, Delegate: NIOAsyncSequenceProducerDel
self = .nioThrowingAsyncSequenceProducer(stream)
}
internal init<S: AsyncSequence>(wrapping stream: S) where S.Element == Element {
internal init<S: AsyncSequence & Sendable>(wrapping stream: S) where S.Element == Element {
self = .anyAsyncSequence(AnyAsyncSequence(wrapping: stream))
}
@@ -69,10 +69,10 @@ internal enum BufferedOrAnyStream<Element, Delegate: NIOAsyncSequenceProducerDel
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal struct AnyAsyncSequence<Element>: AsyncSequence {
private let _makeAsyncIterator: () -> AsyncIterator
internal struct AnyAsyncSequence<Element>: AsyncSequence, Sendable {
private let _makeAsyncIterator: @Sendable () -> AsyncIterator
internal init<S: AsyncSequence>(wrapping sequence: S) where S.Element == Element {
internal init<S: AsyncSequence & Sendable>(wrapping sequence: S) where S.Element == Element {
self._makeAsyncIterator = {
AsyncIterator(wrapping: sequence.makeAsyncIterator())
}
@@ -118,7 +118,7 @@ import NIOConcurrencyHelpers
/// }
///
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal struct BufferedStream<Element> {
internal struct BufferedStream<Element: Sendable> {
final class _Backing: Sendable {
let storage: _BackPressuredStorage
@@ -199,7 +199,7 @@ extension BufferedStream: AsyncSequence {
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension BufferedStream: Sendable where Element: Sendable {}
extension BufferedStream: Sendable {}
internal struct _ManagedCriticalState<State>: @unchecked Sendable {
let lock: NIOLockedValueBox<State>
@@ -303,7 +303,7 @@ extension BufferedStream {
/// - Parameter sequence: The elements to write to the asynchronous stream.
/// - Returns: The result that indicates if more elements should be produced at this time.
internal func write<S>(contentsOf sequence: S) throws -> WriteResult
where Element == S.Element, S: Sequence {
where Element == S.Element, S: Sequence, Element: Sendable {
try self._backing.storage.write(contentsOf: sequence)
}
@@ -363,7 +363,7 @@ extension BufferedStream {
internal func write<S>(
contentsOf sequence: S,
onProduceMore: @escaping @Sendable (Result<Void, Error>) -> Void
) where Element == S.Element, S: Sequence {
) where Element == S.Element, S: Sequence, Element: Sendable {
do {
let writeResult = try self.write(contentsOf: sequence)
@@ -407,7 +407,7 @@ extension BufferedStream {
/// - Parameters:
/// - sequence: The elements to write to the asynchronous stream.
internal func write<S>(contentsOf sequence: S) async throws
where Element == S.Element, S: Sequence {
where Element == S.Element, S: Sequence, Element: Sendable {
let writeResult = try { try self.write(contentsOf: sequence) }()
switch writeResult {
@@ -458,7 +458,7 @@ extension BufferedStream {
/// - Parameters:
/// - sequence: The elements to write to the asynchronous stream.
internal func write<S>(contentsOf sequence: S) async throws
where Element == S.Element, S: AsyncSequence {
where Element == S.Element, S: AsyncSequence, Element: Sendable {
for try await element in sequence {
try await self.write(contentsOf: CollectionOfOne(element))
}
@@ -0,0 +1,88 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2024 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import DequeModule
import NIOConcurrencyHelpers
/// Type modeled after a "token bucket" pattern, which is similar to a semaphore, but is built with
/// Swift Concurrency primitives.
///
/// This is an adaptation of the TokenBucket found in Swift Package Manager.
/// Instead of using an ``actor``, we define a class and limit access through
/// ``NIOLock``.
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
final class TokenBucket: @unchecked Sendable {
private var tokens: Int
private var waiters: Deque<CheckedContinuation<Void, Never>>
private let lock: NIOLock
init(tokens: Int) {
precondition(tokens >= 1, "Need at least one token!")
self.tokens = tokens
self.waiters = Deque()
self.lock = NIOLock()
}
/// Executes an `async` closure immediately when a token is available.
/// Only the same number of closures will be executed concurrently as the number
/// of `tokens` passed to ``TokenBucket/init(tokens:)``, all subsequent
/// invocations of `withToken` will suspend until a "free" token is available.
/// - Parameter body: The closure to invoke when a token is available.
/// - Returns: Resulting value returned by `body`.
func withToken<ReturnType>(
_ body: @Sendable () async throws -> ReturnType
) async rethrows -> ReturnType {
await self.getToken()
defer { self.returnToken() }
return try await body()
}
private func getToken() async {
self.lock.lock()
if self.tokens > 0 {
self.tokens -= 1
self.lock.unlock()
return
}
await withCheckedContinuation {
self.waiters.append($0)
self.lock.unlock()
}
}
private func returnToken() {
if let waiter = self.lock.withLock({ () -> CheckedContinuation<Void, Never>? in
if let nextWaiter = self.waiters.popFirst() {
return nextWaiter
}
self.tokens += 1
return nil
}) {
waiter.resume()
}
}
}
@@ -16,16 +16,18 @@ import NIOCore
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension FileSystem {
/// Iterative implementation of a recursive parallel copy of the directory from `sourcePath` to `destinationPath`.
/// Iterative implementation of a recursive parallel copy of the directory from `sourcePath` to
/// `destinationPath`.
///
/// The parallelism is solely at the level of individual items (so files, symbolic links and directories), a larger file
/// is not considered for being 'split' into concurrent reads or wites.
/// If any symbolic link is encountered then only the link is copied.
/// The copied items will preserve permissions and any extended attributes (if supported by the file system).
/// The parallelism is solely at the level of individual items (files, symbolic links and
/// directories). A larger file is not 'split' into concurrent reads or writes.
///
/// Note: `maxConcurrentOperations` is used as a hard (conservative) limit on the number of open file descriptors at any point.
/// Operations are assume to consume 2 descriptors so maximum open descriptors is `maxConcurrentOperations * 2`
/// If a symbolic link is encountered, then only the link is copied. If supported by the file
/// system, the copied items will preserve permissions and any extended attributes.
///
/// Note: `maxConcurrentOperations` is used as a hard (conservative) limit on the number of open
/// file descriptors at any point. Operations are assumed to consume 2 descriptors, so the
/// maximum open descriptors are `maxConcurrentOperations * 2`
@usableFromInline
func copyDirectoryParallel(
from sourcePath: FilePath,
@@ -40,9 +42,9 @@ extension FileSystem {
_ destination: FilePath
) async -> Bool
) async throws {
// Implemented with NIOAsyncSequenceProducer rather than AsyncStream.
// It is approximately the same speed in the best case but has significantly less variance.
// NIOAsyncSequenceProducer also enforces a multi producer single consumer access pattern.
// Implemented with NIOAsyncSequenceProducer rather than AsyncStream. It is approximately
// the same speed in the best case, but has significantly less variance.
// NIOAsyncSequenceProducer also enforces a multi-producer, single-consumer access pattern.
let copyRequiredQueue = NIOAsyncSequenceProducer.makeSequence(
elementType: DirCopyItem.self,
backPressureStrategy: NoBackPressureStrategy(),
@@ -50,33 +52,35 @@ extension FileSystem {
delegate: DirCopyDelegate()
)
// We ignore the result of yield in all cases because we are not implementing back pressure
// and cancellation is dealt with separately.
// We ignore the result of yield in all cases, because we are not implementing back
// pressure, and cancellation is dealt with separately.
@Sendable func yield(_ contentsOf: [DirCopyItem]) {
_ = copyRequiredQueue.source.yield(contentsOf: contentsOf)
}
// Kick start the procees by enqueuing the root entry,
// the calling function already validated the root needed copying.
// Kick-start the procees by enqueuing the root entry. The calling function already
// validated the root needed copying, so it is safe to force unwrap the value.
_ = copyRequiredQueue.source.yield(
.toCopy(from: .init(path: sourcePath, type: .directory)!, to: destinationPath)
)
// The processing of the very first item (the root) will increment this,
// after then when it hits zero we've finished.
// The processing of the very first item (the root) will increment this counter. Processing
// will finish when the counter hits zero again.
//
// This does not need to be a ManagedAtomic or similar because:
// - All maintenance of state is done in the withThrowingTaskGroup callback
// - All state maintenance is done within the withThrowingTaskGroup closure
// - All actual file system work is done by tasks created on the `taskGroup`
var activeDirCount = 0
// Despite there being no 'result' of each operation we cannot use a discarding task group
// Despite there being no 'result' for each operation, we cannot use a discarding task group,
// because we use the 'drain results' queue as a concurrency limiting side effect.
try await withThrowingTaskGroup(of: Void.self) { taskGroup in
// Code handling each item to process on the current task
// Process each item in the current task.
//
// Side Effects:
// - Updates activeDirCount and finishes the stream if required.
// - Either adds a single task on `taskGroup` or none.
// - Might add a task to `taskGroup`.
//
// Returns true if it added a task, false otherwise.
func onNextItem(_ item: DirCopyItem) -> Bool {
switch item {
@@ -105,7 +109,7 @@ extension FileSystem {
let iter = copyRequiredQueue.sequence.makeAsyncIterator()
// inProgress counts the number of tasks we have added to the task group
// inProgress counts the number of tasks we have added to the task group.
// Get up to the maximum concurrency first.
// We haven't started monitoring for task completion, so inProgress is 'worst case'.
var inProgress = 0
@@ -116,16 +120,15 @@ extension FileSystem {
inProgress += 1
}
} else {
// Either we completed things before we hit the limit or we were cancelled.
// In the latter case we choose to propagate the cancel clearly.
// This makes testing for the cancellation more reliable.
// Either we completed things before we hit the limit or we were cancelled. In
// the latter case we choose to propagate the cancellation clearly. This makes
// testing for it more reliable.
try Task.checkCancellation()
return
}
}
// Then operate one in (finish) -> one out (start another),
// but only for items that trigger a task.
// One in (finish) -> one out (start another), but only for items that trigger a task.
while let _ = try await taskGroup.next() {
var keepConsuming = true
while keepConsuming {
@@ -133,7 +136,7 @@ extension FileSystem {
if let item = item {
keepConsuming = !onNextItem(item)
} else {
// To accurately propagate the cancellation we must check here too
// We must check here, to accurately propagate the cancellation.
try Task.checkCancellation()
keepConsuming = false
}
@@ -143,7 +146,7 @@ extension FileSystem {
}
}
/// An 'always ask for more' no back-pressure strategy for a ``NIOAsyncSequenceProducer``.
/// An 'always ask for more' no back-pressure strategy for a ``NIOAsyncSequenceProducer``.
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
private struct NoBackPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategy {
mutating func didYield(bufferDepth: Int) -> Bool { true }
@@ -0,0 +1,72 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2024 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension FileSystem {
/// Recursively walk all objects found in `path`. Call ourselves recursively
/// on each directory that we find, as soon as the file descriptor for
/// `path` has been closed; also delete all files that we come across.
func discoverAndRemoveItemsInTree(
at path: FilePath,
_ bucket: TokenBucket
) async throws -> Int {
// Discover current directory and find all files/directories. Free up
// the handle as fast as possible.
let (directoriesToRecurseInto, itemsToDelete) = try await bucket.withToken {
try await self.withDirectoryHandle(atPath: path) { directory in
var subdirectories: [FilePath] = []
var itemsInDirectory: [FilePath] = []
for try await batch in directory.listContents().batched() {
for entry in batch {
switch entry.type {
case .directory:
subdirectories.append(entry.path)
default:
itemsInDirectory.append(entry.path)
}
}
}
return (subdirectories, itemsInDirectory)
}
}
return try await withThrowingTaskGroup(of: Int.self) { group in
// Delete all items we found in the current directory.
for item in itemsToDelete {
group.addTask {
try await self.removeOneItem(at: item)
}
}
// Recurse into all newly found subdirectories.
for directory in directoriesToRecurseInto {
group.addTask {
try await self.discoverAndRemoveItemsInTree(at: directory, bucket)
}
}
// Await task groups to finish and sum all items deleted so far.
var numberOfDeletedItems = try await group.reduce(0, +)
// Remove top level directory.
numberOfDeletedItems += try await self.removeOneItem(at: path)
return numberOfDeletedItems
}
}
}
@@ -400,14 +400,7 @@ public enum Libc {
return valueOrErrno {
pathBytes.withUnsafeMutableBufferPointer { pointer in
// The array must be terminated with a nil.
#if os(Android)
libc_fts_open(
[pointer.baseAddress!, unsafeBitCast(0, to: UnsafeMutablePointer<CInterop.PlatformChar>.self)],
options.rawValue
)
#else
libc_fts_open([pointer.baseAddress, nil], options.rawValue)
#endif
}
}
}
@@ -452,21 +452,12 @@ internal func libc_confstr(
#endif
/// fts(3)
#if os(Android)
internal func libc_fts_open(
_ path: [UnsafeMutablePointer<CInterop.PlatformChar>],
_ options: CInt
) -> UnsafeMutablePointer<CInterop.FTS> {
fts_open(path, options, nil)!
}
#else
internal func libc_fts_open(
_ path: [UnsafeMutablePointer<CInterop.PlatformChar>?],
_ options: CInt
) -> UnsafeMutablePointer<CInterop.FTS> {
fts_open(path, options, nil)
fts_open(path, options, nil)!
}
#endif
/// fts(3)
internal func libc_fts_read(
@@ -0,0 +1,56 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension String {
/// Reads the contents of the file at the path into a String.
///
/// - Parameters:
/// - path: The path of the file to read.
/// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. If the file is larger than this, an error is thrown.
/// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file.
///
/// - Throws: If the file is larger than `maximumSizeAllowed`, an ``FileSystemError/Code-swift.struct/resourceExhausted`` error will be thrown.
public init(
contentsOf path: FilePath,
maximumSizeAllowed: ByteCount,
fileSystem: some FileSystemProtocol
) async throws {
let byteBuffer = try await fileSystem.withFileHandle(forReadingAt: path) { handle in
try await handle.readToEnd(maximumSizeAllowed: maximumSizeAllowed)
}
self = Self(buffer: byteBuffer)
}
/// Reads the contents of the file at the path using ``FileSystem``.
///
/// - Parameters:
/// - path: The path of the file to read.
/// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. If the file is larger than this, an error is thrown.
///
/// - Throws: If the file is larger than `maximumSizeAllowed`, an ``FileSystemError/Code-swift.struct/resourceExhausted`` error will be thrown.
public init(
contentsOf path: FilePath,
maximumSizeAllowed: ByteCount
) async throws {
self = try await Self(
contentsOf: path,
maximumSizeAllowed: maximumSizeAllowed,
fileSystem: .shared
)
}
}
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -126,11 +126,11 @@ extension ByteBuffer {
count: Int(length)
)
} else {
_ = storageRef.retain()
let storage = storageRef.takeUnretainedValue()
return Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: ptr.baseAddress!.advanced(by: index)),
count: Int(length),
deallocator: .custom { _, _ in storageRef.release() }
deallocator: .custom { _, _ in withExtendedLifetime(storage) {} }
)
}
}
@@ -377,15 +377,9 @@ extension ByteBufferAllocator {
}
// MARK: - Conformances
#if compiler(>=6.0)
extension ByteBufferView: @retroactive ContiguousBytes {}
extension ByteBufferView: @retroactive DataProtocol {}
extension ByteBufferView: @retroactive MutableDataProtocol {}
#else
extension ByteBufferView: ContiguousBytes {}
extension ByteBufferView: DataProtocol {}
extension ByteBufferView: MutableDataProtocol {}
#endif
extension ByteBufferView {
public typealias Regions = CollectionOfOne<ByteBufferView>
+9 -4
View File
@@ -12,9 +12,14 @@
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CNIOLLHTTP
import NIOCore
#if compiler(>=6.1)
private import CNIOLLHTTP
#else
@_implementationOnly import CNIOLLHTTP
#endif
extension UnsafeMutablePointer where Pointee == llhttp_t {
/// Returns the `KeepAliveState` for the current message that is parsed.
fileprivate var keepAliveState: KeepAliveState {
@@ -631,7 +636,7 @@ public final class HTTPDecoder<In, Out>: ByteToMessageDecoder, HTTPDecoderDelega
self.url = String(decoding: bytes, as: Unicode.UTF8.self)
}
func didFinishHead(
fileprivate func didFinishHead(
versionMajor: Int,
versionMinor: Int,
isUpgrade: Bool,
@@ -815,7 +820,7 @@ extension HTTPParserError {
/// - Parameter fromCHTTPParserErrno: The error from the underlying library.
/// - Returns: The corresponding `HTTPParserError`, or `nil` if there is no
/// corresponding error.
static func httpError(fromCHTTPParserErrno: llhttp_errno_t) -> HTTPParserError? {
fileprivate static func httpError(fromCHTTPParserErrno: llhttp_errno_t) -> HTTPParserError? {
switch fromCHTTPParserErrno {
case HPE_INTERNAL:
return .invalidInternalState
@@ -874,7 +879,7 @@ extension HTTPMethod {
///
/// - Parameter httpParserMethod: The method returned by `http_parser`.
/// - Returns: The corresponding `HTTPMethod`.
static func from(httpParserMethod: llhttp_method) -> HTTPMethod {
fileprivate static func from(httpParserMethod: llhttp_method) -> HTTPMethod {
switch httpParserMethod {
case HTTP_DELETE:
return .DELETE
+261 -18
View File
@@ -84,9 +84,10 @@ extension ChannelPipeline {
let future: EventLoopFuture<Void>
if self.eventLoop.inEventLoop {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
let result = Result<Void, Error> {
try self.syncOperations.addHTTPClientHandlers(
position: position,
position: syncPosition,
leftOverBytesStrategy: leftOverBytesStrategy,
withClientUpgrade: upgrade
)
@@ -94,8 +95,9 @@ extension ChannelPipeline {
future = self.eventLoop.makeCompletedFuture(result)
} else {
future = self.eventLoop.submit {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self.syncOperations.addHTTPClientHandlers(
position: position,
position: syncPosition,
leftOverBytesStrategy: leftOverBytesStrategy,
withClientUpgrade: upgrade
)
@@ -127,9 +129,10 @@ extension ChannelPipeline {
let future: EventLoopFuture<Void>
if self.eventLoop.inEventLoop {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
let result = Result<Void, Error> {
try self.syncOperations.addHTTPClientHandlers(
position: position,
position: syncPosition,
leftOverBytesStrategy: leftOverBytesStrategy,
enableOutboundHeaderValidation: enableOutboundHeaderValidation,
withClientUpgrade: upgrade
@@ -138,8 +141,9 @@ extension ChannelPipeline {
future = self.eventLoop.makeCompletedFuture(result)
} else {
future = self.eventLoop.submit {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self.syncOperations.addHTTPClientHandlers(
position: position,
position: syncPosition,
leftOverBytesStrategy: leftOverBytesStrategy,
enableOutboundHeaderValidation: enableOutboundHeaderValidation,
withClientUpgrade: upgrade
@@ -174,9 +178,10 @@ extension ChannelPipeline {
let future: EventLoopFuture<Void>
if self.eventLoop.inEventLoop {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
let result = Result<Void, Error> {
try self.syncOperations.addHTTPClientHandlers(
position: position,
position: syncPosition,
leftOverBytesStrategy: leftOverBytesStrategy,
enableOutboundHeaderValidation: enableOutboundHeaderValidation,
encoderConfiguration: encoderConfiguration,
@@ -186,8 +191,9 @@ extension ChannelPipeline {
future = self.eventLoop.makeCompletedFuture(result)
} else {
future = self.eventLoop.submit {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self.syncOperations.addHTTPClientHandlers(
position: position,
position: syncPosition,
leftOverBytesStrategy: leftOverBytesStrategy,
enableOutboundHeaderValidation: enableOutboundHeaderValidation,
encoderConfiguration: encoderConfiguration,
@@ -343,9 +349,10 @@ extension ChannelPipeline {
let future: EventLoopFuture<Void>
if self.eventLoop.inEventLoop {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
let result = Result<Void, Error> {
try self.syncOperations.configureHTTPServerPipeline(
position: position,
position: syncPosition,
withPipeliningAssistance: pipelining,
withServerUpgrade: upgrade,
withErrorHandling: errorHandling,
@@ -356,8 +363,9 @@ extension ChannelPipeline {
future = self.eventLoop.makeCompletedFuture(result)
} else {
future = self.eventLoop.submit {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self.syncOperations.configureHTTPServerPipeline(
position: position,
position: syncPosition,
withPipeliningAssistance: pipelining,
withServerUpgrade: upgrade,
withErrorHandling: errorHandling,
@@ -384,14 +392,41 @@ extension ChannelPipeline.SynchronousOperations {
/// the upgrade completion handler. See the documentation on `HTTPClientUpgradeHandler`
/// for more details.
/// - Throws: If the pipeline could not be configured.
public func addHTTPClientHandlers(
position: ChannelPipeline.SynchronousOperations.Position = .last,
leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes,
withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil
) throws {
try self._addHTTPClientHandlers(
position: position,
leftOverBytesStrategy: leftOverBytesStrategy,
withClientUpgrade: upgrade
)
}
/// Configure a `ChannelPipeline` for use as a HTTP client with a client upgrader configuration.
///
/// - important: This **must** be called on the Channel's event loop.
/// - Parameters:
/// - position: The position in the `ChannelPipeline` where to add the HTTP client handlers. Defaults to `.last`.
/// - leftOverBytesStrategy: The strategy to use when dealing with leftover bytes after removing the `HTTPDecoder`
/// from the pipeline.
/// - upgrade: Add a `HTTPClientUpgradeHandler` to the pipeline, configured for
/// HTTP upgrade. Should be a tuple of an array of `HTTPClientProtocolUpgrader` and
/// the upgrade completion handler. See the documentation on `HTTPClientUpgradeHandler`
/// for more details.
/// - Throws: If the pipeline could not be configured.
@available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead")
@_disfavoredOverload
@preconcurrency
public func addHTTPClientHandlers(
position: ChannelPipeline.Position = .last,
leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes,
withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil
) throws {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self._addHTTPClientHandlers(
position: position,
position: syncPosition,
leftOverBytesStrategy: leftOverBytesStrategy,
withClientUpgrade: upgrade
)
@@ -411,7 +446,7 @@ extension ChannelPipeline.SynchronousOperations {
/// for more details.
/// - Throws: If the pipeline could not be configured.
public func addHTTPClientHandlers(
position: ChannelPipeline.Position = .last,
position: ChannelPipeline.SynchronousOperations.Position = .last,
leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes,
enableOutboundHeaderValidation: Bool = true,
withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil
@@ -424,6 +459,36 @@ extension ChannelPipeline.SynchronousOperations {
)
}
/// Configure a `ChannelPipeline` for use as a HTTP client.
///
/// - important: This **must** be called on the Channel's event loop.
/// - Parameters:
/// - position: The position in the `ChannelPipeline` where to add the HTTP client handlers. Defaults to `.last`.
/// - leftOverBytesStrategy: The strategy to use when dealing with leftover bytes after removing the `HTTPDecoder`
/// from the pipeline.
/// - enableOutboundHeaderValidation: Whether or not request header validation is enforced.
/// - upgrade: Add a ``NIOHTTPClientUpgradeHandler`` to the pipeline, configured for
/// HTTP upgrade. Should be a tuple of an array of ``NIOHTTPClientProtocolUpgrader`` and
/// the upgrade completion handler. See the documentation on ``NIOHTTPClientUpgradeHandler``
/// for more details.
/// - Throws: If the pipeline could not be configured.
@available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead")
@_disfavoredOverload
public func addHTTPClientHandlers(
position: ChannelPipeline.Position = .last,
leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes,
enableOutboundHeaderValidation: Bool = true,
withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil
) throws {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self._addHTTPClientHandlers(
position: syncPosition,
leftOverBytesStrategy: leftOverBytesStrategy,
enableOutboundHeaderValidation: enableOutboundHeaderValidation,
withClientUpgrade: upgrade
)
}
/// Configure a `ChannelPipeline` for use as a HTTP client.
///
/// - important: This **must** be called on the Channel's event loop.
@@ -439,7 +504,7 @@ extension ChannelPipeline.SynchronousOperations {
/// for more details.
/// - Throws: If the pipeline could not be configured.
public func addHTTPClientHandlers(
position: ChannelPipeline.Position = .last,
position: ChannelPipeline.SynchronousOperations.Position = .last,
leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes,
enableOutboundHeaderValidation: Bool = true,
encoderConfiguration: HTTPRequestEncoder.Configuration = .init(),
@@ -454,12 +519,45 @@ extension ChannelPipeline.SynchronousOperations {
)
}
private func _addHTTPClientHandlers(
/// Configure a `ChannelPipeline` for use as a HTTP client.
///
/// - important: This **must** be called on the Channel's event loop.
/// - Parameters:
/// - position: The position in the `ChannelPipeline` where to add the HTTP client handlers. Defaults to `.last`.
/// - leftOverBytesStrategy: The strategy to use when dealing with leftover bytes after removing the `HTTPDecoder`
/// from the pipeline.
/// - enableOutboundHeaderValidation: Whether or not request header validation is enforced.
/// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``.
/// - upgrade: Add a ``NIOHTTPClientUpgradeHandler`` to the pipeline, configured for
/// HTTP upgrade. Should be a tuple of an array of ``NIOHTTPClientProtocolUpgrader`` and
/// the upgrade completion handler. See the documentation on ``NIOHTTPClientUpgradeHandler``
/// for more details.
/// - Throws: If the pipeline could not be configured.
@available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead")
@_disfavoredOverload
public func addHTTPClientHandlers(
position: ChannelPipeline.Position = .last,
leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes,
enableOutboundHeaderValidation: Bool = true,
encoderConfiguration: HTTPRequestEncoder.Configuration = .init(),
withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil
) throws {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self._addHTTPClientHandlers(
position: syncPosition,
leftOverBytesStrategy: leftOverBytesStrategy,
enableOutboundHeaderValidation: enableOutboundHeaderValidation,
encoderConfiguration: encoderConfiguration,
withClientUpgrade: upgrade
)
}
private func _addHTTPClientHandlers(
position: ChannelPipeline.SynchronousOperations.Position = .last,
leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes,
enableOutboundHeaderValidation: Bool = true,
encoderConfiguration: HTTPRequestEncoder.Configuration = .init(),
withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil
) throws {
// Why two separate functions? With the fast-path (no upgrader, yes header validator) we can promote the Array of handlers
// to the stack and skip an allocation.
@@ -481,7 +579,7 @@ extension ChannelPipeline.SynchronousOperations {
}
private func _addHTTPClientHandlers(
position: ChannelPipeline.Position,
position: ChannelPipeline.SynchronousOperations.Position,
leftOverBytesStrategy: RemoveAfterUpgradeStrategy,
encoderConfiguration: HTTPRequestEncoder.Configuration
) throws {
@@ -496,7 +594,7 @@ extension ChannelPipeline.SynchronousOperations {
}
private func _addHTTPClientHandlersFallback(
position: ChannelPipeline.Position,
position: ChannelPipeline.SynchronousOperations.Position,
leftOverBytesStrategy: RemoveAfterUpgradeStrategy,
enableOutboundHeaderValidation: Bool,
encoderConfiguration: HTTPRequestEncoder.Configuration,
@@ -522,6 +620,47 @@ extension ChannelPipeline.SynchronousOperations {
try self.addHandlers(handlers, position: position)
}
/// Configure a `ChannelPipeline` for use as a HTTP server.
///
/// This function knows how to set up all first-party HTTP channel handlers appropriately
/// for server use. It supports the following features:
///
/// 1. Providing assistance handling clients that pipeline HTTP requests, using the
/// `HTTPServerPipelineHandler`.
/// 2. Supporting HTTP upgrade, using the `HTTPServerUpgradeHandler`.
///
/// This method will likely be extended in future with more support for other first-party
/// features.
///
/// - important: This **must** be called on the Channel's event loop.
/// - Parameters:
/// - position: Where in the pipeline to add the HTTP server handlers, defaults to `.last`.
/// - pipelining: Whether to provide assistance handling HTTP clients that pipeline
/// their requests. Defaults to `true`. If `false`, users will need to handle
/// clients that pipeline themselves.
/// - upgrade: Whether to add a `HTTPServerUpgradeHandler` to the pipeline, configured for
/// HTTP upgrade. Defaults to `nil`, which will not add the handler to the pipeline. If
/// provided should be a tuple of an array of `HTTPServerProtocolUpgrader` and the upgrade
/// completion handler. See the documentation on `HTTPServerUpgradeHandler` for more
/// details.
/// - errorHandling: Whether to provide assistance handling protocol errors (e.g.
/// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`.
/// - Throws: If the pipeline could not be configured.
public func configureHTTPServerPipeline(
position: ChannelPipeline.SynchronousOperations.Position = .last,
withPipeliningAssistance pipelining: Bool = true,
withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil,
withErrorHandling errorHandling: Bool = true
) throws {
try self._configureHTTPServerPipeline(
position: position,
withPipeliningAssistance: pipelining,
withServerUpgrade: upgrade,
withErrorHandling: errorHandling
)
}
/// Configure a `ChannelPipeline` for use as a HTTP server.
///
/// This function knows how to set up all first-party HTTP channel handlers appropriately
@@ -549,14 +688,17 @@ extension ChannelPipeline.SynchronousOperations {
/// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`.
/// - Throws: If the pipeline could not be configured.
@preconcurrency
@available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead")
@_disfavoredOverload
public func configureHTTPServerPipeline(
position: ChannelPipeline.Position = .last,
withPipeliningAssistance pipelining: Bool = true,
withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil,
withErrorHandling errorHandling: Bool = true
) throws {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self._configureHTTPServerPipeline(
position: position,
position: syncPosition,
withPipeliningAssistance: pipelining,
withServerUpgrade: upgrade,
withErrorHandling: errorHandling
@@ -594,7 +736,7 @@ extension ChannelPipeline.SynchronousOperations {
/// spec compliance. Defaults to `true`.
/// - Throws: If the pipeline could not be configured.
public func configureHTTPServerPipeline(
position: ChannelPipeline.Position = .last,
position: ChannelPipeline.SynchronousOperations.Position = .last,
withPipeliningAssistance pipelining: Bool = true,
withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil,
withErrorHandling errorHandling: Bool = true,
@@ -609,6 +751,55 @@ extension ChannelPipeline.SynchronousOperations {
)
}
/// Configure a `ChannelPipeline` for use as a HTTP server.
///
/// This function knows how to set up all first-party HTTP channel handlers appropriately
/// for server use. It supports the following features:
///
/// 1. Providing assistance handling clients that pipeline HTTP requests, using the
/// `HTTPServerPipelineHandler`.
/// 2. Supporting HTTP upgrade, using the `HTTPServerUpgradeHandler`.
/// 3. Providing assistance handling protocol errors.
/// 4. Validating outbound header fields to protect against response splitting attacks.
///
/// This method will likely be extended in future with more support for other first-party
/// features.
///
/// - important: This **must** be called on the Channel's event loop.
/// - Parameters:
/// - position: Where in the pipeline to add the HTTP server handlers, defaults to `.last`.
/// - pipelining: Whether to provide assistance handling HTTP clients that pipeline
/// their requests. Defaults to `true`. If `false`, users will need to handle
/// clients that pipeline themselves.
/// - upgrade: Whether to add a `HTTPServerUpgradeHandler` to the pipeline, configured for
/// HTTP upgrade. Defaults to `nil`, which will not add the handler to the pipeline. If
/// provided should be a tuple of an array of `HTTPServerProtocolUpgrader` and the upgrade
/// completion handler. See the documentation on `HTTPServerUpgradeHandler` for more
/// details.
/// - errorHandling: Whether to provide assistance handling protocol errors (e.g.
/// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`.
/// - headerValidation: Whether to validate outbound request headers to confirm that they meet
/// spec compliance. Defaults to `true`.
/// - Throws: If the pipeline could not be configured.
@available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead")
@_disfavoredOverload
public func configureHTTPServerPipeline(
position: ChannelPipeline.Position = .last,
withPipeliningAssistance pipelining: Bool = true,
withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil,
withErrorHandling errorHandling: Bool = true,
withOutboundHeaderValidation headerValidation: Bool = true
) throws {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self._configureHTTPServerPipeline(
position: syncPosition,
withPipeliningAssistance: pipelining,
withServerUpgrade: upgrade,
withErrorHandling: errorHandling,
withOutboundHeaderValidation: headerValidation
)
}
/// Configure a `ChannelPipeline` for use as a HTTP server.
///
/// This function knows how to set up all first-party HTTP channel handlers appropriately
@@ -641,7 +832,7 @@ extension ChannelPipeline.SynchronousOperations {
/// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``.
/// - Throws: If the pipeline could not be configured.
public func configureHTTPServerPipeline(
position: ChannelPipeline.Position = .last,
position: ChannelPipeline.SynchronousOperations.Position = .last,
withPipeliningAssistance pipelining: Bool = true,
withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil,
withErrorHandling errorHandling: Bool = true,
@@ -658,12 +849,64 @@ extension ChannelPipeline.SynchronousOperations {
)
}
private func _configureHTTPServerPipeline(
/// Configure a `ChannelPipeline` for use as a HTTP server.
///
/// This function knows how to set up all first-party HTTP channel handlers appropriately
/// for server use. It supports the following features:
///
/// 1. Providing assistance handling clients that pipeline HTTP requests, using the
/// `HTTPServerPipelineHandler`.
/// 2. Supporting HTTP upgrade, using the `HTTPServerUpgradeHandler`.
/// 3. Providing assistance handling protocol errors.
/// 4. Validating outbound header fields to protect against response splitting attacks.
///
/// This method will likely be extended in future with more support for other first-party
/// features.
///
/// - important: This **must** be called on the Channel's event loop.
/// - Parameters:
/// - position: Where in the pipeline to add the HTTP server handlers, defaults to `.last`.
/// - pipelining: Whether to provide assistance handling HTTP clients that pipeline
/// their requests. Defaults to `true`. If `false`, users will need to handle
/// clients that pipeline themselves.
/// - upgrade: Whether to add a `HTTPServerUpgradeHandler` to the pipeline, configured for
/// HTTP upgrade. Defaults to `nil`, which will not add the handler to the pipeline. If
/// provided should be a tuple of an array of `HTTPServerProtocolUpgrader` and the upgrade
/// completion handler. See the documentation on `HTTPServerUpgradeHandler` for more
/// details.
/// - errorHandling: Whether to provide assistance handling protocol errors (e.g.
/// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`.
/// - headerValidation: Whether to validate outbound request headers to confirm that they meet
/// spec compliance. Defaults to `true`.
/// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``.
/// - Throws: If the pipeline could not be configured.
@available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead")
@_disfavoredOverload
public func configureHTTPServerPipeline(
position: ChannelPipeline.Position = .last,
withPipeliningAssistance pipelining: Bool = true,
withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil,
withErrorHandling errorHandling: Bool = true,
withOutboundHeaderValidation headerValidation: Bool = true,
withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration
) throws {
let syncPosition = ChannelPipeline.SynchronousOperations.Position(position)
try self._configureHTTPServerPipeline(
position: syncPosition,
withPipeliningAssistance: pipelining,
withServerUpgrade: upgrade,
withErrorHandling: errorHandling,
withOutboundHeaderValidation: headerValidation,
withEncoderConfiguration: encoderConfiguration
)
}
private func _configureHTTPServerPipeline(
position: ChannelPipeline.SynchronousOperations.Position = .last,
withPipeliningAssistance pipelining: Bool = true,
withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil,
withErrorHandling errorHandling: Bool = true,
withOutboundHeaderValidation headerValidation: Bool = true,
withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration = .init()
) throws {
self.eventLoop.assertInEventLoop()
+4 -1
View File
@@ -313,7 +313,10 @@ public struct HTTPHeaders: CustomStringConvertible, ExpressibleByDictionaryLiter
internal var keepAliveState: KeepAliveState = .unknown
public var description: String {
self.headers.description
self.headers.lazy.map {
"\($0.0): \($0.1)"
}
.joined(separator: "; ")
}
internal var names: [String] {
+3 -2
View File
@@ -11,6 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CNIOLinux
import NIOCore
import NIOPosix
@@ -71,8 +72,8 @@ let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
var datagramBootstrap = DatagramBootstrap(group: group)
.channelOption(.socketOption(.so_reuseaddr), value: 1)
.channelInitializer { channel in
channel.pipeline.addHandler(ChatMessageEncoder()).flatMap {
channel.pipeline.addHandler(ChatMessageDecoder())
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandlers(ChatMessageEncoder(), ChatMessageDecoder())
}
}
+11
View File
@@ -276,6 +276,17 @@ measureAndPrint(desc: "http_headers_canonical_form_trimming_whitespace_from_long
return count
}
measureAndPrint(desc: "http_headers_description_100k") {
let headers = HTTPHeaders(Array(repeating: ("String", "String"), count: 100))
for _ in 0..<100_000 {
let str = headers.description
precondition(str.utf8.count > 100)
}
return 0
}
measureAndPrint(desc: "bytebuffer_write_12MB_short_string_literals") {
let bufferSize = 12 * 1024 * 1024
var buffer = ByteBufferAllocator().buffer(capacity: bufferSize)
+3 -3
View File
@@ -32,7 +32,7 @@ protocol _SocketShutdownProtocol {
}
@usableFromInline
internal enum Shutdown: _SocketShutdownProtocol {
internal enum Shutdown: _SocketShutdownProtocol, Sendable {
case RD
case WR
case RDWR
@@ -49,7 +49,7 @@ extension NIOBSDSocket {
extension NIOBSDSocket {
/// Specifies the type of socket.
@usableFromInline
internal struct SocketType: RawRepresentable {
internal struct SocketType: RawRepresentable, Sendable {
public typealias RawValue = CInt
public var rawValue: RawValue
public init(rawValue: RawValue) {
@@ -144,7 +144,7 @@ extension NIOBSDSocket {
/// They aren't necessarily protocols in their own right: for example, ``mptcp``
/// is not. They act to modify the socket type instead: thus, ``mptcp`` acts
/// to modify `SOCK_STREAM` to ask for ``mptcp`` support.
public struct ProtocolSubtype: RawRepresentable, Hashable {
public struct ProtocolSubtype: RawRepresentable, Hashable, Sendable {
public typealias RawValue = CInt
/// The underlying value of the protocol subtype.
+1
View File
@@ -12,6 +12,7 @@
//
//===----------------------------------------------------------------------===//
import CNIOLinux
import NIOConcurrencyHelpers
import NIOCore
@@ -15,7 +15,7 @@ import NIOCore
extension BaseSocketChannel: SocketOptionProvider {
#if !os(Windows)
func unsafeSetSocketOption<Value>(
func unsafeSetSocketOption<Value: Sendable>(
level: SocketOptionLevel,
name: SocketOptionName,
value: Value
@@ -28,7 +28,7 @@ extension BaseSocketChannel: SocketOptionProvider {
}
#endif
func unsafeSetSocketOption<Value>(
func unsafeSetSocketOption<Value: Sendable>(
level: NIOBSDSocket.OptionLevel,
name: NIOBSDSocket.Option,
value: Value
@@ -47,7 +47,10 @@ extension BaseSocketChannel: SocketOptionProvider {
}
#if !os(Windows)
func unsafeGetSocketOption<Value>(level: SocketOptionLevel, name: SocketOptionName) -> EventLoopFuture<Value> {
func unsafeGetSocketOption<Value: Sendable>(
level: SocketOptionLevel,
name: SocketOptionName
) -> EventLoopFuture<Value> {
unsafeGetSocketOption(
level: NIOBSDSocket.OptionLevel(rawValue: CInt(level)),
name: NIOBSDSocket.Option(rawValue: CInt(name))
@@ -55,7 +58,7 @@ extension BaseSocketChannel: SocketOptionProvider {
}
#endif
func unsafeGetSocketOption<Value>(
func unsafeGetSocketOption<Value: Sendable>(
level: NIOBSDSocket.OptionLevel,
name: NIOBSDSocket.Option
) -> EventLoopFuture<Value> {
+2 -2
View File
@@ -223,7 +223,7 @@ private struct SocketChannelLifecycleManager {
/// For this reason, `BaseSocketChannel` exists to provide a common core implementation of
/// the `SelectableChannel` protocol. It uses a number of private functions to provide hooks
/// for subclasses to implement the specific logic to handle their writes and reads.
class BaseSocketChannel<SocketType: BaseSocketProtocol>: SelectableChannel, ChannelCore {
class BaseSocketChannel<SocketType: BaseSocketProtocol>: SelectableChannel, ChannelCore, @unchecked Sendable {
typealias SelectableType = SocketType.SelectableType
struct AddressCache {
@@ -1419,7 +1419,7 @@ extension BaseSocketChannel {
}
/// Execute the given function and synchronously complete the given `EventLoopPromise` (if not `nil`).
func executeAndComplete<Value>(_ promise: EventLoopPromise<Value>?, _ body: () throws -> Value) {
func executeAndComplete<Value: Sendable>(_ promise: EventLoopPromise<Value>?, _ body: () throws -> Value) {
do {
let result = try body()
promise?.succeed(result)
@@ -13,7 +13,7 @@
//===----------------------------------------------------------------------===//
import NIOCore
class BaseStreamSocketChannel<Socket: SocketProtocol>: BaseSocketChannel<Socket> {
class BaseStreamSocketChannel<Socket: SocketProtocol>: BaseSocketChannel<Socket>, @unchecked Sendable {
internal var connectTimeoutScheduled: Optional<Scheduled<Void>>
private var allowRemoteHalfClosure: Bool = false
private var inputShutdown: Bool = false
+250 -68
View File
@@ -11,6 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CNIOLinux
import NIOCore
#if os(Windows)
@@ -385,7 +386,7 @@ public final class ServerBootstrap {
private func bind0(
makeServerChannel: (_ eventLoop: SelectableEventLoop, _ childGroup: EventLoopGroup, _ enableMPTCP: Bool) throws
-> ServerSocketChannel,
_ register: @escaping (EventLoop, ServerSocketChannel) -> EventLoopFuture<Void>
_ register: @escaping @Sendable (EventLoop, ServerSocketChannel) -> EventLoopFuture<Void>
) -> EventLoopFuture<Channel> {
let eventLoop = self.group.next()
let childEventLoopGroup = self.childGroup
@@ -409,15 +410,18 @@ public final class ServerBootstrap {
serverChannelOptions.applyAllChannelOptions(to: serverChannel).flatMap {
serverChannelInit(serverChannel)
}.flatMap {
serverChannel.pipeline.addHandler(
AcceptHandler(
childChannelInitializer: childChannelInit,
childChannelOptions: childChannelOptions
),
name: "AcceptHandler"
)
}.flatMap {
register(eventLoop, serverChannel)
do {
try serverChannel.pipeline.syncOperations.addHandler(
AcceptHandler(
childChannelInitializer: childChannelInit,
childChannelOptions: childChannelOptions
),
name: "AcceptHandler"
)
return register(eventLoop, serverChannel)
} catch {
return eventLoop.makeFailedFuture(error)
}
}.map {
serverChannel as Channel
}.flatMapError { error in
@@ -433,11 +437,11 @@ public final class ServerBootstrap {
public typealias InboundIn = SocketChannel
public typealias InboundOut = SocketChannel
private let childChannelInit: ((Channel) -> EventLoopFuture<Void>)?
private let childChannelInit: (@Sendable (Channel) -> EventLoopFuture<Void>)?
private let childChannelOptions: ChannelOptions.Storage
init(
childChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?,
childChannelInitializer: (@Sendable (Channel) -> EventLoopFuture<Void>)?,
childChannelOptions: ChannelOptions.Storage
) {
self.childChannelInit = childChannelInitializer
@@ -460,10 +464,12 @@ public final class ServerBootstrap {
let ctxEventLoop = context.eventLoop
let childEventLoop = accepted.eventLoop
let childChannelInit = self.childChannelInit ?? { (_: Channel) in childEventLoop.makeSucceededFuture(()) }
let childChannelOptions = self.childChannelOptions
@inline(__always)
@Sendable
func setupChildChannel() -> EventLoopFuture<Void> {
self.childChannelOptions.applyAllChannelOptions(to: accepted).flatMap { () -> EventLoopFuture<Void> in
childChannelOptions.applyAllChannelOptions(to: accepted).flatMap { () -> EventLoopFuture<Void> in
childEventLoop.assertInEventLoop()
return childChannelInit(accepted)
}
@@ -471,20 +477,17 @@ public final class ServerBootstrap {
@inline(__always)
func fireThroughPipeline(_ future: EventLoopFuture<Void>, context: ChannelHandlerContext) {
// Strictly these asserts are redundant with future.assumeIsolated(), but as this code
// has guarantees that can be quite hard to follow we keep them here.
ctxEventLoop.assertInEventLoop()
assert(ctxEventLoop === context.eventLoop)
let loopBoundContext = context.loopBound
future.flatMap { (_) -> EventLoopFuture<Void> in
let context = loopBoundContext.value
ctxEventLoop.assertInEventLoop()
future.assumeIsolated().flatMap { (_) -> EventLoopFuture<Void> in
guard context.channel.isActive else {
return ctxEventLoop.makeFailedFuture(ChannelError._ioOnClosedChannel)
}
context.fireChannelRead(Self.wrapInboundOut(accepted))
return context.eventLoop.makeSucceededFuture(())
}.whenFailure { error in
let context = loopBoundContext.value
ctxEventLoop.assertInEventLoop()
self.closeAndFire(context: context, accepted: accepted, err: error)
}
}
@@ -769,10 +772,9 @@ extension Channel {
// implementation, `epoll` will send us `EPOLLHUP`. To have it run synchronously, we need to invoke the
// `flatMap` on the eventloop that the `register` will succeed on.
self.eventLoop.assertInEventLoop()
return self.register().flatMap {
self.eventLoop.assertInEventLoop()
return body(self)
}
return self.register().assumeIsolated().flatMap {
body(self)
}.nonisolated()
}
}
@@ -819,8 +821,8 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
if let protocolHandlers = self.protocolHandlers {
let channelInitializer = _channelInitializer
return { channel in
channelInitializer(channel).flatMap {
channel.pipeline.addHandlers(protocolHandlers(), position: .first)
channelInitializer(channel).hop(to: channel.eventLoop).flatMapThrowing {
try channel.pipeline.syncOperations.addHandlers(protocolHandlers(), position: .first)
}
}
} else {
@@ -830,7 +832,7 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
@usableFromInline
internal var _channelOptions: ChannelOptions.Storage
private var connectTimeout: TimeAmount = TimeAmount.seconds(10)
private var resolver: Optional<Resolver>
private var resolver: Optional<Resolver & Sendable>
private var bindTarget: Optional<SocketAddress>
private var enableMPTCP: Bool
@@ -931,7 +933,8 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
///
/// - Parameters:
/// - resolver: The resolver that will be used during the connection attempt.
public func resolver(_ resolver: Resolver?) -> Self {
@preconcurrency
public func resolver(_ resolver: (Resolver & Sendable)?) -> Self {
self.resolver = resolver
return self
}
@@ -964,8 +967,6 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
///
/// Using `bind` is not necessary unless you need the local address to be bound to a specific address.
///
/// - Note: Using `bind` will disable Happy Eyeballs on this `Channel`.
///
/// - Parameters:
/// - address: The `SocketAddress` to bind on.
public func bind(to address: SocketAddress) -> ClientBootstrap {
@@ -977,15 +978,29 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
eventLoop: EventLoop,
protocolFamily: NIOBSDSocket.ProtocolFamily
) throws -> SocketChannel {
try SocketChannel(
eventLoop: eventLoop as! SelectableEventLoop,
try Self.makeSocketChannel(
eventLoop: eventLoop,
protocolFamily: protocolFamily,
enableMPTCP: self.enableMPTCP
)
}
static func makeSocketChannel(
eventLoop: EventLoop,
protocolFamily: NIOBSDSocket.ProtocolFamily,
enableMPTCP: Bool
) throws -> SocketChannel {
try SocketChannel(
eventLoop: eventLoop as! SelectableEventLoop,
protocolFamily: protocolFamily,
enableMPTCP: enableMPTCP
)
}
/// Specify the `host` and `port` to connect to for the TCP `Channel` that will be established.
///
/// - Note: Makes use of Happy Eyeballs.
///
/// - Parameters:
/// - host: The host to connect to.
/// - port: The port to connect to.
@@ -999,6 +1014,11 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
aiSocktype: .stream,
aiProtocol: .tcp
)
let enableMPTCP = self.enableMPTCP
let channelInitializer = self.channelInitializer
let channelOptions = self._channelOptions
let bindTarget = self.bindTarget
let connector = HappyEyeballsConnector(
resolver: resolver,
loop: loop,
@@ -1006,18 +1026,28 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
port: port,
connectTimeout: self.connectTimeout
) { eventLoop, protocolFamily in
self.initializeAndRegisterNewChannel(eventLoop: eventLoop, protocolFamily: protocolFamily) {
Self.initializeAndRegisterNewChannel(
eventLoop: eventLoop,
protocolFamily: protocolFamily,
enableMPTCP: enableMPTCP,
channelInitializer: channelInitializer,
channelOptions: channelOptions,
bindTarget: bindTarget
) {
$0.eventLoop.makeSucceededFuture(())
}
}
return connector.resolveAndConnect()
}
private func connect(freshChannel channel: Channel, address: SocketAddress) -> EventLoopFuture<Void> {
private static func connect(
freshChannel channel: Channel,
address: SocketAddress,
connectTimeout: TimeAmount
) -> EventLoopFuture<Void> {
let connectPromise = channel.eventLoop.makePromise(of: Void.self)
channel.connect(to: address, promise: connectPromise)
let cancelTask = channel.eventLoop.scheduleTask(in: self.connectTimeout) {
[connectTimeout = self.connectTimeout] in
let cancelTask = channel.eventLoop.scheduleTask(in: connectTimeout) {
connectPromise.fail(ChannelError.connectTimeout(connectTimeout))
channel.close(promise: nil)
}
@@ -1032,8 +1062,9 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
injectedChannel: SocketChannel,
to address: SocketAddress
) -> EventLoopFuture<Channel> {
self.initializeAndRegisterChannel(injectedChannel) { channel in
self.connect(freshChannel: channel, address: address)
let connectTimeout = self.connectTimeout
return self.initializeAndRegisterChannel(injectedChannel) { channel in
Self.connect(freshChannel: channel, address: address, connectTimeout: connectTimeout)
}
}
@@ -1043,11 +1074,13 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
/// - address: The address to connect to.
/// - Returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected.
public func connect(to address: SocketAddress) -> EventLoopFuture<Channel> {
self.initializeAndRegisterNewChannel(
let connectTimeout = self.connectTimeout
return self.initializeAndRegisterNewChannel(
eventLoop: self.group.next(),
protocolFamily: address.protocol
) { channel in
self.connect(freshChannel: channel, address: address)
Self.connect(freshChannel: channel, address: address, connectTimeout: connectTimeout)
}
}
@@ -1111,6 +1144,8 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
public func withConnectedSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> {
let eventLoop = group.next()
let channelInitializer = self.channelInitializer
let options = self._channelOptions
let channel: SocketChannel
do {
channel = try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop, socket: socket)
@@ -1118,9 +1153,10 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
return eventLoop.makeFailedFuture(error)
}
@Sendable
func setupChannel() -> EventLoopFuture<Channel> {
eventLoop.assertInEventLoop()
return self._channelOptions.applyAllChannelOptions(to: channel).flatMap {
return options.applyAllChannelOptions(to: channel).flatMap {
channelInitializer(channel)
}.flatMap {
eventLoop.assertInEventLoop()
@@ -1145,29 +1181,74 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
private func initializeAndRegisterNewChannel(
eventLoop: EventLoop,
protocolFamily: NIOBSDSocket.ProtocolFamily,
_ body: @escaping (Channel) -> EventLoopFuture<Void>
_ body: @escaping @Sendable (Channel) -> EventLoopFuture<Void>
) -> EventLoopFuture<Channel> {
Self.initializeAndRegisterNewChannel(
eventLoop: eventLoop,
protocolFamily: protocolFamily,
enableMPTCP: self.enableMPTCP,
channelInitializer: self.channelInitializer,
channelOptions: self._channelOptions,
bindTarget: self.bindTarget,
body
)
}
private static func initializeAndRegisterNewChannel(
eventLoop: EventLoop,
protocolFamily: NIOBSDSocket.ProtocolFamily,
enableMPTCP: Bool,
channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<Void>,
channelOptions: ChannelOptions.Storage,
bindTarget: SocketAddress?,
_ body: @escaping @Sendable (Channel) -> EventLoopFuture<Void>
) -> EventLoopFuture<Channel> {
let channel: SocketChannel
do {
channel = try self.makeSocketChannel(eventLoop: eventLoop, protocolFamily: protocolFamily)
channel = try Self.makeSocketChannel(
eventLoop: eventLoop,
protocolFamily: protocolFamily,
enableMPTCP: enableMPTCP
)
} catch {
return eventLoop.makeFailedFuture(error)
}
return self.initializeAndRegisterChannel(channel, body)
return Self.initializeAndRegisterChannel(
channel,
channelInitializer: channelInitializer,
channelOptions: channelOptions,
bindTarget: bindTarget,
body
)
}
private func initializeAndRegisterChannel(
_ channel: SocketChannel,
_ body: @escaping (Channel) -> EventLoopFuture<Void>
_ body: @escaping @Sendable (Channel) -> EventLoopFuture<Void>
) -> EventLoopFuture<Channel> {
Self.initializeAndRegisterChannel(
channel,
channelInitializer: self.channelInitializer,
channelOptions: self._channelOptions,
bindTarget: self.bindTarget,
body
)
}
private static func initializeAndRegisterChannel(
_ channel: SocketChannel,
channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<Void>,
channelOptions: ChannelOptions.Storage,
bindTarget: SocketAddress?,
_ body: @escaping @Sendable (Channel) -> EventLoopFuture<Void>
) -> EventLoopFuture<Channel> {
let channelInitializer = self.channelInitializer
let channelOptions = self._channelOptions
let eventLoop = channel.eventLoop
@inline(__always)
@Sendable
func setupChannel() -> EventLoopFuture<Channel> {
eventLoop.assertInEventLoop()
return channelOptions.applyAllChannelOptions(to: channel).flatMap { [bindTarget = self.bindTarget] in
return channelOptions.applyAllChannelOptions(to: channel).flatMap {
if let bindTarget = bindTarget {
return channel.bind(to: bindTarget).flatMap {
channelInitializer(channel)
@@ -1238,6 +1319,7 @@ extension ClientBootstrap {
channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<Output>
) async throws -> Output {
let eventLoop = self.group.next()
let connectTimeout = self.connectTimeout
return try await self.initializeAndRegisterNewChannel(
eventLoop: eventLoop,
protocolFamily: address.protocol,
@@ -1246,7 +1328,7 @@ extension ClientBootstrap {
eventLoop.makeSucceededFuture(output)
},
{ channel in
self.connect(freshChannel: channel, address: address)
Self.connect(freshChannel: channel, address: address, connectTimeout: connectTimeout)
}
).get().1
}
@@ -1330,7 +1412,7 @@ extension ClientBootstrap {
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
func connect<ChannelInitializerResult, PostRegistrationTransformationResult>(
func connect<ChannelInitializerResult: Sendable, PostRegistrationTransformationResult: Sendable>(
host: String,
port: Int,
eventLoop: EventLoop,
@@ -1347,6 +1429,11 @@ extension ClientBootstrap {
aiProtocol: .tcp
)
let enableMPTCP = self.enableMPTCP
let bootstrapChannelInitializer = self.channelInitializer
let channelOptions = self._channelOptions
let bindTarget = self.bindTarget
let connector = HappyEyeballsConnector<PostRegistrationTransformationResult>(
resolver: resolver,
loop: eventLoop,
@@ -1354,9 +1441,13 @@ extension ClientBootstrap {
port: port,
connectTimeout: self.connectTimeout
) { eventLoop, protocolFamily in
self.initializeAndRegisterNewChannel(
Self.initializeAndRegisterNewChannel(
eventLoop: eventLoop,
protocolFamily: protocolFamily,
enableMPTPCP: enableMPTCP,
bootstrapChannelInitializer: bootstrapChannelInitializer,
channelOptions: channelOptions,
bindTarget: bindTarget,
channelInitializer: channelInitializer,
postRegisterTransformation: postRegisterTransformation
) {
@@ -1367,7 +1458,10 @@ extension ClientBootstrap {
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
private func withConnectedSocket<ChannelInitializerResult, PostRegistrationTransformationResult>(
private func withConnectedSocket<
ChannelInitializerResult: Sendable,
PostRegistrationTransformationResult: Sendable
>(
eventLoop: EventLoop,
socket: NIOBSDSocket.Handle,
channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<ChannelInitializerResult>,
@@ -1390,14 +1484,17 @@ extension ClientBootstrap {
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
private func initializeAndRegisterNewChannel<ChannelInitializerResult, PostRegistrationTransformationResult>(
private func initializeAndRegisterNewChannel<
ChannelInitializerResult: Sendable,
PostRegistrationTransformationResult: Sendable
>(
eventLoop: EventLoop,
protocolFamily: NIOBSDSocket.ProtocolFamily,
channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<ChannelInitializerResult>,
postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture<
PostRegistrationTransformationResult
>,
_ body: @escaping (Channel) -> EventLoopFuture<Void>
_ body: @escaping @Sendable (Channel) -> EventLoopFuture<Void>
) -> EventLoopFuture<(Channel, PostRegistrationTransformationResult)> {
let channel: SocketChannel
do {
@@ -1416,7 +1513,50 @@ extension ClientBootstrap {
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
private func initializeAndRegisterChannel<ChannelInitializerResult, PostRegistrationTransformationResult>(
private static func initializeAndRegisterNewChannel<
ChannelInitializerResult: Sendable,
PostRegistrationTransformationResult: Sendable
>(
eventLoop: EventLoop,
protocolFamily: NIOBSDSocket.ProtocolFamily,
enableMPTPCP: Bool,
bootstrapChannelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<Void>,
channelOptions: ChannelOptions.Storage,
bindTarget: SocketAddress?,
channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<ChannelInitializerResult>,
postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture<
PostRegistrationTransformationResult
>,
_ body: @escaping @Sendable (Channel) -> EventLoopFuture<Void>
) -> EventLoopFuture<(Channel, PostRegistrationTransformationResult)> {
let channel: SocketChannel
do {
channel = try Self.makeSocketChannel(
eventLoop: eventLoop,
protocolFamily: protocolFamily,
enableMPTCP: enableMPTPCP
)
} catch {
return eventLoop.makeFailedFuture(error)
}
return Self.initializeAndRegisterChannel(
channel: channel,
bootstrapChannelInitializer: bootstrapChannelInitializer,
channelOptions: channelOptions,
bindTarget: bindTarget,
channelInitializer: channelInitializer,
registration: { channel in
channel.registerAndDoSynchronously(body)
},
postRegisterTransformation: postRegisterTransformation
).map { (channel, $0) }
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
private func initializeAndRegisterChannel<
ChannelInitializerResult: Sendable,
PostRegistrationTransformationResult: Sendable
>(
channel: SocketChannel,
channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<ChannelInitializerResult>,
registration: @escaping @Sendable (SocketChannel) -> EventLoopFuture<Void>,
@@ -1424,13 +1564,39 @@ extension ClientBootstrap {
PostRegistrationTransformationResult
>
) -> EventLoopFuture<PostRegistrationTransformationResult> {
let channelInitializer = { channel in
self.channelInitializer(channel)
Self.initializeAndRegisterChannel(
channel: channel,
bootstrapChannelInitializer: self.channelInitializer,
channelOptions: self._channelOptions,
bindTarget: self.bindTarget,
channelInitializer: channelInitializer,
registration: registration,
postRegisterTransformation: postRegisterTransformation
)
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
private static func initializeAndRegisterChannel<
ChannelInitializerResult: Sendable,
PostRegistrationTransformationResult: Sendable
>(
channel: SocketChannel,
bootstrapChannelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<Void>,
channelOptions: ChannelOptions.Storage,
bindTarget: SocketAddress?,
channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<ChannelInitializerResult>,
registration: @escaping @Sendable (SocketChannel) -> EventLoopFuture<Void>,
postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture<
PostRegistrationTransformationResult
>
) -> EventLoopFuture<PostRegistrationTransformationResult> {
let channelInitializer = { @Sendable channel in
bootstrapChannelInitializer(channel).hop(to: channel.eventLoop)
.assumeIsolated()
.flatMap { channelInitializer(channel) }
.nonisolated()
}
let channelOptions = self._channelOptions
let eventLoop = channel.eventLoop
let bindTarget = self.bindTarget
@inline(__always)
@Sendable
@@ -1439,6 +1605,7 @@ extension ClientBootstrap {
return
channelOptions
.applyAllChannelOptions(to: channel)
.assumeIsolated()
.flatMap {
if let bindTarget = bindTarget {
return
@@ -1463,6 +1630,7 @@ extension ClientBootstrap {
channel.close0(error: error, mode: .all, promise: nil)
return channel.eventLoop.makeFailedFuture(error)
}
.nonisolated()
}
if eventLoop.inEventLoop {
@@ -1716,10 +1884,10 @@ public final class DatagramBootstrap {
private func withNewChannel(
makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel,
_ bringup: @escaping (EventLoop, DatagramChannel) -> EventLoopFuture<Void>
_ bringup: @escaping @Sendable (EventLoop, DatagramChannel) -> EventLoopFuture<Void>
) -> EventLoopFuture<Channel> {
let eventLoop = self.group.next()
let channelInitializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) }
let channelInitializer = self.channelInitializer ?? { @Sendable _ in eventLoop.makeSucceededFuture(()) }
let channelOptions = self._channelOptions
let channel: DatagramChannel
@@ -1729,6 +1897,7 @@ public final class DatagramBootstrap {
return eventLoop.makeFailedFuture(error)
}
@Sendable
func setupChannel() -> EventLoopFuture<Channel> {
eventLoop.assertInEventLoop()
return channelOptions.applyAllChannelOptions(to: channel).flatMap {
@@ -1935,7 +2104,7 @@ extension DatagramBootstrap {
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
private func connect0<ChannelInitializerResult, PostRegistrationTransformationResult>(
private func connect0<ChannelInitializerResult: Sendable, PostRegistrationTransformationResult: Sendable>(
makeSocketAddress: () throws -> SocketAddress,
channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<ChannelInitializerResult>,
postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture<
@@ -1966,7 +2135,7 @@ extension DatagramBootstrap {
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
private func bind0<ChannelInitializerResult, PostRegistrationTransformationResult>(
private func bind0<ChannelInitializerResult: Sendable, PostRegistrationTransformationResult: Sendable>(
makeSocketAddress: () throws -> SocketAddress,
channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<ChannelInitializerResult>,
postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture<
@@ -1997,7 +2166,10 @@ extension DatagramBootstrap {
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
private func makeConfiguredChannel<ChannelInitializerResult, PostRegistrationTransformationResult>(
private func makeConfiguredChannel<
ChannelInitializerResult: Sendable,
PostRegistrationTransformationResult: Sendable
>(
makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel,
channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<ChannelInitializerResult>,
registration: @escaping @Sendable (Channel) -> EventLoopFuture<Void>,
@@ -2006,9 +2178,14 @@ extension DatagramBootstrap {
>
) -> EventLoopFuture<PostRegistrationTransformationResult> {
let eventLoop = self.group.next()
let channelInitializer = { (channel: Channel) -> EventLoopFuture<ChannelInitializerResult> in
let initializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) }
return initializer(channel).flatMap { channelInitializer(channel) }
let bootstrapChannelInitializer =
self.channelInitializer ?? { @Sendable _ in eventLoop.makeSucceededFuture(()) }
let channelInitializer = { @Sendable (channel: Channel) -> EventLoopFuture<ChannelInitializerResult> in
bootstrapChannelInitializer(channel)
.hop(to: channel.eventLoop)
.assumeIsolated()
.flatMap { channelInitializer(channel) }
.nonisolated()
}
let channelOptions = self._channelOptions
@@ -2019,6 +2196,7 @@ extension DatagramBootstrap {
return eventLoop.makeFailedFuture(error)
}
@Sendable
func setupChannel() -> EventLoopFuture<PostRegistrationTransformationResult> {
eventLoop.assertInEventLoop()
return channelOptions.applyAllChannelOptions(to: channel).flatMap {
@@ -2429,6 +2607,8 @@ extension NIOPipeBootstrap {
let channel: PipeChannel
let pipeChannelInput: SelectablePipeHandle?
let pipeChannelOutput: SelectablePipeHandle?
let hasNoInputPipe: Bool
let hasNoOutputPipe: Bool
do {
if let input = input {
try self.validateFileDescriptorIsNotAFile(input)
@@ -2439,6 +2619,8 @@ extension NIOPipeBootstrap {
pipeChannelInput = input.flatMap { SelectablePipeHandle(takingOwnershipOfDescriptor: $0) }
pipeChannelOutput = output.flatMap { SelectablePipeHandle(takingOwnershipOfDescriptor: $0) }
hasNoInputPipe = pipeChannelInput == nil
hasNoOutputPipe = pipeChannelOutput == nil
do {
channel = try self.hooks.makePipeChannel(
eventLoop: eventLoop as! SelectableEventLoop,
@@ -2467,10 +2649,10 @@ extension NIOPipeBootstrap {
channel.registerAlreadyConfigured0(promise: promise)
return promise.futureResult.map { result }
}.flatMap { result -> EventLoopFuture<ChannelInitializerResult> in
if pipeChannelInput == nil {
if hasNoInputPipe {
return channel.close(mode: .input).map { result }
}
if pipeChannelOutput == nil {
if hasNoOutputPipe {
return channel.close(mode: .output).map { result }
}
return channel.selectableEventLoop.makeSucceededFuture(result)
+7 -3
View File
@@ -79,7 +79,9 @@ struct UnsafeControlMessageStorage: Collection {
/// Get the part of the buffer for use with a message.
public subscript(position: Int) -> UnsafeMutableRawBufferPointer {
UnsafeMutableRawBufferPointer(
fastRebase: self.buffer[(position * self.bytesPerMessage)..<((position + 1) * self.bytesPerMessage)]
rebasing: self.buffer[
(position * self.bytesPerMessage)..<((position + 1) * self.bytesPerMessage)
]
)
}
@@ -316,7 +318,9 @@ struct UnsafeOutboundControlBytes {
type: CInt,
payload: PayloadType
) {
let writableBuffer = UnsafeMutableRawBufferPointer(fastRebase: self.controlBytes[writePosition...])
let writableBuffer = UnsafeMutableRawBufferPointer(
rebasing: self.controlBytes[writePosition...]
)
let requiredSize = NIOBSDSocketControlMessage.space(payloadSize: MemoryLayout.stride(ofValue: payload))
precondition(writableBuffer.count >= requiredSize, "Insufficient size for cmsghdr and data")
@@ -342,7 +346,7 @@ struct UnsafeOutboundControlBytes {
if writePosition == 0 {
return UnsafeMutableRawBufferPointer(start: nil, count: 0)
}
return UnsafeMutableRawBufferPointer(fastRebase: self.controlBytes[0..<self.writePosition])
return UnsafeMutableRawBufferPointer(rebasing: self.controlBytes[0..<self.writePosition])
}
}
@@ -11,6 +11,8 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CNIODarwin
import CNIOLinux
import NIOCore
/// An object that manages issuing vector reads for datagram channels.
+15 -6
View File
@@ -50,7 +50,8 @@ import struct WinSDK.SOCKADDR_IN6
// A thread-specific variable where we store the offload queue if we're on an `SelectableEventLoop`.
let offloadQueueTSV = ThreadSpecificVariable<DispatchQueue>()
internal class GetaddrinfoResolver: Resolver {
internal final class GetaddrinfoResolver: Resolver, Sendable {
private let loop: EventLoop
private let v4Future: EventLoopPromise<[SocketAddress]>
private let v6Future: EventLoopPromise<[SocketAddress]>
private let aiSocktype: NIOBSDSocket.SocketType
@@ -67,6 +68,7 @@ internal class GetaddrinfoResolver: Resolver {
aiSocktype: NIOBSDSocket.SocketType,
aiProtocol: NIOBSDSocket.OptionLevel
) {
self.loop = loop
self.v4Future = loop.makePromise()
self.v6Future = loop.makePromise()
self.aiSocktype = aiSocktype
@@ -90,7 +92,6 @@ internal class GetaddrinfoResolver: Resolver {
/// Initiate a DNS AAAA query for a given host.
///
/// Due to the nature of `getaddrinfo`, we only actually call the function once, in this function.
/// That means this function call actually blocks: sorry!
///
/// - Parameters:
/// - host: The hostname to do an AAAA lookup on.
@@ -214,8 +215,12 @@ internal class GetaddrinfoResolver: Resolver {
info = nextInfo
}
v6Future.succeed(v6Results)
v4Future.succeed(v4Results)
// Ensure that both futures are succeeded in the same tick
// to avoid racing and potentially leaking a promise
self.loop.execute { [v4Results, v6Results] in
self.v6Future.succeed(v6Results)
self.v4Future.succeed(v4Results)
}
}
/// Record an error and fail the lookup process.
@@ -223,7 +228,11 @@ internal class GetaddrinfoResolver: Resolver {
/// - Parameters:
/// - error: The error encountered during lookup.
private func fail(_ error: Error) {
self.v6Future.fail(error)
self.v4Future.fail(error)
// Ensure that both futures are succeeded in the same tick
// to avoid racing and potentially leaking a promise
self.loop.execute {
self.v6Future.fail(error)
self.v4Future.fail(error)
}
}
}
+171 -132
View File
@@ -126,25 +126,142 @@ private struct TargetIterator: IteratorProtocol {
/// Given a DNS resolver and an event loop, attempts to establish a connection to
/// the target host over both IPv4 and IPv6.
///
/// This class provides the code that implements RFC 8305: Happy Eyeballs 2. This
/// This type provides the code that implements RFC 8305: Happy Eyeballs 2. This
/// is a connection establishment strategy that attempts to efficiently and quickly
/// establish connections to a host that has multiple IP addresses available to it,
/// potentially over two different IP protocol versions (4 and 6).
///
/// This class should be created when a connection attempt is made and will remain
/// This type should be created when a connection attempt is made and will remain
/// active until a connection is established. It is responsible for actually creating
/// connections and managing timeouts.
///
/// This class's public API is thread-safe: the constructor and `resolveAndConnect` can
/// This type's public API is thread-safe: the constructor and `resolveAndConnect` can
/// be called from any thread. `resolveAndConnect` will dispatch itself to the event
/// loop to force serialization.
///
/// This class's private API is *not* thread-safe, and expects to be called from the
/// event loop thread of the `loop` it is passed.
///
/// The `ChannelBuilderResult` generic type can used to tunnel an arbitrary type
/// from the `channelBuilderCallback` to the `resolve` methods return value.
internal final class HappyEyeballsConnector<ChannelBuilderResult> {
internal struct HappyEyeballsConnector<ChannelBuilderResult: Sendable>: Sendable {
/// The DNS resolver provided by the user.
fileprivate let resolver: Resolver & Sendable
/// The event loop this connector will run on.
fileprivate let loop: EventLoop
/// The host name we're connecting to.
fileprivate let host: String
/// The port we're connecting to.
fileprivate let port: Int
/// A callback, provided by the user, that is used to build a channel.
///
/// This callback is expected to build *and register* a channel with the event loop that
/// was used with this resolver. It is free to set up the channel asynchronously, but note
/// that the time taken to set the channel up will be counted against the connection delay,
/// meaning that long channel setup times may cause more connections to be outstanding
/// than intended.
///
/// The channel builder callback takes an event loop and a protocol family as arguments.
fileprivate let channelBuilderCallback:
@Sendable (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture<(Channel, ChannelBuilderResult)>
/// The amount of time to wait for an AAAA response to come in after a A response is
/// received. By default this is 50ms.
fileprivate let resolutionDelay: TimeAmount
/// The amount of time to wait for a connection to succeed before beginning a new connection
/// attempt. By default this is 250ms.
fileprivate let connectionDelay: TimeAmount
/// The amount of time to allow for the overall connection process before timing it out.
fileprivate let connectTimeout: TimeAmount
/// The promise that will hold the final connected channel.
fileprivate let resolutionPromise: EventLoopPromise<(Channel, ChannelBuilderResult)>
@inlinable
init(
resolver: Resolver & Sendable,
loop: EventLoop,
host: String,
port: Int,
connectTimeout: TimeAmount,
resolutionDelay: TimeAmount = .milliseconds(50),
connectionDelay: TimeAmount = .milliseconds(250),
channelBuilderCallback: @escaping @Sendable (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture<
(Channel, ChannelBuilderResult)
>
) {
self.resolver = resolver
self.loop = loop
self.host = host
self.port = port
self.connectTimeout = connectTimeout
self.channelBuilderCallback = channelBuilderCallback
self.resolutionPromise = self.loop.makePromise()
precondition(
resolutionDelay.nanoseconds > 0,
"Resolution delay must be greater than zero, got \(resolutionDelay)."
)
self.resolutionDelay = resolutionDelay
precondition(
connectionDelay >= .milliseconds(100) && connectionDelay <= .milliseconds(2000),
"Connection delay must be between 100 and 2000 ms, got \(connectionDelay)"
)
self.connectionDelay = connectionDelay
}
@inlinable
init(
resolver: Resolver & Sendable,
loop: EventLoop,
host: String,
port: Int,
connectTimeout: TimeAmount,
resolutionDelay: TimeAmount = .milliseconds(50),
connectionDelay: TimeAmount = .milliseconds(250),
channelBuilderCallback: @escaping @Sendable (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture<Channel>
) where ChannelBuilderResult == Void {
self.init(
resolver: resolver,
loop: loop,
host: host,
port: port,
connectTimeout: connectTimeout,
resolutionDelay: resolutionDelay,
connectionDelay: connectionDelay
) { loop, protocolFamily in
channelBuilderCallback(loop, protocolFamily).map { ($0, ()) }
}
}
/// Initiate a DNS resolution attempt using Happy Eyeballs 2.
///
/// returns: An `EventLoopFuture` that fires with a connected `Channel`.
@inlinable
func resolveAndConnect() -> EventLoopFuture<(Channel, ChannelBuilderResult)> {
// We dispatch ourselves onto the event loop, rather than do all the rest of our processing from outside it.
self.loop.execute {
let runner = HappyEyeballsConnectorRunner(connector: self)
runner.resolveAndConnect()
}
return self.resolutionPromise.futureResult
}
/// Initiate a DNS resolution attempt using Happy Eyeballs 2.
///
/// returns: An `EventLoopFuture` that fires with a connected `Channel`.
@inlinable
func resolveAndConnect() -> EventLoopFuture<Channel> where ChannelBuilderResult == Void {
self.resolveAndConnect().map { $0.0 }
}
}
private final class HappyEyeballsConnectorRunner<ChannelBuilderResult: Sendable> {
/// An enum for keeping track of connection state.
private enum ConnectionState {
/// Initial state. No work outstanding.
@@ -205,57 +322,22 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
case noTargetsRemaining
}
/// The DNS resolver provided by the user.
private let resolver: Resolver
/// The event loop this connector will run on.
private let loop: EventLoop
/// The host name we're connecting to.
private let host: String
/// The port we're connecting to.
private let port: Int
/// A callback, provided by the user, that is used to build a channel.
///
/// This callback is expected to build *and register* a channel with the event loop that
/// was used with this resolver. It is free to set up the channel asynchronously, but note
/// that the time taken to set the channel up will be counted against the connection delay,
/// meaning that long channel setup times may cause more connections to be outstanding
/// than intended.
///
/// The channel builder callback takes an event loop and a protocol family as arguments.
private let channelBuilderCallback:
(EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture<(Channel, ChannelBuilderResult)>
/// The amount of time to wait for an AAAA response to come in after a A response is
/// received. By default this is 50ms.
private let resolutionDelay: TimeAmount
/// The thread-safe state across resolutions.
private let connector: HappyEyeballsConnector<ChannelBuilderResult>
/// A reference to the task that will execute after the resolution delay expires, if
/// one is scheduled. This is held to ensure that we can cancel this task if the AAAA
/// response comes in before the resolution delay expires.
private var resolutionTask: Optional<Scheduled<Void>>
/// The amount of time to wait for a connection to succeed before beginning a new connection
/// attempt. By default this is 250ms.
private let connectionDelay: TimeAmount
/// A reference to the task that will execute after the connection delay expires, if one
/// is scheduled. This is held to ensure that we can cancel this task if a connection
/// succeeds before the connection delay expires.
private var connectionTask: Optional<Scheduled<Void>>
/// The amount of time to allow for the overall connection process before timing it out.
private let connectTimeout: TimeAmount
/// A reference to the task that will time us out.
private var timeoutTask: Optional<Scheduled<Void>>
/// The promise that will hold the final connected channel.
private let resolutionPromise: EventLoopPromise<(Channel, ChannelBuilderResult)>
/// Our state machine state.
private var state: ConnectionState
@@ -280,89 +362,24 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
@inlinable
init(
resolver: Resolver,
loop: EventLoop,
host: String,
port: Int,
connectTimeout: TimeAmount,
resolutionDelay: TimeAmount = .milliseconds(50),
connectionDelay: TimeAmount = .milliseconds(250),
channelBuilderCallback: @escaping (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture<
(Channel, ChannelBuilderResult)
>
connector: HappyEyeballsConnector<ChannelBuilderResult>
) {
self.resolver = resolver
self.loop = loop
self.host = host
self.port = port
self.connectTimeout = connectTimeout
self.channelBuilderCallback = channelBuilderCallback
self.connector = connector
self.resolutionTask = nil
self.connectionTask = nil
self.timeoutTask = nil
self.state = .idle
self.resolutionPromise = self.loop.makePromise()
self.error = NIOConnectionError(host: host, port: port)
precondition(
resolutionDelay.nanoseconds > 0,
"Resolution delay must be greater than zero, got \(resolutionDelay)."
)
self.resolutionDelay = resolutionDelay
precondition(
connectionDelay >= .milliseconds(100) && connectionDelay <= .milliseconds(2000),
"Connection delay must be between 100 and 2000 ms, got \(connectionDelay)"
)
self.connectionDelay = connectionDelay
}
@inlinable
convenience init(
resolver: Resolver,
loop: EventLoop,
host: String,
port: Int,
connectTimeout: TimeAmount,
resolutionDelay: TimeAmount = .milliseconds(50),
connectionDelay: TimeAmount = .milliseconds(250),
channelBuilderCallback: @escaping (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture<Channel>
) where ChannelBuilderResult == Void {
self.init(
resolver: resolver,
loop: loop,
host: host,
port: port,
connectTimeout: connectTimeout,
resolutionDelay: resolutionDelay,
connectionDelay: connectionDelay
) { loop, protocolFamily in
channelBuilderCallback(loop, protocolFamily).map { ($0, ()) }
}
self.error = NIOConnectionError(host: self.connector.host, port: self.connector.port)
}
/// Initiate a DNS resolution attempt using Happy Eyeballs 2.
///
/// returns: An `EventLoopFuture` that fires with a connected `Channel`.
@inlinable
func resolveAndConnect() -> EventLoopFuture<(Channel, ChannelBuilderResult)> {
// We dispatch ourselves onto the event loop, rather than do all the rest of our processing from outside it.
self.loop.execute {
self.timeoutTask = self.loop.scheduleTask(in: self.connectTimeout) {
self.processInput(.connectTimeoutElapsed)
}
self.processInput(.resolve)
func resolveAndConnect() {
self.timeoutTask = self.connector.loop.assumeIsolated().scheduleTask(in: self.connector.connectTimeout) {
self.processInput(.connectTimeoutElapsed)
}
return resolutionPromise.futureResult
}
/// Initiate a DNS resolution attempt using Happy Eyeballs 2.
///
/// returns: An `EventLoopFuture` that fires with a connected `Channel`.
@inlinable
func resolveAndConnect() -> EventLoopFuture<Channel> where ChannelBuilderResult == Void {
self.resolveAndConnect().map { $0.0 }
self.processInput(.resolve)
}
/// Spin the state machine.
@@ -464,7 +481,12 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
// notifications, and can also get late scheduled task callbacks. We want to just quietly
// ignore these, as our transition into the complete state should have already sent
// cleanup messages to all of these things.
case (.complete, .resolverACompleted),
//
// We can also get the resolutionDelayElapsed after allResolved, as it's possible that
// callback was already dequeued in the same tick as the cancellation. That's also fine:
// the resolution delay isn't interesting.
case (.allResolved, .resolutionDelayElapsed),
(.complete, .resolverACompleted),
(.complete, .resolverAAAACompleted),
(.complete, .connectSuccess),
(.complete, .connectFailed),
@@ -485,11 +507,18 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
// query.
//
// We hop back to `self.loop` because there's no guarantee the resolver runs
// on our event loop.
let aaaaLookup = self.resolver.initiateAAAAQuery(host: self.host, port: self.port).hop(to: self.loop)
// on our event loop. That hop then makes it safe for us to assumeIsolatedUnsafeUnchecked.
self.connector.loop.assertInEventLoop()
let aaaaLookup = self.connector.resolver.initiateAAAAQuery(
host: self.connector.host,
port: self.connector.port
).hop(to: self.connector.loop).assumeIsolatedUnsafeUnchecked()
self.whenAAAALookupComplete(future: aaaaLookup)
let aLookup = self.resolver.initiateAQuery(host: self.host, port: self.port).hop(to: self.loop)
let aLookup = self.connector.resolver.initiateAQuery(
host: self.connector.host,
port: self.connector.port
).hop(to: self.connector.loop).assumeIsolatedUnsafeUnchecked()
self.whenALookupComplete(future: aLookup)
}
@@ -501,7 +530,10 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
///
/// This method sets off a scheduled task for the resolution delay.
private func beginResolutionDelay() {
resolutionTask = loop.scheduleTask(in: resolutionDelay, resolutionDelayComplete)
resolutionTask = self.connector.loop.assumeIsolated().scheduleTask(
in: self.connector.resolutionDelay,
resolutionDelayComplete
)
}
/// Called when we're ready to start connecting to targets.
@@ -516,7 +548,11 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
return
}
connectionTask = loop.scheduleTask(in: connectionDelay) { self.processInput(.connectDelayElapsed) }
connectionTask = self.connector.loop.assumeIsolated().scheduleTask(
in: self.connector.connectionDelay
) {
self.processInput(.connectDelayElapsed)
}
connectToTarget(target)
}
@@ -568,7 +604,9 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
/// Cleans up internal state and fails the connection promise.
private func timedOut() {
cleanUp()
self.resolutionPromise.fail(ChannelError.connectTimeout(self.connectTimeout))
self.connector.resolutionPromise.fail(
ChannelError.connectTimeout(self.connector.connectTimeout)
)
}
/// Called when we've attempted to connect to all our resolved targets,
@@ -579,7 +617,7 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
private func failed() {
precondition(pendingConnections.isEmpty, "failed with pending connections")
cleanUp()
self.resolutionPromise.fail(self.error)
self.connector.resolutionPromise.fail(self.error)
}
/// Called to connect to a given target.
@@ -587,17 +625,18 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
/// - Parameters:
/// - target: The address to connect to.
private func connectToTarget(_ target: SocketAddress) {
let channelFuture = channelBuilderCallback(self.loop, target.protocol)
let channelFuture = self.connector.channelBuilderCallback(self.connector.loop, target.protocol)
let isolatedChannelFuture = channelFuture.hop(to: self.connector.loop).assumeIsolated()
pendingConnections.append(channelFuture)
channelFuture.whenSuccess { (channel, result) in
isolatedChannelFuture.whenSuccess { (channel, result) in
// If we are in the complete state then we want to abandon this channel. Otherwise, begin
// connecting.
if case .complete = self.state {
self.pendingConnections.removeAll { $0 === channelFuture }
channel.close(promise: nil)
} else {
channel.connect(to: target).map {
channel.connect(to: target).assumeIsolated().map {
// The channel has connected. If we are in the complete state we want to abandon this channel.
// Otherwise, fire the channel connected event. Either way we don't want the channel future to
// be in our list of pending connections, so we don't either double close or close the connection
@@ -608,7 +647,7 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
channel.close(promise: nil)
} else {
self.processInput(.connectSuccess)
self.resolutionPromise.succeed((channel, result))
self.connector.resolutionPromise.succeed((channel, result))
}
}.whenFailure { err in
// The connection attempt failed. If we're in the complete state then there's nothing
@@ -626,7 +665,7 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
}
}
}
channelFuture.whenFailure { error in
isolatedChannelFuture.whenFailure { error in
self.error.connectionErrors.append(SingleConnectionFailure(target: target, error: error))
self.pendingConnections.removeAll { $0 === channelFuture }
self.processInput(.connectFailed)
@@ -639,7 +678,7 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
assert(self.state == .complete, "Clean up in invalid state \(self.state)")
if dnsResolutions < 2 {
resolver.cancelQueries()
self.connector.resolver.cancelQueries()
}
if let resolutionTask = self.resolutionTask {
@@ -665,7 +704,7 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
}
/// A future callback that fires when a DNS A lookup completes.
private func whenALookupComplete(future: EventLoopFuture<[SocketAddress]>) {
private func whenALookupComplete(future: EventLoopFuture<[SocketAddress]>.Isolated) {
future.map { results in
self.targets.aResultsAvailable(results)
}.recover { err in
@@ -677,7 +716,7 @@ internal final class HappyEyeballsConnector<ChannelBuilderResult> {
}
/// A future callback that fires when a DNS AAAA lookup completes.
private func whenAAAALookupComplete(future: EventLoopFuture<[SocketAddress]>) {
private func whenAAAALookupComplete(future: EventLoopFuture<[SocketAddress]>.Isolated) {
future.map { results in
self.targets.aaaaResultsAvailable(results)
}.recover { err in
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff. Show more