forked from FerretDB/FerretDB
/
registry.go
648 lines (520 loc) · 17.4 KB
/
registry.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
// Copyright 2021 FerretDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metadata
import (
"context"
"fmt"
"hash/fnv"
"slices"
"sort"
"strings"
"sync"
"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"golang.org/x/exp/maps"
"github.com/FerretDB/FerretDB/internal/backends"
"github.com/FerretDB/FerretDB/internal/backends/sqlite/metadata/pool"
"github.com/FerretDB/FerretDB/internal/util/fsql"
"github.com/FerretDB/FerretDB/internal/util/lazyerrors"
"github.com/FerretDB/FerretDB/internal/util/must"
"github.com/FerretDB/FerretDB/internal/util/observability"
"github.com/FerretDB/FerretDB/internal/util/state"
)
const (
// This prefix is reserved by SQLite for internal use,
// see https://www.sqlite.org/lang_createtable.html.
reservedTablePrefix = "sqlite_"
// SQLite table name where FerretDB metadata is stored.
metadataTableName = backends.ReservedPrefix + "collections"
)
// Parts of Prometheus metric names.
const (
namespace = "ferretdb"
subsystem = "sqlite_metadata"
)
// Registry provides access to SQLite databases and collections information.
//
// Exported methods are safe for concurrent use. Unexported methods are not.
type Registry struct {
p *pool.Pool
l *zap.Logger
BatchSize int
// rw protects colls but also acts like a global lock for the whole registry.
// The latter effectively replaces transactions (see the sqlite backend package description for more info).
// One global lock should be replaced by more granular locks – one per database or even one per collection.
// But that requires some redesign.
// TODO https://github.com/FerretDB/FerretDB/issues/2755
rw sync.RWMutex
colls map[string]map[string]*Collection // database name -> collection name -> collection
}
// NewRegistry creates a registry for SQLite databases in the directory specified by SQLite URI.
func NewRegistry(u string, batchSize int, l *zap.Logger, sp *state.Provider) (*Registry, error) {
p, initDBs, err := pool.New(u, l, sp)
if err != nil {
return nil, err
}
r := &Registry{
p: p,
l: l,
BatchSize: batchSize,
colls: map[string]map[string]*Collection{},
}
for name, db := range initDBs {
if err = r.initCollections(context.Background(), name, db); err != nil {
r.Close()
return nil, lazyerrors.Error(err)
}
}
return r, nil
}
// Close closes the registry.
func (r *Registry) Close() {
r.p.Close()
}
// initCollections loads collections metadata from the database during initialization.
func (r *Registry) initCollections(ctx context.Context, dbName string, db *fsql.DB) error {
defer observability.FuncCall(ctx)()
rows, err := db.QueryContext(ctx, fmt.Sprintf("SELECT name, table_name, settings FROM %q", metadataTableName))
if err != nil {
return lazyerrors.Error(err)
}
defer rows.Close()
colls := map[string]*Collection{}
for rows.Next() {
var c Collection
if err = rows.Scan(&c.Name, &c.TableName, &c.Settings); err != nil {
return lazyerrors.Error(err)
}
colls[c.Name] = &c
}
if err = rows.Err(); err != nil {
return lazyerrors.Error(err)
}
r.colls[dbName] = colls
return nil
}
// DatabaseList returns a sorted list of existing databases.
func (r *Registry) DatabaseList(ctx context.Context) []string {
defer observability.FuncCall(ctx)()
return r.p.List(ctx)
}
// DatabaseGetExisting returns a connection to existing database or nil if it doesn't exist.
func (r *Registry) DatabaseGetExisting(ctx context.Context, dbName string) *fsql.DB {
defer observability.FuncCall(ctx)()
return r.p.GetExisting(ctx, dbName)
}
// DatabaseGetOrCreate returns a connection to existing database or newly created database.
func (r *Registry) DatabaseGetOrCreate(ctx context.Context, dbName string) (*fsql.DB, error) {
defer observability.FuncCall(ctx)()
r.rw.Lock()
defer r.rw.Unlock()
return r.databaseGetOrCreate(ctx, dbName)
}
// databaseGetOrCreate returns a connection to existing database or newly created database.
//
// It does not hold the lock.
func (r *Registry) databaseGetOrCreate(ctx context.Context, dbName string) (*fsql.DB, error) {
defer observability.FuncCall(ctx)()
db, created, err := r.p.GetOrCreate(ctx, dbName)
if err != nil {
return nil, lazyerrors.Error(err)
}
if !created {
return db, nil
}
q := fmt.Sprintf(
"CREATE TABLE %q ("+
"name TEXT NOT NULL UNIQUE CHECK(name != ''), "+
"table_name TEXT NOT NULL UNIQUE CHECK(table_name != ''), "+
"settings TEXT NOT NULL CHECK(settings != '')"+
") STRICT",
metadataTableName,
)
if _, err = db.ExecContext(ctx, q); err != nil {
r.databaseDrop(ctx, dbName)
return nil, lazyerrors.Error(err)
}
return db, nil
}
// DatabaseDrop drops the database.
//
// Returned boolean value indicates whether the database was dropped.
func (r *Registry) DatabaseDrop(ctx context.Context, dbName string) bool {
defer observability.FuncCall(ctx)()
r.rw.Lock()
defer r.rw.Unlock()
return r.databaseDrop(ctx, dbName)
}
// databaseDrop drops the database.
//
// Returned boolean value indicates whether the database was dropped.
//
// It does not hold the lock.
func (r *Registry) databaseDrop(ctx context.Context, dbName string) bool {
defer observability.FuncCall(ctx)()
delete(r.colls, dbName)
return r.p.Drop(ctx, dbName)
}
// CollectionList returns a sorted copy of collections in the database.
//
// If database does not exist, no error is returned.
func (r *Registry) CollectionList(ctx context.Context, dbName string) ([]*Collection, error) {
defer observability.FuncCall(ctx)()
db := r.DatabaseGetExisting(ctx, dbName)
if db == nil {
return nil, nil
}
r.rw.RLock()
res := make([]*Collection, 0, len(r.colls[dbName]))
for _, c := range r.colls[dbName] {
res = append(res, c.deepCopy())
}
r.rw.RUnlock()
sort.Slice(res, func(i, j int) bool { return res[i].Name < res[j].Name })
return res, nil
}
// CollectionCreateParams contains parameters for CollectionCreate.
type CollectionCreateParams struct {
DBName string
Name string
CappedSize int64
CappedDocuments int64
_ struct{} // prevent unkeyed literals
}
// Capped returns true if capped collection creation is requested.
func (ccp *CollectionCreateParams) Capped() bool {
return ccp.CappedSize > 0 // TODO https://github.com/FerretDB/FerretDB/issues/3631
}
// CollectionCreate creates a collection in the database.
// Database will be created automatically if needed.
//
// Returned boolean value indicates whether the collection was created.
// If collection already exists, (false, nil) is returned.
func (r *Registry) CollectionCreate(ctx context.Context, params *CollectionCreateParams) (bool, error) {
defer observability.FuncCall(ctx)()
r.rw.Lock()
defer r.rw.Unlock()
return r.collectionCreate(ctx, params)
}
// collectionCreate creates a collection in the database.
// Database will be created automatically if needed.
//
// Returned boolean value indicates whether the collection was created.
// If collection already exists, (false, nil) is returned.
//
// It does not hold the lock.
func (r *Registry) collectionCreate(ctx context.Context, params *CollectionCreateParams) (bool, error) {
defer observability.FuncCall(ctx)()
dbName, collectionName := params.DBName, params.Name
db, err := r.databaseGetOrCreate(ctx, dbName)
if err != nil {
return false, lazyerrors.Error(err)
}
colls := r.colls[dbName]
if colls != nil && colls[collectionName] != nil {
return false, nil
}
h := fnv.New32a()
must.NotFail(h.Write([]byte(collectionName)))
s := h.Sum32()
var tableName string
list := maps.Values(colls)
for {
tableName = fmt.Sprintf("%s_%08x", strings.ToLower(collectionName), s)
if strings.HasPrefix(tableName, reservedTablePrefix) {
tableName = "_" + tableName
}
if !slices.ContainsFunc(list, func(c *Collection) bool { return c.TableName == tableName }) {
break
}
// table already exists, generate a new table name by incrementing the hash
s++
}
q := fmt.Sprintf("CREATE TABLE %q (", tableName)
if params.Capped() {
q += fmt.Sprintf("%s INTEGER PRIMARY KEY, ", RecordIDColumn)
}
q += fmt.Sprintf("%[1]s TEXT NOT NULL CHECK(%[1]s != '')) STRICT", DefaultColumn)
if _, err = db.ExecContext(ctx, q); err != nil {
return false, lazyerrors.Error(err)
}
q = fmt.Sprintf("INSERT INTO %q (name, table_name, settings) VALUES (?, ?, ?)", metadataTableName)
if _, err = db.ExecContext(ctx, q, collectionName, tableName, "{}"); err != nil {
_, _ = db.ExecContext(ctx, fmt.Sprintf("DROP TABLE %q", tableName))
return false, lazyerrors.Error(err)
}
if r.colls[dbName] == nil {
r.colls[dbName] = map[string]*Collection{}
}
r.colls[dbName][collectionName] = &Collection{
Name: collectionName,
TableName: tableName,
Settings: Settings{
UUID: uuid.NewString(),
CappedSize: params.CappedSize,
CappedDocuments: params.CappedDocuments,
},
}
err = r.indexesCreate(ctx, dbName, collectionName, []IndexInfo{{
Name: backends.DefaultIndexName,
Key: []IndexKeyPair{{Field: "_id"}},
Unique: true,
}})
if err != nil {
_, _ = r.collectionDrop(ctx, dbName, collectionName)
return false, lazyerrors.Error(err)
}
return true, nil
}
// CollectionGet returns a copy of collection metadata.
// It can be safely modified by a caller.
//
// If database or collection does not exist, nil is returned.
func (r *Registry) CollectionGet(ctx context.Context, dbName, collectionName string) *Collection {
defer observability.FuncCall(ctx)()
r.rw.RLock()
defer r.rw.RUnlock()
return r.collectionGet(dbName, collectionName)
}
// collectionGet returns a copy of collection metadata.
// It can be safely modified by a caller.
//
// If database or collection does not exist, nil is returned.
//
// It does not hold the lock.
func (r *Registry) collectionGet(dbName, collectionName string) *Collection {
colls := r.colls[dbName]
if colls == nil {
return nil
}
return colls[collectionName].deepCopy()
}
// CollectionDrop drops a collection in the database.
//
// Returned boolean value indicates whether the collection was dropped.
// If database or collection did not exist, (false, nil) is returned.
func (r *Registry) CollectionDrop(ctx context.Context, dbName, collectionName string) (bool, error) {
defer observability.FuncCall(ctx)()
r.rw.Lock()
defer r.rw.Unlock()
return r.collectionDrop(ctx, dbName, collectionName)
}
// collectionDrop drops a collection in the database.
//
// Returned boolean value indicates whether the collection was dropped.
// If database or collection did not exist, (false, nil) is returned.
//
// It does not hold the lock.
func (r *Registry) collectionDrop(ctx context.Context, dbName, collectionName string) (bool, error) {
defer observability.FuncCall(ctx)()
db := r.DatabaseGetExisting(ctx, dbName)
if db == nil {
return false, nil
}
c := r.collectionGet(dbName, collectionName)
if c == nil {
return false, nil
}
q := fmt.Sprintf("DELETE FROM %q WHERE name = ?", metadataTableName)
if _, err := db.ExecContext(ctx, q, collectionName); err != nil {
return false, lazyerrors.Error(err)
}
q = fmt.Sprintf("DROP TABLE %q", c.TableName)
if _, err := db.ExecContext(ctx, q); err != nil {
return false, lazyerrors.Error(err)
}
delete(r.colls[dbName], collectionName)
return true, nil
}
// CollectionRename renames a collection in the database.
//
// The collection name is updated, but original table name is kept.
//
// Returned boolean value indicates whether the collection was renamed.
// If database or collection did not exist, (false, nil) is returned.
func (r *Registry) CollectionRename(ctx context.Context, dbName, oldCollectionName, newCollectionName string) (bool, error) {
defer observability.FuncCall(ctx)()
db := r.DatabaseGetExisting(ctx, dbName)
if db == nil {
return false, nil
}
r.rw.Lock()
defer r.rw.Unlock()
c := r.collectionGet(dbName, oldCollectionName)
if c == nil {
return false, nil
}
q := fmt.Sprintf(`UPDATE %q SET name = ? WHERE table_name = ?`, metadataTableName)
if _, err := db.ExecContext(ctx, q, newCollectionName, c.TableName); err != nil {
return false, lazyerrors.Error(err)
}
c.Name = newCollectionName
r.colls[dbName][newCollectionName] = c
delete(r.colls[dbName], oldCollectionName)
return true, nil
}
// IndexesCreate creates indexes in the collection.
//
// Existing indexes with given names are ignored.
func (r *Registry) IndexesCreate(ctx context.Context, dbName, collectionName string, indexes []IndexInfo) error {
defer observability.FuncCall(ctx)()
r.rw.Lock()
defer r.rw.Unlock()
return r.indexesCreate(ctx, dbName, collectionName, indexes)
}
// indexesCreate creates indexes in the collection.
//
// Existing indexes with given names are ignored.
//
// It does not hold the lock.
func (r *Registry) indexesCreate(ctx context.Context, dbName, collectionName string, indexes []IndexInfo) error {
defer observability.FuncCall(ctx)()
_, err := r.collectionCreate(ctx, &CollectionCreateParams{DBName: dbName, Name: collectionName})
if err != nil {
return lazyerrors.Error(err)
}
db := r.DatabaseGetExisting(ctx, dbName)
if db == nil {
panic("database does not exist")
}
c := r.collectionGet(dbName, collectionName)
if c == nil {
panic("collection does not exist")
}
created := make([]string, 0, len(indexes))
for _, index := range indexes {
if slices.ContainsFunc(c.Settings.Indexes, func(i IndexInfo) bool { return index.Name == i.Name }) {
continue
}
q := "CREATE "
if index.Unique {
q += "UNIQUE "
}
// Find a better way to sanitize identifiers.
// TODO https://github.com/FerretDB/FerretDB/issues/3418
q += "INDEX %q ON %q (%s)"
columns := make([]string, len(index.Key))
for i, key := range index.Key {
fields := strings.Split(key.Field, ".")
for j, f := range fields {
fields[j] = fmt.Sprintf("%q", f)
}
columns[i] = fmt.Sprintf("%s->%s", DefaultColumn, strings.Join(fields, "->"))
if key.Descending {
columns[i] += " DESC"
}
}
q = fmt.Sprintf(
q,
c.TableName+"_"+index.Name,
c.TableName,
strings.Join(columns, ", "),
)
if _, err := db.ExecContext(ctx, q); err != nil {
_ = r.indexesDrop(ctx, dbName, collectionName, created)
return lazyerrors.Error(err)
}
created = append(created, index.Name)
c.Settings.Indexes = append(c.Settings.Indexes, index)
}
q := fmt.Sprintf("UPDATE %q SET settings = ? WHERE table_name = ?", metadataTableName)
if _, err := db.ExecContext(ctx, q, c.Settings, c.TableName); err != nil {
_ = r.indexesDrop(ctx, dbName, collectionName, created)
return lazyerrors.Error(err)
}
r.colls[dbName][collectionName] = c
return nil
}
// IndexesDrop removes given connection's indexes.
//
// Non-existing indexes are ignored.
//
// If database or collection does not exist, nil is returned.
func (r *Registry) IndexesDrop(ctx context.Context, dbName, collectionName string, indexNames []string) error {
defer observability.FuncCall(ctx)()
r.rw.Lock()
defer r.rw.Unlock()
return r.indexesDrop(ctx, dbName, collectionName, indexNames)
}
// indexesDrop removes given connection's indexes.
//
// Non-existing indexes are ignored.
//
// If database or collection does not exist, nil is returned.
//
// It does not hold the lock.
func (r *Registry) indexesDrop(ctx context.Context, dbName, collectionName string, indexNames []string) error {
defer observability.FuncCall(ctx)()
c := r.collectionGet(dbName, collectionName)
if c == nil {
return nil
}
db := r.DatabaseGetExisting(ctx, dbName)
if db == nil {
return nil
}
for _, name := range indexNames {
i := slices.IndexFunc(c.Settings.Indexes, func(i IndexInfo) bool { return name == i.Name })
if i < 0 {
continue
}
q := fmt.Sprintf("DROP INDEX %q", c.TableName+"_"+name)
if _, err := db.ExecContext(ctx, q); err != nil {
return lazyerrors.Error(err)
}
c.Settings.Indexes = slices.Delete(c.Settings.Indexes, i, i+1)
}
q := fmt.Sprintf("UPDATE %q SET settings = ? WHERE table_name = ?", metadataTableName)
if _, err := db.ExecContext(ctx, q, c.Settings, c.TableName); err != nil {
return lazyerrors.Error(err)
}
r.colls[dbName][collectionName] = c
return nil
}
// Describe implements prometheus.Collector.
func (r *Registry) Describe(ch chan<- *prometheus.Desc) {
prometheus.DescribeByCollect(r, ch)
}
// Collect implements prometheus.Collector.
func (r *Registry) Collect(ch chan<- prometheus.Metric) {
r.p.Collect(ch)
r.rw.RLock()
defer r.rw.RUnlock()
ch <- prometheus.MustNewConstMetric(
prometheus.NewDesc(
prometheus.BuildFQName(namespace, subsystem, "databases"),
"The current number of database in the registry.",
nil, nil,
),
prometheus.GaugeValue,
float64(len(r.colls)),
)
for db, colls := range r.colls {
ch <- prometheus.MustNewConstMetric(
prometheus.NewDesc(
prometheus.BuildFQName(namespace, subsystem, "collections"),
"The current number of collections in the registry.",
[]string{"db"}, nil,
),
prometheus.GaugeValue,
float64(len(colls)),
db,
)
}
}
// check interfaces
var (
_ prometheus.Collector = (*Registry)(nil)
)