Skip to content

dynamic_modules: scheduler ABI for generic non-blocking async operations - #39765

Merged
mathetake merged 7 commits into
envoyproxy:mainfrom
mathetake:cookingdispathers
Jun 17, 2025
Merged

mathetake merged 7 commits into
envoyproxy:mainfrom
mathetake:cookingdispathers

Conversation

@mathetake

@mathetake mathetake commented Jun 6, 2025 •

Copy link
Copy Markdown
Member

Commit Message: dynamic_modules: scheduler ABI for generic non-blocking async operations
Additional Description:

This commits adds a generic "scheduler" ABI that allows modules to schedule a generic event trigged by the module. More specifically, this adds the capability to create a "scheduler" object per HTTP filter object (== per request) that can be safely sent across threads. It has the method to schedule a generic event invoked against the HTTP filter object on the correct worker thread, and that method can be called from any threads including the ones managed by a module. At Rust SDK level, the scheduler trait implements the Send trait hence can be sent to another thread to offload the processing while freeing the worker thread.

The following functions are added to the ABI:

  • envoy_dynamic_module_on_http_filter_scheduled
  • envoy_dynamic_module_callback_http_filter_scheduler_new
  • envoy_dynamic_module_callback_http_filter_scheduler_commit
  • envoy_dynamic_module_callback_http_filter_scheduler_delete
  • envoy_dynamic_module_callback_http_filter_continue_decoding
  • envoy_dynamic_module_callback_http_filter_continue_encoding

This enables the whole bunch of new use cases. Most notably, now a module can implement their own External Processor, External Authorization, or Global Rate Limit filter style extensions. These require the blocking network calls in their own style so the scheduler allows it to avoid blocking the worker thread while doing the necessary work. One another example is an external-caching filter which talks to a database like DynamoDB, Redis, Memcached, S3, etc.

Here's the example Rust SDK usage which implements an external-caching filter (from the integration test case):

struct FakeExternalCachingFilter {
  rx: Option<std::sync::mpsc::Receiver<String>>,
}

impl<EHF: EnvoyHttpFilter> HttpFilter<EHF> for FakeExternalCachingFilter {
  fn on_request_headers(
    &mut self,
    envoy_filter: &mut EHF,
    _end_of_stream: bool,
  ) -> envoy_dynamic_module_type_on_http_filter_request_headers_status {
    // Get the cache key from the request header, which is owned by the Envoy filter.
    let cache_key_header_value = envoy_filter.get_request_header_value("cacahe-key").unwrap();
    // Construct the cache key String from the Envoy buffer so that it can be sent to the different
    // thread.
    let mut cache_key = String::new();
    cache_key.push_str(std::str::from_utf8(cache_key_header_value.as_slice()).unwrap());
    // We need to send the found cached response body back to the worker thread,
    // so we use a channel to communicate between the filter and the worker thread safely.
    //
    // Alternatively, you can use Arc<Mutex<>> or similar constructs.
    let (cx, rx) = std::sync::mpsc::channel();
    self.rx = Some(rx);
    // In real world scenarios, rather than spawning a thread per request,
    // you would typically use a thread pool or an async runtime to handle
    // the asynchronous I/O or computation.
    let scheduler = envoy_filter.new_scheduler();
    _ = std::thread::spawn(move || {
      // Simulate some processing to check if the cache key exists.
      let cache_hit = if cache_key == "existing" {
        // Do some processing to get the cached response body in real world.
        let cached_body = "cached_response_body".to_string();
        // If the cache key exists, we send it back to the Envoy filter.
        cx.send(cached_body).unwrap();
        1
      } else {
        0
      };
      // We use the event_id pased to the commit method to indicate if the cache key was found.
      scheduler.commit(cache_hit);
    });
    // Return StopIteration to indicate that we will continue the processing
    // once the scheduled event is completed.
    envoy_dynamic_module_type_on_http_filter_request_headers_status::StopIteration
  }

  fn on_scheduled(&mut self, envoy_filter: &mut EHF, event_id: u64) {
    // We use event_id to determine if the cache key was found.
    if event_id == 0 {
      // This means the cache key was not found, so we continue decoding.
      envoy_filter.continue_decoding();
    } else {
      let result = self.rx.take().unwrap().recv().unwrap();
      envoy_filter.send_response(200, vec![("cached", b"yes")], Some(result.as_bytes()));
    }
  }
}

