All Downloads are FREE. Search and download functionalities are using the official Maven repository.

zio.metrics.connectors.datadog.package.scala Maven / Gradle / Ivy

There is a newer version: 2.3.1
Show newest version
package zio.metrics.connectors

import zio._
import zio.internal.RingBuffer
import zio.metrics.{MetricClient, MetricKey, MetricKeyType}
import zio.metrics.connectors.internal.MetricsClient
import zio.metrics.connectors.statsd.{StatsdClient, StatsdConfig}

package object datadog {

  lazy val datadogLayer: ZLayer[DatadogConfig & MetricsConfig, Nothing, Unit] =
    ZLayer.scoped(
      for {
        config  <- ZIO.service[DatadogConfig]
        clt     <- StatsdClient.make.provideSome[Scope](ZLayer.succeed(StatsdConfig(config.host, config.port)))
        queue    = RingBuffer.apply[(MetricKey[MetricKeyType.Histogram], Double)](config.maxQueueSize)
        listener = new DataDogListener(queue)
        _       <- Unsafe.unsafe(unsafe =>
                     ZIO.acquireRelease(ZIO.succeed(MetricClient.addListener(listener)(unsafe)))(_ =>
                       ZIO.succeed(MetricClient.removeListener(listener)(unsafe)),
                     ),
                   )
        _       <- DataDogEventProcessor.make(clt, queue)
        _       <- MetricsClient.make(datadogHandler(clt, config))
      } yield (),
    )

  private def eventFilter(config: DatadogConfig): MetricEvent => Boolean =
    if (config.sendUnchanged) {
      !_.metricKey.keyType.isInstanceOf[metrics.MetricKeyType.Histogram]
    } else {
      case MetricEvent.Unchanged(_, _, _) => false
      case e                              => !e.metricKey.keyType.isInstanceOf[metrics.MetricKeyType.Histogram]
    }

  private[connectors] def datadogHandler(
    client: StatsdClient,
    config: DatadogConfig,
  ): Iterable[MetricEvent] => UIO[Unit] = events => {
    val encoder = DatadogEncoder.encoder(config)

    val send = ZIO
      .foreachDiscard(events.filter(eventFilter(config)))(evt =>
        for {
          encoded <- encoder(evt).catchAll(_ => ZIO.succeed(Chunk.empty))
          _       <- ZIO.when(encoded.nonEmpty)(ZIO.attempt(client.send(encoded)))
        } yield (),
      )

    send.ignore
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy