|
1 | 1 | package com.devsisters.shardcake |
2 | 2 |
|
3 | 3 | import com.devsisters.shardcake.interfaces.Serialization |
4 | | -import com.twitter.chill.{ KryoInstantiator, KryoPool, ScalaKryoInstantiator } |
| 4 | +import com.typesafe.config.{ Config, ConfigFactory } |
| 5 | +import io.altoo.serialization.kryo.scala.ScalaKryoSerializer |
5 | 6 | import zio.{ Has, Task, ZIO, ZLayer } |
6 | 7 |
|
7 | 8 | object KryoSerialization { |
8 | 9 |
|
9 | 10 | /** |
10 | | - * A layer that returns a serialization implementation using the Kryo library |
| 11 | + * A layer that returns a serialization implementation using the Kryo library. |
11 | 12 | */ |
12 | 13 | val live: ZLayer[Any, Throwable, Has[Serialization]] = |
| 14 | + ZIO.effect(ConfigFactory.defaultReference()).flatMap(make).toLayer |
| 15 | + |
| 16 | + /** |
| 17 | + * A layer that returns a serialization implementation using the Kryo library, taking a Config object. |
| 18 | + * See https://github.com/altoo-ag/scala-kryo-serialization for more details about configuration. |
| 19 | + */ |
| 20 | + def liveWithConfig(config: Config): ZLayer[Any, Throwable, Has[Serialization]] = |
| 21 | + make(config).toLayer |
| 22 | + |
| 23 | + private def make(config: Config): Task[Serialization] = |
13 | 24 | ZIO.effect { |
14 | | - def kryoInstantiator: KryoInstantiator = new ScalaKryoInstantiator |
15 | | - def poolSize: Int = 4 * java.lang.Runtime.getRuntime.availableProcessors |
16 | | - KryoPool.withByteArrayOutputStream(poolSize, kryoInstantiator) |
17 | | - }.map(kryoPool => |
| 25 | + new ScalaKryoSerializer(config, getClass.getClassLoader) |
| 26 | + }.map(serializer => |
18 | 27 | new Serialization { |
19 | | - def encode(message: Any): Task[Array[Byte]] = ZIO.effect(kryoPool.toBytesWithClass(message)) |
20 | | - def decode[A](bytes: Array[Byte]): Task[A] = ZIO.effect(kryoPool.fromBytes(bytes).asInstanceOf[A]) |
| 28 | + def encode(message: Any): Task[Array[Byte]] = ZIO.fromTry(serializer.serialize(message)) |
| 29 | + def decode[A](bytes: Array[Byte]): Task[A] = ZIO.fromTry(serializer.deserialize[A](bytes)) |
21 | 30 | } |
22 | | - ).toLayer |
| 31 | + ) |
23 | 32 | } |
0 commit comments