operation.go

  1package dag
  2
  3import (
  4	"crypto/rand"
  5	"encoding/json"
  6	"fmt"
  7	"time"
  8
  9	"github.com/pkg/errors"
 10
 11	"github.com/MichaelMure/git-bug/entity"
 12	"github.com/MichaelMure/git-bug/identity"
 13	"github.com/MichaelMure/git-bug/repository"
 14)
 15
 16// OperationType is an operation type identifier
 17type OperationType int
 18
 19// Operation is a piece of data defining a change to reflect on the state of an Entity.
 20// What this Operation or Entity's state looks like is not of the resort of this package as it only deals with the
 21// data structure and storage.
 22type Operation interface {
 23	// Id return the Operation identifier
 24	//
 25	// Some care need to be taken to define a correct Id derivation and enough entropy in the data used to avoid
 26	// collisions. Notably:
 27	// - the Id of the first Operation will be used as the Id of the Entity. Collision need to be avoided across entities
 28	//   of the same type (example: no collision within the "bug" namespace).
 29	// - collisions can also happen within the set of Operations of an Entity. Simple Operation might not have enough
 30	//   entropy to yield unique Ids (example: two "close" operation within the same second, same author).
 31	//   If this is a concern, it is recommended to include a piece of random data in the operation's data, to guarantee
 32	//   a minimal amount of entropy and avoid collision.
 33	//
 34	//   Author's note: I tried to find a clever way around that inelegance (stuffing random useless data into the stored
 35	//   structure is not exactly elegant), but I failed to find a proper way. Essentially, anything that would reuse some
 36	//   other data (parent operation's Id, lamport clock) or the graph structure (depth) impose that the Id would only
 37	//   make sense in the context of the graph and yield some deep coupling between Entity and Operation. This in turn
 38	//   make the whole thing even less elegant.
 39	//
 40	// A common way to derive an Id will be to use the entity.DeriveId() function on the serialized operation data.
 41	Id() entity.Id
 42	// Type return the type of the operation
 43	Type() OperationType
 44	// Validate check if the Operation data is valid
 45	Validate() error
 46	// Author returns the author of this operation
 47	Author() identity.Interface
 48	// Time return the time when the operation was added
 49	Time() time.Time
 50
 51	// SetMetadata store arbitrary metadata about the operation
 52	SetMetadata(key string, value string)
 53	// GetMetadata retrieve arbitrary metadata about the operation
 54	GetMetadata(key string) (string, bool)
 55	// AllMetadata return all metadata for this operation
 56	AllMetadata() map[string]string
 57
 58	// setId allow to set the Id, used when unmarshalling only
 59	setId(id entity.Id)
 60	// setAuthor allow to set the author, used when unmarshalling only
 61	setAuthor(author identity.Interface)
 62	// setExtraMetadataImmutable add a metadata not carried by the operation itself on the operation
 63	setExtraMetadataImmutable(key string, value string)
 64}
 65
 66// OperationWithFiles is an optional extension for an Operation that has files dependency, stored in git.
 67type OperationWithFiles interface {
 68	// GetFiles return the files needed by this operation
 69	// This implies that the Operation maintain and store internally the references to those files. This is how
 70	// this information is read later, when loading from storage.
 71	// For example, an operation that has a text value referencing some files would maintain a mapping (text ref -->
 72	// hash).
 73	GetFiles() []repository.Hash
 74}
 75
 76// OperationDoesntChangeSnapshot is an interface signaling that the Operation implementing it doesn't change the
 77// snapshot, for example a metadata operation that act on other operations.
 78type OperationDoesntChangeSnapshot interface {
 79	DoesntChangeSnapshot()
 80}
 81
 82// Snapshot is the minimal interface that a snapshot need to implement
 83type Snapshot interface {
 84	// AllOperations returns all the operations that have been applied to that snapshot, in order
 85	AllOperations() []Operation
 86}
 87
 88// OpBase implement the common feature that every Operation should support.
 89type OpBase struct {
 90	// Not serialized. Store the op's id in memory.
 91	id entity.Id
 92	// Not serialized
 93	author identity.Interface
 94
 95	OperationType OperationType `json:"type"`
 96	UnixTime      int64         `json:"timestamp"`
 97
 98	// mandatory random bytes to ensure a better randomness of the data used to later generate the ID
 99	// len(Nonce) should be > 20 and < 64 bytes
100	// It has no functional purpose and should be ignored.
101	Nonce []byte `json:"nonce"`
102
103	Metadata map[string]string `json:"metadata,omitempty"`
104	// Not serialized. Store the extra metadata in memory,
105	// compiled from SetMetadataOperation.
106	extraMetadata map[string]string
107}
108
109func NewOpBase(opType OperationType, author identity.Interface, unixTime int64) OpBase {
110	return OpBase{
111		OperationType: opType,
112		author:        author,
113		UnixTime:      unixTime,
114		Nonce:         makeNonce(20),
115		id:            entity.UnsetId,
116	}
117}
118
119func makeNonce(len int) []byte {
120	result := make([]byte, len)
121	_, err := rand.Read(result)
122	if err != nil {
123		panic(err)
124	}
125	return result
126}
127
128func IdOperation(op Operation, base *OpBase) entity.Id {
129	if base.id == "" {
130		// something went really wrong
131		panic("op's id not set")
132	}
133	if base.id == entity.UnsetId {
134		// This means we are trying to get the op's Id *before* it has been stored, for instance when
135		// adding multiple ops in one go in an OperationPack.
136		// As the Id is computed based on the actual bytes written on the disk, we are going to predict
137		// those and then get the Id. This is safe as it will be the exact same code writing on disk later.
138
139		data, err := json.Marshal(op)
140		if err != nil {
141			panic(err)
142		}
143
144		base.id = entity.DeriveId(data)
145	}
146	return base.id
147}
148
149func (base *OpBase) Type() OperationType {
150	return base.OperationType
151}
152
153// Time return the time when the operation was added
154func (base *OpBase) Time() time.Time {
155	return time.Unix(base.UnixTime, 0)
156}
157
158// Validate check the OpBase for errors
159func (base *OpBase) Validate(op Operation, opType OperationType) error {
160	if base.OperationType == 0 {
161		return fmt.Errorf("operation type unset")
162	}
163	if base.OperationType != opType {
164		return fmt.Errorf("incorrect operation type (expected: %v, actual: %v)", opType, base.OperationType)
165	}
166
167	if op.Time().Unix() == 0 {
168		return fmt.Errorf("time not set")
169	}
170
171	if base.author == nil {
172		return fmt.Errorf("author not set")
173	}
174
175	if err := op.Author().Validate(); err != nil {
176		return errors.Wrap(err, "author")
177	}
178
179	if op, ok := op.(OperationWithFiles); ok {
180		for _, hash := range op.GetFiles() {
181			if !hash.IsValid() {
182				return fmt.Errorf("file with invalid hash %v", hash)
183			}
184		}
185	}
186
187	if len(base.Nonce) > 64 {
188		return fmt.Errorf("nonce is too big")
189	}
190	if len(base.Nonce) < 20 {
191		return fmt.Errorf("nonce is too small")
192	}
193
194	return nil
195}
196
197// IsAuthored is a sign post method for gqlgen
198func (base *OpBase) IsAuthored() {}
199
200// Author return author identity
201func (base *OpBase) Author() identity.Interface {
202	return base.author
203}
204
205// IdIsSet returns true if the id has been set already
206func (base *OpBase) IdIsSet() bool {
207	return base.id != "" && base.id != entity.UnsetId
208}
209
210// SetMetadata store arbitrary metadata about the operation
211func (base *OpBase) SetMetadata(key string, value string) {
212	if base.IdIsSet() {
213		panic("set metadata on an operation with already an Id")
214	}
215
216	if base.Metadata == nil {
217		base.Metadata = make(map[string]string)
218	}
219	base.Metadata[key] = value
220}
221
222// GetMetadata retrieve arbitrary metadata about the operation
223func (base *OpBase) GetMetadata(key string) (string, bool) {
224	val, ok := base.Metadata[key]
225
226	if ok {
227		return val, true
228	}
229
230	// extraMetadata can't replace the original operations value if any
231	val, ok = base.extraMetadata[key]
232
233	return val, ok
234}
235
236// AllMetadata return all metadata for this operation
237func (base *OpBase) AllMetadata() map[string]string {
238	result := make(map[string]string)
239
240	for key, val := range base.extraMetadata {
241		result[key] = val
242	}
243
244	// Original metadata take precedence
245	for key, val := range base.Metadata {
246		result[key] = val
247	}
248
249	return result
250}
251
252// setId allow to set the Id, used when unmarshalling only
253func (base *OpBase) setId(id entity.Id) {
254	if base.id != "" && base.id != entity.UnsetId {
255		panic("trying to set id again")
256	}
257	base.id = id
258}
259
260// setAuthor allow to set the author, used when unmarshalling only
261func (base *OpBase) setAuthor(author identity.Interface) {
262	base.author = author
263}
264
265func (base *OpBase) setExtraMetadataImmutable(key string, value string) {
266	if base.extraMetadata == nil {
267		base.extraMetadata = make(map[string]string)
268	}
269	if _, exist := base.extraMetadata[key]; !exist {
270		base.extraMetadata[key] = value
271	}
272}