Reference

Examples

New to acton-service?

Start with the homepage to understand what acton-service is, then explore Core Concepts for foundational explanations. See the Glossary for technical term definitions.


Browse complete, runnable examples showing how to build different types of services with acton-service. All examples are organized by category in the examples/ directory.


Example Categories

Examples are organized by feature and complexity. New to acton-service? Start with Basic Examples.

πŸ“š Basic Examples {#basic-examples}

Directory: examples/basic/

Simple getting-started examples demonstrating core functionality:

simple-api.rs - Zero-Configuration Versioned API

The simplest possible service with automatic health checks.

use acton_service::prelude::*;

async fn hello() -> &'static str {
    "Hello, world!"
}

#[tokio::main]
async fn main() -> Result<()> {
    let routes = VersionedApiBuilder::new()
        .with_base_path("/api")
        .add_version(ApiVersion::V1, |router| {
            router.route("/hello", get(hello))
        })
        .build_routes();

    ServiceBuilder::new()
        .with_routes(routes)
        .build()
        .serve()
        .await
}

Demonstrates:

  • Automatic configuration loading
  • Type-safe API versioning
  • Auto-generated health endpoints (/health, /ready)
  • Built-in tracing and logging
cargo run --manifest-path=acton-service/Cargo.toml --example simple-api

users-api.rs - Multi-Version API Evolution

Shows how to manage multiple API versions with deprecation headers.

Demonstrates:

  • Multiple API versions (V1, V2, V3)
  • Automatic deprecation warnings
  • API evolution patterns
  • Breaking change management
cargo run --manifest-path=acton-service/Cargo.toml --example users-api

ping-pong.rs - HTTP to gRPC Forwarding

Dual-protocol demo: an HTTP REST API that forwards requests to a gRPC backend. Requires the grpc feature.

Demonstrates:

  • HTTP REST API (port 8080) forwarding to a gRPC backend (port 9090)
  • Running HTTP and gRPC services side by side
  • Using generated protobuf types
  • Proto compilation via the acton-service build_utils helpers
cargo run --manifest-path=acton-service/Cargo.toml --example ping-pong --features grpc

Best for: First-time users, understanding basic patterns (start with simple-api.rs if you only need HTTP)

πŸ“– View Basic Examples README


