Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Create meta.DB interface #92

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 4 additions & 8 deletions internal/meta/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type Branch struct {
// The branch name associated with this stack.
// Not stored in JSON because the name can always be derived from the name
// of the git ref.
Name string `json:"-"`
Name string `json:"name"`

// Information about the parent branch.
Parent BranchState `json:"parent,omitempty"`
Expand Down Expand Up @@ -60,13 +60,9 @@ func (b *Branch) UnmarshalJSON(bytes []byte) error {
return err
}

// Copy over all the data that we unmarshalled into BranchAlias. This is
// everything except since Parent which we'll handle next. We need to take
// special care to copy name since it won't be defined on BranchAlias (since
// Name is not serialized to JSON). Instead we expect that the struct is
// always initialized with the name defined, so we have to copy it over here.
// (Doing just "*b = ..." will result in us erasing the name.)
d.BranchAlias.Name = b.Name
if b.Name != "" {
d.BranchAlias.Name = b.Name
}
*b = Branch(d.BranchAlias)

// Parse the parent information (which can either be a string or a JSON)
Expand Down
35 changes: 35 additions & 0 deletions internal/meta/db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package meta

type DB interface {
ReadTx() ReadTx
WriteTx() WriteTx
}

// ReadTx is a transaction that can be used to read from the database.
// It presents a consistent view of the underlying database.
type ReadTx interface {
// Repository returns the repository information.
Repository() (Repository, bool)
// Branch returns the branch with the given name. If no such branch exists,
// the second return value is false.
Branch(name string) (Branch, bool)
// AllBranches returns a map of all branches in the database.
AllBranches() map[string]Branch
}

// WriteTx is a transaction that can be used to modify the database.
type WriteTx interface {
ReadTx
// Abort aborts the transaction (no changes will be committed).
// The transaction cannot be used after it has been aborted.
Abort()
// Commit commits the transaction (all changes will be committed).
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small ask: Can we add a contract like "Abort can be called even after Commit". Otherwise, we need to cancel the Cleanup.

// If an error is returned, the data could not be commited.
// The transaction cannot be used after it has been committed (even if an
// error is returned).
Commit() error
// SetBranch sets the given branch in the database.
SetBranch(branch Branch)
// SetRepository sets the repository information in the database.
SetRepository(repository Repository)
}
44 changes: 44 additions & 0 deletions internal/meta/jsonfiledb/db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package jsonfiledb

import (
"github.com/aviator-co/av/internal/meta"
"sync"
)

type DB struct {
filepath string

stateMu sync.Mutex
state *state
}

// Open opens a JSON file database at the given path.
// If the file does not exist, it is created.
func Open(filepath string) (*DB, error) {
state, err := readState(filepath)
if err != nil {
return nil, err
}
db := &DB{filepath, sync.Mutex{}, state}
return db, nil
}

func (d *DB) ReadTx() meta.ReadTx {
// Acquire the lock in order to safely access and copy state, but we don't
// need to hold the lock for the entire duration of the read transaction.
d.stateMu.Lock()
defer d.stateMu.Unlock()
return &readTx{d.state.copy()}
}

func (d *DB) WriteTx() meta.WriteTx {
// For a write transaction, we acquire the lock until the transaction is
// aborted/committed in order to prevent other transactions from modifying
// the state.
d.stateMu.Lock()
return &writeTx{d, readTx{d.state.copy()}}
}

var (
_ meta.DB = &DB{}
)
48 changes: 48 additions & 0 deletions internal/meta/jsonfiledb/db_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package jsonfiledb_test

import (
"github.com/aviator-co/av/internal/meta"
"github.com/aviator-co/av/internal/meta/jsonfiledb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"testing"
)

func TestJSONFileDB(t *testing.T) {
tempfile := t.TempDir() + "/db.json"

db, err := jsonfiledb.Open(tempfile)
require.NoError(t, err, "db open should succeed if state file does not exist")

if _, ok := db.ReadTx().Branch("foo"); ok {
t.Error("non existent branch should not be found")
}

tx := db.WriteTx()
tx.SetBranch(meta.Branch{Name: "foo"})
require.NoError(t, tx.Commit(), "tx commit should succeed")

tx = db.WriteTx()
tx.SetBranch(meta.Branch{Name: "bar"})
bar, ok := tx.Branch("bar")
if !ok {
t.Error("modifications should be visible within a transaction")
}
assert.Equal(t, "bar", bar.Name, "branch name should match")
tx.Abort()

if _, ok := db.ReadTx().Branch("bar"); ok {
t.Error("aborted tx should not commit changes")
}

foo, ok := db.ReadTx().Branch("foo")
require.True(t, ok, "branch should be found")
require.Equal(t, "foo", foo.Name, "branch name should match")

// Re-open the database and cause it to re-read from disk
db, err = jsonfiledb.Open(tempfile)
require.NoError(t, err, "db open should succeed if state file exists")
foo, ok = db.ReadTx().Branch("foo")
require.True(t, ok, "branch should be found after re-open")
require.Equal(t, "foo", foo.Name, "branch name should match")
}
25 changes: 25 additions & 0 deletions internal/meta/jsonfiledb/readtx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package jsonfiledb

import (
"github.com/aviator-co/av/internal/meta"
"github.com/aviator-co/av/internal/utils/maputils"
)

type readTx struct {
state state
}

var _ meta.ReadTx = &readTx{}

func (tx *readTx) Repository() (meta.Repository, bool) {
return tx.state.RepositoryState, tx.state.RepositoryState.ID != ""
}

func (tx *readTx) Branch(name string) (branch meta.Branch, ok bool) {
branch, ok = tx.state.BranchState[name]
return
}

func (tx *readTx) AllBranches() map[string]meta.Branch {
return maputils.Copy(tx.state.BranchState)
}
50 changes: 50 additions & 0 deletions internal/meta/jsonfiledb/state.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package jsonfiledb

import (
"emperror.dev/errors"
"encoding/json"
"github.com/aviator-co/av/internal/meta"
"github.com/aviator-co/av/internal/utils/maputils"
"os"
)

func readState(filepath string) (*state, error) {
data, err := os.ReadFile(filepath)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
if len(data) == 0 {
data = []byte("{}")
}
var state state
if err := json.Unmarshal(data, &state); err != nil {
return nil, errors.WrapIff(err, "failed to read av state file %q", filepath)
}
return &state, nil
}

type state struct {
BranchState map[string]meta.Branch `json:"branches"`
RepositoryState meta.Repository `json:"repository"`
}

func (d *state) copy() state {
return state{
maputils.Copy(d.BranchState),
d.RepositoryState,
}
}

func (d *state) write(filepath string) error {
f, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return errors.WrapIff(err, "failed to write av state file")
}
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
if err := enc.Encode(d); err != nil {
_ = f.Close()
return errors.WrapIff(err, "failed to write av state file")
}
return f.Close()
}
35 changes: 35 additions & 0 deletions internal/meta/jsonfiledb/writetx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package jsonfiledb

import "github.com/aviator-co/av/internal/meta"

type writeTx struct {
db *DB
readTx
}

func (tx *writeTx) SetRepository(repository meta.Repository) {
tx.state.RepositoryState = repository
}

func (tx *writeTx) SetBranch(branch meta.Branch) {
tx.state.BranchState[branch.Name] = branch
}

func (tx *writeTx) Abort() {
tx.db.stateMu.Unlock()
tx.db = nil
}

func (tx *writeTx) Commit() error {
// Always unlock the database even if there is an error.
defer tx.db.stateMu.Unlock()
err := tx.state.write(tx.db.filepath)
if err != nil {
return err
}
*tx.db.state = tx.state
tx.db = nil
return nil
}

var _ meta.WriteTx = &writeTx{}
10 changes: 10 additions & 0 deletions internal/utils/maputils/copy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package maputils

// Copy returns a (shallow) copy of the given map.
func Copy[K comparable, T any](m map[K]T) map[K]T {
c := make(map[K]T, len(m))
for k, v := range m {
c[k] = v
}
return c
}