|
| 1 | +package org.ton.kotlin.provider.liteapi.internal |
| 2 | + |
| 3 | +import io.ktor.util.collections.* |
| 4 | +import kotlinx.coroutines.* |
| 5 | +import kotlinx.coroutines.channels.Channel |
| 6 | +import kotlinx.coroutines.sync.Mutex |
| 7 | +import kotlinx.coroutines.sync.withLock |
| 8 | +import kotlinx.io.bytestring.ByteString |
| 9 | +import kotlinx.serialization.SerializationException |
| 10 | +import kotlinx.serialization.decodeFromByteArray |
| 11 | +import org.ton.kotlin.tl.TL |
| 12 | +import kotlin.concurrent.Volatile |
| 13 | +import kotlin.properties.Delegates |
| 14 | +import kotlin.random.Random |
| 15 | + |
| 16 | +internal abstract class LiteConnection { |
| 17 | + private var isTransportReady: Boolean = false |
| 18 | + private var transport: LiteTransport by Delegates.notNull() |
| 19 | + private val transportInitializationLock = Mutex() |
| 20 | + |
| 21 | + private var sendJob: Job? = null |
| 22 | + private var receiveJob: Job? = null |
| 23 | + private var sendChannel: Channel<TransportMessage>? = null |
| 24 | + private val answerSubscriptions = |
| 25 | + ConcurrentMap<ByteString, suspend (LiteMessage.Answer) -> Unit>() |
| 26 | + |
| 27 | + @Volatile |
| 28 | + private var clientCancelled = false |
| 29 | + |
| 30 | + protected abstract suspend fun initializeTransport(): LiteTransport |
| 31 | + |
| 32 | + private suspend fun initializeAndAwaitHandshakeCompletion() { |
| 33 | + if (!isTransportReady) { |
| 34 | + transportInitializationLock.withLock { |
| 35 | + if (isTransportReady) { |
| 36 | + return@withLock |
| 37 | + } |
| 38 | + |
| 39 | + transport = initializeTransport() |
| 40 | + setupTransportLoops() |
| 41 | + isTransportReady = true |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + private fun setupTransportLoops() { |
| 47 | + val channel = Channel<TransportMessage>(Channel.UNLIMITED) |
| 48 | + sendChannel = channel |
| 49 | + |
| 50 | + sendJob = transport.launch(CoroutineName("lite-connection-send-loop")) { |
| 51 | + while (true) { |
| 52 | + val message = channel.receiveCatching().getOrNull() ?: break |
| 53 | + transport.send(message) |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + receiveJob = transport.launch(CoroutineName("lite-connection-receive-loop")) { |
| 58 | + while (true) { |
| 59 | + val incoming = transport.receiveCatching().getOrNull() ?: break |
| 60 | + processTransportMessage(incoming) |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + transport.coroutineContext.job.invokeOnCompletion { |
| 65 | + sendJob?.cancel() |
| 66 | + receiveJob?.cancel() |
| 67 | + clientCancelled = true |
| 68 | + answerSubscriptions.clear() |
| 69 | + channel.close(it) |
| 70 | + sendChannel = null |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + suspend fun call( |
| 75 | + call: ByteArray, |
| 76 | + ): ByteArray { |
| 77 | + if (clientCancelled) { |
| 78 | + error("LiteConnection was canceled") |
| 79 | + } |
| 80 | + |
| 81 | + initializeAndAwaitHandshakeCompletion() |
| 82 | + |
| 83 | + val queryId = ByteString(*Random.nextBytes(32)) |
| 84 | + val channel = Channel<LiteMessage.Answer>() |
| 85 | + try { |
| 86 | + val query = LiteMessage.Query(queryId, ByteString(*call)) |
| 87 | + |
| 88 | + subscribeToAnswer(queryId) { message -> |
| 89 | + channel.send(message) |
| 90 | + } |
| 91 | + |
| 92 | + sendMessage(query) |
| 93 | + |
| 94 | + return channel.receiveCatching().getOrThrow().query.toByteArray() |
| 95 | + } catch (e: CancellationException) { |
| 96 | + throw e |
| 97 | + } finally { |
| 98 | + channel.close() |
| 99 | + unsubscribeFromAnswers(queryId) |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + private fun subscribeToAnswer( |
| 104 | + queryId: ByteString, |
| 105 | + subscription: suspend (LiteMessage.Answer) -> Unit, |
| 106 | + ) { |
| 107 | + answerSubscriptions.computeIfAbsent(queryId) { |
| 108 | + subscription |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + private fun unsubscribeFromAnswers(queryId: ByteString) { |
| 113 | + answerSubscriptions.remove(queryId) |
| 114 | + } |
| 115 | + |
| 116 | + private suspend fun sendMessage(message: LiteMessage) { |
| 117 | + val data = TL.Boxed.encodeToByteArray(LiteMessage.serializer(), message) |
| 118 | + sendTransportMessage(TransportMessage(data)) |
| 119 | + } |
| 120 | + |
| 121 | + private suspend fun sendTransportMessage(transportMessage: TransportMessage) { |
| 122 | + val channel = checkNotNull(sendChannel) { |
| 123 | + "Transport channel is not initialized" |
| 124 | + } |
| 125 | + channel.send(transportMessage) |
| 126 | + } |
| 127 | + |
| 128 | + private suspend fun processTransportMessage(transportMessage: TransportMessage) { |
| 129 | + val message = decodeMessage(transportMessage) ?: return |
| 130 | + processMessage(message) |
| 131 | + } |
| 132 | + |
| 133 | + private fun decodeMessage(transportMessage: TransportMessage): LiteMessage? { |
| 134 | + try { |
| 135 | + return TL.Boxed.decodeFromByteArray<LiteMessage>(transportMessage.value) |
| 136 | + } catch (_: SerializationException) { |
| 137 | + } catch (_: IllegalArgumentException) { |
| 138 | + } |
| 139 | + return null |
| 140 | + } |
| 141 | + |
| 142 | + private suspend fun processMessage(message: LiteMessage) { |
| 143 | + when (message) { |
| 144 | + is LiteMessage.Query -> processQuery(message) |
| 145 | + is LiteMessage.Answer -> processAnswer(message) |
| 146 | + is LiteMessage.Authentificate -> processAuthentificate(message) |
| 147 | + is LiteMessage.AuthentificationComplete -> processAuthentificationComplete(message) |
| 148 | + is LiteMessage.AuthentificationNonce -> processAuthentificationNonce(message) |
| 149 | + is LiteMessage.Ping -> processPing(message) |
| 150 | + is LiteMessage.Pong -> processPong(message) |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + private fun processQuery(message: LiteMessage.Query) {} |
| 155 | + |
| 156 | + private suspend fun processAnswer(message: LiteMessage.Answer) { |
| 157 | + answerSubscriptions[message.queryId]?.invoke(message) |
| 158 | + } |
| 159 | + |
| 160 | + private fun processAuthentificate(message: LiteMessage.Authentificate) {} |
| 161 | + |
| 162 | + private fun processAuthentificationComplete(message: LiteMessage.AuthentificationComplete) {} |
| 163 | + |
| 164 | + private fun processAuthentificationNonce(message: LiteMessage.AuthentificationNonce) {} |
| 165 | + |
| 166 | + private fun processPing(message: LiteMessage.Ping) {} |
| 167 | + |
| 168 | + private fun processPong(message: LiteMessage.Pong) {} |
| 169 | +} |
0 commit comments