You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
397 lines
12 KiB
397 lines
12 KiB
//
|
|
// StoredCollection.swift
|
|
// LeStorage
|
|
//
|
|
// Created by Laurent Morvillier on 02/02/2024.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
protocol CollectionHolder {
|
|
associatedtype Item
|
|
|
|
var items: [Item] { get }
|
|
func reset()
|
|
}
|
|
|
|
protocol SomeCollection: CollectionHolder, Identifiable {
|
|
var resourceName: String { get }
|
|
var hasLoaded: Bool { get }
|
|
var inMemory: Bool { get }
|
|
|
|
func allItems() -> [any Storable]
|
|
func referenceCount<S: Storable>(type: S.Type, id: String) -> Int
|
|
}
|
|
|
|
protocol SomeSyncedCollection: SomeCollection {
|
|
func loadDataFromServerIfAllowed() async throws
|
|
func loadCollectionsFromServerIfNoFile() async throws
|
|
}
|
|
|
|
extension Notification.Name {
|
|
public static let CollectionDidLoad: Notification.Name = Notification.Name.init(
|
|
"notification.collectionDidLoad")
|
|
public static let CollectionDidChange: Notification.Name = Notification.Name.init(
|
|
"notification.collectionDidChange")
|
|
}
|
|
|
|
public class StoredCollection<T: Storable>: RandomAccessCollection, SomeCollection, CollectionHolder
|
|
{
|
|
|
|
/// Doesn't write the collection in a file
|
|
fileprivate(set) var inMemory: Bool = false
|
|
|
|
/// The list of stored items
|
|
@Published public fileprivate(set) var items: [T] = []
|
|
|
|
/// The reference to the Store
|
|
fileprivate(set) var store: Store
|
|
|
|
/// Provides fast access for instances if the collection has been instanced with [indexed] = true
|
|
fileprivate var _indexes: [T.ID: T]? = nil
|
|
|
|
/// Indicates whether the collection has changed, thus requiring a write operation
|
|
fileprivate var _hasChanged: Bool = false {
|
|
didSet {
|
|
if self._hasChanged == true {
|
|
|
|
self._scheduleWrite()
|
|
DispatchQueue.main.async {
|
|
NotificationCenter.default.post(
|
|
name: NSNotification.Name.CollectionDidChange, object: self)
|
|
}
|
|
self._hasChanged = false
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Indicates if the collection has loaded locally, with or without a file
|
|
fileprivate(set) public var hasLoaded: Bool = false
|
|
|
|
fileprivate(set) var limit: Int? = nil
|
|
|
|
|
|
init(store: Store, indexed: Bool = false, inMemory: Bool = false, limit: Int? = nil) {
|
|
if indexed {
|
|
self._indexes = [:]
|
|
}
|
|
self.inMemory = inMemory
|
|
self.store = store
|
|
self.limit = limit
|
|
|
|
self.load()
|
|
}
|
|
|
|
fileprivate init() {
|
|
// self.synchronized = false
|
|
self.store = Store.main
|
|
}
|
|
|
|
/// Returns a dummy StoredCollection instance
|
|
public static func placeholder() -> StoredCollection<T> {
|
|
return StoredCollection<T>()
|
|
}
|
|
|
|
/// Returns the name of the managed resource
|
|
var resourceName: String {
|
|
return T.resourceName()
|
|
}
|
|
|
|
// MARK: - Loading
|
|
|
|
/// Sets the collection as changed to trigger a write
|
|
func setChanged() {
|
|
self._hasChanged = true
|
|
}
|
|
|
|
/// Migrates if necessary and asynchronously decodes the json file
|
|
func load() {
|
|
|
|
do {
|
|
if !self.inMemory {
|
|
try self.loadFromFile()
|
|
}
|
|
} catch {
|
|
Logger.error(error)
|
|
}
|
|
|
|
}
|
|
|
|
/// Starts the JSON file decoding synchronously or asynchronously
|
|
func loadFromFile() throws {
|
|
try self._decodeJSONFile()
|
|
}
|
|
|
|
/// Decodes the json file into the items array
|
|
fileprivate func _decodeJSONFile() throws {
|
|
|
|
let fileURL = try self.store.fileURL(type: T.self)
|
|
|
|
if FileManager.default.fileExists(atPath: fileURL.path()) {
|
|
let jsonString: String = try FileUtils.readFile(fileURL: fileURL)
|
|
let decoded: [T] = try jsonString.decodeArray() ?? []
|
|
for item in decoded {
|
|
item.store = self.store
|
|
}
|
|
self._setItems(decoded)
|
|
}
|
|
self.setAsLoaded()
|
|
}
|
|
|
|
/// Sets the collection as loaded
|
|
/// Send a CollectionDidLoad event
|
|
func setAsLoaded() {
|
|
self.hasLoaded = true
|
|
DispatchQueue.main.async {
|
|
NotificationCenter.default.post(
|
|
name: NSNotification.Name.CollectionDidLoad, object: self)
|
|
}
|
|
}
|
|
|
|
/// Sets a collection of items and indexes them
|
|
fileprivate func _setItems(_ items: [T]) {
|
|
self.items = items
|
|
self._updateIndexIfNecessary()
|
|
}
|
|
|
|
/// Updates the whole index with the items array
|
|
fileprivate func _updateIndexIfNecessary() {
|
|
if self._indexes != nil {
|
|
self._indexes = self.items.dictionary { $0.id }
|
|
}
|
|
}
|
|
|
|
// MARK: - Basic operations
|
|
|
|
/// Adds or updates the provided instance inside the collection
|
|
/// Adds it if its id is not found, and otherwise updates it
|
|
public func addOrUpdate(instance: T) {
|
|
self.addOrUpdateItem(instance: instance)
|
|
}
|
|
|
|
/// Adds or update an instance inside the collection and writes
|
|
func addOrUpdateItem(instance: T) {
|
|
|
|
defer {
|
|
self._hasChanged = true
|
|
}
|
|
|
|
if let index = self.items.firstIndex(where: { $0.id == instance.id }) {
|
|
self.updateItem(instance, index: index)
|
|
} else {
|
|
self.addItem(instance: instance)
|
|
}
|
|
|
|
}
|
|
|
|
/// A method the treat the collection as a single instance holder
|
|
func setSingletonNoSync(instance: T) {
|
|
defer {
|
|
self._hasChanged = true
|
|
}
|
|
self.items.removeAll()
|
|
self.addItem(instance: instance)
|
|
}
|
|
|
|
/// Deletes an item by its id
|
|
func deleteById(_ id: T.ID) {
|
|
if let instance = self.findById(id) {
|
|
self.delete(instance: instance)
|
|
}
|
|
}
|
|
|
|
/// Deletes the instance in the collection and sets the collection as changed to trigger a write
|
|
public func delete(instance: T) {
|
|
defer {
|
|
self._hasChanged = true
|
|
}
|
|
self.deleteItem(instance)
|
|
}
|
|
|
|
/// Deletes all items of the sequence by id and sets the collection as changed to trigger a write
|
|
public func delete(contentOfs sequence: any Sequence<T>) {
|
|
|
|
defer {
|
|
self._hasChanged = true
|
|
}
|
|
|
|
for instance in sequence {
|
|
self.deleteItem(instance)
|
|
}
|
|
}
|
|
|
|
/// Adds or update a sequence of elements
|
|
public func addOrUpdate(contentOfs sequence: any Sequence<T>) {
|
|
self.addSequence(sequence)
|
|
// self._addOrUpdate(contentOfs: sequence)
|
|
}
|
|
|
|
/// Adds a sequence of objects inside the collection and performs a write
|
|
func addSequence(_ sequence: any Sequence<T>) {
|
|
defer {
|
|
self._hasChanged = true
|
|
}
|
|
|
|
for instance in sequence {
|
|
if let index = self.items.firstIndex(where: { $0.id == instance.id }) {
|
|
self.updateItem(instance, index: index)
|
|
} else { // insert
|
|
self.addItem(instance: instance)
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
/// This method sets the storeId for the given instance if the collection belongs to a store with an id
|
|
fileprivate func _affectStoreIdIfNecessary(instance: T) {
|
|
if let storeId = self.store.identifier {
|
|
if var altStorable = instance as? SideStorable {
|
|
altStorable.storeId = storeId
|
|
} else {
|
|
fatalError("instance does not implement AltStorable, thus sync cannot work")
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Adds an instance to the collection
|
|
func addItem(instance: T) {
|
|
self._affectStoreIdIfNecessary(instance: instance)
|
|
self.items.append(instance)
|
|
instance.store = self.store
|
|
self._indexes?[instance.id] = instance
|
|
self._applyLimitIfPresent()
|
|
}
|
|
|
|
/// Updates an instance to the collection by index
|
|
func updateItem(_ instance: T, index: Int) {
|
|
self.items[index].copy(from: instance)
|
|
instance.store = self.store
|
|
self._indexes?[instance.id] = instance
|
|
}
|
|
|
|
/// Deletes an instance from the collection
|
|
func deleteItem(_ instance: T) {
|
|
instance.deleteDependencies()
|
|
self.items.removeAll { $0.id == instance.id }
|
|
self._indexes?.removeValue(forKey: instance.id)
|
|
}
|
|
|
|
/// If the collection has more instance that its limit, remove the surplus
|
|
fileprivate func _applyLimitIfPresent() {
|
|
if let limit {
|
|
self.items = self.items.suffix(limit)
|
|
}
|
|
}
|
|
|
|
/// Returns the instance corresponding to the provided [id]
|
|
public func findById(_ id: T.ID) -> T? {
|
|
if let index = self._indexes, let instance = index[id] {
|
|
return instance
|
|
}
|
|
return self.items.first(where: { $0.id == id })
|
|
}
|
|
|
|
/// Proceeds to "hard" delete the items without synchronizing them
|
|
/// Also removes related API calls
|
|
public func deleteDependencies(_ items: any Sequence<T>) {
|
|
defer {
|
|
self._hasChanged = true
|
|
}
|
|
let itemsArray = Array(items) // fix error if items is self.items
|
|
for item in itemsArray {
|
|
if let index = self.items.firstIndex(where: { $0.id == item.id }) {
|
|
self.items.remove(at: index)
|
|
}
|
|
|
|
// Task {
|
|
// do {
|
|
// try await StoreCenter.main.deleteApiCallByDataId(type: T.self, id: item.stringId)
|
|
// } catch {
|
|
// Logger.error(error)
|
|
// }
|
|
// }
|
|
}
|
|
|
|
}
|
|
|
|
/// Proceeds to delete all instance of the collection, properly cleaning up dependencies and sending API calls
|
|
public func deleteAll() throws {
|
|
self.delete(contentOfs: self.items)
|
|
}
|
|
|
|
// MARK: - SomeCall
|
|
|
|
/// Returns the collection items as [any Storable]
|
|
func allItems() -> [any Storable] {
|
|
return self.items
|
|
}
|
|
|
|
// MARK: - File access
|
|
|
|
/// Schedules a write operation
|
|
fileprivate func _scheduleWrite() {
|
|
|
|
guard !self.inMemory else { return }
|
|
|
|
DispatchQueue(label: "lestorage.queue.write", qos: .utility).asyncAndWait { // sync to make sure we don't have writes performed at the same time
|
|
self._write()
|
|
}
|
|
}
|
|
|
|
/// Writes all the items as a json array inside a file
|
|
fileprivate func _write() {
|
|
do {
|
|
let jsonString: String = try self.items.jsonString()
|
|
try self.store.write(content: jsonString, fileName: T.fileName())
|
|
} catch {
|
|
Logger.error(error)
|
|
StoreCenter.main.log(message: "write failed for \(T.resourceName()): \(error.localizedDescription)")
|
|
}
|
|
}
|
|
|
|
/// Simply clears the items of the collection
|
|
func clear() {
|
|
self.items.removeAll()
|
|
}
|
|
|
|
/// Removes the items of the collection and deletes the corresponding file
|
|
public func reset() {
|
|
self.items.removeAll()
|
|
self.store.removeFile(type: T.self)
|
|
}
|
|
|
|
// MARK: - Reference count
|
|
|
|
/// Counts the references to an object - given its type and id - inside the collection
|
|
func referenceCount<S: Storable>(type: S.Type, id: String) -> Int {
|
|
let relationships = T.relationships().filter { $0.type == type }
|
|
guard relationships.count > 0 else { return 0 }
|
|
|
|
return self.items.reduce(0) { count, item in
|
|
count + relationships.filter { relationship in
|
|
(item[keyPath: relationship.keyPath] as? String) == id
|
|
}.count
|
|
}
|
|
}
|
|
|
|
// MARK: - RandomAccessCollection
|
|
|
|
public var startIndex: Int { return self.items.startIndex }
|
|
|
|
public var endIndex: Int { return self.items.endIndex }
|
|
|
|
public func index(after i: Int) -> Int {
|
|
return self.items.index(after: i)
|
|
}
|
|
|
|
open subscript(index: Int) -> T {
|
|
get {
|
|
return self.items[index]
|
|
}
|
|
set(newValue) {
|
|
self.items[index] = newValue
|
|
self._hasChanged = true
|
|
}
|
|
}
|
|
|
|
}
|
|
|