/* * Copyright 2025 Ry Wiese * * Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE.md file. */////// Effect for accepting TCP server connections, and its functions.///pubmod Net.TcpAccept {use IoError.ErrorKinduse IoError.IoErroruse Net.TcpServeruse Net.TcpServer.TcpServeruse Net.TcpSocketuse Net.TcpSocket.TcpSocketimport java.io.IOExceptionimport java.net.SocketTimeoutException////// Effect for accepting TCP server connections.///pubeffTcpAccept {/// Accepts an incoming connection on `server` and returns the connected socket.defaccept(server: TcpServer): Result[IoError, TcpSocket] }////// Handles the `TcpAccept` effect of the given function `f`.////// In other words, re-interprets the `TcpAccept` effect using the `IO` effect.///pubdefhandle(f: a -> b \ ef): a -> b \ (ef - TcpAccept) + IO = x ->run {f(x) } withhandlerTcpAccept {defaccept(server, k) = {try {let TcpServer(serverSocket) = server;letsocket = serverSocket.accept();letinputStream = socket.getInputStream();letoutputStream = socket.getOutputStream();k(Ok(TcpSocket(socket, inputStream, outputStream))) } catch {caseex: SocketTimeoutException => k(Err(IoError(ErrorKind.Timeout, ex.getMessage())))caseex: IOException => k(Err(IoError(ErrorKind.Other, ex.getMessage()))) } } }////// Runs the `TcpAccept` effect of the given function `f`.////// In other words, re-interprets the `TcpAccept` effect using the `IO` effect.///@DefaultHandlerpubdefrunWithIO(f: Unit -> a \ ef): a \ (ef - TcpAccept) + IO = handle(f)()}