Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix electrum client doubling 'Disconnected' event #173

Merged
merged 4 commits into from
Jan 20, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ internal sealed class ClientEvent
internal data class Start(val serverAddress: ServerAddress) : ClientEvent()
internal object Connected : ClientEvent()
internal object Disconnected : ClientEvent()
internal object Close : ClientEvent()
internal data class ReceivedResponse(val response: Either<ElectrumResponse, JsonRPCResponse>) : ClientEvent()
internal data class SendElectrumApiCall(val electrumRequest: ElectrumRequest) : ClientEvent()
internal object AskForStatus : ClientEvent()
Expand Down Expand Up @@ -160,6 +161,10 @@ private fun ClientState.unhandled(event: ClientEvent): Pair<ClientState, List<El
state = ClientClosed
actions = listOf(BroadcastStatus(Connection.CLOSED), Shutdown)
}
Close -> newState {
state = ClientClosed
actions = listOf(BroadcastStatus(Connection.CLOSED))
}
AskForStatus, AskForHeader -> returnState() // TODO something else ?
else -> {
logger.warning { "cannot process event ${event::class} in state ${this::class}" }
Expand Down Expand Up @@ -228,7 +233,7 @@ class ElectrumClient(
is SendResponse -> notificationsChannel.send(action.response)
is BroadcastStatus -> _connectionState.value = action.connection
StartPing -> pingJob = pingScheduler()
is Shutdown -> closeConnection()
is Shutdown -> disconnect()
}
}
}
Expand All @@ -240,7 +245,9 @@ class ElectrumClient(
}

fun disconnect() {
launch { eventChannel.send(Disconnected) }
pingJob?.cancel()
connectionJob?.cancel() ?: launch { eventChannel.send(Close) }
if (this::socket.isInitialized) socket.close()
}

private var connectionJob: Job? = null
Expand All @@ -261,12 +268,6 @@ class ElectrumClient(
}
}

private fun closeConnection() {
pingJob?.cancel()
connectionJob?.cancel()
if (this::socket.isInitialized) socket.close()
}

private suspend fun send(message: ByteArray) {
try {
socket.send(message)
Expand Down Expand Up @@ -298,7 +299,7 @@ class ElectrumClient(

fun stop() {
logger.info { "electrum client stopping" }
closeConnection()
disconnect()
// Cancel event consumer
runJob?.cancel()
// Cancel broadcast channels
Expand Down