or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus@v1.10.0

docs

client.mderrors.mdindex.mdmessaging.mdreceiver.mdsender.mdsessions.md
tile.json

tessl/golang-github-com--azure--azure-sdk-for-go--sdk--messaging--azservicebus

tessl install tessl/golang-github-com--azure--azure-sdk-for-go--sdk--messaging--azservicebus@1.10.1

Client module for Azure Service Bus, a highly reliable cloud messaging service providing real-time and fault-tolerant communication between distributed senders and receivers.

messaging.mddocs/

Messages and Message Batching

Azure Service Bus messages carry data between senders and receivers. The SDK supports both standard messages for common scenarios and advanced AMQP annotated messages for full protocol control.

Capabilities

Standard Messages

The Message type provides a simple interface for sending messages with common properties.

type Message struct {
    Body []byte
    ApplicationProperties map[string]any
    ContentType *string
    CorrelationID *string
    MessageID *string
    PartitionKey *string
    ReplyTo *string
    ReplyToSessionID *string
    ScheduledEnqueueTime *time.Time
    SessionID *string
    Subject *string
    TimeToLive *time.Duration
    To *string
}
  • Body: The message payload as a byte array
  • ApplicationProperties: Custom metadata as key-value pairs
  • ContentType: MIME type descriptor (RFC2045), e.g., "application/json"
  • CorrelationID: Correlation identifier for request-reply patterns
  • MessageID: Unique message identifier (used for duplicate detection)
  • PartitionKey: Routing key for partitioned entities (overridden by SessionID for session-aware entities)
  • ReplyTo: Reply address for request-reply patterns
  • ReplyToSessionID: Session ID for the reply
  • ScheduledEnqueueTime: Future delivery time
  • SessionID: Session identifier for session-aware entities (empty string is valid)
  • Subject: Message purpose, similar to email subject
  • TimeToLive: Expiration duration from enqueue time
  • To: Logical destination address (reserved for future routing)

Example:

msg := &azservicebus.Message{
    Body:          []byte(`{"orderId": 12345, "amount": 99.99}`),
    ContentType:   to.Ptr("application/json"),
    MessageID:     to.Ptr("order-12345"),
    CorrelationID: to.Ptr("request-67890"),
    Subject:       to.Ptr("NewOrder"),
    TimeToLive:    to.Ptr(time.Hour * 24),
    ApplicationProperties: map[string]any{
        "priority":     "high",
        "orderType":    "express",
        "customerTier": 3,
    },
}

Received Messages

The ReceivedMessage type extends Message with additional server-provided metadata.

type ReceivedMessage struct {
    ApplicationProperties map[string]any
    Body []byte
    ContentType *string
    CorrelationID *string
    DeadLetterErrorDescription *string
    DeadLetterReason *string
    DeadLetterSource *string
    DeliveryCount uint32
    EnqueuedSequenceNumber *int64
    EnqueuedTime *time.Time
    ExpiresAt *time.Time
    LockedUntil *time.Time
    LockToken [16]byte
    MessageID string
    PartitionKey *string
    ReplyTo *string
    ReplyToSessionID *string
    ScheduledEnqueueTime *time.Time
    SequenceNumber *int64
    SessionID *string
    State MessageState
    Subject *string
    TimeToLive *time.Duration
    To *string
    RawAMQPMessage *AMQPAnnotatedMessage
}

Additional fields for received messages:

  • DeadLetterErrorDescription: Error description if message was dead-lettered
  • DeadLetterReason: Reason for dead-lettering
  • DeadLetterSource: Original queue/subscription before dead-lettering
  • DeliveryCount: Number of delivery attempts (increments on abandon or lock expiration)
  • EnqueuedSequenceNumber: Original sequence number before auto-forwarding
  • EnqueuedTime: When the message was accepted by Service Bus
  • ExpiresAt: Calculated expiration time (EnqueuedTime + TimeToLive)
  • LockedUntil: Lock expiration time for peek-lock mode
  • LockToken: Token for message settlement operations (peek-lock mode)
  • SequenceNumber: Unique sequence number assigned by Service Bus
  • State: Message state (Active, Deferred, Scheduled)
  • RawAMQPMessage: Full AMQP message for advanced scenarios

Convert ReceivedMessage to Message

func (rm *ReceivedMessage) Message() *Message

Creates a shallow copy of fields from ReceivedMessage to a new Message instance, useful for forwarding received messages.

Example:

receivedMsg := messages[0]
fmt.Printf("Delivery attempt: %d\n", receivedMsg.DeliveryCount)
fmt.Printf("Enqueued at: %v\n", receivedMsg.EnqueuedTime)
fmt.Printf("Lock expires: %v\n", receivedMsg.LockedUntil)

// Forward to another queue
forwardMsg := receivedMsg.Message()
sender.SendMessage(ctx, forwardMsg, nil)

Message State

type MessageState int32

const (
    MessageStateActive MessageState = 0
    MessageStateDeferred MessageState = 1
    MessageStateScheduled MessageState = 2
)
  • MessageStateActive: Normal active message available for receiving
  • MessageStateDeferred: Message deferred for later retrieval using sequence number
  • MessageStateScheduled: Message scheduled for future delivery

Message Batching

Message batches allow efficient transmission of multiple messages in a single operation, reducing network overhead and improving throughput.

MessageBatch

type MessageBatch struct {
    // ... unexported fields
}

A batch container that enforces Service Bus size limits.

Add Message to Batch

func (mb *MessageBatch) AddMessage(m *Message, options *AddMessageOptions) error

Adds a message to the batch. Returns ErrMessageTooLarge if the message would exceed the batch size limit.

Add AMQP Message to Batch

