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

transaction.go « transaction « praefect « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9bc49bc24beb38dc003dcec44618ae1b689628d2 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/*Package transaction provides transaction management functionality to
coordinate one-to-many clients attempting to modify the shards concurrently.

While Git is distributed in nature, there are some repository wide data points
that can conflict between replicas if something goes wrong. This includes
references, which is why the transaction manager provides an API that allows
an RPC transaction to read/write lock the references being accessed to prevent
contention.
*/
package transaction

import (
	"context"
	"errors"
	"sync"

	"golang.org/x/sync/errgroup"
)

// Repository represents the identity and location of a repository as requested
// by the client
type Repository struct {
	ProjectHash string
	StorageLoc  string // storage location
}

// Verifier verifies the project repository state
type Verifier interface {
	// CheckSum will return the checksum for a project in a storage location
	CheckSum(context.Context, Repository) ([]byte, error)
}

// Coordinator allows the transaction manager to look up the shard for a repo
// at the beginning of each transaction
type Coordinator interface {
	FetchShard(ctx context.Context, repo Repository) (*Shard, error)
}

// ReplicationManager provides services to handle degraded nodes
type ReplicationManager interface {
	NotifyDegradation(context.Context, Repository, Node) error
}

// Manager tracks the progress of RPCs being applied to multiple
// downstream servers that make up a shard. It prevents conflicts that may arise
// from contention between multiple clients trying to modify the same
// references.
type Manager struct {
	mu     sync.Mutex
	shards map[string]*Shard // shards keyed by project

	verifier    Verifier
	coordinator Coordinator
	replman     ReplicationManager
}

func NewManager(v Verifier, c Coordinator, r ReplicationManager) *Manager {
	return &Manager{
		shards:      map[string]*Shard{},
		verifier:    v,
		coordinator: c,
		replman:     r,
	}
}

// State represents the current state of a backend node
// Note: in the future this may be extended to include refs
type State struct {
	Checksum []byte
}

type RPC struct {
	// @zj how do we abstract an RPC invocation? 🤔
}

type Node interface {
	Storage() string // storage location the node hosts
	ForwardRPC(ctx context.Context, rpc *RPC) error
}

// Shard represents
type Shard struct {
	repo Repository

	primary string // the designated primary node name

	// Replicas maps a storage location to the node replicas
	storageReplicas map[string]Node

	// refLocks coordinates changes between many clients attempting to mutate
	// a reference
	refLocks map[string]*sync.RWMutex

	// used to check shard for inconsistencies
	verifier Verifier
}

// ErrShardInconsistent indicates a mutating operation is unable to be executed
// due to lack of quorum of consistent nodes.
var ErrShardInconsistent = errors.New("majority of shard nodes are in inconsistent state")

func (s Shard) validate(ctx context.Context) (good, bad []Node, err error) {
	var (
		mu        sync.RWMutex
		checksums = map[string][]byte{}
	)

	eg, eCtx := errgroup.WithContext(ctx)

	for storage, _ := range s.storageReplicas {
		storage := storage // rescope iterator vars

		eg.Go(func() error {
			cs, err := s.verifier.CheckSum(eCtx, s.repo)
			if err != nil {
				return err
			}

			mu.Lock()
			checksums[storage] = cs
			mu.Unlock()

			return nil
		})

	}

	if err := eg.Wait(); err != nil {
		return nil, nil, err
	}

	pCS := string(checksums[s.primary])
	for storage, cs := range checksums {
		n := s.storageReplicas[storage]
		if string(cs) != pCS {
			bad = append(bad, n)
			continue
		}
		good = append(good, n)
	}

	return good, bad, nil
}

// MutateTx represents the resources available during a mutator transaction
type MutateTx interface {
	AccessTx
	// LockRef acquires a write lock on a reference
	LockRef(context.Context, string) error
	Shard() *Shard
}

// AccessTx represents the resources available during an accessor transaction
type AccessTx interface {
	// Replicas returns all replicas without distinguishing the primary
	Replicas() map[string]Node
	// RLockRef acquires a read lock on a reference
	RLockRef(context.Context, string) error
}

