Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Metric for number of open connections #49

Closed
wants to merge 18 commits into from
Closed
6 changes: 5 additions & 1 deletion core/src/main/scala/zio/jdbc/ZConnectionPool.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import java.sql.Connection
*/
final case class ZConnectionPool(transaction: ZLayer[Any, Throwable, ZConnection])
object ZConnectionPool {
private[jdbc] val connectionsCounter = zio.metrics.Metric.counterInt("zio_jdbc_open_connections")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need a Gauge here because some metric systems do not allow incrementing by negative numbers.

Otherwise, looks good to merge!


def h2test: ZLayer[Any, Throwable, ZConnectionPool] =
ZLayer.scoped {
for {
Expand Down Expand Up @@ -157,7 +159,9 @@ object ZConnectionPool {
ZLayer.scoped {
for {
config <- ZIO.service[ZConnectionPoolConfig]
managed = ZIO.acquireRelease(acquire.retry(config.retryPolicy))(conn => ZIO.succeed(conn.close()))
managed = ZIO.acquireRelease(acquire.retry(config.retryPolicy).zipLeft(connectionsCounter.increment))(conn =>
connectionsCounter.incrementBy(-1).as(conn.close())
)
pool <-
ZPool
.make(managed.map(ZConnection(_)), Range(config.minConnections, config.maxConnections), config.timeToLive)
Expand Down
7 changes: 7 additions & 0 deletions core/src/test/scala/zio/jdbc/ZConnectionPoolSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package zio.jdbc
import zio._
import zio.schema._
import zio.test.TestAspect._
import zio.test.Assertion.isGreaterThan
import zio.test._

object ZConnectionPoolSpec extends ZIOSpecDefault {
Expand Down Expand Up @@ -53,6 +54,12 @@ object ZConnectionPoolSpec extends ZIOSpecDefault {
for {
_ <- ZIO.scoped(ZConnectionPool.h2test.build)
} yield assertCompletes
} + test("increment on connection acquisition") {
for {
initalState <- ZConnectionPool.connectionsCounter.value
_ <- transaction(execute(sql""))
state <- ZConnectionPool.connectionsCounter.value
} yield assert(state.count - initalState.count)(isGreaterThan(0.0))
}
} +
suite("sql") {
Expand Down