From 69dbc926ad592fa362576868d5223fdf43dbf940 Mon Sep 17 00:00:00 2001 From: Chris Piraino Date: Wed, 2 Sep 2020 10:24:19 -0500 Subject: [PATCH] Add WriteTxn interface and convert more functions to ReadTxn We add a WriteTxn interface for use in updating the usage memdb table, with the forward-looking prospect of incrementally converting other functions to accept interfaces. As well, we use the ReadTxn in new usage code, and as a side effect convert a couple of existing functions to use that interface as well. --- agent/consul/state/memdb.go | 7 +++++++ agent/consul/state/usage.go | 6 +++--- agent/consul/state/usage_oss.go | 2 +- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/agent/consul/state/memdb.go b/agent/consul/state/memdb.go index 5cdfd19dd1..3b5d5e696e 100644 --- a/agent/consul/state/memdb.go +++ b/agent/consul/state/memdb.go @@ -15,6 +15,13 @@ type ReadTxn interface { Abort() } +// WriteTxn is implemented by memdb.Txn to perform write operations. +type WriteTxn interface { + ReadTxn + Insert(table string, obj interface{}) error + Commit() error +} + // Changes wraps a memdb.Changes to include the index at which these changes // were made. type Changes struct { diff --git a/agent/consul/state/usage.go b/agent/consul/state/usage.go index 397e157f37..8b226b3e19 100644 --- a/agent/consul/state/usage.go +++ b/agent/consul/state/usage.go @@ -37,7 +37,7 @@ type UsageEntry struct { // updateUsage takes a set of memdb changes and computes a delta for specific // usage metrics that we track. -func updateUsage(tx *txn, changes Changes) error { +func updateUsage(tx WriteTxn, changes Changes) error { usageDeltas := make(map[string]int) for _, change := range changes.Changes { var delta int @@ -140,7 +140,7 @@ func (s *Store) ServiceUsage() (uint64, ServiceUsage, error) { return 0, ServiceUsage{}, fmt.Errorf("failed services lookup: %s", err) } - results, err := s.compileServiceUsage(tx, usage.Count) + results, err := compileServiceUsage(tx, usage.Count) if err != nil { return 0, ServiceUsage{}, fmt.Errorf("failed services lookup: %s", err) } @@ -148,7 +148,7 @@ func (s *Store) ServiceUsage() (uint64, ServiceUsage, error) { return usage.Index, results, nil } -func firstUsageEntry(tx *txn, id string) (*UsageEntry, error) { +func firstUsageEntry(tx ReadTxn, id string) (*UsageEntry, error) { usage, err := tx.First("usage", "id", id) if err != nil { return nil, err diff --git a/agent/consul/state/usage_oss.go b/agent/consul/state/usage_oss.go index ec54313d56..825b804948 100644 --- a/agent/consul/state/usage_oss.go +++ b/agent/consul/state/usage_oss.go @@ -12,7 +12,7 @@ type EnterpriseServiceUsage struct{} func addEnterpriseUsage(map[string]int, memdb.Change) {} -func (s *Store) compileServiceUsage(tx *txn, totalInstances int) (ServiceUsage, error) { +func compileServiceUsage(tx ReadTxn, totalInstances int) (ServiceUsage, error) { var totalServices int results, err := tx.Get( "index",