1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
|
package amqp
import (
"context"
"encoding/json"
"time"
"github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/transport"
"github.com/go-kit/log"
amqp "github.com/rabbitmq/amqp091-go"
)
// Subscriber wraps an endpoint and provides a handler for AMQP Delivery messages.
type Subscriber struct {
e endpoint.Endpoint
dec DecodeRequestFunc
enc EncodeResponseFunc
before []RequestFunc
after []SubscriberResponseFunc
responsePublisher ResponsePublisher
errorEncoder ErrorEncoder
errorHandler transport.ErrorHandler
}
// NewSubscriber constructs a new subscriber, which provides a handler
// for AMQP Delivery messages.
func NewSubscriber(
e endpoint.Endpoint,
dec DecodeRequestFunc,
enc EncodeResponseFunc,
options ...SubscriberOption,
) *Subscriber {
s := &Subscriber{
e: e,
dec: dec,
enc: enc,
responsePublisher: DefaultResponsePublisher,
errorEncoder: DefaultErrorEncoder,
errorHandler: transport.NewLogErrorHandler(log.NewNopLogger()),
}
for _, option := range options {
option(s)
}
return s
}
// SubscriberOption sets an optional parameter for subscribers.
type SubscriberOption func(*Subscriber)
// SubscriberBefore functions are executed on the publisher delivery object
// before the request is decoded.
func SubscriberBefore(before ...RequestFunc) SubscriberOption {
return func(s *Subscriber) { s.before = append(s.before, before...) }
}
// SubscriberAfter functions are executed on the subscriber reply after the
// endpoint is invoked, but before anything is published to the reply.
func SubscriberAfter(after ...SubscriberResponseFunc) SubscriberOption {
return func(s *Subscriber) { s.after = append(s.after, after...) }
}
// SubscriberResponsePublisher is used by the subscriber to deliver response
// objects to the original sender.
// By default, the DefaultResponsePublisher is used.
func SubscriberResponsePublisher(rp ResponsePublisher) SubscriberOption {
return func(s *Subscriber) { s.responsePublisher = rp }
}
// SubscriberErrorEncoder is used to encode errors to the subscriber reply
// whenever they're encountered in the processing of a request. Clients can
// use this to provide custom error formatting. By default,
// errors will be published with the DefaultErrorEncoder.
func SubscriberErrorEncoder(ee ErrorEncoder) SubscriberOption {
return func(s *Subscriber) { s.errorEncoder = ee }
}
// SubscriberErrorLogger is used to log non-terminal errors. By default, no errors
// are logged. This is intended as a diagnostic measure. Finer-grained control
// of error handling, including logging in more detail, should be performed in a
// custom SubscriberErrorEncoder which has access to the context.
// Deprecated: Use SubscriberErrorHandler instead.
func SubscriberErrorLogger(logger log.Logger) SubscriberOption {
return func(s *Subscriber) { s.errorHandler = transport.NewLogErrorHandler(logger) }
}
// SubscriberErrorHandler is used to handle non-terminal errors. By default, non-terminal errors
// are ignored. This is intended as a diagnostic measure. Finer-grained control
// of error handling, including logging in more detail, should be performed in a
// custom SubscriberErrorEncoder which has access to the context.
func SubscriberErrorHandler(errorHandler transport.ErrorHandler) SubscriberOption {
return func(s *Subscriber) { s.errorHandler = errorHandler }
}
// ServeDelivery handles AMQP Delivery messages
// It is strongly recommended to use *amqp.Channel as the
// Channel interface implementation.
func (s Subscriber) ServeDelivery(ch Channel) func(deliv *amqp.Delivery) {
return func(deliv *amqp.Delivery) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
pub := amqp.Publishing{}
for _, f := range s.before {
ctx = f(ctx, &pub, deliv)
}
request, err := s.dec(ctx, deliv)
if err != nil {
s.errorHandler.Handle(ctx, err)
s.errorEncoder(ctx, err, deliv, ch, &pub)
return
}
response, err := s.e(ctx, request)
if err != nil {
s.errorHandler.Handle(ctx, err)
s.errorEncoder(ctx, err, deliv, ch, &pub)
return
}
for _, f := range s.after {
ctx = f(ctx, deliv, ch, &pub)
}
if err := s.enc(ctx, &pub, response); err != nil {
s.errorHandler.Handle(ctx, err)
s.errorEncoder(ctx, err, deliv, ch, &pub)
return
}
if err := s.responsePublisher(ctx, deliv, ch, &pub); err != nil {
s.errorHandler.Handle(ctx, err)
s.errorEncoder(ctx, err, deliv, ch, &pub)
return
}
}
}
// EncodeJSONResponse marshals the response as JSON as part of the
// payload of the AMQP Publishing object.
func EncodeJSONResponse(
ctx context.Context,
pub *amqp.Publishing,
response interface{},
) error {
b, err := json.Marshal(response)
if err != nil {
return err
}
pub.Body = b
return nil
}
// EncodeNopResponse is a response function that does nothing.
func EncodeNopResponse(
ctx context.Context,
pub *amqp.Publishing,
response interface{},
) error {
return nil
}
// ResponsePublisher functions are executed by the subscriber to
// publish response object to the original sender.
// Please note that the word "publisher" does not refer
// to the publisher of pub/sub.
// Rather, publisher is merely a function that publishes, or sends responses.
type ResponsePublisher func(
context.Context,
*amqp.Delivery,
Channel,
*amqp.Publishing,
) error
// DefaultResponsePublisher extracts the reply exchange and reply key
// from the request, and sends the response object to that destination.
func DefaultResponsePublisher(
ctx context.Context,
deliv *amqp.Delivery,
ch Channel,
pub *amqp.Publishing,
) error {
if pub.CorrelationId == "" {
pub.CorrelationId = deliv.CorrelationId
}
replyExchange := getPublishExchange(ctx)
replyTo := getPublishKey(ctx)
if replyTo == "" {
replyTo = deliv.ReplyTo
}
return ch.Publish(
replyExchange,
replyTo,
false, // mandatory
false, // immediate
*pub,
)
}
// NopResponsePublisher does not deliver a response to the original sender.
// This response publisher is used when the user wants the subscriber to
// receive and forget.
func NopResponsePublisher(
ctx context.Context,
deliv *amqp.Delivery,
ch Channel,
pub *amqp.Publishing,
) error {
return nil
}
// ErrorEncoder is responsible for encoding an error to the subscriber reply.
// Users are encouraged to use custom ErrorEncoders to encode errors to
// their replies, and will likely want to pass and check for their own error
// types.
type ErrorEncoder func(ctx context.Context,
err error, deliv *amqp.Delivery, ch Channel, pub *amqp.Publishing)
// DefaultErrorEncoder simply ignores the message. It does not reply
// nor Ack/Nack the message.
func DefaultErrorEncoder(ctx context.Context,
err error, deliv *amqp.Delivery, ch Channel, pub *amqp.Publishing) {
}
// SingleNackRequeueErrorEncoder issues a Nack to the delivery with multiple flag set as false
// and requeue flag set as true. It does not reply the message.
func SingleNackRequeueErrorEncoder(ctx context.Context,
err error, deliv *amqp.Delivery, ch Channel, pub *amqp.Publishing) {
deliv.Nack(
false, //multiple
true, //requeue
)
duration := getNackSleepDuration(ctx)
time.Sleep(duration)
}
// ReplyErrorEncoder serializes the error message as a DefaultErrorResponse
// JSON and sends the message to the ReplyTo address.
func ReplyErrorEncoder(
ctx context.Context,
err error,
deliv *amqp.Delivery,
ch Channel,
pub *amqp.Publishing,
) {
if pub.CorrelationId == "" {
pub.CorrelationId = deliv.CorrelationId
}
replyExchange := getPublishExchange(ctx)
replyTo := getPublishKey(ctx)
if replyTo == "" {
replyTo = deliv.ReplyTo
}
response := DefaultErrorResponse{err.Error()}
b, err := json.Marshal(response)
if err != nil {
return
}
pub.Body = b
ch.Publish(
replyExchange,
replyTo,
false, // mandatory
false, // immediate
*pub,
)
}
// ReplyAndAckErrorEncoder serializes the error message as a DefaultErrorResponse
// JSON and sends the message to the ReplyTo address then Acks the original
// message.
func ReplyAndAckErrorEncoder(ctx context.Context, err error, deliv *amqp.Delivery, ch Channel, pub *amqp.Publishing) {
ReplyErrorEncoder(ctx, err, deliv, ch, pub)
deliv.Ack(false)
}
// DefaultErrorResponse is the default structure of responses in the event
// of an error.
type DefaultErrorResponse struct {
Error string `json:"err"`
}
// Channel is a channel interface to make testing possible.
// It is highly recommended to use *amqp.Channel as the interface implementation.
type Channel interface {
Publish(exchange, key string, mandatory, immediate bool, msg amqp.Publishing) error
Consume(queue, consumer string, autoAck, exclusive, noLocal, noWail bool, args amqp.Table) (<-chan amqp.Delivery, error)
}
|