Переведите приём и чтение вложений на асинхронный контракт
This commit is contained in:
@@ -25,7 +25,13 @@ func (f fixture) attachment(t *testing.T, chatID, owner uuid.UUID, status string
|
||||
INSERT INTO files (hash, size_bytes, mime_type, status, created_at)
|
||||
VALUES ($1, 7, 'image/png', $2, now()) RETURNING hash)
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, file_hash, created_at)
|
||||
SELECT $3, $4, $5, 'image.png', hash, now() FROM file`, hash[:], status, id, chatID, owner)
|
||||
SELECT $3, $4, $5, 'image.png', hash, now() FROM file`, hash[:], "pending", id, chatID, owner)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Pool.Exec(f.ctx, `INSERT INTO attachment_jobs(attachment_id,source_key,state,error_code,lease_token,lease_until)
|
||||
VALUES($1,$2,$3,CASE WHEN $3='failed' THEN 'processing_failed' END,CASE WHEN $3='processing' THEN gen_random_uuid() END,
|
||||
CASE WHEN $3='processing' THEN now()+interval '1 minute' END)`, id, "staging/"+id.String(), status)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -35,7 +41,7 @@ func (f fixture) attachment(t *testing.T, chatID, owner uuid.UUID, status string
|
||||
func TestAttachmentHTTPRoundTripReplayAndOrderedConflict(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
c := f.newChat(t, f.alice, f.bob)
|
||||
a, b := f.attachment(t, c, f.bob, "ready"), f.attachment(t, c, f.alice, "ready")
|
||||
a, b := f.attachment(t, c, f.bob, "queued"), f.attachment(t, c, f.alice, "queued")
|
||||
r := messageRouter(f, f.alice)
|
||||
body := fmt.Sprintf(`{"text":"","attachment_ids":[%q,%q]}`, b, a)
|
||||
first := sendJSON(r, c, "attachments", body)
|
||||
@@ -80,14 +86,46 @@ func TestAttachmentHTTPRoundTripReplayAndOrderedConflict(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPReplayAfterAttachmentFailsAndMembershipChanges(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
c := f.newChat(t, f.alice, f.bob)
|
||||
a := f.attachment(t, c, f.alice, "queued")
|
||||
body := fmt.Sprintf(`{"text":"","attachment_ids":[%q]}`, a)
|
||||
router := messageRouter(f, f.alice)
|
||||
first := sendJSON(router, c, "key", body)
|
||||
if first.Code != http.StatusCreated {
|
||||
t.Fatal(first.Code, first.Body)
|
||||
}
|
||||
if _, err := db.Pool.Exec(f.ctx, `UPDATE attachment_jobs SET state='failed',error_code='source_missing' WHERE attachment_id=$1`, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replay := sendJSON(router, c, "key", body)
|
||||
if replay.Code != http.StatusCreated || replay.Body.String() != first.Body.String() {
|
||||
t.Fatalf("replay=%d %s, want original %s", replay.Code, replay.Body, first.Body)
|
||||
}
|
||||
changed := fmt.Sprintf(`{"text":"changed","attachment_ids":[%q]}`, ident.New())
|
||||
if r := sendJSON(router, c, "key", changed); r.Code != http.StatusConflict {
|
||||
t.Fatalf("changed body: %d %s", r.Code, r.Body)
|
||||
}
|
||||
if r := sendJSON(router, c, "new", body); r.Code != http.StatusConflict {
|
||||
t.Fatalf("new message: %d %s", r.Code, r.Body)
|
||||
}
|
||||
if _, err := db.Pool.Exec(f.ctx, `DELETE FROM chat_members WHERE chat_id=$1 AND user_id=$2`, c, f.alice); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r := sendJSON(router, c, "key", body); r.Code != http.StatusNotFound {
|
||||
t.Fatalf("former member: %d %s", r.Code, r.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentHTTPStatusAndChatAccess(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
c := f.newChat(t, f.alice, f.bob)
|
||||
other := f.newChat(t, f.alice)
|
||||
ready := f.attachment(t, c, f.bob, "ready")
|
||||
foreign := f.attachment(t, other, f.alice, "ready")
|
||||
ready := f.attachment(t, c, f.bob, "queued")
|
||||
foreign := f.attachment(t, other, f.alice, "queued")
|
||||
failed := f.attachment(t, c, f.alice, "failed")
|
||||
pending := f.attachment(t, c, f.alice, "pending")
|
||||
pending := f.attachment(t, c, f.alice, "processing")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
actor, attachment uuid.UUID
|
||||
@@ -96,13 +134,13 @@ func TestAttachmentHTTPStatusAndChatAccess(t *testing.T) {
|
||||
{"unknown", f.alice, ident.New(), http.StatusNotFound},
|
||||
{"foreign", f.alice, foreign, http.StatusNotFound},
|
||||
{"failed", f.alice, failed, http.StatusConflict},
|
||||
{"pending", f.alice, pending, http.StatusConflict},
|
||||
{"processing", f.alice, pending, http.StatusCreated},
|
||||
{"outsider", f.eve, ready, http.StatusNotFound},
|
||||
{"other-owner", f.alice, ready, http.StatusCreated},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
body := fmt.Sprintf(`{"text":"","attachment_ids":[%q]}`, tc.attachment)
|
||||
rec := sendJSON(messageRouter(f, tc.actor), c, "same", body)
|
||||
rec := sendJSON(messageRouter(f, tc.actor), c, tc.name, body)
|
||||
if rec.Code != tc.want {
|
||||
t.Fatalf("send: %d %s, want %d", rec.Code, rec.Body, tc.want)
|
||||
}
|
||||
|
||||
@@ -30,7 +30,12 @@ func (f fixture) attachment(t *testing.T, chatID, owner uuid.UUID, status string
|
||||
VALUES ($1, 7, 'image/png', $2, now()) RETURNING hash)
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, file_hash, created_at)
|
||||
SELECT $3, $4, $5, 'image.png', hash, now() FROM file`,
|
||||
hash[:], status, id, chatID, owner)
|
||||
hash[:], "pending", id, chatID, owner)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Pool.Exec(f.ctx, `INSERT INTO attachment_jobs(attachment_id,source_key,state,error_code)
|
||||
VALUES ($1,$2,$3,CASE WHEN $3='failed' THEN 'source_missing' END)`, id, "staging/"+id.String(), status)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -75,18 +80,18 @@ func TestAppendOnceRejectsUnknownAttachmentWithoutClaim(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAppendOnceAttachmentValidationIsAtomic(t *testing.T) {
|
||||
for _, status := range []string{"foreign", "failed", "pending", "mixed"} {
|
||||
for _, status := range []string{"foreign", "failed", "mixed"} {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice, bob := f.mustUser(t), f.mustUser(t)
|
||||
c := f.mustChat(t, alice, bob)
|
||||
other := f.mustChat(t, alice)
|
||||
ready := f.attachment(t, c.ID, bob, "ready")
|
||||
ready := f.attachment(t, c.ID, bob, "queued")
|
||||
var invalid uuid.UUID
|
||||
want := apperr.KindConflict
|
||||
switch status {
|
||||
case "foreign":
|
||||
invalid = f.attachment(t, other.ID, alice, "ready")
|
||||
invalid = f.attachment(t, other.ID, alice, "queued")
|
||||
want = apperr.KindNotFound
|
||||
case "mixed":
|
||||
ready = f.attachment(t, c.ID, bob, "failed")
|
||||
@@ -100,7 +105,7 @@ func TestAppendOnceAttachmentValidationIsAtomic(t *testing.T) {
|
||||
t.Fatalf("validation: %v; want %v", err, want)
|
||||
}
|
||||
assertCounts(t, 0, 0, 0)
|
||||
good := f.attachment(t, c.ID, bob, "ready")
|
||||
good := f.attachment(t, c.ID, bob, "queued")
|
||||
f.appendOnce(t, attachedMessage(t, c.ID, alice, good), "bad")
|
||||
assertCounts(t, 1, 1, 1)
|
||||
})
|
||||
@@ -111,7 +116,7 @@ func TestAppendOnceAttachmentOrderReplayAndExpiration(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice, bob := f.mustUser(t), f.mustUser(t)
|
||||
c := f.mustChat(t, alice, bob)
|
||||
a, b := f.attachment(t, c.ID, bob, "ready"), f.attachment(t, c.ID, bob, "ready")
|
||||
a, b := f.attachment(t, c.ID, bob, "queued"), f.attachment(t, c.ID, bob, "queued")
|
||||
first := attachedMessage(t, c.ID, alice, b, a)
|
||||
got := f.appendOnce(t, first, "k")
|
||||
if !reflect.DeepEqual(got, first) {
|
||||
@@ -138,19 +143,23 @@ func TestAppendOnceAttachmentOrderReplayAndExpiration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendOnceRevalidatesAttachmentOnReplay(t *testing.T) {
|
||||
func TestAppendOnceReplaysAcceptedMessageAfterAttachmentFails(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice := f.mustUser(t)
|
||||
c := f.mustChat(t, alice)
|
||||
a := f.attachment(t, c.ID, alice, "ready")
|
||||
a := f.attachment(t, c.ID, alice, "queued")
|
||||
first := attachedMessage(t, c.ID, alice, a)
|
||||
f.appendOnce(t, first, "k")
|
||||
if _, err := db.Pool.Exec(f.ctx, `UPDATE files SET status = 'failed'`); err != nil {
|
||||
if _, err := db.Pool.Exec(f.ctx, `UPDATE attachment_jobs SET state = 'failed',error_code='source_missing'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := f.messages.AppendOnce(f.ctx, attachedMessage(t, c.ID, alice, a), "k", keyTTL)
|
||||
got := f.appendOnce(t, attachedMessage(t, c.ID, alice, a), "k")
|
||||
if !reflect.DeepEqual(got, first) {
|
||||
t.Fatalf("replay = %+v, want original %+v", got, first)
|
||||
}
|
||||
_, err := f.messages.AppendOnce(f.ctx, attachedMessage(t, c.ID, alice, a), "new", keyTTL)
|
||||
if err == nil || apperr.KindOf(err) != apperr.KindConflict {
|
||||
t.Fatalf("failed replay attachment = %v, want conflict", err)
|
||||
t.Fatalf("new message with failed attachment = %v, want conflict", err)
|
||||
}
|
||||
page, err := f.messages.ListByChat(f.ctx, c.ID, nil, 10)
|
||||
if err != nil || len(page) != 1 || !reflect.DeepEqual(page[0], first) {
|
||||
@@ -163,7 +172,7 @@ func TestAppendOnceRollsBackClaimAndMessageOnJoinFailure(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice := f.mustUser(t)
|
||||
c := f.mustChat(t, alice)
|
||||
a := f.attachment(t, c.ID, alice, "ready")
|
||||
a := f.attachment(t, c.ID, alice, "queued")
|
||||
// A database fault at the join boundary must not leave a key or message.
|
||||
_, err := db.Pool.Exec(f.ctx, `ALTER TABLE message_attachments ADD CONSTRAINT test_reject_join CHECK (ordinal < 0)`)
|
||||
if err != nil {
|
||||
@@ -184,7 +193,7 @@ func TestConcurrentAttachmentAppendsSameKeyStoreOneOrderedSet(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice := f.mustUser(t)
|
||||
c := f.mustChat(t, alice)
|
||||
a, b := f.attachment(t, c.ID, alice, "ready"), f.attachment(t, c.ID, alice, "ready")
|
||||
a, b := f.attachment(t, c.ID, alice, "queued"), f.attachment(t, c.ID, alice, "queued")
|
||||
const requests = 20
|
||||
results := make(chan chat.Message, requests)
|
||||
start := make(chan struct{})
|
||||
@@ -238,7 +247,7 @@ func TestAttachmentHistorySingleQueryAndBatchedValidation(t *testing.T) {
|
||||
c := f.mustChat(t, alice)
|
||||
var ids []uuid.UUID
|
||||
for range 10 {
|
||||
ids = append(ids, f.attachment(t, c.ID, alice, "ready"))
|
||||
ids = append(ids, f.attachment(t, c.ID, alice, "queued"))
|
||||
}
|
||||
cfg := db.Pool.Config()
|
||||
counter := &queryCounter{}
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"messenger/internal/attachment"
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/postgres"
|
||||
@@ -138,9 +137,6 @@ const claimSQL = `
|
||||
func (r *Messages) AppendOnce(ctx context.Context, m chat.Message, key string, ttl time.Duration) (chat.Message, error) {
|
||||
var stored chat.Message
|
||||
err := pgx.BeginFunc(ctx, r.pool, func(tx pgx.Tx) error {
|
||||
if err := validateAttachments(ctx, tx, m.ChatID, m.AttachmentIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
@@ -151,6 +147,11 @@ func (r *Messages) AppendOnce(ctx context.Context, m chat.Message, key string, t
|
||||
return fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() == 1 {
|
||||
// Only a new message creates attachment links. A replay returns the
|
||||
// committed message even if its attachment has since failed.
|
||||
if err := validateAttachments(ctx, tx, m.ChatID, m.AttachmentIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(m.AttachmentIDs) > 0 {
|
||||
_, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (chat_id, message_id, attachment_id, ordinal)
|
||||
@@ -192,27 +193,39 @@ func validateAttachments(ctx context.Context, tx pgx.Tx, chatID uuid.UUID, ids [
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
// Shared row locks prevent deletion or a readiness change until joins commit.
|
||||
// Lock attachment identities in the same order for every message. Pipeline
|
||||
// version changes lock the attachment before replacing its current job.
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT f.status
|
||||
FROM attachments a
|
||||
JOIN files f ON f.hash = a.file_hash
|
||||
WHERE a.chat_id = $1 AND a.id = ANY($2::uuid[])
|
||||
ORDER BY a.id
|
||||
FOR SHARE OF a, f`, chatID, ids)
|
||||
SELECT id FROM attachments WHERE chat_id=$1 AND id=ANY($2::uuid[])
|
||||
ORDER BY id FOR SHARE`, chatID, ids)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check attachments: %w", err)
|
||||
return fmt.Errorf("lock attachments: %w", err)
|
||||
}
|
||||
statuses, err := pgx.CollectRows(rows, pgx.RowTo[attachment.FileStatus])
|
||||
locked, err := pgx.CollectRows(rows, pgx.RowTo[uuid.UUID])
|
||||
if err != nil {
|
||||
return fmt.Errorf("read attachment status: %w", err)
|
||||
return err
|
||||
}
|
||||
if len(statuses) != len(ids) {
|
||||
if len(locked) != len(ids) {
|
||||
return apperr.NotFound("attachment not found")
|
||||
}
|
||||
for _, status := range statuses {
|
||||
if status != attachment.FileReady {
|
||||
return apperr.Conflict("attachment is not ready")
|
||||
// A separate statement sees the latest committed transition after a lock wait.
|
||||
// Every referenced attachment must have a current job.
|
||||
rows, err = tx.Query(ctx, `SELECT status FROM attachment_states WHERE id=ANY($1::uuid[]) ORDER BY id FOR SHARE`, ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
states, err := pgx.CollectRows(rows, pgx.RowTo[string])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(states) != len(ids) {
|
||||
return apperr.Conflict("attachment processing state unavailable")
|
||||
}
|
||||
for _, state := range states {
|
||||
switch state {
|
||||
case "queued", "processing", "ready":
|
||||
default:
|
||||
return apperr.Conflict("attachment processing failed")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
Reference in New Issue
Block a user