Skip to content

Commit

Permalink
Allow external ownership for Modules (#106)
Browse files Browse the repository at this point in the history
# Allow external ownership for Modules

## ♻️ Current situation & Problem
When loading modules dynamically using `loadModule(_:)`, Spezi always
takes ownership of the Module. Spezi keeps a strong reference until
`unloadModule(_:)` is called. This isn't strictly necessary (with some
conditions applying). In some cases it is helpful for framework
engineers to not pass ownership to Spezi. Namely, one can make use of
being notified when objects are de-initialized (e.g., a framework
creating a Module and passing ownership to the framework user and
relying on the deinit to be notified when the user deallocated the
object).

This PR introduces the concept of `ModuleOwnership` that can be passed
to the updated `loadModule(_:ownership:)` method. `external` ownership
is available to framework developers via the `APISupport` SPI.
When specifying `external` ownership does not keep any strong references
to the loaded Module. This required making some changes how resources
are automatically cleared (e.g., `@Dependency`, `@Provide`, `@Modifier`
or `@Model` modifiers automatically clean up their resources once their
are deallocated). Some features like `EnvironmentAccessible` are not
available when using `external` ownership as they would inherently imply
strong ownership.
Other modules that depend on such modules either maintain a weak
reference if they declare it as an optional dependency (in this case the
dependency is automatically removed once the Module de-initializes) or a
strong reference if declared as a required dependency. In such a case,
ownership is shared with that module for the lifetime of the module that
declares a required dependency to an externally managed module.

## ⚙️ Release Notes 
* Add support for dynamically loading Modules with external ownership. 


## 📚 Documentation
Documentation was updated for changed interfaces.


## ✅ Testing
Additional unit testing was added to verify functionality of dynamically
loaded modules with external ownership.


## 📝 Code of Conduct & Contributing Guidelines 

By submitting creating this pull request, you agree to follow our [Code
of
Conduct](https://github.com/StanfordSpezi/.github/blob/main/CODE_OF_CONDUCT.md)
and [Contributing
Guidelines](https://github.com/StanfordSpezi/.github/blob/main/CONTRIBUTING.md):
- [x] I agree to follow the [Code of
Conduct](https://github.com/StanfordSpezi/.github/blob/main/CODE_OF_CONDUCT.md)
and [Contributing
Guidelines](https://github.com/StanfordSpezi/.github/blob/main/CONTRIBUTING.md).
  • Loading branch information
Supereg authored Jun 26, 2024
1 parent 734f90c commit 5ada3f3
Show file tree
Hide file tree
Showing 38 changed files with 675 additions and 226 deletions.
50 changes: 44 additions & 6 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,15 @@
// SPDX-License-Identifier: MIT
//

import class Foundation.ProcessInfo
import PackageDescription

#if swift(<6)
let swiftConcurrency: SwiftSetting = .enableExperimentalFeature("SwiftConcurrency")
#else
let swiftConcurrency: SwiftSetting = .enableUpcomingFeature("SwiftConcurrency")
#endif


let package = Package(
name: "Spezi",
Expand All @@ -27,29 +34,60 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/StanfordSpezi/SpeziFoundation", from: "1.0.2"),
.package(url: "https://github.com/StanfordBDHG/XCTRuntimeAssertions", from: "1.0.1")
],
.package(url: "https://github.com/StanfordBDHG/XCTRuntimeAssertions", from: "1.0.1"),
.package(url: "https://github.com/apple/swift-collections.git", from: "1.1.1")
] + swiftLintPackage(),
targets: [
.target(
name: "Spezi",
dependencies: [
.product(name: "SpeziFoundation", package: "SpeziFoundation"),
.product(name: "XCTRuntimeAssertions", package: "XCTRuntimeAssertions")
]
.product(name: "XCTRuntimeAssertions", package: "XCTRuntimeAssertions"),
.product(name: "OrderedCollections", package: "swift-collections")
],
swiftSettings: [
swiftConcurrency
],
plugins: [] + swiftLintPlugin()
),
.target(
name: "XCTSpezi",
dependencies: [
.target(name: "Spezi")
]
],
swiftSettings: [
swiftConcurrency
],
plugins: [] + swiftLintPlugin()
),
.testTarget(
name: "SpeziTests",
dependencies: [
.target(name: "Spezi"),
.target(name: "XCTSpezi"),
.product(name: "XCTRuntimeAssertions", package: "XCTRuntimeAssertions")
]
],
swiftSettings: [
swiftConcurrency
],
plugins: [] + swiftLintPlugin()
)
]
)

