Commit c3d04d3b authored by Adrian Sutton's avatar Adrian Sutton

op-program: Recreate preimage data dir if required

parent 8b9acddf
...@@ -37,7 +37,7 @@ func (d *DiskKV) pathKey(k common.Hash) string { ...@@ -37,7 +37,7 @@ func (d *DiskKV) pathKey(k common.Hash) string {
func (d *DiskKV) Put(k common.Hash, v []byte) error { func (d *DiskKV) Put(k common.Hash, v []byte) error {
d.Lock() d.Lock()
defer d.Unlock() defer d.Unlock()
f, err := os.CreateTemp(d.path, k.String()+".txt.*") f, err := openTempFile(d.path, k.String()+".txt.*")
if err != nil { if err != nil {
return fmt.Errorf("failed to open temp file for pre-image %s: %w", k, err) return fmt.Errorf("failed to open temp file for pre-image %s: %w", k, err)
} }
...@@ -57,6 +57,21 @@ func (d *DiskKV) Put(k common.Hash, v []byte) error { ...@@ -57,6 +57,21 @@ func (d *DiskKV) Put(k common.Hash, v []byte) error {
return nil return nil
} }
func openTempFile(dir string, nameTemplate string) (*os.File, error) {
f, err := os.CreateTemp(dir, nameTemplate)
// Directory has been deleted out from underneath us. Recreate it.
if errors.Is(err, os.ErrNotExist) {
if mkdirErr := os.MkdirAll(dir, 0777); mkdirErr != nil {
return nil, errors.Join(fmt.Errorf("failed to create directory %v: %w", dir, mkdirErr), err)
}
f, err = os.CreateTemp(dir, nameTemplate)
}
if err != nil {
return nil, err
}
return f, nil
}
func (d *DiskKV) Get(k common.Hash) ([]byte, error) { func (d *DiskKV) Get(k common.Hash) ([]byte, error) {
d.RLock() d.RLock()
defer d.RUnlock() defer d.RUnlock()
......
package kvstore package kvstore
import "testing" import (
"path/filepath"
"testing"
"github.com/ethereum/go-ethereum/crypto"
"github.com/stretchr/testify/require"
)
func TestDiskKV(t *testing.T) { func TestDiskKV(t *testing.T) {
tmp := t.TempDir() // automatically removed by testing cleanup tmp := t.TempDir() // automatically removed by testing cleanup
kv := NewDiskKV(tmp) kv := NewDiskKV(tmp)
kvTest(t, kv) kvTest(t, kv)
} }
func TestCreateMissingDirectory(t *testing.T) {
tmp := t.TempDir()
dir := filepath.Join(tmp, "data")
kv := NewDiskKV(dir)
val := []byte{1, 2, 3, 4}
key := crypto.Keccak256Hash(val)
require.NoError(t, kv.Put(key, val))
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment