Перенеси реализацию мессенджера из ЛР 6
Источник — проверенное рабочее дерево ЛР 6 поверх 18878d6, включая изменения после повторного ревью. SHA-256 списка исходных файлов: e45a3d85b41feff1da78dce3f20fd1f4af1c5ee629e6ed703218bc8e21ad58fe.
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
// Package broker owns the AMQP connection for one publisher or consumer.
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"net"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
const queue = "attachment.jobs"
|
||||
|
||||
// Failure codes identify the failed AMQP operation without retaining URLs,
|
||||
// broker diagnostics, delivery payloads or credentials.
|
||||
type FailureCode string
|
||||
|
||||
func (c FailureCode) Error() string { return string(c) }
|
||||
|
||||
const (
|
||||
ErrConnect FailureCode = "broker_connect"
|
||||
ErrSetup FailureCode = "broker_queue_setup"
|
||||
ErrSubscribe FailureCode = "broker_subscribe"
|
||||
ErrPublish FailureCode = "broker_publish"
|
||||
ErrConfirm FailureCode = "broker_confirm"
|
||||
ErrReturned FailureCode = "broker_returned"
|
||||
ErrAcknowledge FailureCode = "broker_acknowledge"
|
||||
ErrStreamClosed FailureCode = "broker_stream_closed"
|
||||
)
|
||||
|
||||
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, ErrConnect
|
||||
}
|
||||
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, ErrSetup
|
||||
}
|
||||
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, ErrConfirm
|
||||
}
|
||||
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 ErrPublish
|
||||
}
|
||||
ok, err := confirmation.WaitContext(ctx)
|
||||
if err != nil || !ok {
|
||||
return ErrConfirm
|
||||
}
|
||||
// RabbitMQ sends basic.return before the associated publisher confirm.
|
||||
select {
|
||||
case <-p.returned:
|
||||
return ErrReturned
|
||||
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, ErrSubscribe
|
||||
}
|
||||
d, err := l.channel.ConsumeWithContext(ctx, queue, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
l.Close()
|
||||
return nil, ErrSubscribe
|
||||
}
|
||||
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