What is the type for a vector of async functions that return "impl Responder"? - asynchronous

use actix_web::{delete, get, post, put, HttpResponse, Responder};
#[get("/user")]
async fn get_user() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
#[post("/user")]
async fn add_user() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
#[delete("/user")]
async fn delete_user() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
#[put("/user")]
async fn update_user() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
pub const my_functions: Vec<fn() -> impl Responder> = vec![get_user, add_user, delete_user, apdate_user].iter();
Trying to create web app with actix.rs. I want to split all API handlers to controllers and than map it as the services like App::new().service(func1).service(func2).
I can't understand how to add correct type for vector.

The type .body() returns is HttpResponse. But you cannot put your functions together in a vector, for two reasons: a) The underlying type of impl Trait is supposed to be opaque. The compiler won't let you use it, even if you know it, to not leak encapsulation. From the compiler point of view, you have different functions that returns different types. b) even if you would specify the type directly (and not rely on impl Trait), like #StefanZobel said they're async functions, and thus returns an impl Future<...>. The returned future is a different type for each function.
You can use a closure to wrap the futures into Pin<Box<dyn Future<...>>> (you can use dyn Responder too, or specify the concrete type. I wrote like if you specified the concrete type):
let my_functions: Vec<fn() -> Pin<Box<dyn Future<Output = HttpResponse>>>> = vec![|| Box::pin(get_user()), || Box::pin(add_user), || Box::pin(delete_user), || Box::pin(update_user)].iter();
Also note that you cannot create a Vec (nor a Box) inside const or static.
But all of that doesn't matter because you wrapped your functions with actix's macros (#[get("...")] etc.). They transform the function into an anonymous struct that implements HttpServiceFactory. So you can't just call them or whatever. What you need to do depends on what you want to do with your functions, but you can e.g. wrap them into Box<dyn HttpServiceFactory>

Related

Asynchronous Projections in Rust

Is it possible to do asynchronous projections in rust?
By a projection, I mean a method on a struct that returns a reference to one of its fields. A minimal synchronous example:
struct Aggregate<T>(T);
impl<T> Aggregate<T> {
fn project(&self) -> &T {
&self.0
}
}
An asynchronous projection should not yield a &T but some Future with output &T. Naively trying to implement such a Future does not work; in the following example, the reference in the Output type &T (rightly so) requires a lifetime.
impl<T> Future for Aggregate<T> {
type Output = &T;
fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(self.project())
}
}
A correct implementation would have to look like this:
impl<T> Future for Aggregate<T> {
type Output<'s> = &'s T where T: 's;
fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output<'_>> {
Poll::Ready(self.project())
}
}
But this clashes with the definition of the Future trait, which does not accept a lifetime for Output:
lifetime parameters or bounds on type `Output` do not match the trait declaration
lifetimes do not match type in trait rustcE0195
Is there any way of getting this to work with the core Future trait, or would a dedicated LendingFuture trait be needed (analogous to how a LendingIterator needs a new, dedicated trait)?
If this is not possible to do with the Future trait, are there workarounds and/or are there plans to provide a LendingFuture in core eventually?
I want to explicitly implement Future for some first-class type, not rely on some type automatically generated by async fn desugaring or on trait objects.
My interest in asynchronous projections comes from exploring asynchronous APIs in the style of bytes::Buf, the chunk method boils down to a projection. For way more details, see panda_pile::why, and this section for why I'm interested in explicitly working with futures rather than with async functions.

Async method that consumes self causes error "returns a value referencing data owned by the current function"

Is it possible to consume self in an async method?
Here is my method (please note the poller is unrelated to the poll method in rust futures).
pub async fn all(self) -> WebDriverResult<Vec<WebElement<'a>>> {
let elements = self.poller.run(&self.selectors).await?;
Ok(elements)
}
and for completeness, here is the struct it belongs to:
pub struct ElementQuery<'a> {
session: &'a WebDriverSession,
poller: ElementPoller,
selectors: Vec<ElementSelector<'a>>,
}
NOTE: session is passed in via the new() fn. It is owned by the caller that creates ElementQuery and runs it to completion. The above method should return Vec<WebElement>.
The error says:
error[E0515]: cannot return value referencing local data `self.poller`
--> src/query.rs:193:9
|
193 | self.poller.run(&self.selectors).await
| -----------^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `self.poller` is borrowed here
However, as far as I can tell, I am not returning any references owned by the current function. The only reference being returned (inside WebElement) is session, which I passed into the struct to begin with.
I can change the ? to unwrap() so that the only return path is Ok(elements) just to eliminate any other possibilities (same error).
Here is WebElement:
#[derive(Debug, Clone)]
pub struct WebElement<'a> {
pub element_id: ElementId,
pub session: &'a WebDriverSession,
}
ElementId is just a newtype wrapper around String - no references.
Is this something to do with the method returning a Future that may execute later? and perhaps something to do with something being held over an .await boundary?
If the ONLY reference being returned is &WebDriverSession, and that same reference was passed in via new(), then why is it telling me that I'm returning a reference owned by the function?
EDIT: Managed to get this to compile by effectively inlining some code rather than calling additional async functions. Still not sure why this fails, other than it seems to be related to holding a reference across .await boundaries, even if that reference is not owned by the function/struct on either side.
Here's a playground link with a simplified example:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f38546480aaeb3594c8c17fec9b7d62c

