Skip to content

Commit

Permalink
-some cleanup in the rules engine
Browse files Browse the repository at this point in the history
  • Loading branch information
sbenedicadb committed Jan 6, 2021
1 parent 47ebd2b commit 42d077d
Show file tree
Hide file tree
Showing 34 changed files with 308 additions and 169 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright 2020 Adobe
Copyright 2021 Adobe

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
44 changes: 38 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,43 @@ AEPRulesEngine is currently in beta. Use of this code is by invitation only and

A simple, generic, extensible Rules Engine in Swift.

## Requirements
- Xcode 11.0 (or newer)
- Swift 5.0 (or newer)

## Installation

### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html)
```ruby
# Podfile
use_frameworks!

# for app development, include all the following pods
target 'YOUR_TARGET_NAME' do
pod 'AEPRulesEngine', :git => 'https://github.com/adobe/aepsdk-rulesengine-ios.git', :branch => 'main'
pod 'AEPCore', :git => 'https://github.com/adobe/aepsdk-core-ios.git', :branch => 'main'
pod 'AEPServices', :git => 'https://github.com/adobe/aepsdk-core-ios.git', :branch => 'main'
pod 'AEPLifecycle', :git => 'https://github.com/adobe/aepsdk-core-ios.git', :branch => 'main'
pod 'AEPIdentity', :git => 'https://github.com/adobe/aepsdk-core-ios.git', :branch => 'main'
end

# for extension development, include AEPCore and its dependencies
target 'YOUR_TARGET_NAME' do
pod 'AEPRulesEngine', :git => 'https://github.com/adobe/aepsdk-rulesengine-ios.git', :branch => 'main'
pod 'AEPCore', :git => 'https://github.com/adobe/aepsdk-core-ios.git', :branch => 'main'
pod 'AEPServices', :git => 'https://github.com/adobe/aepsdk-core-ios.git', :branch => 'main'
end
```

Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type:

```bash
$ pod install
```

### Swift Package Manager

To add the AEPRulesEngine Package to your application, from the Xcode menu select:
To add the AEPRulesEngine package to your application, from the Xcode menu select:

`File > Swift Packages > Add Package Dependency...`

