lab5 done
This commit is contained in:
@@ -33,7 +33,7 @@ func (h *Chat) uploadAttachment(c echo.Context) error {
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, a)
|
||||
return c.JSON(http.StatusAccepted, a)
|
||||
}
|
||||
func (h *Chat) getAttachment(c echo.Context) error {
|
||||
a, err := h.attachments.Get(c.Request().Context(), c.Param("attachment_id"), authenticatedUser(c).ID)
|
||||
@@ -51,8 +51,15 @@ func (h *Chat) attachmentContent(c echo.Context) error {
|
||||
if err != nil {
|
||||
return h.invalid(c, "Некорректный variant")
|
||||
}
|
||||
if present && variant != "original" {
|
||||
return h.writeError(c, 404, "not_found", "Вариант не найден")
|
||||
if a.Status != "ready" {
|
||||
return h.writeError(c, 409, "conflict", "Вложение не готово")
|
||||
}
|
||||
if !present {
|
||||
variant = "original"
|
||||
}
|
||||
a, err = h.attachments.Variant(a, variant)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(c.Request().Context(), 45*time.Second)
|
||||
defer cancel()
|
||||
|
||||
@@ -35,6 +35,9 @@ func (h *Chat) useCaseError(c echo.Context, err error) error {
|
||||
switch applicationError.Code {
|
||||
case "unsupported_media_type":
|
||||
status = http.StatusUnsupportedMediaType
|
||||
case "rate_limited":
|
||||
status = http.StatusTooManyRequests
|
||||
c.Response().Header().Set("Retry-After", "2")
|
||||
case "payload_too_large":
|
||||
status = http.StatusRequestEntityTooLarge
|
||||
case domain.ErrorUnavailable:
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Concurrency, Prefetch, MaxOutstanding, MaxAttempts, PixelBudget int
|
||||
Timeout, Lease time.Duration
|
||||
}
|
||||
|
||||
func LoadOptions() (Options, error) {
|
||||
o := Options{}
|
||||
for _, v := range []struct {
|
||||
name string
|
||||
target *int
|
||||
def, max int
|
||||
}{
|
||||
{"WORKER_CONCURRENCY", &o.Concurrency, 2, 8}, {"WORKER_PREFETCH", &o.Prefetch, 4, 32},
|
||||
{"MAX_OUTSTANDING_JOBS", &o.MaxOutstanding, 200, 10000}, {"WORKER_MAX_ATTEMPTS", &o.MaxAttempts, 5, 20},
|
||||
{"WORKER_PIXEL_BUDGET", &o.PixelBudget, 40000000, 80000000},
|
||||
} {
|
||||
n := v.def
|
||||
if raw := os.Getenv(v.name); raw != "" {
|
||||
var err error
|
||||
n, err = strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return o, fmt.Errorf("invalid %s", v.name)
|
||||
}
|
||||
}
|
||||
if n < 1 || n > v.max {
|
||||
return o, fmt.Errorf("invalid %s", v.name)
|
||||
}
|
||||
*v.target = n
|
||||
}
|
||||
for _, v := range []struct {
|
||||
name string
|
||||
target *time.Duration
|
||||
def int
|
||||
}{{"WORKER_TIMEOUT_SECONDS", &o.Timeout, 25}, {"WORKER_LEASE_SECONDS", &o.Lease, 40}} {
|
||||
n := v.def
|
||||
if raw := os.Getenv(v.name); raw != "" {
|
||||
var e error
|
||||
n, e = strconv.Atoi(raw)
|
||||
if e != nil {
|
||||
return o, fmt.Errorf("invalid %s", v.name)
|
||||
}
|
||||
}
|
||||
if n < 1 || n > 300 {
|
||||
return o, fmt.Errorf("invalid %s", v.name)
|
||||
}
|
||||
*v.target = time.Duration(n) * time.Second
|
||||
}
|
||||
if o.Lease < o.Timeout+5*time.Second {
|
||||
return o, fmt.Errorf("worker lease must exceed timeout by at least 5s")
|
||||
}
|
||||
if o.PixelBudget < int(MaxPixels) {
|
||||
return o, fmt.Errorf("WORKER_PIXEL_BUDGET must allow one 40MP image")
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
func NewAsync(pool *pgxpool.Pool, store *Store, o Options) *Service {
|
||||
s := New(pool, store)
|
||||
s.Async = true
|
||||
s.Options = o
|
||||
return s
|
||||
}
|
||||
func (s *Service) Upload(ctx context.Context, chatID, userID, name, contentType string, body interface{ Read([]byte) (int, error) }) (Attachment, error) {
|
||||
if !s.Async {
|
||||
return s.uploadSync(ctx, chatID, userID, name, contentType, body)
|
||||
}
|
||||
if err := ValidateFilename(name); err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, UploadTimeout)
|
||||
defer cancel()
|
||||
select {
|
||||
case s.slots <- struct{}{}:
|
||||
defer func() { <-s.slots }()
|
||||
case <-ctx.Done():
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
original, err := Spool(ctx, body, contentType)
|
||||
if err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
defer original.Close()
|
||||
tx, err := s.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
// All API replicas serialize admission, including inserts before their COMMIT.
|
||||
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(578903551)`); err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
var pending int
|
||||
if err = tx.QueryRow(ctx, `SELECT count(*) FROM attachment_jobs WHERE state IN ('queued','processing')`).Scan(&pending); err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
if pending >= s.Options.MaxOutstanding {
|
||||
return Attachment{}, appError("rate_limited", "Очередь заполнена; повторите загрузку позднее")
|
||||
}
|
||||
a := Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: name, ContentType: original.ContentType, Size: original.Size, SHA256: original.SHA256, Status: "queued", Variants: []any{}, PipelineVersion: 1}
|
||||
stage := "staging/" + a.ID
|
||||
a.Key = effectKey(a.ID, 1, "original")
|
||||
// The stage lock protects even a slow PUT from the orphan cleaner.
|
||||
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, stage); err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
if err = s.put(ctx, stage, original.File, original.Size, original.ContentType); err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,uploader_id,filename,object_key,content_type,size_bytes,sha256,width,height,status,staging_key) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,'queued',$11) RETURNING created_at,updated_at`, a.ID, chatID, userID, name, a.Key, a.ContentType, a.Size, a.SHA256, original.Width, original.Height, stage).Scan(&a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
job := uuid.NewString()
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,state,max_attempts) VALUES($1,$2,'queued',$3)`, job, a.ID, s.Options.MaxAttempts); err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id) VALUES($1)`, job); err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
func effectKey(id string, version int, name string) string {
|
||||
return fmt.Sprintf("original/%s/v%d/%s", id, version, name)
|
||||
}
|
||||
func (s *Service) Variant(a Attachment, name string) (Attachment, error) {
|
||||
if name == "original" {
|
||||
return a, nil
|
||||
}
|
||||
for _, item := range a.Variants {
|
||||
raw, _ := json.Marshal(item)
|
||||
var v Variant
|
||||
if json.Unmarshal(raw, &v) == nil && v.Name == name {
|
||||
a.Key = effectKey(a.ID, a.PipelineVersion, name)
|
||||
a.ContentType = v.ContentType
|
||||
return a, nil
|
||||
}
|
||||
}
|
||||
return Attachment{}, appError(domain.ErrorNotFound, "Вариант не найден")
|
||||
}
|
||||
@@ -139,7 +139,7 @@ func (s *Service) reconcileObject(ctx context.Context, key string, cutoff time.T
|
||||
defer tx.Rollback(context.Background())
|
||||
var exists bool
|
||||
r.DBQueries++
|
||||
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)`, key).Scan(&exists); err != nil {
|
||||
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1 OR staging_key=$1 OR $1 LIKE 'original/'||id::text||'/v'||pipeline_version::text||'/%')`, key).Scan(&exists); err != nil {
|
||||
return fmt.Errorf("metadata recheck failed")
|
||||
}
|
||||
if exists {
|
||||
@@ -207,9 +207,12 @@ func (s *Service) reconcileMetadata(ctx context.Context, id, key string, cutoff
|
||||
}
|
||||
if apply {
|
||||
r.DBQueries++
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='original_missing' WHERE id=$1 AND status='ready'`, id); err != nil {
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='original_missing',updated_at=clock_timestamp() WHERE id=$1 AND status='ready'`, id); err != nil {
|
||||
return fmt.Errorf("mark missing failed")
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state='failed',last_error='original_missing',fence=fence+1,updated_at=clock_timestamp() WHERE attachment_id=$1 AND state='ready'`, id); err != nil {
|
||||
return fmt.Errorf("mark job missing failed")
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit missing failed")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"math"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
var ErrInvalidImage = errors.New("invalid image")
|
||||
|
||||
type oriented struct {
|
||||
image.Image
|
||||
orientation int
|
||||
}
|
||||
|
||||
func (o oriented) Bounds() image.Rectangle {
|
||||
b := o.Image.Bounds()
|
||||
w, h := b.Dx(), b.Dy()
|
||||
if o.orientation >= 5 && o.orientation <= 8 {
|
||||
w, h = h, w
|
||||
}
|
||||
return image.Rect(0, 0, w, h)
|
||||
}
|
||||
func (o oriented) At(x, y int) color.Color {
|
||||
b := o.Image.Bounds()
|
||||
w, h := b.Dx(), b.Dy()
|
||||
sx, sy := x, y
|
||||
switch o.orientation {
|
||||
case 2:
|
||||
sx = w - 1 - x
|
||||
case 3:
|
||||
sx, sy = w-1-x, h-1-y
|
||||
case 4:
|
||||
sy = h - 1 - y
|
||||
case 5:
|
||||
sx, sy = y, x
|
||||
case 6:
|
||||
sx, sy = y, h-1-x
|
||||
case 7:
|
||||
sx, sy = w-1-y, h-1-x
|
||||
case 8:
|
||||
sx, sy = w-1-y, x
|
||||
}
|
||||
r, g, blue, a := o.Image.At(b.Min.X+sx, b.Min.Y+sy).RGBA()
|
||||
white := uint32(65535) - a
|
||||
return color.RGBA{uint8((r + white) / 257), uint8((g + white) / 257), uint8((blue + white) / 257), 255}
|
||||
}
|
||||
|
||||
// EXIF IFD0 orientation; bounded segment parsing does not follow client offsets outside APP1.
|
||||
func tiffOrientation(t []byte) int {
|
||||
if len(t) < 8 {
|
||||
return 1
|
||||
}
|
||||
var order binary.ByteOrder
|
||||
if string(t[:2]) == "II" {
|
||||
order = binary.LittleEndian
|
||||
} else if string(t[:2]) == "MM" {
|
||||
order = binary.BigEndian
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
if order.Uint16(t[2:4]) != 42 {
|
||||
return 1
|
||||
}
|
||||
offset := uint64(order.Uint32(t[4:8]))
|
||||
if offset+2 > uint64(len(t)) {
|
||||
return 1
|
||||
}
|
||||
count := uint64(order.Uint16(t[offset : offset+2]))
|
||||
for k := uint64(0); k < count; k++ {
|
||||
p := offset + 2 + k*12
|
||||
if p+12 > uint64(len(t)) {
|
||||
break
|
||||
}
|
||||
entry := t[p : p+12]
|
||||
if order.Uint16(entry[:2]) == 0x112 && order.Uint16(entry[2:4]) == 3 && order.Uint32(entry[4:8]) == 1 {
|
||||
v := int(order.Uint16(entry[8:10]))
|
||||
if v >= 1 && v <= 8 {
|
||||
return v
|
||||
}
|
||||
}
|
||||
}
|
||||
return 1
|
||||
}
|
||||
func Orientation(data []byte) int {
|
||||
if len(data) >= 8 && bytes.Equal(data[:8], []byte{137, 80, 78, 71, 13, 10, 26, 10}) {
|
||||
for i := 8; i+12 <= len(data); {
|
||||
n := uint64(binary.BigEndian.Uint32(data[i : i+4]))
|
||||
if n > uint64(len(data)-i-12) {
|
||||
return 1
|
||||
}
|
||||
end := i + 8 + int(n)
|
||||
if string(data[i+4:i+8]) == "eXIf" {
|
||||
return tiffOrientation(data[i+8 : end])
|
||||
}
|
||||
i = end + 4
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if len(data) < 4 || data[0] != 255 || data[1] != 216 {
|
||||
return 1
|
||||
}
|
||||
for i := 2; i+4 <= len(data); {
|
||||
if data[i] != 255 {
|
||||
return 1
|
||||
}
|
||||
for i+1 < len(data) && data[i+1] == 255 {
|
||||
i++
|
||||
}
|
||||
if i+3 >= len(data) {
|
||||
return 1
|
||||
}
|
||||
marker := data[i+1]
|
||||
i += 2
|
||||
if marker == 0xda || marker == 0xd9 {
|
||||
return 1
|
||||
}
|
||||
if marker == 0x01 || marker >= 0xd0 && marker <= 0xd7 {
|
||||
continue
|
||||
}
|
||||
n := int(binary.BigEndian.Uint16(data[i : i+2]))
|
||||
if n < 2 || i+n > len(data) {
|
||||
return 1
|
||||
}
|
||||
body := data[i+2 : i+n]
|
||||
i += n
|
||||
if marker == 0xe1 && len(body) >= 14 && bytes.Equal(body[:6], []byte("Exif\x00\x00")) {
|
||||
return tiffOrientation(body[6:])
|
||||
}
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func fit(w, h, maxSide int) (int, int) {
|
||||
if w <= maxSide && h <= maxSide {
|
||||
return w, h
|
||||
}
|
||||
if w >= h {
|
||||
return maxSide, max(1, int(int64(h)*int64(maxSide)/int64(w)))
|
||||
}
|
||||
return max(1, int(int64(w)*int64(maxSide)/int64(h))), maxSide
|
||||
}
|
||||
|
||||
func resize(src image.Image, region image.Rectangle, w, h int) *image.RGBA {
|
||||
out := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
fy := (float64(y)+.5)*float64(region.Dy())/float64(h) - .5
|
||||
fy = math.Max(0, fy)
|
||||
y0 := min(int(fy), region.Dy()-1)
|
||||
y1 := min(y0+1, region.Dy()-1)
|
||||
dy := fy - float64(y0)
|
||||
for x := 0; x < w; x++ {
|
||||
fx := (float64(x)+.5)*float64(region.Dx())/float64(w) - .5
|
||||
fx = math.Max(0, fx)
|
||||
x0 := min(int(fx), region.Dx()-1)
|
||||
x1 := min(x0+1, region.Dx()-1)
|
||||
dx := fx - float64(x0)
|
||||
colors := [4]color.RGBA{color.RGBAModel.Convert(src.At(region.Min.X+x0, region.Min.Y+y0)).(color.RGBA), color.RGBAModel.Convert(src.At(region.Min.X+x1, region.Min.Y+y0)).(color.RGBA), color.RGBAModel.Convert(src.At(region.Min.X+x0, region.Min.Y+y1)).(color.RGBA), color.RGBAModel.Convert(src.At(region.Min.X+x1, region.Min.Y+y1)).(color.RGBA)}
|
||||
blend := func(a, b, c, d uint8) uint8 {
|
||||
return uint8(math.Round(float64(a)*(1-dx)*(1-dy) + float64(b)*dx*(1-dy) + float64(c)*(1-dx)*dy + float64(d)*dx*dy))
|
||||
}
|
||||
out.SetRGBA(x, y, color.RGBA{blend(colors[0].R, colors[1].R, colors[2].R, colors[3].R), blend(colors[0].G, colors[1].G, colors[2].G, colors[3].G), blend(colors[0].B, colors[1].B, colors[2].B, colors[3].B), 255})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Render runs only inside a deadline-killed child, never in the HTTP process.
|
||||
func Render(ctx context.Context, source, dir, expectedSHA string) error {
|
||||
raw, err := os.ReadFile(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
if int64(len(raw)) > MaxBytes || hex.EncodeToString(sum[:]) != expectedSHA {
|
||||
return ErrInvalidImage
|
||||
}
|
||||
cfg, _, err := image.DecodeConfig(bytes.NewReader(raw))
|
||||
if err != nil || cfg.Width < 1 || cfg.Height < 1 || int64(cfg.Width) > MaxPixels/int64(cfg.Height) {
|
||||
return ErrInvalidImage
|
||||
}
|
||||
if os.Getenv("PIPELINE_FAILPOINT") == "renderer_timeout" {
|
||||
fifo := filepath.Join(dir, "blocked-input.png")
|
||||
if err = syscall.Mkfifo(fifo, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
return exec.CommandContext(ctx, "cwebp", "-quiet", fifo, "-o", filepath.Join(dir, "blocked.webp")).Run()
|
||||
}
|
||||
decoded, _, err := image.Decode(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return ErrInvalidImage
|
||||
}
|
||||
src := oriented{decoded, Orientation(raw)}
|
||||
bounds := src.Bounds()
|
||||
tw, th := fit(bounds.Dx(), bounds.Dy(), 256)
|
||||
ow, oh := fit(bounds.Dx(), bounds.Dy(), 1280)
|
||||
variants := []Variant{}
|
||||
for _, name := range []string{"thumbnail", "crop", "optimized"} {
|
||||
w, h := tw, th
|
||||
region := bounds
|
||||
if name == "crop" {
|
||||
w, h = 128, 128
|
||||
side := min(bounds.Dx(), bounds.Dy())
|
||||
left, top := (bounds.Dx()-side)/2, (bounds.Dy()-side)/2
|
||||
region = image.Rect(left, top, left+side, top+side)
|
||||
}
|
||||
if name == "optimized" {
|
||||
w, h = ow, oh
|
||||
}
|
||||
img := resize(src, region, w, h)
|
||||
path := filepath.Join(dir, name)
|
||||
if name == "optimized" {
|
||||
input := filepath.Join(dir, "webp-input.png")
|
||||
f, e := os.Create(input)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
e = png.Encode(f, img)
|
||||
f.Close()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
command := exec.CommandContext(ctx, "cwebp", "-quiet", "-q", "80", "-m", "4", "-metadata", "none", input, "-o", path)
|
||||
if err = command.Run(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
f, e := os.Create(path)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
e = jpeg.Encode(f, img, &jpeg.Options{Quality: 85})
|
||||
f.Close()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
data, e := os.ReadFile(path)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
hash := sha256.Sum256(data)
|
||||
mime := "image/jpeg"
|
||||
if name == "optimized" {
|
||||
mime = "image/webp"
|
||||
}
|
||||
variants = append(variants, Variant{Name: name, ContentType: mime, Width: w, Height: h, Size: int64(len(data)), SHA256: hex.EncodeToString(hash[:])})
|
||||
}
|
||||
data, err := json.Marshal(variants)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(filepath.Join(dir, "manifest.json"), data, 0600)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"image"
|
||||
"image/color"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFitGeometry(t *testing.T) {
|
||||
for _, c := range []struct{ w, h, limit, x, y int }{{320, 200, 256, 256, 160}, {513, 257, 256, 256, 128}, {257, 513, 256, 128, 256}, {12, 8, 256, 12, 8}, {1, 40000, 256, 1, 256}} {
|
||||
w, h := fit(c.w, c.h, c.limit)
|
||||
if w != c.x || h != c.y {
|
||||
t.Fatalf("fit(%d,%d)=%d,%d", c.w, c.h, w, h)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestOrientationsAndAlpha(t *testing.T) {
|
||||
img := image.NewNRGBA(image.Rect(0, 0, 3, 2))
|
||||
for y := 0; y < 2; y++ {
|
||||
for x := 0; x < 3; x++ {
|
||||
img.SetNRGBA(x, y, color.NRGBA{R: uint8(1 + x + y*3), A: 255})
|
||||
}
|
||||
}
|
||||
expected := [][]uint8{{1, 2, 3, 4, 5, 6}, {3, 2, 1, 6, 5, 4}, {6, 5, 4, 3, 2, 1}, {4, 5, 6, 1, 2, 3}, {1, 4, 2, 5, 3, 6}, {4, 1, 5, 2, 6, 3}, {6, 3, 5, 2, 4, 1}, {3, 6, 2, 5, 1, 4}}
|
||||
for i, want := range expected {
|
||||
src := oriented{img, i + 1}
|
||||
got := []uint8{}
|
||||
for y := 0; y < src.Bounds().Dy(); y++ {
|
||||
for x := 0; x < src.Bounds().Dx(); x++ {
|
||||
got = append(got, src.At(x, y).(color.RGBA).R)
|
||||
}
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("orientation %d: %v want %v", i+1, got, want)
|
||||
}
|
||||
}
|
||||
img.SetNRGBA(0, 0, color.NRGBA{R: 255, A: 128})
|
||||
got := oriented{img, 1}.At(0, 0).(color.RGBA)
|
||||
if got != (color.RGBA{255, 127, 127, 255}) {
|
||||
t.Fatalf("white alpha: %v", got)
|
||||
}
|
||||
}
|
||||
func TestEXIFOrientation(t *testing.T) {
|
||||
for _, order := range []binary.ByteOrder{binary.LittleEndian, binary.BigEndian} {
|
||||
for v := 1; v <= 8; v++ {
|
||||
tiff := make([]byte, 26)
|
||||
copy(tiff, "II")
|
||||
if order == binary.BigEndian {
|
||||
copy(tiff, "MM")
|
||||
}
|
||||
order.PutUint16(tiff[2:], 42)
|
||||
order.PutUint32(tiff[4:], 8)
|
||||
order.PutUint16(tiff[8:], 1)
|
||||
order.PutUint16(tiff[10:], 0x112)
|
||||
order.PutUint16(tiff[12:], 3)
|
||||
order.PutUint32(tiff[14:], 1)
|
||||
order.PutUint16(tiff[18:], uint16(v))
|
||||
data := append([]byte{255, 216, 255, 225, 0, 34}, append([]byte("Exif\x00\x00"), tiff...)...)
|
||||
if Orientation(data) != v {
|
||||
t.Fatalf("EXIF value %d", v)
|
||||
}
|
||||
pngData := []byte{137, 80, 78, 71, 13, 10, 26, 10}
|
||||
size := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(size, uint32(len(tiff)))
|
||||
pngData = append(pngData, size...)
|
||||
pngData = append(pngData, []byte("eXIf")...)
|
||||
pngData = append(pngData, tiff...)
|
||||
pngData = append(pngData, 0, 0, 0, 0)
|
||||
if Orientation(pngData) != v {
|
||||
t.Fatalf("PNG EXIF value %d", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, b := range [][]byte{nil, {}, {255, 216, 255, 225, 255, 255}, {255, 216, 255, 255, 225, 0, 2}} {
|
||||
if Orientation(b) != 1 {
|
||||
t.Fatal("malformed EXIF should be ignored")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
@@ -19,32 +20,35 @@ const UploadTimeout = 45 * time.Second
|
||||
const MinimumGrace = 90 * time.Second
|
||||
|
||||
type Attachment struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
Size int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []any `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Key string `json:"-"`
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
Size int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []any `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Key string `json:"-"`
|
||||
PipelineVersion int `json:"-"`
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
Pool *pgxpool.Pool
|
||||
Store *Store
|
||||
slots chan struct{}
|
||||
Pool *pgxpool.Pool
|
||||
Store *Store
|
||||
slots chan struct{}
|
||||
Async bool
|
||||
Options Options
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, store *Store) *Service {
|
||||
return &Service{Pool: pool, Store: store, slots: make(chan struct{}, 1)}
|
||||
}
|
||||
func (s *Service) Ready(ctx context.Context) error { return s.Store.Ready(ctx) }
|
||||
func (s *Service) Upload(ctx context.Context, chatID, userID, name, contentType string, body io.Reader) (Attachment, error) {
|
||||
func (s *Service) uploadSync(ctx context.Context, chatID, userID, name, contentType string, body io.Reader) (Attachment, error) {
|
||||
if err := ValidateFilename(name); err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
@@ -98,17 +102,19 @@ func (s *Service) Get(ctx context.Context, id, userID string) (Attachment, error
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
a := Attachment{Variants: []any{}}
|
||||
err = s.Pool.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.uploader_id::text,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,a.error_code,a.created_at FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=$1 AND m.user_id=$2`, parsed.String(), userID).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.Key, &a.ContentType, &a.Size, &a.SHA256, &a.Status, &a.ErrorCode, &a.CreatedAt)
|
||||
var variants []byte
|
||||
err = s.Pool.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.uploader_id::text,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,a.error_code,a.created_at,a.updated_at,a.variants,a.pipeline_version FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=$1 AND m.user_id=$2`, parsed.String(), userID).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.Key, &a.ContentType, &a.Size, &a.SHA256, &a.Status, &a.ErrorCode, &a.CreatedAt, &a.UpdatedAt, &variants, &a.PipelineVersion)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return Attachment{}, appError(domain.ErrorNotFound, "Объект не найден")
|
||||
}
|
||||
if err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
a.UpdatedAt = a.CreatedAt
|
||||
// Keep the mandatory lab4 ready-only metadata schema. Failed originals are
|
||||
// represented by 409; internal status remains inspectable in reconciliation.
|
||||
if a.Status != "ready" {
|
||||
if err = json.Unmarshal(variants, &a.Variants); err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
// The legacy fixture service preserves lab4 errors; production Async exposes all states.
|
||||
if a.Status != "ready" && !s.Async {
|
||||
return Attachment{}, appError(domain.ErrorConflict, "Оригинал вложения недоступен")
|
||||
}
|
||||
return a, nil
|
||||
|
||||
@@ -0,0 +1,618 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math/rand/v2"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"golang.org/x/sync/semaphore"
|
||||
)
|
||||
|
||||
const Stream = "attachments:jobs:v1"
|
||||
const Group = "image-workers-v1"
|
||||
|
||||
type JobMessage struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
JobID string `json:"job_id"`
|
||||
Type string `json:"type"`
|
||||
AttachmentID string `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"`
|
||||
}
|
||||
type Variant struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Size int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
type claimed struct {
|
||||
JobMessage
|
||||
Fence int64
|
||||
Stage, Original, MIME, SHA string
|
||||
Width, Height int
|
||||
Size int64
|
||||
}
|
||||
|
||||
func (s *Service) put(ctx context.Context, key string, r io.Reader, size int64, mime string) error {
|
||||
_, err := s.Store.Client.PutObject(ctx, s.Store.Bucket, key, r, size, minio.PutObjectOptions{ContentType: mime, DisableMultipart: true})
|
||||
return err
|
||||
}
|
||||
func (s *Service) Publish(ctx context.Context, r *redis.Client) error {
|
||||
tx, err := s.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
rows, err := tx.Query(ctx, `SELECT j.id::text,j.attachment_id::text,j.pipeline_version,j.attempts+1,j.created_at FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE o.published_at IS NULL AND o.available_at<=clock_timestamp() AND j.state='queued' ORDER BY o.available_at LIMIT 32 FOR UPDATE OF o SKIP LOCKED`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
messages := []JobMessage{}
|
||||
for rows.Next() {
|
||||
m := JobMessage{SchemaVersion: 1, Type: "attachment.process.v1"}
|
||||
if err = rows.Scan(&m.JobID, &m.AttachmentID, &m.PipelineVersion, &m.Attempt, &m.CreatedAt); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
messages = append(messages, m)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range messages {
|
||||
raw, _ := json.Marshal(m)
|
||||
id, e := r.XAdd(ctx, &redis.XAddArgs{Stream: Stream, Values: map[string]interface{}{"job": string(raw)}}).Result()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=clock_timestamp(),stream_id=$2 WHERE job_id=$1`, m.JobID, id); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
func (s *Service) recover(ctx context.Context) error {
|
||||
tx, err := s.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
rows, err := tx.Query(ctx, `SELECT id::text,attachment_id::text,attempts,max_attempts FROM attachment_jobs WHERE state='processing' AND lease_until<clock_timestamp() FOR UPDATE SKIP LOCKED`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
type lost struct {
|
||||
id, att string
|
||||
attempt, max int
|
||||
}
|
||||
all := []lost{}
|
||||
for rows.Next() {
|
||||
var l lost
|
||||
if err = rows.Scan(&l.id, &l.att, &l.attempt, &l.max); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
all = append(all, l)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, l := range all {
|
||||
state := "queued"
|
||||
var code *string
|
||||
if l.attempt >= l.max {
|
||||
state = "failed"
|
||||
v := "retry_exhausted"
|
||||
code = &v
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state=$2,lease_until=NULL,available_at=clock_timestamp(),updated_at=clock_timestamp(),last_error='worker_lost' WHERE id=$1`, l.id, state); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,updated_at=clock_timestamp() WHERE id=$1`, l.att, state, code); err != nil {
|
||||
return err
|
||||
}
|
||||
if state == "queued" {
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL,available_at=clock_timestamp() WHERE job_id=$1`, l.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
func (s *Service) claim(ctx context.Context, m JobMessage) (claimed, bool, error) {
|
||||
j := claimed{JobMessage: m}
|
||||
tx, err := s.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return j, false, err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var state string
|
||||
var attempts, max, version int
|
||||
var available time.Time
|
||||
err = tx.QueryRow(ctx, `SELECT state,attempts,max_attempts,available_at,pipeline_version FROM attachment_jobs WHERE id=$1 AND attachment_id=$2 FOR UPDATE`, m.JobID, m.AttachmentID).Scan(&state, &attempts, &max, &available, &version)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return j, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return j, false, err
|
||||
}
|
||||
if state == "ready" {
|
||||
var key, mime string
|
||||
var size int64
|
||||
var raw []byte
|
||||
if err = tx.QueryRow(ctx, `SELECT object_key,content_type,size_bytes,variants FROM attachments WHERE id=$1 AND status='ready' AND pipeline_version=$2`, m.AttachmentID, version).Scan(&key, &mime, &size, &raw); err != nil {
|
||||
return j, false, err
|
||||
}
|
||||
var variants []Variant
|
||||
if err = json.Unmarshal(raw, &variants); err != nil || len(variants) != 3 {
|
||||
return j, false, fmt.Errorf("completed effect metadata incomplete")
|
||||
}
|
||||
objects := map[string]int64{key: size}
|
||||
for _, v := range variants {
|
||||
objects[effectKey(m.AttachmentID, version, v.Name)] = v.Size
|
||||
}
|
||||
for object, n := range objects {
|
||||
info, e := s.Store.Client.StatObject(ctx, s.Store.Bucket, object, minio.StatObjectOptions{})
|
||||
if e != nil {
|
||||
return j, false, e
|
||||
}
|
||||
if info.Size != n {
|
||||
return j, false, fmt.Errorf("completed effect size mismatch")
|
||||
}
|
||||
}
|
||||
return j, false, nil
|
||||
}
|
||||
if state != "queued" || available.After(time.Now()) || m.Attempt != attempts+1 || version != m.PipelineVersion {
|
||||
return j, false, nil
|
||||
}
|
||||
if attempts >= max {
|
||||
return j, false, fmt.Errorf("attempt invariant violated")
|
||||
}
|
||||
err = tx.QueryRow(ctx, `UPDATE attachment_jobs SET state='processing',attempts=attempts+1,fence=fence+1,lease_until=clock_timestamp()+$2*interval '1 second',updated_at=clock_timestamp() WHERE id=$1 RETURNING fence`, m.JobID, s.Options.Lease.Seconds()).Scan(&j.Fence)
|
||||
if err != nil {
|
||||
return j, false, err
|
||||
}
|
||||
err = tx.QueryRow(ctx, `UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=$1 AND pipeline_version=$2 AND status IN ('queued','processing') RETURNING staging_key,object_key,content_type,size_bytes,sha256,width,height`, m.AttachmentID, version).Scan(&j.Stage, &j.Original, &j.MIME, &j.Size, &j.SHA, &j.Width, &j.Height)
|
||||
if err != nil {
|
||||
return j, false, err
|
||||
}
|
||||
return j, true, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// finish publishes metadata only for the current, unexpired fencing token.
|
||||
func (s *Service) finish(ctx context.Context, j claimed, variants []Variant, code string, permanent bool) (bool, error) {
|
||||
tx, err := s.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var max int
|
||||
err = tx.QueryRow(ctx, `SELECT max_attempts FROM attachment_jobs WHERE id=$1 AND fence=$2 AND state='processing' AND lease_until>clock_timestamp() AND pipeline_version=$3 FOR UPDATE`, j.JobID, j.Fence, j.PipelineVersion).Scan(&max)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
lastError := code
|
||||
state := "ready"
|
||||
var failure *string
|
||||
available := time.Now()
|
||||
if code != "" {
|
||||
state = "queued"
|
||||
if permanent || j.Attempt >= max {
|
||||
state = "failed"
|
||||
if !permanent {
|
||||
code = "retry_exhausted"
|
||||
}
|
||||
failure = &code
|
||||
}
|
||||
delay := time.Duration(1<<min(j.Attempt, 5)) * time.Second
|
||||
available = available.Add(delay + time.Duration(rand.IntN(500))*time.Millisecond)
|
||||
}
|
||||
raw := []byte("[]")
|
||||
if state == "ready" {
|
||||
raw, err = json.Marshal(variants)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state=$2,lease_until=NULL,available_at=$3,last_error=NULLIF($4,''),updated_at=clock_timestamp() WHERE id=$1`, j.JobID, state, available, lastError); err != nil {
|
||||
return false, err
|
||||
}
|
||||
tag, updateErr := tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,variants=$4,updated_at=clock_timestamp() WHERE id=$1 AND pipeline_version=$5 AND status='processing'`, j.AttachmentID, state, failure, raw, j.PipelineVersion)
|
||||
if updateErr != nil {
|
||||
return false, updateErr
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return false, fmt.Errorf("attachment version/state changed")
|
||||
}
|
||||
if state == "queued" {
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL,available_at=$2 WHERE job_id=$1`, j.JobID, available); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
func (s *Service) render(ctx context.Context, j claimed) ([]Variant, string, bool) {
|
||||
if os.Getenv("PIPELINE_FAILPOINT") == "transient" {
|
||||
return nil, "storage_unavailable", false
|
||||
}
|
||||
dir, err := os.MkdirTemp("", "pipeline-*")
|
||||
if err != nil {
|
||||
return nil, "processing_failed", false
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
source := filepath.Join(dir, "source")
|
||||
obj, err := s.Store.Client.GetObject(ctx, s.Store.Bucket, j.Stage, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, "storage_unavailable", false
|
||||
}
|
||||
defer obj.Close()
|
||||
f, err := os.Create(source)
|
||||
if err != nil {
|
||||
return nil, "processing_failed", false
|
||||
}
|
||||
n, err := io.Copy(f, io.LimitReader(&contextReader{ctx: ctx, r: obj}, MaxBytes+1))
|
||||
f.Close()
|
||||
if err != nil {
|
||||
if IsMissing(err) {
|
||||
return nil, "original_missing", true
|
||||
}
|
||||
return nil, "storage_unavailable", false
|
||||
}
|
||||
if n != j.Size {
|
||||
return nil, "invalid_image", true
|
||||
}
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return nil, "processing_failed", false
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, exe, "render", source, dir, j.SHA)
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
cmd.Cancel = func() error {
|
||||
if cmd.Process == nil {
|
||||
return nil
|
||||
}
|
||||
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
}
|
||||
cmd.WaitDelay = time.Second
|
||||
cmd.Env = append(os.Environ(), "GOMEMLIMIT=384MiB")
|
||||
if err = cmd.Run(); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil, "processing_timeout", false
|
||||
}
|
||||
if cmd.ProcessState != nil && cmd.ProcessState.ExitCode() == 2 {
|
||||
return nil, "invalid_image", true
|
||||
}
|
||||
return nil, "processing_failed", false
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "manifest.json"))
|
||||
if err != nil {
|
||||
return nil, "processing_failed", false
|
||||
}
|
||||
var variants []Variant
|
||||
if json.Unmarshal(raw, &variants) != nil {
|
||||
return nil, "processing_failed", false
|
||||
}
|
||||
f, err = os.Open(source)
|
||||
if err != nil {
|
||||
return nil, "processing_failed", false
|
||||
}
|
||||
err = s.put(ctx, j.Original, f, j.Size, j.MIME)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return nil, "storage_unavailable", false
|
||||
}
|
||||
for _, v := range variants {
|
||||
f, err = os.Open(filepath.Join(dir, v.Name))
|
||||
if err != nil {
|
||||
return nil, "processing_failed", false
|
||||
}
|
||||
err = s.put(ctx, effectKey(j.AttachmentID, j.PipelineVersion, v.Name), f, v.Size, v.ContentType)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return nil, "storage_unavailable", false
|
||||
}
|
||||
}
|
||||
if os.Getenv("PIPELINE_FAILPOINT") == "after_objects" {
|
||||
log.Print("FAILPOINT after_objects reached")
|
||||
os.Exit(86)
|
||||
}
|
||||
return variants, "", false
|
||||
}
|
||||
func (s *Service) RunWorker(ctx context.Context, r *redis.Client) error {
|
||||
if err := r.XGroupCreateMkStream(ctx, Stream, Group, "0").Err(); err != nil && !strings.Contains(err.Error(), "BUSYGROUP") {
|
||||
return err
|
||||
}
|
||||
consumer := uuid.NewString()
|
||||
queue := make(chan redis.XMessage, s.Options.Prefetch)
|
||||
pixels := semaphore.NewWeighted(int64(s.Options.PixelBudget))
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < s.Options.Concurrency; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for msg := range queue {
|
||||
var m JobMessage
|
||||
decoder := json.NewDecoder(strings.NewReader(fmt.Sprint(msg.Values["job"])))
|
||||
decoder.DisallowUnknownFields()
|
||||
err := decoder.Decode(&m)
|
||||
if err != nil || m.SchemaVersion != 1 || m.Type != "attachment.process.v1" || m.Attempt < 1 || m.PipelineVersion < 1 || m.CreatedAt.IsZero() || uuid.Validate(m.JobID) != nil || uuid.Validate(m.AttachmentID) != nil {
|
||||
log.Print("invalid stream envelope ignored")
|
||||
ack(ctx, r, msg.ID)
|
||||
continue
|
||||
}
|
||||
op, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
j, ok, err := s.claim(op, m)
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Print("job claim/effect verification will retry")
|
||||
continue
|
||||
}
|
||||
if !ok {
|
||||
ack(ctx, r, msg.ID)
|
||||
continue
|
||||
}
|
||||
weight := int64(j.Width) * int64(j.Height)
|
||||
// The whole lease includes pixel admission, download, decoder and all S3 writes.
|
||||
op, cancel = context.WithTimeout(ctx, s.Options.Timeout)
|
||||
var variants []Variant
|
||||
code := "processing_timeout"
|
||||
permanent := false
|
||||
if err = pixels.Acquire(op, weight); err == nil {
|
||||
variants, code, permanent = s.render(op, j)
|
||||
pixels.Release(weight)
|
||||
}
|
||||
cancel()
|
||||
finishCtx, finishCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
durable, e := s.finish(finishCtx, j, variants, code, permanent)
|
||||
finishCancel()
|
||||
if e == nil && durable {
|
||||
if os.Getenv("PIPELINE_FAILPOINT") == "after_commit" && code == "" {
|
||||
log.Print("FAILPOINT after_commit reached")
|
||||
os.Exit(87)
|
||||
}
|
||||
ack(ctx, r, msg.ID)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
lastCleanup := time.Now()
|
||||
ticker := time.NewTicker(250 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
defer func() { close(queue); wg.Wait() }()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
}
|
||||
op, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
if err := s.recover(op); err != nil {
|
||||
log.Print("lease recovery will retry")
|
||||
}
|
||||
if os.Getenv("PIPELINE_PAUSE_PUBLISH") != "1" {
|
||||
if err := s.Publish(op, r); err != nil {
|
||||
log.Print("outbox publish will retry")
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
// Claim PEL entries left by a dead consumer; PG leases remain the effect authority.
|
||||
op, cancel = context.WithTimeout(ctx, 2*time.Second)
|
||||
pending, _, _ := r.XAutoClaim(op, &redis.XAutoClaimArgs{Stream: Stream, Group: Group, Consumer: consumer, MinIdle: s.Options.Lease, Start: "0-0", Count: int64(s.Options.Prefetch)}).Result()
|
||||
cancel()
|
||||
for _, m := range pending {
|
||||
select {
|
||||
case queue <- m:
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
}
|
||||
}
|
||||
// Never fetch beyond bounded prefetch capacity; no unbounded in-memory backlog.
|
||||
room := cap(queue) - len(queue)
|
||||
if room > 0 {
|
||||
op, cancel = context.WithTimeout(ctx, time.Second)
|
||||
streams, e := r.XReadGroup(op, &redis.XReadGroupArgs{Group: Group, Consumer: consumer, Streams: []string{Stream, ">"}, Count: int64(room), Block: 100 * time.Millisecond}).Result()
|
||||
cancel()
|
||||
if e == nil {
|
||||
for _, stream := range streams {
|
||||
for _, m := range stream.Messages {
|
||||
select {
|
||||
case queue <- m:
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if time.Since(lastCleanup) >= 5*time.Second {
|
||||
lastCleanup = time.Now()
|
||||
op, cancel = context.WithTimeout(ctx, 5*time.Second)
|
||||
s.cleanStages(op)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
func ack(ctx context.Context, r *redis.Client, id string) {
|
||||
if r.XAck(ctx, Stream, Group, id).Err() == nil {
|
||||
r.XDel(ctx, Stream, id)
|
||||
}
|
||||
}
|
||||
|
||||
// Replay is an explicit operator action, serialized with admission and job claims.
|
||||
// It preserves job/effect identity and refuses already successful work.
|
||||
func (s *Service) Replay(ctx context.Context, id, operator, reason string) error {
|
||||
if uuid.Validate(id) != nil || len(operator) < 1 || len(operator) > 100 || len(reason) < 1 || len(reason) > 300 {
|
||||
return fmt.Errorf("job UUID, operator and reason are required")
|
||||
}
|
||||
tx, err := s.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(578903551)`); err != nil {
|
||||
return err
|
||||
}
|
||||
var pending int
|
||||
if err = tx.QueryRow(ctx, `SELECT count(*) FROM attachment_jobs WHERE state IN ('queued','processing')`).Scan(&pending); err != nil {
|
||||
return err
|
||||
}
|
||||
if pending >= s.Options.MaxOutstanding {
|
||||
return fmt.Errorf("admission limit reached")
|
||||
}
|
||||
var att, state, previous string
|
||||
err = tx.QueryRow(ctx, `SELECT attachment_id::text,state,coalesce(last_error,'processing_failed') FROM attachment_jobs WHERE id=$1 FOR UPDATE`, id).Scan(&att, &state, &previous)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if state != "failed" {
|
||||
return fmt.Errorf("only failed jobs may be replayed")
|
||||
}
|
||||
var stage *string
|
||||
if err = tx.QueryRow(ctx, `SELECT staging_key FROM attachments WHERE id=$1 FOR UPDATE`, att).Scan(&stage); err != nil {
|
||||
return err
|
||||
}
|
||||
if stage == nil {
|
||||
return fmt.Errorf("staging retention expired")
|
||||
}
|
||||
if _, err = s.Store.Client.StatObject(ctx, s.Store.Bucket, *stage, minio.StatObjectOptions{}); err != nil {
|
||||
return fmt.Errorf("staging unavailable")
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO attachment_replays(job_id,operator,reason,previous_error) VALUES($1,$2,$3,$4)`, id, operator, reason, previous); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state='queued',attempts=0,fence=fence+1,last_error=NULL,available_at=clock_timestamp(),updated_at=clock_timestamp() WHERE id=$1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, att); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL,available_at=clock_timestamp() WHERE job_id=$1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// Keep failed stages for seven days for explicit replay; ready stages are garbage.
|
||||
func (s *Service) cleanStages(ctx context.Context) {
|
||||
rows, err := s.Pool.Query(ctx, `SELECT id::text FROM attachments WHERE (status='ready' AND staging_key IS NOT NULL) OR (status='failed' AND updated_at<clock_timestamp()-interval '7 days' AND storage_cleaned_at IS NULL) LIMIT 100`)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ids := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if rows.Scan(&id) == nil {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
for _, id := range ids {
|
||||
tx, e := s.Pool.Begin(ctx)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
var stage *string
|
||||
var state, original string
|
||||
var version int
|
||||
e = tx.QueryRow(ctx, `SELECT staging_key,status,object_key,pipeline_version FROM attachments WHERE id=$1 AND ((status='ready' AND staging_key IS NOT NULL) OR (status='failed' AND updated_at<clock_timestamp()-interval '7 days' AND storage_cleaned_at IS NULL)) FOR UPDATE`, id).Scan(&stage, &state, &original, &version)
|
||||
if e == nil && state == "failed" {
|
||||
for _, name := range []string{"original", "thumbnail", "crop", "optimized"} {
|
||||
key := effectKey(id, version, name)
|
||||
if name == "original" {
|
||||
key = original
|
||||
}
|
||||
e = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, key, minio.RemoveObjectOptions{})
|
||||
if e != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if e == nil && stage != nil {
|
||||
e = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, *stage, minio.RemoveObjectOptions{})
|
||||
}
|
||||
if e == nil {
|
||||
if state == "failed" {
|
||||
_, e = tx.Exec(ctx, `UPDATE attachments SET staging_key=NULL,variants='[]',storage_cleaned_at=clock_timestamp() WHERE id=$1`, id)
|
||||
} else {
|
||||
_, e = tx.Exec(ctx, `UPDATE attachments SET staging_key=NULL WHERE id=$1`, id)
|
||||
}
|
||||
}
|
||||
if e == nil {
|
||||
tx.Commit(ctx)
|
||||
} else {
|
||||
tx.Rollback(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// Unconfirmed stages (PUT succeeded, DB did not COMMIT) have a 90s grace and upload lock.
|
||||
for obj := range s.Store.Client.ListObjects(ctx, s.Store.Bucket, minio.ListObjectsOptions{Prefix: "staging/", Recursive: true}) {
|
||||
if obj.Err != nil {
|
||||
return
|
||||
}
|
||||
if time.Since(obj.LastModified) < MinimumGrace {
|
||||
continue
|
||||
}
|
||||
tx, e := s.Pool.Begin(ctx)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
var locked, exists bool
|
||||
e = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))`, obj.Key).Scan(&locked)
|
||||
if e == nil && locked {
|
||||
e = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE staging_key=$1)`, obj.Key).Scan(&exists)
|
||||
if e == nil && !exists {
|
||||
e = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, obj.Key, minio.RemoveObjectOptions{})
|
||||
}
|
||||
}
|
||||
tx.Rollback(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// RunPublisher drains durable DB intentions independently of worker availability.
|
||||
func (s *Service) RunPublisher(ctx context.Context, r *redis.Client) {
|
||||
ticker := time.NewTicker(200 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
if os.Getenv("PIPELINE_PAUSE_PUBLISH") == "1" {
|
||||
continue
|
||||
}
|
||||
op, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
if err := s.Publish(op, r); err != nil {
|
||||
log.Print("outbox publisher will retry")
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The HTTP/S3 fault suite supplies real processing; this test isolates the DB fence.
|
||||
func TestFenceIntegration(t *testing.T) {
|
||||
if os.Getenv("INTEGRATION_TESTS") != "1" {
|
||||
t.Skip("run make test-integration")
|
||||
}
|
||||
cfg, e := config.Load()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
pc, e := pgxpool.ParseConfig("sslmode=disable")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
pc.ConnConfig.Host = cfg.PostgresHost
|
||||
pc.ConnConfig.Port = cfg.PostgresPort
|
||||
pc.ConnConfig.User = cfg.PostgresUser
|
||||
pc.ConnConfig.Password = cfg.PostgresPassword
|
||||
pc.ConnConfig.Database = cfg.PostgresDatabase
|
||||
pool, e := pgxpool.NewWithConfig(context.Background(), pc)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer pool.Close()
|
||||
ctx := context.Background()
|
||||
user, chat, att, id := uuid.NewString(), uuid.NewString(), uuid.NewString(), uuid.NewString()
|
||||
defer func() {
|
||||
pool.Exec(ctx, `DELETE FROM attachment_outbox WHERE job_id=$1`, id)
|
||||
pool.Exec(ctx, `DELETE FROM attachment_jobs WHERE id=$1`, id)
|
||||
pool.Exec(ctx, `DELETE FROM attachments WHERE id=$1`, att)
|
||||
pool.Exec(ctx, `DELETE FROM chat_members WHERE chat_id=$1`, chat)
|
||||
pool.Exec(ctx, `DELETE FROM chats WHERE id=$1`, chat)
|
||||
pool.Exec(ctx, `DELETE FROM users WHERE id=$1`, user)
|
||||
}()
|
||||
if _, e = pool.Exec(ctx, `INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,'Fence','test')`, user, "fence_"+user[:8]); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = pool.Exec(ctx, `INSERT INTO chats(id,title) VALUES($1,'Fence')`, chat); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = pool.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id,ordinal) VALUES($1,$2,0)`, chat, user); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = pool.Exec(ctx, `INSERT INTO attachments(id,chat_id,uploader_id,filename,object_key,content_type,size_bytes,sha256,width,height,status,staging_key) VALUES($1,$2,$3,'x.png',$4,'image/png',1,repeat('a',64),1,1,'queued',$5)`, att, chat, user, effectKey(att, 1, "original"), "staging/"+att); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = pool.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,state,max_attempts) VALUES($1,$2,'queued',5)`, id, att); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
|
||||
options, _ := LoadOptions()
|
||||
s := NewAsync(pool, nil, options)
|
||||
message := JobMessage{SchemaVersion: 1, JobID: id, AttachmentID: att, PipelineVersion: 1, Attempt: 1, CreatedAt: time.Now()}
|
||||
first, ok, e := s.claim(ctx, message)
|
||||
if e != nil || !ok {
|
||||
t.Fatalf("claim: %v %v", ok, e)
|
||||
}
|
||||
if _, ok, e = s.claim(ctx, message); e != nil || ok {
|
||||
t.Fatalf("duplicate claimed active lease: %v %v", ok, e)
|
||||
}
|
||||
if _, e = pool.Exec(ctx, `UPDATE attachment_jobs SET lease_until=clock_timestamp()-interval '1 second' WHERE id=$1`, id); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if durable, e := s.finish(ctx, first, []Variant{}, "", false); e != nil || durable {
|
||||
t.Fatalf("expired fence published: %v %v", durable, e)
|
||||
}
|
||||
if e = s.recover(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
message.Attempt = 2
|
||||
second, ok, e := s.claim(ctx, message)
|
||||
if e != nil || !ok || second.Fence <= first.Fence {
|
||||
t.Fatalf("reclaim: %+v %v %v", second, ok, e)
|
||||
}
|
||||
if durable, e := s.finish(ctx, first, []Variant{}, "", false); e != nil || durable {
|
||||
t.Fatalf("stale fence published: %v %v", durable, e)
|
||||
}
|
||||
if _, e = pool.Exec(ctx, `UPDATE attachments SET pipeline_version=2 WHERE id=$1`, att); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if durable, e := s.finish(ctx, second, []Variant{}, "", false); e == nil || durable {
|
||||
t.Fatal("stale pipeline version accepted")
|
||||
}
|
||||
var state string
|
||||
if e = pool.QueryRow(ctx, `SELECT state FROM attachment_jobs WHERE id=$1`, id).Scan(&state); e != nil || state != "processing" {
|
||||
t.Fatalf("partial result committed: %s %v", state, e)
|
||||
}
|
||||
}
|
||||
@@ -259,7 +259,11 @@ func lab4Backend(t *testing.T, pool *pgxpool.Pool, repo *postgres.Storage, user
|
||||
fake.objects[orphan] = fakeObject{data: []byte("orphan"), modified: old}
|
||||
fake.objects[fresh] = fakeObject{data: []byte("fresh"), modified: time.Now()}
|
||||
fake.objects[locked] = fakeObject{data: []byte("locked"), modified: old}
|
||||
fake.objects["original/legacy-staging"] = fakeObject{data: []byte("legacy stage"), modified: old}
|
||||
fake.mu.Unlock()
|
||||
if _, err = pool.Exec(ctx, `UPDATE attachments SET staging_key='original/legacy-staging' WHERE id=$1`, second.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `UPDATE attachments SET created_at=$1 WHERE id=ANY($2::uuid[])`, old, []string{first.ID, second.ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -294,8 +298,9 @@ func lab4Backend(t *testing.T, pool *pgxpool.Pool, repo *postgres.Storage, user
|
||||
_, hasFresh := fake.objects[fresh]
|
||||
_, hasLinked := fake.objects[second.Key]
|
||||
_, hasLocked := fake.objects[locked]
|
||||
_, hasLegacyStage := fake.objects["original/legacy-staging"]
|
||||
fake.mu.Unlock()
|
||||
if hasOrphan || !hasFresh || !hasLinked || !hasLocked {
|
||||
if hasOrphan || !hasFresh || !hasLinked || !hasLocked || !hasLegacyStage {
|
||||
t.Fatal("unsafe object cleanup")
|
||||
}
|
||||
_, err = service.Get(ctx, first.ID, user.ID)
|
||||
|
||||
@@ -53,7 +53,7 @@ func (s *Storage) CreateMessageWithAttachments(ctx context.Context, chatID, send
|
||||
if err != nil {
|
||||
return domain.Message{}, dbError(err)
|
||||
}
|
||||
if status != "ready" {
|
||||
if status == "failed" {
|
||||
return domain.Message{}, domain.NewApplicationError(domain.ErrorConflict, "Вложение не готово")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ func TestIntegration(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
runGoose := func(t *testing.T, command string) {
|
||||
runGoose := func(t *testing.T, command string, params ...string) {
|
||||
t.Helper()
|
||||
migrationDir := os.Getenv("GOOSE_MIGRATION_DIR")
|
||||
if migrationDir == "" {
|
||||
@@ -73,7 +73,8 @@ func TestIntegration(t *testing.T) {
|
||||
connection.RawQuery = url.Values{"sslmode": {"disable"}, "search_path": {schema}, "connect_timeout": {"5"}}.Encode()
|
||||
commandCtx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
defer cancel()
|
||||
commandExec := exec.CommandContext(commandCtx, "goose", "-env", "/dev/null", "-dir", migrationDir, "-timeout", "30s", command)
|
||||
args := append([]string{"-env", "/dev/null", "-dir", migrationDir, "-timeout", "30s", command}, params...)
|
||||
commandExec := exec.CommandContext(commandCtx, "goose", args...)
|
||||
commandExec.Env = append(os.Environ(), "GOOSE_DRIVER=postgres", "GOOSE_DBSTRING="+connection.String(), "PGPASSWORD="+cfg.PostgresPassword)
|
||||
output, err := commandExec.CombinedOutput()
|
||||
if err != nil {
|
||||
@@ -260,6 +261,8 @@ func TestIntegration(t *testing.T) {
|
||||
if err = pool.QueryRow(ctx, digestSQL).Scan(&before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Model the actual lab4 physical schema before adopting its legacy journal.
|
||||
runGoose(t, "down-to", "4")
|
||||
if _, err = pool.Exec(ctx, `DROP TABLE goose_db_version;
|
||||
CREATE TABLE schema_migrations(version text PRIMARY KEY,applied_at timestamptz NOT NULL DEFAULT now());
|
||||
INSERT INTO schema_migrations(version) VALUES('001_initial.sql')`); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user