by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 19:54
    cybuch commented #1469
  • 19:52
    cybuch commented #1469
  • Jun 03 17:53
    Dowwie commented #1550
  • Jun 03 17:43
    fafhrd91 commented #1550
  • Jun 03 15:41
    mamcx closed #1517
  • Jun 03 15:41
    mamcx commented #1517
  • Jun 03 08:41
    GopherJ commented #1460
  • Jun 03 08:41
    GopherJ commented #1460
  • Jun 03 01:43

    JohnTitor on master

    Remove AppVeyor config Merge pull request #1547 from J… (compare)

  • Jun 03 01:43
    JohnTitor closed #1547
  • Jun 02 21:07
    Pzixel commented #1045
  • Jun 02 20:29
    Zhappa commented #1045
  • Jun 02 20:28
    Zhappa commented #1045
  • Jun 02 20:12
    botika commented #942
  • Jun 02 19:15
    codecov-commenter commented #1547
  • Jun 02 18:40
    JohnTitor synchronize #1547
  • Jun 02 18:14
    JohnTitor labeled #1552
  • Jun 02 18:14
    JohnTitor labeled #1552
  • Jun 02 17:35
    Pzixel commented #1045
  • Jun 02 17:04

    robjtede on master

    Fix typo in timeout error displ… (compare)

sentryadam0000345
@sentryadam0000345
does anyone know if this works with the latest version of actix?
Skyler
@wgahnagl
hey!
I'm trying to set up a simple project with actix right now, and is there a way to start the actix server, and then attach an actix web server to it later?
I can make a new system with system::new and then call run() on that, but without a parameter, does it do anything?
I was thinking it would be a good idea to start the actix server from something independent from the web portion, so if that fails I'll still be able to use the runtime for command line things like talking to the db or something.
Is that even a good idea to do?
KOKOU AFIDEGNON
@afidegnum
anyone familiar with https://docs.rs/jsonapi/ ? how do i build the relationship and attributes?
Peanuts
@peanut996
image.png
1 reply
image.png
i add the actix_web::extrator but it is a private mod
1 reply
V584
@V584
Is there anything in this that seems wrong? I'm trying to query a database but it just hangs forever, works everywhere else except this middleware (Using Postgres with SQLx)
            .wrap_fn(|req, srv| {
                let pool = req.app_data::<PgPool>().unwrap();
                Box::pin(async {
                    let uid = req
                        .get_session()
                        .get::<i32>("uid")
                        .unwrap_or(Some(0))
                        .unwrap_or(0);
                    if uid > 0 {
                        let set_last_seen = sqlx::query!(
                            r#"
                                    UPDATE users SET site_last_seen = current_timestamp WHERE id = $1
                            "#,
                            uid
                        )
                        .execute(pool.get_ref())
                        .await; //hangs here

                        if let Err(_) = set_last_seen {
                            error!("Unable to set last seen for u{}", uid);
                        }
                    }
                });
                srv.call(req)
            })
matrixbot
@matrixbot
Aode (Lion) He/They the async block doesn't ever run. You put it in a box & then it's dropped. You can try moving srv.call(req) inside the block. or you can actix_rt::spawn the block
V584
@V584
I'm not sure how I looked that over, thank you!
SavioSantos0808
@SavioSantos0808
Hi People, I am trying to create an Ionic App to consume an API using Axtix Web. I enabled CORS but Ionic does not identify it. Can someone help me?
image.png
image.png
Example Angular, on Stackblitz.
Thank you very much in advance.
fakeshadow
@fakeshadow
try remove the allow_origin if you want a wildcard for cors
SavioSantos0808
@SavioSantos0808
It worked, thanks.
Geometrically
@Geometrically
what library should you use when using MongoDB
somewheve
@somewheve
``` ctx.wait((async {
let codes = codes.await.unwrap();
let x = CodeList { code: 200, topic: "code_list".to_string(), data: codes, typed: typed.clone() };
let mm = serde_json::to_string(&x).unwrap();
ctx.text(mm)
}).into_actor(self));
I try to use ctx.text in the ctx.spawn? but error error[E0477]: the type `actix::fut::FutureWrap<impl core::future::future::Future, websocket_rs::RealtimeServer>` does not fulfill the required lifetime --> src\websocket_rs.rs:188:29 | 188 | ctx.wait((async { | ^^^^ | = note: type must satisfy the static lifetime so how can add life time to avoid this error?
Rob Ede
@robjtede
that's a great result, glad theyve introduced the composite score
Chris Morin
@cmtm_gitlab

I'm confused about the intersection of async code and multithreading. If I do something like this:

futures::join!(
    HttpServer::new(|| App::new().service(...)
            .bind("127.0.0.1:8080")?
            .workers(4)
            .run(),
    some_other_future);

actix will spawn 4 threads. Which thread will some_other_future run in? The first one? None of them?

4 replies
Chris Morin
@cmtm_gitlab
What's the difference between actix_web::App::data() and actix_web::App::app_data ? Don't they both set thread-specific data?
2 replies
Chris Morin
@cmtm_gitlab
Does anyone know why Application state isn't mutable? There's a copy of it per worker thread, so I would've thought there wouldn't be any concurrency concerns. The documentation described how to achieve shared mutable state with a Mutex (which has interior mutability), but if I want to have non-shared state between workers, why do I still need to use an interior mutability wrapper like std::cell::Cell ?
1 reply
Mitchell Tannenbaum
@naturallymitchell
@everyone , Here's a Discord server with well-organized channels for planning and talking about Actix-related projects... Discord also has voice-and-video channels for high-definition conversations! Come check it out and post your Rust content!
https://discord.gg/2A9h75V
Nish Tahir
@nishtahir
Hi friends, does anyone know of a good way to get some typesafety in responses in handler functions?
I have something like this
#[get("/path")]
fn test() -> Result<HttpResponse, Error> { ... }
I'd like to get something similar to the impl Future<Json<Type>, Error> in V1 where I have some typesafety in the response
Ideally, I'm looking for something like Result<HttpResponse<Type>, Error> { ... }
1 reply
Eric Methot
@macprog-guy

Hello,
Here is a little snippet from the Actix website regarding Resources:

Resource configuration
Resource configuration is the act of adding a new resources to an application. A resource has a name, which acts as an identifier to be used for URL generation. The name also allows developers to add routes to existing resources.

I'm especially looking to add routes to an existing resource but even after having looked at the source I still can't find a way to add a route to a named resource after it has been defined.

What I'm trying to do is something along the lines of:

  • Resource foo on path /foos
  • Later when defining the resource bar on path /bars, I also want to add the route /foos/{parent_id}/bars to the foo resource.

Any ideas on how to do this?

4 replies
Dennis Kievits
@elertan

I have a question related to actix-extras, actix_web_httpauth in particular.
I'm trying to parse a Bearer authorization header in an optional fashion. Right now by parsing the value you either get the parsed value or a parse error. However my endpoint needs to support both authorized and non authorized calls, so if the auth header is set, I want to parse it, and if it doesn't then don't parse it at all.

How do I go about this? Manually check if the header exists before trying to parse? Or is there a optional version?

1 reply
Cyprien Taque
@ctaque
Hey guys, I'm having trouble to make this function work, I don't know why it does not work.. :
#[derive(serde::Deserialize, serde::Serialize)]
struct GetProjectInfo{
    id: u32,
}
#[get("/projects/{id}")]
async fn index(info: web::Path<GetProjectInfo>) -> impl Responder {
    use ctprods::schema::projects::dsl::projects;
    let connection = establish_connection();
    let project = projects.find(info.id.into()).first(&connection).map_err(|err| match err {
        Error::NotFound => HttpResponse::NotFound().body(err),
        _ => HttpResponse::InternalServerError().body(err)
    });

    HttpResponse::Ok().body(project)
}
2 replies
the error is : ^^^^ the trait 'std::convert::From<diesel::result::Error>' is not implemented for 'actix_http::body::Body''
on every body()
Cyprien Taque
@ctaque
I tried this :

struct GetProjectInfo{
    id: u32,
}
#[get("/projects/{id}")]
async fn index(info: web::Path<GetProjectInfo>) -> impl Responder {
    use ctprods::schema::projects::dsl::projects;
    let connection = establish_connection();
    let project = projects.find(info.id.into()).first(&connection).map_err(|err| match err {
        Error::NotFound => HttpResponse::NotFound().body(err),
        _ => HttpResponse::InternalServerError().body(err)
    });

    match project {
        Ok(project) => HttpResponse::Ok().body(project),
        Err(err) => HttpResponse::InternalServerError().body(err)
    }

}
3 replies
but I still have :
^^^ the trait std::convert::From<actix_http::response::Response> is not implemented for `actix_http::body::Body
Cyprien Taque
@ctaque
Ok so this is nearly working :
async fn index(info: web::Path<GetProjectInfo>) -> impl Responder {
    use ctprods::schema::projects::dsl::projects;
    let connection = establish_connection();
    let project = projects.find(info.id.into()).first(&connection).map_err(|err| match err {
        Error::NotFound => HttpResponse::NotFound().body(err),
        _ => HttpResponse::InternalServerError().body(err)
    });

    match project {
        Ok(project) => HttpResponse::Ok().body(project),
        Err(err) => err
    }

}

but on these lines :

        Error::NotFound => HttpResponse::NotFound().body(err),
        _ => HttpResponse::InternalServerError().body(err)

I have this error :

    _ => HttpResponse::InternalServerError().body(err)
   |                                                  ^^^^ the trait `std::convert::From<diesel::result::Error>` is not implemented for `actix_http::body::Body`
19 replies
Carl Fredrik Samson
@cfsamson
Hi. I have a few questions about actix which I couldn't find a good answer to:
  1. What are the major differences between using tokio runtime directly and actix_rt? I know actix_rt builds on tokio but what does it do on top of tokio preventing using it directly?
  2. Can someone explain the Arbiters role in actix? I have read about Arbiters in theory but I find it hard to relate to what actix actually uses them for (and when I should use them)?
19 replies
Dessalines
@dessalines
Does anyone know how to add headers such as cache-control to actix_files / static content?
Marcelo Fornet
@mfornet

Hi everyone! I am interested in running several actors concurrently (in separate threads) but ideally using a thread pool.
I learnt about SyncArbiter which is useful to spawn several instance of an actor on separate threads, but it doesn't fit my final goal, which is having less threads than actors.

One possible solution is create one Arbiter (which creates a thread) and then subscribe each actor to one of the arbiters, this "solves" the problem, but not in the best way. The drawback is that resources might not be divided evenly among threads,
for example, suppose there are 4 actors (A, B, C, D) and 2 threads (U, V). A, B are running on thread U, and C, D are running on thread V. It is possible that C, D become idle at some point, and in that case thread V will be idle, even when A and B both might be competing for thread U. So ideally, all actors should be able to run on all thread.

I found the crate threadpool which is among the lines about what I want to achieve, but it can't be used with actix model. I'm wondering if something like this already exists for actix already?

17 replies
deklanw
@deklanw
out of curiosity, anyone know what the drogon framework is doing to beat actix so handily in the new TechEmpower benchmarks? In "Multiple queries" and "Data updates" it's around twice as fast as actix.
13 replies
yiv
@yiv
Help:if I wait to read a channel in one actor handle, then all other handle request is blocked ?
Martin André
@Martichou

Hi, I'm facing a little issue. I'm trying to fetch a file from a S3 server, the file is available at an URL (public).
And Actix is acting as a proxy to return the data of the image (at least it should), but I'm getting a 413 Reached payload limit..

I don't know how nor what I can do to solve this.. Is using Rusoto instead to get a Bytestream and then stream that bytestream to the user requesting the file possible?
My current code looks like that:

pub async fn get_one(
    req: HttpRequest,
    body: web::Bytes,
    db: web::Data<Pool>,
    client: web::Data<Client>
) -> Result<HttpResponse, Error> {
    let conn = db.get().unwrap();
    let user_id_f = get_user_id(&req).unwrap().parse::<i32>().unwrap();
    let filename = sanitize_filename::sanitize(req.match_info().query("filename"));
    let item_f = images.filter(realname.eq(&filename).and(user_id.eq(user_id_f))).select(fakedname).first::<String>(&conn);
    if item_f.is_ok() {
        let url = format!("https://unswayed.eu-central-1.linodeobjects.com/{}", item_f.unwrap());
        let mut forwarded_req = client.request_from(url, req.head());
        // Modify header for the S3 restriction
        forwarded_req.headers_mut().clear();
        let mut res = forwarded_req.send_body(body).await.map_err(Error::from)?;
        let mut client_resp = HttpResponse::build(res.status());
        for (header_name, header_value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
            client_resp.header(header_name.clone(), header_value.clone());
        }
        Ok(client_resp.body(res.body().await?))
    } else {
        Ok(HttpResponse::new(StatusCode::UNAUTHORIZED))
    }
}
Alex Stapleton
@public
I am trying to parse a form encoded request body with Actix Web. I can use a web::Form<T> argument in my handler to parse it but I also want to get the raw request body at the same time. If I add body: String, then this either results in body being empty (if I put it after my form) or the form failing with a Parse error.
5 replies
matt-vib
@matt-vib

Hi, has anyone managed to use either Redis pipelines or MULTI with RedisActor from the actix-extras library (https://github.com/actix/actix-extras/tree/master/actix-redis)?
I tried formatting a MULTI command with the resp_array macro along the lines of

redis.send(Command(resp_array!["MULTI", "EXEC", "GET", key.as_str(), "EXEC", "TTL", key.as_str()])

but I get a runtime error saying it's the wrong number of arguments for 'multi' command. Same if I try using .append on the vector to add the parameters. I cannot find any relevant docs/samples, so any help would be appreciated

fakeshadow
@fakeshadow
Maybe you should check the redis-async-rs repo for some info. Last time I saw it didn't support transactions therefore you can't use multi or exec
matt-vib
@matt-vib
thanks, that confirms what I suspected looking at the code. I guess I might end up creating my own actor using a different underlying redis client library