forked from mtusi2026/mtusi2026lab7
lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
+70
-125
@@ -1,26 +1,27 @@
|
||||
// Package broker owns the RabbitMQ topology, confirmed publishing and the
|
||||
// consumer loop. Business state never lives here: PostgreSQL is the source of
|
||||
// truth for jobs and the outbox.
|
||||
// Package broker provides confirmed publishing and consumption over certificate-
|
||||
// authenticated AMQP. The operator owns topology; PostgreSQL owns business state.
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
URL string
|
||||
Role string
|
||||
Producer bool
|
||||
Exchange string
|
||||
DLX string
|
||||
Queue string
|
||||
DLQ string
|
||||
ConnectTimeout time.Duration
|
||||
ConfirmTimeout time.Duration
|
||||
Heartbeat time.Duration
|
||||
@@ -33,135 +34,85 @@ type Client struct {
|
||||
conn *amqp.Connection
|
||||
publisher *amqp.Channel
|
||||
|
||||
mu sync.Mutex
|
||||
returns chan amqp.Return
|
||||
closed chan *amqp.Error
|
||||
returns chan amqp.Return
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
// Dial connects, declares the durable topology idempotently and opens a
|
||||
// confirm-mode publisher channel.
|
||||
// Dial connects using EXTERNAL only. Relay gets a confirm-mode publisher;
|
||||
// worker opens consumer channels only when Consume is called.
|
||||
func Dial(cfg Config) (*Client, error) {
|
||||
if cfg.URL == "" {
|
||||
return nil, errors.New("broker url is empty")
|
||||
endpoint, err := url.Parse(cfg.URL)
|
||||
if err != nil || endpoint.Scheme != "amqps" || endpoint.Hostname() == "" || endpoint.User != nil {
|
||||
return nil, errors.New("broker: url must be amqps without credentials")
|
||||
}
|
||||
if endpoint.RawQuery != "" || endpoint.Fragment != "" {
|
||||
return nil, errors.New("broker: url query and fragment are not permitted")
|
||||
}
|
||||
switch cfg.Role {
|
||||
case "relay":
|
||||
if !cfg.Producer || cfg.Exchange == "" {
|
||||
return nil, errors.New("broker: relay requires producer mode and an exchange")
|
||||
}
|
||||
case "worker":
|
||||
if cfg.Producer || cfg.Queue == "" {
|
||||
return nil, errors.New("broker: worker requires consumer mode and a queue")
|
||||
}
|
||||
default:
|
||||
return nil, errors.New("broker: role must be relay or worker")
|
||||
}
|
||||
if cfg.ConnectTimeout <= 0 || cfg.ConnectTimeout > 5*time.Second {
|
||||
return nil, errors.New("broker: connect timeout must be positive and at most 5s")
|
||||
}
|
||||
clientTLS, err := tlsconfig.NewClientFromEnv(endpoint.Hostname())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure broker tls: %w", err)
|
||||
}
|
||||
|
||||
conn, err := amqp.DialConfig(cfg.URL, amqp.Config{
|
||||
Heartbeat: cfg.Heartbeat,
|
||||
Dial: amqp.DefaultDial(cfg.ConnectTimeout),
|
||||
Heartbeat: cfg.Heartbeat,
|
||||
Dial: amqp.DefaultDial(cfg.ConnectTimeout),
|
||||
TLSClientConfig: clientTLS,
|
||||
SASL: []amqp.Authentication{&amqp.ExternalAuth{}},
|
||||
Properties: amqp.Table{
|
||||
"connection_name": "messenger-relay",
|
||||
"connection_name": "messenger-" + cfg.Role,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dial broker: %w", err)
|
||||
}
|
||||
|
||||
channel, err := conn.Channel()
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
|
||||
return nil, fmt.Errorf("open topology channel: %w", err)
|
||||
client := &Client{cfg: cfg, conn: conn}
|
||||
if !cfg.Producer {
|
||||
return client, nil
|
||||
}
|
||||
|
||||
if err := declareTopology(channel, cfg); err != nil {
|
||||
_ = channel.Close()
|
||||
_ = conn.Close()
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := channel.Close(); err != nil {
|
||||
_ = conn.Close()
|
||||
|
||||
return nil, fmt.Errorf("close topology channel: %w", err)
|
||||
}
|
||||
|
||||
publisher, err := conn.Channel()
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
|
||||
return nil, fmt.Errorf("open publisher channel: %w", err)
|
||||
return nil, errors.Join(
|
||||
fmt.Errorf("open publisher channel: %w", err),
|
||||
client.Close(),
|
||||
)
|
||||
}
|
||||
|
||||
client := &Client{
|
||||
cfg: cfg,
|
||||
conn: conn,
|
||||
publisher: publisher,
|
||||
returns: make(chan amqp.Return, 16),
|
||||
closed: conn.NotifyClose(make(chan *amqp.Error, 1)),
|
||||
}
|
||||
|
||||
client.publisher = publisher
|
||||
client.returns = make(chan amqp.Return, 16)
|
||||
if err := publisher.Confirm(false); err != nil {
|
||||
_ = client.Close()
|
||||
|
||||
return nil, fmt.Errorf("enable publisher confirms: %w", err)
|
||||
return nil, errors.Join(
|
||||
fmt.Errorf("enable publisher confirms: %w", err),
|
||||
client.Close(),
|
||||
)
|
||||
}
|
||||
|
||||
publisher.NotifyReturn(client.returns)
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func declareTopology(channel *amqp.Channel, cfg Config) error {
|
||||
if err := channel.ExchangeDeclare(cfg.Exchange, "direct", true, false, false, false, nil); err != nil {
|
||||
return fmt.Errorf("declare exchange: %w", err)
|
||||
}
|
||||
|
||||
if err := channel.ExchangeDeclare(cfg.DLX, "direct", true, false, false, false, nil); err != nil {
|
||||
return fmt.Errorf("declare dlx: %w", err)
|
||||
}
|
||||
|
||||
queue, err := channel.QueueDeclare(cfg.Queue, true, false, false, false, amqp.Table{
|
||||
"x-queue-type": "quorum",
|
||||
"x-delivery-limit": int32(100),
|
||||
"x-delayed-retry-type": "all",
|
||||
"x-delayed-retry-min": int32(5000),
|
||||
"x-delayed-retry-max": int32(60000),
|
||||
"x-dead-letter-exchange": cfg.DLX,
|
||||
"x-dead-letter-routing-key": cfg.DLQ,
|
||||
"x-dead-letter-strategy": "at-least-once",
|
||||
"x-overflow": "reject-publish",
|
||||
"x-max-length": int32(100000),
|
||||
"x-consumer-timeout": int32(300000),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("declare job queue: %w", err)
|
||||
}
|
||||
|
||||
if queue.Name != cfg.Queue {
|
||||
return fmt.Errorf("broker returned queue %q, want %q", queue.Name, cfg.Queue)
|
||||
}
|
||||
|
||||
if err := channel.QueueBind(cfg.Queue, cfg.Queue, cfg.Exchange, false, nil); err != nil {
|
||||
return fmt.Errorf("bind job queue: %w", err)
|
||||
}
|
||||
|
||||
if _, err := channel.QueueDeclare(cfg.DLQ, true, false, false, false, amqp.Table{
|
||||
"x-queue-type": "quorum",
|
||||
"x-max-length": int32(100000),
|
||||
"x-overflow": "reject-publish",
|
||||
"x-message-ttl": int32(7 * 24 * 60 * 60 * 1000),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("declare dlq: %w", err)
|
||||
}
|
||||
|
||||
if err := channel.QueueBind(cfg.DLQ, cfg.DLQ, cfg.DLX, false, nil); err != nil {
|
||||
return fmt.Errorf("bind dlq: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) Connected() bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
return c.conn != nil && !c.conn.IsClosed()
|
||||
}
|
||||
|
||||
// PublishConfirmed returns only after the broker acknowledged the persistent
|
||||
// message. A duplicate publication after a crash is normal and harmless.
|
||||
func (c *Client) PublishConfirmed(ctx context.Context, routingKey string, message domain.JobMessage) error {
|
||||
if c.cfg.Role != "relay" || !c.cfg.Producer || c.publisher == nil {
|
||||
return errors.New("broker: publication is restricted to relay")
|
||||
}
|
||||
payload, err := message.MarshalPayload()
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal job message: %w", err)
|
||||
@@ -202,9 +153,8 @@ func (c *Client) PublishConfirmed(ctx context.Context, routingKey string, messag
|
||||
return errors.New("broker nacked the job message")
|
||||
}
|
||||
|
||||
// mandatory=true: an unroutable message is returned even though the
|
||||
// confirm may still be positive. The topology is declared before publish,
|
||||
// so this is a safety net rather than a normal path.
|
||||
// mandatory=true: an unroutable message is returned even if confirmed.
|
||||
// The operator must provision bindings before relay startup.
|
||||
select {
|
||||
case returned := <-c.returns:
|
||||
if returned.MessageId == message.JobID.String() {
|
||||
@@ -229,6 +179,9 @@ type Handler func(ctx context.Context, delivery amqp.Delivery) Outcome
|
||||
// Consume blocks until the context is cancelled or the consumer channel fails.
|
||||
// Each call uses its own channel so worker slots do not share prefetch state.
|
||||
func (c *Client) Consume(ctx context.Context, handler Handler) error {
|
||||
if c.cfg.Role != "worker" || c.cfg.Producer {
|
||||
return errors.New("broker: consumption is restricted to worker")
|
||||
}
|
||||
channel, err := c.conn.Channel()
|
||||
if err != nil {
|
||||
return fmt.Errorf("open consumer channel: %w", err)
|
||||
@@ -301,20 +254,12 @@ func safeHandle(ctx context.Context, handler Handler, delivery amqp.Delivery) (o
|
||||
}
|
||||
|
||||
func (c *Client) Close() error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if c.publisher != nil {
|
||||
_ = c.publisher.Close()
|
||||
c.publisher = nil
|
||||
}
|
||||
|
||||
if c.conn != nil {
|
||||
err := c.conn.Close()
|
||||
c.conn = nil
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
c.closeOnce.Do(func() {
|
||||
// Closing the connection first interrupts consumers and publication.
|
||||
// Keep pointers immutable while those operations unwind concurrently.
|
||||
if c.conn != nil && !c.conn.IsClosed() {
|
||||
c.closeErr = c.conn.CloseDeadline(time.Now().Add(time.Second))
|
||||
}
|
||||
})
|
||||
return c.closeErr
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user