Added locking, broke all the tests.

master
jdl 2022-07-26 14:10:41 +02:00
parent 5a9e355df8
commit a3ca69101e
2 changed files with 27 additions and 10 deletions

View File

@ -4,7 +4,8 @@ An in-process, in-memory database for Go.
## TO DO ## TO DO
* [ ] kvstore: tests * [ ] mdb: db exclusive lock
* [ ] mdb: clean up tests
## Structure ## Structure

View File

@ -3,35 +3,49 @@ package mdb
import ( import (
"net" "net"
"os" "os"
"path/filepath"
"sync" "sync"
"git.crumpington.com/private/mdb/kvstore" "git.crumpington.com/private/mdb/kvstore"
"golang.org/x/sys/unix"
) )
type Database struct { type Database struct {
root string root string
lock *os.File
kv *kvstore.KV kv *kvstore.KV
collections map[string]dbCollection collections map[string]dbCollection
} }
func NewPrimary(root string) *Database { func NewPrimary(root string) *Database {
must(os.MkdirAll(root, 0700)) return newDB(root, true)
db := &Database{
root: root,
collections: map[string]dbCollection{},
}
db.kv = kvstore.NewPrimary(root)
return db
} }
func NewSecondary(root string) *Database { func NewSecondary(root string) *Database {
return newDB(root, false)
}
func newDB(root string, primary bool) *Database {
must(os.MkdirAll(root, 0700)) must(os.MkdirAll(root, 0700))
lockPath := filepath.Join(root, "lock")
// Acquire the lock.
lock, err := os.OpenFile(lockPath, os.O_RDWR|os.O_CREATE, 0600)
must(err)
must(unix.Flock(int(lock.Fd()), unix.LOCK_EX))
db := &Database{ db := &Database{
root: root, root: root,
collections: map[string]dbCollection{}, collections: map[string]dbCollection{},
lock: lock,
}
if primary {
db.kv = kvstore.NewPrimary(root)
} else {
db.kv = kvstore.NewSecondary(root, db.onStore, db.onDelete)
} }
db.kv = kvstore.NewSecondary(root, db.onStore, db.onDelete)
return db return db
} }
@ -55,9 +69,11 @@ func (db *Database) WALStatus() (ws WALStatus) {
func (db *Database) Close() { func (db *Database) Close() {
db.kv.Close() db.kv.Close()
db.lock.Close()
} }
// ---------------------------------------------------------------------------- // -----------------
db.kv = kvstore.NewSecondary(root)-----------------------------------------------------------
func (db *Database) onStore(collection string, id uint64, data []byte) { func (db *Database) onStore(collection string, id uint64, data []byte) {
c, ok := db.collections[collection] c, ok := db.collections[collection]