Sneakers Documentation

repository·master·Indexed 25 days ago

https://github.com/jondot/sneakers

A high-performance RabbitMQ background processing framework for Ruby designed for I/O and CPU intensive workloads. It provides tools for creating workers, managing processes via a CLI, configuring global settings, and integrating with Docker and Docker Compose. Features include custom content encoding/decoding, metrics logging, and support for various Ruby versions from 1.9.x to 3.0+.

Tokens
5.2K
Snippets
12
Records
41
Agent score
81%

What's inside Sneakers

  1. Use Docker with Sneakers

    master

    Sneakers provides Docker support for testing and running workers without local RabbitMQ/Redis setups.

    • Build image: docker build . -t sneakers_sneakers
    • Run non-integration tests: docker run --rm sneakers_sneakers:latest
    • Run full integration tests: Execute scripts/local_integration (uses docker-compose).
    • Run a sample worker: Execute script/local_worker (uses docker-compose).
    • Production builds: Use Dockerfile.slim for a compact image; use the standard Dockerfile for faster development iteration.
  2. Create a Sneakers worker

    master

    To create a worker, define a class that includes Sneakers::Worker and use the from_queue method to specify the RabbitMQ queue name. Implement the work(msg) method to process incoming messages. Within work, you must call ack! to acknowledge the message once processing is complete.

    require 'sneakers'
    require 'redis'
    require 'json'
    
    $redis = Redis.new
    
    class Processor
      include Sneakers::Worker
      from_queue :logs
    
      def work(msg)
        err = JSON.parse(msg)
        if err["type"] == "error"
          $redis.incr "processor:#{err["error"]}"
        end
    
        ack!
      end
    end
  3. Configure the Maxretry handler for RabbitMQ retries

    master

    The Maxretry handler implements a retry mechanism using RabbitMQ dead-letter policies. When a message fails (via reject or error), it is routed to a retry exchange/queue. If the maximum number of retries is reached, the message is published to an error exchange with metadata about the failure (error class, message, backtrace, and attempt count).

    To use this handler, you must configure your queue with the correct x-dead-letter-exchange argument so that rejected messages are routed to the retry infrastructure. Use Sneakers::Handlers::Maxretry.configure_queue to generate the necessary options for your queue configuration.

  4. Configure logging metrics for Sneakers

    master

    To see real-time metrics (such as work start, completion, and timing) in your logs, use the Sneakers::Metrics::LoggingMetrics provider via Sneakers.configure.

    require 'sneakers'
    require 'sneakers/metrics/logging_metrics'
    
    Sneakers.configure(metrics: Sneakers::Metrics::LoggingMetrics.new)
  5. Configure Sneakers with Docker Compose

    master

    You can run Sneakers using Docker Compose. The setup requires rabbitmq and redis services. The sneakers service depends on both and requires a RABBITMQ_URL environment variable to connect to the message broker.

    Key configuration details:

    • Service Dependencies: The sneakers service depends on rabbitmq and redis.
    • Environment Variables: Set RABBITMQ_URL to the connection string for RabbitMQ (e.g., amqp://guest:guest@rabbitmq:5672).
    • Volumes: The local directory is mounted to /sneakers inside the container.
    version: '3'
    
    services:
      sneakers:
        build: .
        volumes:
          - .:/sneakers
        depends_on:
          - rabbitmq
          - redis
        environment:
          - RABBITMQ_URL=amqp://guest:guest@rabbitmq:5672
    
    rabbitmq:
        image: rabbitmq:management-alpine
        ports:
          - "5672:5672"
          - "15672:15672"
    
    redis:
        image: redis:alpine
        ports:
          - "6379:6379"
  6. Configure Maxretry handler options

    master

    When initializing or configuring the Maxretry handler, you can provide several options to customize the retry behavior and RabbitMQ topology:

    OptionDescription
    :retry_exchangeSets the name of the retry exchange and queue (defaults to #{worker_queue_name}-retry)
    :retry_error_exchangeSets the name of the error exchange and queue (defaults to #{worker_queue_name}-error)
    :retry_requeue_exchangeSets the name of the exchange used to requeue messages back to the worker queue (defaults to #{worker_queue_name}-retry-requeue)
    :retry_routing_keyThe routing key used for requeueing (defaults to #)
    :retry_timeoutThe TTL (Time To Live) for messages in the retry queue in milliseconds (defaults to 60000)
    :retry_max_timesThe maximum number of retry attempts before moving the message to the error queue (defaults to 5)
    :queue_optionsA hash of RabbitMQ queue arguments (e.g., { durable: true })
  7. Configure Sneakers settings and options

    master

    Sneakers uses a Configuration object to manage settings for both the runner and the individual workers. You can configure these settings by merging a hash into the existing configuration.

    Important Security Note: By default, Sneakers includes Sneakers::ErrorReporter::DefaultLogger, which logs errors to STDOUT. In production environments, you should remove this or replace it to avoid logging sensitive data.

    If you provide a connection object (a Bunny object) in your configuration hash, Sneakers will ignore the :vhost, :amqp, and :heartbeat parameters to ensure the provided connection is the single source of truth.

  8. Configure Sneakers::Publisher via options

    master

    When initializing Sneakers::Publisher, the options hash is merged with Sneakers::CONFIG. Key configuration options include:

    • :connection: An existing Bunny connection object. If provided, Sneakers uses this instead of creating a new one.
    • :amqp: AMQP connection settings (passed to Bunny.new).
    • :vhost: The RabbitMQ virtual host.
    • :heartbeat: Heartbeat interval.
    • :properties: A hash of properties for the connection.
    • :exchange: The name of the exchange to use.
    • :exchange_options: Options passed to the exchange creation method (e.g., type, durable).
  9. Run a Sneakers worker from the command line

    master

    Use the sneakers CLI command to spawn a worker. Use the --require flag to specify a file (e.g., boot.rb) that sets up your environment, dependencies, and worker definitions.

    $ sneakers work Processor --require boot.rb
  10. Register custom content type serializers and deserializers

    master

    You can define how specific content types are transformed when being sent (serialized) or received (deserialized) by using Sneakers::ContentType.register. This is useful for handling custom formats like JSON, MessagePack, or Protobuf within your background workers.

    To register a type, you must provide:

    • content_type: A unique identifier for the type.
    • serializer: A Proc that accepts exactly one argument (the payload) and returns the serialized version.
    • deserializer: A Proc that accepts exactly one argument (the payload) and returns the deserialized version.

    If no content type is specified during serialization or deserialization, Sneakers will default to a 'passthrough' behavior, returning the payload unchanged.