-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathProtoLiteCelValueConverter.java
More file actions
348 lines (314 loc) · 13.6 KB
/
ProtoLiteCelValueConverter.java
File metadata and controls
348 lines (314 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright 2025 Google LLC
//
// 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
//
// https://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 dev.cel.common.values;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Defaults;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.ExtensionRegistryLite;
import com.google.protobuf.MessageLite;
import com.google.protobuf.WireFormat;
import dev.cel.common.annotations.Internal;
import dev.cel.common.internal.CelLiteDescriptorPool;
import dev.cel.common.internal.WellKnownProto;
import dev.cel.protobuf.CelLiteDescriptor.FieldLiteDescriptor;
import dev.cel.protobuf.CelLiteDescriptor.FieldLiteDescriptor.CelFieldValueType;
import dev.cel.protobuf.CelLiteDescriptor.FieldLiteDescriptor.JavaType;
import dev.cel.protobuf.CelLiteDescriptor.MessageLiteDescriptor;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* {@code ProtoLiteCelValueConverter} handles bidirectional conversion between native Java and
* protobuf objects to {@link CelValue}. This converter is specifically designed for use with
* lite-variants of protobuf messages.
*
* <p>Protobuf semantics take precedence for conversion. For example, CEL's TimestampValue will be
* converted into Protobuf's Timestamp instead of java.time.Instant.
*
* <p>CEL Library Internals. Do Not Use.
*/
@Immutable
@Internal
public final class ProtoLiteCelValueConverter extends BaseProtoCelValueConverter {
private final CelLiteDescriptorPool descriptorPool;
public static ProtoLiteCelValueConverter newInstance(
CelLiteDescriptorPool celLiteDescriptorPool) {
return new ProtoLiteCelValueConverter(celLiteDescriptorPool);
}
private static Object readPrimitiveField(
CodedInputStream inputStream, FieldLiteDescriptor fieldDescriptor) throws IOException {
switch (fieldDescriptor.getProtoFieldType()) {
case SINT32:
return inputStream.readSInt32();
case SINT64:
return inputStream.readSInt64();
case INT32:
case ENUM:
return inputStream.readInt32();
case INT64:
return inputStream.readInt64();
case UINT32:
return UnsignedLong.fromLongBits(inputStream.readUInt32());
case UINT64:
return UnsignedLong.fromLongBits(inputStream.readUInt64());
case BOOL:
return inputStream.readBool();
case FLOAT:
case FIXED32:
case SFIXED32:
return readFixed32BitField(inputStream, fieldDescriptor);
case DOUBLE:
case FIXED64:
case SFIXED64:
return readFixed64BitField(inputStream, fieldDescriptor);
default:
throw new IllegalStateException(
"Unexpected field type: " + fieldDescriptor.getProtoFieldType());
}
}
private static Object readFixed32BitField(
CodedInputStream inputStream, FieldLiteDescriptor fieldDescriptor) throws IOException {
switch (fieldDescriptor.getProtoFieldType()) {
case FLOAT:
return inputStream.readFloat();
case FIXED32:
case SFIXED32:
return inputStream.readRawLittleEndian32();
default:
throw new IllegalStateException(
"Unexpected field type: " + fieldDescriptor.getProtoFieldType());
}
}
private static Object readFixed64BitField(
CodedInputStream inputStream, FieldLiteDescriptor fieldDescriptor) throws IOException {
switch (fieldDescriptor.getProtoFieldType()) {
case DOUBLE:
return inputStream.readDouble();
case FIXED64:
case SFIXED64:
return inputStream.readRawLittleEndian64();
default:
throw new IllegalStateException(
"Unexpected field type: " + fieldDescriptor.getProtoFieldType());
}
}
private Object readLengthDelimitedField(
CodedInputStream inputStream, FieldLiteDescriptor fieldDescriptor) throws IOException {
FieldLiteDescriptor.Type fieldType = fieldDescriptor.getProtoFieldType();
switch (fieldType) {
case BYTES:
return inputStream.readBytes();
case MESSAGE:
MessageLite.Builder builder =
getDefaultMessageBuilder(fieldDescriptor.getFieldProtoTypeName());
inputStream.readMessage(builder, ExtensionRegistryLite.getEmptyRegistry());
return builder.build();
case STRING:
return inputStream.readStringRequireUtf8();
default:
throw new IllegalStateException("Unexpected field type: " + fieldType);
}
}
private MessageLite.Builder getDefaultMessageBuilder(String protoTypeName) {
return descriptorPool.getDescriptorOrThrow(protoTypeName).newMessageBuilder();
}
CelValue getDefaultCelValue(String protoTypeName, String fieldName) {
MessageLiteDescriptor messageDescriptor = descriptorPool.getDescriptorOrThrow(protoTypeName);
FieldLiteDescriptor fieldDescriptor = messageDescriptor.getByFieldNameOrThrow(fieldName);
Object defaultValue = getDefaultValue(fieldDescriptor);
if (defaultValue instanceof MessageLite) {
return fromProtoMessageToCelValue(
fieldDescriptor.getFieldProtoTypeName(), (MessageLite) defaultValue);
}
return fromJavaObjectToCelValue(defaultValue);
}
private Object getDefaultValue(FieldLiteDescriptor fieldDescriptor) {
FieldLiteDescriptor.CelFieldValueType celFieldValueType =
fieldDescriptor.getCelFieldValueType();
switch (celFieldValueType) {
case LIST:
return ImmutableList.of();
case MAP:
return ImmutableMap.of();
case SCALAR:
return getScalarDefaultValue(fieldDescriptor);
}
throw new IllegalStateException("Unexpected cel field value type: " + celFieldValueType);
}
private Object getScalarDefaultValue(FieldLiteDescriptor fieldDescriptor) {
JavaType type = fieldDescriptor.getJavaType();
switch (type) {
case INT:
return fieldDescriptor.getProtoFieldType().equals(FieldLiteDescriptor.Type.UINT32)
? UnsignedLong.ZERO
: Defaults.defaultValue(long.class);
case LONG:
return fieldDescriptor.getProtoFieldType().equals(FieldLiteDescriptor.Type.UINT64)
? UnsignedLong.ZERO
: Defaults.defaultValue(long.class);
case ENUM:
return Defaults.defaultValue(long.class);
case FLOAT:
return Defaults.defaultValue(float.class);
case DOUBLE:
return Defaults.defaultValue(double.class);
case BOOLEAN:
return Defaults.defaultValue(boolean.class);
case STRING:
return "";
case BYTE_STRING:
return ByteString.EMPTY;
case MESSAGE:
if (WellKnownProto.isWrapperType(fieldDescriptor.getFieldProtoTypeName())) {
return com.google.protobuf.NullValue.NULL_VALUE;
}
return getDefaultMessageBuilder(fieldDescriptor.getFieldProtoTypeName()).build();
}
throw new IllegalStateException("Unexpected java type: " + type);
}
private ImmutableList<Object> readPackedRepeatedFields(
CodedInputStream inputStream, FieldLiteDescriptor fieldDescriptor) throws IOException {
int length = inputStream.readInt32();
int oldLimit = inputStream.pushLimit(length);
ImmutableList.Builder<Object> builder = ImmutableList.builder();
while (inputStream.getBytesUntilLimit() > 0) {
builder.add(readPrimitiveField(inputStream, fieldDescriptor));
}
inputStream.popLimit(oldLimit);
return builder.build();
}
private Map.Entry<Object, Object> readSingleMapEntry(
CodedInputStream inputStream, FieldLiteDescriptor fieldDescriptor) throws IOException {
ImmutableMap<String, Object> singleMapEntry =
readAllFields(inputStream.readByteArray(), fieldDescriptor.getFieldProtoTypeName());
Object key = checkNotNull(singleMapEntry.get("key"));
Object value = checkNotNull(singleMapEntry.get("value"));
return new AbstractMap.SimpleEntry<>(key, value);
}
@VisibleForTesting
ImmutableMap<String, Object> readAllFields(byte[] bytes, String protoTypeName)
throws IOException {
// TODO: Handle unknown fields by collecting them into a separate map.
MessageLiteDescriptor messageDescriptor = descriptorPool.getDescriptorOrThrow(protoTypeName);
CodedInputStream inputStream = CodedInputStream.newInstance(bytes);
ImmutableMap.Builder<String, Object> fieldValues = ImmutableMap.builder();
Map<Integer, List<Object>> repeatedFieldValues = new LinkedHashMap<>();
Map<Integer, Map<Object, Object>> mapFieldValues = new LinkedHashMap<>();
for (int tag = inputStream.readTag(); tag != 0; tag = inputStream.readTag()) {
int tagWireType = WireFormat.getTagWireType(tag);
int fieldNumber = WireFormat.getTagFieldNumber(tag);
FieldLiteDescriptor fieldDescriptor = messageDescriptor.getByFieldNumberOrThrow(fieldNumber);
Object payload;
switch (tagWireType) {
case WireFormat.WIRETYPE_VARINT:
payload = readPrimitiveField(inputStream, fieldDescriptor);
break;
case WireFormat.WIRETYPE_FIXED32:
payload = readFixed32BitField(inputStream, fieldDescriptor);
break;
case WireFormat.WIRETYPE_FIXED64:
payload = readFixed64BitField(inputStream, fieldDescriptor);
break;
case WireFormat.WIRETYPE_LENGTH_DELIMITED:
CelFieldValueType celFieldValueType = fieldDescriptor.getCelFieldValueType();
switch (celFieldValueType) {
case LIST:
if (fieldDescriptor.getIsPacked()) {
payload = readPackedRepeatedFields(inputStream, fieldDescriptor);
} else {
FieldLiteDescriptor.Type protoFieldType = fieldDescriptor.getProtoFieldType();
boolean isLenDelimited =
protoFieldType.equals(FieldLiteDescriptor.Type.MESSAGE)
|| protoFieldType.equals(FieldLiteDescriptor.Type.STRING)
|| protoFieldType.equals(FieldLiteDescriptor.Type.BYTES);
if (!isLenDelimited) {
throw new IllegalStateException(
"Unexpected field type encountered for LEN-Delimited record: "
+ protoFieldType);
}
payload = readLengthDelimitedField(inputStream, fieldDescriptor);
}
break;
case MAP:
Map<Object, Object> fieldMap =
mapFieldValues.computeIfAbsent(fieldNumber, (unused) -> new LinkedHashMap<>());
Map.Entry<Object, Object> mapEntry = readSingleMapEntry(inputStream, fieldDescriptor);
fieldMap.put(mapEntry.getKey(), mapEntry.getValue());
payload = fieldMap;
break;
default:
payload = readLengthDelimitedField(inputStream, fieldDescriptor);
break;
}
break;
case WireFormat.WIRETYPE_START_GROUP:
case WireFormat.WIRETYPE_END_GROUP:
// TODO: Support groups
throw new UnsupportedOperationException("Groups are not supported");
default:
throw new IllegalArgumentException("Unexpected wire type: " + tagWireType);
}
if (fieldDescriptor.getCelFieldValueType().equals(CelFieldValueType.LIST)) {
String fieldName = fieldDescriptor.getFieldName();
List<Object> repeatedValues =
repeatedFieldValues.computeIfAbsent(
fieldNumber,
(unused) -> {
List<Object> newList = new ArrayList<>();
fieldValues.put(fieldName, newList);
return newList;
});
if (payload instanceof Collection) {
repeatedValues.addAll((Collection<?>) payload);
} else {
repeatedValues.add(payload);
}
} else {
fieldValues.put(fieldDescriptor.getFieldName(), payload);
}
}
// Protobuf encoding follows a "last one wins" semantics. This means for duplicated fields,
// we accept the last value encountered.
return fieldValues.buildKeepingLast();
}
ImmutableMap<String, Object> readAllFields(MessageLite msg, String protoTypeName)
throws IOException {
return readAllFields(msg.toByteArray(), protoTypeName);
}
@Override
public CelValue fromProtoMessageToCelValue(String protoTypeName, MessageLite msg) {
checkNotNull(msg);
checkNotNull(protoTypeName);
MessageLiteDescriptor descriptor = descriptorPool.getDescriptorOrThrow(protoTypeName);
WellKnownProto wellKnownProto =
WellKnownProto.getByTypeName(descriptor.getProtoTypeName()).orElse(null);
if (wellKnownProto == null) {
return ProtoMessageLiteValue.create(msg, descriptor.getProtoTypeName(), this);
}
return super.fromWellKnownProtoToCelValue(msg, wellKnownProto);
}
private ProtoLiteCelValueConverter(CelLiteDescriptorPool celLiteDescriptorPool) {
this.descriptorPool = celLiteDescriptorPool;
}
}