Risk Level: low (completely new optional code path)
Testing: done
Docs Changes: done
Release Notes: n/a
Platform Specific Features: n/a

@repokitteh-read-only

Copy link
Copy Markdown

As a reminder, PRs marked as draft will not be automatically assigned reviewers,
or be handled by maintainer-oncall triage.

Please mark your PR as ready when you want it to be reviewed!

🐱

Caused by: #39765 was opened by mathetake.

see: more, trace.

@mathetake mathetake mentioned this pull request Jun 6, 2025
11 tasks done
@mathetake
mathetake force-pushed the cookingdispathers branch from 4eb725e to 366d9dd Compare June 6, 2025 17:09
@mathetake mathetake changed the title dynamic_modules: initial impl of dispatcher abstraction dynamic_modules: scheduler ABI for generic non-blocking async operations Jun 6, 2025
@mathetake
mathetake force-pushed the cookingdispathers branch from 80255ae to 9f6abd3 Compare June 6, 2025 19:53
@mathetake
mathetake marked this pull request as ready for review June 6, 2025 20:25
@mathetake
mathetake requested a review from mattklein123 as a code owner June 6, 2025 20:25

@wbpcode wbpcode left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this contribution and I add two comment to it.

Comment on lines +1314 to +1332
/**
* envoy_dynamic_module_callback_http_filter_continue_decoding is called by the module to continue
* decoding the HTTP request.
*
* @param filter_envoy_ptr is the pointer to the DynamicModuleHttpFilter object of the
* corresponding HTTP filter.
*/
void envoy_dynamic_module_callback_http_filter_continue_decoding(
envoy_dynamic_module_type_http_filter_envoy_ptr filter_envoy_ptr);

/**
* envoy_dynamic_module_callback_http_filter_continue_encoding is called by the module to continue
* encoding the HTTP response.
*
* @param filter_envoy_ptr is the pointer to the DynamicModuleHttpFilter object of the
* corresponding HTTP filter.
*/
void envoy_dynamic_module_callback_http_filter_continue_encoding(
envoy_dynamic_module_type_http_filter_envoy_ptr filter_envoy_ptr);

@wbpcode wbpcode Jun 16, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this two method should be scheduled to correct worker thread to run first, right? If so, please add an obvious note or attention on the comment. (or all methods actually have similar requirement? If so, just ignore this comment)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah all functions accepting envoy_dynamic_module_type_http_filter_envoy_ptr filter_envoy_ptr is basically the same so i will end up adding that comment to all methods ... haha. But you comment is actually valid though, I think i add that comment to all functions in a follow PR.

Comment on lines +1229 to +1237
/**
* envoy_dynamic_module_callback_http_filter_scheduler_delete is called by the module to delete
* the HTTP filter scheduler created by envoy_dynamic_module_callback_http_filter_scheduler_new.
*
* @param scheduler_module_ptr is the pointer to the HTTP filter scheduler created by
* envoy_dynamic_module_callback_http_filter_scheduler_new.
*/
void envoy_dynamic_module_callback_http_filter_scheduler_delete(
envoy_dynamic_module_type_http_filter_scheduler_module_ptr scheduler_module_ptr);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we actually need the create/delete ABI? IMO, I think only the commit/scheduled is necessary. The create/delete and the DynamicModuleHttpFilterScheduler may extend the lifetime of the Filter object in unexpected way and result in unexpected results.

I think you can use scheduler_commit to post an task to the filter related worker. And when the task is scheduled at worker, we can check if the filter is still alive or not (for example, a lifetime flag that will be reset after the onDestroy() is called), if the filter is still alive, we can run the scheduler_scheduled or the task will be noop.

Feel free to point my error if I misunderstood it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

without holding the shared_ptr of the filter to the scheduler class, that "checking the lifetime flag in the scheduler callback" can be null pointer exception as by the time when it is called, the entire filter instance might have been deallocated.

It indeed does what you meant by "ou can use scheduler_commit to post an task to the filter related worker. ":

  void commit(uint64_t event_id) {
    dispatcher_.post([filter = filter_, event_id]() { filter->onScheduled(event_id); });
  }

and without holding "filter_" to the scheduler class shared_ptr, the posted callback here can be invalid.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so the point is that commit can be called anytime -- before or after very long network call, etc, so by the time this commit itself being called, the filter can be destroyed already

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i am open to finding the way to eliminate new/delete ABI though...