Rust Futures for String

I've been trying to understand and play with futures (version 0.3) but couldn't make this work. As I understand, a function is able to return a future of type A only if the type A implements the future trait. If I create a struct and implement the future trait, it's okay but why String doesn't work?
use futures::prelude::*;
async fn future_test() -> impl Future<Output=String> {
return "test".to_string();
}
I get the error:
the trait bound `std::string::String: core::future::future::Future` is not satisfied
the trait `core::future::future::Future` is not implemented for `std::string::String`
note: the return type of a function must have a statically known sizerustc(E0277)
So I told myself, okay then I can use Box like:
async fn future_test() -> impl Future<Output=Box<String>> {
return Box::new("test".to_string());
}
But the error is same:
the trait bound `std::string::String: core::future::future::Future` is not satisfied
the trait `core::future::future::Future` is not implemented for `std::string::String`
note: the return type of a function must have a statically known sizerustc(E0277)
What am I doing wrong? And why does the future hold the String instead of the Box itself?
When a function is declared async, it implicitly returns a future, with the return type of the function as its Output type. So you would write this function:
async fn future_test() -> String {
"test".to_string()
}
Alternatively, if you wanted to explicitly specify return type as a Future, you would drop the async keyword. If you did that you would also need to construct a future to return, and you would not be able to use await inside the function.
fn future_test2() -> impl Future<Output=String> {
ready("test2".to_string())
}
Note that futures::ready constructs a Future that is immediately ready, which is appropriate in this case since there is no actual asynchronous activity going on in this function.
Link to Playground

Rust - Wrapping FFI Pointers

I'm trying to wrap a FFI in a Rust Safe way.
The FFI Exposes raw pointers to structs with vtables, basically a struct looks like this:
pub struct InterfaceVTBL {
pub Release: unsafe extern "system" fn(This: *mut Interface) -> u64
}
pub struct Interface {
pub lpVtbl: *const InterfaceVTBL,
}
impl Interface {
pub unsafe fn Release(&self) -> u64 {
((*self.lpVtbl).Release)(self as *const _ as *mut _)
}
}
The Release Method is important, because it has to be called, when you are finished using the pointer to avoid a memory leak.
Now, im currently wrapping the pointers i get into Container Structs like this:
pub struct InterfaceContainer {
interface: *mut Interface
}
impl InterfaceContainer {
fn Release(&mut self) {
let reference = &*self.interface;
reference.Release();
}
}
impl Drop for InterfaceContainer {
fn drop(&mut self) {
self.Release();
}
}
Notice, that i didn't make the Release function of the Container pub, because it really should only be called on drop.
Now, the problem i'm facing, is that i need to pass the raw pointer to the interface to FFI Functions that will most likely be in different modules than the container structs, so they can't access the raw pointers in the Containers.
I could of course make the pointers pub or add a get_ptr function that returns a reference to the pointer, but i think that would defeat the purpose of wrapping the pointer in the first place, since all restrictions on function use through the pointers could be circumvented.
Now, im asking, is there a different way of exposing the pointer to those functions only, that i missed, or do i have to use an entirely different approach to wrapping those pointers?
Answers are much appreciated, thanks in advance.
Found a Solution:
Using pub (crate), the internal pointer can be made accessible only to code in the crate and not to outside users.

Should I return await in Rust?

In JavaScript, async code is written with Promises and async/await syntax similar to that of Rust. It is generally considered redundant (and therefore discouraged) to return and await a Promise when it can simply be returned (i.e., when an async function is executed as the last thing in another function):
async function myFn() { /* ... */ }
async function myFn2() {
// do setup work
return await myFn()
// ^ this is not necessary when we can just return the Promise
}
I am wondering whether a similar pattern applies in Rust. Should I prefer this:
pub async fn my_function(
&mut self,
) -> Result<()> {
// do synchronous setup work
self.exec_command(
/* ... */
)
.await
}
Or this:
pub fn my_function(
&mut self,
) -> impl Future<Output = Result<()>> {
// do synchronous setup work
self.exec_command(
/* ... */
)
}
The former feels more ergonomic to me, but I suspect that the latter might be more performant. Is this the case?
One semantic difference between the two variants is that in the first variant the synchronous setup code will run only when the returned future is awaited, while in the second variant it will run as soon as the function is called:
let fut = x.my_function();
// in the second variant, the synchronous setup has finished by now
...
let val = fut.await; // in the first variant, it runs here
For the difference to be noticeable, the synchronous setup code must have side effects, and there needs to be a delay between calling the async function and awaiting the future it returns.
Unless you have specific reason to execute the preamble immediately, go with the async function, i.e. the first variant. It makes the function slightly more predictable, and makes it easier to add more awaits later as the function is refactored.
There is no real difference between the two since async just resolves down to impl Future<Output=Result<T, E>>. I don't believe there is any meaningful performance difference between the two, at least in my empirical usage of both.
If you are asking for preference in style then in my opinion the first one is preferred as the types are clearer to me and I agree it is more ergonomic.

Resources