forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,259 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/adapter/broker"
|
||||
"mtusi2026lab7/internal/adapter/objectstore"
|
||||
"mtusi2026lab7/internal/adapter/postgres"
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/config"
|
||||
"mtusi2026lab7/internal/database"
|
||||
"mtusi2026lab7/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)
|
||||
}
|
||||
Reference in New Issue
Block a user