Welcome to mirror list, hosted at ThFree Co, Russian Federation.

mock.go « transaction « gitaly « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 10ad6efdf0fafe281e9af50ac5ce331d860d7fa6 (plain)
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
78
79
package transaction

import (
	"context"
	"errors"
	"sync"

	"gitlab.com/gitlab-org/gitaly/v14/internal/transaction/txinfo"
	"gitlab.com/gitlab-org/gitaly/v14/internal/transaction/voting"
)

// MockManager is a mock Manager for use in tests.
type MockManager struct {
	VoteFn func(context.Context, txinfo.Transaction, voting.Vote, voting.Phase) error
	StopFn func(context.Context, txinfo.Transaction) error
}

// Vote calls the MockManager's Vote function, if set. Otherwise, it returns an error.
func (m *MockManager) Vote(ctx context.Context, tx txinfo.Transaction, vote voting.Vote, phase voting.Phase) error {
	if m.VoteFn == nil {
		return errors.New("mock does not implement Vote function")
	}
	return m.VoteFn(ctx, tx, vote, phase)
}

// Stop calls the MockManager's Stop function, if set. Otherwise, it returns an error.
func (m *MockManager) Stop(ctx context.Context, tx txinfo.Transaction) error {
	if m.StopFn == nil {
		return errors.New("mock does not implement Stop function")
	}
	return m.StopFn(ctx, tx)
}

// PhasedVote is used to keep track of votes and the phase they were cast in.
type PhasedVote struct {
	Vote  voting.Vote
	Phase voting.Phase
}

// TrackingManager is a transaction manager which tracks all votes. Voting functions never return
// an error.
type TrackingManager struct {
	MockManager

	votesLock sync.Mutex
	votes     []PhasedVote
}

// NewTrackingManager creates a new TrackingManager which is ready for use.
func NewTrackingManager() *TrackingManager {
	manager := &TrackingManager{}

	manager.VoteFn = func(_ context.Context, _ txinfo.Transaction, vote voting.Vote, phase voting.Phase) error {
		manager.votesLock.Lock()
		defer manager.votesLock.Unlock()
		manager.votes = append(manager.votes, PhasedVote{Vote: vote, Phase: phase})
		return nil
	}

	return manager
}

// Votes returns a copy of all votes which have been cast.
func (m *TrackingManager) Votes() []PhasedVote {
	m.votesLock.Lock()
	defer m.votesLock.Unlock()

	votes := make([]PhasedVote, len(m.votes))
	copy(votes, m.votes)

	return votes
}

// Reset resets all votes which have been recorded up to this point.
func (m *TrackingManager) Reset() {
	m.votesLock.Lock()
	defer m.votesLock.Unlock()
	m.votes = nil
}