Skip to content
gunavanthvarma-devPublic

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

52 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

AMQPlite

A lightweight AMQP 0-9-1 message broker built from scratch in Go. AMQPlite implements the core of the AMQP 0-9-1 specification wire-level frame parsing, connection lifecycle management, exchange routing, queue delivery, and consumer acknowledgments — without relying on any existing broker codebase.

Why

RabbitMQ is powerful but opaque. AMQPlite exists to understand how a message broker actually works at the protocol level: how bytes on a TCP socket become routed messages, how channels multiplex over a single connection, and how consumers receive deliveries. Every component, from the frame unmarshaler to the exchange router, is hand-written against the AMQP spec.

Architecture

Client (TCP :5672)
  │
  ▼
┌──────────────────────────────────────────┐
│  Broker                                  │
│  ├── ConnectionHandler (goroutine/conn)  │
│  │     ├── ConnWriter (goroutine)        │
│  │     ├── ConnectionControl (chan 0)     │
│  │     └── ChannelManager                │
│  │           └── Channel (goroutine/ch)  │
│  │                 └── BasicClass        │
│  ├── ExchangeManager                     │
│  │     ├── DirectExchange                │
│  │     ├── FanoutExchange                │
│  │     ├── TopicExchange                 │
│  │     └── HeadersExchange               │
│  └── QueueManager                        │
│        ├── Queue (goroutine)             │
│        └── ConsumerManager               │
│              └── Consumer (goroutine)    │
└──────────────────────────────────────────┘

Each connection spawns dedicated goroutines for reading, writing, and connection control. Channels, exchanges, queues, and consumers each run as independent goroutines communicating through Go channels, with context.Context used throughout for lifecycle and cancellation propagation.

Implemented Features

Connection Lifecycle (Class 10)

  • connection.start / connection.start-ok — protocol version and capability negotiation
  • connection.tune / connection.tune-ok — channel-max, frame-max, heartbeat negotiation
  • connection.open / connection.open-ok — virtual host selection
  • connection.close / connection.close-ok — graceful shutdown

Channel Multiplexing (Class 20)

  • channel.open / channel.open-ok
  • channel.close / channel.close-ok
  • Multiple independent channels per connection, each on its own goroutine

Exchange Management (Class 40)

  • exchange.declare / exchange.declare-ok
  • exchange.delete / exchange.delete-ok
  • Exchange types: direct (fully implemented with routing-key matching), fanout, topic, headers (scaffolded)
  • Default nameless direct exchange created on broker startup per AMQP spec

Queue Management (Class 50)

  • queue.declare / queue.declare-ok
  • queue.bind / queue.bind-ok
  • queue.delete / queue.delete-ok
  • queue.purge / queue.purge-ok
  • Per-queue message counting and round-robin consumer dispatch

Message Publishing & Delivery (Class 60)

  • basic.publish — multi-frame content assembly (method → header → body)
  • basic.deliver — push-based delivery to subscribed consumers
  • basic.consume / basic.consume-ok — long-lived consumer subscriptions
  • basic.cancel / basic.cancel-ok — consumer removal
  • basic.get / basic.get-ok / basic.get-empty — pull-based single-message fetch using temporary consumers
  • basic.ack — positive acknowledgment (single and multiple)
  • basic.reject — negative acknowledgment with optional requeue and redelivery flag

Wire Protocol

  • Binary frame marshaling and unmarshaling (method, content-header, content-body, heartbeat)
  • AMQP field table encoding/decoding (strings, integers, nested tables)
  • AMQP protocol header handshake validation
  • Frame-end byte (0xCE) verification

Compatibility

AMQPlite listens on the standard AMQP port (5672) and speaks the AMQP 0-9-1 wire protocol. It has been tested with the official amqp091-go client library — the same library used by most Go applications that connect to RabbitMQ.

Getting Started

Prerequisites

  • Go 1.21+

Run the broker

cd AMQPlite/AMQPliteServer
go run ./main

Type start to launch the broker on localhost:5672, and stop to shut it down.

Connect with any AMQP 0-9-1 client

package main

import (
    "fmt"
    amqp "github.com/rabbitmq/amqp091-go"
)

func main() {
    conn, _ := amqp.Dial("amqp://guest:guest@localhost:5672/")
    defer conn.Close()

    ch, _ := conn.Channel()
    q, _ := ch.QueueDeclare("hello", false, false, false, false, nil)

    ch.Publish("", q.Name, false, false, amqp.Publishing{
        Body: []byte("Hello from AMQPlite!"),
    })
    fmt.Println("Message published")
}

Project Structure

