cel-rs-rb 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -2,7 +2,9 @@
2
2
 
3
3
  [![Gem Version](https://img.shields.io/gem/v/cel-rs-rb.svg)](https://rubygems.org/gems/cel-rs-rb)
4
4
 
5
- Ruby bindings for the Rust [`cel`](https://crates.io/crates/cel) 0.15 crate, implemented with [Magnus](https://github.com/matsadler/magnus).
5
+ Ruby bindings for the Rust [`cel`](https://crates.io/crates/cel) 0.16 crate, implemented with [Magnus](https://github.com/matsadler/magnus).
6
+
7
+ See the [changelog](CHANGELOG.md) for breaking changes and upgrade notes.
6
8
 
7
9
  ## Goals
8
10
 
@@ -76,10 +78,11 @@ program.execute(CEL::Context.build(label: "TacoCat", scores: [2, 9, -3]))
76
78
 
77
79
  | Library | Examples |
78
80
  | --- | --- |
79
- | [`strings`](https://docs.rs/cel/0.15.0/cel/extensions/fn.strings.html) | `'TacoCat'.lowerAscii()`, `'a,b'.split(',')` |
80
- | [`lists`](https://docs.rs/cel/0.15.0/cel/extensions/fn.lists.html) | `lists.range(3)`, `[3, 1, 2].sort()`, `items.sortBy(x, x.score)` |
81
- | [`math`](https://docs.rs/cel/0.15.0/cel/extensions/fn.math.html) | `math.greatest(1, 5, 3)`, `math.least([1, 5, 3])` |
82
- | [`encoders`](https://docs.rs/cel/0.15.0/cel/extensions/fn.encoders.html) | `base64.encode(b'hi')`, `base64.decode('aGk=')` |
81
+ | [`strings`](https://docs.rs/cel/0.16.0/cel/extensions/fn.strings.html) | `'TacoCat'.lowerAscii()`, `'a,b'.split(',')` |
82
+ | [`lists`](https://docs.rs/cel/0.16.0/cel/extensions/fn.lists.html) | `lists.range(3)`, `[3, 1, 2].sort()`, `items.sortBy(x, x.score)` |
83
+ | [`math`](https://docs.rs/cel/0.16.0/cel/extensions/fn.math.html) | `math.greatest(1, 5, 3)`, `math.least([1, 5, 3])` |
84
+ | [`encoders`](https://docs.rs/cel/0.16.0/cel/extensions/fn.encoders.html) | `base64.encode(b'hi')`, `base64.decode('aGk=')` |
85
+ | [`sets`](https://docs.rs/cel/0.16.0/cel/extensions/fn.sets.html) | `sets.contains([1, 2], [2])`, `sets.equivalent([1, 1], [1])`, `sets.intersects([1], [2])` |
83
86
 
84
87
  `CEL::Program.compile` accepts the same `extensions:` option. Names can be
85
88
  symbols or strings; unknown or repeated names raise `ArgumentError`.
@@ -91,16 +94,51 @@ or add functions to explicitly empty contexts. Ruby callbacks that conflict
91
94
  with enabled extension functions raise `CEL::ExecutionError` during execution,
92
95
  just like conflicts with standard CEL builtins.
93
96
 
97
+ ### Evaluation limits and cancellation
98
+
99
+ Set a comprehension-iteration budget when compiling, and a timeout in seconds
100
+ or cancellation token for each execution:
101
+
102
+ ```ruby
103
+ program = CEL.compile("items.map(x, x * 2)", max_iterations: 1_000)
104
+ context = CEL::Context.build(items: [2, 5, 9])
105
+ program.execute(context, timeout: 0.05) # => [4, 10, 18]
106
+
107
+ token = CEL::CancellationToken.new
108
+ token.cancel! # Another Ruby thread can call this while evaluation runs.
109
+ program.execute(context, interrupt: token)
110
+ # raises CEL::ExecutionError: operation interrupted
111
+ ```
112
+
113
+ `max_iterations` is an unsigned 64-bit integer; `0` (the default) means unlimited.
114
+ It counts total iterations across nested and sibling comprehensions, with a fresh
115
+ budget per execution, including concurrent executions and explicitly empty contexts.
116
+
117
+ `timeout: nil` and `interrupt: nil` disable interruption. Timeouts must be finite,
118
+ non-negative seconds within Rust's duration range. Each call gets a fresh deadline,
119
+ starting before the execution snapshot is built. Tokens are one-way: `cancelled?`
120
+ stays true after `cancel!`, and every execution sharing a token sees cancellation.
121
+ Use a new token for an independent run. When both options are supplied, either can
122
+ interrupt execution. `call` and `execute_with_context` accept the same options.
123
+
124
+ Checks are **cooperative**, performed on comprehension iterations (`all`, `exists`,
125
+ `map`, `filter`, etc.). They are not hard wall-clock timeouts or general cost limits.
126
+ Straight-line expressions, extension work outside comprehensions, and Ruby callbacks
127
+ are not preempted. Once observed, interruption or budget exhaustion fails the whole
128
+ evaluation with `CEL::ExecutionError`, even inside `||`, `&&`, or optional accessors.
129
+
94
130
  ### API mapping
95
131
 
96
- - `CEL.compile(source, extensions: [])` -> `CEL::Program`
97
- - `CEL::Program.compile(source, extensions: [])` -> `CEL::Program`
98
- - `CEL::Program#execute(context = nil)` -> Ruby value
132
+ - `CEL.compile(source, extensions: [], max_iterations: 0)` -> `CEL::Program`
133
+ - `CEL::Program.compile(source, extensions: [], max_iterations: 0)` -> `CEL::Program`
134
+ - `CEL::Program#execute(context = nil, timeout: nil, interrupt: nil)` -> Ruby value
99
135
  - `CEL::Program#references` -> `{ "variables" => [...], "functions" => [...] }`
136
+ - `CEL::CancellationToken.new`, `#cancel!`, `#cancelled?` -> cooperative cancellation
100
137
  - `CEL::Context.new(empty = false)` -> context with builtins (`false`) or empty (`true`)
101
138
  - `CEL::Context#add_variable(name, value)`
102
139
  - `CEL::Context#define_function(name) { |*args| ... }`
103
140
  - `CEL::Duration.new(seconds)` -> duration value for context variables and duration results
141
+ - `CEL::Duration::MIN_NANOSECONDS`, `MAX_NANOSECONDS` -> exact inclusive duration bounds as Ruby Integers
104
142
 
105
143
  ## Type support
106
144
 
@@ -127,6 +165,10 @@ just like conflicts with standard CEL builtins.
127
165
  - `list` -> `Array`
128
166
  - `map` -> `Hash`
129
167
 
168
+ Ruby's `CEL::Duration.new`, `total_seconds` / `to_f`, and display methods use
169
+ floating-point seconds, so they cannot represent every nanosecond at large magnitudes. Keep exact
170
+ duration arithmetic and `string(duration)` formatting inside CEL when precision matters.
171
+
130
172
  ## Error classes
131
173
 
132
174
  - `CEL::Error`
@@ -145,6 +187,11 @@ just like conflicts with standard CEL builtins.
145
187
  - Ruby callbacks from CEL functions temporarily re-acquire the GVL before
146
188
  invoking Ruby code.
147
189
 
190
+ Registering a function name again with `define_function` or `add_function`
191
+ replaces its callback for future executions. In-flight executions keep using
192
+ their original snapshot. Callbacks are kept alive and pinned against Ruby GC
193
+ compaction while registered or used by an in-flight execution.
194
+
148
195
  ## Development
149
196
 
150
197
  ### Tooling
@@ -208,15 +255,3 @@ change alongside `lib/cel/version.rb`.
208
255
  The `release:verify-tag` step fails the build if the tag and
209
256
  `CEL::VERSION` disagree, so the tag (`v0.2.0`) must match `version.rb`
210
257
  (`0.2.0`).
211
-
212
- ## Compatibility notes
213
-
214
- - Compilation uses the standard CEL environment, including optional access syntax (`user.?name`) and the `optMap` / `optFlatMap` macros.
215
- - The upstream strings, lists, math, and encoders extension libraries are opt-in through the `extensions:` compile option.
216
- - cel 0.15 no longer includes `max` and `min` by default, so default contexts register them for compatibility with cel 0.13. See [`max` and `min`](#max-and-min).
217
- - When upgrading from cel 0.13, replace list/map `.contains(value)` expressions with `value in collection`; `.contains()` now only accepts strings. Map literals with duplicate keys raise `CEL::ExecutionError`, and string `size()` counts Unicode code points rather than bytes. See the [cel 0.15 release notes](https://github.com/cel-rust/cel-rust/releases/tag/v0.15.0) for further CEL semantic changes.
218
- - `string(bytes)` now rejects invalid UTF-8. Numeric conversions reject out-of-range results, and parsed timestamps and durations must fit CEL's allowed ranges.
219
- - `all()` and `exists()` can now absorb an earlier evaluation error when a later element determines the result. For example, `[2, 1].exists(e, 6 / (2 - e) == 6)` returns `true` despite the first element's division by zero.
220
- - Ruby callbacks cannot shadow standard CEL builtins (such as `size`) in a default context; the compatibility functions `max` and `min` are exceptions. Conflicts raise `CEL::ExecutionError` when `Program#execute(context)` builds the execution snapshot, even if the expression does not call the conflicting function. Use `CEL::Context.new(true)` or `CEL::Context.build(empty: true)` to define functions without builtins. Registering the same custom callback name again replaces the previous callback.
221
- - Some CEL value variants (e.g. opaque custom Rust types) cannot be fully marshaled to Ruby and raise `CEL::TypeError`.
222
- - This project targets broad CEL compatibility, but parity for every Rust-only extension point is still evolving.
data/ext/cel/Cargo.toml CHANGED
@@ -10,5 +10,5 @@ crate-type = ["cdylib"]
10
10
  [dependencies]
11
11
  magnus = { version = "0.8.2", features = ["chrono", "rb-sys"] }
12
12
  rb-sys = { version = "0.9.128", features = ["stable-api-compiled-fallback"] }
13
- cel = { version = "0.15.0", features = ["chrono", "regex", "json"] }
13
+ cel = { version = "0.16.0", features = ["chrono", "regex", "json"] }
14
14
  chrono = "0.4.45"
data/ext/cel/src/lib.rs CHANGED
@@ -4,71 +4,55 @@ use cel::{
4
4
  };
5
5
  use magnus::block::Proc;
6
6
  use magnus::prelude::*;
7
+ use magnus::rb_sys::AsRawValue;
7
8
  use magnus::typed_data::Obj;
9
+ use magnus::value::BoxValue;
8
10
  use magnus::{function, method, Error, IntoValue, RHash, RString, Ruby, TryConvert, Value};
9
11
  use rb_sys::{rb_thread_call_with_gvl, rb_thread_call_without_gvl};
10
12
  use std::collections::HashMap;
11
13
  use std::ffi::c_void;
12
14
  use std::panic::{self, AssertUnwindSafe};
15
+ use std::sync::atomic::{AtomicBool, Ordering};
13
16
  use std::sync::{Arc, Mutex};
17
+ use std::time::Duration;
14
18
 
15
19
  mod errors {
16
20
  use magnus::prelude::*;
17
21
  use magnus::{Error, ExceptionClass, RModule, Ruby};
18
- use std::cell::RefCell;
19
-
20
- thread_local! {
21
- static PARSE: RefCell<Option<ExceptionClass>> = const { RefCell::new(None) };
22
- static EXECUTION: RefCell<Option<ExceptionClass>> = const { RefCell::new(None) };
23
- static TYPE: RefCell<Option<ExceptionClass>> = const { RefCell::new(None) };
24
- }
25
22
 
26
23
  pub fn define(ruby: &Ruby, module: &RModule) -> Result<(), Error> {
27
24
  let standard = ruby.exception_standard_error();
28
25
  let base = module.define_error("Error", standard)?;
29
- let parse = module.define_error("ParseError", base)?;
30
- let execution = module.define_error("ExecutionError", base)?;
31
- let ty = module.define_error("TypeError", base)?;
32
- PARSE.with(|slot| *slot.borrow_mut() = Some(parse));
33
- EXECUTION.with(|slot| *slot.borrow_mut() = Some(execution));
34
- TYPE.with(|slot| *slot.borrow_mut() = Some(ty));
26
+ module.define_error("ParseError", base)?;
27
+ module.define_error("ExecutionError", base)?;
28
+ module.define_error("TypeError", base)?;
35
29
  Ok(())
36
30
  }
37
31
 
38
- fn fallback(msg: String) -> Error {
32
+ fn error(class: &str, msg: impl Into<String>) -> Error {
39
33
  let ruby = Ruby::get().expect("ruby runtime");
40
- Error::new(ruby.exception_runtime_error(), msg)
34
+ let class = ruby
35
+ .class_object()
36
+ .const_get::<_, RModule>("CEL")
37
+ .and_then(|module| module.const_get::<_, ExceptionClass>(class))
38
+ .unwrap_or_else(|_| ruby.exception_runtime_error());
39
+ Error::new(class, msg.into())
41
40
  }
42
41
 
43
42
  pub fn parse(msg: impl Into<String>) -> Error {
44
- let msg = msg.into();
45
- PARSE.with(|slot| {
46
- slot.borrow()
47
- .map(|exc| Error::new(exc, msg.clone()))
48
- .unwrap_or_else(|| fallback(msg))
49
- })
43
+ error("ParseError", msg)
50
44
  }
51
45
 
52
46
  pub fn execution(msg: impl Into<String>) -> Error {
53
- let msg = msg.into();
54
- EXECUTION.with(|slot| {
55
- slot.borrow()
56
- .map(|exc| Error::new(exc, msg.clone()))
57
- .unwrap_or_else(|| fallback(msg))
58
- })
47
+ error("ExecutionError", msg)
59
48
  }
60
49
 
61
50
  pub fn ty(msg: impl Into<String>) -> Error {
62
- let msg = msg.into();
63
- TYPE.with(|slot| {
64
- slot.borrow()
65
- .map(|exc| Error::new(exc, msg.clone()))
66
- .unwrap_or_else(|| fallback(msg))
67
- })
51
+ error("TypeError", msg)
68
52
  }
69
53
  }
70
54
 
71
- fn without_gvl<F, T>(f: F) -> T
55
+ fn without_gvl<F, T>(f: F) -> Result<T, Error>
72
56
  where
73
57
  F: FnOnce() -> T,
74
58
  T: Send,
@@ -98,16 +82,19 @@ where
98
82
  result: None,
99
83
  };
100
84
 
101
- unsafe {
85
+ // Ruby can raise an interrupt while reacquiring the GVL. Catch its longjmp
86
+ // here so the caller's Rust-owned execution context and GC roots are dropped.
87
+ magnus::rb_sys::protect(|| unsafe {
102
88
  rb_thread_call_without_gvl(
103
89
  Some(call::<F, T>),
104
90
  &mut state as *mut _ as *mut c_void,
105
91
  None,
106
92
  std::ptr::null_mut(),
107
93
  );
108
- }
94
+ Ruby::get().expect("ruby runtime").qnil().as_raw()
95
+ })?;
109
96
 
110
- state.result.expect("result missing")
97
+ Ok(state.result.expect("result missing"))
111
98
  }
112
99
 
113
100
  fn with_gvl<F, T>(f: F) -> T
@@ -149,25 +136,19 @@ struct CallbackFunction {
149
136
  unsafe impl Send for CallbackFunction {}
150
137
  unsafe impl Sync for CallbackFunction {}
151
138
 
152
- #[derive(Clone)]
153
- struct FunctionRegistration {
154
- name: String,
155
- callback: Arc<CallbackFunction>,
156
- }
157
-
158
139
  #[derive(Default, magnus::TypedData)]
159
140
  #[magnus(class = "CEL::Context", free_immediately, size, mark)]
160
141
  struct ContextWrap {
161
142
  use_empty: bool,
162
143
  variables: Mutex<HashMap<String, CelValue>>,
163
- functions: Mutex<Vec<FunctionRegistration>>,
144
+ functions: Mutex<HashMap<String, Arc<CallbackFunction>>>,
164
145
  }
165
146
 
166
147
  impl magnus::DataTypeFunctions for ContextWrap {
167
148
  fn mark(&self, marker: &magnus::gc::Marker) {
168
- for registration in self.functions.lock().unwrap().iter() {
149
+ for callback in self.functions.lock().unwrap().values() {
169
150
  // Non-movable marking also pins the Proc during Ruby compaction.
170
- marker.mark(registration.callback.proc);
151
+ marker.mark(callback.proc);
171
152
  }
172
153
  }
173
154
  }
@@ -178,6 +159,26 @@ struct ProgramWrap {
178
159
  env: Arc<cel::Env>,
179
160
  }
180
161
 
162
+ #[derive(Default)]
163
+ #[magnus::wrap(class = "CEL::CancellationToken", free_immediately, size)]
164
+ struct CancellationTokenWrap {
165
+ cancelled: AtomicBool,
166
+ }
167
+
168
+ impl CancellationTokenWrap {
169
+ fn new() -> Self {
170
+ Self::default()
171
+ }
172
+
173
+ fn cancel(&self) {
174
+ self.cancelled.store(true, Ordering::Relaxed);
175
+ }
176
+
177
+ fn is_cancelled(&self) -> bool {
178
+ self.cancelled.load(Ordering::Relaxed)
179
+ }
180
+ }
181
+
181
182
  #[derive(Clone)]
182
183
  #[magnus::wrap(class = "CEL::Duration", free_immediately, size)]
183
184
  struct DurationWrap {
@@ -301,31 +302,36 @@ fn cel_to_ruby(ruby: &Ruby, value: &CelValue) -> Result<Value, Error> {
301
302
  }
302
303
 
303
304
  impl DurationWrap {
305
+ const NANOS_PER_SECOND: i128 = 1_000_000_000;
306
+
307
+ // https://github.com/cel-rust/cel-rust/blob/v0.16.0/src/common/types/duration.rs
308
+ const MAX_NANOSECONDS: i128 = 315_576_000_000_999_999_999;
309
+ const MIN_NANOSECONDS: i128 = -Self::MAX_NANOSECONDS;
310
+
311
+ // CEL's exact maximum rounds up to this first invalid whole second in f64.
312
+ const MAX_ABS_SECONDS_EXCLUSIVE: f64 =
313
+ (Self::MAX_NANOSECONDS / Self::NANOS_PER_SECOND + 1) as f64;
314
+
304
315
  fn new(seconds: f64) -> Result<Self, Error> {
305
316
  if !seconds.is_finite() {
306
317
  return Err(errors::ty("Duration seconds must be finite"));
307
318
  }
308
319
 
309
- let nanos = (seconds * 1_000_000_000.0).round();
310
- if nanos < i64::MIN as f64 || nanos > i64::MAX as f64 {
320
+ if seconds.abs() >= Self::MAX_ABS_SECONDS_EXCLUSIVE {
311
321
  return Err(errors::ty("Duration is out of range"));
312
322
  }
313
323
 
314
324
  Ok(Self {
315
- inner: chrono::Duration::nanoseconds(nanos as i64),
325
+ inner: chrono::Duration::seconds(seconds.trunc() as i64)
326
+ + chrono::Duration::nanoseconds(
327
+ (seconds.fract() * Self::NANOS_PER_SECOND as f64).round() as i64,
328
+ ),
316
329
  })
317
330
  }
318
331
 
319
332
  fn total_seconds(&self) -> f64 {
320
- let nanos = self.inner.num_nanoseconds().unwrap_or_else(|| {
321
- if self.inner < chrono::Duration::zero() {
322
- i64::MIN
323
- } else {
324
- i64::MAX
325
- }
326
- });
327
-
328
- nanos as f64 / 1_000_000_000.0
333
+ self.inner.num_seconds() as f64
334
+ + self.inner.subsec_nanos() as f64 / Self::NANOS_PER_SECOND as f64
329
335
  }
330
336
 
331
337
  fn to_s(&self) -> String {
@@ -346,7 +352,7 @@ impl ContextWrap {
346
352
  Self {
347
353
  use_empty: empty,
348
354
  variables: Mutex::new(HashMap::new()),
349
- functions: Mutex::new(Vec::new()),
355
+ functions: Mutex::new(HashMap::new()),
350
356
  }
351
357
  }
352
358
 
@@ -359,15 +365,17 @@ impl ContextWrap {
359
365
  }
360
366
 
361
367
  fn add_function(&self, name: String, proc: Proc) {
362
- self.functions.lock().unwrap().push(FunctionRegistration {
363
- name,
364
- callback: Arc::new(CallbackFunction { proc }),
365
- });
368
+ self.functions
369
+ .lock()
370
+ .unwrap()
371
+ .insert(name, Arc::new(CallbackFunction { proc }));
366
372
  }
367
373
 
368
- fn build_context(&self, env: Arc<cel::Env>) -> Result<CelContext<'static, 'static>, Error> {
374
+ fn build_context<'v>(&self, env: Arc<cel::Env>) -> Result<CelContext<'v, 'v>, Error> {
369
375
  let mut ctx = if self.use_empty {
370
- CelContext::empty()
376
+ let mut empty_env = cel::Env::default();
377
+ empty_env.set_options(env.options().clone());
378
+ CelContext::with_env(Arc::new(empty_env))
371
379
  } else {
372
380
  let mut ctx = CelContext::with_env(env);
373
381
  ctx.add_function("max", cel::functions::max)
@@ -381,11 +389,10 @@ impl ContextWrap {
381
389
  ctx.add_variable_from_value(name.as_str(), value.clone());
382
390
  }
383
391
 
384
- for registration in self.functions.lock().unwrap().iter() {
385
- let callback = registration.callback.clone();
386
- let function_name = registration.name.clone();
392
+ for (name, callback) in self.functions.lock().unwrap().iter() {
393
+ let callback = callback.clone();
387
394
  ctx.add_function(
388
- &function_name,
395
+ name,
389
396
  move |ftx: &FunctionContext,
390
397
  cel::extractors::Arguments(args): cel::extractors::Arguments|
391
398
  -> ResolveResult {
@@ -434,15 +441,21 @@ impl ContextWrap {
434
441
  }
435
442
 
436
443
  impl ProgramWrap {
437
- fn compile(source: String, extensions: Vec<String>) -> Result<Self, Error> {
444
+ fn compile(
445
+ source: String,
446
+ extensions: Vec<String>,
447
+ max_iterations: u64,
448
+ ) -> Result<Self, Error> {
438
449
  let ruby = Ruby::get().expect("ruby runtime");
439
450
  let mut env = cel::Env::stdlib();
451
+ env.set_options(cel::RuntimeOptions::default().with_max_iterations(max_iterations));
440
452
  for name in extensions {
441
453
  let extension = match name.as_str() {
442
454
  "strings" => cel::extensions::strings,
443
455
  "lists" => cel::extensions::lists,
444
456
  "math" => cel::extensions::math,
445
457
  "encoders" => cel::extensions::encoders,
458
+ "sets" => cel::extensions::sets,
446
459
  _ => {
447
460
  return Err(Error::new(
448
461
  ruby.exception_arg_error(),
@@ -459,20 +472,58 @@ impl ProgramWrap {
459
472
  .map_err(|e: ParseErrors| errors::parse(e.to_string()))
460
473
  }
461
474
 
462
- fn execute(&self) -> Result<Value, Error> {
463
- self.execute_with_context(&ContextWrap::new(false))
475
+ fn execute(
476
+ &self,
477
+ timeout: Option<f64>,
478
+ interrupt: Option<Obj<CancellationTokenWrap>>,
479
+ ) -> Result<Value, Error> {
480
+ self.execute_with_context(&ContextWrap::new(false), timeout, interrupt)
464
481
  }
465
482
 
466
- fn execute_with_context(&self, context: &ContextWrap) -> Result<Value, Error> {
467
- self.execute_with_context_internal(&context.build_context(self.env.clone())?)
468
- }
483
+ fn execute_with_context(
484
+ &self,
485
+ context: &ContextWrap,
486
+ timeout: Option<f64>,
487
+ interrupt: Option<Obj<CancellationTokenWrap>>,
488
+ ) -> Result<Value, Error> {
489
+ let ruby = Ruby::get().expect("ruby runtime");
490
+ let timeout = timeout
491
+ .map(|seconds| {
492
+ Duration::try_from_secs_f64(seconds).map_err(|_| {
493
+ Error::new(
494
+ ruby.exception_arg_error(),
495
+ "timeout must be finite, non-negative seconds within range",
496
+ )
497
+ })
498
+ })
499
+ .transpose()?;
500
+ let deadline = timeout.map(cel::Deadline::after);
501
+ let cancelled = interrupt.as_ref().map(|token| &token.cancelled);
502
+ let signal = || {
503
+ cancelled.is_some_and(|flag| flag.load(Ordering::Relaxed))
504
+ || deadline.is_some_and(|deadline| cel::Interrupt::is_interrupted(&deadline))
505
+ };
506
+ // Root and pin this run's callbacks before releasing the GVL. A registration
507
+ // can be replaced while execution is in flight, including from a callback.
508
+ // These roots are dropped with the GVL held, on both success and error.
509
+ let callbacks: Vec<_> = context
510
+ .functions
511
+ .lock()
512
+ .unwrap()
513
+ .values()
514
+ .map(|callback| callback.proc)
515
+ .collect();
516
+ // Registering a root can trigger GC, whose mark hook locks functions again.
517
+ let _callbacks: Vec<_> = callbacks.into_iter().map(BoxValue::new).collect();
518
+ let mut ctx = context.build_context(self.env.clone())?;
519
+ if timeout.is_some() || cancelled.is_some() {
520
+ ctx.set_interrupt(&signal);
521
+ }
469
522
 
470
- fn execute_with_context_internal(&self, ctx: &CelContext<'_, '_>) -> Result<Value, Error> {
471
- let run = || self.inner.execute(ctx);
523
+ let run = || self.inner.execute(&ctx);
472
524
  let result = panic::catch_unwind(AssertUnwindSafe(|| without_gvl(run)))
473
- .map_err(|_| errors::execution("CEL execution panicked"))?;
525
+ .map_err(|_| errors::execution("CEL execution panicked"))??;
474
526
 
475
- let ruby = Ruby::get().expect("ruby runtime");
476
527
  result
477
528
  .map_err(|e| errors::execution(e.to_string()))
478
529
  .and_then(|value| cel_to_ruby(&ruby, &value))
@@ -508,6 +559,14 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
508
559
  let module = ruby.define_module("CEL")?;
509
560
  errors::define(ruby, &module)?;
510
561
 
562
+ let token_class = module.define_class("CancellationToken", ruby.class_object())?;
563
+ token_class.define_singleton_method("new", function!(CancellationTokenWrap::new, 0))?;
564
+ token_class.define_method("cancel!", method!(CancellationTokenWrap::cancel, 0))?;
565
+ token_class.define_method(
566
+ "cancelled?",
567
+ method!(CancellationTokenWrap::is_cancelled, 0),
568
+ )?;
569
+
511
570
  let context_class = module.define_class("Context", ruby.class_object())?;
512
571
  context_class.define_singleton_method("new", function!(ContextWrap::new, 1))?;
513
572
  context_class.define_method("add_variable", method!(ContextWrap::add_variable, 2))?;
@@ -515,6 +574,8 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
515
574
  context_class.define_method("add_function", method!(ContextWrap::add_function, 2))?;
516
575
 
517
576
  let duration_class = module.define_class("Duration", ruby.class_object())?;
577
+ duration_class.const_set("MAX_NANOSECONDS", DurationWrap::MAX_NANOSECONDS)?;
578
+ duration_class.const_set("MIN_NANOSECONDS", DurationWrap::MIN_NANOSECONDS)?;
518
579
  duration_class.define_singleton_method("new", function!(DurationWrap::new, 1))?;
519
580
  duration_class.define_method("total_seconds", method!(DurationWrap::total_seconds, 0))?;
520
581
  duration_class.define_method("to_f", method!(DurationWrap::total_seconds, 0))?;
@@ -523,11 +584,11 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
523
584
  duration_class.define_method("==", method!(DurationWrap::eq, 1))?;
524
585
 
525
586
  let program_class = module.define_class("Program", ruby.class_object())?;
526
- program_class.define_singleton_method("compile", function!(ProgramWrap::compile, 2))?;
527
- program_class.define_method("execute", method!(ProgramWrap::execute, 0))?;
587
+ program_class.define_singleton_method("compile", function!(ProgramWrap::compile, 3))?;
588
+ program_class.define_method("execute", method!(ProgramWrap::execute, 2))?;
528
589
  program_class.define_method(
529
590
  "execute_with_context",
530
- method!(ProgramWrap::execute_with_context, 1),
591
+ method!(ProgramWrap::execute_with_context, 3),
531
592
  )?;
532
593
  program_class.define_method("references", method!(ProgramWrap::references, 0))?;
533
594
  program_class.define_method("expression", method!(ProgramWrap::expression, 0))?;
data/lib/cel/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module CEL
4
- VERSION = "0.3.1"
4
+ VERSION = "0.4.0"
5
5
  end
data/lib/cel.rb CHANGED
@@ -10,8 +10,8 @@ rescue LoadError
10
10
  end
11
11
 
12
12
  module CEL
13
- def self.compile(source, extensions: [])
14
- Program.compile(source, extensions: extensions)
13
+ def self.compile(source, extensions: [], max_iterations: 0)
14
+ Program.compile(source, extensions: extensions, max_iterations: max_iterations)
15
15
  end
16
16
 
17
17
  class Context
@@ -41,21 +41,34 @@ module CEL
41
41
  class << self
42
42
  alias_method :__native_compile, :compile
43
43
 
44
- def compile(source, extensions: [])
45
- __native_compile(source, extensions.map(&:to_s))
44
+ def compile(source, extensions: [], max_iterations: 0)
45
+ unless max_iterations.is_a?(Integer) && max_iterations >= 0
46
+ raise ArgumentError, "max_iterations must be a non-negative Integer"
47
+ end
48
+
49
+ names = extensions.map(&:to_s)
50
+ raise ArgumentError, "Repeated CEL extension" if names.uniq.length != names.length
51
+
52
+ __native_compile(source, names, max_iterations)
46
53
  end
47
54
  end
48
55
 
49
56
  alias_method :__native_execute, :execute
50
57
 
51
- def execute(context = nil)
52
- return __native_execute if context.nil?
58
+ def execute(context = nil, timeout: nil, interrupt: nil)
59
+ return __native_execute(timeout, interrupt) if context.nil?
60
+
61
+ execute_with_context(context, timeout: timeout, interrupt: interrupt)
62
+ end
63
+
64
+ alias_method :__native_execute_with_context, :execute_with_context
53
65
 
54
- execute_with_context(context)
66
+ def execute_with_context(context, timeout: nil, interrupt: nil)
67
+ __native_execute_with_context(context, timeout, interrupt)
55
68
  end
56
69
 
57
- def call(context = nil)
58
- execute(context)
70
+ def call(context = nil, timeout: nil, interrupt: nil)
71
+ execute(context, timeout: timeout, interrupt: interrupt)
59
72
  end
60
73
  end
61
74
  end