diff --git a/.github/actions/pull_request_semver_label_checker/action.yml b/.github/actions/pull_request_semver_label_checker/action.yml index 31dda8124..bbdeffd75 100644 --- a/.github/actions/pull_request_semver_label_checker/action.yml +++ b/.github/actions/pull_request_semver_label_checker/action.yml @@ -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")' diff --git a/.github/release.yml b/.github/release.yml index f96b51492..e29eb8464 100644 --- a/.github/release.yml +++ b/.github/release.yml @@ -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 diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml index 2b2e4eb38..a5114b2f2 100644 --- a/.github/workflows/benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -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 }}' diff --git a/.github/workflows/cxx_interop.yml b/.github/workflows/cxx_interop.yml index 3e6642607..c36eb3c0d 100644 --- a/.github/workflows/cxx_interop.yml +++ b/.github/workflows/cxx_interop.yml @@ -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 }}' diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 13420a4d8..7b7111804 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -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 }}' diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 1e5a3b734..1925c4a54 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -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 diff --git a/.github/workflows/pull_request_label.yml b/.github/workflows/pull_request_label.yml index fbc861863..c78fe14fa 100644 --- a/.github/workflows/pull_request_label.yml +++ b/.github/workflows/pull_request_label.yml @@ -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: diff --git a/.github/workflows/swift_load_test_matrix.yml b/.github/workflows/swift_load_test_matrix.yml new file mode 100644 index 000000000..f0c34c2da --- /dev/null +++ b/.github/workflows/swift_load_test_matrix.yml @@ -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 }}' diff --git a/.github/workflows/swift_matrix.yml b/.github/workflows/swift_matrix.yml index 4c4734cbb..6d501bb6e 100644 --- a/.github/workflows/swift_matrix.yml +++ b/.github/workflows/swift_matrix.yml @@ -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" diff --git a/.github/workflows/swift_test_matrix.yml b/.github/workflows/swift_test_matrix.yml new file mode 100644 index 000000000..9b4a36e93 --- /dev/null +++ b/.github/workflows/swift_test_matrix.yml @@ -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 }} diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 8a70518bb..d09b45ed9 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -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 }}' diff --git a/.gitignore b/.gitignore index f22758cad..f6bd1f104 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ .DS_Store -/.build +.build /.index-build /Packages /*.xcodeproj diff --git a/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json index d7233c85b..c6a93680d 100644 --- a/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 555 + "mallocCountTotal" : 108 } diff --git a/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json index 8517c2fe4..248bd9606 100644 --- a/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 556 + "mallocCountTotal" : 110 } diff --git a/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json index 67abcf36a..c6a93680d 100644 --- a/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 548 + "mallocCountTotal" : 108 } diff --git a/Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEcho.p90.json deleted file mode 100644 index 67abcf36a..000000000 --- a/Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEcho.p90.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "mallocCountTotal" : 548 -} diff --git a/Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/nightly-6.1/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json similarity index 100% rename from Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json rename to Benchmarks/Thresholds/nightly-6.1/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json diff --git a/Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEcho.p90.json new file mode 100644 index 000000000..c6a93680d --- /dev/null +++ b/Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEcho.p90.json @@ -0,0 +1,3 @@ +{ + "mallocCountTotal" : 108 +} diff --git a/Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEchoAsyncChannel.p90.json b/Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEchoAsyncChannel.p90.json similarity index 100% rename from Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEchoAsyncChannel.p90.json rename to Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEchoAsyncChannel.p90.json diff --git a/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json index 67abcf36a..c6a93680d 100644 --- a/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 548 + "mallocCountTotal" : 108 } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7d1311924..05b102e75 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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. diff --git a/IntegrationTests/tests_01_http/test_07_headers_work.sh b/IntegrationTests/tests_01_http/test_07_headers_work.sh index 6e3dc3365..6389929d9 100644 --- a/IntegrationTests/tests_01_http/test_07_headers_work.sh +++ b/IntegrationTests/tests_01_http/test_07_headers_work.sh @@ -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" diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.10.json b/IntegrationTests/tests_04_performance/Thresholds/5.10.json index 1fb41c219..29a7bf1e7 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.10.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.10.json @@ -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 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.9.json b/IntegrationTests/tests_04_performance/Thresholds/5.9.json index b77ad41e4..2d8cb07bf 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.9.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.9.json @@ -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 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/6.0.json b/IntegrationTests/tests_04_performance/Thresholds/6.0.json index 1fb41c219..0870e3343 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/6.0.json @@ -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 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json deleted file mode 100644 index 1fb41c219..000000000 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json +++ /dev/null @@ -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 -} diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.1.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.1.json new file mode 100644 index 000000000..29a7bf1e7 --- /dev/null +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.1.json @@ -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 +} diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index 1fb41c219..a5ce73574 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -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 } diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_assume_isolated_scheduling_10000_executions.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_assume_isolated_scheduling_10000_executions.swift new file mode 100644 index 000000000..7087e17aa --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_assume_isolated_scheduling_10000_executions.swift @@ -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 + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_10000_tasks.swift new file mode 100644 index 000000000..1d80f8d43 --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_10000_tasks.swift @@ -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 + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_assume_isolated_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_assume_isolated_10000_tasks.swift new file mode 100644 index 000000000..4f980a00b --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_assume_isolated_10000_tasks.swift @@ -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 + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_future_assume_isolated_lots_of_callbacks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_future_assume_isolated_lots_of_callbacks.swift new file mode 100644 index 000000000..d9a04d14e --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_future_assume_isolated_lots_of_callbacks.swift @@ -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 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 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 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 + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_future_lots_of_callbacks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_future_lots_of_callbacks.swift index 2e0173ba0..42e8e5731 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/test_future_lots_of_callbacks.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_future_lots_of_callbacks.swift @@ -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 in + }.flatMapError { (err: Error) -> EventLoopFuture 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 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. diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_assume_isolated_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_assume_isolated_10000_tasks.swift new file mode 100644 index 000000000..7d63b19fb --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_assume_isolated_10000_tasks.swift @@ -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 + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_10000_tasks.swift new file mode 100644 index 000000000..8b10c78eb --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_10000_tasks.swift @@ -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 + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_assume_isolated_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_assume_isolated_10000_tasks.swift new file mode 100644 index 000000000..b0e157b0c --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_assume_isolated_10000_tasks.swift @@ -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 + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_submit_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_submit_10000_tasks.swift new file mode 100644 index 000000000..88ae88542 --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_submit_10000_tasks.swift @@ -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 + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_submit_assume_isolated_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_submit_assume_isolated_10000_tasks.swift new file mode 100644 index 000000000..47f16587a --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_submit_assume_isolated_10000_tasks.swift @@ -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 + } +} diff --git a/NOTICE.txt b/NOTICE.txt index cbcc2e69b..d79250ea5 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -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 diff --git a/Package.swift b/Package.swift index 4bbbe48e7..008de4f82 100644 --- a/Package.swift +++ b/Package.swift @@ -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 --- // diff --git a/README.md b/README.md index 055c5359c..48d8b2497 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/Sources/NIOAsyncAwaitDemo/AsyncChannelIO.swift b/Sources/NIOAsyncAwaitDemo/AsyncChannelIO.swift index e5612e1f6..5e6f04a38 100644 --- a/Sources/NIOAsyncAwaitDemo/AsyncChannelIO.swift +++ b/Sources/NIOAsyncAwaitDemo/AsyncChannelIO.swift @@ -24,8 +24,11 @@ struct AsyncChannelIO { } func start() async throws -> AsyncChannelIO { - try await channel.pipeline.addHandler(RequestResponseHandler()) - .get() + try await channel.eventLoop.submit { + try channel.pipeline.syncOperations.addHandler( + RequestResponseHandler() + ) + }.get() return self } diff --git a/Sources/NIOChatClient/main.swift b/Sources/NIOChatClient/main.swift index c41250e39..a350bf14b 100644 --- a/Sources/NIOChatClient/main.swift +++ b/Sources/NIOChatClient/main.swift @@ -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() diff --git a/Sources/NIOCore/AsyncAwaitSupport.swift b/Sources/NIOCore/AsyncAwaitSupport.swift index 5152728c0..ba8dfa3cf 100644 --- a/Sources/NIOCore/AsyncAwaitSupport.swift +++ b/Sources/NIOCore/AsyncAwaitSupport.swift @@ -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: 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 diff --git a/Sources/NIOCore/AsyncChannel/AsyncChannel.swift b/Sources/NIOCore/AsyncChannel/AsyncChannel.swift index 10354f076..105862576 100644 --- a/Sources/NIOCore/AsyncChannel/AsyncChannel.swift +++ b/Sources/NIOCore/AsyncChannel/AsyncChannel.swift @@ -301,15 +301,25 @@ public struct NIOAsyncChannel: 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 } } diff --git a/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift b/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift index 63d243b74..149c0ff5e 100644 --- a/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift +++ b/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift @@ -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: diff --git a/Sources/NIOCore/AsyncSequences/NIOAsyncSequenceProducer.swift b/Sources/NIOCore/AsyncSequences/NIOAsyncSequenceProducer.swift index e6484d846..acc3aff5e 100644 --- a/Sources/NIOCore/AsyncSequences/NIOAsyncSequenceProducer.swift +++ b/Sources/NIOCore/AsyncSequences/NIOAsyncSequenceProducer.swift @@ -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 diff --git a/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift b/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift index badc34f96..f232d518f 100644 --- a/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift +++ b/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift @@ -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, diff --git a/Sources/NIOCore/ByteBuffer-aux.swift b/Sources/NIOCore/ByteBuffer-aux.swift index 5e07f4af2..1ec8e9cf3 100644 --- a/Sources/NIOCore/ByteBuffer-aux.swift +++ b/Sources/NIOCore/ByteBuffer-aux.swift @@ -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..= 0, "Can't write fewer than 0 bytes") self.reserveCapacity(index + count) self.withVeryUnsafeMutableBytes { pointer in - let dest = UnsafeMutableRawBufferPointer(fastRebase: pointer[index.. 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 { self._ensureAvailableCapacity(_Capacity(capacity), at: index) let newBytesPtr = UnsafeMutableRawBufferPointer( - fastRebase: self._slicedStorageBuffer[Int(index)..= writerIndex let range = Range(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(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T { // This is safe, writerIndex >= readerIndex let range = Range(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 = Unmanaged.passUnretained(self._storage) // This is safe, writerIndex >= readerIndex let range = Range(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) } diff --git a/Sources/NIOCore/ByteBuffer-int.swift b/Sources/NIOCore/ByteBuffer-int.swift index d0fb02690..5e39004e9 100644 --- a/Sources/NIOCore/ByteBuffer-int.swift +++ b/Sources/NIOCore/ByteBuffer-int.swift @@ -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 { diff --git a/Sources/NIOCore/Channel.swift b/Sources/NIOCore/Channel.swift index 8d0af1fec..9793102d5 100644 --- a/Sources/NIOCore/Channel.swift +++ b/Sources/NIOCore/Channel.swift @@ -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 { get } /// The `ChannelPipeline` which handles all I/O events and requests associated with this `Channel`. diff --git a/Sources/NIOCore/ChannelHandlers.swift b/Sources/NIOCore/ChannelHandlers.swift index 8e0da681e..358332945 100644 --- a/Sources/NIOCore/ChannelHandlers.swift +++ b/Sources/NIOCore/ChannelHandlers.swift @@ -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) in + writePromise.futureResult.hop( + to: context.eventLoop + ).assumeIsolatedUnsafeUnchecked().whenComplete { (_: Result) 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? { 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 } diff --git a/Sources/NIOCore/ChannelOption.swift b/Sources/NIOCore/ChannelOption.swift index 17109fa98..b97647f85 100644 --- a/Sources/NIOCore/ChannelOption.swift +++ b/Sources/NIOCore/ChannelOption.swift @@ -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. /// diff --git a/Sources/NIOCore/ChannelPipeline.swift b/Sources/NIOCore/ChannelPipeline.swift index 2aa8d6c62..6b63c5e2b 100644 --- a/Sources/NIOCore/ChannelPipeline.swift +++ b/Sources/NIOCore/ChannelPipeline.swift @@ -176,10 +176,14 @@ public final class ChannelPipeline: ChannelInvoker { let future: EventLoopFuture 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 { 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 { + 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 { 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: Handlers, - position: ChannelPipeline.Position + position: ChannelPipeline.SynchronousOperations.Position + ) -> Result 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: Handlers, + position: ChannelPipeline.SynchronousOperations.Position ) -> Result 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 { diff --git a/Sources/NIOCore/Codec.swift b/Sources/NIOCore/Codec.swift index acb4fc139..f38f2eb9e 100644 --- a/Sources/NIOCore/Codec.swift +++ b/Sources/NIOCore/Codec.swift @@ -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 { diff --git a/Sources/NIOCore/Docs.docc/index.md b/Sources/NIOCore/Docs.docc/index.md index 13d76894e..5b437b073 100644 --- a/Sources/NIOCore/Docs.docc/index.md +++ b/Sources/NIOCore/Docs.docc/index.md @@ -21,7 +21,6 @@ More specialized modules provide concrete implementations of many of the abstrac - ``EventLoopGroup`` - ``EventLoop`` -- ``NIOEventLoopGroupProvider`` - ``EventLoopIterator`` - ``Scheduled`` - ``RepeatedTask`` diff --git a/Sources/NIOCore/Docs.docc/loops-futures-concurrency.md b/Sources/NIOCore/Docs.docc/loops-futures-concurrency.md index b5cbffa4f..a9af119ec 100644 --- a/Sources/NIOCore/Docs.docc/loops-futures-concurrency.md +++ b/Sources/NIOCore/Docs.docc/loops-futures-concurrency.md @@ -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. diff --git a/Sources/NIOCore/EventLoop.swift b/Sources/NIOCore/EventLoop.swift index 047c06e67..d31640b0a 100644 --- a/Sources/NIOCore/EventLoop.swift +++ b/Sources/NIOCore/EventLoop.swift @@ -269,6 +269,9 @@ public protocol EventLoop: EventLoopGroup { @preconcurrency func submit(_ task: @escaping @Sendable () throws -> T) -> EventLoopFuture + /// 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(_ task: @escaping () throws -> T) -> EventLoopFuture + + /// 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( + deadline: NIODeadline, + _ task: @escaping () throws -> T + ) -> Scheduled + + /// 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( + in: TimeAmount, + _ task: @escaping () throws -> T + ) -> Scheduled +} + +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(_ task: @escaping () throws -> T) -> EventLoopFuture { + 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( + deadline: NIODeadline, + _ task: @escaping () throws -> T + ) -> Scheduled { + 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( + in delay: TimeAmount, + _ task: @escaping () throws -> T + ) -> Scheduled { + 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(_ task: @escaping @Sendable () throws -> T) -> EventLoopFuture { + public func submit(_ task: @escaping @Sendable () throws -> T) -> EventLoopFuture { let promise: EventLoopPromise = 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 = 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 = 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 } diff --git a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift index d2dded2cf..7e7dd9f74 100644 --- a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift +++ b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift @@ -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(_ task: @escaping () throws -> T) -> EventLoopFuture { - self._wrapped.assertInEventLoop() - let unsafeTransfer = UnsafeTransfer(task) - return self._wrapped.submit { - try unsafeTransfer.wrappedValue() - } + public func submit(_ task: @escaping () throws -> T) -> EventLoopFuture { + 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( + public func scheduleTask( deadline: NIODeadline, _ task: @escaping () throws -> T ) -> Scheduled { - 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( + public func scheduleTask( in delay: TimeAmount, _ task: @escaping () throws -> T ) -> Scheduled { - 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( + public func flatScheduleTask( deadline: NIODeadline, file: StaticString = #file, line: UInt = #line, _ task: @escaping () throws -> EventLoopFuture ) -> Scheduled { - self._wrapped.assertInEventLoop() - let unsafeTransfer = UnsafeTransfer(task) - return self._wrapped.flatScheduleTask(deadline: deadline, file: file, line: line) { - try unsafeTransfer.wrappedValue() + let promise: EventLoopPromise = 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 + @inlinable + init(_wrapped: EventLoopFuture) { + self._wrapped = _wrapped + } + /// When the current `EventLoopFuture` 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` 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( + @available(*, noasync) + public func flatMap( _ callback: @escaping (Value) -> EventLoopFuture ) -> EventLoopFuture.Isolated { - self._wrapped.eventLoop.assertInEventLoop() - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.flatMap { - unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + let next = EventLoopPromise.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` 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( + @available(*, noasync) + public func flatMapThrowing( _ callback: @escaping (Value) throws -> NewValue ) -> EventLoopFuture.Isolated { - self._wrapped.eventLoop.assertInEventLoop() - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.flatMapThrowing { - try unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + let next = EventLoopPromise.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` 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.Isolated { - self._wrapped.eventLoop.assertInEventLoop() - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.flatMapErrorThrowing { - try unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + let next = EventLoopPromise.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` 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( + @available(*, noasync) + public func map( _ callback: @escaping (Value) -> (NewValue) ) -> EventLoopFuture.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.Isolated + } else { + let next = EventLoopPromise.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` 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 ) -> EventLoopFuture.Isolated where Value: Sendable { - self._wrapped.eventLoop.assertInEventLoop() - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.flatMapError { - unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + let next = EventLoopPromise.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` 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( + @available(*, noasync) + public func flatMapResult( _ body: @escaping (Value) -> Result ) -> EventLoopFuture.Isolated { - self._wrapped.eventLoop.assertInEventLoop() - let unsafeTransfer = UnsafeTransfer(body) - return self._wrapped.flatMapResult { - unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + let next = EventLoopPromise.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` 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.Isolated { - self._wrapped.eventLoop.assertInEventLoop() - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.recover { - unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + let next = EventLoopPromise.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) -> 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) -> Void - ) -> EventLoopFuture { - self._wrapped.eventLoop.assertInEventLoop() - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.always { - unsafeTransfer.wrappedValue($0) - } + ) -> EventLoopFuture.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( + @available(*, noasync) + public func unwrap( orReplace replacement: NewValue ) -> EventLoopFuture.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( + @available(*, noasync) + public func unwrap( orElse callback: @escaping () -> NewValue ) -> EventLoopFuture.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 { + public func nonisolated() -> EventLoopFuture { 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 + @inlinable + init(_wrapped: EventLoopPromise) { + self._wrapped = _wrapped + } + /// Deliver a successful result to the associated `EventLoopFuture` 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) { - self._wrapped.futureResult.eventLoop.assertInEventLoop() + @available(*, noasync) + public func completeWith(_ result: Result) { self._wrapped._setValue(value: result)._run() } /// Returns the wrapped event loop promise. @inlinable - func nonisolated() -> EventLoopPromise { + public func nonisolated() -> EventLoopPromise { 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 {} diff --git a/Sources/NIOCore/EventLoopFuture.swift b/Sources/NIOCore/EventLoopFuture.swift index 793d3a7ed..482bdb5af 100644 --- a/Sources/NIOCore/EventLoopFuture.swift +++ b/Sources/NIOCore/EventLoopFuture.swift @@ -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 @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 { internal static func makeUnleakablePromise(eventLoop: EventLoop, line: UInt = #line) -> EventLoopPromise { EventLoopPromise( 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. /// diff --git a/Sources/NIOCore/FileHandle.swift b/Sources/NIOCore/FileHandle.swift index 62fd100e2..6c7dc0812 100644 --- a/Sources/NIOCore/FileHandle.swift +++ b/Sources/NIOCore/FileHandle.swift @@ -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) } diff --git a/Sources/NIOCore/FileRegion.swift b/Sources/NIOCore/FileRegion.swift index 1b1f1c5b0..7ceaacd5d 100644 --- a/Sources/NIOCore/FileRegion.swift +++ b/Sources/NIOCore/FileRegion.swift @@ -93,9 +93,6 @@ public struct FileRegion: Sendable { } } -@available(*, unavailable) -extension FileRegion: Sendable {} - extension FileRegion { /// Create a new `FileRegion` forming a complete file. /// diff --git a/Sources/NIOCore/PointerHelpers.swift b/Sources/NIOCore/PointerHelpers.swift deleted file mode 100644 index 0acc2f2c2..000000000 --- a/Sources/NIOCore/PointerHelpers.swift +++ /dev/null @@ -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) { - let base = slice.base.baseAddress?.advanced(by: slice.startIndex) - self.init(start: base, count: slice.endIndex &- slice.startIndex) - } - - @inlinable - init(fastRebase slice: Slice) { - 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) { - let base = slice.base.baseAddress?.advanced(by: slice.startIndex) - self.init(start: base, count: slice.endIndex &- slice.startIndex) - } -} diff --git a/Sources/NIOCore/SocketOptionProvider.swift b/Sources/NIOCore/SocketOptionProvider.swift index 97f177298..d0592d0f5 100644 --- a/Sources/NIOCore/SocketOptionProvider.swift +++ b/Sources/NIOCore/SocketOptionProvider.swift @@ -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( + @preconcurrency + func unsafeSetSocketOption( 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( + @preconcurrency + func unsafeSetSocketOption( 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(level: SocketOptionLevel, name: SocketOptionName) -> EventLoopFuture + @preconcurrency + func unsafeGetSocketOption( + level: SocketOptionLevel, + name: SocketOptionName + ) -> EventLoopFuture #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( + @preconcurrency + func unsafeGetSocketOption( level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option ) -> EventLoopFuture @@ -137,7 +144,7 @@ public protocol SocketOptionProvider: _NIOPreconcurrencySendable { #if !os(Windows) extension SocketOptionProvider { - func unsafeSetSocketOption( + func unsafeSetSocketOption( level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option, value: Value @@ -149,7 +156,7 @@ extension SocketOptionProvider { ) } - func unsafeGetSocketOption( + func unsafeGetSocketOption( level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option ) -> EventLoopFuture { @@ -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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { #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 { + private func _getSoLinger() -> EventLoopFuture { #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 { + private func _setIPMulticastIF(_ value: in_addr) -> EventLoopFuture { 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 { + private func _getIPMulticastIF() -> EventLoopFuture { 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 { + private func _setIPMulticastTTL(_ value: CUnsignedChar) -> EventLoopFuture { 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 { + private func _getIPMulticastTTL() -> EventLoopFuture { 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 { + private func _setIPMulticastLoop(_ value: CUnsignedChar) -> EventLoopFuture { 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 { + private func _getIPMulticastLoop() -> EventLoopFuture { 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 { + private func _setIPv6MulticastIF(_ value: CUnsignedInt) -> EventLoopFuture { 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 { + private func _getIPv6MulticastIF() -> EventLoopFuture { 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 { + private func _setIPv6MulticastHops(_ value: CInt) -> EventLoopFuture { 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 { + private func _getIPv6MulticastHops() -> EventLoopFuture { 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 { + private func _setIPv6MulticastLoop(_ value: CUnsignedInt) -> EventLoopFuture { 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 { + private func _getIPv6MulticastLoop() -> EventLoopFuture { 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 { + private func _getTCPInfo() -> EventLoopFuture { 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 { + private func _getTCPConnectionInfo() -> EventLoopFuture { 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 { + private func _getMPTCPInfo() -> EventLoopFuture { self.unsafeGetSocketOption(level: .mptcp, name: .mptcp_info) } #endif diff --git a/Sources/NIOCrashTester/CrashTests+Strict.swift b/Sources/NIOCrashTester/CrashTests+Strict.swift index d97a737a0..cbbe46a52 100644 --- a/Sources/NIOCrashTester/CrashTests+Strict.swift +++ b/Sources/NIOCrashTester/CrashTests+Strict.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// #if !canImport(Darwin) || os(macOS) +import NIOCore import NIOPosix struct StrictCrashTests { diff --git a/Sources/NIOCrashTester/CrashTests+System.swift b/Sources/NIOCrashTester/CrashTests+System.swift index 3147ff081..b5863eb20 100644 --- a/Sources/NIOCrashTester/CrashTests+System.swift +++ b/Sources/NIOCrashTester/CrashTests+System.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// #if !canImport(Darwin) || os(macOS) +import NIOCore import NIOPosix import Foundation diff --git a/Sources/NIOEchoClient/main.swift b/Sources/NIOEchoClient/main.swift index d7de8eb35..e92ebc02f 100644 --- a/Sources/NIOEchoClient/main.swift +++ b/Sources/NIOEchoClient/main.swift @@ -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() diff --git a/Sources/NIOEmbedded/AsyncTestingChannel.swift b/Sources/NIOEmbedded/AsyncTestingChannel.swift index 75889e5c3..8e0ca9c33 100644 --- a/Sources/NIOEmbedded/AsyncTestingChannel.swift +++ b/Sources/NIOEmbedded/AsyncTestingChannel.swift @@ -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 {} diff --git a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift index 14e5242df..ef0070b1c 100644 --- a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift +++ b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift @@ -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(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( taskID: UInt64, deadline: NIODeadline, - promise: EventLoopPromise, + promise: EventLoopPromise?, 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(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled { - let promise: EventLoopPromise = self.makePromise() - let taskID = self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed) + @preconcurrency + public func scheduleTask( + deadline: NIODeadline, + _ task: @escaping @Sendable () throws -> T + ) -> Scheduled { + let scheduled: Scheduled + 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(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled { + @preconcurrency + public func scheduleTask(in: TimeAmount, _ task: @escaping @Sendable () throws -> T) -> Scheduled { 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(_ task: @escaping () throws -> T) -> EventLoopFuture { + // 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( + deadline: NIODeadline, + _ task: @escaping () throws -> T + ) -> Scheduled { + // 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 + 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( + in delay: TimeAmount, + _ task: @escaping () throws -> T + ) -> Scheduled { + 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 { + case doSchedule(taskID: UInt64, promise: EventLoopPromise, scheduled: Scheduled) + case returnImmediately(Scheduled) + } + private func _prepareToSchedule( + returnType: ReturnType.Type = ReturnType.self + ) -> ScheduleCreationResult { + 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!") } diff --git a/Sources/NIOEmbedded/Embedded.swift b/Sources/NIOEmbedded/Embedded.swift index c509a8ffa..e19caf40a 100644 --- a/Sources/NIOEmbedded/Embedded.swift +++ b/Sources/NIOEmbedded/Embedded.swift @@ -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(_ task: @escaping () throws -> T) -> EventLoopFuture { + // 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( + deadline: NIODeadline, + _ task: @escaping () throws -> T + ) -> Scheduled { + // Because of the way EmbeddedEL works, we can delegate this directly to schedule. + self.scheduleTask(deadline: deadline, task) + } + + @discardableResult + public func _scheduleTaskIsolatedUnsafeUnchecked( + in delay: TimeAmount, + _ task: @escaping () throws -> T + ) -> Scheduled { + // 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(_ 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 {} diff --git a/Sources/NIOFileSystem/CopyStrategy.swift b/Sources/NIOFileSystem/CopyStrategy.swift deleted file mode 100644 index 790206dae..000000000 --- a/Sources/NIOFileSystem/CopyStrategy.swift +++ /dev/null @@ -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" - } - } -} diff --git a/Sources/NIOFileSystem/DirectoryEntries.swift b/Sources/NIOFileSystem/DirectoryEntries.swift index 3830d94ab..1c0fa9d0b 100644 --- a/Sources/NIOFileSystem/DirectoryEntries.swift +++ b/Sources/NIOFileSystem/DirectoryEntries.swift @@ -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(wrapping sequence: S) where S.Element == Batched.Element { + @preconcurrency + public init(wrapping sequence: S) where S.Element == Batched.Element { self.batchedSequence = Batched(wrapping: sequence) } @@ -85,7 +86,7 @@ extension DirectoryEntries { /// The ``Batched`` sequence uses `Array` 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(wrapping sequence: S) where S.Element == Element { + @preconcurrency + public init(wrapping sequence: S) where S.Element == Element { self.stream = BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>(wrapping: sequence) } diff --git a/Sources/NIOFileSystem/FileSystem.swift b/Sources/NIOFileSystem/FileSystem.swift index 76a1bcb8a..b6af73fd5 100644 --- a/Sources/NIOFileSystem/FileSystem.swift +++ b/Sources/NIOFileSystem/FileSystem.swift @@ -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 { - // 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: diff --git a/Sources/NIOFileSystem/FileSystemProtocol.swift b/Sources/NIOFileSystem/FileSystemProtocol.swift index b5bf70143..934220762 100644 --- a/Sources/NIOFileSystem/FileSystemProtocol.swift +++ b/Sources/NIOFileSystem/FileSystemProtocol.swift @@ -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) } } } diff --git a/Sources/NIOFileSystem/IOStrategy.swift b/Sources/NIOFileSystem/IOStrategy.swift new file mode 100644 index 000000000..fcb7fb432 --- /dev/null +++ b/Sources/NIOFileSystem/IOStrategy.swift @@ -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" + } + } +} diff --git a/Sources/NIOFileSystem/Internal/BufferedOrAnyStream.swift b/Sources/NIOFileSystem/Internal/BufferedOrAnyStream.swift index d28b756b9..50e097b93 100644 --- a/Sources/NIOFileSystem/Internal/BufferedOrAnyStream.swift +++ b/Sources/NIOFileSystem/Internal/BufferedOrAnyStream.swift @@ -16,7 +16,7 @@ import NIOCore /// Wraps a ``NIOThrowingAsyncSequenceProducer`` or ``AnyAsyncSequence``. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) -internal enum BufferedOrAnyStream { +internal enum BufferedOrAnyStream: Sendable { typealias AsyncSequenceProducer = NIOThrowingAsyncSequenceProducer< Element, Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, Delegate > @@ -28,7 +28,7 @@ internal enum BufferedOrAnyStream(wrapping stream: S) where S.Element == Element { + internal init(wrapping stream: S) where S.Element == Element { self = .anyAsyncSequence(AnyAsyncSequence(wrapping: stream)) } @@ -69,10 +69,10 @@ internal enum BufferedOrAnyStream: AsyncSequence { - private let _makeAsyncIterator: () -> AsyncIterator +internal struct AnyAsyncSequence: AsyncSequence, Sendable { + private let _makeAsyncIterator: @Sendable () -> AsyncIterator - internal init(wrapping sequence: S) where S.Element == Element { + internal init(wrapping sequence: S) where S.Element == Element { self._makeAsyncIterator = { AsyncIterator(wrapping: sequence.makeAsyncIterator()) } diff --git a/Sources/NIOFileSystem/Internal/BufferedStream.swift b/Sources/NIOFileSystem/Internal/BufferedStream.swift index d450b00b5..0195fd0ef 100644 --- a/Sources/NIOFileSystem/Internal/BufferedStream.swift +++ b/Sources/NIOFileSystem/Internal/BufferedStream.swift @@ -118,7 +118,7 @@ import NIOConcurrencyHelpers /// } /// @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) -internal struct BufferedStream { +internal struct BufferedStream { 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: @unchecked Sendable { let lock: NIOLockedValueBox @@ -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(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( contentsOf sequence: S, onProduceMore: @escaping @Sendable (Result) -> 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(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(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)) } diff --git a/Sources/NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift b/Sources/NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift new file mode 100644 index 000000000..3a998f5b2 --- /dev/null +++ b/Sources/NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift @@ -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> + 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( + _ 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? in + if let nextWaiter = self.waiters.popFirst() { + return nextWaiter + } + + self.tokens += 1 + return nil + }) { + waiter.resume() + } + } +} diff --git a/Sources/NIOFileSystem/Internal/ParallelDirCopy.swift b/Sources/NIOFileSystem/Internal/ParallelDirCopy.swift index 8f1d6b381..ce793264a 100644 --- a/Sources/NIOFileSystem/Internal/ParallelDirCopy.swift +++ b/Sources/NIOFileSystem/Internal/ParallelDirCopy.swift @@ -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 } diff --git a/Sources/NIOFileSystem/Internal/ParallelRemoval.swift b/Sources/NIOFileSystem/Internal/ParallelRemoval.swift new file mode 100644 index 000000000..cd8b6702d --- /dev/null +++ b/Sources/NIOFileSystem/Internal/ParallelRemoval.swift @@ -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 + } + } +} diff --git a/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift b/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift index de5325940..fe0318707 100644 --- a/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift +++ b/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift @@ -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.self)], - options.rawValue - ) - #else libc_fts_open([pointer.baseAddress, nil], options.rawValue) - #endif } } } diff --git a/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift b/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift index dcff57801..e2f5efd32 100644 --- a/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift +++ b/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift @@ -452,21 +452,12 @@ internal func libc_confstr( #endif /// fts(3) -#if os(Android) -internal func libc_fts_open( - _ path: [UnsafeMutablePointer], - _ options: CInt -) -> UnsafeMutablePointer { - fts_open(path, options, nil)! -} -#else internal func libc_fts_open( _ path: [UnsafeMutablePointer?], _ options: CInt ) -> UnsafeMutablePointer { - fts_open(path, options, nil) + fts_open(path, options, nil)! } -#endif /// fts(3) internal func libc_fts_read( diff --git a/Sources/NIOFileSystem/String+FileSystem.swift b/Sources/NIOFileSystem/String+FileSystem.swift new file mode 100644 index 000000000..57e2d51c0 --- /dev/null +++ b/Sources/NIOFileSystem/String+FileSystem.swift @@ -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 + ) + } +} diff --git a/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift b/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift index 8b221d75c..c4240d4ed 100644 --- a/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift +++ b/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift @@ -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 diff --git a/Sources/NIOHTTP1/HTTPDecoder.swift b/Sources/NIOHTTP1/HTTPDecoder.swift index a38c775cf..763319891 100644 --- a/Sources/NIOHTTP1/HTTPDecoder.swift +++ b/Sources/NIOHTTP1/HTTPDecoder.swift @@ -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: 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 diff --git a/Sources/NIOHTTP1/HTTPPipelineSetup.swift b/Sources/NIOHTTP1/HTTPPipelineSetup.swift index a789b8f6a..5e935123c 100644 --- a/Sources/NIOHTTP1/HTTPPipelineSetup.swift +++ b/Sources/NIOHTTP1/HTTPPipelineSetup.swift @@ -84,9 +84,10 @@ extension ChannelPipeline { let future: EventLoopFuture if self.eventLoop.inEventLoop { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) let result = Result { 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 if self.eventLoop.inEventLoop { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) let result = Result { 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 if self.eventLoop.inEventLoop { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) let result = Result { 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 if self.eventLoop.inEventLoop { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) let result = Result { 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() diff --git a/Sources/NIOHTTP1/HTTPTypes.swift b/Sources/NIOHTTP1/HTTPTypes.swift index 321b494d6..92579c9ec 100644 --- a/Sources/NIOHTTP1/HTTPTypes.swift +++ b/Sources/NIOHTTP1/HTTPTypes.swift @@ -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] { diff --git a/Sources/NIOMulticastChat/main.swift b/Sources/NIOMulticastChat/main.swift index 94beddc8f..94316e5ec 100644 --- a/Sources/NIOMulticastChat/main.swift +++ b/Sources/NIOMulticastChat/main.swift @@ -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()) } } diff --git a/Sources/NIOPerformanceTester/main.swift b/Sources/NIOPerformanceTester/main.swift index 13fc75222..48b84d352 100644 --- a/Sources/NIOPerformanceTester/main.swift +++ b/Sources/NIOPerformanceTester/main.swift @@ -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) diff --git a/Sources/NIOPosix/BSDSocketAPICommon.swift b/Sources/NIOPosix/BSDSocketAPICommon.swift index 37f91f403..4e7be4831 100644 --- a/Sources/NIOPosix/BSDSocketAPICommon.swift +++ b/Sources/NIOPosix/BSDSocketAPICommon.swift @@ -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. diff --git a/Sources/NIOPosix/BaseSocket.swift b/Sources/NIOPosix/BaseSocket.swift index 58e20d3e8..5c5ab3ceb 100644 --- a/Sources/NIOPosix/BaseSocket.swift +++ b/Sources/NIOPosix/BaseSocket.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOConcurrencyHelpers import NIOCore diff --git a/Sources/NIOPosix/BaseSocketChannel+SocketOptionProvider.swift b/Sources/NIOPosix/BaseSocketChannel+SocketOptionProvider.swift index c50429abd..47eb8dd11 100644 --- a/Sources/NIOPosix/BaseSocketChannel+SocketOptionProvider.swift +++ b/Sources/NIOPosix/BaseSocketChannel+SocketOptionProvider.swift @@ -15,7 +15,7 @@ import NIOCore extension BaseSocketChannel: SocketOptionProvider { #if !os(Windows) - func unsafeSetSocketOption( + func unsafeSetSocketOption( level: SocketOptionLevel, name: SocketOptionName, value: Value @@ -28,7 +28,7 @@ extension BaseSocketChannel: SocketOptionProvider { } #endif - func unsafeSetSocketOption( + func unsafeSetSocketOption( level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option, value: Value @@ -47,7 +47,10 @@ extension BaseSocketChannel: SocketOptionProvider { } #if !os(Windows) - func unsafeGetSocketOption(level: SocketOptionLevel, name: SocketOptionName) -> EventLoopFuture { + func unsafeGetSocketOption( + level: SocketOptionLevel, + name: SocketOptionName + ) -> EventLoopFuture { unsafeGetSocketOption( level: NIOBSDSocket.OptionLevel(rawValue: CInt(level)), name: NIOBSDSocket.Option(rawValue: CInt(name)) @@ -55,7 +58,7 @@ extension BaseSocketChannel: SocketOptionProvider { } #endif - func unsafeGetSocketOption( + func unsafeGetSocketOption( level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option ) -> EventLoopFuture { diff --git a/Sources/NIOPosix/BaseSocketChannel.swift b/Sources/NIOPosix/BaseSocketChannel.swift index 50668f35a..2a1951531 100644 --- a/Sources/NIOPosix/BaseSocketChannel.swift +++ b/Sources/NIOPosix/BaseSocketChannel.swift @@ -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: SelectableChannel, ChannelCore { +class BaseSocketChannel: 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(_ promise: EventLoopPromise?, _ body: () throws -> Value) { +func executeAndComplete(_ promise: EventLoopPromise?, _ body: () throws -> Value) { do { let result = try body() promise?.succeed(result) diff --git a/Sources/NIOPosix/BaseStreamSocketChannel.swift b/Sources/NIOPosix/BaseStreamSocketChannel.swift index 6f04ecec6..7878415d3 100644 --- a/Sources/NIOPosix/BaseStreamSocketChannel.swift +++ b/Sources/NIOPosix/BaseStreamSocketChannel.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// import NIOCore -class BaseStreamSocketChannel: BaseSocketChannel { +class BaseStreamSocketChannel: BaseSocketChannel, @unchecked Sendable { internal var connectTimeoutScheduled: Optional> private var allowRemoteHalfClosure: Bool = false private var inputShutdown: Bool = false diff --git a/Sources/NIOPosix/Bootstrap.swift b/Sources/NIOPosix/Bootstrap.swift index 174b42ca8..6549ffbb6 100644 --- a/Sources/NIOPosix/Bootstrap.swift +++ b/Sources/NIOPosix/Bootstrap.swift @@ -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 + _ register: @escaping @Sendable (EventLoop, ServerSocketChannel) -> EventLoopFuture ) -> EventLoopFuture { 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)? + private let childChannelInit: (@Sendable (Channel) -> EventLoopFuture)? private let childChannelOptions: ChannelOptions.Storage init( - childChannelInitializer: ((Channel) -> EventLoopFuture)?, + childChannelInitializer: (@Sendable (Channel) -> EventLoopFuture)?, 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 { - self.childChannelOptions.applyAllChannelOptions(to: accepted).flatMap { () -> EventLoopFuture in + childChannelOptions.applyAllChannelOptions(to: accepted).flatMap { () -> EventLoopFuture in childEventLoop.assertInEventLoop() return childChannelInit(accepted) } @@ -471,20 +477,17 @@ public final class ServerBootstrap { @inline(__always) func fireThroughPipeline(_ future: EventLoopFuture, 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 in - let context = loopBoundContext.value - ctxEventLoop.assertInEventLoop() + future.assumeIsolated().flatMap { (_) -> EventLoopFuture 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 + private var resolver: Optional private var bindTarget: Optional 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 { + private static func connect( + freshChannel channel: Channel, + address: SocketAddress, + connectTimeout: TimeAmount + ) -> EventLoopFuture { 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 { - 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` to deliver the `Channel` when connected. public func connect(to address: SocketAddress) -> EventLoopFuture { - 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 { 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 { 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 + _ body: @escaping @Sendable (Channel) -> EventLoopFuture + ) -> EventLoopFuture { + 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, + channelOptions: ChannelOptions.Storage, + bindTarget: SocketAddress?, + _ body: @escaping @Sendable (Channel) -> EventLoopFuture ) -> EventLoopFuture { 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 + _ body: @escaping @Sendable (Channel) -> EventLoopFuture + ) -> EventLoopFuture { + Self.initializeAndRegisterChannel( + channel, + channelInitializer: self.channelInitializer, + channelOptions: self._channelOptions, + bindTarget: self.bindTarget, + body + ) + } + + private static func initializeAndRegisterChannel( + _ channel: SocketChannel, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + channelOptions: ChannelOptions.Storage, + bindTarget: SocketAddress?, + _ body: @escaping @Sendable (Channel) -> EventLoopFuture ) -> EventLoopFuture { - let channelInitializer = self.channelInitializer - let channelOptions = self._channelOptions let eventLoop = channel.eventLoop @inline(__always) + @Sendable func setupChannel() -> EventLoopFuture { 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 ) 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( + func connect( 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( 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( + private func withConnectedSocket< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( eventLoop: EventLoop, socket: NIOBSDSocket.Handle, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, @@ -1390,14 +1484,17 @@ extension ClientBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func initializeAndRegisterNewChannel( + private func initializeAndRegisterNewChannel< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( eventLoop: EventLoop, protocolFamily: NIOBSDSocket.ProtocolFamily, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture< PostRegistrationTransformationResult >, - _ body: @escaping (Channel) -> EventLoopFuture + _ body: @escaping @Sendable (Channel) -> EventLoopFuture ) -> 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( + private static func initializeAndRegisterNewChannel< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( + eventLoop: EventLoop, + protocolFamily: NIOBSDSocket.ProtocolFamily, + enableMPTPCP: Bool, + bootstrapChannelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + channelOptions: ChannelOptions.Storage, + bindTarget: SocketAddress?, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture< + PostRegistrationTransformationResult + >, + _ body: @escaping @Sendable (Channel) -> EventLoopFuture + ) -> 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, registration: @escaping @Sendable (SocketChannel) -> EventLoopFuture, @@ -1424,13 +1564,39 @@ extension ClientBootstrap { PostRegistrationTransformationResult > ) -> EventLoopFuture { - 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, + channelOptions: ChannelOptions.Storage, + bindTarget: SocketAddress?, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + registration: @escaping @Sendable (SocketChannel) -> EventLoopFuture, + postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture< + PostRegistrationTransformationResult + > + ) -> EventLoopFuture { + 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 + _ bringup: @escaping @Sendable (EventLoop, DatagramChannel) -> EventLoopFuture ) -> EventLoopFuture { 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 { 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( + private func connect0( makeSocketAddress: () throws -> SocketAddress, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, 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( + private func bind0( makeSocketAddress: () throws -> SocketAddress, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, 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( + private func makeConfiguredChannel< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, registration: @escaping @Sendable (Channel) -> EventLoopFuture, @@ -2006,9 +2178,14 @@ extension DatagramBootstrap { > ) -> EventLoopFuture { let eventLoop = self.group.next() - let channelInitializer = { (channel: Channel) -> EventLoopFuture 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 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 { 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 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) diff --git a/Sources/NIOPosix/ControlMessage.swift b/Sources/NIOPosix/ControlMessage.swift index 79cf861e5..6e6338e6b 100644 --- a/Sources/NIOPosix/ControlMessage.swift +++ b/Sources/NIOPosix/ControlMessage.swift @@ -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..() -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) + } } } diff --git a/Sources/NIOPosix/HappyEyeballs.swift b/Sources/NIOPosix/HappyEyeballs.swift index 015a8b4af..f1d2e9e3e 100644 --- a/Sources/NIOPosix/HappyEyeballs.swift +++ b/Sources/NIOPosix/HappyEyeballs.swift @@ -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 { +internal struct HappyEyeballsConnector: 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 + ) 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 where ChannelBuilderResult == Void { + self.resolveAndConnect().map { $0.0 } + } +} + +private final class HappyEyeballsConnectorRunner { /// An enum for keeping track of connection state. private enum ConnectionState { /// Initial state. No work outstanding. @@ -205,57 +322,22 @@ internal final class HappyEyeballsConnector { 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 /// 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> - /// 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> - /// 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> - /// 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 { @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 ) { - 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 - ) 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 where ChannelBuilderResult == Void { - self.resolveAndConnect().map { $0.0 } + self.processInput(.resolve) } /// Spin the state machine. @@ -464,7 +481,12 @@ internal final class HappyEyeballsConnector { // 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 { // 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 { /// /// 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 { 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 { /// 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 { 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 { /// - 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 { 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 { } } } - 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 { 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 { } /// 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 { } /// 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 diff --git a/Sources/NIOPosix/IntegerTypes.swift b/Sources/NIOPosix/IntegerTypes.swift index 3ac37dc0b..2a0a1fe3d 100644 --- a/Sources/NIOPosix/IntegerTypes.swift +++ b/Sources/NIOPosix/IntegerTypes.swift @@ -16,7 +16,7 @@ /// A 24-bit unsigned integer value type. @usableFromInline -struct _UInt24 { +struct _UInt24: Sendable { @usableFromInline var _backing: (UInt16, UInt8) @inlinable @@ -65,7 +65,7 @@ extension _UInt24: CustomStringConvertible { // MARK: _UInt56 /// A 56-bit unsigned integer value type. -struct _UInt56 { +struct _UInt56: Sendable { @usableFromInline var _backing: (UInt32, UInt16, UInt8) @inlinable init(_ value: UInt64) { diff --git a/Sources/NIOPosix/LinuxCPUSet.swift b/Sources/NIOPosix/LinuxCPUSet.swift index 6e4af51c4..4ca63931d 100644 --- a/Sources/NIOPosix/LinuxCPUSet.swift +++ b/Sources/NIOPosix/LinuxCPUSet.swift @@ -52,7 +52,7 @@ extension NIOThread { CNIOLinux_CPU_ZERO(&cpuset) let res = self.withUnsafeThreadHandle { p in - CNIOLinux_pthread_getaffinity_np(p, MemoryLayout.size(ofValue: cpuset), &cpuset) + CNIOLinux_pthread_getaffinity_np(p.handle, MemoryLayout.size(ofValue: cpuset), &cpuset) } precondition(res == 0, "pthread_getaffinity_np failed: \(res)") @@ -75,7 +75,7 @@ extension NIOThread { CNIOLinux_CPU_SET(CInt(cpuID), &cpuset) } let res = self.withUnsafeThreadHandle { p in - CNIOLinux_pthread_setaffinity_np(p, MemoryLayout.size(ofValue: cpuset), &cpuset) + CNIOLinux_pthread_setaffinity_np(p.handle, MemoryLayout.size(ofValue: cpuset), &cpuset) } precondition(res == 0, "pthread_setaffinity_np failed: \(res)") } diff --git a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift index b92a4bb01..e6418d891 100644 --- a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift +++ b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift @@ -40,6 +40,9 @@ struct NIORegistration: Registration { var registrationID: SelectorRegistrationID } +@available(*, unavailable) +extension NIORegistration: Sendable {} + private let nextEventLoopGroupID = ManagedAtomic(0) /// Called per `NIOThread` that is created for an EventLoop to do custom initialization of the `NIOThread` before the actual `EventLoop` is run on it. @@ -51,9 +54,6 @@ typealias ThreadInitializer = (NIOThread) -> Void /// all run their own `EventLoop`. Those threads will not be shut down until `shutdownGracefully` or /// `syncShutdownGracefully` is called. /// -/// - Note: It's good style to call `MultiThreadedEventLoopGroup.shutdownGracefully` or -/// `MultiThreadedEventLoopGroup.syncShutdownGracefully` when you no longer need this `EventLoopGroup`. In -/// many cases that is just before your program exits. /// - warning: Unit tests often spawn one `MultiThreadedEventLoopGroup` per unit test to force isolation between the /// tests. In those cases it's important to shut the `MultiThreadedEventLoopGroup` down at the end of the /// test. A good place to start a `MultiThreadedEventLoopGroup` is the `setUp` method of your `XCTestCase` @@ -394,7 +394,7 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { return } - var result: Result = .success(()) + let result: NIOLockedValueBox> = NIOLockedValueBox(.success(())) for loop in self.eventLoops { g.enter() @@ -403,7 +403,9 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { case .success: () case .failure(let error): - result = .failure(error) + result.withLockedValue { + $0 = .failure(error) + } } g.leave() } @@ -421,14 +423,14 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { "MultiThreadedEventLoopGroup in illegal state when closing: \(self.runState)" ) case .closing(let callbacks): - let overallError: Error? = { - switch result { + let overallError: Error? = result.withLockedValue { + switch $0 { case .success: return nil case .failure(let error): return error } - }() + } self.runState = .closed(overallError) return (overallError, callbacks) } @@ -493,9 +495,9 @@ extension MultiThreadedEventLoopGroup: CustomStringConvertible { } @usableFromInline -struct ErasedUnownedJob { +struct ErasedUnownedJob: Sendable { @usableFromInline - let erasedJob: Any + let erasedJob: any Sendable @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) init(job: UnownedJob) { @@ -570,6 +572,12 @@ extension ScheduledTask: Comparable { } } +@available(*, unavailable) +extension ScheduledTask: Sendable {} + +@available(*, unavailable) +extension ScheduledTask.Kind: Sendable {} + extension NIODeadline { @inlinable func readyIn(_ target: NIODeadline) -> TimeAmount { diff --git a/Sources/NIOPosix/NIOThreadPool.swift b/Sources/NIOPosix/NIOThreadPool.swift index 6d3bc08f7..c3196b677 100644 --- a/Sources/NIOPosix/NIOThreadPool.swift +++ b/Sources/NIOPosix/NIOThreadPool.swift @@ -22,7 +22,7 @@ import Dispatch #endif /// Errors that may be thrown when executing work on a `NIOThreadPool` -public enum NIOThreadPoolError { +public enum NIOThreadPoolError: Sendable { /// The `NIOThreadPool` was not active. public struct ThreadPoolInactive: Error { @@ -73,7 +73,7 @@ public final class NIOThreadPool { } @usableFromInline - internal enum State { + internal enum State: Sendable { /// The `NIOThreadPool` is already stopped. case stopped /// The `NIOThreadPool` is shutting down, the array has one boolean entry for each thread indicating if it has shut down already. @@ -87,7 +87,7 @@ public final class NIOThreadPool { /// Whether threads in the pool have work. @usableFromInline - internal enum _WorkState: Hashable { + internal enum _WorkState: Hashable, Sendable { case hasWork case hasNoWork } @@ -138,7 +138,7 @@ public final class NIOThreadPool { self._shutdownGracefully(queue: queue, callback) } - private func _shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) { + private func _shutdownGracefully(queue: DispatchQueue, _ callback: @escaping @Sendable (Error?) -> Void) { guard self.canBeStopped else { queue.async { callback(NIOThreadPoolError.UnsupportedOperation()) @@ -420,11 +420,17 @@ extension NIOThreadPool { /// - body: The closure which performs some blocking work to be done on the thread pool. /// - Returns: The `EventLoopFuture` of `promise` fulfilled with the result (or error) of the passed closure. @preconcurrency - public func runIfActive(eventLoop: EventLoop, _ body: @escaping @Sendable () throws -> T) -> EventLoopFuture { + public func runIfActive( + eventLoop: EventLoop, + _ body: @escaping @Sendable () throws -> T + ) -> EventLoopFuture { self._runIfActive(eventLoop: eventLoop, body) } - private func _runIfActive(eventLoop: EventLoop, _ body: @escaping () throws -> T) -> EventLoopFuture { + private func _runIfActive( + eventLoop: EventLoop, + _ body: @escaping @Sendable () throws -> T + ) -> EventLoopFuture { let promise = eventLoop.makePromise(of: T.self) self.submit { shouldRun in guard case shouldRun = NIOThreadPool.WorkItemState.active else { @@ -441,11 +447,11 @@ extension NIOThreadPool { } /// Runs the submitted closure if the thread pool is still active, otherwise throw an error. - /// The closure will be run on the thread pool so can do blocking work. + /// The closure will be run on the thread pool, such that we can do blocking work. /// /// - Parameters: /// - body: The closure which performs some blocking work to be done on the thread pool. - /// - Returns: result of the passed closure. + /// - Returns: Result of the passed closure. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func runIfActive(_ body: @escaping @Sendable () throws -> T) async throws -> T { let workID = self.nextWorkID.loadThenWrappingIncrement(ordering: .relaxed) @@ -498,20 +504,21 @@ extension NIOThreadPool { } private func _syncShutdownGracefully() throws { - let errorStorageLock = NIOLock() - var errorStorage: Swift.Error? = nil - let continuation = DispatchWorkItem {} + let errorStorageLock = NIOLockedValueBox(nil) + let continuation = ConditionLock(value: 0) self.shutdownGracefully { error in if let error = error { - errorStorageLock.withLock { - errorStorage = error + errorStorageLock.withLockedValue { + $0 = error } } - continuation.perform() + continuation.lock(whenValue: 0) + continuation.unlock(withValue: 1) } - continuation.wait() - try errorStorageLock.withLock { - if let error = errorStorage { + continuation.lock(whenValue: 1) + continuation.unlock() + try errorStorageLock.withLockedValue { + if let error = $0 { throw error } } diff --git a/Sources/NIOPosix/NonBlockingFileIO.swift b/Sources/NIOPosix/NonBlockingFileIO.swift index fe3448d11..b8218e040 100644 --- a/Sources/NIOPosix/NonBlockingFileIO.swift +++ b/Sources/NIOPosix/NonBlockingFileIO.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOConcurrencyHelpers import NIOCore @@ -204,6 +205,7 @@ public struct NonBlockingFileIO: Sendable { let promise = eventLoop.makePromise(of: Void.self) + @Sendable func _read(remainingReads: Int, bytesReadSoFar: Int64) { if remainingReads > 1 || (remainingReads == 1 && lastReadSize > 0) { let readSize = remainingReads > 1 ? chunkSize : lastReadSize @@ -842,7 +844,7 @@ public struct NonBlockingFileIO: Sendable { #if !os(Windows) /// A `NIODirectoryEntry` represents a single directory entry. -public struct NIODirectoryEntry: Hashable { +public struct NIODirectoryEntry: Hashable, Sendable { // File number of entry public var ino: UInt64 // File type diff --git a/Sources/NIOPosix/PendingDatagramWritesManager.swift b/Sources/NIOPosix/PendingDatagramWritesManager.swift index ace953fbc..e9f201ce9 100644 --- a/Sources/NIOPosix/PendingDatagramWritesManager.swift +++ b/Sources/NIOPosix/PendingDatagramWritesManager.swift @@ -13,6 +13,8 @@ //===----------------------------------------------------------------------===// import Atomics +import CNIODarwin +import CNIOLinux import NIOCore private struct PendingDatagramWrite { diff --git a/Sources/NIOPosix/PendingWritesManager.swift b/Sources/NIOPosix/PendingWritesManager.swift index 001b05c21..6e6b3fff7 100644 --- a/Sources/NIOPosix/PendingWritesManager.swift +++ b/Sources/NIOPosix/PendingWritesManager.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import Atomics +import CNIOLinux import NIOCore private struct PendingStreamWrite { diff --git a/Sources/NIOPosix/PipeChannel.swift b/Sources/NIOPosix/PipeChannel.swift index e105a724f..27130a292 100644 --- a/Sources/NIOPosix/PipeChannel.swift +++ b/Sources/NIOPosix/PipeChannel.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// import NIOCore -final class PipeChannel: BaseStreamSocketChannel { +final class PipeChannel: BaseStreamSocketChannel, @unchecked Sendable { private let pipePair: PipePair internal enum Direction { diff --git a/Sources/NIOPosix/PointerHelpers.swift b/Sources/NIOPosix/PointerHelpers.swift deleted file mode 100644 index 918fbf6dd..000000000 --- a/Sources/NIOPosix/PointerHelpers.swift +++ /dev/null @@ -1,41 +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 - -// 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) { - let base = slice.base.baseAddress?.advanced(by: slice.startIndex) - self.init(start: base, count: slice.endIndex &- slice.startIndex) - } - - @inlinable - init(fastRebase slice: Slice) { - 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) { - let base = slice.base.baseAddress?.advanced(by: slice.startIndex) - self.init(start: base, count: slice.endIndex &- slice.startIndex) - } -} diff --git a/Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift b/Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift index 64b53d837..010a06297 100644 --- a/Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift +++ b/Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift @@ -40,7 +40,7 @@ extension NIOSingletons { @discardableResult public static func unsafeTryInstallSingletonPosixEventLoopGroupAsConcurrencyGlobalExecutor() -> Bool { // Guard between the minimum and maximum supported version for the hook - #if compiler(>=5.9) && compiler(<6.2) + #if compiler(>=5.9) && compiler(<6.3) guard #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) else { return false } diff --git a/Sources/NIOPosix/RawSocketBootstrap.swift b/Sources/NIOPosix/RawSocketBootstrap.swift index 72aec18cc..3389bb080 100644 --- a/Sources/NIOPosix/RawSocketBootstrap.swift +++ b/Sources/NIOPosix/RawSocketBootstrap.swift @@ -169,10 +169,10 @@ public final class NIORawSocketBootstrap { private func withNewChannel( makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel, - _ bringup: @escaping (EventLoop, DatagramChannel) -> EventLoopFuture + _ bringup: @escaping @Sendable (EventLoop, DatagramChannel) -> EventLoopFuture ) -> EventLoopFuture { 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 @@ -182,6 +182,7 @@ public final class NIORawSocketBootstrap { return eventLoop.makeFailedFuture(error) } + @Sendable func setupChannel() -> EventLoopFuture { eventLoop.assertInEventLoop() return channelOptions.applyAllChannelOptions(to: channel).flatMap { @@ -255,7 +256,7 @@ extension NIORawSocketBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func connect0( + private func connect0( host: String, ipProtocol: NIOIPProtocol, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, @@ -287,7 +288,7 @@ extension NIORawSocketBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func bind0( + private func bind0( host: String, ipProtocol: NIOIPProtocol, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, @@ -320,7 +321,10 @@ extension NIORawSocketBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func makeConfiguredChannel( + private func makeConfiguredChannel< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, registration: @escaping @Sendable (Channel) -> EventLoopFuture, @@ -329,9 +333,9 @@ extension NIORawSocketBootstrap { > ) -> EventLoopFuture { let eventLoop = self.group.next() - let channelInitializer = { (channel: Channel) -> EventLoopFuture in - let initializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) } - return initializer(channel).flatMap { channelInitializer(channel) } + let bootstrapInitializer = self.channelInitializer ?? { @Sendable _ in eventLoop.makeSucceededFuture(()) } + let channelInitializer = { @Sendable (channel: Channel) -> EventLoopFuture in + bootstrapInitializer(channel).flatMap { channelInitializer(channel) } } let channelOptions = self._channelOptions @@ -342,6 +346,7 @@ extension NIORawSocketBootstrap { return eventLoop.makeFailedFuture(error) } + @Sendable func setupChannel() -> EventLoopFuture { eventLoop.assertInEventLoop() return channelOptions.applyAllChannelOptions(to: channel).flatMap { diff --git a/Sources/NIOPosix/SelectableEventLoop.swift b/Sources/NIOPosix/SelectableEventLoop.swift index 89fc4737f..bfad156e7 100644 --- a/Sources/NIOPosix/SelectableEventLoop.swift +++ b/Sources/NIOPosix/SelectableEventLoop.swift @@ -19,6 +19,22 @@ import NIOConcurrencyHelpers import NIOCore import _NIODataStructures +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))) + } + } +} + /// Execute the given closure and ensure we release all auto pools if needed. @inlinable internal func withAutoReleasePool(_ execute: () throws -> T) rethrows -> T { @@ -60,7 +76,7 @@ public protocol NIOEventLoopMetricsDelegate: Sendable { /// The whole processing of I/O and tasks is done by a `NIOThread` that is tied to the `SelectableEventLoop`. This `NIOThread` /// is guaranteed to never change! @usableFromInline -internal final class SelectableEventLoop: EventLoop { +internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { static let strictModeEnabled: Bool = { switch getenv("SWIFTNIO_STRICT").map({ String.init(cString: $0).lowercased() }) { @@ -298,15 +314,44 @@ internal final class SelectableEventLoop: EventLoop { thread.isCurrent } + /// - see: `EventLoop.now` + @usableFromInline + internal var now: NIODeadline { + .now() + } + /// - see: `EventLoop.scheduleTask(deadline:_:)` @inlinable internal func scheduleTask(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled { let promise: EventLoopPromise = self.makePromise() + let (task, scheduled) = self._prepareToSchedule(deadline: deadline, promise: promise, task: task) + + do { + try self._schedule0(.scheduled(task)) + } catch { + promise.fail(error) + } + + return scheduled + } + + /// - see: `EventLoop.scheduleTask(in:_:)` + @inlinable + internal func scheduleTask(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled { + self.scheduleTask(deadline: .now() + `in`, task) + } + + @inlinable + func _prepareToSchedule( + deadline: NIODeadline, + promise: EventLoopPromise, + task: @escaping () throws -> T + ) -> (ScheduledTask, Scheduled) { let task = ScheduledTask( id: self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed), { do { - promise.succeed(try task()) + promise.assumeIsolatedUnsafeUnchecked().succeed(try task()) } catch let err { promise.fail(err) } @@ -331,9 +376,42 @@ internal final class SelectableEventLoop: EventLoop { // one wakeup. } ) + return (task, scheduled) + } + + @inlinable + func _executeIsolatedUnsafeUnchecked(_ task: @escaping () -> Void) { + // nothing we can do if we fail enqueuing here. + try? self._scheduleIsolated0(.immediate(.function(task))) + } + + @inlinable + func _submitIsolatedUnsafeUnchecked(_ task: @escaping () throws -> T) -> EventLoopFuture { + let promise = self.makePromise(of: T.self) + + self._executeIsolatedUnsafeUnchecked { + do { + // UnsafeUnchecked is allowed here because we know we are on the EL. + promise.assumeIsolatedUnsafeUnchecked().succeed(try task()) + } catch let err { + promise.fail(err) + } + } + + return promise.futureResult + } + + @inlinable + @discardableResult + func _scheduleTaskIsolatedUnsafeUnchecked( + deadline: NIODeadline, + _ task: @escaping () throws -> T + ) -> Scheduled { + let promise: EventLoopPromise = self.makePromise() + let (task, scheduled) = self._prepareToSchedule(deadline: deadline, promise: promise, task: task) do { - try self._schedule0(.scheduled(task)) + try self._scheduleIsolated0(.scheduled(task)) } catch { promise.fail(error) } @@ -341,10 +419,13 @@ internal final class SelectableEventLoop: EventLoop { return scheduled } - /// - see: `EventLoop.scheduleTask(in:_:)` @inlinable - internal func scheduleTask(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled { - scheduleTask(deadline: .now() + `in`, task) + @discardableResult + func _scheduleTaskIsolatedUnsafeUnchecked( + in delay: TimeAmount, + _ task: @escaping () throws -> T + ) -> Scheduled { + self._scheduleTaskIsolatedUnsafeUnchecked(deadline: .now() + delay, task) } // - see: `EventLoop.execute` @@ -366,31 +447,18 @@ internal final class SelectableEventLoop: EventLoop { @usableFromInline internal func _schedule0(_ task: LoopTask) throws { if self.inEventLoop { - precondition( - self._validInternalStateToScheduleTasks, - "BUG IN NIO (please report): EventLoop is shutdown, yet we're on the EventLoop." - ) - - self._tasksLock.withLock { () -> Void in - switch task { - case .scheduled(let task): - self._scheduledTasks.push(task) - case .immediate(let task): - self._immediateTasks.append(task) - } - } + try self._scheduleIsolated0(task) } else { let shouldWakeSelector: Bool = self.externalStateLock.withLock { guard self.validExternalStateToScheduleTasks else { if Self.strictModeEnabled { fatalError("Cannot schedule tasks on an EventLoop that has already shut down.") } - fputs( + printError( """ ERROR: Cannot schedule tasks on an EventLoop that has already shut down. \ This will be upgraded to a forced crash in future SwiftNIO versions.\n - """, - stderr + """ ) return false } @@ -428,6 +496,25 @@ internal final class SelectableEventLoop: EventLoop { } } + /// Add the `ScheduledTask` to be executed. + @usableFromInline + internal func _scheduleIsolated0(_ task: LoopTask) throws { + self.assertInEventLoop() + precondition( + self._validInternalStateToScheduleTasks, + "BUG IN NIO (please report): EventLoop is shutdown, yet we're on the EventLoop." + ) + + self._tasksLock.withLock { () -> Void in + switch task { + case .scheduled(let task): + self._scheduledTasks.push(task) + case .immediate(let task): + self._immediateTasks.append(task) + } + } + } + /// Wake the `Selector` which means `Selector.whenReady(...)` will unblock. @usableFromInline internal func _wakeupSelector() throws { @@ -797,7 +884,10 @@ internal final class SelectableEventLoop: EventLoop { self._succeededVoidFuture = nil } - internal func initiateClose(queue: DispatchQueue, completionHandler: @escaping (Result) -> Void) { + internal func initiateClose( + queue: DispatchQueue, + completionHandler: @escaping @Sendable (Result) -> Void + ) { func doClose() { self.assertInEventLoop() self._parentGroup = nil // break the cycle @@ -876,7 +966,7 @@ internal final class SelectableEventLoop: EventLoop { } @usableFromInline - func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) { + func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping @Sendable (Error?) -> Void) { if self.canBeShutdownIndividually { self.initiateClose(queue: queue) { result in self.syncFinaliseClose(joinThread: false) // This thread was taken over by somebody else @@ -940,12 +1030,18 @@ enum UnderlyingTask { case callback(any NIOScheduledCallbackHandler) } +@available(*, unavailable) +extension UnderlyingTask: Sendable {} + @usableFromInline internal enum LoopTask { case scheduled(ScheduledTask) case immediate(UnderlyingTask) } +@available(*, unavailable) +extension LoopTask: Sendable {} + @inlinable internal func assertExpression(_ body: () -> Bool) { assert( diff --git a/Sources/NIOPosix/SelectorEpoll.swift b/Sources/NIOPosix/SelectorEpoll.swift index 832dc41df..d0dbf09ed 100644 --- a/Sources/NIOPosix/SelectorEpoll.swift +++ b/Sources/NIOPosix/SelectorEpoll.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import NIOConcurrencyHelpers import NIOCore #if !SWIFTNIO_USE_IO_URING diff --git a/Sources/NIOPosix/SelectorGeneric.swift b/Sources/NIOPosix/SelectorGeneric.swift index cb2626c76..e2f7197fa 100644 --- a/Sources/NIOPosix/SelectorGeneric.swift +++ b/Sources/NIOPosix/SelectorGeneric.swift @@ -20,7 +20,7 @@ import CNIOLinux #endif @usableFromInline -internal enum SelectorLifecycleState { +internal enum SelectorLifecycleState: Sendable { case open case closing case closed @@ -60,7 +60,7 @@ extension timespec { /// If then suddenly the socket becomes both readable and writable, the eventing mechanism will tell you about that /// fact using `[.read, .write]`. @usableFromInline -struct SelectorEventSet: OptionSet, Equatable { +struct SelectorEventSet: OptionSet, Equatable, Sendable { @usableFromInline typealias RawValue = UInt8 @@ -404,6 +404,9 @@ extension Selector: CustomStringConvertible { } } +@available(*, unavailable) +extension Selector: Sendable {} + /// An event that is triggered once the `Selector` was able to select something. @usableFromInline struct SelectorEvent { @@ -422,6 +425,9 @@ struct SelectorEvent { } } +@available(*, unavailable) +extension SelectorEvent: Sendable {} + extension Selector where R == NIORegistration { /// Gently close the `Selector` after all registered `Channel`s are closed. func closeGently(eventLoop: EventLoop) -> EventLoopFuture { @@ -473,7 +479,7 @@ extension Selector where R == NIORegistration { /// The strategy used for the `Selector`. @usableFromInline -enum SelectorStrategy { +enum SelectorStrategy: Sendable { /// Block until there is some IO ready to be processed or the `Selector` is explicitly woken up. case block @@ -489,7 +495,7 @@ enum SelectorStrategy { /// to mark events to allow for filtering of received return values to not be delivered to a /// new `Registration` instance that receives the same file descriptor. Ok if it wraps. /// Needed for i.e. testWeDoNotDeliverEventsForPreviouslyClosedChannels to succeed. -@usableFromInline struct SelectorRegistrationID: Hashable { +@usableFromInline struct SelectorRegistrationID: Hashable, Sendable { @usableFromInline var _rawValue: UInt32 @inlinable var rawValue: UInt32 { diff --git a/Sources/NIOPosix/SelectorKqueue.swift b/Sources/NIOPosix/SelectorKqueue.swift index 4c45dd159..34651bd49 100644 --- a/Sources/NIOPosix/SelectorKqueue.swift +++ b/Sources/NIOPosix/SelectorKqueue.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import NIOConcurrencyHelpers import NIOCore #if canImport(Darwin) diff --git a/Sources/NIOPosix/Socket.swift b/Sources/NIOPosix/Socket.swift index 1535e42d0..6ae3de3c5 100644 --- a/Sources/NIOPosix/Socket.swift +++ b/Sources/NIOPosix/Socket.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOCore /// The container used for writing multiple buffers via `writev`. @@ -22,7 +23,7 @@ class Socket: BaseSocket, SocketProtocol { typealias SocketType = Socket /// The maximum number of bytes to write per `writev` call. - static var writevLimitBytes = Int(Int32.max) + static let writevLimitBytes = Int(Int32.max) /// The maximum number of `IOVector`s to write per `writev` call. static let writevLimitIOVectors: Int = Posix.UIO_MAXIOV diff --git a/Sources/NIOPosix/SocketChannel.swift b/Sources/NIOPosix/SocketChannel.swift index e1a9a473c..fd51c008c 100644 --- a/Sources/NIOPosix/SocketChannel.swift +++ b/Sources/NIOPosix/SocketChannel.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOCore #if os(Windows) @@ -49,7 +50,7 @@ extension ByteBuffer { /// A `Channel` for a client socket. /// /// - Note: All operations on `SocketChannel` are thread-safe. -final class SocketChannel: BaseStreamSocketChannel { +final class SocketChannel: BaseStreamSocketChannel, @unchecked Sendable { private var connectTimeout: TimeAmount? = nil init(eventLoop: SelectableEventLoop, protocolFamily: NIOBSDSocket.ProtocolFamily, enableMPTCP: Bool = false) throws @@ -191,7 +192,7 @@ final class SocketChannel: BaseStreamSocketChannel { /// A `Channel` for a server socket. /// /// - Note: All operations on `ServerSocketChannel` are thread-safe. -final class ServerSocketChannel: BaseSocketChannel { +final class ServerSocketChannel: BaseSocketChannel, @unchecked Sendable { private var backlog: Int32 = 128 private let group: EventLoopGroup @@ -450,7 +451,7 @@ final class ServerSocketChannel: BaseSocketChannel { /// A channel used with datagram sockets. /// /// Currently, it does not support connected mode which is well worth adding. -final class DatagramChannel: BaseSocketChannel { +final class DatagramChannel: BaseSocketChannel, @unchecked Sendable { private var reportExplicitCongestionNotifications = false private var receivePacketInfo = false diff --git a/Sources/NIOPosix/System.swift b/Sources/NIOPosix/System.swift index adb7cb2ff..b320f20ce 100644 --- a/Sources/NIOPosix/System.swift +++ b/Sources/NIOPosix/System.swift @@ -86,15 +86,17 @@ let S_IFBLK = UInt32(SwiftGlibc.S_IFBLK) private let sysClose = close private let sysShutdown = shutdown private let sysBind = bind -private let sysFcntl: (CInt, CInt, CInt) -> CInt = fcntl +private let sysFcntl: @Sendable @convention(c) (CInt, CInt, CInt) -> CInt = { fcntl($0, $1, $2) } private let sysSocket = socket private let sysSetsockopt = setsockopt private let sysGetsockopt = getsockopt private let sysListen = listen private let sysAccept = accept private let sysConnect = connect -private let sysOpen: (UnsafePointer, CInt) -> CInt = open -private let sysOpenWithMode: (UnsafePointer, CInt, mode_t) -> CInt = open +private let sysOpen: @Sendable @convention(c) (UnsafePointer, CInt) -> CInt = { open($0, $1) } +private let sysOpenWithMode: @Sendable @convention(c) (UnsafePointer, CInt, mode_t) -> CInt = { + open($0, $1, $2) +} private let sysFtruncate = ftruncate private let sysWrite = write private let sysPwrite = pwrite @@ -124,12 +126,20 @@ private let sysWritev = sysWritev_wrapper #elseif !os(Windows) private let sysWritev: @convention(c) (Int32, UnsafePointer?, CInt) -> CLong = writev #endif -#if !os(Windows) +#if canImport(Android) +private let sysRecvMsg: @convention(c) (CInt, UnsafeMutablePointer, CInt) -> ssize_t = recvmsg +private let sysSendMsg: @convention(c) (CInt, UnsafePointer, CInt) -> ssize_t = sendmsg +#elseif !os(Windows) private let sysRecvMsg: @convention(c) (CInt, UnsafeMutablePointer?, CInt) -> ssize_t = recvmsg private let sysSendMsg: @convention(c) (CInt, UnsafePointer?, CInt) -> ssize_t = sendmsg #endif private let sysDup: @convention(c) (CInt) -> CInt = dup -#if !os(Windows) +#if canImport(Android) +private let sysGetpeername: + @convention(c) (CInt, UnsafeMutablePointer, UnsafeMutablePointer) -> CInt = getpeername +private let sysGetsockname: + @convention(c) (CInt, UnsafeMutablePointer, UnsafeMutablePointer) -> CInt = getsockname +#elseif !os(Windows) private let sysGetpeername: @convention(c) (CInt, UnsafeMutablePointer?, UnsafeMutablePointer?) -> CInt = getpeername private let sysGetsockname: @@ -141,7 +151,9 @@ private let sysIfNameToIndex: @convention(c) (UnsafePointer) -> CUnsigned #else private let sysIfNameToIndex: @convention(c) (UnsafePointer?) -> CUnsignedInt = if_nametoindex #endif -#if !os(Windows) +#if canImport(Android) +private let sysSocketpair: @convention(c) (CInt, CInt, CInt, UnsafeMutablePointer) -> CInt = socketpair +#elseif !os(Windows) private let sysSocketpair: @convention(c) (CInt, CInt, CInt, UnsafeMutablePointer?) -> CInt = socketpair #endif @@ -434,7 +446,7 @@ internal func syscallForbiddingEINVAL( } @usableFromInline -internal enum Posix { +internal enum Posix: Sendable { #if canImport(Darwin) @usableFromInline static let UIO_MAXIOV: Int = 1024 @@ -1000,7 +1012,7 @@ internal enum Posix { socketVector: UnsafeMutablePointer? ) throws { _ = try syscall(blocking: false) { - sysSocketpair(domain.rawValue, type.rawValue, protocolSubtype.rawValue, socketVector) + sysSocketpair(domain.rawValue, type.rawValue, protocolSubtype.rawValue, socketVector!) } } #endif @@ -1049,7 +1061,7 @@ extension Posix { #if canImport(Darwin) @usableFromInline -internal enum KQueue { +internal enum KQueue: Sendable { // TODO: Figure out how to specify a typealias to the kevent struct without run into trouble with the swift compiler diff --git a/Sources/NIOPosix/Thread.swift b/Sources/NIOPosix/Thread.swift index 565b775ef..ab5afb979 100644 --- a/Sources/NIOPosix/Thread.swift +++ b/Sources/NIOPosix/Thread.swift @@ -21,7 +21,7 @@ enum LowLevelThreadOperations { } protocol ThreadOps { - associatedtype ThreadHandle + associatedtype ThreadHandle: Sendable associatedtype ThreadSpecificKey associatedtype ThreadSpecificKeyDestructor @@ -41,7 +41,7 @@ protocol ThreadOps { /// /// All methods exposed are thread-safe. @usableFromInline -final class NIOThread { +final class NIOThread: Sendable { internal typealias ThreadBoxValue = (body: (NIOThread) -> Void, name: String?) internal typealias ThreadBox = Box diff --git a/Sources/NIOPosix/ThreadPosix.swift b/Sources/NIOPosix/ThreadPosix.swift index f876c42c8..9da877516 100644 --- a/Sources/NIOPosix/ThreadPosix.swift +++ b/Sources/NIOPosix/ThreadPosix.swift @@ -74,8 +74,27 @@ private func sysPthread_create( typealias ThreadOpsSystem = ThreadOpsPosix +struct PthreadWrapper: @unchecked Sendable { + var handle: pthread_t +} + +extension Optional where Wrapped == PthreadWrapper { + mutating func withHandlePointer< + ReturnValue + >( + _ body: (UnsafeMutablePointer) throws -> ReturnValue + ) rethrows -> ReturnValue { + var handle = self?.handle + defer { + self = handle.map { PthreadWrapper(handle: $0) } + } + + return try body(&handle) + } +} + enum ThreadOpsPosix: ThreadOps { - typealias ThreadHandle = pthread_t + typealias ThreadHandle = PthreadWrapper typealias ThreadSpecificKey = pthread_key_t #if canImport(Darwin) typealias ThreadSpecificKeyDestructor = @convention(c) (UnsafeMutableRawPointer) -> Void @@ -89,7 +108,7 @@ enum ThreadOpsPosix: ThreadOps { // anyway. var chars: [CChar] = Array(repeating: 0, count: 64) return chars.withUnsafeMutableBufferPointer { ptr in - guard sys_pthread_getname_np(thread, ptr.baseAddress!, ptr.count) == 0 else { + guard sys_pthread_getname_np(thread.handle, ptr.baseAddress!, ptr.count) == 0 else { return nil } @@ -105,60 +124,61 @@ enum ThreadOpsPosix: ThreadOps { detachThread: Bool ) { let argv0 = Unmanaged.passRetained(args).toOpaque() - let res = sysPthread_create( - handle: &handle, - destructor: { - // Cast to UnsafeMutableRawPointer? and force unwrap to make the - // same code work on macOS and Linux. - let boxed = Unmanaged - .fromOpaque(($0 as UnsafeMutableRawPointer?)!) - .takeRetainedValue() - let (body, name) = (boxed.value.body, boxed.value.name) - let hThread: ThreadOpsSystem.ThreadHandle = pthread_self() + let res = handle.withHandlePointer { handlePtr in + sysPthread_create( + handle: handlePtr, + destructor: { + // Cast to UnsafeMutableRawPointer? and force unwrap to make the + // same code work on macOS and Linux. + let boxed = Unmanaged + .fromOpaque(($0 as UnsafeMutableRawPointer?)!) + .takeRetainedValue() + let (body, name) = (boxed.value.body, boxed.value.name) + let hThread: ThreadOpsSystem.ThreadHandle = PthreadWrapper(handle: pthread_self()) - if let name = name { - let maximumThreadNameLength: Int - #if os(Linux) || os(Android) - maximumThreadNameLength = 15 - #else - maximumThreadNameLength = .max - #endif - name.prefix(maximumThreadNameLength).withCString { namePtr in - // this is non-critical so we ignore the result here, we've seen - // EPERM in containers. - _ = sys_pthread_setname_np(hThread, namePtr) + if let name = name { + let maximumThreadNameLength: Int + #if os(Linux) || os(Android) + maximumThreadNameLength = 15 + #else + maximumThreadNameLength = .max + #endif + name.prefix(maximumThreadNameLength).withCString { namePtr in + // this is non-critical so we ignore the result here, we've seen + // EPERM in containers. + _ = sys_pthread_setname_np(hThread.handle, namePtr) + } } - } - body(NIOThread(handle: hThread, desiredName: name)) + body(NIOThread(handle: hThread, desiredName: name)) - #if os(Android) - return UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! - #else - return nil - #endif - }, - args: argv0 - ) + #if os(Android) + return UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! + #else + return nil + #endif + }, + args: argv0 + ) + } precondition(res == 0, "Unable to create thread: \(res)") if detachThread { - let detachError = pthread_detach(handle!) + let detachError = pthread_detach(handle!.handle) precondition(detachError == 0, "pthread_detach failed with error \(detachError)") } - } static func isCurrentThread(_ thread: ThreadOpsSystem.ThreadHandle) -> Bool { - pthread_equal(thread, pthread_self()) != 0 + pthread_equal(thread.handle, pthread_self()) != 0 } static var currentThread: ThreadOpsSystem.ThreadHandle { - pthread_self() + PthreadWrapper(handle: pthread_self()) } static func joinThread(_ thread: ThreadOpsSystem.ThreadHandle) { - let err = pthread_join(thread, nil) + let err = pthread_join(thread.handle, nil) assert(err == 0, "pthread_join failed with \(err)") } @@ -184,7 +204,7 @@ enum ThreadOpsPosix: ThreadOps { } static func compareThreads(_ lhs: ThreadOpsSystem.ThreadHandle, _ rhs: ThreadOpsSystem.ThreadHandle) -> Bool { - pthread_equal(lhs, rhs) != 0 + pthread_equal(lhs.handle, rhs.handle) != 0 } } diff --git a/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift b/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift index 75d95c5a4..0911efa95 100644 --- a/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift +++ b/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift @@ -39,7 +39,8 @@ import NIOCore /// specify a type that must be returned from the supplied closure. The result will then be used to succeed the ``NIOTypedApplicationProtocolNegotiationHandler/protocolNegotiationResult`` /// promise. This allows us to construct pipelines that include protocol negotiation handlers and be able to bridge them into `NIOAsyncChannel` /// based bootstraps. -public final class NIOTypedApplicationProtocolNegotiationHandler: ChannelInboundHandler, +@preconcurrency +public final class NIOTypedApplicationProtocolNegotiationHandler: ChannelInboundHandler, RemovableChannelHandler { public typealias InboundIn = Any diff --git a/Sources/NIOUDPEchoClient/main.swift b/Sources/NIOUDPEchoClient/main.swift index 3a74de9d0..9d131b889 100644 --- a/Sources/NIOUDPEchoClient/main.swift +++ b/Sources/NIOUDPEchoClient/main.swift @@ -115,7 +115,7 @@ default: connectTarget = .ip(host: defaultHost, sendPort: defaultServerPort, listeningPort: defaultListeningPort) } -let remoteAddress = { () -> SocketAddress in +let remoteAddress = { @Sendable () -> SocketAddress in switch connectTarget { case .ip(let host, let sendPort, _): return try SocketAddress.makeAddressResolvingHost(host, port: sendPort) @@ -129,7 +129,9 @@ let bootstrap = DatagramBootstrap(group: group) // Enable SO_REUSEADDR. .channelOption(.socketOption(.so_reuseaddr), value: 1) .channelInitializer { channel in - channel.pipeline.addHandler(EchoHandler(remoteAddressInitializer: remoteAddress)) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(EchoHandler(remoteAddressInitializer: remoteAddress)) + } } defer { try! group.syncShutdownGracefully() diff --git a/Sources/NIOUDPEchoServer/main.swift b/Sources/NIOUDPEchoServer/main.swift index a33de6780..f8dd50857 100644 --- a/Sources/NIOUDPEchoServer/main.swift +++ b/Sources/NIOUDPEchoServer/main.swift @@ -47,8 +47,9 @@ var bootstrap = DatagramBootstrap(group: group) // Set the handlers that are applied to the bound channel .channelInitializer { channel in - // Ensure we don't read faster than we can write by adding the BackPressureHandler into the pipeline. - channel.pipeline.addHandler(EchoHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(EchoHandler()) + } } defer { diff --git a/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift b/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift index a25e69df9..e8f1b5ca4 100644 --- a/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift +++ b/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift @@ -149,7 +149,7 @@ extension NIOWebSocketClientUpgrader { UInt64.random(in: UInt64.min...UInt64.max, using: &generator), UInt64.random(in: UInt64.min...UInt64.max, using: &generator) ) - return String(base64Encoding: buffer.readableBytesView) + return String(_base64Encoding: buffer.readableBytesView) } /// Generates a random WebSocket Request Key by generating 16 bytes randomly using the `SystemRandomNumberGenerator` and encoding them as a base64 string as defined in RFC6455 https://tools.ietf.org/html/rfc6455#section-4.1. /// - Returns: base64 encoded request key @@ -179,7 +179,7 @@ private func _shouldAllowUpgrade(upgradeResponse: HTTPResponseHead, requestKey: var hasher = SHA1() hasher.update(string: requestKey) hasher.update(string: magicWebSocketGUID) - let expectedAcceptValue = String(base64Encoding: hasher.finish()) + let expectedAcceptValue = String(_base64Encoding: hasher.finish()) return expectedAcceptValue == acceptValueHeader[0] } @@ -199,7 +199,7 @@ private func _upgrade( ByteToMessageHandler(WebSocketFrameDecoder(maxFrameSize: maxFrameSize)) ) if enableAutomaticErrorHandling { - try channel.pipeline.syncOperations.addHandler(WebSocketProtocolErrorHandler()) + try channel.pipeline.syncOperations.addHandler(WebSocketProtocolErrorHandler(isServer: false)) } } .flatMap { diff --git a/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift b/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift index 8aa16eec7..14e3c7261 100644 --- a/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift +++ b/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift @@ -15,6 +15,7 @@ import CNIOSHA1 import NIOCore import NIOHTTP1 +import _NIOBase64 let magicWebSocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" @@ -61,11 +62,8 @@ extension HTTPHeaders { /// /// This upgrader assumes that the `HTTPServerUpgradeHandler` will appropriately mutate the pipeline to /// remove the HTTP `ChannelHandler`s. -public final class NIOWebSocketServerUpgrader: HTTPServerProtocolUpgrader, @unchecked Sendable { - // This type *is* Sendable but we can't express that properly until Swift 5.7. In the meantime - // the conformance is `@unchecked`. +public final class NIOWebSocketServerUpgrader: HTTPServerProtocolUpgrader, Sendable { - // FIXME: remove @unchecked when 5.7 is the minimum supported version. private typealias ShouldUpgrade = @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture private typealias UpgradePipelineHandler = @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture /// RFC 6455 specs this as the required entry in the Upgrade header. @@ -303,7 +301,7 @@ private func _buildUpgradeResponse( var hasher = SHA1() hasher.update(string: key) hasher.update(string: magicWebSocketGUID) - acceptValue = String(base64Encoding: hasher.finish()) + acceptValue = String(_base64Encoding: hasher.finish()) } extraHeaders.replaceOrAdd(name: "Upgrade", value: "websocket") diff --git a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift index e367184b6..6c63126e9 100644 --- a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift +++ b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift @@ -22,7 +22,20 @@ public final class WebSocketProtocolErrorHandler: ChannelInboundHandler { public typealias InboundIn = Never public typealias OutboundOut = WebSocketFrame - public init() {} + /// Indicate that this `ChannelHandeler` is used by a WebSocket server or client. Default is true. + private let isServer: Bool + + public init() { + self.isServer = true + } + + /// Initialize this `ChannelHandler` to be used by a WebSocket server or client. + /// + /// - Parameters: + /// - isServer: indicate whether this `ChannelHandler` is used by a WebSocket server or client. + public init(isServer: Bool) { + self.isServer = isServer + } public func errorCaught(context: ChannelHandlerContext, error: Error) { let loopBoundContext = context.loopBound @@ -32,6 +45,7 @@ public final class WebSocketProtocolErrorHandler: ChannelInboundHandler { let frame = WebSocketFrame( fin: true, opcode: .connectionClose, + maskKey: self.makeMaskingKey(), data: data ) context.writeAndFlush(Self.wrapOutboundOut(frame)).whenComplete { (_: Result) in @@ -44,6 +58,12 @@ public final class WebSocketProtocolErrorHandler: ChannelInboundHandler { // forward the error on to let others see it. context.fireErrorCaught(error) } + + private func makeMaskingKey() -> WebSocketMaskingKey? { + // According to RFC 6455 Section 5, a client *must* mask all frames that it sends to the server. + // A server *must not* mask any frames that it sends to the client + self.isServer ? nil : .random() + } } @available(*, unavailable) diff --git a/Sources/_NIOBase64/Base64.swift b/Sources/_NIOBase64/Base64.swift index dc001f85b..15bf79e3b 100644 --- a/Sources/_NIOBase64/Base64.swift +++ b/Sources/_NIOBase64/Base64.swift @@ -16,15 +16,27 @@ // https://github.com/fabianfett/swift-base64-kit extension String { + /// Base64 encode a collection of UInt8 to a string, without the use of Foundation. + @available(*, deprecated, message: "This API was unintentionally made public.") + @inlinable + public init(base64Encoding bytes: Buffer) where Buffer.Element == UInt8 { + self.init(_base64Encoding: bytes) + } + + @available(*, deprecated, message: "This API was unintentionally made public.") + @inlinable + public func base64Decoded() throws -> [UInt8] { + try self._base64Decoded() + } /// Base64 encode a collection of UInt8 to a string, without the use of Foundation. @inlinable - public init(base64Encoding bytes: Buffer) where Buffer.Element == UInt8 { + public init(_base64Encoding bytes: Buffer) where Buffer.Element == UInt8 { self = Base64.encode(bytes: bytes) } @inlinable - public func base64Decoded() throws -> [UInt8] { + public func _base64Decoded() throws -> [UInt8] { try Base64.decode(string: self) } } diff --git a/Tests/NIOBase64Tests/Base64Test.swift b/Tests/NIOBase64Tests/Base64Test.swift index dd6262a9d..5c320706b 100644 --- a/Tests/NIOBase64Tests/Base64Test.swift +++ b/Tests/NIOBase64Tests/Base64Test.swift @@ -13,59 +13,58 @@ //===----------------------------------------------------------------------===// import XCTest - -@testable import _NIOBase64 +import _NIOBase64 class Base64Test: XCTestCase { func testEncodeEmptyData() throws { let data = [UInt8]() - let encodedData = String(base64Encoding: data) + let encodedData = String(_base64Encoding: data) XCTAssertEqual(encodedData.count, 0) } func testBase64EncodingOfEmptyString() throws { let string = "" - let encoded = String(base64Encoding: string.utf8) + let encoded = String(_base64Encoding: string.utf8) XCTAssertEqual(encoded, "") } func testBase64DecodingOfEmptyString() throws { let encoded = "" XCTAssertNoThrow { - let decoded = try encoded.base64Decoded() + let decoded = try encoded._base64Decoded() XCTAssertEqual(decoded, [UInt8]()) } } func testBase64EncodingArrayOfNulls() throws { let data = Array(repeating: UInt8(0), count: 10) - let encodedData = String(base64Encoding: data) + let encodedData = String(_base64Encoding: data) XCTAssertEqual(encodedData, "AAAAAAAAAAAAAA==") } func testBase64DecodeArrayOfNulls() throws { let encoded = "AAAAAAAAAAAAAA==" - let decoded = try! encoded.base64Decoded() + let decoded = try! encoded._base64Decoded() let expected = Array(repeating: UInt8(0), count: 10) XCTAssertEqual(decoded, expected) } func testBase64EncodeingHelloWorld() throws { let string = "Hello, world!" - let encoded = String(base64Encoding: string.utf8) + let encoded = String(_base64Encoding: string.utf8) let expected = "SGVsbG8sIHdvcmxkIQ==" XCTAssertEqual(encoded, expected) } func testBase64DecodeHelloWorld() throws { let encoded = "SGVsbG8sIHdvcmxkIQ==" - let decoded = try! encoded.base64Decoded() + let decoded = try! encoded._base64Decoded() XCTAssertEqual(decoded, "Hello, world!".utf8.map { UInt8($0) }) } func testBase64EncodingAllTheBytesSequentially() throws { let data = Array(UInt8(0)...UInt8(255)) - let encodedData = String(base64Encoding: data) + let encodedData = String(_base64Encoding: data) XCTAssertEqual( encodedData, "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==" @@ -74,14 +73,14 @@ class Base64Test: XCTestCase { func testBase64DecodingWithInvalidLength() { let encoded = "dGVzbA!==" - XCTAssertThrowsError(try encoded.base64Decoded()) { error in + XCTAssertThrowsError(try encoded._base64Decoded()) { error in XCTAssertEqual(error as? Base64Error, .invalidLength) } } func testBase64DecodeWithInvalidCharacter() throws { let encoded = "SGVsbG8sI_dvcmxkIQ==" - XCTAssertThrowsError(try encoded.base64Decoded()) { error in + XCTAssertThrowsError(try encoded._base64Decoded()) { error in XCTAssertEqual(error as? Base64Error, .invalidCharacter) } } diff --git a/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift b/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift index 53864db0f..bb0622262 100644 --- a/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift +++ b/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift @@ -22,8 +22,8 @@ import XCTest import Darwin #elseif canImport(Glibc) import Glibc -#elseif canImport(Bionic) -import Bionic +#elseif canImport(Android) +import Android #else #error("The Concurrency helpers test module was unable to identify your C library.") #endif diff --git a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift index 31c680b8b..848c65f86 100644 --- a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift +++ b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift @@ -606,6 +606,50 @@ final class NIOAsyncWriterTests: XCTestCase { self.assert(suspendCallCount: 1, yieldCallCount: 1, terminateCallCount: 1) } + func testSuspendingBufferedYield_whenWriterFinished() async throws { + self.sink.setWritability(to: false) + + let bothSuspended = expectation(description: "suspended on both yields") + let suspendedAgain = ConditionLock(value: false) + self.delegate.didSuspendHandler = { + if self.delegate.didSuspendCallCount == 2 { + bothSuspended.fulfill() + } else if self.delegate.didSuspendCallCount > 2 { + suspendedAgain.lock() + suspendedAgain.unlock(withValue: true) + } + } + + self.delegate.didYieldHandler = { _ in + if self.delegate.didYieldCallCount == 1 { + // Delay this yield until the other yield is suspended again. + suspendedAgain.lock(whenValue: true) + suspendedAgain.unlock() + } + } + + let task1 = Task { [writer] in + try await writer!.yield("message1") + } + let task2 = Task { [writer] in + try await writer!.yield("message2") + } + + await fulfillment(of: [bothSuspended], timeout: 1) + self.writer.finish() + + self.assert(suspendCallCount: 2, yieldCallCount: 0, terminateCallCount: 0) + + // We have to become writable again to unbuffer the yields + // The first call to didYield will pause, so that the other yield will be suspended again. + self.sink.setWritability(to: true) + + await XCTAssertNoThrow(try await task1.value) + await XCTAssertNoThrow(try await task2.value) + + self.assert(suspendCallCount: 3, yieldCallCount: 2, terminateCallCount: 1) + } + func testWriterFinish_whenFinished() { // This tests just checks that finishing again is a no-op self.writer.finish() diff --git a/Tests/NIOCoreTests/ByteBufferTest.swift b/Tests/NIOCoreTests/ByteBufferTest.swift index 6be0ce37a..91e0ac0df 100644 --- a/Tests/NIOCoreTests/ByteBufferTest.swift +++ b/Tests/NIOCoreTests/ByteBufferTest.swift @@ -3499,6 +3499,29 @@ extension ByteBufferTest { } +// MARK: - Int / FixedWidthInteger init +extension ByteBufferTest { + func testCreateIntegersFromByteBuffer() { + let uint32BufferLE = ByteBuffer(bytes: [0x04, 0x03, 0x02, 0x01]) + let uint32BufferBE = ByteBuffer(bytes: [0x01, 0x02, 0x03, 0x04]) + let tooSmallInt32Buffer = ByteBuffer(bytes: [0x01, 0x02, 0x03]) + + XCTAssertEqual(Int32(buffer: uint32BufferLE, endianness: .little), 0x0102_0304) + XCTAssertEqual(Int32(buffer: uint32BufferBE, endianness: .big), 0x0102_0304) + XCTAssertNil(Int32(buffer: tooSmallInt32Buffer)) + + let uint64BufferLE = ByteBuffer(bytes: [0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01]) + let uint64BufferBE = ByteBuffer(bytes: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) + let tooSmallInt64Buffer = ByteBuffer(bytes: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]) + let tooBigInt64Buffer = ByteBuffer(bytes: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09]) + + XCTAssertEqual(Int64(buffer: uint64BufferLE, endianness: .little), 0x0102_0304_0506_0708) + XCTAssertEqual(Int64(buffer: uint64BufferBE, endianness: .big), 0x0102_0304_0506_0708) + XCTAssertNil(Int64(buffer: tooSmallInt64Buffer)) + XCTAssertNil(Int64(buffer: tooBigInt64Buffer)) + } +} + // MARK: - DispatchData init extension ByteBufferTest { diff --git a/Tests/NIOCoreTests/TimeAmountTests.swift b/Tests/NIOCoreTests/TimeAmountTests.swift index 0cf762a1d..1285b7584 100644 --- a/Tests/NIOCoreTests/TimeAmountTests.swift +++ b/Tests/NIOCoreTests/TimeAmountTests.swift @@ -11,9 +11,11 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -import NIOCore + import XCTest +@testable import NIOCore + class TimeAmountTests: XCTestCase { func testTimeAmountConversion() { XCTAssertEqual(TimeAmount.nanoseconds(3), .nanoseconds(3)) @@ -61,4 +63,103 @@ class TimeAmountTests: XCTestCase { XCTAssertEqual(TimeAmount.minutes(.min), underflowCap) XCTAssertEqual(TimeAmount.hours(.min), underflowCap) } + + func testTimeAmountParsing() throws { + // Test all supported hour formats + XCTAssertEqual(try TimeAmount("2h"), .hours(2)) + XCTAssertEqual(try TimeAmount("2hr"), .hours(2)) + XCTAssertEqual(try TimeAmount("2hrs"), .hours(2)) + + // Test all supported minute formats + XCTAssertEqual(try TimeAmount("3m"), .minutes(3)) + XCTAssertEqual(try TimeAmount("3min"), .minutes(3)) + + // Test all supported second formats + XCTAssertEqual(try TimeAmount("4s"), .seconds(4)) + XCTAssertEqual(try TimeAmount("4sec"), .seconds(4)) + XCTAssertEqual(try TimeAmount("4secs"), .seconds(4)) + + // Test all supported millisecond formats + XCTAssertEqual(try TimeAmount("5ms"), .milliseconds(5)) + XCTAssertEqual(try TimeAmount("5millis"), .milliseconds(5)) + + // Test all supported microsecond formats + XCTAssertEqual(try TimeAmount("6us"), .microseconds(6)) + XCTAssertEqual(try TimeAmount("6µs"), .microseconds(6)) + XCTAssertEqual(try TimeAmount("6micros"), .microseconds(6)) + + // Test all supported nanosecond formats + XCTAssertEqual(try TimeAmount("7ns"), .nanoseconds(7)) + XCTAssertEqual(try TimeAmount("7nanos"), .nanoseconds(7)) + } + + func testTimeAmountParsingWithWhitespace() throws { + XCTAssertEqual(try TimeAmount("5 s"), .seconds(5)) + XCTAssertEqual(try TimeAmount("100 ms"), .milliseconds(100)) + XCTAssertEqual(try TimeAmount("42 ns"), .nanoseconds(42)) + XCTAssertEqual(try TimeAmount(" 5s "), .seconds(5)) + } + + func testTimeAmountParsingCaseInsensitive() throws { + XCTAssertEqual(try TimeAmount("5S"), .seconds(5)) + XCTAssertEqual(try TimeAmount("100MS"), .milliseconds(100)) + XCTAssertEqual(try TimeAmount("1HR"), .hours(1)) + XCTAssertEqual(try TimeAmount("30MIN"), .minutes(30)) + } + + func testTimeAmountParsingInvalidInput() throws { + // Empty string + XCTAssertThrowsError(try TimeAmount("")) { error in + XCTAssertEqual( + error as? TimeAmount.ValidationError, + TimeAmount.ValidationError.invalidNumber("'' cannot be parsed as number and unit") + ) + } + + // Invalid number + XCTAssertThrowsError(try TimeAmount("abc")) { error in + XCTAssertEqual( + error as? TimeAmount.ValidationError, + TimeAmount.ValidationError.invalidNumber("'abc' cannot be parsed as number and unit") + ) + } + + // Unknown unit + XCTAssertThrowsError(try TimeAmount("5x")) { error in + XCTAssertEqual( + error as? TimeAmount.ValidationError, + TimeAmount.ValidationError.unsupportedUnit("Unknown unit 'x' in '5x'") + ) + } + + // Missing number + XCTAssertThrowsError(try TimeAmount("ms")) { error in + XCTAssertEqual( + error as? TimeAmount.ValidationError, + TimeAmount.ValidationError.invalidNumber("'ms' cannot be parsed as number and unit") + ) + } + } + + func testTimeAmountPrettyPrint() { + // Basic formatting + XCTAssertEqual(TimeAmount.seconds(5).description, "5 s") + XCTAssertEqual(TimeAmount.milliseconds(100).description, "100 ms") + XCTAssertEqual(TimeAmount.microseconds(250).description, "250 us") + XCTAssertEqual(TimeAmount.nanoseconds(42).description, "42 ns") + + // Unit selection based on value + XCTAssertEqual(TimeAmount.nanoseconds(1_000).description, "1 us") + XCTAssertEqual(TimeAmount.nanoseconds(1_000_000).description, "1 ms") + XCTAssertEqual(TimeAmount.nanoseconds(1_000_000_000).description, "1 s") + + // Values with remainders + XCTAssertEqual(TimeAmount.nanoseconds(1_500).description, "1500 ns") + XCTAssertEqual(TimeAmount.nanoseconds(1_500_000).description, "1500 us") + XCTAssertEqual(TimeAmount.nanoseconds(1_500_000_000).description, "1500 ms") + + // Negative values + XCTAssertEqual(TimeAmount.seconds(-5).description, "-5 s") + XCTAssertEqual(TimeAmount.milliseconds(-100).description, "-100 ms") + } } diff --git a/Tests/NIOCoreTests/XCTest+Extensions.swift b/Tests/NIOCoreTests/XCTest+Extensions.swift index 0fc5c8b7d..2970c6551 100644 --- a/Tests/NIOCoreTests/XCTest+Extensions.swift +++ b/Tests/NIOCoreTests/XCTest+Extensions.swift @@ -15,6 +15,10 @@ import NIOCore import XCTest +#if canImport(Android) +import Android +#endif + func assert( _ condition: @autoclosure () -> Bool, within time: TimeAmount, diff --git a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift index 1619f9563..4e9cd0754 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift @@ -21,7 +21,7 @@ import XCTest @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) class AsyncTestingChannelTests: XCTestCase { func testSingleHandlerInit() async throws { - class Handler: ChannelInboundHandler { + final class Handler: ChannelInboundHandler, Sendable { typealias InboundIn = Never } @@ -36,14 +36,14 @@ class AsyncTestingChannelTests: XCTestCase { } let channel = NIOAsyncTestingChannel() - XCTAssertThrowsError(try channel.pipeline.handler(type: Handler.self).wait()) { e in + XCTAssertThrowsError(try channel.pipeline.handler(type: Handler.self).map { _ in }.wait()) { e in XCTAssertEqual(e as? ChannelPipelineError, .notFound) } } func testMultipleHandlerInit() async throws { - class Handler: ChannelInboundHandler, RemovableChannelHandler { + final class Handler: ChannelInboundHandler, RemovableChannelHandler, Sendable { typealias InboundIn = Never let identifier: String @@ -65,6 +65,17 @@ class AsyncTestingChannelTests: XCTestCase { XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler2").wait()) } + func testClosureInit() async throws { + final class Handler: ChannelInboundHandler, Sendable { + typealias InboundIn = Never + } + + let channel = try await NIOAsyncTestingChannel { + try $0.pipeline.syncOperations.addHandler(Handler()) + } + XCTAssertNoThrow(try channel.pipeline.handler(type: Handler.self).wait()) + } + func testWaitForInboundWrite() async throws { let channel = NIOAsyncTestingChannel() let task = Task { @@ -334,7 +345,7 @@ class AsyncTestingChannelTests: XCTestCase { try await XCTAsyncAssertTrue(await channel.finish().isClean) // channelInactive should fire only once. - XCTAssertEqual(inactiveHandler.inactiveNotifications, 1) + XCTAssertEqual(inactiveHandler.inactiveNotifications.load(ordering: .sequentiallyConsistent), 1) } func testEmbeddedLifecycle() async throws { @@ -355,7 +366,7 @@ class AsyncTestingChannelTests: XCTestCase { XCTAssertFalse(channel.isActive) } - private final class ExceptionThrowingInboundHandler: ChannelInboundHandler { + private final class ExceptionThrowingInboundHandler: ChannelInboundHandler, Sendable { typealias InboundIn = String public func channelRead(context: ChannelHandlerContext, data: NIOAny) { @@ -363,7 +374,7 @@ class AsyncTestingChannelTests: XCTestCase { } } - private final class ExceptionThrowingOutboundHandler: ChannelOutboundHandler { + private final class ExceptionThrowingOutboundHandler: ChannelOutboundHandler, Sendable { typealias OutboundIn = String typealias OutboundOut = Never @@ -372,12 +383,12 @@ class AsyncTestingChannelTests: XCTestCase { } } - private final class CloseInChannelInactiveHandler: ChannelInboundHandler { + private final class CloseInChannelInactiveHandler: ChannelInboundHandler, Sendable { typealias InboundIn = ByteBuffer - public var inactiveNotifications = 0 + public let inactiveNotifications = ManagedAtomic(0) public func channelInactive(context: ChannelHandlerContext) { - inactiveNotifications += 1 + inactiveNotifications.wrappingIncrement(by: 1, ordering: .sequentiallyConsistent) context.close(promise: nil) } } diff --git a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift index 08cee06cb..c4d33f78e 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift @@ -19,7 +19,7 @@ import XCTest @testable import NIOEmbedded -private class EmbeddedTestError: Error {} +private final class EmbeddedTestError: Error {} @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) final class NIOAsyncTestingEventLoopTests: XCTestCase { @@ -336,10 +336,12 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { // advanceTime(by:) is the same as on MultiThreadedEventLoopGroup: specifically, that tasks run via // schedule that expire "now" all run at the same time, and that any work they schedule is run // after all such tasks expire. + struct TestState { + var firstScheduled: Scheduled? + var secondScheduled: Scheduled? + } let loop = NIOAsyncTestingEventLoop() - let lock = NIOLock() - var firstScheduled: Scheduled? = nil - var secondScheduled: Scheduled? = nil + let lock = NIOLockedValueBox(TestState()) let orderingCounter = ManagedAtomic(0) // Here's the setup. First, we'll set up two scheduled tasks to fire in 5 nanoseconds. Each of these @@ -356,13 +358,13 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { // // To validate the ordering, we'll use a counter. - lock.withLock { () -> Void in - firstScheduled = loop.scheduleTask(in: .nanoseconds(5)) { - let second = lock.withLock { () -> Scheduled? in - XCTAssertNotNil(firstScheduled) - firstScheduled = nil - XCTAssertNotNil(secondScheduled) - return secondScheduled + lock.withLockedValue { + $0.firstScheduled = loop.scheduleTask(in: .nanoseconds(5)) { + let second = lock.withLockedValue { + XCTAssertNotNil($0.firstScheduled) + $0.firstScheduled = nil + XCTAssertNotNil($0.secondScheduled) + return $0.secondScheduled } if let partner = second { @@ -379,11 +381,11 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { } } - secondScheduled = loop.scheduleTask(in: .nanoseconds(5)) { - lock.withLock { () -> Void in - secondScheduled = nil - XCTAssertNil(firstScheduled) - XCTAssertNil(secondScheduled) + $0.secondScheduled = loop.scheduleTask(in: .nanoseconds(5)) { + lock.withLockedValue { + $0.secondScheduled = nil + XCTAssertNil($0.firstScheduled) + XCTAssertNil($0.secondScheduled) } XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 2, desired: 3) @@ -478,10 +480,11 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { } } - func testTasksScheduledDuringShutdownAreAutomaticallyCancelled() async throws { + func testTasksScheduledDuringShutdownAreAutomaticallyCancelledOrNotScheduled() async throws { let eventLoop = NIOAsyncTestingEventLoop() let tasksRun = ManagedAtomic(0) + @Sendable func scheduleRecursiveTask( at taskStartTime: NIODeadline, andChildTaskAfter childTaskStartDelay: TimeAmount @@ -508,35 +511,39 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { } try await eventLoop.executeInContext { - XCTAssertGreaterThan(tasksRun.load(ordering: .acquiring), 1) + XCTAssertGreaterThan(tasksRun.load(ordering: .acquiring), 0) } } func testShutdownCancelsRemainingScheduledTasks() async { let eventLoop = NIOAsyncTestingEventLoop() - var tasksRun = 0 + let tasksRun = ManagedAtomic(0) - let a = eventLoop.scheduleTask(in: .seconds(1)) { tasksRun += 1 } - let b = eventLoop.scheduleTask(in: .seconds(2)) { tasksRun += 1 } + let a = eventLoop.scheduleTask(in: .seconds(1)) { + tasksRun.wrappingIncrement(ordering: .sequentiallyConsistent) + } + let b = eventLoop.scheduleTask(in: .seconds(2)) { + tasksRun.wrappingIncrement(ordering: .sequentiallyConsistent) + } - XCTAssertEqual(tasksRun, 0) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 0) await eventLoop.advanceTime(by: .seconds(1)) - XCTAssertEqual(tasksRun, 1) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 1) XCTAssertNoThrow(try eventLoop.syncShutdownGracefully()) - XCTAssertEqual(tasksRun, 1) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 1) await eventLoop.advanceTime(by: .seconds(1)) - XCTAssertEqual(tasksRun, 1) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 1) await eventLoop.advanceTime(to: .distantFuture) - XCTAssertEqual(tasksRun, 1) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 1) XCTAssertNoThrow(try a.futureResult.wait()) await XCTAssertThrowsError(try await b.futureResult.get()) { error in XCTAssertEqual(error as? EventLoopError, .cancelled) - XCTAssertEqual(tasksRun, 1) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 1) } } @@ -619,4 +626,14 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { await eventLoop.advanceTime(by: .seconds(1)) XCTAssertEqual(counter.load(ordering: .relaxed), 3) } + + func testCurrentTime() async { + let eventLoop = NIOAsyncTestingEventLoop() + + await eventLoop.advanceTime(to: .uptimeNanoseconds(42)) + XCTAssertEqual(eventLoop.now, .uptimeNanoseconds(42)) + + await eventLoop.advanceTime(by: .nanoseconds(42)) + XCTAssertEqual(eventLoop.now, .uptimeNanoseconds(84)) + } } diff --git a/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift b/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift index 3c77ca624..3b48ed3b3 100644 --- a/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift +++ b/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift @@ -12,12 +12,14 @@ // //===----------------------------------------------------------------------===// +import Atomics +import NIOConcurrencyHelpers import NIOCore import XCTest @testable import NIOEmbedded -class ChannelLifecycleHandler: ChannelInboundHandler { +final class ChannelLifecycleHandler: ChannelInboundHandler, Sendable { public typealias InboundIn = Any public enum ChannelState { @@ -27,17 +29,28 @@ class ChannelLifecycleHandler: ChannelInboundHandler { case active } - public var currentState: ChannelState - public var stateHistory: [ChannelState] + public var currentState: ChannelState { + get { + self._state.withLockedValue { $0.currentState } + } + } + public var stateHistory: [ChannelState] { + get { + self._state.withLockedValue { $0.stateHistory } + } + } + + private let _state: NIOLockedValueBox<(currentState: ChannelState, stateHistory: [ChannelState])> public init() { - currentState = .unregistered - stateHistory = [.unregistered] + self._state = NIOLockedValueBox((currentState: .unregistered, stateHistory: [.unregistered])) } private func updateState(_ state: ChannelState) { - currentState = state - stateHistory.append(state) + self._state.withLockedValue { + $0.currentState = state + $0.stateHistory.append(state) + } } public func channelRegistered(context: ChannelHandlerContext) { @@ -77,7 +90,7 @@ class EmbeddedChannelTest: XCTestCase { } let channel = EmbeddedChannel(handler: Handler()) - XCTAssertNoThrow(try channel.pipeline.handler(type: Handler.self).wait()) + XCTAssertNoThrow(try channel.pipeline.handler(type: Handler.self).map { _ in }.wait()) } func testSingleHandlerInitNil() { @@ -86,7 +99,7 @@ class EmbeddedChannelTest: XCTestCase { } let channel = EmbeddedChannel(handler: nil) - XCTAssertThrowsError(try channel.pipeline.handler(type: Handler.self).wait()) { e in + XCTAssertThrowsError(try channel.pipeline.handler(type: Handler.self).map { _ in }.wait()) { e in XCTAssertEqual(e as? ChannelPipelineError, .notFound) } } @@ -104,13 +117,19 @@ class EmbeddedChannelTest: XCTestCase { let channel = EmbeddedChannel( handlers: [Handler(identifier: "0"), Handler(identifier: "1"), Handler(identifier: "2")] ) - XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "0")) + XCTAssertNoThrow( + XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).map { $0.identifier }.wait(), "0") + ) XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler0").wait()) - XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "1")) + XCTAssertNoThrow( + XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).map { $0.identifier }.wait(), "1") + ) XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler1").wait()) - XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "2")) + XCTAssertNoThrow( + XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).map { $0.identifier }.wait(), "2") + ) XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler2").wait()) } @@ -180,7 +199,7 @@ class EmbeddedChannelTest: XCTestCase { func testWriteInboundByteBufferReThrow() { let channel = EmbeddedChannel() - XCTAssertNoThrow(try channel.pipeline.addHandler(ExceptionThrowingInboundHandler()).wait()) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ExceptionThrowingInboundHandler())) XCTAssertThrowsError(try channel.writeInbound("msg")) { error in XCTAssertEqual(ChannelError.operationUnsupported, error as? ChannelError) } @@ -189,7 +208,7 @@ class EmbeddedChannelTest: XCTestCase { func testWriteOutboundByteBufferReThrow() { let channel = EmbeddedChannel() - XCTAssertNoThrow(try channel.pipeline.addHandler(ExceptionThrowingOutboundHandler()).wait()) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ExceptionThrowingOutboundHandler())) XCTAssertThrowsError(try channel.writeOutbound("msg")) { error in XCTAssertEqual(ChannelError.operationUnsupported, error as? ChannelError) } @@ -323,7 +342,7 @@ class EmbeddedChannelTest: XCTestCase { func testCloseOnInactiveIsOk() throws { let channel = EmbeddedChannel() let inactiveHandler = CloseInChannelInactiveHandler() - XCTAssertNoThrow(try channel.pipeline.addHandler(inactiveHandler).wait()) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(inactiveHandler)) XCTAssertTrue(try channel.finish().isClean) // channelInactive should fire only once. @@ -479,11 +498,12 @@ class EmbeddedChannelTest: XCTestCase { func testFinishWithRecursivelyScheduledTasks() throws { let channel = EmbeddedChannel() let tasks: NIOLoopBoundBox<[Scheduled]> = NIOLoopBoundBox([], eventLoop: channel.eventLoop) - var invocations = 0 + let invocations = ManagedAtomic(0) + @Sendable func recursivelyScheduleAndIncrement() { let task = channel.pipeline.eventLoop.scheduleTask(deadline: .distantFuture) { - invocations += 1 + invocations.wrappingIncrement(ordering: .sequentiallyConsistent) recursivelyScheduleAndIncrement() } tasks.value.append(task) @@ -494,7 +514,7 @@ class EmbeddedChannelTest: XCTestCase { try XCTAssertNoThrow(channel.finish()) // None of the tasks should have been executed, they were scheduled for distant future. - XCTAssertEqual(invocations, 0) + XCTAssertEqual(invocations.load(ordering: .sequentiallyConsistent), 0) // Because the root task didn't run, it should be the onnly one scheduled. XCTAssertEqual(tasks.value.count, 1) diff --git a/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift b/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift index a23665ec2..989bef581 100644 --- a/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift +++ b/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift @@ -12,13 +12,14 @@ // //===----------------------------------------------------------------------===// +import Atomics import NIOConcurrencyHelpers import NIOCore import XCTest @testable import NIOEmbedded -private class EmbeddedTestError: Error {} +private final class EmbeddedTestError: Error {} public final class EmbeddedEventLoopTest: XCTestCase { func testExecuteDoesNotImmediatelyRunTasks() throws { @@ -195,37 +196,38 @@ public final class EmbeddedEventLoopTest: XCTestCase { } func testScheduledTasksFuturesFire() throws { - var fired = false + let fired = ManagedAtomic(false) let loop = EmbeddedEventLoop() let task = loop.scheduleTask(in: .nanoseconds(5)) { true } - task.futureResult.whenSuccess { fired = $0 } + task.futureResult.whenSuccess { fired.store($0, ordering: .sequentiallyConsistent) } loop.advanceTime(by: .nanoseconds(4)) - XCTAssertFalse(fired) + XCTAssertFalse(fired.load(ordering: .sequentiallyConsistent)) loop.advanceTime(by: .nanoseconds(1)) - XCTAssertTrue(fired) + XCTAssertTrue(fired.load(ordering: .sequentiallyConsistent)) } func testScheduledTasksFuturesError() throws { - var err: EmbeddedTestError? = nil - var fired = false + let err: NIOLockedValueBox = NIOLockedValueBox(nil) + let fired = ManagedAtomic(false) let loop = EmbeddedEventLoop() let task = loop.scheduleTask(in: .nanoseconds(5)) { - err = EmbeddedTestError() - throw err! + let localErr = EmbeddedTestError() + err.withLockedValue { $0 = localErr } + throw localErr } task.futureResult.map { XCTFail("Scheduled future completed") }.recover { caughtErr in - XCTAssertTrue(err === caughtErr as? EmbeddedTestError) + XCTAssertTrue(err.withLockedValue { $0 === caughtErr as? EmbeddedTestError }) }.whenComplete { (_: Result) in - fired = true + fired.store(true, ordering: .sequentiallyConsistent) } loop.advanceTime(by: .nanoseconds(4)) - XCTAssertFalse(fired) + XCTAssertFalse(fired.load(ordering: .sequentiallyConsistent)) loop.advanceTime(by: .nanoseconds(1)) - XCTAssertTrue(fired) + XCTAssertTrue(fired.load(ordering: .sequentiallyConsistent)) } func testTaskOrdering() { @@ -396,7 +398,7 @@ public final class EmbeddedEventLoopTest: XCTestCase { try eventLoop.syncShutdownGracefully() childTasks.append( scheduleRecursiveTask( - at: eventLoop._now + childTaskStartDelay, + at: eventLoop.now + childTaskStartDelay, andChildTaskAfter: childTaskStartDelay ) ) @@ -497,4 +499,38 @@ public final class EmbeddedEventLoopTest: XCTestCase { eventLoop.advanceTime(by: .seconds(1)) XCTAssertEqual(counter, 3) } + + func testCurrentTime() { + let eventLoop = EmbeddedEventLoop() + + eventLoop.advanceTime(to: .uptimeNanoseconds(42)) + XCTAssertEqual(eventLoop.now, .uptimeNanoseconds(42)) + + eventLoop.advanceTime(by: .nanoseconds(42)) + XCTAssertEqual(eventLoop.now, .uptimeNanoseconds(84)) + } + + func testScheduleRepeatedTask() { + let eventLoop = EmbeddedEventLoop() + + let counter = ManagedAtomic(0) + eventLoop.scheduleRepeatedTask(initialDelay: .seconds(1), delay: .seconds(1)) { repeatedTask in + guard counter.load(ordering: .sequentiallyConsistent) < 10 else { + repeatedTask.cancel() + return + } + counter.wrappingIncrement(ordering: .sequentiallyConsistent) + } + + XCTAssertEqual(counter.load(ordering: .sequentiallyConsistent), 0) + + eventLoop.advanceTime(by: .seconds(1)) + XCTAssertEqual(counter.load(ordering: .sequentiallyConsistent), 1) + + eventLoop.advanceTime(by: .seconds(9)) + XCTAssertEqual(counter.load(ordering: .sequentiallyConsistent), 10) + } } + +@available(*, unavailable) +extension EmbeddedEventLoopTest: Sendable {} diff --git a/Tests/NIOEmbeddedTests/TestUtils.swift b/Tests/NIOEmbeddedTests/TestUtils.swift index 02fe152e7..3cefa8106 100644 --- a/Tests/NIOEmbeddedTests/TestUtils.swift +++ b/Tests/NIOEmbeddedTests/TestUtils.swift @@ -17,6 +17,10 @@ import NIOConcurrencyHelpers import NIOCore import XCTest +#if canImport(Android) +import Android +#endif + // FIXME: Duplicated with NIO func assert( _ condition: @autoclosure () -> Bool, @@ -44,26 +48,25 @@ extension EventLoopFuture { if self.eventLoop.inEventLoop { // Easy, we're on the EventLoop. Let's just use our knowledge that we run completed future callbacks // immediately. - var fulfilled = false + let fulfilled = NIOLoopBoundBox(false, eventLoop: self.eventLoop) self.whenComplete { _ in - fulfilled = true + fulfilled.value = true } - return fulfilled + return fulfilled.value } else { - let lock = NIOLock() + let fulfilled = NIOLockedValueBox(false) let group = DispatchGroup() - var fulfilled = false // protected by lock group.enter() self.eventLoop.execute { let isFulfilled = self.isFulfilled // This will now enter the above branch. - lock.withLock { - fulfilled = isFulfilled + fulfilled.withLockedValue { + $0 = isFulfilled } group.leave() } group.wait() // this is very nasty but this is for tests only, so... - return lock.withLock { fulfilled } + return fulfilled.withLockedValue { $0 } } } } diff --git a/Tests/NIOFileSystemIntegrationTests/ConvenienceTests.swift b/Tests/NIOFileSystemIntegrationTests/ConvenienceTests.swift index 85a09505d..de9a60948 100644 --- a/Tests/NIOFileSystemIntegrationTests/ConvenienceTests.swift +++ b/Tests/NIOFileSystemIntegrationTests/ConvenienceTests.swift @@ -70,4 +70,31 @@ final class ConvenienceTests: XCTestCase { let bytes = try await ByteBuffer(contentsOf: path, maximumSizeAllowed: .bytes(1024)) XCTAssertEqual(bytes, ByteBuffer(bytes: Array(0..<64))) } + + // MARK: - String + FileSystem + + func testStringFromFullFile() async throws { + let path = try await Self.fs.temporaryFilePath() + try await "some text".write(toFileAt: path) + + let string = try await String(contentsOf: path, maximumSizeAllowed: .bytes(1024)) + XCTAssertEqual(string, "some text") + } + + func testStringFromPartOfAFile() async throws { + let path = try await Self.fs.temporaryFilePath() + try await "some text".write(toFileAt: path) + + await XCTAssertThrowsFileSystemErrorAsync { + try await String(contentsOf: path, maximumSizeAllowed: .bytes(4)) + } + } + + // MARK: - Array + FileSystem + func testArrayFromFullFile() async throws { + let path = try await Self.fs.temporaryFilePath() + try await Array("some text".utf8).write(toFileAt: path) + let array = try await Array(contentsOf: path, maximumSizeAllowed: .bytes(1024)) + XCTAssertEqual(array, Array("some text".utf8)) + } } diff --git a/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift index 5de584660..4e82f7405 100644 --- a/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift +++ b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift @@ -222,7 +222,7 @@ final class FileSystemTests: XCTestCase { // Avoid dirtying the current working directory. if path.isRelative { self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: path) + try await fileSystem.removeItem(at: path, strategy: .platformDefault) } } @@ -351,7 +351,7 @@ final class FileSystemTests: XCTestCase { // Avoid dirtying the current working directory. if directoryPath.isRelative { self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: directoryPath) + try await fileSystem.removeItem(at: directoryPath, strategy: .platformDefault) } } @@ -399,7 +399,7 @@ final class FileSystemTests: XCTestCase { if directoryPath.isRelative { self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: directoryPath, recursively: true) + try await fileSystem.removeItem(at: directoryPath, strategy: .platformDefault, recursively: true) } } @@ -585,9 +585,9 @@ final class FileSystemTests: XCTestCase { func testCopyLargeFile() async throws { let sourcePath = try await self.fs.temporaryFilePath() let destPath = try await self.fs.temporaryFilePath() - self.addTeardownBlock { - _ = try? await self.fs.removeItem(at: sourcePath) - _ = try? await self.fs.removeItem(at: destPath) + self.addTeardownBlock { [fs] in + _ = try? await fs.removeItem(at: sourcePath, strategy: .platformDefault) + _ = try? await fs.removeItem(at: destPath, strategy: .platformDefault) } let sourceInfo = try await self.fs.withFileHandle( @@ -854,7 +854,7 @@ final class FileSystemTests: XCTestCase { _ copyStrategy: CopyStrategy, _ description: String, _ path: FilePath, - triggerCancel: @escaping (DirectoryEntry) -> Bool, + triggerCancel: @escaping @Sendable (DirectoryEntry) -> Bool, line: UInt = #line ) async throws { @@ -863,8 +863,8 @@ final class FileSystemTests: XCTestCase { let requestedCancel = NIOLockedValueBox(false) let cancelRequested = expectation(description: "cancel requested") - let task = Task { - try await self.fs.copyItem(at: path, to: copyPath, strategy: copyStrategy) { _, error in + let task = Task { [fs] in + try await fs.copyItem(at: path, to: copyPath, strategy: copyStrategy) { _, error in throw error } shouldCopyItem: { source, destination in // Abuse shouldCopy to trigger the cancellation after getting some way in. @@ -991,7 +991,7 @@ final class FileSystemTests: XCTestCase { let infoAfterCreation = try await self.fs.info(forFileAt: path) XCTAssertNotNil(infoAfterCreation) - let removed = try await self.fs.removeItem(at: path) + let removed = try await self.fs.removeItem(at: path, strategy: .platformDefault) XCTAssertEqual(removed, 1) let infoAfterRemoval = try await self.fs.info(forFileAt: path) @@ -1002,11 +1002,11 @@ final class FileSystemTests: XCTestCase { let path = try await self.fs.temporaryFilePath() let info = try await self.fs.info(forFileAt: path) XCTAssertNil(info) - let removed = try await self.fs.removeItem(at: path) + let removed = try await self.fs.removeItem(at: path, strategy: .platformDefault) XCTAssertEqual(removed, 0) } - func testRemoveDirectory() async throws { + func testRemoveDirectorySequentially() async throws { let path = try await self.fs.temporaryFilePath() let created = try await self.generateDirectoryStructure( root: path, @@ -1019,12 +1019,37 @@ final class FileSystemTests: XCTestCase { // Removing a non-empty directory recursively should throw 'notEmpty' await XCTAssertThrowsFileSystemErrorAsync { - try await self.fs.removeItem(at: path, recursively: false) + try await self.fs.removeItem(at: path, strategy: .sequential, recursively: false) } onError: { error in XCTAssertEqual(error.code, .notEmpty) } - let removed = try await self.fs.removeItem(at: path) + let removed = try await self.fs.removeItem(at: path, strategy: .sequential) + XCTAssertEqual(created, removed) + + let infoAfterRemoval = try await self.fs.info(forFileAt: path) + XCTAssertNil(infoAfterRemoval) + } + + func testRemoveDirectoryConcurrently() async throws { + let path = try await self.fs.temporaryFilePath() + let created = try await self.generateDirectoryStructure( + root: path, + maxDepth: 3, + maxFilesPerDirectory: 10 + ) + + let infoAfterCreation = try await self.fs.info(forFileAt: path) + XCTAssertNotNil(infoAfterCreation) + + // Removing a non-empty directory recursively should throw 'notEmpty' + await XCTAssertThrowsFileSystemErrorAsync { + try await self.fs.removeItem(at: path, strategy: .parallel(maxDescriptors: 2), recursively: false) + } onError: { error in + XCTAssertEqual(error.code, .notEmpty) + } + + let removed = try await self.fs.removeItem(at: path, strategy: .parallel(maxDescriptors: 2)) XCTAssertEqual(created, removed) let infoAfterRemoval = try await self.fs.info(forFileAt: path) @@ -1602,7 +1627,7 @@ extension FileSystemTests { // Clean up after ourselves. self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: temporaryDirectoryPath) + try await fileSystem.removeItem(at: temporaryDirectoryPath, strategy: .platformDefault) } guard let info = try await self.fs.info(forFileAt: temporaryDirectoryPath) else { @@ -1640,7 +1665,7 @@ extension FileSystemTests { let temporaryDirectoryPath = try await self.fs.createTemporaryDirectory(template: template) self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: templateRoot, recursively: true) + try await fileSystem.removeItem(at: templateRoot, strategy: .platformDefault, recursively: true) } guard @@ -1656,6 +1681,14 @@ extension FileSystemTests { XCTAssertGreaterThan(info.size, 0) } + func testTemporaryDirectoryRespectsEnvironment() async throws { + if let envTmpDir = getenv("TMPDIR") { + let envTmpDirString = String(cString: envTmpDir) + let fsTempDirectory = try await fs.temporaryDirectory + XCTAssertEqual(fsTempDirectory, FilePath(envTmpDirString)) + } + } + func testReadChunksRange() async throws { try await self.fs.withFileHandle(forReadingAt: FilePath(#filePath)) { handle in let info = try await handle.info() diff --git a/Tests/NIOFileSystemTests/FileInfoTests.swift b/Tests/NIOFileSystemTests/FileInfoTests.swift index 2e679d9a9..6760b5d3a 100644 --- a/Tests/NIOFileSystemTests/FileInfoTests.swift +++ b/Tests/NIOFileSystemTests/FileInfoTests.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import XCTest import _NIOFileSystem @@ -19,8 +20,16 @@ import _NIOFileSystem import Darwin #elseif canImport(Glibc) import Glibc -#elseif canImport(Bionic) -import Bionic +#elseif canImport(Android) +import Android +#endif + +#if canImport(Darwin) +private let S_IFREG = Darwin.S_IFREG +#elseif canImport(Glibc) +private let S_IFREG = Glibc.S_IFREG +#elseif canImport(Musl) +private let S_IFREG = Musl.S_IFREG #endif final class FileInfoTests: XCTestCase { @@ -44,7 +53,7 @@ final class FileInfoTests: XCTestCase { status.st_birthtimespec = timespec(tv_sec: 3, tv_nsec: 0) status.st_flags = 11 status.st_gen = 12 - #elseif canImport(Glibc) || canImport(Bionic) + #elseif canImport(Glibc) || canImport(Android) status.st_atim = timespec(tv_sec: 0, tv_nsec: 0) status.st_mtim = timespec(tv_sec: 1, tv_nsec: 0) status.st_ctim = timespec(tv_sec: 2, tv_nsec: 0) @@ -98,7 +107,7 @@ final class FileInfoTests: XCTestCase { assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_birthtimespec.tv_sec += 1 } assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_flags += 1 } assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_gen += 1 } - #elseif canImport(Glibc) || canImport(Bionic) + #elseif canImport(Glibc) || canImport(Android) assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_atim.tv_sec += 1 } assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_mtim.tv_sec += 1 } assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_ctim.tv_sec += 1 } @@ -151,7 +160,7 @@ final class FileInfoTests: XCTestCase { } assertDifferentHashValueAfterMutation { $0.platformSpecificStatus!.st_flags += 1 } assertDifferentHashValueAfterMutation { $0.platformSpecificStatus!.st_gen += 1 } - #elseif canImport(Glibc) || canImport(Bionic) + #elseif canImport(Glibc) || canImport(Android) assertDifferentHashValueAfterMutation { $0.platformSpecificStatus!.st_atim.tv_sec += 1 } assertDifferentHashValueAfterMutation { $0.platformSpecificStatus!.st_mtim.tv_sec += 1 } assertDifferentHashValueAfterMutation { $0.platformSpecificStatus!.st_ctim.tv_sec += 1 } diff --git a/Tests/NIOFileSystemTests/FileTypeTests.swift b/Tests/NIOFileSystemTests/FileTypeTests.swift index 0655d32a5..b25e2170f 100644 --- a/Tests/NIOFileSystemTests/FileTypeTests.swift +++ b/Tests/NIOFileSystemTests/FileTypeTests.swift @@ -19,6 +19,8 @@ import XCTest import Darwin #elseif canImport(Glibc) import Glibc +#elseif canImport(Android) +import Android #endif final class FileTypeTests: XCTestCase { diff --git a/Tests/NIOFileSystemTests/Internal/SyscallTests.swift b/Tests/NIOFileSystemTests/Internal/SyscallTests.swift index 2ca520421..aa067798f 100644 --- a/Tests/NIOFileSystemTests/Internal/SyscallTests.swift +++ b/Tests/NIOFileSystemTests/Internal/SyscallTests.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import SystemPackage import XCTest @_spi(Testing) import _NIOFileSystem diff --git a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift index 43cfbb4c6..97d9df956 100644 --- a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift @@ -318,7 +318,7 @@ private func assertPipelineContainsUpgradeHandler(channel: Channel) { @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) class HTTPClientUpgradeTestCase: XCTestCase { func setUpClientChannel( - clientHTTPHandler: RemovableChannelHandler, + clientHTTPHandler: RemovableChannelHandler & Sendable, clientUpgraders: [any TypedAndUntypedHTTPClientProtocolUpgrader], _ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void ) throws -> EmbeddedChannel { @@ -1063,7 +1063,7 @@ class HTTPClientUpgradeTestCase: XCTestCase { @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase { override func setUpClientChannel( - clientHTTPHandler: RemovableChannelHandler, + clientHTTPHandler: RemovableChannelHandler & Sendable, clientUpgraders: [any TypedAndUntypedHTTPClientProtocolUpgrader], _ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void ) throws -> EmbeddedChannel { diff --git a/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift b/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift index bd424f77d..4971af97a 100644 --- a/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift @@ -400,4 +400,26 @@ class HTTPHeadersTest: XCTestCase { headers.reserveCapacity(4) XCTAssertEqual(headers.capacity, 4) } + + func testHTTPHeadersDescription() { + let originalHeaders = [ + ("User-Agent", "1"), + ("host", "2"), + ("X-SOMETHING", "3"), + ("SET-COOKIE", "foo=bar"), + ("Set-Cookie", "buz=cux"), + ] + + let headers = HTTPHeaders(originalHeaders) + + let expectedOutput = """ + User-Agent: 1; \ + host: 2; \ + X-SOMETHING: 3; \ + SET-COOKIE: foo=bar; \ + Set-Cookie: buz=cux + """ + + XCTAssertEqual(expectedOutput, headers.description) + } } diff --git a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift index 3a69f806e..9049c5122 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift @@ -1388,7 +1388,7 @@ class HTTPServerUpgradeTestCase: XCTestCase { XCTAssertNil(upgradeRequest.wrappedValue) upgradeHandlerCbFired.wrappedValue = true - _ = context.channel.pipeline.addHandler( + try! context.channel.pipeline.syncOperations.addHandler( CheckWeReadInlineAndExtraData( firstByteDonePromise: firstByteDonePromise, secondByteDonePromise: secondByteDonePromise, @@ -2145,7 +2145,7 @@ final class TypedHTTPServerUpgradeTestCase: HTTPServerUpgradeTestCase { XCTAssertNotNil(upgradeRequest.wrappedValue) upgradeHandlerCbFired.wrappedValue = true - _ = context.channel.pipeline.addHandler( + try! context.channel.pipeline.syncOperations.addHandler( CheckWeReadInlineAndExtraData( firstByteDonePromise: firstByteDonePromise, secondByteDonePromise: secondByteDonePromise, diff --git a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift index 847a5ac78..68604ef0f 100644 --- a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift +++ b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift @@ -284,7 +284,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { port: 0 ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureProtocolNegotiationHandlers(channel: channel) + try Self.configureProtocolNegotiationHandlers(channel: channel) } } @@ -366,7 +366,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { port: 0 ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureNestedProtocolNegotiationHandlers(channel: channel) + try Self.configureNestedProtocolNegotiationHandlers(channel: channel) } } @@ -508,7 +508,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { port: 0 ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureProtocolNegotiationHandlers(channel: channel) + try Self.configureProtocolNegotiationHandlers(channel: channel) } } @@ -958,7 +958,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { output: pipe2WriteFD ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureProtocolNegotiationHandlers(channel: channel) + try Self.configureProtocolNegotiationHandlers(channel: channel) } } } catch { @@ -1251,7 +1251,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { try channel.pipeline.syncOperations.addHandler( AddressedEnvelopingHandler(remoteAddress: SocketAddress(ipAddress: "127.0.0.1", port: 0)) ) - return try self.configureProtocolNegotiationHandlers( + return try Self.configureProtocolNegotiationHandlers( channel: channel, proposedALPN: nil, inboundID: 1, @@ -1275,7 +1275,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { try channel.pipeline.syncOperations.addHandler( AddressedEnvelopingHandler(remoteAddress: SocketAddress(ipAddress: "127.0.0.1", port: 0)) ) - return try self.configureProtocolNegotiationHandlers( + return try Self.configureProtocolNegotiationHandlers( channel: channel, proposedALPN: proposedALPN, inboundID: 2, @@ -1329,7 +1329,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { to: .init(ipAddress: "127.0.0.1", port: port) ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) + try Self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) } } } @@ -1345,7 +1345,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { to: .init(ipAddress: "127.0.0.1", port: port) ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureNestedProtocolNegotiationHandlers( + try Self.configureNestedProtocolNegotiationHandlers( channel: channel, proposedOuterALPN: proposedOuterALPN, proposedInnerALPN: proposedInnerALPN @@ -1382,7 +1382,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { ) { channel in channel.eventLoop.makeCompletedFuture { try channel.pipeline.syncOperations.addHandler(AddressedEnvelopingHandler()) - return try self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) + return try Self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) } } } @@ -1418,13 +1418,13 @@ final class AsyncChannelBootstrapTests: XCTestCase { ) { channel in channel.eventLoop.makeCompletedFuture { try channel.pipeline.syncOperations.addHandler(AddressedEnvelopingHandler()) - return try self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) + return try Self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) } } } @discardableResult - private func configureProtocolNegotiationHandlers( + private static func configureProtocolNegotiationHandlers( channel: Channel, proposedALPN: TLSUserEventHandler.ALPN? = nil, inboundID: UInt8? = nil, @@ -1437,7 +1437,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { } @discardableResult - private func configureNestedProtocolNegotiationHandlers( + private static func configureNestedProtocolNegotiationHandlers( channel: Channel, proposedOuterALPN: TLSUserEventHandler.ALPN? = nil, proposedInnerALPN: TLSUserEventHandler.ALPN? = nil @@ -1456,7 +1456,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { try channel.pipeline.syncOperations.addHandler( TLSUserEventHandler(proposedALPN: proposedInnerALPN) ) - let negotiationFuture = try self.addTypedApplicationProtocolNegotiationHandler(to: channel) + let negotiationFuture = try Self.addTypedApplicationProtocolNegotiationHandler(to: channel) return negotiationFuture } @@ -1465,7 +1465,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { try channel.pipeline.syncOperations.addHandler( TLSUserEventHandler(proposedALPN: proposedInnerALPN) ) - let negotiationHandler = try self.addTypedApplicationProtocolNegotiationHandler(to: channel) + let negotiationHandler = try Self.addTypedApplicationProtocolNegotiationHandler(to: channel) return negotiationHandler } @@ -1481,7 +1481,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { } @discardableResult - private func addTypedApplicationProtocolNegotiationHandler( + private static func addTypedApplicationProtocolNegotiationHandler( to channel: Channel ) throws -> EventLoopFuture { let negotiationHandler = NIOTypedApplicationProtocolNegotiationHandler { diff --git a/Tests/NIOPosixTests/BlockingIOThreadPoolTest.swift b/Tests/NIOPosixTests/BlockingIOThreadPoolTest.swift index 1545d88ad..38dabf7d0 100644 --- a/Tests/NIOPosixTests/BlockingIOThreadPoolTest.swift +++ b/Tests/NIOPosixTests/BlockingIOThreadPoolTest.swift @@ -14,6 +14,7 @@ import Dispatch import Foundation +import NIOCore import NIOPosix import XCTest diff --git a/Tests/NIOPosixTests/BootstrapTest.swift b/Tests/NIOPosixTests/BootstrapTest.swift index 8c64a578e..309f8b1c8 100644 --- a/Tests/NIOPosixTests/BootstrapTest.swift +++ b/Tests/NIOPosixTests/BootstrapTest.swift @@ -734,7 +734,7 @@ class BootstrapTest: XCTestCase { // Some platforms don't define "localhost" for IPv6, so check that // and use "ip6-localhost" instead. if !isIPv4 { - let hostResolver = GetaddrinfoResolver(loop: group.next(), aiSocktype: .stream, aiProtocol: .tcp) + let hostResolver = GetaddrinfoResolver(loop: self.group.next(), aiSocktype: .stream, aiProtocol: .tcp) let hostv6 = try! hostResolver.initiateAAAAQuery(host: "localhost", port: 8088).wait() if hostv6.isEmpty { localhost = "ip6-localhost" @@ -752,7 +752,7 @@ class BootstrapTest: XCTestCase { XCTFail("can't connect channel 1") return } - XCTAssertEqual(localIP, maybeChannel1?.localAddress?.ipAddress) + XCTAssertEqual(localIP, myChannel1Address.ipAddress) // Try 3: Bind the client to the same address/port as in try 2 but to server 2. XCTAssertNoThrow( try ClientBootstrap(group: self.group) diff --git a/Tests/NIOPosixTests/ChannelPipelineTest.swift b/Tests/NIOPosixTests/ChannelPipelineTest.swift index 130e39fd2..d00f460d0 100644 --- a/Tests/NIOPosixTests/ChannelPipelineTest.swift +++ b/Tests/NIOPosixTests/ChannelPipelineTest.swift @@ -2693,6 +2693,132 @@ class ChannelPipelineTest: XCTestCase { XCTAssertTrue(try channel.finish().isClean) } + + func testAddAfterForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + let firstHandler = IndexWritingHandler(1) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(firstHandler)) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(2))) + XCTAssertNoThrow( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(3), + position: .after(firstHandler) + ) + ) + + channel.assertReadIndexOrder([1, 3, 2]) + channel.assertWriteIndexOrder([2, 3, 1]) + } + + func testAddBeforeForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + let secondHandler = IndexWritingHandler(2) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(1))) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(secondHandler)) + XCTAssertNoThrow( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(3), + position: .before(secondHandler) + ) + ) + + channel.assertReadIndexOrder([1, 3, 2]) + channel.assertWriteIndexOrder([2, 3, 1]) + } + + func testAddAfterLastForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + let secondHandler = IndexWritingHandler(2) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(1))) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(secondHandler)) + XCTAssertNoThrow( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(3), + position: .after(secondHandler) + ) + ) + + channel.assertReadIndexOrder([1, 2, 3]) + channel.assertWriteIndexOrder([3, 2, 1]) + } + + func testAddBeforeFirstForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + let firstHandler = IndexWritingHandler(1) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(firstHandler)) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(2))) + XCTAssertNoThrow( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(3), + position: .before(firstHandler) + ) + ) + + channel.assertReadIndexOrder([3, 1, 2]) + channel.assertWriteIndexOrder([2, 1, 3]) + } + + func testAddAfterWhileClosedForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertThrowsError(try channel.finish()) { error in + XCTAssertEqual(.alreadyClosed, error as? ChannelError) + } + } + + let handler = IndexWritingHandler(1) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler)) + XCTAssertNoThrow(try channel.close().wait()) + channel.embeddedEventLoop.run() + + XCTAssertThrowsError( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(2), + position: .after(handler) + ) + ) { error in + XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError) + } + } + + func testAddBeforeWhileClosedForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertThrowsError(try channel.finish()) { error in + XCTAssertEqual(.alreadyClosed, error as? ChannelError) + } + } + + let handler = IndexWritingHandler(1) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler)) + XCTAssertNoThrow(try channel.close().wait()) + channel.embeddedEventLoop.run() + + XCTAssertThrowsError( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(2), + position: .before(handler) + ) + ) { error in + XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError) + } + } } // this should be within `testAddMultipleHandlers` but https://bugs.swift.org/browse/SR-9956 diff --git a/Tests/NIOPosixTests/ControlMessageTests.swift b/Tests/NIOPosixTests/ControlMessageTests.swift index fc33f634a..26b6634bb 100644 --- a/Tests/NIOPosixTests/ControlMessageTests.swift +++ b/Tests/NIOPosixTests/ControlMessageTests.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import XCTest @testable import NIOPosix diff --git a/Tests/NIOPosixTests/EchoServerClientTest.swift b/Tests/NIOPosixTests/EchoServerClientTest.swift index 678f6da80..9675e1946 100644 --- a/Tests/NIOPosixTests/EchoServerClientTest.swift +++ b/Tests/NIOPosixTests/EchoServerClientTest.swift @@ -224,7 +224,7 @@ class EchoServerClientTest: XCTestCase { try withTemporaryUnixDomainSocketPathName { udsPath in // Bootstrap should not overwrite an existing file unless it is a socket - FileManager.default.createFile(atPath: udsPath, contents: nil, attributes: nil) + _ = FileManager.default.createFile(atPath: udsPath, contents: nil, attributes: nil) let bootstrap = ServerBootstrap(group: group) XCTAssertThrowsError( diff --git a/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift b/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift new file mode 100644 index 000000000..705d63197 --- /dev/null +++ b/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift @@ -0,0 +1,599 @@ +//===----------------------------------------------------------------------===// +// +// 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 NIOConcurrencyHelpers +import NIOCore +import NIOEmbedded +import NIOPosix +import XCTest + +final class SuperNotSendable { + var x: Int = 5 +} + +@available(*, unavailable) +extension SuperNotSendable: Sendable {} + +// A very stupid event loop that implements as little of the protocol as possible. +// +// We use this to confirm that the fallback path for the isolated views works, by not implementing +// their fast-paths. Instead, we forward to the underlying implementation. We use `AsyncTestingEventLoop` +// to provide the backing implementation. +private final class FallbackEventLoop: RunnableEventLoop { + private let base: NIOAsyncTestingEventLoop + + init() { + self.base = .init() + } + + var now: NIODeadline { + self.base.now + } + + var inEventLoop: Bool { + self.base.inEventLoop + } + + func execute(_ task: @escaping @Sendable () -> Void) { + self.base.execute(task) + } + + func scheduleTask( + deadline: NIOCore.NIODeadline, + _ task: @escaping @Sendable () throws -> T + ) -> NIOCore.Scheduled { + self.base.scheduleTask(deadline: deadline, task) + } + + func scheduleTask( + in delay: NIOCore.TimeAmount, + _ task: @escaping @Sendable () throws -> T + ) -> NIOCore.Scheduled { + self.base.scheduleTask(in: delay, task) + } + + func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping @Sendable ((any Error)?) -> Void) { + self.base.shutdownGracefully(queue: queue, callback) + } + + func runForTests() { + self.base.runForTests() + } + + func advanceTimeForTests(by amount: TimeAmount) { + self.base.advanceTimeForTests(by: amount) + } +} + +private protocol RunnableEventLoop: EventLoop { + func runForTests() + func advanceTimeForTests(by: TimeAmount) +} + +extension EmbeddedEventLoop: RunnableEventLoop { + fileprivate func runForTests() { + self.run() + } + + fileprivate func advanceTimeForTests(by amount: TimeAmount) { + self.advanceTime(by: amount) + } +} + +extension NIOAsyncTestingEventLoop: RunnableEventLoop { + fileprivate func runForTests() { + // This is horrible, but it's the only general-purpose implementation. + let promise = self.makePromise(of: Void.self) + promise.completeWithTask { + await self.run() + } + try! promise.futureResult.wait() + } + + fileprivate func advanceTimeForTests(by amount: TimeAmount) { + // This is horrible, but it's the only general-purpose implementation. + let promise = self.makePromise(of: Void.self) + promise.completeWithTask { + await self.advanceTime(by: amount) + } + try! promise.futureResult.wait() + } +} + +final class EventLoopFutureIsolatedTest: XCTestCase { + func _completingPromiseWithNonSendableValue(loop: any EventLoop) throws { + let f = loop.flatSubmit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let value = SuperNotSendable() + promise.assumeIsolated().succeed(value) + return promise.futureResult.assumeIsolated().map { val in + XCTAssertIdentical(val, value) + }.nonisolated() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() + } + + func _completingPromiseWithNonSendableResult(loop: any EventLoop) throws { + let f = loop.flatSubmit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let value = SuperNotSendable() + promise.assumeIsolated().completeWith(.success(value)) + return promise.futureResult.assumeIsolated().map { val in + XCTAssertIdentical(val, value) + }.nonisolated() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() + } + + func _completingPromiseWithNonSendableValueUnchecked(loop: any EventLoop) throws { + let f = loop.flatSubmit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let value = SuperNotSendable() + promise.assumeIsolatedUnsafeUnchecked().succeed(value) + return promise.futureResult.assumeIsolatedUnsafeUnchecked().map { val in + XCTAssertIdentical(val, value) + }.nonisolated() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() + } + + func _completingPromiseWithNonSendableResultUnchecked(loop: any EventLoop) throws { + let f = loop.flatSubmit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let value = SuperNotSendable() + promise.assumeIsolatedUnsafeUnchecked().completeWith(.success(value)) + return promise.futureResult.assumeIsolatedUnsafeUnchecked().map { val in + XCTAssertIdentical(val, value) + }.nonisolated() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() + } + + func _backAndForthUnwrapping(loop: any EventLoop) throws { + let f = loop.submit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let future = promise.futureResult + + XCTAssertEqual(promise.assumeIsolated().nonisolated(), promise) + XCTAssertEqual(future.assumeIsolated().nonisolated(), future) + promise.assumeIsolated().succeed(SuperNotSendable()) + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() + } + + func _backAndForthUnwrappingUnchecked(loop: any EventLoop) throws { + let f = loop.submit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let future = promise.futureResult + + XCTAssertEqual(promise.assumeIsolatedUnsafeUnchecked().nonisolated(), promise) + XCTAssertEqual(future.assumeIsolatedUnsafeUnchecked().nonisolated(), future) + promise.assumeIsolated().succeed(SuperNotSendable()) + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() + } + + func _futureChaining(loop: any EventLoop) throws { + enum TestError: Error { + case error + } + + let f = loop.flatSubmit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let future = promise.futureResult.assumeIsolated() + let originalValue = SuperNotSendable() + + // Note that for this test it is _very important_ that all of these + // close over `originalValue`. This proves the non-Sendability of + // the closure. + + // This block is the main happy path. + let newFuture = future.flatMap { result in + XCTAssertIdentical(originalValue, result) + let promise = loop.makePromise(of: Int.self) + promise.succeed(4) + return promise.futureResult + }.map { (result: Int) in + XCTAssertEqual(result, 4) + return originalValue + }.flatMapThrowing { (result: SuperNotSendable) in + XCTAssertIdentical(originalValue, result) + return SuperNotSendable() + }.flatMapResult { (result: SuperNotSendable) -> Result in + XCTAssertNotIdentical(originalValue, result) + return .failure(TestError.error) + }.recover { err in + XCTAssertTrue(err is TestError) + return originalValue + }.always { val in + XCTAssertNotNil(try? val.get()) + } + + newFuture.whenComplete { result in + guard case .success(let r) = result else { + XCTFail("Unexpected error") + return + } + XCTAssertIdentical(r, originalValue) + } + newFuture.whenSuccess { result in + XCTAssertIdentical(result, originalValue) + } + + // This block covers the flatMapError and whenFailure tests + let throwingFuture = newFuture.flatMapThrowing { (_: SuperNotSendable) throws -> SuperNotSendable in + XCTAssertEqual(originalValue.x, 5) + throw TestError.error + } + throwingFuture.whenFailure { error in + // Supurious but forces the closure. + XCTAssertEqual(originalValue.x, 5) + guard let error = error as? TestError, error == .error else { + XCTFail("Invalid passed error: \(error)") + return + } + } + throwingFuture.flatMapErrorThrowing { error in + guard let error = error as? TestError, error == .error else { + XCTFail("Invalid passed error: \(error)") + throw error + } + return originalValue + }.whenComplete { result in + guard case .success(let r) = result else { + XCTFail("Unexpected error") + return + } + XCTAssertIdentical(r, originalValue) + } + throwingFuture.map { _ in 5 }.flatMapError { (error: any Error) -> EventLoopFuture in + guard let error = error as? TestError, error == .error else { + XCTFail("Invalid passed error: \(error)") + return loop.makeSucceededFuture(originalValue.x) + } + return loop.makeSucceededFuture(originalValue.x - 1) + }.whenComplete { (result: Result) in + guard case .success(let r) = result else { + XCTFail("Unexpected error") + return + } + XCTAssertEqual(r, originalValue.x - 1) + } + + // This block handles unwrap. + newFuture.map { x -> SuperNotSendable? in + XCTAssertEqual(originalValue.x, 5) + return nil + }.unwrap(orReplace: originalValue).unwrap( + orReplace: SuperNotSendable() + ).map { x -> SuperNotSendable? in + XCTAssertIdentical(x, originalValue) + return nil + }.unwrap(orElse: { + originalValue + }).unwrap(orElse: { + SuperNotSendable() + }).whenSuccess { x in + XCTAssertIdentical(x, originalValue) + } + + promise.assumeIsolated().succeed(originalValue) + return newFuture.map { _ in }.nonisolated() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() + } + + func _eventLoopIsolated(loop: any EventLoop) throws { + let f = loop.flatSubmit { + let value = SuperNotSendable() + + // Again, all of these need to close over value. In addition, + // many need to return it as well. + let isolated = loop.assumeIsolated() + XCTAssertIdentical(isolated.nonisolated(), loop) + isolated.execute { + XCTAssertEqual(value.x, 5) + } + let firstFuture = isolated.submit { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.map { $0.x } + + let secondFuture = isolated.scheduleTask(deadline: loop.now + .milliseconds(50)) { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.futureResult.map { $0.x } + + let thirdFuture = isolated.scheduleTask(in: .milliseconds(50)) { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.futureResult.map { $0.x } + + let fourthFuture = isolated.flatScheduleTask(deadline: loop.now + .milliseconds(50)) { + let promise = loop.makePromise(of: Int.self) + promise.succeed(value.x + 1) + return promise.futureResult + }.futureResult.map { $0 } + + return EventLoopFuture.reduce( + into: 0, + [firstFuture, secondFuture, thirdFuture, fourthFuture], + on: loop + ) { $0 += $1 } + } + if let runnable = loop as? RunnableEventLoop { + runnable.advanceTimeForTests(by: .milliseconds(51)) + } + let result = try f.wait() + + XCTAssertEqual(result, 6 * 4) + } + + func _eventLoopIsolatedUnchecked(loop: any EventLoop) throws { + let f = loop.flatSubmit { + let value = SuperNotSendable() + + // Again, all of these need to close over value. In addition, + // many need to return it as well. + let isolated = loop.assumeIsolatedUnsafeUnchecked() + XCTAssertIdentical(isolated.nonisolated(), loop) + isolated.execute { + XCTAssertEqual(value.x, 5) + } + let firstFuture = isolated.submit { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.map { $0.x } + + let secondFuture = isolated.scheduleTask(deadline: loop.now + .milliseconds(50)) { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.futureResult.map { $0.x } + + let thirdFuture = isolated.scheduleTask(in: .milliseconds(50)) { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.futureResult.map { $0.x } + + let fourthFuture = isolated.flatScheduleTask(deadline: loop.now + .milliseconds(50)) { + let promise = loop.makePromise(of: Int.self) + promise.succeed(value.x + 1) + return promise.futureResult + }.futureResult.map { $0 } + + return EventLoopFuture.reduce( + into: 0, + [firstFuture, secondFuture, thirdFuture, fourthFuture], + on: loop + ) { $0 += $1 } + } + if let runnable = loop as? RunnableEventLoop { + runnable.advanceTimeForTests(by: .milliseconds(50)) + } + let result = try f.wait() + + XCTAssertEqual(result, 6 * 4) + } + + // MARK: SelectableEL + func testCompletingPromiseWithNonSendableValue_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._completingPromiseWithNonSendableValue(loop: loop) + } + + func testCompletingPromiseWithNonSendableResult_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._completingPromiseWithNonSendableResult(loop: loop) + } + + func testCompletingPromiseWithNonSendableValueUnchecked_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._completingPromiseWithNonSendableValueUnchecked(loop: loop) + } + + func testCompletingPromiseWithNonSendableResultUnchecked_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._completingPromiseWithNonSendableResultUnchecked(loop: loop) + } + + func testBackAndForthUnwrapping_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._backAndForthUnwrapping(loop: loop) + } + + func testBackAndForthUnwrappingUnchecked_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._backAndForthUnwrappingUnchecked(loop: loop) + } + + func testFutureChaining_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._futureChaining(loop: loop) + } + + func testEventLoopIsolated_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._eventLoopIsolated(loop: loop) + } + + func testEventLoopIsolatedUnchecked_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._eventLoopIsolatedUnchecked(loop: loop) + } + + // MARK: EmbeddedEL + func testCompletingPromiseWithNonSendableValue_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._completingPromiseWithNonSendableValue(loop: loop) + } + + func testCompletingPromiseWithNonSendableResult_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._completingPromiseWithNonSendableResult(loop: loop) + } + + func testCompletingPromiseWithNonSendableValueUnchecked_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._completingPromiseWithNonSendableValueUnchecked(loop: loop) + } + + func testCompletingPromiseWithNonSendableResultUnchecked_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._completingPromiseWithNonSendableResultUnchecked(loop: loop) + } + + func testBackAndForthUnwrapping_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._backAndForthUnwrapping(loop: loop) + } + + func testBackAndForthUnwrappingUnchecked_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._backAndForthUnwrappingUnchecked(loop: loop) + } + + func testFutureChaining_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._futureChaining(loop: loop) + } + + func testEventLoopIsolated_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._eventLoopIsolated(loop: loop) + } + + func testEventLoopIsolatedUnchecked_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._eventLoopIsolatedUnchecked(loop: loop) + } + + // MARK: AsyncTestingEL + func testCompletingPromiseWithNonSendableValue_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._completingPromiseWithNonSendableValue(loop: loop) + } + + func testCompletingPromiseWithNonSendableResult_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._completingPromiseWithNonSendableResult(loop: loop) + } + + func testCompletingPromiseWithNonSendableValueUnchecked_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._completingPromiseWithNonSendableValueUnchecked(loop: loop) + } + + func testCompletingPromiseWithNonSendableResultUnchecked_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._completingPromiseWithNonSendableResultUnchecked(loop: loop) + } + + func testBackAndForthUnwrapping_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._backAndForthUnwrapping(loop: loop) + } + + func testBackAndForthUnwrappingUnchecked_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._backAndForthUnwrappingUnchecked(loop: loop) + } + + func testFutureChaining_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._futureChaining(loop: loop) + } + + func testEventLoopIsolated_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._eventLoopIsolated(loop: loop) + } + + func testEventLoopIsolatedUnchecked_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._eventLoopIsolatedUnchecked(loop: loop) + } + + // MARK: Fallback + func testCompletingPromiseWithNonSendableValue_Fallback() throws { + let loop = FallbackEventLoop() + try self._completingPromiseWithNonSendableValue(loop: loop) + } + + func testCompletingPromiseWithNonSendableResult_() throws { + let loop = FallbackEventLoop() + try self._completingPromiseWithNonSendableResult(loop: loop) + } + + func testCompletingPromiseWithNonSendableValueUnchecked_Fallback() throws { + let loop = FallbackEventLoop() + try self._completingPromiseWithNonSendableValueUnchecked(loop: loop) + } + + func testCompletingPromiseWithNonSendableResultUnchecked_Fallback() throws { + let loop = FallbackEventLoop() + try self._completingPromiseWithNonSendableResultUnchecked(loop: loop) + } + + func testBackAndForthUnwrapping_Fallback() throws { + let loop = FallbackEventLoop() + try self._backAndForthUnwrapping(loop: loop) + } + + func testBackAndForthUnwrappingUnchecked_Fallback() throws { + let loop = FallbackEventLoop() + try self._backAndForthUnwrappingUnchecked(loop: loop) + } + + func testFutureChaining_Fallback() throws { + let loop = FallbackEventLoop() + try self._futureChaining(loop: loop) + } + + func testEventLoopIsolated_Fallback() throws { + let loop = FallbackEventLoop() + try self._eventLoopIsolated(loop: loop) + } + + func testEventLoopIsolatedUnchecked_Fallback() throws { + let loop = FallbackEventLoop() + try self._eventLoopIsolatedUnchecked(loop: loop) + } +} diff --git a/Tests/NIOPosixTests/EventLoopTest.swift b/Tests/NIOPosixTests/EventLoopTest.swift index f14ba2dc4..947d916be 100644 --- a/Tests/NIOPosixTests/EventLoopTest.swift +++ b/Tests/NIOPosixTests/EventLoopTest.swift @@ -1962,6 +1962,10 @@ private class EventLoopWithPreSucceededFuture: EventLoop { preconditionFailure("not implemented") } + var now: NIODeadline { + preconditionFailure("not implemented") + } + @discardableResult func scheduleTask(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled { preconditionFailure("not implemented") @@ -2013,6 +2017,10 @@ private class EventLoopWithoutPreSucceededFuture: EventLoop { preconditionFailure("not implemented") } + var now: NIODeadline { + preconditionFailure("not implemented") + } + @discardableResult func scheduleTask(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled { preconditionFailure("not implemented") diff --git a/Tests/NIOPosixTests/HappyEyeballsTest.swift b/Tests/NIOPosixTests/HappyEyeballsTest.swift index 66f0dec09..bebf3d48f 100644 --- a/Tests/NIOPosixTests/HappyEyeballsTest.swift +++ b/Tests/NIOPosixTests/HappyEyeballsTest.swift @@ -12,6 +12,8 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux +import NIOConcurrencyHelpers import NIOEmbedded import XCTest @@ -239,9 +241,12 @@ private class DummyResolver: Resolver { extension DummyResolver.Event: Equatable { } +@Sendable private func defaultChannelBuilder(loop: EventLoop, family: NIOBSDSocket.ProtocolFamily) -> EventLoopFuture { let channel = EmbeddedChannel(loop: loop as! EmbeddedEventLoop) - XCTAssertNoThrow(try channel.pipeline.addHandler(ConnectRecorder(), name: CONNECT_RECORDER).wait()) + XCTAssertNoThrow( + try channel.pipeline.syncOperations.addHandler(ConnectRecorder(), name: CONNECT_RECORDER) + ) return loop.makeSucceededFuture(channel) } @@ -249,7 +254,7 @@ private func buildEyeballer( host: String, port: Int, connectTimeout: TimeAmount = .seconds(10), - channelBuilderCallback: @escaping (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture = + channelBuilderCallback: @escaping @Sendable (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture = defaultChannelBuilder ) -> (eyeballer: HappyEyeballsConnector, resolver: DummyResolver, loop: EmbeddedEventLoop) { let loop = EmbeddedEventLoop() @@ -585,7 +590,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testMaximalConnectionDelay() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -654,7 +659,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testAllConnectionsFail() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -724,7 +729,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testDelayedAAAAResult() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -811,7 +816,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testTimeoutAfterAQuery() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -860,7 +865,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testAConnectFailsWaitingForAAAA() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -919,7 +924,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testDelayedAResult() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -965,7 +970,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testTimeoutBeforeAResponse() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -1014,7 +1019,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testAllConnectionsFailImmediately() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -1064,7 +1069,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testLaterConnections() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -1109,10 +1114,15 @@ public final class HappyEyeballsTest: XCTestCase { } func testDelayedChannelCreation() throws { - var ourChannelFutures: [EventLoopPromise] = [] + // This lock isn't really needed as the test is single-threaded, but because + // the buildEyeballer function constructs the event loop we can't use a LoopBoundBox. + // This is fine anyway. + let ourChannelFutures: NIOLockedValueBox<[EventLoopPromise]> = NIOLockedValueBox([]) let (eyeballer, resolver, loop) = buildEyeballer(host: "example.com", port: 80) { loop, _ in - ourChannelFutures.append(loop.makePromise()) - return ourChannelFutures.last!.futureResult + ourChannelFutures.withLockedValue { + $0.append(loop.makePromise()) + return $0.last!.futureResult + } } let channelFuture = eyeballer.resolveAndConnect() let expectedQueries: [DummyResolver.Event] = [ @@ -1126,37 +1136,51 @@ public final class HappyEyeballsTest: XCTestCase { // Return the IPv6 results and observe the channel creation attempts. resolver.v6Promise.succeed(MANY_IPv6_RESULTS) for channelCount in 1...10 { - XCTAssertEqual(ourChannelFutures.count, channelCount) + XCTAssertEqual( + ourChannelFutures.withLockedValue { $0.count }, + channelCount + ) loop.advanceTime(by: .milliseconds(250)) } XCTAssertFalse(channelFuture.isFulfilled) // Succeed the first channel future, which will connect because the default // channel builder always does. - defaultChannelBuilder(loop: loop, family: .inet6).whenSuccess { - ourChannelFutures.first!.succeed($0) - XCTAssertEqual($0.state(), .connected) + defaultChannelBuilder(loop: loop, family: .inet6).whenSuccess { result in + ourChannelFutures.withLockedValue { + $0.first!.succeed(result) + } + XCTAssertEqual(result.state(), .connected) } XCTAssertTrue(channelFuture.isFulfilled) // Ok, now succeed the second channel future. This should cause the channel to immediately be closed. - defaultChannelBuilder(loop: loop, family: .inet6).whenSuccess { - ourChannelFutures[1].succeed($0) - XCTAssertEqual($0.state(), .closed) + defaultChannelBuilder(loop: loop, family: .inet6).whenSuccess { result in + ourChannelFutures.withLockedValue { + $0[1].succeed(result) + } + XCTAssertEqual(result.state(), .closed) } - // Ok, now fail the third channel future. Nothing bad should happen here. - ourChannelFutures[2].fail(DummyError()) + try ourChannelFutures.withLockedValue { + // Ok, now fail the third channel future. Nothing bad should happen here. + $0[2].fail(DummyError()) - // Verify that the first channel is the one listed as connected. - XCTAssertTrue((try ourChannelFutures.first!.futureResult.wait()) === (try channelFuture.wait())) + // Verify that the first channel is the one listed as connected. + XCTAssertTrue((try $0.first!.futureResult.wait()) === (try channelFuture.wait())) + } } func testChannelCreationFails() throws { - var errors: [DummyError] = [] + // This lock isn't really needed as the test is single-threaded, but because + // the buildEyeballer function constructs the event loop we can't use a LoopBoundBox. + // This is fine anyway. + let errors: NIOLockedValueBox<[DummyError]> = NIOLockedValueBox([]) let (eyeballer, resolver, loop) = buildEyeballer(host: "example.com", port: 80) { loop, _ in - errors.append(DummyError()) - return loop.makeFailedFuture(errors.last!) + errors.withLockedValue { + $0.append(DummyError()) + return loop.makeFailedFuture($0.last!) + } } let channelFuture = eyeballer.resolveAndConnect() let expectedQueries: [DummyResolver.Event] = [ @@ -1170,21 +1194,21 @@ public final class HappyEyeballsTest: XCTestCase { // Here the AAAA and A results return. We are going to fail the channel creation // instantly, which should cause all 20 to appear. resolver.v6Promise.succeed(MANY_IPv6_RESULTS) - XCTAssertEqual(errors.count, 10) + XCTAssertEqual(errors.withLockedValue { $0.count }, 10) XCTAssertFalse(channelFuture.isFulfilled) resolver.v4Promise.succeed(MANY_IPv4_RESULTS) - XCTAssertEqual(errors.count, 20) + XCTAssertEqual(errors.withLockedValue { $0.count }, 20) XCTAssertTrue(channelFuture.isFulfilled) if let error = channelFuture.getError() as? NIOConnectionError { - XCTAssertEqual(error.connectionErrors.map { $0.error as! DummyError }, errors) + XCTAssertEqual(error.connectionErrors.map { $0.error as! DummyError }, errors.withLockedValue { $0 }) } else { XCTFail("Got unexpected error: \(String(describing: channelFuture.getError()))") } } func testCancellationSyncWithConnectDelay() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -1232,7 +1256,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testCancellationSyncWithResolutionDelay() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -1308,4 +1332,83 @@ public final class HappyEyeballsTest: XCTestCase { XCTAssertNoThrow(try client.close().wait()) } + + func testResolutionTimeoutAndResolutionInSameTick() throws { + let channels = ChannelSet() + let (eyeballer, resolver, loop) = buildEyeballer(host: "example.com", port: 80) { + let channelFuture = defaultChannelBuilder(loop: $0, family: $1) + channelFuture.whenSuccess { channel in + try! channel.pipeline.addHandler(ConnectionDelayer(), name: CONNECT_DELAYER, position: .first).wait() + channels.append(channel) + } + return channelFuture + } + let targetFuture = eyeballer.resolveAndConnect().flatMapThrowing { (channel) -> String? in + let target = channel.connectTarget() + _ = try (channel as! EmbeddedChannel).finish() + return target + } + loop.run() + + // Then, queue a task to resolve the v6 promise after 50ms. + // Why 50ms? This is the same time as the resolution delay. + let promise = resolver.v6Promise + loop.scheduleTask(in: .milliseconds(50)) { + promise.fail(DummyError()) + } + + // Kick off the IPv4 resolution. This triggers the timer for the resolution delay. + resolver.v4Promise.succeed(SINGLE_IPv4_RESULT) + loop.run() + + // Advance time 50ms. + loop.advanceTime(by: .milliseconds(50)) + + // Then complete the connection future. + XCTAssertEqual(channels.count, 1) + channels.first!.succeedConnection() + + // Should be done. + let target = try targetFuture.wait() + XCTAssertEqual(target!, "10.0.0.1") + + // We should have had queries for AAAA and A. + let expectedQueries: [DummyResolver.Event] = [ + .aaaa(host: "example.com", port: 80), + .a(host: "example.com", port: 80), + ] + XCTAssertEqual(resolver.events, expectedQueries) + } +} + +struct ChannelSet: Sendable, Sequence { + private let channels: NIOLockedValueBox<[Channel]> = .init([]) + + func append(_ channel: Channel) { + self.channels.withLockedValue { $0.append(channel) } + } + + var first: Channel? { + self.channels.withLockedValue { $0.first } + } + + var last: Channel? { + self.channels.withLockedValue { $0.last } + } + + var count: Int { + self.channels.withLockedValue { $0.count } + } + + subscript(index: Int) -> Channel { + self.channels.withLockedValue { $0[index] } + } + + func makeIterator() -> some IteratorProtocol { + self.channels.withLockedValue { $0.makeIterator() } + } + + func finishAll() { + self.channels.withLockedValue { $0 }.finishAll() + } } diff --git a/Tests/NIOPosixTests/MulticastTest.swift b/Tests/NIOPosixTests/MulticastTest.swift index c9ae19d29..e2fe3a8b0 100644 --- a/Tests/NIOPosixTests/MulticastTest.swift +++ b/Tests/NIOPosixTests/MulticastTest.swift @@ -11,7 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// - +import CNIOLinux import NIOCore import NIOPosix import XCTest diff --git a/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift b/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift index b115ac2f8..16dc984ac 100644 --- a/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift +++ b/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import Atomics import NIOCore import NIOEmbedded import NIOPosix @@ -27,8 +28,7 @@ protocol ScheduledCallbackTestRequirements { // ELG-backed ELs need to be shutdown via the ELG. func shutdownEventLoop() async throws - // This is here for NIOAsyncTestingEventLoop only. - func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R + func waitForLoopTick() async throws } final class MTELGScheduledCallbackTests: _BaseScheduledCallbackTests { @@ -44,8 +44,8 @@ final class MTELGScheduledCallbackTests: _BaseScheduledCallbackTests { try await self.group.shutdownGracefully() } - func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R { - try body() + func waitForLoopTick() async throws { + try await self.loop.submit {}.get() } } @@ -67,8 +67,8 @@ final class NIOAsyncTestingEventLoopScheduledCallbackTests: _BaseScheduledCallba await self._loop.shutdownGracefully() } - func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R { - try await self._loop.executeInContext(body) + func waitForLoopTick() async throws { + try await self._loop.executeInContext {} } } @@ -93,15 +93,12 @@ extension _BaseScheduledCallbackTests { func advanceTime(by amount: TimeAmount) async throws { try await self.requirements.advanceTime(by: amount) + try await self.requirements.waitForLoopTick() } func shutdownEventLoop() async throws { try await self.requirements.shutdownEventLoop() } - - func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R { - try await self.requirements.maybeInContext(body) - } } // The tests, abstracted over any of the event loops. @@ -111,10 +108,10 @@ extension _BaseScheduledCallbackTests { let handler = MockScheduledCallbackHandler() _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 0) } + handler.assert(callbackCount: 0, cancelCount: 0) try await self.advanceTime(by: .microseconds(1)) - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 0) } + handler.assert(callbackCount: 0, cancelCount: 0) } func testSheduledCallbackExecutedAtDeadline() async throws { @@ -123,7 +120,7 @@ extension _BaseScheduledCallbackTests { _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) try await self.advanceTime(by: .milliseconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) - try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + handler.assert(callbackCount: 1, cancelCount: 0) } func testMultipleSheduledCallbacksUsingSameHandler() async throws { @@ -135,7 +132,7 @@ extension _BaseScheduledCallbackTests { try await self.advanceTime(by: .milliseconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) - try await self.maybeInContext { handler.assert(callbackCount: 2, cancelCount: 0) } + handler.assert(callbackCount: 2, cancelCount: 0) _ = try self.loop.scheduleCallback(in: .milliseconds(2), handler: handler) _ = try self.loop.scheduleCallback(in: .milliseconds(3), handler: handler) @@ -143,7 +140,7 @@ extension _BaseScheduledCallbackTests { try await self.advanceTime(by: .milliseconds(3)) try await handler.waitForCallback(timeout: .seconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) - try await self.maybeInContext { handler.assert(callbackCount: 4, cancelCount: 0) } + handler.assert(callbackCount: 4, cancelCount: 0) } func testMultipleSheduledCallbacksUsingDifferentHandlers() async throws { @@ -156,8 +153,8 @@ extension _BaseScheduledCallbackTests { try await self.advanceTime(by: .milliseconds(1)) try await handlerA.waitForCallback(timeout: .seconds(1)) try await handlerB.waitForCallback(timeout: .seconds(1)) - try await self.maybeInContext { handlerA.assert(callbackCount: 1, cancelCount: 0) } - try await self.maybeInContext { handlerB.assert(callbackCount: 1, cancelCount: 0) } + handlerA.assert(callbackCount: 1, cancelCount: 0) + handlerB.assert(callbackCount: 1, cancelCount: 0) } func testCancelExecutesCancellationCallback() async throws { @@ -165,7 +162,8 @@ extension _BaseScheduledCallbackTests { let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) scheduledCallback.cancel() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + try await self.requirements.waitForLoopTick() + handler.assert(callbackCount: 0, cancelCount: 1) } func testCancelAfterDeadlineDoesNotExecutesCancellationCallback() async throws { @@ -175,7 +173,8 @@ extension _BaseScheduledCallbackTests { try await self.advanceTime(by: .milliseconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) scheduledCallback.cancel() - try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + try await self.requirements.waitForLoopTick() + handler.assert(callbackCount: 1, cancelCount: 0) } func testCancelAfterCancelDoesNotCallCancellationCallbackAgain() async throws { @@ -183,8 +182,10 @@ extension _BaseScheduledCallbackTests { let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) scheduledCallback.cancel() + try await self.requirements.waitForLoopTick() scheduledCallback.cancel() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + try await self.requirements.waitForLoopTick() + handler.assert(callbackCount: 0, cancelCount: 1) } func testCancelAfterShutdownDoesNotCallCancellationCallbackAgain() async throws { @@ -192,10 +193,10 @@ extension _BaseScheduledCallbackTests { let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) try await self.shutdownEventLoop() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + handler.assert(callbackCount: 0, cancelCount: 1) scheduledCallback.cancel() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + handler.assert(callbackCount: 0, cancelCount: 1) } func testShutdownCancelsOutstandingScheduledCallbacks() async throws { @@ -203,7 +204,7 @@ extension _BaseScheduledCallbackTests { _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) try await self.shutdownEventLoop() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + handler.assert(callbackCount: 0, cancelCount: 1) } func testShutdownDoesNotCancelCancelledCallbacksAgain() async throws { @@ -211,10 +212,11 @@ extension _BaseScheduledCallbackTests { let handle = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) handle.cancel() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + try await self.requirements.waitForLoopTick() + handler.assert(callbackCount: 0, cancelCount: 1) try await self.shutdownEventLoop() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + handler.assert(callbackCount: 0, cancelCount: 1) } func testShutdownDoesNotCancelPastCallbacks() async throws { @@ -223,16 +225,16 @@ extension _BaseScheduledCallbackTests { _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) try await self.advanceTime(by: .milliseconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) - try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + handler.assert(callbackCount: 1, cancelCount: 0) try await self.shutdownEventLoop() - try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + handler.assert(callbackCount: 1, cancelCount: 0) } } -private final class MockScheduledCallbackHandler: NIOScheduledCallbackHandler { - var callbackCount = 0 - var cancelCount = 0 +private final class MockScheduledCallbackHandler: NIOScheduledCallbackHandler, Sendable { + let callbackCount = ManagedAtomic(0) + let cancelCount = ManagedAtomic(0) let callbackStream: AsyncStream private let callbackStreamContinuation: AsyncStream.Continuation @@ -246,17 +248,29 @@ private final class MockScheduledCallbackHandler: NIOScheduledCallbackHandler { } func handleScheduledCallback(eventLoop: some EventLoop) { - self.callbackCount += 1 + self.callbackCount.wrappingIncrement(by: 1, ordering: .sequentiallyConsistent) self.callbackStreamContinuation.yield() } func didCancelScheduledCallback(eventLoop: some EventLoop) { - self.cancelCount += 1 + self.cancelCount.wrappingIncrement(by: 1, ordering: .sequentiallyConsistent) } func assert(callbackCount: Int, cancelCount: Int, file: StaticString = #file, line: UInt = #line) { - XCTAssertEqual(self.callbackCount, callbackCount, "Unexpected callback count", file: file, line: line) - XCTAssertEqual(self.cancelCount, cancelCount, "Unexpected cancel count", file: file, line: line) + XCTAssertEqual( + self.callbackCount.load(ordering: .sequentiallyConsistent), + callbackCount, + "Unexpected callback count", + file: file, + line: line + ) + XCTAssertEqual( + self.cancelCount.load(ordering: .sequentiallyConsistent), + cancelCount, + "Unexpected cancel count", + file: file, + line: line + ) } func waitForCallback(timeout: TimeAmount, file: StaticString = #file, line: UInt = #line) async throws { diff --git a/Tests/NIOPosixTests/NIOThreadPoolTest.swift b/Tests/NIOPosixTests/NIOThreadPoolTest.swift index ed39352df..d88f7c87e 100644 --- a/Tests/NIOPosixTests/NIOThreadPoolTest.swift +++ b/Tests/NIOPosixTests/NIOThreadPoolTest.swift @@ -15,6 +15,7 @@ import Atomics import Dispatch import NIOConcurrencyHelpers +import NIOCore import NIOEmbedded import XCTest @@ -78,18 +79,15 @@ class NIOThreadPoolTest: XCTestCase { // The lock here is arguably redundant with the dispatchgroup, but let's make // this test thread-safe even if I screw up. - let lock = NIOLock() - let threadOne: NIOLockedValueBox = NIOLockedValueBox(Thread?.none) - let threadTwo: NIOLockedValueBox = NIOLockedValueBox(Thread?.none) + let threadOne: NIOLockedValueBox = NIOLockedValueBox(NIOThread?.none) + let threadTwo: NIOLockedValueBox = NIOLockedValueBox(NIOThread?.none) completionGroup.enter() pool.submit { s in precondition(s == .active) - lock.withLock { () -> Void in - threadOne.withLockedValue { threadOne in - XCTAssertEqual(threadOne, nil) - threadOne = Thread.current - } + threadOne.withLockedValue { threadOne in + XCTAssertEqual(threadOne, nil) + threadOne = NIOThread.current } completionGroup.leave() } @@ -99,22 +97,18 @@ class NIOThreadPoolTest: XCTestCase { completionGroup.enter() pool.submit { s in precondition(s == .active) - lock.withLock { () -> Void in - threadTwo.withLockedValue { threadTwo in - XCTAssertEqual(threadTwo, nil) - threadTwo = Thread.current - } + threadTwo.withLockedValue { threadTwo in + XCTAssertEqual(threadTwo, nil) + threadTwo = NIOThread.current } completionGroup.leave() } completionGroup.wait() - lock.withLock { () -> Void in - XCTAssertNotNil(threadOne) - XCTAssertNotNil(threadTwo) - XCTAssertEqual(threadOne.withLockedValue { $0 }, threadTwo.withLockedValue { $0 }) - } + XCTAssertNotNil(threadOne.withLockedValue { $0 }) + XCTAssertNotNil(threadTwo.withLockedValue { $0 }) + XCTAssertEqual(threadOne.withLockedValue { $0 }, threadTwo.withLockedValue { $0 }) } func testAsyncThreadPool() async throws { diff --git a/Tests/NIOPosixTests/NonBlockingFileIOTest.swift b/Tests/NIOPosixTests/NonBlockingFileIOTest.swift index 26ab80d61..4e452b1f1 100644 --- a/Tests/NIOPosixTests/NonBlockingFileIOTest.swift +++ b/Tests/NIOPosixTests/NonBlockingFileIOTest.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import Atomics +import CNIOLinux import NIOCore import XCTest diff --git a/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift b/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift index 3ef944b19..dee71c2a6 100644 --- a/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift +++ b/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift @@ -12,6 +12,8 @@ // //===----------------------------------------------------------------------===// +import CNIODarwin +import CNIOLinux import NIOEmbedded import XCTest diff --git a/Tests/NIOPosixTests/RawSocketBootstrapTests.swift b/Tests/NIOPosixTests/RawSocketBootstrapTests.swift index a65ad1ae9..a7c42c3c8 100644 --- a/Tests/NIOPosixTests/RawSocketBootstrapTests.swift +++ b/Tests/NIOPosixTests/RawSocketBootstrapTests.swift @@ -47,8 +47,13 @@ final class RawSocketBootstrapTests: XCTestCase { let elg = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { XCTAssertNoThrow(try elg.syncShutdownGracefully()) } let channel = try NIORawSocketBootstrap(group: elg) - .channelInitializer { - $0.pipeline.addHandler(DatagramReadRecorder(), name: "ByteReadRecorder") + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler( + DatagramReadRecorder(), + name: "ByteReadRecorder" + ) + } } .bind(host: "127.0.0.1", ipProtocol: .reservedForTesting).wait() defer { XCTAssertNoThrow(try channel.close().wait()) } @@ -93,15 +98,25 @@ final class RawSocketBootstrapTests: XCTestCase { let elg = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { XCTAssertNoThrow(try elg.syncShutdownGracefully()) } let readChannel = try NIORawSocketBootstrap(group: elg) - .channelInitializer { - $0.pipeline.addHandler(DatagramReadRecorder(), name: "ByteReadRecorder") + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler( + DatagramReadRecorder(), + name: "ByteReadRecorder" + ) + } } .bind(host: "127.0.0.1", ipProtocol: .reservedForTesting).wait() defer { XCTAssertNoThrow(try readChannel.close().wait()) } let writeChannel = try NIORawSocketBootstrap(group: elg) - .channelInitializer { - $0.pipeline.addHandler(DatagramReadRecorder(), name: "ByteReadRecorder") + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler( + DatagramReadRecorder(), + name: "ByteReadRecorder" + ) + } } .bind(host: "127.0.0.1", ipProtocol: .reservedForTesting).wait() defer { XCTAssertNoThrow(try writeChannel.close().wait()) } @@ -147,8 +162,13 @@ final class RawSocketBootstrapTests: XCTestCase { defer { XCTAssertNoThrow(try elg.syncShutdownGracefully()) } let channel = try NIORawSocketBootstrap(group: elg) .channelOption(.ipOption(.ip_hdrincl), value: 1) - .channelInitializer { - $0.pipeline.addHandler(DatagramReadRecorder(), name: "ByteReadRecorder") + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler( + DatagramReadRecorder(), + name: "ByteReadRecorder" + ) + } } .bind(host: "127.0.0.1", ipProtocol: .reservedForTesting).wait() defer { XCTAssertNoThrow(try channel.close().wait()) } diff --git a/Tests/NIOPosixTests/SALEventLoopTests.swift b/Tests/NIOPosixTests/SALEventLoopTests.swift index 6cc81f5c8..ad3656475 100644 --- a/Tests/NIOPosixTests/SALEventLoopTests.swift +++ b/Tests/NIOPosixTests/SALEventLoopTests.swift @@ -59,16 +59,12 @@ final class SALEventLoopTests: XCTestCase, SALTest { } // Now execute 10 tasks. - var i = 0 for _ in 0..<10 { - thisLoop.execute { - i &+= 1 - } + thisLoop.execute {} } // Now enqueue a "last" task. thisLoop.execute { - i &+= 1 promise.succeed(()) } diff --git a/Tests/NIOPosixTests/SocketAddressTest.swift b/Tests/NIOPosixTests/SocketAddressTest.swift index d12d8e626..e08ebbe74 100644 --- a/Tests/NIOPosixTests/SocketAddressTest.swift +++ b/Tests/NIOPosixTests/SocketAddressTest.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import XCTest @testable import NIOCore diff --git a/Tests/NIOPosixTests/SocketChannelTest.swift b/Tests/NIOPosixTests/SocketChannelTest.swift index cb8161a7e..a42eefb0f 100644 --- a/Tests/NIOPosixTests/SocketChannelTest.swift +++ b/Tests/NIOPosixTests/SocketChannelTest.swift @@ -1138,11 +1138,12 @@ class DropAllReadsOnTheFloorHandler: ChannelDuplexHandler { // What we're trying to do here is forcing a close without calling `close`. We know that the other side of // the connection is fully closed but because we support half-closure, we need to write to 'learn' that the // other side has actually fully closed the socket. + let promise = self.waitUntilWriteFailedPromise func writeUntilError() { context.writeAndFlush(Self.wrapOutboundOut(buffer)).map { writeUntilError() }.whenFailure { (_: Error) in - self.waitUntilWriteFailedPromise.succeed(()) + promise.succeed(()) } } writeUntilError() diff --git a/Tests/NIOPosixTests/SocketOptionProviderTest.swift b/Tests/NIOPosixTests/SocketOptionProviderTest.swift index 962a620da..32d2c704e 100644 --- a/Tests/NIOPosixTests/SocketOptionProviderTest.swift +++ b/Tests/NIOPosixTests/SocketOptionProviderTest.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOCore import NIOPosix import XCTest diff --git a/Tests/NIOPosixTests/StreamChannelsTest.swift b/Tests/NIOPosixTests/StreamChannelsTest.swift index 072f35d41..668dd1d33 100644 --- a/Tests/NIOPosixTests/StreamChannelsTest.swift +++ b/Tests/NIOPosixTests/StreamChannelsTest.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import Atomics +import CNIOLinux import NIOCore import NIOTestUtils import XCTest diff --git a/Tests/NIOPosixTests/SyscallAbstractionLayer.swift b/Tests/NIOPosixTests/SyscallAbstractionLayer.swift index 6137b4349..36e774e2d 100644 --- a/Tests/NIOPosixTests/SyscallAbstractionLayer.swift +++ b/Tests/NIOPosixTests/SyscallAbstractionLayer.swift @@ -15,6 +15,7 @@ // This file contains a syscall abstraction layer (SAL) which hooks the Selector and the Socket in a way that we can // play the kernel whilst NIO thinks it's running on a real OS. +import CNIOLinux import NIOConcurrencyHelpers import NIOCore import XCTest diff --git a/Tests/NIOPosixTests/SystemTest.swift b/Tests/NIOPosixTests/SystemTest.swift index aabe80090..41840e3d0 100644 --- a/Tests/NIOPosixTests/SystemTest.swift +++ b/Tests/NIOPosixTests/SystemTest.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOCore import XCTest diff --git a/Tests/NIOPosixTests/TestUtils.swift b/Tests/NIOPosixTests/TestUtils.swift index c239a09c8..ab5a11891 100644 --- a/Tests/NIOPosixTests/TestUtils.swift +++ b/Tests/NIOPosixTests/TestUtils.swift @@ -127,7 +127,7 @@ func withTemporaryUnixDomainSocketPathName( shortEnoughPath = path restoreSavedCWD = false } catch SocketAddressError.unixDomainSocketPathTooLong { - FileManager.default.changeCurrentDirectoryPath( + _ = FileManager.default.changeCurrentDirectoryPath( URL(fileURLWithPath: path).deletingLastPathComponent().absoluteString ) shortEnoughPath = URL(fileURLWithPath: path).lastPathComponent @@ -141,7 +141,7 @@ func withTemporaryUnixDomainSocketPathName( try? FileManager.default.removeItem(atPath: path) } if restoreSavedCWD { - FileManager.default.changeCurrentDirectoryPath(saveCurrentDirectory) + _ = FileManager.default.changeCurrentDirectoryPath(saveCurrentDirectory) } } return try body(shortEnoughPath) diff --git a/Tests/NIOPosixTests/ThreadTest.swift b/Tests/NIOPosixTests/ThreadTest.swift index 8320f068d..d0d5b1172 100644 --- a/Tests/NIOPosixTests/ThreadTest.swift +++ b/Tests/NIOPosixTests/ThreadTest.swift @@ -14,6 +14,7 @@ import Dispatch import NIOConcurrencyHelpers +import NIOCore import XCTest @testable import NIOPosix diff --git a/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift b/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift index 8b671fce6..9d729c553 100644 --- a/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift +++ b/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift @@ -83,7 +83,13 @@ class UniversalBootstrapSupportTest: XCTestCase { let client = try NIOClientTCPBootstrap(ClientBootstrap(group: group), tls: DummyTLSProvider()) .channelInitializer { channel in - channel.pipeline.addHandlers(counter1, DropChannelReadsHandler(), counter2) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandlers( + counter1, + DropChannelReadsHandler(), + counter2 + ) + } } .channelOption(.autoRead, value: false) .connectTimeout(.hours(1)) diff --git a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift index 23202c2c4..11e8f848e 100644 --- a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift +++ b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift @@ -170,7 +170,9 @@ class WebSocketClientEndToEndTests: XCTestCase { let basicUpgrader = NIOWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -244,7 +246,9 @@ class WebSocketClientEndToEndTests: XCTestCase { let basicUpgrader = NIOWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -275,7 +279,9 @@ class WebSocketClientEndToEndTests: XCTestCase { let basicUpgrader = NIOWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -307,7 +313,9 @@ class WebSocketClientEndToEndTests: XCTestCase { let basicUpgrader = NIOWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -332,13 +340,12 @@ class WebSocketClientEndToEndTests: XCTestCase { } fileprivate func runSuccessfulUpgrade() throws -> (EmbeddedChannel, WebSocketRecorderHandler) { - - let handler = WebSocketRecorderHandler() - let basicUpgrader = NIOWebSocketClientUpgrader( requestKey: "OfS0wDaT5NoxF2gqm7Zj2YtetzM=", upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(handler) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -361,6 +368,10 @@ class WebSocketClientEndToEndTests: XCTestCase { clientChannel.embeddedEventLoop.run() + // Ok, now grab the handler. We can do this with sync operations, because this is an + // EmbeddedChannel. + let handler = try clientChannel.pipeline.syncOperations.handler(type: WebSocketRecorderHandler.self) + return (clientChannel, handler) } @@ -455,6 +466,35 @@ class WebSocketClientEndToEndTests: XCTestCase { // Close the pipeline. XCTAssertNoThrow(try clientChannel.close().wait()) } + + func testErrorHandlerMaskFrameForClient() throws { + + let (clientChannel, _) = try self.runSuccessfulUpgrade() + let maskBitMask: UInt8 = 0x80 + + var data = clientChannel.allocator.buffer(capacity: 4) + // A fake frame header that claims that the length of the frame is 16385 bytes, + // larger than the frame max. + data.writeBytes([0x81, 0xFE, 0x40, 0x01]) + + XCTAssertThrowsError(try clientChannel.writeInbound(data)) { error in + XCTAssertEqual(.invalidFrameLength, error as? NIOWebSocketError) + } + + clientChannel.embeddedEventLoop.run() + var buffer = try clientChannel.readAllOutboundBuffers() + + guard let (_, secondByte) = buffer.readMultipleIntegers(as: (UInt8, UInt8).self) else { + XCTFail("Insufficient bytes from WebSocket frame") + return + } + + let maskedBit = (secondByte & maskBitMask) + XCTAssertEqual(0x80, maskedBit) + + XCTAssertNoThrow(!clientChannel.isActive) + XCTAssertTrue(try clientChannel.finish(acceptAlreadyClosed: true).isClean) + } } #if !canImport(Darwin) || swift(>=5.10) @@ -501,7 +541,9 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { let basicUpgrader = NIOTypedWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -570,7 +612,9 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { let basicUpgrader = NIOTypedWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -603,7 +647,9 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { let basicUpgrader = NIOTypedWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -637,7 +683,9 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { let basicUpgrader = NIOTypedWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -665,12 +713,12 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { } override fileprivate func runSuccessfulUpgrade() throws -> (EmbeddedChannel, WebSocketRecorderHandler) { - let handler = WebSocketRecorderHandler() - let basicUpgrader = NIOTypedWebSocketClientUpgrader( requestKey: "OfS0wDaT5NoxF2gqm7Zj2YtetzM=", upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(handler) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -695,6 +743,10 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { try upgradeResult.wait() + // Ok, now grab the handler. We can do this with sync operations, because this is an + // EmbeddedChannel. + let handler = try clientChannel.pipeline.syncOperations.handler(type: WebSocketRecorderHandler.self) + return (clientChannel, handler) } } diff --git a/dev/alloc-limits-from-test-output b/dev/alloc-limits-from-test-output index 2fa9322ce..d6718709d 100755 --- a/dev/alloc-limits-from-test-output +++ b/dev/alloc-limits-from-test-output @@ -49,6 +49,12 @@ case "$mode_flag" in ;; esac +# stdin is coming from a terminal, i.e. nothing is being piped in. +if [[ -t 0 ]]; then + usage + exit 1 +fi + function allow_slack() { raw="$1" if [[ ! "$raw" =~ ^[0-9]+$ ]]; then diff --git a/dev/malloc-aggregation.d b/dev/malloc-aggregation.d index a0c2f3aa4..af9803fc3 100755 --- a/dev/malloc-aggregation.d +++ b/dev/malloc-aggregation.d @@ -28,17 +28,24 @@ printf("=====\n"); } +pid$target::aligned_alloc:entry, +pid$target::calloc:entry, pid$target::malloc:entry, pid$target::posix_memalign:entry, pid$target::realloc:entry, pid$target::reallocf:entry, -pid$target::calloc:entry, pid$target::valloc:entry, -pid$target::malloc_zone_malloc:entry, -pid$target::malloc_zone_realloc:entry, +pid$target::malloc_type_aligned_alloc:entry, +pid$target::malloc_type_calloc:entry, +pid$target::malloc_type_malloc:entry, +pid$target::malloc_type_posix_memalign:entry, +pid$target::malloc_type_realloc:entry, +pid$target::malloc_type_valloc:entry, pid$target::malloc_zone_calloc:entry, -pid$target::malloc_zone_valloc:entry, -pid$target::malloc_zone_memalign:entry { +pid$target::malloc_zone_malloc:entry, +pid$target::malloc_zone_memalign:entry, +pid$target::malloc_zone_realloc:entry, +pid$target::malloc_zone_valloc:entry { @malloc_calls[ustack()] = count(); } diff --git a/dev/stackdiff-dtrace.py b/dev/stackdiff-dtrace.py index 6f95335f5..a277915d6 100755 --- a/dev/stackdiff-dtrace.py +++ b/dev/stackdiff-dtrace.py @@ -17,7 +17,7 @@ import collections import re import sys -num_regex = "^ +([0-9]+)$" +num_regex = b"^ +([0-9]+)$" def put_in_dict(path): @@ -54,10 +54,10 @@ def put_in_dict(path): # libswiftCore.dylib`swift_allocObject+0x27 # (truncated) dictionary = collections.defaultdict(list) - with open(path, "r") as f: + with open(path, "rb") as f: current_stack = [] for line in f: - if not line.startswith(" "): + if not line.startswith(b" "): # All lines we're intereted in are indented so ignore this one. pass elif re.match(num_regex, line): @@ -69,10 +69,10 @@ def put_in_dict(path): # everything before the '+'. We only take at most the first 8 # lines for the key so that we group 'similar' stacks in our # output. - key = "\n".join(line.split("+")[0] for line in current_stack[:8]) + key = b"\n".join(line.split(b"+")[0] for line in current_stack[:8]) # Record this stack and reset our state to build a new one. - dictionary[key].append((int(line), "\n".join(current_stack))) + dictionary[key].append((int(line), b"\n".join(current_stack))) current_stack = [] else: # This line doesn't contain just a number. This might be an @@ -106,7 +106,7 @@ def extract_useful_keys(d): def print_dictionary_member(d, key): print(total_count_for_key(d, key)) - print(key) + print(key.decode('utf8')) print() print_dictionary_member_detail(d, key) print() @@ -116,7 +116,7 @@ def print_dictionary_member_detail(d, key): value = d[key] for (count, stack) in value: print(" %d" % count) - print(" " + stack.replace("\n", "\n ")) + print((b" " + stack.replace(b"\n", b"\n ")).decode('utf8')) def usage(): diff --git a/scripts/check-cxx-interop-compatibility.sh b/scripts/check-cxx-interop-compatibility.sh index 5ad33a609..9e868e94b 100755 --- a/scripts/check-cxx-interop-compatibility.sh +++ b/scripts/check-cxx-interop-compatibility.sh @@ -33,7 +33,7 @@ swift package init { echo "let swiftSettings: [SwiftSetting] = [.interoperabilityMode(.Cxx)]" - echo "for target in package.targets { target.swiftSettings = swiftSettings }" + echo "for target in package.targets { target.swiftSettings = (target.swiftSettings ?? []) + swiftSettings }" } >> Package.swift echo "package.dependencies.append(.package(path: \"$source_dir\"))" >> Package.swift diff --git a/scripts/check-matrix-job.ps1 b/scripts/check-matrix-job.ps1 index c48aeb550..3f60cc5e8 100644 --- a/scripts/check-matrix-job.ps1 +++ b/scripts/check-matrix-job.ps1 @@ -52,7 +52,7 @@ $command = $env:COMMAND $command_5_9 = $env:COMMAND_OVERRIDE_5_9 $command_5_10 = $env:COMMAND_OVERRIDE_5_10 $command_6_0 = $env:COMMAND_OVERRIDE_6_0 -$command_nightly_6_0 = $env:COMMAND_OVERRIDE_NIGHTLY_6_0 +$command_nightly_6_1 = $env:COMMAND_OVERRIDE_NIGHTLY_6_1 $command_nightly_main = $env:COMMAND_OVERRIDE_NIGHTLY_MAIN if ($swift_version -eq "5.9" -and $command_5_9) { @@ -64,9 +64,9 @@ if ($swift_version -eq "5.9" -and $command_5_9) { } elseif ($swift_version -eq "6.0" -and $command_6_0) { Log "Running 6.0 command override" Invoke-Expression $command_6_0 -} elseif ($swift_version -eq "nightly-6.0" -and $command_nightly_6_0) { - Log "Running nightly 6.0 command override" - Invoke-Expression $command_nightly_6_0 +} elseif ($swift_version -eq "nightly-6.1" -and $command_nightly_6_1) { + Log "Running nightly 6.1 command override" + Invoke-Expression $command_nightly_6_1 } elseif ($swift_version -eq "nightly-main" -and $command_nightly_main) { Log "Running nightly main command override" Invoke-Expression $command_nightly_main diff --git a/scripts/check-matrix-job.sh b/scripts/check-matrix-job.sh index 3b264670c..a6723b929 100755 --- a/scripts/check-matrix-job.sh +++ b/scripts/check-matrix-job.sh @@ -25,7 +25,7 @@ command="$COMMAND" command_5_9="$COMMAND_OVERRIDE_5_9" command_5_10="$COMMAND_OVERRIDE_5_10" command_6_0="$COMMAND_OVERRIDE_6_0" -command_nightly_6_0="$COMMAND_OVERRIDE_NIGHTLY_6_0" +command_nightly_6_1="${COMMAND_OVERRIDE_NIGHTLY_6_1:=""}" command_nightly_main="$COMMAND_OVERRIDE_NIGHTLY_MAIN" if [[ "$swift_version" == "5.9" ]] && [[ -n "$command_5_9" ]]; then @@ -37,9 +37,9 @@ elif [[ "$swift_version" == "5.10" ]] && [[ -n "$command_5_10" ]]; then elif [[ "$swift_version" == "6.0" ]] && [[ -n "$command_6_0" ]]; then log "Running 6.0 command override" eval "$command_6_0" -elif [[ "$swift_version" == "nightly-6.0" ]] && [[ -n "$command_nightly_6_0" ]]; then - log "Running nightly 6.0 command override" - eval "$command_nightly_6_0" +elif [[ "$swift_version" == "nightly-6.1" ]] && [[ -n "$command_nightly_6_1" ]]; then + log "Running nightly 6.1 command override" + eval "$command_nightly_6_1" elif [[ "$swift_version" == "nightly-main" ]] && [[ -n "$command_nightly_main" ]]; then log "Running nightly main command override" eval "$command_nightly_main" diff --git a/scripts/generate_matrix.sh b/scripts/generate_matrix.sh new file mode 100755 index 000000000..56a8ca6b9 --- /dev/null +++ b/scripts/generate_matrix.sh @@ -0,0 +1,153 @@ +#!/bin/bash +##===----------------------------------------------------------------------===## +## +## 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 +## +##===----------------------------------------------------------------------===## + +# Parameters +linux_command="$MATRIX_LINUX_COMMAND" # required if any Linux pipeline is enabled +linux_setup_command="$MATRIX_LINUX_SETUP_COMMAND" +linux_5_9_enabled="${MATRIX_LINUX_5_9_ENABLED:=true}" +linux_5_9_command_arguments="$MATRIX_LINUX_5_9_COMMAND_ARGUMENTS" +linux_5_10_enabled="${MATRIX_LINUX_5_10_ENABLED:=true}" +linux_5_10_command_arguments="$MATRIX_LINUX_5_10_COMMAND_ARGUMENTS" +linux_6_0_enabled="${MATRIX_LINUX_6_0_ENABLED:=true}" +linux_6_0_command_arguments="$MATRIX_LINUX_6_0_COMMAND_ARGUMENTS" +linux_nightly_6_1_enabled="${MATRIX_LINUX_NIGHTLY_6_1_ENABLED:=true}" +linux_nightly_6_1_command_arguments="$MATRIX_LINUX_NIGHTLY_6_1_COMMAND_ARGUMENTS" +linux_nightly_main_enabled="${MATRIX_LINUX_NIGHTLY_MAIN_ENABLED:=true}" +linux_nightly_main_command_arguments="$MATRIX_LINUX_NIGHTLY_MAIN_COMMAND_ARGUMENTS" + +windows_command="$MATRIX_WINDOWS_COMMAND" # required if any Windows pipeline is enabled +windows_setup_command="$MATRIX_WINDOWS_SETUP_COMMAND" +windows_6_0_enabled="${MATRIX_WINDOWS_6_0_ENABLED:=false}" +windows_6_0_command_arguments="$MATRIX_WINDOWS_6_0_COMMAND_ARGUMENTS" +windows_nightly_6_1_enabled="${MATRIX_WINDOWS_NIGHTLY_6_1_ENABLED:=false}" +windows_nightly_6_1_command_arguments="$MATRIX_WINDOWS_NIGHTLY_6_1_COMMAND_ARGUMENTS" +windows_nightly_main_enabled="${MATRIX_WINDOWS_NIGHTLY_MAIN_ENABLED:=false}" +windows_nightly_main_command_arguments="$MATRIX_WINDOWS_NIGHTLY_MAIN_COMMAND_ARGUMENTS" + +# Defaults +linux_runner="ubuntu-latest" +linux_5_9_container_image="swift:5.9-jammy" +linux_5_10_container_image="swift:5.10-jammy" +linux_6_0_container_image="swift:6.0-jammy" +linux_nightly_6_1_container_image="swiftlang/swift:nightly-6.1-jammy" +linux_nightly_main_container_image="swiftlang/swift:nightly-main-jammy" + +windows_6_0_runner="windows-2022" +windows_6_0_container_image="swift:6.0-windowsservercore-ltsc2022" +windows_nightly_6_1_runner="windows-2019" +windows_nightly_6_1_container_image="swiftlang/swift:nightly-6.1-windowsservercore-1809" +windows_nightly_main_runner="windows-2019" +windows_nightly_main_container_image="swiftlang/swift:nightly-main-windowsservercore-1809" + +# Create matrix from inputs +matrix='{"config": []}' + +## Linux +if [[ "$linux_5_9_enabled" == "true" || "$linux_5_10_enabled" == "true" || "$linux_6_0_enabled" == "true" || \ + "$linux_nightly_6_1_enabled" == "true" || "$linux_nightly_main_enabled" == "true" ]]; then + if [[ -z "$linux_command" ]]; then + echo "No linux command defined"; exit 1 + fi +fi + + +if [[ "$linux_5_9_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$linux_setup_command" \ + --arg command "$linux_command" \ + --arg command_arguments "$linux_5_9_command_arguments" \ + --arg container_image "$linux_5_9_container_image" \ + --arg runner "$linux_runner" \ + '.config[.config| length] |= . + { "name": "5.9", "image": $container_image, "swift_version": "5.9", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') +fi + +if [[ "$linux_5_10_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$linux_setup_command" \ + --arg command "$linux_command" \ + --arg command_arguments "$linux_5_10_command_arguments" \ + --arg container_image "$linux_5_10_container_image" \ + --arg runner "$linux_runner" \ + '.config[.config| length] |= . + { "name": "5.10", "image": $container_image, "swift_version": "5.10", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') +fi + +if [[ "$linux_6_0_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$linux_setup_command" \ + --arg command "$linux_command" \ + --arg command_arguments "$linux_6_0_command_arguments" \ + --arg container_image "$linux_6_0_container_image" \ + --arg runner "$linux_runner" \ + '.config[.config| length] |= . + { "name": "6.0", "image": $container_image, "swift_version": "6.0", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') +fi + +if [[ "$linux_nightly_6_1_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$linux_setup_command" \ + --arg command "$linux_command" \ + --arg command_arguments "$linux_nightly_6_1_command_arguments" \ + --arg container_image "$linux_nightly_6_1_container_image" \ + --arg runner "$linux_runner" \ + '.config[.config| length] |= . + { "name": "nightly-6.1", "image": $container_image, "swift_version": "nightly-6.1", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') +fi + +if [[ "$linux_nightly_main_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$linux_setup_command" \ + --arg command "$linux_command" \ + --arg command_arguments "$linux_nightly_main_command_arguments" \ + --arg container_image "$linux_nightly_main_container_image" \ + --arg runner "$linux_runner" \ + '.config[.config| length] |= . + { "name": "nightly-main", "image": $container_image, "swift_version": "nightly-main", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') +fi + +## Windows +if [[ "$windows_6_0_enabled" == "true" || "$windows_nightly_6_1_enabled" == "true" || "$windows_nightly_main_enabled" == "true" ]]; then + if [[ -z "$windows_command" ]]; then + echo "No windows command defined"; exit 1 + fi +fi + +if [[ "$windows_6_0_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$windows_setup_command" \ + --arg command "$windows_command" \ + --arg command_arguments "$windows_6_0_command_arguments" \ + --arg container_image "$windows_6_0_container_image" \ + --arg runner "$windows_6_0_runner" \ + '.config[.config| length] |= . + { "name": "6.0", "image": $container_image, "swift_version": "6.0", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') +fi + +if [[ "$windows_nightly_6_1_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$windows_setup_command" \ + --arg command "$windows_command" \ + --arg command_arguments "$windows_nightly_6_1_command_arguments" \ + --arg container_image "$windows_nightly_6_1_container_image" \ + --arg runner "$windows_nightly_6_1_runner" \ + '.config[.config| length] |= . + { "name": "nightly-6.1", "image": $container_image, "swift_version": "nightly-6.1", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') +fi + +if [[ "$windows_nightly_main_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$windows_setup_command" \ + --arg command "$windows_command" \ + --arg command_arguments "$windows_nightly_main_command_arguments" \ + --arg container_image "$windows_nightly_main_container_image" \ + --arg runner "$windows_nightly_main_runner" \ + '.config[.config| length] |= . + { "name": "nightly-main", "image": $container_image, "swift_version": "nightly-main", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') +fi + +echo "$matrix" | jq -c \ No newline at end of file