Skip to content
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
6 changes: 3 additions & 3 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jobs:

steps:
- name: Check out repository
uses: actions/checkout@v6
uses: actions/checkout@v7

- name: Set up Xcode
uses: maxim-lobanov/setup-xcode@v1
Expand Down Expand Up @@ -63,7 +63,7 @@ jobs:

steps:
- name: Check out repository
uses: actions/checkout@v6
uses: actions/checkout@v7

- name: Set up Xcode
uses: maxim-lobanov/setup-xcode@v1
Expand Down Expand Up @@ -91,7 +91,7 @@ jobs:
run: ./scripts/verify-consumers.sh

- name: Set up Node.js
uses: actions/setup-node@v6
uses: actions/setup-node@v7
with:
node-version-file: ".nvmrc"
package-manager-cache: false
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:

steps:
- name: Check out repository
uses: actions/checkout@v6
uses: actions/checkout@v7

- name: Set up Xcode
uses: maxim-lobanov/setup-xcode@v1
Expand All @@ -26,7 +26,7 @@ jobs:
shell: bash
run: |
if [[ ! "$GITHUB_REF_NAME" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
echo "Expected a semantic version tag such as v1.1.0"
echo "Expected a semantic version tag such as v2.0.0"
exit 1
fi
version="${GITHUB_REF_NAME#v}"
Expand Down
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ This SDK is compatible with [Featurevisor](https://featurevisor.com/) v3.0 proje
In your Swift application, add this package using Swift Package Manager:

```swift
.package(url: "https://github.com/featurevisor/featurevisor-swift2.git", from: "1.1.0")
.package(url: "https://github.com/featurevisor/featurevisor-swift2.git", from: "2.0.0")
```

Then add the product dependency:
Expand Down Expand Up @@ -544,8 +544,13 @@ let child = f.spawn([
])

let enabled = child.isEnabled("my_feature")
let flagEvaluation = child.evaluateFlag("my_feature")
let variationEvaluation = child.evaluateVariation("my_feature")
let variableEvaluation = child.evaluateVariable("my_feature", "my_variable")
```

A child snapshots the parent keys that exist when it is spawned. Child values win for those keys. Parent keys introduced later are still inherited. Calling `close()` removes both child-owned listeners and subscriptions delegated to the parent.

## Close

To clear listeners and close resources:
Expand Down Expand Up @@ -594,7 +599,7 @@ swift run featurevisor assess-distribution \
The package exposes `FeaturevisorOpenFeature` as a separate library product. Targets using it should declare both package dependencies:

```swift
.package(url: "https://github.com/featurevisor/featurevisor-swift2.git", from: "1.1.0"),
.package(url: "https://github.com/featurevisor/featurevisor-swift2.git", from: "2.0.0"),
.package(url: "https://github.com/open-feature/swift-sdk.git", from: "0.5.0")
```

Expand Down Expand Up @@ -702,7 +707,7 @@ To verify the public products from clean consumer packages:
./scripts/verify-consumers.sh
```

Release tags use semantic versions such as `v1.1.0`. The release validation workflow tests both public library targets and clean consumers for every release tag.
Release tags use semantic versions such as `v2.0.0`. The release validation workflow tests both public library targets and clean consumers for every release tag.

## License

Expand Down
54 changes: 41 additions & 13 deletions Sources/Featurevisor/Bucketer.swift
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import Foundation

public let MAX_BUCKETED_NUMBER = 100_000
let MAX_BUCKETED_NUMBER = 100_000

public func getBucketKey(featureKey: FeatureKey, bucketBy: BucketBy, context: Context) -> String? {
func getBucketKey(featureKey: FeatureKey, bucketBy: BucketBy, context: Context) -> String? {
var parts: [String] = []

switch bucketBy {
case .single(let key):
if let value = context[key] {
if let value = bucketValue(context, path: key) {
parts.append(stringify(value))
}
case .and(let keys):
for key in keys {
if let value = context[key] {
if let value = bucketValue(context, path: key) {
parts.append(stringify(value))
}
}
case .or(let value):
for key in value.or {
if let raw = context[key] {
if let raw = bucketValue(context, path: key) {
parts.append(stringify(raw))
break
}
Expand All @@ -29,23 +29,51 @@ public func getBucketKey(featureKey: FeatureKey, bucketBy: BucketBy, context: Co
return parts.joined(separator: ".")
}

public func getBucketedNumber(_ bucketKey: String) -> Int {
private func bucketValue(_ context: Context, path: String) -> AnyValue? {
let parts = path.split(separator: ".").map(String.init)
guard let first = parts.first, var value = context[first] else { return nil }
for part in parts.dropFirst() {
guard case .object(let object) = value, let nested = object[part] else { return nil }
value = nested
}
return value
}

func getBucketedNumber(_ bucketKey: String) -> Int {
let hash = murmurhash3(bucketKey)
let ratio = Double(hash) / 4_294_967_296.0 // 2^32, matching TypeScript SDK
return Int(floor(ratio * Double(MAX_BUCKETED_NUMBER)))
}

public func stringify(_ value: AnyValue) -> String {
func stringify(_ value: AnyValue) -> String {
switch value {
case .string(let v): return v
case .int(let v): return String(v)
case .double(let v): return String(v)
case .double(let v): return stringifyDouble(v)
case .bool(let v): return v ? "true" : "false"
case .null: return "null"
case .array, .object:
if let data = try? JSONEncoder().encode(value), let text = String(data: data, encoding: .utf8) {
return text
case .null: return ""
case .array(let values): return values.map(stringify).joined(separator: ",")
case .object: return "[object Object]"
}
}

private func stringifyDouble(_ value: Double) -> String {
if value.isNaN { return "NaN" }
if value == .infinity { return "Infinity" }
if value == -.infinity { return "-Infinity" }
if value == 0 { return "0" }

let absolute = abs(value)
let raw = String(value).lowercased()
if absolute >= 1e-6 && absolute < 1e21 {
if let decimal = Decimal(string: raw, locale: Locale(identifier: "en_US_POSIX")) {
return NSDecimalNumber(decimal: decimal).stringValue
}
return ""
return raw.hasSuffix(".0") ? String(raw.dropLast(2)) : raw
}

let parts = raw.split(separator: "e", maxSplits: 1).map(String.init)
guard parts.count == 2, let exponent = Int(parts[1]) else { return raw }
let coefficient = parts[0].hasSuffix(".0") ? String(parts[0].dropLast(2)) : parts[0]
return "\(coefficient)e\(exponent >= 0 ? "+" : "")\(exponent)"
}
50 changes: 42 additions & 8 deletions Sources/Featurevisor/Child.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ public final class FeaturevisorChildInstance: @unchecked Sendable {
private var context: Context
private var sticky: StickyFeatures?
private let emitter = Emitter()
private var parentUnsubscribers: [(UUID, FeaturevisorUnsubscribe)] = []

init(parent: Featurevisor, context: Context, sticky: StickyFeatures?) {
self.parent = parent
Expand All @@ -14,35 +15,68 @@ public final class FeaturevisorChildInstance: @unchecked Sendable {
}

public func getContext(_ context: Context? = nil) -> Context {
lock.withLock {
guard let context else { return self.context }
return self.context.merging(context, uniquingKeysWith: { _, new in new })
let childContext = lock.withLock {
self.context.merging(context ?? [:], uniquingKeysWith: { _, new in new })
}
return parent.getContext(childContext)
}

public func setContext(_ context: Context, replace: Bool = false) {
lock.withLock {
let updatedContext = lock.withLock {
self.context = replace ? context : self.context.merging(context, uniquingKeysWith: { _, new in new })
return self.context
}
emitter.trigger(.contextSet)
emitter.trigger(.contextSet, payload: EventPayload([
"context": .object(updatedContext),
"replaced": .bool(replace),
]))
}

public func setSticky(_ sticky: StickyFeatures, replace: Bool = false) {
lock.withLock {
let values = lock.withLock { () -> (StickyFeatures, StickyFeatures) in
let previous = self.sticky ?? [:]
self.sticky = replace ? sticky : (self.sticky ?? [:]).merging(sticky, uniquingKeysWith: { _, new in new })
return (previous, self.sticky ?? [:])
}
emitter.trigger(.stickySet)
emitter.trigger(
.stickySet,
payload: EventPayload(
getParamsForStickySetEvent(
previousStickyFeatures: values.0,
newStickyFeatures: values.1,
replace: replace
)
)
)
}

@discardableResult
public func on(_ eventName: EventName, callback: @escaping EventCallback) -> () -> Void {
if eventName == .contextSet || eventName == .stickySet {
return emitter.on(eventName, callback: callback)
}
return parent.on(eventName, callback: callback)
let parentUnsubscribe = parent.on(eventName, callback: callback)
let token = UUID()
var active = true
let unsubscribe: FeaturevisorUnsubscribe = { [weak self] in
guard active else { return }
active = false
parentUnsubscribe()
self?.lock.withLock {
self?.parentUnsubscribers.removeAll { $0.0 == token }
}
}
lock.withLock { parentUnsubscribers.append((token, unsubscribe)) }
return unsubscribe
}

public func close() {
let unsubscribers = lock.withLock { () -> [FeaturevisorUnsubscribe] in
let current = parentUnsubscribers.map(\.1)
parentUnsubscribers = []
return current
}
unsubscribers.forEach { $0() }
emitter.clearAll()
}

Expand Down
98 changes: 89 additions & 9 deletions Sources/Featurevisor/CompareVersions.swift
Original file line number Diff line number Diff line change
@@ -1,22 +1,102 @@
import Foundation

public enum VersionComparison: Sendable {
enum VersionComparison: Sendable, Equatable {
case lessThan
case equal
case greaterThan
}

public func compareVersions(_ lhs: String, _ rhs: String) -> VersionComparison {
let left = lhs.split(separator: ".").map { Int($0) ?? 0 }
let right = rhs.split(separator: ".").map { Int($0) ?? 0 }
let count = max(left.count, right.count)
private struct InvalidSemanticVersion: LocalizedError {
let value: String

var errorDescription: String? {
"Invalid argument not valid semver ('\(value)' received)"
}
}

private let semanticVersionPattern = try! NSRegularExpression(
pattern: #"^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$"#,
options: [.caseInsensitive]
)

func compareVersions(_ lhs: String, _ rhs: String) throws -> VersionComparison {
guard let left = ParsedVersion(lhs) else { throw InvalidSemanticVersion(value: lhs) }
guard let right = ParsedVersion(rhs) else { throw InvalidSemanticVersion(value: rhs) }
let count = max(left.core.count, right.core.count)

for idx in 0..<count {
let l = idx < left.count ? left[idx] : 0
let r = idx < right.count ? right[idx] : 0
if l < r { return .lessThan }
if l > r { return .greaterThan }
let l = idx < left.core.count ? left.core[idx] : "0"
let r = idx < right.core.count ? right.core[idx] : "0"
let comparison = compareIdentifier(l, r)
if comparison < 0 { return .lessThan }
if comparison > 0 { return .greaterThan }
}

switch (left.prerelease, right.prerelease) {
case (nil, nil):
return .equal
case (.some, nil):
return .lessThan
case (nil, .some):
return .greaterThan
case let (.some(leftPrerelease), .some(rightPrerelease)):
let prereleaseCount = max(leftPrerelease.count, rightPrerelease.count)
for idx in 0..<prereleaseCount {
let l = idx < leftPrerelease.count ? leftPrerelease[idx] : "0"
let r = idx < rightPrerelease.count ? rightPrerelease[idx] : "0"
let comparison = compareIdentifier(l, r)
if comparison < 0 { return .lessThan }
if comparison > 0 { return .greaterThan }
}
}

return .equal
}

private struct ParsedVersion {
let core: [String]
let prerelease: [String]?

init?(_ value: String) {
let fullRange = NSRange(value.startIndex..<value.endIndex, in: value)
guard let match = semanticVersionPattern.firstMatch(
in: value,
range: fullRange
), match.range == fullRange else {
return nil
}

func capture(_ index: Int) -> String? {
let range = match.range(at: index)
guard range.location != NSNotFound, let swiftRange = Swift.Range(range, in: value) else {
return nil
}
return String(value[swiftRange])
}

self.core = (1...4).compactMap(capture)
self.prerelease = capture(5)?.split(separator: ".").map(String.init)
}
}

private func compareIdentifier(_ lhs: String, _ rhs: String) -> Int {
if ["x", "X", "*"].contains(lhs) || ["x", "X", "*"].contains(rhs) {
return 0
}

if let left = Int(lhs), let right = Int(rhs) {
if left < right { return -1 }
if left > right { return 1 }
return 0
}

let left = lhs
let right = rhs
if left < right {
return -1
}
if left > right {
return 1
}
return 0
}
Loading
Loading