forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema.go
288 lines (239 loc) · 7.82 KB
/
schema.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
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
package collections
import (
"context"
"fmt"
"regexp"
"sort"
"strings"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/core/store"
)
// SchemaBuilder is used for building schemas. The Build method should always
// be called after all collections have been initialized. Initializing new
// collections with the builder after initialization will result in panics.
type SchemaBuilder struct {
schema *Schema
err error
}
// NewSchemaBuilderFromAccessor creates a new schema builder from the provided store accessor function.
func NewSchemaBuilderFromAccessor(accessorFunc func(ctx context.Context) store.KVStore) *SchemaBuilder {
return &SchemaBuilder{
schema: &Schema{
storeAccessor: accessorFunc,
collectionsByName: map[string]collection{},
collectionsByPrefix: map[string]collection{},
},
}
}
// NewSchemaBuilder creates a new schema builder from the provided store key.
// Callers should always call the SchemaBuilder.Build method when they are
// done adding collections to the schema.
func NewSchemaBuilder(service store.KVStoreService) *SchemaBuilder {
return NewSchemaBuilderFromAccessor(service.OpenKVStore)
}
// Build should be called after all collections that are part of the schema
// have been initialized in order to get a reference to the Schema. It is
// important to check the returned error for any initialization errors.
// The SchemaBuilder CANNOT be used after Build is called - doing so will
// result in panics.
func (s *SchemaBuilder) Build() (Schema, error) {
if s.err != nil {
return Schema{}, s.err
}
// check for any overlapping prefixes
for prefix := range s.schema.collectionsByPrefix {
for prefix2 := range s.schema.collectionsByPrefix {
// don't compare the prefix to itself
if prefix == prefix2 {
continue
}
// if one prefix is the prefix of the other we have an overlap and
// this schema is corrupt
if strings.HasPrefix(prefix, prefix2) {
return Schema{}, fmt.Errorf("schema has overlapping prefixes 0x%x and 0x%x", prefix, prefix2)
}
}
}
// compute ordered collections
collectionsOrdered := make([]string, 0, len(s.schema.collectionsByName))
for name := range s.schema.collectionsByName {
collectionsOrdered = append(collectionsOrdered, name)
}
sort.Strings(collectionsOrdered)
s.schema.collectionsOrdered = collectionsOrdered
if s.schema == nil {
// explicit panic to avoid nil pointer dereference
panic("builder already used to construct a schema")
}
schema := *s.schema
s.schema = nil // this makes the builder unusable
return schema, nil
}
func (s *SchemaBuilder) addCollection(collection collection) {
prefix := collection.getPrefix()
name := collection.getName()
if _, ok := s.schema.collectionsByPrefix[string(prefix)]; ok {
s.appendError(fmt.Errorf("prefix %v already taken within schema", prefix))
return
}
if _, ok := s.schema.collectionsByName[name]; ok {
s.appendError(fmt.Errorf("name %s already taken within schema", name))
return
}
if !nameRegex.MatchString(name) {
s.appendError(fmt.Errorf("name must match regex %s, got %s", NameRegex, name))
return
}
s.schema.collectionsByPrefix[string(prefix)] = collection
s.schema.collectionsByName[name] = collection
}
func (s *SchemaBuilder) appendError(err error) {
if s.err == nil {
s.err = err
return
}
s.err = fmt.Errorf("%w\n%w", s.err, err)
}
// NameRegex is the regular expression that all valid collection names must match.
const NameRegex = "[A-Za-z][A-Za-z0-9_]*"
var nameRegex = regexp.MustCompile("^" + NameRegex + "$")
// Schema specifies a group of collections stored within the storage specified
// by a single store key. All the collections within the schema must have a
// unique binary prefix and human-readable name. Schema will eventually include
// methods for importing/exporting genesis data and for schema reflection for
// clients.
type Schema struct {
storeAccessor func(context.Context) store.KVStore
collectionsOrdered []string
collectionsByPrefix map[string]collection
collectionsByName map[string]collection
}
// NewSchema creates a new schema for the provided KVStoreService.
func NewSchema(service store.KVStoreService) Schema {
return NewSchemaFromAccessor(func(ctx context.Context) store.KVStore {
return service.OpenKVStore(ctx)
})
}
// NewMemoryStoreSchema creates a new schema for the provided MemoryStoreService.
func NewMemoryStoreSchema(service store.MemoryStoreService) Schema {
return NewSchemaFromAccessor(func(ctx context.Context) store.KVStore {
return service.OpenMemoryStore(ctx)
})
}
// NewSchemaFromAccessor creates a new schema for the provided store accessor
// function. Modules built against versions of the SDK which do not support
// the cosmossdk.io/core/appmodule APIs should use this method.
// Ex:
// NewSchemaFromAccessor(func(ctx context.Context) store.KVStore {
// return sdk.UnwrapSDKContext(ctx).KVStore(kvStoreKey)
// }
func NewSchemaFromAccessor(accessor func(context.Context) store.KVStore) Schema {
return Schema{
storeAccessor: accessor,
collectionsByName: map[string]collection{},
collectionsByPrefix: map[string]collection{},
}
}
// DefaultGenesis implements the appmodule.HasGenesis.DefaultGenesis method.
func (s Schema) DefaultGenesis(target appmodule.GenesisTarget) error {
for _, name := range s.collectionsOrdered {
err := s.defaultGenesis(target, name)
if err != nil {
return fmt.Errorf("failed to instantiate default genesis for %s: %w", name, err)
}
}
return nil
}
func (s Schema) defaultGenesis(target appmodule.GenesisTarget, name string) error {
wc, err := target(name)
if err != nil {
return err
}
defer wc.Close()
coll, err := s.getCollection(name)
if err != nil {
return err
}
return coll.defaultGenesis(wc)
}
// ValidateGenesis implements the appmodule.HasGenesis.ValidateGenesis method.
func (s Schema) ValidateGenesis(source appmodule.GenesisSource) error {
for _, name := range s.collectionsOrdered {
err := s.validateGenesis(source, name)
if err != nil {
return fmt.Errorf("failed genesis validation of %s: %w", name, err)
}
}
return nil
}
func (s Schema) validateGenesis(source appmodule.GenesisSource, name string) error {
rc, err := source(name)
if err != nil {
return err
}
defer rc.Close()
coll, err := s.getCollection(name)
if err != nil {
return err
}
err = coll.validateGenesis(rc)
if err != nil {
return err
}
return nil
}
// InitGenesis implements the appmodule.HasGenesis.InitGenesis method.
func (s Schema) InitGenesis(ctx context.Context, source appmodule.GenesisSource) error {
for _, name := range s.collectionsOrdered {
err := s.initGenesis(ctx, source, name)
if err != nil {
return fmt.Errorf("failed genesis initialisation of %s: %w", name, err)
}
}
return nil
}
func (s Schema) initGenesis(ctx context.Context, source appmodule.GenesisSource, name string) error {
rc, err := source(name)
if err != nil {
return err
}
defer rc.Close()
coll, err := s.getCollection(name)
if err != nil {
return err
}
err = coll.importGenesis(ctx, rc)
if err != nil {
return err
}
return nil
}
// ExportGenesis implements the appmodule.HasGenesis.ExportGenesis method.
func (s Schema) ExportGenesis(ctx context.Context, target appmodule.GenesisTarget) error {
for _, name := range s.collectionsOrdered {
err := s.exportGenesis(ctx, target, name)
if err != nil {
return fmt.Errorf("failed to export genesis for %s: %w", name, err)
}
}
return nil
}
func (s Schema) exportGenesis(ctx context.Context, target appmodule.GenesisTarget, name string) error {
wc, err := target(name)
if err != nil {
return err
}
defer wc.Close()
coll, err := s.getCollection(name)
if err != nil {
return err
}
return coll.exportGenesis(ctx, wc)
}
func (s Schema) getCollection(name string) (collection, error) {
coll, ok := s.collectionsByName[name]
if !ok {
return nil, fmt.Errorf("unknown collection: %s", name)
}
return coll, nil
}