dehora / nakadi-java

🌀 Client library for the Nakadi Event Broker (examples: http://bit.ly/njc-examples, site: https://dehora.github.io/nakadi-java/)
MIT License
30 stars 19 forks source link

Cannot supply my own OkHttp client #345

Open herojan opened 5 years ago

herojan commented 5 years ago

Hi, I wanted to add my own OkHttp client to the OkHttpResourceProvider. This is to allow me to add an interceptor to the client so that I can add tracing. The issue is that the NakadiClient Builder does not allow me to provide a ResourceProvider implementation, and all of the relevant classes are package-private even if it did.

For example, what I thought I could do is (in kotlin):

val okHttp = OkHttpClient.Builder()
    .connectTimeout(20000, TimeUnit.MILLISECONDS)
    .readTimeout(20000, TimeUnit.MILLISECONDS)
    .writeTimeout(10000, TimeUnit.MILLISECONDS)
    .addInterceptor(tracingInterceptor)
    .build()

val resourceProvider = OkHttpResourceProvider(okHttp, GsonSupport(), MetricCollector())
return NakadiClient.newBuilder()
    .baseURI(nakadiBaseUri)
    .resourceProvider(resourceProvider)
    .build()

For Reference, I wanted to add a tracer interceptor such as:

class NakadiTracingInterceptor(private val tracer: Tracer) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val httpMethod = request.method().toUpperCase()
        val flowId: String = request.header(FLOW_ID_HEADER)
        val span = tracer.buildSpan("nakadi_${request.method()}".toLowerCase())
            .withTag(Tags.SPAN_KIND.key, Tags.SPAN_KIND_CLIENT)
            .withTag(Tags.HTTP_URL.key, request.url().toString())
            .withTag(Tags.HTTP_METHOD.key, httpMethod)
            .withTag(FLOW_ID_TRACING_TAG, flowId)
            .start()

        val scope = tracer.scopeManager().activate(span, true)

        try {
            val response = chain.proceed(request)
            Tags.HTTP_STATUS.set(span, response.code())
            return response
        } catch (ex: Exception) {
            span.log(mapOf(Fields.EVENT to Tags.ERROR.key, Fields.ERROR_OBJECT to ex))
            Tags.ERROR.set(span, true)
            throw ex
        } finally {
            scope.close()
        }
    }
}