Skip to content

Commit

Permalink
Re-organize FormulaRuntime.
Browse files Browse the repository at this point in the history
  • Loading branch information
Laimiux committed Jun 30, 2023
1 parent 4cdcb4c commit b0c42d6
Showing 1 changed file with 40 additions and 31 deletions.
71 changes: 40 additions & 31 deletions formula/src/main/java/com/instacart/formula/FormulaRuntime.kt
Original file line number Diff line number Diff line change
Expand Up @@ -89,41 +89,42 @@ class FormulaRuntime<Input : Any, Output : Any>(
if (isEvaluating) return

try {
val freshRun = !isExecuting
if (freshRun) {
inspector?.onRunStarted(shouldEvaluate)
}
runFormula(shouldEvaluate)
emitOutputIfNeeded()
} catch (e: Throwable) {
isEvaluating = false

val manager = checkNotNull(manager)
val currentInput = checkNotNull(input)
manager?.markAsTerminated()
onError(e)
manager?.performTerminationSideEffects()
}
}

isEvaluating = true
if (shouldEvaluate && !manager.terminated) {
evaluationPhase(manager, currentInput)
}
isEvaluating = false
private fun runFormula(evaluate: Boolean) {
val freshRun = !isExecuting
if (freshRun) {
inspector?.onRunStarted(evaluate)
}

if (shouldEvaluate || effectQueue.isNotEmpty()) {
executionRequested = true
}
if (isExecuting) return
val manager = checkNotNull(manager)
val currentInput = checkNotNull(input)

isEvaluating = true
if (evaluate && !manager.terminated) {
evaluationPhase(manager, currentInput)
}
isEvaluating = false

effectPhase(manager)
if (evaluate || effectQueue.isNotEmpty()) {
executionRequested = true
}

if (freshRun) {
inspector?.onRunFinished()
}
if (isExecuting) return

if (hasInitialFinished && emitOutput) {
emitOutput = false
onOutput(checkNotNull(lastOutput))
}
} catch (e: Throwable) {
isEvaluating = false
effectPhase(manager)

manager?.markAsTerminated()
onError(e)
manager?.performTerminationSideEffects()
if (freshRun) {
inspector?.onRunFinished()
}
}

Expand Down Expand Up @@ -157,9 +158,8 @@ class FormulaRuntime<Input : Any, Output : Any>(
while (executionRequested) {
executionRequested = false

val transitionId = manager.transitionID
// We execute pending side-effects even after termination
if (executeEffects(manager, transitionId)) {
if (executeEffects(manager)) {
continue
}
}
Expand All @@ -169,7 +169,9 @@ class FormulaRuntime<Input : Any, Output : Any>(
/**
* Executes effects from the [effectQueue].
*/
private fun executeEffects(manager: FormulaManagerImpl<*, *, *>, transitionId: Long): Boolean {
private fun executeEffects(manager: FormulaManagerImpl<*, *, *>): Boolean {
isExecuting = true
val transitionId = manager.transitionID
while (effectQueue.isNotEmpty()) {
val effects = effectQueue.pollFirst()
if (effects != null) {
Expand All @@ -183,4 +185,11 @@ class FormulaRuntime<Input : Any, Output : Any>(
}
return false
}

private fun emitOutputIfNeeded() {
if (hasInitialFinished && emitOutput) {
emitOutput = false
onOutput(checkNotNull(lastOutput))
}
}
}

0 comments on commit b0c42d6

Please sign in to comment.