@wbpcode wbpcode Jun 16, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After a rethinking about that. I think the new/delete may inevitable because the commit may be called at any thread. Or we need some more complex state management.

But it's more dangerous to extend the filter lifetime anyway because the filter depends the ActiveStream and the ActiveStream may have gone. So, we'd better to avoid do that.

I think it would be better to keep only a weak pointer of filter in the DynamicModuleHttpFilterScheduler. And before to schedule the event at the worker thread, ensure the weak point is not expired and the onDestory() of filter haven't be called.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah weak pointer that's nice

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

5f1aa72 thanks for the great suggestino

@wbpcode wbpcode self-assigned this Jun 16, 2025
Comment on lines +205 to +209
dispatcher_.post([filter = filter_, event_id]() {
if (DynamicModuleHttpFilterSharedPtr filter_shared = filter.lock()) {
filter_shared->onScheduled(event_id);
}
});

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: last comment: I think we shouldn't schedule the event after the onDestroy() is called. There is a little gap between the onDestory() and the destruction of the filter.

But I am OK if you insist on this way.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah i don't think that would be worth another lock but i understand your suggestion

@mattklein123 mattklein123 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems fine, but as I mentioned a long time ago, if you are going to all of this effort I really think we should implement an async executor on top of the envoy thread pool and then we can just run async functions on the main thread without needing any other threads. I don't think it would be that hard and it would also be a really fun project. :)

Once you can spawn() things to Envoy the main thread loop can just pool futures as needed. It would be so nice!

@wbpcode

wbpcode commented Jun 17, 2025

Copy link
Copy Markdown
Member

This seems fine, but as I mentioned a long time ago, if you are going to all of this effort I really think we should implement an async executor on top of the envoy thread pool and then we can just run async functions on the main thread without needing any other threads. I don't think it would be that hard and it would also be a really fun project. :)

Once you can spawn() things to Envoy the main thread loop can just pool futures as needed. It would be so nice!

Sound pretty great to me. But we also need to notice although we can wrap an async executor based on the envoy event loop to support task/timer/etc, it's hard to use it for go/rust lib. The go/rust ecology has their own async solution and won't use our wrap executor anyway. If we want to cooperate with go/rust, we still need this cross thread commit. orz.

@mattklein123

Copy link
Copy Markdown
Member

Sound pretty great to me. But we also need to notice although we can wrap an async executor based on the envoy event loop to support task/timer/etc, it's hard to use it for go/rust lib. The go/rust ecology has their own async solution and won't use our wrap executor anyway. If we want to cooperate with go/rust, we still need this cross thread commit. orz.

Regarding rust that is not true. Rust async is abstract from the executor. We for sure cannot use tokio in this way but we absolutely can use compiler generated async functions if we have a custom executor.

@wbpcode

wbpcode commented Jun 17, 2025

Copy link
Copy Markdown
Member

Sound pretty great to me. But we also need to notice although we can wrap an async executor based on the envoy event loop to support task/timer/etc, it's hard to use it for go/rust lib. The go/rust ecology has their own async solution and won't use our wrap executor anyway. If we want to cooperate with go/rust, we still need this cross thread commit. orz.

Regarding rust that is not true. Rust async is abstract from the executor. We for sure cannot use tokio in this way but we absolutely can use compiler generated async functions if we have a custom executor.

Got it. Then that will make more sense.

@mathetake

Copy link
Copy Markdown
Member Author

ok it seems i'm late to the discussion, but yeah i am not at against the rust async runtime impl in envoy...that would be indeed really cool. The only concern is however just @wbpcode briefly mentions that how it can be done without tying this dynamic modules code to Rust specific as we are looking to pave the way for Go SDK in the short term (about which wpbcode and I chatted offline yesterday...).

@mathetake

Copy link
Copy Markdown
Member Author

anyways thank you two for taking a look at this one

@mathetake

Copy link
Copy Markdown
Member Author

i think that can be a good candidate theme for GSoc maybe

@mathetake
mathetake merged commit 422f17a into envoyproxy:main Jun 17, 2025
@mathetake
mathetake deleted the cookingdispathers branch June 17, 2025 08:51
mathetake added a commit to envoyproxy/dynamic-modules-examples that referenced this pull request Jun 24, 2025
Notably, the latest main comes with:
* Scheduler ABI: envoyproxy/envoy#39765
* Callouts ABI: envoyproxy/envoy#39151

Signed-off-by: Takeshi Yoneda <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants