- Notifications
You must be signed in to change notification settings - Fork1
impl: improved logging and error collection for the http client#165
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
9 commits Select commitHold shift + click to select a range
4f1c279
impl: relax json syntax rules for deserialization
fioan8950da220
Merge branch 'main' into impl-lenient-http-client
fioan897d4a8ad
impl: add error logging for malformed JSON responses in Coder REST AP…
fioan898fca449
impl: configuration for controlling the rest api client log level
fioan89f8606a0
impl: configure the rest api client log level from the Settings page
fioan894cab216
impl: log the rest api client request and response
fioan898a3a698
chore: remove support for lenient moshi marshaller
fioan892decf9b
chore: refactor interceptor around the kotlin buildString DSL
fioan893899d77
doc: how to enable http logging
fioan89File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
1 change: 1 addition & 0 deletionsCHANGELOG.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
58 changes: 58 additions & 0 deletionsREADME.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
14 changes: 11 additions & 3 deletionssrc/main/kotlin/com/coder/toolbox/sdk/CoderRestClient.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletionssrc/main/kotlin/com/coder/toolbox/sdk/convertors/LoggingConverterFactory.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package com.coder.toolbox.sdk.convertors | ||
import com.coder.toolbox.CoderToolboxContext | ||
import okhttp3.RequestBody | ||
import okhttp3.ResponseBody | ||
import retrofit2.Converter | ||
import retrofit2.Retrofit | ||
import java.lang.reflect.Type | ||
class LoggingConverterFactory private constructor( | ||
private val context: CoderToolboxContext, | ||
private val delegate: Converter.Factory, | ||
) : Converter.Factory() { | ||
override fun responseBodyConverter( | ||
type: Type, | ||
annotations: Array<Annotation>, | ||
retrofit: Retrofit | ||
): Converter<ResponseBody, *>? { | ||
// Get the delegate converter | ||
val delegateConverter = delegate.responseBodyConverter(type, annotations, retrofit) | ||
?: return null | ||
@Suppress("UNCHECKED_CAST") | ||
return LoggingMoshiConverter(context, delegateConverter as Converter<ResponseBody, Any?>) | ||
} | ||
override fun requestBodyConverter( | ||
type: Type, | ||
parameterAnnotations: Array<Annotation>, | ||
methodAnnotations: Array<Annotation>, | ||
retrofit: Retrofit | ||
): Converter<*, RequestBody>? { | ||
return delegate.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit) | ||
} | ||
override fun stringConverter( | ||
type: Type, | ||
annotations: Array<Annotation>, | ||
retrofit: Retrofit | ||
): Converter<*, String>? { | ||
return delegate.stringConverter(type, annotations, retrofit) | ||
} | ||
companion object { | ||
fun wrap( | ||
context: CoderToolboxContext, | ||
delegate: Converter.Factory, | ||
): LoggingConverterFactory { | ||
return LoggingConverterFactory(context, delegate) | ||
} | ||
} | ||
} |
34 changes: 34 additions & 0 deletionssrc/main/kotlin/com/coder/toolbox/sdk/convertors/LoggingMoshiConverter.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package com.coder.toolbox.sdk.convertors | ||
import com.coder.toolbox.CoderToolboxContext | ||
import okhttp3.ResponseBody | ||
import okhttp3.ResponseBody.Companion.toResponseBody | ||
import retrofit2.Converter | ||
class LoggingMoshiConverter( | ||
private val context: CoderToolboxContext, | ||
private val delegate: Converter<ResponseBody, Any?> | ||
) : Converter<ResponseBody, Any> { | ||
override fun convert(value: ResponseBody): Any? { | ||
val bodyString = value.string() | ||
return try { | ||
// Parse with Moshi | ||
delegate.convert(bodyString.toResponseBody(value.contentType())) | ||
} catch (e: Exception) { | ||
// Log the raw content that failed to parse | ||
context.logger.error( | ||
""" | ||
|Moshi parsing failed: | ||
|Content-Type: ${value.contentType()} | ||
|Content: $bodyString | ||
|Error: ${e.message} | ||
""".trimMargin() | ||
) | ||
// Re-throw so the onFailure callback still gets called | ||
throw e | ||
} | ||
} | ||
} |
120 changes: 120 additions & 0 deletionssrc/main/kotlin/com/coder/toolbox/sdk/interceptors/LoggingInterceptor.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
package com.coder.toolbox.sdk.interceptors | ||
import com.coder.toolbox.CoderToolboxContext | ||
import com.coder.toolbox.settings.HttpLoggingVerbosity | ||
import okhttp3.Headers | ||
import okhttp3.Interceptor | ||
import okhttp3.MediaType | ||
import okhttp3.Request | ||
import okhttp3.RequestBody | ||
import okhttp3.Response | ||
import okhttp3.ResponseBody | ||
import okio.Buffer | ||
import java.nio.charset.StandardCharsets | ||
private val SENSITIVE_HEADERS = setOf("Coder-Session-Token", "Proxy-Authorization") | ||
class LoggingInterceptor(private val context: CoderToolboxContext) : Interceptor { | ||
override fun intercept(chain: Interceptor.Chain): Response { | ||
val logLevel = context.settingsStore.httpClientLogLevel | ||
if (logLevel == HttpLoggingVerbosity.NONE) { | ||
return chain.proceed(chain.request()) | ||
} | ||
val request = chain.request() | ||
logRequest(request, logLevel) | ||
val response = chain.proceed(request) | ||
logResponse(response, request, logLevel) | ||
return response | ||
} | ||
private fun logRequest(request: Request, logLevel: HttpLoggingVerbosity) { | ||
val log = buildString { | ||
append("request --> ${request.method} ${request.url}") | ||
if (logLevel >= HttpLoggingVerbosity.HEADERS) { | ||
append("\n${request.headers.sanitized()}") | ||
} | ||
if (logLevel == HttpLoggingVerbosity.BODY) { | ||
request.body?.let { body -> | ||
append("\n${body.toPrintableString()}") | ||
} | ||
} | ||
} | ||
context.logger.info(log) | ||
} | ||
private fun logResponse(response: Response, request: Request, logLevel: HttpLoggingVerbosity) { | ||
val log = buildString { | ||
append("response <-- ${response.code} ${response.message} ${request.url}") | ||
if (logLevel >= HttpLoggingVerbosity.HEADERS) { | ||
append("\n${response.headers.sanitized()}") | ||
} | ||
if (logLevel == HttpLoggingVerbosity.BODY) { | ||
response.body?.let { body -> | ||
append("\n${body.toPrintableString()}") | ||
} | ||
} | ||
} | ||
context.logger.info(log) | ||
} | ||
} | ||
// Extension functions for cleaner code | ||
private fun Headers.sanitized(): String = buildString { | ||
this@sanitized.forEach { (name, value) -> | ||
val displayValue = if (name in SENSITIVE_HEADERS) "<redacted>" else value | ||
append("$name: $displayValue\n") | ||
} | ||
} | ||
private fun RequestBody.toPrintableString(): String { | ||
if (!contentType().isPrintable()) { | ||
return "[Binary body: ${contentLength().formatBytes()}, ${contentType()}]" | ||
} | ||
return try { | ||
val buffer = Buffer() | ||
writeTo(buffer) | ||
buffer.readString(contentType()?.charset() ?: StandardCharsets.UTF_8) | ||
} catch (e: Exception) { | ||
"[Error reading body: ${e.message}]" | ||
} | ||
} | ||
private fun ResponseBody.toPrintableString(): String { | ||
if (!contentType().isPrintable()) { | ||
return "[Binary body: ${contentLength().formatBytes()}, ${contentType()}]" | ||
} | ||
return try { | ||
val source = source() | ||
source.request(Long.MAX_VALUE) | ||
source.buffer.clone().readString(contentType()?.charset() ?: StandardCharsets.UTF_8) | ||
} catch (e: Exception) { | ||
"[Error reading body: ${e.message}]" | ||
} | ||
} | ||
private fun MediaType?.isPrintable(): Boolean = when { | ||
this == null -> false | ||
type == "text" -> true | ||
subtype == "json" || subtype.endsWith("+json") -> true | ||
else -> false | ||
} | ||
private fun Long.formatBytes(): String = when { | ||
this < 0 -> "unknown" | ||
this < 1024 -> "${this}B" | ||
this < 1024 * 1024 -> "${this / 1024}KB" | ||
this < 1024 * 1024 * 1024 -> "${this / (1024 * 1024)}MB" | ||
else -> "${this / (1024 * 1024 * 1024)}GB" | ||
} |
33 changes: 33 additions & 0 deletionssrc/main/kotlin/com/coder/toolbox/settings/ReadOnlyCoderSettings.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.