Skip to content

feat: GOFF Specificity #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,5 @@ identifier_name:
- GlobalAPIKey
- key
- dto
- ctx
reporter: "xcode" # reporter type (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging, summary)
4 changes: 2 additions & 2 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
"repositoryURL": "https://github.com/open-feature/swift-sdk.git",
"state": {
"branch": null,
"revision": "02b033c954766e86d5706bfc8ee5248244c11e77",
"version": "0.1.0"
"revision": "907567cf9d43aad4c015a8758a7d53d755e76213",
"version": "0.2.0"
}
}
]
Expand Down
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ let package = Package(
targets: ["OFREP"])
],
dependencies: [
.package(url: "https://github.com/open-feature/swift-sdk.git", from: "0.1.0")
.package(url: "https://github.com/open-feature/swift-sdk.git", from: "0.2.0")
],
targets: [
.target(
Expand Down
58 changes: 58 additions & 0 deletions Sources/GOFeatureFlag/controller/data_collector_manager.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import Foundation
import OpenFeature
import Combine

class DataCollectorManager {
var events: [FeatureEvent] = []
var hooks: [any Hook] = []
let queue = DispatchQueue(label: "org.gofeatureflag.feature.events", attributes: .concurrent)
let goffAPI: GoFeatureFlagAPI
let options: GoFeatureFlagProviderOptions
private var timer: DispatchSourceTimer?

init(goffAPI: GoFeatureFlagAPI, options: GoFeatureFlagProviderOptions) {
self.goffAPI = goffAPI
self.options = options
}

func start() {
timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
timer?.schedule(deadline: .now(), repeating: self.options.dataCollectorInterval, leeway: .milliseconds(100))
timer?.setEventHandler { [weak self] in
guard let weakSelf = self else { return }
Task {
await weakSelf.pushEvents()
}
}
timer?.resume()
}

func appendFeatureEvent(event: FeatureEvent) {
self.queue.async(flags:.barrier) {
self.events.append(event)
}
}

func pushEvents() async {
self.queue.async(flags:.barrier) {
Task {
do {
if !self.events.isEmpty {
(_,_) = try await self.goffAPI.postDataCollector(events: self.events)
self.events = []
}
} catch {
NSLog("data collector error: \(error)")

Check warning on line 45 in Sources/GOFeatureFlag/controller/data_collector_manager.swift

View check run for this annotation

Codecov / codecov/patch

Sources/GOFeatureFlag/controller/data_collector_manager.swift#L45

Added line #L45 was not covered by tests
}
}
}
}

func getHooks() -> [any Hook] {
return self.hooks
}

func stop() async {
await self.pushEvents()

Check warning on line 56 in Sources/GOFeatureFlag/controller/data_collector_manager.swift

View check run for this annotation

Codecov / codecov/patch

Sources/GOFeatureFlag/controller/data_collector_manager.swift#L55-L56

Added lines #L55 - L56 were not covered by tests
}
}
65 changes: 65 additions & 0 deletions Sources/GOFeatureFlag/controller/goff_api.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import Foundation
import OpenFeature
import OFREP

class GoFeatureFlagAPI {
private let networkingService: NetworkingService
private let options: GoFeatureFlagProviderOptions
private let metadata: [String:String] = ["provider": "openfeature-swift"]

init(networkingService: NetworkingService, options: GoFeatureFlagProviderOptions) {
self.networkingService = networkingService
self.options = options
}

func postDataCollector(events: [FeatureEvent]?) async throws -> (DataCollectorResponse, HTTPURLResponse) {
guard let events = events else {
throw GoFeatureFlagError.noEventToSend
}
if events.isEmpty {
throw GoFeatureFlagError.noEventToSend
}

guard let url = URL(string: options.endpoint) else {
throw InvalidOptions.invalidEndpoint(message: "endpoint [" + options.endpoint + "] is not valid")
}

let dataCollectorURL = url.appendingPathComponent("v1/data/collector")
var request = URLRequest(url: dataCollectorURL)
request.httpMethod = "POST"

let requestBody = DataCollectorRequest(meta: metadata, events: events)
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
request.httpBody = try encoder.encode(requestBody)
request.setValue(
"application/json",
forHTTPHeaderField: "Content-Type"
)
if let apiKey = self.options.apiKey {
request.setValue("Bearer \(apiKey)", forHTTPHeaderField:"Authorization")
}

let (data, response) = try await networkingService.doRequest(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw GoFeatureFlagError.httpResponseCastError

Check warning on line 45 in Sources/GOFeatureFlag/controller/goff_api.swift

View check run for this annotation

Codecov / codecov/patch

Sources/GOFeatureFlag/controller/goff_api.swift#L45

Added line #L45 was not covered by tests
}

if httpResponse.statusCode == 401 {
throw GoFeatureFlagError.apiUnauthorizedError(response: httpResponse)
}
if httpResponse.statusCode == 403 {
throw GoFeatureFlagError.forbiddenError(response: httpResponse)
}
if httpResponse.statusCode >= 400 {
throw GoFeatureFlagError.unexpectedResponseError(response: httpResponse)
}

do {
let response = try JSONDecoder().decode(DataCollectorResponse.self, from: data)
return (response, httpResponse)
} catch {
throw GoFeatureFlagError.unmarshallError(error: error)
}
}
}
14 changes: 14 additions & 0 deletions Sources/GOFeatureFlag/exception/goff_errors.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import Foundation

enum GoFeatureFlagError: Error, Equatable {
static func == (left: GoFeatureFlagError, right: GoFeatureFlagError) -> Bool {
return type(of: left) == type(of: right)
}

case httpResponseCastError
case noEventToSend
case unmarshallError(error: Error)
case apiUnauthorizedError(response: HTTPURLResponse)
case forbiddenError(response: HTTPURLResponse)
case unexpectedResponseError(response: HTTPURLResponse)
}
72 changes: 72 additions & 0 deletions Sources/GOFeatureFlag/hook/data_collector_bool_hook.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import Foundation
import OpenFeature
import OFREP

class BooleanHook: Hook {
typealias HookValue = Bool
let dataCollectorMngr: DataCollectorManager

init(dataCollectorMngr: DataCollectorManager) {
self.dataCollectorMngr = dataCollectorMngr
}

func before<HookValue>(ctx: HookContext<HookValue>, hints: [String: Any]) {
return
}

func after<HookValue>(
ctx: HookContext<HookValue>,
details: FlagEvaluationDetails<HookValue>,
hints: [String: Any]) {
let contextKind = "user"
let userKey = ctx.ctx?.getTargetingKey() ?? ""
let key = ctx.flagKey
guard let value = details.value as? Bool else {
NSLog("Default value is not of type Bool")
return

Check warning on line 26 in Sources/GOFeatureFlag/hook/data_collector_bool_hook.swift

View check run for this annotation

Codecov / codecov/patch

Sources/GOFeatureFlag/hook/data_collector_bool_hook.swift#L25-L26

Added lines #L25 - L26 were not covered by tests
}

let event = FeatureEvent(
kind: "feature",
contextKind: contextKind,
userKey: userKey,
creationDate: Int64(Date().timeIntervalSince1970),
key: key,
variation: details.variant ?? "SdkDefault",
value: JSONValue.bool(value),
default: false,
source: "PROVIDER_CACHE"
)
self.dataCollectorMngr.appendFeatureEvent(event: event)
}

func error<HookValue>(
ctx: HookContext<HookValue>,
error: Error,
hints: [String: Any]) {
let contextKind = "user"
let userKey = ctx.ctx?.getTargetingKey() ?? ""
let key = ctx.flagKey
guard let value = ctx.defaultValue as? Bool else {
NSLog("Default value is not of type Bool")
return

Check warning on line 52 in Sources/GOFeatureFlag/hook/data_collector_bool_hook.swift

View check run for this annotation

Codecov / codecov/patch

Sources/GOFeatureFlag/hook/data_collector_bool_hook.swift#L51-L52

Added lines #L51 - L52 were not covered by tests
}

let event = FeatureEvent(
kind: "feature",
contextKind: contextKind,
userKey: userKey,
creationDate: Int64(Date().timeIntervalSince1970),
key: key,
variation: "SdkDefault",
value: JSONValue.bool(value),
default: true,
source: "PROVIDER_CACHE"
)
self.dataCollectorMngr.appendFeatureEvent(event: event)
}

func finallyAfter<HookValue>(ctx: HookContext<HookValue>, hints: [String: Any]) {
return
}
}
73 changes: 73 additions & 0 deletions Sources/GOFeatureFlag/hook/data_collector_double_hook.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import Foundation
import OpenFeature
import OFREP

class DoubleHook: Hook {
typealias HookValue = Double
let dataCollectorMngr: DataCollectorManager

init(dataCollectorMngr: DataCollectorManager) {
self.dataCollectorMngr = dataCollectorMngr
}

func before<HookValue>(ctx: HookContext<HookValue>, hints: [String: Any]) {
return
}

func after<HookValue>(
ctx: HookContext<HookValue>,
details: FlagEvaluationDetails<HookValue>,
hints: [String: Any]) {
let contextKind = "user"
let userKey = ctx.ctx?.getTargetingKey() ?? ""
let key = ctx.flagKey
guard let value = details.value as? Double else {
NSLog("Default value is not of type Double")
return

Check warning on line 26 in Sources/GOFeatureFlag/hook/data_collector_double_hook.swift

View check run for this annotation

Codecov / codecov/patch

Sources/GOFeatureFlag/hook/data_collector_double_hook.swift#L25-L26

Added lines #L25 - L26 were not covered by tests
}

let event = FeatureEvent(
kind: "feature",
contextKind: contextKind,
userKey: userKey,
creationDate: Int64(Date().timeIntervalSince1970),
key: key,
variation: details.variant ?? "SdkDefault",
value: JSONValue.double(value),
default: false,
source: "PROVIDER_CACHE"
)
self.dataCollectorMngr.appendFeatureEvent(event: event)
}

func error<HookValue>(
ctx: HookContext<HookValue>,
error: Error,
hints: [String: Any]) {
let contextKind = "user"
let userKey = ctx.ctx?.getTargetingKey() ?? ""
let key = ctx.flagKey

guard let value = ctx.defaultValue as? Double else {
NSLog("Default value is not of type Double")
return

Check warning on line 53 in Sources/GOFeatureFlag/hook/data_collector_double_hook.swift

View check run for this annotation

Codecov / codecov/patch

Sources/GOFeatureFlag/hook/data_collector_double_hook.swift#L52-L53

Added lines #L52 - L53 were not covered by tests
}

let event = FeatureEvent(
kind: "feature",
contextKind: contextKind,
userKey: userKey,
creationDate: Int64(Date().timeIntervalSince1970),
key: key,
variation: "SdkDefault",
value: JSONValue.double(value),
default: true,
source: "PROVIDER_CACHE"
)
self.dataCollectorMngr.appendFeatureEvent(event: event)
}

func finallyAfter<HookValue>(ctx: HookContext<HookValue>, hints: [String: Any]) {
return
}
}
69 changes: 69 additions & 0 deletions Sources/GOFeatureFlag/hook/data_collector_integer_hook.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import Foundation
import OpenFeature
import OFREP

class IntegerHook: Hook {
typealias HookValue = Int64
let dataCollectorMngr: DataCollectorManager

init(dataCollectorMngr: DataCollectorManager) {
self.dataCollectorMngr = dataCollectorMngr
}

func before<HookValue>(ctx: HookContext<HookValue>, hints: [String: Any]) {
return
}

func after<HookValue>(
ctx: HookContext<HookValue>,
details: FlagEvaluationDetails<HookValue>,
hints: [String: Any]) {
let contextKind = "user"
let userKey = ctx.ctx?.getTargetingKey() ?? ""
let key = ctx.flagKey
guard let value = details.value as? Int64 else {
NSLog("Default value is not of type Integer")
return

Check warning on line 26 in Sources/GOFeatureFlag/hook/data_collector_integer_hook.swift

View check run for this annotation

Codecov / codecov/patch

Sources/GOFeatureFlag/hook/data_collector_integer_hook.swift#L25-L26

Added lines #L25 - L26 were not covered by tests
}

let event = FeatureEvent(
kind: "feature",
contextKind: contextKind,
userKey: userKey,
creationDate: Int64(Date().timeIntervalSince1970),
key: key,
variation: details.variant ?? "SdkDefault",
value: JSONValue.integer(value),
default: false,
source: "PROVIDER_CACHE"
)
self.dataCollectorMngr.appendFeatureEvent(event: event)
}

func error<HookValue>(ctx: HookContext<HookValue>, error: Error, hints: [String: Any]) {
let contextKind = "user"
let userKey = ctx.ctx?.getTargetingKey() ?? ""
let key = ctx.flagKey
guard let value = ctx.defaultValue as? Int64 else {
NSLog("Default value is not of type Integer")
return

Check warning on line 49 in Sources/GOFeatureFlag/hook/data_collector_integer_hook.swift

View check run for this annotation

Codecov / codecov/patch

Sources/GOFeatureFlag/hook/data_collector_integer_hook.swift#L48-L49

Added lines #L48 - L49 were not covered by tests
}

let event = FeatureEvent(
kind: "feature",
contextKind: contextKind,
userKey: userKey,
creationDate: Int64(Date().timeIntervalSince1970),
key: key,
variation: "SdkDefault",
value: JSONValue.integer(value),
default: true,
source: "PROVIDER_CACHE"
)
self.dataCollectorMngr.appendFeatureEvent(event: event)
}

func finallyAfter<HookValue>(ctx: HookContext<HookValue>, hints: [String: Any]) {
return
}
}
Loading