-
Notifications
You must be signed in to change notification settings - Fork 32
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
Showing
3 changed files
with
157 additions
and
20 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
138 changes: 138 additions & 0 deletions
138
.../com.snowplowanalytics.snowplow.collectors.scalastream/sinks/GooglePubSubSinkHttp4s.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,138 @@ | ||
/* | ||
* Copyright (c) 2013-2023 Snowplow Analytics Ltd. All rights reserved. | ||
* | ||
* This program is licensed to you under the Apache License Version 2.0, | ||
* and you may not use this file except in compliance with the Apache License Version 2.0. | ||
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. | ||
* | ||
* Unless required by applicable law or agreed to in writing, | ||
* software distributed under the Apache License Version 2.0 is distributed on an | ||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. | ||
*/ | ||
package com.snowplowanalytics.snowplow.collectors.scalastream.sinks | ||
|
||
import cats.Parallel | ||
import cats.effect.implicits.genSpawnOps | ||
import cats.effect.{Async, Resource, Sync} | ||
import cats.implicits._ | ||
import com.google.api.gax.core.NoCredentialsProvider | ||
import com.google.api.gax.grpc.GrpcTransportChannel | ||
import com.google.api.gax.retrying.RetrySettings | ||
import com.google.api.gax.rpc.{ApiException, FixedHeaderProvider, FixedTransportChannelProvider} | ||
import com.google.cloud.pubsub.v1.Publisher | ||
import com.permutive.pubsub.producer.Model.{ProjectId, Topic} | ||
import com.permutive.pubsub.producer.PubsubProducer | ||
import com.permutive.pubsub.producer.encoder.MessageEncoder | ||
import com.permutive.pubsub.producer.grpc.{GooglePubsubProducer, PubsubProducerConfig} | ||
import com.snowplowanalytics.snowplow.collectors.scalastream.{Config, Sink, generated} | ||
import io.grpc.ManagedChannelBuilder | ||
import org.threeten.bp.Duration | ||
import org.typelevel.log4cats.Logger | ||
import org.typelevel.log4cats.slf4j.Slf4jLogger | ||
import retry.RetryPolicies | ||
import retry.syntax.all._ | ||
|
||
import scala.concurrent.duration.{DurationLong, FiniteDuration} | ||
import scala.util._ | ||
|
||
class GooglePubSubSinkHttp4s[F[_]: Async: Parallel: Logger] private ( | ||
val maxBytes: Int, | ||
producer: PubsubProducer[F, Array[Byte]], | ||
retryInterval: FiniteDuration, | ||
topicName: String | ||
) extends Sink[F] { | ||
|
||
override def isHealthy: F[Boolean] = Sync[F].pure(true) //TODO | ||
|
||
override def storeRawEvents(events: List[Array[Byte]], key: String): F[Unit] = | ||
produce(events).start.void | ||
|
||
private def produce(events: List[Array[Byte]]): F[Unit] = | ||
events.parTraverse_ { event => | ||
producer | ||
.produce(event) | ||
.retryingOnAllErrors( | ||
policy = RetryPolicies.constantDelay(retryInterval), | ||
onError = (error, _) => Logger[F].error(createErrorMessage(error)) | ||
) | ||
} | ||
|
||
private def createErrorMessage(error: Throwable): String = | ||
error match { | ||
case apiEx: ApiException => | ||
val retryable = if (apiEx.isRetryable) "retryable" else "non-retryable" | ||
s"Publishing message to $topicName failed with code ${apiEx.getStatusCode} and $retryable error: ${apiEx.getMessage}" | ||
case t => s"Publishing message to $topicName failed with error: ${t.getMessage}" | ||
} | ||
} | ||
|
||
object GooglePubSubSinkHttp4s { | ||
private val UserAgent = s"snowplow/stream-collector-${generated.BuildInfo.version}" | ||
|
||
implicit private def unsafeLogger[F[_]: Sync]: Logger[F] = | ||
Slf4jLogger.getLogger[F] | ||
|
||
implicit val byteArrayEncoder: MessageEncoder[Array[Byte]] = | ||
new MessageEncoder[Array[Byte]] { | ||
def encode(a: Array[Byte]): Either[Throwable, Array[Byte]] = | ||
a.asRight | ||
} | ||
|
||
def create[F[_]: Async: Parallel]( | ||
maxBytes: Int, | ||
sinkConfig: Config.Sink.PubSub, | ||
bufferConfig: Config.Buffer, | ||
topicName: String | ||
): Resource[F, GooglePubSubSinkHttp4s[F]] = { | ||
val config = PubsubProducerConfig[F]( | ||
batchSize = bufferConfig.recordLimit, | ||
requestByteThreshold = Some(bufferConfig.byteLimit), | ||
delayThreshold = bufferConfig.timeLimit.millis, | ||
onFailedTerminate = err => Logger[F].error(err)("PubSub sink termination error"), | ||
customizePublisher = Some(customizePublisher(sinkConfig)) | ||
) | ||
|
||
GooglePubsubProducer.of[F, Array[Byte]](ProjectId(sinkConfig.googleProjectId), Topic(topicName), config).map { | ||
producer => | ||
new GooglePubSubSinkHttp4s( | ||
maxBytes, | ||
producer, | ||
sinkConfig.retryInterval, | ||
topicName | ||
) | ||
} | ||
} | ||
|
||
private def customizePublisher(sinkConfig: Config.Sink.PubSub)(builder: Publisher.Builder) = { | ||
val custom = builder | ||
.setRetrySettings(retrySettings(sinkConfig.backoffPolicy)) | ||
.setHeaderProvider(FixedHeaderProvider.create("User-Agent", UserAgent)) | ||
createCustomProviders().foreach { | ||
case (channelProvider, credentialsProvider) => | ||
custom.setChannelProvider(channelProvider).setCredentialsProvider(credentialsProvider) | ||
} | ||
custom | ||
} | ||
|
||
private def createCustomProviders(): Option[(FixedTransportChannelProvider, NoCredentialsProvider)] = | ||
sys.env.get("PUBSUB_EMULATOR_HOST").map { hostPort => | ||
val channel = ManagedChannelBuilder.forTarget(hostPort).usePlaintext().build() | ||
val channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel)) | ||
val credentialsProvider = NoCredentialsProvider.create() | ||
(channelProvider, credentialsProvider) | ||
} | ||
|
||
private def retrySettings(backoffPolicy: Config.Sink.PubSubBackoffPolicy): RetrySettings = | ||
RetrySettings | ||
.newBuilder() | ||
.setInitialRetryDelay(Duration.ofMillis(backoffPolicy.minBackoff)) | ||
.setMaxRetryDelay(Duration.ofMillis(backoffPolicy.maxBackoff)) | ||
.setRetryDelayMultiplier(backoffPolicy.multiplier) | ||
.setTotalTimeout(Duration.ofMillis(backoffPolicy.totalBackoff)) | ||
.setInitialRpcTimeout(Duration.ofMillis(backoffPolicy.initialRpcTimeout)) | ||
.setRpcTimeoutMultiplier(backoffPolicy.rpcTimeoutMultiplier) | ||
.setMaxRpcTimeout(Duration.ofMillis(backoffPolicy.maxRpcTimeout)) | ||
.build() | ||
|
||
} |