ooni-probe-cli/internal/engine/saver.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

70 lines
1.6 KiB
Go

package engine
import (
"errors"
"github.com/ooni/probe-cli/v3/internal/model"
)
// Saver saves a measurement on some persistent storage.
type Saver interface {
SaveMeasurement(m *model.Measurement) error
}
// SaverConfig is the configuration for creating a new Saver.
type SaverConfig struct {
// Enabled is true if saving is enabled.
Enabled bool
// Experiment is the experiment we're currently running.
Experiment SaverExperiment
// FilePath is the filepath where to append the measurement as a
// serialized JSON followed by a newline character.
FilePath string
// Logger is the logger used by the saver.
Logger model.Logger
}
// SaverExperiment is an experiment according to the Saver.
type SaverExperiment interface {
SaveMeasurement(m *model.Measurement, filepath string) error
}
// NewSaver creates a new instance of Saver.
func NewSaver(config SaverConfig) (Saver, error) {
if !config.Enabled {
return fakeSaver{}, nil
}
if config.FilePath == "" {
return nil, errors.New("saver: passed an empty filepath")
}
return realSaver{
Experiment: config.Experiment,
FilePath: config.FilePath,
Logger: config.Logger,
}, nil
}
type fakeSaver struct{}
func (fs fakeSaver) SaveMeasurement(m *model.Measurement) error {
return nil
}
var _ Saver = fakeSaver{}
type realSaver struct {
Experiment SaverExperiment
FilePath string
Logger model.Logger
}
func (rs realSaver) SaveMeasurement(m *model.Measurement) error {
rs.Logger.Info("saving measurement to disk")
return rs.Experiment.SaveMeasurement(m, rs.FilePath)
}
var _ Saver = realSaver{}