-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathengine.go
384 lines (315 loc) · 9.3 KB
/
engine.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
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
* Copyright 2025 Hypermode Inc.
* Licensed under the terms of the Apache License, Version 2.0
* See the LICENSE file that accompanied this code for further details.
*
* SPDX-FileCopyrightText: 2025 Hypermode Inc. <[email protected]>
* SPDX-License-Identifier: Apache-2.0
*/
package modusdb
import (
"context"
"errors"
"fmt"
"path"
"strconv"
"sync"
"sync/atomic"
"github.com/dgraph-io/badger/v4"
"github.com/dgraph-io/dgo/v240/protos/api"
"github.com/dgraph-io/dgraph/v24/dql"
"github.com/dgraph-io/dgraph/v24/edgraph"
"github.com/dgraph-io/dgraph/v24/posting"
"github.com/dgraph-io/dgraph/v24/protos/pb"
"github.com/dgraph-io/dgraph/v24/query"
"github.com/dgraph-io/dgraph/v24/schema"
"github.com/dgraph-io/dgraph/v24/worker"
"github.com/dgraph-io/dgraph/v24/x"
"github.com/dgraph-io/ristretto/v2/z"
)
var (
// This ensures that we only have one instance of modusDB in this process.
singleton atomic.Bool
ErrSingletonOnly = errors.New("only one modusDB engine is supported")
ErrEmptyDataDir = errors.New("data directory is required")
ErrClosedEngine = errors.New("modusDB engine is closed")
ErrNonExistentDB = errors.New("namespace does not exist")
)
// Engine is an instance of modusDB.
// For now, we only support one instance of modusDB per process.
type Engine struct {
mutex sync.RWMutex
isOpen atomic.Bool
z *zero
// points to default / 0 / galaxy namespace
db0 *Namespace
}
// NewEngine returns a new modusDB instance.
func NewEngine(conf Config) (*Engine, error) {
// Ensure that we do not create another instance of modusDB in the same process
if !singleton.CompareAndSwap(false, true) {
return nil, ErrSingletonOnly
}
if err := conf.validate(); err != nil {
return nil, err
}
// setup data directories
worker.Config.PostingDir = path.Join(conf.dataDir, "p")
worker.Config.WALDir = path.Join(conf.dataDir, "w")
x.WorkerConfig.TmpDir = path.Join(conf.dataDir, "t")
// TODO: optimize these and more options
x.WorkerConfig.Badger = badger.DefaultOptions("").FromSuperFlag(worker.BadgerDefaults)
x.Config.MaxRetries = 10
x.Config.Limit = z.NewSuperFlag("max-pending-queries=100000")
x.Config.LimitNormalizeNode = conf.limitNormalizeNode
// initialize each package
edgraph.Init()
worker.State.InitStorage()
worker.InitForLite(worker.State.Pstore)
schema.Init(worker.State.Pstore)
posting.Init(worker.State.Pstore, 0) // TODO: set cache size
engine := &Engine{}
engine.isOpen.Store(true)
if err := engine.reset(); err != nil {
return nil, fmt.Errorf("error resetting db: %w", err)
}
x.UpdateHealthStatus(true)
engine.db0 = &Namespace{id: 0, engine: engine}
return engine, nil
}
func (engine *Engine) CreateNamespace() (*Namespace, error) {
engine.mutex.RLock()
defer engine.mutex.RUnlock()
if !engine.isOpen.Load() {
return nil, ErrClosedEngine
}
startTs, err := engine.z.nextTs()
if err != nil {
return nil, err
}
nsID, err := engine.z.nextNamespace()
if err != nil {
return nil, err
}
if err := worker.ApplyInitialSchema(nsID, startTs); err != nil {
return nil, fmt.Errorf("error applying initial schema: %w", err)
}
for _, pred := range schema.State().Predicates() {
worker.InitTablet(pred)
}
return &Namespace{id: nsID, engine: engine}, nil
}
func (engine *Engine) GetNamespace(nsID uint64) (*Namespace, error) {
engine.mutex.RLock()
defer engine.mutex.RUnlock()
return engine.getNamespaceWithLock(nsID)
}
func (engine *Engine) getNamespaceWithLock(nsID uint64) (*Namespace, error) {
if !engine.isOpen.Load() {
return nil, ErrClosedEngine
}
if nsID > engine.z.lastNamespace {
return nil, ErrNonExistentDB
}
// TODO: when delete namespace is implemented, check if the namespace exists
return &Namespace{id: nsID, engine: engine}, nil
}
func (engine *Engine) GetDefaultNamespace() *Namespace {
return engine.db0
}
// DropAll drops all the data and schema in the modusDB instance.
func (engine *Engine) DropAll(ctx context.Context) error {
engine.mutex.Lock()
defer engine.mutex.Unlock()
if !engine.isOpen.Load() {
return ErrClosedEngine
}
p := &pb.Proposal{Mutations: &pb.Mutations{
GroupId: 1,
DropOp: pb.Mutations_ALL,
}}
if err := worker.ApplyMutations(ctx, p); err != nil {
return fmt.Errorf("error applying mutation: %w", err)
}
if err := engine.reset(); err != nil {
return fmt.Errorf("error resetting db: %w", err)
}
// TODO: insert drop record
return nil
}
func (engine *Engine) dropData(ctx context.Context, ns *Namespace) error {
engine.mutex.Lock()
defer engine.mutex.Unlock()
if !engine.isOpen.Load() {
return ErrClosedEngine
}
p := &pb.Proposal{Mutations: &pb.Mutations{
GroupId: 1,
DropOp: pb.Mutations_DATA,
DropValue: strconv.FormatUint(ns.ID(), 10),
}}
if err := worker.ApplyMutations(ctx, p); err != nil {
return fmt.Errorf("error applying mutation: %w", err)
}
// TODO: insert drop record
// TODO: should we reset back the timestamp as well?
return nil
}
func (engine *Engine) alterSchema(ctx context.Context, ns *Namespace, sch string) error {
engine.mutex.Lock()
defer engine.mutex.Unlock()
if !engine.isOpen.Load() {
return ErrClosedEngine
}
sc, err := schema.ParseWithNamespace(sch, ns.ID())
if err != nil {
return fmt.Errorf("error parsing schema: %w", err)
}
return engine.alterSchemaWithParsed(ctx, sc)
}
func (engine *Engine) alterSchemaWithParsed(ctx context.Context, sc *schema.ParsedSchema) error {
for _, pred := range sc.Preds {
worker.InitTablet(pred.Predicate)
}
startTs, err := engine.z.nextTs()
if err != nil {
return err
}
p := &pb.Proposal{Mutations: &pb.Mutations{
GroupId: 1,
StartTs: startTs,
Schema: sc.Preds,
Types: sc.Types,
}}
if err := worker.ApplyMutations(ctx, p); err != nil {
return fmt.Errorf("error applying mutation: %w", err)
}
return nil
}
func (engine *Engine) query(ctx context.Context, ns *Namespace, q string) (*api.Response, error) {
engine.mutex.RLock()
defer engine.mutex.RUnlock()
return engine.queryWithLock(ctx, ns, q)
}
func (engine *Engine) queryWithLock(ctx context.Context, ns *Namespace, q string) (*api.Response, error) {
if !engine.isOpen.Load() {
return nil, ErrClosedEngine
}
ctx = x.AttachNamespace(ctx, ns.ID())
return (&edgraph.Server{}).QueryNoAuth(ctx, &api.Request{
ReadOnly: true,
Query: q,
StartTs: engine.z.readTs(),
})
}
func (engine *Engine) mutate(ctx context.Context, ns *Namespace, ms []*api.Mutation) (map[string]uint64, error) {
if len(ms) == 0 {
return nil, nil
}
engine.mutex.Lock()
defer engine.mutex.Unlock()
dms := make([]*dql.Mutation, 0, len(ms))
for _, mu := range ms {
dm, err := edgraph.ParseMutationObject(mu, false)
if err != nil {
return nil, fmt.Errorf("error parsing mutation: %w", err)
}
dms = append(dms, dm)
}
newUids, err := query.ExtractBlankUIDs(ctx, dms)
if err != nil {
return nil, err
}
if len(newUids) > 0 {
num := &pb.Num{Val: uint64(len(newUids)), Type: pb.Num_UID}
res, err := engine.z.nextUIDs(num)
if err != nil {
return nil, err
}
curId := res.StartId
for k := range newUids {
x.AssertTruef(curId != 0 && curId <= res.EndId, "not enough uids generated")
newUids[k] = curId
curId++
}
}
return engine.mutateWithDqlMutation(ctx, ns, dms, newUids)
}
func (engine *Engine) mutateWithDqlMutation(ctx context.Context, ns *Namespace, dms []*dql.Mutation,
newUids map[string]uint64) (map[string]uint64, error) {
edges, err := query.ToDirectedEdges(dms, newUids)
if err != nil {
return nil, fmt.Errorf("error converting to directed edges: %w", err)
}
ctx = x.AttachNamespace(ctx, ns.ID())
if !engine.isOpen.Load() {
return nil, ErrClosedEngine
}
startTs, err := engine.z.nextTs()
if err != nil {
return nil, err
}
commitTs, err := engine.z.nextTs()
if err != nil {
return nil, err
}
m := &pb.Mutations{
GroupId: 1,
StartTs: startTs,
Edges: edges,
}
m.Edges, err = query.ExpandEdges(ctx, m)
if err != nil {
return nil, fmt.Errorf("error expanding edges: %w", err)
}
for _, edge := range m.Edges {
worker.InitTablet(edge.Attr)
}
p := &pb.Proposal{Mutations: m, StartTs: startTs}
if err := worker.ApplyMutations(ctx, p); err != nil {
return nil, err
}
return newUids, worker.ApplyCommited(ctx, &pb.OracleDelta{
Txns: []*pb.TxnStatus{{StartTs: startTs, CommitTs: commitTs}},
})
}
func (engine *Engine) Load(ctx context.Context, schemaPath, dataPath string) error {
return engine.db0.Load(ctx, schemaPath, dataPath)
}
func (engine *Engine) LoadData(inCtx context.Context, dataDir string) error {
return engine.db0.LoadData(inCtx, dataDir)
}
// Close closes the modusDB instance.
func (engine *Engine) Close() {
engine.mutex.Lock()
defer engine.mutex.Unlock()
if !engine.isOpen.Load() {
return
}
if !singleton.CompareAndSwap(true, false) {
panic("modusDB instance was not properly opened")
}
engine.isOpen.Store(false)
x.UpdateHealthStatus(false)
posting.Cleanup()
worker.State.Dispose()
}
func (ns *Engine) reset() error {
z, restart, err := newZero()
if err != nil {
return fmt.Errorf("error initializing zero: %w", err)
}
if !restart {
if err := worker.ApplyInitialSchema(0, 1); err != nil {
return fmt.Errorf("error applying initial schema: %w", err)
}
}
if err := schema.LoadFromDb(context.Background()); err != nil {
return fmt.Errorf("error loading schema: %w", err)
}
for _, pred := range schema.State().Predicates() {
worker.InitTablet(pred)
}
ns.z = z
return nil
}