Azure / Azure/azure-iot-service-sdk-java

MessagingClient dies and connection won't be reopen

Open
#37 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
5
Forks
14
PR merge metrics
No merged PRs in 30d

Description

I'm currently using the `MessagingClient` to send c2d messages over the iothub. We're sometimes experiencing the problem of losing the connection to the IoTHub.

We're using spring-boot with Kotlin and made a `Bean` which we're using internally.

`java.util.concurrent.TimeoutException: Timed out waiting for the connection to the service to open` is the error we're experiencing.

We already had a `try-catch` around the `sendAsync` method which tried after an exception occurred to call it like this:
```kotlin
private fun reopenConnection() {
try {
messagingClient.close()
} catch (ex: Exception) {
log.error("Failed to close IoT Hub connection", ex)
}

try {
messagingClient.open(reconnectTimeoutMs)
} catch (ex: Exception) {
log.error("Error reopening connection to IoT Hub", ex)
}
}
```

The closing did work and the `open`-call failed with the given exception message above. After that, the `open` call will never fail again or at least doesn't show that it didn't work.

I would expect that this works without any problem. The timeout is kinda low currently configured 10 seconds. But we will call this reopen in exceptional cases which occur during `sendAsync`:

```kotlin
suspend fun sendMessage(deviceId: String, message: Message) {
try {
messagingClient.sendAsync(deviceId, message, {
when (it.wasSentSuccessfully()) {
true -> {
// ...
}

false -> {
// ...
}
}
}, "sendTelemetryEvent")
} catch (ex: Exception) {
// ...
reopenConnection()
}
}
```

We now adjusted the given `reopenConnection` function to use a `Semaphore` to avoid multiple calls:
```kotlin
private suspend fun reopenConnection() {
semaphore.withPermit {
try {
messagingClient.open(reconnectTimeoutMs)
} catch (ex: Exception) {
log.error("Error reopening connection to IoT Hub", ex)
}
}
}
```
Which still seems to break it. Some feedback regarding this would be great what do we need to change to make it work (besides increasing the timeout)

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.