Skip to content
Closed
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
16 changes: 15 additions & 1 deletion src/main/java/build/buf/protovalidate/RuleCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ private CelRule(AstExpression astExpression, FieldDescriptor field, FieldPath ru
private static final Map<FieldDescriptor, List<CelRule>> descriptorMap =
new ConcurrentHashMap<>();

/**
* Concurrent map for caching compiled programs by the serialized rule message bytes. This allows
* fields sharing the same resolved rules (same type + same values) to reuse compiled programs.
*/
private static final Map<com.google.protobuf.ByteString, List<CompiledProgram>> programCache =
new ConcurrentHashMap<>();

/** The environment to use for evaluation. */
private final Cel cel;

Expand Down Expand Up @@ -109,6 +116,11 @@ List<CompiledProgram> compile(
return Collections.emptyList();
}
Message message = resolved.message;
com.google.protobuf.ByteString cacheKey = message.toByteString();
List<CompiledProgram> cachedPrograms = programCache.get(cacheKey);
if (cachedPrograms != null) {
return cachedPrograms;
}
List<CelRule> completeProgramList = new ArrayList<>();
for (Map.Entry<FieldDescriptor, Object> entry : message.getAllFields().entrySet()) {
FieldDescriptor ruleFieldDesc = entry.getKey();
Expand All @@ -134,7 +146,9 @@ List<CompiledProgram> compile(
"failed to evaluate rule " + rule.astExpression.source.id, e);
}
}
return Collections.unmodifiableList(programs);
List<CompiledProgram> result = Collections.unmodifiableList(programs);
programCache.putIfAbsent(cacheKey, result);
return result;
}

private @Nullable List<CelRule> compileRule(
Expand Down
Loading