Переведите приём и чтение вложений на асинхронный контракт
This commit is contained in:
@@ -3,7 +3,6 @@ package attachment_test
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
@@ -20,159 +19,79 @@ import (
|
||||
"messenger/internal/testenv"
|
||||
)
|
||||
|
||||
type testBlobs struct {
|
||||
mu sync.Mutex
|
||||
data map[string][]byte
|
||||
copies int
|
||||
failCopy bool
|
||||
}
|
||||
|
||||
type blockingPublication struct {
|
||||
*testBlobs
|
||||
entered, resume chan struct{}
|
||||
}
|
||||
|
||||
func (b *blockingPublication) Copy(ctx context.Context, from, to string) error {
|
||||
close(b.entered)
|
||||
select {
|
||||
case <-b.resume:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
return b.testBlobs.Copy(ctx, from, to)
|
||||
}
|
||||
func (b *blockingPublication) Stat(ctx context.Context, key string) (attachment.Object, error) {
|
||||
o, e := b.testBlobs.Stat(ctx, key)
|
||||
o.Modified = time.Now().Add(-2 * time.Hour)
|
||||
return o, e
|
||||
}
|
||||
|
||||
func TestCollectorRechecksReferencesAfterConcurrentPublication(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
func TestCollectorRechecksStageAfterConcurrentEnqueue(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
defer cancel()
|
||||
db, err := testenv.StartPostgres(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
actor, room := ident.New(), ident.New()
|
||||
if _, err = db.Pool.Exec(ctx, `INSERT INTO users VALUES($1,'race_user','User','hash',now())`, actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Pool.Exec(ctx, `INSERT INTO chats VALUES($1,'race',now())`, room); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Pool.Exec(ctx, `INSERT INTO chat_members VALUES($1,$2)`, room, actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := reconcileSetup(t, db)
|
||||
f.exec(`INSERT INTO chat_members VALUES ($1,$2)`, f.chat, f.user)
|
||||
data, err := os.ReadFile("../../tests/fixtures/sample.png")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hash := sha256.Sum256(data)
|
||||
if _, err = db.Pool.Exec(ctx, `INSERT INTO files(hash,size_bytes,mime_type,status,created_at) VALUES($1,$2,'image/png','pending',now()-interval '2 hours')`, hash[:], len(data)); err != nil {
|
||||
t.Fatal(err)
|
||||
entered := make(chan string, 1)
|
||||
resume := make(chan struct{})
|
||||
var once sync.Once
|
||||
f.b.stating = func(key string) {
|
||||
once.Do(func() {
|
||||
f.b.add(key, data, time.Now().Add(-2*time.Hour))
|
||||
entered <- key
|
||||
select {
|
||||
case <-resume:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
})
|
||||
}
|
||||
b := &blockingPublication{testBlobs: &testBlobs{data: map[string][]byte{}}, entered: make(chan struct{}), resume: make(chan struct{})}
|
||||
s := attachment.NewService(store.NewAttachments(db.Pool), chatstore.NewChats(db.Pool), b, attachment.Config{})
|
||||
s := attachment.NewService(store.NewAttachments(db.Pool), chatstore.NewChats(db.Pool), f.b, attachment.Config{})
|
||||
uploaded := make(chan error, 1)
|
||||
go func() {
|
||||
input := attachment.UploadInput{ChatID: room, Filename: "race.png", MIMEType: "image/png", SizeBytes: int64(len(data))}
|
||||
_, e := s.Upload(ctx, actor, input, bytes.NewReader(data))
|
||||
uploaded <- e
|
||||
_, err := s.Upload(ctx, f.user, attachment.UploadInput{ChatID: f.chat, Filename: "photo.png", MIMEType: "image/png", SizeBytes: int64(len(data))}, bytes.NewReader(data))
|
||||
uploaded <- err
|
||||
}()
|
||||
var key string
|
||||
select {
|
||||
case <-b.entered:
|
||||
case key = <-entered:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("publisher never reached copy")
|
||||
t.Fatal("upload never verified staging under lock")
|
||||
}
|
||||
r, err := attachment.NewReconciler(db.Pool, b, time.Hour)
|
||||
r, err := attachment.NewReconciler(db.Pool, f.b, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collected := make(chan error, 1)
|
||||
collect := make(chan error, 1)
|
||||
go func() {
|
||||
stats, e := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
|
||||
if e == nil && stats.Repaired != 0 {
|
||||
e = errors.New("collector removed a newly referenced file")
|
||||
stats, err := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
|
||||
if err == nil && stats.Repaired != 0 {
|
||||
err = errors.New("removed concurrent upload")
|
||||
}
|
||||
collected <- e
|
||||
collect <- err
|
||||
}()
|
||||
// Observe a real waiting advisory lock, rather than guessing which goroutine won.
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
waiting := false
|
||||
for time.Now().Before(deadline) {
|
||||
var n int
|
||||
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND NOT granted`).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n > 0 {
|
||||
waiting = true
|
||||
break
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
close(b.resume)
|
||||
if !waiting {
|
||||
t.Fatal("collector did not serialize with the publisher")
|
||||
}
|
||||
waitReconcileLock(t, ctx, db.Pool)
|
||||
close(resume)
|
||||
if err := <-uploaded; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-collected; err != nil {
|
||||
if err := <-collect; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.Stat(ctx, attachment.BlobKey(hash[:])); err != nil {
|
||||
t.Fatal("collector deleted published data", err)
|
||||
if !f.b.has(key) {
|
||||
t.Fatal("accepted source lost")
|
||||
}
|
||||
}
|
||||
|
||||
func (b *testBlobs) Put(_ context.Context, k string, r io.Reader, n int64, m string) error {
|
||||
data, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
type lostCommitReply struct {
|
||||
attachment.AttachmentRepository
|
||||
}
|
||||
|
||||
func (r lostCommitReply) Enqueue(ctx context.Context, a attachment.Attachment, stage string, check func() error) error {
|
||||
if err := r.AttachmentRepository.Enqueue(ctx, a, stage, check); err != nil {
|
||||
return err
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.data[k] = data
|
||||
return nil
|
||||
}
|
||||
func (b *testBlobs) Open(_ context.Context, k string) (io.ReadCloser, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
data, ok := b.data[k]
|
||||
if !ok {
|
||||
return nil, attachment.ErrObjectMissing
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(data)), nil
|
||||
}
|
||||
func (b *testBlobs) Stat(_ context.Context, k string) (attachment.Object, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
data, ok := b.data[k]
|
||||
if !ok {
|
||||
return attachment.Object{}, attachment.ErrObjectMissing
|
||||
}
|
||||
return attachment.Object{Key: k, Size: int64(len(data)), Modified: time.Now()}, nil
|
||||
}
|
||||
func (b *testBlobs) Copy(_ context.Context, from, to string) error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if b.failCopy {
|
||||
return errors.New("copy outage")
|
||||
}
|
||||
b.copies++
|
||||
b.data[to] = bytes.Clone(b.data[from])
|
||||
return nil
|
||||
}
|
||||
func (b *testBlobs) Delete(_ context.Context, k string) error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
delete(b.data, k)
|
||||
return nil
|
||||
}
|
||||
func (b *testBlobs) List(context.Context, string, string, int) ([]attachment.Object, error) {
|
||||
return nil, nil
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
|
||||
func TestUploadDeduplicatesContentButKeepsChatScopedIdentities(t *testing.T) {
|
||||
@@ -197,7 +116,7 @@ func TestUploadDeduplicatesContentButKeepsChatScopedIdentities(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
b := &testBlobs{data: map[string][]byte{}}
|
||||
b := newReconcileBlobs()
|
||||
s := attachment.NewService(store.NewAttachments(db.Pool), chatstore.NewChats(db.Pool), b, attachment.Config{})
|
||||
data, err := os.ReadFile("../../tests/fixtures/sample.png")
|
||||
if err != nil {
|
||||
@@ -220,13 +139,16 @@ func TestUploadDeduplicatesContentButKeepsChatScopedIdentities(t *testing.T) {
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
var files, atts int
|
||||
err = db.Pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM files),(SELECT count(*) FROM attachments)`).Scan(&files, &atts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
var files, atts, jobs int
|
||||
err = db.Pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM files),(SELECT count(*) FROM attachments),
|
||||
(SELECT count(*) FROM attachment_jobs WHERE state='queued' AND attempt=1 AND published_at IS NULL)`).Scan(&files, &atts, &jobs)
|
||||
if err != nil || files != 1 || atts != 10 || jobs != 10 || len(b.objects) != 10 {
|
||||
t.Fatalf("handoff: files=%d attachments=%d jobs=%d objects=%d err=%v", files, atts, jobs, len(b.objects), err)
|
||||
}
|
||||
if files != 1 || atts != 10 || b.copies != 1 || len(b.data) != 1 {
|
||||
t.Fatalf("files=%d attachments=%d copies=%d objects=%d", files, atts, b.copies, len(b.data))
|
||||
for _, a := range results {
|
||||
if a.Status != attachment.FileQueued || !bytes.Equal(b.bodies["staging/"+a.ID.String()], data) {
|
||||
t.Fatal("missing queued source", a.ID)
|
||||
}
|
||||
}
|
||||
if results[0].ID == results[1].ID {
|
||||
t.Fatal("deduplication merged chat ACL identity")
|
||||
@@ -234,43 +156,26 @@ func TestUploadDeduplicatesContentButKeepsChatScopedIdentities(t *testing.T) {
|
||||
if _, err := s.Get(ctx, ident.New(), results[0].ID); apperr.KindOf(err) != apperr.KindNotFound {
|
||||
t.Fatalf("outsider got %v", err)
|
||||
}
|
||||
// A removed blob is republished from the new upload, preserving old references.
|
||||
b.mu.Lock()
|
||||
clear(b.data)
|
||||
b.mu.Unlock()
|
||||
input := attachment.UploadInput{ChatID: c1, Filename: "again.png", MIMEType: "image/png", SizeBytes: int64(len(data))}
|
||||
if _, err := s.Upload(ctx, actor, input, bytes.NewReader(data)); err != nil {
|
||||
t.Fatal(err)
|
||||
input := attachment.UploadInput{ChatID: c1, Filename: "lost.png", MIMEType: "image/png", SizeBytes: int64(len(data))}
|
||||
lost := attachment.NewService(lostCommitReply{store.NewAttachments(db.Pool)}, chatstore.NewChats(db.Pool), b, attachment.Config{})
|
||||
if _, err := lost.Upload(ctx, actor, input, bytes.NewReader(data)); !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
t.Fatal("lost commit reply:", err)
|
||||
}
|
||||
if b.copies != 2 {
|
||||
t.Fatalf("missing ready blob was not restored: copies=%d", b.copies)
|
||||
var source string
|
||||
if err := db.Pool.QueryRow(ctx, `SELECT j.source_key FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.filename='lost.png'`).Scan(&source); err != nil || !bytes.Equal(b.bodies[source], data) {
|
||||
t.Fatal("committed job lost source", err)
|
||||
}
|
||||
b.failCopy = true
|
||||
other := bytes.Clone(data)
|
||||
other = append(other, 0)
|
||||
input.Filename, input.SizeBytes = "failed.png", int64(len(other))
|
||||
if _, err := s.Upload(ctx, actor, input, bytes.NewReader(other)); apperr.KindOf(err) != apperr.KindUnavailable {
|
||||
t.Fatalf("copy outage: %v", err)
|
||||
}
|
||||
if len(b.data) != 1 {
|
||||
t.Fatalf("failed publication left staging: %d objects", len(b.data))
|
||||
}
|
||||
b.failCopy = false
|
||||
// S3 publication succeeds, then PostgreSQL refuses the logical attachment.
|
||||
// Compensation may remove staging but must leave shared CAS data intact.
|
||||
_, err = db.Pool.Exec(ctx, `CREATE FUNCTION reject_attachment() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected insert failure'; END $$;
|
||||
CREATE TRIGGER reject_attachment BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION reject_attachment()`)
|
||||
_, err = db.Pool.Exec(ctx, `CREATE FUNCTION reject_job() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected insert failure'; END $$;
|
||||
CREATE TRIGGER reject_job BEFORE INSERT ON attachment_jobs FOR EACH ROW EXECUTE FUNCTION reject_job()`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input.Filename = "rollback.png"
|
||||
other := append(bytes.Clone(data), 0)
|
||||
input.Filename, input.SizeBytes = "rollback.png", int64(len(other))
|
||||
if _, err := s.Upload(ctx, actor, input, bytes.NewReader(other)); err == nil {
|
||||
t.Fatal("publication survived rejected metadata")
|
||||
t.Fatal("accepted rejected job")
|
||||
}
|
||||
if len(b.data) != 2 {
|
||||
t.Fatalf("expected original and recoverable orphan, got %d objects", len(b.data))
|
||||
}
|
||||
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM files`).Scan(&files); err != nil || files != 1 {
|
||||
t.Fatalf("failed DB insert committed file metadata: %d %v", files, err)
|
||||
if err := db.Pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM files),(SELECT count(*) FROM attachments),(SELECT count(*) FROM attachment_jobs)`).Scan(&files, &atts, &jobs); err != nil || files != 1 || atts != 11 || jobs != 11 || len(b.objects) != 12 {
|
||||
t.Fatalf("rollback: files=%d attachments=%d jobs=%d objects=%d err=%v", files, atts, jobs, len(b.objects), err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user