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
2 changes: 1 addition & 1 deletion .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ jobs:
run: |
mkdir example-1
cd example-1
npx --yes @featurevisor/cli@3.1.0 init --example=1
npx --yes @featurevisor/cli@3 init --example=1
npm install
npx featurevisor build
npx featurevisor test --onlyFailures
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 v2.0.0"
echo "Expected a semantic version tag such as v3.0.0"
exit 1
fi
version="${GITHUB_REF_NAME#v}"
Expand Down
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ let package = Package(
),
],
dependencies: [
.package(url: "https://github.com/open-feature/swift-sdk.git", from: "0.5.0")
.package(url: "https://github.com/open-feature/swift-sdk.git", .upToNextMinor(from: "0.5.0"))
],
targets: [
.target(
Expand Down
78 changes: 52 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ This SDK is compatible with [Featurevisor](https://featurevisor.com/) v3.0 proje
- [Getting variation](#getting-variation)
- [Getting variables](#getting-variables)
- [Type specific methods](#type-specific-methods)
- [Getting all evaluations](#getting-all-evaluations)
- [Sticky](#sticky)
- [Getting global variables](#getting-global-variables)
- [Getting aggregate evaluations](#getting-aggregate-evaluations)
- [Sticky features and variables](#sticky-features-and-variables)
- [Initialize with sticky](#initialize-with-sticky)
- [Set sticky afterwards](#set-sticky-afterwards)
- [Setting datafile](#setting-datafile)
Expand All @@ -35,7 +36,7 @@ This SDK is compatible with [Featurevisor](https://featurevisor.com/) v3.0 proje
- [Events](#events)
- [`datafile_set`](#datafile_set)
- [`context_set`](#context_set)
- [`sticky_set`](#sticky_set)
- [`sticky_features_set` and `sticky_variables_set`](#sticky_features_set-and-sticky_variables_set)
- [`error`](#error)
- [Evaluation details](#evaluation-details)
- [Modules](#modules)
Expand All @@ -59,7 +60,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: "2.0.0")
.package(url: "https://github.com/featurevisor/featurevisor-swift2.git", from: "3.0.0")
```

Then add the product dependency:
Expand Down Expand Up @@ -267,51 +268,64 @@ f.getVariableJSON(featureKey, variableKey, context)

Type specific methods do not coerce strings or booleans into numbers. They return `nil` when the value does not match the requested type.

## Getting all evaluations
## Getting global variables

Global variables use the same methods with a single variable key:

```swift
let message = f.getVariableString("welcomeMessage", context)
let value = f.getVariable("checkoutSettings", context)
let evaluation = f.evaluateVariable("checkoutSettings", context: context)
```

Global variables resolve sticky values first, then required features, then the first matching override, and finally their default value.

## Getting aggregate evaluations

You can get evaluations of all features available in the SDK instance:

```swift
let allEvaluations = f.getAllEvaluations([:])
let allEvaluations = f.getFeatureEvaluations([:])
print(allEvaluations)

let globalVariables = f.getVariableEvaluations([:])
```

This is handy especially when you want to pass all evaluations from a backend application to the frontend.

## Sticky
## Sticky features and variables

For the lifecycle of the SDK instance in your application, you can set some features with sticky values, meaning that they will not be evaluated against the fetched [datafile](https://featurevisor.com/docs/building-datafiles/):

Sticky values belong to an SDK or child instance. Evaluation options do not accept sticky overrides; use `SpawnOptions(sticky: ...)` when a child needs its own sticky state.

### Initialize with sticky
Sticky values belong to an SDK or child instance. Feature sticky values and global variable sticky values are independent.

```swift
let f = createFeaturevisor(
FeaturevisorOptions(
sticky: [
stickyFeatures: [
"myFeatureKey": EvaluatedFeature(
enabled: true,
variation: "treatment",
variables: ["myVariableKey": .string("myVariableValue")]
),
"anotherFeatureKey": EvaluatedFeature(enabled: false),
]
],
stickyVariables: ["welcomeMessage": .string("Welcome back")]
)
)
```

### Set sticky afterwards

```swift
f.setSticky([
f.setStickyFeatures([
"myFeatureKey": EvaluatedFeature(
enabled: true,
variation: "treatment",
variables: ["myVariableKey": .string("myVariableValue")]
),
"anotherFeatureKey": EvaluatedFeature(enabled: false),
], replace: true)

f.setStickyVariables(["welcomeMessage": .string("Welcome back")], replace: true)
```

## Setting datafile
Expand All @@ -332,7 +346,7 @@ f.setDatafile(json: jsonString)

By default, `setDatafile` merges the incoming datafile with the SDK instance's existing datafile:

- incoming `features` and `segments` override matching keys
- incoming `features`, `segments`, and global `variables` override matching keys
- existing `features` and `segments` that are missing from the incoming datafile are kept
- `revision`, `schemaVersion`, and `featurevisorVersion` are taken from the incoming datafile

Expand Down Expand Up @@ -451,14 +465,19 @@ let unsubscribe = f.on(.contextSet) { _ in
unsubscribe()
```

### `sticky_set`
### `sticky_features_set` and `sticky_variables_set`

```swift
let unsubscribe = f.on(.stickySet) { _ in
// handle sticky updates
let featureUnsubscribe = f.on(.stickyFeaturesSet) { _ in
// handle sticky feature updates
}

unsubscribe()
let variableUnsubscribe = f.on(.stickyVariablesSet) { _ in
// handle sticky global variable updates
}

featureUnsubscribe()
variableUnsubscribe()
```

### `error`
Expand All @@ -483,12 +502,15 @@ If you need evaluation metadata, use:
let flagDetails = f.evaluateFlag("my_feature")
let variationDetails = f.evaluateVariation("my_feature")
let variableDetails = f.evaluateVariable("my_feature", "my_variable")
let globalVariableDetails = f.evaluateVariable("welcomeMessage")
```

## Modules

Modules allow you to intercept evaluation inputs and outputs.

For feature evaluations, all `before` callbacks run in registration order, followed by all `beforeEvaluation` callbacks. After evaluation and caller defaults, all `afterEvaluation` callbacks run, followed by all `after` callbacks. Global variable evaluations use only `beforeEvaluation` and `afterEvaluation`. Required feature checks run through the complete module pipeline, and transformed defaults are preserved.

### Defining a module

```swift
Expand All @@ -508,6 +530,7 @@ let module = FeaturevisorModule(
updated.dependencies.context["someAdditionalAttribute"] = .string("value")
return updated
},
beforeEvaluation: { options in options },
bucketKey: { options in
options.bucketKey
},
Expand All @@ -517,6 +540,7 @@ let module = FeaturevisorModule(
after: { evaluation, _ in
evaluation
},
afterEvaluation: { evaluation, _ in evaluation },
close: {
// clean up module resources
}
Expand Down Expand Up @@ -549,6 +573,7 @@ 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")
let globalVariable = child.getVariable("welcomeMessage")
```

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.
Expand Down Expand Up @@ -601,7 +626,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: "2.0.0"),
.package(url: "https://github.com/featurevisor/featurevisor-swift2.git", from: "3.0.0"),
.package(url: "https://github.com/open-feature/swift-sdk.git", from: "0.5.0")
```

Expand Down Expand Up @@ -634,7 +659,7 @@ let enabled = client.getBooleanValue(
)
```

Use `checkout` for a flag, `checkout:variation` for its variation, and `checkout:title` for its `title` variable. Boolean variables use the boolean resolver. Lists, structures, and JSON variables use the object resolver.
Use `checkout` for a flag, `checkout:variation` for its variation, `checkout:title` for its `title` variable, and `variable:welcomeMessage` for a global variable. Boolean variables use the boolean resolver. Lists, structures, and JSON variables use the object resolver.

The provider maps Featurevisor values to OpenFeature resolvers as follows:

Expand All @@ -643,10 +668,11 @@ The provider maps Featurevisor values to OpenFeature resolvers as follows:
| `feature` | Boolean flag |
| `feature:variation` | String variation |
| `feature:variable` | Resolver matching the variable schema |
| `variable:key` | Resolver matching the global variable type |

Integer variables can be resolved with either the integer or double resolver. Non-finite doubles are rejected with `TYPE_MISMATCH`. Invalid JSON variables also return `TYPE_MISMATCH` and the caller's default value.

OpenFeature's targeting key maps to `userId` by default. `targetingKeyField`, `keySeparator`, and `variationKey` can customize the mapping. Call `provider.close()` when the application owns the provider lifecycle and is finished with it.
OpenFeature's targeting key maps to `userId` by default. `targetingKeyField`, `keySeparator`, `variationKey`, and `globalVariablePrefix` can customize the mapping. The global variable prefix defaults to `variable` and cannot contain the separator. Call `provider.close()` when the application owns the provider lifecycle and is finished with it.

You can initialize the provider from raw JSON when the application has not decoded a datafile yet:

Expand Down Expand Up @@ -674,12 +700,12 @@ Featurevisor evaluation reasons map to OpenFeature reasons:
| --- | --- |
| `required`, `forced`, `sticky`, `rule`, variable overrides | `TARGETING_MATCH` |
| `allocated` | `SPLIT` |
| disabled flag, variation, or variable | `DISABLED` |
| disabled flag, variation, or variable, and unmet global variable requirements | `DISABLED` |
| no match, out of range, variable default | `DEFAULT` |
| missing feature, variable, or variations | `ERROR` with `FLAG_NOT_FOUND` |
| evaluation error | `ERROR` with `GENERAL` |

Resolution metadata includes `featureKey`, `featurevisorReason`, `schemaVersion`, and `revision`. It also includes `variableKey`, `ruleKey`, `bucketKey`, `bucketValue`, `forceIndex`, and `variableOverrideIndex` when those values are available. Variation resolutions populate OpenFeature's `variant` field.
Resolution metadata includes `featureKey` when present, `featurevisorReason`, `schemaVersion`, and `revision`. It also includes `variableKey`, `ruleKey`, `bucketKey`, `bucketValue`, `forceIndex`, `variableOverrideIndex`, `variableOverrideKey`, and `variableOverridePath` when those values are available. Variation resolutions populate OpenFeature's `variant` field.

The provider forwards OpenFeature tracking calls to `onTrack`. Closing a provider it owns closes Featurevisor modules and subscriptions. Closing a provider created with a caller-owned Featurevisor instance only removes provider subscriptions.

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

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.
Release tags use semantic versions such as `v3.0.0`. The release validation workflow tests both public library targets and clean consumers for every release tag.

## License

Expand Down
51 changes: 38 additions & 13 deletions Sources/Featurevisor/Child.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ public final class FeaturevisorChildInstance: @unchecked Sendable {
private let lock = FeaturevisorLock()
private let parent: Featurevisor
private var context: Context
private var sticky: StickyFeatures?
private var stickyFeatures: StickyFeatures?
private var stickyVariables: StickyVariables?
private let emitter = Emitter()
private var parentUnsubscribers: [(UUID, FeaturevisorUnsubscribe)] = []

init(parent: Featurevisor, context: Context, sticky: StickyFeatures?) {
init(parent: Featurevisor, context: Context, stickyFeatures: StickyFeatures?, stickyVariables: StickyVariables?) {
self.parent = parent
self.context = context
self.sticky = sticky
self.stickyFeatures = stickyFeatures
self.stickyVariables = stickyVariables
}

public func getContext(_ context: Context? = nil) -> Context {
Expand All @@ -32,16 +34,16 @@ public final class FeaturevisorChildInstance: @unchecked Sendable {
]))
}

public func setSticky(_ sticky: StickyFeatures, replace: Bool = false) {
public func setStickyFeatures(_ sticky: StickyFeatures, replace: Bool = false) {
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 ?? [:])
let previous = self.stickyFeatures ?? [:]
self.stickyFeatures = replace ? sticky : (self.stickyFeatures ?? [:]).merging(sticky, uniquingKeysWith: { _, new in new })
return (previous, self.stickyFeatures ?? [:])
}
emitter.trigger(
.stickySet,
.stickyFeaturesSet,
payload: EventPayload(
getParamsForStickySetEvent(
getParamsForStickyFeaturesSetEvent(
previousStickyFeatures: values.0,
newStickyFeatures: values.1,
replace: replace
Expand All @@ -50,9 +52,18 @@ public final class FeaturevisorChildInstance: @unchecked Sendable {
)
}

public func setStickyVariables(_ sticky: StickyVariables, replace: Bool = false) {
let values = lock.withLock { () -> (StickyVariables, StickyVariables) in
let previous = stickyVariables ?? [:]
stickyVariables = replace ? sticky : previous.merging(sticky, uniquingKeysWith: { _, new in new })
return (previous, stickyVariables ?? [:])
}
emitter.trigger(.stickyVariablesSet, payload: EventPayload(getParamsForStickyVariablesSetEvent(previousStickyVariables: values.0, newStickyVariables: values.1, replace: replace)))
}

@discardableResult
public func on(_ eventName: EventName, callback: @escaping EventCallback) -> () -> Void {
if eventName == .contextSet || eventName == .stickySet {
if eventName == .contextSet || eventName == .stickyFeaturesSet || eventName == .stickyVariablesSet {
return emitter.on(eventName, callback: callback)
}
let parentUnsubscribe = parent.on(eventName, callback: callback)
Expand Down Expand Up @@ -85,7 +96,9 @@ public final class FeaturevisorChildInstance: @unchecked Sendable {
defaultVariationValue: options.defaultVariationValue,
defaultVariableValue: options.defaultVariableValue
)
merged.sticky = lock.withLock { sticky }
let values = lock.withLock { (stickyFeatures, stickyVariables) }
merged.stickyFeatures = values.0
merged.stickyVariables = values.1
return merged
}

Expand Down Expand Up @@ -113,6 +126,16 @@ public final class FeaturevisorChildInstance: @unchecked Sendable {
parent.getVariable(featureKey, variableKey, getContext(context), merge(options))
}

public func evaluateVariable(_ variableKey: VariableKey, context: Context = [:], options: OverrideOptions = OverrideOptions()) -> Evaluation { parent.evaluateVariable(variableKey, context: getContext(context), options: merge(options)) }
public func getVariable(_ variableKey: VariableKey, _ context: Context = [:], _ options: OverrideOptions = OverrideOptions()) -> VariableValue? { parent.getVariable(variableKey, getContext(context), merge(options)) }
public func getVariableBoolean(_ variableKey: VariableKey, _ context: Context = [:], _ options: OverrideOptions = OverrideOptions()) -> Bool? { parent.getVariableBoolean(variableKey, getContext(context), merge(options)) }
public func getVariableString(_ variableKey: VariableKey, _ context: Context = [:], _ options: OverrideOptions = OverrideOptions()) -> String? { parent.getVariableString(variableKey, getContext(context), merge(options)) }
public func getVariableInteger(_ variableKey: VariableKey, _ context: Context = [:], _ options: OverrideOptions = OverrideOptions()) -> Int? { parent.getVariableInteger(variableKey, getContext(context), merge(options)) }
public func getVariableDouble(_ variableKey: VariableKey, _ context: Context = [:], _ options: OverrideOptions = OverrideOptions()) -> Double? { parent.getVariableDouble(variableKey, getContext(context), merge(options)) }
public func getVariableArray(_ variableKey: VariableKey, _ context: Context = [:], _ options: OverrideOptions = OverrideOptions()) -> [AnyValue]? { parent.getVariableArray(variableKey, getContext(context), merge(options)) }
public func getVariableObject(_ variableKey: VariableKey, _ context: Context = [:], _ options: OverrideOptions = OverrideOptions()) -> [String: AnyValue]? { parent.getVariableObject(variableKey, getContext(context), merge(options)) }
public func getVariableJSON(_ variableKey: VariableKey, _ context: Context = [:], _ options: OverrideOptions = OverrideOptions()) -> AnyValue? { parent.getVariableJSON(variableKey, getContext(context), merge(options)) }

public func getVariableBoolean(_ featureKey: FeatureKey, _ variableKey: VariableKey, _ context: Context = [:], _ options: OverrideOptions = OverrideOptions()) -> Bool? {
parent.getVariableBoolean(featureKey, variableKey, getContext(context), merge(options))
}
Expand Down Expand Up @@ -141,7 +164,9 @@ public final class FeaturevisorChildInstance: @unchecked Sendable {
parent.getVariableJSON(featureKey, variableKey, getContext(context), merge(options))
}

public func getAllEvaluations(_ context: Context = [:], _ featureKeys: [FeatureKey] = [], _ options: OverrideOptions = OverrideOptions()) -> EvaluatedFeatures {
parent.getAllEvaluations(getContext(context), featureKeys, merge(options))
public func getFeatureEvaluations(_ context: Context = [:], _ featureKeys: [FeatureKey] = [], _ options: OverrideOptions = OverrideOptions()) -> EvaluatedFeatures {
parent.getFeatureEvaluations(getContext(context), featureKeys, merge(options))
}

public func getVariableEvaluations(_ context: Context = [:], _ variableKeys: [VariableKey] = [], _ options: OverrideOptions = OverrideOptions()) -> EvaluatedVariables { parent.getVariableEvaluations(getContext(context), variableKeys, merge(options)) }
}
3 changes: 2 additions & 1 deletion Sources/Featurevisor/Emitter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import Foundation
public enum EventName: String, Sendable {
case datafileSet = "datafile_set"
case contextSet = "context_set"
case stickySet = "sticky_set"
case stickyFeaturesSet = "sticky_features_set"
case stickyVariablesSet = "sticky_variables_set"
case error
}

Expand Down
Loading
Loading