func swiftLintPlugin() -> [Target.PluginUsage] {
// Fully quit Xcode and open again with `open --env SPEZI_DEVELOPMENT_SWIFTLINT /Applications/Xcode.app`
if ProcessInfo.processInfo.environment["SPEZI_DEVELOPMENT_SWIFTLINT"] != nil {
[.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLint")]
} else {
[]
}
}

func swiftLintPackage() -> [PackageDescription.Package.Dependency] {
if ProcessInfo.processInfo.environment["SPEZI_DEVELOPMENT_SWIFTLINT"] != nil {
[.package(url: "https://github.com/realm/SwiftLint.git", .upToNextMinor(from: "0.55.1"))]
} else {
[]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ public class _CollectPropertyWrapper<Value> {

extension _CollectPropertyWrapper: StorageValueCollector {
public func retrieve<Repository: SharedRepository<SpeziAnchor>>(from repository: Repository) {
injectedValues = repository[CollectedModuleValues<Value>.self]?.map { $0.value } ?? []
injectedValues = repository[CollectedModuleValues<Value>.self].reduce(into: []) { partialResult, entry in
partialResult.append(contentsOf: entry.value)
}
}

func clear() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,74 +6,16 @@
// SPDX-License-Identifier: MIT
//

import Foundation
import OrderedCollections
import SpeziFoundation

protocol AnyCollectModuleValue {
associatedtype Value

var moduleReference: ModuleReference { get }
}

protocol AnyCollectModuleValues {
associatedtype Value

var values: [any AnyCollectModuleValue] { get }

mutating func removeValues(from module: any Module) -> Bool

func store(into storage: inout SpeziStorage)
}


struct CollectModuleValue<Value>: AnyCollectModuleValue {
let value: Value
let moduleReference: ModuleReference

init(_ value: Value) {
self.value = value

guard let module = Spezi.moduleInitContext else {
preconditionFailure("Tried to initialize CollectModuleValue with unknown module init context.")
}
self.moduleReference = ModuleReference(module)
}
}

/// Provides the ``KnowledgeSource`` for any value we store in the ``SpeziStorage`` that is
/// provided or request from am ``Module``.
///
/// For more information, look at the ``Module/Provide`` or ``Module/Collect`` property wrappers.
struct CollectedModuleValues<ModuleValue>: DefaultProvidingKnowledgeSource {
typealias Anchor = SpeziAnchor

typealias Value = [CollectModuleValue<ModuleValue>]

typealias Value = OrderedDictionary<UUID, [ModuleValue]>

static var defaultValue: Value {
[]
}
}


extension Array: AnyCollectModuleValues where Element: AnyCollectModuleValue {
typealias Value = Element.Value

var values: [any AnyCollectModuleValue] {
self
}

mutating func removeValues(from module: any Module) -> Bool {
let previousCount = count
removeAll { entry in
entry.moduleReference == ModuleReference(module)
}
return previousCount != count
}

func store(into storage: inout SpeziStorage) {
guard let values = self as? [CollectModuleValue<Value>] else {
preconditionFailure("Unexpected array type: \(type(of: self))")
}
storage[CollectedModuleValues<Value>.self] = values
[:]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,25 @@
// SPDX-License-Identifier: MIT
//


import Foundation
import SpeziFoundation
import XCTRuntimeAssertions


/// A protocol that identifies a ``_ProvidePropertyWrapper`` which `Value` type is a `Collection`.
protocol CollectionBasedProvideProperty {
func collectArrayElements<Repository: SharedRepository<SpeziAnchor>>(into repository: inout Repository)

func clearValues()
}


/// A protocol that identifies a ``_ProvidePropertyWrapper`` which `Value` type is a `Optional`.
protocol OptionalBasedProvideProperty {
func collectOptional<Repository: SharedRepository<SpeziAnchor>>(into repository: inout Repository)

func clearValues()
}


Expand All @@ -28,10 +34,16 @@ public class _ProvidePropertyWrapper<Value> {
// swiftlint:disable:previous type_name
// We want the type to be hidden from autocompletion and documentation generation

/// Persistent identifier to store and remove @Provide values.
fileprivate let id = UUID()

private var storedValue: Value
private var collected = false


private weak var spezi: Spezi?


/// Access the store value.
/// - Note: You cannot access the value once it was collected.
public var wrappedValue: Value {
Expand All @@ -50,6 +62,15 @@ public class _ProvidePropertyWrapper<Value> {
public init(wrappedValue value: Value) {
self.storedValue = value
}

func inject(spezi: Spezi) {
self.spezi = spezi
}


deinit {
clear()
}
}


Expand Down Expand Up @@ -116,38 +137,54 @@ extension _ProvidePropertyWrapper: StorageValueProvider {
} else if let wrapperWithArray = self as? CollectionBasedProvideProperty {
wrapperWithArray.collectArrayElements(into: &repository)
} else {
repository.appendValues([CollectModuleValue(storedValue)])
repository.setValues(for: id, [storedValue])
}

collected = true
}

func clear() {
collected = false

if let wrapperWithOptional = self as? OptionalBasedProvideProperty {
wrapperWithOptional.clearValues()
} else if let wrapperWithArray = self as? CollectionBasedProvideProperty {
wrapperWithArray.clearValues()
} else {
spezi?.handleCollectedValueRemoval(for: id, of: Value.self)
}
}
}


extension _ProvidePropertyWrapper: CollectionBasedProvideProperty where Value: AnyArray {
func collectArrayElements<Repository: SharedRepository<SpeziAnchor>>(into repository: inout Repository) {
repository.appendValues(storedValue.unwrappedArray.map { CollectModuleValue($0) })
repository.setValues(for: id, storedValue.unwrappedArray)
}

func clearValues() {
spezi?.handleCollectedValueRemoval(for: id, of: Value.Element.self)
}
}


extension _ProvidePropertyWrapper: OptionalBasedProvideProperty where Value: AnyOptional {
func collectOptional<Repository: SharedRepository<SpeziAnchor>>(into repository: inout Repository) {
if let storedValue = storedValue.unwrappedOptional {
repository.appendValues([CollectModuleValue(storedValue)])
repository.setValues(for: id, [storedValue])
}
}

func clearValues() {
spezi?.handleCollectedValueRemoval(for: id, of: Value.Wrapped.self)
}
}


extension SharedRepository where Anchor == SpeziAnchor {
fileprivate mutating func appendValues<Value>(_ values: [CollectModuleValue<Value>]) {
fileprivate mutating func setValues<Value>(for id: UUID, _ values: [Value]) {
var current = self[CollectedModuleValues<Value>.self]
current.append(contentsOf: values)
current[id] = values
self[CollectedModuleValues<Value>.self] = current
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import SpeziFoundation
import SwiftUI


private class RemoteNotificationContinuation: DefaultProvidingKnowledgeSource {
private final class RemoteNotificationContinuation: DefaultProvidingKnowledgeSource {
typealias Anchor = SpeziAnchor

static let defaultValue = RemoteNotificationContinuation()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public struct UnregisterRemoteNotificationsAction {


/// Unregisters for all remote notifications received through Apple Push Notification service.
@MainActor
public func callAsFunction() {
#if os(watchOS)
let application = _Application.shared()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public protocol EnvironmentAccessible: AnyObject, Observable {}


extension EnvironmentAccessible {
var viewModifier: any ViewModifier {
ModelModifier(model: self)
var viewModifierInitialization: any ViewModifierInitialization {
ModelModifierInitialization(model: self)
}
}
17 changes: 15 additions & 2 deletions Sources/Spezi/Capabilities/Observable/ModelPropertyWrapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@ public class _ModelPropertyWrapper<Model: Observable & AnyObject> {
// swiftlint:disable:previous type_name
// We want the type to be hidden from autocompletion and documentation generation

let id = UUID()
private var storedValue: Model?
private var collected = false

private weak var spezi: Spezi?


/// Access the store model.
///
Expand All @@ -44,12 +47,22 @@ public class _ModelPropertyWrapper<Model: Observable & AnyObject> {
public init(wrappedValue: Model) {
self.storedValue = wrappedValue
}


deinit {
clear()
}
}


extension _ModelPropertyWrapper: SpeziPropertyWrapper {
func clear() {
collected = false
spezi?.handleViewModifierRemoval(for: id)
}

func inject(spezi: Spezi) {
self.spezi = spezi
}
}

Expand Down Expand Up @@ -84,15 +97,15 @@ extension Module {


extension _ModelPropertyWrapper: ViewModifierProvider {
var viewModifier: (any ViewModifier)? {
var viewModifierInitialization: (any ViewModifierInitialization)? {
collected = true

guard let storedValue else {
assertionFailure("@Model with type \(Model.self) was collected but no value was provided!")
return nil
}

return ModelModifier(model: storedValue)
return ModelModifierInitialization(model: storedValue)
}

var placement: ModifierPlacement {
Expand Down
Loading

0 comments on commit 5ada3f3

Please sign in to comment.