func (mb *MessageBatch) AddAMQPAnnotatedMessage(m *AMQPAnnotatedMessage, options *AddAMQPAnnotatedMessageOptions) error

Adds an AMQP annotated message to the batch. Returns ErrMessageTooLarge if the message would exceed the batch size limit.

Batch Metrics

func (mb *MessageBatch) NumMessages() int32

Returns the number of messages currently in the batch.

func (mb *MessageBatch) NumBytes() uint64

Returns the current size of the batch in bytes.

Batch Error Constant

var ErrMessageTooLarge = errors.New("the message is too large")

Error returned when a message cannot fit into a batch or exceeds the link's maximum message size.

Example:

batch, err := sender.NewMessageBatch(ctx, nil)
if err != nil {
    panic(err)
}

messages := []*azservicebus.Message{
    {Body: []byte("message 1")},
    {Body: []byte("message 2")},
    {Body: []byte("message 3")},
}

for i, msg := range messages {
    err := batch.AddMessage(msg, nil)
    if errors.Is(err, azservicebus.ErrMessageTooLarge) {
        if batch.NumMessages() == 0 {
            // Single message too large, cannot be sent
            fmt.Printf("Message %d is too large to send\n", i)
            continue
        }

        // Batch full, send current batch and create new one
        sender.SendMessageBatch(ctx, batch, nil)
        batch, _ = sender.NewMessageBatch(ctx, nil)

        // Retry adding the message
        batch.AddMessage(msg, nil)
    } else if err != nil {
        panic(err)
    }
}

// Send remaining messages
if batch.NumMessages() > 0 {
    sender.SendMessageBatch(ctx, batch, nil)
}

Advanced AMQP Messages

For advanced scenarios requiring full AMQP protocol control, use AMQPAnnotatedMessage.

AMQPAnnotatedMessage

type AMQPAnnotatedMessage struct {
    ApplicationProperties map[string]any
    Body AMQPAnnotatedMessageBody
    DeliveryAnnotations map[any]any
    DeliveryTag []byte
    Footer map[any]any
    Header *AMQPAnnotatedMessageHeader
    MessageAnnotations map[any]any
    Properties *AMQPAnnotatedMessageProperties
}

Represents the complete AMQP message format as defined in the AMQP 1.0 specification. Use this for:

  • Custom AMQP body sections (Data, Sequence, or Value)
  • Message annotations for AMQP brokers
  • Delivery annotations for routing hints
  • Message footers
  • Full control over AMQP properties

AMQP Simple Types: Maps and sequences accept AMQP simple types including int (any size), uint (any size), float (any size), string, bool, time.Time.

AMQPAnnotatedMessageBody

type AMQPAnnotatedMessageBody struct {
    Data [][]byte
    Sequence [][]any
    Value any
}

AMQP message body with three mutually exclusive representations:

  • Data: One or more data sections ([]byte arrays) - most common for binary payloads
  • Sequence: One or more AMQP sequence sections (slices of AMQP simple types)
  • Value: Single AMQP value section (AMQP simple type, slice, or map)

Only one of these fields should be populated at a time.

Example:

// Data section (most common)
msg := &azservicebus.AMQPAnnotatedMessage{
    Body: azservicebus.AMQPAnnotatedMessageBody{
        Data: [][]byte{[]byte("payload")},
    },
}

// Sequence section
msg := &azservicebus.AMQPAnnotatedMessage{
    Body: azservicebus.AMQPAnnotatedMessageBody{
        Sequence: [][]any{
            {"string", int64(42), true},
            {3.14, time.Now()},
        },
    },
}

// Value section
msg := &azservicebus.AMQPAnnotatedMessage{
    Body: azservicebus.AMQPAnnotatedMessageBody{
        Value: map[string]any{
            "orderId": int64(12345),
            "amount":  99.99,
        },
    },
}

AMQPAnnotatedMessageHeader

type AMQPAnnotatedMessageHeader struct {
    DeliveryCount uint32
    Durable bool
    FirstAcquirer bool
    Priority uint8
    TTL time.Duration
}

AMQP message header with delivery details:

  • DeliveryCount: Number of unsuccessful previous delivery attempts
  • Durable: Request durable delivery to storage
  • FirstAcquirer: Indicates if receiver is first to acquire message
  • Priority: Message priority (0-255, higher is more important)
  • TTL: Time-to-live duration

AMQPAnnotatedMessageProperties

type AMQPAnnotatedMessageProperties struct {
    AbsoluteExpiryTime *time.Time
    ContentEncoding *string
    ContentType *string
    CorrelationID any
    CreationTime *time.Time
    GroupID *string
    GroupSequence *uint32
    MessageID any
    ReplyTo *string
    ReplyToGroupID *string
    Subject *string
    To *string
    UserID []byte
}

AMQP message properties section:

  • CorrelationID: Can be uint64, UUID, []byte, or string
  • MessageID: Can be uint64, UUID, []byte, or string
  • GroupID: Equivalent to SessionID in Service Bus
  • GroupSequence: Sequence number within a group
  • UserID: Authenticated user ID
  • Other fields similar to standard Message properties

Types

MessageBatchOptions

type MessageBatchOptions struct {
    MaxBytes uint64
}

Options for creating a message batch:

  • MaxBytes: Override maximum batch size (defaults to namespace maximum)

AddMessageOptions

type AddMessageOptions struct {
    // Currently empty, reserved for future expansion
}

Options for adding a message to a batch.

AddAMQPAnnotatedMessageOptions

type AddAMQPAnnotatedMessageOptions struct {
    // Currently empty, reserved for future expansion
}

Options for adding an AMQP annotated message to a batch.