r/actix • • Apr 18 '22

🙋What are your Advices & Suggestions on Open Source Contribution 🦀?

0 Upvotes

I have been only learning from tutorials so far. But I want to begin to contribute to open source Rust projects, and I'm interested Rust projects e.g. Rust 🦀, Actix-Web, Meilisearch, etc.

As I have already mentioned, I am a beginner, so I am looking for your advice and suggestions.

💡 How should I begin? 👩‍💻 How should I approach the codebase? 🗣️ How should I communicate with other fellow developers? 📡 How may I network with others and learn from others? 🧠 What do you recommend?

Thank you for your Time ⌚🙏


r/actix • • Feb 03 '22

Actix-web over Node.js

3 Upvotes

How may I convince others to use actix-web over nodejs? So far I have been building rest api using nodejs (express.js), but I love rust more than JavaScript. So I was wondering if I can use actix-web instead of nodejs.

Do you use actix-web only for fun or is it suitable for production applications? How may I represent my arguments? Your any help is appreciated🙏


r/actix • • Feb 26 '21

How do I pass the state into function for HttpAuthentication::bearer

0 Upvotes

I am changing a free software project that it uses actix web.

And I coded a function to validate a jwt token. It runs fine with a secret (it is string to validate the token) as string literal or const.

But now I load the value for the secret from a config file and I save into state for to pass this state as:

App::new() .data(state)

But I don't know how to get the state from inner code of function that I registed or attach to HttpAuthentication::bearer .


r/actix • • May 06 '21

How to test this example of `json-validation`?

0 Upvotes

project:

https://github.com/actix/examples/tree/master/basics/json-validation

Why will my test fail?

This is tested with Postman, it prompts 404, is it a problem of my understanding?


r/actix • • Apr 09 '21

Problem returning Result from handler using ?

0 Upvotes

I have a function that returns a custom enum error type: ApiError. I have impl ResponseError for ApiError but when I use

let result = do_thing_that_can_error()?;

which has the signature: fn do_thing_that_can_error() -> Result<String, ApiError> I am getting the message:

type annotations needed

cannot infer type of error for `?` operator

note: `?` implicitly converts the error value into a type implementing `From<api::ApiError>`

If I try to impl From<ApiError> for Error I am told it overlaps with the implementation from impl ResponseError for ApiError so that would imply that just implementing ResponseError for my type would be good enough. Any idea why the type system is getting confused here?


r/actix • • Sep 03 '22

Log incoming post request data.

0 Upvotes

Is there a way to print/log the information that a client sends( In this case the sent data is unknown the only known thing is that it is text)?


r/actix • • Mar 06 '21

Getting a 404 every other time I refresh page ACTIX_FILES

1 Upvotes

Howdy all, weird one, I refresh my page, get 404, refresh again and no 404, refresh again and 404


r/actix • • May 17 '20

actic-redis compile error

1 Upvotes

[dependencies]
actix-web = "2.0"
actix-redis = "0.8.0"

use actix_web::{App, HttpServer, web, middleware};
use actix_web::middleware::session::SessionStorage;
use actix_redis::RedisSessionBackend;
#[actix_rt::main]
async fn main() -> std::io::Result {
HttpServer::new(|| App::new()
// enable logger
.middleware(middleware::Logger::default())
// cookie session middleware
.middleware(SessionStorage::new(
RedisSessionBackend::new("127.0.0.1:6379", &[0; 32])
))
// register simple route, handle all methods
.service(web::resource("/").to(index))
)
.bind("0.0.0.0:8080")?
.start()
.await
}

Error

error[E0277]: the trait bound `redis_async::resp::RespCodec: tokio_util::codec::encoder::Encoder` is not satisfied

--> /Users/yongyutjantaboot/.cargo/registry/src/github.com-1ecc6299db9ec823/actix-redis-0.8.1/src/redis.rs:30:5

|

30 | cell: Option<actix::io::FramedWrite<WriteHalf<TcpStream>, RespCodec>>,

| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `tokio_util::codec::encoder::Encoder` is not implemented for `redis_async::resp::RespCodec`

|

= note: required by `actix::io::FramedWrite`

error[E0277]: the trait bound `redis_async::resp::RespCodec: tokio_util::codec::encoder::Encoder` is not satisfied in `redis::RedisActor`

--> /Users/yongyutjantaboot/.cargo/registry/src/github.com-1ecc6299db9ec823/actix-redis-0.8.1/src/redis.rs:51:6

|


r/actix • • Aug 24 '20

Request(/send?) a stream from one actor to antoher

1 Upvotes

Say I have an actor Foo that can produce data, and another actor Bar that needs to process that data. I want Foo to stream the data to Bar (it shouldn't just collect it all in a vector and send it...) but it should be done in a single "command" - that is, I don't want Foo to send each piece of data as a separate message and Bar to handle it separately, I want all the messages to be bundled together in some context closure.

If the explanation is not clear, the example should make it clear: https://gist.github.com/idanarye/05a00860aa4a142730e5d113ce229ffb

The important part is:

impl Handler<StartProcessingData> for Bar {
    type Result = ();

    fn handle(&mut self, _: StartProcessingData, ctx: &mut Self::Context) -> Self::Result {
        let (tx, rx) = mpsc::channel(16);
        self.foo.do_send(RequestDataGeneration(tx));
        ctx.spawn(
            rx.into_actor(self)
            .map(|number, actor, _| {
                actor.sum += number;
                println!("Added {}, sum is now {}", number, actor.sum);
            })
            .finish()
            .map(|_, actor, _| {
                println!("Done! total is {}", actor.sum);
                System::current().stop();
            })
        );
    }
}

Here Bar uses a channel. It sends the Sender to Foo and keeps the Receiver which it converts to an ActorStream that can be used to process the messages in the context of both the actor and the closure.

This works, but I find it a bit ugly. Is there a more elegant way to do it?


r/actix • • Apr 06 '19

Actix/Askama large app size (>100MB)

2 Upvotes

Hi all,

I've been using actix along with askama to create a website. It consists of 2 pages pretty much along with some small error pages.

The compiled executable however is plus of 100MB, which is larger than I'd expect (and I presume it hasn't got static files bundled with it, so I have to send those around too.)

Is this relatively normal? Thanks


r/actix • • Jan 07 '19

Question: how to I get body from an HTTP reponse

4 Upvotes

I learned some things from an example. But it is just proxying the http response. I need to read it into a String.

This is what I have so far:

use actix;
use actix_web::client;
use futures::future::Future;

fn main() {
    actix::run(|| {
        client::get("http://monitortvdigital.nuevotiempo.cl:8080/hls/tv4.m3u8")
            .header("User-Agent", "Actix-web")
            .finish()
            .unwrap()
            .send()
            .map_err(|_| ())
            .and_then(|response| {
                println!("Response: {:?}", response);
                // how to extract response body??
                Ok(())
            })
    });
}

Thanks!


r/actix • • Nov 22 '19

test function for actix middleware

4 Upvotes

I have a bunch of custom middleware to test, and I'm trying to develop a generic function for doing so.

    pub fn test_middleware<F, S, T>(request: Request, middleware: T, test_function: F)
    where
        F: Fn(HttpRequest) -> Result<(), failure::Error>,
        T: Transform<S>
    {
        let mut app = test::init_service(
            App::new()
                .wrap(middleware)
                .default_service(web::to(|request: HttpRequest| {
                    let result = test_function(request);

                    assert!(result.is_ok());

                    HttpResponse::Ok();
                }))
        );

        let _ = test::block_on(app.call(request));
    }

I've tried juggling the generic constraints, even replacing T with a concrete type that impl Transform<S>, but always end up with the trait 'actix_service::transform::IntoTransform<_, actix_web::app_service::AppRouting>' is not implemented for 'T'

