package pipeline import ( "crypto/sha256" "errors" "fmt" "math/rand/v2" "regexp" "time" "github.com/google/uuid" ) type Job struct { SchemaVersion int `json:"schema_version"` JobID uuid.UUID `json:"job_id"` Type string `json:"type"` AttachmentID uuid.UUID `json:"attachment_id"` PipelineVersion int `json:"pipeline_version"` Attempt int `json:"attempt"` CreatedAt time.Time `json:"created_at"` Traceparent string `json:"traceparent,omitempty"` Tracestate string `json:"tracestate,omitempty"` } var traceParent = regexp.MustCompile("^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$") func (j Job) Valid() bool { return j.SchemaVersion == 1 && j.Type == "attachment.process.v1" && j.JobID != uuid.Nil && j.AttachmentID != uuid.Nil && j.PipelineVersion >= 1 && j.Attempt >= 1 && !j.CreatedAt.IsZero() && (j.Traceparent == "" || traceParent.MatchString(j.Traceparent)) && len(j.Tracestate) <= 512 } type Claim struct { Job Token uuid.UUID SourceKey string Hash []byte SizeBytes int64 MIMEType string } type Variant struct { Name, Key, MIMEType string Width, Height int SizeBytes int64 SHA256 []byte } func VariantKey(id uuid.UUID, version int, name string, hash []byte) string { return fmt.Sprintf("variants/%s/%d/%s/%x", id, version, name, hash) } func validateVariants(c *Claim, variants []Variant) error { if len(variants) != 3 { return errors.New("three variants are required") } seen := map[string]bool{} for _, v := range variants { mime := "image/jpeg" switch v.Name { case "thumbnail", "crop": case "optimized": mime = "image/webp" default: return errors.New("unknown variant") } if seen[v.Name] || v.MIMEType != mime || len(v.SHA256) != sha256.Size || v.Key != VariantKey(c.AttachmentID, c.PipelineVersion, v.Name, v.SHA256) || v.Width <= 0 || v.Height <= 0 || v.SizeBytes <= 0 { return errors.New("invalid variant metadata") } seen[v.Name] = true } return nil } type RetryPolicy struct { MaxAttempts int BaseDelay, MaxDelay time.Duration } func (p RetryPolicy) validate() error { if p.MaxAttempts < 1 || p.BaseDelay < time.Microsecond || p.MaxDelay < p.BaseDelay { return errors.New("invalid pipeline retry policy") } return nil } // Equal jitter keeps a minimum delay while distributing simultaneous failures. func (p RetryPolicy) delay(attempt int) time.Duration { limit := p.BaseDelay for i := 1; i < attempt && limit < p.MaxDelay; i++ { if limit > p.MaxDelay/2 { limit = p.MaxDelay } else { limit *= 2 } } return limit/2 + time.Duration(rand.Int64N(int64(limit-limit/2)+1)) }