forked from zio/zio-sql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConnectionPool.scala
194 lines (172 loc) · 6.41 KB
/
ConnectionPool.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package zio.sql
import java.io.IOException
import java.sql._
import zio.stm._
import zio._
import zio.sql.ConnectionPool.QueueItem
trait ConnectionPool {
/**
* Retrieves a JDBC java.sql.Connection as a [[ZIO[Scope, Exception, Connection]]] resource.
* The managed resource will safely acquire and release the connection, and
* may be interrupted or timed out if necessary.
*/
def connection: ZIO[Scope, Exception, Connection]
}
object ConnectionPool {
case class QueueItem(promise: TPromise[Nothing, ResettableConnection], interrupted: TRef[Boolean])
/**
* A live layer for `ConnectionPool` that creates a JDBC connection pool
* from the specified connection pool settings.
*/
val live: ZLayer[ConnectionPoolConfig, IOException, ConnectionPool] =
ZLayer.scoped {
for {
config <- ZIO.service[ConnectionPoolConfig]
queue <- TQueue.bounded[QueueItem](config.queueCapacity).commit
available <- TRef.make(List.empty[ResettableConnection]).commit
pool = ConnectionPoolLive(queue, available, config)
_ <- pool.initialize
_ <- ZIO.addFinalizer(pool.close.orDie)
} yield pool
}
}
/**
* A live concurrent connection pool.
*
* Improvements to make:
*
* - A connection may die. If so, it should be reacquired.
* - Someone may try to use a connection forever. If so, we should
* take it away from them.
*/
final case class ConnectionPoolLive(
queue: TQueue[QueueItem],
available: TRef[List[ResettableConnection]],
config: ConnectionPoolConfig
) extends ConnectionPool {
/**
* Adds a fresh connection to the connection pool.
*/
val addFreshConnection: IO[IOException, ResettableConnection] = {
val makeConnection = ZIO.attemptBlocking {
val connection = DriverManager.getConnection(config.url, config.properties)
val autoCommit = config.autoCommit
val catalog = connection.getCatalog()
val clientInfo = connection.getClientInfo()
val holdability = connection.getHoldability()
val schema = connection.getSchema()
val isolation = connection.getTransactionIsolation()
val restore: Connection => Unit = connection => {
if (connection.getAutoCommit() != autoCommit) connection.setAutoCommit(autoCommit)
if (connection.getCatalog() ne catalog) connection.setCatalog(catalog)
if (connection.getClientInfo() ne clientInfo) connection.setClientInfo(clientInfo)
if (connection.getHoldability() != holdability) connection.setHoldability(holdability)
if (connection.getSchema() != schema) connection.setSchema(schema)
if (connection.getTransactionIsolation() != isolation) connection.setTransactionIsolation(isolation)
}
new ResettableConnection(connection, restore)
}.refineToOrDie[IOException]
for {
connection <- makeConnection.retry(config.retryPolicy)
_ <- available.update(connection :: _).commit
} yield connection
}
/**
* Closes the connection pool, terminating each connection in parallel.
*/
val close: IO[IOException, Any] =
ZIO.uninterruptible {
available.get.commit.flatMap { all =>
ZIO.foreachPar(all) { connection =>
ZIO.attemptBlocking(connection.connection.close()).refineToOrDie[IOException]
}
}
}
def connection: ZIO[Scope, Exception, Connection] =
ZIO
.acquireRelease(tryTake.commit.flatMap {
case Left(queueItem) =>
ZIO.interruptible(queueItem.promise.await.commit).onInterrupt {
(for {
res <- queueItem.promise.poll
_ <- res match {
case Some(Right(connection)) =>
ZSTM.succeed(release(connection))
case _ =>
queueItem.interrupted.set(true)
}
} yield ()).commit
}
case Right(connection) =>
ZIO.succeed(connection)
})(release(_))
.flatMap(rc => rc.reset.as(rc.connection))
/**
* Initializes the connection pool.
*/
val initialize: IO[IOException, Unit] =
ZIO.uninterruptible {
ZIO
.foreachParDiscard(1 to config.poolSize) { _ =>
addFreshConnection
}
.unit
}
private def release(connection: ResettableConnection): UIO[Any] =
ZIO.uninterruptible {
ZIO
.whenZIO(connection.isValid.map(!_)) {
ZIO.attempt(connection.connection.close).zipParRight(addFreshConnection).orDie
}
.flatMap { opt =>
val conn = opt match {
case Some(c) => c
case None => connection
}
tryRelease(conn).commit.flatMap {
case Some(handle) =>
handle.interrupted.get.tap { interrupted =>
ZSTM.when(!interrupted)(handle.promise.succeed(conn))
}.commit.flatMap { interrupted =>
ZIO.when(interrupted)(release(conn))
}
case None => ZIO.unit
}
}
}
private def tryRelease(
connection: ResettableConnection
): STM[Nothing, Option[QueueItem]] =
for {
empty <- queue.isEmpty
result <- if (empty) available.update(connection :: _) *> STM.none
else queue.take.map(Some(_))
} yield result
private val tryTake: STM[Nothing, Either[QueueItem, ResettableConnection]] =
for {
headOption <- available.get.map(_.headOption)
either <- headOption match {
case None =>
for {
promise <- TPromise.make[Nothing, ResettableConnection]
ref <- TRef.make[Boolean](false)
item = QueueItem(promise, ref)
_ <- queue.offer(item)
} yield Left(item)
case Some(connection) =>
available.update(_.tail) *> ZSTM.succeed(Right(connection))
}
} yield either
}
private[sql] final class ResettableConnection(val connection: Connection, resetter: Connection => Unit) {
def reset: UIO[Any] = ZIO.succeed(resetter(connection))
def isValid: UIO[Boolean] =
ZIO
.when(!connection.isClosed) {
ZIO.succeed(connection.prepareStatement("SELECT 1"))
}
.map {
case Some(stmt) => stmt != null
case None => false
}
}