forked from mtusi2026/mtusi2026lab7
194 lines
5.5 KiB
Go
194 lines
5.5 KiB
Go
package broker
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
neturl "net/url"
|
|
"os"
|
|
"sync"
|
|
"time"
|
|
|
|
"mtusi2026lab7/internal/domain"
|
|
"mtusi2026lab7/internal/security"
|
|
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/propagation"
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
const QueueName = "attachment.process.v1"
|
|
|
|
type RabbitMQ struct {
|
|
connection *amqp.Connection
|
|
channel *amqp.Channel
|
|
confirms <-chan amqp.Confirmation
|
|
publishMu sync.Mutex
|
|
}
|
|
|
|
func Open(url string, prefetch int) (*RabbitMQ, error) {
|
|
if url == "" {
|
|
return nil, fmt.Errorf("broker URL is required")
|
|
}
|
|
parsedURL, err := neturl.Parse(url)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse broker URL: %w", err)
|
|
}
|
|
connectionConfig := amqp.Config{Heartbeat: 10 * time.Second, Locale: "en_US"}
|
|
if parsedURL.Scheme == "amqps" {
|
|
serverName := os.Getenv("BROKER_TLS_SERVER_NAME")
|
|
if serverName == "" {
|
|
serverName = "dependency-gateway"
|
|
}
|
|
connectionConfig.TLSClientConfig, err = security.ClientMTLSConfig(
|
|
os.Getenv("CLIENT_TLS_CA_FILE"),
|
|
os.Getenv("CLIENT_TLS_CERT_FILE"),
|
|
os.Getenv("CLIENT_TLS_KEY_FILE"),
|
|
serverName,
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("configure broker mTLS: %w", err)
|
|
}
|
|
}
|
|
connection, err := amqp.DialConfig(url, connectionConfig)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("connect RabbitMQ: %w", err)
|
|
}
|
|
channel, err := connection.Channel()
|
|
if err != nil {
|
|
_ = connection.Close()
|
|
return nil, fmt.Errorf("open RabbitMQ channel: %w", err)
|
|
}
|
|
if _, err = channel.QueueDeclare(QueueName, true, false, false, false, nil); err != nil {
|
|
_ = channel.Close()
|
|
_ = connection.Close()
|
|
return nil, fmt.Errorf("declare RabbitMQ queue: %w", err)
|
|
}
|
|
if prefetch > 0 {
|
|
if err = channel.Qos(prefetch, 0, false); err != nil {
|
|
_ = channel.Close()
|
|
_ = connection.Close()
|
|
return nil, fmt.Errorf("set RabbitMQ prefetch: %w", err)
|
|
}
|
|
}
|
|
client := &RabbitMQ{connection: connection, channel: channel}
|
|
if err = channel.Confirm(false); err != nil {
|
|
client.Close()
|
|
return nil, fmt.Errorf("enable RabbitMQ publisher confirms: %w", err)
|
|
}
|
|
client.confirms = channel.NotifyPublish(make(chan amqp.Confirmation, 1))
|
|
return client, nil
|
|
}
|
|
|
|
func (client *RabbitMQ) Publish(ctx context.Context, job domain.AttachmentJob) (err error) {
|
|
parentCarrier := propagation.MapCarrier{}
|
|
if job.TraceParent != "" {
|
|
parentCarrier.Set("traceparent", job.TraceParent)
|
|
}
|
|
if job.TraceState != "" {
|
|
parentCarrier.Set("tracestate", job.TraceState)
|
|
}
|
|
ctx = otel.GetTextMapPropagator().Extract(ctx, parentCarrier)
|
|
ctx, span := otel.Tracer("mtusi2026lab7/broker").Start(
|
|
ctx,
|
|
QueueName+" publish",
|
|
trace.WithSpanKind(trace.SpanKindProducer),
|
|
trace.WithAttributes(
|
|
attribute.String("messaging.system", "rabbitmq"),
|
|
attribute.String("messaging.destination.name", QueueName),
|
|
attribute.String("messaging.operation.name", "publish"),
|
|
attribute.Int("job.attempt", job.Attempt),
|
|
),
|
|
)
|
|
defer func() {
|
|
if err != nil {
|
|
span.SetStatus(codes.Error, "broker publish failed")
|
|
} else {
|
|
span.SetStatus(codes.Ok, "")
|
|
}
|
|
span.End()
|
|
}()
|
|
|
|
body, err := json.Marshal(job.Message())
|
|
if err != nil {
|
|
return fmt.Errorf("encode attachment job: %w", err)
|
|
}
|
|
traceCarrier := propagation.MapCarrier{}
|
|
otel.GetTextMapPropagator().Inject(ctx, traceCarrier)
|
|
headers := amqp.Table{}
|
|
for _, key := range traceCarrier.Keys() {
|
|
headers[key] = traceCarrier.Get(key)
|
|
}
|
|
|
|
client.publishMu.Lock()
|
|
defer client.publishMu.Unlock()
|
|
if err = client.channel.PublishWithContext(ctx, "", QueueName, false, false, amqp.Publishing{
|
|
DeliveryMode: amqp.Persistent,
|
|
ContentType: "application/json",
|
|
Type: domain.AttachmentJobType,
|
|
MessageId: job.JobID,
|
|
Timestamp: time.Now().UTC(),
|
|
Headers: headers,
|
|
Body: body,
|
|
}); err != nil {
|
|
return fmt.Errorf("publish attachment job: %w", err)
|
|
}
|
|
select {
|
|
case confirmation, ok := <-client.confirms:
|
|
if !ok {
|
|
return fmt.Errorf("publisher confirm channel closed")
|
|
}
|
|
if !confirmation.Ack {
|
|
return fmt.Errorf("broker rejected attachment job")
|
|
}
|
|
return nil
|
|
case <-ctx.Done():
|
|
return fmt.Errorf("wait for publisher confirm: %w", ctx.Err())
|
|
}
|
|
}
|
|
|
|
func ContextFromDelivery(ctx context.Context, delivery amqp.Delivery) context.Context {
|
|
carrier := propagation.MapCarrier{}
|
|
for key, value := range delivery.Headers {
|
|
if text, ok := value.(string); ok {
|
|
carrier.Set(key, text)
|
|
}
|
|
}
|
|
return otel.GetTextMapPropagator().Extract(ctx, carrier)
|
|
}
|
|
|
|
func (client *RabbitMQ) Consume(consumerName string) (<-chan amqp.Delivery, error) {
|
|
deliveries, err := client.channel.Consume(QueueName, consumerName, false, false, false, false, nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("consume attachment jobs: %w", err)
|
|
}
|
|
return deliveries, nil
|
|
}
|
|
|
|
func Decode(delivery amqp.Delivery) (domain.AttachmentJobMessage, error) {
|
|
var message domain.AttachmentJobMessage
|
|
if err := json.Unmarshal(delivery.Body, &message); err != nil {
|
|
return message, fmt.Errorf("decode attachment job: %w", err)
|
|
}
|
|
if message.SchemaVersion != 1 || message.Type != domain.AttachmentJobType || message.JobID == "" || message.AttachmentID == "" || message.PipelineVersion < 1 || message.Attempt < 1 {
|
|
return message, fmt.Errorf("attachment job has invalid required fields")
|
|
}
|
|
return message, nil
|
|
}
|
|
|
|
func (client *RabbitMQ) Close() error {
|
|
if client == nil {
|
|
return nil
|
|
}
|
|
if client.channel != nil {
|
|
_ = client.channel.Close()
|
|
}
|
|
if client.connection != nil {
|
|
return client.connection.Close()
|
|
}
|
|
return nil
|
|
}
|