How vkcom/knet works
Project Type and Purpose
• This is a multi‑module Android networking library (“KNet”) that wraps Google’s Cronet engine, adds a core HTTP client layer, and provides an OkHttp integration adapter. Its goal is to give Android apps easy access to HTTP/3/QUIC, HTTP/2, metrics, interceptors, logging, and fallback points.
File‑Structure Analysis
• Top‑level Gradle files (build.gradle, settings.gradle, dependencies.gradle, etc.) orchestrate a 3‑module Gradle project under the knet directory.
• knet/core – The pure Kotlin HTTP client core (pipeline, request/response abstractions, interceptors, metrics, utilities, exceptions).
• knet/cronet – The Cronet‑backed engine module (JNI libs, Cronet API jars, builders, dispatcher, native pools, CronetConfig, logging).
• knet/okcronet – The OkHttp interceptor adapter module (adapts KNet core to OkHttp’s Interceptor API).
Key README Insights
• Initialization flows: build a CronetKnetEngine, configure QUIC/HTTP2, timeouts, cache, pools, metrics, interceptors → wrap into core Knet → optionally wrap into an OkHttp interceptor.
• Emphasizes extensibility (interceptors, metrics listeners) and upcoming integrations (ExoPlayer, Ktor, Flipper).
Main Components
a. Android Application (host app)
b. KNet Core module – contains KnetEngine, HttpPipeline, interceptors, metrics, exceptions
c. Cronet Engine module – JNI layer, Cronet native libs, CronetKnetEngine, network dispatcher, QUIC/HTTP2 config
d. OkHttp Adapter module – KnetToOkHttpInterceptor
e. External Dependencies – Cronet native libraries, OkHttp, Android framework, ByteArrayPools
Relationships and Data Flow
• App calls → CronetKnetEngine.Build(...) → Cronet Engine config & initialization (native libs, thread pools, cache)
• CronetKnetEngine → passed into Knet.Build(cronetEngine) → instantiates core KnetEngine
• KnetEngine creates an HttpPipeline (chain of interceptors) → user interceptors → final executor
• Executor hands off to Cronet dispatcher (native network I/O) → returns HttpResponse back up the pipeline
• Optionally, wrap the KnetEngine into an OkHttp Interceptor to let OkHttp use it as its transport
• Metric listeners plug into core pipeline, Cronet logging plugs in at the Cronet layer
Architectural Patterns and Principles
• Modularization: separates core HTTP abstraction, Cronet‑specific engine, and OkHttp adapter into independent modules.
• Builder Pattern: heavy use in CronetKnetEngine.Build and Knet.Build to allow fluent configuration.
• Interceptor Chain: core pipeline uses chain‑of‑responsibility to allow request/response modification and retry logic.
• Adapter Pattern: wraps KNet into OkHttp interceptor.
• Native Bridging: JNI libs for Cronet, with thread pools, byte‑buffer pools, locking.