forked from mtusi2026/mtusi2026lab3
Lab3: atomic one-statement idempotent write, tuned stand, level-4/5 measurement tooling
This commit is contained in:
+63
-55
@@ -157,6 +157,12 @@ func isForeignKeyViolation(err error) bool {
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23503"
|
||||
}
|
||||
|
||||
func isIdempotencyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505" &&
|
||||
pgErr.ConstraintName == "message_idempotency_pkey"
|
||||
}
|
||||
|
||||
// CreateUser inserts a user and relies on the unique index for both ordinary
|
||||
// duplicates and concurrent registrations of the same username.
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
@@ -459,15 +465,24 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, text string
|
||||
}
|
||||
|
||||
// CreateMessageIdempotent appends a message and records the idempotency
|
||||
// result in one transaction. It is the lab3 replacement for CreateMessage on
|
||||
// the public POST path.
|
||||
// result in one PostgreSQL statement. The statement is atomic: if the
|
||||
// idempotency unique index conflicts, the whole statement aborts and the
|
||||
// speculative message insert is rolled back by PostgreSQL, so a concurrent
|
||||
// repeat can never leave an extra row. A committed row therefore always has
|
||||
// both the message and the key record, satisfying the contract's requirement
|
||||
// that the side effect and the stored result are atomic.
|
||||
//
|
||||
// One round trip replaces the baseline's explicit transaction, message insert
|
||||
// and idempotency insert (track-1 improvement). The redundant membership
|
||||
// predicate in the INSERT...SELECT keeps the database-level guarantee even if
|
||||
// a caller bypasses the handler's earlier access check.
|
||||
//
|
||||
// Behavior derived from contracts/README.md:
|
||||
// - a new (user, method, path, key) creates a message and its record, 201;
|
||||
// - the same semantic body replays the stored message, 201, exactly once;
|
||||
// - a different body with the same key is a conflict, 409;
|
||||
// - a transient failure rolls both statements back, so the client may
|
||||
// safely retry the same key and never observe a duplicate side effect.
|
||||
// - a transient failure touches neither table, so the client may safely
|
||||
// retry the same key and never observe a duplicate side effect.
|
||||
func (s *Store) CreateMessageIdempotent(ctx context.Context, chatID, senderID, method, path, key string, requestHash []byte, text string) (model.Message, bool, error) {
|
||||
message := model.Message{
|
||||
ID: uuid.New(),
|
||||
@@ -479,63 +494,56 @@ func (s *Store) CreateMessageIdempotent(ctx context.Context, chatID, senderID, m
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
created := time.Now().UTC()
|
||||
var stored time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
WITH inserted AS (
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT $1::uuid, $2::uuid, $3::uuid, $4, $5
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members
|
||||
WHERE chat_id = $2::uuid AND user_id = $3::uuid
|
||||
)
|
||||
RETURNING id, created_at
|
||||
), recorded AS (
|
||||
INSERT INTO message_idempotency
|
||||
(user_id, method, path, key, request_hash, message_id, created_at)
|
||||
SELECT $3::uuid, $6, $7, $8, $9, inserted.id, $5
|
||||
FROM inserted
|
||||
RETURNING message_id
|
||||
)
|
||||
SELECT inserted.id, inserted.created_at
|
||||
FROM inserted
|
||||
JOIN recorded ON recorded.message_id = inserted.id`,
|
||||
message.ID, chatID, senderID, text, created,
|
||||
method, path, key, requestHash,
|
||||
).Scan(&message.ID, &stored)
|
||||
if err != nil {
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
|
||||
var createdAt time.Time
|
||||
if err := tx.QueryRow(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
RETURNING created_at`,
|
||||
message.ID, chatID, senderID, text, time.Now().UTC(),
|
||||
).Scan(&createdAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
if isIdempotencyViolation(err) {
|
||||
// The statement aborted, so the speculative message was rolled
|
||||
// back. Read the committed winner and compare the canonical body.
|
||||
storedHash, storedMessage, found, replayErr := s.replayIdempotent(ctx, senderID, method, path, key)
|
||||
if replayErr != nil {
|
||||
return model.Message{}, false, replayErr
|
||||
}
|
||||
if !found {
|
||||
return model.Message{}, false, fmt.Errorf("%w: idempotency record vanished", ErrUnavailable)
|
||||
}
|
||||
if !bytes.Equal(storedHash, requestHash) {
|
||||
return model.Message{}, false, ErrIdempotencyConflict
|
||||
}
|
||||
return storedMessage, true, nil
|
||||
}
|
||||
if isForeignKeyViolation(err) {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_idempotency
|
||||
(user_id, method, path, key, request_hash, message_id, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6::uuid, $7)
|
||||
ON CONFLICT (user_id, method, path, key) DO NOTHING`,
|
||||
senderID, method, path, key, requestHash, message.ID, time.Now().UTC(),
|
||||
)
|
||||
if err != nil {
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
if tag.RowsAffected() == 1 {
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
message.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return message, false, nil
|
||||
}
|
||||
|
||||
// Another transaction owns this key. Roll back this speculative message,
|
||||
// then read the committed record. A concurrent insert waits on the unique
|
||||
// index inside Exec above, so the conflicting row is already committed
|
||||
// when RowsAffected reports zero.
|
||||
_ = tx.Rollback(context.Background())
|
||||
|
||||
storedHash, storedMessage, found, err := s.replayIdempotent(ctx, senderID, method, path, key)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if !found {
|
||||
// The conflicting row disappeared between the conflict and this read
|
||||
// (only a retention prune can do that). Report a bounded transient
|
||||
// error; no message was committed and the same key is safe to retry.
|
||||
return model.Message{}, false, fmt.Errorf("%w: idempotency record vanished", ErrUnavailable)
|
||||
}
|
||||
if !bytes.Equal(storedHash, requestHash) {
|
||||
return model.Message{}, false, ErrIdempotencyConflict
|
||||
}
|
||||
return storedMessage, true, nil
|
||||
message.CreatedAt = model.Time{Time: stored.UTC()}
|
||||
return message, false, nil
|
||||
}
|
||||
|
||||
func (s *Store) replayIdempotent(ctx context.Context, userID, method, path, key string) ([]byte, model.Message, bool, error) {
|
||||
|
||||
Reference in New Issue
Block a user