πŸ” Authorization {#authorization}

Directory: examples/authorization/

Fine-grained access control using AWS Cedar policies.

cedar-authz.rs - Policy-Based Authorization

Complete example with JWT authentication + Cedar authorization.

Demonstrates:

  • Role-based access control (admin vs user)
  • Resource ownership patterns
  • JWT + Cedar integration
  • Optional Redis caching for policy decisions
cargo run --manifest-path=acton-service/Cargo.toml --example cedar-authz --features cedar-authz,cache

Features auto-setup with:

  • policies.cedar - Policy definitions
  • jwt-public.pem - JWT validation key
  • config.toml - Service configuration

Best for: Implementing RBAC or attribute-based access control

πŸ“– View Authorization README for detailed setup, testing instructions, and policy explanations.


πŸ”Œ gRPC Examples {#grpc}

Directory: examples/grpc/

gRPC service integration patterns.

single-port.rs - HTTP + gRPC on One Port

Run both REST and gRPC on a single port with automatic protocol detection.

Demonstrates:

  • Dual-protocol support on port 8080
  • Automatic routing based on content-type
  • gRPC (application/grpc) β†’ tonic services
  • All other requests β†’ axum HTTP handlers
cargo run --manifest-path=acton-service/Cargo.toml --example single-port --features grpc

Test HTTP:

curl http://localhost:8080/api/v1/hello

Test gRPC:

grpcurl -plaintext -d '{"name": "world"}' localhost:8080 hello.HelloService/SayHello

Best for: Services needing both REST and gRPC interfaces

πŸ“– View gRPC Examples README


πŸ“¨ Event-Driven Architecture {#events}

Directory: examples/events/

Event bus patterns and asynchronous communication.

event-driven.rs - HTTP API + gRPC with Event Bus

Recommended architecture: HTTP publishes events, gRPC consumes them.

Demonstrates:

  • HTTP REST API (port 8080) publishing events
  • gRPC service (port 9090) consuming events
  • Decoupled microservice communication
  • Async event processing
cargo run --manifest-path=acton-service/Cargo.toml --example event-driven --features grpc

Architecture:

HTTP Client β†’ REST API β†’ Event Bus β†’ gRPC Service β†’ Business Logic

Best for: Decoupled microservices, async message processing

πŸ“– View Events README


πŸ“Š Observability {#observability}

Directory: examples/observability/

Metrics, tracing, and monitoring integration.

test-prometheus-metrics.rs - Prometheus Scrape Endpoint

Pull-based /metrics endpoint via the prometheus-metrics feature, mounted automatically by ServiceBuilder. Also configures the optional [middleware.metrics.exporter] listener, which serves the same document in plaintext on a port of its own β€” the surface a platform collector such as Fly.io [[metrics]] or a PodMonitor would scrape.

cargo run --manifest-path=acton-service/Cargo.toml --example test-prometheus-metrics --features prometheus-metrics
curl http://localhost:8080/api/v1/hello
curl http://localhost:8080/metrics
curl http://localhost:9091/metrics

test-metrics.rs - HTTP Metrics Layer

Constructing the OpenTelemetry HTTP metrics layer manually and applying it to a hand-built router.

cargo run --manifest-path=acton-service/Cargo.toml --example test-metrics --features otel-metrics

test-observability.rs - OpenTelemetry Tracing

Distributed tracing setup with OpenTelemetry.

cargo run --manifest-path=acton-service/Cargo.toml --example test-observability --features observability

Demonstrates:

  • OpenTelemetry initialization
  • Span creation and propagation
  • Integration with Jaeger/Zipkin
  • Structured logging correlation

Best for: Production monitoring, debugging, performance analysis

πŸ“– View Observability README


🎨 HTMX Applications {#htmx}

Directory: examples/htmx/

Server-rendered hypermedia applications with HTMX, Askama templates, and real-time updates.

task-manager.rs - Complete HTMX Application

Comprehensive example demonstrating all HTMX features in a working task management app.

cargo run --manifest-path=acton-service/Cargo.toml --example task-manager --features htmx-full

Open http://localhost:8080 to explore the application.

Demonstrates:

  • Askama templates with TemplateContext for flash messages and auth
  • Session-based authentication with TypedSession<AuthSession>
  • Out-of-band swaps for updating multiple elements simultaneously
  • Server-Sent Events for real-time task updates
  • Flash messages that survive redirects
  • Inline editing patterns with HTMX forms
  • CSRF protection via session middleware

Architecture:

Browser (HTMX) β†’ Server renders HTML β†’ Returns fragments or full pages
                      ↓
              SSE broadcasts real-time updates to all connected clients

Key patterns shown:

  • Fragment vs. Full Page: Same handler returns fragment for HTMX, full page for direct navigation
  • OOB Swaps: Task creation updates both the task list and statistics counter
  • Flash Messages: Success/error feedback via FlashMessages::push()
  • SSE Integration: Real-time updates without polling

Best for: Building interactive web applications without heavy JavaScript frameworks

πŸ“– View HTMX README for detailed setup, testing instructions, and pattern explanations.


πŸ—„οΈ Database {#database}

Directory: examples/database/

PostgreSQL integration with SQLx.

database-api.rs - PostgreSQL CRUD API

Versioned REST API backed by PostgreSQL, with a Docker Compose stack and migrations included.

Demonstrates:

  • Database connection pooling with SQLx
  • Executing queries against PostgreSQL
  • CRUD operations with typed responses
  • Error handling for database operations (state.db().await)
  • Integration with the versioned API builder

Start the database, then run:

cd acton-service/examples/database && docker compose up -d && cd -
export ACTON_DATABASE_URL="postgres://acton:acton_secret@localhost:5433/acton_example"
cargo run --manifest-path=acton-service/Cargo.toml --example database-api --features database

Best for: Standard CRUD services on PostgreSQL

πŸ“– View Database README


πŸ’¬ WebSocket {#websocket}

Directory: examples/websocket/

Real-time bidirectional communication.

chat-server.rs - Room-Based Chat Server

A WebSocket chat server with rooms and broadcast messaging.

Demonstrates:

  • WebSocket upgrades from HTTP
  • Room-based chat functionality
  • Broadcasting messages to room members
  • Connection management with the Broadcaster
cargo run --manifest-path=acton-service/Cargo.toml --example chat-server --features websocket

Connect with a WebSocket client and send JSON frames:

websocat ws://localhost:8080/api/v1/ws
{"type": "join", "room": "general"}
{"type": "message", "room": "general", "content": "Hello everyone!"}
{"type": "leave", "room": "general"}

Best for: Chat, live updates, and other real-time features


β—ˆ GraphQL {#graphql}

Directory: examples/graphql/

Versioned GraphQL transport alongside HTTP and gRPC.

graphql-basic.rs - Versioned GraphQL Schemas

Registers two GraphQL schemas (V1, V2) under the versioned router.

Demonstrates:

  • Registering schemas under /api/v1/graphql and /api/v2/graphql via VersionedGraphQLBuilder
  • Reading authenticated claims inside a resolver via GraphQLContextExt
  • Cedar policy authorization at the resolver level via CedarResolverCheck (only compiled with the graphql-cedar feature)
cargo run --manifest-path=acton-service/Cargo.toml --example graphql-basic --features graphql,auth

Then open the GraphiQL UI at http://localhost:8080/api/v1/graphql, or query directly:

curl -X POST http://localhost:8080/api/v1/graphql \
     -H 'content-type: application/json' \
     -d '{"query":"{ hello }"}'

Best for: GraphQL APIs that need versioning and policy-based authorization


πŸ“‹ Templates {#templates}

Directory: examples/templates/

Configuration and build templates for new projects.

  • config.toml.example - Complete service configuration template
  • build.rs.example - Build script for proto compilation

Use these as starting points for your own services:

cp examples/templates/config.toml.example config.toml
cp examples/templates/build.rs.example build.rs

Best for: Starting a new project, understanding all configuration options

πŸ“– View Templates README


Running Examples

All examples run from the repository root with updated paths:

# Basic examples
cargo run --manifest-path=acton-service/Cargo.toml --example simple-api
cargo run --manifest-path=acton-service/Cargo.toml --example users-api
cargo run --manifest-path=acton-service/Cargo.toml --example ping-pong --features grpc

# Authorization (requires features)
cargo run --manifest-path=acton-service/Cargo.toml --example cedar-authz --features cedar-authz,cache

# gRPC (requires features)
cargo run --manifest-path=acton-service/Cargo.toml --example single-port --features grpc

# Events (requires features)
cargo run --manifest-path=acton-service/Cargo.toml --example event-driven --features grpc

# Observability (requires features)
cargo run --manifest-path=acton-service/Cargo.toml --example test-metrics --features otel-metrics
cargo run --manifest-path=acton-service/Cargo.toml --example test-observability --features observability

# Database (requires a running PostgreSQL β€” see examples/database/docker-compose.yml)
cargo run --manifest-path=acton-service/Cargo.toml --example database-api --features database

# WebSocket
cargo run --manifest-path=acton-service/Cargo.toml --example chat-server --features websocket

# GraphQL
cargo run --manifest-path=acton-service/Cargo.toml --example graphql-basic --features graphql,auth

# HTMX
cargo run --manifest-path=acton-service/Cargo.toml --example task-manager --features htmx-full

Feature Flags for Examples

Some examples require specific feature flags:

FeatureRequired ForDescription
cedar-authzcedar-authzAWS Cedar policy authorization
cachecedar-authzRedis caching for policy decisions
grpcping-pong, single-port, event-driventonic gRPC server support
otel-metricstest-metricsOpenTelemetry metrics collection (OTLP push)
prometheus-metricstest-prometheus-metricsPull-based Prometheus /metrics endpoint
observabilitytest-observabilityOpenTelemetry tracing
databasedatabase-apiPostgreSQL via SQLx
websocketchat-serverWebSocket support
graphqlgraphql-basicGraphQL transport
htmx-fulltask-managerHTMX, Askama, SSE, and sessions
httpsimple-api, users-apiHTTP REST API (default feature)

Learning Path

Recommended order for exploring acton-service:

  1. Start: simple-api.rs - Understand basic service setup
  2. Versioning: users-api.rs - Learn API version management
  3. Authorization: cedar-authz.rs - Add access control
  4. Advanced: Explore gRPC, events, and observability as needed

Example Structure

Each category includes:

  • README.md - Detailed category documentation
  • Complete source code - Runnable examples
  • Inline documentation - Code comments explaining key concepts
  • Test commands - Copy/paste curl/grpcurl commands

Next Steps

Previous
Production Checklist