Expand All @@ -37,17 +69,17 @@ dependencies: [
## Usage


### Initialize Rules Engine
### Initialize the Rules Engine

To create a `RuleEngine` instance, first define an `Evaluator` and then use it as the parameter for `RuleEngine`.
To create a `RulesEngine` instance, define an `Evaluator` and pass it to the `RulesEngine`'s initializer:
```
let evaluator = ConditionEvaluator(options: .caseInsensitive)
let rulesEngine = RulesEngine(evaluator: evaluator)
```

### Define Rules

Any thing that conforms to the `Rule` protocol can be used as rule.
Anything that conforms to the `Rule` protocol can be used as rule:
``` Swift
public class MobileRule: Rule {
init(condition: Evaluable) { self.condition = condition }
Expand All @@ -57,7 +89,7 @@ let condition = ComparisonExpression(lhs: "abc", operationName: "equals", rhs: "
let rule = MobileRule(condition: condition)
rulesEngine.addRules(rules: [rule])
```
However, a rule like this doesn't make much sense, without the ability to dynamically fetch a value it will always be true or false.
A rule without the flexibility to dynamically fetch a value will always evaluate to true or false. To fetch the value for a rule at runtime, use a Mustache Token:

``` Swift
let mustache = Operand<String>(mustache: "{{company}}")
Expand All @@ -68,7 +100,7 @@ rulesEngine.addRules(rules: [rule])

### Evaluate data

Use the method `evaluate` to run rule engine on the input data that is `Traversable`.
Use the `evaluate` method to process `Traversable` data through the `RulesEngine`:

```
let matchedRules = rulesEngine.evaluate(data: ["company":"adobe"])
Expand Down
18 changes: 12 additions & 6 deletions Sources/AEPRulesEngine/ConditionEvaluator.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand All @@ -13,11 +13,14 @@
public class ConditionEvaluator: Evaluating {
fileprivate let LOG_TAG = "ConditionEvaluator"
var operators: [String: Any] = [:]

// MARK: - Evaluating
public func evaluate<A>(operation: String, lhs: A) -> Result<Bool, RulesFailure> {
let op = operators[getHash(operation: operation, typeA: A.self)] as? ((A) -> Bool)

guard let op_ = op else {
let message = "Operator not defined for \(getHash(operation: operation, typeA: A.self))"
RulesEngineLog.trace(label: LOG_TAG, message)
let message = "No operator defined for \(getHash(operation: operation, typeA: A.self))"
Log.trace(label: LOG_TAG, message)
return Result.failure(RulesFailure.missingOperator(message: message))
}
return op_(lhs) ? Result.success(true) : Result.failure(.conditionNotMatched(message: "(\(String(describing: A.self))(\(lhs)) \(operation))"))
Expand All @@ -27,8 +30,8 @@ public class ConditionEvaluator: Evaluating {
let op = operators[getHash(operation: operation, typeA: A.self, typeB: B.self)] as? ((A, B) -> Bool)

guard let op_ = op else {
let message = "Operator not defined for \(getHash(operation: operation, typeA: A.self, typeB: B.self))"
RulesEngineLog.trace(label: LOG_TAG, message)
let message = "No operator defined for \(getHash(operation: operation, typeA: A.self, typeB: B.self))"
Log.trace(label: LOG_TAG, message)
return Result.failure(RulesFailure.missingOperator(message: message))
}
return op_(lhs, rhs) ? Result.success(true) : Result.failure(.conditionNotMatched(message: "\(String(describing: A.self))(\(lhs)) \(operation) \(String(describing: B.self))(\(rhs))"))
Expand Down Expand Up @@ -78,6 +81,7 @@ public extension ConditionEvaluator {
}

private func addDefaultOperators() {

addComparisonOperator(operation: "and", type: Bool.self, closure: { $0 && $1 })
addComparisonOperator(operation: "or", type: Bool.self, closure: { $0 || $1 })

Expand Down Expand Up @@ -117,9 +121,11 @@ public extension ConditionEvaluator {
}

private func addCaseInSensitiveOperators() {
addComparisonOperator(operation: "startsWith", type: String.self, closure: { $0.lowercased().starts(with: $1.lowercased()) })
addComparisonOperator(operation: "equals", type: String.self, closure: { $0.lowercased() == $1.lowercased() })
addComparisonOperator(operation: "notEquals", type: String.self, closure: { $0.lowercased() != $1.lowercased() })
addComparisonOperator(operation: "startsWith", type: String.self, closure: { $0.lowercased().starts(with: $1.lowercased()) })
addComparisonOperator(operation: "endsWith", type: String.self, closure: { $0.lowercased().hasSuffix($1.lowercased()) })
addComparisonOperator(operation: "contains", type: String.self, closure: { $0.lowercased().contains($1.lowercased()) })
addComparisonOperator(operation: "notContains", type: String.self, closure: { !$0.lowercased().contains($1.lowercased()) })
}
}
20 changes: 20 additions & 0 deletions Sources/AEPRulesEngine/Context.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

import Foundation

/// A type that contains all pieces necessary for boolean evaluation
public struct Context {
public let data: Traversable
public let evaluator: Evaluating
public let transformer: Transforming
}
2 changes: 1 addition & 1 deletion Sources/AEPRulesEngine/Evaluating.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand Down
10 changes: 6 additions & 4 deletions Sources/AEPRulesEngine/Expression/ComparisonExpression.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand All @@ -24,8 +24,10 @@ public struct ComparisonExpression<A, B>: Evaluable {
self.operationName = operationName
}

// MARK: - Evaluable

public func evaluate(in context: Context) -> Result<Bool, RulesFailure> {
RulesEngineLog.trace(label: LOG_TAG, "Evaluating \(lhs) - \(operationName) - \(rhs)")
Log.trace(label: LOG_TAG, "Evaluating \(lhs) - \(operationName) - \(rhs)")
let resolvedLhs = lhs(context)
let resolvedRhs = rhs(context)
var result: Result<Bool, RulesFailure>
Expand All @@ -38,8 +40,8 @@ public struct ComparisonExpression<A, B>: Evaluable {
case .success:
return result
case let .failure(error):
RulesEngineLog.debug(label: LOG_TAG, "Failed to evaluate \(String(describing: resolvedLhs)) - \(operationName) - \(String(describing: resolvedRhs))")
return Result.failure(.innerFailure(message: "Comparison (\(lhs) \(operationName) \(rhs)) returns false", error: error))
Log.debug(label: LOG_TAG, "Failed to evaluate \(String(describing: resolvedLhs)) - \(operationName) - \(String(describing: resolvedRhs))")
return Result.failure(.innerFailure(message: "Comparison (\(lhs) \(operationName) \(rhs)) returned false", error: error))
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand Down
4 changes: 2 additions & 2 deletions Sources/AEPRulesEngine/Expression/LogicalExpression.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand Down Expand Up @@ -43,7 +43,7 @@ public struct LogicalExpression: Evaluable {
}
return Result.failure(.innerFailures(message: "`Or` returns false", errors: operandsResolve.filter { !$0.value }.map { $0.error ?? RulesFailure.unknown }))
default:
return .failure(.missingOperator(message: "Unkonwn conjunction operator"))
return .failure(.missingOperator(message: "Unknown conjunction operator '\(operationName)'"))
}
}
}
6 changes: 3 additions & 3 deletions Sources/AEPRulesEngine/Expression/Operand.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand Down Expand Up @@ -51,9 +51,9 @@ extension Operand: CustomStringConvertible {
case .none:
return "<None>"
case let .some(value):
return "<Value:\(value)>"
return "<Value: \(value)>"
case let .token(mustache):
return "<Token:\(mustache)>"
return "<Token: \(mustache)>"
}
}
}
4 changes: 2 additions & 2 deletions Sources/AEPRulesEngine/Expression/UnaryExpression.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand All @@ -23,7 +23,7 @@ public struct UnaryExpression<A>: Evaluable {
}

public func evaluate(in context: Context) -> Result<Bool, RulesFailure> {
RulesEngineLog.trace(label: LOG_TAG, "Evaluating \(operationName) - \(lhs)")
Log.trace(label: LOG_TAG, "Evaluating \(operationName) - \(lhs)")
let resolvedLhs = lhs(context)
if let resolvedLhs_ = resolvedLhs {
return context.evaluator.evaluate(operation: operationName, lhs: resolvedLhs_)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand All @@ -12,8 +12,11 @@

import Foundation

public class RulesEngineLog {
public static var logging: RulesEngineLogging?
/// The `Log` class will be dormant unless its static `logging` variable is initialized.
/// To enable logging from the RulesEngine, implement a class that conforms to the
/// `Logging` protocol and use an instance of it to set the `Log.logging` variable.
public class Log {
public static var logging: Logging?
/// Used to print more verbose information.
/// - Parameters:
/// - label: the name of the label to localize message
Expand Down
Original file line number Diff line number Diff line change
@@ -1,40 +1,32 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

import Foundation
public protocol RulesEngineLogging {
/// Logs a message
/// - Parameters:
/// - level: One of the message level identifiers, e.g., DEBUG
/// - label: Name of a label to localize message
/// - message: The string message
func log(level: RulesEngineLogLevel, label: String, message: String)
}

public enum RulesEngineLogLevel: Int, Comparable {
public enum LogLevel: Int, Comparable {
case error = 0
case warning = 1
case debug = 2
case trace = 3

/// Compares two `RulesEngineLogLevel`s for order
/// Compares two `LogLevel`s for order
/// - Parameters:
/// - lhs: the first `RulesEngineLogLevel` to be compared
/// - rhs: the second `RulesEngineLogLevel` to be compared
/// - Returns: true, only if the second `LogLevel` is more critical
public static func < (lhs: RulesEngineLogLevel, rhs: RulesEngineLogLevel) -> Bool {
/// - lhs: the first `LogLevel` to be compared
/// - rhs: the second `LogLevel` to be compared
/// - Returns: true if the second `LogLevel` is more critical
public static func < (lhs: LogLevel, rhs: LogLevel) -> Bool {
lhs.rawValue < rhs.rawValue
}

public func toString() -> String {
switch self {
case .trace:
Expand Down
22 changes: 22 additions & 0 deletions Sources/AEPRulesEngine/Log/Logging.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

import Foundation

public protocol Logging {
/// Logs a message
/// - Parameters:
/// - level: A `LogLevel` identifying the severity of the log. e.g. - `.debug`
/// - label: Label for the log
/// - message: The `String` message
func log(level: LogLevel, label: String, message: String)
}
2 changes: 1 addition & 1 deletion Sources/AEPRulesEngine/Operand+Literal.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand Down
2 changes: 1 addition & 1 deletion Sources/AEPRulesEngine/Result+RulesFailure.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand Down
2 changes: 1 addition & 1 deletion Sources/AEPRulesEngine/Rule.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand Down
Loading

0 comments on commit 42d077d

Please sign in to comment.