0fdc9cafb5
* fix(all): introduce and use iox.ReadAllContext This improvement over the ioutil.ReadAll utility returns early if the context expires. This enables us to unblock stuck code in case there's censorship confounding the TCP stack. See https://github.com/ooni/probe/issues/1417. Compared to the functionality postulated in the above mentioned issue, I choose to be more generic and separate limiting the maximum body size (not implemented here) from using the context to return early when reading a body (or any other reader). After implementing iox.ReadAllContext, I made sure we always use it everywhere in the tree instead of ioutil.ReadAll. This includes many parts of the codebase where in theory we don't need iox.ReadAllContext. Though, changing all the places makes checking whether we're not using ioutil.ReadAll where we should not be using it easy: `git grep` should return no lines. * Update internal/iox/iox_test.go * fix(ndt7): treat context errors as non-errors The rationale is explained by the comment documenting reduceErr. * Update internal/engine/experiment/ndt7/download.go
73 lines
1.5 KiB
Go
73 lines
1.5 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"embed"
|
|
|
|
"github.com/apex/log"
|
|
"github.com/ooni/probe-cli/v3/internal/iox"
|
|
migrate "github.com/rubenv/sql-migrate"
|
|
"upper.io/db.v3/lib/sqlbuilder"
|
|
"upper.io/db.v3/sqlite"
|
|
)
|
|
|
|
//go:embed migrations/*.sql
|
|
var efs embed.FS
|
|
|
|
func readAsset(path string) ([]byte, error) {
|
|
filep, err := efs.Open(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return iox.ReadAllContext(context.Background(), filep)
|
|
}
|
|
|
|
func readAssetDir(path string) ([]string, error) {
|
|
var out []string
|
|
lst, err := efs.ReadDir(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, e := range lst {
|
|
out = append(out, e.Name())
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// RunMigrations runs the database migrations
|
|
func RunMigrations(db *sql.DB) error {
|
|
log.Debugf("running migrations")
|
|
migrations := &migrate.AssetMigrationSource{
|
|
Asset: readAsset,
|
|
AssetDir: readAssetDir,
|
|
Dir: "migrations",
|
|
}
|
|
n, err := migrate.Exec(db, "sqlite3", migrations, migrate.Up)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
log.Debugf("performed %d migrations", n)
|
|
return nil
|
|
}
|
|
|
|
// Connect to the database
|
|
func Connect(path string) (db sqlbuilder.Database, err error) {
|
|
settings := sqlite.ConnectionURL{
|
|
Database: path,
|
|
Options: map[string]string{"_foreign_keys": "1"},
|
|
}
|
|
sess, err := sqlite.Open(settings)
|
|
if err != nil {
|
|
log.WithError(err).Error("failed to open the DB")
|
|
return nil, err
|
|
}
|
|
|
|
err = RunMigrations(sess.Driver().(*sql.DB))
|
|
if err != nil {
|
|
log.WithError(err).Error("failed to run DB migration")
|
|
return nil, err
|
|
}
|
|
return sess, err
|
|
}
|