-
Notifications
You must be signed in to change notification settings - Fork 40
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
80f331e
commit 4f34362
Showing
1 changed file
with
18 additions
and
41 deletions.
There are no files selected for viewing
59 changes: 18 additions & 41 deletions
59
zio-quickstart-restful-webservice-metrics/src/main/scala/dev/zio/quickstart/MainApp.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 |
---|---|---|
@@ -1,56 +1,33 @@ | ||
|
||
package dev.zio.quickstart | ||
|
||
import dev.zio.quickstart.prometheus.PrometheusPublisherApp | ||
import dev.zio.quickstart.users._ | ||
import zio._ | ||
import zio.http._ | ||
import zio.metrics.connectors.{MetricsConfig, prometheus} | ||
import zio.Console._ | ||
import scala.util.Random | ||
|
||
object MainApp extends ZIOAppDefault { | ||
private val metricsConfig = ZLayer.succeed(MetricsConfig(5.seconds)) | ||
|
||
def run = { | ||
val retries = 5 | ||
val portRangeStart = 8000 | ||
val portRangeEnd = 8005 | ||
|
||
def allocatePort(retriesLeft: Int): ZIO[Any, Throwable, Unit] = | ||
if (retriesLeft <= 0) { | ||
ZIO.fail( | ||
new RuntimeException( | ||
"Failed to allocate a port within the retry limit" | ||
) | ||
) | ||
} else { | ||
val randomPort = | ||
Random.nextInt(portRangeEnd - portRangeStart + 1) + portRangeStart | ||
Server | ||
.serve(UserRoutes() ++ PrometheusPublisherApp()) | ||
.provide( | ||
Server.defaultWithPort(randomPort), | ||
|
||
// A layer responsible for storing the state of the `counterApp` | ||
ZLayer.fromZIO(Ref.make(0)), | ||
|
||
// To use the persistence layer, provide the `PersistentUserRepo.layer` layer instead | ||
InmemoryUserRepo.layer, | ||
|
||
// General config for all metric backend | ||
metricsConfig, | ||
|
||
// The Prometheus reporting layer | ||
prometheus.publisherLayer, | ||
prometheus.prometheusLayer | ||
) | ||
.catchAll(_ => allocatePort(retriesLeft - 1)) | ||
} | ||
|
||
allocatePort(retries) | ||
.fold( | ||
ex => ExitCode.failure, | ||
_ => ExitCode.success | ||
Server | ||
.serve(UserRoutes() ++ PrometheusPublisherApp()) | ||
.provide( | ||
Server.defaultWithPort(8080), | ||
|
||
// An layer responsible for storing the state of the `counterApp` | ||
ZLayer.fromZIO(Ref.make(0)), | ||
|
||
// To use the persistence layer, provide the `PersistentUserRepo.layer` layer instead | ||
InmemoryUserRepo.layer, | ||
|
||
// general config for all metric backend | ||
metricsConfig, | ||
|
||
// The prometheus reporting layer | ||
prometheus.publisherLayer, | ||
prometheus.prometheusLayer | ||
) | ||
} | ||
} |