-
Notifications
You must be signed in to change notification settings - Fork 36
/
io.scala
472 lines (410 loc) · 16.2 KB
/
io.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*
* Copyright (c) 2020-2022 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.enrich.common.fs2.config
import java.nio.file.{InvalidPathException, Path, Paths}
import java.time.Instant
import java.net.URI
import java.util.UUID
import cats.syntax.either._
import cats.data.NonEmptyList
import scala.concurrent.duration.{Duration, FiniteDuration}
import _root_.io.circe.{Decoder, DecodingFailure, Encoder}
import _root_.io.circe.generic.extras.semiauto._
import _root_.io.circe.config.syntax._
import _root_.io.circe.DecodingFailure
import org.http4s.{ParseFailure, Uri}
import com.snowplowanalytics.snowplow.enrich.common.EtlPipeline.{FeatureFlags => CommonFeatureFlags}
object io {
val putRecordsMaxRecords = 500
import ConfigFile.finiteDurationEncoder
implicit val javaPathDecoder: Decoder[Path] =
Decoder[String].emap { s =>
Either.catchOnly[InvalidPathException](Paths.get(s)).leftMap(_.getMessage)
}
implicit val javaPathEncoder: Encoder[Path] =
Encoder[String].contramap(_.toString)
implicit val javaUriDecoder: Decoder[URI] =
Decoder[String].emap { s =>
Either.catchOnly[IllegalArgumentException](URI.create(s)).leftMap(err => s"error while parsing URI $s: ${err.getMessage}")
}
implicit val javaUriEncoder: Encoder[URI] =
Encoder.encodeString.contramap[URI](_.toString)
implicit val http4sUriDecoder: Decoder[Uri] =
Decoder[String].emap(s => Either.catchOnly[ParseFailure](Uri.unsafeFromString(s)).leftMap(_.toString))
implicit val http4sUriEncoder: Encoder[Uri] =
Encoder[String].contramap(_.toString)
import ConfigFile.finiteDurationEncoder
case class BackoffPolicy(
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
maxRetries: Option[Int]
)
object BackoffPolicy {
implicit def backoffPolicyDecoder: Decoder[BackoffPolicy] =
deriveConfiguredDecoder[BackoffPolicy]
implicit def backoffPolicyEncoder: Encoder[BackoffPolicy] =
deriveConfiguredEncoder[BackoffPolicy]
}
sealed trait RetryCheckpointing {
val checkpointBackoff: BackoffPolicy
}
case class RabbitMQNode(
host: String,
port: Int
)
object RabbitMQNode {
implicit val rabbitMQNodeDecoder: Decoder[RabbitMQNode] = deriveConfiguredDecoder[RabbitMQNode]
implicit val rabbitMQNodeEncoder: Encoder[RabbitMQNode] = deriveConfiguredEncoder[RabbitMQNode]
}
case class RabbitMQConfig(
nodes: NonEmptyList[RabbitMQNode],
username: String,
password: String,
virtualHost: String,
connectionTimeout: Int,
ssl: Boolean,
internalQueueSize: Int,
requestedHeartbeat: Int,
automaticRecovery: Boolean
)
object RabbitMQConfig {
implicit val rabbitMQConfigDecoder: Decoder[RabbitMQConfig] = deriveConfiguredDecoder[RabbitMQConfig]
implicit val rabbitMQConfigEncoder: Encoder[RabbitMQConfig] = deriveConfiguredEncoder[RabbitMQConfig]
}
sealed trait Input
object Input {
case class PubSub private (
subscription: String,
parallelPullCount: Int,
maxQueueSize: Int,
maxRequestBytes: Int,
maxAckExtensionPeriod: FiniteDuration
) extends Input {
val (project, name) =
subscription.split("/").toList match {
case List("projects", project, "subscriptions", name) =>
(project, name)
case _ =>
throw new IllegalArgumentException(s"Subscription format $subscription invalid")
}
}
case class FileSystem(dir: Path) extends Input
case class Kinesis private (
appName: String,
streamName: String,
region: Option[String],
initialPosition: Kinesis.InitPosition,
retrievalMode: Kinesis.Retrieval,
bufferSize: Int,
checkpointBackoff: BackoffPolicy,
customEndpoint: Option[URI],
dynamodbCustomEndpoint: Option[URI],
cloudwatchCustomEndpoint: Option[URI]
) extends Input
with RetryCheckpointing
case class RabbitMQ(
cluster: RabbitMQConfig,
queue: String,
checkpointBackoff: BackoffPolicy
) extends Input
with RetryCheckpointing
object Kinesis {
sealed trait InitPosition
object InitPosition {
case object Latest extends InitPosition
case object TrimHorizon extends InitPosition
case class AtTimestamp(timestamp: Instant) extends InitPosition
case class InitPositionRaw(`type`: String, timestamp: Option[Instant])
implicit val initPositionRawDecoder: Decoder[InitPositionRaw] = deriveConfiguredDecoder[InitPositionRaw]
implicit val initPositionDecoder: Decoder[InitPosition] =
Decoder.instance { cur =>
for {
rawParsed <- cur.as[InitPositionRaw].map(raw => raw.copy(`type` = raw.`type`.toUpperCase))
initPosition <- rawParsed match {
case InitPositionRaw("TRIM_HORIZON", _) =>
TrimHorizon.asRight
case InitPositionRaw("LATEST", _) =>
Latest.asRight
case InitPositionRaw("AT_TIMESTAMP", Some(timestamp)) =>
AtTimestamp(timestamp).asRight
case other =>
DecodingFailure(
s"Initial position $other is not supported. Possible types are TRIM_HORIZON, LATEST and AT_TIMESTAMP (must provide timestamp field)",
cur.history
).asLeft
}
} yield initPosition
}
implicit val initPositionEncoder: Encoder[InitPosition] = deriveConfiguredEncoder[InitPosition]
}
sealed trait Retrieval
object Retrieval {
case class Polling(maxRecords: Int) extends Retrieval
case object FanOut extends Retrieval
case class RetrievalRaw(`type`: String, maxRecords: Option[Int])
implicit val retrievalRawDecoder: Decoder[RetrievalRaw] = deriveConfiguredDecoder[RetrievalRaw]
implicit val retrievalDecoder: Decoder[Retrieval] =
Decoder.instance { cur =>
for {
rawParsed <- cur.as[RetrievalRaw].map(raw => raw.copy(`type` = raw.`type`.toUpperCase))
retrieval <- rawParsed match {
case RetrievalRaw("POLLING", Some(maxRecords)) =>
Polling(maxRecords).asRight
case RetrievalRaw("FANOUT", _) =>
FanOut.asRight
case other =>
DecodingFailure(
s"Retrieval mode $other is not supported. Possible types are FanOut and Polling (must provide maxRecords field)",
cur.history
).asLeft
}
} yield retrieval
}
implicit val retrievalEncoder: Encoder[Retrieval] = deriveConfiguredEncoder[Retrieval]
}
implicit val kinesisDecoder: Decoder[Kinesis] = deriveConfiguredDecoder[Kinesis]
implicit val kinesisEncoder: Encoder[Kinesis] = deriveConfiguredEncoder[Kinesis]
}
implicit val inputDecoder: Decoder[Input] =
deriveConfiguredDecoder[Input]
.emap {
case s @ PubSub(sub, _, _, _, _) =>
sub.split("/").toList match {
case List("projects", _, "subscriptions", _) =>
s.asRight
case _ =>
s"Subscription must conform projects/project-name/subscriptions/subscription-name format, $s given".asLeft
}
case other => other.asRight
}
.emap {
case PubSub(_, p, _, _, _) if p <= 0 =>
"PubSub parallelPullCount must be > 0".asLeft
case PubSub(_, _, m, _, _) if m <= 0 =>
"PubSub maxQueueSize must be > 0".asLeft
case PubSub(_, _, _, m, _) if m <= 0 =>
"PubSub maxRequestBytes must be > 0".asLeft
case PubSub(_, _, _, _, m) if m < Duration.Zero =>
"PubSub maxAckExtensionPeriod must be >= 0".asLeft
case other =>
other.asRight
}
implicit val inputEncoder: Encoder[Input] =
deriveConfiguredEncoder[Input]
}
case class Outputs(
good: Output,
pii: Option[Output],
bad: Output
)
object Outputs {
implicit val outputsDecoder: Decoder[Outputs] = deriveConfiguredDecoder[Outputs]
implicit val outputsEncoder: Encoder[Outputs] = deriveConfiguredEncoder[Outputs]
}
sealed trait Output
object Output {
case class PubSub private (
topic: String,
attributes: Option[Set[String]],
delayThreshold: FiniteDuration,
maxBatchSize: Long,
maxBatchBytes: Long
) extends Output {
val (project, name) =
topic.split("/").toList match {
case _ if topic.isEmpty =>
("", "")
case List("projects", project, "topics", name) =>
(project, name)
case _ =>
throw new IllegalArgumentException(s"Topic format $topic invalid")
}
}
case class FileSystem(file: Path, maxBytes: Option[Long]) extends Output
case class Kinesis(
streamName: String,
region: Option[String],
partitionKey: Option[String],
backoffPolicy: BackoffPolicy,
throttledBackoffPolicy: BackoffPolicy,
recordLimit: Int,
byteLimit: Int,
customEndpoint: Option[URI]
) extends Output
case class RabbitMQ(
cluster: RabbitMQConfig,
exchange: String,
routingKey: String,
backoffPolicy: BackoffPolicy
) extends Output
implicit val outputDecoder: Decoder[Output] =
deriveConfiguredDecoder[Output]
.emap {
case s @ PubSub(top, _, _, _, _) if top.nonEmpty =>
top.split("/").toList match {
case List("projects", _, "topics", _) =>
s.asRight
case _ =>
s"Topic must conform projects/project-name/topics/topic-name format, $top given".asLeft
}
case k: Kinesis if k.streamName.isEmpty && k.region.nonEmpty =>
"streamName needs to be set".asLeft
case other => other.asRight
}
.emap {
case p: PubSub if p.delayThreshold < Duration.Zero =>
"PubSub delay threshold cannot be less than 0".asLeft
case p: PubSub if p.maxBatchSize < 0 =>
"PubSub max batch size cannot be less than 0".asLeft
case p: PubSub if p.maxBatchBytes < 0 =>
"PubSub max batch bytes cannot be less than 0".asLeft
case k: Kinesis if k.recordLimit > putRecordsMaxRecords =>
s"recordLimit can't be > $putRecordsMaxRecords".asLeft
case other =>
other.asRight
}
implicit val outputEncoder: Encoder[Output] =
deriveConfiguredEncoder[Output]
}
final case class Concurrency(enrich: Long, sink: Int)
object Concurrency {
implicit val concurrencyDecoder: Decoder[Concurrency] =
deriveConfiguredDecoder[Concurrency]
implicit val concurrencyEncoder: Encoder[Concurrency] =
deriveConfiguredEncoder[Concurrency]
}
final case class MetricsReporters(
statsd: Option[MetricsReporters.StatsD],
stdout: Option[MetricsReporters.Stdout],
cloudwatch: Boolean
)
object MetricsReporters {
final case class Stdout(period: FiniteDuration, prefix: Option[String])
final case class StatsD(
hostname: String,
port: Int,
tags: Map[String, String],
period: FiniteDuration,
prefix: Option[String]
)
implicit val stdoutDecoder: Decoder[Stdout] =
deriveConfiguredDecoder[Stdout].emap { stdout =>
if (stdout.period < Duration.Zero)
"metrics report period in config file cannot be less than 0".asLeft
else
stdout.asRight
}
implicit val statsDecoder: Decoder[StatsD] =
deriveConfiguredDecoder[StatsD].emap { statsd =>
if (statsd.period < Duration.Zero)
"metrics report period in config file cannot be less than 0".asLeft
else
statsd.asRight
}
implicit val metricsReportersDecoder: Decoder[MetricsReporters] =
deriveConfiguredDecoder[MetricsReporters]
implicit val stdoutEncoder: Encoder[Stdout] =
deriveConfiguredEncoder[Stdout]
implicit val statsdEncoder: Encoder[StatsD] =
deriveConfiguredEncoder[StatsD]
implicit val metricsReportersEncoder: Encoder[MetricsReporters] =
deriveConfiguredEncoder[MetricsReporters]
def normalizeMetric(prefix: Option[String], metric: String): String =
s"${prefix.getOrElse(DefaultPrefix).stripSuffix(".")}.$metric".stripPrefix(".")
val DefaultPrefix = "snowplow.enrich"
}
case class Monitoring(sentry: Option[Sentry], metrics: MetricsReporters)
object Monitoring {
implicit val monitoringDecoder: Decoder[Monitoring] =
deriveConfiguredDecoder[Monitoring]
implicit val monitoringEncoder: Encoder[Monitoring] =
deriveConfiguredEncoder[Monitoring]
}
case class RemoteAdapterConfig(
vendor: String,
version: String,
url: String
)
object RemoteAdapterConfig {
implicit val remoteAdapterConfigEncoder: Encoder[RemoteAdapterConfig] =
deriveConfiguredEncoder[RemoteAdapterConfig]
implicit val remoteAdapterConfigDecoder: Decoder[RemoteAdapterConfig] =
deriveConfiguredDecoder[RemoteAdapterConfig]
}
case class RemoteAdapterConfigs(
connectionTimeout: FiniteDuration,
readTimeout: FiniteDuration,
maxConnections: Int,
configs: List[RemoteAdapterConfig]
)
object RemoteAdapterConfigs {
implicit val remoteAdapterConfigsEncoder: Encoder[RemoteAdapterConfigs] =
deriveConfiguredEncoder[RemoteAdapterConfigs]
implicit val remoteAdapterConfigsDecoder: Decoder[RemoteAdapterConfigs] =
deriveConfiguredDecoder[RemoteAdapterConfigs]
}
case class Telemetry(
disable: Boolean,
interval: FiniteDuration,
method: String,
collectorUri: String,
collectorPort: Int,
secure: Boolean,
userProvidedId: Option[String],
autoGeneratedId: Option[String],
instanceId: Option[String],
moduleName: Option[String],
moduleVersion: Option[String]
)
object Telemetry {
implicit val telemetryDecoder: Decoder[Telemetry] =
deriveConfiguredDecoder[Telemetry]
implicit val telemetryEncoder: Encoder[Telemetry] =
deriveConfiguredEncoder[Telemetry]
}
case class Metadata(
endpoint: Uri,
interval: FiniteDuration,
organizationId: UUID,
pipelineId: UUID
)
object Metadata {
implicit val metadataDecoder: Decoder[Metadata] =
deriveConfiguredDecoder[Metadata]
implicit val metadataEncoder: Encoder[Metadata] =
deriveConfiguredEncoder[Metadata]
}
case class Experimental(metadata: Option[Metadata])
object Experimental {
implicit val experimentalDecoder: Decoder[Experimental] =
deriveConfiguredDecoder[Experimental]
implicit val experimentalEncoder: Encoder[Experimental] =
deriveConfiguredEncoder[Experimental]
}
case class FeatureFlags(
acceptInvalid: Boolean,
legacyEnrichmentOrder: Boolean
)
object FeatureFlags {
implicit val featureFlagsDecoder: Decoder[FeatureFlags] =
deriveConfiguredDecoder[FeatureFlags]
implicit val featureFlagsEncoder: Encoder[FeatureFlags] =
deriveConfiguredEncoder[FeatureFlags]
// Currently the FS2 feature flags exactly match the common feature flags, but it might not always be like this.
def toCommon(ff: FeatureFlags): CommonFeatureFlags =
CommonFeatureFlags(
acceptInvalid = ff.acceptInvalid,
legacyEnrichmentOrder = ff.legacyEnrichmentOrder
)
}
}