Skip to content

Instantly share code, notes, and snippets.

@matfournier
Last active March 29, 2020 22:41
Show Gist options
  • Save matfournier/ad3279dc63135101886a117aef9047ac to your computer and use it in GitHub Desktop.
Save matfournier/ad3279dc63135101886a117aef9047ac to your computer and use it in GitHub Desktop.
Legacy Context Shfit Example
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