actix-extras

repository·main·Indexed 21 days ago

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

A suite of specialized crates extending the Actix Web framework. Includes actix-cors for Cross-Origin Resource Sharing, actix-identity for user identity management, actix-session for session state via cookies and storage backends (Cookie, Redis), actix-limitation for Redis-backed rate limiting, actix-protobuf for Protocol Buffers payloads, and actix-settings for TOML and environment variable configuration.

Tokens
50.7K
Snippets
146
Records
198
Agent score
74%

What's inside actix-extras

  1. Overview of actix-extras crates

    main
    actix-extras is a collection of additional crates designed to support [Actix Web]. These crates provide specialized functionality such as CORS, identity management, rate-limiting, session management, and more, extending the core capabilities of the Actix ecosystem.
  2. Manage Actix Web settings with actix-settings

    main
    The actix-settings crate allows you to easily manage Actix Web configuration by loading settings from a TOML file and environment variables. It supports extending the default settings to include custom application-specific configurations, allowing you to combine Actix Web settings with your own server settings.
  3. Key features of actix-web-httpauth

    main

    When using actix-web-httpauth, you have access to:

    • Typed Headers: Specifically for Authorization and WWW-Authenticate.
    • Extractors: To pull authorization information directly from request headers in your handlers.
    • Middleware: To perform authorization checks globally or on specific scopes.
  4. How the root span works in tracing-actix-web

    main
    When an actix-web request is received, TracingLogger creates a root span. This span represents the entire lifecycle of the request. Any spans created during request processing (e.g., database queries, internal logic) will be child spans of this root span. You can attach structured properties (key-value pairs) to this span to enable powerful querying in observability tools like ElasticSearch, Honeycomb, or DataDog.
  5. Implement distributed tracing with OpenTelemetry

    main

    To trace a single request across multiple services (e.g., microservices), you should use the trace_id rather than the request_id. tracing-actix-web supports the OpenTelemetry standard and follows its semantic conventions for field names.

    Trace Propagation

    By enabling the opentelemetry_0_17 feature flag, tracing-actix-web automatically performs trace propagation. It attempts to extract the OpenTelemetry context from incoming request headers. If found, it sets this as the remote context for the current root span. This context can then be propagated to downstream dependencies (like HTTP or gRPC clients) if they are OpenTelemetry-aware (e.g., using reqwest-middleware and reqwest-tracing).

    Exporting Spans

    To export the root span and its children as OpenTelemetry spans, add tracing_opentelemetry::OpenTelemetryLayer to your tracing::Subscriber.

  6. Extend settings with Custom Settings

    main
    You can extend the available settings in actix-settings to combine standard Actix Web settings with your own application-specific settings. This is useful for managing a unified configuration object that covers both the web server and your business logic.
  7. How actix-session works

    main

    Session Management Overview

    actix-session provides a framework for attaching state to a set of requests from the same client using session cookies.

    Core Components:

    • Session Cookie: The cookie sent by the server via the Set-Cookie header and returned by the client via the Cookie header.
    • Session Key (Session ID): The content of the session cookie used to identify the session.
    • Session State: The actual data attached to the session.
    • SessionMiddleware: The underlying middleware that handles cookie management and instructs the storage backend to create, delete, or update session state.
    • Session: An extractor used in request handlers to access and modify the session state.
    • Storage Backend: A component (implementing the SessionStore trait) responsible for persisting the session state. Common backends include CookieSessionStore and RedisSessionStore.
  8. Quickstart: Add TracingLogger middleware to actix-web

    main

    To start collecting telemetry, mount TracingLogger as a middleware in your actix-web application using .wrap(TracingLogger::default()).

    use actix_web::{App, web, HttpServer};
    use tracing_actix_web::TracingLogger;
    
    fn main() {
        // Init your `tracing` subscriber here!
    
        let server = HttpServer::new(|| {
            App::new()
                // Mount `TracingLogger` as a middleware
                .wrap(TracingLogger::default())
                .service( /*  */ )
        });
    }
  9. Set up identity management with actix-identity

    main

    To use actix-identity for tracking user identity across requests, you must register both IdentityMiddleware and SessionMiddleware on your App.

    Important Middleware Ordering: actix-web invokes middleware in the OPPOSITE order of registration for incoming requests. Therefore, you must register IdentityMiddleware BEFORE SessionMiddleware so that the session middleware is processed first when a request arrives.

    1. Initialize a Key (preferably from a config/env var, not Key::generate() in production).
    2. Set up a session store (e.g., RedisSessionStore).
    3. Register IdentityMiddleware::default().
    4. Register SessionMiddleware.
    use actix_web::{cookie::Key, App, HttpServer, HttpResponse};
    use actix_identity::IdentityMiddleware;
    use actix_session::{storage::RedisSessionStore, SessionMiddleware};
    
    #[actix_web::main]
    async fn main() {
        // Initialize key outside HttpServer::new
        let secret_key = Key::generate();
    
        let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
            .await
            .unwrap();
    
        HttpServer::new(move || {
            App::new()
                // 1. Install identity middleware first
                .wrap(IdentityMiddleware::default())
                // 2. Install session middleware AFTER identity middleware
                // so that session is processed first on incoming requests
                .wrap(SessionMiddleware::new(
                     redis_store.clone(),
                     secret_key.clone(),
                ))
        })
        .bind("127.0.0.1:8080")
        .unwrap()
        .run()
        .await;
    }
  10. Set up actix-session middleware

    main

    To use sessions, you must register SessionMiddleware as middleware on your App. You need a SessionStore (like RedisSessionStore) and a Key for signing/encrypting cookies.

    Important: When using Key::generate(), initialize it outside of the HttpServer::new closure to ensure the same key is used across all worker threads. In production, load this key from a configuration file or environment variable.

    use actix_web::{web, App, HttpServer, HttpResponse, Error};
    use actix_session::{Session, SessionMiddleware, storage::RedisSessionStore};
    use actix_web::cookie::Key;
    
    #[actix_web::main]
    async fn main() -> std::io::Result<()> {
        // Initialize key outside the closure
        let secret_key = Key::generate();
    
        let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
            .await
            .unwrap();
    
        HttpServer::new(move ||
                App::new()
                // Register SessionMiddleware
                .wrap(
                    SessionMiddleware::new(
                        redis_store.clone(),
                        secret_key.clone(),
                    )
                )
                .default_service(web::to(|| HttpResponse::Ok())))
            .bind(("127.0.0.1", 8080))?
            .run()
            .await
    }
    use actix_web::{web, App, HttpServer, HttpResponse, Error};
    use actix_session::{Session, SessionMiddleware, storage::RedisSessionStore};
    use actix_web::cookie::Key;
    
    #[actix_web::main]
    async fn main() -> std::io::Result<()> {
        let secret_key = Key::generate();
    
        let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
            .await
            .unwrap();
    
        HttpServer::new(move ||
                App::new()
                .wrap(
                    SessionMiddleware::new(
                        redis_store.clone(),
                        secret_key.clone(),
                    )
                )
                .default_service(web::to(|| HttpResponse::Ok())))
            .bind(("127.0.0.1", 8080))?
            .run()
            .await
    }
  11. Use actix-protobuf to extract and send Protobuf payloads

    main

    The actix-protobuf crate provides tools to work with Protocol Buffers (Protobuf) in Actix Web.

    Extracting Protobuf payloads

    To extract a Protobuf message from an incoming request, use the ProtoBuf<T> extractor in your handler function, where T is a type that implements the prost::Message trait.

    Sending Protobuf responses

    To send a Protobuf message as a response, use the .protobuf() method on an HttpResponse builder, passing the inner message (accessible via .0 on the ProtoBuf wrapper).

    use actix_protobuf::ProtoBuf;
    use actix_web::*;
    use prost::Message;
    
    #[derive(Clone, PartialEq, Message)]
    pub struct MyObj {
        #[prost(int32, tag = "1")]
        pub number: i32,
    
        #[prost(string, tag = "2")]
        pub name: String,
    }
    
    async fn index(msg: ProtoBuf<MyObj>) -> Result<HttpResponse> {
        // msg.0 accesses the inner MyObj
        HttpResponse::Ok().protobuf(msg.0)
    }