Skip to content

Setting the HttpRequestBody buffer from inside an httpCall callback in a WASM filter #17208

Open

Description

@pdeligia

I am writing a custom Envoy filter using the WASM C++ SDK and I am trying to make an httpCall that is able to setBuffer the WasmBufferType::HttpRequestBody from inside its callback. The httpCall is invoked inside the overriden onRequestBody method of the filter's Context for the reason I explain below.

So the use case is that the filter intercepts certain incoming HTTP POST requests and passes their body as payload to a sidecar server using httpCall, which then does some manipulation on the body. The callback will then update the body of the request and invoke continueRequest() so that the POST request continues to its destination.

I am able to successfully update the body of a request as follows (simplified code snippet):

// Works fine.
FilterDataStatus FilterContext::onRequestBody(size_t body_buffer_length, bool end_of_stream) {
  if (!end_of_stream) {
    auto body = getBufferBytes(WasmBufferType::HttpRequestBody, 0, body_buffer_length);
    auto updated_body = ...; // some logic that edits the JSON body.
    WasmResult result = setBuffer(WasmBufferType::HttpRequestBody, 0, body_buffer_length, updated_body); // This succeeds.
  }
  
  return FilterDataStatus::Continue;
}

However, if I try to do this via an httpCall callback, like this (simplified some custom logic that does not matter to focus on the issue):

FilterDataStatus FilterContext::onRequestBody(size_t body_buffer_length, bool end_of_stream) {
  if (!end_of_stream) {
    auto body = getBufferBytes(WasmBufferType::HttpRequestBody, 0, body_buffer_length);
    rootContext()->remoteCall(id(), body->toString()); // This call happens in the root context below.
    return FilterDataStatus::StopIterationAndBuffer;
  }
  
  return FilterDataStatus::Continue;
}

// Function in the root context.
void FilterRootContext::remoteCall(uint32_t stream_context_id, std::string request_body) {
  // some custom logic
  ...
  
  // Calls the sidecar server, which manipulates the body of the HTTP POST request.
  WasmResult http_call_result = httpCall(cluster_name_, headers, request_body, HeaderStringPairs(), 5000,
    [stream_context_id, request_body](uint32_t header_count, size_t body_size, uint32_t trailer_count) {
     // Callback is triggered inside root context so we need to switch the
     // background context from root context to the current stream context.
     getContext(stream_context_id)->setEffectiveContext();
      
     auto status = getHeaderMapValue(WasmHeaderMapType::HttpCallResponseHeaders, ":status")->toString(); // 200
     if (status != "200") {
       // error handling with local response
       sendLocalResponse(...);
       return;
     }

     // The sidecar server gives an updated body in its response.
     auto response_body = getBufferBytes(WasmBufferType::HttpCallResponseBody, 0, body_size)->toString();
     
     // Returns an empty string! But this shouldn't match the request_body that was bind to this callback?
     auto test = getBufferBytes(WasmBufferType::HttpRequestBody, 0, request_body.size())->toString();
     
     // This fails with BadRequest!
     WasmResult result = setBuffer(WasmBufferType::HttpRequestBody, 0, request_body.size(), response_body);

     // Continue request with the updated body.
     continueRequest();
    });
  
  // Error handling if httpCall failed ...
}

Then the setBuffer(WasmBufferType::HttpRequestBody, 0, request_body.size(), response_body) inside the httpCall callback fails with BadRequest. And if I try (just for testing) to do getBufferBytes(WasmBufferType::HttpCallResponseBody, 0, body_size)->toString() as above to grab the current HTTP POST request body from the context, then it returns the empty string, which is strange. However, I have already set the current stream context via getContext(stream_context_id)->setEffectiveContext();, which I thought would allow me to do the above, and get/update the body.

Am I doing something wrong here? Any help would be much appreciated, as I cannot seem to find anything similar in the very few examples or unit tests that are around (I have only seen examples where the httpCall callback is updating headers, but here I want to update the body of the request). Thanks a ton!

