Просмотр исходного кода

Update the handler return value to error to potentially halt iteration on failure

Matt Bolt 6 лет назад
Родитель
Сommit
0b1595f1ea

+ 7 - 3
pkg/clustermanager/boltdbstorage.go

@@ -64,8 +64,9 @@ func (cs *BoltDBClusterStorage) Remove(key string) error {
 	})
 }
 
-// Retrieve all the keys stored
-func (cs *BoltDBClusterStorage) Each(handler func(string, []byte)) error {
+// Iterates through all key/values for the storage and calls the handler func. If a handler returns
+// an error, the iteration stops.
+func (cs *BoltDBClusterStorage) Each(handler func(string, []byte) error) error {
 	return cs.db.View(func(tx *bolt.Tx) error {
 		bucket := tx.Bucket(cs.bucket)
 
@@ -77,7 +78,10 @@ func (cs *BoltDBClusterStorage) Each(handler func(string, []byte)) error {
 			copy(key, k)
 			copy(value, v)
 
-			handler(string(key), value)
+			if err := handler(string(key), value); err != nil {
+				return err
+			}
+
 			return nil
 		})
 	})

+ 3 - 2
pkg/clustermanager/clustermanager.go

@@ -39,8 +39,9 @@ type ClusterStorage interface {
 	// Removes a key from the cluster storage
 	Remove(key string) error
 
-	// Call a handler to receive each key and value stored
-	Each(handler func(string, []byte)) error
+	// Iterates through all key/values for the storage and calls the handler func. If a handler returns
+	// an error, the iteration stops.
+	Each(handler func(string, []byte) error) error
 
 	// Closes the backing storage
 	Close() error

+ 6 - 3
pkg/clustermanager/mapdbstorage.go

@@ -35,13 +35,16 @@ func (cs *MapDBClusterStorage) Remove(key string) error {
 	return nil
 }
 
-// Retrieve all the keys stored
-func (cs *MapDBClusterStorage) Each(handler func(string, []byte)) error {
+// Iterates through all key/values for the storage and calls the handler func. If a handler returns
+// an error, the iteration stops.
+func (cs *MapDBClusterStorage) Each(handler func(string, []byte) error) error {
 	for k, v := range cs.store {
 		value := make([]byte, len(v))
 		copy(value, v)
 
-		handler(k, value)
+		if err := handler(k, value); err != nil {
+			return err
+		}
 	}
 	return nil
 }