-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
08f952a
commit 9249dbd
Showing
3 changed files
with
176 additions
and
65 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
40 changes: 40 additions & 0 deletions
40
modules/server/src/main/scala/gql/server/interpreter/SharedResource.scala
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package gql.server.interpreter | ||
|
||
import cats.effect._ | ||
import cats.implicits._ | ||
import cats.effect.kernel.Resource.ExitCase | ||
|
||
object SharedResource { | ||
sealed trait State[F[_]] | ||
object State { | ||
final case class Closed[F[_]]() extends State[F] | ||
final case class Open[F[_]](leases: Int) extends State[F] | ||
} | ||
|
||
def make[F[_]](res: Resource[F, Unit])(implicit F: Async[F]): Resource[F, Resource[F, Option[Int]]] = | ||
Resource.applyFull { poll => | ||
poll((res.allocated, F.ref[State[F]](State.Open(1))).tupled).map { case ((_, release), ref) => | ||
val open = ref.modify { | ||
case State.Closed() => (State.Closed[F](), None) | ||
case State.Open(n) => | ||
val n2 = n + 1 | ||
(State.Open(n2), Some(n2)) | ||
} | ||
|
||
val close = ref.modify { | ||
case State.Closed() => (State.Closed[F](), F.unit) | ||
case State.Open(n) => | ||
val n2 = n - 1 | ||
if (n2 === 0) (State.Closed[F](), release) | ||
else (State.Open(n2), F.unit) | ||
}.flatten | ||
|
||
val api = Resource.make(open) { | ||
case None => F.unit | ||
case Some(_) => close | ||
} | ||
|
||
(api, ((_: ExitCase) => close)) | ||
} | ||
} | ||
} |