Repository navigation
Expand file tree
/
Copy pathpy_cel_function.cc
More file actions
162 lines (145 loc) · 5.38 KB
/
Copy pathpy_cel_function.cc
File metadata and controls
162 lines (145 loc) · 5.38 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
// 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_function.h"
#include <Python.h>
#include <cstddef>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/log/absl_check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_format.h"
#include "absl/types/span.h"
#include "common/value.h"
#include "runtime/embedder_context.h"
#include "runtime/function.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.h"
#include "cel_expr_python/py_error_status.h"
#include "cel_expr_python/status_macros.h"
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace cel_python {
namespace py = ::pybind11;
namespace {
static std::shared_ptr<PyCelEnvInternal> GetEnvFromContext(
const cel::Function::InvokeContext& context) {
ABSL_CHECK(context.embedder_context()); // Crash OK: all call sites are local
// to the library.
return *context.embedder_context()->Get<std::shared_ptr<PyCelEnvInternal>*>();
}
} // namespace
void PyCelFunction::DefinePythonBindings(pybind11::module& m) {
py::class_<PyCelFunction, std::shared_ptr<PyCelFunction>>(m, "Function")
.def(py::init<std::string, std::vector<PyCelType>, bool, py::object,
PyCelType>(),
py::arg("function_name"), py::arg("parameters"),
py::arg("is_member"), py::arg("impl"),
py::arg("return_type") = PyCelType::Dyn());
}
PyCelFunction::PyCelFunction(std::string function_name,
std::vector<PyCelType> parameters, bool is_member,
py::object impl, PyCelType return_type)
: function_name_(std::move(function_name)),
return_type_(std::move(return_type)),
parameters_(std::move(parameters)),
is_member_(is_member),
impl_(std::move(impl)) {
ABSL_CHECK(PyGILState_Check());
}
PyCelFunctionAdapter::PyCelFunctionAdapter(std::string function_name,
PyCelType return_type,
const py::object& py_function)
: function_name_(std::move(function_name)),
return_type_(std::move(return_type)),
py_function_(py_function.ptr()) {
if (!PyGILState_Check()) {
py::gil_scoped_acquire acquire;
Py_XINCREF(py_function_);
} else {
Py_XINCREF(py_function_);
}
}
PyCelFunctionAdapter::~PyCelFunctionAdapter() {
if (py_function_ != nullptr) {
if (!PyGILState_Check()) {
py::gil_scoped_acquire acquire;
Py_XDECREF(py_function_);
} else {
Py_XDECREF(py_function_);
}
}
}
absl::StatusOr<cel::Value> PyCelFunctionAdapter::Invoke(
absl::Span<const cel::Value> args,
const cel::Function::InvokeContext& context) const {
py::gil_scoped_acquire acquire;
std::shared_ptr<PyCelEnvInternal> env = GetEnvFromContext(context);
CEL_PYTHON_ASSIGN_OR_RETURN(auto py_arena,
PyCelArena::FromProtoArena(context.arena()));
PyObject* py_args = PyTuple_New(args.size());
if (py_args == nullptr) {
absl::Status status = PyErr_toStatus();
if (status.ok()) {
status = absl::ResourceExhaustedError("Failed to allocate args tuple");
}
return cel::ErrorValue::From(status, context.arena());
}
for (size_t i = 0; i < args.size(); ++i) {
PyObject* py_arg = CelValueToPyObject(args[i], env, py_arena,
/*plain_value=*/true);
if (py_arg == nullptr) {
absl::Status status = PyErr_toStatus();
Py_DECREF(py_args);
if (status.ok()) {
status = absl::InternalError(
"Failed to convert CEL argument to Python object");
}
return cel::ErrorValue::From(status, context.arena());
}
PyTuple_SetItem(py_args, i, py_arg);
}
PyObject* result = PyObject_CallObject(py_function_, py_args);
absl::Status status = PyErr_toStatus();
Py_DECREF(py_args);
if (status.ok() && result == nullptr) {
status = absl::InternalError(
"Python function returned null without setting an error");
}
if (!status.ok()) {
Py_XDECREF(result);
return cel::ErrorValue::From(status, context.arena());
}
absl::StatusOr<cel::Value> cel_result = PyObjectToCelValue(
result, return_type_,
[this]() {
PyObject* repr = PyObject_Repr(py_function_);
const char* repr_cstr =
repr != nullptr ? PyUnicode_AsUTF8(repr) : nullptr;
if (repr_cstr == nullptr) {
PyErr_Clear();
}
std::string repr_str = repr_cstr != nullptr ? repr_cstr : "<unknown>";
Py_XDECREF(repr);
return absl::StrFormat("Python function '%s'", repr_str);
},
env, context.arena());
Py_XDECREF(result);
return cel_result;
}
} // namespace cel_python