From 3720dd21d079f3026646809667bb887a722fbad2 Mon Sep 17 00:00:00 2001 From: Fabrizio Demaria Date: Mon, 15 Apr 2024 14:44:13 +0200 Subject: [PATCH] Main rebase --- Sources/Common/Backport.swift | 36 +------ Sources/Confidence/Confidence.swift | 100 ++++++++++-------- .../ConfidenceClient/ConfidenceClient.swift | 8 +- .../RemoteConfidenceClient.swift | 18 ++-- Sources/Confidence/EventSenderEngine.swift | 27 ++--- Sources/Confidence/EventSenderStorage.swift | 15 --- Sources/Confidence/EventStorage.swift | 25 +++-- Sources/Confidence/EventStorageInMemory.swift | 27 +++++ Sources/Confidence/SizeFlushPolicy.swift | 22 ++++ .../EventSenderEngineTest.swift | 11 +- .../EventUploaderMock.swift | 12 +-- Tests/ConfidenceTests/ConfidenceTests.swift | 44 ++++---- Tests/ConfidenceTests/EventStorageTests.swift | 23 ++-- .../Helpers/ConfidenceClientMock.swift | 2 +- .../Helpers/EventSenderEngineMock.swift | 12 +++ .../RemooteConfidenceClientTests.swift | 36 +++---- 16 files changed, 202 insertions(+), 216 deletions(-) delete mode 100644 Sources/Confidence/EventSenderStorage.swift create mode 100644 Sources/Confidence/EventStorageInMemory.swift create mode 100644 Sources/Confidence/SizeFlushPolicy.swift create mode 100644 Tests/ConfidenceTests/Helpers/EventSenderEngineMock.swift diff --git a/Sources/Common/Backport.swift b/Sources/Common/Backport.swift index 857de563..2b069b0c 100644 --- a/Sources/Common/Backport.swift +++ b/Sources/Common/Backport.swift @@ -1,18 +1,10 @@ import Foundation -<<<<<<<< HEAD:Sources/Confidence/Backport.swift -public extension URL { - struct Backport { -|||||||| parent of 44209ae (Finalize the network layer for events):Sources/ConfidenceProvider/Utils/Backport.swift -extension URL { - struct Backport { -======== extension URL { public struct Backport { ->>>>>>>> 44209ae (Finalize the network layer for events):Sources/Common/Backport.swift var base: URL - public init(base: URL) { + init(base: URL) { self.base = base } } @@ -22,16 +14,8 @@ extension URL { } } -<<<<<<<< HEAD:Sources/Confidence/Backport.swift -public extension URL.Backport { - var path: String { -|||||||| parent of 44209ae (Finalize the network layer for events):Sources/ConfidenceProvider/Utils/Backport.swift -extension URL.Backport { - var path: String { -======== extension URL.Backport { public var path: String { ->>>>>>>> 44209ae (Finalize the network layer for events):Sources/Common/Backport.swift if #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) { return self.base.path(percentEncoded: false) } else { @@ -52,31 +36,15 @@ extension URL.Backport { } } -<<<<<<<< HEAD:Sources/Confidence/Backport.swift -public extension Date { - struct Backport { -|||||||| parent of 44209ae (Finalize the network layer for events):Sources/ConfidenceProvider/Utils/Backport.swift -extension Date { - struct Backport { -======== extension Date { public struct Backport { ->>>>>>>> 44209ae (Finalize the network layer for events):Sources/Common/Backport.swift } static public var backport: Backport.Type { Backport.self } } -<<<<<<<< HEAD:Sources/Confidence/Backport.swift -public extension Date.Backport { - static var now: Date { -|||||||| parent of 44209ae (Finalize the network layer for events):Sources/ConfidenceProvider/Utils/Backport.swift -extension Date.Backport { - static var now: Date { -======== extension Date.Backport { static public var now: Date { ->>>>>>>> 44209ae (Finalize the network layer for events):Sources/Common/Backport.swift if #available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) { return Date.now } else { @@ -92,7 +60,7 @@ extension Date.Backport { } } - static func toISOString(date: Date) -> String { + static public func toISOString(date: Date) -> String { if #available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) { return date.ISO8601Format() } else { diff --git a/Sources/Confidence/Confidence.swift b/Sources/Confidence/Confidence.swift index 39efb321..1e823e43 100644 --- a/Sources/Confidence/Confidence.swift +++ b/Sources/Confidence/Confidence.swift @@ -6,64 +6,56 @@ public class Confidence: ConfidenceEventSender { public let clientSecret: String public var timeout: TimeInterval public var region: ConfidenceRegion + let eventSenderEngine: EventSenderEngine public var initializationStrategy: InitializationStrategy private var removedContextKeys: Set = Set() - private var client: ConfidenceClient required init( clientSecret: String, timeout: TimeInterval, region: ConfidenceRegion, + eventSenderEngine: EventSenderEngine, initializationStrategy: InitializationStrategy, context: ConfidenceStruct = [:], - client: ConfidenceClient, parent: ConfidenceEventSender? = nil ) { + self.eventSenderEngine = eventSenderEngine self.clientSecret = clientSecret self.timeout = timeout self.region = region self.initializationStrategy = initializationStrategy self.context = context - self.client = client self.parent = parent } - public convenience init( - clientSecret: String, - timeout: TimeInterval, - region: ConfidenceRegion, - initializationStrategy: InitializationStrategy, - context: ConfidenceStruct = [:], - parent: ConfidenceEventSender? = nil - ) { - self.init( - clientSecret: clientSecret, - timeout: timeout, - region: region, - initializationStrategy: initializationStrategy, - client: RemoteConfidenceClient( - options: ConfidenceClientOptions( - credentials: ConfidenceClientCredentials.clientSecret(secret: clientSecret), - timeout: timeout, - region: region), - metadata: ConfidenceMetadata( - name: "SDK_ID_SWIFT_CONFIDENCE", - version: "0.1.4") // x-release-please-version) - ) - ) - } +// public convenience init( +// clientSecret: String, +// timeout: TimeInterval, +// region: ConfidenceRegion, +// initializationStrategy: InitializationStrategy, +// context: ConfidenceStruct = [:], +// parent: ConfidenceEventSender? = nil +// ) { +// self.init( +// clientSecret: clientSecret, +// timeout: timeout, +// region: region, +// eventSenderEngine: self.eventSenderEngine, +// initializationStrategy: initializationStrategy, +// client: RemoteConfidenceClient( +// options: ConfidenceClientOptions( +// credentials: ConfidenceClientCredentials.clientSecret(secret: clientSecret), +// timeout: timeout, +// region: region), +// metadata: ConfidenceMetadata( +// name: "SDK_ID_SWIFT_CONFIDENCE", +// version: "0.1.4") // x-release-please-version) +// ) +// ) +// } public func send(name: String, payload: ConfidenceStruct) { - print("Sending: \"\(name)\".\nMessage: \(payload)\nContext: \(context)") - Task { - // TODO: This will be called inside the EventSenderEngine once implemented - try? await client.upload(batch: [ - ConfidenceEvent( - name: name, - payload: NetworkTypeMapper.from(value: payload), - time: Date.backport.nowISOString) - ]) - } + eventSenderEngine.send(name: name, message: payload) } @@ -92,9 +84,9 @@ public class Confidence: ConfidenceEventSender { clientSecret: clientSecret, timeout: timeout, region: region, + eventSenderEngine: eventSenderEngine, initializationStrategy: initializationStrategy, context: context, - client: client, parent: self) } } @@ -105,9 +97,15 @@ extension Confidence { var timeout: TimeInterval = 10.0 var region: ConfidenceRegion = .global var initializationStrategy: InitializationStrategy = .fetchAndActivate + let eventStorage: EventStorage public init(clientSecret: String) { self.clientSecret = clientSecret + do { + eventStorage = try EventStorageImpl() + } catch { + eventStorage = EventStorageInMemory() + } } public func withTimeout(timeout: TimeInterval) -> Builder { @@ -127,20 +125,28 @@ extension Confidence { } public func build() -> Confidence { + let uploader = RemoteConfidenceClient( + options: ConfidenceClientOptions( + credentials: ConfidenceClientCredentials.clientSecret(secret: clientSecret), + timeout: timeout, + region: region), + metadata: ConfidenceMetadata( + name: "SDK_ID_SWIFT_CONFIDENCE", + version: "0.1.4") // x-release-please-version + ) + let eventSenderEngine = EventSenderEngineImpl( + clientSecret: clientSecret, + uploader: uploader, + storage: eventStorage, + flushPolicies: []) return Confidence( clientSecret: clientSecret, timeout: timeout, region: region, + eventSenderEngine: eventSenderEngine, initializationStrategy: initializationStrategy, - client: RemoteConfidenceClient( - options: ConfidenceClientOptions( - credentials: ConfidenceClientCredentials.clientSecret(secret: clientSecret), - timeout: timeout, - region: region), - metadata: ConfidenceMetadata( - name: "SDK_ID_SWIFT_CONFIDENCE", - version: "0.1.4") // x-release-please-version - ) + context: [:], + parent: nil ) } } diff --git a/Sources/Confidence/ConfidenceClient/ConfidenceClient.swift b/Sources/Confidence/ConfidenceClient/ConfidenceClient.swift index 0c6231d2..cec60f45 100644 --- a/Sources/Confidence/ConfidenceClient/ConfidenceClient.swift +++ b/Sources/Confidence/ConfidenceClient/ConfidenceClient.swift @@ -3,11 +3,5 @@ import Common protocol ConfidenceClient { // Returns true if the batch has been correctly processed by the backend - func upload(batch: [ConfidenceEvent]) async throws -> Bool -} - -struct ConfidenceEvent: Codable { - var name: String - var payload: NetworkStruct - var time: String + func upload(events: [NetworkEvent]) async throws -> Bool } diff --git a/Sources/Confidence/ConfidenceClient/RemoteConfidenceClient.swift b/Sources/Confidence/ConfidenceClient/RemoteConfidenceClient.swift index a9c78688..41de2e8e 100644 --- a/Sources/Confidence/ConfidenceClient/RemoteConfidenceClient.swift +++ b/Sources/Confidence/ConfidenceClient/RemoteConfidenceClient.swift @@ -3,7 +3,7 @@ import Common import os public class RemoteConfidenceClient: ConfidenceClient { - private var options: ConfidenceClientOptions + private var options: ConfidenceClientOptions private let metadata: ConfidenceMetadata private var httpClient: HttpClient private var baseUrl: String @@ -26,16 +26,10 @@ public class RemoteConfidenceClient: ConfidenceClient { self.metadata = metadata } - func upload(batch: [ConfidenceEvent]) async throws -> Bool { + func upload(events: [NetworkEvent]) async throws -> Bool { let timeString = Date.backport.nowISOString let request = PublishEventRequest( - events: batch.map { event in - Event( - eventDefinition: "eventDefinitions/\(event.name)", - payload: event.payload, - time: timeString - ) - }, + events: events, clientSecret: options.credentials.getSecret(), sendTime: timeString, sdk: Sdk(id: metadata.name, version: metadata.version) @@ -71,16 +65,16 @@ public class RemoteConfidenceClient: ConfidenceClient { } struct PublishEventRequest: Codable { - var events: [Event] + var events: [NetworkEvent] var clientSecret: String var sendTime: String var sdk: Sdk } -struct Event: Codable { +struct NetworkEvent: Codable { var eventDefinition: String var payload: NetworkStruct - var time: String + var eventTime: String } struct PublishEventResponse: Codable { diff --git a/Sources/Confidence/EventSenderEngine.swift b/Sources/Confidence/EventSenderEngine.swift index c467ed32..a2a0e61f 100644 --- a/Sources/Confidence/EventSenderEngine.swift +++ b/Sources/Confidence/EventSenderEngine.swift @@ -1,4 +1,5 @@ import Combine +import Common import Foundation protocol FlushPolicy { @@ -7,12 +8,8 @@ protocol FlushPolicy { func shouldFlush() -> Bool } -protocol Clock { - func now() -> Date -} - protocol EventSenderEngine { - func send(name: String, message: ConfidenceStruct) throws + func send(name: String, message: ConfidenceStruct) func shutdown() } @@ -25,16 +22,13 @@ final class EventSenderEngineImpl: EventSenderEngine { private let flushPolicies: [FlushPolicy] private let uploader: ConfidenceClient private let clientSecret: String - private let clock: Clock init( clientSecret: String, uploader: ConfidenceClient, - clock: Clock, storage: EventStorage, flushPolicies: [FlushPolicy] ) { - self.clock = clock self.uploader = uploader self.clientSecret = clientSecret self.storage = storage @@ -63,8 +57,15 @@ final class EventSenderEngineImpl: EventSenderEngine { try self.storage.startNewBatch() let ids = try storage.batchReadyIds() for id in ids { - let events = try self.storage.eventsFrom(id: id) - let shouldCleanup = try await self.uploader.upload(batch: events) + let events: [NetworkEvent] = try self.storage.eventsFrom(id: id) + .compactMap({ event in + let networkPayload = event.payload.compactMapValues({ payloadValue in try? NetworkTypeMapper.convertValue(payloadValue)}) + return NetworkEvent( + eventDefinition: event.name, + payload: NetworkStruct(fields: networkPayload), + eventTime: Date.backport.toISOString(date: event.eventTime)) + }) + let shouldCleanup = try await self.uploader.upload(events: events) if shouldCleanup { try storage.remove(id: id) } @@ -75,11 +76,11 @@ final class EventSenderEngineImpl: EventSenderEngine { .store(in: &cancellables) } - func send(name: String, message: [String: ConfidenceValue]) throws { + func send(name: String, message: [String: ConfidenceValue]) { writeReqChannel.send(ConfidenceEvent( name: name, - payload: try NetworkTypeMapper.from(value: message), - time: Date.backport.nowISOString) + payload: message, + eventTime: Date.backport.now) ) } diff --git a/Sources/Confidence/EventSenderStorage.swift b/Sources/Confidence/EventSenderStorage.swift deleted file mode 100644 index a4f0296a..00000000 --- a/Sources/Confidence/EventSenderStorage.swift +++ /dev/null @@ -1,15 +0,0 @@ -import Foundation - -struct EventBatchRequest: Encodable { - let clientSecret: String - let sendTime: Date - let events: [ConfidenceEvent] -} - -internal protocol EventStorage { - func startNewBatch() throws - func writeEvent(event: Event) throws - func batchReadyIds() -> [String] - func eventsFrom(id: String) throws -> [Event] - func remove(id: String) throws -} diff --git a/Sources/Confidence/EventStorage.swift b/Sources/Confidence/EventStorage.swift index 7e1ef3e6..e4e6197d 100644 --- a/Sources/Confidence/EventStorage.swift +++ b/Sources/Confidence/EventStorage.swift @@ -1,11 +1,18 @@ import Foundation +import Common import os +struct ConfidenceEvent: Codable { + let name: String + let payload: [String: ConfidenceValue] + let eventTime: Date +} + internal protocol EventStorage { func startNewBatch() throws - func writeEvent(event: Event) throws + func writeEvent(event: ConfidenceEvent) throws func batchReadyIds() throws -> [String] - func eventsFrom(id: String) throws -> [Event] + func eventsFrom(id: String) throws -> [ConfidenceEvent] func remove(id: String) throws } @@ -35,7 +42,7 @@ internal class EventStorageImpl: EventStorage { } } - func writeEvent(event: Event) throws { + func writeEvent(event: ConfidenceEvent) throws { try storageQueue.sync { guard let currentFileHandle = currentFileHandle else { return @@ -60,7 +67,7 @@ internal class EventStorageImpl: EventStorage { } } - func eventsFrom(id: String) throws -> [Event] { + func eventsFrom(id: String) throws -> [ConfidenceEvent] { try storageQueue.sync { let decoder = JSONDecoder() let fileUrl = folderURL.appendingPathComponent(id) @@ -68,7 +75,7 @@ internal class EventStorageImpl: EventStorage { let dataString = String(data: data, encoding: .utf8) return try dataString?.components(separatedBy: "\n") .filter({ events in !events.isEmpty }) - .map({ eventString in try decoder.decode(Event.self, from: eventString.data(using: .utf8)!) }) ?? [] + .map({ eventString in try decoder.decode(ConfidenceEvent.self, from: eventString.data(using: .utf8)!) }) ?? [] } } @@ -119,11 +126,3 @@ internal class EventStorageImpl: EventStorage { components: "com.confidence.events.storage", "\(bundleIdentifier)", "events") } } - -struct Event: Codable { - let eventDefinition: String - let eventTime: Date - // TODO: fix this to be ConfidenceValue - let payload: [String] - let context: [String] -} diff --git a/Sources/Confidence/EventStorageInMemory.swift b/Sources/Confidence/EventStorageInMemory.swift new file mode 100644 index 00000000..e3b342ef --- /dev/null +++ b/Sources/Confidence/EventStorageInMemory.swift @@ -0,0 +1,27 @@ +import Foundation + +final class EventStorageInMemory: EventStorage { + private var events: [ConfidenceEvent] = [] + private var batches: [String: [ConfidenceEvent]] = [:] + func startNewBatch() throws { + batches[("\(batches.count)")] = events + events.removeAll() + } + + func writeEvent(event: ConfidenceEvent) throws { + events.append(event) + } + + func batchReadyIds() -> [String] { + return batches.map { batch in batch.0 } + } + + func eventsFrom(id: String) throws -> [ConfidenceEvent] { + // swiftlint:disable:next force_unwrapping + return batches[id]! + } + + func remove(id: String) throws { + batches.removeValue(forKey: id) + } +} diff --git a/Sources/Confidence/SizeFlushPolicy.swift b/Sources/Confidence/SizeFlushPolicy.swift new file mode 100644 index 00000000..c3cf180e --- /dev/null +++ b/Sources/Confidence/SizeFlushPolicy.swift @@ -0,0 +1,22 @@ +import Foundation + +class SizeFlushPolicy: FlushPolicy { + private var currentSize = 0 + private let batchSize: Int + + init(batchSize: Int) { + self.batchSize = batchSize + } + + func reset() { + currentSize = 0 + } + + func hit(event: ConfidenceEvent) { + currentSize += 1 + } + + func shouldFlush() -> Bool { + currentSize >= batchSize + } +} diff --git a/Tests/ConfidenceProviderTests/EventSenderEngineTest.swift b/Tests/ConfidenceProviderTests/EventSenderEngineTest.swift index 02cb1d3b..2f9a0b79 100644 --- a/Tests/ConfidenceProviderTests/EventSenderEngineTest.swift +++ b/Tests/ConfidenceProviderTests/EventSenderEngineTest.swift @@ -27,7 +27,6 @@ final class EventSenderEngineTest: XCTestCase { let eventSenderEngine = EventSenderEngineImpl( clientSecret: "CLIENT_SECRET", uploader: uploader, - clock: ClockMock(), storage: EventStorageMock(), flushPolicies: flushPolicies ) @@ -41,18 +40,18 @@ final class EventSenderEngineTest: XCTestCase { for i in 0..<5 { events.append(ConfidenceEvent( name: "\(i)", - payload: NetworkStruct.init(fields: [:]), - time: Date.backport.nowISOString) + payload: [:], + eventTime: Date.backport.now) ) - try eventSenderEngine.send(name: "\(i)", message: ConfidenceStruct()) + eventSenderEngine.send(name: "\(i)", message: ConfidenceStruct()) } wait(for: [expectation], timeout: 5) let uploadRequest = try XCTUnwrap(uploader.calledRequest) - XCTAssertTrue(uploadRequest.map { $0.name } == events.map { $0.name }) + XCTAssertTrue(uploadRequest.map { $0.eventDefinition } == events.map { $0.name }) uploader.reset() - try eventSenderEngine.send(name: "Hello", message: [:]) + eventSenderEngine.send(name: "Hello", message: [:]) XCTAssertNil(uploader.calledRequest) cancellable.cancel() } diff --git a/Tests/ConfidenceProviderTests/EventUploaderMock.swift b/Tests/ConfidenceProviderTests/EventUploaderMock.swift index 7e47dc24..4f79cbbc 100644 --- a/Tests/ConfidenceProviderTests/EventUploaderMock.swift +++ b/Tests/ConfidenceProviderTests/EventUploaderMock.swift @@ -3,11 +3,11 @@ import Combine @testable import Confidence final class EventUploaderMock: ConfidenceClient { - var calledRequest: [ConfidenceEvent]? + var calledRequest: [NetworkEvent]? let subject: PassthroughSubject = PassthroughSubject() - func upload(batch: [ConfidenceEvent]) async throws -> Bool { - calledRequest = batch + func upload(events: [NetworkEvent]) async throws -> Bool { + calledRequest = events subject.send(1) return true } @@ -17,12 +17,6 @@ final class EventUploaderMock: ConfidenceClient { } } -final class ClockMock: Clock { - func now() -> Date { - return Date() - } -} - final class EventStorageMock: EventStorage { private var events: [ConfidenceEvent] = [] private var batches: [String: [ConfidenceEvent]] = [:] diff --git a/Tests/ConfidenceTests/ConfidenceTests.swift b/Tests/ConfidenceTests/ConfidenceTests.swift index f71be150..8f3094bb 100644 --- a/Tests/ConfidenceTests/ConfidenceTests.swift +++ b/Tests/ConfidenceTests/ConfidenceTests.swift @@ -6,10 +6,9 @@ final class ConfidenceTests: XCTestCase { let confidenceParent = Confidence.init( clientSecret: "", timeout: TimeInterval(), - region: .europe, + region: .europe, eventSenderEngine: EventSenderEngineMock(), initializationStrategy: .activateAndFetchAsync, - context: ["k1": ConfidenceValue(string: "v1")], - client: ConfidenceClientMock() + context: ["k1": ConfidenceValue(string: "v1")] ) let confidenceChild: ConfidenceEventSender = confidenceParent.withContext( ["k2": ConfidenceValue(string: "v2")] @@ -25,10 +24,9 @@ final class ConfidenceTests: XCTestCase { let confidenceParent = Confidence.init( clientSecret: "", timeout: TimeInterval(), - region: .europe, + region: .europe, eventSenderEngine: EventSenderEngineMock(), initializationStrategy: .activateAndFetchAsync, - context: ["k1": ConfidenceValue(string: "v1")], - client: ConfidenceClientMock() + context: ["k1": ConfidenceValue(string: "v1")], parent: nil ) let confidenceChild: ConfidenceEventSender = confidenceParent.withContext( ["k2": ConfidenceValue(string: "v2")] @@ -48,10 +46,9 @@ final class ConfidenceTests: XCTestCase { let confidence = Confidence.init( clientSecret: "", timeout: TimeInterval(), - region: .europe, + region: .europe, eventSenderEngine: EventSenderEngineMock(), initializationStrategy: .activateAndFetchAsync, - context: ["k1": ConfidenceValue(string: "v1")], - client: ConfidenceClientMock() + context: ["k1": ConfidenceValue(string: "v1")], parent: nil ) confidence.updateContextEntry( key: "k1", @@ -66,10 +63,9 @@ final class ConfidenceTests: XCTestCase { let confidenceParent = Confidence.init( clientSecret: "", timeout: TimeInterval(), - region: .europe, + region: .europe, eventSenderEngine: EventSenderEngineMock(), initializationStrategy: .activateAndFetchAsync, - context: ["k1": ConfidenceValue(string: "v1")], - client: ConfidenceClientMock() + context: ["k1": ConfidenceValue(string: "v1")], parent: nil ) let confidenceChild: ConfidenceEventSender = confidenceParent.withContext( ["k2": ConfidenceValue(string: "v2")] @@ -88,10 +84,9 @@ final class ConfidenceTests: XCTestCase { let confidenceParent = Confidence.init( clientSecret: "", timeout: TimeInterval(), - region: .europe, + region: .europe, eventSenderEngine: EventSenderEngineMock(), initializationStrategy: .activateAndFetchAsync, - context: ["k1": ConfidenceValue(string: "v1")], - client: ConfidenceClientMock() + context: ["k1": ConfidenceValue(string: "v1")], parent: nil ) let confidenceChild: ConfidenceEventSender = confidenceParent.withContext( ["k2": ConfidenceValue(string: "v2")] @@ -110,13 +105,13 @@ final class ConfidenceTests: XCTestCase { let confidence = Confidence.init( clientSecret: "", timeout: TimeInterval(), - region: .europe, + region: .europe, eventSenderEngine: EventSenderEngineMock(), initializationStrategy: .activateAndFetchAsync, context: [ "k1": ConfidenceValue(string: "v1"), "k2": ConfidenceValue(string: "v2") ], - client: ConfidenceClientMock() + parent: nil ) confidence.removeContextEntry(key: "k2") let expected = [ @@ -129,10 +124,9 @@ final class ConfidenceTests: XCTestCase { let confidenceParent = Confidence.init( clientSecret: "", timeout: TimeInterval(), - region: .europe, + region: .europe, eventSenderEngine: EventSenderEngineMock(), initializationStrategy: .activateAndFetchAsync, - context: ["k1": ConfidenceValue(string: "v1")], - client: ConfidenceClientMock() + context: ["k1": ConfidenceValue(string: "v1")], parent: nil ) let confidenceChild: ConfidenceEventSender = confidenceParent.withContext( ["k2": ConfidenceValue(string: "v2")] @@ -148,10 +142,9 @@ final class ConfidenceTests: XCTestCase { let confidenceParent = Confidence.init( clientSecret: "", timeout: TimeInterval(), - region: .europe, + region: .europe, eventSenderEngine: EventSenderEngineMock(), initializationStrategy: .activateAndFetchAsync, - context: ["k1": ConfidenceValue(string: "v1")], - client: ConfidenceClientMock() + context: ["k1": ConfidenceValue(string: "v1")], parent: nil ) let confidenceChild: ConfidenceEventSender = confidenceParent.withContext( [ @@ -170,10 +163,9 @@ final class ConfidenceTests: XCTestCase { let confidenceParent = Confidence.init( clientSecret: "", timeout: TimeInterval(), - region: .europe, + region: .europe, eventSenderEngine: EventSenderEngineMock(), initializationStrategy: .activateAndFetchAsync, - context: ["k1": ConfidenceValue(string: "v1")], - client: ConfidenceClientMock() + context: ["k1": ConfidenceValue(string: "v1")], parent: nil ) let confidenceChild: ConfidenceEventSender = confidenceParent.withContext( [ diff --git a/Tests/ConfidenceTests/EventStorageTests.swift b/Tests/ConfidenceTests/EventStorageTests.swift index d54afaad..d0f97519 100644 --- a/Tests/ConfidenceTests/EventStorageTests.swift +++ b/Tests/ConfidenceTests/EventStorageTests.swift @@ -11,30 +11,23 @@ class EventStorageTest: XCTestCase { } } - override func setUp() async throws { - let folderURL = try! EventStorageImpl.getFolderURL() - if FileManager.default.fileExists(atPath: folderURL.path) { - try! FileManager.default.removeItem(at: folderURL) - } - } - func testCreateNewBatch() throws { let eventStorage = try EventStorageImpl() - try eventStorage.writeEvent(event: Event(name: "some event", payload: ["pants": ConfidenceValue(string: "green")], eventTime: Date().self)) - try eventStorage.writeEvent(event: Event(name: "some event 2", payload: ["pants": ConfidenceValue(string: "red")], eventTime: Date().self)) + try eventStorage.writeEvent(event: ConfidenceEvent(name: "some event", payload: ["pants": ConfidenceValue(string: "green")], eventTime: Date().self)) + try eventStorage.writeEvent(event: ConfidenceEvent(name: "some event 2", payload: ["pants": ConfidenceValue(string: "red")], eventTime: Date().self)) try eventStorage.startNewBatch() try XCTAssertEqual(eventStorage.batchReadyIds().count, 1) let events = try eventStorage.eventsFrom(id: try eventStorage.batchReadyIds()[0]) - XCTAssertEqual(events[0].eventDefinition, "some event") - XCTAssertEqual(events[1].eventDefinition, "some event 2") + XCTAssertEqual(events[0].name, "some event") + XCTAssertEqual(events[1].name, "some event 2") } func testContinueWritingToOldBatch() throws { let eventStorage = try EventStorageImpl() - try eventStorage.writeEvent(event: Event(name: "some event", payload: ["pants": ConfidenceValue(string: "green")], eventTime: Date().self)) + try eventStorage.writeEvent(event: ConfidenceEvent(name: "some event", payload: ["pants": ConfidenceValue(string: "green")], eventTime: Date().self)) // user stops using app, new session after this let eventStorageNew = try EventStorageImpl() - try eventStorageNew.writeEvent(event: Event(name: "some event 2", payload: ["pants": ConfidenceValue(string: "red")], eventTime: Date().self)) + try eventStorageNew.writeEvent(event: ConfidenceEvent(name: "some event 2", payload: ["pants": ConfidenceValue(string: "red")], eventTime: Date().self)) try eventStorageNew.startNewBatch() try XCTAssertEqual(eventStorageNew.batchReadyIds().count, 1) let events = try eventStorageNew.eventsFrom(id: try eventStorageNew.batchReadyIds()[0]) @@ -44,8 +37,8 @@ class EventStorageTest: XCTestCase { func testRemoveFile() throws { let eventStorage = try EventStorageImpl() - try eventStorage.writeEvent(event: Event(name: "some event", payload: ["pants": ConfidenceValue(string: "green")], eventTime: Date().self)) - try eventStorage.writeEvent(event: Event(name: "some event 2", payload: ["pants": ConfidenceValue(string: "red")], eventTime: Date().self)) + try eventStorage.writeEvent(event: ConfidenceEvent(name: "some event", payload: ["pants": ConfidenceValue(string: "green")], eventTime: Date().self)) + try eventStorage.writeEvent(event: ConfidenceEvent(name: "some event 2", payload: ["pants": ConfidenceValue(string: "red")], eventTime: Date().self)) try eventStorage.startNewBatch() try eventStorage.remove(id: eventStorage.batchReadyIds()[0]) try XCTAssertEqual(eventStorage.batchReadyIds().count, 0) diff --git a/Tests/ConfidenceTests/Helpers/ConfidenceClientMock.swift b/Tests/ConfidenceTests/Helpers/ConfidenceClientMock.swift index a4f5863e..b16fbb9d 100644 --- a/Tests/ConfidenceTests/Helpers/ConfidenceClientMock.swift +++ b/Tests/ConfidenceTests/Helpers/ConfidenceClientMock.swift @@ -3,7 +3,7 @@ import Foundation @testable import Confidence class ConfidenceClientMock: ConfidenceClient { - func upload(batch: [ConfidenceEvent]) async throws -> Bool { + func upload(events: [NetworkEvent]) async throws -> Bool { return true } } diff --git a/Tests/ConfidenceTests/Helpers/EventSenderEngineMock.swift b/Tests/ConfidenceTests/Helpers/EventSenderEngineMock.swift new file mode 100644 index 00000000..e3ff4f3d --- /dev/null +++ b/Tests/ConfidenceTests/Helpers/EventSenderEngineMock.swift @@ -0,0 +1,12 @@ +import Foundation +@testable import Confidence + +class EventSenderEngineMock: EventSenderEngine { + func send(name: String, message: ConfidenceStruct) { + // NO-OP + } + + func shutdown() { + // NO-OP + } +} diff --git a/Tests/ConfidenceTests/RemooteConfidenceClientTests.swift b/Tests/ConfidenceTests/RemooteConfidenceClientTests.swift index 3c965f23..9e7a89d3 100644 --- a/Tests/ConfidenceTests/RemooteConfidenceClientTests.swift +++ b/Tests/ConfidenceTests/RemooteConfidenceClientTests.swift @@ -18,24 +18,24 @@ class RemoteConfidenceClientTest: XCTestCase { session: MockedClientURLProtocol.mockedSession(), metadata: ConfidenceMetadata(name: "", version: "")) - let processed = try await client.upload(batch: [ - ConfidenceEvent( - name: "testEvent", + let processed = try await client.upload(events: [ + NetworkEvent( + eventDefinition: "testEvent", payload: NetworkStruct.init(fields: [:]), - time: Date.backport.nowISOString + eventTime: Date.backport.nowISOString ) ]) XCTAssertTrue(processed) } - func testUploadEmptyBatchDoesntThrow() async throws { + func testUploadEmptyeventsDoesntThrow() async throws { let client = RemoteConfidenceClient( options: ConfidenceClientOptions( credentials: ConfidenceClientCredentials.clientSecret(secret: "")), session: MockedClientURLProtocol.mockedSession(), metadata: ConfidenceMetadata(name: "", version: "")) - let processed = try await client.upload(batch: []) + let processed = try await client.upload(events: []) XCTAssertTrue(processed) } @@ -47,11 +47,11 @@ class RemoteConfidenceClientTest: XCTestCase { session: MockedClientURLProtocol.mockedSession(), metadata: ConfidenceMetadata(name: "", version: "")) - let processed = try await client.upload(batch: [ - ConfidenceEvent( - name: "testEvent", + let processed = try await client.upload(events: [ + NetworkEvent( + eventDefinition: "testEvent", payload: NetworkStruct.init(fields: [:]), - time: Date.backport.nowISOString + eventTime: Date.backport.nowISOString ) ]) XCTAssertTrue(processed) @@ -67,11 +67,11 @@ class RemoteConfidenceClientTest: XCTestCase { var caughtError: ConfidenceError? do { - _ = try await client.upload(batch: [ - ConfidenceEvent( - name: "testEvent", + _ = try await client.upload(events: [ + NetworkEvent( + eventDefinition: "testEvent", payload: NetworkStruct.init(fields: [:]), - time: Date.backport.nowISOString + eventTime: Date.backport.nowISOString ) ]) } catch { @@ -91,11 +91,11 @@ class RemoteConfidenceClientTest: XCTestCase { var caughtError: ConfidenceError? do { - _ = try await client.upload(batch: [ - ConfidenceEvent( - name: "testEvent", + _ = try await client.upload(events: [ + NetworkEvent( + eventDefinition: "testEvent", payload: NetworkStruct.init(fields: [:]), - time: Date.backport.nowISOString + eventTime: Date.backport.nowISOString ) ]) } catch {