/* * Copyright 2025 Cade Lueker * * Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE.md file. */////// Effect for determining whether an address is reachable, and its functions.///pubmod Net.Ping {use IoError.ErrorKinduse IoError.IoErroruse Net.IpAddruse Time.TimeUnitimport java.io.IOExceptionimport java.lang.IllegalArgumentExceptionimport java.net.InetAddressimport java.net.UnknownHostException////// Effect for determining whether an address is reachable.///pubeffPing {/// Returns `true` if `host` is reachable within `timeout` units of `u`.defisReachable(host: IpAddr, timeout: Int32, u: TimeUnit): Result[IoError, Bool] }////// Handles the `Ping` effect of the given function `f`.////// In other words, re-interprets the `Ping` effect using the `IO` effect.///pubdefhandle(f: a -> b \ ef): a -> b \ (ef - Ping) + IO = x ->run {f(x) } withhandlerPing {defisReachable(host, timeout, u, k) = {try {letms = TimeUnit.toMilliseconds(u);lettimeoutMs = ms*timeout;letaddr = InetAddress.getByAddress(IpAddr.toBytes(host));k(Ok(addr.isReachable(timeoutMs))) } catch {caseex: UnknownHostException => k(Err(IoError(ErrorKind.UnknownHost, ex.getMessage())))caseex: IllegalArgumentException => k(Err(IoError(ErrorKind.InvalidInput, ex.getMessage())))caseex: IOException => k(Err(IoError(ErrorKind.Other, ex.getMessage()))) } } }////// Runs the `Ping` effect of the given function `f`.////// In other words, re-interprets the `Ping` effect using the `IO` effect.///@DefaultHandlerpubdefrunWithIO(f: Unit -> a \ ef): a \ (ef - Ping) + IO = handle(f)()}