Apache Pekko HTTP

repository·main·Indexed 41 days ago

https://github.com/apache/pekko-http

A toolkit for building server-side and client-side HTTP services, implemented as a full stack on top of Pekko actors and streams. It provides multiple API levels of abstraction for both high-level ease of use and low-level flexibility, including support for TLS encryption, custom client transports, and HTTP(S) proxies.

Tokens
130.5K
Snippets
340
Records
619
Agent score
52%

What's inside Apache Pekko HTTP

  1. Overview of Apache Pekko HTTP

    main

    Apache Pekko HTTP is a full server- and client-side HTTP stack built on top of pekko-actor and pekko-stream.

    It is designed as a general toolkit for providing and consuming HTTP-based services rather than a high-level web framework. It follows an open design that provides multiple API levels of abstraction. This allows developers to choose between high-level APIs for ease of use or low-level APIs for maximum flexibility and control.

  2. Overview of the Apache Pekko HTTP Server API

    main

    Apache Pekko HTTP provides an embedded, asynchronous HTTP/1.1 server built on top of Pekko Streams and Reactive Streams. It is designed to handle thousands of concurrent connections and supports features such as:

    • HTTP persistent connections: Full support for keeping connections open.
    • Asynchronous HTTP streaming: Includes support for "chunked" transfer encoding via an idiomatic API.
    • WebSocket support: For real-time, bidirectional communication.
    • SSL/TLS encryption: Optional support for secure connections.
    • HTTP pipelining: Optional support for sending multiple HTTP requests without waiting for individual responses.

    Because the server is "streaming-first," it is highly recommended to understand the implications of the streaming nature of Request/Response Entities, as the behavior may differ from non-streaming HTTP servers.

  3. Use FormFieldDirectives to extract form data

    main

    Pekko HTTP provides a set of directives for extracting data from HTTP request bodies, specifically designed for handling form data (e.g., application/x-www-form-urlencoded). These directives allow you to map specific form field names to Scala types within your routing logic.

    Available directives include:

    • formField: Extracts a single field.
    • formFields: Extracts multiple fields as a sequence.
    • formFieldSeq: Extracts multiple values for a single field name as a sequence.
    • formFieldMap: Extracts form data into a Map.
    • formFieldMultiMap: Extracts form data into a MultiMap.
  4. Understand the Apache Pekko HTTP module structure

    main

    Apache Pekko HTTP is composed of several modules depending on your needs:

    • pekko-http: The recommended module for writing HTTP servers. It provides high-level functionality like (un)marshalling, (de)compression, and a powerful Routing DSL.
    • pekko-http-core: A low-level implementation of both server-side and client-side HTTP (including WebSockets).
    • pekko-http-testkit: A test harness and utilities for verifying server-side implementations.

    Serialization/Marshalling Modules:

    • Scala-based:
      • pekko-http-spray-json: Glue-code for JSON using spray-json.
      • pekko-http-xml: Glue-code for XML using scala-xml.
    • Java-based:
  5. What is Marshalling in Apache Pekko HTTP?

    main

    Marshalling is the process of converting a high-level object structure into a lower-level representation, such as a "wire format".

    In Apache Pekko HTTP, this typically means converting an object of type T into a MessageEntity (the body of a request or response) or a full HttpRequest or HttpResponse.

    On the server side, marshalling is used to convert application-domain objects into response entities. The process supports content negotiation: a marshaller can provide multiple representations (e.g., JSON and XML), and the specific one used is determined by the client's Accept and AcceptCharset headers.

  6. What is a Route in Pekko HTTP?

    main

    A Route is the fundamental building block of the Pekko HTTP Routing DSL. It is a function that transforms a RequestContext into a Future[RouteResult] (Scala) or a CompletionStage<RouteResult> (Java).

    When a route processes a request, it can perform one of the following actions:

    • Complete: Return a response to the client using requestContext.complete(...).
    • Reject: Indicate that the route does not want to handle the request using requestContext.reject(...). This allows other routes in a chain to attempt handling it.
    • Fail: Fail the request using requestContext.fail(...) or by throwing an exception.
    • Asynchronous Processing: Return a future that will eventually complete with one of the above results.
    // Scala type alias
    type Route = RequestContext => Future[RouteResult]
  7. What is Unmarshalling in Apache Pekko HTTP

    main

    Unmarshalling is the process of converting a lower-level representation (often a "wire format") into a higher-level object structure. In Apache Pekko HTTP, this specifically refers to converting a source object—such as a MessageEntity (the entity body of a request or response), an HttpRequest, or an HttpResponse—into an instance of a target type T.

    Unmarshalling is performed by an Unmarshaller[A, B], which conceptually functions as a Function<A, CompletionStage<B>> (Java) or A => Future[B] (Scala).

  8. Manage HTTP connections and entity streaming

    main

    Streaming Entities

    HTTP request and response entities are handled via subclasses of HttpEntity. You can use Pekko HTTP's Marshalling and Unmarshalling facilities to convert custom types to and from these streamed entities.

    Closing Connections

    Connections are closed when:

    1. The handling Flow cancels its upstream subscription.
    2. The peer (client) closes the connection.
    3. The request entity is cancelled (e.g., by using the take combinator or attaching to Sink.cancelled()). To prevent this, explicitly drain the entity using Sink.ignore().

    Recommended approach: To explicitly signal that a connection should close after a response, add the Connection: close header to your HttpResponse.

  9. Understand the precedence of HTTP client settings

    main

    When using pool-based APIs (like Http.singleRequest), Pekko HTTP resolves settings using the following order of precedence (from highest to lowest):

    1. Per-host overrides: The settings in the first per-host-override entry whose host-pattern matches the target host.
    2. Pool-specific client overrides: Settings defined in pekko.http.host-connection-pool.client.
    3. Global client settings: The default settings defined in pekko.http.client.
  10. Supported Content-Encoding algorithms

    main

    Apache Pekko HTTP supports the compression and decompression of HTTP requests and responses using the following Content-Encoding algorithms:

    • gzip
    • deflate

    Core logic for these encodings is located in the org.apache.pekko.http.scaladsl.coding package (Scala) or the org.apache.pekko.http.javadsl.coding.Coder enum class (Java).