solo-io / wasm

Web Assembly tools and SDKs for extending cloud-native infrastructure
Apache License 2.0
306 stars 40 forks source link

How to get result from external API to response for this #258

Closed thinhtranquoc closed 3 years ago

thinhtranquoc commented 3 years ago

I see an example for httpcall https://github.com/envoyproxy/envoy-wasm/blob/dfb104874b3babc7e676aaa0199f2926410c0671/test/extensions/filters/http/wasm/test_data/async_call_cpp.cc#L15

I have a question. How to not using async in this case? Because I want to return the result of the external API.

auto callback = [context_id](uint32_t headerCount, size_t body_size, uint32_t trailerCount) { WasmDataPtr wdpGhmv = getHeaderMapValue(WasmHeaderMapType::HttpCallResponseHeaders, ":status"); uint32_t status = std::stoi(wdpGhmv->toString()); WasmDataPtr wdpBody = getBufferBytes(WasmBufferType::HttpCallResponseBody, 0, body_size); std::string reponse = wdpBody->toString(); getContext(context_id)->setEffectiveContext(); if (status == 200){ sendLocalResponse(428, "Precondition Required", reponse, {}); return FilterHeadersStatus::StopIteration; } };

Sodman commented 3 years ago

Hi @thinhtranquoc. While the calls will always technically be async (as we don't want to block Envoy, we're on the critical request path!), there is a way to do what I believe you're probably trying to do, which is essentially:

You can do this by making an async request, pausing via a StopIteration, and then in the callback if everything looks good you can resume iteration with a call to proxy_continue_stream.

Here is an example of this exact flow working using our AssemblyScript proxy runtime - https://github.com/solo-io/proxy-runtime/blob/master/examples/auth/assembly/index.ts#L37-L60

thinhtranquoc commented 3 years ago

Thanks, @Sodman, I will try it.

Sodman commented 3 years ago

Closing this issue due to inactivity, let me know if there's still any issues and we can re-open!