Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 00:04
    danloh closed #1756
  • 00:00
    robjtede commented #1756
  • Oct 25 23:34
    danloh commented #1756
  • Oct 25 23:20
    codecov-io commented #1756
  • Oct 25 22:50
    danloh edited #1756
  • Oct 25 22:50
    danloh edited #1756
  • Oct 25 22:50
    danloh edited #1756
  • Oct 25 22:50
    danloh edited #1756
  • Oct 25 22:49
    danloh opened #1756
  • Oct 25 19:42
    robjtede labeled #1755
  • Oct 25 19:41
    robjtede demilestoned #1721
  • Oct 25 19:40
    jplatte closed #1721
  • Oct 25 19:40
    jplatte commented #1721
  • Oct 25 19:14
    codecov-io commented #1754
  • Oct 25 18:55
    robjtede commented #1721
  • Oct 25 18:54
    robjtede commented #1251
  • Oct 25 18:54
    robjtede commented #1251
  • Oct 25 18:54
    robjtede commented #1251
  • Oct 25 18:54
    robjtede commented #1735
  • Oct 25 18:53
    robjtede commented #1727
Laurențiu Nicola
@lnicola
Hi. I'm sure I'm missing something, but I dived right into writing code for a small app. Can I return Result from a handler? The docs seem to imply so, but I'm getting a weird error:
the trait `Factory<_, _, _>` is not implemented for `fn(actix_web::web::Path<(u8, u32, u32)>) -> impl std::future::Future {<index as HttpServiceFactory>::register::index}
That's with Result<NamedFile, Box<dyn std::error::Error>>
Laurențiu Nicola
@lnicola
Never mind, it's ResponseError
matrixbot
@matrixbot
projectmoon do i need to import futures/futures_util for access to the mapping methods on actix requests?
projectmoon it would seem that i do
tronta
@tronta
Hi, I try to create an authorization middleware which automatically verifies a requests using a an external system which is called via a REST call.
To not block the system, I want to do this call async. But unfortunately I get the error that async traits are currently not supported. Should I use async_trait.
What would be the right approach to do that? Is there an example?
1 reply
Linus Behrbohm
@mankinskin
Hi everyone, shouldn't http::StatusCode implement ResponseError?
4 replies
vepqrtx
@vepqrtx_gitlab
hello, I'm getting an error in trying to implement a handler with a state object that is generic: https://pastebin.com/VSkB7Ptj It seems to be an issue inside the code generation that actix is doing and I'm not sure quite what to do.
5 replies
AKA.baoyachi
@baoyachi

how to get https serial_number in actix-web ?
I just find in rust-openssl get 'serial_number' method with link:https://github.com/sfackler/rust-openssl/blob/master/openssl/src/x509/mod.rs#L573

how to use get this function in actix-web

Alan Briolat
@alanbriolat
In a situation where you have a whole load of outbound TCP connections, but want to retain information about the target host even when not connected, what would be the "normal" way of structuring it? Having an actor that lives only for the duration of the connection and sharing/duplicating the retained host state elsewhere, or having an actor that owns the state and can be connected and disconnected, outliving any particular connection?
2 replies
Stefan Schindler
@dns2utf8
Hi people
I have a strange error in my actix code: the trait actix::dev::MessageResponse<Snake, ExecuteTick> is not implemented for actix::MessageResult<SnakeBody>
What I want to do is reply to the ExecuteTick Message with a SnakeBody (maybe also a message?)

#[derive(Message)]
#[rtype(result = "SnakeBody")]
struct ExecuteTick;
#[derive(Message)]
#[rtype("()")]
pub struct  SnakeBody(Vec<Pos2d>);

impl Handler<ExecuteTick> for Snake {
    type Result = MessageResult<SnakeBody>;

    fn handle(&mut self, _msg: ExecuteTick, ctx: &mut Context<Self>) -> Self::Result {
        println!("Snake::ExecuteTick");

        todo!("collect user input");

        todo!("do step");

        MessageResult(SnakeBody(self.body.clone()))
    }
}
Am I missing something?
Stefan Schindler
@dns2utf8
Also, is there a difference between #[rtype("()")] and #[rtype(result = "()")]?
Stefan Schindler
@dns2utf8

I got it to compile like this:

#[derive(Debug, MessageResponse, Serialize)]
pub struct SnakeBody(Vec<Pos2d>);

impl Handler<ExecuteTick> for Snake {
    type Result = SnakeBody;

    fn handle(&mut self, _msg: ExecuteTick, ctx: &mut Context<Self>) -> Self::Result {
        println!("Snake::ExecuteTick");

        let (sender, receiver) = channel::<PlayerInput>(100);
        let mut inputs: Vec<PlayerInput> = vec![];
        for client in &self.subscribers {
             client
                .send(GetCurrentUserAction)
                .into_actor(self)
                .then(|res, _snake, ctx| {
                    if let Some(input) = res.expect("unable to collect current user input") {
                        //inputs.push(input);
                        sender.do_send(input);
                    }

                    fut::ready(())
                })
                .wait(ctx);
        }

        //MessageResult(
        SnakeBody(self.body.clone())
        //)
    }
}

Now I would like to collect the results from the subscribers, but I get either moved out error or the channel can not send the results back.
Does anyone have any idea?

Stefan Schindler
@dns2utf8
Can I await the actix_utils::mpsc::channel() in a fn handle(...)?
Kevin Hoffman
@autodidaddict
I'm getting a mailbox closed error in my actor. It's a sync actor being invoked by an async actor. The async actor starts the sync actor in an arbiter , I see the actor's "started" function fire, the sync actor seems fine after that, then when a different async actor goes to invoke it, it immediately gets the "mailbox closed" error. what would cause the mailbox to be closed? Does the arbiter thread go away? If so, how do I keep the arbiter thread alive?
4 replies
Jayshua
@Jayshua
I'm looking at Actix for a new project and had a quick question: are actors with a SyncArbiter suitable for a 100% CPU-bound task like video encoding? Would I be able to setup a SyncArbiter for the video encoding with threads=cpu cores and still have other actors handling the other parts of the application without scheduling issues on the regular Arbiter? (Or am I completely misunderstanding how arbiters work?)
1 reply
Jayshua
@Jayshua
Someone responded to my question, but now the response is gone :shrug: I'll respond to that response anyway. I haven't written any code yet, I'm just trying to figure out if Actix would work for my use case since most actor-type frameworks I've seen focus pretty exclusively on I/O intensive tasks and die horribly for CPU bound tasks. It looks like a SyncArbiter is meant to support CPU-bound tasks, I just figured a quick question would be better than building a prototype only to find out I'm completely misunderstanding and need my own threading system anyway.
Kevin Hoffman
@autodidaddict
I'm certainly no expert... far from it.. however, my testing on syncarbiters makes me think this will work. A 100% utilized sync arbiter should perform the same way as a tight "for" loop running in its own thread... the thread will be fully utilized but it shouldn't lock the CPU
unless you're out of cores, and all of them are at 100%
when I do stuff like that, I typically run at cores/2 or cores-1
so that there's always a core available for the "regular" work-stealing async stuff
Jayshua
@Jayshua
Great, thanks! That's what I gathered from the documentation too so I'll give it a shot.
Kevin Hoffman
@autodidaddict
is there a way to "sit and wait" for an actor to finish starting? I want to give a consumer outside the system the ability to start actors.. but if they start making calls before that actor is done with all of its initialization, things don't work right.
I realize this probably goes against the very heart of writing "non-blocking" code... but I just want to ensure people a) don't get inconsistent results and b) have to use thread:sleep to wait for actors to start (like when I'm writing acceptance tests)
Kevin Hoffman
@autodidaddict
I'm looking at Condition/Waiter - neither of which are sync/send so I can't send them to another actor so the actor can let me know when to stop waiting.
Erik
@strtok
Hello! I have a daemon where configuration (e.g. what address to bind to) for an actix server can be changed at runtime, so I need to start/stop actix servers from a non-async thread anytime the config changes. This means I need a way to tell an actix runtime to shutdown so I can start a new one. Is there an idiomatic way of communicating/stopping async code from non-async code? channels?
2 replies
Kesav Kolla
@kesavkolla
Hi I am trying to build a server which listens on multiple ports one port is for HTTP and other ports are for custom TCP/IP protocols. I'm using tokio::main and using tokio.spawn a thread to start actix web server. Is there a snippet someone can share on how to start actx web server from a tokio thread?
4 replies
Kunjan Dalal
@kunjee17
What is the strategy actix users are using to serve static data with deployed application? Like they are copying data with build.rs or something else. or content is served using in memory binary. Asking for things like config files, html, css and js.
It works fine with development, asking for deployment part only. eg. if I m using docker how I deploy static data with the same ?
6 replies
Kevin Hoffman
@autodidaddict
I can't seem to find a good, idiomatic example of how to call an async actor from an async actor? I want to invoke do_send during one service's service_started function
1 reply
Kevin Hoffman
@autodidaddict
from sync to async, I can do block_on(async move { ... }) .. but from async to async - I can't find an example of how to await that response
Ahmed Agabani
@agabani

Hi! I'm using actix_web::client to make several unique http requests in quick succession. Is there any documentation of best practices around the use of actix_web::client?

If there is no documentation around it. What is the recommended practice for my use case.
1) Is a long lived client reuse recommended, or should a new client be used for each HTTP request?
2) If client reuse is recommended, what limitations and gotchas should a developer be aware about?

6 replies
Malhar Vora
@vbmade2000
Does Actix create instance of each middleware per request ?
39 replies
Malhar Vora
@vbmade2000
Is there any difference between implementing middleware using Transform and Service Trait and using Middleware trait ?
3 replies
Erik
@strtok
I devised this insane method of being able to start and stop an actix server from non-async code. IUs this really the way to do this? Am I missing an easier way? https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1ce784f55b04d3f72c94de4b62113f48
7 replies
Leonardo Teteo
@Leoat12
Hi! I'm using actix_web as a server for some simple load tests using Docker in a very limited container with just 128m of memory and 1 cpu. The test involves reading a csv file, manipulating it and give the result. The file is around 40 mb and in a constrained environment like that it takes some seconds and it should anyway. However, some requests are finished with 408. All timeout configurations I found don't seem related and the benchmark tool don't drop requests. There are any configuration I'm missing here?
Malhar Vora
@vbmade2000
How route table can be access ? I want to log name of the handler function associated with route.
8 replies
Antoine D
@antoine-de
Hi, I'm looking for a way to run a Futur and wait for completion in the main thread with Actix. SystemRunner::block_on seems to fit my needs, but I think I'm missing something, I don't see a way to get a systemrunner :/ What is the right way to do this ?
24 replies
Kunjan Dalal
@kunjee17
Actix is very active in development and managed by wonderful community. But history do catch up many times. As, many people (not me for now :P ) are still afraid to move it production because long back author did pulled the project down. Just a humble suggestion to maintainers to make some good noise that Actix is not going to anywhere at least not soon enough.
1 reply
twiclo
@twiclo
Can someone help me understand what I'm doing wrong with this udp send_to I'm trying to do?
https://p.twil.cx/iqa.rs
1 reply
x04
@x04
What would be the proper way to run async code in an actix websocket handler?
12 replies
Linus Behrbohm
@mankinskin
Can SyncContext implement AsyncContext? I need it to work with actix_interop and to use AsyncContext::notify()
23 replies
matrixbot
@matrixbot
Mike Cardwell If I have a request handler that takes a while to run and return values, is there any way of detecting whilst it's running if the client is still connected?
Mike Cardwell I.e:

Mike Cardwell ```

[get("/test")]

async fn timer() -> impl Responder {
// Simulate some work by looping 10 times and sleeping for 1 second
for n in 0..10 {
delay_for(Duration::from_secs(1)).await;
// Check here if client is still connected. If not, bail out early
}
"Test"
}
```

Cyprien Taque
@ctaque

Hello, beginner question : I want to run actix in tokio runtime.
So I found this :

    let local = tokio::task::LocalSet::new();
    let sys = actix_rt::System::run_in_tokio("server", &local);
    let server = HttpServer::new(move || {...}).await?;
    sys.await?;

&local needs to be tokio::task::local::LocalSet but module tokio::task::local is private. How should I do ?

6 replies
fakeshadow
@fakeshadow
I think we should get rid of these. https://github.com/actix/actix-net/blob/704af672b9ae1b80c1bbaf5cf2dfedfd6e5a8e21/actix-rt/src/arbiter.rs#L26. and spawn futures directly to tokio
8 replies
ghostff
@Ghostff

Am using https://github.com/rambler-digital-solutions/actix-web-validator But I don't know how to extract the error.

let message = match response.status() {
        StatusCode::METHOD_NOT_ALLOWED => "Method Not Allowed.",
        StatusCode::BAD_REQUEST => {
            match response.response().error() {
                Some(e) => format!("{:?}", e),
                // Output: 
                /* Error in response: Validate(ValidationErrors({"password": Field([ValidationError { code: "403", message: Some("Password must be above 6 characters long."), params: {"value": String("foo"), "min": Number(6),
 "max": Number(255)} }])})) */
                None =>  String::from("Unknown Error")
            }
        },
        _ => "An Error Occurred."
    };

Am trying to extract the validation message.