# Retrofit Networking -- Reference Patterns

Full code for the patterns summarized in `SKILL.md`. Load the section you need
when implementing that part of the networking layer.

## Contents

- [API Interface](#api-interface)
- [Retrofit Setup with Hilt](#retrofit-setup-with-hilt)
- [OkHttp Interceptors](#okhttp-interceptors)
- [Error Handling](#error-handling)
- [Network-Bound Resource](#network-bound-resource)
- [Multipart Uploads](#multipart-uploads)
- [WebSocket Support](#websocket-support)
- [Envelope to Typed Exception](#envelope-to-typed-exception)
- [Unknown-Tolerant Enum Serialization](#unknown-tolerant-enum-serialization)
- [Client Composition and Environment Config](#client-composition-and-environment-config)

## API Interface

Define endpoints as suspend functions. Retrofit handles coroutine integration.

```kotlin
interface OrderApiService {

    @GET("orders")
    suspend fun searchOrders(
        @Query("store") store: String,
        @Query("region") region: String,
        @Query("date") date: String,
    ): List<OrderDto>

    @GET("orders/{id}")
    suspend fun getOrderDetail(
        @Path("id") orderId: String,
    ): OrderDetailDto

    @POST("payments")
    suspend fun createPayment(
        @Body request: PaymentRequest,
    ): PaymentResponse

    @PUT("payments/{id}")
    suspend fun updatePayment(
        @Path("id") paymentId: String,
        @Body request: UpdatePaymentRequest,
    ): PaymentResponse

    @DELETE("payments/{id}")
    suspend fun cancelPayment(
        @Path("id") paymentId: String,
    ): Response<Unit>

    @GET("orders")
    suspend fun searchOrdersWithHeaders(
        @Query("store") store: String,
        @Header("Accept-Language") language: String = "en",
    ): List<OrderDto>
}
```

### DTO Classes

```kotlin
@Serializable
data class OrderDto(
    val id: String,
    val store: LocationDto,
    val region: LocationDto,
    @SerialName("placed_at")
    val placedAt: String,
    @SerialName("delivered_at")
    val deliveredAt: String,
    val price: PriceDto,
    val status: String,
)

@Serializable
data class LocationDto(
    val code: String,
    val name: String,
)

@Serializable
data class PriceDto(
    val amount: Double,
    val currency: String,
)
```

## Retrofit Setup with Hilt

```kotlin
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

    @Provides
    @Singleton
    fun provideJson(): Json = Json {
        ignoreUnknownKeys = true
        coerceInputValues = true
        encodeDefaults = true
    }

    @Provides
    @Singleton
    fun provideOkHttpClient(
        authInterceptor: AuthInterceptor,
        loggingInterceptor: HttpLoggingInterceptor,
    ): OkHttpClient = OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .addInterceptor(authInterceptor)
        .addInterceptor(loggingInterceptor)
        .build()

    @Provides
    @Singleton
    fun provideLoggingInterceptor(): HttpLoggingInterceptor =
        HttpLoggingInterceptor().apply {
            level = if (BuildConfig.DEBUG) {
                HttpLoggingInterceptor.Level.BODY
            } else {
                HttpLoggingInterceptor.Level.NONE
            }
        }

    @Provides
    @Singleton
    fun provideRetrofit(
        client: OkHttpClient,
        json: Json,
    ): Retrofit = Retrofit.Builder()
        .baseUrl(BuildConfig.BASE_URL)
        .client(client)
        .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
        .build()

    @Provides
    @Singleton
    fun provideOrderApiService(retrofit: Retrofit): OrderApiService =
        retrofit.create(OrderApiService::class.java)
}
```

## OkHttp Interceptors

### Auth Interceptor (Token Injection)

```kotlin
class AuthInterceptor @Inject constructor(
    private val tokenProvider: TokenProvider,
) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val token = tokenProvider.getAccessToken()
        val request = chain.request().newBuilder().apply {
            token?.let { addHeader("Authorization", "Bearer $it") }
        }.build()

        val response = chain.proceed(request)

        // Handle 401: refresh token and retry
        if (response.code == 401) {
            response.close()
            val newToken = tokenProvider.refreshToken()
                ?: return response

            val retryRequest = chain.request().newBuilder()
                .header("Authorization", "Bearer $newToken")
                .build()

            return chain.proceed(retryRequest)
        }

        return response
    }
}
```

### Retry Interceptor

```kotlin
class RetryInterceptor(
    private val maxRetries: Int = 3,
    private val initialDelayMs: Long = 1_000,
) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        var lastException: IOException? = null
        var delay = initialDelayMs

        repeat(maxRetries) { attempt ->
            try {
                val response = chain.proceed(chain.request())
                if (response.isSuccessful || response.code !in 500..599) {
                    return response
                }
                response.close()
            } catch (e: IOException) {
                lastException = e
            }

            if (attempt < maxRetries - 1) {
                Thread.sleep(delay)
                delay *= 2 // Exponential backoff
            }
        }

        throw lastException ?: IOException("Request failed after $maxRetries retries")
    }
}
```

### Cache Interceptor

```kotlin
class CacheInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        val cacheControl = CacheControl.Builder()
            .maxAge(5, TimeUnit.MINUTES)
            .build()

        return response.newBuilder()
            .header("Cache-Control", cacheControl.toString())
            .removeHeader("Pragma")
            .build()
    }
}

// Add cache to OkHttpClient
val cacheDir = File(context.cacheDir, "http_cache")
val cache = Cache(cacheDir, 10L * 1024 * 1024) // 10 MB

OkHttpClient.Builder()
    .cache(cache)
    .addNetworkInterceptor(CacheInterceptor())
    .build()
```

## Error Handling

### Sealed Result Type

```kotlin
sealed interface NetworkResult<out T> {
    data class Success<T>(val data: T) : NetworkResult<T>
    data class Error(val code: Int, val message: String) : NetworkResult<Nothing>
    data class Exception(val throwable: Throwable) : NetworkResult<Nothing>
}
```

### Safe API Call Wrapper

```kotlin
suspend fun <T> safeApiCall(
    apiCall: suspend () -> T,
): NetworkResult<T> = try {
    NetworkResult.Success(apiCall())
} catch (e: HttpException) {
    val errorBody = e.response()?.errorBody()?.string()
    NetworkResult.Error(
        code = e.code(),
        message = errorBody ?: e.message(),
    )
} catch (e: IOException) {
    NetworkResult.Exception(e)
} catch (e: CancellationException) {
    throw e // Never swallow cancellation
}
```

### Usage in Repository

```kotlin
class OrderRepositoryImpl @Inject constructor(
    private val api: OrderApiService,
    private val mapper: OrderMapper,
) : OrderRepository {

    override suspend fun searchOrders(
        store: String,
        region: String,
        date: LocalDate,
    ): NetworkResult<List<Order>> = safeApiCall {
        api.searchOrders(store, region, date.toString())
            .map(mapper::toDomain)
    }
}
```

### ViewModel Consumption

```kotlin
@HiltViewModel
class SearchViewModel @Inject constructor(
    private val repository: OrderRepository,
) : ViewModel() {

    private val _uiState = MutableStateFlow<SearchUiState>(SearchUiState.Idle)
    val uiState: StateFlow<SearchUiState> = _uiState.asStateFlow()

    fun search(store: String, region: String, date: LocalDate) {
        viewModelScope.launch {
            _uiState.value = SearchUiState.Loading

            _uiState.value = when (val result = repository.searchOrders(store, region, date)) {
                is NetworkResult.Success -> SearchUiState.Success(result.data)
                is NetworkResult.Error -> SearchUiState.Error("Server error: ${result.message}")
                is NetworkResult.Exception -> SearchUiState.Error(
                    result.throwable.localizedMessage ?: "Network error"
                )
            }
        }
    }
}
```

## Network-Bound Resource

Pattern for showing cached data while fetching fresh data from the network.

```kotlin
inline fun <ResultType, RequestType> networkBoundResource(
    crossinline query: () -> Flow<ResultType>,
    crossinline fetch: suspend () -> RequestType,
    crossinline saveFetchResult: suspend (RequestType) -> Unit,
    crossinline shouldFetch: (ResultType) -> Boolean = { true },
): Flow<Resource<ResultType>> = flow {
    emit(Resource.Loading())

    val data = query().first()

    val flow = if (shouldFetch(data)) {
        emit(Resource.Loading(data))
        try {
            val fetchedData = fetch()
            saveFetchResult(fetchedData)
            query().map { Resource.Success(it) }
        } catch (throwable: Throwable) {
            if (throwable is CancellationException) throw throwable
            query().map { Resource.Error(throwable, it) }
        }
    } else {
        query().map { Resource.Success(it) }
    }

    emitAll(flow)
}

sealed class Resource<T>(
    val data: T? = null,
    val error: Throwable? = null,
) {
    class Success<T>(data: T) : Resource<T>(data)
    class Loading<T>(data: T? = null) : Resource<T>(data)
    class Error<T>(throwable: Throwable, data: T? = null) : Resource<T>(data, throwable)
}
```

### Usage

```kotlin
override fun getOrders(store: String, region: String): Flow<Resource<List<Order>>> =
    networkBoundResource(
        query = {
            dao.getOrders(store, region)
                .map { entities -> entities.map(mapper::toDomain) }
        },
        fetch = { api.searchOrders(store, region, today()) },
        saveFetchResult = { dtos ->
            dao.upsertOrders(dtos.map(mapper::toEntity))
        },
        shouldFetch = { cachedOrders ->
            cachedOrders.isEmpty() || cacheExpired()
        },
    )
```

## Multipart Uploads

```kotlin
interface FileApiService {

    @Multipart
    @POST("documents/upload")
    suspend fun uploadDocument(
        @Part file: MultipartBody.Part,
        @Part("description") description: RequestBody,
    ): UploadResponse
}

// Usage
suspend fun uploadFile(context: Context, uri: Uri, description: String) {
    val contentResolver = context.contentResolver
    val inputStream = contentResolver.openInputStream(uri) ?: return
    val fileName = getFileName(context, uri)

    val requestBody = inputStream.readBytes()
        .toRequestBody("application/octet-stream".toMediaType())

    val part = MultipartBody.Part.createFormData("file", fileName, requestBody)
    val descriptionBody = description.toRequestBody("text/plain".toMediaType())

    api.uploadDocument(part, descriptionBody)
}
```

## WebSocket Support

```kotlin
class OrderUpdatesWebSocket @Inject constructor(
    private val client: OkHttpClient,
) {
    private var webSocket: WebSocket? = null

    fun connect(orderId: String): Flow<OrderUpdate> = callbackFlow {
        val request = Request.Builder()
            .url("wss://api.example.com/orders/$orderId/updates")
            .build()

        val listener = object : WebSocketListener() {
            override fun onMessage(webSocket: WebSocket, text: String) {
                val update = Json.decodeFromString<OrderUpdate>(text)
                trySend(update)
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                close(t)
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                channel.close()
            }
        }

        webSocket = client.newWebSocket(request, listener)

        awaitClose {
            webSocket?.close(1000, "Client closed")
        }
    }

    fun disconnect() {
        webSocket?.close(1000, "Client closed")
        webSocket = null
    }
}
```

## Envelope to Typed Exception

The backend wraps every payload in a `success` envelope. A delegating
`Converter.Factory` unwraps it and turns a business failure into a typed
`ApiException`, so `success == false` surfaces through the same catch path as a
transport failure instead of forcing every call site to inspect the body.

```kotlin
@Serializable
data class ApiEnvelope<T>(
    val success: Boolean,
    val data: T? = null,
    @SerialName("error_code") val errorCode: Int? = null,
    val message: String? = null,
)

class ApiException(
    val code: Int,
    override val message: String,
) : IOException(message)

private fun parameterized(raw: Type, arg: Type): ParameterizedType =
    object : ParameterizedType {
        override fun getRawType(): Type = raw
        override fun getActualTypeArguments(): Array<Type> = arrayOf(arg)
        override fun getOwnerType(): Type? = null
    }

class EnvelopeUnwrapFactory(
    private val delegate: Converter.Factory,
) : Converter.Factory() {
    override fun responseBodyConverter(
        type: Type,
        annotations: Array<out Annotation>,
        retrofit: Retrofit,
    ): Converter<ResponseBody, *>? {
        val envelopeType = parameterized(ApiEnvelope::class.java, type)
        val inner = delegate.responseBodyConverter(envelopeType, annotations, retrofit)
            ?: return null
        return Converter<ResponseBody, Any?> { body ->
            val envelope = inner.convert(body) as ApiEnvelope<*>
            if (!envelope.success) {
                throw ApiException(envelope.errorCode ?: -1, envelope.message.orEmpty())
            }
            envelope.data
        }
    }
}
```

Register it in front of the serialization converter:

```kotlin
Retrofit.Builder()
    .baseUrl(config.baseUrl)
    .client(client)
    .addConverterFactory(EnvelopeUnwrapFactory(json.asConverterFactory(contentType)))
    .build()
```

Central throwable-to-sealed mapper, called from `safeApiCall`:

```kotlin
fun Throwable.toNetworkError(): NetworkResult.Error = when (this) {
    is ApiException -> NetworkResult.Error(code, message)
    is HttpException -> NetworkResult.Error(code(), message())
    is SocketTimeoutException -> NetworkResult.Error(-1, "Request timed out")
    is IOException -> NetworkResult.Error(-1, "No network connection")
    else -> NetworkResult.Error(-1, message ?: "Unexpected error")
}

suspend fun <T> safeApiCall(block: suspend () -> T): NetworkResult<T> =
    try {
        NetworkResult.Success(block())
    } catch (e: CancellationException) {
        throw e
    } catch (e: Throwable) {
        e.toNetworkError()
    }
```

## Unknown-Tolerant Enum Serialization

`ignoreUnknownKeys` tolerates unknown object keys, not unknown enum values: a new
server code fails the whole response. A base `KSerializer` maps any unrecognized
value to a declared default so a single field degrades instead of the payload.

```kotlin
interface DefaultedEnum {
    val serialName: String
}

abstract class UnknownTolerantEnumSerializer<T>(
    serialName: String,
    private val values: Array<T>,
    private val default: T,
) : KSerializer<T> where T : Enum<T>, T : DefaultedEnum {
    override val descriptor: SerialDescriptor =
        PrimitiveSerialDescriptor(serialName, PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: T) = encoder.encodeString(value.serialName)

    override fun deserialize(decoder: Decoder): T {
        val raw = decoder.decodeString()
        return values.firstOrNull { it.serialName == raw } ?: default
    }
}
```

Usage:

```kotlin
@Serializable(with = ShippingClassSerializer::class)
enum class ShippingClass(override val serialName: String) : DefaultedEnum {
    STANDARD("STANDARD"),
    EXPRESS("EXPRESS"),
    UNKNOWN("UNKNOWN"),
}

object ShippingClassSerializer : UnknownTolerantEnumSerializer<ShippingClass>(
    "ShippingClass", ShippingClass.entries.toTypedArray(), ShippingClass.UNKNOWN,
)
```

## Client Composition and Environment Config

Derive every specialized client from one base with `newBuilder()`. An image
pipeline must not send auth headers, so it clears inherited interceptors:

```kotlin
@Provides
@Singleton
@ImageClient
fun provideImageClient(
    @BaseClient base: OkHttpClient,
    cache: Cache,
): OkHttpClient = base.newBuilder()
    .apply { interceptors().clear() }
    .cache(cache)
    .build()
```

Resolve the base URL and pin hashes per flavor from build config, with a runtime
override allowed only outside production (QA environment switching):

```kotlin
class NetworkConfig(
    private val settings: EnvironmentSettings,
) {
    val baseUrl: String
        get() = if (BuildConfig.IS_PRODUCTION) {
            BuildConfig.BASE_URL
        } else {
            settings.overrideBaseUrl ?: BuildConfig.BASE_URL
        }

    fun certificatePinner(): CertificatePinner {
        val host = baseUrl.toHttpUrl().host
        return CertificatePinner.Builder()
            .apply { BuildConfig.PIN_HASHES.forEach { add(host, it) } }
            .build()
    }
}
```

`BASE_URL` and `PIN_HASHES` are `buildConfigField`s per product flavor;
`IS_PRODUCTION` gates the override so QA builds can retarget without a rebuild.

Deadlock-safe suspend-in-interceptor bridge. Plain `runBlocking { }` resumes on
the interceptor's own thread and can deadlock when the token fetch reuses the
same dispatcher. Pin the suspend work to a dedicated single-thread dispatcher:

```kotlin
class TokenInterceptor @Inject constructor(
    private val tokenProvider: TokenProvider,
) : Interceptor {
    private val tokenDispatcher = Dispatchers.IO.limitedParallelism(1)

    override fun intercept(chain: Interceptor.Chain): Response {
        val token = runBlocking(tokenDispatcher) { tokenProvider.currentToken() }
        val request = chain.request().newBuilder()
            .header("Authorization", "Bearer $token")
            .build()
        return chain.proceed(request)
    }
}
```
