GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — cel-python/cel_expr_python/py_cel_value.cc at main · yarikoptic/cel-python Expand file tree/ Copy pathpy_cel_value.ccMore file actions 908 lines (850 loc) · 32.3 KB / Copy pathpy_cel_value.ccFile metadata and controls908 lines (850 loc) · 32.3 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 // 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. #include "cel_expr_python/py_cel_value.h" #include <Python.h> // IWYU pragma: keep - Needed for PyObject #include <datetime.h> // IWYU pragma: keep #include <cstdint> #include <memory> #include <optional> #include <string> #include <string_view> #include <utility> #include "absl/base/call_once.h" #include "absl/functional/function_ref.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/optional.h" #include "common/kind.h" #include "common/type.h" #include "common/value.h" #include "common/value_kind.h" #include "cel_expr_python/free_threading_mutex.h" #include "cel_expr_python/py_cel_arena.h" #include "cel_expr_python/py_cel_env_internal.h" #include "cel_expr_python/py_cel_type.h" #include "cel_expr_python/py_cel_value_provider.h" #include "cel_expr_python/py_error_status.h" #include "cel_expr_python/status_macros.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "pybind11_abseil/absl_casters.h" namespace cel_python { namespace py = ::pybind11; void PyCelValue::DefinePythonBindings(py::module& m) { py::class_<PyCelValue>(m, "Value") .def("type", &PyCelValue::Type) .def("value", [](PyCelValue& self) { PyObject* obj = self.Value(); if (obj == nullptr) { throw py::error_already_set(); } return py::reinterpret_borrow<py::object>(obj); }) .def("plain_value", [](PyCelValue& self) { PyObject* obj = self.PlainValue(); if (obj == nullptr) { throw py::error_already_set(); } return py::reinterpret_borrow<py::object>(obj); }) .def("__repr__", &PyCelValue::ToString); py::class_<PyCelListItemAccessor, PyCelValue>(m, "_CelListItemAccessor"); py::class_<PyCelMapItemAccessor, PyCelValue>(m, "_CelMapItemAccessor"); } // Should be called with the GIL held. PyCelValue::PyCelValue(cel::Value& cel_value, std::shared_ptr<PyCelArena> arena, std::shared_ptr<PyCelEnvInternal> env) : cel_value_(std::move(cel_value)), object_(nullptr), plain_object_(nullptr), arena_(std::move(arena)), env_(std::move(env)) {} PyCelValue::PyCelValue(PyCelValue&& other) noexcept : object_(nullptr), plain_object_(nullptr) { FreeThreadingLockGuard lock(other.mutex_); cel_value_ = std::move(other.cel_value_); arena_ = std::move(other.arena_); env_ = std::move(other.env_); object_ = other.object_; plain_object_ = other.plain_object_; other.object_ = nullptr; other.plain_object_ = nullptr; } PyCelValue::~PyCelValue() { if (object_ || plain_object_) { if (!PyGILState_Check()) { py::gil_scoped_acquire acquire; Py_XDECREF(object_); Py_XDECREF(plain_object_); } else { Py_XDECREF(object_); Py_XDECREF(plain_object_); } } } PyCelType PyCelValue::Type() { return PyCelType::ForCelValue(cel_value_); } PyObject* PyCelValue::Value() { ABSL_CHECK(PyGILState_Check()); FreeThreadingLockGuard lock(mutex_); if (object_) { return object_; } object_ = CelValueToPyObject(cel_value_, env_, arena_, /*plain_value=*/false); if (object_ == nullptr && !PyErr_Occurred()) { PyErr_SetString(PyExc_AssertionError, "Cannot create object"); } return object_; } PyObject* PyCelValue::PlainValue() { ABSL_CHECK(PyGILState_Check()); FreeThreadingLockGuard lock(mutex_); if (plain_object_) { return plain_object_; } plain_object_ = CelValueToPyObject(cel_value_, env_, arena_, /*plain_value=*/true); if (plain_object_ == nullptr && !PyErr_Occurred()) { PyErr_SetString(PyExc_AssertionError, "Cannot create object"); } return plain_object_; } std::string PyCelValue::ToString() { return cel_value_.DebugString(); } PyCelValueProvider::PyCelValueProvider(std::string name, PyObject* value, std::shared_ptr<PyCelEnvInternal> env) : name_(std::move(name)), py_object_(value), env_(std::move(env)) { Py_INCREF(py_object_); } PyCelValueProvider::~PyCelValueProvider() { if (!PyGILState_Check()) { py::gil_scoped_acquire acquire; Py_DECREF(py_object_); } else { Py_DECREF(py_object_); } } cel::Value PyCelValueProvider::Provide( const google::protobuf::DescriptorPool* descriptor_pool, google::protobuf::MessageFactory* message_factory, google::protobuf::Arena* arena) const { py::gil_scoped_acquire acquire; const PyCelType& type = env_->GetVariableType(name_); absl::StatusOr<cel::Value> converted_value = PyObjectToCelValue( py_object_, type, [this]() { return name_; }, env_, arena); if (!converted_value.ok()) { return cel::ErrorValue::From(converted_value.status(), arena); } return *converted_value; } PyCelListItemAccessor::PyCelListItemAccessor( PyCelListItemAccessor&& other) noexcept : PyCelValue(std::move(other)), index_(other.index_) { FreeThreadingLockGuard lock(other.mutex_); resolved_ = other.resolved_; element_value_ = std::move(other.element_value_); } void PyCelListItemAccessor::ResolveElementLocked() { if (resolved_) { return; } cel::ListValue list = cel_value_.GetList(); absl::StatusOr<cel::Value> element = list.Get(index_, env_->GetDescriptorPool(), env_->GetMessageFactory(), arena_->GetArena()); if (!element.ok()) { element_value_ = cel::ErrorValue::From(element.status(), arena_->GetArena()); resolved_ = true; return; } element_value_ = element.value(); resolved_ = true; } PyCelType PyCelListItemAccessor::Type() { FreeThreadingLockGuard lock(mutex_); ResolveElementLocked(); return PyCelType::ForCelValue(element_value_); } PyObject* PyCelListItemAccessor::Value() { ABSL_CHECK(PyGILState_Check()); FreeThreadingLockGuard lock(mutex_); if (object_) { return object_; } ResolveElementLocked(); object_ = CelValueToPyObject(element_value_, env_, arena_, /*plain_value=*/false); if (object_ == nullptr && !PyErr_Occurred()) { PyErr_SetString(PyExc_AssertionError, "Cannot create object"); } return object_; } PyObject* PyCelListItemAccessor::PlainValue() { ABSL_CHECK(PyGILState_Check()); FreeThreadingLockGuard lock(mutex_); if (plain_object_) { return plain_object_; } ResolveElementLocked(); plain_object_ = CelValueToPyObject(element_value_, env_, arena_, /*plain_value=*/true); if (plain_object_ == nullptr && !PyErr_Occurred()) { PyErr_SetString(PyExc_AssertionError, "Cannot create object"); } return plain_object_; } std::string PyCelListItemAccessor::ToString() { FreeThreadingLockGuard lock(mutex_); ResolveElementLocked(); return element_value_.DebugString(); } PyCelMapItemAccessor::PyCelMapItemAccessor( PyCelMapItemAccessor&& other) noexcept : PyCelValue(std::move(other)) { FreeThreadingLockGuard lock(other.mutex_); key_ = std::move(other.key_); element_value_ = std::move(other.element_value_); resolved_ = other.resolved_; } void PyCelMapItemAccessor::ResolveElementLocked() { if (resolved_) { return; } cel::MapValue map = cel_value_.GetMap(); absl::Status status = map.Get(key_, env_->GetDescriptorPool(), env_->GetMessageFactory(), arena_->GetArena(), &element_value_); if (!status.ok()) { element_value_ = cel::ErrorValue::From(status, arena_->GetArena()); resolved_ = true; return; } resolved_ = true; } PyCelType PyCelMapItemAccessor::Type() { FreeThreadingLockGuard lock(mutex_); ResolveElementLocked(); return PyCelType::ForCelValue(element_value_); } PyObject* PyCelMapItemAccessor::Value() { ABSL_CHECK(PyGILState_Check()); FreeThreadingLockGuard lock(mutex_); if (object_) { return object_; } ResolveElementLocked(); object_ = CelValueToPyObject(element_value_, env_, arena_, /*plain_value=*/false); if (object_ == nullptr && !PyErr_Occurred()) { PyErr_SetString(PyExc_AssertionError, "Cannot create object"); } return object_; } PyObject* PyCelMapItemAccessor::PlainValue() { ABSL_CHECK(PyGILState_Check()); FreeThreadingLockGuard lock(mutex_); if (plain_object_) { return plain_object_; } ResolveElementLocked(); plain_object_ = CelValueToPyObject(element_value_, env_, arena_, /*plain_value=*/true); if (plain_object_ == nullptr && !PyErr_Occurred()) { PyErr_SetString(PyExc_AssertionError, "Cannot create object"); } return plain_object_; } std::string PyCelMapItemAccessor::ToString() { FreeThreadingLockGuard lock(mutex_); ResolveElementLocked(); return element_value_.DebugString(); } // This should be called with the GIL held. PyObject* CelValueToPyObject(const cel::Value& cel_value, const std::shared_ptr<PyCelEnvInternal>& env, const std::shared_ptr<PyCelArena>& arena, bool plain_value) { switch (cel_value.kind()) { case cel::ValueKind::kNull: { Py_INCREF(Py_None); return Py_None; } case cel::ValueKind::kBool: { PyObject* py_bool = cel_value.AsBool().value() ? Py_True : Py_False; Py_INCREF(py_bool); return py_bool; } case cel::ValueKind::kInt: { int64_t value = cel_value.AsInt().value(); return PyLong_FromLongLong(value); } case cel::ValueKind::kUint: { uint64_t value = cel_value.AsUint().value(); return PyLong_FromUnsignedLongLong(value); } case cel::ValueKind::kDouble: { double value = cel_value.AsDouble().value(); return PyFloat_FromDouble(value); } case cel::ValueKind::kString: { std::string value = cel_value.AsString().value().ToString(); return PyUnicode_FromStringAndSize(value.data(), value.size()); } case cel::ValueKind::kBytes: { std::string value = cel_value.AsBytes().value().ToString(); return PyByteArray_FromStringAndSize(value.data(), value.size()); } case cel::ValueKind::kMessage: { cel::MessageValue value = cel_value.AsMessage().value(); std::string serialized_data; if (!value.GetParsed()->SerializePartialToString(&serialized_data)) { PyErr_Format(PyExc_RuntimeError, "Cannot serialize message"); return nullptr; } return env->GetPyMessageFactory()->FromString( std::string(value.GetTypeName()), serialized_data); } case cel::ValueKind::kList: { cel::ListValue list = *cel_value.AsList(); Py_ssize_t size = *list.Size(); PyObject* py_list = PyList_New(size); absl::Status status = absl::OkStatus(); for (int i = 0; i < size; ++i) { PyObject* py_item; if (plain_value) { absl::StatusOr<cel::Value> item = list.Get(i, env->GetDescriptorPool(), env->GetMessageFactory(), arena->GetArena()); if (!item.ok()) { status = item.status(); break; } py_item = CelValueToPyObject(*item, env, arena, /*plain_value=*/true); } else { py_item = py::cast(PyCelListItemAccessor(cel_value, i, arena, env)) .release() .ptr(); } // PyList_SetItem is special in that it "steals" the reference to the // item being set, so we must not decref it. // https://docs.python.org/3/c-api/list.html#:~:text=int-,pylist_setitem PyList_SetItem(py_list, i, py_item); } if (!status.ok()) { Py_DECREF(py_list); return CelValueToPyObject( cel::ErrorValue::From(status, arena->GetArena()), env, arena, /*plain_value=*/plain_value); } return py_list; } case cel::ValueKind::kMap: { cel::MapValue map = *cel_value.AsMap(); cel::ListValue key_list; absl::Status status = map.ListKeys(env->GetDescriptorPool(), env->GetMessageFactory(), arena->GetArena(), &key_list); if (!status.ok()) { PyErr_Format(PyExc_RuntimeError, "Cannot list keys: %s", status.ToString().c_str()); return nullptr; } PyObject* py_map = PyDict_New(); Py_ssize_t size = *key_list.Size(); for (int i = 0; i < size; ++i) { absl::StatusOr<cel::Value> key = key_list.Get(i, env->GetDescriptorPool(), env->GetMessageFactory(), arena->GetArena()); if (!key.ok()) { PyErr_Format(PyExc_RuntimeError, "Cannot get key: %s", key.status().ToString().c_str()); return nullptr; } PyObject* py_key = CelValueToPyObject(*key, env, arena, /*plain_value=*/true); PyObject* py_value; if (plain_value) { cel::Value element_value; absl::Status status = map.Get(*key, env->GetDescriptorPool(), env->GetMessageFactory(), arena->GetArena(), &element_value); if (!status.ok()) { PyErr_Format(PyExc_RuntimeError, "Cannot get value: %s", status.ToString().c_str()); Py_DECREF(py_key); return nullptr; } py_value = CelValueToPyObject(element_value, env, arena, /*plain_value=*/true); } else { py_value = py::cast(PyCelMapItemAccessor(cel_value, *key, arena, env)) .release() .ptr(); } // In contrast to PyList_SetItem, PyDict_SetItem does not "steal" the // reference to the key and value being set, so we must decref them. // https://docs.python.org/3/c-api/dict.html#:~:text=int-,pydict_setitem PyDict_SetItem(py_map, py_key, py_value); Py_DECREF(py_key); Py_DECREF(py_value); } return py_map; } case cel::ValueKind::kTimestamp: { std::optional<cel::TimestampValue> timestamp = cel_value.AsTimestamp(); if (!timestamp.has_value()) { PyErr_Format(PyExc_RuntimeError, "Cannot convert to timestamp"); return nullptr; } return py::cast(timestamp->ToTime()).release().ptr(); } case cel::ValueKind::kDuration: { std::optional<cel::DurationValue> duration = cel_value.AsDuration(); if (!duration.has_value()) { PyErr_Format(PyExc_RuntimeError, "Cannot convert to duration"); return nullptr; } return py::cast(duration->ToDuration()).release().ptr(); } case cel::ValueKind::kError: { std::string value = cel_value.AsError()->ToStatus().ToString(); return PyUnicode_FromStringAndSize(value.data(), value.size()); } case cel::ValueKind::kType: { const cel::Type& type = cel_value.AsType()->type(); return py::cast(PyCelType::FromCelType(type)).release().ptr(); } default: { PyErr_Format(PyExc_RuntimeError, "Unimplemented type: %d", (int)cel_value.kind()); return nullptr; } } } static absl::string_view NormalizeTypeName(absl::string_view type_name) { // 32-bit wrappers are equivalent to 64-bit. if (type_name == "google.protobuf.Int32Value") { return cel::IntWrapperType::kName; } else if (type_name == "google.protobuf.UInt32Value") { return cel::UintWrapperType::kName; } else if (type_name == "google.protobuf.FloatValue") { return cel::DoubleWrapperType::kName; } return type_name; } static cel::ErrorValue InvalidTypeError( PyObject* py_object, absl::FunctionRef<std::string()> context, const PyCelType& expected_type, google::protobuf::Arena* arena) { PyTypeObject* type = Py_TYPE(py_object); return cel::ErrorValue::From( absl::InvalidArgumentError( absl::StrFormat("Unexpected value type for '%s': %s. (Expected %s)", context(), type->tp_name, expected_type.GetName())), arena); } static void EnsureDateTimeModuleImported() { static absl::once_flag import_py_datetime_once_flag; absl::call_once(import_py_datetime_once_flag, []() { PyDateTime_IMPORT; }); } // Converts a serialized protocol buffer message to a CEL value. // // The CEL value of the protocol buffer message or cel::ErrorValue if the // conversion fails. static cel::Value ProtoMessageToCelValue( absl::string_view message_type_name, PyObject* serialized_bytes, const std::shared_ptr<PyCelEnvInternal>& env, google::protobuf::Arena* arena) { // The Python GIL is required to safely inspect the serialized_bytes PyObject. // The caller retains ownership of serialized_bytes, so the extracted buffer // (bytes_ptr and bytes_size) remains valid across GIL release within the // lifetime of this function. const uint8_t* bytes_ptr = reinterpret_cast<const uint8_t*>(PyBytes_AS_STRING(serialized_bytes)); const Py_ssize_t bytes_size = PyBytes_GET_SIZE(serialized_bytes); absl::StatusOr<cel::Value> wrapped_message; { // Release the GIL before calling into C++ DescriptorPool and MessageFactory // to maintain the lock hierarchy (DescriptorPool Mutex -> Python GIL). // Any fallback lookups into Python (e.g., via PyDescriptorDatabase) // will re-acquire the GIL on demand. py::gil_scoped_release gil_release; const google::protobuf::Descriptor* descriptor = env->GetDescriptorPool()->FindMessageTypeByName(message_type_name); if (descriptor == nullptr) { wrapped_message = absl::InvalidArgumentError(absl::StrFormat( "Descriptor not found for message type '%s'", message_type_name)); } else { const google::protobuf::Message* prototype = env->GetMessageFactory()->GetPrototype(descriptor); if (prototype == nullptr) { wrapped_message = absl::InvalidArgumentError(absl::StrFormat( "Prototype not found for message type '%s'", message_type_name)); } else { google::protobuf::Message* message = prototype->New(arena); if (message == nullptr) { wrapped_message = absl::InternalError(absl::StrFormat( "Failed to create new message of type '%s'", message_type_name)); } else { google::protobuf::io::CodedInputStream coded_input_stream(bytes_ptr, bytes_size); if (!message->MergePartialFromCodedStream(&coded_input_stream)) { wrapped_message = absl::InvalidArgumentError(absl::StrFormat( "Failed to parse serialized data for type '%s' ", message_type_name)); } else { wrapped_message = cel::Value::WrapMessage(message, env->GetDescriptorPool(), env->GetMessageFactory(), arena); } } } } } // The GIL is re-acquired here. Check if protobuf parsing or descriptor // lookups raised a Python exception in PyDescriptorDatabase. absl::Status status = PyErr_toStatus(); if (!status.ok()) { return cel::ErrorValue::From(status, arena); } if (!wrapped_message.ok()) { return cel::ErrorValue::From(wrapped_message.status(), arena); } return *wrapped_message; } absl::StatusOr<cel::Value> PyObjectToCelValue( PyObject* py_object, const PyCelType& expected_type, absl::FunctionRef<std::string()> context, const std::shared_ptr<PyCelEnvInternal>& env, google::protobuf::Arena* arena, bool bypass_type_check) { if (!py_object) { return cel::ErrorValue::From( absl::InvalidArgumentError( absl::StrFormat("Unexpected None value for '%s'. (Expected %s)", context(), expected_type.GetName())), arena); } switch (expected_type.GetKind()) { case cel::Kind::kDyn: { CEL_PYTHON_ASSIGN_OR_RETURN(const PyCelType& type, PyCelType::ForPyObject(py_object, context)); return PyObjectToCelValue(py_object, type, context, env, arena, /*bypass_type_check=*/true); } case cel::Kind::kNull: { return cel::NullValue(); } case cel::Kind::kBool: { if (py_object == Py_True) { return cel::BoolValue(true); } else if (py_object == Py_False) { return cel::BoolValue(false); } else { return InvalidTypeError(py_object, context, expected_type, arena); } } case cel::Kind::kInt: { if (bypass_type_check || PyNumber_Check(py_object)) { int64_t value = PyLong_AsLongLong(py_object); if (PyErr_Occurred()) { return cel::ErrorValue::From(PyErr_toStatus(), arena); } return cel::IntValue(value); } else { return InvalidTypeError(py_object, context, expected_type, arena); } } case cel::Kind::kUint: { if (bypass_type_check || PyNumber_Check(py_object)) { uint64_t value = PyLong_AsUnsignedLongLong(py_object); if (PyErr_Occurred()) { return cel::ErrorValue::From(PyErr_toStatus(), arena); } return cel::UintValue(value); } else { return InvalidTypeError(py_object, context, expected_type, arena); } } case cel::Kind::kDouble: { if (bypass_type_check || PyNumber_Check(py_object)) { double value = PyFloat_AsDouble(py_object); if (PyErr_Occurred()) { return cel::ErrorValue::From(PyErr_toStatus(), arena); } return cel::DoubleValue(value); } else { return InvalidTypeError(py_object, context, expected_type, arena); } } case cel::Kind::kString: { if (PyUnicode_Check(py_object)) { std::string value = PyUnicode_AsUTF8(py_object); return cel::StringValue::From(value, arena); } else if (PyBytes_Check(py_object)) { return cel::StringValue::From(PyBytes_AsString(py_object), arena); } else { return InvalidTypeError(py_object, context, expected_type, arena); } } case cel::Kind::kBytes: { if (PyByteArray_Check(py_object)) { Py_ssize_t size = PyByteArray_Size(py_object); char* bytes = PyByteArray_AsString(py_object); return cel::BytesValue::From(std::string(bytes, size), arena); } else if (PyBytes_Check(py_object)) { return cel::BytesValue::From(PyBytes_AsString(py_object), arena); } return InvalidTypeError(py_object, context, expected_type, arena); } case cel::Kind::kTimestamp: { EnsureDateTimeModuleImported(); if (PyDateTime_Check(py_object)) { absl::Time time; try { time = py::cast<absl::Time>(py_object); } catch (const py::cast_error& e) { PyErr_Clear(); return absl::UnknownError(absl::StrFormat( "Cannot convert %s to absl::Time: %s", PyUnicode_AsUTF8(PyObject_Repr(py_object)), e.what())); } absl::StatusOr<cel::TimestampValue> timestamp_value = cel::SafeTimestampValue(time); if (!timestamp_value.ok()) { return cel::ErrorValue::From(timestamp_value.status(), arena); } return *timestamp_value; } else if (std::string_view(Py_TYPE(py_object)->tp_name) == "Timestamp") { PyObject* py_seconds = nullptr; PyObject* py_nanos = nullptr; int64_t seconds; int32_t nanos; bool ok = true; py_seconds = PyObject_GetAttrString(py_object, "seconds"); if (PyErr_Occurred() || !PyLong_Check(py_seconds)) { ok = false; } else { seconds = PyLong_AsLongLong(py_seconds); if (PyErr_Occurred()) { ok = false; } else { py_nanos = PyObject_GetAttrString(py_object, "nanos"); if (PyErr_Occurred() || !PyLong_Check(py_nanos)) { ok = false; } else { nanos = PyLong_AsLongLong(py_nanos); if (PyErr_Occurred()) { ok = false; } } } } Py_XDECREF(py_seconds); Py_XDECREF(py_nanos); if (!ok) { PyErr_Clear(); return absl::UnknownError( absl::StrFormat("Cannot convert %s to cel.Type.TIMESTAMP", PyUnicode_AsUTF8(PyObject_Repr(py_object)))); } absl::Time time = absl::FromUnixSeconds(seconds) + absl::Nanoseconds(nanos); absl::StatusOr<cel::TimestampValue> timestamp_value = cel::SafeTimestampValue(time); if (!timestamp_value.ok()) { return cel::ErrorValue::From(timestamp_value.status(), arena); } return *timestamp_value; } else { return InvalidTypeError(py_object, context, expected_type, arena); } } case cel::Kind::kDuration: { EnsureDateTimeModuleImported(); if (PyDelta_Check(py_object)) { absl::Duration duration; try { duration = py::cast<absl::Duration>(py_object); } catch (const py::cast_error& e) { PyErr_Clear(); return absl::UnknownError(absl::StrFormat( "Cannot convert %s to absl::Duration: %s", PyUnicode_AsUTF8(PyObject_Repr(py_object)), e.what())); } absl::StatusOr<cel::DurationValue> duration_value = cel::SafeDurationValue(duration); if (!duration_value.ok()) { return cel::ErrorValue::From(duration_value.status(), arena); } return *duration_value; } else if (std::string_view(Py_TYPE(py_object)->tp_name) == "Duration") { PyObject* py_seconds = nullptr; PyObject* py_nanos = nullptr; int64_t seconds; int32_t nanos; bool ok = true; py_seconds = PyObject_GetAttrString(py_object, "seconds"); if (PyErr_Occurred() || !PyLong_Check(py_seconds)) { ok = false; } else { seconds = PyLong_AsLongLong(py_seconds); if (PyErr_Occurred()) { ok = false; } else { py_nanos = PyObject_GetAttrString(py_object, "nanos"); if (PyErr_Occurred() || !PyLong_Check(py_nanos)) { ok = false; } else { nanos = PyLong_AsLongLong(py_nanos); if (PyErr_Occurred()) { ok = false; } } } } Py_XDECREF(py_seconds); Py_XDECREF(py_nanos); if (!ok) { PyErr_Clear(); return absl::UnknownError( absl::StrFormat("Cannot convert %s to absl::Duration", PyUnicode_AsUTF8(PyObject_Repr(py_object)))); } absl::Duration duration = absl::Seconds(seconds) + absl::Nanoseconds(nanos); absl::StatusOr<cel::DurationValue> duration_value = cel::SafeDurationValue(duration); if (!duration_value.ok()) { return cel::ErrorValue::From(duration_value.status(), arena); } return *duration_value; } else { return InvalidTypeError(py_object, context, expected_type, arena); } } case cel::Kind::kMessage: { CEL_PYTHON_ASSIGN_OR_RETURN(const PyCelType& type, PyCelType::ForPyObject(py_object, context)); if (!bypass_type_check && type.GetName() != expected_type.GetName() && NormalizeTypeName(type.GetName()) != NormalizeTypeName(expected_type.GetName())) { return InvalidTypeError(py_object, context, expected_type, arena); } PyObject* serialized_bytes = PyObject_CallMethod(py_object, "SerializePartialToString", ""); if (!serialized_bytes) { PyErr_Clear(); return cel::ErrorValue::From(PyErr_toStatus(), arena); } if (!PyBytes_Check(serialized_bytes)) { Py_DECREF(serialized_bytes); // Expected SerializePartialToString to return bytes. return InvalidTypeError(py_object, context, expected_type, arena); } cel::Value value = ProtoMessageToCelValue(type.ToString(), serialized_bytes, env, arena); Py_DECREF(serialized_bytes); return value; } case cel::Kind::kList: { if (PyList_Check(py_object)) { const PyCelType& element_type = expected_type.GetParam(0); Py_ssize_t size = PyList_Size(py_object); auto builder = cel::NewListValueBuilder(arena); for (int i = 0; i < size; ++i) { PyObject* item = PyList_GetItem(py_object, i); // Note: PyList_GetItem returns a borrowed reference, so we shouldn't // DECREF it. CEL_PYTHON_ASSIGN_OR_RETURN(cel::Value converted_value, PyObjectToCelValue( item, element_type, [context, i]() { return absl::StrFormat( "%s[%d]", context(), i); }, env, arena)); CEL_PYTHON_RETURN_IF_ERROR(builder->Add(converted_value)); } return std::move(*builder).Build(); } else { CEL_PYTHON_ASSIGN_OR_RETURN(const PyCelType& object_type, PyCelType::ForPyObject(py_object, context)); if (object_type.IsMessage() && object_type.GetName() == "google.protobuf.ListValue") { return PyObjectToCelValue(py_object, object_type, context, env, arena, /*bypass_type_check=*/true); } } return InvalidTypeError(py_object, context, expected_type, arena); } case cel::Kind::kMap: { if (PyDict_Check(py_object)) { const PyCelType& key_type = expected_type.GetParam(0); const PyCelType& value_type = expected_type.GetParam(1); PyObject *key, *value; Py_ssize_t pos = 0; auto builder = cel::NewMapValueBuilder(arena); while (PyDict_Next(py_object, &pos, &key, &value)) { // Note: PyDict_Next returns borrowed references, so we shouldn't // DECREF them. CEL_PYTHON_ASSIGN_OR_RETURN( cel::Value converted_key, PyObjectToCelValue( key, key_type, [context, key]() { return absl::StrFormat( "%s[%s]", context(), PyUnicode_AsUTF8(PyObject_Repr(key))); }, env, arena)); CEL_PYTHON_ASSIGN_OR_RETURN( cel::Value converted_value, PyObjectToCelValue( value, value_type, [context, key, value]() { return absl::StrFormat( "%s[%s] -> %s", context(), PyUnicode_AsUTF8(PyObject_Repr(key)), PyUnicode_AsUTF8(PyObject_Repr(value))); }, env, arena)); CEL_PYTHON_RETURN_IF_ERROR( builder->Put(converted_key, converted_value)); } return std::move(*builder).Build(); } else { CEL_PYTHON_ASSIGN_OR_RETURN(const PyCelType& object_type, PyCelType::ForPyObject(py_object, context)); if (object_type.IsMessage() && object_type.GetName() == "google.protobuf.Struct") { return PyObjectToCelValue(py_object, object_type, context, env, arena, /*bypass_type_check=*/true); } } return InvalidTypeError(py_object, context, expected_type, arena); } default: { return absl::UnimplementedError( absl::StrFormat("Unimplemented type: %d", expected_type.GetKind())); } } } } // namespace cel_python |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |