Actix Documentation

repository·main·Indexed 42 days ago

https://github.com/actix/actix-website

Documentation for the Actix actor framework, covering the Actor Model, actor lifecycles, and communication via Addresses and Recipients. Includes guides on implementing the Actor and Message traits, handling messages with Handler<M>, and using the #[actix::main] attribute for asynchronous execution in Rust (version 1.40.0 or higher).

Tokens
27.7K
Snippets
89
Records
128
Agent score
53%

What's inside Actix

  1. Explore community-maintained Actix crates

    main

    The Actix ecosystem includes several third-party crates maintained by the community. These crates provide specialized functionality such as rate-limiting, authorization, authentication, and specialized extractors.

    Warning: These are third-party crates. The Actix project is not involved in their development, maintenance, support, review, or distribution, and provides no warranty for them.

    | Crate | Description |
    | :--- | :--- |
    | [actix-web-lab](https://crates.io/crates/actix-web-lab) | Experimental extractors, middleware, and other extras for possible inclusion in Actix Web. |
    | [actix-form-data](https://crates.io/crates/actix-form-data) | Multipart form data from actix multipart streams. |
    | [actix-governor](https://crates.io/crates/actix-governor) | Rate-limiting backed by governor. |
    | [actix-casbin](https://crates.io/crates/actix-casbin) | Authorization library that supports access control models like ACL, RBAC & ABAC. |
    | [actix-ip-filter](https://crates.io/crates/actix-ip-filter) | IP address filter. Supports glob patterns. |
    | [actix-web-static-files](https://crates.io/crates/actix-web-static-files) | Static files as embedded resources. |
    | [actix-web-grants](https://crates.io/crates/actix-web-grants) | Extension for validating user authorities. |
    | [aliri_actix](https://crates.io/crates/aliri_actix) | Endpoint authorization and authentication using scoped OAuth2 JWT tokens. |
    | [actix-web-flash-messages](https://crates.io/crates/actix-web-flash-messages) | Support for flash messages or one-time notifications in `actix-web`. |
    | [awmp](https://crates.io/crates/awmp) | An easy to use wrapper around multipart fields for Actix Web. |
    | [actix-hash](https://crates.io/crates/actix-hash) | Hashing utilities for Actix Web. |
    | [actix-bincode](https://crates.io/crates/actix-bincode) | Bincode payload extractor for Actix Web. |
    | [sentinel-actix](https://crates.io/crates/sentinel-actix) | General and flexible protection for Actix Web. |
    | [actix-telepathy](https://crates.io/crates/actix-telepathy) | Build distributed applications with `RemoteActors` and `RemoteMessages`. |
    | [apistos](https://crates.io/crates/apistos) | Automatic OpenAPI v3 documentation for Actix Web. |
    | [actix-web-validation](https://crates.io/crates/actix-web-validation) | Request validation for Actix Web. |
    | [actix-jwt-cookies](https://crates.io/crates/actix-jwt-cookies) | Store your data in encrypted cookies and get it elegantly. |
    | [actix-ws-broadcaster](https://crates.io/crates/actix-ws-broadcaster) | A broadcaster library for actix-ws that includes grouping and conditional broadcasting. |
    | [actix-web-metrics](https://crates.io/crates/actix-web-metrics) | Metrics.rs integration for Actix Web. |
    | [actix-htmx](https://crates.io/crates/actix-htmx) | Htmx integration for Actix Web. |
    | [actix-web-helmet](https://crates.io/crates/actix-web-helmet) | A security middleware library for popular Rust web frameworks, with first-class `actix` support. |
    | [actix-mark](https://crates.io/crates/actix-mark) | An actix-web service for serving Markdown files as HTML. |
  2. Access Actix source code and documentation

    main

    The Actix ecosystem is open source and hosted under the @actix GitHub organization. You can find the core web framework, additional crates, and practical usage examples in the following repositories:

    • actix-web: The core web framework. API documentation.
    • actix-extras: A collection of additional crates for the Actix ecosystem.
    • examples: A dedicated repository containing various implementation examples.
  3. What is a SyncArbiter and when to use it

    main

    By default, Actix Actors run on the System's Arbiter thread using its event loop. For CPU-bound workloads or highly concurrent workloads where you need to process tasks in parallel, you should use a SyncArbiter.

    A SyncArbiter launches multiple instances of a single Actor type across a pool of OS threads. Note that a SyncArbiter can only host one specific type of Actor; you must create a separate SyncArbiter for every different Actor type you wish to run in a thread pool.

  4. What is an Arbiter and how does it work?

    main

    An Arbiter provides an asynchronous execution context for Actors, functions, and futures. While an Actor contains a Context for its own state, the Arbiter hosts the environment where that actor actually runs.

    Key characteristics of an Arbiter:

    • Single-threaded event loop: One Arbiter controls exactly one thread with one event loop. It queues tasks (via Arbiter::spawn, Context<Actor>::run_later, etc.) for execution on that single thread.
    • Concurrency model: Standard Arbiters do not support concurrency (they are single-threaded). To achieve concurrency, you must spin up multiple Arbiters using Arbiter::new, ArbiterBuilder, or Arbiter::start.
    • Actor Isolation: Actors are tied to the Arbiter they were spawned in and cannot move between them. However, Actors on different Arbiters can communicate seamlessly using standard Addr or Recipient methods, as the messaging mechanism is agnostic to the underlying Arbiter.
  5. Implement Graceful Shutdown

    main

    The HttpServer supports graceful shutdown when it receives a stop signal. Upon receiving a signal, workers are given a specific amount of time to finish serving active requests before being force-dropped.

    • Default Timeout: 30 seconds.
    • Configure Timeout: Use HttpServer::shutdown_timeout() to change this value.
    • Supported Signals:
      • CTRL-C (all OSes)
      • SIGINT (Force shutdown)
      • SIGTERM (Graceful shutdown)
      • SIGQUIT (Force shutdown)
    • Disable Signals: Use HttpServer::disable_signals() if you want to manage signal handling manually.
  6. Organize routes using Scopes

    main

    Scopes allow you to group routes that share a common root path. Scopes can be nested to create hierarchical URL structures. Variable path segments within a scope are accessible via HttpRequest::match_info() or the Path extractor.

    // Example of scoping routes
    App::new().service(
        web::scope("/users")
            .route("/show", web::get().to(show_user))
            .route("/{id}/profile", web::get().to(user_profile))
    );
  7. How Actor Context works

    main

    The Context is the internal execution environment for an Actor. It provides the interface for an actor to interact with the Actix runtime. Through the Context, an actor can:

    • Manage its Mailbox (capacity and message flow).
    • Access its own Address (Addr).
    • Control its Lifecycle (e.g., stopping execution via stop()).

    Every actor implementation must define its Context type, typically as Context<Self>.

  8. How the Actix connection lifecycle works

    main

    The Actix connection lifecycle is driven by three primary loops that manage the transition from a listening socket to a processed HTTP request:

    1. Accept Loop: Responsible for listening to sockets and accepting incoming client connections. This is primarily implemented in the actix-server crate via the Accept struct.
    2. Worker Loop: Once a connection is accepted, it is handed off to a Worker. The worker loop manages the lifecycle of that specific connection. This is also implemented in actix-server via the Worker struct.
    3. Dispatcher Loop: Within the Worker loop, a protocol-specific Dispatcher is spawned to handle application-level protocol processing (e.g., HTTP). This loop is responsible for the actual request/response handling.

    Understanding this flow helps in debugging connection issues, optimizing worker counts, or implementing custom protocol dispatchers.

  9. Best practices: User-facing vs. Internal errors

    main

    To prevent leaking sensitive system information, divide your application errors into two categories:

    1. User-facing errors: Errors intended to be read by the client (e.g., ValidationError). These should implement ResponseError and use messages that are helpful to the user.
    2. Internal errors: Errors that occur within the server environment (e.g., database connection timeouts, template rendering failures). These should be mapped to a generic InternalError before being returned to the user, ensuring specific technical details remain hidden.

    Pattern: Use map_err to transform internal failures into a generic user-facing error type.

  10. Configure Content-Encoding and compression

    main

    Actix Web can automatically compress payloads using the Compress middleware. Supported codecs include:

    • Brotli
    • Gzip
    • Deflate
    • Identity

    Automatic Compression

    By default, a response's Content-Encoding header is set to ContentEncoding::Auto. This performs automatic negotiation based on the client's Accept-Encoding request header.

    Disabling Compression

    To explicitly disable compression for a specific handler, set the Content-Encoding header to Identity.

    Serving Pre-compressed Assets

    If you are serving a body that is already compressed (e.g., pre-compressed static assets), manually set the Content-Encoding header on the response to bypass the automatic compression middleware.

  11. Start an Actor and communicate via Address

    main

    Actors can be started using Actor::start() (if the instance can be created immediately) or Actor::create() (if you need access to the context during creation). Both methods return an address object used for communication.

    • addr.send(msg): Sends a message and returns a future that resolves to the result.
    • addr.do_send(msg): Sends a message without waiting for a response.
    // Start the actor
    let addr = MyActor { count: 10 }.start();
    
    // Send a message and await the result
    let res = addr.send(Ping(10)).await;