-
Notifications
You must be signed in to change notification settings - Fork 4
/
ConfluentSchemaRegistryClient.scala
292 lines (268 loc) · 8.89 KB
/
ConfluentSchemaRegistryClient.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
package io.epiphanous.flinkrunner.avro
import cats.effect.{ContextShift, IO, Resource, Timer}
import com.google.common.cache.{CacheBuilder, CacheLoader, LoadingCache}
import com.typesafe.scalalogging.LazyLogging
import io.circe.Decoder
import io.epiphanous.flinkrunner.model.FlinkConfig
import io.epiphanous.flinkrunner.util.StringUtils
import org.apache.avro.Schema.Parser
import org.apache.flink.runtime.concurrent.Executors.directExecutionContext
import org.http4s.EntityDecoder
import org.http4s.circe.jsonOf
import org.http4s.client.Client
import org.http4s.client.blaze.BlazeClientBuilder
import java.nio.ByteBuffer
import java.util.concurrent.TimeUnit
import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success, Try}
class ConfluentSchemaRegistryClient()(implicit
config: FlinkConfig,
decoder: Decoder[ConfluentSchemaRegistryResponse])
extends AvroSchemaRegistryClient[ConfluentSchemaRegistryContext]
with StringUtils
with LazyLogging
with Serializable {
import ConfluentSchemaRegistryClient.configPrefix
@transient
lazy val preloaded: Map[String, RegisteredAvroSchema] = Map.empty
@transient
lazy implicit val entityDecoder
: EntityDecoder[IO, ConfluentSchemaRegistryResponse] =
jsonOf[IO, ConfluentSchemaRegistryResponse]
@transient
lazy implicit val ec: ExecutionContext = directExecutionContext()
@transient
lazy implicit val cs: ContextShift[IO] = IO.contextShift(ec)
@transient
lazy implicit val timer: Timer[IO] = IO.timer(ec)
@transient
lazy val api: Resource[IO, Client[IO]] =
BlazeClientBuilder[IO](ec).resource
@transient
lazy val parser = new Parser()
@transient
lazy val urlBase: String = config.getString(s"$configPrefix.url.base")
@transient
lazy val cacheLoader: CacheLoader[String, Try[RegisteredAvroSchema]] =
new CacheLoader[String, Try[RegisteredAvroSchema]] {
override def load(uri: String): Try[RegisteredAvroSchema] = {
logger.debug(s"=== confluent schema registry cache load $uri")
preloaded.get(uri) match {
case Some(pre) => Success(pre)
case None =>
api
.use { client =>
client
.expect[ConfluentSchemaRegistryResponse](uri)
.attempt
}
.unsafeRunSync() match {
case Left(failure) =>
logger.error(s"Can't load key $uri: ${failure.getMessage}")
Failure(failure)
case Right(response) =>
response match {
case byId: ConfluentSchemaRegistryResponseById =>
val id = uri.split("/").last
val schema = parser.parse(byId.schema)
Success(RegisteredAvroSchema(schema, id))
case bySubjectVersion: ConfluentSchemaRegistryResponseBySubjectVersion =>
val schema = parser.parse(bySubjectVersion.schema)
Success(
RegisteredAvroSchema(
schema,
bySubjectVersion.id.toString,
Some(bySubjectVersion.subject),
Some(bySubjectVersion.version.toString)
)
)
}
}
}
}
}
@transient
lazy val cache: LoadingCache[String, Try[RegisteredAvroSchema]] = {
logger.debug("=== initializing new confluent schema registry cache")
val expireAfter =
config.getDuration(s"$configPrefix.cache.expire.after")
val builder = CacheBuilder
.newBuilder()
.concurrencyLevel(
config.getInt(s"$configPrefix.cache.concurrency.level")
)
.maximumSize(config.getInt(s"$configPrefix.cache.max.size"))
.expireAfterWrite(expireAfter.toMillis, TimeUnit.MILLISECONDS)
// .expireAfterWrite(expireAfter) // for guava 27
if (!config.getBoolean(s"$configPrefix.cache.use.strong.keys"))
builder.weakKeys()
if (config.getBoolean(s"$configPrefix.cache.record.stats"))
builder.recordStats()
builder.build[String, Try[RegisteredAvroSchema]](cacheLoader)
}
/**
* Extract the schema id from the first 5 bytes (first byte is magic 0x0,
* next 4 is integer id), load the schema from the confluent registry and
* return the schema and remaining encoded bytes.
* @param message
* a byte array containing any schema identification as well as a
* binary avro encoded message
* @param optContext
* the optional context (not used here)
* @return
* a (schema, bytes) tuple, wrapped in a [[Try]]
*/
override def getFromMessage(
message: Array[Byte],
optContext: Option[ConfluentSchemaRegistryContext] = None)
: Try[(RegisteredAvroSchema, Array[Byte])] = for {
buffer <- Try(ByteBuffer.wrap(message))
_ <- Try {
if (buffer.get == 0x0) Success(true)
else
Failure(
new Throwable(
s"message bytes missing initial magic 0x0 byte"
)
)
}
id <- Try(buffer.getInt())
schema <- cache
.get(url(id))
.map(schema =>
putCache(
schema,
url(
schema.subject,
optContext
.getOrElse(ConfluentSchemaRegistryContext())
.version
)
)
)
bytes <- Try {
val b = new Array[Byte](buffer.remaining())
buffer.get(b)
b
}
} yield (schema, bytes)
/**
* @param event
* the event
* @param optContext
* the optional context
* @tparam E
* the type of event
* @return
* a (schema, magic) tuple, wrapped in a [[Try]]
*/
override def getFromEvent[E](
event: E,
optContext: Option[ConfluentSchemaRegistryContext] = None)
: Try[(RegisteredAvroSchema, Array[Byte])] = for {
schema <-
cache
.get(
url(
getSubjectName(event, optContext),
optContext.getOrElse(ConfluentSchemaRegistryContext()).version
)
)
.map(schema => putCache(schema, url(schema.id.toInt)))
magic <- Try {
ByteBuffer
.wrap(new Array[Byte](5))
.put(0x0.toByte)
.putInt(schema.id.toInt)
.array()
}
} yield (schema, magic)
/**
* Return the registry subject name of the schema associated with the
* provided event instance.
*
* @param event
* an instance of E
* @param optContext
* optional [[ConfluentSchemaRegistryContext]]
* @tparam E
* event class
* @return
* schema subject name
*/
protected def getSubjectName[E](
event: E,
optContext: Option[ConfluentSchemaRegistryContext] = None): String =
(event.getClass.getCanonicalName.split("\\.")
:+ (if (optContext.getOrElse(ConfluentSchemaRegistryContext()).isKey)
"key"
else "value"))
.map(snakify)
.map(name => clean(name, replacement = "_"))
.mkString("_")
/**
* Retrieve a schema based on its id or subject, and optionally, some
* additional context information.
*
* @param idOrSubject
* the id or subject key
* @param optContext
* the optional context
* @return
*/
override def get(
idOrSubject: String,
optContext: Option[ConfluentSchemaRegistryContext])
: Try[RegisteredAvroSchema] = ???
/**
* Put the schema into the registry.
*
* @param schema
* a registered avro schema instance
* @return
* the schema sent in
*/
override def put(
schema: RegisteredAvroSchema,
optContext: Option[ConfluentSchemaRegistryContext] = None)
: Try[RegisteredAvroSchema] = ???
/**
* Ensure a schema is in the cache at a provided key.
* @param schema
* the schema to install
* @param key
* the key to find the schema by
* @return
* the schema
*/
def putCache(
schema: RegisteredAvroSchema,
key: String): RegisteredAvroSchema = {
cache.put(key, Success(schema))
schema
}
/**
* Return the api endpoint used to retrieve a schema by id
*
* @param id
* the id of the schema to retrieve
* @return
* the endpoint url
*/
protected def url(id: Int): String = s"$urlBase/schemas/ids/$id"
/**
* Return the api endpoint used to retrieve a schema by its subject name
* and version string.
*
* @param subject
* the full name of the schema
* @param version
* the version to retrieve (defaults to "latest")
* @return
*/
protected def url(subject: String, version: String = "1"): String =
s"$urlBase/subjects/$subject/versions/$version"
}
object ConfluentSchemaRegistryClient {
final val configPrefix = "confluent.avro.schema.registry"
}