Просмотр исходного кода

rewrite FileStorage with sync methods

Ivan Valkou 5 лет назад
Родитель
Сommit
580f82154d

+ 9 - 2
FreeAPS/Sources/APS/BaseAPSManager.swift

@@ -1,5 +1,12 @@
-final class BaseAPSManager: APSManager {
-    private let openAPS = OpenAPS()
+import Swinject
+
+final class BaseAPSManager: APSManager, Injectable {
+    private var openAPS: OpenAPS!
+
+    init(resolver: Resolver) {
+        injectServices(resolver)
+        openAPS = OpenAPS(storage: resolver.resolve(FileStorage.self)!)
+    }
 
     func runTest() {
         openAPS.test()

+ 2 - 2
FreeAPS/Sources/APS/OpenAPS/JavaScriptWorker.swift

@@ -31,11 +31,11 @@ final class JavaScriptWorker {
         return ctx.evaluateScript(string)
     }
 
-    private func json(for string: String) -> JSON {
+    private func json(for string: String) -> RawJSON {
         evaluate(string: "JSON.stringify(\(string));")!.toString()!
     }
 
-    func call(function: String, with arguments: [JSON]) -> JSON {
+    func call(function: String, with arguments: [JSON]) -> RawJSON {
         let joined = arguments.map(\.string).joined(separator: ",")
         return json(for: "\(function)(\(joined))")
     }

+ 28 - 18
FreeAPS/Sources/APS/OpenAPS/OpenAPS.swift

@@ -5,6 +5,12 @@ final class OpenAPS {
     private let jsWorker = JavaScriptWorker()
     private let processQueue = DispatchQueue(label: "OpenAPS.processQueue", qos: .utility)
 
+    private let storage: FileStorage
+
+    init(storage: FileStorage) {
+        self.storage = storage
+    }
+
     func test() {
         processQueue.async {
             let now = Date()
@@ -79,12 +85,16 @@ final class OpenAPS {
             )
             print("AUTOTUNE PREP: \(autotunePreppedGlucose)")
 
+            let previousAutotune = try? self.storage.retrieve("autotune.json", as: RawJSON.self)
+
             let autotuneResult = self.autotuneRun(
-                autotuneprepareddata: autotunePreppedGlucose,
-                previousautotuneresult: profile,
-                pumpprofile: profile
+                autotunePreparedData: autotunePreppedGlucose,
+                previousAutotuneResult: previousAutotune ?? profile,
+                pumpProfile: profile
             )
 
+            try? self.storage.save(autotuneResult, as: "autotune.json")
+
             print("AUTOTUNE RESULT: \(autotuneResult)")
 
             let finishDate = Date()
@@ -92,7 +102,7 @@ final class OpenAPS {
         }
     }
 
-    private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON, pumphistory24: JSON) -> JSON {
+    private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON, pumphistory24: JSON) -> RawJSON {
         dispatchPrecondition(condition: .onQueue(processQueue))
         return jsWorker.inCommonContext { worker in
             worker.evaluate(script: Script(name: "bundle/iob"))
@@ -107,7 +117,7 @@ final class OpenAPS {
         }
     }
 
-    private func meal(pumphistory: JSON, profile: JSON, basalProfile: JSON, clock: JSON, carbs: JSON, glucose: JSON) -> JSON {
+    private func meal(pumphistory: JSON, profile: JSON, basalProfile: JSON, clock: JSON, carbs: JSON, glucose: JSON) -> RawJSON {
         dispatchPrecondition(condition: .onQueue(processQueue))
         return jsWorker.inCommonContext { worker in
             worker.evaluate(script: Script(name: "bundle/meal"))
@@ -130,7 +140,7 @@ final class OpenAPS {
         pumpprofile: JSON,
         categorizeUamAsBasal: Bool,
         tuneInsulinCurve: Bool
-    ) -> JSON {
+    ) -> RawJSON {
         dispatchPrecondition(condition: .onQueue(processQueue))
         return jsWorker.inCommonContext { worker in
             worker.evaluate(script: Script(name: "bundle/autotune-prep"))
@@ -147,23 +157,23 @@ final class OpenAPS {
     }
 
     private func autotuneRun(
-        autotuneprepareddata: JSON,
-        previousautotuneresult: JSON,
-        pumpprofile: JSON
-    ) -> JSON {
+        autotunePreparedData: JSON,
+        previousAutotuneResult: JSON,
+        pumpProfile: JSON
+    ) -> RawJSON {
         dispatchPrecondition(condition: .onQueue(processQueue))
         return jsWorker.inCommonContext { worker in
             worker.evaluate(script: Script(name: "bundle/autotune-core"))
             worker.evaluate(script: Script(name: "prepare/autotune-core"))
             return worker.call(function: "generate", with: [
-                autotuneprepareddata,
-                previousautotuneresult,
-                pumpprofile
+                autotunePreparedData,
+                previousAutotuneResult,
+                pumpProfile
             ])
         }
     }
 
-    private func glucoseGetLast(glucose: JSON) -> JSON {
+    private func glucoseGetLast(glucose: JSON) -> RawJSON {
         dispatchPrecondition(condition: .onQueue(processQueue))
         return jsWorker.inCommonContext { worker in
             worker.evaluate(script: Script(name: "bundle/glucose-get-last"))
@@ -181,7 +191,7 @@ final class OpenAPS {
         microBolusAllowed: Bool,
         reservoir: Int,
         tsMilliseconds: Double
-    ) -> JSON {
+    ) -> RawJSON {
         dispatchPrecondition(condition: .onQueue(processQueue))
         return jsWorker.inCommonContext { worker in
             worker.evaluate(script: Script(name: "bundle/basal-set-temp"))
@@ -214,7 +224,7 @@ final class OpenAPS {
         glucose: JSON,
         basalprofile: JSON,
         temptargets: JSON
-    ) -> JSON {
+    ) -> RawJSON {
         dispatchPrecondition(condition: .onQueue(processQueue))
         return jsWorker.inCommonContext { worker in
             worker.evaluate(script: Script(name: "bundle/autosens"))
@@ -234,7 +244,7 @@ final class OpenAPS {
         }
     }
 
-    private func exportDefaultPreferences() -> JSON {
+    private func exportDefaultPreferences() -> RawJSON {
         dispatchPrecondition(condition: .onQueue(processQueue))
         return jsWorker.inCommonContext { worker in
             worker.evaluate(script: Script(name: "bundle/profile"))
@@ -253,7 +263,7 @@ final class OpenAPS {
         tempTargets: JSON,
         model: JSON,
         autotune: JSON
-    ) -> JSON {
+    ) -> RawJSON {
         dispatchPrecondition(condition: .onQueue(processQueue))
         return jsWorker.inCommonContext { worker in
             worker.evaluate(script: Script(name: "bundle/profile"))

+ 1 - 1
FreeAPS/Sources/Containers/ServiceContainer.swift

@@ -5,6 +5,6 @@ private let resolver = FreeAPSApp.resolver
 
 enum ServiceContainer: DependeciesContainer {
     static func register(container: Container) {
-        container.register(APSManager.self) { _ in BaseAPSManager() }
+        container.register(APSManager.self) { _ in BaseAPSManager(resolver: resolver) }
     }
 }

+ 2 - 0
FreeAPS/Sources/Helpers/JSON.swift

@@ -48,3 +48,5 @@ extension Date: JSON {
         }
     }
 }
+
+typealias RawJSON = String

+ 28 - 11
FreeAPS/Sources/Services/Storage/FileStorage.swift

@@ -3,21 +3,30 @@ import Disk
 import Foundation
 
 protocol FileStorage {
-    func save<Value: JSON>(_: Value, as name: String) -> AnyPublisher<Void, Error>
-    func retrieve<Value: JSON>(_: String, as type: Value.Type) -> AnyPublisher<Value, Error>
-    func append<Value: JSON>(_: Value, to name: String) -> AnyPublisher<Void, Error>
+    func save<Value: JSON>(_ value: Value, as name: String) throws
+    func savePublisher<Value: JSON>(_: Value, as name: String) -> AnyPublisher<Void, Error>
+
+    func retrieve<Value: JSON>(_ name: String, as type: Value.Type) throws -> Value
+    func retrievePublisher<Value: JSON>(_: String, as type: Value.Type) -> AnyPublisher<Value, Error>
+
+    func append<Value: JSON>(_ newValue: Value, to name: String) throws
+    func appendPublisher<Value: JSON>(_: Value, to name: String) -> AnyPublisher<Void, Error>
 }
 
 final class BaseFileStorage: FileStorage {
     private let processQueue = DispatchQueue(label: "BaseFileStorage.processQueue")
 
-    func save<Value: JSON>(_ value: Value, as name: String) -> AnyPublisher<Void, Error> {
+    func save<Value: JSON>(_ value: Value, as name: String) throws {
+        let encoder = JSONEncoder()
+        encoder.outputFormatting = .prettyPrinted
+        try Disk.save(value, to: .documents, as: name, encoder: encoder)
+    }
+
+    func savePublisher<Value: JSON>(_ value: Value, as name: String) -> AnyPublisher<Void, Error> {
         Future { promise in
             self.processQueue.async {
                 do {
-                    let encoder = JSONEncoder()
-                    encoder.outputFormatting = .prettyPrinted
-                    try Disk.save(value, to: .documents, as: name, encoder: encoder)
+                    try self.save(value, as: name)
                     promise(.success(()))
                 } catch {
                     promise(.failure(error))
@@ -27,11 +36,15 @@ final class BaseFileStorage: FileStorage {
         .eraseToAnyPublisher()
     }
 
-    func retrieve<Value: JSON>(_ name: String, as type: Value.Type) -> AnyPublisher<Value, Error> {
+    func retrieve<Value: JSON>(_ name: String, as type: Value.Type) throws -> Value {
+        try Disk.retrieve(name, from: .documents, as: type)
+    }
+
+    func retrievePublisher<Value: JSON>(_ name: String, as type: Value.Type) -> AnyPublisher<Value, Error> {
         Future { promise in
             self.processQueue.async {
                 do {
-                    let value = try Disk.retrieve(name, from: .documents, as: type)
+                    let value = try self.retrieve(name, as: type)
                     promise(.success(value))
                 } catch {
                     promise(.failure(error))
@@ -41,11 +54,15 @@ final class BaseFileStorage: FileStorage {
         .eraseToAnyPublisher()
     }
 
-    func append<Value: JSON>(_ newValue: Value, to name: String) -> AnyPublisher<Void, Error> {
+    func append<Value: JSON>(_ newValue: Value, to name: String) throws {
+        try Disk.append(newValue, to: name, in: .documents)
+    }
+
+    func appendPublisher<Value: JSON>(_ newValue: Value, to name: String) -> AnyPublisher<Void, Error> {
         Future { promise in
             self.processQueue.async {
                 do {
-                    try Disk.append(newValue, to: name, in: .documents)
+                    try self.append(newValue, to: name)
                     promise(.success(()))
                 } catch {
                     promise(.failure(error))