|
| 1 | +// Copyright 2022 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package dev.cel.runtime.async; |
| 16 | + |
| 17 | +import static com.google.common.collect.ImmutableMap.toImmutableMap; |
| 18 | +import static com.google.common.util.concurrent.Futures.immediateFailedFuture; |
| 19 | +import static com.google.common.util.concurrent.Futures.immediateFuture; |
| 20 | +import static com.google.common.util.concurrent.Futures.transformAsync; |
| 21 | +import static com.google.common.util.concurrent.Futures.whenAllSucceed; |
| 22 | + |
| 23 | +import javax.annotation.concurrent.ThreadSafe; |
| 24 | +import com.google.common.collect.ImmutableMap; |
| 25 | +import com.google.common.collect.ImmutableSet; |
| 26 | +import com.google.common.util.concurrent.Futures; |
| 27 | +import com.google.common.util.concurrent.ListenableFuture; |
| 28 | +import com.google.common.util.concurrent.ListeningExecutorService; |
| 29 | +import dev.cel.runtime.CelAttribute; |
| 30 | +import dev.cel.runtime.CelAttributePattern; |
| 31 | +import dev.cel.runtime.CelEvaluationException; |
| 32 | +import dev.cel.runtime.CelRuntime.Program; |
| 33 | +import dev.cel.runtime.CelUnknownSet; |
| 34 | +import dev.cel.runtime.UnknownContext; |
| 35 | +import java.util.LinkedHashMap; |
| 36 | +import java.util.Map; |
| 37 | +import java.util.Optional; |
| 38 | +import java.util.concurrent.ExecutionException; |
| 39 | + |
| 40 | +/** |
| 41 | + * Default runtime implementation for {@link CelAsyncRuntime.AsyncProgram}. |
| 42 | + * |
| 43 | + * <p>Control flow is: |
| 44 | + * |
| 45 | + * <ol> |
| 46 | + * <li>Evaluate the expression (synchronously), identifying unknowns or final result |
| 47 | + * <li>If unknowns identified, schedule lookups (calls to *Resolver.resolve) on the executor |
| 48 | + * <li>On any failure, return failed future. CEL errors can be introduced by the return value of |
| 49 | + * resolver. |
| 50 | + * <li>On all successful, generate new context for next round of evaluation on the executor |
| 51 | + * <li>repeat until a final (non-unknown) result, no progress is made, or iteration limit reached. |
| 52 | + * </ol> |
| 53 | + */ |
| 54 | +@ThreadSafe |
| 55 | +final class AsyncProgramImpl implements CelAsyncRuntime.AsyncProgram { |
| 56 | + // Safety limit for resolution rounds. |
| 57 | + private final int maxEvaluateIterations; |
| 58 | + private final Program program; |
| 59 | + private final ListeningExecutorService executor; |
| 60 | + private final ImmutableMap<CelAttributePattern, CelUnknownAttributeValueResolver> resolvers; |
| 61 | + |
| 62 | + AsyncProgramImpl( |
| 63 | + Program program, |
| 64 | + ListeningExecutorService executor, |
| 65 | + ImmutableMap<CelAttributePattern, CelUnknownAttributeValueResolver> resolvers, |
| 66 | + int maxEvaluateIterations) { |
| 67 | + this.program = program; |
| 68 | + this.executor = executor; |
| 69 | + this.resolvers = resolvers; |
| 70 | + this.maxEvaluateIterations = maxEvaluateIterations; |
| 71 | + } |
| 72 | + |
| 73 | + private Optional<CelUnknownAttributeValueResolver> lookupResolver(CelAttribute attribute) { |
| 74 | + // TODO: may need to handle multiple resolvers for partial case. |
| 75 | + for (Map.Entry<CelAttributePattern, CelUnknownAttributeValueResolver> entry : |
| 76 | + resolvers.entrySet()) { |
| 77 | + if (entry.getKey().isPartialMatch(attribute)) { |
| 78 | + return Optional.of(entry.getValue()); |
| 79 | + } |
| 80 | + } |
| 81 | + return Optional.empty(); |
| 82 | + } |
| 83 | + |
| 84 | + private ListenableFuture<ImmutableMap<CelAttribute, Object>> allAsMapOnSuccess( |
| 85 | + Map<CelAttribute, ListenableFuture<Object>> futureMap) { |
| 86 | + return whenAllSucceed(futureMap.values()) |
| 87 | + .call( |
| 88 | + () -> |
| 89 | + futureMap.entrySet().stream() |
| 90 | + .collect( |
| 91 | + toImmutableMap( |
| 92 | + Map.Entry::getKey, |
| 93 | + entry -> { |
| 94 | + try { |
| 95 | + return Futures.getDone(entry.getValue()); |
| 96 | + } catch (ExecutionException e) { |
| 97 | + throw new AssertionError( |
| 98 | + "Futures.whenAllSucceed forwarded failed future", e); |
| 99 | + } |
| 100 | + })), |
| 101 | + executor); |
| 102 | + } |
| 103 | + |
| 104 | + private ListenableFuture<Object> resolveAndReevaluate( |
| 105 | + CelUnknownSet unknowns, UnknownContext ctx, int iteration) { |
| 106 | + Map<CelAttribute, ListenableFuture<Object>> futureMap = new LinkedHashMap<>(); |
| 107 | + for (CelAttribute attr : unknowns.attributes()) { |
| 108 | + Optional<CelUnknownAttributeValueResolver> maybeResolver = lookupResolver(attr); |
| 109 | + |
| 110 | + maybeResolver.ifPresent((resolver) -> futureMap.put(attr, resolver.resolve(executor, attr))); |
| 111 | + } |
| 112 | + |
| 113 | + if (futureMap.isEmpty()) { |
| 114 | + return immediateFailedFuture( |
| 115 | + new CelEvaluationException( |
| 116 | + String.format("Unknown resolution failed -- no resolvers for: %s", unknowns))); |
| 117 | + } |
| 118 | + |
| 119 | + // TODO: lookup fails on any failure. Fine for prototyping, but this would likely |
| 120 | + // need to be configurable in the future. |
| 121 | + return transformAsync( |
| 122 | + allAsMapOnSuccess(futureMap), |
| 123 | + (result) -> evalPass(ctx.withResolvedAttributes(result), unknowns, iteration), |
| 124 | + executor); |
| 125 | + } |
| 126 | + |
| 127 | + private ListenableFuture<Object> evalPass( |
| 128 | + UnknownContext ctx, CelUnknownSet lastSet, int iteration) { |
| 129 | + Object result = null; |
| 130 | + try { |
| 131 | + result = program.advanceEvaluation(ctx); |
| 132 | + } catch (CelEvaluationException e) { |
| 133 | + return immediateFailedFuture(e); |
| 134 | + } |
| 135 | + if (result instanceof CelUnknownSet) { |
| 136 | + if (result.equals(lastSet)) { |
| 137 | + return immediateFailedFuture( |
| 138 | + new CelEvaluationException("No progress in iterative eval. Last result: " + result)); |
| 139 | + } |
| 140 | + // Don't handle unknowns if next evaluation would exceed eval limit. |
| 141 | + iteration++; |
| 142 | + if (iteration >= maxEvaluateIterations) { |
| 143 | + return immediateFailedFuture( |
| 144 | + new CelEvaluationException("Max Evaluation iterations exceeded: " + iteration)); |
| 145 | + } |
| 146 | + return resolveAndReevaluate((CelUnknownSet) result, ctx, iteration); |
| 147 | + } |
| 148 | + |
| 149 | + return immediateFuture(result); |
| 150 | + } |
| 151 | + |
| 152 | + @Override |
| 153 | + public ListenableFuture<Object> evaluateToCompletion(UnknownContext ctx) { |
| 154 | + return evalPass(ctx, CelUnknownSet.create(ImmutableSet.of()), 0); |
| 155 | + } |
| 156 | +} |
0 commit comments