Skip to content

Commit 0ca584c

Browse files
committed
Improve OuraServiceUserRepository http requests
1 parent 763ba23 commit 0ca584c

File tree

1 file changed

+41
-13
lines changed

1 file changed

+41
-13
lines changed

kafka-connect-oura-source/src/main/java/org/radarbase/connect/rest/oura/user/OuraServiceUserRepository.kt

Lines changed: 41 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -251,25 +251,53 @@ class OuraServiceUserRepository : OuraUserRepository() {
251251
crossinline builder: HttpRequestBuilder.() -> Unit,
252252
): T =
253253
withContext(Dispatchers.IO) {
254+
val requestBuilder = HttpRequestBuilder()
255+
builder(requestBuilder)
256+
logger.info("Making HTTP request: ${requestBuilder.method} ${requestBuilder.url}")
257+
254258
val response = client.request(builder)
259+
logger.info("Response status: ${response.status}")
255260
val contentLength = response.contentLength()
256-
val hasBody = contentLength != null && contentLength > 0
261+
val transferEncoding = response.headers["Transfer-Encoding"]
262+
val hasBody = (contentLength != null && contentLength > 0) ||
263+
(transferEncoding != null && transferEncoding.contains("chunked"))
264+
val responseBody = try {
265+
response.bodyAsText()
266+
} catch (e: Exception) {
267+
"Error reading body: ${e.message}"
268+
}
269+
257270
if (response.status == HttpStatusCode.NotFound) {
271+
logger.error("HTTP 404 Not Found: ${response.request.url}")
258272
throw NoSuchElementException("URL " + response.request.url + " does not exist")
259-
} else if (!response.status.isSuccess() || !hasBody) {
260-
val message =
261-
buildString {
262-
append("Failed to make request (HTTP status code ")
263-
append(response.status)
264-
append(')')
265-
if (hasBody) {
266-
append(": ")
267-
append(response.bodyAsText())
268-
}
269-
}
273+
} else if (!response.status.isSuccess()) {
274+
val message = "HTTP ${response.status.value} error: $responseBody"
275+
logger.error(message)
270276
throw HttpResponseException(message, response.status.value)
277+
} else if (!hasBody) {
278+
logger.warn(
279+
"HTTP ${response.status.value} OK but no body content. Returning empty result.",
280+
)
281+
// Handle successful responses with empty body
282+
@Suppress("UNCHECKED_CAST")
283+
return@withContext when (T::class) {
284+
String::class -> "" as T
285+
List::class -> emptyList<Any>() as T
286+
else -> mapper.readValue<T>("{}")
287+
}
288+
}
289+
290+
try {
291+
val result = mapper.readValue<T>(responseBody)
292+
logger.info("Successfully parsed response as ${T::class.simpleName}")
293+
result
294+
} catch (e: Exception) {
295+
logger.error(
296+
"Failed to parse response body as ${T::class.simpleName}: ${e.message}",
297+
)
298+
logger.error("Response body that failed to parse: $responseBody")
299+
throw e
271300
}
272-
mapper.readValue<T>(response.bodyAsText())
273301
}
274302

275303
companion object {

0 commit comments

Comments
 (0)