Перенеси реализацию мессенджера из ЛР 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
|
||||
}
|
||||
Reference in New Issue
Block a user