/
db.go
90 lines (77 loc) · 2.48 KB
/
db.go
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
package db
import (
"crypto/rand"
"strings"
ds "github.com/ipfs/go-datastore"
"github.com/ipfs/go-ipld-format"
ulid "github.com/oklog/ulid/v2"
)
const (
// EmptyInstanceID represents an empty InstanceID.
EmptyInstanceID = InstanceID("")
)
// InstanceID is the type used in instance identities.
type InstanceID string
// NewInstanceID generates a new identity for an instance.
func NewInstanceID() InstanceID {
id := ulid.MustNew(ulid.Now(), rand.Reader)
return InstanceID(strings.ToLower(id.String()))
}
func (e InstanceID) String() string {
return string(e)
}
// Event is a local or remote event generated in collection and dispatcher
// by Dispatcher.
type Event interface {
// Time (wall-clock) the event was created.
Time() []byte
// InstanceID is the associated instance's unique identifier.
InstanceID() InstanceID
// Collection is the associated instance's collection name.
Collection() string
// Marshal the event to JSON.
Marshal() ([]byte, error)
}
// ActionType is the type used by actions done in a txn.
type ActionType int
const (
// Create indicates the creation of an instance in a txn.
Create ActionType = iota
// Save indicates the mutation of an instance in a txn.
Save
// Delete indicates the deletion of an instance by ID in a txn.
Delete
)
// Action is a operation done in the collection.
type Action struct {
// Type of the action.
Type ActionType
// InstanceID of the instance in action.
InstanceID InstanceID
// CollectionName of the instance in action.
CollectionName string
// Previous is the instance before the action.
Previous []byte
// Current is the instance after the action was done.
Current []byte
}
type ReduceAction struct {
// Type of the reduced action.
Type ActionType
// Collection in which action was made.
Collection string
// InstanceID of the instance in reduced action.
InstanceID InstanceID
}
// IndexFunc handles index updates.
type IndexFunc func(collection string, key ds.Key, oldData, newData []byte, txn ds.Txn) error
// EventCodec transforms actions generated in collections to
// events dispatched to thread logs, and viceversa.
type EventCodec interface {
// Reduce applies generated events into state.
Reduce(events []Event, store ds.TxnDatastore, baseKey ds.Key, indexFunc IndexFunc) ([]ReduceAction, error)
// Create corresponding events to be dispatched.
Create(ops []Action) ([]Event, format.Node, error)
// EventsFromBytes deserializes a format.Node bytes payload into Events.
EventsFromBytes(data []byte) ([]Event, error)
}