-
Notifications
You must be signed in to change notification settings - Fork 3k
/
RustPlaces.swift
337 lines (271 loc) · 11.6 KB
/
RustPlaces.swift
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/* 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/. */
import Foundation
import Shared
@_exported import MozillaAppServices
private let log = Logger.syncLogger
public class RustPlaces {
let databasePath: String
let writerQueue: DispatchQueue
let readerQueue: DispatchQueue
var api: PlacesAPI?
var writer: PlacesWriteConnection?
var reader: PlacesReadConnection?
public fileprivate(set) var isOpen: Bool = false
private var didAttemptToMoveToBackup = false
public init(databasePath: String) {
self.databasePath = databasePath
self.writerQueue = DispatchQueue(label: "RustPlaces writer queue: \(databasePath)", attributes: [])
self.readerQueue = DispatchQueue(label: "RustPlaces reader queue: \(databasePath)", attributes: [])
}
private func open() -> NSError? {
do {
api = try PlacesAPI(path: databasePath)
isOpen = true
return nil
} catch let err as NSError {
if let placesError = err as? PlacesError {
switch placesError {
case .panic(let message):
Sentry.shared.sendWithStacktrace(message: "Panicked when opening Rust Places database", tag: SentryTag.rustPlaces, severity: .error, description: message)
default:
Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when opening Rust Places database", tag: SentryTag.rustPlaces, severity: .error, description: placesError.localizedDescription)
}
} else {
Sentry.shared.sendWithStacktrace(message: "Unknown error when opening Rust Places database", tag: SentryTag.rustPlaces, severity: .error, description: err.localizedDescription)
}
return err
}
}
private func close() -> NSError? {
api = nil
writer = nil
reader = nil
isOpen = false
return nil
}
private func withWriter<T>(_ callback: @escaping(_ connection: PlacesWriteConnection) throws -> T) -> Deferred<Maybe<T>> {
let deferred = Deferred<Maybe<T>>()
writerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
return
}
if self.writer == nil {
self.writer = self.api?.getWriter()
}
if let writer = self.writer {
do {
let result = try callback(writer)
deferred.fill(Maybe(success: result))
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
} else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
}
}
return deferred
}
private func withReader<T>(_ callback: @escaping(_ connection: PlacesReadConnection) throws -> T) -> Deferred<Maybe<T>> {
let deferred = Deferred<Maybe<T>>()
readerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
return
}
if self.reader == nil {
do {
self.reader = try self.api?.openReader()
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
}
if let reader = self.reader {
do {
let result = try callback(reader)
deferred.fill(Maybe(success: result))
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
} else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
}
}
return deferred
}
public func migrateBookmarksIfNeeded(fromBrowserDB browserDB: BrowserDB) {
// Since we use the existence of places.db as an indication that we've
// already migrated bookmarks, assert that places.db is not open here.
assert(!isOpen, "Shouldn't attempt to migrate bookmarks after opening Rust places.db")
// We only need to migrate bookmarks here if the old browser.db file
// already exists AND the new Rust places.db file does NOT exist yet.
// This is to ensure that we only ever run this migration ONCE. In
// addition, it is the caller's (Profile.swift) responsibility to NOT
// use this migration API for users signed into a Firefox Account.
// Those users will automatically get all their bookmarks on next Sync.
guard FileManager.default.fileExists(atPath: browserDB.databasePath),
!FileManager.default.fileExists(atPath: databasePath) else {
return
}
// Ensure that the old BrowserDB schema is up-to-date before migrating.
_ = browserDB.touch().value
// Open the Rust places.db now for the first time.
_ = reopenIfClosed()
do {
try api?.migrateBookmarksFromBrowserDb(path: browserDB.databasePath)
} catch let err as NSError {
Sentry.shared.sendWithStacktrace(message: "Error encountered while migrating bookmarks from BrowserDB", tag: SentryTag.rustPlaces, severity: .error, description: err.localizedDescription)
}
}
public func getBookmarksTree(rootGUID: GUID, recursive: Bool) -> Deferred<Maybe<BookmarkNode?>> {
return withReader { connection in
return try connection.getBookmarksTree(rootGUID: rootGUID, recursive: recursive)
}
}
public func getBookmark(guid: GUID) -> Deferred<Maybe<BookmarkNode?>> {
return withReader { connection in
return try connection.getBookmark(guid: guid)
}
}
public func getRecentBookmarks(limit: UInt) -> Deferred<Maybe<[BookmarkItem]>> {
return withReader { connection in
return try connection.getRecentBookmarks(limit: limit)
}
}
public func getBookmarkURLForKeyword(keyword: String) -> Deferred<Maybe<String?>> {
return withReader { connection in
return try connection.getBookmarkURLForKeyword(keyword: keyword)
}
}
public func getBookmarksWithURL(url: String) -> Deferred<Maybe<[BookmarkItem]>> {
return withReader { connection in
return try connection.getBookmarksWithURL(url: url)
}
}
public func isBookmarked(url: String) -> Deferred<Maybe<Bool>> {
return getBookmarksWithURL(url: url).bind { result in
guard let bookmarks = result.successValue else {
return deferMaybe(false)
}
return deferMaybe(!bookmarks.isEmpty)
}
}
public func searchBookmarks(query: String, limit: UInt) -> Deferred<Maybe<[BookmarkItem]>> {
return withReader { connection in
return try connection.searchBookmarks(query: query, limit: limit)
}
}
public func interruptWriter() {
writer?.interrupt()
}
public func interruptReader() {
reader?.interrupt()
}
public func runMaintenance() {
_ = withWriter { connection in
try connection.runMaintenance()
}
}
public func deleteBookmarkNode(guid: GUID) -> Success {
return withWriter { connection in
let result = try connection.deleteBookmarkNode(guid: guid)
if !result {
log.debug("Bookmark with GUID \(guid) does not exist.")
}
}
}
public func deleteBookmarksWithURL(url: String) -> Success {
return getBookmarksWithURL(url: url) >>== { bookmarks in
let deferreds = bookmarks.map({ self.deleteBookmarkNode(guid: $0.guid) })
return all(deferreds).bind { results in
if let error = results.find({ $0.isFailure })?.failureValue {
return deferMaybe(error)
}
return succeed()
}
}
}
public func createFolder(parentGUID: GUID, title: String, position: UInt32? = nil) -> Deferred<Maybe<GUID>> {
return withWriter { connection in
return try connection.createFolder(parentGUID: parentGUID, title: title, position: position)
}
}
public func createSeparator(parentGUID: GUID, position: UInt32? = nil) -> Deferred<Maybe<GUID>> {
return withWriter { connection in
return try connection.createSeparator(parentGUID: parentGUID, position: position)
}
}
@discardableResult
public func createBookmark(parentGUID: GUID, url: String, title: String?, position: UInt32? = nil) -> Deferred<Maybe<GUID>> {
return withWriter { connection in
return try connection.createBookmark(parentGUID: parentGUID, url: url, title: title, position: position)
}
}
public func updateBookmarkNode(guid: GUID, parentGUID: GUID? = nil, position: UInt32? = nil, title: String? = nil, url: String? = nil) -> Success {
return withWriter { connection in
return try connection.updateBookmarkNode(guid: guid, parentGUID: parentGUID, position: position, title: title, url: url)
}
}
public func reopenIfClosed() -> NSError? {
var error: NSError? = nil
writerQueue.sync {
guard !isOpen else { return }
error = open()
}
return error
}
public func interrupt() {
api?.interrupt()
}
public func forceClose() -> NSError? {
var error: NSError? = nil
api?.interrupt()
writerQueue.sync {
guard isOpen else { return }
error = close()
}
return error
}
public func syncBookmarks(unlockInfo: SyncUnlockInfo) -> Success {
let deferred = Success()
writerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
return
}
do {
try _ = self.api?.syncBookmarks(unlockInfo: unlockInfo)
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
if let placesError = err as? PlacesError {
switch placesError {
case .panic(let message):
Sentry.shared.sendWithStacktrace(message: "Panicked when syncing Places database", tag: SentryTag.rustPlaces, severity: .error, description: message)
default:
Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when syncing Places database", tag: SentryTag.rustPlaces, severity: .error, description: placesError.localizedDescription)
}
}
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func resetBookmarksMetadata() -> Success {
let deferred = Success()
writerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
return
}
do {
try self.api?.resetBookmarkSyncMetadata()
deferred.fill(Maybe(success: ()))
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
}
return deferred
}
}