Creating a local instance of my middleware inside the function and passing it to wrap works as expected.

I'm hoping for some guidance so I can understand why I'm getting this error, if its fixable, and if there's a better way to do what I'm trying to do (test middleware without a lot of repeated boilerplate)

thanks


r/actix • • Jun 07 '18

Does anyone know how session middlewares work?

6 Upvotes

I've been looking at rewriting an old project which uses redis in actix, and I'm trying to figure out exactly how https://github.com/actix/actix-redis functions and what it does.

I can tell it gives me some access to the redis database, but I don't know if it's caching things through cookies or having some other kind of "session" data stored in the browser?

Ideally I'd like to just have some middleware to get a redis connection, and not have any impact on cookies passed into the browser. I'll be calling into redis on almost every call but I don't think sessions for any particular user or browser or connection should matter- each page request will be independent.

If this is what I want to do, is actix-redis what I want? Or should I look into just hooking into redis-async directly instead?


r/actix • • Mar 25 '19

Actix-web with Diesel and Juniper

6 Upvotes

Hi,

I am trying to do a pet project with actix and rust (I trying to learn both, which causes even more problems).

I went trough the actix examples about both, Diesel and Juniper, integrations. I played with both examples and on their own they work fine. What I am having big problems setting up is a way to have both. I found a github example (https://github.com/BrendanBall/example-actix-web-juniper-diesel) which is kind of similar to what I came to (which is just trying to glue both examples together).

The actual functions that would write the request in the db (found in: src/graphql.rs) are commented out and if I uncomment them I get:

expected enum `std::result::Result`, found struct `std::boxed::Box`

I'm still not very familiar with all the Rust types, so I'm asking for some help here

  1. Is this the right way how to include both Diesel and Juniper to actix application?

  2. Can someone point in me the right direction how to solve the problem?

Thank you all!


r/actix • • May 30 '20

New Unofficial Actix Discord Server -- come make async Rust great

7 Upvotes

Come join https://discord.gg/2A9h75V to chat about Actix-related projects. There are text channels for things like project planning within and around Actix; and, there are audio/video channels for high-definitions talks for powerful learning opportunities. Between Rust's official server, Tokio's server, and tons of new project servers, you can definitely find great information for async Rust on Discord.


r/actix • • Jun 03 '18

New intermediate TechEmpower results

Thumbnail
techempower.com
20 Upvotes

r/actix • • Jul 18 '19

Thank You! 🚀🥰

24 Upvotes

Thank you to the Actix Community and /u/fafhrd91 for all your hard work on Actix. I first started learning Rust at the beginning of the year and I was happy to find a project with such active development. You've personally answered some of my questions on GitHub and here. This is a great project despite what some of the more hardcore Rust community think.

I'm super happy to have found Actix and enjoy the plethora of examples and documentation. It's an awesome body of work!


r/actix • • Jul 26 '20

is it okay to do `tokio::spawn` in actix_web context or do I have to use actix_rt::spawn?

8 Upvotes

r/actix • • Aug 30 '25

Need help in structuring project

3 Upvotes

I am currently starting to use actix framework and I need help structuring the project and I also want to follow conventions. Unfortunately I cannot find a resource that contains everything that i need to know before starting a project. Can someone guide me.


r/actix • • Jul 23 '19

Struggling with async message results

4 Upvotes

Hi friends! I'm just getting started with actix and actix-web. I write Elixir at work and Rust at home, so I was really excited to come across these frameworks.

I'm still new to Rust traits, and how actix Actors take advantage of them, so I'm having a hard time understanding how to properly handle async messages in an Actor. I want to have an Actor called Coordinator that can communicate with many Workers over HTTP, so the Coordinator Actor needs to make HTTP requests out to the Worker nodes.

From what I understand, I should use the actix_web Client, and I need to define the Result of the message handler myself. I tried to follow the ActorFuture documentation, but I'm not sure how Error is bound in the example, and I'm not sure I'm headed in the right direction trying to define my own.

Here's the (broken) code I have so far:

use std::error;
use std::fmt;
use actix::prelude::*;
use actix::fut::wrap_future;
use actix_web::client::Client;

// ...

#[derive(Debug)]
struct CreateWorkerError {

}

impl fmt::Display for CreateWorkerError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "An error happened")
    }
}

