feat(lab6): add observability and SLO burn-rate alerts

This commit is contained in:
2026-11-15 06:54:54 +03:00
parent 470d9d6f1e
commit 63c1f06b84
204 changed files with 25348 additions and 37 deletions
+162
View File
@@ -0,0 +1,162 @@
package main
import (
"context"
"errors"
"log"
"os"
"os/signal"
"syscall"
"time"
"mtusi2026lab6/internal/adapter/broker"
"mtusi2026lab6/internal/adapter/postgres"
"mtusi2026lab6/internal/config"
"mtusi2026lab6/internal/database"
"mtusi2026lab6/internal/domain"
apptelemetry "mtusi2026lab6/internal/telemetry"
"mtusi2026lab6/internal/worker"
)
const defaultBeforePublishFaultFile = "/tmp/mtusi-fault-before-publish"
func main() {
cfg, err := config.LoadDispatcher()
if err != nil {
log.Fatalf("[FATAL] Invalid configuration: %v", err)
}
if cfg.BrokerURL == "" {
log.Fatal("[FATAL] BROKER_URL or BROKER_URL_FILE is required")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
telemetryRuntime, err := apptelemetry.Start(ctx, "messenger-dispatcher", cfg.InstanceID, "lab")
if err != nil {
log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err)
}
defer func() {
shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil {
log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr)
}
}()
pool, err := database.Open(ctx, cfg)
if err != nil {
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
}
defer pool.Close()
if err = apptelemetry.RegisterDBPool(telemetryRuntime, pool); err != nil {
log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err)
}
store := postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout)
queueRecorder, err := apptelemetry.NewQueueRecorder(telemetryRuntime)
if err != nil {
log.Fatalf("[FATAL] Queue observability initialization failed: %v", err)
}
client, err := broker.Open(cfg.BrokerURL, 0)
if err != nil {
log.Fatalf("[FATAL] RabbitMQ initialization failed: %v", err)
}
defer client.Close()
faultFile := os.Getenv("DISPATCHER_FAULT_BEFORE_PUBLISH_FILE")
if faultFile == "" {
faultFile = defaultBeforePublishFaultFile
}
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
log.Println("[INFO] Attachment job dispatcher and lease reaper started")
nextQueueObservation := time.Time{}
for {
now := time.Now().UTC()
if !now.Before(nextQueueObservation) {
depth, ageSeconds, statsErr := store.AttachmentQueueStats(ctx, now)
if statsErr != nil {
if ctx.Err() == nil {
log.Printf("[WARN] Read queue stats failed: %v", statsErr)
}
} else {
queueRecorder.Record(ctx, depth, ageSeconds)
}
nextQueueObservation = now.Add(time.Second)
}
expired, queryErr := store.ListExpiredAttachmentJobs(ctx, now, 50)
if queryErr != nil {
if ctx.Err() != nil {
return
}
log.Printf("[WARN] List expired jobs failed: %v", queryErr)
} else {
for _, job := range expired {
delay := worker.RetryDelay(
job.JobID,
job.Attempt+1,
cfg.JobRetryBase,
cfg.JobRetryMax,
)
recovered, final, recoverErr := store.RetryAttachmentJob(
ctx,
job.JobID,
"lease_expired",
now.Add(delay),
now,
"lease_recovered",
)
if recoverErr != nil {
log.Printf("[WARN] Recover expired job %s failed: %v", job.JobID, recoverErr)
continue
}
if final && recovered.Status == domain.AttachmentJobFailed {
log.Printf("[WARN] Expired job %s exhausted retries", job.JobID)
} else if !final {
log.Printf("[INFO] Recovered expired job %s as attempt %d", job.JobID, recovered.Attempt)
}
}
}
jobs, queryErr := store.ListUnpublishedAttachmentJobs(ctx, 50)
if queryErr != nil {
if ctx.Err() != nil {
return
}
log.Printf("[WARN] List unpublished jobs failed: %v", queryErr)
} else {
for _, job := range jobs {
removeErr := os.Remove(faultFile)
if removeErr == nil {
log.Printf("[FAULT] exiting after DB commit and before publish for job %s", job.JobID)
os.Exit(87)
}
if removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) {
log.Printf("[WARN] Consume before-publish fault marker: %v", removeErr)
}
publishContext, cancel := context.WithTimeout(ctx, 10*time.Second)
publishErr := client.Publish(publishContext, job)
cancel()
if publishErr != nil {
log.Fatalf("[FATAL] Publish job %s failed: %v", job.JobID, publishErr)
}
if err = store.MarkAttachmentJobPublished(
ctx,
job.JobID,
job.Attempt,
time.Now().UTC(),
); err != nil {
// Publisher confirm proves broker acceptance. Leaving the
// marker unset intentionally causes a safe duplicate.
log.Printf("[WARN] Job %s was confirmed but publish marker failed: %v", job.JobID, err)
}
}
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
+259
View File
@@ -0,0 +1,259 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strconv"
"time"
"mtusi2026lab6/internal/adapter/broker"
"mtusi2026lab6/internal/adapter/objectstore"
"mtusi2026lab6/internal/adapter/postgres"
"mtusi2026lab6/internal/application"
"mtusi2026lab6/internal/config"
"mtusi2026lab6/internal/database"
"mtusi2026lab6/internal/domain"
"github.com/google/uuid"
)
type jobView struct {
JobID string `json:"job_id"`
AttachmentID string `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Status domain.AttachmentJobStatus `json:"status"`
Attempt int `json:"attempt"`
MaxAttempts int `json:"max_attempts"`
ErrorCode *string `json:"error_code"`
ReplayCount int `json:"replay_count"`
UpdatedAt time.Time `json:"updated_at"`
}
func main() {
if len(os.Args) < 2 {
usage()
}
switch os.Args[1] {
case "list-failed":
runListFailed()
case "replay":
runReplay()
case "inject":
runInject()
case "upgrade":
runUpgrade()
default:
usage()
}
}
func openStore(ctx context.Context, cfg config.Config) (*postgres.PostgreSQLStore, func()) {
pool, err := database.Open(ctx, cfg)
if err != nil {
log.Fatalf("PostgreSQL initialization failed: %v", err)
}
return postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout), pool.Close
}
func runListFailed() {
limit := 100
if len(os.Args) == 3 {
parsed, err := strconv.Atoi(os.Args[2])
if err != nil || parsed < 1 || parsed > 1000 {
log.Fatal("limit must be an integer between 1 and 1000")
}
limit = parsed
} else if len(os.Args) != 2 {
usage()
}
cfg, err := config.LoadDispatcher()
if err != nil {
log.Fatalf("invalid configuration: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
store, closeStore := openStore(ctx, cfg)
defer closeStore()
jobs, err := store.ListFailedAttachmentJobs(ctx, limit)
if err != nil {
log.Fatalf("list failed jobs: %v", err)
}
views := make([]jobView, 0, len(jobs))
for _, job := range jobs {
views = append(views, view(job))
}
writeJSON(views)
}
func runReplay() {
if len(os.Args) != 3 {
usage()
}
jobID := requireUUID(os.Args[2], "job_id")
cfg, err := config.LoadDispatcher()
if err != nil {
log.Fatalf("invalid configuration: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
store, closeStore := openStore(ctx, cfg)
defer closeStore()
job, err := store.ReplayFailedAttachmentJob(ctx, jobID, time.Now().UTC())
if errors.Is(err, postgres.ErrConflict) {
log.Fatal("replay rejected: job is not the active failed pipeline or retained staging is unavailable")
}
if errors.Is(err, postgres.ErrNotFound) {
log.Fatal("replay rejected: job not found")
}
if err != nil {
log.Fatalf("replay failed: %v", err)
}
writeJSON(view(job))
}
func runInject() {
if len(os.Args) != 3 {
usage()
}
jobID := requireUUID(os.Args[2], "job_id")
cfg, err := config.LoadDispatcher()
if err != nil {
log.Fatalf("invalid configuration: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
store, closeStore := openStore(ctx, cfg)
defer closeStore()
job, err := store.GetAttachmentJob(ctx, jobID)
if errors.Is(err, postgres.ErrNotFound) {
log.Fatal("inject rejected: job not found")
}
if err != nil {
log.Fatalf("read job for injection: %v", err)
}
client, err := broker.Open(cfg.BrokerURL, 1)
if err != nil {
log.Fatalf("RabbitMQ initialization failed: %v", err)
}
defer client.Close()
if err = client.Publish(ctx, job); err != nil {
log.Fatalf("inject broker message: %v", err)
}
writeJSON(view(job))
}
func runUpgrade() {
if len(os.Args) != 4 {
usage()
}
attachmentID := requireUUID(os.Args[2], "attachment_id")
targetVersion, err := strconv.Atoi(os.Args[3])
if err != nil || targetVersion != 2 {
log.Fatal("target pipeline version must be 2")
}
cfg, err := config.LoadWorker()
if err != nil {
log.Fatalf("invalid configuration: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
store, closeStore := openStore(ctx, cfg)
defer closeStore()
attachment, err := store.GetAttachmentForProcessing(ctx, attachmentID)
if errors.Is(err, postgres.ErrNotFound) {
log.Fatal("upgrade rejected: attachment not found")
}
if err != nil {
log.Fatalf("read attachment for upgrade: %v", err)
}
if attachment.PipelineVersion+1 != targetVersion {
log.Fatalf("upgrade rejected: current pipeline is v%d", attachment.PipelineVersion)
}
objects, err := objectstore.NewMinIOStore(
cfg.S3Endpoint,
cfg.S3Region,
cfg.S3Bucket,
cfg.S3AccessKeyID,
cfg.S3SecretAccessKey,
cfg.S3OperationTimeout,
)
if err != nil {
log.Fatalf("object storage initialization failed: %v", err)
}
source, err := objects.Get(ctx, attachment.ObjectKey)
if err != nil {
log.Fatalf("upgrade source original is unavailable: %v", err)
}
defer source.Body.Close()
stagingKey := fmt.Sprintf("staging/%s/v%d/original", attachment.ID, targetVersion)
if err = objects.Put(ctx, application.ObjectPut{
Key: stagingKey,
ContentType: attachment.ContentType,
SizeBytes: attachment.SizeBytes,
Body: source.Body,
}); err != nil {
log.Fatalf("create durable upgrade staging: %v", err)
}
now := time.Now().UTC()
job := domain.AttachmentJob{
SchemaVersion: 1,
JobID: uuid.NewString(),
Type: domain.AttachmentJobType,
AttachmentID: attachment.ID,
PipelineVersion: targetVersion,
Attempt: 1,
MaxAttempts: cfg.JobMaxAttempts,
Status: domain.AttachmentJobQueued,
AvailableAt: now,
CreatedAt: now,
UpdatedAt: now,
}
job, err = store.UpgradeAttachmentPipeline(ctx, attachment.ID, targetVersion, stagingKey, job, now)
if errors.Is(err, postgres.ErrConflict) {
log.Fatal("upgrade rejected: attachment is not in an upgradeable state or target is not the next version")
}
if err != nil {
// Keep the copied source: a COMMIT error is ambiguous and cleanup can
// safely remove an actual orphan after the retention period.
log.Fatalf("upgrade pipeline: %v", err)
}
writeJSON(view(job))
}
func requireUUID(value, name string) string {
if _, err := uuid.Parse(value); err != nil {
log.Fatalf("%s must be a UUID", name)
}
return value
}
func view(job domain.AttachmentJob) jobView {
return jobView{
JobID: job.JobID,
AttachmentID: job.AttachmentID,
PipelineVersion: job.PipelineVersion,
Status: job.Status,
Attempt: job.Attempt,
MaxAttempts: job.MaxAttempts,
ErrorCode: job.ErrorCode,
ReplayCount: job.ReplayCount,
UpdatedAt: job.UpdatedAt,
}
}
func writeJSON(value any) {
encoder := json.NewEncoder(os.Stdout)
encoder.SetEscapeHTML(true)
if err := encoder.Encode(value); err != nil {
log.Fatalf("encode output: %v", err)
}
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: jobctl list-failed [limit] | replay <job_id> | inject <job_id> | upgrade <attachment_id> 2")
os.Exit(2)
}
+75
View File
@@ -0,0 +1,75 @@
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"time"
"mtusi2026lab6/internal/adapter/objectstore"
"mtusi2026lab6/internal/adapter/postgres"
"mtusi2026lab6/internal/config"
"mtusi2026lab6/internal/database"
"mtusi2026lab6/internal/reconcile"
)
func main() {
apply := flag.Bool("apply", false, "apply safe repairs; default is dry-run")
gracePeriod := flag.Duration("grace-period", 15*time.Minute,
"ignore metadata and objects newer than this duration")
timeout := flag.Duration("timeout", 2*time.Minute, "maximum reconciliation runtime")
flag.Parse()
if *gracePeriod <= 0 || *timeout <= 0 {
log.Fatal("[FATAL] grace-period and timeout must be positive")
}
cfg, err := config.Load()
if err != nil {
log.Fatalf("[FATAL] Invalid configuration: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
databasePool, err := database.Open(ctx, cfg)
if err != nil {
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
}
defer databasePool.Close()
metadataStore := postgres.NewPostgreSQLStore(databasePool, cfg.DatabaseQueryTimeout)
objectStore, err := objectstore.NewMinIOStore(
cfg.S3Endpoint,
cfg.S3Region,
cfg.S3Bucket,
cfg.S3AccessKeyID,
cfg.S3SecretAccessKey,
cfg.S3OperationTimeout,
)
if err != nil {
log.Fatalf("[FATAL] Invalid object storage configuration: %v", err)
}
if err = objectStore.Ping(ctx); err != nil {
log.Fatalf("[FATAL] Object storage unavailable: %v", err)
}
reconciler, err := reconcile.New(metadataStore, objectStore)
if err != nil {
log.Fatalf("[FATAL] Reconciler initialization failed: %v", err)
}
result, err := reconciler.Run(ctx, *gracePeriod, *apply)
if err != nil {
log.Fatalf("[FATAL] Reconciliation failed: %v", err)
}
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
if err = encoder.Encode(result); err != nil {
log.Fatalf("[FATAL] Encode reconciliation result: %v", err)
}
if !*apply && len(result.Issues) > 0 {
fmt.Fprintln(os.Stderr, "dry-run found reconciliation issues; rerun with --apply after review")
}
}
+283
View File
@@ -0,0 +1,283 @@
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
cacheadapter "mtusi2026lab6/internal/adapter/cache"
"mtusi2026lab6/internal/adapter/health"
"mtusi2026lab6/internal/adapter/objectstore"
"mtusi2026lab6/internal/adapter/postgres"
redisadapter "mtusi2026lab6/internal/adapter/redis"
"mtusi2026lab6/internal/application"
"mtusi2026lab6/internal/config"
"mtusi2026lab6/internal/database"
apptelemetry "mtusi2026lab6/internal/telemetry"
"mtusi2026lab6/internal/transport/http/handlers"
"mtusi2026lab6/internal/transport/http/middleware"
)
func main() {
cfg, err := config.Load()
if err != nil {
log.Fatalf("[FATAL] Invalid configuration: %v", err)
}
telemetryRuntime, err := apptelemetry.Start(
context.Background(),
"messenger-api",
cfg.InstanceID,
"lab",
)
if err != nil {
log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err)
}
defer func() {
shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil {
log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr)
}
}()
startupContext, startupCancel := context.WithTimeout(
context.Background(),
cfg.DatabaseConnectTimeout,
)
databasePool, err := database.Open(startupContext, cfg)
startupCancel()
if err != nil {
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
}
defer databasePool.Close()
if err = apptelemetry.RegisterDBPool(telemetryRuntime, databasePool); err != nil {
log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err)
}
postgresStore := postgres.NewPostgreSQLStore(
databasePool,
cfg.DatabaseQueryTimeout,
)
minioStore, err := objectstore.NewMinIOStore(
cfg.S3Endpoint,
cfg.S3Region,
cfg.S3Bucket,
cfg.S3AccessKeyID,
cfg.S3SecretAccessKey,
cfg.S3OperationTimeout,
)
if err != nil {
log.Fatalf("[FATAL] Invalid object storage configuration: %v", err)
}
storageContext, storageCancel := context.WithTimeout(
context.Background(),
cfg.S3OperationTimeout,
)
if err = minioStore.Ping(storageContext); err != nil {
log.Printf("[WARN] Object storage unavailable at startup: %v", err)
}
storageCancel()
var applicationStore application.Repository = postgresStore
if cfg.RedisURL != "" {
redisChatCache, cacheError := redisadapter.NewRedisChatCache(
cfg.RedisURL,
cfg.RedisCacheTTL,
cfg.RedisOperationTimeout,
cfg.RedisPoolSize,
)
if cacheError != nil {
log.Fatalf("[FATAL] Invalid Redis configuration: %v", cacheError)
}
defer func() {
if closeError := redisChatCache.Close(); closeError != nil {
log.Printf("[WARN] Redis client close failed: %v", closeError)
}
}()
cacheContext, cacheCancel := context.WithTimeout(
context.Background(),
cfg.RedisOperationTimeout,
)
if cacheError = redisChatCache.Ping(cacheContext); cacheError != nil {
log.Printf("[WARN] Redis unavailable at startup; PostgreSQL fallback is active: %v", cacheError)
} else {
log.Println("[INFO] Redis chat cache is available")
}
cacheCancel()
applicationStore = cacheadapter.NewCachedRepository(
postgresStore,
redisChatCache,
log.Default(),
)
}
cursorCodec, err := application.NewCursorCodec(cfg.CursorSigningKey)
if err != nil {
log.Fatalf("[FATAL] Invalid cursor configuration: %v", err)
}
service, err := application.NewService(
applicationStore,
cursorCodec,
cfg.SessionTTL,
application.WithIdempotencyTTL(cfg.IdempotencyTTL),
application.WithObjectStore(minioStore),
application.WithJobMaxAttempts(cfg.JobMaxAttempts),
)
if err != nil {
log.Fatalf("[FATAL] Application initialization failed: %v", err)
}
handler := handlers.NewHandler(
service,
handlers.WithReadiness(
health.NewMultiChecker(databasePool, minioStore),
cfg.ReadinessTimeout,
),
handlers.WithSessionCookieSecure(cfg.SessionCookieSecure),
)
mux := http.NewServeMux()
mux.HandleFunc("GET /health/live", handler.HealthLive)
mux.HandleFunc("GET /health/lb", handler.HealthLive)
mux.HandleFunc("GET /health/ready", handler.HealthReady)
mux.HandleFunc(
"POST /api/v1/auth/sessions",
handler.CreateSession,
)
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
requireAuth := func(next http.HandlerFunc) http.HandlerFunc {
return middleware.RequireAuth(service, next)
}
mux.HandleFunc(
"GET /api/v1/users/me",
requireAuth(handler.GetMe),
)
mux.HandleFunc(
"DELETE /api/v1/auth/sessions/current",
requireAuth(handler.DeleteCurrentSession),
)
mux.HandleFunc(
"POST /api/v1/chats",
requireAuth(handler.CreateChat),
)
mux.HandleFunc(
"GET /api/v1/chats",
requireAuth(handler.ListChats),
)
mux.HandleFunc(
"GET /api/v1/chats/{chat_id}",
requireAuth(handler.GetChat),
)
mux.HandleFunc(
"POST /api/v1/chats/{chat_id}/messages",
requireAuth(handler.CreateMessage),
)
mux.HandleFunc(
"GET /api/v1/chats/{chat_id}/messages",
requireAuth(handler.GetMessages),
)
mux.HandleFunc(
"POST /api/v1/chats/{chat_id}/attachments",
requireAuth(handler.UploadAttachment),
)
mux.HandleFunc(
"GET /api/v1/attachments/{attachment_id}",
requireAuth(handler.GetAttachment),
)
mux.HandleFunc(
"GET /api/v1/attachments/{attachment_id}/content",
requireAuth(handler.DownloadAttachment),
)
var rootHandler http.Handler = mux
rootHandler = middleware.Recovery(rootHandler)
rootHandler, err = middleware.Observability(telemetryRuntime, rootHandler)
if err != nil {
log.Fatalf("[FATAL] HTTP observability initialization failed: %v", err)
}
availabilityGate := middleware.NewAvailabilityGate()
rootHandler = availabilityGate.Middleware(rootHandler)
rootHandler = middleware.RequestID(rootHandler)
rootHandler = middleware.InstanceID(cfg.InstanceID, rootHandler)
server := &http.Server{
Addr: cfg.HTTPAddress(),
Handler: rootHandler,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
serverErrors := make(chan error, 1)
go func() {
log.Printf(
"[INFO] Server instance %s starting on %s",
cfg.InstanceID,
server.Addr,
)
serverErrors <- server.ListenAndServe()
}()
shutdownSignals := make(chan os.Signal, 1)
signal.Notify(
shutdownSignals,
os.Interrupt,
syscall.SIGTERM,
)
defer signal.Stop(shutdownSignals)
select {
case serverError := <-serverErrors:
if !errors.Is(serverError, http.ErrServerClosed) {
log.Fatalf("[FATAL] Server crashed: %v", serverError)
}
case signalValue := <-shutdownSignals:
log.Printf(
"[INFO] Signal %v received. Starting graceful shutdown...",
signalValue,
)
availabilityGate.BeginDrain()
log.Printf(
"[INFO] Readiness disabled; draining new traffic for %s",
cfg.ShutdownDrainDelay,
)
time.Sleep(cfg.ShutdownDrainDelay)
shutdownContext, shutdownCancel := context.WithTimeout(
context.Background(),
cfg.ShutdownTimeout,
)
defer shutdownCancel()
if err := server.Shutdown(shutdownContext); err != nil {
log.Printf(
"[WARN] Graceful shutdown failed: %v. Forcing close.",
err,
)
_ = server.Close()
}
log.Println("[INFO] Server stopped gracefully.")
}
}
+273
View File
@@ -0,0 +1,273 @@
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"sync"
"syscall"
"time"
"mtusi2026lab6/internal/adapter/broker"
"mtusi2026lab6/internal/adapter/objectstore"
"mtusi2026lab6/internal/adapter/postgres"
"mtusi2026lab6/internal/config"
"mtusi2026lab6/internal/database"
"mtusi2026lab6/internal/domain"
apptelemetry "mtusi2026lab6/internal/telemetry"
"mtusi2026lab6/internal/worker"
)
const (
defaultBeforeObjectsFaultFile = "/tmp/mtusi-fault-before-objects"
defaultAfterObjectsFaultFile = "/tmp/mtusi-fault-after-objects"
)
func main() {
cfg, err := config.LoadWorker()
if err != nil {
log.Fatalf("[FATAL] Invalid configuration: %v", err)
}
if cfg.BrokerURL == "" {
log.Fatal("[FATAL] BROKER_URL or BROKER_URL_FILE is required")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
telemetryRuntime, err := apptelemetry.Start(
ctx,
"messenger-worker",
cfg.InstanceID,
"lab",
)
if err != nil {
log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err)
}
defer func() {
shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil {
log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr)
}
}()
jobRecorder, err := apptelemetry.NewJobRecorder(telemetryRuntime, cfg.WorkerConcurrency)
if err != nil {
log.Fatalf("[FATAL] Worker observability initialization failed: %v", err)
}
pool, err := database.Open(ctx, cfg)
if err != nil {
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
}
defer pool.Close()
if err = apptelemetry.RegisterDBPool(telemetryRuntime, pool); err != nil {
log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err)
}
store := postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout)
objects, err := objectstore.NewMinIOStore(
cfg.S3Endpoint,
cfg.S3Region,
cfg.S3Bucket,
cfg.S3AccessKeyID,
cfg.S3SecretAccessKey,
cfg.S3OperationTimeout,
)
if err != nil {
log.Fatalf("[FATAL] Object storage initialization failed: %v", err)
}
beforeFaultFile := os.Getenv("WORKER_FAULT_BEFORE_OBJECTS_FILE")
if beforeFaultFile == "" {
beforeFaultFile = defaultBeforeObjectsFaultFile
}
afterFaultFile := os.Getenv("WORKER_FAULT_AFTER_OBJECTS_FILE")
if afterFaultFile == "" {
afterFaultFile = defaultAfterObjectsFaultFile
}
processor, err := worker.NewProcessor(store, objects, worker.ProcessorHooks{
BeforeObjects: func(job domain.AttachmentJob) error {
removeErr := os.Remove(beforeFaultFile)
if errors.Is(removeErr, os.ErrNotExist) {
return nil
}
if removeErr != nil {
return fmt.Errorf("consume before-objects fault marker: %w", removeErr)
}
log.Printf("[FAULT] exiting before object writes for job %s", job.JobID)
os.Exit(85)
return nil
},
AfterObjects: func(job domain.AttachmentJob) error {
removeErr := os.Remove(afterFaultFile)
if errors.Is(removeErr, os.ErrNotExist) {
return nil
}
if removeErr != nil {
return fmt.Errorf("consume after-objects fault marker: %w", removeErr)
}
log.Printf("[FAULT] exiting after object writes and before DB commit for job %s", job.JobID)
os.Exit(86)
return nil
},
})
if err != nil {
log.Fatalf("[FATAL] Worker processor initialization failed: %v", err)
}
cleaner, err := worker.NewStagingCleaner(store, objects, cfg.StagingRetention)
if err != nil {
log.Fatalf("[FATAL] Staging cleaner initialization failed: %v", err)
}
var maintenance sync.WaitGroup
maintenance.Add(1)
go func() {
defer maintenance.Done()
runCleanup := func() {
cleanupContext, cancel := context.WithTimeout(ctx, cfg.S3OperationTimeout+cfg.DatabaseQueryTimeout)
deleted, cleanupErr := cleaner.RunOnce(cleanupContext, time.Now().UTC())
cancel()
if cleanupErr != nil && ctx.Err() == nil {
log.Printf("[WARN] Staging cleanup failed: %v", cleanupErr)
} else if deleted > 0 {
log.Printf("[INFO] Staging cleanup removed %d object(s)", deleted)
}
}
runCleanup()
ticker := time.NewTicker(cfg.StagingCleanupInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
runCleanup()
}
}
}()
client, err := broker.Open(cfg.BrokerURL, cfg.WorkerConcurrency)
if err != nil {
log.Fatalf("[FATAL] RabbitMQ initialization failed: %v", err)
}
defer client.Close()
deliveries, err := client.Consume(cfg.InstanceID)
if err != nil {
log.Fatalf("[FATAL] RabbitMQ consume failed: %v", err)
}
var group sync.WaitGroup
for index := 0; index < cfg.WorkerConcurrency; index++ {
group.Add(1)
go func(workerIndex int) {
defer group.Done()
workerID := fmt.Sprintf("%s-%d", cfg.InstanceID, workerIndex)
for delivery := range deliveries {
deliveryContext := broker.ContextFromDelivery(ctx, delivery)
message, decodeErr := broker.Decode(delivery)
if decodeErr != nil {
log.Printf("[WARN] Reject invalid broker message: %v", decodeErr)
_ = delivery.Reject(false)
continue
}
now := time.Now().UTC()
job, claimed, claimErr := store.ClaimAttachmentJob(
deliveryContext,
message,
workerID,
now.Add(cfg.JobLease),
)
if errors.Is(claimErr, postgres.ErrNotFound) {
log.Printf("[INFO] Stale broker message for missing job %s acknowledged", message.JobID)
_ = delivery.Ack(false)
continue
}
if claimErr != nil {
log.Printf("[WARN] Claim job %s failed: %v", message.JobID, claimErr)
_ = delivery.Nack(false, true)
continue
}
if !claimed {
_ = delivery.Ack(false)
continue
}
jobContext, cancel := context.WithTimeout(deliveryContext, cfg.JobTimeout)
jobContext, observedAttempt := jobRecorder.Start(
jobContext,
domain.AttachmentJobType,
broker.QueueName,
job.Attempt,
job.CreatedAt,
)
processErr := processor.Process(jobContext, job)
observedAttempt.End(processErr)
cancel()
if processErr == nil {
_ = delivery.Ack(false)
continue
}
var permanent *worker.PermanentError
if errors.As(processErr, &permanent) {
if failErr := store.FailAttachmentJob(
ctx,
job.JobID,
permanent.Code,
time.Now().UTC(),
); failErr != nil {
log.Printf("[WARN] Persist permanent failure for job %s failed: %v", job.JobID, failErr)
_ = delivery.Nack(false, true)
} else {
log.Printf("[WARN] Job %s failed permanently with %s", job.JobID, permanent.Code)
_ = delivery.Ack(false)
}
continue
}
retryAt := time.Now().UTC()
delay := worker.RetryDelay(
job.JobID,
job.Attempt+1,
cfg.JobRetryBase,
cfg.JobRetryMax,
)
retried, final, retryErr := store.RetryAttachmentJob(
ctx,
job.JobID,
"processing_failed",
retryAt.Add(delay),
retryAt,
"retry_scheduled",
)
if retryErr != nil {
log.Printf("[WARN] Schedule retry for job %s failed: %v", job.JobID, retryErr)
_ = delivery.Nack(false, true)
continue
}
if final && retried.Status == domain.AttachmentJobFailed {
log.Printf("[WARN] Job %s exhausted retries", job.JobID)
} else if final && retried.Status == domain.AttachmentJobSucceeded {
log.Printf("[INFO] Duplicate delivery for completed job %s acknowledged", job.JobID)
} else if final && retried.Status == domain.AttachmentJobSuperseded {
log.Printf("[INFO] Stale pipeline job %s acknowledged as superseded", job.JobID)
} else {
log.Printf("[INFO] Job %s retry %d scheduled after %s", job.JobID, retried.Attempt, delay)
}
_ = delivery.Ack(false)
}
}(index)
}
log.Printf(
"[INFO] Attachment worker started with concurrency=%d prefetch=%d lease=%s",
cfg.WorkerConcurrency,
cfg.WorkerConcurrency,
cfg.JobLease,
)
<-ctx.Done()
_ = client.Close()
group.Wait()
maintenance.Wait()
log.Println("[INFO] Attachment worker stopped")
}