entity.go

  1// Package dag contains the base common code to define an entity stored
  2// in a chain of git objects, supporting actions like Push, Pull and Merge.
  3package dag
  4
  5import (
  6	"encoding/json"
  7	"fmt"
  8	"sort"
  9
 10	"github.com/pkg/errors"
 11
 12	"github.com/MichaelMure/git-bug/entity"
 13	"github.com/MichaelMure/git-bug/identity"
 14	"github.com/MichaelMure/git-bug/repository"
 15	"github.com/MichaelMure/git-bug/util/lamport"
 16)
 17
 18const refsPattern = "refs/%s/%s"
 19const creationClockPattern = "%s-create"
 20const editClockPattern = "%s-edit"
 21
 22// Definition hold the details defining one specialization of an Entity.
 23type Definition struct {
 24	// the name of the entity (bug, pull-request, ...)
 25	Typename string
 26	// the Namespace in git (bugs, prs, ...)
 27	Namespace string
 28	// a function decoding a JSON message into an Operation
 29	OperationUnmarshaler func(author identity.Interface, raw json.RawMessage) (Operation, error)
 30	// the expected format version number, that can be used for data migration/upgrade
 31	FormatVersion uint
 32}
 33
 34// Entity is a data structure stored in a chain of git objects, supporting actions like Push, Pull and Merge.
 35type Entity struct {
 36	// A Lamport clock is a logical clock that allow to order event
 37	// inside a distributed system.
 38	// It must be the first field in this struct due to https://github.com/golang/go/issues/36606
 39	createTime lamport.Time
 40	editTime   lamport.Time
 41
 42	Definition
 43
 44	// operations that are already stored in the repository
 45	ops []Operation
 46	// operations not yet stored in the repository
 47	staging []Operation
 48
 49	lastCommit repository.Hash
 50}
 51
 52// New create an empty Entity
 53func New(definition Definition) *Entity {
 54	return &Entity{
 55		Definition: definition,
 56	}
 57}
 58
 59// Read will read and decode a stored local Entity from a repository
 60func Read(def Definition, repo repository.ClockedRepo, resolver identity.Resolver, id entity.Id) (*Entity, error) {
 61	if err := id.Validate(); err != nil {
 62		return nil, errors.Wrap(err, "invalid id")
 63	}
 64
 65	ref := fmt.Sprintf("refs/%s/%s", def.Namespace, id.String())
 66
 67	return read(def, repo, resolver, ref)
 68}
 69
 70// readRemote will read and decode a stored remote Entity from a repository
 71func readRemote(def Definition, repo repository.ClockedRepo, resolver identity.Resolver, remote string, id entity.Id) (*Entity, error) {
 72	if err := id.Validate(); err != nil {
 73		return nil, errors.Wrap(err, "invalid id")
 74	}
 75
 76	ref := fmt.Sprintf("refs/remotes/%s/%s/%s", def.Namespace, remote, id.String())
 77
 78	return read(def, repo, resolver, ref)
 79}
 80
 81// read fetch from git and decode an Entity at an arbitrary git reference.
 82func read(def Definition, repo repository.ClockedRepo, resolver identity.Resolver, ref string) (*Entity, error) {
 83	rootHash, err := repo.ResolveRef(ref)
 84	if err != nil {
 85		return nil, err
 86	}
 87
 88	// Perform a breadth-first search to get a topological order of the DAG where we discover the
 89	// parents commit and go back in time up to the chronological root
 90
 91	queue := make([]repository.Hash, 0, 32)
 92	visited := make(map[repository.Hash]struct{})
 93	BFSOrder := make([]repository.Commit, 0, 32)
 94
 95	queue = append(queue, rootHash)
 96	visited[rootHash] = struct{}{}
 97
 98	for len(queue) > 0 {
 99		// pop
100		hash := queue[0]
101		queue = queue[1:]
102
103		commit, err := repo.ReadCommit(hash)
104		if err != nil {
105			return nil, err
106		}
107
108		BFSOrder = append(BFSOrder, commit)
109
110		for _, parent := range commit.Parents {
111			if _, ok := visited[parent]; !ok {
112				queue = append(queue, parent)
113				// mark as visited
114				visited[parent] = struct{}{}
115			}
116		}
117	}
118
119	// Now, we can reverse this topological order and read the commits in an order where
120	// we are sure to have read all the chronological ancestors when we read a commit.
121
122	// Next step is to:
123	// 1) read the operationPacks
124	// 2) make sure that the clocks causality respect the DAG topology.
125
126	oppMap := make(map[repository.Hash]*operationPack)
127	var opsCount int
128
129	for i := len(BFSOrder) - 1; i >= 0; i-- {
130		commit := BFSOrder[i]
131		isFirstCommit := i == len(BFSOrder)-1
132		isMerge := len(commit.Parents) > 1
133
134		// Verify DAG structure: single chronological root, so only the root
135		// can have no parents. Said otherwise, the DAG need to have exactly
136		// one leaf.
137		if !isFirstCommit && len(commit.Parents) == 0 {
138			return nil, fmt.Errorf("multiple leafs in the entity DAG")
139		}
140
141		opp, err := readOperationPack(def, repo, resolver, commit)
142		if err != nil {
143			return nil, err
144		}
145
146		err = opp.Validate()
147		if err != nil {
148			return nil, err
149		}
150
151		// Check that the create lamport clock is set (not checked in Validate() as it's optional)
152		if isFirstCommit && opp.CreateTime <= 0 {
153			return nil, fmt.Errorf("creation lamport time not set")
154		}
155
156		// make sure that the lamport clocks causality match the DAG topology
157		for _, parentHash := range commit.Parents {
158			parentPack, ok := oppMap[parentHash]
159			if !ok {
160				panic("DFS failed")
161			}
162
163			if parentPack.EditTime >= opp.EditTime {
164				return nil, fmt.Errorf("lamport clock ordering doesn't match the DAG")
165			}
166
167			// to avoid an attack where clocks are pushed toward the uint64 rollover, make sure
168			// that the clocks don't jump too far in the future
169			// we ignore merge commits here to allow merging after a loooong time without breaking anything,
170			// as long as there is one valid chain of small hops, it's fine.
171			if !isMerge && opp.EditTime-parentPack.EditTime > 1_000_000 {
172				return nil, fmt.Errorf("lamport clock jumping too far in the future, likely an attack")
173			}
174		}
175
176		oppMap[commit.Hash] = opp
177		opsCount += len(opp.Operations)
178	}
179
180	// The clocks are fine, we witness them
181	for _, opp := range oppMap {
182		err = repo.Witness(fmt.Sprintf(creationClockPattern, def.Namespace), opp.CreateTime)
183		if err != nil {
184			return nil, err
185		}
186		err = repo.Witness(fmt.Sprintf(editClockPattern, def.Namespace), opp.EditTime)
187		if err != nil {
188			return nil, err
189		}
190	}
191
192	// Now that we know that the topological order and clocks are fine, we order the operationPacks
193	// based on the logical clocks, entirely ignoring the DAG topology
194
195	oppSlice := make([]*operationPack, 0, len(oppMap))
196	for _, pack := range oppMap {
197		oppSlice = append(oppSlice, pack)
198	}
199	sort.Slice(oppSlice, func(i, j int) bool {
200		// Primary ordering with the EditTime.
201		if oppSlice[i].EditTime != oppSlice[j].EditTime {
202			return oppSlice[i].EditTime < oppSlice[j].EditTime
203		}
204		// We have equal EditTime, which means we have concurrent edition over different machines and we
205		// can't tell which one came first. So, what now? We still need a total ordering and the most stable possible.
206		// As a secondary ordering, we can order based on a hash of the serialized Operations in the
207		// operationPack. It doesn't carry much meaning but it's unbiased and hard to abuse.
208		// This is a lexicographic ordering on the stringified ID.
209		return oppSlice[i].Id() < oppSlice[j].Id()
210	})
211
212	// Now that we ordered the operationPacks, we have the order of the Operations
213
214	ops := make([]Operation, 0, opsCount)
215	var createTime lamport.Time
216	var editTime lamport.Time
217	for _, pack := range oppSlice {
218		for _, operation := range pack.Operations {
219			ops = append(ops, operation)
220		}
221		if pack.CreateTime > createTime {
222			createTime = pack.CreateTime
223		}
224		if pack.EditTime > editTime {
225			editTime = pack.EditTime
226		}
227	}
228
229	return &Entity{
230		Definition: def,
231		ops:        ops,
232		lastCommit: rootHash,
233		createTime: createTime,
234		editTime:   editTime,
235	}, nil
236}
237
238type StreamedEntity struct {
239	Entity *Entity
240	Err    error
241}
242
243// ReadAll read and parse all local Entity
244func ReadAll(def Definition, repo repository.ClockedRepo, resolver identity.Resolver) <-chan StreamedEntity {
245	out := make(chan StreamedEntity)
246
247	go func() {
248		defer close(out)
249
250		refPrefix := fmt.Sprintf("refs/%s/", def.Namespace)
251
252		refs, err := repo.ListRefs(refPrefix)
253		if err != nil {
254			out <- StreamedEntity{Err: err}
255			return
256		}
257
258		for _, ref := range refs {
259			e, err := read(def, repo, resolver, ref)
260
261			if err != nil {
262				out <- StreamedEntity{Err: err}
263				return
264			}
265
266			out <- StreamedEntity{Entity: e}
267		}
268	}()
269
270	return out
271}
272
273// Id return the Entity identifier
274func (e *Entity) Id() entity.Id {
275	// id is the id of the first operation
276	return e.FirstOp().Id()
277}
278
279// Validate check if the Entity data is valid
280func (e *Entity) Validate() error {
281	// non-empty
282	if len(e.ops) == 0 && len(e.staging) == 0 {
283		return fmt.Errorf("entity has no operations")
284	}
285
286	// check if each operations are valid
287	for _, op := range e.ops {
288		if err := op.Validate(); err != nil {
289			return err
290		}
291	}
292
293	// check if staging is valid if needed
294	for _, op := range e.staging {
295		if err := op.Validate(); err != nil {
296			return err
297		}
298	}
299
300	// Check that there is no colliding operation's ID
301	ids := make(map[entity.Id]struct{})
302	for _, op := range e.Operations() {
303		if _, ok := ids[op.Id()]; ok {
304			return fmt.Errorf("id collision: %s", op.Id())
305		}
306		ids[op.Id()] = struct{}{}
307	}
308
309	return nil
310}
311
312// Operations return the ordered operations
313func (e *Entity) Operations() []Operation {
314	return append(e.ops, e.staging...)
315}
316
317// FirstOp lookup for the very first operation of the Entity
318func (e *Entity) FirstOp() Operation {
319	for _, op := range e.ops {
320		return op
321	}
322	for _, op := range e.staging {
323		return op
324	}
325	return nil
326}
327
328// LastOp lookup for the very last operation of the Entity
329func (e *Entity) LastOp() Operation {
330	if len(e.staging) > 0 {
331		return e.staging[len(e.staging)-1]
332	}
333	if len(e.ops) > 0 {
334		return e.ops[len(e.ops)-1]
335	}
336	return nil
337}
338
339// Append add a new Operation to the Entity
340func (e *Entity) Append(op Operation) {
341	e.staging = append(e.staging, op)
342}
343
344// NeedCommit indicate if the in-memory state changed and need to be commit in the repository
345func (e *Entity) NeedCommit() bool {
346	return len(e.staging) > 0
347}
348
349// CommitAsNeeded execute a Commit only if necessary. This function is useful to avoid getting an error if the Entity
350// is already in sync with the repository.
351func (e *Entity) CommitAsNeeded(repo repository.ClockedRepo) error {
352	if e.NeedCommit() {
353		return e.Commit(repo)
354	}
355	return nil
356}
357
358// Commit write the appended operations in the repository
359func (e *Entity) Commit(repo repository.ClockedRepo) error {
360	if !e.NeedCommit() {
361		return fmt.Errorf("can't commit an entity with no pending operation")
362	}
363
364	err := e.Validate()
365	if err != nil {
366		return errors.Wrapf(err, "can't commit a %s with invalid data", e.Definition.Typename)
367	}
368
369	for len(e.staging) > 0 {
370		var author identity.Interface
371		var toCommit []Operation
372
373		// Split into chunks with the same author
374		for len(e.staging) > 0 {
375			op := e.staging[0]
376			if author != nil && op.Author().Id() != author.Id() {
377				break
378			}
379			author = e.staging[0].Author()
380			toCommit = append(toCommit, op)
381			e.staging = e.staging[1:]
382		}
383
384		e.editTime, err = repo.Increment(fmt.Sprintf(editClockPattern, e.Namespace))
385		if err != nil {
386			return err
387		}
388
389		opp := &operationPack{
390			Author:     author,
391			Operations: toCommit,
392			EditTime:   e.editTime,
393		}
394
395		if e.lastCommit == "" {
396			e.createTime, err = repo.Increment(fmt.Sprintf(creationClockPattern, e.Namespace))
397			if err != nil {
398				return err
399			}
400			opp.CreateTime = e.createTime
401		}
402
403		var parentCommit []repository.Hash
404		if e.lastCommit != "" {
405			parentCommit = []repository.Hash{e.lastCommit}
406		}
407
408		commitHash, err := opp.Write(e.Definition, repo, parentCommit...)
409		if err != nil {
410			return err
411		}
412
413		e.lastCommit = commitHash
414		e.ops = append(e.ops, toCommit...)
415	}
416
417	// not strictly necessary but make equality testing easier in tests
418	e.staging = nil
419
420	// Create or update the Git reference for this entity
421	// When pushing later, the remote will ensure that this ref update
422	// is fast-forward, that is no data has been overwritten.
423	ref := fmt.Sprintf(refsPattern, e.Namespace, e.Id().String())
424	return repo.UpdateRef(ref, e.lastCommit)
425}
426
427// CreateLamportTime return the Lamport time of creation
428func (e *Entity) CreateLamportTime() lamport.Time {
429	return e.createTime
430}
431
432// EditLamportTime return the Lamport time of the last edition
433func (e *Entity) EditLamportTime() lamport.Time {
434	return e.editTime
435}