// This is important for other errors to wrap this one.
impl error::Error for CreateWorkerError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        // Generic error, underlying cause isn't tracked.
        None
    }
}

impl Handler<CreateWorker> for Coordinator {
    type Result = ResponseActFuture<Self, (), CreateWorkerError>;
    // type Result = ();

    fn handle(&mut self, msg: CreateWorker, _: &mut Context<Self>) -> Self::Result {
        println!("[Coordinator] Creating worker...");

        println!("[Coordinator] Sending request...");

        let execution = Client::new()
            .get("http://localhost:4000/some_endpoint")   // <- Create request builder
            .header("User-Agent", "Actix-web")
            .send();

        let execution_wrapped = wrap_future::<_, Self>(execution);

        let wrapped_again = execution_wrapped.map(|result, actor, _ctx| {
            // Actor's state updated here
            // actor.inner_state.update_from(result);
            println!("[Coordinator] Finished");
        });

        Box::new(wrapped_again)
    }
}

Here's the compiler error I'm seeing:

error[E0271]: type mismatch resolving `<coordinator::CreateWorker as coordinator::_impl_act_statusupdate::actix::Message>::Result == std::result::Result<(), coordinator::CreateWorkerError>`
   --> src/controller/coordinator/mod.rs:133:6
    |
133 | impl Handler<CreateWorker> for Coordinator {
    |      ^^^^^^^^^^^^^^^^^^^^^ expected (), found enum `std::result::Result`
    |
    = note: expected type `()`
               found type `std::result::Result<(), coordinator::CreateWorkerError>`
    = note: required because of the requirements on the impl of `coordinator::_impl_act_statusupdate::actix::dev::MessageResponse<coordinator::Coordinator, coordinator::CreateWorker>` for `std::boxed::Box<(dyn coordinator::_impl_act_statusupdate::actix::ActorFuture<Item = (), Actor = coordinator::Coordinator, Error = coordinator::CreateWorkerError> + 'static)>`

Could somebody give me some advice or point me to an example about how to define this result correctly? Thanks!


r/actix • • Feb 19 '19

Question: How can i get which method is requested?

3 Upvotes

I want to use a resource without method extractor. with one single function, i want to get method type and call function with it.

fn main() {

server::new(|| {

let tera =

compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));

App::with_state(AppState{template: tera})

.middleware(middleware::Logger::default())

.handler( "/static", fs::StaticFiles::new("static")

.unwrap()

.show_files_listing())

.resource("/", |r| r.with(views::index))

}).bind("127.0.0.1:8080")

.expect("Could not bind to port 8080")

.run();

}

fn index2(&self, (state, query): (State<crate::AppState>, Query<HashMap<String, String>>))->

Result<HttpResponse, Error>{

if method=="POST{ call a.func()}

else { call b.func()}

Ok(HttpResponse::Ok().content_type("text/html").body("AAAA"))

}


r/actix • • Sep 25 '19

Making requests inside route without actix_web::client

1 Upvotes

Hi, I want to make a web request inside one of my routes and print out the result of the request.

I found some examples doing this with actix_web::client but I'm using an existing crate that constructs a fairly complicated request as a Future. I don't have access to the final URL so I cannot use actix_web::client to make the request.

So I have a really basic route that wraps the external request:

fn test_route(data: web::Data<AppState>) -> String {
    external_request()
}

And external_request() performs the request and should return a String. The crate documentation suggests using something like this:

let mut core = tokio_core::reactor::Core::new()?;

let future = ... // Build up the actual request as a Future

core.run(future)?;

