-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpy_cel_env_internal.cc
More file actions
402 lines (363 loc) · 14.7 KB
/
Copy pathpy_cel_env_internal.cc
File metadata and controls
402 lines (363 loc) · 14.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
// 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_env_internal.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/log/absl_check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "checker/type_checker_builder.h"
#include "common/container.h"
#include "common/function_descriptor.h"
#include "common/kind.h"
#include "common/type.h"
#include "compiler/compiler.h"
#include "env/config.h"
#include "env/env.h"
#include "env/env_std_extensions.h"
#include "env/runtime_std_extensions.h"
#include "env/type_info.h"
#include "runtime/reference_resolver.h"
#include "runtime/runtime.h"
#include "runtime/runtime_builder.h"
#include "runtime/runtime_options.h"
#include "validator/validator.h"
#include "cel_expr_python/cel_extension.h"
#include "cel_expr_python/py_cel_env_config.h"
#include "cel_expr_python/py_cel_function.h"
#include "cel_expr_python/py_cel_function_decl.h"
#include "cel_expr_python/py_cel_overload.h"
#include "cel_expr_python/py_cel_python_extension.h"
#include "cel_expr_python/py_cel_type.h"
#include "cel_expr_python/py_descriptor_database.h"
#include "cel_expr_python/py_error_status.h"
#include "cel_expr_python/py_message_factory.h"
#include "cel_expr_python/status_macros.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/descriptor.h"
#include <pybind11/pybind11.h>
namespace cel_python {
namespace {
static const cel::FunctionDescriptorOptions kFunctionDescriptorOptions = {
.is_strict = true, .is_contextual = true};
} // namespace
PyCelEnvInternal::PyCelEnvInternal(
const PyCelEnvConfig& env_config, PyObject* py_descriptor_pool,
std::vector<CelExtensionHandle> extension_handles,
absl::flat_hash_map<std::string, py::object>& function_impls)
: env_config_(env_config),
py_descriptor_database_(py_descriptor_pool),
descriptor_pool_(
std::make_shared<google::protobuf::DescriptorPool>(&py_descriptor_database_)),
message_factory_(descriptor_pool_.get()),
py_message_factory_(
std::make_shared<PyMessageFactory>(py_descriptor_pool)),
extensions_(std::move(extension_handles)),
function_impls_(std::move(function_impls)) {
cel_env_.SetDescriptorPool(descriptor_pool_);
cel_env_.SetConfig(env_config_.GetConfig());
cel::RegisterStandardExtensions(cel_env_);
cel_env_runtime_.SetDescriptorPool(descriptor_pool_);
cel_env_runtime_.SetConfig(env_config_.GetConfig());
cel::RegisterStandardExtensions(cel_env_runtime_);
for (CelExtensionHandle& extension_handle : extensions_) {
// This should never fail because we have already called GetExtension() once
// before calling this constructor.
CelExtension* extension = ThrowIfError(extension_handle.GetExtension());
cel_env_.RegisterCompilerLibrary(
extension->name(), extension->name(), 0,
[extension]() { return extension->GetCompilerLibrary(); });
cel_env_runtime_.RegisterExtensionFunctions(
extension->name(), extension->name(), 0,
[extension](
cel::RuntimeBuilder& runtime_builder,
const cel::RuntimeOptions& runtime_options) -> absl::Status {
return extension->ConfigureRuntime(runtime_builder, runtime_options);
});
}
}
absl::StatusOr<std::shared_ptr<PyCelEnvInternal>>
PyCelEnvInternal::NewCelEnvInternal(
const PyCelEnvConfig& env_config, PyObject* py_descriptor_pool,
const std::unordered_map<std::string, PyCelType>& variable_types,
const std::vector<PyObject*>& extensions,
cel::ExpressionContainer container,
const std::vector<std::shared_ptr<PyCelFunctionDecl>>& functions,
const std::unordered_map<std::string, py::object>& function_impls) {
cel::Config config = env_config.GetConfig();
for (const auto& [name, type] : variable_types) {
CEL_PYTHON_RETURN_IF_ERROR(
config.AddVariableConfig(cel::Config::VariableConfig{
.name = name,
.type_info = PyCelType::ToTypeInfo(type),
}));
}
std::vector<CelExtensionHandle> extension_handles;
extension_handles.reserve(extensions.size());
for (PyObject* ext : extensions) {
CelExtensionHandle handle(ext);
CEL_PYTHON_ASSIGN_OR_RETURN(CelExtension * extension,
handle.GetExtension());
std::string name;
if (!extension->alias().empty() &&
extension->alias() != extension->name()) {
// If the configuration lists the extension by name, use the name;
// otherwise, use the alias. This allows us to detect conflicting
// extension registrations, whether they are included by the extension
// name or alias.
name = extension->alias();
for (const cel::Config::ExtensionConfig& extension_config :
config.GetExtensionConfigs()) {
if (extension_config.name == extension->name()) {
name = extension_config.name;
break;
}
}
} else {
name = extension->name();
}
CEL_PYTHON_RETURN_IF_ERROR(config.AddExtensionConfig(
name, extension->version() >= 0
? extension->version()
: cel::Config::ExtensionConfig::kLatest));
extension_handles.push_back(std::move(handle));
}
cel::Config::ContainerConfig container_config = config.GetContainerConfig();
if (!container.container().empty()) {
container_config.name = std::string(container.container());
}
for (const auto& abbr : container.ListAbbreviations()) {
bool found = false;
for (const auto& existing : container_config.abbreviations) {
if (existing == abbr) {
found = true;
break;
}
}
if (!found) {
container_config.abbreviations.push_back(abbr);
}
}
for (const auto& alias_listing : container.ListAliases()) {
if (alias_listing.IsAbbreviation()) {
continue;
}
bool found = false;
for (const auto& existing : container_config.aliases) {
if (existing.alias == alias_listing.alias) {
if (existing.qualified_name != alias_listing.name) {
return absl::InvalidArgumentError(absl::StrCat(
"Alias '", alias_listing.alias,
"' is already defined with a different qualified name: ",
existing.qualified_name));
}
found = true;
break;
}
}
if (!found) {
container_config.aliases.push_back(
{.alias = alias_listing.alias, .qualified_name = alias_listing.name});
}
}
config.SetContainerConfig(container_config);
absl::flat_hash_map<std::string, py::object> impls;
for (const std::shared_ptr<PyCelFunctionDecl>& function : functions) {
CEL_PYTHON_RETURN_IF_ERROR(
config.AddFunctionConfig(function->ToFunctionConfig()));
for (const PyCelOverload& overload : function->overloads()) {
if (overload.py_function().is_none()) {
continue;
}
if (!impls.insert({overload.overload_id(), overload.py_function()})
.second) {
return absl::AlreadyExistsError(
absl::StrCat("An implementation for function overload id '",
overload.overload_id(), "' already exists."));
}
}
}
for (const auto& [overload_id, py_function] : function_impls) {
if (!impls.insert({overload_id, py_function}).second) {
return absl::AlreadyExistsError(
absl::StrCat("An implementation for function overload id '",
overload_id, "' already exists."));
}
}
return std::shared_ptr<PyCelEnvInternal>(
new PyCelEnvInternal(PyCelEnvConfig(config), py_descriptor_pool,
std::move(extension_handles), impls));
}
absl::StatusOr<const cel::Compiler*> PyCelEnvInternal::GetCompiler(
const std::shared_ptr<PyCelEnvInternal>& env) {
ABSL_CHECK(PyGILState_Check());
if (env->compiler_) {
return env->compiler_.get();
}
const cel::Config& config = env->env_config_.GetConfig();
CEL_PYTHON_ASSIGN_OR_RETURN(
std::unique_ptr<cel::CompilerBuilder> compiler_builder,
env->cel_env_.NewCompilerBuilder());
cel::TypeCheckerBuilder& checker_builder =
compiler_builder->GetCheckerBuilder();
cel::ExpressionContainer container;
const auto& container_config = config.GetContainerConfig();
if (!container_config.IsEmpty()) {
CEL_PYTHON_RETURN_IF_ERROR(container.SetContainer(container_config.name));
for (const auto& abbr : container_config.abbreviations) {
CEL_PYTHON_RETURN_IF_ERROR(container.AddAbbreviation(abbr));
}
for (const auto& alias : container_config.aliases) {
CEL_PYTHON_RETURN_IF_ERROR(
container.AddAlias(alias.alias, alias.qualified_name));
}
}
checker_builder.SetExpressionContainer(std::move(container));
// Convert variable types from cel::TypeInfo to PyCelType.
google::protobuf::Arena* arena = checker_builder.arena();
for (const cel::Config::VariableConfig& variable_config :
config.GetVariableConfigs()) {
CEL_PYTHON_ASSIGN_OR_RETURN(
cel::Type cel_type,
cel::TypeInfoToType(variable_config.type_info,
env->descriptor_pool_.get(), arena));
PyCelType py_cel_type = PyCelType::FromCelType(cel_type);
env->variable_types_[variable_config.name] = py_cel_type;
}
CEL_PYTHON_ASSIGN_OR_RETURN(env->compiler_, compiler_builder->Build());
return env->compiler_.get();
}
absl::StatusOr<const cel::Runtime*> PyCelEnvInternal::GetRuntime(
const std::shared_ptr<PyCelEnvInternal>& env, RuntimeMode runtime_mode) {
if (auto it = env->runtimes_.find(runtime_mode); it != env->runtimes_.end()) {
return it->second.get();
}
cel::RuntimeOptions& opts = env->cel_env_runtime_.mutable_runtime_options();
opts.container = env->GetEnvConfig().GetConfig().GetContainerConfig().name;
opts.enable_empty_wrapper_null_unboxing = true;
opts.enable_qualified_type_identifiers = true;
opts.enable_timestamp_duration_overflow_errors = true;
switch (runtime_mode) {
case kStandard:
break;
case kStandardIgnoreWarnings:
opts.fail_on_warnings = false;
break;
}
CEL_PYTHON_ASSIGN_OR_RETURN(cel::RuntimeBuilder builder,
env->cel_env_runtime_.CreateRuntimeBuilder());
CEL_PYTHON_RETURN_IF_ERROR(cel::EnableReferenceResolver(
builder, cel::ReferenceResolverEnabled::kAlways));
for (const cel::Config::FunctionConfig& function_config :
env->GetEnvConfig().GetConfig().GetFunctionConfigs()) {
for (const cel::Config::FunctionOverloadConfig& overload_config :
function_config.overload_configs) {
auto it = env->function_impls_.find(overload_config.overload_id);
if (it == env->function_impls_.end()) {
continue;
}
py::object py_function = it->second;
std::vector<cel::Kind> param_kinds;
param_kinds.reserve(overload_config.parameters.size());
for (const cel::Config::TypeInfo& parameter :
overload_config.parameters) {
CEL_PYTHON_ASSIGN_OR_RETURN(
cel::Type type,
cel::TypeInfoToType(parameter, env->descriptor_pool_.get(),
&env->arena_));
param_kinds.push_back(static_cast<cel::Kind>(type.kind()));
}
cel::FunctionDescriptor descriptor(
function_config.name, overload_config.is_member_function, param_kinds,
kFunctionDescriptorOptions);
CEL_PYTHON_ASSIGN_OR_RETURN(
cel::Type return_type,
cel::TypeInfoToType(overload_config.return_type,
env->descriptor_pool_.get(), &env->arena_));
CEL_PYTHON_RETURN_IF_ERROR(builder.function_registry().Register(
descriptor, std::make_unique<PyCelFunctionAdapter>(
function_config.name,
PyCelType::FromCelType(return_type), py_function)));
}
}
CEL_PYTHON_ASSIGN_OR_RETURN(std::unique_ptr<cel::Runtime> runtime,
std::move(builder).Build());
const cel::Runtime* runtime_ptr = runtime.get();
env->runtimes_[runtime_mode] = std::move(runtime);
return runtime_ptr;
}
const PyCelType& PyCelEnvInternal::GetVariableType(
const std::string& name) const {
ABSL_CHECK(PyGILState_Check());
auto it = variable_types_.find(name);
if (it != variable_types_.end()) {
return it->second;
}
return PyCelType::Dyn();
}
CelExtensionHandle::CelExtensionHandle(PyObject* extension)
: py_extension_(extension), cel_extension_(nullptr) {
ABSL_CHECK(PyGILState_Check());
Py_INCREF(py_extension_);
}
CelExtensionHandle::CelExtensionHandle(CelExtensionHandle&& other)
: py_extension_(other.py_extension_), cel_extension_(other.cel_extension_) {
other.py_extension_ = nullptr;
other.cel_extension_ = nullptr;
}
CelExtensionHandle::~CelExtensionHandle() {
if (py_extension_ != nullptr) {
auto gil_state = PyGILState_Ensure();
Py_DECREF(py_extension_);
PyGILState_Release(gil_state);
}
}
absl::StatusOr<CelExtension*> CelExtensionHandle::GetExtension() {
if (cel_extension_) {
return cel_extension_;
}
if (Py_IsNone(py_extension_)) {
return absl::InvalidArgumentError("Provided extension is None");
}
// First, check if the object is a CelExtension (extension implemented in
// Python)
absl::Status status_py_cel_extension;
try {
pybind11::handle handle = pybind11::handle(py_extension_);
return handle.cast<PyCelPythonExtension*>();
} catch (const pybind11::cast_error& e) {
status_py_cel_extension = absl::InvalidArgumentError(e.what());
}
// If that fails, check if the object is a pybind11 wrapper for
// CelExtension.
absl::Status status_cc_cel_extension;
try {
pybind11::handle handle = pybind11::handle(py_extension_);
return handle.cast<CelExtension*>();
} catch (const pybind11::cast_error& e) {
status_cc_cel_extension = absl::InvalidArgumentError(e.what());
}
PyTypeObject* py_type = Py_TYPE(py_extension_);
return absl::InternalError(absl::StrCat(
"Failed to cast ", py_type ? py_type->tp_name : "unknown",
" either as a Python CelExtension instance (",
status_py_cel_extension.ToString(), ") or as a pybind11 wrapper (",
status_cc_cel_extension.ToString(), ")"));
}
} // namespace cel_python