Skip to content
Open
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import org.projectnessie.cel.common.containers.Container;
import org.projectnessie.cel.common.types.ref.FieldType;
import org.projectnessie.cel.common.types.ref.TypeRegistry;
import org.projectnessie.cel.interpreter.AttributeFactory.Attribute;
import org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute;
Expand All @@ -56,6 +57,24 @@
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class AttributesBench {

@State(Scope.Benchmark)
public static class GeneratedScalarFieldGetterState {

final NestedMessage message;
final FieldType fieldType;

public GeneratedScalarFieldGetterState() {
message = NestedMessage.newBuilder().setBb(123).build();
TypeRegistry reg = newRegistry(message);
fieldType = reg.findFieldType("cel.expr.conformance.proto3.TestAllTypes.NestedMessage", "bb");
}
}

@Benchmark
public Object generatedScalarFieldGetter(GeneratedScalarFieldGetterState state) {
return state.fieldType.getFrom.getFrom(state.message);
}

@Benchmark
public void attributesConditionalAttr_TrueBranch() {
TypeRegistry reg = newRegistry();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* Copyright (C) 2021 The Authors of CEL-Java
*
* Licensed 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 CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.projectnessie.cel.common.types.pb;

import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.DynamicMessage;
import com.google.protobuf.Message;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import org.projectnessie.cel.common.types.ref.FieldGetter;

final class GeneratedFieldAccessor {

private static final MethodType OBJECT_GETTER = MethodType.methodType(Object.class, Object.class);

private GeneratedFieldAccessor() {}

static FieldGetter create(PbTypeDescription type, FieldDescription field) {
FieldDescriptor descriptor = field.descriptor();
Class<?> returnType = generatedReturnType(descriptor);
Message zero = type.zero();
Class<?> messageClass = type.reflectType();
if (returnType == null
|| descriptor.isExtension()
|| descriptor.isRepeated()
|| zero instanceof DynamicMessage
|| !messageClass.isInstance(zero)) {
return null;
}

String suffix = accessorSuffix(descriptor.getName());
for (String methodName : new String[] {"get" + suffix, "get" + suffix + '_'}) {
try {
MethodHandle getter =
MethodHandles.publicLookup()
.findVirtual(messageClass, methodName, MethodType.methodType(returnType));
if (!matchesField(getter, zero, descriptor)) {
continue;
}
MethodHandle objectGetter = getter.asType(OBJECT_GETTER);
return target -> invoke(objectGetter, target);
} catch (IllegalAccessException | NoSuchMethodException | RuntimeException e) {
// Generated-name collisions and inaccessible generated classes use descriptor access.
}
}
return null;
}

private static Class<?> generatedReturnType(FieldDescriptor descriptor) {
return switch (descriptor.getType()) {
case BOOL -> boolean.class;
case STRING -> String.class;
case BYTES -> ByteString.class;
case INT32, SINT32, SFIXED32 -> int.class;
case INT64, SINT64, SFIXED64 -> long.class;
case FLOAT -> float.class;
case DOUBLE -> double.class;
default -> null;
};
}

private static boolean matchesField(
MethodHandle getter, Message zero, FieldDescriptor descriptor) {
Object expected = validationValue(descriptor);
Message probe = zero.newBuilderForType().setField(descriptor, expected).buildPartial();
try {
return expected.equals(getter.invoke(probe));
} catch (Throwable e) {
return false;
}
}

private static Object validationValue(FieldDescriptor descriptor) {
return switch (descriptor.getType()) {
case BOOL -> true;
case STRING -> "cel_generated_field_accessor";
case BYTES -> ByteString.copyFromUtf8("cel_generated_field_accessor");
case INT32, SINT32, SFIXED32 -> 0x51a7;
case INT64, SINT64, SFIXED64 -> 0x51a7_19b3_42c5L;
case FLOAT -> 123.25f;
case DOUBLE -> 123.25d;
default ->
throw new IllegalArgumentException("Unsupported field type " + descriptor.getType());
};
}

private static String accessorSuffix(String fieldName) {
StringBuilder result = new StringBuilder(fieldName.length());
boolean capitalizeNext = true;
for (int i = 0; i < fieldName.length(); i++) {
char c = fieldName.charAt(i);
if (c >= 'a' && c <= 'z') {
result.append(capitalizeNext ? Character.toUpperCase(c) : c);
capitalizeNext = false;
} else if ((c >= 'A' && c <= 'Z')) {
result.append(c);
capitalizeNext = false;
} else if (c >= '0' && c <= '9') {
result.append(c);
capitalizeNext = true;
} else {
capitalizeNext = true;
}
}
return result.toString();
}

private static Object invoke(MethodHandle getter, Object target) {
try {
return (Object) getter.invokeExact(target);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package org.projectnessie.cel.common.types.pb;

import static org.projectnessie.cel.common.types.BoolT.BoolType;
import static org.projectnessie.cel.common.types.BoolT.True;
import static org.projectnessie.cel.common.types.BytesT.BytesType;
import static org.projectnessie.cel.common.types.DoubleT.DoubleType;
import static org.projectnessie.cel.common.types.DurationT.DurationType;
Expand Down Expand Up @@ -45,6 +46,7 @@
import com.google.api.expr.v1alpha1.Type;
import com.google.protobuf.Any;
import com.google.protobuf.BoolValue;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
Expand Down Expand Up @@ -81,8 +83,12 @@
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.projectnessie.cel.common.ULong;
import org.projectnessie.cel.common.types.IteratorT;
import org.projectnessie.cel.common.types.MapT;
import org.projectnessie.cel.common.types.NullT;
import org.projectnessie.cel.common.types.TypeT;
import org.projectnessie.cel.common.types.ref.FieldGetter;
import org.projectnessie.cel.common.types.ref.FieldType;
import org.projectnessie.cel.common.types.ref.TypeRegistry;
import org.projectnessie.cel.common.types.ref.Val;
Expand Down Expand Up @@ -214,11 +220,18 @@ private FieldType loadFieldType(String messageType, String fieldName) {
if (field == null) {
return null;
}
FieldDescription resolvedField = field;
return new FieldType(
resolvedField.checkedType(),
resolvedField::hasField,
target -> resolvedField.getField(target, this));
FieldGetter getter = target -> field.getField(target, this);
PbTypeDescription type = pbdb.describeType(messageType);
FieldGetter generatedGetter = type != null ? GeneratedFieldAccessor.create(type, field) : null;
if (generatedGetter != null) {
Class<?> generatedType = type.reflectType();
getter =
target ->
generatedType.isInstance(target)
? generatedGetter.getFrom(target)
: field.getField(target, this);
}
return new FieldType(field.checkedType(), field::hasField, getter);
}

FieldDescription findFieldDescription(String messageType, String fieldName) {
Expand All @@ -230,9 +243,6 @@ FieldDescription findFieldDescription(String messageType, String fieldName) {
if (field == null) {
field = pbdb.describeExtension(messageType, fieldName);
}
if (field == null) {
return null;
}
return field;
}

Expand Down Expand Up @@ -287,27 +297,29 @@ private Val newValueSetFields(Map<String, Val> fields, PbTypeDescription td, Bui
return noSuchField(name);
}

// TODO resolve inefficiency for maps: first converted from a MapT to a native Java map and
// then to a protobuf struct. The intermediate step (the Java map) could be omitted.

FieldDescriptor pbDesc = field.descriptor();
if (nv.getValue() == org.projectnessie.cel.common.types.NullT.NullValue
&& isNullClearedField(pbDesc)) {
continue;
}

try {
Object value = toNativeFieldValue(nv.getValue(), field);
if (value.getClass().isArray()) {
value = Arrays.asList((Object[]) value);
}
Object value;
if (pbDesc.isMapField() && nv.getValue() instanceof MapT map) {
value = toProtoMapStructure(field, map);
} else {
value = toNativeFieldValue(nv.getValue(), field);
if (value.getClass().isArray()) {
value = Arrays.asList((Object[]) value);
}

if (pbDesc.getJavaType() == JavaType.ENUM) {
value = intToProtoEnumValues(field, value);
}
if (pbDesc.getJavaType() == JavaType.ENUM) {
value = intToProtoEnumValues(field, value);
}

if (pbDesc.isMapField()) {
value = toProtoMapStructure(pbDesc, value);
if (pbDesc.isMapField()) {
value = toProtoMapStructure(pbDesc, value);
}
}

builder.setField(pbDesc, value);
Expand Down Expand Up @@ -385,6 +397,58 @@ private static Class<?> messageNativeType(FieldDescriptor field) {
};
}

/** Converts a CEL map directly to protobuf map entries without an intermediate Java map. */
private Object toProtoMapStructure(FieldDescription field, MapT value) {
FieldDescriptor fieldDesc = field.descriptor();
Descriptor entryType = fieldDesc.getMessageType();
FieldDescriptor keyType = field.keyType.descriptor();
FieldDescriptor valueType = field.valueType.descriptor();
WireFormat.FieldType keyFieldType = WireFormat.FieldType.valueOf(keyType.getType().name());
WireFormat.FieldType valueFieldType = WireFormat.FieldType.valueOf(valueType.getType().name());
List<MapEntry<?, ?>> entries = new ArrayList<>((int) value.size().intValue());

IteratorT iterator = value.iterator();
while (iterator.hasNext() == True) {
Val key = iterator.next();
Val mapValue = value.find(key);
if (mapValue == NullT.NullValue && isNullPrunedMessageField(valueType)) {
continue;
}

Object nativeKey = toNativeMapEntryValue(key, keyType);
Object nativeValue = toNativeMapEntryValue(mapValue, valueType);
entries.add(
MapEntry.newDefaultInstance(
entryType, keyFieldType, nativeKey, valueFieldType, nativeValue));
}
return entries;
}

private static Object toNativeMapEntryValue(Val value, FieldDescriptor field) {
return switch (field.getType()) {
case DOUBLE -> value.convertToNative(Double.class);
case FLOAT -> value.convertToNative(Float.class);
case INT64, SINT64, SFIXED64 -> value.convertToNative(Long.class);
case UINT64, FIXED64 -> value.convertToNative(ULong.class).longValue();
case INT32, SINT32, SFIXED32 -> value.convertToNative(Integer.class);
case UINT32, FIXED32 -> value.convertToNative(ULong.class).intValue();
case BOOL -> value.convertToNative(Boolean.class);
case STRING -> value.convertToNative(String.class);
case BYTES -> value.convertToNative(ByteString.class);
case ENUM -> {
if (value == NullT.NullValue) {
if (field.getEnumType().getFullName().equals("google.protobuf.NullValue")) {
yield 0;
}
throw new IllegalArgumentException("null is only valid for google.protobuf.NullValue");
}
yield value.convertToNative(Integer.class);
}
case MESSAGE -> value.convertToNative(messageNativeType(field));
case GROUP -> throw new IllegalArgumentException("protobuf maps cannot contain group values");
};
}

/**
* Converts {@code value}, of the map-field {@code fieldDesc} from its Java {@link Map}
* representation to the protobuf-y {@code {@link List}<{@link MapEntry}>} representation.
Expand Down
Loading
Loading