Last active
March 29, 2020 22:41
-
-
Save matfournier/ad3279dc63135101886a117aef9047ac to your computer and use it in GitHub Desktop.
Legacy Context Shfit Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Statsd[F[_]] { | |
def inc(key: String, magnitude: Int = 1, sampleRate: Double = 1.0): F[Unit] | |
def dec(key: String, magnitude: Int = 1, sampleRate: Double = 1.0): F[Unit] | |
def gauge(key: String, magnitude: Double, sampleRate: Double = 1.0): F[Unit] | |
def timer(key: String, value: Int, sampleRate: Double = 1.0): F[Unit] | |
} | |
// the legacy client takes in a fixed thread pool of 1. Under the hood it does some | |
// websocket / NIO stuff | |
// am I wrong to contextShift onto the same thread pool that it's using? | |
// in this example, ec here is the same as the ec that client() is using to make NIO calls | |
// or should I have ec2 (another fixed thread pool of 1) JUST for IO to be shifting onto when making calls | |
// to client? | |
class UdpCatsStatds[F[_]: ContextShift : Sync](private val client: UdpStatsdClient, private val ec: ExecutionContext) | |
extends Statsd[F] { | |
def inc(key: String, magnitude: Int = 1, sampleRate: Double = 1.0): F[Unit] = | |
ContextShift[F].evalOn(ec)(Sync[F].delay(client.inc(key, magnitude, sampleRate))) | |
def dec(key: String, magnitude: Int, sampleRate: Double): F[Unit] = | |
ContextShift[F].evalOn(ec)(Sync[F].delay(client.dec(key, magnitude, sampleRate))) | |
def gauge(key: String, magnitude: Double, sampleRate: Double): F[Unit] = | |
ContextShift[F].evalOn(ec)(Sync[F].delay(client.gauge(key, magnitude, sampleRate))) | |
def timer(key: String, value: Int, sampleRate: Double): F[Unit] = | |
ContextShift[F].evalOn(ec)(Sync[F].delay(client.timer(key, value, sampleRate))) | |
} | |
object UdpCatsStatsd { | |
def make[F[_]: Sync: ContextShift](config: Config): Resource[F, UdpCatsStatds[F]] = | |
Resource(Sync[F].delay { | |
val executor = Executors.newFixedThreadPool(1) | |
val ec = ExecutionContext.fromExecutor(executor) | |
val underlyingClient = new UdpStatsdClient(config, Some(ec)) | |
val wrappedClient = new UdpCatsStatds[F](underlyingClient, ec) | |
(wrappedClient, Sync[F].delay(executor.shutdown())) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment