Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Jan 25 18:02

    robjtede on win-fs-trav

    (compare)

  • Jan 25 18:02
    robjtede closed #2607
  • Jan 25 18:02
    robjtede commented #2607
  • Jan 25 17:52
    aliemjay commented #2607
  • Jan 25 16:47

    github-actions[bot] on gh-pages

    Deploying to gh-pages from @ 1… (compare)

  • Jan 25 16:44

    robjtede on master

    prevent drive traversal in wind… (compare)

  • Jan 25 16:31
    robjtede synchronize #2607
  • Jan 25 16:31

    robjtede on win-fs-trav

    lol (compare)

  • Jan 25 16:05
    robjtede synchronize #2607
  • Jan 25 16:05

    robjtede on win-fs-trav

    lol (compare)

  • Jan 25 16:02
    robjtede opened #2607
  • Jan 25 16:02

    robjtede on win-fs-trav

    add test for windows drive trav… (compare)

  • Jan 25 15:03
    robjtede unassigned #1350
  • Jan 25 12:14
    robjtede commented #1350
  • Jan 25 12:14
    robjtede milestoned #1350
  • Jan 25 12:14
    robjtede demilestoned #1350
  • Jan 24 16:22
    robjtede edited #2606
  • Jan 24 16:22
    robjtede edited #2606
  • Jan 24 16:22
    robjtede labeled #2606
  • Jan 24 16:22
    robjtede labeled #2606
Yoric
@dotyoric:matrix.org
[m]
(now attempting to deploy a MVP)
quambene
@quambene

Consider an endpoint for post requests via post macro (https://docs.rs/actix-web/3.3.2/actix_web/attr.post.html). For example using #[post("/login")].

Is it possible to define the path elsewhere like const LOGIN: &str = "/login" and use it in the post macro? I would like to collect all endpoints at one place.

I couldn't make it work. I tried #[post(LOGIN)] and #[post("{}", LOGIN)] as well as #[post("{LOGIN}")] but without success.

Cheers

3 replies
robjtede
@robjtede:matrix.org
[m]
rkfox
@rkfox
Are wildcard routes supported? ie.
#[get("/files/*"
I'm not sure what happened; I thought this was working before. But now this wildcard route is not working.
rkfox
@rkfox
I was using one of the betas previously; maybe v4.0.0-beta.4 but I can't seem to get it working again. I think it broke after upgrading to beta.8.
1 reply
Stepan Kuzmin
@stepankuzmin

Hi everyone!

I'm getting thread panic in runtime after upgrading actix from 0.10 to either 0.11 or 0.12 with

thread 'main' panicked at '`spawn_local` called from outside of a `task::LocalSet`', /Users/stepan/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.12.0/src/task/local.rs:305:18

The only change I've made to my code is that I've removed the name argument from the actix::System::new:

let sys = actix::System::new();

let db = SyncArbiter::start(3, move || DbActor(pool.clone()));
let coordinator: Addr<_> = CoordinatorActor::default().start();

HttpServer::new(move || {
    let state = create_state(db.clone(), coordinator.clone(), config.clone());

    let cors_middleware = Cors::default().allow_any_origin();

    App::new()
        .data(state)
        .wrap(cors_middleware)
        .wrap(middleware::NormalizePath::new(
            middleware::normalize::TrailingSlash::MergeOnly,
        ))
        .wrap(middleware::Logger::default())
        .wrap(middleware::Compress::default())
        .configure(router)
})
.bind(listen_addresses.clone())
.unwrap_or_else(|_| panic!("Can't bind to {}", listen_addresses))
.keep_alive(keep_alive)
.shutdown_timeout(0)
.workers(worker_processes)
.run();

sys.run()

My current dependencies are

actix = "0.12"
actix-cors = "0.5.4"
actix-rt = "1.1"
actix-web = "3.3.2"

What am I missing?

Stepan Kuzmin
@stepankuzmin

I got it

actix 0.12 depends on actix-rt 2 which is not compat with actix-rt 1

Namely this pattern would not work anymore.
let sys = System::new();
HttpServer::run();
Instead it should be changed to something like this.
System::new().block_on(some_future)

Izdihar
@tengkuizdihar:matrix.org
[m]
So, I'm using actix + diesel for one of my hobby project. What do you guys think about using block_on when using diesel?
5 replies
Given that I use web::block
Well thank you for the insight. I've seen some questions online being asked about this and they said that I'm going to use the same thread pool as actix and might block the process if there's enough load? That's how I remember it anyway.
2 replies
Izdihar
@tengkuizdihar:matrix.org
[m]
I guess I need to get a deeper understanding on how this block thing works, given I'm a bit blind on this topic
2 replies
robjtede
@robjtede:matrix.org
[m]
It's come to our attention that the MSRV for Actix Web v3 was recently increased by a dependency update: http v0.2.5. It would now be Rust 1.46. If you want to keep the old MSRV 1.42 it should be as easy as adding an exact dep in your Cargo.toml: http = "=0.2.4".
asonix (he/they)
@asonix:matrix.asonix.dog
[m]
I tried implemeting io-uring support in my image hosting api and it works
1 reply
i think it's a tiny bit slower than using tokio::fs::File but that's because i implemented AsyncRead, AsyncWrite, and AsyncSeek on a wrapper of tokio_uring::fs::File and reading and writing copies all the bytes around
so maybe if I reworked my program to play more directly to io-uring i could squeeze out some more performance
Maybe implementing Stream<Item = Bytes> on tokio_uring::fs::File could work, since you could read directly into a Vec<u8> which you can magic into a Bytes at little cost
fakeshadow
@fakeshadow
I observer dobule the throughput with high concurrent file streaming.
I tried with 12core and 2048 connections.
I also found some tips to optimize the performance on system side. Like make the memlock setting bigger. disable cpu mitigation. and use newest kernel release. Right now 5.15-rc could be the fastest for io-uring. I recall earlier some people claim to achieve a new peak of IOPS using it.
fakeshadow
@fakeshadow
BTW I have not tested it on regular hard drive but I believe the best use case for it is at least a decent nvme ssd.
Vince
@vlmutolo:matrix.org
[m]

Quick question: the actix docs for "shared mutable state" (here) suggest to use a Mutex from std::sync to make types thread-safe. This seems like it could be problematic since Mutex can block the current thread.

I don't know much about the internals of Actix. Is this just not a problem?

22 replies
gzp-crey
@gzp-crey
Is there some utility function to url (percent) encode/decode strings ? I'd not pull in another crate if actix_web has one already.
1 reply
Ashanti Mutinta
@AshantiMutinta
Quick question, I am doing some monitoring of my server which doesn't really have state. One thing I am finding is that my virtual memory usage is pretty high. I was wondering if anyone has some insight into this or has come across this in anyway? Using actix-web 4.0.0.beta
1 reply
Tanner Wilcox
@twiclo
What am I doing wrong to get this error back from curl?
(Check thread)
2 replies
Simon Oualid
@soualid
hello, I am looking for a documentation on how to migrate multipart upload to actix4
1 reply
YarikHG
@YarikHG
Hello everyone! I made a small web application based on Actix. Now I want to make multiple language versions. How can I get the browser language using Actix? I would like to know the main preferred language of the user, for example "en", then I can give pages in English
3 replies
christian
@christian:matrix.boseck.net
[m]

Hello, I try to write a function that returns an App instance this is usefull for my integration tests.

I used the extract into method, function i my ide to get the function declaration.
This is what I got:

pub fn construct_app() -> App<impl ServiceFactory<Request=ServiceRequest, Response=ServiceResponse<StreamLog<_>>, Error=Error, Config=(), Service=_, InitError=(), Future=_>, StreamLog<_>> {
    let pool = application_config.pg.create_pool(NoTls).unwrap();

    let cors = Cors::permissive();

    let app = App::new()
        .wrap(
            middleware::DefaultHeaders::new()
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Headers", "*"))
        .wrap(cors)
        .wrap(Logger::default())
        .service(hosts::all_hosts)
        .service(hosts::new_host)
        .service(hosts::get_host_by_id)
        .service(hosts::save_host)
        .service(hosts::delete_host)
        .service(ips::list)
        .service(ips::list_networks)
        .service(macs::list)
        .data(pool.clone());

    return app;
}

Now rust cant resolve ServiceFactory and even if I add this dependency (what I don't want) other parameter are missing as well.
What are the actual type that would be returned I onestly don't know how to figure that out, or is there another way to do this.
Can you guys help me?

2 replies
YarikHG
@YarikHG
I am storing the data entered by the user in app_data. As long as I was working on a local machine and the application was only testing 1 user everything was fine. But after deploying the app https://polar-journey-32537.herokuapp.com/ I found that ALL users save their data to the same structure inside app_data. Data from different users is mixed in one structure. (The year of birth of one user is added to the month of birth of the other user, and so on). How can I provide each user with their personal .app_data or their personal structure in app_data? Perhaps my question is amateurish, but I'm new to programming. Here is my code: .app_data (web :: Data :: new (Mutex :: new (UserInputData :: new ())). сlone ())
2 replies
Konrad Gołuchowski
@kodieg

Hi, I have a question. I'm using #[post] macro to generate register endpoint. Is it possible to somehow alias this endpoint with different path?

For example:

#[post("/a/path"]
fn test() -> impl Responser {
  "Ok"
}

I'd like to have this test function also exposed as /b/another/path. Is it possible?

gzp-crey
@gzp-crey
What is the status for 4.0-beta ? It is beta for a really long time. What's missing to get it released as non-beta ?
Is there some tracking ticket for it ?
2 replies
Johannes-Maria Frank
@jmfrank63

Hi all, I wrote these small piece of testing code to get access to the internal web:Data<T>:

#[actix_web::test]
    async fn test_crawl_does_get_root_page_links() {
        let set: HashSet<Url> = HashSet::default();
        let (server, port) = spawn_server(set).unwrap();
        let client = reqwest::Client::default();
        let response = client
            .get(format!("http://localhost:{}/", port))
            .send()
            .await
            .expect("Failed to execute the request");
        assert_eq!(response.text().await.unwrap(), root_body(&port));
        server.stop(false).await;
    }

    fn spawn_server(set: HashSet<Url>) -> Result<(Server, u16), std::io::Error> {
        let (server, port) = run_server(set).unwrap();
        let _ = tokio::spawn(server.clone());
        Ok((server, port))
    }

    fn run_server(set: HashSet<Url>) -> Result<(Server, u16), std::io::Error> {
        let listener = TcpListener::bind("localhost:0").expect("Failed to bind to random port");
        let port = listener.local_addr().unwrap().port();
        let server = HttpServer::new(move || {
            App::new()
                .app_data(web::Data::new(set.clone()))
                .app_data(web::Data::new(port.clone()))
                .wrap_fn(|request, server| {
                    let app_state = request.app_data::<web::Data<HashSet<Url>>>();
                    let s = app_state.unwrap().get_ref();
                    println!("{}", s.len());
                    let fut = server.call(request);
                    async move {
                        let response = fut.await.unwrap();
                        Ok(response)
                    }
                })
                .wrap_fn(|request, server| {
                    let fut = server.call(request);
                    async move {
                        let response = fut.await.unwrap();
                        Ok(response)
                    }
                })
                .route("/", web::get().to(root_page))
        })
        .listen(listener)?
        .run();

        Ok((server, port))
    }

The idea was to have two of these wrapped middleware running, with the first registered running last and thus containing the modifications of the first request, which doesn't do any modifications. However, I do not understand how this is supposed to work. Once the outer layer has run, I have a response. The inner layer doesn't know anything about this response and creates a response on its own. I am sure it is my understanding that is lacking, could someone explain to me how I get these to middlewares chained? Maybe the whole idea is flawed, but it is my first success to actually access web:Data<T> from a unit test. I am open to any suggestions ;-)

I'd like to add the actual main code has the HashSet wrapped in a structure and with a Mutex around. I thought just for testing if the hashset is actually filled I leave this out for now. My question is around the chaining of middleware with clousres.
Johannes-Maria Frank
@jmfrank63
@kodieg I don't have a solution for this, but have you tried to expand the macro? IntelliJ can do it, and so I think can VSCode but it is a cargo subcommand you can install, instructions are here: https://github.com/dtolnay/cargo-expand
gzp-crey
@gzp-crey
actix-files has the Files server. How can I restrict the path to leave same "sandboxed" directory (ex to avoid requests like ../../etc/passwd) ?
Johannes-Maria Frank
@jmfrank63
@gzp-crey Huh? That is possible? Have you tried it? From the look at the documentation, it seems to me as if the path is canonicalized, so this shouldn't be possible. If you are concerned, however, and want a real sandbox, you could always run the single binary rust compiles to in a chroot environment, a well-known technique for ages.
3 replies
Mehmet ERİBOL
@mehmeteribol_gitlab
Hi. I am planning to create subdomain system with actix-web. I dont how i handle it but my plan is, creating web server forevery subdomain, every one of them will use actix-redis session middleware. Are they will use the same session data or, do i have find another way?
for example, like google apps?
robjtede
@robjtede:matrix.org
[m]

if they're connected to the same backend redis server then the auth with work across domains (assuming the cookies are set up correctly)

for subdomains, there is a Host guard (see docs) which would allow you to use the same AW server for multiple subdomains

otherwise, if you want to use separate servers, then a reverse proxy set up with Traefik or Nginx is a good route to explore

Mehmet ERİBOL
@mehmeteribol_gitlab
They are all using same host resource(postgres, redis etc). Thank you so much.
Kunjan Dalal
@kunjee17
if I m having static site generated using separate framework like nextjs and I want to map files to url? What is best way to do it with actix and actix-files. I can easily map index files and works well when there is hash routing and SPA. But I couldn't make it work with generated static site.
2 replies
ieow
@ieow

Hey guys,
I am trying to use SSE (server send events) with code below
when browser try to subscribe, it is just stuck till timeout. (req timeout)

#[get("/events")]
async fn event( broadcaster: web::Data<Mutex<Broadcaster>>) -> impl Responder {
    println!("enter events locking broadcaster"); 
    let mut map : HashMap<String, String> = HashMap::new();
    map.insert("status".to_string() , "connected".to_string());
    let rx = broadcaster.lock().unwrap().new_client( map );
    println!("add newclient");

    HttpResponse::Ok()
    .header("content-type", "text/event-stream")
    // .no_chunking(64)
    .streaming(rx)
}

I trace it, it reach HttpResponse::Ok and stuck there
I wonder if the no_chunking is required?

1 reply
Kunjan Dalal
@kunjee17

May be mostly dumb question.

if I want to achieve organizations/{id}/providers/{id} url. Then I need to add providers config on organizations/{id} web scope ? or I am thinking completely wrong ?

7 replies
Dmitry Miasnenko
@clowzed
Hello everyone! I need too implement a function which runs in interval. I've found solutions like actix_web::rt::spawn and others but I cannot access app_data inside this function. Any suggestions?
2 replies
Ashanti Mutinta
@AshantiMutinta
I'm looking for some resources were I can read about the actix event loop. Bonus points if it also mentions how this corresponds with actix-web
Ashanti Mutinta
@AshantiMutinta
Woops found this thank you all https://actix.rs/book/actix/sec-5-arbiter.html
Ashanti Mutinta
@AshantiMutinta
Actix-web uses the number of logical cpus to allocate the number of workers. If I use an actor with an async arbiter, where does that execute?
1 reply
AsyncContext* I guess
Ashanti Mutinta
@AshantiMutinta
Hmmmm I start it in the main of my actix-rt::main
1 reply
Actix_web::main*