Подключите RabbitMQ и отдельный обработчик заданий
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
// Package broker owns the AMQP connection for one publisher or consumer.
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
const queue = "attachment.jobs"
|
||||
|
||||
type link struct {
|
||||
conn *amqp.Connection
|
||||
channel *amqp.Channel
|
||||
}
|
||||
|
||||
func open(ctx context.Context, url string) (*link, error) {
|
||||
conn, err := amqp.DialConfig(url, amqp.Config{Heartbeat: 5 * time.Second, Dial: func(network, addr string) (net.Conn, error) {
|
||||
d := net.Dialer{Timeout: 3 * time.Second}
|
||||
c, err := d.DialContext(ctx, network, addr)
|
||||
if err == nil {
|
||||
err = c.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
}
|
||||
return c, err
|
||||
}})
|
||||
// Parse errors can contain the complete connection URL.
|
||||
if err != nil {
|
||||
return nil, errors.New("RabbitMQ connection unavailable")
|
||||
}
|
||||
l := &link{conn: conn}
|
||||
l.channel, err = conn.Channel()
|
||||
if err == nil {
|
||||
// PostgreSQL limits processing attempts. A broker redelivery can occur
|
||||
// before PostgreSQL is reachable and must leave the job recoverable.
|
||||
_, err = l.channel.QueueDeclare(queue, true, false, false, false, amqp.Table{
|
||||
"x-queue-type": "quorum", "x-delivery-limit": int32(-1),
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
l.Close()
|
||||
return nil, err
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
func (l *link) Close() { _ = l.conn.CloseDeadline(time.Now().Add(time.Second)) }
|
||||
|
||||
type Publisher struct {
|
||||
*link
|
||||
returned <-chan amqp.Return
|
||||
}
|
||||
|
||||
func NewPublisher(ctx context.Context, url string) (*Publisher, error) {
|
||||
l, err := open(ctx, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = l.channel.Confirm(false); err != nil {
|
||||
l.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Publisher{l, l.channel.NotifyReturn(make(chan amqp.Return, 1))}, nil
|
||||
}
|
||||
|
||||
// Publish has one in-flight confirm on its channel. An ambiguous result means
|
||||
// the caller discards this publisher and leaves the outbox row pending.
|
||||
func (p *Publisher) Publish(ctx context.Context, body []byte) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
stop := context.AfterFunc(ctx, p.Close)
|
||||
defer stop()
|
||||
confirmation, err := p.channel.PublishWithDeferredConfirmWithContext(ctx, "", queue, true, false, amqp.Publishing{ContentType: "application/json", DeliveryMode: amqp.Persistent, Body: body})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ok, err := confirmation.WaitContext(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return errors.New("broker did not confirm publication")
|
||||
}
|
||||
// RabbitMQ sends basic.return before the associated publisher confirm.
|
||||
select {
|
||||
case <-p.returned:
|
||||
return errors.New("broker returned publication")
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type Consumer struct {
|
||||
*link
|
||||
Deliveries <-chan amqp.Delivery
|
||||
}
|
||||
|
||||
func NewConsumer(ctx context.Context, url string) (*Consumer, error) {
|
||||
l, err := open(ctx, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = l.channel.Qos(1, 0, false); err != nil {
|
||||
l.Close()
|
||||
return nil, err
|
||||
}
|
||||
d, err := l.channel.ConsumeWithContext(ctx, queue, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
l.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Consumer{l, d}, nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
)
|
||||
|
||||
func TestConfirmAndRedeliverUnacked(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute)
|
||||
defer cancel()
|
||||
c, err := testcontainers.Run(ctx, "rabbitmq:4.1.4-alpine", testcontainers.WithEnv(map[string]string{"RABBITMQ_DEFAULT_USER": "lab", "RABBITMQ_DEFAULT_PASS": "test-only"}), testcontainers.WithExposedPorts("5672/tcp"), testcontainers.WithWaitStrategy(wait.ForLog("Server startup complete")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
testcontainers.CleanupContainer(t, c)
|
||||
endpoint, err := c.PortEndpoint(ctx, "5672/tcp", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
url := "amqp://lab:test-only@" + endpoint + "/"
|
||||
pub, err := NewPublisher(ctx, url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pub.Close()
|
||||
if err = pub.Publish(ctx, []byte("work")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Broker redeliveries while PostgreSQL is unreachable do not consume
|
||||
// the application budget. Exercise more than the quorum queue default.
|
||||
for attempt := 0; attempt <= 22; attempt++ {
|
||||
consumer, err := NewConsumer(ctx, url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case msg := <-consumer.Deliveries:
|
||||
if string(msg.Body) != "work" || msg.Redelivered != (attempt > 0) {
|
||||
t.Fatalf("unexpected delivery on attempt %d", attempt)
|
||||
}
|
||||
if attempt == 22 {
|
||||
if err := msg.Ack(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
consumer.Close()
|
||||
t.Fatalf("confirmed job missing on delivery %d", attempt+1)
|
||||
}
|
||||
consumer.Close()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user