-
Notifications
You must be signed in to change notification settings - Fork 194
/
RealMutableStore.kt
264 lines (229 loc) · 11.6 KB
/
RealMutableStore.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
@file:Suppress("UNCHECKED_CAST")
package org.mobilenativefoundation.store.store5.impl
import co.touchlab.kermit.CommonWriter
import co.touchlab.kermit.Logger
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.mobilenativefoundation.store.store5.Bookkeeper
import org.mobilenativefoundation.store.store5.Clear
import org.mobilenativefoundation.store.core5.ExperimentalStoreApi
import org.mobilenativefoundation.store.store5.MutableStore
import org.mobilenativefoundation.store.store5.StoreReadRequest
import org.mobilenativefoundation.store.store5.StoreReadResponse
import org.mobilenativefoundation.store.store5.StoreWriteRequest
import org.mobilenativefoundation.store.store5.StoreWriteResponse
import org.mobilenativefoundation.store.store5.Updater
import org.mobilenativefoundation.store.store5.UpdaterResult
import org.mobilenativefoundation.store.store5.impl.extensions.now
import org.mobilenativefoundation.store.store5.internal.concurrent.AnyThread
import org.mobilenativefoundation.store.store5.internal.concurrent.ThreadSafety
import org.mobilenativefoundation.store.store5.internal.definition.WriteRequestQueue
import org.mobilenativefoundation.store.store5.internal.result.EagerConflictResolutionResult
@ExperimentalStoreApi
internal class RealMutableStore<Key : Any, Network : Any, Output : Any, Local : Any>(
private val delegate: RealStore<Key, Network, Output, Local>,
private val updater: Updater<Key, Output, *>,
private val bookkeeper: Bookkeeper<Key>?,
) : MutableStore<Key, Output>, Clear.Key<Key> by delegate, Clear.All by delegate {
private val storeLock = Mutex()
private val keyToWriteRequestQueue = mutableMapOf<Key, WriteRequestQueue<Key, Output, *>>()
private val keyToThreadSafety = mutableMapOf<Key, ThreadSafety>()
override fun <Response : Any> stream(request: StoreReadRequest<Key>): Flow<StoreReadResponse<Output>> =
flow {
safeInitStore(request.key)
when (val eagerConflictResolutionResult = tryEagerlyResolveConflicts<Response>(request.key)) {
is EagerConflictResolutionResult.Error.Exception -> {
logger.e(eagerConflictResolutionResult.error.toString())
}
is EagerConflictResolutionResult.Error.Message -> {
logger.e(eagerConflictResolutionResult.message)
}
is EagerConflictResolutionResult.Success.ConflictsResolved -> {
logger.d(eagerConflictResolutionResult.value.toString())
}
EagerConflictResolutionResult.Success.NoConflicts -> {
logger.d(eagerConflictResolutionResult.toString())
}
}
delegate.stream(request).collect { storeReadResponse -> emit(storeReadResponse) }
}
@ExperimentalStoreApi
override fun <Response : Any> stream(requestStream: Flow<StoreWriteRequest<Key, Output, Response>>): Flow<StoreWriteResponse> =
flow {
requestStream
.onEach { writeRequest ->
safeInitStore(writeRequest.key)
addWriteRequestToQueue(writeRequest)
}
.collect { writeRequest ->
val storeWriteResponse = try {
delegate.write(writeRequest.key, writeRequest.value)
when (val updaterResult = tryUpdateServer(writeRequest)) {
is UpdaterResult.Error.Exception -> StoreWriteResponse.Error.Exception(updaterResult.error)
is UpdaterResult.Error.Message -> StoreWriteResponse.Error.Message(updaterResult.message)
is UpdaterResult.Success.Typed<*> -> {
val typedValue = updaterResult.value as? Response
if (typedValue == null) {
StoreWriteResponse.Success.Untyped(updaterResult.value)
} else {
StoreWriteResponse.Success.Typed(updaterResult.value)
}
}
is UpdaterResult.Success.Untyped -> StoreWriteResponse.Success.Untyped(updaterResult.value)
}
} catch (throwable: Throwable) {
StoreWriteResponse.Error.Exception(throwable)
}
emit(storeWriteResponse)
}
}
@ExperimentalStoreApi
override suspend fun <Response : Any> write(request: StoreWriteRequest<Key, Output, Response>): StoreWriteResponse =
stream(flowOf(request)).first()
private suspend fun <Response : Any> tryUpdateServer(request: StoreWriteRequest<Key, Output, Response>): UpdaterResult {
val updaterResult = postLatest<Response>(request.key)
if (updaterResult is UpdaterResult.Success) {
updateWriteRequestQueue<Response>(
key = request.key,
created = request.created,
updaterResult = updaterResult
)
bookkeeper?.clear(request.key)
} else {
bookkeeper?.setLastFailedSync(request.key)
}
return updaterResult
}
private suspend fun <Response : Any> postLatest(key: Key): UpdaterResult {
val writer = getLatestWriteRequest(key)
return when (val updaterResult = updater.post(key, writer.value)) {
is UpdaterResult.Error.Exception -> UpdaterResult.Error.Exception(updaterResult.error)
is UpdaterResult.Error.Message -> UpdaterResult.Error.Message(updaterResult.message)
is UpdaterResult.Success.Untyped -> UpdaterResult.Success.Untyped(updaterResult.value)
is UpdaterResult.Success.Typed<*> -> {
val typedValue = updaterResult.value as? Response
if (typedValue == null) {
UpdaterResult.Success.Untyped(updaterResult.value)
} else {
UpdaterResult.Success.Typed(updaterResult.value)
}
}
}
}
@AnyThread
private suspend fun <Response : Any> updateWriteRequestQueue(key: Key, created: Long, updaterResult: UpdaterResult.Success) {
val nextWriteRequestQueue = withWriteRequestQueueLock(key) {
val outstandingWriteRequests = ArrayDeque<StoreWriteRequest<Key, Output, *>>()
for (writeRequest in this) {
if (writeRequest.created <= created) {
updater.onCompletion?.onSuccess?.invoke(updaterResult)
val storeWriteResponse = when (updaterResult) {
is UpdaterResult.Success.Typed<*> -> {
val typedValue = updaterResult.value as? Response
if (typedValue == null) {
StoreWriteResponse.Success.Untyped(updaterResult.value)
} else {
StoreWriteResponse.Success.Typed(updaterResult.value)
}
}
is UpdaterResult.Success.Untyped -> StoreWriteResponse.Success.Untyped(updaterResult.value)
}
writeRequest.onCompletions?.forEach { onStoreWriteCompletion ->
onStoreWriteCompletion.onSuccess(storeWriteResponse)
}
} else {
outstandingWriteRequests.add(writeRequest)
}
}
outstandingWriteRequests
}
withThreadSafety(key) {
keyToWriteRequestQueue[key] = nextWriteRequestQueue
}
}
@AnyThread
private suspend fun <Result : Any> withWriteRequestQueueLock(
key: Key,
block: suspend WriteRequestQueue<Key, Output, *>.() -> Result
): Result =
withThreadSafety(key) {
writeRequests.lightswitch.lock(writeRequests.mutex)
val writeRequestQueue = requireNotNull(keyToWriteRequestQueue[key])
val output = writeRequestQueue.block()
writeRequests.lightswitch.unlock(writeRequests.mutex)
output
}
private suspend fun getLatestWriteRequest(key: Key): StoreWriteRequest<Key, Output, *> = withThreadSafety(key) {
writeRequests.mutex.lock()
val output = requireNotNull(keyToWriteRequestQueue[key]?.last())
writeRequests.mutex.unlock()
output
}
@AnyThread
private suspend fun <Output : Any?> withThreadSafety(key: Key, block: suspend ThreadSafety.() -> Output): Output {
storeLock.lock()
val threadSafety = requireNotNull(keyToThreadSafety[key])
val output = threadSafety.block()
storeLock.unlock()
return output
}
private suspend fun conflictsMightExist(key: Key): Boolean {
val lastFailedSync = bookkeeper?.getLastFailedSync(key)
return lastFailedSync != null || writeRequestsQueueIsEmpty(key).not()
}
private fun writeRequestsQueueIsEmpty(key: Key): Boolean = keyToWriteRequestQueue[key].isNullOrEmpty()
private suspend fun <Response : Any> addWriteRequestToQueue(writeRequest: StoreWriteRequest<Key, Output, Response>) =
withWriteRequestQueueLock(writeRequest.key) {
add(writeRequest)
}
@AnyThread
private suspend fun <Response : Any> tryEagerlyResolveConflicts(key: Key): EagerConflictResolutionResult<Response> =
withThreadSafety(key) {
val latest = delegate.latestOrNull(key)
when {
latest == null || bookkeeper == null || conflictsMightExist(key).not() -> EagerConflictResolutionResult.Success.NoConflicts
else -> {
try {
val updaterResult = updater.post(key, latest).also { updaterResult ->
if (updaterResult is UpdaterResult.Success) {
updateWriteRequestQueue<Response>(key = key, created = now(), updaterResult = updaterResult)
}
}
when (updaterResult) {
is UpdaterResult.Error.Exception -> EagerConflictResolutionResult.Error.Exception(updaterResult.error)
is UpdaterResult.Error.Message -> EagerConflictResolutionResult.Error.Message(updaterResult.message)
is UpdaterResult.Success -> EagerConflictResolutionResult.Success.ConflictsResolved(updaterResult)
}
} catch (throwable: Throwable) {
EagerConflictResolutionResult.Error.Exception(throwable)
}
}
}
}
private suspend fun safeInitWriteRequestQueue(key: Key) = withThreadSafety(key) {
if (keyToWriteRequestQueue[key] == null) {
keyToWriteRequestQueue[key] = ArrayDeque()
}
}
private suspend fun safeInitThreadSafety(key: Key) = storeLock.withLock {
if (keyToThreadSafety[key] == null) {
keyToThreadSafety[key] = ThreadSafety()
}
}
private suspend fun safeInitStore(key: Key) {
safeInitThreadSafety(key)
safeInitWriteRequestQueue(key)
}
companion object {
private val logger = Logger.apply {
setLogWriters(listOf(CommonWriter()))
setTag("Store")
}
private const val UNKNOWN_ERROR = "Unknown error occurred"
}
}