type transaction struct {
	shard    *Shard
	refLocks map[string]*sync.RWMutex
}

func (t transaction) Shard() *Shard { return t.shard }

// LockRef attempts to acquire a write lock on the reference name provided
//  (ref). If the context is cancelled first, the lock acquisition will be
// aborted.
func (t transaction) LockRef(ctx context.Context, ref string) error {
	lockQ := make(chan *sync.RWMutex)

	go func() {
		l := t.shard.refLocks[ref]
		l.Lock()
		lockQ <- l
	}()

	// ensure lockQ is consumed in all code paths so that goroutine doesn't
	// stray
	select {

	case <-ctx.Done():
		// unlock before aborting
		l := <-lockQ
		l.Unlock()

		return ctx.Err()

	case l := <-lockQ:
		t.refLocks[ref] = l

	}

	return nil
}

// unlockAll will unlock all acquired locks at the end of a transaction
func (t transaction) unlockAll() {
	// unlock all refs
	for _, rl := range t.refLocks {
		rl.Unlock()
	}
}

func (t transaction) Replicas() map[string]Node {
	return t.shard.storageReplicas
}

// RLockRef attempts to acquire a read lock on the reference name provided
// (ref). If  the context is cancelled first, the lock acquisition will be
// aborted.
func (t transaction) RLockRef(ctx context.Context, ref string) error {
	lockQ := make(chan *sync.RWMutex)

	go func() {
		l := t.shard.refLocks[ref]
		l.RLock()
		lockQ <- l
	}()

	// ensure lockQ is consumed in all code paths so that goroutine doesn't
	// stray
	select {

	case <-ctx.Done():
		// unlock before aborting
		l := <-lockQ
		l.RUnlock()

		return ctx.Err()

	case l := <-lockQ:
		t.refLocks[ref] = l

	}

	return nil
}

// Mutate accepts a closure whose environment is a snapshot of the repository
// before the transaction begins. It is the responsibility of the closure
// author to mark all relevant assets being modified during a mutating
// transaction to ensure they are locked and protected from other closures
// modifying the same.
func (m *Manager) Mutate(ctx context.Context, repo Repository, fn func(MutateTx) error) error {
	shard, err := m.coordinator.FetchShard(ctx, repo)
	if err != nil {
		return err
	}

	good, bad, err := shard.validate(ctx)
	if err != nil {
		return err
	}

	// are a majority of the nodes good (consistent)?
	if len(bad) >= len(good) {
		return ErrShardInconsistent
	}

	eg, eCtx := errgroup.WithContext(ctx)
	for _, node := range bad {
		node := node // rescope iterator var for goroutine closure

		eg.Go(func() error {
			return m.replman.NotifyDegradation(eCtx, repo, node)
		})
	}

	tx := transaction{
		shard:    shard,
		refLocks: map[string]*sync.RWMutex{},
	}
	defer tx.unlockAll()

	err = fn(tx)
	if err != nil {
		return err
	}

	return nil
}

func (m *Manager) Access(ctx context.Context, repo Repository, fn func(AccessTx) error) error {
	shard, err := m.coordinator.FetchShard(ctx, repo)
	if err != nil {
		return err
	}

	good, bad, err := shard.validate(ctx)
	if err != nil {
		return err
	}

	// are a majority of the nodes good (consistent)?
	if len(bad) >= len(good) {
		return ErrShardInconsistent
	}

	eg, eCtx := errgroup.WithContext(ctx)
	for _, node := range bad {
		node := node // rescope iterator var for goroutine closure

		eg.Go(func() error {
			return m.replman.NotifyDegradation(eCtx, repo, node)
		})
	}

	tx := transaction{
		shard:    shard,
		refLocks: map[string]*sync.RWMutex{},
	}
	defer tx.unlockAll()

	err = fn(tx)
	if err != nil {
		return err
	}

	return nil
}