From b292872303718a9b0e2c90fb7c86ad8a230149ad Mon Sep 17 00:00:00 2001 From: wenja0618 Date: Sun, 22 Nov 2026 22:13:40 -0500 Subject: [PATCH] Add Retrofit client, auth, users and houses Split out of #6 (retrofit networking layer). Co-Authored-By: Claude Opus 5.5 --- .../com/example/roomie/data/AuthRepository.kt | 59 ++++++ .../example/roomie/data/HouseRepository.kt | 66 ++++++ .../com/example/roomie/data/api/ApiModels.kt | 76 +++++++ .../roomie/data/api/HouseApiService.kt | 74 +++++++ .../example/roomie/data/api/NetworkModule.kt | 14 ++ .../roomie/data/api/RetrofitInstance.kt | 97 +++++++++ .../roomie/data/api/RoomieApiResponse.kt | 189 ++++++++++++++++++ .../com/example/roomie/data/api/RoomieGson.kt | 38 ++++ .../example/roomie/data/api/TokenProvider.kt | 39 ++++ .../example/roomie/data/api/UserApiService.kt | 49 +++++ .../roomie/data/api/ResponseFlowTest.kt | 51 +++++ .../example/roomie/data/api/RoomieApiTest.kt | 117 +++++++++++ 12 files changed, 869 insertions(+) create mode 100644 app/src/main/java/com/example/roomie/data/AuthRepository.kt create mode 100644 app/src/main/java/com/example/roomie/data/HouseRepository.kt create mode 100644 app/src/main/java/com/example/roomie/data/api/ApiModels.kt create mode 100644 app/src/main/java/com/example/roomie/data/api/HouseApiService.kt create mode 100644 app/src/main/java/com/example/roomie/data/api/NetworkModule.kt create mode 100644 app/src/main/java/com/example/roomie/data/api/RetrofitInstance.kt create mode 100644 app/src/main/java/com/example/roomie/data/api/RoomieApiResponse.kt create mode 100644 app/src/main/java/com/example/roomie/data/api/RoomieGson.kt create mode 100644 app/src/main/java/com/example/roomie/data/api/TokenProvider.kt create mode 100644 app/src/main/java/com/example/roomie/data/api/UserApiService.kt create mode 100644 app/src/test/java/com/example/roomie/data/api/ResponseFlowTest.kt create mode 100644 app/src/test/java/com/example/roomie/data/api/RoomieApiTest.kt diff --git a/app/src/main/java/com/example/roomie/data/AuthRepository.kt b/app/src/main/java/com/example/roomie/data/AuthRepository.kt new file mode 100644 index 0000000..4f9bc00 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/AuthRepository.kt @@ -0,0 +1,59 @@ +package com.example.roomie.data + +import com.example.roomie.data.api.DevTokenProvider +import com.example.roomie.data.api.LoginResponse +import com.example.roomie.data.api.MeResponse +import com.example.roomie.data.api.Presence +import com.example.roomie.data.api.RetrofitInstance +import com.example.roomie.data.api.RoomieApiResponse +import com.example.roomie.data.api.UpdateMeBody +import com.example.roomie.data.api.apiCall +import com.example.roomie.data.api.ResponseFlow +import com.example.roomie.data.api.repositoryScope +import kotlinx.coroutines.flow.StateFlow +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class AuthRepository @Inject constructor( + private val retrofitInstance: RetrofitInstance, + private val devTokenProvider: DevTokenProvider, +) { + private val scope = repositoryScope() + + private val _me = ResponseFlow(scope) + + /** You, your house, and invites you've received. */ + val me: StateFlow> = _me.state + + /** Signs in to the local backend or mock server as [netId], with no Firebase involved. */ + suspend fun devLogin(netId: String): RoomieApiResponse { + devTokenProvider.netId = netId.trim().lowercase() + return login() + } + + /** Call right after sign-in, once the [com.example.roomie.data.api.TokenProvider] has a token. */ + suspend fun login(): RoomieApiResponse = apiCall { retrofitInstance.userApi.login() } + + /** Pipelines the response into [me]. */ + fun fetchMe(refresh: Boolean = false) { + _me.fetch(refresh) { retrofitInstance.userApi.getMe() } + } + + /** Updates [me] too, unless you signed in as someone else while the request was out. */ + suspend fun updateMe( + name: String? = null, + major: String? = null, + presence: Presence? = null, + ): RoomieApiResponse { + val session = devTokenProvider.session + return apiCall { retrofitInstance.userApi.updateMe(UpdateMeBody(name, major, presence)) }.also { result -> + result.ifSuccess { if (devTokenProvider.session == session) _me.set(RoomieApiResponse.Success(it)) } + } + } + + fun signOut() { + devTokenProvider.netId = null + _me.set(RoomieApiResponse.Pending) + } +} diff --git a/app/src/main/java/com/example/roomie/data/HouseRepository.kt b/app/src/main/java/com/example/roomie/data/HouseRepository.kt new file mode 100644 index 0000000..403ab53 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/HouseRepository.kt @@ -0,0 +1,66 @@ +package com.example.roomie.data + +import com.example.roomie.data.api.CreateHouseBody +import com.example.roomie.data.api.HouseDto +import com.example.roomie.data.api.InviteBody +import com.example.roomie.data.api.JoinHouseBody +import com.example.roomie.data.api.RetrofitInstance +import com.example.roomie.data.api.RoomieApiResponse +import com.example.roomie.data.api.UpdateHouseBody +import com.example.roomie.data.api.apiCall +import com.example.roomie.data.api.ResponseFlow +import com.example.roomie.data.api.repositoryScope +import kotlinx.coroutines.flow.StateFlow +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class HouseRepository @Inject constructor(private val retrofitInstance: RetrofitInstance) { + + private val scope = repositoryScope() + private val api get() = retrofitInstance.houseApi + + private val _house = ResponseFlow(scope) + + /** Your house. Every call below that returns the house updates this too. */ + val house: StateFlow> = _house.state + + /** Pipelines the response into [house]. */ + fun fetchHouse(houseId: Int, refresh: Boolean = false) { + _house.fetch(refresh) { api.getHouse(houseId).house } + } + + suspend fun createHouse(body: CreateHouseBody): RoomieApiResponse = + updatingHouse { api.createHouse(body).house } + + suspend fun updateHouse(houseId: Int, body: UpdateHouseBody): RoomieApiResponse = + updatingHouse { api.updateHouse(houseId, body).house } + + suspend fun invite(houseId: Int, netIds: List): RoomieApiResponse = + updatingHouse { api.invite(houseId, InviteBody(netIds)).house } + + suspend fun cancelInvite(houseId: Int, inviteId: Int): RoomieApiResponse = + apiCall { api.cancelInvite(houseId, inviteId) }.also { it.ifSuccess { fetchHouse(houseId, refresh = true) } } + + suspend fun regenerateInviteCode(houseId: Int): RoomieApiResponse = + updatingHouse { api.regenerateInviteCode(houseId).house } + + suspend fun joinHouse(inviteCode: String): RoomieApiResponse = + updatingHouse { api.joinHouse(JoinHouseBody(inviteCode.trim())).house } + + suspend fun acceptInvite(inviteId: Int): RoomieApiResponse = + updatingHouse { api.acceptInvite(inviteId).house } + + suspend fun declineInvite(inviteId: Int): RoomieApiResponse = + apiCall { api.declineInvite(inviteId) } + + /** Clears [house]. Any [fetchHouse] still in flight is cancelled so it can't bring the house back. */ + suspend fun leaveHouse(houseId: Int): RoomieApiResponse = + apiCall { api.leaveHouse(houseId) }.also { it.ifSuccess { _house.set(RoomieApiResponse.Pending) } } + + suspend fun removeMember(houseId: Int, userId: Int): RoomieApiResponse = + apiCall { api.removeMember(houseId, userId) }.also { it.ifSuccess { fetchHouse(houseId, refresh = true) } } + + private suspend fun updatingHouse(call: suspend () -> HouseDto): RoomieApiResponse = + apiCall(call).also { result -> result.ifSuccess { _house.set(RoomieApiResponse.Success(it)) } } +} diff --git a/app/src/main/java/com/example/roomie/data/api/ApiModels.kt b/app/src/main/java/com/example/roomie/data/api/ApiModels.kt new file mode 100644 index 0000000..9de826d --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/ApiModels.kt @@ -0,0 +1,76 @@ +package com.example.roomie.data.api + +import java.time.Instant +import java.time.LocalDate + +// Objects the backend returns, shared across services. Money is whole cents and IDs are ints. +// These mirror the API exactly; map them to the app's models in data/Models.kt at the repository +// or ViewModel layer. + +enum class MemberRole { OWNER, MEMBER } + +/** The "I'm home / away" toggle. */ +enum class Presence { HOME, AWAY } + +/** The public view of a person: members, rotation, assignee, claimedBy, … */ +data class UserDto( + val id: Int, + /** Lowercase, e.g. `mnh49`. */ + val netid: String, + val name: String, + val avatarUrl: String?, + val presence: Presence, +) + +/** Your own user, from `/auth/login` and `/users/me`. */ +data class SelfDto( + val id: Int, + val netid: String, + val name: String, + val avatarUrl: String?, + val presence: Presence, + val email: String, + val major: String?, + val createdAt: Instant, +) + +/** A [UserDto] plus what only makes sense inside a house. */ +data class MemberDto( + val id: Int, + val netid: String, + val name: String, + val avatarUrl: String?, + val presence: Presence, + val role: MemberRole, + /** If the owner leaves, the member who joined earliest becomes owner. */ + val joinedAt: Instant, +) + +data class HouseDto( + val id: Int, + val name: String, + /** e.g. `LOFT-4827`. Not case-sensitive. */ + val inviteCode: String, + val unit: String?, + val leaseEndsOn: LocalDate?, + /** IANA name. Decides what "today" means for chores. */ + val timezone: String, + val members: List, + val pendingInvites: List, +) + +/** An invite the house sent that hasn't been answered. */ +data class PendingInviteDto(val id: Int, val netid: String, val createdAt: Instant) + +/** The short house in `GET /users/me`. [role] is yours. */ +data class HouseSummaryDto(val id: Int, val name: String, val role: MemberRole) + +/** An invite you received. Has enough for the "Join this house?" prompt. */ +data class InviteDto( + val id: Int, + val createdAt: Instant, + val house: InviteHouseDto, + val invitedBy: UserDto, +) + +data class InviteHouseDto(val id: Int, val name: String, val members: List) diff --git a/app/src/main/java/com/example/roomie/data/api/HouseApiService.kt b/app/src/main/java/com/example/roomie/data/api/HouseApiService.kt new file mode 100644 index 0000000..bd8d399 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/HouseApiService.kt @@ -0,0 +1,74 @@ +package com.example.roomie.data.api + +import retrofit2.http.Body +import retrofit2.http.DELETE +import retrofit2.http.GET +import retrofit2.http.PATCH +import retrofit2.http.POST +import retrofit2.http.Path +import java.time.LocalDate + +interface HouseApiService { + + /** Creates a house with you as owner and invites [CreateHouseBody.inviteNetids]. */ + @POST("houses") + suspend fun createHouse(@Body body: CreateHouseBody): HouseResponse + + @GET("houses/{houseId}") + suspend fun getHouse(@Path("houseId") houseId: Int): HouseResponse + + /** Any member can edit house settings. */ + @PATCH("houses/{houseId}") + suspend fun updateHouse(@Path("houseId") houseId: Int, @Body body: UpdateHouseBody): HouseResponse + + /** Skips people already in the house. */ + @POST("houses/{houseId}/invites") + suspend fun invite(@Path("houseId") houseId: Int, @Body body: InviteBody): HouseResponse + + @DELETE("houses/{houseId}/invites/{inviteId}") + suspend fun cancelInvite(@Path("houseId") houseId: Int, @Path("inviteId") inviteId: Int) + + /** Owner only. The old code stops working. */ + @POST("houses/{houseId}/invite-code") + suspend fun regenerateInviteCode(@Path("houseId") houseId: Int): HouseResponse + + @POST("houses/join") + suspend fun joinHouse(@Body body: JoinHouseBody): HouseResponse + + @POST("invites/{inviteId}/accept") + suspend fun acceptInvite(@Path("inviteId") inviteId: Int): HouseResponse + + @POST("invites/{inviteId}/decline") + suspend fun declineInvite(@Path("inviteId") inviteId: Int) + + /** Also removes you from rotations, releases your shopping claims and passes on ownership. */ + @DELETE("houses/{houseId}/members/me") + suspend fun leaveHouse(@Path("houseId") houseId: Int) + + /** Owner only, with the same cleanup as leaving. */ + @DELETE("houses/{houseId}/members/{userId}") + suspend fun removeMember(@Path("houseId") houseId: Int, @Path("userId") userId: Int) +} + +data class HouseResponse(val house: HouseDto) + +data class CreateHouseBody( + val name: String, + val unit: String? = null, + val leaseEndsOn: LocalDate? = null, + /** IANA name. The server defaults to America/New_York. */ + val timezone: String? = null, + val inviteNetids: List? = null, +) + +data class UpdateHouseBody( + val name: String? = null, + val unit: String? = null, + val leaseEndsOn: LocalDate? = null, + val timezone: String? = null, +) + +data class InviteBody(val netids: List) + +/** Not case-sensitive. */ +data class JoinHouseBody(val inviteCode: String) diff --git a/app/src/main/java/com/example/roomie/data/api/NetworkModule.kt b/app/src/main/java/com/example/roomie/data/api/NetworkModule.kt new file mode 100644 index 0000000..cdd507b --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/NetworkModule.kt @@ -0,0 +1,14 @@ +package com.example.roomie.data.api + +import dagger.Binds +import dagger.Module +import dagger.hilt.InstallIn +import dagger.hilt.components.SingletonComponent + +@Module +@InstallIn(SingletonComponent::class) +abstract class NetworkModule { + + @Binds + abstract fun bindTokenProvider(provider: DevTokenProvider): TokenProvider +} diff --git a/app/src/main/java/com/example/roomie/data/api/RetrofitInstance.kt b/app/src/main/java/com/example/roomie/data/api/RetrofitInstance.kt new file mode 100644 index 0000000..01a8503 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/RetrofitInstance.kt @@ -0,0 +1,97 @@ +package com.example.roomie.data.api + +import com.example.roomie.BuildConfig +import kotlinx.coroutines.runBlocking +import okhttp3.Authenticator +import okhttp3.HttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import okhttp3.Response +import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Retrofit +import retrofit2.converter.gson.GsonConverterFactory +import javax.inject.Inject +import javax.inject.Singleton + +/** + * The Retrofit client every Roomie API service shares. It adds `Authorization: Bearer ` + * to each request and, on a 401, asks [TokenProvider] for a fresh token and retries once, as long as + * the request went to the API's own origin and the user hasn't switched accounts in the meantime. + */ +@Singleton +class RetrofitInstance internal constructor(retrofit: Retrofit) { + + @Inject + constructor(tokenProvider: TokenProvider) : + this(roomieRetrofit(BuildConfig.API_URL, tokenProvider, logBodies = BuildConfig.DEBUG)) + + val userApi: UserApiService by lazy { retrofit.create(UserApiService::class.java) } + val houseApi: HouseApiService by lazy { retrofit.create(HouseApiService::class.java) } +} + +/** Builds the client. Separate from [RetrofitInstance] so tests can point it at a fake server. */ +internal fun roomieRetrofit( + baseUrl: String, + tokenProvider: TokenProvider, + logBodies: Boolean, +): Retrofit { + val apiOrigin = baseUrl.toHttpUrl() + + val authInterceptor = Interceptor { chain -> + val request = chain.request() + // Read the session before the token: if they disagree, the retry is refused (the safe side). + val session = AuthSession(tokenProvider.session) + val token = runBlocking { tokenProvider.token(forceRefresh = false) } + val tagged = request.newBuilder().tag(AuthSession::class.java, session) + if (token != null && request.header("Authorization") == null) { + tagged.header("Authorization", "Bearer $token") + } + chain.proceed(tagged.build()) + } + + val authenticator = Authenticator { _, response -> + val request = response.request + // Never send the token anywhere but the API itself, e.g. after a cross-origin redirect. + if (!request.url.hasSameOrigin(apiOrigin)) return@Authenticator null + // Retry once. Count only earlier 401s: redirects and retries also show up in priorResponse. + if (response.prior401Count() > 0) return@Authenticator null + // The request belongs to the session it started in. If the user switched accounts since, + // replaying it with the new account's token would act as the wrong user. + val startedIn = request.tag(AuthSession::class.java) ?: return@Authenticator null + if (startedIn.id != tokenProvider.session) return@Authenticator null + val token = runBlocking { tokenProvider.token(forceRefresh = true) } + ?: return@Authenticator null + if (startedIn.id != tokenProvider.session) return@Authenticator null + request.newBuilder().header("Authorization", "Bearer $token").build() + } + + val client = OkHttpClient.Builder() + .addInterceptor(authInterceptor) + .apply { + if (logBodies) { + addInterceptor(HttpLoggingInterceptor().apply { + level = HttpLoggingInterceptor.Level.BODY + redactHeader("Authorization") + }) + } + } + .authenticator(authenticator) + .build() + + return Retrofit.Builder() + .baseUrl(baseUrl) + .client(client) + .addConverterFactory(GsonConverterFactory.create(RoomieGson.gson)) + .build() +} + +/** Which [TokenProvider.session] a request was started in. Attached as an OkHttp request tag. */ +private class AuthSession(val id: Long) + +private fun HttpUrl.hasSameOrigin(other: HttpUrl) = + scheme == other.scheme && host == other.host && port == other.port + +/** How many 401s came before this response in the same call (not counting this one). */ +private fun Response.prior401Count(): Int = + generateSequence(priorResponse) { it.priorResponse }.count { it.code == 401 } diff --git a/app/src/main/java/com/example/roomie/data/api/RoomieApiResponse.kt b/app/src/main/java/com/example/roomie/data/api/RoomieApiResponse.kt new file mode 100644 index 0000000..8829afc --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/RoomieApiResponse.kt @@ -0,0 +1,189 @@ +package com.example.roomie.data.api + +import androidx.compose.runtime.Composable +import com.google.gson.JsonElement +import com.google.gson.JsonParseException +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import retrofit2.HttpException +import java.io.IOException +import java.time.format.DateTimeParseException + +/** + * The state of an API call returning [T]: still loading ([Pending]), done ([Success]), or failed + * ([Error]). Endpoints that return 204 give `Success(Unit)`. + */ +sealed class RoomieApiResponse { + data object Pending : RoomieApiResponse() + data class Success(val data: T) : RoomieApiResponse() + data class Error(val error: ApiError) : RoomieApiResponse() + + fun map(transform: (T) -> R): RoomieApiResponse = when (this) { + Pending -> Pending + is Success -> Success(transform(data)) + is Error -> this + } + + /** Both responses' data as a pair. [Error] wins over [Pending]. */ + fun combine(other: RoomieApiResponse): RoomieApiResponse> = when { + this is Error -> this + other is Error -> other + this is Success && other is Success -> Success(data to other.data) + else -> Pending + } + + fun dataOrNull(): T? = (this as? Success)?.data + + fun asSuccessOrNull(): Success? = this as? Success + + /** Basically a force `!!`, but for [Success] responses. */ + fun asSuccess(): Success = + this as? Success ?: throw IllegalStateException("Response is not a success: $this") + + /** Runs [block] if the response is a [Success]. */ + fun ifSuccess(block: (T) -> Unit) { + if (this is Success) block(data) + } + + @Composable + fun ComposableIfSuccess(block: @Composable (T) -> Unit) { + if (this is Success) block(data) + } +} + +/** A response with its data dropped, for screens that only show loading, done, or failed. */ +sealed class RoomieApiState { + data object Success : RoomieApiState() + data object Error : RoomieApiState() + data object Loading : RoomieApiState() +} + +fun RoomieApiResponse<*>.toRoomieApiState(): RoomieApiState = when (this) { + is RoomieApiResponse.Success -> RoomieApiState.Success + is RoomieApiResponse.Error -> RoomieApiState.Error + RoomieApiResponse.Pending -> RoomieApiState.Loading +} + +data class ApiError( + val code: ApiErrorCode, + /** The HTTP status, or null when the request never got a response. */ + val statusCode: Int?, + val message: String, + /** For [ApiErrorCode.VALIDATION_ERROR]: each bad field (e.g. `body.name`) and what's wrong with it. */ + val fieldErrors: Map = emptyMap(), +) + +/** The backend's `errorCode`s, plus [NETWORK] and [UNKNOWN] for failures it didn't describe. */ +enum class ApiErrorCode { + VALIDATION_ERROR, BAD_REQUEST, UNAUTHORIZED, FORBIDDEN, NOT_FOUND, CONFLICT, TOO_MANY_REQUESTS, + NETWORK, UNKNOWN, +} + +/** Runs one API call and turns any failure into a [RoomieApiResponse.Error] instead of throwing. */ +suspend fun apiCall(call: suspend () -> T): RoomieApiResponse = try { + RoomieApiResponse.Success(call()) +} catch (e: CancellationException) { + throw e +} catch (e: HttpException) { + RoomieApiResponse.Error(e.toApiError()) +} catch (e: IOException) { + RoomieApiResponse.Error(ApiError(ApiErrorCode.NETWORK, null, "Couldn't reach the server.")) +} catch (e: JsonParseException) { + RoomieApiResponse.Error(ApiError(ApiErrorCode.UNKNOWN, null, "Unexpected response: ${e.message}")) +} catch (e: DateTimeParseException) { + RoomieApiResponse.Error(ApiError(ApiErrorCode.UNKNOWN, null, "Unexpected date: ${e.message}")) +} + +/** The scope a repository runs its fetches in. Lives as long as the (singleton) repository. */ +internal fun repositoryScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + +/** + * A [RoomieApiResponse] that a repository fetches into and patches, exposed as [state]. + * + * Only the latest fetch may publish: starting a fetch, or replacing the value with [set], cancels + * the fetch in flight and discards its result even if it already finished. Every write goes + * through one lock, so concurrent [update]s can't overwrite each other. + */ +internal class ResponseFlow(private val scope: CoroutineScope) { + private val lock = Any() + private val flow = MutableStateFlow>(RoomieApiResponse.Pending) + + /** Bumped by every [fetch] and [set]; a fetch publishes only if it's still the latest. */ + private var generation = 0L + private var inFlight: Job? = null + + val state: StateFlow> = flow.asStateFlow() + + /** + * Starts [call] and pipelines the result into [state], like Resell's `fetchX()`s. Shows + * [RoomieApiResponse.Pending] first unless [refresh] is true; a failed refresh keeps the data + * already shown instead of replacing it with an error. Returns the fetch's [Job]. + */ + fun fetch(refresh: Boolean = false, call: suspend () -> T): Job = synchronized(lock) { + val mine = invalidate() + if (!refresh) flow.value = RoomieApiResponse.Pending + scope.launch { + val result = apiCall(call) + synchronized(lock) { + if (mine != generation) return@synchronized + val keepShownData = refresh && result is RoomieApiResponse.Error && + flow.value is RoomieApiResponse.Success + if (!keepShownData) flow.value = result + inFlight = null + } + }.also { inFlight = it } + } + + /** Replaces the value outright. Any fetch in flight is cancelled and can't overwrite it. */ + fun set(value: RoomieApiResponse) = synchronized(lock) { + invalidate() + flow.value = value + } + + /** + * Patches the value in place, atomically with respect to other writes. Unlike [set], this + * leaves a fetch in flight alone: that fetch is what the caller last asked to see. + */ + fun update(transform: (RoomieApiResponse) -> RoomieApiResponse) = synchronized(lock) { + flow.value = transform(flow.value) + } + + /** Must hold [lock]. */ + private fun invalidate(): Long { + inFlight?.cancel() + inFlight = null + return ++generation + } +} + +/** `{ status, statusCode, message, errorCode, data }`, the body of every error response. */ +private class ErrorBody(val message: String?, val errorCode: String?, val data: JsonElement?) + +private fun HttpException.toApiError(): ApiError { + val body = try { + response()?.errorBody()?.string()?.let { RoomieGson.gson.fromJson(it, ErrorBody::class.java) } + } catch (e: Exception) { + null + } + val code = ApiErrorCode.entries.firstOrNull { it.name == body?.errorCode } ?: when (code()) { + 400 -> ApiErrorCode.BAD_REQUEST + 401 -> ApiErrorCode.UNAUTHORIZED + 403 -> ApiErrorCode.FORBIDDEN + 404 -> ApiErrorCode.NOT_FOUND + 409 -> ApiErrorCode.CONFLICT + 429 -> ApiErrorCode.TOO_MANY_REQUESTS + else -> ApiErrorCode.UNKNOWN + } + val fieldErrors = body?.data?.takeIf { it.isJsonObject }?.asJsonObject?.entrySet() + ?.filter { it.value.isJsonPrimitive } + ?.associate { it.key to it.value.asString } + .orEmpty() + return ApiError(code, code(), body?.message ?: message(), fieldErrors) +} diff --git a/app/src/main/java/com/example/roomie/data/api/RoomieGson.kt b/app/src/main/java/com/example/roomie/data/api/RoomieGson.kt new file mode 100644 index 0000000..a790153 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/RoomieGson.kt @@ -0,0 +1,38 @@ +package com.example.roomie.data.api + +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import com.google.gson.TypeAdapter +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonWriter +import java.time.Instant +import java.time.LocalDate +import java.time.OffsetDateTime + +/** + * The API sends dates as `YYYY-MM-DD` ([LocalDate]) and timestamps as ISO 8601 ([Instant]). + * Nulls are left out of request bodies, so an unset PATCH field isn't changed. + */ +object RoomieGson { + val gson: Gson = GsonBuilder() + .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter.nullSafe()) + .registerTypeAdapter(Instant::class.java, InstantAdapter.nullSafe()) + .create() +} + +private object LocalDateAdapter : TypeAdapter() { + override fun write(out: JsonWriter, value: LocalDate) { + out.value(value.toString()) + } + + override fun read(reader: JsonReader): LocalDate = LocalDate.parse(reader.nextString()) +} + +private object InstantAdapter : TypeAdapter() { + override fun write(out: JsonWriter, value: Instant) { + out.value(value.toString()) + } + + // OffsetDateTime accepts both `Z` and `+00:00` offsets. + override fun read(reader: JsonReader): Instant = OffsetDateTime.parse(reader.nextString()).toInstant() +} diff --git a/app/src/main/java/com/example/roomie/data/api/TokenProvider.kt b/app/src/main/java/com/example/roomie/data/api/TokenProvider.kt new file mode 100644 index 0000000..3f2f7a0 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/TokenProvider.kt @@ -0,0 +1,39 @@ +package com.example.roomie.data.api + +import java.util.concurrent.atomic.AtomicLong +import javax.inject.Inject +import javax.inject.Singleton + +/** Where [RetrofitInstance] gets the token it sends as `Authorization: Bearer `. */ +fun interface TokenProvider { + /** Returns the token, or null when signed out. [forceRefresh] is true after a 401. */ + suspend fun token(forceRefresh: Boolean): String? + + /** + * Changes whenever the signed-in account changes. [RetrofitInstance] won't retry a request + * after a 401 if the session changed since the request started. Providers with only one + * account can leave this at 0. + */ + val session: Long get() = 0L +} + +/** + * Signs in as [netId] with the `dev:` tokens that the local backend and the mock server + * accept. The deployed server rejects them, so it needs a Firebase ID token instead. + * [NetworkModule] binds this as the app's [TokenProvider]; swap the binding once Google sign-in exists. + */ +@Singleton +class DevTokenProvider @Inject constructor() : TokenProvider { + private val generation = AtomicLong() + + @Volatile + var netId: String? = null + set(value) { + field = value + generation.incrementAndGet() + } + + override val session: Long get() = generation.get() + + override suspend fun token(forceRefresh: Boolean): String? = netId?.let { "dev:$it" } +} diff --git a/app/src/main/java/com/example/roomie/data/api/UserApiService.kt b/app/src/main/java/com/example/roomie/data/api/UserApiService.kt new file mode 100644 index 0000000..1225834 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/UserApiService.kt @@ -0,0 +1,49 @@ +package com.example.roomie.data.api + +import retrofit2.http.Body +import retrofit2.http.GET +import retrofit2.http.PATCH +import retrofit2.http.POST + +interface UserApiService { + + /** Signs in, creating the account the first time. Call it right after Google sign-in. */ + @POST("auth/login") + suspend fun login(): LoginResponse + + /** The user, their house and pending invites. Use it on app launch. */ + @GET("users/me") + suspend fun getMe(): MeResponse + + @PATCH("users/me") + suspend fun updateMe(@Body body: UpdateMeBody): MeResponse + + /** Checks the server and its database are up. Needs no token. */ + @GET("health") + suspend fun health(): HealthResponse +} + +/** + * Open Home if there's a [house], a "Join this house?" prompt if there are [pendingInvites], + * otherwise onboarding. + */ +data class LoginResponse( + val isNewUser: Boolean, + val user: SelfDto, + val house: HouseDto?, + val pendingInvites: List, +) + +data class MeResponse( + val user: SelfDto, + val house: HouseSummaryDto?, + val pendingInvites: List, +) + +data class UpdateMeBody( + val name: String? = null, + val major: String? = null, + val presence: Presence? = null, +) + +data class HealthResponse(val status: String, val database: String) diff --git a/app/src/test/java/com/example/roomie/data/api/ResponseFlowTest.kt b/app/src/test/java/com/example/roomie/data/api/ResponseFlowTest.kt new file mode 100644 index 0000000..77dc7fa --- /dev/null +++ b/app/src/test/java/com/example/roomie/data/api/ResponseFlowTest.kt @@ -0,0 +1,51 @@ +package com.example.roomie.data.api + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Test + +class ResponseFlowTest { + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + @Test + fun olderFetchCannotOverwriteNewerOne() = runBlocking { + val flow = ResponseFlow(scope) + val january = CompletableDeferred() + + flow.fetch { january.await() } + flow.fetch { "february" }.join() + january.complete("january") + + assertEquals(RoomieApiResponse.Success("february"), flow.state.value) + } + + @Test + fun setDiscardsFetchInFlight() = runBlocking { + val flow = ResponseFlow(scope) + val house = CompletableDeferred() + + val fetch = flow.fetch { house.await() } + flow.set(RoomieApiResponse.Pending) + house.complete("departed house") + fetch.join() + + assertEquals(RoomieApiResponse.Pending, flow.state.value) + } + + @Test + fun concurrentUpdatesAreNotLost() = runBlocking { + val flow = ResponseFlow(scope) + flow.set(RoomieApiResponse.Success(0)) + + (1..1000).map { async(Dispatchers.Default) { flow.update { r -> r.map { it + 1 } } } }.awaitAll() + + assertEquals(RoomieApiResponse.Success(1000), flow.state.value) + } +} diff --git a/app/src/test/java/com/example/roomie/data/api/RoomieApiTest.kt b/app/src/test/java/com/example/roomie/data/api/RoomieApiTest.kt new file mode 100644 index 0000000..96bea68 --- /dev/null +++ b/app/src/test/java/com/example/roomie/data/api/RoomieApiTest.kt @@ -0,0 +1,117 @@ +package com.example.roomie.data.api + +import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class RoomieApiTest { + + private val server = MockWebServer() + private var refreshes = 0 + private val tokens = TokenProvider { forceRefresh -> + if (forceRefresh) "fresh-${++refreshes}" else "dev:mnh49" + } + private lateinit var houseApi: HouseApiService + + @Before + fun setUp() { + server.start() + val retrofit = roomieRetrofit(server.url("/").toString(), tokens, logBodies = false) + houseApi = retrofit.create(HouseApiService::class.java) + } + + @After + fun tearDown() { + server.shutdown() + } + + @Test + fun retriesOnceWithRefreshedTokenAfter401() = runBlocking { + server.enqueue(json(401, """{"status":"fail","statusCode":401,"message":"Expired","errorCode":"UNAUTHORIZED"}""")) + server.enqueue(MockResponse().setResponseCode(204)) + + val result = apiCall { houseApi.leaveHouse(1) } + + assertEquals(RoomieApiResponse.Success(Unit), result) + assertEquals("Bearer dev:mnh49", server.takeRequest().getHeader("Authorization")) + assertEquals("Bearer fresh-1", server.takeRequest().getHeader("Authorization")) + } + + @Test + fun givesUpAfterSecond401() = runBlocking { + repeat(2) { server.enqueue(json(401, """{"errorCode":"UNAUTHORIZED","message":"Bad token"}""")) } + + val error = (apiCall { houseApi.leaveHouse(1) } as RoomieApiResponse.Error).error + + assertEquals(ApiErrorCode.UNAUTHORIZED, error.code) + assertEquals(2, server.requestCount) + } + + @Test + fun stillRefreshesWhenARedirectCameBeforeThe401() = runBlocking { + server.enqueue(MockResponse().setResponseCode(307).setHeader("Location", "/houses/1/leave")) + server.enqueue(json(401, """{"errorCode":"UNAUTHORIZED","message":"Expired"}""")) + server.enqueue(MockResponse().setResponseCode(204)) + + val result = apiCall { houseApi.leaveHouse(1) } + + assertEquals(RoomieApiResponse.Success(Unit), result) + assertEquals(3, server.requestCount) + server.takeRequest() + server.takeRequest() + assertEquals("Bearer fresh-1", server.takeRequest().getHeader("Authorization")) + } + + @Test + fun doesNotRetryAsAnotherAccount() = runBlocking { + // Signs in as someone else between sending the request and getting its 401. + val switching = object : TokenProvider { + @Volatile var current = 1L + override val session get() = current + override suspend fun token(forceRefresh: Boolean) = "dev:user$current" + } + val api = roomieRetrofit(server.url("/").toString(), switching, logBodies = false) + .create(HouseApiService::class.java) + server.enqueue(json(401, """{"errorCode":"UNAUTHORIZED","message":"Expired"}""").apply { + // MockWebServer can't run code mid-call, so switch before it answers. + setHeadersDelay(300, java.util.concurrent.TimeUnit.MILLISECONDS) + }) + server.enqueue(MockResponse().setResponseCode(204)) + + val call = async(kotlinx.coroutines.Dispatchers.IO) { apiCall { api.leaveHouse(1) } } + server.takeRequest() + switching.current = 2L + val error = (call.await() as RoomieApiResponse.Error).error + + assertEquals(ApiErrorCode.UNAUTHORIZED, error.code) + assertEquals(1, server.requestCount) + } + + @Test + fun fallsBackToStatusWhenBodyIsNotJson() = runBlocking { + server.enqueue(MockResponse().setResponseCode(409).setBody("Conflict")) + + val error = (apiCall { houseApi.joinHouse(JoinHouseBody("LOFT-4827")) } as RoomieApiResponse.Error).error + + assertEquals(ApiErrorCode.CONFLICT, error.code) + } + + @Test + fun reportsNetworkFailures() = runBlocking { + server.shutdown() + + val error = (apiCall { houseApi.getHouse(1) } as RoomieApiResponse.Error).error + + assertEquals(ApiErrorCode.NETWORK, error.code) + assertTrue(error.statusCode == null) + } + + private fun json(code: Int, body: String) = + MockResponse().setResponseCode(code).setHeader("Content-Type", "application/json").setBody(body.trimIndent()) +}