improvements

sync2
Laurent 9 months ago
parent 64130849e8
commit 190528e964
  1. 73
      LeStorage/ApiCallCollection.swift
  2. 5
      LeStorage/StoreCenter.swift
  3. 2
      LeStorage/StoredCollection+Sync.swift
  4. 2
      LeStorage/StoredCollection.swift

@ -163,7 +163,7 @@ actor ApiCallCollection<T: SyncedStorable>: SomeCallCollection {
/// Reschedule API calls if necessary
func rescheduleApiCallsIfNecessary() {
if self.items.isNotEmpty {
if self.items.isNotEmpty && !self._isRescheduling {
self._schedulingTask = Task {
await self._rescheduleApiCalls()
}
@ -190,44 +190,16 @@ actor ApiCallCollection<T: SyncedStorable>: SomeCallCollection {
if batch.count == 1, let apiCall = batch.first, apiCall.method == .get {
let _: Empty = try await self._executeGetCall(apiCall)
} else {
let success = try await self._executeApiCalls(batch)
let results = try await self._executeApiCalls(batch)
if T.copyServerResponse {
StoreCenter.main.updateLocalInstances(success)
StoreCenter.main.updateLocalInstances(results)
}
self._attemptLoops = -1
}
self._attemptLoops = -1
} catch {
Logger.error(error)
}
}
// let apiCallsCopy = self.items
// for apiCall in apiCallsCopy {
// apiCall.attemptsCount += 1
// apiCall.lastAttemptDate = Date()
//
// do {
// switch apiCall.method {
// case .post:
// let result: T = try await self._executeApiCall(apiCall)
// StoreCenter.main.updateFromServerInstance(result)
//// Logger.log("\(T.resourceName()) > SUCCESS!")
// case .put:
// let _: T = try await self._executeApiCall(apiCall)
// case .delete:
// let _: Empty = try await self._executeApiCall(apiCall)
// case .get:
// if T.self == GetSyncData.self {
// let _: Empty = try await self._executeApiCall(apiCall)
// } else {
// let _: [T] = try await self._executeApiCall(apiCall)
// }
// }
// } catch {
//// Logger.log("\(T.resourceName()) > API CALL RETRY ERROR:")
//// Logger.error(error)
// }
// }
self._isRescheduling = false
if self.items.isNotEmpty {
@ -339,43 +311,6 @@ actor ApiCallCollection<T: SyncedStorable>: SomeCallCollection {
return try await self._executeApiCalls(apiCalls)
}
/// Sends an insert api call for the provided [instance]
// func sendInsertion(_ instance: T) async throws -> T? {
// do {
// return try await self._sendServerRequest(HTTPMethod.post, instance: instance)
// } catch {
// self.rescheduleApiCallsIfNecessary()
// StoreCenter.main.log(message: "POST failed for \(instance): \(error.localizedDescription)")
// Logger.error(error)
// }
// return nil
//
// }
//
// /// Sends an update api call for the provided [instance]
// func sendUpdate(_ instance: T) async throws -> T? {
// do {
// return try await self._sendServerRequest(HTTPMethod.put, instance: instance)
// } catch {
// self.rescheduleApiCallsIfNecessary()
// StoreCenter.main.log(message: "PUT failed for \(instance): \(error.localizedDescription)")
// Logger.error(error)
// }
// return nil
// }
//
// /// Sends an delete api call for the provided [instance]
// func sendDeletion(_ instance: T) async throws {
// do {
// let _: Empty? = try await self._sendServerRequest(HTTPMethod.delete, instance: instance)
// } catch {
// self.rescheduleApiCallsIfNecessary()
// StoreCenter.main.log(message: "DELETE failed for \(instance): \(error.localizedDescription)")
// Logger.error(error)
// }
// return
// }
/// Initiates the process of sending the data with the server
fileprivate func _sendServerRequest<V: Decodable>(_ method: HTTPMethod, instance: T? = nil) async throws -> V? {
if let apiCall = try self._call(method: method, instance: instance) {

@ -256,6 +256,8 @@ public class StoreCenter {
Task {
do {
try await apiCallCollection.loadFromFile()
let count = await apiCallCollection.items.count
Logger.log("collection \(T.resourceName()) loaded with \(count)")
await apiCallCollection.rescheduleApiCallsIfNecessary()
} catch {
Logger.error(error)
@ -539,10 +541,12 @@ public class StoreCenter {
/// - shared: indicates if the content should be flagged as shared
@MainActor func _parseSyncUpdates(_ updates: [String: Any], shared: Bool = false) throws {
for (className, updateData) in updates {
guard let updateArray = updateData as? [[String: Any]] else {
Logger.w("Invalid update data for \(className)")
continue
}
// Logger.log(">>> UPDATE \(updateArray.count) \(className)")
let type = try StoreCenter.classFromName(className)
@ -552,6 +556,7 @@ public class StoreCenter {
let jsonData = try JSONSerialization.data(
withJSONObject: updateItem, options: [])
let decodedObject = try JSON.decoder.decode(type, from: jsonData)
// Logger.log(">>> \(decodedObject.lastUpdate.timeIntervalSince1970) : \(decodedObject.id)")
let storeId: String? = decodedObject.getStoreId()
StoreCenter.main.synchronizationAddOrUpdate(decodedObject, storeId: storeId, shared: shared)

@ -275,6 +275,8 @@ extension StoredCollection: SomeSyncedCollection where T : SyncedStorable {
let localInstance = self.items[index]
if instance.lastUpdate > localInstance.lastUpdate {
self.updateItem(instance, index: index)
} else {
Logger.log("dont update: \(instance.lastUpdate.timeIntervalSince1970) / \(localInstance.lastUpdate.timeIntervalSince1970)")
}
} else { // insert
if shared {

@ -241,7 +241,7 @@ public class StoredCollection<T: Storable>: RandomAccessCollection, SomeCollecti
if var altStorable = instance as? SideStorable {
altStorable.storeId = storeId
} else {
fatalError("instance does not implement AltStorable, thus sync cannot work")
fatalError("instance does not implement SideStorable, thus sync cannot work")
}
}
}

Loading…
Cancel
Save