forked from mozilla-mobile/firefox-android
/
PlacesStorage.kt
252 lines (230 loc) · 10.2 KB
/
PlacesStorage.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package mozilla.components.browser.storage.sync
import android.content.Context
import androidx.annotation.VisibleForTesting
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.plus
import kotlinx.coroutines.withContext
import mozilla.appservices.places.PlacesReaderConnection
import mozilla.appservices.places.PlacesWriterConnection
import mozilla.appservices.places.uniffi.PlacesApiException
import mozilla.components.concept.base.crash.CrashReporting
import mozilla.components.concept.storage.Storage
import mozilla.components.concept.storage.StorageMaintenanceRegistry
import mozilla.components.concept.sync.SyncStatus
import mozilla.components.concept.sync.SyncableStore
import mozilla.components.support.base.log.logger.Logger
import mozilla.components.support.base.utils.NamedThreadFactory
import mozilla.components.support.utils.logElapsedTime
import java.util.concurrent.Executors
/**
* A base class for concrete implementations of PlacesStorages
*/
abstract class PlacesStorage(
context: Context,
val crashReporter: CrashReporting? = null,
) : Storage, SyncableStore, StorageMaintenanceRegistry {
internal var writeScope =
CoroutineScope(
Executors.newSingleThreadExecutor(
NamedThreadFactory("PlacesStorageWriteScope"),
).asCoroutineDispatcher(),
) +
CoroutineExceptionHandler { _, throwable ->
// Workaround for https://github.com/Kotlin/kotlinx.coroutines/issues/3328 to prevent
// adding DiagnosticCoroutineContextException as suppressed exception which is not
// serializable in 1.6.4. We are otherwise not able to serialize the exception and
// pass it to our crash reporter. Without a handler on the context, the global handler
// will otherwise add:
// runCatching { exception.addSuppressed(DiagnosticCoroutineContextException(context)) }
val currentThread = Thread.currentThread()
currentThread.uncaughtExceptionHandler.uncaughtException(currentThread, throwable)
}
@VisibleForTesting internal set
internal var readScope = CoroutineScope(Dispatchers.IO) +
CoroutineExceptionHandler { _, throwable ->
// Workaround for https://github.com/Kotlin/kotlinx.coroutines/issues/3328 to prevent
// adding DiagnosticCoroutineContextException as suppressed exception which is not
// serializable in 1.6.4. We are otherwise not able to serialize the exception and
// pass it to our crash reporter. Without a handler on the context, the global handler
// will otherwise add:
// runCatching { exception.addSuppressed(DiagnosticCoroutineContextException(context)) }
val currentThread = Thread.currentThread()
currentThread.uncaughtExceptionHandler.uncaughtException(currentThread, throwable)
}
@VisibleForTesting internal set
private val storageDir by lazy { context.filesDir }
/**
* Cache of the last value with which [cancelReads] was called.
* Used to check whether a new call to [cancelReads] should trigger a cancellation or not.
*/
private var lastCancelledQuery = ""
abstract val logger: Logger
internal open val places: Connection by lazy {
RustPlacesConnection.init(storageDir)
RustPlacesConnection
}
internal open val writer: PlacesWriterConnection by lazy { places.writer() }
internal open val reader: PlacesReaderConnection by lazy { places.reader() }
override suspend fun warmUp() {
logElapsedTime(logger, "Warming up places storage") {
writer
reader
}
}
/**
* Internal database maintenance tasks. Ideally this should be called once a day.
*
* @param dbSizeLimit Maximum DB size to aim for, in bytes. If the
* database exceeds this size, a small number of visits will be pruned.
*/
override suspend fun runMaintenance(dbSizeLimit: UInt) {
withContext(writeScope.coroutineContext) {
places.writer().runMaintenance(dbSizeLimit)
}
}
@Deprecated(
"Use `cancelWrites` and `cancelReads` to get a similar functionality. " +
"See https://github.com/mozilla-mobile/android-components/issues/7348 for a description of the issues " +
"for when using this method",
)
override fun cleanup() {
writeScope.coroutineContext.cancelChildren()
readScope.coroutineContext.cancelChildren()
places.close()
}
override fun cancelWrites() {
interruptCurrentWrites()
writeScope.coroutineContext.cancelChildren()
}
override fun cancelReads() {
interruptCurrentReads()
readScope.coroutineContext.cancelChildren()
}
/**
* Cleans up pending read operations of a specific query.
*
* @param nextQuery Previous query to cancel reads for.
* Calling cancel multiple times for the same query has effect only the first time.
* Use this in scenarios where the same instance is used in multiple scenarios to prevent cases
* in which a general cancel operation for one scenario cancels other reads for the same query.
* If the value is an empty string all current reads are immediately cancelled.
*/
override fun cancelReads(nextQuery: String) {
if (nextQuery.isEmpty() || lastCancelledQuery != nextQuery) {
lastCancelledQuery = nextQuery
interruptCurrentReads()
readScope.coroutineContext.cancelChildren()
}
}
/**
* Stop all current write operations.
* Allows immediately dismissing all write operations and clearing the write queue.
*/
internal fun interruptCurrentWrites() {
handlePlacesExceptions("interruptCurrentWrites") {
writer.interrupt()
}
}
/**
* Stop all current read queries.
* Allows avoiding having to wait for stale queries responses and clears the queries queue.
*/
internal fun interruptCurrentReads() {
handlePlacesExceptions("interruptCurrentReads") {
reader.interrupt()
}
}
/**
* Runs [block] described by [operation], ignoring and logging non-fatal exceptions.
*
* @param operation the name of the operation to run.
* @param block the operation to run.
*/
protected inline fun handlePlacesExceptions(operation: String, block: () -> Unit) {
try {
block()
} catch (e: PlacesApiException.UnexpectedPlacesException) {
throw e
} catch (e: PlacesApiException.OperationInterrupted) {
logger.debug("Ignoring expected OperationInterrupted exception when running $operation", e)
} catch (e: PlacesApiException.UrlParseFailed) {
// it's not uncommon to get a mal-formed url, probably the user typing.
logger.debug("Ignoring invalid URL while running $operation", e)
} catch (e: PlacesApiException) {
crashReporter?.submitCaughtException(e)
logger.warn("Ignoring PlacesApiException while running $operation", e)
}
}
/**
* Runs [block] described by [operation] to return a result of type [T], ignoring and
* logging non-fatal exceptions. In case of a non-fatal exception, the provided
* [default] value is returned.
*
* @param operation the name of the operation to run.
* @param block the operation to run.
* @param default the default value to return in case of errors.
*/
inline fun <T> handlePlacesExceptions(
operation: String,
default: T,
block: () -> T,
): T {
return try {
block()
} catch (e: PlacesApiException.UnexpectedPlacesException) {
throw e
} catch (e: PlacesApiException.OperationInterrupted) {
logger.debug("Ignoring expected OperationInterrupted exception when running $operation", e)
default
} catch (e: PlacesApiException.UrlParseFailed) {
// it's not uncommon to get a mal-formed url, probably the user typing.
logger.debug("Ignoring invalid URL while running $operation", e)
default
} catch (e: PlacesApiException) {
crashReporter?.submitCaughtException(e)
logger.warn("Ignoring PlacesApiException while running $operation", e)
default
}
}
/**
* Runs a [syncBlock], re-throwing any panics that may be encountered.
* @return [SyncStatus.Ok] on success, or [SyncStatus.Error] on non-panic [PlacesApiException].
*/
protected inline fun syncAndHandleExceptions(syncBlock: () -> Unit): SyncStatus {
return try {
logger.debug("Syncing...")
syncBlock()
logger.debug("Successfully synced.")
SyncStatus.Ok
// Order of these catches matters: UnexpectedPlacesException extends PlacesException
} catch (e: PlacesApiException.UnexpectedPlacesException) {
logger.error("Places panic while syncing", e)
throw e
} catch (e: PlacesApiException) {
logger.error("Places exception while syncing", e)
SyncStatus.Error(e)
}
}
/**
* Registers a storage maintenance worker that prunes database when its size exceeds a size limit.
* */
override fun registerStorageMaintenanceWorker() {
// See child classes for implementation details, it is not implemented by default
}
/**
* Unregisters the storage maintenance worker that is registered
* by [PlacesStorage.registerStorageMaintenanceWorker].
*
* @param uniqueWorkName Unique name of the work request that needs to be unregistered
* */
override fun unregisterStorageMaintenanceWorker(uniqueWorkName: String) {
// See child classes for implementation details, it is not implemented by default
}
}