Move ValueObservation support to DatabaseReader

This commit is contained in:
Gwendal Roué committed 2018-10-25 20:39:04 +02:00
1 parent fe0f238f32
commit 0df4815086
4 files changed
+179 -151

No files matched your search

+19
View File
@@ -149,6 +149,14 @@ public protocol DatabaseReader : class {
/// Remove a collation.
func remove(collation: DatabaseCollation)
// MARK: - Value Observation
/// TODO
func add<Value>(
observation: ValueObservation<Value>,
onError: ((Error) -> Void)?,
onChange: @escaping (Value) -> Void) throws -> TransactionObserver
}
extension DatabaseReader {
@@ -228,4 +236,15 @@ public final class AnyDatabaseReader : DatabaseReader {
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
// MARK: - Value Observation
/// TODO
public func add<Value>(
observation: ValueObservation<Value>,
onError: ((Error) -> Void)? = nil,
onChange: @escaping (Value) -> Void) throws -> TransactionObserver
{
return try base.add(observation: observation, onError: onError, onChange: onChange)
}
}
+33 -23
View File
@@ -81,45 +81,55 @@ extension DatabaseSnapshot {
// MARK: - Functions
/// Add or redefine an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
/// return nil
/// }
/// return int + 1
/// }
/// snapshot.add(function: fn)
/// try snapshot.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
serializedDatabase.sync { $0.add(function: function) }
}
/// Remove an SQL function.
public func remove(function: DatabaseFunction) {
serializedDatabase.sync { $0.remove(function: function) }
}
// MARK: - Collations
/// Add or redefine a collation.
///
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// snapshot.add(collation: collation)
/// let files = try snapshot.read { db in
/// try File.fetchAll(db, "SELECT * FROM file ORDER BY name COLLATE localized_standard")
/// }
public func add(collation: DatabaseCollation) {
serializedDatabase.sync { $0.add(collation: collation) }
}
/// Remove a collation.
public func remove(collation: DatabaseCollation) {
serializedDatabase.sync { $0.remove(collation: collation) }
}
// MARK: - Value Observation
public func add<Value>(
observation: ValueObservation<Value>,
onError: ((Error) -> Void)? = nil,
onChange: @escaping (Value) -> Void) throws -> TransactionObserver
{
// Deal with initial value
switch observation.initialDispatch {
case .none:
break
case .deferred:
let initialValue = try unsafeReentrantRead { try observation.read($0) }
observation.queue.async {
onChange(initialValue)
}
case .immediateOnCurrentQueue:
let initialValue = try unsafeReentrantRead { try observation.read($0) }
onChange(initialValue)
}
// Return a dummy observer, because snapshots never change
return SnapshotValueObserver()
}
}
/// An observer that does nothing, support for
/// `DatabaseSnapshot.add(observation:onError:onChange:)`.
private class SnapshotValueObserver: TransactionObserver {
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
func databaseDidChange(with event: DatabaseEvent) { }
func databaseDidCommit(_ db: Database) { }
func databaseDidRollback(_ db: Database) { }
}
+125
View File
@@ -229,6 +229,131 @@ extension DatabaseWriter {
}
}
/// The database transaction observer, support for ValueObservation.
private class ValueObserver<Value>: TransactionObserver {
private let region: DatabaseRegion
private let future: () -> Future<Value>
private let queue: DispatchQueue
private let onChange: (Value) -> Void
private let onError: ((Error) -> Void)?
private let notificationQueue = DispatchQueue(label: "ValueObserver")
private var changed = false
init(
region: DatabaseRegion,
future: @escaping () -> Future<Value>,
queue: DispatchQueue,
onError: ((Error) -> Void)?,
onChange: @escaping (Value) -> Void)
{
self.region = region
self.future = future
self.queue = queue
self.onChange = onChange
self.onError = onError
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return region.isModified(byEventsOfKind: eventKind)
}
func databaseDidChange(with event: DatabaseEvent) {
if region.isModified(by: event) {
changed = true
stopObservingDatabaseChangesUntilNextTransaction()
}
}
func databaseDidCommit(_ db: Database) {
guard changed else {
return
}
changed = false
// Fetch future value now, from the database writer queue
let futureValue = future()
// Wait for future value in notificationQueue, in order to guarantee
// that notifications have the same ordering as transactions.
notificationQueue.async { [weak self] in
guard let strongSelf = self else { return }
do {
let value = try futureValue.wait()
strongSelf.queue.async {
guard let strongSelf = self else { return }
strongSelf.onChange(value)
}
} catch {
strongSelf.queue.async {
guard let strongSelf = self else { return }
strongSelf.onError?(error)
}
}
}
}
func databaseDidRollback(_ db: Database) {
changed = false
}
}
extension DatabaseWriter {
public func add<Value>(
observation: ValueObservation<Value>,
onError: ((Error) -> Void)? = nil,
onChange: @escaping (Value) -> Void)
throws -> TransactionObserver
{
// Will be set and notified on the caller queue if initialDispatch is .immediateOnCurrentQueue
var immediateValue: Value? = nil
defer {
if let immediateValue = immediateValue {
onChange(immediateValue)
}
}
// Enter database in order to start observation, and fetch initial
// value if needed.
//
// We use an unsafe reentrant method so that this initializer can be
// called from a database queue.
return try unsafeReentrantWrite { db in
// Start observing the database (take care of future transactions
// that change the observed region).
//
// Observation stops when transactionObserver is deallocated,
// which happens when self is deallocated.
let transactionObserver = try ValueObserver(
region: observation.observedRegion(db),
future: { [unowned self] in self.concurrentRead { try observation.read($0) } },
queue: observation.queue,
onError: onError,
onChange: onChange)
db.add(transactionObserver: transactionObserver, extent: observation.extent)
switch observation.initialDispatch {
case .none:
break
case .immediateOnCurrentQueue:
immediateValue = try observation.read(db)
case .deferred:
// We're still on the database writer queue. Let's dispatch
// initial value right now, before any future transaction has
// any opportunity to trigger a change notification, and mess
// with the ordering of value notifications.
let initialValue = try observation.read(db)
observation.queue.async {
onChange(initialValue)
}
}
return transactionObserver
}
}
}
/// A future value.
public class Future<Value> {
private var consumed = false
+2 -128
View File
@@ -19,140 +19,14 @@ public enum InitialDispatch {
case deferred
}
/// The database transaction observer, generic on the type of fetched values.
private class ValueObserver<T>: TransactionObserver {
private let region: DatabaseRegion
private let future: () -> Future<T>
private let queue: DispatchQueue
private let onChange: (T) -> Void
private let onError: ((Error) -> Void)?
private let notificationQueue = DispatchQueue(label: "ValueObserver")
private var changed = false
init(
region: DatabaseRegion,
future: @escaping () -> Future<T>,
queue: DispatchQueue,
onError: ((Error) -> Void)?,
onChange: @escaping (T) -> Void)
{
self.region = region
self.future = future
self.queue = queue
self.onChange = onChange
self.onError = onError
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return region.isModified(byEventsOfKind: eventKind)
}
func databaseDidChange(with event: DatabaseEvent) {
if region.isModified(by: event) {
changed = true
stopObservingDatabaseChangesUntilNextTransaction()
}
}
func databaseDidCommit(_ db: Database) {
guard changed else {
return
}
changed = false
// Fetch future results now...
let future = self.future()
// ...but wait for them in notificationQueue, which guarantees
// that notifications have the same ordering as transactions.
notificationQueue.async { [weak self] in
guard let strongSelf = self else { return }
do {
// block notificationQueue until the concurrent fetch is done
let result = try future.wait()
strongSelf.queue.async {
guard let strongSelf = self else { return }
strongSelf.onChange(result)
}
} catch {
strongSelf.queue.async {
guard let strongSelf = self else { return }
strongSelf.onError?(error)
}
}
}
}
func databaseDidRollback(_ db: Database) {
changed = false
}
}
extension DatabaseWriter {
/// TODO
public func add<Value>(
observation: ValueObservation<Value>,
onError: ((Error) -> Void)? = nil,
onChange: @escaping (Value) -> Void)
throws -> TransactionObserver
{
// Will be set and notified on the caller queue if initialDispatch is .immediateOnCurrentQueue
var immediateValue: Value? = nil
defer {
if let immediateValue = immediateValue {
onChange(immediateValue)
}
}
// Enter database in order to start observation, and fetch initial
// value if needed.
//
// We use an unsafe reentrant method so that this initializer can be
// called from a database queue.
return try unsafeReentrantWrite { db in
// Start observing the database (take care of future transactions
// that change the observed region).
//
// Observation stops when transactionObserver is deallocated,
// which happens when self is deallocated.
let transactionObserver = try ValueObserver(
region: observation.observedRegion(db),
future: { [unowned self] in self.concurrentRead { try observation.read($0) } },
queue: observation.queue,
onError: onError,
onChange: onChange)
db.add(transactionObserver: transactionObserver, extent: observation.extent)
switch observation.initialDispatch {
case .none:
break
case .immediateOnCurrentQueue:
immediateValue = try observation.read(db)
case .deferred:
let initialValue = try observation.read(db)
// We're still on the database writer queue. Let's dispatch
// initial value now, before any future transaction has any
// opportunity to trigger a change notification.
observation.queue.async {
onChange(initialValue)
}
}
return transactionObserver
}
}
}
/// TODO
public struct ValueObservation<Value> {
/// A closure that is evaluated when the observation startst, and returns
/// the observed database region.
fileprivate var observedRegion: (Database) throws -> DatabaseRegion
var observedRegion: (Database) throws -> DatabaseRegion
/// A closure that fetches fresh results whenever the database changes.
fileprivate var read: (Database) throws -> Value
var read: (Database) throws -> Value
/// The extent of the database observation. The default is
/// `.observerLifetime`: once started, the observation lasts until the