|
| 1 | +package com.flipcash.app.blob |
| 2 | + |
| 3 | +import android.content.Context |
| 4 | +import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler |
| 5 | +import androidx.datastore.preferences.core.PreferenceDataStoreFactory |
| 6 | +import androidx.datastore.preferences.core.Preferences |
| 7 | +import androidx.datastore.preferences.core.edit |
| 8 | +import androidx.datastore.preferences.core.emptyPreferences |
| 9 | +import androidx.datastore.preferences.core.stringPreferencesKey |
| 10 | +import androidx.datastore.preferences.preferencesDataStoreFile |
| 11 | +import com.flipcash.libs.coroutines.DispatcherProvider |
| 12 | +import com.flipcash.services.controllers.BlobStorageController |
| 13 | +import com.flipcash.services.models.InitiateExternalUploadError |
| 14 | +import com.flipcash.services.models.blob.MimeTypeConstraints |
| 15 | +import com.flipcash.services.models.blob.UploadPolicy |
| 16 | +import com.flipcash.services.models.chat.BlobId |
| 17 | +import dagger.hilt.android.qualifiers.ApplicationContext |
| 18 | +import kotlinx.coroutines.CoroutineScope |
| 19 | +import kotlinx.coroutines.SupervisorJob |
| 20 | +import kotlinx.coroutines.flow.Flow |
| 21 | +import kotlinx.coroutines.flow.first |
| 22 | +import kotlinx.coroutines.flow.map |
| 23 | +import kotlinx.coroutines.flow.onEach |
| 24 | +import kotlinx.coroutines.launch |
| 25 | +import kotlinx.serialization.json.Json |
| 26 | +import java.util.concurrent.atomic.AtomicBoolean |
| 27 | +import javax.inject.Inject |
| 28 | +import javax.inject.Singleton |
| 29 | +import kotlin.time.Duration.Companion.milliseconds |
| 30 | + |
| 31 | +/** |
| 32 | + * App-layer facade over blob storage ([BlobStorageController]). ViewModels use this coordinator |
| 33 | + * rather than the service-layer controller, mirroring the app's Coordinator → Controller pattern |
| 34 | + * (e.g. [ChatCoordinator][com.flipcash.shared.chat.ChatCoordinator]). |
| 35 | + * |
| 36 | + * It also owns the persisted [UploadPolicy] cache, which honours the policy's own `ttl` and |
| 37 | + * `version`: [preloadPolicy] is called on launch by the session controller, [policy] re-fetches |
| 38 | + * when the cached copy has aged past its ttl, and [upload] re-fetches when the server rejects an |
| 39 | + * upload on policy grounds (a version-mismatch signal). |
| 40 | + */ |
| 41 | +@Singleton |
| 42 | +class BlobStorageCoordinator @Inject constructor( |
| 43 | + @param:ApplicationContext private val context: Context, |
| 44 | + private val blobStorageController: BlobStorageController, |
| 45 | + dispatchers: DispatcherProvider, |
| 46 | +) { |
| 47 | + private val scope = CoroutineScope(SupervisorJob() + dispatchers.IO) |
| 48 | + |
| 49 | + private val dataStore = PreferenceDataStoreFactory.create( |
| 50 | + corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() }, |
| 51 | + scope = scope, |
| 52 | + produceFile = { context.preferencesDataStoreFile("upload-policy") } |
| 53 | + ) |
| 54 | + |
| 55 | + private val json = Json { ignoreUnknownKeys = true } |
| 56 | + |
| 57 | + private val refreshing = AtomicBoolean(false) |
| 58 | + |
| 59 | + /** |
| 60 | + * The upload policy, kept fresh. Emits the cached value and, whenever that value is stale (past |
| 61 | + * its `ttl`) or absent, triggers a background refresh whose result re-emits here. Observe it |
| 62 | + * directly from a ViewModel; a stale cache resolves to a fresh value without a manual fetch. |
| 63 | + */ |
| 64 | + val policy: Flow<UploadPolicy?> = dataStore.data |
| 65 | + .map { it.decode() } |
| 66 | + .onEach { cached -> if (cached == null || !cached.isFresh()) triggerRefresh() } |
| 67 | + .map { it?.toDomain() } |
| 68 | + |
| 69 | + /** Fetches the latest upload policy and caches it (stamped with the fetch time). */ |
| 70 | + suspend fun preloadPolicy(): Result<UploadPolicy> = |
| 71 | + blobStorageController.getUploadPolicy().onSuccess { persist(it) } |
| 72 | + |
| 73 | + /** |
| 74 | + * Uploads [bytes] to storage and returns the READY [BlobId] — reserve, PUT/POST, complete, and |
| 75 | + * poll are all handled inside the controller. A policy-driven rejection invalidates the cached |
| 76 | + * policy (the server echoes a newer policy version on such denials). |
| 77 | + */ |
| 78 | + suspend fun upload(bytes: ByteArray, mimeType: String): Result<BlobId> { |
| 79 | + val result = blobStorageController.upload(bytes, mimeType) |
| 80 | + result.exceptionOrNull()?.let { refreshIfPolicyChanged(it) } |
| 81 | + return result |
| 82 | + } |
| 83 | + |
| 84 | + suspend fun reset() { |
| 85 | + dataStore.edit { it.remove(KEY_UPLOAD_POLICY) } |
| 86 | + } |
| 87 | + |
| 88 | + // Fire-and-forget refresh, deduped so a burst of stale emissions launches at most one fetch. |
| 89 | + private fun triggerRefresh() { |
| 90 | + if (refreshing.compareAndSet(false, true)) { |
| 91 | + scope.launch { |
| 92 | + try { |
| 93 | + preloadPolicy() |
| 94 | + } finally { |
| 95 | + refreshing.set(false) |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + // A policy-driven denial means our cached policy let something through the server now rejects. |
| 102 | + // Re-fetch when the echoed version differs from what we cached (or we have nothing cached). |
| 103 | + private suspend fun refreshIfPolicyChanged(cause: Throwable) { |
| 104 | + val deniedVersion = when (cause) { |
| 105 | + is InitiateExternalUploadError.UnsupportedType -> cause.policyVersion |
| 106 | + is InitiateExternalUploadError.TooLarge -> cause.policyVersion |
| 107 | + else -> return |
| 108 | + } |
| 109 | + if (deniedVersion == null || deniedVersion != cached()?.version) { |
| 110 | + preloadPolicy() |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + private suspend fun persist(policy: UploadPolicy) { |
| 115 | + val raw = json.encodeToString(CachedUploadPolicy.fromDomain(policy, now())) |
| 116 | + dataStore.edit { it[KEY_UPLOAD_POLICY] = raw } |
| 117 | + } |
| 118 | + |
| 119 | + private suspend fun cached(): CachedUploadPolicy? = dataStore.data.first().decode() |
| 120 | + |
| 121 | + private fun Preferences.decode(): CachedUploadPolicy? = |
| 122 | + this[KEY_UPLOAD_POLICY]?.let { raw -> |
| 123 | + runCatching { json.decodeFromString<CachedUploadPolicy>(raw) }.getOrNull() |
| 124 | + } |
| 125 | + |
| 126 | + private fun CachedUploadPolicy.isFresh(): Boolean = now() - fetchedAtMillis < ttlMillis |
| 127 | + |
| 128 | + private fun now(): Long = System.currentTimeMillis() |
| 129 | + |
| 130 | + companion object { |
| 131 | + private val KEY_UPLOAD_POLICY = stringPreferencesKey("cached_upload_policy") |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +/** |
| 136 | + * On-disk form. [UploadPolicy.ttl] is a [kotlin.time.Duration] (not kotlinx-serializable) so it is |
| 137 | + * stored as milliseconds; [fetchedAtMillis] stamps when it was cached so freshness can be checked |
| 138 | + * against the ttl; [MimeTypeConstraints] is already `@Serializable` and stored as-is. |
| 139 | + */ |
| 140 | +@kotlinx.serialization.Serializable |
| 141 | +private data class CachedUploadPolicy( |
| 142 | + val version: String, |
| 143 | + val ttlMillis: Long, |
| 144 | + val fetchedAtMillis: Long, |
| 145 | + val mimeTypeConstraints: List<MimeTypeConstraints>, |
| 146 | +) { |
| 147 | + fun toDomain(): UploadPolicy = UploadPolicy( |
| 148 | + version = version, |
| 149 | + ttl = ttlMillis.milliseconds, |
| 150 | + mimeTypeConstraints = mimeTypeConstraints, |
| 151 | + ) |
| 152 | + |
| 153 | + companion object { |
| 154 | + fun fromDomain(policy: UploadPolicy, fetchedAtMillis: Long): CachedUploadPolicy = CachedUploadPolicy( |
| 155 | + version = policy.version, |
| 156 | + ttlMillis = policy.ttl.inWholeMilliseconds, |
| 157 | + fetchedAtMillis = fetchedAtMillis, |
| 158 | + mimeTypeConstraints = policy.mimeTypeConstraints, |
| 159 | + ) |
| 160 | + } |
| 161 | +} |
0 commit comments