Activity

  1. added
    triage
    on Jul 1, 2021
  2. pdeligia commented on Jul 2, 2021

    @pdeligia
    Author
  3. added and removed
    triage
    on Jul 2, 2021
  4. PiotrSikora commented on Jul 2, 2021

    @PiotrSikora
    Contributor

    @pdeligia headers and bodies are only accessible in their respective callbacks (e.g. you can only get/set request headers in the onRequestHeaders callback), since they are streamed and not available afterwards, which is why you cannot access HTTP request body from the callout.

    There are 2 things that we could improve:

    1. Headers and bodies should be accessible on a stream paused in their respective callbacks.
    2. Body chunks should be injectable from other callbacks. Note that there is no way to change the end_of_stream flag in the current ABI, so this wouldn't work for all the use cases until next ABI iteration.

    I need to think a little bit more about all the interactions, but I believe that (1) alone should work for your use case.

  5. pdeligia commented on Jul 3, 2021

    @pdeligia
    Author

    @pdeligia headers and bodies are only accessible in their respective callbacks (e.g. you can only get/set request headers in the onRequestHeaders callback), since they are streamed and not available afterwards, which is why you cannot access HTTP request body from the callout.

    Thanks for the quick response @PiotrSikora! Cool, what you are saying matches my understanding based on the debugging that I did with Envoy traces on when I hit this issue.

    There are 2 things that we could improve:

    1. Headers and bodies should be accessible on a stream paused in their respective callbacks.
    2. Body chunks should be injectable from other callbacks. Note that there is no way to change the end_of_stream flag in the current ABI, so this wouldn't work for all the use cases until next ABI iteration.

    I need to think a little bit more about all the interactions, but I believe that (1) alone should work for your use case.

    Both options make sense to me, and would definitely work for my use case.

    The first one probably sounds simpler, and also feels quite natural from a user's perspective (at least mine!): if you pause on one of these callbacks, because you need to do some async work (like this http call in my case to do some processing), when you resume it feels natural that you should be able to access (and manipulate) either the header or the body, based on the respective paused callback. I feel this will be really useful for many similar scenarios that involve async computation during these callbacks.

    Btw, one interesting thing that I noticed while testing things, is that if you have more than one custom filters, say Filter A and B, then if you pause on onRequestBody of Filter A, then all the onRequestBody for each filter in the chain will be invoked before the actual httpCallBack is invoked due to the httpCall response from Filter A (same happens for onRequestHeaders and the other callbacks). I was surprised by this, as I was expecting first the httpCallBack to happen and only once I do continueRequest the rest of the filter chain to execute! The reason I am bringing this up, is because I am thinking that once we have (1) implemented (or even (2)), the user logic might have to take this order of execution into account when they update the body asynchronously from the callback, right? Also what happens if say two filters do an httpCall request each? Are the callbacks guaranteed to be processed in the same order as the filters? As long as things are deterministic, I feel its OK. Just thinking aloud here -- this does not affect my scenario as we are only implementing a single filter.

    In any case, regardless of which option you feel makes more sense (or both, they seem orthogonal), supporting this feature will be incredibly helpful, so thanks a lot in advance!

  6. PiotrSikora commented on Jul 3, 2021

    @PiotrSikora
    Contributor

    Btw, one interesting thing that I noticed while testing things, is that if you have more than one custom filters, say Filter A and B, then if you pause on onRequestBody of Filter A, then all the onRequestBody for each filter in the chain will be invoked before the actual httpCallBack is invoked due to the httpCall response from Filter A (same happens for onRequestHeaders and the other callbacks). I was surprised by this, as I was expecting first the httpCallBack to happen and only once I do continueRequest the rest of the filter chain to execute! The reason I am bringing this up, is because I am thinking that once we have (1) implemented (or even (2)), the user logic might have to take this order of execution into account when they update the body asynchronously from the callback, right? Also what happens if say two filters do an httpCall request each? Are the callbacks guaranteed to be processed in the same order as the filters? As long as things are deterministic, I feel its OK. Just thinking aloud here -- this does not affect my scenario as we are only implementing a single filter.

    When you say "more than one custom filter", do you mean multiple plugins in a single Wasm module, the same plugin configured multiple times, or something else? In any case, that doesn't sound right, but could you please open a separate issue for it? Otherwise, it's going to get lost in the comments... If you happen to have a minimal reproducer with Envoy config and/or a trace log, that would be helpful.

  7. pdeligia commented on Jul 3, 2021

    @pdeligia
    Author

    When you say "more than one custom filter", do you mean multiple plugins in a single Wasm module, the same plugin configured multiple times, or something else? In any case, that doesn't sound right, but could you please open a separate issue for it? Otherwise, it's going to get lost in the comments... If you happen to have a minimal reproducer with Envoy config and/or a trace log, that would be helpful.

    Yes, let me indeed open a new issue for this. I will do a bit more investigation first, and gather some info as you say, and open an issue after the weekend.

  8. github-actions commented on Aug 2, 2021

    @github-actions

    This issue has been automatically marked as stale because it has not had activity in the last 30 days. It will be closed in the next 7 days unless it is tagged "help wanted" or "no stalebot" or other activity occurs. Thank you for your contributions.

  9. added
    stale
    on Aug 2, 2021
  10. pdeligia commented on Aug 2, 2021

    @pdeligia
    Author

    Yes, let me indeed open a new issue for this. I will do a bit more investigation first, and gather some info as you say, and open an issue after the weekend.

    Btw, @PiotrSikora please ignore my last comment, this was a red-flag because of "re-entrancy" (the httpCall was not going directly to the localhost container so the request was "re-entering" Envoy). Once I changed it to localhost (thanks to your help in #17178) this bit was resolved, that is why I did not open another issue.

    So we can just focus on the original issue with being able to set the HttpRequestBody buffers after an async httpCall response on this thread.

  11. removed
    stale
    on Aug 2, 2021
  12. github-actions commented on Sep 2, 2021

    @github-actions

    This issue has been automatically marked as stale because it has not had activity in the last 30 days. It will be closed in the next 7 days unless it is tagged "help wanted" or "no stalebot" or other activity occurs. Thank you for your contributions.

  13. added
    stale
    on Sep 2, 2021
  14. pdeligia commented on Sep 8, 2021

    @pdeligia
    Author

    @PiotrSikora @mathetake could you please tag this with "no stalebot" so that the issue does not automatically close? (I am not able to do this myself)

  15. added
    no stalebot
    and removed
    stale
    on Sep 8, 2021
  16. mathetake commented on Sep 9, 2021

    @mathetake
    Member

    @pdeligia done.

  17. owenammann commented on Nov 3, 2021

    @owenammann

    Is there any update on this? I have a similar issue. I would like to change the path of my original request after making a new httpCall based on the response of the httpCall. Since headers are not accessible from the callback, this seems impossible. Are there any workarounds? It seems like an intuitive use case to change the original http request based on the result of an httpCall.

  18. owenammann commented on Dec 7, 2021

    @owenammann

    I've found a solution for this and will be making a PR

  19. owenammann commented on Dec 8, 2021

    @owenammann

    Nevermind, it appears I don't have this issue in the first place. I am able to access the original request in the callback. I had a code error which was causing a crash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/wasmno stalebot

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions