Skip to content

Commit

Permalink
refactor: Re-arrange code for readability
Browse files Browse the repository at this point in the history
  • Loading branch information
fabriziodemaria committed Jun 26, 2024
1 parent 2ffc41d commit 4b506fd
Show file tree
Hide file tree
Showing 31 changed files with 87 additions and 97 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Foundation
import os

public class RemoteConfidenceClient: ConfidenceClient {
public class ConfidenceClientEventsRemote: ConfidenceEventsClient {
private var options: ConfidenceClientOptions
private let metadata: ConfidenceMetadata
private var httpClient: HttpClient
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation

public class RemoteConfidenceResolveClient: ConfidenceResolveClient {
public class ConfidenceClientResolveRemote: ConfidenceResolveClient {
private let targetingKey = "targeting_key"
private var options: ConfidenceClientOptions
private let metadata: ConfidenceMetadata
Expand Down Expand Up @@ -147,6 +147,11 @@ struct ApplyFlagsRequest: Codable {
struct ApplyFlagsResponse: Codable {
}

struct Sdk: Codable {
var id: String
var version: String
}

private func displayName(resolvedFlag: ResolvedFlag) throws -> String {
let flagNameComponents = resolvedFlag.flag.components(separatedBy: "/")
if flagNameComponents.count <= 1 || flagNameComponents[0] != "flags" {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation

protocol ConfidenceClient {
protocol ConfidenceEventsClient {
// Returns true if the batch has been correctly processed by the backend
func upload(events: [NetworkEvent]) async throws -> Bool
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/Confidence/Confidence.swift
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ extension Confidence {
let metadata = ConfidenceMetadata(
name: sdkId,
version: "0.2.3") // x-release-please-version
let uploader = RemoteConfidenceClient(
let uploader = ConfidenceClientEventsRemote(
options: options,
metadata: metadata
)
Expand All @@ -337,7 +337,7 @@ extension Confidence {
options: options,
metadata: metadata
)
let flagResolver = flagResolver ?? RemoteConfidenceResolveClient(
let flagResolver = flagResolver ?? ConfidenceClientResolveRemote(
options: options,
applyOnResolve: false,
metadata: metadata
Expand Down
6 changes: 3 additions & 3 deletions Sources/Confidence/EventSenderEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ final class EventSenderEngineImpl: EventSenderEngine {
private let uploadReqChannel = PassthroughSubject<String, Never>()
private var cancellables = Set<AnyCancellable>()
private let flushPolicies: [FlushPolicy]
private let uploader: ConfidenceClient
private let uploader: ConfidenceEventsClient
private let clientSecret: String
private let payloadMerger: PayloadMerger = PayloadMergerImpl()
private let semaphore = DispatchSemaphore(value: 1)
private let writeQueue: DispatchQueue

convenience init(
clientSecret: String,
uploader: ConfidenceClient,
uploader: ConfidenceEventsClient,
storage: EventStorage
) {
self.init(
Expand All @@ -42,7 +42,7 @@ final class EventSenderEngineImpl: EventSenderEngine {

init(
clientSecret: String,
uploader: ConfidenceClient,
uploader: ConfidenceEventsClient,
storage: EventStorage,
flushPolicies: [FlushPolicy],
writeQueue: DispatchQueue
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Foundation
import UIKit
import Combine

public class ConfidenceScreenTracker: ConfidenceEventProducer {
public class ConfidenceScreenTrackProducer: ConfidenceEventProducer {
private var events = BufferedPassthrough<Event>()
static let notificationName = Notification.Name(rawValue: "ConfidenceScreenTracker")
static let screenName = "screen_name"
Expand Down Expand Up @@ -70,7 +70,7 @@ extension UIViewController {
private func sendNotification(event: String) {
var className = String(describing: type(of: self))
.replacingOccurrences(of: "ViewController", with: "")
var message: [String: String] = [ConfidenceScreenTracker.screenName: className]
var message: [String: String] = [ConfidenceScreenTrackProducer.screenName: className]

if let trackable = self as? TrackableComponent {
className = trackable.trackName()
Expand All @@ -79,14 +79,14 @@ extension UIViewController {
do {
let data = try encoder.encode(trackableWithMessage.trackMessage())
let messageString = String(decoding: data, as: UTF8.self)
message.updateValue(messageString, forKey: ConfidenceScreenTracker.messageKey)
message.updateValue(messageString, forKey: ConfidenceScreenTrackProducer.messageKey)
} catch {
}
}
}

NotificationCenter.default.post(
name: ConfidenceScreenTracker.notificationName,
name: ConfidenceScreenTrackProducer.notificationName,
object: self,
userInfo: message
)
Expand Down
6 changes: 0 additions & 6 deletions Sources/Confidence/Sdk.swift

This file was deleted.

52 changes: 0 additions & 52 deletions Sources/Confidence/TestHelpers/Extensions.swift

This file was deleted.

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
16 changes: 8 additions & 8 deletions Sources/ConfidenceProvider/ConfidenceFeatureProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,6 @@ public class ConfidenceFeatureProvider: FeatureProvider {
}
}

func shutdown() {
for cancellable in cancellables {
cancellable.cancel()
}
cancellables.removeAll()
currentResolveTask?.cancel()
}

public func onContextSet(
oldContext: OpenFeature.EvaluationContext?,
newContext: OpenFeature.EvaluationContext
Expand Down Expand Up @@ -123,6 +115,14 @@ public class ConfidenceFeatureProvider: FeatureProvider {
return eventHandler.observe()
}

func shutdown() {
for cancellable in cancellables {
cancellable.cancel()
}
cancellables.removeAll()
currentResolveTask?.cancel()
}

private func withLock(callback: @escaping (ConfidenceFeatureProvider) -> Void) {
confidenceFeatureProviderQueue.sync { [weak self] in
guard let self = self else {
Expand Down
20 changes: 10 additions & 10 deletions Tests/ConfidenceTests/ConfidenceContextTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import XCTest
// swiftlint:disable type_body_length
final class ConfidenceContextTests: XCTestCase {
func testWithContext() {
let client = RemoteConfidenceResolveClient(
let client = ConfidenceClientResolveRemote(
options: ConfidenceClientOptions(
credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
Expand All @@ -30,7 +30,7 @@ final class ConfidenceContextTests: XCTestCase {
}

func testWithContextUpdateParent() {
let client = RemoteConfidenceResolveClient(
let client = ConfidenceClientResolveRemote(
options: ConfidenceClientOptions(
credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
Expand Down Expand Up @@ -61,7 +61,7 @@ final class ConfidenceContextTests: XCTestCase {
}

func testUpdateLocalContext() {
let client = RemoteConfidenceResolveClient(
let client = ConfidenceClientResolveRemote(
options: ConfidenceClientOptions(
credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
Expand All @@ -87,7 +87,7 @@ final class ConfidenceContextTests: XCTestCase {
}

func testUpdateLocalContextWithoutOverride() {
let client = RemoteConfidenceResolveClient(
let client = ConfidenceClientResolveRemote(
options: ConfidenceClientOptions(
credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
Expand Down Expand Up @@ -117,7 +117,7 @@ final class ConfidenceContextTests: XCTestCase {
}

func testUpdateParentContextWithOverride() {
let client = RemoteConfidenceResolveClient(
let client = ConfidenceClientResolveRemote(
options: ConfidenceClientOptions(
credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
Expand Down Expand Up @@ -147,7 +147,7 @@ final class ConfidenceContextTests: XCTestCase {
}

func testRemoveContextEntry() {
let client = RemoteConfidenceResolveClient(
let client = ConfidenceClientResolveRemote(
options: ConfidenceClientOptions(
credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
Expand All @@ -171,7 +171,7 @@ final class ConfidenceContextTests: XCTestCase {
}

func testRemoveContextEntryFromParent() {
let client = RemoteConfidenceResolveClient(
let client = ConfidenceClientResolveRemote(
options: ConfidenceClientOptions(
credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
Expand All @@ -198,7 +198,7 @@ final class ConfidenceContextTests: XCTestCase {
}

func testRemoveContextEntryFromParentAndChild() {
let client = RemoteConfidenceResolveClient(
let client = ConfidenceClientResolveRemote(
options: ConfidenceClientOptions(
credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
Expand Down Expand Up @@ -228,7 +228,7 @@ final class ConfidenceContextTests: XCTestCase {
}

func testRemoveContextEntryFromParentAndChildThenUpdate() {
let client = RemoteConfidenceResolveClient(
let client = ConfidenceClientResolveRemote(
options: ConfidenceClientOptions(
credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
Expand Down Expand Up @@ -260,7 +260,7 @@ final class ConfidenceContextTests: XCTestCase {
}

func testVisitorId() {
let client = RemoteConfidenceResolveClient(
let client = ConfidenceClientResolveRemote(
options: ConfidenceClientOptions(
credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
Expand Down
13 changes: 13 additions & 0 deletions Tests/ConfidenceTests/ConfidenceTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -591,4 +591,17 @@ final class DispatchQueueFake: DispatchQueueType {
work()
}
}


/// Used for testing
public protocol DispatchQueueType {
func async(execute work: @escaping @convention(block) () -> Void)
}

extension DispatchQueue: DispatchQueueType {
public func async(execute work: @escaping @convention(block) () -> Void) {
async(group: nil, qos: .unspecified, flags: [], execute: work)
}
}

// swiftlint:enable type_body_length
4 changes: 2 additions & 2 deletions Tests/ConfidenceTests/EventSenderEngineTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ final class EventSenderEngineTest: XCTestCase {

func testRemoveEventsFromStorageOnBadRequest() throws {
MockedClientURLProtocol.mockedOperation = .badRequest
let badRequestUploader = RemoteConfidenceClient(
let badRequestUploader = ConfidenceClientEventsRemote(
options: ConfidenceClientOptions(credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
metadata: ConfidenceMetadata(name: "", version: ""))
Expand All @@ -131,7 +131,7 @@ final class EventSenderEngineTest: XCTestCase {

func testKeepEventsInStorageForRetry() throws {
MockedClientURLProtocol.mockedOperation = .needRetryLater
let retryLaterUploader = RemoteConfidenceClient(
let retryLaterUploader = ConfidenceClientEventsRemote(
options: ConfidenceClientOptions(credentials: ConfidenceClientCredentials.clientSecret(secret: "")),
session: MockedClientURLProtocol.mockedSession(),
metadata: ConfidenceMetadata(name: "", version: ""))
Expand Down
2 changes: 1 addition & 1 deletion Tests/ConfidenceTests/EventUploaderMock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Foundation
import Combine
@testable import Confidence

final class EventUploaderMock: ConfidenceClient {
final class EventUploaderMock: ConfidenceEventsClient {
var calledRequest: [NetworkEvent]?
let subject: PassthroughSubject<Int, Never> = PassthroughSubject()

Expand Down
2 changes: 1 addition & 1 deletion Tests/ConfidenceTests/Helpers/ConfidenceClientMock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Foundation

@testable import Confidence

class ConfidenceClientMock: ConfidenceClient {
class ConfidenceClientMock: ConfidenceEventsClient {
func upload(events: [NetworkEvent]) async throws -> Bool {
return true
}
Expand Down
30 changes: 30 additions & 0 deletions Tests/ConfidenceTests/Helpers/MockedClientURLProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,33 @@ class MockedClientURLProtocol: URLProtocol {
client?.urlProtocolDidFinishLoading(self)
}
}

extension URLRequest {
public func decodeBody<T: Codable>(type: T.Type) -> T? {
guard let bodyStream = self.httpBodyStream else { return nil }

bodyStream.open()

let bufferSize: Int = 128
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)

var data = Data()
while bodyStream.hasBytesAvailable {
let readBytes = bodyStream.read(buffer, maxLength: bufferSize)
data.append(buffer, count: readBytes)
}

buffer.deallocate()

bodyStream.close()

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

do {
return try decoder.decode(type, from: data)
} catch {
return nil
}
}
}
Loading

0 comments on commit 4b506fd

Please sign in to comment.