-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathcel_proto_wrap_util.cc
More file actions
1479 lines (1355 loc) · 52.7 KB
/
Copy pathcel_proto_wrap_util.cc
File metadata and controls
1479 lines (1355 loc) · 52.7 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 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.
#include "eval/public/structs/cel_proto_wrap_util.h"
#include <cstddef>
#include <cstdint>
#include <limits>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "google/protobuf/any.pb.h"
#include "google/protobuf/duration.pb.h"
#include "google/protobuf/struct.pb.h"
#include "google/protobuf/timestamp.pb.h"
#include "google/protobuf/wrappers.pb.h"
#include "absl/base/nullability.h"
#include "absl/base/optimization.h"
#include "absl/functional/overload.h"
#include "absl/log/absl_check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/cord.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/protobuf_value_factory.h"
#include "internal/overflow.h"
#include "internal/proto_time_encoding.h"
#include "internal/status_macros.h"
#include "internal/time.h"
#include "internal/well_known_types.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
#include "google/protobuf/message_lite.h"
namespace google::api::expr::runtime::internal {
namespace {
using cel::internal::DecodeDuration;
using cel::internal::DecodeTime;
using google::protobuf::Any;
using google::protobuf::BoolValue;
using google::protobuf::BytesValue;
using google::protobuf::DoubleValue;
using google::protobuf::Duration;
using google::protobuf::FloatValue;
using google::protobuf::Int32Value;
using google::protobuf::Int64Value;
using google::protobuf::ListValue;
using google::protobuf::StringValue;
using google::protobuf::Struct;
using google::protobuf::Timestamp;
using google::protobuf::UInt32Value;
using google::protobuf::UInt64Value;
using google::protobuf::Value;
using google::protobuf::Arena;
using google::protobuf::Descriptor;
using google::protobuf::DescriptorPool;
using google::protobuf::Message;
using google::protobuf::MessageFactory;
// kMaxIntJSON is defined as the Number.MAX_SAFE_INTEGER value per EcmaScript 6.
constexpr int64_t kMaxIntJSON = (1ll << 53) - 1;
// kMinIntJSON is defined as the Number.MIN_SAFE_INTEGER value per EcmaScript 6.
constexpr int64_t kMinIntJSON = -kMaxIntJSON;
// IsJSONSafe indicates whether the int is safely representable as a floating
// point value in JSON.
static bool IsJSONSafe(int64_t i) {
return i >= kMinIntJSON && i <= kMaxIntJSON;
}
// IsJSONSafe indicates whether the uint is safely representable as a floating
// point value in JSON.
static bool IsJSONSafe(uint64_t i) {
return i <= static_cast<uint64_t>(kMaxIntJSON);
}
// Map implementation wrapping google.protobuf.ListValue
class DynamicList : public CelList {
public:
DynamicList(const ListValue* values, ProtobufValueFactory factory,
Arena* arena)
: arena_(arena), factory_(std::move(factory)), values_(values) {}
CelValue operator[](int index) const override;
// List size
int size() const override { return values_->values_size(); }
private:
Arena* arena_;
ProtobufValueFactory factory_;
const ListValue* values_;
};
// Map implementation wrapping google.protobuf.Struct.
class DynamicMap : public CelMap {
public:
DynamicMap(const Struct* values, ProtobufValueFactory factory, Arena* arena)
: arena_(arena),
factory_(std::move(factory)),
values_(values),
key_list_(values) {}
absl::StatusOr<bool> Has(const CelValue& key) const override {
CelValue::StringHolder str_key;
if (!key.GetValue(&str_key)) {
// Not a string key.
return absl::InvalidArgumentError(absl::StrCat(
"Invalid map key type: '", CelValue::TypeName(key.type()), "'"));
}
return values_->fields().contains(std::string(str_key.value()));
}
absl::optional<CelValue> operator[](CelValue key) const override;
int size() const override { return values_->fields_size(); }
absl::StatusOr<const CelList*> ListKeys() const override {
return &key_list_;
}
private:
// List of keys in Struct.fields map.
// It utilizes lazy initialization, to avoid performance penalties.
class DynamicMapKeyList : public CelList {
public:
explicit DynamicMapKeyList(const Struct* values)
: values_(values), keys_(), initialized_(false) {}
// Index access
CelValue operator[](int index) const override {
CheckInit();
return keys_[index];
}
// List size
int size() const override {
CheckInit();
return values_->fields_size();
}
private:
void CheckInit() const {
absl::MutexLock lock(&mutex_);
if (!initialized_) {
for (const auto& it : values_->fields()) {
keys_.push_back(CelValue::CreateString(&it.first));
}
initialized_ = true;
}
}
const Struct* values_;
mutable absl::Mutex mutex_;
mutable std::vector<CelValue> keys_;
mutable bool initialized_;
};
Arena* arena_;
ProtobufValueFactory factory_;
const Struct* values_;
const DynamicMapKeyList key_list_;
};
// Adapter for usage with CEL_RETURN_IF_ERROR and CEL_ASSIGN_OR_RETURN.
class ReturnCelValueError {
public:
explicit ReturnCelValueError(absl::Nonnull<google::protobuf::Arena*> arena)
: arena_(arena) {}
CelValue operator()(const absl::Status& status) const {
ABSL_DCHECK(!status.ok());
return CelValue::CreateError(
google::protobuf::Arena::Create<absl::Status>(arena_, status));
}
private:
absl::Nonnull<google::protobuf::Arena*> arena_;
};
struct IgnoreErrorAndReturnNullptr {
std::nullptr_t operator()(const absl::Status& status) const {
status.IgnoreError();
return nullptr;
}
};
// ValueManager provides ValueFromMessage(....) function family.
// Functions of this family create CelValue object from specific subtypes of
// protobuf message.
class ValueManager {
public:
ValueManager(const ProtobufValueFactory& value_factory,
const google::protobuf::DescriptorPool* descriptor_pool,
google::protobuf::Arena* arena, google::protobuf::MessageFactory* message_factory)
: value_factory_(value_factory),
descriptor_pool_(descriptor_pool),
arena_(arena),
message_factory_(message_factory) {}
// Note: this overload should only be used in the context of accessing struct
// value members, which have already been adapted to the generated message
// types.
ValueManager(const ProtobufValueFactory& value_factory, google::protobuf::Arena* arena)
: value_factory_(value_factory),
descriptor_pool_(DescriptorPool::generated_pool()),
arena_(arena),
message_factory_(MessageFactory::generated_factory()) {}
static CelValue ValueFromDuration(absl::Duration duration) {
return CelValue::CreateDuration(duration);
}
CelValue ValueFromDuration(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetDurationReflection(message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
return ValueFromDuration(reflection.UnsafeToAbslDuration(*message));
}
CelValue ValueFromMessage(const Duration* duration) {
return ValueFromDuration(DecodeDuration(*duration));
}
CelValue ValueFromTimestamp(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetTimestampReflection(message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
return ValueFromTimestamp(reflection.UnsafeToAbslTime(*message));
}
static CelValue ValueFromTimestamp(absl::Time timestamp) {
return CelValue::CreateTimestamp(timestamp);
}
CelValue ValueFromMessage(const Timestamp* timestamp) {
return ValueFromTimestamp(DecodeTime(*timestamp));
}
CelValue ValueFromMessage(const ListValue* list_values) {
return CelValue::CreateList(Arena::Create<DynamicList>(
arena_, list_values, value_factory_, arena_));
}
CelValue ValueFromMessage(const Struct* struct_value) {
return CelValue::CreateMap(Arena::Create<DynamicMap>(
arena_, struct_value, value_factory_, arena_));
}
CelValue ValueFromAny(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetAnyReflection(message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
std::string type_url_scratch;
std::string value_scratch;
return ValueFromAny(reflection.GetTypeUrl(*message, type_url_scratch),
reflection.GetValue(*message, value_scratch),
descriptor_pool_, message_factory_);
}
CelValue ValueFromAny(const cel::well_known_types::StringValue& type_url,
const cel::well_known_types::BytesValue& payload,
const DescriptorPool* descriptor_pool,
MessageFactory* message_factory) {
std::string type_url_string_scratch;
absl::string_view type_url_string = absl::visit(
absl::Overload([](absl::string_view string)
-> absl::string_view { return string; },
[&type_url_string_scratch](
const absl::Cord& cord) -> absl::string_view {
if (auto flat = cord.TryFlat(); flat) {
return *flat;
}
absl::CopyCordToString(cord, &type_url_string_scratch);
return absl::string_view(type_url_string_scratch);
}),
cel::well_known_types::AsVariant(type_url));
auto pos = type_url_string.find_last_of('/');
if (pos == type_url_string.npos) {
// TODO What error code?
// Malformed type_url
return CreateErrorValue(arena_, "Malformed type_url string");
}
absl::string_view full_name = type_url_string.substr(pos + 1);
const Descriptor* nested_descriptor =
descriptor_pool->FindMessageTypeByName(full_name);
if (nested_descriptor == nullptr) {
// Descriptor not found for the type
// TODO What error code?
return CreateErrorValue(arena_, "Descriptor not found");
}
const Message* prototype = message_factory->GetPrototype(nested_descriptor);
if (prototype == nullptr) {
// Failed to obtain prototype for the descriptor
// TODO What error code?
return CreateErrorValue(arena_, "Prototype not found");
}
Message* nested_message = prototype->New(arena_);
bool ok =
absl::visit(absl::Overload(
[nested_message](absl::string_view string) -> bool {
return nested_message->ParsePartialFromString(string);
},
[nested_message](const absl::Cord& cord) -> bool {
return nested_message->ParsePartialFromCord(cord);
}),
cel::well_known_types::AsVariant(payload));
if (!ok) {
// Failed to unpack.
// TODO What error code?
return CreateErrorValue(arena_, "Failed to unpack Any into message");
}
return UnwrapMessageToValue(nested_message, value_factory_, arena_);
}
CelValue ValueFromMessage(const Any* any_value,
const DescriptorPool* descriptor_pool,
MessageFactory* message_factory) {
return ValueFromAny(any_value->type_url(), absl::Cord(any_value->value()),
descriptor_pool, message_factory);
}
CelValue ValueFromMessage(const Any* any_value) {
return ValueFromMessage(any_value, descriptor_pool_, message_factory_);
}
CelValue ValueFromBool(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetBoolValueReflection(message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
return ValueFromBool(reflection.GetValue(*message));
}
static CelValue ValueFromBool(bool value) {
return CelValue::CreateBool(value);
}
CelValue ValueFromMessage(const BoolValue* wrapper) {
return ValueFromBool(wrapper->value());
}
CelValue ValueFromInt32(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(auto reflection,
cel::well_known_types::GetInt32ValueReflection(
message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
return ValueFromInt32(reflection.GetValue(*message));
}
static CelValue ValueFromInt32(int32_t value) {
return CelValue::CreateInt64(value);
}
CelValue ValueFromMessage(const Int32Value* wrapper) {
return ValueFromInt32(wrapper->value());
}
CelValue ValueFromUInt32(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(auto reflection,
cel::well_known_types::GetUInt32ValueReflection(
message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
return ValueFromUInt32(reflection.GetValue(*message));
}
static CelValue ValueFromUInt32(uint32_t value) {
return CelValue::CreateUint64(value);
}
CelValue ValueFromMessage(const UInt32Value* wrapper) {
return ValueFromUInt32(wrapper->value());
}
CelValue ValueFromInt64(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(auto reflection,
cel::well_known_types::GetInt64ValueReflection(
message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
return ValueFromInt64(reflection.GetValue(*message));
}
static CelValue ValueFromInt64(int64_t value) {
return CelValue::CreateInt64(value);
}
CelValue ValueFromMessage(const Int64Value* wrapper) {
return ValueFromInt64(wrapper->value());
}
CelValue ValueFromUInt64(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(auto reflection,
cel::well_known_types::GetUInt64ValueReflection(
message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
return ValueFromUInt64(reflection.GetValue(*message));
}
static CelValue ValueFromUInt64(uint64_t value) {
return CelValue::CreateUint64(value);
}
CelValue ValueFromMessage(const UInt64Value* wrapper) {
return ValueFromUInt64(wrapper->value());
}
CelValue ValueFromFloat(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(auto reflection,
cel::well_known_types::GetFloatValueReflection(
message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
return ValueFromFloat(reflection.GetValue(*message));
}
static CelValue ValueFromFloat(float value) {
return CelValue::CreateDouble(value);
}
CelValue ValueFromMessage(const FloatValue* wrapper) {
return ValueFromFloat(wrapper->value());
}
CelValue ValueFromDouble(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(auto reflection,
cel::well_known_types::GetDoubleValueReflection(
message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
return ValueFromDouble(reflection.GetValue(*message));
}
static CelValue ValueFromDouble(double value) {
return CelValue::CreateDouble(value);
}
CelValue ValueFromMessage(const DoubleValue* wrapper) {
return ValueFromDouble(wrapper->value());
}
CelValue ValueFromString(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(auto reflection,
cel::well_known_types::GetStringValueReflection(
message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
std::string scratch;
return absl::visit(
absl::Overload(
[&](absl::string_view string) -> CelValue {
if (string.data() == scratch.data() &&
string.size() == scratch.size()) {
return CelValue::CreateString(
google::protobuf::Arena::Create<std::string>(arena_,
std::move(scratch)));
}
return CelValue::CreateString(google::protobuf::Arena::Create<std::string>(
arena_, std::string(string)));
},
[&](absl::Cord&& cord) -> CelValue {
auto* string = google::protobuf::Arena::Create<std::string>(arena_);
absl::CopyCordToString(cord, string);
return CelValue::CreateString(string);
}),
cel::well_known_types::AsVariant(
reflection.GetValue(*message, scratch)));
}
CelValue ValueFromString(const absl::Cord& value) {
return CelValue::CreateString(
Arena::Create<std::string>(arena_, static_cast<std::string>(value)));
}
static CelValue ValueFromString(const std::string* value) {
return CelValue::CreateString(value);
}
CelValue ValueFromMessage(const StringValue* wrapper) {
return ValueFromString(&wrapper->value());
}
CelValue ValueFromBytes(const google::protobuf::Message* message) {
CEL_ASSIGN_OR_RETURN(auto reflection,
cel::well_known_types::GetBytesValueReflection(
message->GetDescriptor()),
_.With(ReturnCelValueError(arena_)));
std::string scratch;
return absl::visit(
absl::Overload(
[&](absl::string_view string) -> CelValue {
if (string.data() == scratch.data() &&
string.size() == scratch.size()) {
return CelValue::CreateBytes(google::protobuf::Arena::Create<std::string>(
arena_, std::move(scratch)));
}
return CelValue::CreateBytes(google::protobuf::Arena::Create<std::string>(
arena_, std::string(string)));
},
[&](absl::Cord&& cord) -> CelValue {
auto* string = google::protobuf::Arena::Create<std::string>(arena_);
absl::CopyCordToString(cord, string);
return CelValue::CreateBytes(string);
}),
cel::well_known_types::AsVariant(
reflection.GetValue(*message, scratch)));
}
CelValue ValueFromBytes(const absl::Cord& value) {
return CelValue::CreateBytes(
Arena::Create<std::string>(arena_, static_cast<std::string>(value)));
}
static CelValue ValueFromBytes(google::protobuf::Arena* arena, std::string value) {
return CelValue::CreateBytes(
Arena::Create<std::string>(arena, std::move(value)));
}
CelValue ValueFromMessage(const BytesValue* wrapper) {
// BytesValue stores value as Cord
return CelValue::CreateBytes(
Arena::Create<std::string>(arena_, std::string(wrapper->value())));
}
CelValue ValueFromMessage(const Value* value) {
switch (value->kind_case()) {
case Value::KindCase::kNullValue:
return CelValue::CreateNull();
case Value::KindCase::kNumberValue:
return CelValue::CreateDouble(value->number_value());
case Value::KindCase::kStringValue:
return CelValue::CreateString(&value->string_value());
case Value::KindCase::kBoolValue:
return CelValue::CreateBool(value->bool_value());
case Value::KindCase::kStructValue:
return ValueFromMessage(&value->struct_value());
case Value::KindCase::kListValue:
return ValueFromMessage(&value->list_value());
default:
return CelValue::CreateNull();
}
}
template <typename T>
CelValue ValueFromGeneratedMessageLite(const google::protobuf::Message* message) {
const auto* downcast_message = google::protobuf::DynamicCastToGenerated<T>(message);
if (downcast_message != nullptr) {
return ValueFromMessage(downcast_message);
}
auto* value = google::protobuf::Arena::Create<T>(arena_);
absl::Cord serialized;
if (!message->SerializeToCord(&serialized)) {
return CreateErrorValue(
arena_, absl::UnknownError(
absl::StrCat("failed to serialize dynamic message: ",
message->GetTypeName())));
}
if (!value->ParseFromCord(serialized)) {
return CreateErrorValue(arena_, absl::UnknownError(absl::StrCat(
"failed to parse generated message: ",
value->GetTypeName())));
}
return ValueFromMessage(value);
}
template <typename T>
CelValue ValueFromMessage(const google::protobuf::Message* message) {
if constexpr (std::is_same_v<Any, T>) {
return ValueFromAny(message);
} else if constexpr (std::is_same_v<BoolValue, T>) {
return ValueFromBool(message);
} else if constexpr (std::is_same_v<BytesValue, T>) {
return ValueFromBytes(message);
} else if constexpr (std::is_same_v<DoubleValue, T>) {
return ValueFromDouble(message);
} else if constexpr (std::is_same_v<Duration, T>) {
return ValueFromDuration(message);
} else if constexpr (std::is_same_v<FloatValue, T>) {
return ValueFromFloat(message);
} else if constexpr (std::is_same_v<Int32Value, T>) {
return ValueFromInt32(message);
} else if constexpr (std::is_same_v<Int64Value, T>) {
return ValueFromInt64(message);
} else if constexpr (std::is_same_v<ListValue, T>) {
return ValueFromGeneratedMessageLite<ListValue>(message);
} else if constexpr (std::is_same_v<StringValue, T>) {
return ValueFromString(message);
} else if constexpr (std::is_same_v<Struct, T>) {
return ValueFromGeneratedMessageLite<Struct>(message);
} else if constexpr (std::is_same_v<Timestamp, T>) {
return ValueFromTimestamp(message);
} else if constexpr (std::is_same_v<UInt32Value, T>) {
return ValueFromUInt32(message);
} else if constexpr (std::is_same_v<UInt64Value, T>) {
return ValueFromUInt64(message);
} else if constexpr (std::is_same_v<Value, T>) {
return ValueFromGeneratedMessageLite<Value>(message);
} else {
ABSL_UNREACHABLE();
}
}
private:
const ProtobufValueFactory& value_factory_;
const google::protobuf::DescriptorPool* descriptor_pool_;
google::protobuf::Arena* arena_;
MessageFactory* message_factory_;
};
// Class makes CelValue from generic protobuf Message.
// It holds a registry of CelValue factories for specific subtypes of Message.
// If message does not match any of types stored in registry, generic
// message-containing CelValue is created.
class ValueFromMessageMaker {
public:
template <class MessageType>
static CelValue CreateWellknownTypeValue(const google::protobuf::Message* msg,
const ProtobufValueFactory& factory,
Arena* arena) {
// Copy the original descriptor pool and message factory for unpacking 'Any'
// values.
google::protobuf::MessageFactory* message_factory =
msg->GetReflection()->GetMessageFactory();
const google::protobuf::DescriptorPool* pool = msg->GetDescriptor()->file()->pool();
return ValueManager(factory, pool, arena, message_factory)
.ValueFromMessage<MessageType>(msg);
}
static absl::optional<CelValue> CreateValue(
const google::protobuf::Message* message, const ProtobufValueFactory& factory,
Arena* arena) {
switch (message->GetDescriptor()->well_known_type()) {
case google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE:
return CreateWellknownTypeValue<DoubleValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE:
return CreateWellknownTypeValue<FloatValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE:
return CreateWellknownTypeValue<Int64Value>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE:
return CreateWellknownTypeValue<UInt64Value>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE:
return CreateWellknownTypeValue<Int32Value>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE:
return CreateWellknownTypeValue<UInt32Value>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE:
return CreateWellknownTypeValue<StringValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE:
return CreateWellknownTypeValue<BytesValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE:
return CreateWellknownTypeValue<BoolValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_ANY:
return CreateWellknownTypeValue<Any>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_DURATION:
return CreateWellknownTypeValue<Duration>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_TIMESTAMP:
return CreateWellknownTypeValue<Timestamp>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE:
return CreateWellknownTypeValue<Value>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_LISTVALUE:
return CreateWellknownTypeValue<ListValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_STRUCT:
return CreateWellknownTypeValue<Struct>(message, factory, arena);
// WELLKNOWNTYPE_FIELDMASK has no special CelValue type
default:
return absl::nullopt;
}
}
// Non-copyable, non-assignable
ValueFromMessageMaker(const ValueFromMessageMaker&) = delete;
ValueFromMessageMaker& operator=(const ValueFromMessageMaker&) = delete;
};
CelValue DynamicList::operator[](int index) const {
return ValueManager(factory_, arena_)
.ValueFromMessage(&values_->values(index));
}
absl::optional<CelValue> DynamicMap::operator[](CelValue key) const {
CelValue::StringHolder str_key;
if (!key.GetValue(&str_key)) {
// Not a string key.
return CreateErrorValue(arena_, absl::InvalidArgumentError(absl::StrCat(
"Invalid map key type: '",
CelValue::TypeName(key.type()), "'")));
}
auto it = values_->fields().find(std::string(str_key.value()));
if (it == values_->fields().end()) {
return absl::nullopt;
}
return ValueManager(factory_, arena_).ValueFromMessage(&it->second);
}
google::protobuf::Message* DurationFromValue(const google::protobuf::Message* prototype,
const CelValue& value,
google::protobuf::Arena* arena) {
absl::Duration val;
if (!value.GetValue(&val)) {
return nullptr;
}
if (!cel::internal::ValidateDuration(val).ok()) {
return nullptr;
}
auto* message = prototype->New(arena);
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetDurationReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
reflection.UnsafeSetFromAbslDuration(message, val);
return message;
}
google::protobuf::Message* BoolFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
bool val;
if (!value.GetValue(&val)) {
return nullptr;
}
auto* message = prototype->New(arena);
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetBoolValueReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
reflection.SetValue(message, val);
return message;
}
google::protobuf::Message* BytesFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
CelValue::BytesHolder view_val;
if (!value.GetValue(&view_val)) {
return nullptr;
}
auto* message = prototype->New(arena);
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetBytesValueReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
reflection.SetValue(message, view_val.value());
return message;
}
google::protobuf::Message* DoubleFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
double val;
if (!value.GetValue(&val)) {
return nullptr;
}
auto* message = prototype->New(arena);
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetDoubleValueReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
reflection.SetValue(message, val);
return message;
}
google::protobuf::Message* FloatFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
double val;
if (!value.GetValue(&val)) {
return nullptr;
}
float fval = val;
// Abort the conversion if the value is outside the float range.
if (val > std::numeric_limits<float>::max()) {
fval = std::numeric_limits<float>::infinity();
} else if (val < std::numeric_limits<float>::lowest()) {
fval = -std::numeric_limits<float>::infinity();
}
auto* message = prototype->New(arena);
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetFloatValueReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
reflection.SetValue(message, static_cast<float>(fval));
return message;
}
google::protobuf::Message* Int32FromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
int64_t val;
if (!value.GetValue(&val)) {
return nullptr;
}
if (!cel::internal::CheckedInt64ToInt32(val)) {
return nullptr;
}
int32_t ival = static_cast<int32_t>(val);
auto* message = prototype->New(arena);
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetInt32ValueReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
reflection.SetValue(message, ival);
return message;
}
google::protobuf::Message* Int64FromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
int64_t val;
if (!value.GetValue(&val)) {
return nullptr;
}
auto* message = prototype->New(arena);
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetInt64ValueReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
reflection.SetValue(message, val);
return message;
}
google::protobuf::Message* StringFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
CelValue::StringHolder view_val;
if (!value.GetValue(&view_val)) {
return nullptr;
}
auto* message = prototype->New(arena);
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetStringValueReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
reflection.SetValue(message, view_val.value());
return message;
}
google::protobuf::Message* TimestampFromValue(const google::protobuf::Message* prototype,
const CelValue& value,
google::protobuf::Arena* arena) {
absl::Time val;
if (!value.GetValue(&val)) {
return nullptr;
}
if (!cel::internal::ValidateTimestamp(val).ok()) {
return nullptr;
}
auto* message = prototype->New(arena);
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetTimestampReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
reflection.UnsafeSetFromAbslTime(message, val);
return message;
}
google::protobuf::Message* UInt32FromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
uint64_t val;
if (!value.GetValue(&val)) {
return nullptr;
}
if (!cel::internal::CheckedUint64ToUint32(val)) {
return nullptr;
}
uint32_t ival = static_cast<uint32_t>(val);
auto* message = prototype->New(arena);
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetUInt32ValueReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
reflection.SetValue(message, ival);
return message;
}
google::protobuf::Message* UInt64FromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
uint64_t val;
if (!value.GetValue(&val)) {
return nullptr;
}
auto* message = prototype->New(arena);
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetUInt64ValueReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
reflection.SetValue(message, val);
return message;
}
google::protobuf::Message* ValueFromValue(google::protobuf::Message* message, const CelValue& value,
google::protobuf::Arena* arena);
google::protobuf::Message* ValueFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
return ValueFromValue(prototype->New(arena), value, arena);
}
google::protobuf::Message* ListFromValue(google::protobuf::Message* message, const CelValue& value,
google::protobuf::Arena* arena) {
if (!value.IsList()) {
return nullptr;
}
const CelList& list = *value.ListOrDie();
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetListValueReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
for (int i = 0; i < list.size(); i++) {
auto e = list.Get(arena, i);
auto* elem = reflection.AddValues(message);
if (ValueFromValue(elem, e, arena) == nullptr) {
return nullptr;
}
}
return message;
}
google::protobuf::Message* ListFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
if (!value.IsList()) {
return nullptr;
}
return ListFromValue(prototype->New(arena), value, arena);
}
google::protobuf::Message* StructFromValue(google::protobuf::Message* message,
const CelValue& value, google::protobuf::Arena* arena) {
if (!value.IsMap()) {
return nullptr;
}
const CelMap& map = *value.MapOrDie();
absl::StatusOr<const CelList*> keys_or = map.ListKeys(arena);
if (!keys_or.ok()) {
// If map doesn't support listing keys, it can't pack into a Struct value.
// This will surface as a CEL error when the object creation expression
// fails.
return nullptr;
}
const CelList& keys = **keys_or;
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetStructReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));
for (int i = 0; i < keys.size(); i++) {
auto k = keys.Get(arena, i);
// If the key is not a string type, abort the conversion.
if (!k.IsString()) {
return nullptr;
}
absl::string_view key = k.StringOrDie().value();
auto v = map.Get(arena, k);
if (!v.has_value()) {
return nullptr;
}
auto* field = reflection.InsertField(message, key);
if (ValueFromValue(field, *v, arena) == nullptr) {
return nullptr;
}
}
return message;
}
google::protobuf::Message* StructFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
if (!value.IsMap()) {
return nullptr;
}
return StructFromValue(prototype->New(arena), value, arena);
}
google::protobuf::Message* ValueFromValue(google::protobuf::Message* message, const CelValue& value,
google::protobuf::Arena* arena) {
CEL_ASSIGN_OR_RETURN(
auto reflection,
cel::well_known_types::GetValueReflection(message->GetDescriptor()),
_.With(IgnoreErrorAndReturnNullptr()));