2025-11-14 08:42:26 +08:00
|
|
|
package app
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"caatsm/internal/adapter/parser"
|
2025-11-17 11:47:23 +08:00
|
|
|
"caatsm/internal/adapter/dto"
|
|
|
|
|
"caatsm/internal/infra/log"
|
|
|
|
|
"caatsm/internal/infra/telemetry"
|
|
|
|
|
"caatsm/internal/port"
|
2025-11-14 21:42:04 +08:00
|
|
|
"context"
|
2025-11-14 08:42:26 +08:00
|
|
|
"fmt"
|
2025-11-14 23:18:10 +08:00
|
|
|
"strings"
|
|
|
|
|
"time"
|
2025-11-14 22:43:04 +08:00
|
|
|
|
2025-11-15 09:01:24 +08:00
|
|
|
"go.opentelemetry.io/otel"
|
|
|
|
|
"go.opentelemetry.io/otel/attribute"
|
|
|
|
|
"go.opentelemetry.io/otel/codes"
|
|
|
|
|
"go.opentelemetry.io/otel/trace"
|
2025-11-14 08:42:26 +08:00
|
|
|
"go.uber.org/zap"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// MessageProcessor handles message processing
|
|
|
|
|
type MessageProcessor struct {
|
|
|
|
|
parser parser.Parser
|
2025-11-17 11:47:23 +08:00
|
|
|
repository port.Repository
|
|
|
|
|
publisher port.Publisher
|
2025-11-14 08:42:26 +08:00
|
|
|
logger *zap.Logger
|
2025-11-16 13:14:46 +08:00
|
|
|
telemetry telemetry.Recorder
|
2025-11-14 08:42:26 +08:00
|
|
|
}
|
|
|
|
|
|
2025-11-16 09:58:49 +08:00
|
|
|
// ProcessingStatus represents the outcome of the processing pipeline
|
|
|
|
|
// (persistence, publishing, etc.), independent from the parsing status
|
2025-11-17 11:47:23 +08:00
|
|
|
// captured in dto.MessageStatus.
|
2025-11-16 09:58:49 +08:00
|
|
|
type ProcessingStatus string
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
ProcessingStatusOK ProcessingStatus = "ok"
|
|
|
|
|
ProcessingStatusPersistFailed ProcessingStatus = "persist_failed"
|
|
|
|
|
ProcessingStatusPublishFailed ProcessingStatus = "publish_failed"
|
|
|
|
|
)
|
|
|
|
|
|
2025-11-14 08:42:26 +08:00
|
|
|
// NewMessageProcessor creates a new message processor
|
|
|
|
|
func NewMessageProcessor(
|
|
|
|
|
parser parser.Parser,
|
2025-11-17 11:47:23 +08:00
|
|
|
repository port.Repository,
|
|
|
|
|
publisher port.Publisher,
|
2025-11-16 13:14:46 +08:00
|
|
|
rec telemetry.Recorder,
|
2025-11-14 08:42:26 +08:00
|
|
|
logger *zap.Logger,
|
|
|
|
|
) *MessageProcessor {
|
|
|
|
|
return &MessageProcessor{
|
|
|
|
|
parser: parser,
|
|
|
|
|
repository: repository,
|
|
|
|
|
publisher: publisher,
|
|
|
|
|
logger: logger,
|
2025-11-16 13:14:46 +08:00
|
|
|
telemetry: rec,
|
2025-11-14 08:42:26 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Handle processes a message
|
|
|
|
|
func (p *MessageProcessor) Handle(ctx context.Context, raw []byte, msgID string) error {
|
2025-11-14 22:43:04 +08:00
|
|
|
if len(raw) == 0 {
|
2025-11-14 21:42:04 +08:00
|
|
|
return Permanent(fmt.Errorf("empty message"))
|
2025-11-14 08:42:26 +08:00
|
|
|
}
|
|
|
|
|
|
2025-11-15 09:01:24 +08:00
|
|
|
tracer := otel.Tracer("caatsm/app")
|
|
|
|
|
ctx, span := tracer.Start(ctx, "MessageProcessor.Handle")
|
|
|
|
|
defer span.End()
|
|
|
|
|
span.SetAttributes(attribute.String("nats.msg_id", msgID))
|
|
|
|
|
|
2025-11-14 23:18:10 +08:00
|
|
|
receivedAt := time.Now()
|
|
|
|
|
|
2025-11-15 09:01:24 +08:00
|
|
|
parsed, parseErr := p.parser.Parse(string(raw))
|
2025-11-14 08:42:26 +08:00
|
|
|
if parsed == nil {
|
2025-11-17 11:47:23 +08:00
|
|
|
parsed = dto.NewParsedTelegram()
|
2025-11-15 09:01:24 +08:00
|
|
|
parsed.Content = string(raw)
|
|
|
|
|
parsed.ErrorReason = "parser returned nil"
|
2025-11-17 11:47:23 +08:00
|
|
|
parsed.Status = dto.MessageStatusBodyError
|
2025-11-15 09:01:24 +08:00
|
|
|
parseErr = fmt.Errorf("parser returned nil")
|
2025-11-14 08:42:26 +08:00
|
|
|
}
|
|
|
|
|
|
2025-11-14 23:18:10 +08:00
|
|
|
if msgID != "" {
|
|
|
|
|
if parsed.Comments == "" {
|
|
|
|
|
parsed.Comments = fmt.Sprintf("nats_msg_id=%s", msgID)
|
|
|
|
|
} else if !strings.Contains(parsed.Comments, "nats_msg_id=") {
|
|
|
|
|
parsed.Comments = fmt.Sprintf("%s; nats_msg_id=%s", parsed.Comments, msgID)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if parsed.ReceivedAt.IsZero() {
|
|
|
|
|
parsed.ReceivedAt = receivedAt
|
|
|
|
|
}
|
|
|
|
|
if parsed.ParsedAt.IsZero() {
|
|
|
|
|
parsed.ParsedAt = time.Now()
|
|
|
|
|
}
|
2025-11-17 11:47:23 +08:00
|
|
|
if parsed.Status == dto.MessageStatusUnknown {
|
2025-11-15 09:01:24 +08:00
|
|
|
if parseErr == nil {
|
2025-11-17 11:47:23 +08:00
|
|
|
parsed.Status = dto.MessageStatusParsed
|
2025-11-15 09:01:24 +08:00
|
|
|
} else {
|
2025-11-17 11:47:23 +08:00
|
|
|
parsed.Status = dto.MessageStatusBodyError
|
2025-11-15 09:01:24 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-16 09:15:37 +08:00
|
|
|
// Enrich span with parsed telegram information as soon as we have it.
|
|
|
|
|
span.SetAttributes(
|
|
|
|
|
attribute.String("telegram.message_id", parsed.MessageID),
|
|
|
|
|
attribute.String("telegram.category", parsed.Category),
|
|
|
|
|
attribute.String("telegram.status", string(parsed.Status)),
|
|
|
|
|
)
|
|
|
|
|
|
2025-11-17 11:47:23 +08:00
|
|
|
msgLogger := log.WithMessageContext(p.logger, log.MessageFields{
|
2025-11-16 09:15:37 +08:00
|
|
|
Service: "caatsm-processor",
|
|
|
|
|
TransportMsgID: msgID,
|
|
|
|
|
BusinessMsgID: parsed.MessageID,
|
|
|
|
|
Category: parsed.Category,
|
|
|
|
|
})
|
|
|
|
|
|
2025-11-15 09:01:24 +08:00
|
|
|
if parseErr != nil || !parsed.Parsed {
|
|
|
|
|
if parsed.ErrorReason == "" && parseErr != nil {
|
|
|
|
|
parsed.ErrorReason = parseErr.Error()
|
|
|
|
|
}
|
|
|
|
|
span.RecordError(parseErr)
|
|
|
|
|
span.SetStatus(codes.Error, parseErr.Error())
|
|
|
|
|
p.persistRaw(ctx, parsed)
|
2025-11-16 09:15:37 +08:00
|
|
|
msgLogger.With(zap.String("status", string(parsed.Status))).
|
|
|
|
|
Warn("Message failed to parse",
|
|
|
|
|
zap.String("content_preview", truncateContent(parsed.Content, 256)),
|
|
|
|
|
zap.Error(parseErr),
|
|
|
|
|
)
|
2025-11-15 16:30:29 +08:00
|
|
|
latency := parsed.ParsedAt.Sub(receivedAt)
|
2025-11-16 13:14:46 +08:00
|
|
|
p.telemetry.RecordFailure("parser")
|
|
|
|
|
p.telemetry.RecordProcessingResult(ctx, string(parsed.Status), parsed.Category, latency)
|
2025-11-15 09:01:24 +08:00
|
|
|
return Permanent(fmt.Errorf("parser error: %w", parseErr))
|
|
|
|
|
}
|
|
|
|
|
parsed.ErrorReason = ""
|
2025-11-14 08:42:26 +08:00
|
|
|
|
|
|
|
|
// Log parsing result
|
2025-11-15 09:01:24 +08:00
|
|
|
span.SetAttributes(
|
|
|
|
|
attribute.String("telegram.status", string(parsed.Status)),
|
|
|
|
|
attribute.Bool("telegram.parsed", parsed.Parsed),
|
|
|
|
|
attribute.String("telegram.category", parsed.Category),
|
|
|
|
|
)
|
|
|
|
|
|
2025-11-16 09:15:37 +08:00
|
|
|
msgLogger.Info("Message parsed successfully",
|
2025-11-15 09:01:24 +08:00
|
|
|
zap.Time("received_at", parsed.ReceivedAt),
|
|
|
|
|
zap.Time("parsed_at", parsed.ParsedAt),
|
|
|
|
|
)
|
2025-11-14 08:42:26 +08:00
|
|
|
|
|
|
|
|
// Insert into database
|
|
|
|
|
if err := p.repository.InsertOne(ctx, parsed); err != nil {
|
2025-11-15 09:01:24 +08:00
|
|
|
span.RecordError(err)
|
|
|
|
|
span.SetStatus(codes.Error, err.Error())
|
2025-11-15 16:30:29 +08:00
|
|
|
latency := parsed.ParsedAt.Sub(receivedAt)
|
2025-11-16 13:14:46 +08:00
|
|
|
p.telemetry.RecordFailure("repository")
|
|
|
|
|
p.telemetry.RecordProcessingResult(ctx, string(parsed.Status), parsed.Category, latency)
|
2025-11-17 12:58:40 +08:00
|
|
|
// Log business layer failure with message context (Repository layer already logged technical error)
|
|
|
|
|
msgLogger.Error("Failed to persist parsed message",
|
|
|
|
|
zap.String("status", string(parsed.Status)),
|
|
|
|
|
zap.Duration("latency", latency),
|
|
|
|
|
zap.Error(err),
|
|
|
|
|
)
|
2025-11-14 08:42:26 +08:00
|
|
|
return fmt.Errorf("failed to insert message: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Publish parsed message
|
2025-11-15 09:01:24 +08:00
|
|
|
_, pubSpan := tracer.Start(ctx, "Publisher.Publish")
|
2025-11-14 08:42:26 +08:00
|
|
|
if err := p.publisher.Publish(parsed); err != nil {
|
|
|
|
|
// Log error but don't fail the entire operation
|
2025-11-16 09:15:37 +08:00
|
|
|
msgLogger.With(zap.String("status", string(parsed.Status))).
|
|
|
|
|
Error("Failed to publish message",
|
|
|
|
|
zap.Error(err),
|
|
|
|
|
)
|
2025-11-15 09:01:24 +08:00
|
|
|
pubSpan.RecordError(err)
|
|
|
|
|
pubSpan.SetStatus(codes.Error, err.Error())
|
|
|
|
|
parsed.ErrorReason = err.Error()
|
2025-11-16 13:14:46 +08:00
|
|
|
p.telemetry.RecordPublishFailure(ctx, parsed.Category)
|
2025-11-15 16:30:29 +08:00
|
|
|
latency := parsed.ParsedAt.Sub(receivedAt)
|
2025-11-16 13:14:46 +08:00
|
|
|
p.telemetry.RecordFailure("publisher")
|
|
|
|
|
p.telemetry.RecordProcessingResult(ctx, string(parsed.Status), parsed.Category, latency)
|
2025-11-15 09:01:24 +08:00
|
|
|
p.persistRaw(ctx, parsed)
|
2025-11-16 17:24:16 +08:00
|
|
|
|
|
|
|
|
// Treat clearly temporary JetStream issues (e.g. no responders) as transient so
|
|
|
|
|
// the consumer will NAK and retry according to backoff settings.
|
|
|
|
|
lowerErr := strings.ToLower(err.Error())
|
|
|
|
|
if strings.Contains(lowerErr, "no responders") {
|
|
|
|
|
pubSpan.End()
|
|
|
|
|
// Return a non-permanent error to trigger retry via nakWithStrategy in the consumer.
|
|
|
|
|
return fmt.Errorf("transient publish error: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Other publish errors are treated as permanent and will go to DLQ + ACK.
|
2025-11-15 09:01:24 +08:00
|
|
|
pubSpan.End()
|
2025-11-14 22:43:04 +08:00
|
|
|
return Permanent(fmt.Errorf("failed to publish message: %w", err))
|
2025-11-14 08:42:26 +08:00
|
|
|
}
|
2025-11-15 09:01:24 +08:00
|
|
|
pubSpan.End()
|
2025-11-14 08:42:26 +08:00
|
|
|
|
2025-11-15 16:30:29 +08:00
|
|
|
latency := parsed.ParsedAt.Sub(receivedAt)
|
2025-11-16 13:14:46 +08:00
|
|
|
p.telemetry.RecordProcessingResult(ctx, string(parsed.Status), parsed.Category, latency)
|
2025-11-15 15:27:53 +08:00
|
|
|
|
2025-11-14 08:42:26 +08:00
|
|
|
return nil
|
|
|
|
|
}
|
2025-11-14 22:43:04 +08:00
|
|
|
|
2025-11-17 11:47:23 +08:00
|
|
|
func (p *MessageProcessor) persistRaw(ctx context.Context, msg *dto.ParsedTelegram) {
|
2025-11-15 09:01:24 +08:00
|
|
|
if msg == nil || p.repository == nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if msg.Content == "" && msg.BodyData != nil {
|
|
|
|
|
msg.Content = fmt.Sprintf("%v", msg.BodyData)
|
|
|
|
|
}
|
|
|
|
|
if msg.ReceivedAt.IsZero() {
|
|
|
|
|
msg.ReceivedAt = time.Now()
|
|
|
|
|
}
|
|
|
|
|
if err := p.repository.InsertRaw(ctx, msg); err != nil {
|
2025-11-17 12:58:40 +08:00
|
|
|
// Error already logged in Repository.InsertRaw, no need to log again
|
|
|
|
|
// Just add event to span if recording
|
|
|
|
|
if span := trace.SpanFromContext(ctx); span.IsRecording() {
|
|
|
|
|
span.RecordError(err)
|
|
|
|
|
}
|
2025-11-15 09:01:24 +08:00
|
|
|
} else {
|
|
|
|
|
if span := trace.SpanFromContext(ctx); span.IsRecording() {
|
|
|
|
|
span.AddEvent("raw telegram persisted",
|
|
|
|
|
trace.WithAttributes(
|
|
|
|
|
attribute.String("telegram.status", string(msg.Status)),
|
|
|
|
|
attribute.String("telegram.message_id", msg.MessageID),
|
|
|
|
|
))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-14 22:43:04 +08:00
|
|
|
func truncateContent(content string, limit int) string {
|
|
|
|
|
if limit <= 0 || len(content) <= limit {
|
|
|
|
|
return content
|
|
|
|
|
}
|
|
|
|
|
if limit <= 3 {
|
|
|
|
|
return content[:limit]
|
|
|
|
|
}
|
|
|
|
|
return content[:limit-3] + "..."
|
|
|
|
|
}
|