1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
package transaction
import (
"context"
"errors"
"fmt"
"io"
"os"
"gitlab.com/gitlab-org/gitaly/v16/internal/safe"
"gitlab.com/gitlab-org/gitaly/v16/internal/transaction/txinfo"
"gitlab.com/gitlab-org/gitaly/v16/internal/transaction/voting"
)
// RunOnContext runs the given function if the context identifies a transaction.
func RunOnContext(ctx context.Context, fn func(txinfo.Transaction) error) error {
transaction, err := txinfo.TransactionFromContext(ctx)
if err != nil {
if errors.Is(err, txinfo.ErrTransactionNotFound) {
return nil
}
return err
}
return fn(transaction)
}
// VoteOnContext casts the vote on a transaction identified by the context, if there is any.
func VoteOnContext(ctx context.Context, m Manager, vote voting.Vote, phase voting.Phase) error {
return RunOnContext(ctx, func(transaction txinfo.Transaction) error {
return m.Vote(ctx, transaction, vote, phase)
})
}
// CommitLockedFile will lock, vote and commit the LockingFileWriter in a race-free manner.
func CommitLockedFile(ctx context.Context, m Manager, writer *safe.LockingFileWriter) (returnedErr error) {
if err := writer.Lock(); err != nil {
return fmt.Errorf("locking file: %w", err)
}
var vote voting.Vote
if err := RunOnContext(ctx, func(tx txinfo.Transaction) error {
hasher := voting.NewVoteHash()
lockedFile, err := os.Open(writer.Path())
if err != nil {
return fmt.Errorf("opening locked file: %w", err)
}
defer lockedFile.Close()
if _, err := io.Copy(hasher, lockedFile); err != nil {
return fmt.Errorf("hashing locked file: %w", err)
}
vote, err = hasher.Vote()
if err != nil {
return fmt.Errorf("computing vote for locked file: %w", err)
}
if err := m.Vote(ctx, tx, vote, voting.Prepared); err != nil {
return fmt.Errorf("preimage vote: %w", err)
}
return nil
}); err != nil {
return fmt.Errorf("voting on locked file: %w", err)
}
if err := writer.Commit(); err != nil {
return fmt.Errorf("committing file: %w", err)
}
if err := VoteOnContext(ctx, m, vote, voting.Committed); err != nil {
return fmt.Errorf("postimage vote: %w", err)
}
return nil
}
|