Skip to content
Open
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
13 changes: 13 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ let package = Package(
.library(name: "CreditKit", targets: ["CreditKit"]),
.library(name: "LifecycleKit", targets: ["LifecycleKit"]),
.library(name: "LifecycleKitUI", targets: ["LifecycleKitUI"]),
.library(name: "Flagger", targets: ["Flagger"]),
.library(name: "FlaggerUI", targets: ["FlaggerUI"]),
.library(name: "JournalKit", targets: ["JournalKit"]),
.library(name: "PeriscopeCore", targets: ["PeriscopeCore"]),
.library(name: "PeriscopeUI", targets: ["PeriscopeUI"]),
Expand Down Expand Up @@ -67,6 +69,17 @@ let package = Package(
name: "JournalKit",
path: "Shared/JournalKit/Sources",
),
.target(
name: "Flagger",
path: "Shared/Flagger/Sources",
),
.target(
name: "FlaggerUI",
dependencies: [
.target(name: "Flagger"),
],
path: "Shared/FlaggerUI/Sources",
),
.target(
name: "PeriscopeCore",
dependencies: [
Expand Down
29 changes: 29 additions & 0 deletions Project.swift
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,19 @@ let project = Project(
productDependency: "JournalKit",
sources: ["Shared/JournalKit/Tests/**"],
),
unitTests(
name: "FlaggerTests",
bundleIdSuffix: "flagger",
productDependency: "Flagger",
sources: ["Shared/Flagger/Tests/**"],
),
unitTests(
name: "FlaggerUITests",
bundleIdSuffix: "flaggerui",
productDependency: "FlaggerUI",
sources: ["Shared/FlaggerUI/Tests/**"],
extraPackageProducts: ["Flagger"],
),
unitTests(
name: "PeriscopeCoreTests",
bundleIdSuffix: "periscopecore",
Expand Down Expand Up @@ -556,6 +569,14 @@ let project = Project(
extraPackageProducts: ["SnapshotKitTesting"],
environmentVariables: snapshotEnvironment,
),
unitTests(
name: "FlaggerUISnapshotTests",
bundleIdSuffix: "flaggerui.snapshot",
productDependency: "FlaggerUI",
sources: ["Shared/FlaggerUI/SnapshotTests/**"],
extraPackageProducts: ["SnapshotKitTesting"],
environmentVariables: snapshotEnvironment,
),
.target(
name: "BroadwayCatalog",
destinations: destinations,
Expand Down Expand Up @@ -630,6 +651,8 @@ let project = Project(
"LifecycleKitTests",
"LifecycleKitUITests",
"JournalKitTests",
"FlaggerTests",
"FlaggerUITests",
"PeriscopeCoreTests",
"PeriscopeUITests",
"PeriscopeToolsTests",
Expand All @@ -654,6 +677,8 @@ let project = Project(
"LifecycleKitTests",
"LifecycleKitUITests",
"JournalKitTests",
"FlaggerTests",
"FlaggerUITests",
"PeriscopeCoreTests",
"PeriscopeUITests",
"PeriscopeToolsTests",
Expand All @@ -678,6 +703,8 @@ let project = Project(
testScheme(name: "LifecycleKitTests"),
testScheme(name: "LifecycleKitUITests"),
testScheme(name: "JournalKitTests"),
testScheme(name: "FlaggerTests"),
testScheme(name: "FlaggerUITests"),
testScheme(name: "PeriscopeCoreTests"),
testScheme(name: "PeriscopeUITests"),
testScheme(name: "PeriscopeToolsTests"),
Expand Down Expand Up @@ -706,13 +733,15 @@ let project = Project(
"FlyoverSnapshotTests",
"PeriscopeToolsSnapshotTests",
"InspectorSnapshotTests",
"FlaggerUISnapshotTests",
]),
testAction: .targets(
[
"WhereUISnapshotTests",
"FlyoverSnapshotTests",
"PeriscopeToolsSnapshotTests",
"InspectorSnapshotTests",
"FlaggerUISnapshotTests",
],
arguments: .arguments(environmentVariables: snapshotEnvironment),
),
Expand Down
23 changes: 23 additions & 0 deletions Shared/Flagger/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Flagger – Module Shape

Flagger is the SwiftUI-free feature-flag engine: typed group/source
registration, behavior policies, cached reads, failure streams, and
default-eliding SwiftData persistence. See [`README.md`](README.md).

This complements the root [`AGENTS.md`](../../AGENTS.md).

## Scope & dependencies

- Foundation, os, and SwiftData only; app flag groups and sources stay in consumers.
- One Flagger instance owns one scope and one physical store; create it once at the composition root and inject it down.

## Invariants

- Persist only overrides; writing the current default deletes the row.
- Launch and first-access policies freeze effective values for the instance lifetime; only `LiveUpdating` has public typed mutation and value-stream APIs.
- Sources, group types, and stable flag IDs are unique within a Flagger.
- Synchronous reads touch only `OSAllocatedUnfairLock` state; mutations replace its cache from a complete, versioned snapshot fetched by `FlaggerPersistence`.

## Testing

Swift Testing in [`Tests/`](Tests) uses fresh in-memory or temporary-URL stores.
78 changes: 78 additions & 0 deletions Shared/Flagger/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Flagger

Flagger is a scoped feature-flag engine backed by SwiftData. Modules own groups
of typed flags, expose those groups through a source, and the composition root
registers sources without enumerating their flags. Every flag has a default;
only JSON overrides different from that default are stored.

## Declare a group

```swift
public struct MapFlags: FeatureFlagGroup {
public static let id = FeatureFlagGroupID("map")
public static let name = "Map"

public let newRenderer = Flag<Bool, LiveUpdating>(
"new-renderer",
name: "New renderer",
default: true
)

public init() {}
}

public extension FeatureFlagGroups {
var map: MapFlags { self[MapFlags.self] }
}
```

The explicit flag ID is the persisted identity and must survive Swift property
renames. Group properties are discovered once when Flagger opens; the typed
definitions are erased only for persistence and editor metadata.

## Expose and register module sources

```swift
public enum WhereUIFlagSource: FlagSource {
public static let id = FlagSourceID("where-ui")
public static let name = "Where UI"
public static let groups = FeatureFlagGroupRegistry {
MapFlags.self
}
}

let sources = FlagSourceRegistry {
WhereCoreFlagSource.self
WhereUIFlagSource.self
}
let flagger = try await Flagger.open(
sources: sources,
storage: .onDisk(name: "WhereFlags")
)
```

Each Flagger instance owns one scope and physical store. Use distinct instances
for app-wide, logged-in, demo, or other worlds; inject an existing
`ModelContainer` or explicit URL when the host owns store placement.

## Behaviors and access

- `ReadOnceOnLaunch` resolves when Flagger opens.
- `ReadOnceOnFirstAccess` resolves on its first read.
- `LiveUpdating` may be changed and observed while Flagger is alive.

Reads are synchronous from lock-protected state loaded at open. SwiftData opens
and writes remain asynchronous and actor-isolated. Because flags change rarely,
each mutation reloads the complete override store and atomically replaces the
cache with the newest versioned snapshot:

```swift
let enabled = try flagger.value(for: MapFlags().newRenderer)
try await flagger.set(false, for: MapFlags().newRenderer)
for await enabled in flagger.values(for: MapFlags().newRenderer) { /* … */ }
```

`value(for:)` throws decoding failures. `valueOrDefault(for:)` returns the
declared default and emits the failure through `failures()`. A failed frozen
flag stays on its default for that lifetime; repairing its override applies to
the next applicable lifetime.
25 changes: 25 additions & 0 deletions Shared/Flagger/Sources/FeatureFlagBehavior.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/// A type-level policy controlling when a flag's effective value may change.
public protocol FeatureFlagBehavior: Sendable {
static var kind: FeatureFlagBehaviorKind { get }
}

/// Resolves when its Flagger opens and stays fixed for that instance's lifetime.
public enum ReadOnceOnLaunch: FeatureFlagBehavior {
public static let kind = FeatureFlagBehaviorKind.readOnceOnLaunch
}

/// Resolves on its first read and stays fixed for that Flagger instance's lifetime.
public enum ReadOnceOnFirstAccess: FeatureFlagBehavior {
public static let kind = FeatureFlagBehaviorKind.readOnceOnFirstAccess
}

/// Resolves from the current override and may be updated while Flagger is alive.
public enum LiveUpdating: FeatureFlagBehavior {
public static let kind = FeatureFlagBehaviorKind.liveUpdating
}

public enum FeatureFlagBehaviorKind: String, Codable, Sendable {
case readOnceOnLaunch
case readOnceOnFirstAccess
case liveUpdating
}
42 changes: 42 additions & 0 deletions Shared/Flagger/Sources/FeatureFlagGroup.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/// A named collection of feature-flag definitions owned by one module source.
public protocol FeatureFlagGroup: Sendable {
init()
static var id: FeatureFlagGroupID { get }
static var name: String { get }
static var detail: String? { get }
}

extension FeatureFlagGroup {
public static var detail: String? {
nil
}
}

/// Stable identity for a feature-flag group.
public struct FeatureFlagGroupID: Hashable, Codable, Sendable, RawRepresentable {
public let rawValue: String

public init(rawValue: String) {
precondition(rawValue.isEmpty == false, "A feature-flag group ID must not be empty.")
self.rawValue = rawValue
}

public init(_ rawValue: String) {
self.init(rawValue: rawValue)
}
}

public struct FeatureFlagGroupMetadata: Identifiable, Hashable, Sendable {
public let id: FeatureFlagGroupID
public let name: String
public let detail: String?
}

/// The environment-style namespace modules extend with named group accessors.
public struct FeatureFlagGroups: Sendable {
public init() {}

public subscript<Group: FeatureFlagGroup>(_: Group.Type) -> Group {
Group()

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Putting a pin in this; seems a bit weird at first glance.

}
}
47 changes: 47 additions & 0 deletions Shared/Flagger/Sources/FeatureFlagGroupRegistry.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/// An immutable, result-builder-created list of group types exposed by a source.
public struct FeatureFlagGroupRegistry: Sendable {
let types: [any FeatureFlagGroup.Type]

public init(@FeatureFlagGroupRegistryBuilder _ content: () -> [any FeatureFlagGroup.Type]) {
types = content()
}
}

@resultBuilder
public enum FeatureFlagGroupRegistryBuilder {
public static func buildExpression(
_ expression: (some FeatureFlagGroup).Type,
) -> [any FeatureFlagGroup.Type] {
[expression]
}

public static func buildBlock(
_ components: [any FeatureFlagGroup.Type]...,
) -> [any FeatureFlagGroup.Type] {
components.flatMap(\.self)
}

public static func buildOptional(
_ component: [any FeatureFlagGroup.Type]?,
) -> [any FeatureFlagGroup.Type] {
component ?? []
}

public static func buildEither(
first component: [any FeatureFlagGroup.Type],
) -> [any FeatureFlagGroup.Type] {
component
}

public static func buildEither(
second component: [any FeatureFlagGroup.Type],
) -> [any FeatureFlagGroup.Type] {
component
}

public static func buildArray(
_ components: [[any FeatureFlagGroup.Type]],
) -> [any FeatureFlagGroup.Type] {
components.flatMap(\.self)
}
}
50 changes: 50 additions & 0 deletions Shared/Flagger/Sources/Flag.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import Foundation

/// A typed feature-flag definition stored as a property on a ``FeatureFlagGroup``.
public struct Flag<Value: Codable & Sendable, Behavior: FeatureFlagBehavior>: Sendable {
public let id: FlagID
public let name: String
public let detail: String?
public let defaultValue: Value

public init(
_ id: FlagID,
name: String,
detail: String? = nil,
default defaultValue: Value,
) {
self.id = id
self.name = name
self.detail = detail
self.defaultValue = defaultValue
}

public init(
_ id: String,
name: String,
detail: String? = nil,
default defaultValue: Value,
) {
self.init(FlagID(rawValue: id), name: name, detail: detail, default: defaultValue)
}
}

protocol AnyFeatureFlag: Sendable {
func definition(
source: FeatureFlagSourceMetadata,
group: FeatureFlagGroupMetadata,
) throws -> FlagDefinition
}

extension Flag: AnyFeatureFlag {
func definition(
source: FeatureFlagSourceMetadata,
group: FeatureFlagGroupMetadata,
) throws -> FlagDefinition {
try FlagDefinition(
flag: self,
source: source,
group: group,
)
}
}
Loading
Loading