ooni-probe-cli/internal/kvstore/fs.go
Simone Basso 273b70bacc
refactor: interfaces and data types into the model package (#642)
## Checklist

- [x] I have read the [contribution guidelines](https://github.com/ooni/probe-cli/blob/master/CONTRIBUTING.md)
- [x] reference issue for this pull request: https://github.com/ooni/probe/issues/1885
- [x] related ooni/spec pull request: N/A

Location of the issue tracker: https://github.com/ooni/probe

## Description

This PR contains a set of changes to move important interfaces and data types into the `./internal/model` package.

The criteria for including an interface or data type in here is roughly that the type should be important and used by several packages. We are especially interested to move more interfaces here to increase modularity.

An additional side effect is that, by reading this package, one should be able to understand more quickly how different parts of the codebase interact with each other.

This is what I want to move in `internal/model`:

- [x] most important interfaces from `internal/netxlite`
- [x] everything that was previously part of `internal/engine/model`
- [x] mocks from `internal/netxlite/mocks` should also be moved in here as a subpackage
2022-01-03 13:53:23 +01:00

57 lines
1.4 KiB
Go

package kvstore
import (
"bytes"
"fmt"
"io/fs"
"os"
"path/filepath"
"github.com/ooni/probe-cli/v3/internal/model"
"github.com/rogpeppe/go-internal/lockedfile"
)
// FS is a file-system based KVStore.
type FS struct {
basedir string
}
var _ model.KeyValueStore = &FS{}
// NewFS creates a new kvstore.FileSystem.
func NewFS(basedir string) (kvs *FS, err error) {
return newFileSystem(basedir, os.MkdirAll)
}
// osMkdirAll is the type of os.MkdirAll.
type osMkdirAll func(path string, perm fs.FileMode) error
// newFileSystem is like NewFileSystem with a customizable
// osMkdirAll function for creating the kvstore dir.
func newFileSystem(basedir string, mkdir osMkdirAll) (*FS, error) {
if err := mkdir(basedir, 0700); err != nil {
return nil, err
}
return &FS{basedir: basedir}, nil
}
// filename returns the filename for a given key.
func (kvs *FS) filename(key string) string {
return filepath.Join(kvs.basedir, key)
}
// Get returns the specified key's value. In case of error, the
// error type is such that errors.Is(err, ErrNoSuchKey).
func (kvs *FS) Get(key string) ([]byte, error) {
data, err := lockedfile.Read(kvs.filename(key))
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrNoSuchKey, err.Error())
}
return data, nil
}
// Set sets the value of a specific key.
func (kvs *FS) Set(key string, value []byte) error {
return lockedfile.Write(kvs.filename(key), bytes.NewReader(value), 0600)
}