However creating a new Core within the request doesn't work and obviously is not a good idea since actix already has its own thread management. So how can I "jack in" on existing actix_web threads to execute a Future like this inside a request? I tried creating a tokio Core outside of HttpServer and including it as shared appdata but it cannot be sent safely between threads.

I also tried to include a Handle in my appdata instead of the whole Core (within an Arc and/or Mutex) but that cannot be sent across threads either.

I also tried some variants where I .wait() the Future, but this seems to deadlock the thread and never resolve.

Appreciate any help!


r/actix • • Nov 21 '18

Generic Methods in Rust: How Exonum Shifted from Iron to Actix-web

Thumbnail
medium.com
9 Upvotes

r/actix • • Sep 26 '19

How can I handle an error in the response when passing a message through a chain of actors?

4 Upvotes

I created a minimal example that demonstrates the problem, and I rather link to a gist because Reddit has no syntax highlighting - so here: https://gist.github.com/idanarye/8caf811b0008b369a5c733f72d629db2

Basically I want to pass a message through multiple actors (each doing their own thing), and get the result all the way back. In the example, I send the message from an Arbiter in the main function to a NodeActor, which passes it to a LeafActor, which returns a result that gets passed back to the NodeActor and from there back to the main function. So the path is main -> node -> leaf -> node -> main.

The problem is that I also care about any possible errors that may occur at the leaf, and I need to know about them back at main. This means they need to pass through the node. But when I send() the Msg from the NodeActor to the LeafActor, I need to do this:

self.leaf_addr.send(msg).into_actor(self)
.map_err(|error: MailboxError, _, _| {
    println!("Got a mailbox error {:?}, but we have to pass a MyError", error);
    MyError::Technical
})
.map(|result: Result<(), MyError>, _, _| {
    println!("The result node actor got from leaf actor is {:?}, but we can't pass the error", result);
    () // this is all we can return here...
})
  • map_err only gets involved if there are problems in Actix' pipes, and I get a MailboxError for that - but I need to return a MyError because that's the Err type of Msg::Result.

  • map gets the actual response from the leaf - which means if we get an actual MyError::Logical it goes there. But it can only return the Ok type of Msg::Result, so I can't pass that MyError back to main!

And indeed - when I run it this is what gets printed:

Node actor got Msg
Leaf actor got Msg
The result node actor got from leaf actor is Err(Logical), but we can't pass the error
Main got response from node actor: Ok(())

When I try to change NodeActor::Result to this:

type Result = ResponseActFuture<Self, Result<(), MyError>, MailboxError>;

It complains that it can't do that because it does not match what it expects from Msg::Result:

error[E0271]: type mismatch resolving `<Msg as actix::handler::Message>::Result == std::result::Result<std::result::Result<(), MyError>, actix::address::MailboxError>`
  --> src/main.rs:44:6
   |
44 | impl Handler<Msg> for NodeActor {
   |      ^^^^^^^^^^^^ expected (), found enum `std::result::Result`
   |
   = note: expected type `std::result::Result<(), MyError>`
              found type `std::result::Result<std::result::Result<(), MyError>, actix::address::MailboxError>`
   = note: required because of the requirements on the impl of `actix::handler::MessageResponse<NodeActor, Msg>` for `std::boxed::Box<(dyn actix::fut::ActorFuture<Actor = NodeActor, Item =
std::result::Result<(), MyError>, Error = actix::address::MailboxError> + 'static)>`

So... what do I do? Changing Msg::Result to Result<Result<(), MyError>, MailboxError> is not a good solution, because then, at least according to the type system, I can get a MailboxError inside the good path of the future I route in NodeActor and I won't be able to pass it as a MailError!. Also it doesn't seem right because MailboxError is not part of my inter-actor API - it's part of Actix' plumbing.


r/actix • • Sep 30 '18

Thumbcloud - A file-sharing server written in Actix-web

Thumbnail
github.com
13 Upvotes