From 5904e4ac79d3b40182dc39945c093cb77676b87f Mon Sep 17 00:00:00 2001 From: Dhia Ayachi Date: Thu, 23 Sep 2021 11:06:23 -0400 Subject: [PATCH] Refactor table index (#11131) * convert tableIndex to use the new pattern * make `indexFromString` available for oss as well * refactor `indexUpdateMaxTxn` --- agent/consul/state/schema.go | 33 ++++++++++++++++++++++++++++--- agent/consul/state/state_store.go | 21 +++++++++++--------- 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/agent/consul/state/schema.go b/agent/consul/state/schema.go index cecb2a2a34..bca4eec01b 100644 --- a/agent/consul/state/schema.go +++ b/agent/consul/state/schema.go @@ -2,6 +2,7 @@ package state import ( "fmt" + "strings" "github.com/hashicorp/go-memdb" ) @@ -75,11 +76,37 @@ func indexTableSchema() *memdb.TableSchema { Name: indexID, AllowMissing: false, Unique: true, - Indexer: &memdb.StringFieldIndex{ - Field: "Key", - Lowercase: true, + Indexer: indexerSingle{ + readIndex: indexFromString, + writeIndex: indexNameFromIndexEntry, }, }, }, } } + +func indexNameFromIndexEntry(raw interface{}) ([]byte, error) { + p, ok := raw.(*IndexEntry) + if !ok { + return nil, fmt.Errorf("unexpected type %T for IndexEntry index", raw) + } + + if p.Key == "" { + return nil, errMissingValueForIndex + } + + var b indexBuilder + b.String(strings.ToLower(p.Key)) + return b.Bytes(), nil +} + +func indexFromString(raw interface{}) ([]byte, error) { + q, ok := raw.(string) + if !ok { + return nil, fmt.Errorf("unexpected type %T for string prefix query", raw) + } + + var b indexBuilder + b.String(strings.ToLower(q)) + return b.Bytes(), nil +} diff --git a/agent/consul/state/state_store.go b/agent/consul/state/state_store.go index a0a26243e8..fdfcb16fcf 100644 --- a/agent/consul/state/state_store.go +++ b/agent/consul/state/state_store.go @@ -295,17 +295,20 @@ func indexUpdateMaxTxn(tx WriteTxn, idx uint64, table string) error { return fmt.Errorf("failed to retrieve existing index: %s", err) } - // Always take the first update, otherwise do the > check. - if ti == nil { - if err := tx.Insert(tableIndex, &IndexEntry{table, idx}); err != nil { - return fmt.Errorf("failed updating index %s", err) + // if this is an update check the idx + if ti != nil { + cur, ok := ti.(*IndexEntry) + if !ok { + return fmt.Errorf("failed updating index %T need to be `*IndexEntry`", ti) } - return nil - } - if cur, ok := ti.(*IndexEntry); ok && idx > cur.Value { - if err := tx.Insert(tableIndex, &IndexEntry{table, idx}); err != nil { - return fmt.Errorf("failed updating index %s", err) + // Stored index is newer, don't insert the index + if idx <= cur.Value { + return nil } } + + if err := tx.Insert(tableIndex, &IndexEntry{table, idx}); err != nil { + return fmt.Errorf("failed updating index %s", err) + } return nil }