feat: fence command acceptance by session
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/rvbox/rvbox/internal/domain"
|
||||
)
|
||||
|
||||
var ErrDispatchMismatch = errors.New("command acceptance does not match dispatched generation or revision")
|
||||
|
||||
// RecordCommandAcceptance fences an acknowledgement to the exact dispatch that
|
||||
// produced it. Repeated acknowledgements are harmless; a stale session cannot
|
||||
// advance a newer dispatch or overwrite a terminal decision.
|
||||
func (store *Store) RecordCommandAcceptance(ctx context.Context, issueUUID domain.UUID, clientID string, generation, revision uint64, accepted bool, now time.Time) (bool, error) {
|
||||
if isZeroUUID([16]byte(issueUUID)) || clientID == "" || generation == 0 || revision == 0 || now.IsZero() {
|
||||
return false, ErrDispatchMismatch
|
||||
}
|
||||
store.writeMu.Lock()
|
||||
defer store.writeMu.Unlock()
|
||||
database, err := store.openDatabase()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
targetLifecycle := 3
|
||||
if !accepted {
|
||||
targetLifecycle = 11
|
||||
}
|
||||
query := `UPDATE commands SET lifecycle = ?`
|
||||
args := []any{targetLifecycle}
|
||||
if !accepted {
|
||||
query += `, terminal_time = ?`
|
||||
args = append(args, now.UTC().UnixNano())
|
||||
}
|
||||
query += ` WHERE issue_uuid = ? AND client_id = ? AND lifecycle = 2 AND target_session_generation = ? AND revision = ?`
|
||||
args = append(args, issueUUID[:], clientID, generation, revision)
|
||||
result, err := database.ExecContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
changed, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if changed == 1 {
|
||||
return true, nil
|
||||
}
|
||||
var lifecycle uint32
|
||||
var storedGeneration, storedRevision uint64
|
||||
err = database.QueryRowContext(ctx, `SELECT lifecycle, COALESCE(target_session_generation, 0), revision FROM commands WHERE issue_uuid = ? AND client_id = ?`, issueUUID[:], clientID).Scan(&lifecycle, &storedGeneration, &storedRevision)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return false, ErrDispatchMismatch
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if storedGeneration == generation && storedRevision == revision && ((accepted && (lifecycle == 3 || lifecycle == 4)) || (!accepted && lifecycle == 11)) {
|
||||
return false, nil
|
||||
}
|
||||
return false, ErrDispatchMismatch
|
||||
}
|
||||
Reference in New Issue
Block a user