Malla.Request (malla v0.1.0)

Copy Markdown View Source

Client-side API for making structured requests to remote services.

This module provides the request/4 function and req/2 macro for invoking operations on remote services using Malla's request protocol. The protocol adds distributed tracing, standardized responses, retry logic, and plugin interception on top of basic RPC.

Usage of this mechanism is optional. You can always use basic Malla RPC using Malla.remote/4 where this tools is based on.

This tool requires the usage of Malla.Status and Malla.Tracer. When including plugin Malla.Plugins.Request in your service, it will include them too.

Quick Example

defmodule APIService do
  use Malla.Service
  use Malla.Request  # Import req macro

  def get_user_info(user_id) do
    # Using macro syntax
    case req UserService.get_user(user_id) do
      {:ok, user} -> format_response(user)
      {:error, %Malla.Status{}} -> render_error()
    end
  end
end

Core Functions

Request Flow

  1. Creates "request-out" span for tracing
  2. Calls malla_request/3 callback (interceptable by plugins)
  3. Uses Malla.remote/4 for RPC to target service
  4. Remote side creates "request-in" span
  5. Executes target function
  6. Normalizes response via Malla.Status
  7. Emits telemetry events

Response Types

Request handlers must return one of:

  • :ok - Success, no data
  • :created - Resource created, no data
  • {:ok, data} - Success with data (map or list)
  • {:created, data} - Resource created with data
  • {:error, term} - Error (normalized via Malla.Status)
  • {:status, term} - Custom status (normalized via Malla.Status)

Options

Both request/4 and req/2 accept options:

  • :timeout - Request timeout in milliseconds (default: 30_000)
  • :direct - Skip RPC, call locally (default: false)
  • :retries - Number of retries on failure
  • :retry_delay - Delay between retries in milliseconds
  • Plus any custom options for plugin use

Examples

# Using req macro (recommended)
use Malla.Request
{:ok, user} = req UserService.get_user(123)
{:created, post} = req BlogService.create_post(params)

# Using explicit function
Malla.Request.request(UserService, :get_user, [123])
Malla.Request.request(UserService, :update_user, [123, params], timeout: 10_000)

# With custom options
req PaymentService.charge(order_id),
  timeout: 15_000,
  auth_token: token

# Raising version
{:ok, user} = request!(UserService, :get_user, [123])

Telemetry

Emits [:malla, :request, :out] events with:

  • Measurements: :counter, :duration
  • Metadata: :target, :op, :result, plus standard fields

For Complete Documentation

See the Request Handling guide for comprehensive documentation including:

  • Plugin-based interception (auth, rate limiting, validation)
  • Distributed tracing patterns
  • Error handling strategies
  • Testing approaches
  • Best practices

See Also

Summary

Functions

Sends a request to a service, local or remote, written as a function call.

Same as req/1, with options for request/4.

Sends a request to fun of remote_service inside a "request-out" span.

Same as request/4, but raises Malla.Request.ReqError when the service is not available (type: :service_not_available) or the answer is an internal error (type: :internal_error). Other errors are returned.

Types

op()

@type op() :: [:atom] | String.t()

req_opt()

@type req_opt() :: Malla.remote_opt() | {:direct, boolean()}

Functions

req(call)

(macro)

Sends a request to a service, local or remote, written as a function call.

req MyApp.UserService.get_user(123) expands to Malla.Request.request(MyApp.UserService, :get_user, [123]), and req MyApp.UserService.get_user(123), timeout: 5000 passes the options as the fourth argument. See request/4 for what it does and returns.

The service must be written as a literal module name, in full: aliases are not expanded, and a variable does not match. Import the macro with use Malla.Request.

req(call, opts)

(macro)

Same as req/1, with options for request/4.

request(remote_service, fun, args, opts \\ [])

@spec request(Malla.id(), atom(), [any()], [req_opt()]) ::
  {:ok, map()} | {:created, map()} | {:error, map()} | {:status, map()}

Sends a request to fun of remote_service inside a "request-out" span.

The call goes through Malla.remote/4 to the malla_request/3 callback of the target service (see Malla.Plugins.Request), which runs fun with args in its own span. The base span is sent along so the trace continues on the other side.

Options are those of Malla.remote/4, plus:

  • :direct - when true, calls malla_request/3 of the target module in this node, without RPC.
  • :service_id - the calling service, when the process has none.

The called function must answer :ok, :created, {:ok, data}, {:created, data} (with a map or list), or {:error, status} / {:status, status} with a Malla.Status. The result is always a two-element tuple: :ok and :created come back with an empty map, a transport error (such as :malla_service_not_available or a remote exception) becomes {:error, %Malla.Status{}} through Malla.Status.public/2, and any other answer becomes an "internal_error" status.

request!(remote_service, op, args \\ [], opts \\ [])

@spec request!(Malla.id(), atom(), [any()], [req_opt()]) ::
  {:created, map()} | {:error, map()} | {:ok, map()} | {:status, map()}

Same as request/4, but raises Malla.Request.ReqError when the service is not available (type: :service_not_available) or the answer is an internal error (type: :internal_error). Other errors are returned.