AMQPlite/
├── AMQPliteServer/
│   ├── main/
│   │   └── server.go              # TCP listener and broker startup
│   ├── components/
│   │   ├── Broker.go              # Core broker, connection acceptance
│   │   ├── Connection.go          # Per-connection state and reader
│   │   ├── ConnectionClass.go     # Connection handshake methods
│   │   ├── ConnectionControl.go   # Channel-0 frame dispatcher
│   │   ├── ConnWriter.go          # Per-connection writer goroutine
│   │   ├── ChannelManager.go      # Channel registry and routing
│   │   ├── Channel.go             # Per-channel frame processing
│   │   ├── BasicClass.go          # Publish, consume, ack, reject, get
│   │   ├── ExchangeManager.go     # Exchange CRUD and routing
│   │   ├── DirectExchange.go      # Direct exchange (routing-key match)
│   │   ├── FanoutExchange.go      # Fanout exchange (scaffold)
│   │   ├── TopicExchange.go       # Topic exchange (scaffold)
│   │   ├── HeadersExchange.go     # Headers exchange (scaffold)
│   │   ├── Exchange.go            # Exchange interface
│   │   ├── QueueManager.go        # Queue CRUD and binding
│   │   ├── Queue.go               # Queue storage and consumer dispatch
│   │   ├── Consumer.go            # Consumer goroutine and delivery
│   │   ├── ConsumerManager.go     # Consumer-to-queue registry
│   │   └── Bindings.go            # Exchange-to-queue binding model
│   ├── frames/
│   │   ├── FrameEnvelope.go       # Method frame container
│   │   ├── ContentEnvelope.go     # Multi-frame message container
│   │   ├── ChannelEnvelope.go     # Inter-component callback envelope
│   │   ├── ContentHeaderFrame.go  # Content header decode/encode
│   │   ├── ContentBodyFrame.go    # Content body handling
│   │   ├── MethodFrame.go         # Method frame structure
│   │   ├── HeartbeatFrame.go      # Heartbeat frame structure
│   │   ├── GeneralFrame.go        # Generic frame marshaling
│   │   ├── FrameMarshaler.go      # Frame → bytes
│   │   ├── FrameUnmarshaler.go    # Bytes → frame
│   │   └── Envelope.go            # Envelope interface
│   └── utilties/
│       ├── AmqpStrings.go         # Short/long string encode/decode
│       ├── FieldTable.go          # AMQP field table encode/decode
│       └── FrameMarshal.go        # General marshal utilities
├── client/
│   ├── amqpclient.go              # Test client using amqp091-go
│   └── debugclient.go             # Raw TCP debug client
└── go.mod

Future Work

Remaining AMQP 0-9-1 spec areas to implement:

Exchange Routing

  • Fanout exchange — broadcast to all bound queues regardless of routing key (type scaffolded, routing logic pending)
  • Topic exchange — wildcard pattern matching on routing keys (* and # bindings)
  • Headers exchange — route based on message header attributes with x-match (all/any) semantics

Quality of Service

  • basic.qos — prefetch count and prefetch size to limit unacknowledged deliveries per consumer/channel
  • basic.nack — negative acknowledgment with multi-message reject and requeue (RabbitMQ extension to AMQP 0-9-1)
  • basic.recover — redeliver all unacknowledged messages on a channel

Message Persistence & Durability

  • Durable queues — survive broker restarts (flag is accepted but not yet persisted to disk)
  • Persistent messages — delivery-mode = 2 messages written to durable storage
  • Message TTL and queue TTL — expiration per message and per queue
  • Dead letter exchanges — route rejected/expired messages to a configured DLX

Connection & Channel Management

  • Heartbeat frames — bidirectional heartbeat send/receive with connection timeout detection (currently accepted but not echoed)
  • connection.blocked / connection.unblocked — flow control notifications under memory/disk pressure
  • Server-initiated connection.close — broker-side close with proper error codes and resource cleanup
  • channel.flow — pause/resume message delivery on a channel
  • Per-connection resource cleanup — release all channels, consumers, and exclusive queues on disconnect

Security

  • connection.secure / connection.secure-ok — SASL challenge-response authentication (currently skipped, only PLAIN supported)
  • TLS/AMQPS — encrypted connections on port 5671
  • Virtual host isolation — multiple vhosts with independent exchange/queue namespaces (currently only / is accepted)

Protocol Completeness

  • exchange.bind / exchange.unbind — exchange-to-exchange routing
  • queue.unbind — remove specific bindings
  • basic.return — return unroutable mandatory/immediate messages to the publisher
  • tx.select / tx.commit / tx.rollback — transaction class for atomic publish/ack batches
  • confirm.select — publisher confirms (RabbitMQ extension)
  • Content header properties — full property parsing (content-type, message-id, correlation-id, reply-to, expiration, timestamp, headers, priority)

Error Handling

  • Channel-level exceptions — send channel.close with proper reply codes (404, 406, 403, etc.) instead of silently dropping errors
  • Connection-level exceptions — send connection.close for fatal protocol violations (frame-error, syntax-error, not-allowed)
  • AMQP reply codes — implement the full reply code table (311, 312, 313, 320, 402, 403, 404, 405, 406, 501, 502, 503, 504, 505, 506)

Operational

  • Management API — HTTP endpoint for listing connections, channels, exchanges, queues, bindings, and consumers
  • Logging and metrics — structured logging, message rates, queue depths
  • Unit and integration test suite — protocol-level tests using amqp091-go client

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages