go-hep.org/x/hep@v0.38.1/groot/rsrv/db.go (about) 1 // Copyright ©2018 The go-hep Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package rsrv 6 7 import ( 8 "fmt" 9 "os" 10 "sort" 11 "sync" 12 13 "go-hep.org/x/hep/groot/riofs" 14 ) 15 16 type DB struct { 17 sync.RWMutex 18 dir string 19 files map[string]*riofs.File // a map of URI -> ROOT file 20 } 21 22 func NewDB(dir string) *DB { 23 err := os.MkdirAll(dir, 0755) 24 if err != nil { 25 panic(fmt.Errorf("rsrv: could not create DB dir %q: %+v", dir, err)) 26 } 27 return &DB{ 28 dir: dir, 29 files: make(map[string]*riofs.File), 30 } 31 } 32 33 func (db *DB) Close() { 34 db.Lock() 35 defer db.Unlock() 36 for _, f := range db.files { 37 f.Close() 38 } 39 db.files = nil 40 os.RemoveAll(db.dir) 41 } 42 43 func (db *DB) Files() []string { 44 db.RLock() 45 defer db.RUnlock() 46 uris := make([]string, 0, len(db.files)) 47 for uri := range db.files { 48 uris = append(uris, uri) 49 } 50 sort.Strings(uris) 51 return uris 52 } 53 54 func (db *DB) Tx(uri string, fct func(f *riofs.File) error) error { 55 db.RLock() 56 defer db.RUnlock() 57 f := db.files[uri] 58 if f == nil { 59 return fmt.Errorf("rsrv: no such file %q", uri) 60 } 61 return fct(db.files[uri]) 62 } 63 64 func (db *DB) get(uri string) *riofs.File { 65 db.RLock() 66 defer db.RUnlock() 67 return db.files[uri] 68 } 69 70 func (db *DB) set(uri string, f *riofs.File) { 71 db.Lock() 72 defer db.Unlock() 73 if old, dup := db.files[uri]; dup { 74 old.Close() 75 } 76 db.files[uri] = f 77 } 78 79 func (db *DB) del(uri string) { 80 db.Lock() 81 defer db.Unlock() 82 83 f, ok := db.files[uri] 84 if !ok { 85 return 86 } 87 f.Close() 88 delete(db.files, uri) 89 }