├── .github └── workflows │ ├── ci.yml │ └── clean.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── benchmarks ├── rps.sh ├── src │ └── main │ │ └── scala │ │ └── fs2 │ │ └── netty │ │ └── benchmarks │ │ └── echo │ │ ├── Fs2IO.scala │ │ ├── Fs2Netty.scala │ │ └── RawNetty.scala └── throughput.sh ├── build.sbt ├── core └── src │ ├── main │ ├── scala-2 │ │ └── fs2 │ │ │ └── netty │ │ │ └── PartiallyAppliedPlatform.scala │ ├── scala-3 │ │ └── fs2 │ │ │ └── netty │ │ │ └── PartiallyAppliedPlatform.scala │ └── scala │ │ └── fs2 │ │ └── netty │ │ ├── ChannelOption.scala │ │ ├── Network.scala │ │ ├── PartiallyApplied.scala │ │ ├── Socket.scala │ │ ├── SocketHandler.scala │ │ └── package.scala │ └── test │ └── scala │ └── fs2 │ └── netty │ └── NetworkSpec.scala └── project ├── build.properties └── plugins.sbt /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by sbt-github-actions using the 2 | # githubWorkflowGenerate task. You should add and commit this file to 3 | # your git repository. It goes without saying that you shouldn't edit 4 | # this file by hand! Instead, if you wish to make changes, you should 5 | # change your sbt build configuration to revise the workflow description 6 | # to meet your needs, then regenerate this file. 7 | 8 | name: Continuous Integration 9 | 10 | on: 11 | pull_request: 12 | branches: ['**'] 13 | push: 14 | branches: ['**'] 15 | 16 | env: 17 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 18 | 19 | jobs: 20 | build: 21 | name: Build and Test 22 | strategy: 23 | matrix: 24 | os: [ubuntu-latest, macos-latest, windows-latest] 25 | scala: [2.12.14, 2.13.6, 3.0.2] 26 | java: [adopt@1.8] 27 | runs-on: ${{ matrix.os }} 28 | steps: 29 | - name: Ignore line ending differences in git 30 | if: contains(runner.os, 'windows') 31 | shell: bash 32 | run: git config --global core.autocrlf false 33 | 34 | - name: Checkout current branch (full) 35 | uses: actions/checkout@v2 36 | with: 37 | fetch-depth: 0 38 | 39 | - name: Setup Java and Scala 40 | uses: olafurpg/setup-scala@v13 41 | with: 42 | java-version: ${{ matrix.java }} 43 | 44 | - name: Cache sbt 45 | uses: actions/cache@v2 46 | with: 47 | path: | 48 | ~/.sbt 49 | ~/.ivy2/cache 50 | ~/.coursier/cache/v1 51 | ~/.cache/coursier/v1 52 | ~/AppData/Local/Coursier/Cache/v1 53 | ~/Library/Caches/Coursier/v1 54 | key: ${{ runner.os }}-sbt-cache-v2-${{ hashFiles('**/*.sbt') }}-${{ hashFiles('project/build.properties') }} 55 | 56 | - name: Check that workflows are up to date 57 | shell: bash 58 | run: sbt ++${{ matrix.scala }} githubWorkflowCheck 59 | 60 | - shell: bash 61 | run: sbt ++${{ matrix.scala }} ci 62 | -------------------------------------------------------------------------------- /.github/workflows/clean.yml: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by sbt-github-actions using the 2 | # githubWorkflowGenerate task. You should add and commit this file to 3 | # your git repository. It goes without saying that you shouldn't edit 4 | # this file by hand! Instead, if you wish to make changes, you should 5 | # change your sbt build configuration to revise the workflow description 6 | # to meet your needs, then regenerate this file. 7 | 8 | name: Clean 9 | 10 | on: push 11 | 12 | jobs: 13 | delete-artifacts: 14 | name: Delete Artifacts 15 | runs-on: ubuntu-latest 16 | env: 17 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 18 | steps: 19 | - name: Delete artifacts 20 | run: | 21 | # Customize those three lines with your repository and credentials: 22 | REPO=${GITHUB_API_URL}/repos/${{ github.repository }} 23 | 24 | # A shortcut to call GitHub API. 25 | ghapi() { curl --silent --location --user _:$GITHUB_TOKEN "$@"; } 26 | 27 | # A temporary file which receives HTTP response headers. 28 | TMPFILE=/tmp/tmp.$$ 29 | 30 | # An associative array, key: artifact name, value: number of artifacts of that name. 31 | declare -A ARTCOUNT 32 | 33 | # Process all artifacts on this repository, loop on returned "pages". 34 | URL=$REPO/actions/artifacts 35 | while [[ -n "$URL" ]]; do 36 | 37 | # Get current page, get response headers in a temporary file. 38 | JSON=$(ghapi --dump-header $TMPFILE "$URL") 39 | 40 | # Get URL of next page. Will be empty if we are at the last page. 41 | URL=$(grep '^Link:' "$TMPFILE" | tr ',' '\n' | grep 'rel="next"' | head -1 | sed -e 's/.*.*//') 42 | rm -f $TMPFILE 43 | 44 | # Number of artifacts on this page: 45 | COUNT=$(( $(jq <<<$JSON -r '.artifacts | length') )) 46 | 47 | # Loop on all artifacts on this page. 48 | for ((i=0; $i < $COUNT; i++)); do 49 | 50 | # Get name of artifact and count instances of this name. 51 | name=$(jq <<<$JSON -r ".artifacts[$i].name?") 52 | ARTCOUNT[$name]=$(( $(( ${ARTCOUNT[$name]} )) + 1)) 53 | 54 | id=$(jq <<<$JSON -r ".artifacts[$i].id?") 55 | size=$(( $(jq <<<$JSON -r ".artifacts[$i].size_in_bytes?") )) 56 | printf "Deleting '%s' #%d, %'d bytes\n" $name ${ARTCOUNT[$name]} $size 57 | ghapi -X DELETE $REPO/actions/artifacts/$id 58 | done 59 | done 60 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | 3 | # vim 4 | *.sw? 5 | 6 | # Ignore [ce]tags files 7 | tags 8 | 9 | /.bsp/ 10 | 11 | # Intellij 12 | .idea 13 | *.iml 14 | 15 | # Mac OS 16 | META-INF/ 17 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fs2-netty 2 | 3 | A very thin wrapper around Netty TCP sockets in terms of Cats Effect and fs2. This is designed to be a *mostly* drop-in replacement for `fs2.io.tcp`, which works directly against raw NIO. The advantages here (over raw NIO) are two-fold: 4 | 5 | - Support for dramatically higher performance backends such as `epoll` and `io_uring` 6 | - Access to Netty's man-millenium of workarounds for bizarre async IO issues across various platforms and architectures 7 | 8 | The latter point is often overlooked, but it's very important to remember that NIO has an enormous number of very subtle bugs, even today. Additionally, the native asynchronous IO facilities on various operating systems *also* have a number of very subtle bugs, even down into the OS kernel layers. Netty very successfully works around all of this and has done so for over a decade. This isn't a wheel that needs to be reinvented. 9 | 10 | ## Usage 11 | 12 | ```sbt 13 | libraryDependencies += "com.codecommit" %% "fs2-netty" % "" 14 | ``` 15 | 16 | **Not production ready; barely has unit tests; please be nice.** Published for Scala 2.13.4. Probably shouldn't be published at all 17 | 18 | ```scala 19 | import cats.effect.{IO, IOApp, ExitCode} 20 | import fs2.netty.Network 21 | import fs2.io.{stdin, stdout} 22 | import java.net.InetSocketAddress 23 | 24 | // usage: sbt "run " 25 | 26 | object EchoServer extends IOApp { 27 | def run(args: List[String]): IO[ExitCode] = { 28 | val host = args(0) 29 | val port = args(1).toInt 30 | 31 | val rsrc = Network[IO] flatMap { net => 32 | val handlers = net.server(new InetSocketAddress(host, port)) map { client => 33 | client.reads.through(client.writes) 34 | } 35 | 36 | handlers.parJoinUnbounded.compile.resource.drain 37 | } 38 | 39 | rsrc.useForever.as(ExitCode.Success) 40 | } 41 | } 42 | 43 | object EchoClient extends IOApp { 44 | def run(args: List[String]): IO[ExitCode] = { 45 | val host = args(0) 46 | val port = args(1).toInt 47 | 48 | val rsrc = Network[IO] flatMap { net => 49 | net.client(new InetSocketAddress(host, port)) flatMap { server => 50 | val writer = stdin[IO](8096).through(server.writes) 51 | val reader = server.reads.through(stdout[IO]) 52 | writer.merge(reader).compile.resource.drain 53 | } 54 | } 55 | 56 | rsrc.useForever.as(ExitCode.Success) 57 | } 58 | } 59 | ``` 60 | 61 | The above implements a very simple echo server and client. The client connects to the server socket and wires up local stdin to send raw bytes to the server, writing response bytes from the server back to stdout. All resources are fully managed, and both processes are killed using Ctrl-C, which will cancel the respective streams and release all resource handles. 62 | 63 | ## Performance 64 | 65 | All of this is super-duper preliminary, okay? But with very minimal optimizations, and on my laptop, the numbers roughly look like this. 66 | 67 | ### Throughput 68 | 69 | A simple echo server, implemented relatively naively in each. The major difference is that the "raw Netty" implementation is doing things that are very unsafe in general (i.e. just passing the read buffer through to the write). You would lose a lot of that throughput if you had to actually use the data for anything other than echoing. So keeping in mind that the raw Netty implementation is effectively cheating, here you go: 70 | 71 | | | Raw Netty | fs2-netty | fs2-io | 72 | |--------------|-------------|-------------|------------| 73 | | **Absolute** | 12,526 Mbps | 13,045 Mbps | 7,364 Mbps | 74 | | **Relative** | 1 | 1.04 | 0.59 | 75 | 76 | This was a 30 second test, echoing a long string of `x`s as fast as passible using `tcpkali`. 200 connections per second were established, up to a throttle of 500 concurrents. The relative numbers are more meaningful than the absolute numbers. 77 | 78 | ### Requests Per Second 79 | 80 | Tested using [rust_echo_bench](https://github.com/haraldh/rust_echo_bench). 81 | 82 | | | Raw Netty | fs2-netty | fs2-io | 83 | |--------------|-------------|------------|------------| 84 | | **Absolute** | 110,690 RPS | 38,673 RPS | 77,330 RPS | 85 | | **Relative** | 1 | 0.35 | 0.70 | 86 | -------------------------------------------------------------------------------- /benchmarks/rps.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # usage: rps.sh 4 | 5 | set -euo pipefail # STRICT MODE 6 | IFS=$'\n\t' # http://redsymbol.net/articles/unofficial-bash-strict-mode/ 7 | 8 | host=$1 9 | port=$2 10 | 11 | exec echo_bench --address "$host:$port" --number 200 --duration 30 --length 128 12 | -------------------------------------------------------------------------------- /benchmarks/src/main/scala/fs2/netty/benchmarks/echo/Fs2IO.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2 18 | package netty 19 | package benchmarks.echo 20 | 21 | import cats.effect.{ExitCode, IO, IOApp} 22 | import cats.syntax.all._ 23 | 24 | import com.comcast.ip4s.{Host, Port} 25 | 26 | import fs2.io.net.Network 27 | 28 | object Fs2IO extends IOApp { 29 | def run(args: List[String]): IO[ExitCode] = { 30 | val host = args(0) 31 | val port = args(1).toInt 32 | 33 | val handlers = Network[IO].server(Host.fromString(host), Port.fromInt(port)) map { client => 34 | client.reads.through(client.writes).attempt.void 35 | } 36 | 37 | handlers.parJoinUnbounded.compile.drain.as(ExitCode.Success) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /benchmarks/src/main/scala/fs2/netty/benchmarks/echo/Fs2Netty.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2 18 | package netty 19 | package benchmarks.echo 20 | 21 | import cats.effect.{ExitCode, IO, IOApp} 22 | import cats.syntax.all._ 23 | 24 | import com.comcast.ip4s.{Host, Port} 25 | 26 | object Fs2Netty extends IOApp { 27 | def run(args: List[String]): IO[ExitCode] = { 28 | val host = Host.fromString(args(0)) 29 | val port = Port.fromInt(args(1).toInt).get 30 | 31 | val rsrc = Network[IO] flatMap { net => 32 | val handlers = net.server(host, port) map { client => 33 | client.reads.through(client.writes).attempt.void 34 | } 35 | 36 | handlers.parJoinUnbounded.compile.resource.drain 37 | } 38 | 39 | rsrc.useForever.as(ExitCode.Success) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /benchmarks/src/main/scala/fs2/netty/benchmarks/echo/RawNetty.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2.netty.benchmarks.echo 18 | 19 | import io.netty.bootstrap.ServerBootstrap 20 | import io.netty.channel.{ChannelFuture, ChannelHandlerContext, ChannelInitializer, ChannelInboundHandlerAdapter, ChannelOption} 21 | import io.netty.channel.nio.NioEventLoopGroup 22 | import io.netty.channel.socket.nio.NioServerSocketChannel 23 | import io.netty.channel.socket.SocketChannel 24 | 25 | import java.net.InetSocketAddress 26 | 27 | object RawNetty { 28 | def main(args: Array[String]): Unit = { 29 | val host = args(0) 30 | val port = args(1).toInt 31 | 32 | val parent = new NioEventLoopGroup(1) 33 | val child = new NioEventLoopGroup(1) 34 | 35 | val bootstrap = new ServerBootstrap 36 | bootstrap.group(parent, child) 37 | .option(ChannelOption.AUTO_READ.asInstanceOf[ChannelOption[Any]], false) 38 | .channel(classOf[NioServerSocketChannel]) 39 | .childHandler(new ChannelInitializer[SocketChannel] { 40 | def initChannel(ch: SocketChannel) = { 41 | ch.config().setAutoRead(false) 42 | ch.pipeline().addLast(new EchoHandler) // allocating is fair 43 | ch.parent().read() 44 | () 45 | } 46 | }) 47 | 48 | val cf = bootstrap.bind(new InetSocketAddress(host, port)) 49 | cf.sync() 50 | cf.channel.read() 51 | cf.channel().closeFuture().sync() 52 | () 53 | } 54 | 55 | final class EchoHandler extends ChannelInboundHandlerAdapter { 56 | 57 | override def channelActive(ctx: ChannelHandlerContext) = { 58 | ctx.channel.read() 59 | () 60 | } 61 | 62 | override def channelRead(ctx: ChannelHandlerContext, msg: AnyRef) = { 63 | ctx.channel.writeAndFlush(msg) addListener { (_: ChannelFuture) => 64 | ctx.channel.read() 65 | 66 | () 67 | } 68 | 69 | () 70 | } 71 | 72 | override def exceptionCaught(ctx: ChannelHandlerContext, t: Throwable) = () 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /benchmarks/throughput.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # usage: throughput.sh 4 | 5 | set -euo pipefail # STRICT MODE 6 | IFS=$'\n\t' # http://redsymbol.net/articles/unofficial-bash-strict-mode/ 7 | 8 | host=$1 9 | port=$2 10 | 11 | exec tcpkali \ 12 | -m xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \ 13 | --connect-rate=200 \ 14 | -c 500 \ 15 | -T 30s \ 16 | $host:$port 17 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | ThisBuild / baseVersion := "0.1" 18 | 19 | ThisBuild / organization := "org.typelevel" 20 | ThisBuild / publishGithubUser := "djspiewak" 21 | ThisBuild / publishFullName := "Daniel Spiewak" 22 | 23 | ThisBuild / organization := "org.typelevel" 24 | ThisBuild / organizationName := "Typelevel" 25 | 26 | ThisBuild / startYear := Some(2021) 27 | 28 | ThisBuild / crossScalaVersions := Seq("2.12.14", "2.13.6", "3.0.2") 29 | 30 | ThisBuild / githubWorkflowOSes ++= Seq("macos-latest", "windows-latest") 31 | 32 | val Fs2Version = "3.0.4" 33 | 34 | lazy val root = project.in(file(".")) 35 | .aggregate(core, benchmarks) 36 | .enablePlugins(NoPublishPlugin) 37 | 38 | lazy val core = project.in(file("core")) 39 | .settings( 40 | name := "fs2-netty", 41 | libraryDependencies ++= Seq( 42 | "io.netty" % "netty-all" % "4.1.69.Final", 43 | "com.comcast" %% "ip4s-core" % "3.0.3", 44 | "co.fs2" %% "fs2-core" % Fs2Version, 45 | 46 | "org.typelevel" %% "cats-effect-testing-specs2" % "1.3.0" % Test)) 47 | 48 | lazy val benchmarks = project.in(file("benchmarks")) 49 | .dependsOn(core) 50 | .settings( 51 | libraryDependencies += "co.fs2" %% "fs2-io" % Fs2Version, 52 | // run / javaOptions += "-Dio.netty.leakDetection.level=paranoid", 53 | run / fork := true) 54 | .enablePlugins(NoPublishPlugin) 55 | -------------------------------------------------------------------------------- /core/src/main/scala-2/fs2/netty/PartiallyAppliedPlatform.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2.netty 18 | 19 | import cats.effect.Async 20 | import cats.syntax.all._ 21 | 22 | import io.netty.channel.ChannelFuture 23 | 24 | private class PartiallyAppliedPlatform[F[_]] { this: PartiallyApplied[F] => 25 | // this only needs to exist because the Scala 2 compiler is really bad at subtyping 26 | def apply(cf: F[ChannelFuture])(implicit F: Async[F], D: DummyImplicit): F[Void] = 27 | apply[Void](cf.widen) 28 | } 29 | -------------------------------------------------------------------------------- /core/src/main/scala-3/fs2/netty/PartiallyAppliedPlatform.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2.netty 18 | 19 | private class PartiallyAppliedPlatform[F[_]] { this: PartiallyApplied[F] => 20 | } 21 | -------------------------------------------------------------------------------- /core/src/main/scala/fs2/netty/ChannelOption.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2.netty 18 | 19 | import io.netty.buffer.ByteBufAllocator 20 | import io.netty.channel.{ChannelOption => JChannelOption, MessageSizeEstimator, RecvByteBufAllocator, WriteBufferWaterMark} 21 | 22 | import java.lang.{Boolean => JBoolean} 23 | 24 | sealed trait ChannelOption { 25 | type Value 26 | val key: JChannelOption[Value] 27 | val value: Value 28 | } 29 | 30 | object ChannelOption { 31 | 32 | def apply[A](key0: JChannelOption[A], value0: A): ChannelOption = 33 | new ChannelOption { 34 | type Value = A 35 | val key = key0 36 | val value = value0 37 | } 38 | 39 | def allocator(value: ByteBufAllocator): ChannelOption = 40 | apply(JChannelOption.ALLOCATOR, value) 41 | 42 | def allowHalfClosure(value: Boolean): ChannelOption = 43 | apply(JChannelOption.ALLOW_HALF_CLOSURE, new JBoolean(value)) 44 | 45 | def autoClose(value: Boolean): ChannelOption = 46 | apply(JChannelOption.AUTO_CLOSE, new JBoolean(value)) 47 | 48 | // we don't allow reconfiguring auto-read because it corrupts backpressure entirely 49 | 50 | def connectTimeoutMillis(value: Int): ChannelOption = 51 | apply(JChannelOption.CONNECT_TIMEOUT_MILLIS, new Integer(value)) 52 | 53 | // TODO multicast options 54 | 55 | def ipTos(value: Int): ChannelOption = 56 | apply(JChannelOption.IP_TOS, new Integer(value)) 57 | 58 | def messageSizeEstimator(value: MessageSizeEstimator): ChannelOption = 59 | apply(JChannelOption.MESSAGE_SIZE_ESTIMATOR, value) 60 | 61 | def rcvBufAllocator(value: RecvByteBufAllocator): ChannelOption = 62 | apply(JChannelOption.RCVBUF_ALLOCATOR, value) 63 | 64 | // TODO tune executor things? 65 | 66 | def backlog(value: Int): ChannelOption = 67 | apply(JChannelOption.SO_BACKLOG, new Integer(value)) 68 | 69 | def broadcast(value: Boolean): ChannelOption = 70 | apply(JChannelOption.SO_BROADCAST, new JBoolean(value)) 71 | 72 | def keepAlive(value: Boolean): ChannelOption = 73 | apply(JChannelOption.SO_KEEPALIVE, new JBoolean(value)) 74 | 75 | def linger(value: Int): ChannelOption = 76 | apply(JChannelOption.SO_LINGER, new Integer(value)) 77 | 78 | def receiveBuffer(value: Int): ChannelOption = 79 | apply(JChannelOption.SO_RCVBUF, new Integer(value)) 80 | 81 | def reuseAddress(value: Boolean): ChannelOption = 82 | apply(JChannelOption.SO_REUSEADDR, new JBoolean(value)) 83 | 84 | def sendBuffer(value: Int): ChannelOption = 85 | apply(JChannelOption.SO_SNDBUF, new Integer(value)) 86 | 87 | def timeout(value: Int): ChannelOption = 88 | apply(JChannelOption.SO_TIMEOUT, new Integer(value)) 89 | 90 | def noDelay(value: Boolean): ChannelOption = 91 | apply(JChannelOption.TCP_NODELAY, new JBoolean(value)) 92 | 93 | def writeBufferWaterMark(value: WriteBufferWaterMark): ChannelOption = 94 | apply(JChannelOption.WRITE_BUFFER_WATER_MARK, value) 95 | 96 | def writeSpinCount(value: Int): ChannelOption = 97 | apply(JChannelOption.WRITE_SPIN_COUNT, new Integer(value)) 98 | } 99 | -------------------------------------------------------------------------------- /core/src/main/scala/fs2/netty/Network.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2 18 | package netty 19 | 20 | import cats.effect.{Async, Concurrent, Resource, Sync} 21 | import cats.effect.std.{Dispatcher, Queue} 22 | import cats.syntax.all._ 23 | 24 | import com.comcast.ip4s.{Host, IpAddress, Port, SocketAddress} 25 | 26 | import io.netty.bootstrap.{Bootstrap, ServerBootstrap} 27 | import io.netty.channel.{Channel, ChannelInitializer, ChannelOption => JChannelOption, EventLoopGroup, ServerChannel} 28 | import io.netty.channel.socket.SocketChannel 29 | 30 | import java.net.InetSocketAddress 31 | import java.util.concurrent.ThreadFactory 32 | import java.util.concurrent.atomic.AtomicInteger 33 | 34 | final class Network[F[_]: Async] private ( 35 | parent: EventLoopGroup, 36 | child: EventLoopGroup, 37 | clientChannelClazz: Class[_ <: Channel], 38 | serverChannelClazz: Class[_ <: ServerChannel]) { 39 | 40 | def client( 41 | addr: SocketAddress[Host], 42 | options: List[ChannelOption] = Nil) 43 | : Resource[F, Socket[F]] = 44 | Dispatcher[F] flatMap { disp => 45 | Resource suspend { 46 | Concurrent[F].deferred[Socket[F]] flatMap { d => 47 | addr.host.resolve[F] flatMap { resolved => 48 | Sync[F] delay { 49 | val bootstrap = new Bootstrap 50 | bootstrap.group(child) 51 | .channel(clientChannelClazz) 52 | .option(JChannelOption.AUTO_READ.asInstanceOf[JChannelOption[Any]], false) // backpressure 53 | .handler(initializer(disp)(d.complete(_).void)) 54 | 55 | options.foreach(opt => bootstrap.option(opt.key, opt.value)) 56 | 57 | val connectChannel = Sync[F] defer { 58 | val cf = bootstrap.connect(resolved.toInetAddress, addr.port.value) 59 | fromNettyFuture[F](cf.pure[F]).as(cf.channel()) 60 | } 61 | 62 | Resource.make(connectChannel <* d.get)(ch => fromNettyFuture(Sync[F].delay(ch.close())).void).evalMap(_ => d.get) 63 | } 64 | } 65 | } 66 | } 67 | } 68 | 69 | def server( 70 | host: Option[Host], 71 | port: Port, 72 | options: List[ChannelOption] = Nil) 73 | : Stream[F, Socket[F]] = 74 | Stream.resource(serverResource(host, Some(port), options)).flatMap(_._2) 75 | 76 | def serverResource( 77 | host: Option[Host], 78 | port: Option[Port], 79 | options: List[ChannelOption] = Nil) 80 | : Resource[F, (SocketAddress[IpAddress], Stream[F, Socket[F]])] = 81 | Dispatcher[F] flatMap { disp => 82 | Resource suspend { 83 | Queue.unbounded[F, Socket[F]] flatMap { sockets => 84 | host.traverse(_.resolve[F]) flatMap { resolved => 85 | Sync[F] delay { 86 | val bootstrap = new ServerBootstrap 87 | bootstrap.group(parent, child) 88 | .option(JChannelOption.AUTO_READ.asInstanceOf[JChannelOption[Any]], false) // backpressure 89 | .channel(serverChannelClazz) 90 | .childHandler(initializer(disp)(sockets.offer)) 91 | 92 | options.foreach(opt => bootstrap.option(opt.key, opt.value)) 93 | 94 | val connectChannel = Sync[F] defer { 95 | val cf = bootstrap.bind( 96 | resolved.map(_.toInetAddress).orNull, 97 | port.map(_.value).getOrElse(0)) 98 | fromNettyFuture[F](cf.pure[F]).as(cf.channel()) 99 | } 100 | 101 | val connection = Resource.make(connectChannel) { ch => 102 | fromNettyFuture[F](Sync[F].delay(ch.close())).void 103 | } 104 | 105 | connection evalMap { ch => 106 | Sync[F].delay(SocketAddress.fromInetSocketAddress(ch.localAddress().asInstanceOf[InetSocketAddress])).tupleRight( 107 | Stream.repeatEval(Sync[F].delay(ch.read()) *> sockets.take)) 108 | } 109 | } 110 | } 111 | } 112 | } 113 | } 114 | 115 | private[this] def initializer( 116 | disp: Dispatcher[F])( 117 | result: Socket[F] => F[Unit]) 118 | : ChannelInitializer[SocketChannel] = 119 | new ChannelInitializer[SocketChannel] { 120 | def initChannel(ch: SocketChannel) = { 121 | val p = ch.pipeline() 122 | ch.config().setAutoRead(false) 123 | 124 | disp unsafeRunAndForget { 125 | SocketHandler[F](disp, ch) flatMap { s => 126 | Sync[F].delay(p.addLast(s)) *> result(s) 127 | } 128 | } 129 | } 130 | } 131 | } 132 | 133 | object Network { 134 | 135 | private[this] val (eventLoopClazz, serverChannelClazz, clientChannelClazz) = { 136 | val (e, s, c) = uring().orElse(epoll()).orElse(kqueue()).getOrElse(nio()) 137 | 138 | (e, s.asInstanceOf[Class[_ <: ServerChannel]], c.asInstanceOf[Class[_ <: Channel]]) 139 | } 140 | 141 | def apply[F[_]: Async]: Resource[F, Network[F]] = { 142 | // TODO configure threads 143 | def instantiate(name: String) = Sync[F] delay { 144 | val constr = eventLoopClazz.getDeclaredConstructor(classOf[Int], classOf[ThreadFactory]) 145 | val result = constr.newInstance(new Integer(1), new ThreadFactory { 146 | private val ctr = new AtomicInteger(0) 147 | def newThread(r: Runnable): Thread = { 148 | val t = new Thread(r) 149 | t.setDaemon(true) 150 | t.setName(s"fs2-netty-$name-io-worker-${ctr.getAndIncrement()}") 151 | t.setPriority(Thread.MAX_PRIORITY) 152 | t 153 | } 154 | }) 155 | 156 | result.asInstanceOf[EventLoopGroup] 157 | } 158 | 159 | def instantiateR(name: String) = 160 | Resource.make(instantiate(name)) { elg => 161 | fromNettyFuture[F](Sync[F].delay(elg.shutdownGracefully())).void 162 | } 163 | 164 | (instantiateR("server"), instantiateR("client")) mapN { (server, client) => 165 | try { 166 | val meth = eventLoopClazz.getDeclaredMethod("setIoRatio", classOf[Int]) 167 | meth.invoke(server, new Integer(90)) // TODO tweak this a bit more; 100 was worse than 50 and 90 was a dramatic step up from both 168 | meth.invoke(client, new Integer(90)) 169 | } catch { 170 | case _: Exception => () 171 | } 172 | 173 | new Network[F](server, client, clientChannelClazz, serverChannelClazz) 174 | } 175 | } 176 | 177 | private[this] def uring() = 178 | try { 179 | if (sys.props.get("fs2.netty.use.io_uring").map(_.toBoolean).getOrElse(false)) { 180 | Class.forName("io.netty.incubator.channel.uring.IOUringEventLoop") 181 | 182 | Some(( 183 | Class.forName("io.netty.incubator.channel.uring.IOUringEventLoopGroup"), 184 | Class.forName("io.netty.incubator.channel.uring.IOUringServerSocketChannel"), 185 | Class.forName("io.netty.incubator.channel.uring.IOUringSocketChannel"))) 186 | } else { 187 | None 188 | } 189 | } catch { 190 | case _: Throwable => None 191 | } 192 | 193 | private[this] def epoll() = 194 | try { 195 | Class.forName("io.netty.channel.epoll.EpollEventLoop") 196 | 197 | Some(( 198 | Class.forName("io.netty.channel.epoll.EpollEventLoopGroup"), 199 | Class.forName("io.netty.channel.epoll.EpollServerSocketChannel"), 200 | Class.forName("io.netty.channel.epoll.EpollSocketChannel"))) 201 | } catch { 202 | case _: Throwable => None 203 | } 204 | 205 | private[this] def kqueue() = 206 | try { 207 | Class.forName("io.netty.channel.kqueue.KQueueEventLoop") 208 | 209 | Some(( 210 | Class.forName("io.netty.channel.kqueue.KQueueEventLoopGroup"), 211 | Class.forName("io.netty.channel.kqueue.KQueueServerSocketChannel"), 212 | Class.forName("io.netty.channel.kqueue.KQueueSocketChannel"))) 213 | } catch { 214 | case _: Throwable => None 215 | } 216 | 217 | private[this] def nio() = 218 | ( 219 | Class.forName("io.netty.channel.nio.NioEventLoopGroup"), 220 | Class.forName("io.netty.channel.socket.nio.NioServerSocketChannel"), 221 | Class.forName("io.netty.channel.socket.nio.NioSocketChannel")) 222 | } 223 | -------------------------------------------------------------------------------- /core/src/main/scala/fs2/netty/PartiallyApplied.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2.netty 18 | 19 | import cats.effect.{Async, Sync} 20 | import cats.syntax.all._ 21 | 22 | import io.netty.util.concurrent.Future 23 | 24 | import java.util.concurrent.CancellationException 25 | 26 | private final class PartiallyApplied[F[_]] extends PartiallyAppliedPlatform[F] { 27 | def apply[A](ff: F[Future[A]])(implicit F: Async[F]): F[A] = { 28 | def inner(fut: Future[A], cancelable: Boolean): F[A] = 29 | Async[F].async[A] { cb => 30 | Sync[F] delay { 31 | fut addListener { (fut: Future[A]) => // intentional shadowing 32 | if (fut.isSuccess()) { 33 | cb(Right(fut.getNow())) 34 | } else { 35 | fut.cause() match { 36 | case _: CancellationException if cancelable => () // swallow this one since it *probably* means we were canceled 37 | case t => cb(Left(t)) 38 | } 39 | } 40 | } 41 | 42 | if (fut.isCancellable() && cancelable) 43 | Some(Sync[F].delay(fut.cancel(false)) >> inner(fut, false).void) // await the cancelation 44 | else 45 | None 46 | } 47 | } 48 | 49 | ff.flatMap(inner(_, true)) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /core/src/main/scala/fs2/netty/Socket.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2 18 | package netty 19 | 20 | import com.comcast.ip4s.{IpAddress, SocketAddress} 21 | 22 | trait Socket[F[_]] { 23 | 24 | def localAddress: F[SocketAddress[IpAddress]] 25 | def remoteAddress: F[SocketAddress[IpAddress]] 26 | 27 | def reads: Stream[F, Byte] 28 | 29 | def write(bytes: Chunk[Byte]): F[Unit] 30 | def writes: Pipe[F, Byte, INothing] 31 | } 32 | -------------------------------------------------------------------------------- /core/src/main/scala/fs2/netty/SocketHandler.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2 18 | package netty 19 | 20 | import cats.{Applicative, Functor} 21 | import cats.effect.{Async, Poll, Sync} 22 | import cats.effect.std.{Dispatcher, Queue} 23 | import cats.syntax.all._ 24 | 25 | import com.comcast.ip4s.{IpAddress, SocketAddress} 26 | 27 | import io.netty.buffer.{ByteBuf, Unpooled} 28 | import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter} 29 | import io.netty.channel.socket.SocketChannel 30 | 31 | private final class SocketHandler[F[_]: Async] ( 32 | disp: Dispatcher[F], 33 | channel: SocketChannel, 34 | bufs: Queue[F, AnyRef]) // ByteBuf | Throwable | Null 35 | extends ChannelInboundHandlerAdapter 36 | with Socket[F] { 37 | 38 | val localAddress: F[SocketAddress[IpAddress]] = 39 | Sync[F].delay(SocketAddress.fromInetSocketAddress(channel.localAddress())) 40 | 41 | val remoteAddress: F[SocketAddress[IpAddress]] = 42 | Sync[F].delay(SocketAddress.fromInetSocketAddress(channel.remoteAddress())) 43 | 44 | private[this] def take(poll: Poll[F]): F[ByteBuf] = 45 | poll(bufs.take) flatMap { 46 | case null => Applicative[F].pure(null) // EOF marker 47 | case buf: ByteBuf => buf.pure[F] 48 | case t: Throwable => t.raiseError[F, ByteBuf] 49 | } 50 | 51 | private[this] val fetch: Stream[F, ByteBuf] = 52 | Stream.bracketFull[F, ByteBuf](poll => Sync[F].delay(channel.read()) *> take(poll)) { (b, _) => 53 | if (b != null) 54 | Sync[F].delay(b.release()).void 55 | else 56 | Applicative[F].unit 57 | } 58 | 59 | lazy val reads: Stream[F, Byte] = 60 | Stream force { 61 | Functor[F].ifF(isOpen)( 62 | fetch.flatMap(b => if (b == null) Stream.empty else Stream.chunk(toChunk(b))) ++ reads, 63 | Stream.empty) 64 | } 65 | 66 | def write(bytes: Chunk[Byte]): F[Unit] = 67 | fromNettyFuture[F](Sync[F].delay(channel.writeAndFlush(toByteBuf(bytes)))).void 68 | 69 | val writes: Pipe[F, Byte, INothing] = 70 | _.chunks.evalMap(c => write(c) *> isOpen).takeWhile(b => b).drain 71 | 72 | private[this] val isOpen: F[Boolean] = 73 | Sync[F].delay(channel.isOpen()) 74 | 75 | override def channelRead(ctx: ChannelHandlerContext, msg: AnyRef) = 76 | disp.unsafeRunAndForget(bufs.offer(msg)) 77 | 78 | override def exceptionCaught(ctx: ChannelHandlerContext, t: Throwable) = 79 | disp.unsafeRunAndForget(bufs.offer(t)) 80 | 81 | override def channelInactive(ctx: ChannelHandlerContext) = 82 | try { 83 | disp.unsafeRunAndForget(bufs.offer(null)) 84 | } catch { 85 | case _: IllegalStateException => () // sometimes we can see this due to race conditions in shutdown 86 | } 87 | 88 | private[this] def toByteBuf(chunk: Chunk[Byte]): ByteBuf = 89 | chunk match { 90 | case Chunk.ArraySlice(arr, off, len) => 91 | Unpooled.wrappedBuffer(arr, off, len) 92 | 93 | case c: Chunk.ByteBuffer => 94 | Unpooled.wrappedBuffer(c.toByteBuffer) 95 | 96 | case c => 97 | Unpooled.wrappedBuffer(c.toArray) 98 | } 99 | 100 | private[this] def toChunk(buf: ByteBuf): Chunk[Byte] = 101 | if (buf.hasArray()) 102 | Chunk.array(buf.array()) 103 | else if (buf.nioBufferCount() > 0) 104 | Chunk.byteBuffer(buf.nioBuffer()) 105 | else 106 | ??? 107 | } 108 | 109 | private object SocketHandler { 110 | def apply[F[_]: Async](disp: Dispatcher[F], channel: SocketChannel): F[SocketHandler[F]] = 111 | Queue.unbounded[F, AnyRef] map { bufs => 112 | new SocketHandler(disp, channel, bufs) 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /core/src/main/scala/fs2/netty/package.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2 18 | 19 | package object netty { 20 | private[netty] def fromNettyFuture[F[_]]: PartiallyApplied[F] = new PartiallyApplied[F] 21 | } 22 | -------------------------------------------------------------------------------- /core/src/test/scala/fs2/netty/NetworkSpec.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package fs2 18 | package netty 19 | 20 | import cats.effect.IO 21 | import cats.effect.testing.specs2.CatsResource 22 | 23 | import org.specs2.mutable.SpecificationLike 24 | 25 | class NetworkSpec extends CatsResource[IO, Network[IO]] with SpecificationLike { 26 | 27 | val resource = Network[IO] 28 | 29 | "network tcp sockets" should { 30 | "create a network instance" in { 31 | Network[IO].use_.as(ok) 32 | } 33 | 34 | "support a simple echo use-case" in withResource { net => 35 | val data = List[Byte](1, 2, 3, 4, 5, 6, 7) 36 | 37 | val rsrc = net.serverResource(None, None) flatMap { 38 | case (isa, incoming) => 39 | val handler = incoming flatMap { socket => 40 | socket.reads.through(socket.writes) 41 | } 42 | 43 | for { 44 | _ <- handler.compile.drain.background 45 | 46 | results <- net.client(isa) flatMap { socket => 47 | Stream.emits(data) 48 | .through(socket.writes) 49 | .merge(socket.reads) 50 | .take(data.length.toLong) 51 | .compile.resource.toList 52 | } 53 | } yield results 54 | } 55 | 56 | rsrc.use(IO.pure(_)) flatMap { results => 57 | IO { 58 | results mustEqual data 59 | } 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.5.5 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("com.codecommit" % "sbt-spiewak-sonatype" % "0.22.1") 2 | --------------------------------------------------------------------------------